code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
# Senecio johnstonianus Cabrera SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Senecio johnstonianus/README.md | Markdown | apache-2.0 | 179 |
all: help
help:
@echo ""
@echo "-- Help Menu"
@echo ""
@echo " 1. make build - build all images"
@echo " 2. make pull - pull all images"
@echo " 3. make clean - remove all images"
@echo ""
build:
@docker build --tag=gazebo:gzserver5-trusty gzserver5/.
@docker build --tag=gazebo:libgazebo5-trusty libgazebo5/.
# @docker build --tag=gazebo:gzclient5-trusty gzclient5/.
# @docker build --tag=gazebo:gzweb5-trusty gzweb5/.
pull:
@docker pull gazebo:libgazebo5-trusty
@docker pull gazebo:gzserver5-trusty
# @docker pull gazebo:gzclient5-trusty
# @docker pull gazebo:gzweb5-trusty
clean:
@docker rmi -f gazebo:libgazebo5-trusty
@docker rmi -f gazebo:gzserver5-trusty
# @docker rmi -f gazebo:gzclient5-trusty
# @docker rmi -f gazebo:gzweb5-trusty
| ruffsl/docker_images | gazebo/5/ubuntu/trusty/Makefile | Makefile | apache-2.0 | 806 |
package gzip
import (
"compress/gzip"
"fmt"
"io/ioutil"
"net/http"
"path/filepath"
"strings"
"sync"
"github.com/gin-gonic/gin"
)
const (
BestCompression = gzip.BestCompression
BestSpeed = gzip.BestSpeed
DefaultCompression = gzip.DefaultCompression
NoCompression = gzip.NoCompression
)
func Gzip(level int) gin.HandlerFunc {
var gzPool sync.Pool
gzPool.New = func() interface{} {
gz, err := gzip.NewWriterLevel(ioutil.Discard, level)
if err != nil {
panic(err)
}
return gz
}
return func(c *gin.Context) {
if !shouldCompress(c.Request) {
return
}
gz := gzPool.Get().(*gzip.Writer)
defer gzPool.Put(gz)
gz.Reset(c.Writer)
c.Header("Content-Encoding", "gzip")
c.Header("Vary", "Accept-Encoding")
c.Writer = &gzipWriter{c.Writer, gz}
defer func() {
gz.Close()
c.Header("Content-Length", fmt.Sprint(c.Writer.Size()))
}()
c.Next()
}
}
type gzipWriter struct {
gin.ResponseWriter
writer *gzip.Writer
}
func (g *gzipWriter) WriteString(s string) (int, error) {
return g.writer.Write([]byte(s))
}
func (g *gzipWriter) Write(data []byte) (int, error) {
return g.writer.Write(data)
}
func shouldCompress(req *http.Request) bool {
if !strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") {
return false
}
extension := filepath.Ext(req.URL.Path)
if len(extension) < 4 { // fast path
return true
}
switch extension {
case ".png", ".gif", ".jpeg", ".jpg":
return false
default:
return true
}
}
| kenota/kommentator | vendor/github.com/gin-contrib/gzip/gzip.go | GO | apache-2.0 | 1,493 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.autoscaling.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.autoscaling.model.*;
import com.amazonaws.transform.Marshaller;
/**
* DescribeAccountLimitsRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeAccountLimitsRequestMarshaller implements Marshaller<Request<DescribeAccountLimitsRequest>, DescribeAccountLimitsRequest> {
public Request<DescribeAccountLimitsRequest> marshall(DescribeAccountLimitsRequest describeAccountLimitsRequest) {
if (describeAccountLimitsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
Request<DescribeAccountLimitsRequest> request = new DefaultRequest<DescribeAccountLimitsRequest>(describeAccountLimitsRequest, "AmazonAutoScaling");
request.addParameter("Action", "DescribeAccountLimits");
request.addParameter("Version", "2011-01-01");
request.setHttpMethod(HttpMethodName.POST);
return request;
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-autoscaling/src/main/java/com/amazonaws/services/autoscaling/model/transform/DescribeAccountLimitsRequestMarshaller.java | Java | apache-2.0 | 1,809 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.ec2.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* Describes the ClassicLink DNS support status of a VPC.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ClassicLinkDnsSupport" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ClassicLinkDnsSupport implements Serializable, Cloneable {
/**
* <p>
* Indicates whether ClassicLink DNS support is enabled for the VPC.
* </p>
*/
private Boolean classicLinkDnsSupported;
/**
* <p>
* The ID of the VPC.
* </p>
*/
private String vpcId;
/**
* <p>
* Indicates whether ClassicLink DNS support is enabled for the VPC.
* </p>
*
* @param classicLinkDnsSupported
* Indicates whether ClassicLink DNS support is enabled for the VPC.
*/
public void setClassicLinkDnsSupported(Boolean classicLinkDnsSupported) {
this.classicLinkDnsSupported = classicLinkDnsSupported;
}
/**
* <p>
* Indicates whether ClassicLink DNS support is enabled for the VPC.
* </p>
*
* @return Indicates whether ClassicLink DNS support is enabled for the VPC.
*/
public Boolean getClassicLinkDnsSupported() {
return this.classicLinkDnsSupported;
}
/**
* <p>
* Indicates whether ClassicLink DNS support is enabled for the VPC.
* </p>
*
* @param classicLinkDnsSupported
* Indicates whether ClassicLink DNS support is enabled for the VPC.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ClassicLinkDnsSupport withClassicLinkDnsSupported(Boolean classicLinkDnsSupported) {
setClassicLinkDnsSupported(classicLinkDnsSupported);
return this;
}
/**
* <p>
* Indicates whether ClassicLink DNS support is enabled for the VPC.
* </p>
*
* @return Indicates whether ClassicLink DNS support is enabled for the VPC.
*/
public Boolean isClassicLinkDnsSupported() {
return this.classicLinkDnsSupported;
}
/**
* <p>
* The ID of the VPC.
* </p>
*
* @param vpcId
* The ID of the VPC.
*/
public void setVpcId(String vpcId) {
this.vpcId = vpcId;
}
/**
* <p>
* The ID of the VPC.
* </p>
*
* @return The ID of the VPC.
*/
public String getVpcId() {
return this.vpcId;
}
/**
* <p>
* The ID of the VPC.
* </p>
*
* @param vpcId
* The ID of the VPC.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ClassicLinkDnsSupport withVpcId(String vpcId) {
setVpcId(vpcId);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getClassicLinkDnsSupported() != null)
sb.append("ClassicLinkDnsSupported: ").append(getClassicLinkDnsSupported()).append(",");
if (getVpcId() != null)
sb.append("VpcId: ").append(getVpcId());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ClassicLinkDnsSupport == false)
return false;
ClassicLinkDnsSupport other = (ClassicLinkDnsSupport) obj;
if (other.getClassicLinkDnsSupported() == null ^ this.getClassicLinkDnsSupported() == null)
return false;
if (other.getClassicLinkDnsSupported() != null && other.getClassicLinkDnsSupported().equals(this.getClassicLinkDnsSupported()) == false)
return false;
if (other.getVpcId() == null ^ this.getVpcId() == null)
return false;
if (other.getVpcId() != null && other.getVpcId().equals(this.getVpcId()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getClassicLinkDnsSupported() == null) ? 0 : getClassicLinkDnsSupported().hashCode());
hashCode = prime * hashCode + ((getVpcId() == null) ? 0 : getVpcId().hashCode());
return hashCode;
}
@Override
public ClassicLinkDnsSupport clone() {
try {
return (ClassicLinkDnsSupport) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/ClassicLinkDnsSupport.java | Java | apache-2.0 | 5,761 |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.poifs.dev;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.poi.poifs.common.POIFSBigBlockSize;
import org.apache.poi.poifs.common.POIFSConstants;
import org.apache.poi.poifs.property.DirectoryProperty;
import org.apache.poi.poifs.property.Property;
import org.apache.poi.poifs.property.PropertyTable;
import org.apache.poi.poifs.storage.BlockAllocationTableReader;
import org.apache.poi.poifs.storage.HeaderBlock;
import org.apache.poi.poifs.storage.ListManagedBlock;
import org.apache.poi.poifs.storage.RawDataBlockList;
import org.apache.poi.poifs.storage.SmallBlockTableReader;
import org.apache.poi.util.HexDump;
import org.apache.poi.util.IntList;
/**
* A very low level debugging tool, for printing out core
* information on the headers and FAT blocks.
* You probably only want to use this if you're trying
* to understand POIFS, or if you're trying to track
* down the source of corruption in a file.
*/
public class POIFSHeaderDumper {
/**
* Display the entries of multiple POIFS files
*
* @param args the names of the files to be displayed
*/
public static void main(final String args[]) throws Exception {
if (args.length == 0) {
System.err.println("Must specify at least one file to view");
System.exit(1);
}
for (int j = 0; j < args.length; j++) {
viewFile(args[j]);
}
}
public static void viewFile(final String filename) throws Exception {
System.out.println("Dumping headers from: " + filename);
InputStream inp = new FileInputStream(filename);
// Header
HeaderBlock header_block = new HeaderBlock(inp);
displayHeader(header_block);
// Raw blocks
POIFSBigBlockSize bigBlockSize = header_block.getBigBlockSize();
RawDataBlockList data_blocks = new RawDataBlockList(inp, bigBlockSize);
displayRawBlocksSummary(data_blocks);
// Main FAT Table
BlockAllocationTableReader batReader =
new BlockAllocationTableReader(
header_block.getBigBlockSize(),
header_block.getBATCount(),
header_block.getBATArray(),
header_block.getXBATCount(),
header_block.getXBATIndex(),
data_blocks);
displayBATReader("Big Blocks", batReader);
// Properties Table
PropertyTable properties =
new PropertyTable(header_block, data_blocks);
// Mini Fat
BlockAllocationTableReader sbatReader =
SmallBlockTableReader._getSmallDocumentBlockReader(
bigBlockSize, data_blocks, properties.getRoot(),
header_block.getSBATStart()
);
displayBATReader("Small Blocks", sbatReader);
// Summary of the properties
displayPropertiesSummary(properties);
}
public static void displayHeader(HeaderBlock header_block) throws Exception {
System.out.println("Header Details:");
System.out.println(" Block size: " + header_block.getBigBlockSize().getBigBlockSize());
System.out.println(" BAT (FAT) header blocks: " + header_block.getBATArray().length);
System.out.println(" BAT (FAT) block count: " + header_block.getBATCount());
if (header_block.getBATCount() > 0)
System.out.println(" BAT (FAT) block 1 at: " + header_block.getBATArray()[0]);
System.out.println(" XBAT (FAT) block count: " + header_block.getXBATCount());
System.out.println(" XBAT (FAT) block 1 at: " + header_block.getXBATIndex());
System.out.println(" SBAT (MiniFAT) block count: " + header_block.getSBATCount());
System.out.println(" SBAT (MiniFAT) block 1 at: " + header_block.getSBATStart());
System.out.println(" Property table at: " + header_block.getPropertyStart());
System.out.println("");
}
public static void displayRawBlocksSummary(RawDataBlockList data_blocks) throws Exception {
System.out.println("Raw Blocks Details:");
System.out.println(" Number of blocks: " + data_blocks.blockCount());
for(int i=0; i<Math.min(16, data_blocks.blockCount()); i++) {
ListManagedBlock block = data_blocks.get(i);
byte[] data = new byte[Math.min(48, block.getData().length)];
System.arraycopy(block.getData(), 0, data, 0, data.length);
System.out.println(" Block #" + i + ":");
System.out.println(HexDump.dump(data, 0, 0));
}
System.out.println("");
}
public static void displayBATReader(String type, BlockAllocationTableReader batReader) throws Exception {
System.out.println("Sectors, as referenced from the "+type+" FAT:");
IntList entries = batReader.getEntries();
for(int i=0; i<entries.size(); i++) {
int bn = entries.get(i);
String bnS = Integer.toString(bn);
if(bn == POIFSConstants.END_OF_CHAIN) {
bnS = "End Of Chain";
} else if(bn == POIFSConstants.DIFAT_SECTOR_BLOCK) {
bnS = "DI Fat Block";
} else if(bn == POIFSConstants.FAT_SECTOR_BLOCK) {
bnS = "Normal Fat Block";
} else if(bn == POIFSConstants.UNUSED_BLOCK) {
bnS = "Block Not Used (Free)";
}
System.out.println(" Block # " + i + " -> " + bnS);
}
System.out.println("");
}
public static void displayPropertiesSummary(PropertyTable properties) {
System.out.println("Mini Stream starts at " + properties.getRoot().getStartBlock());
System.out.println("Mini Stream length is " + properties.getRoot().getSize());
System.out.println();
System.out.println("Properties and their block start:");
displayProperties(properties.getRoot(), "");
System.out.println("");
}
public static void displayProperties(DirectoryProperty prop, String indent) {
String nextIndent = indent + " ";
System.out.println(indent + "-> " + prop.getName());
for (Property cp : prop) {
if (cp instanceof DirectoryProperty) {
displayProperties((DirectoryProperty)cp, nextIndent);
} else {
System.out.println(nextIndent + "=> " + cp.getName());
System.out.print(nextIndent + " " + cp.getSize() + " bytes in ");
if (cp.shouldUseSmallBlocks()) {
System.out.print("mini");
} else {
System.out.print("main");
}
System.out.println(" stream, starts at " + cp.getStartBlock());
}
}
}
}
| lvweiwolf/poi-3.16 | src/java/org/apache/poi/poifs/dev/POIFSHeaderDumper.java | Java | apache-2.0 | 7,805 |
/** Automatically generated file. DO NOT MODIFY */
package com.leoz.bz.zview;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | leoz/zview | gen/com/leoz/bz/zview/BuildConfig.java | Java | apache-2.0 | 159 |
/******************************************************************************/
/**
@file gen_bench_relations.h
@author Graeme Douglas
@brief A quick and dirty program for creating test relations for
benchmarking the database.
@details
@copyright Copyright 2013 Graeme Douglas
@license Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
@par
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 GEN_BENCH_RELATIONS_H
#define GEN_BENCH_RELATIONS_H
#ifdef __cplusplus
extern "C" {
#endif
#include "../ref.h"
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include "../dbstorage/dbstorage.h"
#include "../dblogic/eet.h"
#include "../dbindex/dbindex.h"
#include "../db_ctconf.h"
#include <stdlib.h>
/* Initialize a test relation using Contiki Filesystem interface (CFS). */
/**
@brief Build a test relation for any system.
*/
db_int gen_bench_relation(char *relationname, db_int numattr,
db_int numtuples, db_int bound, db_int seed, db_int type);
#ifdef __cplusplus
}
#endif
#endif
| graemedouglas/LittleD | src/utils/gen_bench_relations.h | C | apache-2.0 | 1,533 |
/**
*
*/
package me.learn.personal.month3;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* Title 414 :
*
* Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.
*
* @author bramanarayan
* @date Jun 24, 2020
*/
public class ThirdMaximumNumber {
/**
* @param args
*/
public static void main(String[] args) {
ThirdMaximumNumber solution = new ThirdMaximumNumber();
System.out.println(solution.thirdMax(new int[] {3,2,1}));
System.out.println(solution.thirdMax(new int[] {2,2,3,1}));
}
// Keep a set to track the top 3 elements.
public int thirdMax(int[] a) {
Set<Integer> s = new HashSet<Integer>();
for (int i = 0; i < a.length; i++) {
s.add(a[i]);
if (s.size() > 3) {
s.remove(Collections.min(s));// remove the minimum
}
}
return s.size() == 3 ? Collections.min(s) : Collections.max(s);
}
// Without duplicates - just three integers
public int thirdMaxMy(int[] a) {
// Init all to negative infinity
int first = Integer.MIN_VALUE;
int second = first;
int third = second;
for (int i = 0; i < a.length; i++) {
if(a[i] > third) {
third = a[i];
}
if(third > second) {
int t = third;
third = second ;
second = t;
}
if( second > first) {
int t = second;
second= first;
first = t;
}
}
return third;
}
}
| balajiboggaram/algorithms | src/me/learn/personal/month3/ThirdMaximumNumber.java | Java | apache-2.0 | 1,602 |
package tpl.admin.api.entities;
import org.nutz.dao.Dao;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.mvc.adaptor.JsonAdaptor;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.DELETE;
import org.nutz.mvc.annotation.GET;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.PUT;
import tpl.entities.EntityDef;
import tpl.entities.StatusCodes;
@InjectName("api.entityModule")
public class EntityModule {
private Dao dao;
@At("/entity/?")
@GET
public EntityDef get(String name) {
return dao.fetch(EntityDef.class, name);
}
@At("/entity")
@POST
@AdaptBy(type=JsonAdaptor.class)
public EntityDef add(EntityDef entity) {
if (entity == null || entity.getName() == null)
throw new RuntimeException("No entity definition to save.");
EntityDef origin = dao.fetch(EntityDef.class, entity.getName());
if (origin != null)
throw new RuntimeException("Entity definition already exists.");
entity.setStatus(StatusCodes.STATUS_BRAND_NEW | StatusCodes.STATUS_UNAPPLIED);
return dao.insert(entity);
}
@At("/entity")
@PUT
@AdaptBy(type=JsonAdaptor.class)
public EntityDef update(EntityDef entity) {
if (entity == null || entity.getName() == null)
throw new RuntimeException("No entity definition to save.");
EntityDef origin = dao.fetch(EntityDef.class, entity.getName());
if (origin == null)
throw new RuntimeException("Entity definition is not found.");
origin.setDisplayName(entity.getDisplayName());
origin.setDescription(entity.getDescription());
origin.setStatus(origin.getStatus() | StatusCodes.STATUS_UNAPPLIED);
dao.update(origin);
return entity;
}
@At("/entity/?")
@DELETE
public EntityDef delete(String name) {
EntityDef origin = dao.fetch(EntityDef.class, name);
if (origin != null) {
dao.delete(origin);
}
return origin;
}
public void setDao(Dao dao) {
this.dao = dao;
}
}
| weiht/nutz-tpl | nutz-tpl-admin/src/main/java/tpl/admin/api/entities/EntityModule.java | Java | apache-2.0 | 1,938 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-GB" xml:lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Statistics of Polarity in UD_Japanese-GSD</title>
<link rel="root" href=""/> <!-- for JS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
<link rel="stylesheet" type="text/css" href="../../css/hint.css"/>
<script type="text/javascript" src="../../lib/ext/head.load.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.2/anchor.min.js"></script>
<script>document.addEventListener("DOMContentLoaded", function(event) {anchors.add();});</script>
<!-- Set up this custom Google search at https://cse.google.com/cse/business/settings?cx=001145188882102106025:dl1mehhcgbo -->
<!-- DZ 2021-01-22: I am temporarily hiding the search field to find out whether it slows down loading of the title page.
<script>
(function() {
var cx = '001145188882102106025:dl1mehhcgbo';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script> -->
<!-- <link rel="shortcut icon" href="favicon.ico"/> -->
</head>
<body>
<div id="main" class="center">
<div id="hp-header">
<table width="100%"><tr><td width="50%">
<span class="header-text"><a href="http://universaldependencies.org/#language-">home</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/edit/pages-source/treebanks/ja_gsd/ja_gsd-feat-Polarity.md" target="#">edit page</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/issues">issue tracker</a></span>
</td><td>
<gcse:search></gcse:search>
</td></tr></table>
</div>
<hr/>
<div class="v2complete">
This page pertains to UD version 2.
</div>
<div id="content">
<noscript>
<div id="noscript">
It appears that you have Javascript disabled.
Please consider enabling Javascript for this page to see the visualizations.
</div>
</noscript>
<!-- The content may include scripts and styles, hence we must load the shared libraries before the content. -->
<script type="text/javascript">
console.time('loading libraries');
var root = '../../'; // filled in by jekyll
head.js(
// External libraries
// DZ: Copied from embedding.html. I don't know which one is needed for what, so I'm currently keeping them all.
root + 'lib/ext/jquery.min.js',
root + 'lib/ext/jquery.svg.min.js',
root + 'lib/ext/jquery.svgdom.min.js',
root + 'lib/ext/jquery.timeago.js',
root + 'lib/ext/jquery-ui.min.js',
root + 'lib/ext/waypoints.min.js',
root + 'lib/ext/jquery.address.min.js'
);
</script>
<h2 id="treebank-statistics-ud_japanese-gsd-features-polarity">Treebank Statistics: UD_Japanese-GSD: Features: <code class="language-plaintext highlighter-rouge">Polarity</code></h2>
<p>This feature is universal.
It occurs with 1 different values: <code class="language-plaintext highlighter-rouge">Neg</code>.</p>
<p>1077 tokens (1%) have a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>.
17 types (0%) occur at least once with a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>.
8 lemmas (0%) occur at least once with a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>.
The feature is used with 2 part-of-speech tags: <tt><a href="ja_gsd-pos-SCONJ.html">SCONJ</a></tt> (959; 0% instances), <tt><a href="ja_gsd-pos-NOUN.html">NOUN</a></tt> (118; 0% instances).</p>
<h3 id="sconj"><code class="language-plaintext highlighter-rouge">SCONJ</code></h3>
<p>959 <tt><a href="ja_gsd-pos-SCONJ.html">SCONJ</a></tt> tokens (11% of all <code class="language-plaintext highlighter-rouge">SCONJ</code> tokens) have a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>.</p>
<p><code class="language-plaintext highlighter-rouge">SCONJ</code> tokens may have the following values of <code class="language-plaintext highlighter-rouge">Polarity</code>:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">Neg</code> (959; 100% of non-empty <code class="language-plaintext highlighter-rouge">Polarity</code>): ない, ず, ん, なかっ, なく, なけれ, ざる, ぬ, なきゃ, な</li>
<li><code class="language-plaintext highlighter-rouge">EMPTY</code> (8061): て, の, が, と, で, ば, に, ながら, から, ため</li>
</ul>
<h3 id="noun"><code class="language-plaintext highlighter-rouge">NOUN</code></h3>
<p>118 <tt><a href="ja_gsd-pos-NOUN.html">NOUN</a></tt> tokens (0% of all <code class="language-plaintext highlighter-rouge">NOUN</code> tokens) have a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>.</p>
<p><code class="language-plaintext highlighter-rouge">NOUN</code> tokens may have the following values of <code class="language-plaintext highlighter-rouge">Polarity</code>:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">Neg</code> (118; 100% of non-empty <code class="language-plaintext highlighter-rouge">Polarity</code>): 不, 非, 反, 無, 未, 異</li>
<li><code class="language-plaintext highlighter-rouge">EMPTY</code> (58067): 年, こと, 月, 日, 人, 者, お, 後, ため, もの</li>
</ul>
</div>
<!-- support for embedded visualizations -->
<script type="text/javascript">
var root = '../../'; // filled in by jekyll
head.js(
// We assume that external libraries such as jquery.min.js have already been loaded outside!
// (See _layouts/base.html.)
// brat helper modules
root + 'lib/brat/configuration.js',
root + 'lib/brat/util.js',
root + 'lib/brat/annotation_log.js',
root + 'lib/ext/webfont.js',
// brat modules
root + 'lib/brat/dispatcher.js',
root + 'lib/brat/url_monitor.js',
root + 'lib/brat/visualizer.js',
// embedding configuration
root + 'lib/local/config.js',
// project-specific collection data
root + 'lib/local/collections.js',
// Annodoc
root + 'lib/annodoc/annodoc.js',
// NOTE: non-local libraries
'https://spyysalo.github.io/conllu.js/conllu.js'
);
var webFontURLs = [
// root + 'static/fonts/Astloch-Bold.ttf',
root + 'static/fonts/PT_Sans-Caption-Web-Regular.ttf',
root + 'static/fonts/Liberation_Sans-Regular.ttf'
];
var setupTimeago = function() {
jQuery("time.timeago").timeago();
};
head.ready(function() {
setupTimeago();
// mark current collection (filled in by Jekyll)
Collections.listing['_current'] = '';
// perform all embedding and support functions
Annodoc.activate(Config.bratCollData, Collections.listing);
});
</script>
<!-- google analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-55233688-1', 'auto');
ga('send', 'pageview');
</script>
<div id="footer">
<p class="footer-text">© 2014–2021
<a href="http://universaldependencies.org/introduction.html#contributors" style="color:gray">Universal Dependencies contributors</a>.
Site powered by <a href="http://spyysalo.github.io/annodoc" style="color:gray">Annodoc</a> and <a href="http://brat.nlplab.org/" style="color:gray">brat</a></p>.
</div>
</div>
</body>
</html>
| UniversalDependencies/universaldependencies.github.io | treebanks/ja_gsd/ja_gsd-feat-Polarity.html | HTML | apache-2.0 | 8,730 |
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package client
// Different parameter keys and values used by the system
const (
// S1 instructions
sampledParam = "sampled"
server1NameParam = "s1name"
// S1->S2 instructions
server2NameParam = "s2name"
server2TransportParam = "s2transport"
// S2->S3 instructions
server3NameParam = "s3name"
server3TransportParam = "s3transport"
transportHTTP = "http"
transportDummy = "dummy"
behaviorTrace = "trace"
// RoleS1 is the name of the role for server S1
RoleS1 = "S1"
// RoleS2 is the name of the role for server S2
RoleS2 = "S2"
// RoleS3 is the name of the role for server S3
RoleS3 = "S3"
)
| amshinde/shim | vendor/github.com/uber/jaeger-client-go/crossdock/client/constants.go | GO | apache-2.0 | 1,231 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.util;
import com.intellij.ide.IdeTooltip;
import com.intellij.ide.IdeTooltipManager;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.progress.util.ProgressWindow;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.util.Disposer;
import com.intellij.ui.HintHint;
import com.intellij.ui.JBColor;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.components.panels.Wrapper;
import com.intellij.vcs.log.data.VcsLogData;
import com.intellij.vcs.log.data.VcsLogProgress;
import com.intellij.vcs.log.ui.frame.DetailsPanel;
import com.intellij.vcs.log.ui.frame.ProgressStripe;
import com.intellij.vcs.log.ui.table.VcsLogGraphTable;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
public class VcsLogUiUtil {
@NotNull
public static JComponent installProgress(@NotNull JComponent component,
@NotNull VcsLogData logData,
@NotNull Disposable disposableParent) {
ProgressStripe progressStripe =
new ProgressStripe(component, disposableParent, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS) {
@Override
public void updateUI() {
super.updateUI();
if (myDecorator != null && logData.getProgress().isRunning()) startLoadingImmediately();
}
};
logData.getProgress().addProgressIndicatorListener(new VcsLogProgress.ProgressListener() {
@Override
public void progressStarted() {
progressStripe.startLoading();
}
@Override
public void progressStopped() {
progressStripe.stopLoading();
}
}, disposableParent);
return progressStripe;
}
@NotNull
public static JScrollPane setupScrolledGraph(@NotNull VcsLogGraphTable graphTable, int border) {
JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(graphTable, border);
graphTable.viewportSet(scrollPane.getViewport());
return scrollPane;
}
public static void installDetailsListeners(@NotNull VcsLogGraphTable graphTable,
@NotNull DetailsPanel detailsPanel,
@NotNull VcsLogData logData,
@NotNull Disposable disposableParent) {
Runnable miniDetailsLoadedListener = () -> {
graphTable.reLayout();
graphTable.repaint();
};
Runnable containingBranchesListener = () -> {
detailsPanel.branchesChanged();
graphTable.repaint(); // we may need to repaint highlighters
};
logData.getMiniDetailsGetter().addDetailsLoadedListener(miniDetailsLoadedListener);
logData.getContainingBranchesGetter().addTaskCompletedListener(containingBranchesListener);
Disposer.register(disposableParent, () -> {
logData.getContainingBranchesGetter().removeTaskCompletedListener(containingBranchesListener);
logData.getMiniDetailsGetter().removeDetailsLoadedListener(miniDetailsLoadedListener);
});
}
@NotNull
public static SimpleTextAttributes getLinkAttributes() {
return new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, JBColor.link());
}
public static void showTooltip(@NotNull JComponent component, @NotNull Point point, @NotNull Balloon.Position position, @NotNull String text) {
JEditorPane tipComponent = IdeTooltipManager.initPane(text, new HintHint(component, point).setAwtTooltip(true), null);
IdeTooltip tooltip = new IdeTooltip(component, point, new Wrapper(tipComponent)).setPreferredPosition(position).setToCenter(false).setToCenterIfSmall(false);
IdeTooltipManager.getInstance().show(tooltip, false);
}
}
| xfournet/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/util/VcsLogUiUtil.java | Java | apache-2.0 | 3,929 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hyperion.Core.Abstract
{
using Poseidon.Base.Framework;
using Poseidon.Data;
/// <summary>
/// MySQL抽象数据访问类,默认主键类型int
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
internal abstract class AbstractDALMySql<T> : AbstractDALMySql<T, int> where T : IBaseEntity<int>
{
#region Constructor
/// <summary>
/// MySQL抽象数据访问类
/// </summary>
/// <param name="tableName">数据表名</param>
/// <param name="primaryKey">主键名称</param>
public AbstractDALMySql(string tableName, string primaryKey) : base(tableName, primaryKey)
{ }
#endregion //Constructor
}
}
| robertzml/Hyperion | Hyperion.Core/Abstract/AbstractDALMySql.cs | C# | apache-2.0 | 850 |
/*
* Copyright (c) 2010-2013 Evolveum
*
* 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.evolveum.midpoint.prism.crypto;
import java.security.KeyStore;
import java.util.List;
import javax.net.ssl.TrustManager;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
import org.w3c.dom.Element;
import com.evolveum.midpoint.util.exception.SchemaException;
public interface Protector {
<T> void decrypt(ProtectedData<T> protectedData) throws EncryptionException, SchemaException;
<T> void encrypt(ProtectedData<T> protectedData) throws EncryptionException;
/**
* Returns a list of trust managers that will be used to validate communicating party credentials.
* (e.g. used to validate remote connector connections).
*/
List<TrustManager> getTrustManagers();
KeyStore getKeyStore();
/**
*
* @param protectedString
* @return decrypted String from protectedString object
* @throws EncryptionException
* this is thrown probably in case JRE/JDK doesn't have JCE
* installed
* @throws IllegalArgumentException
* if protectedString argument is null or EncryptedData in
* protectedString argument is null
*/
String decryptString(ProtectedStringType protectedString) throws EncryptionException;
// /**
// *
// * @param protectedString
// * @return decrypted DOM {@link Element}
// * @throws EncryptionException
// * this is thrown probably in case JRE/JDK doesn't have JCE
// * installed
// * @throws IllegalArgumentException
// * if protectedString argument is null or EncryptedData in
// * protectedString argument is null
// */
// Element decrypt(ProtectedStringType protectedString) throws EncryptionException;
/**
*
* @param text
* @return {@link ProtectedStringType} with encrypted string inside it. If
* input argument is null or empty, method returns null.
* @throws EncryptionException
* this is thrown probably in case JRE/JDK doesn't have JCE
* installed
*/
ProtectedStringType encryptString(String text) throws EncryptionException;
// /**
// *
// * @param plain
// * @return {@link ProtectedStringType} with encrypted element inside it. If
// * input argument is null, method returns null.
// * @throws EncryptionException
// * this is thrown probably in case JRE/JDK doesn't have JCE
// * installed
// */
// ProtectedStringType encrypt(Element plain) throws EncryptionException;
//
// /**
// * Encrypts the ProtectedStringType "in place".
// * @param ps
// * @throws EncryptionException
// */
// void encrypt(ProtectedStringType ps) throws EncryptionException;
//
/**
* Returns true if protected string contains encrypted data that seems valid.
*/
boolean isEncrypted(ProtectedStringType ps);
} | sabriarabacioglu/engerek | infra/prism/src/main/java/com/evolveum/midpoint/prism/crypto/Protector.java | Java | apache-2.0 | 3,505 |
package br.edu.unipampa.geketcc.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/*
* Autorizador Interceptor
*
* Classe responsável por realizar a autenticação dos usuários e restringir
* os mesmos, verificando as permissões de acesso a determinadas telas.
*
* @author Gean Pereira
* @since 09/12/2014
*/
public class AutorizadorInterceptor extends HandlerInterceptorAdapter {
/**
*
* Método executado antes da requisição ser totalmente processada, ou seja,
* realiza todas as verificações para depois retornar a resposta da
* requisição
*
* @param request
* @param response
* @param controller
* @return boolean
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object controller) throws Exception {
System.out.println("Processo de autenticação inciado");
String uri = request.getRequestURI();
if (uri.equals("/GekeTCC/")
|| uri.contains("/GekeTCC/login")
|| uri.contains("/GekeTCC/index")
|| uri.endsWith("efetuaLogin")
|| uri.contains("resources")) {
System.out.println("Acesso a tela de login");
return true;
}
if (request.getSession().getAttribute("usuarioLogado") != null || uri.endsWith("cadastroBanca")) {
System.out.println("Acesso as demais telas...");
return true;
}
System.out.println("Acesso negado!");
response.sendRedirect("/GekeTCC/");
return false;
}
}
| alexporthal/GerenciadorTCC_UNIPAMPA | GekeTCC/src/main/java/br/edu/unipampa/geketcc/service/AutorizadorInterceptor.java | Java | apache-2.0 | 1,777 |
--------------------------------------------------------------------------------
## Treebank Statistics (UD_Ancient_Greek)
This feature is universal.
It occurs with 2 different values: `Imp`, `Perf`.
8674 tokens (4%) have a non-empty value of `Aspect`.
4141 types (9%) occur at least once with a non-empty value of `Aspect`.
1747 lemmas (11%) occur at least once with a non-empty value of `Aspect`.
The feature is used with 2 part-of-speech tags: [grc-pos/VERB]() (8673; 4% instances), [grc-pos/CONJ]() (1; 0% instances).
### `VERB`
8673 [grc-pos/VERB]() tokens (19% of all `VERB` tokens) have a non-empty value of `Aspect`.
The most frequent other feature values with which `VERB` and `Aspect` co-occurred: <tt><a href="Tense.html">Tense</a>=Past</tt> (8653; 100%), <tt><a href="Gender.html">Gender</a>=EMPTY</tt> (7146; 82%), <tt><a href="Case.html">Case</a>=EMPTY</tt> (7146; 82%), <tt><a href="VerbForm.html">VerbForm</a>=Fin</tt> (6942; 80%), <tt><a href="Mood.html">Mood</a>=Ind</tt> (6839; 79%), <tt><a href="Person.html">Person</a>=3</tt> (5976; 69%), <tt><a href="Number.html">Number</a>=Sing</tt> (5906; 68%), <tt><a href="Voice.html">Voice</a>=Act</tt> (5841; 67%).
`VERB` tokens may have the following values of `Aspect`:
* `Imp` (5847; 67% of non-empty `Aspect`): _ἦν, ἔφη, ἦσαν, προσέφη, προσηύδα, ἔφατ̓, ηὔδα, εἶχον, ἔφαθ̓, ἦεν_
* `Perf` (2826; 33% of non-empty `Aspect`): _οἶδα, πεπνυμένος, οἶδ̓, ἔοικεν, οἶσθα, εἰδὼς, ἔοικε, εἰδέναι, εἰδώς, γεγονέναι_
* `EMPTY` (36833): _εἶναι, ἔχει, ἐστιν, ἔχων, γενέσθαι, ἐστὶ, ἐστι, φησιν, χρὴ, ἔχειν_
<table>
<tr><th>Paradigm <i>ἔχω</i></th><th><tt>Imp</tt></th><th><tt>Perf</tt></th></tr>
<tr><td><tt><a href="Case.html">Case</a>=Gen|<a href="Gender.html">Gender</a>=Masc|<a href="Number.html">Number</a>=Plur|<a href="VerbForm.html">VerbForm</a>=Part|<a href="Voice.html">Voice</a>=Act</tt></td><td></td><td><i>ἐσχηκότων</i></td></tr>
<tr><td><tt><a href="Mood.html">Mood</a>=Ind|<a href="Number.html">Number</a>=Sing|<a href="Person.html">Person</a>=1|<a href="VerbForm.html">VerbForm</a>=Fin|<a href="Voice.html">Voice</a>=Act</tt></td><td><i>εἶχον, ἔχον</i></td><td></td></tr>
<tr><td><tt><a href="Mood.html">Mood</a>=Ind|<a href="Number.html">Number</a>=Sing|<a href="Person.html">Person</a>=1|<a href="VerbForm.html">VerbForm</a>=Fin|<a href="Voice.html">Voice</a>=Mid,Pass</tt></td><td><i>ἐχόμην</i></td><td></td></tr>
<tr><td><tt><a href="Mood.html">Mood</a>=Ind|<a href="Number.html">Number</a>=Sing|<a href="Person.html">Person</a>=2|<a href="VerbForm.html">VerbForm</a>=Fin|<a href="Voice.html">Voice</a>=Act</tt></td><td><i>εἶχες, ἔχες</i></td><td><i>ἔσχηκας</i></td></tr>
<tr><td><tt><a href="Mood.html">Mood</a>=Ind|<a href="Number.html">Number</a>=Sing|<a href="Person.html">Person</a>=3|<a href="VerbForm.html">VerbForm</a>=Fin|<a href="Voice.html">Voice</a>=Act</tt></td><td><i>εἶχε, εἶχεν, ἔχε, ἔχεν, ἔσχεθεν, ἔχ̓, εἶχέ, εἶχ̓, ἔχεσκεν, σχέθε, ἔχει</i></td><td></td></tr>
<tr><td><tt><a href="Mood.html">Mood</a>=Ind|<a href="Number.html">Number</a>=Sing|<a href="Person.html">Person</a>=3|<a href="VerbForm.html">VerbForm</a>=Fin|<a href="Voice.html">Voice</a>=Mid,Pass</tt></td><td><i>εἴχετ̓, εἴχετο, εἴχεθ̓, ἔχετο</i></td><td></td></tr>
<tr><td><tt><a href="Mood.html">Mood</a>=Ind|<a href="Number.html">Number</a>=Plur|<a href="Person.html">Person</a>=1|<a href="VerbForm.html">VerbForm</a>=Fin|<a href="Voice.html">Voice</a>=Act</tt></td><td><i>εἴχομεν, ἔχομεν</i></td><td></td></tr>
<tr><td><tt><a href="Mood.html">Mood</a>=Ind|<a href="Number.html">Number</a>=Plur|<a href="Person.html">Person</a>=3|<a href="VerbForm.html">VerbForm</a>=Fin|<a href="Voice.html">Voice</a>=Act</tt></td><td><i>εἶχον, ἔχον, ἔχεσκον, εἶχόν</i></td><td></td></tr>
<tr><td><tt><a href="Mood.html">Mood</a>=Ind|<a href="Number.html">Number</a>=Plur|<a href="Person.html">Person</a>=3|<a href="VerbForm.html">VerbForm</a>=Fin|<a href="Voice.html">Voice</a>=Mid,Pass</tt></td><td><i>εἴχοντο</i></td><td></td></tr>
</table>
### `CONJ`
1 [grc-pos/CONJ]() tokens (0% of all `CONJ` tokens) have a non-empty value of `Aspect`.
`CONJ` tokens may have the following values of `Aspect`:
* `Imp` (1; 100% of non-empty `Aspect`): _κ-_
* `EMPTY` (9005): _καὶ, δὲ, ἀλλ̓, ἢ, ἀλλὰ, δ̓, καί, μὴ, τε, ἠδὲ_
--------------------------------------------------------------------------------
## Treebank Statistics (UD_Ancient_Greek-PROIEL)
This feature is universal.
It occurs with 2 different values: `Imp`, `Perf`.
22570 tokens (11%) have a non-empty value of `Aspect`.
9072 types (28%) occur at least once with a non-empty value of `Aspect`.
2155 lemmas (23%) occur at least once with a non-empty value of `Aspect`.
The feature is used with 1 part-of-speech tags: [grc-pos/VERB]() (22570; 11% instances).
### `VERB`
22570 [grc-pos/VERB]() tokens (53% of all `VERB` tokens) have a non-empty value of `Aspect`.
The most frequent other feature values with which `VERB` and `Aspect` co-occurred: <tt><a href="Tense.html">Tense</a>=Past</tt> (22569; 100%), <tt><a href="Gender.html">Gender</a>=EMPTY</tt> (17192; 76%), <tt><a href="Case.html">Case</a>=EMPTY</tt> (17187; 76%), <tt><a href="Voice.html">Voice</a>=Act</tt> (15480; 69%), <tt><a href="VerbForm.html">VerbForm</a>=Fin</tt> (15096; 67%), <tt><a href="Number.html">Number</a>=Sing</tt> (13284; 59%), <tt><a href="Mood.html">Mood</a>=Ind</tt> (12644; 56%), <tt><a href="Person.html">Person</a>=3</tt> (12098; 54%).
`VERB` tokens may have the following values of `Aspect`:
* `Imp` (4019; 18% of non-empty `Aspect`): _ἦν, ἦσαν, ἔλεγον, εἶχον, ἔφη, ἔλεγεν, εἶχε, ἔλεγε, ἐγίνετο, ἐκέλευε_
* `Perf` (18551; 82% of non-empty `Aspect`): _εἶπεν, ἐγένετο, γενέσθαι, ἀποκριθεὶς, εἶπαν, ἦλθεν, ἀπεκρίθη, ἐποίησεν, εἶπον, ἦλθον_
* `EMPTY` (19834): _ἐστιν, εἶναι, λέγει, λέγω, λέγων, λέγοντες, ἐστὶ, ἔστιν, ἔχει, ἔσται_
<table>
<tr><th>Paradigm <i>εἰμί#1</i></th><th><tt>Imp</tt></th><th><tt>Perf</tt></th></tr>
<tr><td><tt><a href="Mood.html">Mood</a>=Ind|<a href="Number.html">Number</a>=Sing|<a href="Person.html">Person</a>=1|<a href="VerbForm.html">VerbForm</a>=Fin|<a href="Voice.html">Voice</a>=Mid</tt></td><td><i>ἤμην</i></td><td></td></tr>
<tr><td><tt><a href="Mood.html">Mood</a>=Ind|<a href="Number.html">Number</a>=Sing|<a href="Person.html">Person</a>=2|<a href="VerbForm.html">VerbForm</a>=Fin|<a href="Voice.html">Voice</a>=Act</tt></td><td><i>ἦς, ἔας</i></td><td></td></tr>
<tr><td><tt><a href="Mood.html">Mood</a>=Ind|<a href="Number.html">Number</a>=Sing|<a href="Person.html">Person</a>=2|<a href="VerbForm.html">VerbForm</a>=Fin|<a href="Voice.html">Voice</a>=Mid</tt></td><td><i>ἦσθα</i></td><td></td></tr>
<tr><td><tt><a href="Mood.html">Mood</a>=Ind|<a href="Number.html">Number</a>=Sing|<a href="Person.html">Person</a>=3|<a href="VerbForm.html">VerbForm</a>=Fin|<a href="Voice.html">Voice</a>=Act</tt></td><td><i>ἦν, ἔσκε, ἣν</i></td><td></td></tr>
<tr><td><tt><a href="Mood.html">Mood</a>=Ind|<a href="Number.html">Number</a>=Plur|<a href="Person.html">Person</a>=1|<a href="VerbForm.html">VerbForm</a>=Fin|<a href="Voice.html">Voice</a>=Act</tt></td><td><i>ἦμεν</i></td><td></td></tr>
<tr><td><tt><a href="Mood.html">Mood</a>=Ind|<a href="Number.html">Number</a>=Plur|<a href="Person.html">Person</a>=1|<a href="VerbForm.html">VerbForm</a>=Fin|<a href="Voice.html">Voice</a>=Mid</tt></td><td><i>ἤμεθα</i></td><td></td></tr>
<tr><td><tt><a href="Mood.html">Mood</a>=Ind|<a href="Number.html">Number</a>=Plur|<a href="Person.html">Person</a>=2|<a href="VerbForm.html">VerbForm</a>=Fin|<a href="Voice.html">Voice</a>=Act</tt></td><td><i>ἦτε, ἔατε</i></td><td></td></tr>
<tr><td><tt><a href="Mood.html">Mood</a>=Ind|<a href="Number.html">Number</a>=Plur|<a href="Person.html">Person</a>=3|<a href="VerbForm.html">VerbForm</a>=Fin|<a href="Voice.html">Voice</a>=Act</tt></td><td><i>ἦσαν, ἦσάν, ἔσκον</i></td><td></td></tr>
<tr><td><tt><a href="VerbForm.html">VerbForm</a>=Inf|<a href="Voice.html">Voice</a>=Mid</tt></td><td></td><td><i>ἔσεσθαι</i></td></tr>
</table>
## Relations with Agreement in `Aspect`
The 10 most frequent relations where parent and child node agree in `Aspect`:
<tt>VERB --[<a href="../dep/conj.html">conj</a>]--> VERB</tt> (2138; 65%),
<tt>VERB --[<a href="../dep/remnant.html">remnant</a>]--> VERB</tt> (16; 53%).
| coltekin/docs | _includes/stats/grc/feat/Aspect.md | Markdown | apache-2.0 | 8,981 |
package com.git.huanghaifeng.java.basis;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializableDemo {
public static void main(String[] args) {
write();
read();
}
private static void write() {
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try {
FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in /tmp/employee.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
private static void read() {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
class Employee implements java.io.Serializable {
private static final long serialVersionUID = 1L;
public String name;
public String address;
public transient int SSN;// 临时不需要序列化的变量
public int number;
public void mailCheck() {
System.out.println("Mailing a check to " + name + " " + address);
}
} | prucehuang/quickly-start-java | src/main/java/com/git/huanghaifeng/java/basis/SerializableDemo.java | Java | apache-2.0 | 1,809 |
WishPal
=======
Ebay Challenge Hack
| Opportunity-Hack-San-Jose-2014/WishCompleted | README.md | Markdown | apache-2.0 | 37 |
package edu.harvard.mgh.lcs.sprout.forms.study.to;
import java.io.Serializable;
import java.util.Date;
public class NarrativeTO implements Serializable {
private static final long serialVersionUID = -5808452918661227118L;
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
| stephenlorenz/sproutstudy | sproutStudy_ejb/src/main/java/edu/harvard/mgh/lcs/sprout/forms/study/to/NarrativeTO.java | Java | apache-2.0 | 408 |
cordova.define("org.jshybugger.cordova.jsHybuggerLoader", function(require, exports, module) { var newLocation = typeof(JsHybuggerNI) !== 'undefined' ? JsHybuggerNI.getDebugUrl(window.location.toString()) : window.location.toString();
if (newLocation != window.location.toString()) {
console.log('jsHybugger redirected to: ' + newLocation);
window.location = newLocation;
}
});
| levexis/phonegap-fun | platforms/android/assets/www/plugins/org.jshybugger.cordova/www/jsHybuggerLoader.js | JavaScript | apache-2.0 | 381 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ToolGood.ReadyGo3.Test
{
public class Config
{
public const string DbFile = "db.db3";
[ThreadStatic]
private static SqlHelper _dbHelper;
[ThreadStatic]
private static SqlHelper _insertHelper;
public static SqlHelper DbHelper
{
get {
if (_dbHelper==null) {
_dbHelper = SqlHelperFactory.OpenSqliteFile(DbFile);
}
return _dbHelper;
}
}
public static SqlHelper InsertHelper
{
get {
if (_insertHelper == null) {
_insertHelper = SqlHelperFactory.OpenSqliteFile(DbFile);
_insertHelper._Config.Insert_DateTime_Default_Now = true;
_insertHelper._Config.Insert_Guid_Default_New = true;
_insertHelper._Config.Insert_String_Default_NotNull = true;
}
return _insertHelper;
}
}
public static SqlHelper TempHelper
{
get
{
return SqlHelperFactory.OpenSqliteFile(DbFile);
}
}
public static SqlHelper SqlServerHelper {
get {
return SqlHelperFactory.OpenDatabase(@"Server=(LocalDB)\MSSQLLocalDB; Integrated Security=true ;AttachDbFileName=F:\git\ToolGood.ReadyGo\ToolGood.ReadyGo3.CoreTest\bin\Debug\test.mdf", "", SqlType.SqlServer);
}
}
}
}
| toolgood/ToolGood.ReadyGo | ToolGood.ReadyGo3.CoreTest/Config.cs | C# | apache-2.0 | 1,665 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_312) on Wed Dec 15 20:57:54 UTC 2021 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.github.shynixn.petblocks.api.business.service</title>
<meta name="date" content="2021-12-15">
<meta name="keywords" content="com.github.shynixn.petblocks.api.business.service package">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="com.github.shynixn.petblocks.api.business.service";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../com/github/shynixn/petblocks/api/business/serializer/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../../../com/github/shynixn/petblocks/api/persistence/context/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/github/shynixn/petblocks/api/business/service/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package com.github.shynixn.petblocks.api.business.service</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Interface Summary table, listing interfaces, and an explanation">
<caption><span>Interface Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Interface</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/AIService.html" title="interface in com.github.shynixn.petblocks.api.business.service">AIService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/CarryPetService.html" title="interface in com.github.shynixn.petblocks.api.business.service">CarryPetService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/CombatPetService.html" title="interface in com.github.shynixn.petblocks.api.business.service">CombatPetService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/CommandService.html" title="interface in com.github.shynixn.petblocks.api.business.service">CommandService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/ConcurrencyService.html" title="interface in com.github.shynixn.petblocks.api.business.service">ConcurrencyService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/ConfigurationService.html" title="interface in com.github.shynixn.petblocks.api.business.service">ConfigurationService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/CoroutineSessionService.html" title="interface in com.github.shynixn.petblocks.api.business.service">CoroutineSessionService</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/DependencyHeadDatabaseService.html" title="interface in com.github.shynixn.petblocks.api.business.service">DependencyHeadDatabaseService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/DependencyPlaceholderApiService.html" title="interface in com.github.shynixn.petblocks.api.business.service">DependencyPlaceholderApiService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2020.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/DependencyService.html" title="interface in com.github.shynixn.petblocks.api.business.service">DependencyService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/EntityRegistrationService.html" title="interface in com.github.shynixn.petblocks.api.business.service">EntityRegistrationService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/EntityService.html" title="interface in com.github.shynixn.petblocks.api.business.service">EntityService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/EventService.html" title="interface in com.github.shynixn.petblocks.api.business.service">EventService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2019.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/FeedingPetService.html" title="interface in com.github.shynixn.petblocks.api.business.service">FeedingPetService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/GUIItemLoadService.html" title="interface in com.github.shynixn.petblocks.api.business.service">GUIItemLoadService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2019.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/GUIPetStorageService.html" title="interface in com.github.shynixn.petblocks.api.business.service">GUIPetStorageService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2019.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/GUIService.html" title="interface in com.github.shynixn.petblocks.api.business.service">GUIService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/HandService.html" title="interface in com.github.shynixn.petblocks.api.business.service">HandService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2019.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/HealthService.html" title="interface in com.github.shynixn.petblocks.api.business.service">HealthService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2019.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/ItemTypeService.html" title="interface in com.github.shynixn.petblocks.api.business.service">ItemTypeService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2019.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/LocalizationService.html" title="interface in com.github.shynixn.petblocks.api.business.service">LocalizationService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2020.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/LoggingService.html" title="interface in com.github.shynixn.petblocks.api.business.service">LoggingService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/MessageService.html" title="interface in com.github.shynixn.petblocks.api.business.service">MessageService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/NavigationService.html" title="interface in com.github.shynixn.petblocks.api.business.service">NavigationService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/ParticleService.html" title="interface in com.github.shynixn.petblocks.api.business.service">ParticleService</a></td>
<td class="colLast">
<div class="block">Handles particle effects in the world.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/PersistencePetMetaService.html" title="interface in com.github.shynixn.petblocks.api.business.service">PersistencePetMetaService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/PetActionService.html" title="interface in com.github.shynixn.petblocks.api.business.service">PetActionService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/PetDebugService.html" title="interface in com.github.shynixn.petblocks.api.business.service">PetDebugService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2019.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/PetService.html" title="interface in com.github.shynixn.petblocks.api.business.service">PetService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/PropertyTrackingService.html" title="interface in com.github.shynixn.petblocks.api.business.service">PropertyTrackingService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2019.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/ProtocolService.html" title="interface in com.github.shynixn.petblocks.api.business.service">ProtocolService</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/ProxyService.html" title="interface in com.github.shynixn.petblocks.api.business.service">ProxyService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/SoundService.html" title="interface in com.github.shynixn.petblocks.api.business.service">SoundService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/UpdateCheckService.html" title="interface in com.github.shynixn.petblocks.api.business.service">UpdateCheckService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2018.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/YamlSerializationService.html" title="interface in com.github.shynixn.petblocks.api.business.service">YamlSerializationService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2019.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../com/github/shynixn/petblocks/api/business/service/YamlService.html" title="interface in com.github.shynixn.petblocks.api.business.service">YamlService</a></td>
<td class="colLast">
<div class="block">Created by Shynixn 2019.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../com/github/shynixn/petblocks/api/business/serializer/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../../../com/github/shynixn/petblocks/api/persistence/context/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/github/shynixn/petblocks/api/business/service/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Shynixn/PetBlocks | docs/apidocs/com/github/shynixn/petblocks/api/business/service/package-summary.html | HTML | apache-2.0 | 16,857 |
package com.lpnpcs.yuanhelper.util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
*工具类
*/
public class ToolsUtil {
public static final int getHeightInPx(Context context) {
final int height = context.getResources().getDisplayMetrics().heightPixels;
return height;
}
public static final int getWidthInPx(Context context) {
final int width = context.getResources().getDisplayMetrics().widthPixels;
return width;
}
public static final int getHeightInDp(Context context) {
final float height = context.getResources().getDisplayMetrics().heightPixels;
int heightInDp = px2dip(context, height);
return heightInDp;
}
public static final int getWidthInDp(Context context) {
final float width = context.getResources().getDisplayMetrics().widthPixels;
int widthInDp = px2dip(context, width);
return widthInDp;
}
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
public static int px2sp(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
public static int sp2px(Context context, float spValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (spValue * scale + 0.5f);
}
/**
* 获得状态栏的高度
*
* @param context
* @return
*/
public static int getStatusHeight(Context context) {
int statusHeight = -1;
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
int height = Integer.parseInt(clazz.getField("status_bar_height")
.get(object).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
} catch (Exception e) {
e.printStackTrace();
}
return statusHeight;
}
/**
* 判断网络是否可用
*
* @param context
* @return
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
//如果仅仅是用来判断网络连接
//则可以使用 cm.getActiveNetworkInfo().isAvailable();
NetworkInfo[] info = cm.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
| lpnpcs/yuanhelper | app/src/main/java/com/lpnpcs/yuanhelper/util/ToolsUtil.java | Java | apache-2.0 | 3,201 |
{% extends 'base.html' %}
{% block title %}User SignUp{% endblock %}
{% load staticfiles %}
{% block body_block %}
<section id="registration" class="container">
<div class="padding_top">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="text-center">Volunteer SignUp</h1>
</div>
<div class="modal-body row">
<form data-toggle="validator" {% comment %}id="myForm"{% endcomment %} class="col-md-12" role="form" method="post" action="/account/registeruser/">
<fieldset class="registration-form">
{% csrf_token %}
<div class="form-group">
<div class="has-error">
<span class="help-block">
{{ form.non_field_errors }}
{{ form.name_of_field.errors }}
</span>
</div>
</div>
<div class="form-group">
<div class="has-error">
<span class="help-block">{{ form.username.errors }}</span>
</div>
<input type="text" id="username" name="username" placeholder="Username" class="form-control" value="{{ form.username.value|default_if_none:""}}" required>
</div>
<div class="form-group">
<div class="has-error">
<span class="help-block">{{ form.email.errors }}</span>
</div>
<input type="email" id="email" name="email" placeholder="E-mail" class="form-control" value="{{ form.email.value|default_if_none:""}}" data-error="Bruh, that email address is invalid" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<div class="has-error">
<span class="help-block">{{ form.password1.errors }}</span>
</div>
<input type="password" data-minlength="6" id="password" name="password1" placeholder="Password" class="form-control" required>
<!--span class="help-block">Minimum of 6 characters</span-->
</div>
<div class="form-group">
<div class="has-error">
<span class="help-block">{{ form.password2.errors }}</span>
</div>
<input type="password" id="verify" name="password2" placeholder="Password (Confirm)" class="form-control" data-match-error="Whoops, these don't match" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<div class="has-error">
<span class="help-block">{{ form.phone_number.errors }}</span>
</div>
<input type="text" id="phone_number" name="phone_number" placeholder="Phone (9999999999)" class="form-control" value="{{ form.phone_number.value|default_if_none:"}}" required>
</div>
<div class="form-group">
<button class="btn btn-primary btn-lg btn-block">SignUp</button>
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
<div class="col-md-12">
<span class="pull-right"><a href="/account/login/">Sign In</a></span>
</div>
</div>
</div>
</div>
</div>
</section><!--/#registration-->
{% comment %} {% block script_block %}
<script type="text/javascript">
$(document).ready(function(){
$('#myForm').validator()
});
</script>
{% endblock %}{% endcomment %}
{% endblock %} | Codeepy/Share.it | templates/account/register_user.html | HTML | apache-2.0 | 4,599 |
<?php
include("connect_db_login.php");
$cookie_name = "loggedin";
//session_start();
if (isset($_COOKIE[$cookie_name])) {
$cookie_value = $_COOKIE[$cookie_name];
header("Location: estacionate.php");
}
?>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>parkingUAI - la mejor forma de ahorrar tiempo</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/grayscale.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar navbar-custom navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">
<i class="fa fa-bars"></i>
</button>
<a class="navbar-brand page-scroll" href="index.php">
<i class="fa fa-play-circle"></i> <span class="light">parking</span> UAI
</a>
</div>
<div class="collapse navbar-collapse navbar-right navbar-main-collapse">
<ul class="nav navbar-nav">
<li class="hidden">
<a href="#page-top"></a>
</li>
<li>
<a class="page-scroll" href="#login">Entrar</a>
</li>
<li>
<a class="page-scroll" href="#register">Registrarme</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<header id="login" class="intro">
<div class="intro-body">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="transparentback">Entra a parking UAI</h1>
<form role="form" name="login" action="connect_db_login.php" method="POST"><p/>
<input type="text" id="username" name="username" placeholder="Usuario" required="required" /><p/>
<input type="password" id="password" name="password" placeholder="Password" required="required" /><p/>
<button type="submit" class="btn btn-default btn-lg">Entrar</button>
</form>
<?php
if (isset($_SESSION['error_message'])) {
echo $_SESSION['error_message'];
unset($_SESSION['error_message']);
}
?>
</div>
</div>
</div>
</div>
</header>
<section id="register" class="container content-section text-center">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<h1>Registrate en parking UAI</h1>
<form method="POST" action=""/><p/>
<input type="name" name="username" placeholder="Usuario" required="required" /><p/>
<input type="name" name="email" placeholder="Email" required="required" /><p/>
<input type="password" name="password" placeholder="Contraseña" required="required" /><p/>
<input type="password" name="rpassword" placeholder="Repetir Contraseña" required="required" /><p/>
<button type="submit" name="submit" class="btn btn-default btn-lg">Registrarme</button>
</form>
<?php
if(isset($_POST['submit'])) {
require("connect_db_register.php");
}
?>
</div>
</div>
</section>
<!-- Footer -->
<footer>
<div class="container text-center">
<p>Copyright © parkingUAI</p>
</div>
</footer>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="js/jquery.easing.min.js"></script>
<!-- Google Maps API Key - Use your own API key to enable the map feature. More information on the Google Maps API can be found at https://developers.google.com/maps/ -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCRngKslUGJTlibkQ3FkfTxj3Xss1UlZDA&sensor=false"></script>
<!-- Custom Theme JavaScript -->
<script src="js/grayscale.js"></script>
</body>
</html>
| feldrok/parkingUAI | entrar.php | PHP | apache-2.0 | 5,347 |
package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class NavigationHelper extends HelperBase {
public NavigationHelper(WebDriver wd) {
super(wd);
}
public void groupPage() {
if (isElementPresent(By.tagName("h1"))
&& wd.findElement(By.tagName("h1")).getText().equals("Groups")
&& isElementPresent(By.name("new"))) {
return;
}
click(By.linkText("groups"));
}
public void gotoHomePage() {
if (isElementPresent(By.id("maintable"))) {
return;
}
click(By.linkText("home"));
}
}
| barancev/java_pft | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/NavigationHelper.java | Java | apache-2.0 | 672 |
package noo.promise;
/**
* @author Tal Shani
*/
public interface PromiseHandler<T> {
void handle(T value);
}
| gwt-noo/promise | noo-promise/src/main/java/noo/promise/PromiseHandler.java | Java | apache-2.0 | 116 |
<?php
/**
* PHPMaker functions and classes
* (C) 2002-2007 e.World Technology Limited. All rights reserved.
*/
/**
* Functions to init arrays
*/
function ew_InitArray($iLen, $vValue) {
if (function_exists('array_fill')) { // PHP 4 >= 4.2.0,
return array_fill(0, $iLen, $vValue);
} else {
$aResult = array();
for ($iCount = 0; $iCount < $iLen; $iCount++)
$aResult[] = $vValue;
return $aResult;
}
}
function ew_Init2DArray($iLen1, $iLen2, $vValue) {
return ew_InitArray($iLen1, ew_InitArray($iLen2, $vValue));
}
/**
* Functions for converting encoding
*/
function ew_ConvertToUtf8($str) {
return ew_Convert(EW_ENCODING, "UTF-8", $str);
}
function ew_ConvertFromUtf8($str) {
return ew_Convert("UTF-8", EW_ENCODING, $str);
}
function ew_Convert($from, $to, $str)
{
if ($from != "" && $to != "" && $from != $to) {
if (function_exists("iconv")) {
return iconv($from, $to, $str);
} elseif (function_exists("mb_convert_encoding")) {
return mb_convert_encoding($str, $to, $from);
} else {
return $str;
}
} else {
return $str;
}
}
/**
* XML document class
*/
class cXMLDocument {
var $Encoding = EW_XML_ENCODING;
var $RootTagName = 'table';
var $RowTagName = 'row';
var $XmlDoc;
var $XmlTbl;
var $XmlRow;
var $XML = '';
var $NullValue = 'NULL';
function cXMLDocument() {
if (EW_IS_PHP5) {
$this->XmlDoc = new DOMDocument("1.0", $this->Encoding);
$this->XmlTbl = $this->XmlDoc->createElement($this->RootTagName);
$this->XmlDoc->appendChild($this->XmlTbl);
}
}
function BeginRow() {
if (EW_IS_PHP5) {
$this->XmlRow = $this->XmlDoc->createElement($this->RowTagName);
$this->XmlTbl->appendChild($this->XmlRow);
} else {
$this->XML .= "<$this->RowTagName>";
}
}
function EndRow() {
if (!EW_IS_PHP5) {
$this->XML .= "</$this->RowTagName>";
}
}
function AddField($name, $value) {
if (is_null($value)) $value = $this->NullValue;
if (EW_IS_PHP5) {
$value = ew_ConvertToUtf8($value); // Convert to UTF-8
$xmlfld = $this->XmlDoc->createElement($name);
$this->XmlRow->appendChild($xmlfld);
$xmlfld->appendChild($this->XmlDoc->createTextNode($value));
} else {
$value = ew_Convert(EW_ENCODING, EW_XML_ENCODING, $value); // Convert to output encoding
$this->XML .= "<$name>" . htmlspecialchars($value) . "</$name>";
}
}
function XML() {
if (EW_IS_PHP5) {
return $this->XmlDoc->saveXML();
} else {
return "<?xml version=\"1.0\"". (($this->Encoding <> "") ? " encoding=\"$this->Encoding\"" : "") .
" ?>\n<$this->RootTagName>$this->XML</$this->RootTagName>";
}
}
}
/**
* QueryString class
*/
class cQueryString {
var $values = array();
var $Count;
function cQueryString() {
$ar = explode("&", ew_ServerVar("QUERY_STRING"));
foreach ($ar as $p) {
$arp = explode("=", $p);
if (count($arp) == 2) $this->values[urldecode($arp[0])] = $arp[1];
}
$this->Count = count($this->values);
}
function getValue($name) {
return (array_key_exists($name, $this->values)) ? $this->values[$name] : "";
}
function getUrlDecodedValue($name) {
return urldecode($this->getValue($name));
}
function getRawUrlDecodedValue($name) {
return rawurldecode($this->getValue($name));
}
function getConvertedValue($name) {
return ew_ConvertFromUtf8($this->getRawUrlDecodedValue($name));
}
}
/**
* Email class
*/
class cEmail {
// Class properties
var $Sender; // Sender
var $Recipient; // Recipient
var $Cc; // Cc
var $Bcc; // Bcc
var $Subject; // Subject
var $Format; // Format
var $Content; // Content
function cEmail() {
$this->Sender = "";
$this->Recipient = "";
$this->Cc = "";
$this->Bcc = "";
$this->Subject = "";
$this->Format = "";
$this->Content = "";
}
// Method to load email from template
function Load($fn) {
$fn = realpath(".") . EW_PATH_DELIMITER . $fn;
$sWrk = ew_ReadFile($fn); // Load text file content
if ($sWrk <> "") {
// Locate Header & Mail Content
if (EW_IS_WINDOWS) {
$i = strpos($sWrk, "\r\n\r\n");
} else {
$i = strpos($sWrk, "\n\n");
if ($i === FALSE) $i = strpos($sWrk, "\r\n\r\n");
}
if ($i > 0) {
$sHeader = substr($sWrk, 0, $i);
$this->Content = trim(substr($sWrk, $i, strlen($sWrk)));
if (EW_IS_WINDOWS) {
$arrHeader = explode("\r\n", $sHeader);
} else {
$arrHeader = explode("\n", $sHeader);
}
for ($j = 0; $j < count($arrHeader); $j++) {
$i = strpos($arrHeader[$j], ":");
if ($i > 0) {
$sName = trim(substr($arrHeader[$j], 0, $i));
$sValue = trim(substr($arrHeader[$j], $i+1, strlen($arrHeader[$j])));
switch (strtolower($sName))
{
case "subject":
$this->Subject = $sValue;
break;
case "from":
$this->Sender = $sValue;
break;
case "to":
$this->Recipient = $sValue;
break;
case "cc":
$this->Cc = $sValue;
break;
case "bcc":
$this->Bcc = $sValue;
break;
case "format":
$this->Format = $sValue;
break;
}
}
}
}
}
}
// Method to replace sender
function ReplaceSender($ASender) {
$this->Sender = str_replace('<!--$From-->', $ASender, $this->Sender);
}
// Method to replace recipient
function ReplaceRecipient($ARecipient) {
$this->Recipient = str_replace('<!--$To-->', $ARecipient, $this->Recipient);
}
// Method to add Cc email
function AddCc($ACc) {
if ($ACc <> "") {
if ($this->Cc <> "") $this->Cc .= ";";
$this->Cc .= $ACc;
}
}
// Method to add Bcc email
function AddBcc($ABcc) {
if ($ABcc <> "") {
if ($this->Bcc <> "") $this->Bcc .= ";";
$this->Bcc .= $ABcc;
}
}
// Method to replace subject
function ReplaceSubject($ASubject) {
$this->Subject = str_replace('<!--$Subject-->', $ASubject, $this->Subject);
}
// Method to replace content
function ReplaceContent($Find, $ReplaceWith) {
$this->Content = str_replace($Find, $ReplaceWith, $this->Content);
}
// Method to send email
function Send() {
return ew_SendEmail($this->Sender, $this->Recipient, $this->Cc, $this->Bcc,
$this->Subject, $this->Content, $this->Format);
}
}
/**
* Pager item class
*/
class cPagerItem {
var $Start;
var $Text;
var $Enabled;
}
/**
* Numeric pager class
*/
class cNumericPager {
var $Items = array();
var $Count, $FromIndex, $ToIndex, $RecordCount, $PageSize, $Range;
var $FirstButton, $PrevButton, $NextButton, $LastButton;
var $ButtonCount = 0;
function cNumericPager($StartRec, $DisplayRecs, $TotalRecs, $RecRange)
{
$this->FirstButton = new cPagerItem;
$this->PrevButton = new cPagerItem;
$this->NextButton = new cPagerItem;
$this->LastButton = new cPagerItem;
$this->FromIndex = intval($StartRec);
$this->PageSize = intval($DisplayRecs);
$this->RecordCount = intval($TotalRecs);
$this->Range = intval($RecRange);
if ($this->PageSize == 0) return;
if ($this->FromIndex > $this->RecordCount)
$this->FromIndex = $this->RecordCount;
$this->ToIndex = $this->FromIndex + $this->PageSize - 1;
if ($this->ToIndex > $this->RecordCount)
$this->ToIndex = $this->RecordCount;
// setup
$this->SetupNumericPager();
// update button count
if ($this->FirstButton->Enabled) $this->ButtonCount++;
if ($this->PrevButton->Enabled) $this->ButtonCount++;
if ($this->NextButton->Enabled) $this->ButtonCount++;
if ($this->LastButton->Enabled) $this->ButtonCount++;
$this->ButtonCount += count($this->Items);
}
// Add pager item
function AddPagerItem($StartIndex, $Text, $Enabled)
{
$Item = new cPagerItem;
$Item->Start = $StartIndex;
$Item->Text = $Text;
$Item->Enabled = $Enabled;
$this->Items[] = $Item;
}
// Setup pager items
function SetupNumericPager()
{
if ($this->RecordCount > $this->PageSize) {
$Eof = ($this->RecordCount < ($this->FromIndex + $this->PageSize));
$HasPrev = ($this->FromIndex > 1);
// First Button
$TempIndex = 1;
$this->FirstButton->Start = $TempIndex;
$this->FirstButton->Enabled = ($this->FromIndex > $TempIndex);
// Prev Button
$TempIndex = $this->FromIndex - $this->PageSize;
if ($TempIndex < 1) $TempIndex = 1;
$this->PrevButton->Start = $TempIndex;
$this->PrevButton->Enabled = $HasPrev;
// Page links
if ($HasPrev || !$Eof) {
$x = 1;
$y = 1;
$dx1 = intval(($this->FromIndex-1)/($this->PageSize*$this->Range))*$this->PageSize*$this->Range + 1;
$dy1 = intval(($this->FromIndex-1)/($this->PageSize*$this->Range))*$this->Range + 1;
if (($dx1+$this->PageSize*$this->Range-1) > $this->RecordCount) {
$dx2 = intval($this->RecordCount/$this->PageSize)*$this->PageSize + 1;
$dy2 = intval($this->RecordCount/$this->PageSize) + 1;
} else {
$dx2 = $dx1 + $this->PageSize*$this->Range - 1;
$dy2 = $dy1 + $this->Range - 1;
}
while ($x <= $this->RecordCount) {
if ($x >= $dx1 && $x <= $dx2) {
$this->AddPagerItem($x, $y, $this->FromIndex<>$x);
$x += $this->PageSize;
$y++;
} elseif ($x >= ($dx1-$this->PageSize*$this->Range) && $x <= ($dx2+$this->PageSize*$this->Range)) {
if ($x+$this->Range*$this->PageSize < $this->RecordCount) {
$this->AddPagerItem($x, $y . "-" . ($y+$this->Range-1), TRUE);
} else {
$ny = intval(($this->RecordCount-1)/$this->PageSize) + 1;
if ($ny == $y) {
$this->AddPagerItem($x, $y, TRUE);
} else {
$this->AddPagerItem($x, $y . "-" . $ny, TRUE);
}
}
$x += $this->Range*$this->PageSize;
$y += $this->Range;
} else {
$x += $this->Range*$this->PageSize;
$y += $this->Range;
}
}
}
// Next Button
$TempIndex = $this->FromIndex + $this->PageSize;
$this->NextButton->Start = $TempIndex;
$this->NextButton->Enabled = !$Eof;
// Last Button
$TempIndex = intval(($this->RecordCount-1)/$this->PageSize)*$this->PageSize + 1;
$this->LastButton->Start = $TempIndex;
$this->LastButton->Enabled = ($this->FromIndex < $TempIndex);
}
}
}
/**
* PrevNext pager class
*/
class cPrevNextPager {
var $FirstButton, $PrevButton, $NextButton, $LastButton;
var $CurrentPage, $PageCount, $FromIndex, $ToIndex, $RecordCount;
function cPrevNextPager($StartRec, $DisplayRecs, $TotalRecs)
{
$this->FirstButton = new cPagerItem;
$this->PrevButton = new cPagerItem;
$this->NextButton = new cPagerItem;
$this->LastButton = new cPagerItem;
$this->FromIndex = intval($StartRec);
$this->PageSize = intval($DisplayRecs);
$this->RecordCount = intval($TotalRecs);
if ($this->PageSize == 0) return;
$this->CurrentPage = intval(($this->FromIndex-1)/$this->PageSize) + 1;
$this->PageCount = intval(($this->RecordCount-1)/$this->PageSize) + 1;
if ($this->FromIndex > $this->RecordCount)
$this->FromIndex = $this->RecordCount;
$this->ToIndex = $this->FromIndex + $this->PageSize - 1;
if ($this->ToIndex > $this->RecordCount)
$this->ToIndex = $this->RecordCount;
// First Button
$TempIndex = 1;
$this->FirstButton->Start = $TempIndex;
$this->FirstButton->Enabled = ($TempIndex <> $this->FromIndex);
// Prev Button
$TempIndex = $this->FromIndex - $this->PageSize;
if ($TempIndex < 1) $TempIndex = 1;
$this->PrevButton->Start = $TempIndex;
$this->PrevButton->Enabled = ($TempIndex <> $this->FromIndex);
// Next Button
$TempIndex = $this->FromIndex + $this->PageSize;
if ($TempIndex > $this->RecordCount)
$TempIndex = $this->FromIndex;
$this->NextButton->Start = $TempIndex;
$this->NextButton->Enabled = ($TempIndex <> $this->FromIndex);
// Last Button
$TempIndex = intval(($this->RecordCount-1)/$this->PageSize)*$this->PageSize + 1;
$this->LastButton->Start = $TempIndex;
$this->LastButton->Enabled = ($TempIndex <> $this->FromIndex);
}
}
/**
* Field class
*/
class cField {
var $TblVar; // Table var
var $FldName; // Field name
var $FldVar; // Field var
var $FldExpression; // Field expression (used in sql)
var $FldType; // Field type
var $FldDataType; // PHPMaker Field type
var $AdvancedSearch; // AdvancedSearch Object
var $Upload; // Upload Object
var $FldDateTimeFormat; // Date time format
var $CssStyle; // Css style
var $CssClass; // Css class
var $ImageAlt; // Image alt
var $ImageWidth = 0; // Image width
var $ImageHeight = 0; // Image height
var $ViewCustomAttributes; // View custom attributes
var $EditCustomAttributes; // Edit custom attributes
var $Count; // Count
var $Total; // Total
var $TrueValue = '1';
var $FalseValue = '0';
function cField($tblvar, $fldvar, $fldname, $fldexpression, $fldtype, $flddtfmt, $upload = FALSE) {
$this->TblVar = $tblvar;
$this->FldVar = $fldvar;
$this->FldName = $fldname;
$this->FldExpression = $fldexpression;
$this->FldType = $fldtype;
$this->FldDataType = ew_FieldDataType($fldtype);
$this->FldDateTimeFormat = $flddtfmt;
$this->AdvancedSearch = new cAdvancedSearch();
if ($upload) $this->Upload = new cUpload($this->TblVar, $this->FldVar, ($this->FldDataType == EW_DATATYPE_BLOB));
}
// View Attributes
function ViewAttributes() {
$sAtt = "";
if (trim($this->CssStyle) <> "") {
$sAtt .= " style=\"" . trim($this->CssStyle) . "\"";
}
if (trim($this->CssClass) <> "") {
$sAtt .= " class=\"" . trim($this->CssClass) . "\"";
}
if (trim($this->ImageAlt) <> "") {
$sAtt .= " alt=\"" . trim($this->ImageAlt) . "\"";
}
if (intval($this->ImageWidth) > 0) {
$sAtt .= " width=\"" . intval($this->ImageWidth) . "\"";
}
if (intval($this->ImageHeight) > 0) {
$sAtt .= " height=\"" . intval($this->ImageHeight) . "\"";
}
if (trim($this->ViewCustomAttributes) <> "") {
$sAtt .= " " . trim($this->ViewCustomAttributes);
}
return $sAtt;
}
// Edit Attributes
function EditAttributes() {
$sAtt = "";
if (trim($this->CssStyle) <> "") {
$sAtt .= " style=\"" . trim($this->CssStyle) . "\"";
}
if (trim($this->CssClass) <> "") {
$sAtt .= " class=\"" . trim($this->CssClass) . "\"";
}
if (trim($this->EditCustomAttributes) <> "") {
$sAtt .= " " . trim($this->EditCustomAttributes);
}
return $sAtt;
}
var $CellCssClass; // Cell Css class
var $CellCssStyle; // Cell Css style
// Cell Attributes
function CellAttributes() {
$sAtt = "";
if (trim($this->CellCssStyle) <> "") {
$sAtt .= " style=\"" . trim($this->CellCssStyle) . "\"";
}
if (trim($this->CellCssClass) <> "") {
$sAtt .= " class=\"" . trim($this->CellCssClass) . "\"";
}
return $sAtt;
}
// Sort Attributes
function getSort() {
return @$_SESSION[EW_PROJECT_NAME . "_" . $this->TblVar . "_" . EW_TABLE_SORT . "_" . $this->FldVar];
}
function setSort($v) {
if (@$_SESSION[EW_PROJECT_NAME . "_" . $this->TblVar . "_" . EW_TABLE_SORT . "_" . $this->FldVar] <> $v) {
$_SESSION[EW_PROJECT_NAME . "_" . $this->TblVar . "_" . EW_TABLE_SORT . "_" . $this->FldVar] = $v;
}
}
function ReverseSort() {
return ($this->getSort() == "ASC") ? "DESC" : "ASC";
}
var $MultiUpdate; // Multi update
var $CurrentValue; // Current value
var $ViewValue; // View value
var $EditValue; // Edit value
var $EditValue2; // Edit value 2 (search)
var $HrefValue; // Href value
// Form value
var $FormValue;
function setFormValue($v) {
$this->FormValue = ew_StripSlashes($v);
if (is_array($this->FormValue)) $this->FormValue = implode(",", $this->FormValue);
$this->CurrentValue = $this->FormValue;
}
// QueryString value
var $QueryStringValue;
function setQueryStringValue($v) {
$this->QueryStringValue = ew_StripSlashes($v);
$this->CurrentValue = $this->QueryStringValue;
}
// Database Value
var $DbValue;
function setDbValue($v) {
$this->DbValue = $v;
$this->CurrentValue = $this->DbValue;
}
// Set database value with error default
function SetDbValueDef($value, $default) {
switch ($this->FldType) {
case 2:
case 3:
case 16:
case 17:
case 18: // Int
$DbValue = (is_numeric($value)) ? intval($value) : $default;
break;
case 19:
case 20:
case 21: // Big Int
$DbValue = (is_numeric($value)) ? $value : $default;
break;
case 5:
case 6:
case 14:
case 131: // Double
case 4: // Single
if (function_exists('floatval')) { // PHP 4 >= 4.2.0
$DbValue = (is_numeric($value)) ? floatval($value) : $default;
} else {
$DbValue = (is_numeric($value)) ? (float)$value : $default;
}
break;
case 7:
case 133:
case 134:
case 135: //Date
case 201:
case 203:
case 129:
case 130:
case 200:
case 202: // String
$DbValue = trim($value);
if ($DbValue == "") $DbValue = $default;
break;
case 128:
case 204:
case 205: // Binary
$DbValue = is_null($value) ? $default : $value;
break;
case 72: // GUID
if (function_exists('preg_match')) {
$p1 = '/^{{1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}}{1}$/';
$p2 = '/^([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}$/';
$DbValue = (preg_match($p1, trim($value)) || preg_match($p2, trim($value))) ? trim($value) : $default;
} else {
$DbValue = (is_string($value) && ((strlen($value) == 38 && strspn($value, '{}-0123456789abcdefABCDEF') == 38)) ||
(strlen($value) == 36 && strspn($value, '-0123456789abcdefABCDEF') == 36)) ? $value : $default;
}
break;
default:
$DbValue = $value;
}
$this->setDbValue($DbValue);
}
// Session Value
function getSessionValue() {
return @$_SESSION[EW_PROJECT_NAME . "_" . $this->TblVar . "_" . $this->FldVar . "_SessionValue"];
}
function setSessionValue($v) {
$_SESSION[EW_PROJECT_NAME . "_" . $this->TblVar . "_" . $this->FldVar . "_SessionValue"] = $v;
}
}
?>
<?php
/**
* Advanced Search class
*/
class cAdvancedSearch {
var $SearchValue; // Search value
var $SearchOperator; // Search operator
var $SearchCondition; // Search condition
var $SearchValue2; // Search value 2
var $SearchOperator2; // Search operator 2
}
?>
<?php
/**
* Upload class
*/
class cUpload {
var $Index = 0; // Index to handle multiple form elements
var $TblVar; // Table variable
var $FldVar; // Field variable
var $Message; // Error message
var $DbValue; // Value from database
var $Value = NULL; // Upload value
var $Binary = NULL; // Temporary file
var $IsBinary; // Is BLOB field
var $Action; // Upload action
var $UploadPath; // Upload path
var $FileName; // Upload file name
var $FileSize; // Upload file size
var $ContentType; // File content type
var $ImageWidth; // Image width
var $ImageHeight; // Image height
// Class initialize
function cUpload($TblVar, $FldVar, $Binary = FALSE) {
$this->TblVar = $TblVar;
$this->FldVar = $FldVar;
$this->IsBinary = $Binary;
}
function getSessionID() {
return EW_PROJECT_NAME . "_" . $this->TblVar . "_" . $this->FldVar . "_" . $this->Index;
}
// Save Db value to Session
function SaveDbToSession() {
$sSessionID = $this->getSessionID();
$_SESSION[$sSessionID . "_DbValue"] = $this->DbValue;
}
// Restore Db value from Session
function RestoreDbFromSession() {
$sSessionID = $this->getSessionID();
$this->DbValue = @$_SESSION[$sSessionID . "_DbValue"];
}
// Remove Db value from Session
function RemoveDbFromSession() {
$sSessionID = $this->getSessionID();
unset($_SESSION[$sSessionID . "_DbValue"]);
}
// Save Upload values to Session
function SaveToSession() {
$sSessionID = $this->getSessionID();
$_SESSION[$sSessionID . "_Action"] = $this->Action;
$_SESSION[$sSessionID . "_FileSize"] = $this->FileSize;
$_SESSION[$sSessionID . "_FileName"] = $this->FileName;
$_SESSION[$sSessionID . "_ContentType"] = $this->ContentType;
$_SESSION[$sSessionID . "_ImageWidth"] = $this->ImageWidth;
$_SESSION[$sSessionID . "_ImageHeight"] = $this->ImageHeight;
$path = pathinfo($this->FileName);
$ext = @$path['extension'];
if ($ext == '') $ext = 'tmp';
$f = tempnam(ew_TmpFolder(), 'tmp') . '.' . $ext;
if (!is_null($this->Value)) {
if (rename($this->Value, $this->Value . '.' . $ext)) {
$this->Value .= '.' . $ext;
} elseif (move_uploaded_file($this->Value, $f)) {
$this->Value = $f;
}
}
$_SESSION[$sSessionID . "_Value"] = $this->Value;
}
// Restore Upload values from Session
function RestoreFromSession() {
$sSessionID = $this->getSessionID();
$this->Action = @$_SESSION[$sSessionID . "_Action"];
$this->FileSize = @$_SESSION[$sSessionID . "_FileSize"];
$this->FileName = @$_SESSION[$sSessionID . "_FileName"];
$this->ContentType = @$_SESSION[$sSessionID . "_ContentType"];
$this->ImageWidth = @$_SESSION[$sSessionID . "_ImageWidth"];
$this->ImageHeight = @$_SESSION[$sSessionID . "_ImageHeight"];
$this->Value = @$_SESSION[$sSessionID . "_Value"];
}
// Remove Upload values from Session
function RemoveFromSession() {
$sSessionID = $this->getSessionID();
unset($_SESSION[$sSessionID . "_Action"]);
unset($_SESSION[$sSessionID . "_FileSize"]);
unset($_SESSION[$sSessionID . "_FileName"]);
unset($_SESSION[$sSessionID . "_ContentType"]);
unset($_SESSION[$sSessionID . "_ImageWidth"]);
unset($_SESSION[$sSessionID . "_ImageHeight"]);
if (is_file($this->Value)) @unlink($this->Value);
unset($_SESSION[$sSessionID . "_Value"]);
}
// function to check the file type of the uploaded file
function UploadAllowedFileExt($filename) {
if (trim($filename) == "") return TRUE;
$extension = substr(strtolower(strrchr($filename, ".")), 1);
$allowExt = explode(",", strtolower(EW_UPLOAD_ALLOWED_FILE_EXT));
return in_array($extension, $allowExt);
}
// Get upload file
function UploadFile() {
global $objForm;
$this->Value = NULL; // Reset first
$sFldVar = $this->FldVar;
$sFldVarAction = "a" . substr($sFldVar, 1);
$sFldVarWidth = "wd" . substr($sFldVar, 1);
$sFldVarHeight = "ht" . substr($sFldVar, 1);
// Get action
$this->Action = $objForm->GetValue($sFldVarAction);
// Get and check the upload file size
$this->FileSize = $objForm->GetUploadFileSize($sFldVar);
if ($this->FileSize > 0 && intval(EW_MAX_FILE_SIZE) > 0) {
if ($this->FileSize > intval(EW_MAX_FILE_SIZE)) {
$this->Message = str_replace("%s", EW_MAX_FILE_SIZE, "Max. file size (%s bytes) exceeded.");
return FALSE;
}
}
// Get and check the upload file type
$this->FileName = $objForm->GetUploadFileName($sFldVar);
$this->FileName = str_replace(" ", "_", $this->FileName); // Replace space with underscore
if (!$this->UploadAllowedFileExt($this->FileName)) {
$this->Message = "File type is not allowed.";
return FALSE;
}
// Get upload file content type
$this->ContentType = $objForm->GetUploadFileContentType($sFldVar);
// Get upload value
//$this->Value = $objForm->GetUploadFileData($sFldVar);
if ($objForm->IsUploadedFile($sFldVar)) {
$this->Value = $objForm->GetUploadFileTmpName($sFldVar); // store the tmp file name only
}
// Get image width and height
$this->ImageWidth = $objForm->GetUploadImageWidth($sFldVar);
$this->ImageHeight = $objForm->GetUploadImageHeight($sFldVar);
if ($this->ImageWidth < 0 || $this->ImageHeight < 0) {
$this->ImageWidth = $objForm->GetValue($sFldVarWidth);
$this->ImageHeight = $objForm->GetValue($sFldVarHeight);
}
return TRUE; // Normal return
}
// Resize image
function Resize($width, $height, $quality) {
if (!is_null($this->Value)) {
$wrkwidth = $width;
$wrkheight = $height;
if ($this->IsBinary) {
$this->Binary = ew_ResizeFileToBinary($this->Value, $wrkwidth, $wrkheight, $quality);
$this->FileSize = strlen($this->Binary);
} else {
ew_ResizeFile($this->Value, $this->Value, $wrkwidth, $wrkheight, $quality);
$this->FileSize = filesize($this->Value);
}
$this->ImageWidth = $wrkwidth;
$this->ImageHeight = $wrkheight;
}
}
// Get binary date
function GetBinary() {
if (is_null($this->Binary)) {
if (!is_null($this->Value)) return ew_ReadFile($this->Value);
} else {
return $this->Binary;
}
return NULL;
}
}
?>
<?php
/**
* Advanced Security class
*/
class cAdvancedSecurity {
var $UserLevel = array();
var $UserLevelPriv = array();
// Current user name
function getCurrentUserName() {
return strval(@$_SESSION[EW_SESSION_USER_NAME]);
}
function setCurrentUserName($v) {
$_SESSION[EW_SESSION_USER_NAME] = $v;
}
function CurrentUserName() {
return $this->getCurrentUserName();
}
// Current User ID
function getCurrentUserID() {
return strval(@$_SESSION[EW_SESSION_USER_ID]);
}
function setCurrentUserID($v) {
$_SESSION[EW_SESSION_USER_ID] = $v;
}
function CurrentUserID() {
return $this->getCurrentUserID();
}
// Current parent User ID
function getCurrentParentUserID() {
return strval(@$_SESSION[EW_SESSION_PARENT_USER_ID]);
}
function setCurrentParentUserID($v) {
$_SESSION[EW_SESSION_PARENT_USER_ID] = $v;
}
function CurrentParentUserID() {
return $this->getCurrentParentUserID();
}
// Current User Level id
function getCurrentUserLevelID() {
return @$_SESSION[EW_SESSION_USER_LEVEL_ID];
}
function setCurrentUserLevelID($v) {
$_SESSION[EW_SESSION_USER_LEVEL_ID] = $v;
}
function CurrentUserLevelID() {
return $this->getCurrentUserLevelID();
}
// Current User Level value
function getCurrentUserLevel() {
return @$_SESSION[EW_SESSION_USER_LEVEL];
}
function setCurrentUserLevel($v) {
$_SESSION[EW_SESSION_USER_LEVEL] = $v;
}
function CurrentUserLevel() {
return $this->getCurrentUserLevel();
}
// Can add
function CanAdd() {
return (($this->CurrentUserLevel() & EW_ALLOW_ADD) == EW_ALLOW_ADD);
}
// Can delete
function CanDelete() {
return (($this->CurrentUserLevel() & EW_ALLOW_DELETE) == EW_ALLOW_DELETE);
}
// Can edit
function CanEdit() {
return (($this->CurrentUserLevel() & EW_ALLOW_EDIT) == EW_ALLOW_EDIT);
}
// Can view
function CanView() {
return (($this->CurrentUserLevel() & EW_ALLOW_VIEW) == EW_ALLOW_VIEW);
}
// Can list
function CanList() {
return (($this->CurrentUserLevel() & EW_ALLOW_LIST) == EW_ALLOW_LIST);
}
// Can report
function CanReport() {
return (($this->CurrentUserLevel() & EW_ALLOW_REPORT) == EW_ALLOW_REPORT);
}
// Can search
function CanSearch() {
return (($this->CurrentUserLevel() & EW_ALLOW_SEARCH) == EW_ALLOW_SEARCH);
}
// Can admin
function CanAdmin() {
return (($this->CurrentUserLevel() & EW_ALLOW_ADMIN) == EW_ALLOW_ADMIN);
}
// Last url
function LastUrl() {
//globlal $_COOKIE;
return @$_COOKIE[EW_PROJECT_NAME]['LastUrl'];
}
// Save last url
function SaveLastUrl() {
$s = ew_ServerVar("SCRIPT_NAME");
$q = ew_ServerVar("QUERY_STRING");
if ($q <> "") $s .= "?" . $q;
if ($this->LastUrl() == $s) $s = "";
@setcookie(EW_PROJECT_NAME . '[LastUrl]', $s);
}
// Auto login
function AutoLogin() {
if (@$_COOKIE[EW_PROJECT_NAME]['AutoLogin'] == "autologin") {
$usr = @$_COOKIE[EW_PROJECT_NAME]['UserName'];
$pwd = @$_COOKIE[EW_PROJECT_NAME]['Password'];
$pwd = TEAdecrypt($pwd, EW_RANDOM_KEY);
$AutoLogin = $this->ValidateUser($usr, $pwd);
} else {
$AutoLogin = FALSE;
}
return $AutoLogin;
}
// Validate user
function ValidateUser($usr, $pwd) {
global $conn;
global $admin;
$ValidateUser = FALSE;
// Check hard coded admin first
if (EW_CASE_SENSITIVE_PASSWORD) {
$ValidateUser = (EW_ADMIN_USER_NAME == $usr && EW_ADMIN_PASSWORD == $pwd);
} else {
$ValidateUser = (strtolower(EW_ADMIN_USER_NAME) == strtolower($usr) &&
strtolower(EW_ADMIN_PASSWORD) == strtolower($pwd));
}
if ($ValidateUser) {
$_SESSION[EW_SESSION_STATUS] = "login";
$_SESSION[EW_SESSION_SYS_ADMIN] = 1; // System Administrator
$this->setCurrentUserName("Administrator"); // Load user name
$this->setCurrentUserLevelID(-1); // System Administrator
$this->SetUpUserLevel();
}
// Check other users
if (!$ValidateUser) {
$sFilter = "(`username` = '" . ew_AdjustSql($usr) . "')";
// Set up filter (Sql Where Clause) and get Return Sql
// Sql constructor in <UseTable> class, <UserTable>info.php
$admin->CurrentFilter = $sFilter;
$sSql = $admin->SQL();
if ($rs = $conn->Execute($sSql)) {
if (!$rs->EOF) {
if (EW_CASE_SENSITIVE_PASSWORD) {
if (EW_MD5_PASSWORD) {
$ValidateUser = ($rs->fields('password') == md5($pwd));
} else {
$ValidateUser = ($rs->fields('password') == $pwd);
}
} else {
if (EW_MD5_PASSWORD) {
$ValidateUser = ($rs->fields('password') == md5(strtolower($pwd)));
} else {
$ValidateUser = (strtolower($rs->fields('password')) == strtolower($pwd));
}
}
if ($ValidateUser) {
$_SESSION[EW_SESSION_STATUS] = "login";
$_SESSION[EW_SESSION_SYS_ADMIN] = 0; // Non System Administrator
$this->setCurrentUserName($rs->fields('username')); // Load user name
if (is_null($rs->fields('privilegi_admin'))) {
$this->setCurrentUserLevelID(0);
} else {
$this->setCurrentUserLevelID(intval($rs->fields('privilegi_admin'))); // Load User Level
}
$this->SetUpUserLevel();
}
}
$rs->Close();
}
}
return $ValidateUser;
}
// Static User Level security
function SetUpUserLevel() {
// User Level definitions
array_splice($this->UserLevel, 0);
$this->UserLevel[] = array("0", "Default");
$this->UserLevel[] = array("1", "Manager");
array_splice($this->UserLevelPriv, 0);
$this->UserLevelPriv[] = array("multiprocesssteps", 0, 0);
$this->UserLevelPriv[] = array("multiprocesssteps", 1, 0);
$this->UserLevelPriv[] = array("process", 0, 0);
$this->UserLevelPriv[] = array("process", 1, 8);
$this->UserLevelPriv[] = array("processparams", 0, 0);
$this->UserLevelPriv[] = array("processparams", 1, 0);
$this->UserLevelPriv[] = array("processparamsvalue", 0, 0);
$this->UserLevelPriv[] = array("processparamsvalue", 1, 0);
$this->UserLevelPriv[] = array("setprocess", 0, 0);
$this->UserLevelPriv[] = array("setprocess", 1, 8);
$this->UserLevelPriv[] = array("processstatus", 0, 0);
$this->UserLevelPriv[] = array("processstatus", 1, 8);
$this->UserLevelPriv[] = array("admin", 0, 0);
$this->UserLevelPriv[] = array("admin", 1, 0);
$this->UserLevelPriv[] = array("paramsconnection", 0, 0);
$this->UserLevelPriv[] = array("paramsconnection", 1, 8);
// Save the User Level to session variable
$this->SaveUserLevel();
}
// Load current User Level
function LoadCurrentUserLevel($Table) {
$this->LoadUserLevel();
$this->setCurrentUserLevel($this->CurrentUserLevelPriv($Table));
}
// Get current user privilege
function CurrentUserLevelPriv($TableName) {
if ($this->IsLoggedIn()) {
return $this->GetUserLevelPrivEx($TableName, $this->CurrentUserLevelID());
} else {
//return $this->GetUserLevelPrivEx($TableName, 0);
return 0;
}
}
// Get user privilege based on table name and User Level
function GetUserLevelPrivEx($TableName, $UserLevelID) {
if (strval($UserLevelID) == "-1") { // System Administrator
if (defined("EW_USER_LEVEL_COMPAT")) {
return 31; // Use old User Level values
} else {
return 127; // Use new User Level values (separate View/Search)
}
} elseif ($UserLevelID >= 0) {
if (is_array($this->UserLevelPriv)) {
foreach ($this->UserLevelPriv as $row) {
list($table, $levelid, $priv) = $row;
if (strtolower($table) == strtolower($TableName) && strval($levelid) == strval($UserLevelID)) {
if (is_null($priv) || !is_numeric($priv)) return 0;
return intval($priv);
}
}
}
}
return 0;
}
// Get current User Level name
function CurrentUserLevelName() {
return $this->GetUserLevelName($this->CurrentUserLevelID());
}
// Get User Level name based on User Level
function GetUserLevelName($UserLevelID) {
if (strval($UserLevelID) == "-1") {
return "Administrator";
} elseif ($UserLevelID >= 0) {
if (is_array($this->UserLevel)) {
foreach ($this->UserLevel as $row) {
list($levelid, $name) = $row;
if (strval($levelid) == strval($UserLevelID)) return $name;
}
}
}
return "";
}
// function to display all the User Level settings (for debug only)
function ShowUserLevelInfo() {
echo "<pre class=\"phpmaker\">";
print_r($this->UserLevel);
print_r($this->UserLevelPriv);
echo "</pre>";
echo "<p>CurrentUserLevel = " . $this->CurrentUserLevel() . "</p>";
}
// function to check privilege for List page (for menu items)
function AllowList($TableName) {
return ($this->CurrentUserLevelPriv($TableName) & EW_ALLOW_LIST);
}
// Check if user is logged in
function IsLoggedIn() {
return (@$_SESSION[EW_SESSION_STATUS] == "login");
}
// Check if user is system administrator
function IsSysAdmin() {
return (@$_SESSION[EW_SESSION_SYS_ADMIN] == 1);
}
// Check if user is administrator
function IsAdmin() {
return ($this->CurrentUserLevelID() == -1 || $this->IsSysAdmin());
}
// Save User Level to session
function SaveUserLevel() {
$_SESSION[EW_SESSION_AR_USER_LEVEL] = $this->UserLevel;
$_SESSION[EW_SESSION_AR_USER_LEVEL_PRIV] = $this->UserLevelPriv;
}
// Load User Level from session
function LoadUserLevel() {
if (!is_array(@$_SESSION[EW_SESSION_AR_USER_LEVEL])) {
$this->SetupUserLevel();
$this->SaveUserLevel();
} else {
$this->UserLevel = $_SESSION[EW_SESSION_AR_USER_LEVEL];
$this->UserLevelPriv = $_SESSION[EW_SESSION_AR_USER_LEVEL_PRIV];
}
}
// function to get user info
function CurrentUserInfo($fieldname) {
$conn;
$info = NULL;
if ($this->CurrentUserName() == "") return $info;
// Set up filter (Sql Where Clause) and get Return Sql
// Sql constructor in <UseTable> class, <UserTable>info.php
$sFilter = "(`username` = '" . ew_AdjustSql($this->CurrentUserName()) . "')";
$admin->CurrentFilter = $sFilter;
$sSql = $admin->SQL();
if ($rs = $conn->Execute($sSql)) {
if (!$rs->EOF) $info = $rs->fields($fieldname);
$rs->Close();
}
return $info;
}
}
?>
<?php
/**
* Common functions
*/
// Connection/Query error handler
function ew_ErrorFn($DbType, $ErrorType, $ErrorNo, $ErrorMsg, $Param1, $Param2, $Object) {
if ($ErrorType == 'CONNECT') {
$msg = "Failed to connect to $Param2 at $Param1. Error: " . $ErrorMsg;
} elseif ($ErrorType == 'EXECUTE') {
$msg = "Failed to execute SQL: $Param1. Error: " . $ErrorMsg;
}
$_SESSION[EW_SESSION_MESSAGE] = $msg;
}
// Connect to database
function &ew_Connect() {
$object = new mysqlt_driver_ADOConnection();
if (defined("EW_DEBUG_ENABLED")) $object->debug = TRUE;
$object->port = EW_CONN_PORT;
$object->raiseErrorFn = 'ew_ErrorFn';
$object->Connect(EW_CONN_HOST, EW_CONN_USER, EW_CONN_PASS, EW_CONN_DB);
if (EW_MYSQL_CHARSET <> "") $object->Execute("SET NAMES '" . EW_MYSQL_CHARSET . "'");
$object->raiseErrorFn = '';
return $object;
}
// Get server variable by name
function ew_ServerVar($Name) {
$str = @$_SERVER[$Name];
if (empty($str)) $str = @$_ENV[$Name];
return $str;
}
// Check if HTTP POST
function ew_IsHttpPost() {
$ct = ew_ServerVar("CONTENT_TYPE");
if (empty($ct)) $ct = ew_ServerVar("HTTP_CONTENT_TYPE");
return ($ct == "application/x-www-form-urlencoded");
}
// Get script name
function ew_ScriptName() {
$sn = ew_ServerVar("PHP_SELF");
if (empty($sn)) $sn = ew_ServerVar("SCRIPT_NAME");
if (empty($sn)) $sn = ew_ServerVar("ORIG_PATH_INFO");
if (empty($sn)) $sn = ew_ServerVar("ORIG_SCRIPT_NAME");
if (empty($sn)) $sn = ew_ServerVar("REQUEST_URI");
if (empty($sn)) $sn = ew_ServerVar("URL");
if (empty($sn)) $sn = "UNKNOWN";
return $sn;
}
// Check if valid operator
function ew_IsValidOpr($Opr, $FldType) {
$Valid = ($Opr == "=" || $Opr == "<" || $Opr == "<=" ||
$Opr == ">" || $Opr == ">=" || $Opr == "<>");
if ($FldType == EW_DATATYPE_STRING || $FldType == EW_DATATYPE_MEMO) {
$Valid = ($Valid || $Opr == "LIKE" || $Opr == "NOT LIKE" ||
$Opr == "STARTS WITH");
}
return $Valid;
}
// quote field values
function ew_QuotedValue($Value, $FldType) {
if (is_null($Value)) return "NULL";
switch ($FldType) {
case EW_DATATYPE_STRING:
case EW_DATATYPE_BLOB:
case EW_DATATYPE_MEMO:
case EW_DATATYPE_TIME:
return "'" . ew_AdjustSql($Value) . "'";
case EW_DATATYPE_DATE:
return (EW_IS_MSACCESS) ? "#" . ew_AdjustSql($Value) . "#" :
"'" . ew_AdjustSql($Value) . "'";
case EW_DATATYPE_GUID:
if (EW_IS_MSACCESS) {
if (strlen($Value) == 38) {
return "{guid " . $Value . "}";
} elseif (strlen($Value) == 36) {
return "{guid {" . $Value . "}}";
}
} else {
return "'" . $Value . "'";
}
case EW_DATATYPE_BOOLEAN: // enum('Y'/'N') or enum('1'/'0')
return "'" . $Value . "'";
default:
return $Value;
}
}
// Convert different data type value
function ew_Conv($v, $t) {
switch ($t) {
case 2:
case 3:
case 16:
case 17:
case 18:
case 19: // adSmallInt/adInteger/adTinyInt/adUnsignedTinyInt/adUnsignedSmallInt
return (is_null($v)) ? NULL : intval($v);
case 4:
Case 5:
case 6:
case 131: // adSingle/adDouble/adCurrency/adNumeric
if (function_exists('floatval')) { // PHP 4 >= 4.2.0
return (is_null($v)) ? NULL : floatval($v);
} else {
return (is_null($v)) ? NULL : (float)$v;
}
default:
return (is_null($v)) ? NULL : $v;
}
}
// function for debug
function ew_Trace($msg) {
$filename = "debug.txt";
if (!$handle = fopen($filename, 'a')) exit;
if (is_writable($filename)) fwrite($handle, $msg . "\n");
fclose($handle);
}
// function to compare values with special handling for null values
function ew_CompareValue($v1, $v2) {
if (is_null($v1) && is_null($v2)) {
return TRUE;
} elseif (is_null($v1) || is_null($v2)) {
return FALSE;
} else {
return ($v1 == $v2);
}
}
// Strip slashes
function ew_StripSlashes($value) {
if (!get_magic_quotes_gpc()) return $value;
if (is_array($value)) {
return array_map('ew_StripSlashes', $value);
} else {
return stripslashes($value);
}
}
// Add slashes for SQL
function ew_AdjustSql($val) {
$val = addslashes(trim($val));
return $val;
}
// Build sql based on different sql part
function ew_BuildSql($sSelect, $sWhere, $sGroupBy, $sHaving, $sOrderBy, $sFilter, $sSort) {
$sDbWhere = $sWhere;
if ($sDbWhere <> "") $sDbWhere = "(" . $sDbWhere . ")";
if ($sFilter <> "") {
if ($sDbWhere <> "") $sDbWhere .= " AND ";
$sDbWhere .= "(" . $sFilter . ")";
}
$sDbOrderBy = $sOrderBy;
if ($sSort <> "") $sDbOrderBy = $sSort;
$sSql = $sSelect;
if ($sDbWhere <> "") $sSql .= " WHERE " . $sDbWhere;
if ($sGroupBy <> "") $sSql .= " GROUP BY " . $sGroupBy;
if ($sHaving <> "") $sql .= " HAVING " . $sHaving;
if ($sDbOrderBy <> "") $sSql .= " ORDER BY " . $sDbOrderBy;
return $sSql;
}
// Executes the query, and returns the first column of the first row
function ew_ExecuteScalar($SQL) {
global $conn;
if ($conn) {
if ($rs = $conn->Execute($SQL)) {
if (!$rs->EOF && $rs->FieldCount() > 0)
return $rs->fields[0];
}
}
return NULL;
}
// Write Audit Trail (login/logout)
function ew_WriteAuditTrailOnLogInOut($logtype) {
$table = $logtype;
$sKey = "";
// Write Audit Trail
$filePfx = "log";
$curDate = date("Y/m/d");
$curTime = date("H:i:s");
$id = ew_ScriptName();
$user = CurrentUserName();
$action = $logtype;
ew_WriteAuditTrail($filePfx, $curDate, $curTime, $id, $user, $action, $table, "", "", "", "");
}
// Function for writing audit trail
function ew_WriteAuditTrail($pfx, $curDate, $curTime, $id, $user, $action, $table, $field, $keyvalue, $oldvalue, $newvalue) {
global $conn;
$sFolder = "";
$sFolder = str_replace("/", EW_PATH_DELIMITER, $sFolder);
$ewFilePath = ew_AppRoot() . $sFolder;
$sTab = "\t";
$userwrk = $user;
if ($userwrk == "") $userwrk = "-1"; // assume Administrator if no user
$sHeader = "date" . $sTab . "time" . $sTab . "id" .
$sTab . "user" . $sTab . "action" . $sTab . "table" .
$sTab . "field" . $sTab . "key value" . $sTab . "old value" .
$sTab . "new value";
$sMsg = $curDate . $sTab . $curTime . $sTab .
$id . $sTab . $user . $sTab .
$action . $sTab . $table . $sTab .
$field . $sTab . $keyvalue . $sTab .
$oldvalue . $sTab . $newvalue;
$sFolder = EW_AUDIT_TRAIL_PATH;
$sFn = $pfx . "_" . date("Ymd") . ".txt";
$filename = ew_UploadPathEx(TRUE, $sFolder) . $sFn;
if (file_exists($filename)) {
$fileHandler = fopen($filename, "a+b");
} else {
$fileHandler = fopen($filename, "a+b");
fwrite($fileHandler,$sHeader."\r\n");
}
fwrite($fileHandler, $sMsg."\r\n");
fclose($fileHandler);
// Sample code to write audit trail to database
// (change the table and names according to your table schema)
$sAuditSql = "INSERT INTO AuditTrailTable (`date`, `time`, `id`, `user`, " .
"`action`, `table`, `field`, `keyvalue`, `oldvalue`, `newvalue`) VALUES (" .
"'" . ew_AdjustSql($curDate) . "', " .
"'" . ew_AdjustSql($curTime) . "', " .
"'" . ew_AdjustSql($id) . "', " .
"'" . ew_AdjustSql($user) . "', " .
"'" . ew_AdjustSql($action) . "', " .
"'" . ew_AdjustSql($table) . "', " .
"'" . ew_AdjustSql($field) . "', " .
"'" . ew_AdjustSql($keyvalue) . "', " .
"'" . ew_AdjustSql($oldvalue) . "', " .
"'" . ew_AdjustSql($newvalue) . "')";
// echo sAuditSql; // uncomment to debug
$conn->Execute($sAuditSql);
}
// Unformat date time based on format type
function ew_UnFormatDateTime($dt, $namedformat) {
$dt = trim($dt);
while (strpos($dt, " ") !== FALSE) $dt = str_replace(" ", " ", $dt);
$arDateTime = explode(" ", $dt);
if (count($arDateTime) == 0) return $dt;
$arDatePt = explode(EW_DATE_SEPARATOR, $arDateTime[0]);
if ($namedformat == 0) {
$arDefFmt = explode(EW_DATE_SEPARATOR, EW_DEFAULT_DATE_FORMAT);
if ($arDefFmt[0] == "yyyy") {
$namedformat = 9;
} elseif ($arDefFmt[0] == "mm") {
$namedformat = 10;
} elseif ($arDefFmt[0] == "dd") {
$namedformat = 11;
}
}
if (count($arDatePt) == 3) {
switch ($namedformat) {
case 5:
case 9: //yyyymmdd
list($year, $month, $day) = $arDatePt;
break;
case 6:
case 10: //mmddyyyy
list($month, $day, $year) = $arDatePt;
break;
case 7:
case 11: //ddmmyyyy
list($day, $month, $year) = $arDatePt;
break;
default:
return $dt;
}
if (strlen($year) <= 4 && strlen($month) <= 2 && strlen($day) <= 2) {
return $year . "-" . str_pad($month, 2, "0", STR_PAD_LEFT) . "-" .
str_pad($day, 2, "0", STR_PAD_LEFT) .
((count($arDateTime) > 1) ? " " . $arDateTime[1] : "");
} else {
return $dt;
}
} else {
return $dt;
}
}
//-------------------------------------------------------------------------------
// Functions for default date format
// FormatDateTime
//Format a timestamp, datetime, date or time field from MySQL
//$namedformat:
//0 - General Date,
//1 - Long Date,
//2 - Short Date (Default),
//3 - Long Time,
//4 - Short Time (hh:mm:ss),
//5 - Short Date (yyyy/mm/dd),
//6 - Short Date (mm/dd/yyyy),
//7 - Short Date (dd/mm/yyyy),
//8 - Short Date (Default) + Short Time (if not 00:00:00)
//9 - Short Date (yyyy/mm/dd) + Short Time (hh:mm:ss),
//10 - Short Date (mm/dd/yyyy) + Short Time (hh:mm:ss),
//11 - Short Date (dd/mm/yyyy) + Short Time (hh:mm:ss)
function ew_FormatDateTime($ts, $namedformat) {
$DefDateFormat = str_replace("yyyy", "%Y", EW_DEFAULT_DATE_FORMAT);
$DefDateFormat = str_replace("mm", "%m", $DefDateFormat);
$DefDateFormat = str_replace("dd", "%d", $DefDateFormat);
if (is_numeric($ts)) // timestamp
{
switch (strlen($ts)) {
case 14:
$patt = '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/';
break;
case 12:
$patt = '/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/';
break;
case 10:
$patt = '/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/';
break;
case 8:
$patt = '/(\d{4})(\d{2})(\d{2})/';
break;
case 6:
$patt = '/(\d{2})(\d{2})(\d{2})/';
break;
case 4:
$patt = '/(\d{2})(\d{2})/';
break;
case 2:
$patt = '/(\d{2})/';
break;
default:
return $ts;
}
if ((isset($patt))&&(preg_match($patt, $ts, $matches)))
{
$year = $matches[1];
$month = @$matches[2];
$day = @$matches[3];
$hour = @$matches[4];
$min = @$matches[5];
$sec = @$matches[6];
}
if (($namedformat==0)&&(strlen($ts)<10)) $namedformat = 2;
}
elseif (is_string($ts))
{
if (preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/', $ts, $matches)) // datetime
{
$year = $matches[1];
$month = $matches[2];
$day = $matches[3];
$hour = $matches[4];
$min = $matches[5];
$sec = $matches[6];
}
elseif (preg_match('/(\d{4})-(\d{2})-(\d{2})/', $ts, $matches)) // date
{
$year = $matches[1];
$month = $matches[2];
$day = $matches[3];
if ($namedformat==0) $namedformat = 2;
}
elseif (preg_match('/(^|\s)(\d{2}):(\d{2}):(\d{2})/', $ts, $matches)) // time
{
$hour = $matches[2];
$min = $matches[3];
$sec = $matches[4];
if (($namedformat==0)||($namedformat==1)) $namedformat = 3;
if ($namedformat==2) $namedformat = 4;
}
else
{
return $ts;
}
}
else
{
return $ts;
}
if (!isset($year)) $year = 0; // dummy value for times
if (!isset($month)) $month = 1;
if (!isset($day)) $day = 1;
if (!isset($hour)) $hour = 0;
if (!isset($min)) $min = 0;
if (!isset($sec)) $sec = 0;
$uts = @mktime($hour, $min, $sec, $month, $day, $year);
if ($uts < 0 || $uts == FALSE) { // failed to convert
$year = substr_replace("0000", $year, -1 * strlen($year));
$month = substr_replace("00", $month, -1 * strlen($month));
$day = substr_replace("00", $day, -1 * strlen($day));
$hour = substr_replace("00", $hour, -1 * strlen($hour));
$min = substr_replace("00", $min, -1 * strlen($min));
$sec = substr_replace("00", $sec, -1 * strlen($sec));
$DefDateFormat = str_replace("yyyy", $year, EW_DEFAULT_DATE_FORMAT);
$DefDateFormat = str_replace("mm", $month, $DefDateFormat);
$DefDateFormat = str_replace("dd", $day, $DefDateFormat);
switch ($namedformat) {
case 0:
return $DefDateFormat." $hour:$min:$sec";
break;
case 1://unsupported, return general date
return $DefDateFormat." $hour:$min:$sec";
break;
case 2:
return $DefDateFormat;
break;
case 3:
if (intval($hour)==0)
return "12:$min:$sec AM";
elseif (intval($hour)>0 && intval($hour)<12)
return "$hour:$min:$sec AM";
elseif (intval($hour)==12)
return "$hour:$min:$sec PM";
elseif (intval($hour)>12 && intval($hour)<=23)
return (intval($hour)-12).":$min:$sec PM";
else
return "$hour:$min:$sec";
break;
case 4:
return "$hour:$min:$sec";
break;
case 5:
return "$year". EW_DATE_SEPARATOR . "$month" . EW_DATE_SEPARATOR . "$day";
break;
case 6:
return "$month". EW_DATE_SEPARATOR ."$day" . EW_DATE_SEPARATOR . "$year";
break;
case 7:
return "$day" . EW_DATE_SEPARATOR ."$month" . EW_DATE_SEPARATOR . "$year";
break;
case 8:
return $DefDateFormat . (($hour == 0 && $min == 0 && $sec == 0) ? "" : " $hour:$min:$sec");
break;
case 9:
return "$year". EW_DATE_SEPARATOR . "$month" . EW_DATE_SEPARATOR . "$day $hour:$min:$sec";
break;
case 10:
return "$month". EW_DATE_SEPARATOR ."$day" . EW_DATE_SEPARATOR . "$year $hour:$min:$sec";
break;
case 11:
return "$day" . EW_DATE_SEPARATOR ."$month" . EW_DATE_SEPARATOR . "$year $hour:$min:$sec";
break;
}
} else {
switch ($namedformat) {
case 0:
return strftime($DefDateFormat." %H:%M:%S", $uts);
break;
case 1:
return strftime("%A, %B %d, %Y", $uts);
break;
case 2:
return strftime($DefDateFormat, $uts);
break;
case 3:
return strftime("%I:%M:%S %p", $uts);
break;
case 4:
return strftime("%H:%M:%S", $uts);
break;
case 5:
return strftime("%Y" . EW_DATE_SEPARATOR . "%m" . EW_DATE_SEPARATOR . "%d", $uts);
break;
case 6:
return strftime("%m" . EW_DATE_SEPARATOR . "%d" . EW_DATE_SEPARATOR . "%Y", $uts);
break;
case 7:
return strftime("%d" . EW_DATE_SEPARATOR . "%m" . EW_DATE_SEPARATOR . "%Y", $uts);
break;
case 8:
return strftime($DefDateFormat . (($hour == 0 && $min == 0 && $sec == 0) ? "" : " %H:%M:%S"), $uts);
break;
case 9:
return strftime("%Y" . EW_DATE_SEPARATOR . "%m" . EW_DATE_SEPARATOR . "%d %H:%M:%S", $uts);
break;
case 10:
return strftime("%m" . EW_DATE_SEPARATOR . "%d" . EW_DATE_SEPARATOR . "%Y %H:%M:%S", $uts);
break;
case 11:
return strftime("%d" . EW_DATE_SEPARATOR . "%m" . EW_DATE_SEPARATOR . "%Y %H:%M:%S", $uts);
break;
}
}
}
// FormatCurrency
//ew_FormatCurrency(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit
// [,UseParensForNegativeNumbers [,GroupDigits]]]])
//NumDigitsAfterDecimal is the numeric value indicating how many places to the
//right of the decimal are displayed
//-1 Use Default
//The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits
//arguments have the following settings:
//-1 True
//0 False
//-2 Use Default
function ew_FormatCurrency($amount, $NumDigitsAfterDecimal, $IncludeLeadingDigit = -2, $UseParensForNegativeNumbers = -2, $GroupDigits = -2) {
// export the values returned by localeconv into the local scope
//if (function_exists("localeconv"))
extract(localeconv()); // PHP 4 >= 4.0.5
// set defaults if locale is not set
if (empty($currency_symbol)) $currency_symbol = DEFAULT_CURRENCY_SYMBOL;
if (empty($mon_decimal_point)) $mon_decimal_point = DEFAULT_MON_DECIMAL_POINT;
if (empty($mon_thousands_sep)) $mon_thousands_sep = DEFAULT_MON_THOUSANDS_SEP;
if (empty($positive_sign)) $positive_sign = DEFAULT_POSITIVE_SIGN;
if (empty($negative_sign)) $negative_sign = DEFAULT_NEGATIVE_SIGN;
if (empty($frac_digits) || $frac_digits == CHAR_MAX) $frac_digits = DEFAULT_FRAC_DIGITS;
if (empty($p_cs_precedes) || $p_cs_precedes == CHAR_MAX) $p_cs_precedes = DEFAULT_P_CS_PRECEDES;
if (empty($p_sep_by_space) || $p_sep_by_space == CHAR_MAX) $p_sep_by_space = DEFAULT_P_SEP_BY_SPACE;
if (empty($n_cs_precedes) || $n_cs_precedes == CHAR_MAX) $n_cs_precedes = DEFAULT_N_CS_PRECEDES;
if (empty($n_sep_by_space) || $n_sep_by_space == CHAR_MAX) $n_sep_by_space = DEFAULT_N_SEP_BY_SPACE;
if (empty($p_sign_posn) || $p_sign_posn == CHAR_MAX) $p_sign_posn = DEFAULT_P_SIGN_POSN;
if (empty($n_sign_posn) || $n_sign_posn == CHAR_MAX) $n_sign_posn = DEFAULT_N_SIGN_POSN;
// check $NumDigitsAfterDecimal
if ($NumDigitsAfterDecimal > -1)
$frac_digits = $NumDigitsAfterDecimal;
// check $UseParensForNegativeNumbers
if ($UseParensForNegativeNumbers == -1) {
$n_sign_posn = 0;
if ($p_sign_posn == 0) {
if (DEFAULT_P_SIGN_POSN != 0)
$p_sign_posn = DEFAULT_P_SIGN_POSN;
else
$p_sign_posn = 3;
}
} elseif ($UseParensForNegativeNumbers == 0) {
if ($n_sign_posn == 0)
if (DEFAULT_P_SIGN_POSN != 0)
$n_sign_posn = DEFAULT_P_SIGN_POSN;
else
$n_sign_posn = 3;
}
// check $GroupDigits
if ($GroupDigits == -1) {
$mon_thousands_sep = DEFAULT_MON_THOUSANDS_SEP;
} elseif ($GroupDigits == 0) {
$mon_thousands_sep = "";
}
// start by formatting the unsigned number
$number = number_format(abs($amount),
$frac_digits,
$mon_decimal_point,
$mon_thousands_sep);
// check $IncludeLeadingDigit
if ($IncludeLeadingDigit == 0) {
if (substr($number, 0, 2) == "0.")
$number = substr($number, 1, strlen($number)-1);
}
if ($amount < 0) {
$sign = $negative_sign;
// "extracts" the boolean value as an integer
$n_cs_precedes = intval($n_cs_precedes == true);
$n_sep_by_space = intval($n_sep_by_space == true);
$key = $n_cs_precedes . $n_sep_by_space . $n_sign_posn;
} else {
$sign = $positive_sign;
$p_cs_precedes = intval($p_cs_precedes == true);
$p_sep_by_space = intval($p_sep_by_space == true);
$key = $p_cs_precedes . $p_sep_by_space . $p_sign_posn;
}
$formats = array(
// currency symbol is after amount
// no space between amount and sign
'000' => '(%s' . $currency_symbol . ')',
'001' => $sign . '%s ' . $currency_symbol,
'002' => '%s' . $currency_symbol . $sign,
'003' => '%s' . $sign . $currency_symbol,
'004' => '%s' . $sign . $currency_symbol,
// one space between amount and sign
'010' => '(%s ' . $currency_symbol . ')',
'011' => $sign . '%s ' . $currency_symbol,
'012' => '%s ' . $currency_symbol . $sign,
'013' => '%s ' . $sign . $currency_symbol,
'014' => '%s ' . $sign . $currency_symbol,
// currency symbol is before amount
// no space between amount and sign
'100' => '(' . $currency_symbol . '%s)',
'101' => $sign . $currency_symbol . '%s',
'102' => $currency_symbol . '%s' . $sign,
'103' => $sign . $currency_symbol . '%s',
'104' => $currency_symbol . $sign . '%s',
// one space between amount and sign
'110' => '(' . $currency_symbol . ' %s)',
'111' => $sign . $currency_symbol . ' %s',
'112' => $currency_symbol . ' %s' . $sign,
'113' => $sign . $currency_symbol . ' %s',
'114' => $currency_symbol . ' ' . $sign . '%s');
// lookup the key in the above array
return sprintf($formats[$key], $number);
}
// FormatNumber
//ew_FormatNumber(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit
// [,UseParensForNegativeNumbers [,GroupDigits]]]])
//NumDigitsAfterDecimal is the numeric value indicating how many places to the
//right of the decimal are displayed
//-1 Use Default
//The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits
//arguments have the following settings:
//-1 True
//0 False
//-2 Use Default
function ew_FormatNumber($amount, $NumDigitsAfterDecimal, $IncludeLeadingDigit = -2, $UseParensForNegativeNumbers = -2, $GroupDigits = -2) {
// export the values returned by localeconv into the local scope
//if (function_exists("localeconv"))
extract(localeconv()); // PHP 4 >= 4.0.5
// set defaults if locale is not set
if (empty($currency_symbol)) $currency_symbol = DEFAULT_CURRENCY_SYMBOL;
if (empty($mon_decimal_point)) $mon_decimal_point = DEFAULT_MON_DECIMAL_POINT;
if (empty($mon_thousands_sep)) $mon_thousands_sep = DEFAULT_MON_THOUSANDS_SEP;
if (empty($positive_sign)) $positive_sign = DEFAULT_POSITIVE_SIGN;
if (empty($negative_sign)) $negative_sign = DEFAULT_NEGATIVE_SIGN;
if (empty($frac_digits) || $frac_digits == CHAR_MAX) $frac_digits = DEFAULT_FRAC_DIGITS;
if (empty($p_cs_precedes) || $p_cs_precedes == CHAR_MAX) $p_cs_precedes = DEFAULT_P_CS_PRECEDES;
if (empty($p_sep_by_space) || $p_sep_by_space == CHAR_MAX) $p_sep_by_space = DEFAULT_P_SEP_BY_SPACE;
if (empty($n_cs_precedes) || $n_cs_precedes == CHAR_MAX) $n_cs_precedes = DEFAULT_N_CS_PRECEDES;
if (empty($n_sep_by_space) || $n_sep_by_space == CHAR_MAX) $n_sep_by_space = DEFAULT_N_SEP_BY_SPACE;
if (empty($p_sign_posn) || $p_sign_posn == CHAR_MAX) $p_sign_posn = DEFAULT_P_SIGN_POSN;
if (empty($n_sign_posn) || $n_sign_posn == CHAR_MAX) $n_sign_posn = DEFAULT_N_SIGN_POSN;
// check $NumDigitsAfterDecimal
if ($NumDigitsAfterDecimal > -1)
$frac_digits = $NumDigitsAfterDecimal;
// check $UseParensForNegativeNumbers
if ($UseParensForNegativeNumbers == -1) {
$n_sign_posn = 0;
if ($p_sign_posn == 0) {
if (DEFAULT_P_SIGN_POSN != 0)
$p_sign_posn = DEFAULT_P_SIGN_POSN;
else
$p_sign_posn = 3;
}
} elseif ($UseParensForNegativeNumbers == 0) {
if ($n_sign_posn == 0)
if (DEFAULT_P_SIGN_POSN != 0)
$n_sign_posn = DEFAULT_P_SIGN_POSN;
else
$n_sign_posn = 3;
}
// check $GroupDigits
if ($GroupDigits == -1) {
$mon_thousands_sep = DEFAULT_MON_THOUSANDS_SEP;
} elseif ($GroupDigits == 0) {
$mon_thousands_sep = "";
}
// start by formatting the unsigned number
$number = number_format(abs($amount),
$frac_digits,
$mon_decimal_point,
$mon_thousands_sep);
// check $IncludeLeadingDigit
if ($IncludeLeadingDigit == 0) {
if (substr($number, 0, 2) == "0.")
$number = substr($number, 1, strlen($number)-1);
}
if ($amount < 0) {
$sign = $negative_sign;
$key = $n_sign_posn;
} else {
$sign = $positive_sign;
$key = $p_sign_posn;
}
$formats = array(
'0' => '(%s)',
'1' => $sign . '%s',
'2' => $sign . '%s',
'3' => $sign . '%s',
'4' => $sign . '%s');
// lookup the key in the above array
return sprintf($formats[$key], $number);
}
// FormatPercent
//ew_FormatPercent(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit
// [,UseParensForNegativeNumbers [,GroupDigits]]]])
//NumDigitsAfterDecimal is the numeric value indicating how many places to the
//right of the decimal are displayed
//-1 Use Default
//The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits
//arguments have the following settings:
//-1 True
//0 False
//-2 Use Default
function ew_FormatPercent($amount, $NumDigitsAfterDecimal, $IncludeLeadingDigit = -2, $UseParensForNegativeNumbers = -2, $GroupDigits = -2) {
// export the values returned by localeconv into the local scope
//if (function_exists("localeconv"))
extract(localeconv()); // PHP 4 >= 4.0.5
// set defaults if locale is not set
if (empty($currency_symbol)) $currency_symbol = DEFAULT_CURRENCY_SYMBOL;
if (empty($mon_decimal_point)) $mon_decimal_point = DEFAULT_MON_DECIMAL_POINT;
if (empty($mon_thousands_sep)) $mon_thousands_sep = DEFAULT_MON_THOUSANDS_SEP;
if (empty($positive_sign)) $positive_sign = DEFAULT_POSITIVE_SIGN;
if (empty($negative_sign)) $negative_sign = DEFAULT_NEGATIVE_SIGN;
if (empty($frac_digits) || $frac_digits == CHAR_MAX) $frac_digits = DEFAULT_FRAC_DIGITS;
if (empty($p_cs_precedes) || $p_cs_precedes == CHAR_MAX) $p_cs_precedes = DEFAULT_P_CS_PRECEDES;
if (empty($p_sep_by_space) || $p_sep_by_space == CHAR_MAX) $p_sep_by_space = DEFAULT_P_SEP_BY_SPACE;
if (empty($n_cs_precedes) || $n_cs_precedes == CHAR_MAX) $n_cs_precedes = DEFAULT_N_CS_PRECEDES;
if (empty($n_sep_by_space) || $n_sep_by_space == CHAR_MAX) $n_sep_by_space = DEFAULT_N_SEP_BY_SPACE;
if (empty($p_sign_posn) || $p_sign_posn == CHAR_MAX) $p_sign_posn = DEFAULT_P_SIGN_POSN;
if (empty($n_sign_posn) || $n_sign_posn == CHAR_MAX) $n_sign_posn = DEFAULT_N_SIGN_POSN;
// check $NumDigitsAfterDecimal
if ($NumDigitsAfterDecimal > -1)
$frac_digits = $NumDigitsAfterDecimal;
// check $UseParensForNegativeNumbers
if ($UseParensForNegativeNumbers == -1) {
$n_sign_posn = 0;
if ($p_sign_posn == 0) {
if (DEFAULT_P_SIGN_POSN != 0)
$p_sign_posn = DEFAULT_P_SIGN_POSN;
else
$p_sign_posn = 3;
}
} elseif ($UseParensForNegativeNumbers == 0) {
if ($n_sign_posn == 0)
if (DEFAULT_P_SIGN_POSN != 0)
$n_sign_posn = DEFAULT_P_SIGN_POSN;
else
$n_sign_posn = 3;
}
// check $GroupDigits
if ($GroupDigits == -1) {
$mon_thousands_sep = DEFAULT_MON_THOUSANDS_SEP;
} elseif ($GroupDigits == 0) {
$mon_thousands_sep = "";
}
// start by formatting the unsigned number
$number = number_format(abs($amount)*100,
$frac_digits,
$mon_decimal_point,
$mon_thousands_sep);
// check $IncludeLeadingDigit
if ($IncludeLeadingDigit == 0) {
if (substr($number, 0, 2) == "0.")
$number = substr($number, 1, strlen($number)-1);
}
if ($amount < 0) {
$sign = $negative_sign;
$key = $n_sign_posn;
} else {
$sign = $positive_sign;
$key = $p_sign_posn;
}
$formats = array(
'0' => '(%s%%)',
'1' => $sign . '%s%%',
'2' => $sign . '%s%%',
'3' => $sign . '%s%%',
'4' => $sign . '%s%%');
// lookup the key in the above array
return sprintf($formats[$key], $number);
}
// Encode html
function ew_HtmlEncode($exp) {
return htmlspecialchars(strval($exp));
}
// Generate Value Separator based on current row count
// rowcnt - zero based row count
function ew_ValueSeparator($rowcnt) {
return ", ";
}
// Generate View Option Separator based on current row count (Multi-Select / CheckBox)
// rowcnt - zero based row count
function ew_ViewOptionSeparator($rowcnt) {
$sep = ", ";
// Sample code to adjust 2 options per row
//if (($rowcnt + 1) % 2 == 0) { // 2 options per row
//return $sep += "<br>";
//}
return $sep;
}
// Move uploaded file
function ew_MoveUploadFile($srcfile, $destfile) {
$res = move_uploaded_file($srcfile, $destfile);
if ($res) chmod($destfile, EW_UPLOADED_FILE_MODE);
return $res;
}
// Render repeat column table
// rowcnt - zero based row count
function ew_RepeatColumnTable($totcnt, $rowcnt, $repeatcnt, $rendertype) {
$sWrk = "";
if ($rendertype == 1) { // Render control start
if ($rowcnt == 0) $sWrk .= "<table class=\"phpmakerlist\">";
if ($rowcnt % $repeatcnt == 0) $sWrk .= "<tr>";
$sWrk .= "<td>";
} elseif ($rendertype == 2) { // Render control end
$sWrk .= "</td>";
if ($rowcnt % $repeatcnt == $repeatcnt - 1) {
$sWrk .= "</tr>";
} elseif ($rowcnt == $totcnt - 1) {
for ($i = ($rowcnt % $repeatcnt) + 1; $i < $repeatcnt; $i++) {
$sWrk .= "<td> </td>";
}
$sWrk .= "</tr>";
}
if ($rowcnt == $totcnt - 1) $sWrk .= "</table>";
}
return $sWrk;
}
// Truncate Memo Field based on specified length, string truncated to nearest space or CrLf
function ew_TruncateMemo($str, $ln) {
if (strlen($str) > 0 && strlen($str) > $ln) {
$k = 0;
while ($k >= 0 && $k < strlen($str)) {
$i = strpos($str, " ", $k);
$j = strpos($str, chr(10), $k);
if ($i === FALSE && $j === FALSE) { // Not able to truncate
return $str;
} else {
// Get nearest space or CrLf
if ($i > 0 && $j > 0) {
if ($i < $j) {
$k = $i;
} else {
$k = $j;
}
} elseif ($i > 0) {
$k = $i;
} elseif ($j > 0) {
$k = $j;
}
// Get truncated text
if ($k >= $ln) {
return substr($str, 0, $k) . "...";
} else {
$k++;
}
}
}
} else {
return $str;
}
}
// Send notify email
function ew_SendNotifyEmail($sFn, $sSubject, $sTable, $sKey, $sAction) {
// Send Email
if (EW_SENDER_EMAIL <> "" && EW_RECIPIENT_EMAIL <> "") {
$Email = new cEmail;
$Email->Load($sFn);
$Email->ReplaceSender(EW_SENDER_EMAIL); // Replace Sender
$Email->ReplaceRecipient(EW_RECIPIENT_EMAIL); // Replace Recipient
$Email->ReplaceSubject($sSubject); // Replace Subject
$Email->ReplaceContent("<!--table-->", $sTable);
$Email->ReplaceContent("<!--key-->", $sKey);
$Email->ReplaceContent("<!--action-->", $sAction);
$Email->Send();
}
}
// Include PHPMailer class is selected
if (EW_EMAIL_COMPONENT == "PHPMAILER") {
include("phpmailer" . EW_PATH_DELIMITER . "class.phpmailer.php");
}
// Function to send email
function ew_SendEmail($sFrEmail, $sToEmail, $sCcEmail, $sBccEmail, $sSubject, $sMail, $sFormat) {
/* for debug only
echo "sSubject: " . $sSubject . "<br>";
echo "sFrEmail: " . $sFrEmail . "<br>";
echo "sToEmail: " . $sToEmail . "<br>";
echo "sCcEmail: " . $sCcEmail . "<br>";
echo "sSubject: " . $sSubject . "<br>";
echo "sMail: " . $sMail . "<br>";
echo "sFormat: " . $sFormat . "<br>";
*/
if (EW_EMAIL_COMPONENT == "PHPMAILER") {
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = EW_SMTP_SERVER;
$mail->SMTPAuth = (EW_SMTP_SERVER_USERNAME <> "" && EW_SMTP_SERVER_PASSWORD <> "");
$mail->Username = EW_SMTP_SERVER_USERNAME;
$mail->Password = EW_SMTP_SERVER_PASSWORD;
$mail->Port = EW_SMTP_SERVER_PORT;
$mail->From = $sFrEmail;
$mail->FromName = $sFrEmail;
$mail->Subject = $sSubject;
$mail->Body = $sMail;
$sToEmail = str_replace(";", ",", $sToEmail);
$arrTo = explode(",", $sToEmail);
foreach ($arrTo as $sTo) {
$mail->AddAddress(trim($sTo));
}
if ($sCcEmail <> "") {
$sCcEmail = str_replace(";", ",", $sCcEmail);
$arrCc = explode(",", $sCcEmail);
foreach ($arrCc as $sCc) {
$mail->AddCC(trim($sCc));
}
}
if ($sBccEmail <> "") {
$sBccEmail = str_replace(";", ",", $sBccEmail);
$arrBcc = explode(",", $sBccEmail);
foreach ($arrBcc as $sBcc) {
$mail->AddBCC(trim($sBcc));
}
}
if (strtolower($sFormat) == "html") {
$mail->ContentType = "text/html";
} else {
$mail->ContentType = "text/plain";
}
$res = $mail->Send();
$mail->ClearAddresses();
$mail->ClearAttachments();
return $res;
} else {
$to = $sToEmail;
$subject = $sSubject;
$headers = "";
if (strtolower($sFormat) == "html") {
$content_type = "text/html";
} else {
$content_type = "text/plain";
}
$headers = "Content-type: " . $content_type . "\r\n";
$message = $sMail;
$headers .= "From: " . str_replace(";", ",", $sFrEmail) . "\r\n";
if ($sCcEmail <> "") {
$headers .= "Cc: " . str_replace(";", ",", $sCcEmail) . "\r\n";
}
if ($sBccEmail <>"") {
$headers .= "Bcc: " . str_replace(";", ",", $sBccEmail) . "\r\n";
}
if (EW_IS_WINDOWS) {
ini_set("SMTP", EW_SMTP_SERVER);
ini_set("smtp_port", EW_SMTP_SERVER_PORT);
}
ini_set("sendmail_from", $sFrEmail);
return mail($to, $subject, $message, $headers);
}
}
// Field data type
function ew_FieldDataType($fldtype) {
switch ($fldtype) {
case 20:
case 3:
case 2:
case 16:
case 4:
case 5:
case 131:
case 6:
case 17:
case 18:
case 19:
case 21: // Numeric
return EW_DATATYPE_NUMBER;
case 7:
case 133:
case 135: // Date
return EW_DATATYPE_DATE;
case 134: // Time
return EW_DATATYPE_TIME;
case 201:
case 203: // Memo
return EW_DATATYPE_MEMO;
case 129:
case 130:
case 200:
case 202: // String
return EW_DATATYPE_STRING;
case 11: // Boolean
return EW_DATATYPE_BOOLEAN;
case 72: // GUID
return 5;
case 128:
case 204:
case 205: // Binary
return EW_DATATYPE_BLOB;
default:
return EW_DATATYPE_OTHER;
}
}
// function to get application root
function ew_AppRoot() {
// 1. use root relative path
if (EW_ROOT_RELATIVE_PATH <> "") {
$Path = realpath(EW_ROOT_RELATIVE_PATH);
$Path = str_replace("\\\\", EW_PATH_DELIMITER, $Path);
}
// 2. if empty, use the document root if available
if (empty($Path)) $Path = ew_ServerVar("DOCUMENT_ROOT");
// 3. if empty, use current folder
if (empty($Path)) $Path = realpath(".");
// 4. use custom path, uncomment the following line and enter your path
// e.g. $Path = 'C:\Inetpub\wwwroot\MyWebRoot'; // Windows
//$Path = 'enter your path here';
if (empty($Path)) die("Path of website root unknown.");
return ew_IncludeTrailingDelimiter($Path, TRUE);
}
// function to include the last delimiter for a path
function ew_IncludeTrailingDelimiter($Path, $PhyPath) {
if ($PhyPath) {
if (substr($Path, -1) <> EW_PATH_DELIMITER) $Path .= EW_PATH_DELIMITER;
} else {
if (substr($Path, -1) <> "/") $Path .= "/";
}
return $Path;
}
// function to write the paths for config/debug only
function ew_WritePaths() {
echo 'DOCUMENT_ROOT=' . ew_ServerVar("DOCUMENT_ROOT") . "<br>";
echo 'EW_ROOT_RELATIVE_PATH=' . EW_ROOT_RELATIVE_PATH . "<br>";
echo 'ew_AppRoot()=' . ew_AppRoot() . "<br>";
echo 'realpath(".")=' . realpath(".") . "<br>";
echo '__FILE__=' . __FILE__ . "<br>";
}
// function to return path of the uploaded file
// Parameter: If PhyPath is true(1), return physical path on the server;
// If PhyPath is false(0), return relative URL
function ew_UploadPathEx($PhyPath, $DestPath) {
if ($PhyPath) {
$Path = ew_AppRoot();
$Path .= str_replace("/", EW_PATH_DELIMITER, $DestPath);
} else {
$Path = EW_ROOT_RELATIVE_PATH;
$Path = str_replace("\\\\", "/", $Path);
$Path = str_replace("\\", "/", $Path);
$Path = ew_IncludeTrailingDelimiter($Path, FALSE) . $DestPath;
}
return ew_IncludeTrailingDelimiter($Path, $PhyPath);
}
// Return path of the uploaded file
// returns global upload folder, for backward compatibility only
function ew_UploadPath($PhyPath) {
return ew_UploadPathEx($PhyPath, EW_UPLOAD_DEST_PATH);
}
function ew_UploadFileNameEx($folder, $sFileName) {
// By default, ew_UniqueFileName() is used to get an unique file name,
// you can change the logic here
$sOutFileName = ew_UniqueFilename($folder, $sFileName);
// Return computed output file name
return $sOutFileName;
}
// function to generate an unique file name (filename(n).ext)
function ew_UniqueFilename($folder, $oriFilename) {
if ($oriFilename == "") $oriFilename = ew_DefaultFileName();
$oriFilename = str_replace(" ", "_", $oriFilename);
$oriFilename = strtolower(basename($oriFilename));
$destFullPath = $folder . $oriFilename;
$newFilename = $oriFilename;
$i = 1;
if (!file_exists($folder)) {
if (!ew_CreateFolder($folder)) {
die("Folder does not exist: " . $folder);
}
}
while (file_exists($destFullPath)) {
$file_extension = strtolower(strrchr($oriFilename, "."));
$file_name = basename($oriFilename, $file_extension);
$newFilename = $file_name . "($i)" . $file_extension;
$destFullPath = $folder . $newFilename;
$i++;
}
return $newFilename;
}
// function to create a default file name(yyyymmddhhmmss.bin)
function ew_DefaultFileName() {
return date("YmdHis") . ".bin";
}
// Get full url
function ew_FullUrl() {
$sUrl = "http";
if (ew_ServerVar("HTTPS") <> "" && ew_ServerVar("HTTPS") <> "off") $sUrl .= "s";
$sUrl .= "://";
$sUrl .= ew_ServerVar("SERVER_NAME") . ew_ScriptName();
return $sUrl;
}
// Convert to full url
function ew_ConvertFullUrl($url) {
if ($url == "") return "";
$sUrl = ew_FullUrl();
return substr($sUrl, 0, strrpos($sUrl, "/")+1) . $url;
}
// Get a temp folder for temp file
function ew_TmpFolder() {
$tmpfolder = NULL;
$folders = array();
if (EW_IS_WINDOWS) {
$folders[] = ew_ServerVar("TEMP");
$folders[] = ew_ServerVar("TMP");
} else {
$folders[] = '/tmp';
}
if (ini_get('upload_tmp_dir')) {
$folders[] = ini_get('upload_tmp_dir');
}
foreach ($folders as $folder) {
if (!$tmpfolder && is_dir($folder)) {
$tmpfolder = $folder;
}
}
//if ($tmpfolder) $tmpfolder = ew_IncludeTrailingDelimiter($tmpfolder, TRUE);
return $tmpfolder;
}
// Create folder
function ew_CreateFolder($dir, $mode = 0777) {
if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
if (!ew_CreateFolder(dirname($dir), $mode)) return FALSE;
return @mkdir($dir, $mode);
}
// Load file data
function ew_ReadFile($file) {
$content = '';
if ($handle = @fopen($file, 'r')) {
$content = fread($handle, filesize($file));
fclose($handle);
}
return $content;
}
// Save file
function ew_SaveFile($folder, $fn, $file) {
$res = FALSE;
if (ew_CreateFolder($folder)) {
$res = @rename($file, $folder . $fn);
if (!$res) $res = @copy($file, $folder . $fn); // for PHP < 4.3.3
// if ($handle = fopen($folder . $fn, 'w')) {
// $res = fwrite($handle, $filedata);
// fclose($handle);
// }
if ($res) chmod($folder . $fn, EW_UPLOADED_FILE_MODE);
}
return $res;
}
// function to generate random number
function ew_Random() {
if (phpversion() < "4.2.0") {
list($usec, $sec) = explode(' ', microtime());
$seed = (float) $sec + ((float) $usec * 100000);
mt_srand($seed);
}
return mt_rand();
}
// function to remove CR and LF
function ew_RemoveCrLf($s) {
if (strlen($s) > 0) {
$s = str_replace("\n", " ", $s);
$s = str_replace("\r", " ", $s);
$s = str_replace("\l", " ", $s);
}
return $s;
}
?>
<?php
/**
* Form class
*/
class cFormObj {
var $Index;
// Class Inialize
function cFormObj() {
$this->Index = 0;
}
// Get form element name based on index
function GetIndexedName($name) {
if ($this->Index <= 0) {
return $name;
} else {
return substr($name, 0, 1) . $this->Index . substr($name, 1);
}
}
// Get value for form element
function GetValue($name) {
$wrkname = $this->GetIndexedName($name);
return @$_POST[$wrkname];
}
// Get upload file size
function GetUploadFileSize($name) {
$wrkname = $this->GetIndexedName($name);
return @$_FILES[$wrkname]['size'];
}
// Get upload file name
function GetUploadFileName($name) {
$wrkname = $this->GetIndexedName($name);
return @$_FILES[$wrkname]['name'];
}
// Get file content type
function GetUploadFileContentType($name) {
$wrkname = $this->GetIndexedName($name);
return @$_FILES[$wrkname]['type'];
}
// Get file error
function GetUploadFileError($name) {
$wrkname = $this->GetIndexedName($name);
return @$_FILES[$wrkname]['error'];
}
// Get file temp name
function GetUploadFileTmpName($name) {
$wrkname = $this->GetIndexedName($name);
return @$_FILES[$wrkname]['tmp_name'];
}
// Check if is uplaod file
function IsUploadedFile($name) {
$wrkname = $this->GetIndexedName($name);
return is_uploaded_file(@$_FILES[$wrkname]["tmp_name"]);
}
// Get upload file data
// function GetUploadFileData($name) {
// if ($this->IsUploadedFile($name)) {
// $wrkname = $this->GetIndexedName($name);
// return ew_ReadFile($_FILES[$wrkname]["tmp_name"]);
// } else {
// return NULL;
// }
// }
// Get image sizes
var $size;
function GetImageDimension($name) {
if (!isset($this->size)) {
$wrkname = $this->GetIndexedName($name);
$this->size = @getimagesize($_FILES[$wrkname]['tmp_name']);
}
}
// Get file image width
function GetUploadImageWidth($name) {
$this->GetImageDimension($name);
return $this->size[0];
}
// Get file image height
function GetUploadImageHeight($name) {
$this->GetImageDimension($name);
return $this->size[1];
}
}
?>
<?php
/**
* Functions for image resize
*/
// Resize binary to thumbnail
function ew_ResizeBinary($filedata, $width, $height, $quality) {
return TRUE; // No resize
}
// Resize file to thumbnail file
function ew_ResizeFile($fn, $tn, $width, $height, $quality) {
if (file_exists($fn)) { // Copy only
return ($fn <> $tn) ? copy($fn, $tn) : TRUE;
} else {
return FALSE;
}
}
// Resize file to binary
function ew_ResizeFileToBinary($fn, $width, $height, $quality) {
return ew_ReadFile($fn); // Return original file content only
}
?>
<?php
/**
* Fucntions for search
*/
// Highlight value based on basic search / advanced search keywords
function ew_Highlight($src, $bkw, $bkwtype, $akw) {
$outstr = "";
if (strlen($src) > 0 && (strlen($bkw) > 0 || strlen($akw) > 0)) {
$kwstr = $bkw;
if (strlen($akw) > 0) {
if (strlen($kwstr) > 0) $kwstr .= " ";
$kwstr .= $akw;
}
$kwlist = explode(" ", $kwstr);
$x = 0;
ew_GetKeyword($src, $kwlist, $x, $y, $kw);
while ($y >= 0) {
$outstr .= substr($src, $x, $y-$x) .
"<span name=\"ewHighlightSearch\" id=\"ewHighlightSearch\" class=\"ewHighlightSearch\">" .
substr($src, $y, strlen($kw)) . "</span>";
$x = $y + strlen($kw);
ew_GetKeyword($src, $kwlist, $x, $y, $kw);
}
$outstr .= substr($src, $x);
} else {
$outstr = $src;
}
return $outstr;
}
// Get keyword
function ew_GetKeyword(&$src, &$kwlist, &$x, &$y, &$kw) {
$thisy = -1;
$thiskw = "";
foreach ($kwlist as $wrkkw) {
$wrkkw = trim($wrkkw);
if (EW_HIGHLIGHT_COMPARE) { // Case-insensitive
if (function_exists('stripos')) { // PHP 5
$wrky = stripos($src, $wrkkw, $x);
} else {
$wrky = strpos(strtoupper($src), strtoupper($wrkkw), $x);
}
} else {
$wrky = strpos($src, $wrkkw, $x);
}
if ($wrky !== FALSE) {
if ($thisy == -1) {
$thisy = $wrky;
$thiskw = $wrkkw;
} elseif ($wrky < $thisy) {
$thisy = $wrky;
$thiskw = $wrkkw;
}
}
}
$y = $thisy;
$kw = $thiskw;
}
?>
<?php
/**
* Functions for Auto-Update fields
*/
// Get user IP
function ew_CurrentUserIP() {
return ew_ServerVar("REMOTE_ADDR");
}
// Get current host name, e.g. "www.mycompany.com"
function ew_CurrentHost() {
return ew_ServerVar("HTTP_HOST");
}
// Get current date in default date format
// $namedformat = -1|5|6|7 (see comment for ew_FormatDateTime)
function ew_CurrentDate($namedformat = -1) {
if ($namedformat > -1) {
if ($namedformat == 6 || $namedformat == 7) {
return ew_FormatDateTime(date('Y-m-d'), $namedformat);
} else {
return ew_FormatDateTime(date('Y-m-d'), 5);
}
} else {
return date('Y-m-d');
}
}
// Get current time in hh:mm:ss format
function ew_CurrentTime() {
return date("H:i:s");
}
// Get current date in default date format with time in hh:mm:ss format
// $namedformat = -1|9|10|11 (see comment for ew_FormatDateTime)
function ew_CurrentDateTime($namedformat = -1) {
if ($namedformat > -1) {
if ($namedformat == 10 || $namedformat == 11) {
return ew_FormatDateTime(date('Y-m-d H:i:s'), $namedformat);
} else {
return ew_FormatDateTime(date('Y-m-d H:i:s'), 9);
}
} else {
return date('Y-m-d H:i:s');
}
}
/**
* Functions for backward compatibilty
*/
// Get current user name
function CurrentUserName() {
global $Security;
return (isset($Security)) ? $Security->CurrentUserName() : '';
}
// Get current user ID
function CurrentUserID() {
global $Security;
return (isset($Security)) ? $Security->CurrentUserID() : '';
}
// Get current parent user ID
function CurrentParentUserID() {
global $Security;
return (isset($Security)) ? $Security->CurrentParentUserID() : '';
}
// Get current User Level
function CurrentUserLevel() {
global $Security;
return (isset($Security)) ? $Security->CurrentUserLevelID() : -2;
}
// Allow list
function AllowList($TableName) {
global $Security;
return $Security->AllowList($TableName);
}
// Is Logged In
function IsLoggedIn() {
global $Security;
return $Security->IsLoggedIn();
}
// Is System Admin
function IsSysAdmin() {
global $Security;
return $Security->IsSysAdmin();
}
/**
* Functions for TEA encryption/decryption
*/
function long2str($v, $w) {
$len = count($v);
$s = array();
for ($i = 0; $i < $len; $i++)
{
$s[$i] = pack("V", $v[$i]);
}
if ($w) {
return substr(join('', $s), 0, $v[$len - 1]);
} else {
return join('', $s);
}
}
function str2long($s, $w) {
$v = unpack("V*", $s. str_repeat("\0", (4 - strlen($s) % 4) & 3));
$v = array_values($v);
if ($w) {
$v[count($v)] = strlen($s);
}
return $v;
}
// encrypt
function TEAencrypt($str, $key) {
if ($str == "") {
return "";
}
$v = str2long($str, true);
$k = str2long($key, false);
if (count($k) < 4) {
for ($i = count($k); $i < 4; $i++) {
$k[$i] = 0;
}
}
$n = count($v) - 1;
$z = $v[$n];
$y = $v[0];
$delta = 0x9E3779B9;
$q = floor(6 + 52 / ($n + 1));
$sum = 0;
while (0 < $q--) {
$sum = int32($sum + $delta);
$e = $sum >> 2 & 3;
for ($p = 0; $p < $n; $p++) {
$y = $v[$p + 1];
$mx = int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
$z = $v[$p] = int32($v[$p] + $mx);
}
$y = $v[0];
$mx = int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
$z = $v[$n] = int32($v[$n] + $mx);
}
return ew_UrlEncode(long2str($v, false));
}
// decrypt
function TEAdecrypt($str, $key) {
$str = ew_UrlDecode($str);
if ($str == "") {
return "";
}
$v = str2long($str, false);
$k = str2long($key, false);
if (count($k) < 4) {
for ($i = count($k); $i < 4; $i++) {
$k[$i] = 0;
}
}
$n = count($v) - 1;
$z = $v[$n];
$y = $v[0];
$delta = 0x9E3779B9;
$q = floor(6 + 52 / ($n + 1));
$sum = int32($q * $delta);
while ($sum != 0) {
$e = $sum >> 2 & 3;
for ($p = $n; $p > 0; $p--) {
$z = $v[$p - 1];
$mx = int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
$y = $v[$p] = int32($v[$p] - $mx);
}
$z = $v[$n];
$mx = int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
$y = $v[0] = int32($v[0] - $mx);
$sum = int32($sum - $delta);
}
return long2str($v, true);
}
function int32($n) {
while ($n >= 2147483648) $n -= 4294967296;
while ($n <= -2147483649) $n += 4294967296;
return (int)$n;
}
function ew_UrlEncode($string) {
$data = base64_encode($string);
return str_replace(array('+','/','='), array('-','_','.'), $data);
}
function ew_UrlDecode($string) {
$data = str_replace(array('-','_','.'), array('+','/','='), $string);
return base64_decode($data);
}
function rand_str($length = 32, $chars = 'abcdefghijklmnopqrstuvwxyz1234567890')
{
// Length of character list
$chars_length = (strlen($chars) - 1);
// Start our string
$string = $chars{rand(0, $chars_length)};
// Generate random string
for ($i = 1; $i < $length; $i = strlen($string))
{
// Grab a random character from our list
$r = $chars{rand(0, $chars_length)};
// Make sure the same two characters don't appear next to each other
if ($r != $string{$i - 1}) $string .= $r;
}
// Return the string
return $string;
}
function rand_int(){
return rand(1000000,9999999);
}
function check_rmtp_url($url){
$slashes_number = substr_count($url, '/');
$string = $url;
$nthtimes = 4;
$replaceme = '/';
if($slashes_number==5){
//echo "stringa modificata<br>";
$pos_4 = strnpos($url, $replaceme, $nthtimes);
//echo "posizione $nthtimes slashes : $pos_4<br>";
$new_url = substr($url, 0, $pos_4).'/'.substr($url, -(strlen($url)-$pos_4));
return $new_url;
}
return $url;
}
function strnpos($haystack, $needle, $nth, $offset = 0)
{
for ($retOffs=$offset-1; ($nth>0)&&($retOffs!==FALSE); $nth--) $retOffs = strpos($haystack, $needle, $retOffs+1);
return $retOffs;
}
function debug($text){
if (defined("EW_DEBUG_ENABLED")) echo($text."<br>");
}
function debug_var($var,$title = ""){
if (defined("EW_DEBUG_ENABLED")) echo("$title<pre>");
if (defined("EW_DEBUG_ENABLED")) var_dump($var);
if (defined("EW_DEBUG_ENABLED")) echo("</pre><br>");
}
function debug_die($msg = ""){ if (defined("EW_DEBUG_ENABLED")) die ("<strong>$msg</strong>");}
function setMessage($v) {
if (@$_SESSION[EW_SESSION_MESSAGE] <> "") { // Append
$_SESSION[EW_SESSION_MESSAGE] .= "<br>" . $v;
} else {
$_SESSION[EW_SESSION_MESSAGE] = $v;
}
}
// Show Message
function printMessage() {
if ($_SESSION[EW_SESSION_MESSAGE] <> "") { // Message in Session, display
echo "<p><span class=\"ewMessage\">" . $_SESSION[EW_SESSION_MESSAGE] . "</span></p>";
$_SESSION[EW_SESSION_MESSAGE] = ""; // Clear message in Session
}
}
?>
| miccunifi/Loki | web/service/include/phpfn50.php | PHP | apache-2.0 | 81,702 |
class Solution {
public int subarraySum(int[] nums, int k) {
int ret = 0;
for (int i = 0; i < nums.length; i++) {
int cur = nums[i];
if (cur == k) {
ret++;
}
for (int j = i+1; j < nums.length; j++) {
cur += nums[j];
if (cur == k) {
ret++;
}
}
}
return ret;
}
}
| MingfeiPan/leetcode | array/560.java | Java | apache-2.0 | 445 |
/*
* Copyright (C) 2015 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.primitives.UnsignedBytes;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.util.Arrays;
/**
* An {@link InputStream} that converts characters from a {@link Reader} into bytes using an
* arbitrary Charset.
*
* <p>This is an alternative to copying the data to an {@code OutputStream} via a {@code Writer},
* which is necessarily blocking. By implementing an {@code InputStream} it allows consumers to
* "pull" as much data as they can handle, which is more convenient when dealing with flow
* controlled, async APIs.
*
* @author Chris Nokleberg
*/
@GwtIncompatible
final class ReaderInputStream extends InputStream {
private final Reader reader;
private final CharsetEncoder encoder;
private final byte[] singleByte = new byte[1];
/**
* charBuffer holds characters that have been read from the Reader but not encoded yet. The buffer
* is perpetually "flipped" (unencoded characters between position and limit).
*/
private CharBuffer charBuffer;
/**
* byteBuffer holds encoded characters that have not yet been sent to the caller of the input
* stream. When encoding it is "unflipped" (encoded bytes between 0 and position) and when
* draining it is flipped (undrained bytes between position and limit).
*/
private ByteBuffer byteBuffer;
/** Whether we've finished reading the reader. */
private boolean endOfInput;
/** Whether we're copying encoded bytes to the caller's buffer. */
private boolean draining;
/** Whether we've successfully flushed the encoder. */
private boolean doneFlushing;
/**
* Creates a new input stream that will encode the characters from {@code reader} into bytes using
* the given character set. Malformed input and unmappable characters will be replaced.
*
* @param reader input source
* @param charset character set used for encoding chars to bytes
* @param bufferSize size of internal input and output buffers
* @throws IllegalArgumentException if bufferSize is non-positive
*/
ReaderInputStream(Reader reader, Charset charset, int bufferSize) {
this(reader,
charset.newEncoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE),
bufferSize);
}
/**
* Creates a new input stream that will encode the characters from {@code reader} into bytes using
* the given character set encoder.
*
* @param reader input source
* @param encoder character set encoder used for encoding chars to bytes
* @param bufferSize size of internal input and output buffers
* @throws IllegalArgumentException if bufferSize is non-positive
*/
ReaderInputStream(Reader reader, CharsetEncoder encoder, int bufferSize) {
this.reader = checkNotNull(reader);
this.encoder = checkNotNull(encoder);
checkArgument(bufferSize > 0, "bufferSize must be positive: %s", bufferSize);
encoder.reset();
charBuffer = CharBuffer.allocate(bufferSize);
charBuffer.flip();
byteBuffer = ByteBuffer.allocate(bufferSize);
}
@Override public void close() throws IOException {
reader.close();
}
@Override public int read() throws IOException {
return (read(singleByte) == 1) ? UnsignedBytes.toInt(singleByte[0]) : -1;
}
// TODO(chrisn): Consider trying to encode/flush directly to the argument byte
// buffer when possible.
@Override public int read(byte[] b, int off, int len) throws IOException {
// Obey InputStream contract.
checkPositionIndexes(off, off + len, b.length);
if (len == 0) {
return 0;
}
// The rest of this method implements the process described by the CharsetEncoder javadoc.
int totalBytesRead = 0;
boolean doneEncoding = endOfInput;
DRAINING: while (true) {
// We stay in draining mode until there are no bytes left in the output buffer. Then we go
// back to encoding/flushing.
if (draining) {
totalBytesRead += drain(b, off + totalBytesRead, len - totalBytesRead);
if (totalBytesRead == len || doneFlushing) {
return (totalBytesRead > 0) ? totalBytesRead : -1;
}
draining = false;
byteBuffer.clear();
}
while (true) {
// We call encode until there is no more input. The last call to encode will have endOfInput
// == true. Then there is a final call to flush.
CoderResult result;
if (doneFlushing) {
result = CoderResult.UNDERFLOW;
} else if (doneEncoding) {
result = encoder.flush(byteBuffer);
} else {
result = encoder.encode(charBuffer, byteBuffer, endOfInput);
}
if (result.isOverflow()) {
// Not enough room in output buffer--drain it, creating a bigger buffer if necessary.
startDraining(true);
continue DRAINING;
} else if (result.isUnderflow()) {
// If encoder underflows, it means either:
// a) the final flush() succeeded; next drain (then done)
// b) we encoded all of the input; next flush
// c) we ran of out input to encode; next read more input
if (doneEncoding) { // (a)
doneFlushing = true;
startDraining(false);
continue DRAINING;
} else if (endOfInput) { // (b)
doneEncoding = true;
} else { // (c)
readMoreChars();
}
} else if (result.isError()) {
// Only reach here if a CharsetEncoder with non-REPLACE settings is used.
result.throwException();
return 0; // Not called.
}
}
}
}
/** Returns a new CharBuffer identical to buf, except twice the capacity. */
private static CharBuffer grow(CharBuffer buf) {
char[] copy = Arrays.copyOf(buf.array(), buf.capacity() * 2);
CharBuffer bigger = CharBuffer.wrap(copy);
bigger.position(buf.position());
bigger.limit(buf.limit());
return bigger;
}
/** Handle the case of underflow caused by needing more input characters. */
private void readMoreChars() throws IOException {
// Possibilities:
// 1) array has space available on right hand side (between limit and capacity)
// 2) array has space available on left hand side (before position)
// 3) array has no space available
//
// In case 2 we shift the existing chars to the left, and in case 3 we create a bigger
// array, then they both become case 1.
if (availableCapacity(charBuffer) == 0) {
if (charBuffer.position() > 0) {
// (2) There is room in the buffer. Move existing bytes to the beginning.
charBuffer.compact().flip();
} else {
// (3) Entire buffer is full, need bigger buffer.
charBuffer = grow(charBuffer);
}
}
// (1) Read more characters into free space at end of array.
int limit = charBuffer.limit();
int numChars = reader.read(charBuffer.array(), limit, availableCapacity(charBuffer));
if (numChars == -1) {
endOfInput = true;
} else {
charBuffer.limit(limit + numChars);
}
}
/** Returns the number of elements between the limit and capacity. */
private static int availableCapacity(Buffer buffer) {
return buffer.capacity() - buffer.limit();
}
/**
* Flips the buffer output buffer so we can start reading bytes from it. If we are starting to
* drain because there was overflow, and there aren't actually any characters to drain, then the
* overflow must be due to a small output buffer.
*/
private void startDraining(boolean overflow) {
byteBuffer.flip();
if (overflow && byteBuffer.remaining() == 0) {
byteBuffer = ByteBuffer.allocate(byteBuffer.capacity() * 2);
} else {
draining = true;
}
}
/**
* Copy as much of the byte buffer into the output array as possible, returning the (positive)
* number of characters copied.
*/
private int drain(byte[] b, int off, int len) {
int remaining = Math.min(len, byteBuffer.remaining());
byteBuffer.get(b, off, remaining);
return remaining;
}
}
| aiyanbo/guava | guava/src/com/google/common/io/ReaderInputStream.java | Java | apache-2.0 | 9,274 |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.synchronoss.cloud.nio.multipart.util.collect;
import java.util.Iterator;
/**
* <p> Class taken from the google guava project <a href="https://code.google.com/p/guava-libraries/">guava</a>.
*
* @param <E> the type of elements returned by this iterator
*/
public abstract class UnmodifiableIterator<E> implements Iterator<E> {
/** Constructor for use by subclasses. */
protected UnmodifiableIterator() {}
/**
* Guaranteed to throw an exception and leave the underlying data unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final void remove() {
throw new UnsupportedOperationException();
}
}
| synchronoss/nio-multipart | nio-multipart-parser/src/main/java/org/synchronoss/cloud/nio/multipart/util/collect/UnmodifiableIterator.java | Java | apache-2.0 | 1,352 |
import streamcorpus as sc
import cuttsum.events
import cuttsum.corpora
from cuttsum.trecdata import SCChunkResource
from cuttsum.pipeline import ArticlesResource, DedupedArticlesResource
import os
import pandas as pd
from datetime import datetime
from collections import defaultdict
import matplotlib.pylab as plt
plt.style.use('ggplot')
pd.set_option('display.max_rows', 500)
pd.set_option('display.width', 200)
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF8')
def format_int(x):
return locale.format("%d", x, grouping=True)
def epoch(dt):
return int((dt - datetime(1970, 1, 1)).total_seconds())
chunk_res = SCChunkResource()
articles_res = ArticlesResource()
ded_articles_res = DedupedArticlesResource()
data = []
event2ids = defaultdict(set)
fltr_event2ids = defaultdict(set)
for event in cuttsum.events.get_events():
corpus = cuttsum.corpora.get_raw_corpus(event)
hours = event.list_event_hours()
hour2ded = defaultdict(int)
hour2ded_fltr = defaultdict(int)
ded_df = ded_articles_res.get_stats_df(event, corpus, "goose", .8)
if ded_df is not None:
if event.query_num > 25:
for ids in ded_df["stream ids"].apply(eval).tolist():
for id1 in ids:
event2ids[event.fs_name()].add(id1)
for _, row in ded_df.iterrows():
dt = datetime.utcfromtimestamp(row["earliest"])
hour = datetime(dt.year, dt.month, dt.day, dt.hour)
hour2ded[hour] += 1
if row["match"] == True:
hour2ded_fltr[hour] += 1
hour2goose = defaultdict(int)
for hour in hours:
path = articles_res.get_chunk_path(event, "goose", hour, corpus)
if path is None:
continue
#print path
fname = os.path.split(path)[1]
num_goose = int(fname.split("-")[0])
hour2goose[hour] = num_goose
# goose_df = articles_res.get_stats_df(event, "goose")
# if goose_df is not None:
# for _, row in goose_df.iterrows():
# dt = datetime.utcfromtimestamp(row["hour"])
# hour = datetime(dt.year, dt.month, dt.day, dt.hour)
# hour2goose[hour] = row["goose articles"]
for hour in hours:
raw_chunks = chunk_res.get_chunks_for_hour(hour, corpus, event)
num_raw_si = 0
for chunk in raw_chunks:
fname = os.path.split(chunk)[1]
num_raw_si += int(fname.split("-")[1])
#num_fltr_si = len(articles_res.get_si(event, corpus, "goose", hour))
data.append({
"event": event.query_id,
"title": event.title,
"hour": hour,
"raw articles": num_raw_si,
"goose articles": hour2goose[hour],
"deduped articles": hour2ded[hour],
"deduped match articles": hour2ded_fltr[hour],
})
for event in cuttsum.events.get_events():
if event.query_num < 26: continue
corpus = cuttsum.corpora.FilteredTS2015()
hours = event.list_event_hours()
hour2ded = defaultdict(int)
hour2ded_fltr = defaultdict(int)
ded_df = ded_articles_res.get_stats_df(event, corpus, "goose", .8)
if ded_df is not None:
for ids in ded_df["stream ids"].apply(eval).tolist():
for id1 in ids:
fltr_event2ids[event.fs_name()].add(id1)
for _, row in ded_df.iterrows():
dt = datetime.utcfromtimestamp(row["earliest"])
hour = datetime(dt.year, dt.month, dt.day, dt.hour)
hour2ded[hour] += 1
if row["match"] == True:
hour2ded_fltr[hour] += 1
hour2goose = defaultdict(int)
for hour in hours:
path = articles_res.get_chunk_path(event, "goose", hour, corpus)
if path is None:
continue
print path
fname = os.path.split(path)[1]
num_goose = int(fname.split("-")[0])
hour2goose[hour] = num_goose
# goose_df = articles_res.get_stats_df(event, "goose")
# if goose_df is not None:
# for _, row in goose_df.iterrows():
# dt = datetime.utcfromtimestamp(row["hour"])
# hour = datetime(dt.year, dt.month, dt.day, dt.hour)
# hour2goose[hour] = row["goose articles"]
for hour in hours:
print hour
raw_chunks = chunk_res.get_chunks_for_hour(hour, corpus, event)
num_raw_si = 0
for chunk in raw_chunks:
fname = os.path.split(chunk)[1]
#num_raw_si += int(fname.split("-")[1])
with sc.Chunk(path=chunk, mode="rb", message=corpus.sc_msg()) as c:
for si in c:
num_raw_si += 1
#num_fltr_si = len(articles_res.get_si(event, corpus, "goose", hour))
data.append({
"event": event.query_id + " (filtered)",
"title": event.title,
"hour": hour,
"raw articles": num_raw_si,
"goose articles": hour2goose[hour],
"deduped articles": hour2ded[hour],
"deduped match articles": hour2ded_fltr[hour],
})
df = pd.DataFrame(data)
cols = ["raw articles", "goose articles", "deduped articles",
"deduped match articles"]
df_sum = df.groupby("event")[cols].sum()
df_sum["raw articles"] = df_sum["raw articles"].apply(format_int)
df_sum["goose articles"] = df_sum["goose articles"].apply(format_int)
df_sum["deduped articles"] = df_sum["deduped articles"].apply(format_int)
df_sum["deduped match articles"] = df_sum["deduped match articles"].apply(format_int)
print df_sum
print
coverage = []
for event in cuttsum.events.get_events():
if event.query_num < 26: continue
isect = event2ids[event.fs_name()].intersection(fltr_event2ids[event.fs_name()])
n_isect = len(isect)
n_unfltr = max(len(event2ids[event.fs_name()]), 1)
n_fltr = max(len(fltr_event2ids[event.fs_name()]), 1)
print event.fs_name()
print n_isect, float(n_isect) / n_fltr, float(n_isect) / n_unfltr
coverage.append({
"event": event.query_id,
"intersection": n_isect,
"isect/n_2015F": float(n_isect) / n_fltr,
"isect/n_2014": float(n_isect) / n_unfltr,
})
df = pd.DataFrame(coverage)
df_u = df.mean()
df_u["event"] = "mean"
print pd.concat([df, df_u.to_frame().T]).set_index("event")
exit()
with open("article_count.tex", "w") as f:
f.write(df_sum.to_latex())
import os
if not os.path.exists("plots"):
os.makedirs("plots")
import cuttsum.judgements
ndf = cuttsum.judgements.get_merged_dataframe()
for (event, title), group in df.groupby(["event", "title"]):
matches = ndf[ndf["query id"] == event]
#fig = plt.figure()
group = group.set_index(["hour"])
#ax = group[["goose articles", "deduped articles", "deduped match articles"]].plot()
linex = epoch(group.index[10])
ax = plt.plot(group.index, group["goose articles"], label="goose")
ax = plt.plot(group.index, group["deduped articles"], label="dedupe")
ax = plt.plot(group.index, group["deduped match articles"], label="dedupe qmatch")
for nugget, ngroup in matches.groupby("nugget id"):
times = ngroup["update id"].apply(lambda x: datetime.utcfromtimestamp(int(x.split("-")[0])))
#ngroup = ngroup.sort("timestamp")
times.sort()
times = times.reset_index(drop=True)
if len(times) == 0: continue
plt.plot_date(
(times[0], times[0]),
(0, plt.ylim()[1]),
'--', color="black", linewidth=.5, alpha=.5)
plt.gcf().autofmt_xdate()
plt.gcf().suptitle(title)
plt.gcf().savefig(os.path.join("plots", "{}-stream.png".format(event)))
plt.close("all")
| kedz/cuttsum | trec2015/sbin/reports/raw-stream-count.py | Python | apache-2.0 | 7,738 |
/*!
* Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
body {
overflow-x: hidden;
}
p {
font-size: 20px;
font-family: 'Amatic SC', cursive,Helvetica,Arial,sans-serif;
}
p.med{
font-size: 25px;
color: #000000;
}
p.sub {
color: #18bc9c;
font-size:25px;
}
p.stwo {
color: #18bc9c;
font-size:20px;
}
p.small {
font-size: 16px;
}
p.big {
font-size: 48px;
}
.boxie{
padding: 25px;
border-radius: 5px 5px 5px 5px;
-moz-border-radius: 5px 5px 5px 5px;
-webkit-border-radius: 5px 5px 5px 5px;
border: 0px solid #000000;
color: #18bc9c;
display: inline-block center;
}
.blue{
color: #18bc9c;
}
a,
a:hover,
a:focus,
a:active,
a.active {
outline: 0;
color: #18bc9c;
}
label,
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: 'Amatic SC', cursive,Helvetica,Arial,sans-serif;
}
hr.star-light,
hr.star-primary {
margin: 25px auto 30px;
padding: 0;
max-width: 250px;
border: 0;
border-top: solid 5px;
text-align: center;
}
hr.star-light:after,
hr.star-primary:after {
content: "\f005";
display: inline-block;
position: relative;
top: -.8em;
padding: 0 .25em;
font-family: 'Amatic SC', cursive;
font-size: 2em;
}
hr.star-light {
border-color: #fff;
}
hr.star-light:after {
color: #fff;
background-color: #187489;
}
hr.star-primary {
border-color: #2c3e50;
}
hr.star-primary:after {
color: #2c3e50;
background-color: #fff;
}
.img-centered {
margin: 0 auto;
}
header {
text-align: center;
color: #fff;
background: #187489;
}
header .container {
padding: 0px;
}
header img {
display: block;
margin: 0 auto 10px;
margin-top: -60px;
padding-bottom: 40px;
}
.img-abs {
position: absolute;
margin-top: -650px;
margin-left:60px;
}
header .intro-text .name {
display: block;
margin: 0;
font-family: 'Amatic SC', cursive;
font-size: 3em;
font-weight: 300;
}
header .intro-text .skills {
margin-top: -30px;
font-family: 'Amatic SC', cursive;
font-size: 4em;
font-weight: 300;
}
@media(min-width:768px) {
header .container {
padding-top: 75px;
padding-bottom: 25px;
}
header .intro-text .name {
font-size: 4.75em;
}
header .intro-text .skills {
font-size: 3em;
}
}
@media(min-width:768px) {
.navbar-fixed-top {
padding: 25px 0;
-webkit-transition: padding .3s;
-moz-transition: padding .3s;
transition: padding .3s;
}
.navbar-fixed-top .navbar-brand {
font-size: 1.5em;
-webkit-transition: all .3s;
-moz-transition: all .3s;
transition: all .3s;
}
.navbar-fixed-top.navbar-shrink {
padding: 10px 0;
}
.navbar-fixed-top.navbar-shrink .navbar-brand {
font-size: 1.5em;
}
}
.navbar {
background-color: #187489;
padding-bottom: 20px;
margin: 0;
font-family: 'Amatic SC', cursive;
font-size: 2.5em;
font-weight: 500;
color: #628e9c;
}
.navbar a:focus {
outline: 0;
}
.navbar .navbar-nav {
letter-spacing: 1px;
}
.navbar .navbar-nav li a:focus {
outline: 0;
}
.navbar-default,
.navbar-inverse {
border: 0;
}
section {
padding: 100px 0;
}
section h2 {
margin: 0;
font-size: 3em;
}
section.success {
color: #fff;
background: #18bc9c;
}
section.success a,
section.success a:hover,
section.success a:focus,
section.success a:active,
section.success a.active {
outline: 0;
color: #2c3e50;
}
@media(max-width:767px) {
section {
padding: 75px 0;
}
section.first {
padding-top: 75px;
}
}
#portfolio .portfolio-item {
right: 0;
margin: 0 0 15px;
}
#portfolio .portfolio-item .portfolio-link {
display: block;
position: relative;
margin: 0 auto;
max-width: 400px;
}
#portfolio .portfolio-item .portfolio-link .caption {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
background: rgba(24,188,156,.9);
-webkit-transition: all ease .5s;
-moz-transition: all ease .5s;
transition: all ease .5s;
}
#portfolio .portfolio-item .portfolio-link .caption:hover {
opacity: 1;
}
#portfolio .portfolio-item .portfolio-link .caption .caption-content {
position: absolute;
top: 50%;
width: 100%;
height: 20px;
margin-top: -12px;
text-align: center;
font-size: 20px;
color: #fff;
}
#portfolio .portfolio-item .portfolio-link .caption .caption-content i {
margin-top: -12px;
}
#portfolio .portfolio-item .portfolio-link .caption .caption-content h3,
#portfolio .portfolio-item .portfolio-link .caption .caption-content h4 {
margin: 0;
}
#portfolio * {
z-index: 2;
}
@media(min-width:767px) {
#portfolio .portfolio-item {
margin: 0 0 30px;
}
}
.btn-outline {
margin-top: 15px;
border: solid 2px #fff;
font-size: 20px;
color: #fff;
background: 0 0;
transition: all .3s ease-in-out;
}
.btn-outline:hover,
.btn-outline:focus,
.btn-outline:active,
.btn-outline.active {
border: solid 2px #fff;
color: #18bc9c;
background: #fff;
}
.floating-label-form-group {
position: relative;
margin-bottom: 0;
padding-bottom: .5em;
border-bottom: 1px solid #eee;
}
.floating-label-form-group input,
.floating-label-form-group textarea {
z-index: 1;
position: relative;
padding-right: 0;
padding-left: 0;
border: 0;
border-radius: 0;
font-size: 1.5em;
background: 0 0;
box-shadow: none!important;
resize: none;
}
.floating-label-form-group label {
display: block;
z-index: 0;
position: relative;
top: 2em;
margin: 0;
font-size: .85em;
line-height: 1.764705882em;
vertical-align: middle;
vertical-align: baseline;
opacity: 0;
-webkit-transition: top .3s ease,opacity .3s ease;
-moz-transition: top .3s ease,opacity .3s ease;
-ms-transition: top .3s ease,opacity .3s ease;
transition: top .3s ease,opacity .3s ease;
}
.floating-label-form-group::not(:first-child) {
padding-left: 14px;
border-left: 1px solid #eee;
}
.floating-label-form-group-with-value label {
top: 0;
opacity: 1;
}
.floating-label-form-group-with-focus label {
color: #18bc9c;
}
form .row:first-child .floating-label-form-group {
border-top: 1px solid #eee;
}
footer {
color: #fff;
}
footer h3 {
margin-bottom: 30px;
}
footer .footer-above {
padding-top: 50px;
background-color: #2c3e50;
}
footer .footer-col {
margin-bottom: 50px;
}
footer .footer-below {
padding: 25px 0;
background-color: #233140;
}
.btn-social {
display: inline-block;
width: 50px;
height: 50px;
border: 2px solid #fff;
border-radius: 100%;
text-align: center;
font-size: 20px;
line-height: 45px;
}
.btn:focus,
.btn:active,
.btn.active {
outline: 0;
}
.scroll-top {
z-index: 1049;
position: fixed;
right: 2%;
bottom: 2%;
width: 50px;
height: 50px;
}
.scroll-top .btn {
width: 50px;
height: 50px;
border-radius: 100%;
font-size: 20px;
line-height: 28px;
}
.scroll-top .btn:focus {
outline: 0;
}
.portfolio-modal .modal-content {
padding: 100px 0;
min-height: 100%;
border: 0;
border-radius: 0;
text-align: center;
background-clip: border-box;
-webkit-box-shadow: none;
box-shadow: none;
}
.portfolio-modal .modal-content h2 {
margin: 0;
font-size: 3em;
}
.portfolio-modal .modal-content img {
margin-bottom: 30px;
}
.portfolio-modal .modal-content .item-details {
margin: 30px 0;
}
.portfolio-modal .close-modal {
position: absolute;
top: 25px;
right: 25px;
width: 75px;
height: 75px;
background-color: transparent;
cursor: pointer;
}
.portfolio-modal .close-modal:hover {
opacity: .3;
}
.portfolio-modal .close-modal .lr {
z-index: 1051;
width: 1px;
height: 75px;
margin-left: 35px;
background-color: #2c3e50;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
.portfolio-modal .close-modal .lr .rl {
z-index: 1052;
width: 1px;
height: 75px;
background-color: #2c3e50;
-webkit-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
.portfolio-modal .modal-backdrop {
display: none;
opacity: 0;
}
.floating{
float: left;
-webkit-animation-name: Floatingx;
-webkit-animation-duration: 4s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: ease-in-out;
-moz-animation-name: Floating;
-moz-animation-duration: 4s;
-moz-animation-iteration-count: infinite;
-moz-animation-timing-function: ease-in-out;
}
@-webkit-keyframes Floatingx{
from {-webkit-transform:translate(0, 0px);}
65% {-webkit-transform:translate(0, 15px);}
to {-webkit-transform: translate(0, -0px); }
}
@-moz-keyframes Floating{
from {-moz-transform:translate(0, 0px);}
65% {-moz-transform:translate(0, 15px);}
to {-moz-transform: translate(0, -0px);}
}
.easing{
float: left;
transition: transform 2s ease-in-out;
-webkit-animation-name: Floatingx;
-webkit-animation-duration: 2s;
-webkit-animation-iteration-count: 1;
-webkit-animation-timing-function: ease-in-out;
-moz-animation-name: Floating;
-moz-animation-duration: 2s;
-moz-animation-iteration-count: 1;
-moz-animation-timing-function: ease-in-out;
}
@-webkit-keyframes Floatingx{
from {-webkit-transform:translate(0, 0px);}
65% {-webkit-transform:translate(0, 20px);}
to {-webkit-transform: translate(0, -0px); }
}
@-moz-keyframes Floating{
from {-moz-transform:translate(0, 0px);}
65% {-moz-transform:translate(0, 20px);}
to {-moz-transform: translate(0, -0px);}
}
| sangeethaalagappan/floobes | css/freelancer.css | CSS | apache-2.0 | 10,103 |
namespace UnityEngine.TestTools.Utils
{
internal interface IScriptingRuntimeProxy
{
string[] GetAllUserAssemblies();
}
}
| IanFMartin/Character-Creator | Character creator/Library/PackageCache/com.unity.test-framework@1.0.13/UnityEngine.TestRunner/Utils/AssemblyProvider/IScriptingRuntimeProxy.cs | C# | apache-2.0 | 141 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_29) on Sat Mar 17 18:05:26 MSK 2012 -->
<TITLE>
org.apache.poi.xssf.extractor Class Hierarchy (POI API Documentation)
</TITLE>
<META NAME="date" CONTENT="2012-03-17">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.apache.poi.xssf.extractor Class Hierarchy (POI API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/apache/poi/xssf/eventusermodel/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../../org/apache/poi/xssf/model/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/poi/xssf/extractor/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
Hierarchy For Package org.apache.poi.xssf.extractor
</H2>
</CENTER>
<DL>
<DT><B>Package Hierarchies:</B><DD><A HREF="../../../../../overview-tree.html">All Packages</A></DL>
<HR>
<H2>
Class Hierarchy
</H2>
<UL>
<LI TYPE="circle">java.lang.Object<UL>
<LI TYPE="circle">org.apache.poi.<A HREF="../../../../../org/apache/poi/POITextExtractor.html" title="class in org.apache.poi"><B>POITextExtractor</B></A><UL>
<LI TYPE="circle">org.apache.poi.<A HREF="../../../../../org/apache/poi/POIXMLTextExtractor.html" title="class in org.apache.poi"><B>POIXMLTextExtractor</B></A><UL>
<LI TYPE="circle">org.apache.poi.xssf.extractor.<A HREF="../../../../../org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.html" title="class in org.apache.poi.xssf.extractor"><B>XSSFEventBasedExcelExtractor</B></A><LI TYPE="circle">org.apache.poi.xssf.extractor.<A HREF="../../../../../org/apache/poi/xssf/extractor/XSSFExcelExtractor.html" title="class in org.apache.poi.xssf.extractor"><B>XSSFExcelExtractor</B></A> (implements org.apache.poi.ss.extractor.<A HREF="../../../../../org/apache/poi/ss/extractor/ExcelExtractor.html" title="interface in org.apache.poi.ss.extractor">ExcelExtractor</A>)
</UL>
</UL>
<LI TYPE="circle">org.apache.poi.xssf.extractor.<A HREF="../../../../../org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.SheetTextExtractor.html" title="class in org.apache.poi.xssf.extractor"><B>XSSFEventBasedExcelExtractor.SheetTextExtractor</B></A> (implements org.apache.poi.xssf.eventusermodel.<A HREF="../../../../../org/apache/poi/xssf/eventusermodel/XSSFSheetXMLHandler.SheetContentsHandler.html" title="interface in org.apache.poi.xssf.eventusermodel">XSSFSheetXMLHandler.SheetContentsHandler</A>)
<LI TYPE="circle">org.apache.poi.xssf.extractor.<A HREF="../../../../../org/apache/poi/xssf/extractor/XSSFExportToXml.html" title="class in org.apache.poi.xssf.extractor"><B>XSSFExportToXml</B></A> (implements java.util.Comparator<T>)
<LI TYPE="circle">org.apache.poi.xssf.extractor.<A HREF="../../../../../org/apache/poi/xssf/extractor/XSSFImportFromXML.html" title="class in org.apache.poi.xssf.extractor"><B>XSSFImportFromXML</B></A></UL>
</UL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/apache/poi/xssf/eventusermodel/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../../org/apache/poi/xssf/model/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/poi/xssf/extractor/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright 2012 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML>
| Stephania16/ProductDesignGame | MinimaxAlgorithm/poi-3.8/docs/apidocs/org/apache/poi/xssf/extractor/package-tree.html | HTML | apache-2.0 | 8,084 |
/**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.math.interpolation;
/**
*
*/
public class NonnegativityPreservingCubicSplineInterpolator1D extends PiecewisePolynomialInterpolator1D {
/** Serialization version */
private static final long serialVersionUID = 1L;
/**
* If the primary interpolation method is not specified, the cubic spline interpolation with natrual endpoint conditions is used.
*/
public NonnegativityPreservingCubicSplineInterpolator1D() {
super(new NonnegativityPreservingCubicSplineInterpolator(new NaturalSplineInterpolator()));
}
/**
* @param method
* Primary interpolation method whose first derivative values are modified according to the non-negativity conditions
*/
public NonnegativityPreservingCubicSplineInterpolator1D(final PiecewisePolynomialInterpolator method) {
super(new NonnegativityPreservingCubicSplineInterpolator(method));
}
}
| McLeodMoores/starling | projects/analytics/src/main/java/com/opengamma/analytics/math/interpolation/NonnegativityPreservingCubicSplineInterpolator1D.java | Java | apache-2.0 | 1,042 |
package importer
import (
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
"github.com/anz-bank/sysl/pkg/syslutil"
"github.com/sirupsen/logrus/hooks/test"
"github.com/stretchr/testify/require"
)
var (
update = flag.Bool("update", false, "Update golden test files")
)
func TestMain(m *testing.M) {
flag.Parse()
os.Exit(m.Run())
}
type testConfig struct {
name string
testDir string
testExtension string
format string
}
func runImportEqualityTests(t *testing.T, cfg testConfig) {
t.Helper()
files, err := ioutil.ReadDir(cfg.testDir)
require.NoError(t, err)
for _, f := range files {
if f.IsDir() {
continue
}
logger, _ := test.NewNullLogger()
ext := filepath.Ext(f.Name())
if strings.EqualFold(ext, cfg.testExtension) {
filename := strings.TrimSuffix(f.Name(), ext)
t.Run(fmt.Sprintf("%s-%s", cfg.name, filename), func(t *testing.T) {
t.Parallel()
syslFile := filepath.Join(cfg.testDir, filename+".sysl")
fileToImport := syslutil.MustAbsolute(t, filepath.Join(cfg.testDir, filename+cfg.testExtension))
input, err := ioutil.ReadFile(fileToImport)
require.NoError(t, err)
absFilePath, err := filepath.Abs(filepath.Join(cfg.testDir, filename+cfg.testExtension))
require.NoError(t, err)
imp, err := Factory(absFilePath, false, cfg.format, input, logger)
require.NoError(t, err)
imp.WithAppName("TestApp").WithPackage("com.example.package")
result, err := imp.LoadFile(absFilePath)
require.NoError(t, err)
if *update {
err = ioutil.WriteFile(syslFile, []byte(result), 0600)
if err != nil {
t.Error(err)
}
}
expected, err := ioutil.ReadFile(syslFile)
require.NoError(t, err)
expected = syslutil.HandleCRLF(expected)
require.NoError(t, err)
require.Equal(t, string(expected), result)
})
}
}
}
func runImportDirEqualityTests(t *testing.T, cfg testConfig) {
t.Helper()
logger, _ := test.NewNullLogger()
syslFile := filepath.Join(cfg.testDir, filepath.Base(cfg.testDir)+".sysl")
path := syslutil.MustAbsolute(t, cfg.testDir)
imp, err := Factory(path, true, cfg.format, nil, logger)
require.NoError(t, err)
out, err := imp.WithAppName("TestApp").WithPackage("com.example.package").LoadFile(path)
require.NoError(t, err)
expected, err := ioutil.ReadFile(syslFile)
require.NoError(t, err)
expected = syslutil.HandleCRLF(expected)
require.NoError(t, err)
require.Equal(t, string(expected), out)
}
func TestLoadOpenAPI2JSONFromTestFiles(t *testing.T) {
runImportEqualityTests(t, testConfig{
name: "TestLoadOpenAPI2JSONFromTestFiles",
testDir: "tests/openapi2",
testExtension: ".json",
})
}
func TestLoadOpenAPI2FromTestFiles(t *testing.T) {
runImportEqualityTests(t, testConfig{
name: "TestLoadOpenAPI2FromTestFiles",
testDir: "tests/openapi2",
testExtension: ".yaml",
})
}
func TestLoadOpenAPI3FromTestFiles(t *testing.T) {
runImportEqualityTests(t, testConfig{
name: "TestLoadOpenAPI3FromTestFiles",
testDir: "tests/openapi3",
testExtension: ".yaml",
})
}
func TestLoadXSDFromTestFiles(t *testing.T) {
runImportEqualityTests(t, testConfig{
name: "TestLoadXSDFromTestFiles",
testDir: "tests/xsd",
testExtension: ".xsd",
})
}
func TestLoadSpannerFromTestFiles(t *testing.T) {
runImportEqualityTests(t, testConfig{
name: "TestLoadSpannerFromTestFiles",
testDir: "sql/tests/spanner",
testExtension: ".sql",
format: "spannerSQL",
})
}
func TestLoadSpannerDirFromTestDir(t *testing.T) {
runImportDirEqualityTests(t, testConfig{
name: "TestLoadSpannerDirFromTestDir",
testDir: "sql/tests/spanner/migrations",
testExtension: "",
format: "spannerSQLdir",
})
}
func TestLoadPostgresqlFromTestFiles(t *testing.T) {
runImportEqualityTests(t, testConfig{
name: "TestLoadPostgresqlFromTestFiles",
testDir: "sql/tests/postgresql",
testExtension: ".sql",
format: "postgres",
})
}
func TestLoadPostgresqlDirFromTestFiles(t *testing.T) {
runImportEqualityTests(t, testConfig{
name: "TestLoadPostgresqlDirFromTestFiles",
testDir: "sql/tests/postgresql/migrations",
testExtension: "",
format: "postgresDir",
})
}
func TestLoadMySQLFromTestFiles(t *testing.T) {
runImportEqualityTests(t, testConfig{
name: "TestLoadMySQLFromTestFiles",
testDir: "sql/tests/mysql",
testExtension: ".sql",
format: "mysql",
})
}
func TestLoadMySQLDirFromTestFiles(t *testing.T) {
runImportEqualityTests(t, testConfig{
name: "TestLoadMySQLDirFromTestFiles",
testDir: "sql/tests/mysql/migrations",
testExtension: "",
format: "mysqlDir",
})
}
func TestLoadBigQueryFromTestFiles(t *testing.T) {
runImportEqualityTests(t, testConfig{
name: "TestLoadBigQueryFromTestFiles",
testDir: "sql/tests/bigquery",
testExtension: ".sql",
format: "bigquery",
})
}
/*
func TestLoadGrammarFromTestFiles(t *testing.T) {
runImportEqualityTests(t, testConfig{
name: "TestLoadGrammarFromTestFiles",
testDir: "tests-grammar",
testExtension: "g",
mode: ModeGrammar,
fn: LoadGrammar,
})
}
*/
func TestLoadAvroFromTestFiles(t *testing.T) {
runImportEqualityTests(t, testConfig{
name: "TestLoadAvroFromTestFiles",
testDir: "avro/tests",
testExtension: ".avsc",
})
}
| ANZ-bank/Sysl | pkg/importer/importer_test.go | GO | apache-2.0 | 5,486 |
/*
* Copyright 2014 The Netty Project
*
* The Netty Project 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:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.channel.epoll;
import io.netty.channel.DefaultSelectStrategyFactory;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.EventLoopTaskQueueFactory;
import io.netty.channel.MultithreadEventLoopGroup;
import io.netty.channel.SelectStrategyFactory;
import io.netty.channel.SingleThreadEventLoop;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.EventExecutorChooserFactory;
import io.netty.util.concurrent.RejectedExecutionHandler;
import io.netty.util.concurrent.RejectedExecutionHandlers;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadFactory;
/**
* {@link EventLoopGroup} which uses epoll under the covers. Because of this
* it only works on linux.
*/
public final class EpollEventLoopGroup extends MultithreadEventLoopGroup {
{
// Ensure JNI is initialized by the time this class is loaded.
Epoll.ensureAvailability();
}
/**
* Create a new instance using the default number of threads and the default {@link ThreadFactory}.
*/
public EpollEventLoopGroup() {
this(0);
}
/**
* Create a new instance using the specified number of threads and the default {@link ThreadFactory}.
*/
public EpollEventLoopGroup(int nThreads) {
this(nThreads, (ThreadFactory) null);
}
/**
* Create a new instance using the default number of threads and the given {@link ThreadFactory}.
*/
@SuppressWarnings("deprecation")
public EpollEventLoopGroup(ThreadFactory threadFactory) {
this(0, threadFactory, 0);
}
/**
* Create a new instance using the specified number of threads and the default {@link ThreadFactory}.
*/
@SuppressWarnings("deprecation")
public EpollEventLoopGroup(int nThreads, SelectStrategyFactory selectStrategyFactory) {
this(nThreads, (ThreadFactory) null, selectStrategyFactory);
}
/**
* Create a new instance using the specified number of threads and the given {@link ThreadFactory}.
*/
@SuppressWarnings("deprecation")
public EpollEventLoopGroup(int nThreads, ThreadFactory threadFactory) {
this(nThreads, threadFactory, 0);
}
public EpollEventLoopGroup(int nThreads, Executor executor) {
this(nThreads, executor, DefaultSelectStrategyFactory.INSTANCE);
}
/**
* Create a new instance using the specified number of threads and the given {@link ThreadFactory}.
*/
@SuppressWarnings("deprecation")
public EpollEventLoopGroup(int nThreads, ThreadFactory threadFactory, SelectStrategyFactory selectStrategyFactory) {
this(nThreads, threadFactory, 0, selectStrategyFactory);
}
/**
* Create a new instance using the specified number of threads, the given {@link ThreadFactory} and the given
* maximal amount of epoll events to handle per epollWait(...).
*
* @deprecated Use {@link #EpollEventLoopGroup(int)} or {@link #EpollEventLoopGroup(int, ThreadFactory)}
*/
@Deprecated
public EpollEventLoopGroup(int nThreads, ThreadFactory threadFactory, int maxEventsAtOnce) {
this(nThreads, threadFactory, maxEventsAtOnce, DefaultSelectStrategyFactory.INSTANCE);
}
/**
* Create a new instance using the specified number of threads, the given {@link ThreadFactory} and the given
* maximal amount of epoll events to handle per epollWait(...).
*
* @deprecated Use {@link #EpollEventLoopGroup(int)}, {@link #EpollEventLoopGroup(int, ThreadFactory)}, or
* {@link #EpollEventLoopGroup(int, SelectStrategyFactory)}
*/
@Deprecated
public EpollEventLoopGroup(int nThreads, ThreadFactory threadFactory, int maxEventsAtOnce,
SelectStrategyFactory selectStrategyFactory) {
super(nThreads, threadFactory, maxEventsAtOnce, selectStrategyFactory, RejectedExecutionHandlers.reject());
}
public EpollEventLoopGroup(int nThreads, Executor executor, SelectStrategyFactory selectStrategyFactory) {
super(nThreads, executor, 0, selectStrategyFactory, RejectedExecutionHandlers.reject());
}
public EpollEventLoopGroup(int nThreads, Executor executor, EventExecutorChooserFactory chooserFactory,
SelectStrategyFactory selectStrategyFactory) {
super(nThreads, executor, chooserFactory, 0, selectStrategyFactory, RejectedExecutionHandlers.reject());
}
public EpollEventLoopGroup(int nThreads, Executor executor, EventExecutorChooserFactory chooserFactory,
SelectStrategyFactory selectStrategyFactory,
RejectedExecutionHandler rejectedExecutionHandler) {
super(nThreads, executor, chooserFactory, 0, selectStrategyFactory, rejectedExecutionHandler);
}
public EpollEventLoopGroup(int nThreads, Executor executor, EventExecutorChooserFactory chooserFactory,
SelectStrategyFactory selectStrategyFactory,
RejectedExecutionHandler rejectedExecutionHandler,
EventLoopTaskQueueFactory queueFactory) {
super(nThreads, executor, chooserFactory, 0, selectStrategyFactory, rejectedExecutionHandler, queueFactory);
}
/**
* @param nThreads the number of threads that will be used by this instance.
* @param executor the Executor to use, or {@code null} if default one should be used.
* @param chooserFactory the {@link EventExecutorChooserFactory} to use.
* @param selectStrategyFactory the {@link SelectStrategyFactory} to use.
* @param rejectedExecutionHandler the {@link RejectedExecutionHandler} to use.
* @param taskQueueFactory the {@link EventLoopTaskQueueFactory} to use for
* {@link SingleThreadEventLoop#execute(Runnable)},
* or {@code null} if default one should be used.
* @param tailTaskQueueFactory the {@link EventLoopTaskQueueFactory} to use for
* {@link SingleThreadEventLoop#executeAfterEventLoopIteration(Runnable)},
* or {@code null} if default one should be used.
*/
public EpollEventLoopGroup(int nThreads, Executor executor, EventExecutorChooserFactory chooserFactory,
SelectStrategyFactory selectStrategyFactory,
RejectedExecutionHandler rejectedExecutionHandler,
EventLoopTaskQueueFactory taskQueueFactory,
EventLoopTaskQueueFactory tailTaskQueueFactory) {
super(nThreads, executor, chooserFactory, 0, selectStrategyFactory, rejectedExecutionHandler, taskQueueFactory,
tailTaskQueueFactory);
}
/**
* Sets the percentage of the desired amount of time spent for I/O in the child event loops. The default value is
* {@code 50}, which means the event loop will try to spend the same amount of time for I/O as for non-I/O tasks.
*/
public void setIoRatio(int ioRatio) {
for (EventExecutor e: this) {
((EpollEventLoop) e).setIoRatio(ioRatio);
}
}
@Override
protected EventLoop newChild(Executor executor, Object... args) throws Exception {
Integer maxEvents = (Integer) args[0];
SelectStrategyFactory selectStrategyFactory = (SelectStrategyFactory) args[1];
RejectedExecutionHandler rejectedExecutionHandler = (RejectedExecutionHandler) args[2];
EventLoopTaskQueueFactory taskQueueFactory = null;
EventLoopTaskQueueFactory tailTaskQueueFactory = null;
int argsLength = args.length;
if (argsLength > 3) {
taskQueueFactory = (EventLoopTaskQueueFactory) args[3];
}
if (argsLength > 4) {
tailTaskQueueFactory = (EventLoopTaskQueueFactory) args[4];
}
return new EpollEventLoop(this, executor, maxEvents,
selectStrategyFactory.newSelectStrategy(),
rejectedExecutionHandler, taskQueueFactory, tailTaskQueueFactory);
}
}
| netty/netty | transport-classes-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoopGroup.java | Java | apache-2.0 | 8,812 |
/*############################################################################
# Copyright 2016-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
############################################################################*/
/// Implementation of issuer material file parsing utilities.
/*! \file */
#include "epid/file_parser.h"
#include <string.h>
#include "ippmath/ecdsa.h"
#include "ippmath/memory.h"
#include "file_parser-internal.h"
const OctStr16 kEpidVersionCode[kNumEpidVersions] = {{0x01, 0x00},
{0x02, 0x00}};
const OctStr16 kEpidFileTypeCode[kNumFileTypes] = {
{0x00, 0x11}, {0x00, 0x0C}, {0x00, 0x0D}, {0x00, 0x0E},
{0x00, 0x0F}, {0x00, 0x03}, {0x00, 0x0B}, {0x00, 0x13}};
/// Intel(R) EPID 2.0 Group Public Key binary format
typedef struct EpidGroupPubKeyCertificate {
EpidFileHeader header; ///< Intel(R) EPID binary file header
GroupId gid; ///< group ID
G1ElemStr h1; ///< an element in G1
G1ElemStr h2; ///< an element in G1
G2ElemStr w; ///< an element in G2
EcdsaSignature signature; ///< ECDSA Signature on SHA-256 of above values
} EpidGroupPubKeyCertificate;
/// Intel(R) EPID version
static const OctStr16 kEpidVersion = {0x02, 0x00};
/// Verify that certificate contains of EC secp256r1 parameters
EpidStatus EpidVerifyCaCertificate(EpidCaCertificate const* cert) {
// Prime of GF(p) for secp256r1
static const unsigned char secp256r1_p[] = {
// 2^256 -2^224 +2^192 +2^96 -1
0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
// Coefficient of E Curve secp256r1
static const unsigned char secp256r1_a[] = {
0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc};
// Coefficient of E Curve secp256r1
static const unsigned char secp256r1_b[] = {
0x5a, 0xc6, 0x35, 0xd8, 0xaa, 0x3a, 0x93, 0xe7, 0xb3, 0xeb, 0xbd,
0x55, 0x76, 0x98, 0x86, 0xbc, 0x65, 0x1d, 0x06, 0xb0, 0xcc, 0x53,
0xb0, 0xf6, 0x3b, 0xce, 0x3c, 0x3e, 0x27, 0xd2, 0x60, 0x4b};
// X coordinate of Base point G of secp256r1
static const unsigned char secp256r1_gx[] = {
0x6b, 0x17, 0xd1, 0xf2, 0xe1, 0x2c, 0x42, 0x47, 0xf8, 0xbc, 0xe6,
0xe5, 0x63, 0xa4, 0x40, 0xf2, 0x77, 0x03, 0x7d, 0x81, 0x2d, 0xeb,
0x33, 0xa0, 0xf4, 0xa1, 0x39, 0x45, 0xd8, 0x98, 0xc2, 0x96};
// Y coordinate of Base point G of secp256r1
static const unsigned char secp256r1_gy[] = {
0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb,
0x4a, 0x7c, 0x0f, 0x9e, 0x16, 0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31,
0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5};
// Order of base point of secp256r1
static const unsigned char secp256r1_r[] = {
0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17,
0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51,
};
if (!cert) return kEpidBadArgErr;
// Verify that certificate contains of correct file header
if (0 !=
memcmp(&cert->header.epid_version, &kEpidVersion, sizeof(kEpidVersion))) {
return kEpidBadArgErr;
}
if (0 != memcmp(&cert->header.file_type,
&kEpidFileTypeCode[kIssuingCaPubKeyFile],
sizeof(cert->header.file_type))) {
return kEpidBadArgErr;
}
// Verify that certificate contains of EC secp256r1 parameters
if (0 != memcmp(&cert->prime, secp256r1_p, sizeof(secp256r1_p))) {
return kEpidBadArgErr;
}
if (0 != memcmp(&cert->a, secp256r1_a, sizeof(secp256r1_a))) {
return kEpidBadArgErr;
}
if (0 != memcmp(&cert->b, secp256r1_b, sizeof(secp256r1_b))) {
return kEpidBadArgErr;
}
if (0 != memcmp(&cert->x, secp256r1_gx, sizeof(secp256r1_gx))) {
return kEpidBadArgErr;
}
if (0 != memcmp(&cert->y, secp256r1_gy, sizeof(secp256r1_gy))) {
return kEpidBadArgErr;
}
if (0 != memcmp(&cert->r, secp256r1_r, sizeof(secp256r1_r))) {
return kEpidBadArgErr;
}
return kEpidNoErr;
}
EpidStatus EpidParseFileHeader(void const* buf, size_t len,
EpidVersion* epid_version,
EpidFileType* file_type) {
EpidFileHeader* header = (EpidFileHeader*)buf;
if (!buf) return kEpidBadArgErr;
if (len < sizeof(EpidFileHeader)) return kEpidBadArgErr;
if (epid_version) {
if (0 == memcmp((void*)&header->epid_version, &kEpidVersionCode[kEpid1x],
sizeof(header->epid_version))) {
*epid_version = kEpid1x;
} else if (0 == memcmp((void*)&header->epid_version,
&kEpidVersionCode[kEpid2x],
sizeof(header->epid_version))) {
*epid_version = kEpid2x;
} else {
// set default value
*epid_version = kNumEpidVersions;
}
}
if (file_type) {
if (0 == memcmp((void*)&header->file_type,
&kEpidFileTypeCode[kIssuingCaPubKeyFile],
sizeof(header->file_type))) {
*file_type = kIssuingCaPubKeyFile;
} else if (0 == memcmp((void*)&header->file_type,
&kEpidFileTypeCode[kGroupPubKeyFile],
sizeof(header->file_type))) {
*file_type = kGroupPubKeyFile;
} else if (0 == memcmp((void*)&header->file_type,
&kEpidFileTypeCode[kPrivRlFile],
sizeof(header->file_type))) {
*file_type = kPrivRlFile;
} else if (0 == memcmp((void*)&header->file_type,
&kEpidFileTypeCode[kSigRlFile],
sizeof(header->file_type))) {
*file_type = kSigRlFile;
} else if (0 == memcmp((void*)&header->file_type,
&kEpidFileTypeCode[kGroupRlFile],
sizeof(header->file_type))) {
*file_type = kGroupRlFile;
} else if (0 == memcmp((void*)&header->file_type,
&kEpidFileTypeCode[kPrivRlRequestFile],
sizeof(header->file_type))) {
*file_type = kPrivRlRequestFile;
} else if (0 == memcmp((void*)&header->file_type,
&kEpidFileTypeCode[kSigRlRequestFile],
sizeof(header->file_type))) {
*file_type = kSigRlRequestFile;
} else if (0 == memcmp((void*)&header->file_type,
&kEpidFileTypeCode[kGroupRlRequestFile],
sizeof(header->file_type))) {
*file_type = kGroupRlRequestFile;
} else {
// set default value
*file_type = kNumFileTypes;
}
}
return kEpidNoErr;
}
/// Parse a file with a revocation list of any type
static EpidStatus EpidParseRlFile(void const* buf, size_t len,
EpidCaCertificate const* cert, void* rl,
size_t* rl_len, EpidFileType file_type) {
size_t min_rl_file_size = 0;
size_t empty_rl_size = 0;
size_t rl_entry_size = 0;
EpidStatus result = kEpidErr;
EpidFileHeader const* file_header = (EpidFileHeader*)buf;
void const* buf_rl =
(void const*)((unsigned char*)buf + sizeof(EpidFileHeader));
size_t buf_rl_len = 0;
EcdsaSignature const* signature = NULL;
if (!buf) {
return kEpidBadArgErr;
}
if (!cert) {
return kEpidBadArgErr;
}
if (!rl_len) {
return kEpidBadArgErr;
}
switch (file_type) {
case kPrivRlFile:
empty_rl_size = sizeof(PrivRl) - sizeof(((PrivRl*)0)->f[0]);
rl_entry_size = sizeof(((PrivRl*)0)->f[0]);
min_rl_file_size = sizeof(EpidFileHeader) + sizeof(PrivRl) -
sizeof(((PrivRl*)0)->f[0]) + sizeof(EcdsaSignature);
break;
case kSigRlFile:
empty_rl_size = sizeof(SigRl) - sizeof(((SigRl*)0)->bk[0]);
rl_entry_size = sizeof(((SigRl*)0)->bk[0]);
min_rl_file_size = sizeof(EpidFileHeader) + sizeof(SigRl) -
sizeof(((SigRl*)0)->bk[0]) + sizeof(EcdsaSignature);
break;
case kGroupRlFile:
empty_rl_size = sizeof(GroupRl) - sizeof(((GroupRl*)0)->gid[0]);
rl_entry_size = sizeof(((GroupRl*)0)->gid[0]);
min_rl_file_size = sizeof(EpidFileHeader) + sizeof(GroupRl) -
sizeof(((GroupRl*)0)->gid[0]) + sizeof(EcdsaSignature);
break;
default:
return kEpidErr;
}
if (min_rl_file_size > len) {
return kEpidBadArgErr;
}
// Verify that Intel(R) EPID file header in the buffer is correct
if (0 !=
memcmp(&file_header->epid_version, &kEpidVersion, sizeof(kEpidVersion))) {
return kEpidBadArgErr;
}
if (0 != memcmp(&file_header->file_type, &kEpidFileTypeCode[file_type],
sizeof(file_header->file_type))) {
return kEpidBadArgErr;
}
// Verify that CA certificate is correct
result = EpidVerifyCaCertificate(cert);
if (kEpidNoErr != result) return result;
// Verify that RL in file buffer contains of integer number of entries
buf_rl_len = len - sizeof(EpidFileHeader) - sizeof(EcdsaSignature);
if (0 != ((buf_rl_len - empty_rl_size) % rl_entry_size)) {
return kEpidBadArgErr;
}
signature =
(EcdsaSignature*)((unsigned char*)buf + len - sizeof(EcdsaSignature));
// Authenticate signature for buffer
result = EcdsaVerifyBuffer(buf, len - sizeof(EcdsaSignature),
(EcdsaPublicKey*)&cert->pubkey, signature);
if (kEpidSigValid != result) return result;
buf_rl_len = len - sizeof(EpidFileHeader) - sizeof(EcdsaSignature);
// If pointer to output buffer is NULL it should return required size of RL
if (!rl) {
*rl_len = buf_rl_len;
return kEpidNoErr;
}
if (*rl_len < buf_rl_len) {
return kEpidBadArgErr;
}
*rl_len = buf_rl_len;
// Copy revocation list from file buffer to output
// Memory copy is used to copy a revocation list of variable length
if (0 != memcpy_S(rl, *rl_len, buf_rl, buf_rl_len)) {
return kEpidBadArgErr;
}
return kEpidNoErr;
}
EpidStatus EpidParseGroupPubKeyFile(void const* buf, size_t len,
EpidCaCertificate const* cert,
GroupPubKey* pubkey) {
EpidStatus result;
EpidGroupPubKeyCertificate* buf_pubkey = (EpidGroupPubKeyCertificate*)buf;
if (!buf) {
return kEpidBadArgErr;
}
if (!cert) {
return kEpidBadArgErr;
}
if (!pubkey) {
return kEpidBadArgErr;
}
if (len == 0 || len % sizeof(EpidGroupPubKeyCertificate) != 0) {
return kEpidBadArgErr;
}
// Verify that Intel(R) EPID file header in the buffer is correct
if (0 != memcmp(&buf_pubkey->header.epid_version, &kEpidVersion,
sizeof(kEpidVersion))) {
return kEpidBadArgErr;
}
if (0 != memcmp(&buf_pubkey->header.file_type,
&kEpidFileTypeCode[kGroupPubKeyFile],
sizeof(buf_pubkey->header.file_type))) {
return kEpidBadArgErr;
}
// Verify that CA certificate is correct
result = EpidVerifyCaCertificate(cert);
if (kEpidNoErr != result) return result;
// Authenticate signature for buffer
result = EcdsaVerifyBuffer(
buf_pubkey, sizeof(EpidGroupPubKeyCertificate) - sizeof(EcdsaSignature),
(EcdsaPublicKey*)&cert->pubkey, &buf_pubkey->signature);
if (kEpidSigValid != result) return result;
// Copy public from the buffer to output
pubkey->gid = buf_pubkey->gid;
pubkey->h1 = buf_pubkey->h1;
pubkey->h2 = buf_pubkey->h2;
pubkey->w = buf_pubkey->w;
return kEpidNoErr;
}
EpidStatus EpidParsePrivRlFile(void const* buf, size_t len,
EpidCaCertificate const* cert, PrivRl* rl,
size_t* rl_len) {
return EpidParseRlFile(buf, len, cert, rl, rl_len, kPrivRlFile);
}
EpidStatus EpidParseSigRlFile(void const* buf, size_t len,
EpidCaCertificate const* cert, SigRl* rl,
size_t* rl_len) {
return EpidParseRlFile(buf, len, cert, rl, rl_len, kSigRlFile);
}
EpidStatus EpidParseGroupRlFile(void const* buf, size_t len,
EpidCaCertificate const* cert, GroupRl* rl,
size_t* rl_len) {
return EpidParseRlFile(buf, len, cert, rl, rl_len, kGroupRlFile);
}
| Intel-EPID-SDK/epid-sdk | epid/util/src/ipp-impl/file_parser.c | C | apache-2.0 | 13,105 |
/*
* Copyright © 2009 HotPads (admin@hotpads.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.datarouter.virtualnode.redundant.mixin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.datarouter.storage.node.Node;
public class RedundantQueueNodeTool{
private static final Logger logger = LoggerFactory.getLogger(RedundantQueueNodeTool.class);
private static final String SQS_MSG = "The input receipt handle";
private static final String SQS_KEYWORD = "is invalid";
private static final String GCP_PUBSUB_MSG = "io.grpc.StatusRuntimeException:";
private static final String GCP_PUBSUB_KEYWORD = "ack ID";
public static void swallowIfNotFound(RuntimeException exception, Node<?,?,?> node){
if(exception.getMessage().startsWith(SQS_MSG) && exception.getMessage().contains(SQS_KEYWORD) || exception
.getMessage().startsWith(GCP_PUBSUB_MSG) && exception.getMessage().contains(GCP_PUBSUB_KEYWORD)){
logger.info("not found in node={}", node, exception);
return;
}
throw exception;
}
}
| hotpads/datarouter | datarouter-virtual-node/src/main/java/io/datarouter/virtualnode/redundant/mixin/RedundantQueueNodeTool.java | Java | apache-2.0 | 1,555 |
import { expect } from 'chai';
import * as Rx from '../../src/internal/Rx';
import { hot, cold, expectObservable, expectSubscriptions } from '../helpers/marble-testing';
declare function asDiagram(arg: string): Function;
const Observable = Rx.Observable;
/** @test {max} */
describe('Observable.prototype.max', () => {
asDiagram('max')('should find the max of values of an observable', () => {
const e1 = hot('--a--b--c--|', { a: 42, b: -1, c: 3 });
const subs = '^ !';
const expected = '-----------(x|)';
expectObservable((<any>e1).max()).toBe(expected, { x: 42 });
expectSubscriptions(e1.subscriptions).toBe(subs);
});
it('should be never when source is never', () => {
const e1 = cold('-');
const e1subs = '^';
const expected = '-';
expectObservable((<any>e1).max()).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should be zero when source is empty', () => {
const e1 = cold('|');
const e1subs = '(^!)';
const expected = '|';
expectObservable((<any>e1).max()).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should be never when source doesn\'t complete', () => {
const e1 = hot('--x--^--y--');
const e1subs = '^ ';
const expected = '------';
expectObservable((<any>e1).max()).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should be completes when source doesn\'t have values', () => {
const e1 = hot('-x-^---|');
const e1subs = '^ !';
const expected = '----|';
expectObservable((<any>e1).max()).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should max the unique value of an observable', () => {
const e1 = hot('-x-^--y--|', { y: 42 });
const e1subs = '^ !';
const expected = '------(w|)';
expectObservable((<any>e1).max()).toBe(expected, { w: 42 });
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should max the values of an ongoing hot observable', () => {
const e1 = hot('--a-^-b--c--d--|', { a: 42, b: -1, c: 0, d: 666 });
const subs = '^ !';
const expected = '-----------(x|)';
expectObservable((<any>e1).max()).toBe(expected, { x: 666 });
expectSubscriptions(e1.subscriptions).toBe(subs);
});
it('should allow unsubscribing explicitly and early', () => {
const e1 = hot('--a--b--c--|', { a: 42, b: -1, c: 0 });
const unsub = ' ! ';
const subs = '^ ! ';
const expected = '------- ';
expectObservable((<any>e1).max(), unsub).toBe(expected, { x: 42 });
expectSubscriptions(e1.subscriptions).toBe(subs);
});
it('should not break unsubscription chains when result is unsubscribed explicitly', () => {
const source = hot('--a--b--c--|', { a: 42, b: -1, c: 0 });
const subs = '^ ! ';
const expected = '------- ';
const unsub = ' ! ';
const result = (<any>source)
.mergeMap((x: string) => Observable.of(x))
.max()
.mergeMap((x: string) => Observable.of(x));
expectObservable(result, unsub).toBe(expected, { x: 42 });
expectSubscriptions(source.subscriptions).toBe(subs);
});
it('should max a range() source observable', (done: MochaDone) => {
(<any>Rx.Observable.range(1, 10000)).max().subscribe(
(value: number) => {
expect(value).to.equal(10000);
}, (x) => {
done(new Error('should not be called'));
}, () => {
done();
});
});
it('should max a range().skip(1) source observable', (done: MochaDone) => {
(<any>Rx.Observable.range(1, 10)).skip(1).max().subscribe(
(value: number) => {
expect(value).to.equal(10);
}, (x) => {
done(new Error('should not be called'));
}, () => {
done();
});
});
it('should max a range().take(1) source observable', (done: MochaDone) => {
(<any>Rx.Observable.range(1, 10)).take(1).max().subscribe(
(value: number) => {
expect(value).to.equal(1);
}, (x) => {
done(new Error('should not be called'));
}, () => {
done();
});
});
it('should work with error', () => {
const e1 = hot('-x-^--y--z--#', { x: 1, y: 2, z: 3 }, 'too bad');
const e1subs = '^ !';
const expected = '---------#';
expectObservable((<any>e1).max()).toBe(expected, null, 'too bad');
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should work with throw', () => {
const e1 = cold('#');
const e1subs = '(^!)';
const expected = '#';
expectObservable((<any>e1).max()).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should handle a constant predicate on an empty hot observable', () => {
const e1 = hot('-x-^---|');
const e1subs = '^ !';
const expected = '----|';
const predicate = function (x, y) {
return 42;
};
expectObservable((<any>e1).max(predicate)).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should handle a constant predicate on an never hot observable', () => {
const e1 = hot('-x-^----');
const e1subs = '^ ';
const expected = '-----';
const predicate = function (x, y) {
return 42;
};
expectObservable((<any>e1).max(predicate)).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should handle a constant predicate on a simple hot observable', () => {
const e1 = hot('-x-^-a-|', { a: 1 });
const e1subs = '^ !';
const expected = '----(w|)';
const predicate = function () {
return 42;
};
expectObservable((<any>e1).max(predicate)).toBe(expected, { w: 1 });
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should handle a reverse predicate on observable with many values', () => {
const e1 = hot('-a-^-b--c--d-|', { a: 42, b: -1, c: 0, d: 666 });
const e1subs = '^ !';
const expected = '----------(w|)';
const predicate = function (x, y) {
return x > y ? -1 : 1;
};
expectObservable((<any>e1).max(predicate)).toBe(expected, { w: -1 });
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should handle a predicate for string on observable with many values', () => {
const e1 = hot('-a-^-b--c--d-|');
const e1subs = '^ !';
const expected = '----------(w|)';
const predicate = function (x, y) {
return x > y ? -1 : 1;
};
expectObservable((<any>e1).max(predicate)).toBe(expected, { w: 'b' });
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should handle a constant predicate on observable that throws', () => {
const e1 = hot('-1-^---#');
const e1subs = '^ !';
const expected = '----#';
const predicate = () => {
return 42;
};
expectObservable((<any>e1).max(predicate)).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should handle a predicate that throws, on observable with many values', () => {
const e1 = hot('-1-^-2--3--|');
const e1subs = '^ ! ';
const expected = '-----# ';
const predicate = function (x, y) {
if (y === '3') {
throw 'error';
}
return x > y ? x : y;
};
expectObservable((<any>e1).max(predicate)).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
| IgorMinar/RxJS | spec/operators/max-spec.ts | TypeScript | apache-2.0 | 7,599 |
package org.grobid.core.utilities.counters;
import java.io.IOException;
public interface CntManagerRepresentation {
String getRepresentation(CntManager cntManager) throws IOException;
}
| kermitt2/grobid | grobid-core/src/main/java/org/grobid/core/utilities/counters/CntManagerRepresentation.java | Java | apache-2.0 | 192 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_79) on Mon Aug 17 17:10:58 IST 2015 -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Uses of Class org.apache.solr.client.solrj.request.schema.SchemaRequest.DynamicFields (Solr 5.3.0 API)</title>
<meta name="date" content="2015-08-17">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.client.solrj.request.schema.SchemaRequest.DynamicFields (Solr 5.3.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../org/apache/solr/client/solrj/request/schema/SchemaRequest.DynamicFields.html" title="class in org.apache.solr.client.solrj.request.schema">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?org/apache/solr/client/solrj/request/schema/class-use/SchemaRequest.DynamicFields.html" target="_top">Frames</a></li>
<li><a href="SchemaRequest.DynamicFields.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.solr.client.solrj.request.schema.SchemaRequest.DynamicFields" class="title">Uses of Class<br>org.apache.solr.client.solrj.request.schema.SchemaRequest.DynamicFields</h2>
</div>
<div class="classUseContainer">No usage of org.apache.solr.client.solrj.request.schema.SchemaRequest.DynamicFields</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../org/apache/solr/client/solrj/request/schema/SchemaRequest.DynamicFields.html" title="class in org.apache.solr.client.solrj.request.schema">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?org/apache/solr/client/solrj/request/schema/class-use/SchemaRequest.DynamicFields.html" target="_top">Frames</a></li>
<li><a href="SchemaRequest.DynamicFields.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2015 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| changwu/mqa | solr-5.3.0/docs/solr-solrj/org/apache/solr/client/solrj/request/schema/class-use/SchemaRequest.DynamicFields.html | HTML | apache-2.0 | 5,257 |
# Copyright 2012 OpenStack Foundation
# 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.
import netaddr
import testtools
from tempest.api.compute import base
from tempest.common.utils import data_utils
from tempest.common.utils.linux import remote_client
from tempest.common import waiters
from tempest import config
from tempest import test
CONF = config.CONF
class ServersTestJSON(base.BaseV2ComputeTest):
disk_config = 'AUTO'
@classmethod
def setup_credentials(cls):
cls.prepare_instance_network()
super(ServersTestJSON, cls).setup_credentials()
@classmethod
def setup_clients(cls):
super(ServersTestJSON, cls).setup_clients()
cls.client = cls.servers_client
cls.networks_client = cls.os.networks_client
cls.subnets_client = cls.os.subnets_client
@classmethod
def resource_setup(cls):
cls.set_validation_resources()
super(ServersTestJSON, cls).resource_setup()
cls.meta = {'hello': 'world'}
cls.accessIPv4 = '1.1.1.1'
cls.accessIPv6 = '0000:0000:0000:0000:0000:babe:220.12.22.2'
cls.name = data_utils.rand_name(cls.__name__ + '-server')
cls.password = data_utils.rand_password()
disk_config = cls.disk_config
cls.server_initial = cls.create_test_server(
validatable=True,
wait_until='ACTIVE',
name=cls.name,
metadata=cls.meta,
accessIPv4=cls.accessIPv4,
accessIPv6=cls.accessIPv6,
disk_config=disk_config,
adminPass=cls.password)
cls.server = (cls.client.show_server(cls.server_initial['id'])
['server'])
def _create_net_subnet_ret_net_from_cidr(self, cidr):
name_net = data_utils.rand_name(self.__class__.__name__)
net = self.networks_client.create_network(name=name_net)
self.addCleanup(self.networks_client.delete_network,
net['network']['id'])
subnet = self.subnets_client.create_subnet(
network_id=net['network']['id'],
cidr=cidr,
ip_version=4)
self.addCleanup(self.subnets_client.delete_subnet,
subnet['subnet']['id'])
return net
@test.attr(type='smoke')
@test.idempotent_id('5de47127-9977-400a-936f-abcfbec1218f')
def test_verify_server_details(self):
# Verify the specified server attributes are set correctly
self.assertEqual(self.accessIPv4, self.server['accessIPv4'])
# NOTE(maurosr): See http://tools.ietf.org/html/rfc5952 (section 4)
# Here we compare directly with the canonicalized format.
self.assertEqual(self.server['accessIPv6'],
str(netaddr.IPAddress(self.accessIPv6)))
self.assertEqual(self.name, self.server['name'])
self.assertEqual(self.image_ref, self.server['image']['id'])
self.assertEqual(self.flavor_ref, self.server['flavor']['id'])
self.assertEqual(self.meta, self.server['metadata'])
@test.attr(type='smoke')
@test.idempotent_id('9a438d88-10c6-4bcd-8b5b-5b6e25e1346f')
def test_list_servers(self):
# The created server should be in the list of all servers
body = self.client.list_servers()
servers = body['servers']
found = any([i for i in servers if i['id'] == self.server['id']])
self.assertTrue(found)
@test.idempotent_id('585e934c-448e-43c4-acbf-d06a9b899997')
def test_list_servers_with_detail(self):
# The created server should be in the detailed list of all servers
body = self.client.list_servers(detail=True)
servers = body['servers']
found = any([i for i in servers if i['id'] == self.server['id']])
self.assertTrue(found)
@test.idempotent_id('cbc0f52f-05aa-492b-bdc1-84b575ca294b')
@testtools.skipUnless(CONF.validation.run_validation,
'Instance validation tests are disabled.')
def test_verify_created_server_vcpus(self):
# Verify that the number of vcpus reported by the instance matches
# the amount stated by the flavor
flavor = self.flavors_client.show_flavor(self.flavor_ref)['flavor']
linux_client = remote_client.RemoteClient(
self.get_server_ip(self.server),
self.ssh_user,
self.password,
self.validation_resources['keypair']['private_key'],
server=self.server,
servers_client=self.client)
self.assertEqual(flavor['vcpus'], linux_client.get_number_of_vcpus())
@test.idempotent_id('ac1ad47f-984b-4441-9274-c9079b7a0666')
@testtools.skipUnless(CONF.validation.run_validation,
'Instance validation tests are disabled.')
def test_host_name_is_same_as_server_name(self):
# Verify the instance host name is the same as the server name
linux_client = remote_client.RemoteClient(
self.get_server_ip(self.server),
self.ssh_user,
self.password,
self.validation_resources['keypair']['private_key'],
server=self.server,
servers_client=self.client)
hostname = linux_client.get_hostname()
msg = ('Failed while verifying servername equals hostname. Expected '
'hostname "%s" but got "%s".' % (self.name, hostname))
self.assertEqual(self.name.lower(), hostname, msg)
@test.idempotent_id('ed20d3fb-9d1f-4329-b160-543fbd5d9811')
@testtools.skipUnless(
test.is_scheduler_filter_enabled("ServerGroupAffinityFilter"),
'ServerGroupAffinityFilter is not available.')
def test_create_server_with_scheduler_hint_group(self):
# Create a server with the scheduler hint "group".
group_id = self.create_test_server_group()['id']
hints = {'group': group_id}
server = self.create_test_server(scheduler_hints=hints,
wait_until='ACTIVE')
# Check a server is in the group
server_group = (self.server_groups_client.show_server_group(group_id)
['server_group'])
self.assertIn(server['id'], server_group['members'])
@test.idempotent_id('0578d144-ed74-43f8-8e57-ab10dbf9b3c2')
@testtools.skipUnless(CONF.service_available.neutron,
'Neutron service must be available.')
def test_verify_multiple_nics_order(self):
# Verify that the networks order given at the server creation is
# preserved within the server.
net1 = self._create_net_subnet_ret_net_from_cidr('19.80.0.0/24')
net2 = self._create_net_subnet_ret_net_from_cidr('19.86.0.0/24')
networks = [{'uuid': net1['network']['id']},
{'uuid': net2['network']['id']}]
server_multi_nics = self.create_test_server(
networks=networks, wait_until='ACTIVE')
# Cleanup server; this is needed in the test case because with the LIFO
# nature of the cleanups, if we don't delete the server first, the port
# will still be part of the subnet and we'll get a 409 from Neutron
# when trying to delete the subnet. The tear down in the base class
# will try to delete the server and get a 404 but it's ignored so
# we're OK.
def cleanup_server():
self.client.delete_server(server_multi_nics['id'])
waiters.wait_for_server_termination(self.client,
server_multi_nics['id'])
self.addCleanup(cleanup_server)
addresses = (self.client.list_addresses(server_multi_nics['id'])
['addresses'])
# We can't predict the ip addresses assigned to the server on networks.
# Sometimes the assigned addresses are ['19.80.0.2', '19.86.0.2'], at
# other times ['19.80.0.3', '19.86.0.3']. So we check if the first
# address is in first network, similarly second address is in second
# network.
addr = [addresses[net1['network']['name']][0]['addr'],
addresses[net2['network']['name']][0]['addr']]
networks = [netaddr.IPNetwork('19.80.0.0/24'),
netaddr.IPNetwork('19.86.0.0/24')]
for address, network in zip(addr, networks):
self.assertIn(address, network)
@test.idempotent_id('1678d144-ed74-43f8-8e57-ab10dbf9b3c2')
@testtools.skipUnless(CONF.service_available.neutron,
'Neutron service must be available.')
def test_verify_duplicate_network_nics(self):
# Verify that server creation does not fail when more than one nic
# is created on the same network.
net1 = self._create_net_subnet_ret_net_from_cidr('19.80.0.0/24')
net2 = self._create_net_subnet_ret_net_from_cidr('19.86.0.0/24')
networks = [{'uuid': net1['network']['id']},
{'uuid': net2['network']['id']},
{'uuid': net1['network']['id']}]
server_multi_nics = self.create_test_server(
networks=networks, wait_until='ACTIVE')
def cleanup_server():
self.client.delete_server(server_multi_nics['id'])
waiters.wait_for_server_termination(self.client,
server_multi_nics['id'])
self.addCleanup(cleanup_server)
addresses = (self.client.list_addresses(server_multi_nics['id'])
['addresses'])
addr = [addresses[net1['network']['name']][0]['addr'],
addresses[net2['network']['name']][0]['addr'],
addresses[net1['network']['name']][1]['addr']]
networks = [netaddr.IPNetwork('19.80.0.0/24'),
netaddr.IPNetwork('19.86.0.0/24'),
netaddr.IPNetwork('19.80.0.0/24')]
for address, network in zip(addr, networks):
self.assertIn(address, network)
class ServersWithSpecificFlavorTestJSON(base.BaseV2ComputeAdminTest):
disk_config = 'AUTO'
@classmethod
def setup_credentials(cls):
cls.prepare_instance_network()
super(ServersWithSpecificFlavorTestJSON, cls).setup_credentials()
@classmethod
def setup_clients(cls):
super(ServersWithSpecificFlavorTestJSON, cls).setup_clients()
cls.flavor_client = cls.os_adm.flavors_client
cls.client = cls.servers_client
@classmethod
def resource_setup(cls):
cls.set_validation_resources()
super(ServersWithSpecificFlavorTestJSON, cls).resource_setup()
@test.idempotent_id('b3c7bcfc-bb5b-4e22-b517-c7f686b802ca')
@testtools.skipUnless(CONF.validation.run_validation,
'Instance validation tests are disabled.')
def test_verify_created_server_ephemeral_disk(self):
# Verify that the ephemeral disk is created when creating server
flavor_base = self.flavors_client.show_flavor(
self.flavor_ref)['flavor']
def create_flavor_with_ephemeral(ephem_disk):
flavor_with_eph_disk_id = data_utils.rand_int_id(start=1000)
ram = flavor_base['ram']
vcpus = flavor_base['vcpus']
disk = flavor_base['disk']
if ephem_disk > 0:
# Create a flavor with ephemeral disk
flavor_name = data_utils.rand_name('eph_flavor')
flavor = self.flavor_client.create_flavor(
name=flavor_name, ram=ram, vcpus=vcpus, disk=disk,
id=flavor_with_eph_disk_id, ephemeral=ephem_disk)['flavor']
else:
# Create a flavor without ephemeral disk
flavor_name = data_utils.rand_name('no_eph_flavor')
flavor = self.flavor_client.create_flavor(
name=flavor_name, ram=ram, vcpus=vcpus, disk=disk,
id=flavor_with_eph_disk_id)['flavor']
self.addCleanup(flavor_clean_up, flavor['id'])
return flavor['id']
def flavor_clean_up(flavor_id):
self.flavor_client.delete_flavor(flavor_id)
self.flavor_client.wait_for_resource_deletion(flavor_id)
flavor_with_eph_disk_id = create_flavor_with_ephemeral(ephem_disk=1)
flavor_no_eph_disk_id = create_flavor_with_ephemeral(ephem_disk=0)
admin_pass = self.image_ssh_password
server_no_eph_disk = self.create_test_server(
validatable=True,
wait_until='ACTIVE',
adminPass=admin_pass,
flavor=flavor_no_eph_disk_id)
# Get partition number of server without ephemeral disk.
server_no_eph_disk = self.client.show_server(
server_no_eph_disk['id'])['server']
linux_client = remote_client.RemoteClient(
self.get_server_ip(server_no_eph_disk),
self.ssh_user,
admin_pass,
self.validation_resources['keypair']['private_key'],
server=server_no_eph_disk,
servers_client=self.client)
partition_num = len(linux_client.get_partitions().split('\n'))
# Explicit server deletion necessary for Juno compatibility
self.client.delete_server(server_no_eph_disk['id'])
server_with_eph_disk = self.create_test_server(
validatable=True,
wait_until='ACTIVE',
adminPass=admin_pass,
flavor=flavor_with_eph_disk_id)
server_with_eph_disk = self.client.show_server(
server_with_eph_disk['id'])['server']
linux_client = remote_client.RemoteClient(
self.get_server_ip(server_with_eph_disk),
self.ssh_user,
admin_pass,
self.validation_resources['keypair']['private_key'],
server=server_with_eph_disk,
servers_client=self.client)
partition_num_emph = len(linux_client.get_partitions().split('\n'))
self.assertEqual(partition_num + 1, partition_num_emph)
class ServersTestManualDisk(ServersTestJSON):
disk_config = 'MANUAL'
@classmethod
def skip_checks(cls):
super(ServersTestManualDisk, cls).skip_checks()
if not CONF.compute_feature_enabled.disk_config:
msg = "DiskConfig extension not enabled."
raise cls.skipException(msg)
| Tesora/tesora-tempest | tempest/api/compute/servers/test_create_server.py | Python | apache-2.0 | 14,903 |
/*
* SPDX-FileCopyrightText: 2017-2021 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef _ESP_BLE_MESH_BLE_API_H_
#define _ESP_BLE_MESH_BLE_API_H_
#include "esp_ble_mesh_defs.h"
#ifdef __cplusplus
extern "C" {
#endif
/** This enum value is the event of BLE operations */
typedef enum {
ESP_BLE_MESH_START_BLE_ADVERTISING_COMP_EVT, /*!< Start BLE advertising completion event */
ESP_BLE_MESH_STOP_BLE_ADVERTISING_COMP_EVT, /*!< Stop BLE advertising completion event */
ESP_BLE_MESH_START_BLE_SCANNING_COMP_EVT, /*!< Start BLE scanning completion event */
ESP_BLE_MESH_STOP_BLE_SCANNING_COMP_EVT, /*!< Stop BLE scanning completion event */
ESP_BLE_MESH_SCAN_BLE_ADVERTISING_PKT_EVT, /*!< Scanning BLE advertising packets event */
ESP_BLE_MESH_BLE_EVT_MAX,
} esp_ble_mesh_ble_cb_event_t;
/** BLE operation callback parameters */
typedef union {
/**
* @brief ESP_BLE_MESH_START_BLE_ADVERTISING_COMP_EVT
*/
struct {
int err_code; /*!< Indicate the result of starting BLE advertising */
uint8_t index; /*!< Index of the BLE advertising */
} start_ble_advertising_comp; /*!< Event parameters of ESP_BLE_MESH_START_BLE_ADVERTISING_COMP_EVT */
/**
* @brief ESP_BLE_MESH_STOP_BLE_ADVERTISING_COMP_EVT
*/
struct {
int err_code; /*!< Indicate the result of stopping BLE advertising */
uint8_t index; /*!< Index of the BLE advertising */
} stop_ble_advertising_comp; /*!< Event parameters of ESP_BLE_MESH_STOP_BLE_ADVERTISING_COMP_EVT */
/**
* @brief ESP_BLE_MESH_START_BLE_SCANNING_COMP_EVT
*/
struct {
int err_code; /*!< Indicate the result of starting BLE scanning */
} start_ble_scan_comp; /*!< Event parameters of ESP_BLE_MESH_START_BLE_SCANNING_COMP_EVT */
/**
* @brief ESP_BLE_MESH_STOP_BLE_SCANNING_COMP_EVT
*/
struct {
int err_code; /*!< Indicate the result of stopping BLE scanning */
} stop_ble_scan_comp; /*!< Event parameters of ESP_BLE_MESH_STOP_BLE_SCANNING_COMP_EVT */
/**
* @brief ESP_BLE_MESH_SCAN_BLE_ADVERTISING_PKT_EVT
*/
struct {
uint8_t addr[6]; /*!< Device address */
uint8_t addr_type; /*!< Device address type */
uint8_t adv_type; /*!< Advertising data type */
uint8_t *data; /*!< Advertising data */
uint16_t length; /*!< Advertising data length */
int8_t rssi; /*!< RSSI of the advertising packet */
} scan_ble_adv_pkt; /*!< Event parameters of ESP_BLE_MESH_SCAN_BLE_ADVERTISING_PKT_EVT */
} esp_ble_mesh_ble_cb_param_t;
/**
* @brief BLE scanning callback function type
*
* @param event: BLE scanning callback event type
* @param param: BLE scanning callback parameter
*/
typedef void (* esp_ble_mesh_ble_cb_t)(esp_ble_mesh_ble_cb_event_t event,
esp_ble_mesh_ble_cb_param_t *param);
/**
* @brief Register BLE scanning callback.
*
* @param[in] callback: Pointer to the BLE scaning callback function.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_register_ble_callback(esp_ble_mesh_ble_cb_t callback);
/** Count for sending BLE advertising packet infinitely */
#define ESP_BLE_MESH_BLE_ADV_INFINITE 0xFFFF
/*!< This enum value is the priority of BLE advertising packet */
typedef enum {
ESP_BLE_MESH_BLE_ADV_PRIO_LOW,
ESP_BLE_MESH_BLE_ADV_PRIO_HIGH,
} esp_ble_mesh_ble_adv_priority_t;
/** Context of BLE advertising parameters. */
typedef struct {
uint16_t interval; /*!< BLE advertising interval */
uint8_t adv_type; /*!< BLE advertising type */
uint8_t own_addr_type; /*!< Own address type */
uint8_t peer_addr_type; /*!< Peer address type */
uint8_t peer_addr[BD_ADDR_LEN]; /*!< Peer address */
uint16_t duration; /*!< Duration is milliseconds */
uint16_t period; /*!< Period in milliseconds */
uint16_t count; /*!< Number of advertising duration */
uint8_t priority:2; /*!< Priority of BLE advertising packet */
} esp_ble_mesh_ble_adv_param_t;
/** Context of BLE advertising data. */
typedef struct {
uint8_t adv_data_len; /*!< Advertising data length */
uint8_t adv_data[31]; /*!< Advertising data */
uint8_t scan_rsp_data_len; /*!< Scan response data length */
uint8_t scan_rsp_data[31]; /*!< Scan response data */
} esp_ble_mesh_ble_adv_data_t;
/**
* @brief This function is called to start BLE advertising with the corresponding data
* and parameters while BLE Mesh is working at the same time.
*
* @note 1. When this function is called, the BLE advertising packet will be posted to
* the BLE mesh adv queue in the mesh stack and waited to be sent.
* 2. In the BLE advertising parameters, the "duration" means the time used for
* sending the BLE advertising packet each time, it shall not be smaller than the
* advertising interval. When the packet is sent successfully, it will be posted
* to the adv queue again after the "period" time if the "count" is bigger than 0.
* The "count" means how many durations the packet will be sent after it is sent
* successfully for the first time. And if the "count" is set to 0xFFFF, which
* means the packet will be sent infinitely.
* 3. The "priority" means the priority of BLE advertising packet compared with
* BLE Mesh packets. Currently two options (i.e. low/high) are provided. If the
* "priority" is high, the BLE advertising packet will be posted to the front of
* adv queue. Otherwise it will be posted to the back of adv queue.
*
* @param[in] param: Pointer to the BLE advertising parameters
* @param[in] data: Pointer to the BLE advertising data and scan response data
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_start_ble_advertising(const esp_ble_mesh_ble_adv_param_t *param,
const esp_ble_mesh_ble_adv_data_t *data);
/**
* @brief This function is called to stop BLE advertising with the corresponding index.
*
* @param[in] index: Index of BLE advertising
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_stop_ble_advertising(uint8_t index);
/** Context of BLE scanning parameters. */
typedef struct {
uint32_t duration; /*!< Duration used to scan normal BLE advertising packets */
} esp_ble_mesh_ble_scan_param_t;
/**
* @brief This function is called to start scanning normal BLE advertising packets
* and notifying the packets to the application layer.
*
* @param[in] param: Pointer to the BLE scanning parameters
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_start_ble_scanning(esp_ble_mesh_ble_scan_param_t *param);
/**
* @brief This function is called to stop notifying normal BLE advertising packets
* to the application layer.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_stop_ble_scanning(void);
#ifdef __cplusplus
}
#endif
#endif /* _ESP_BLE_MESH_BLE_API_H_ */
| espressif/esp-idf | components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_ble_api.h | C | apache-2.0 | 7,561 |
// Copyright 2018 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package storetest provides the utility functions of config store for
// testing. Shouldn't be imported outside of the test.
package storetest
import (
"fmt"
"strings"
"sync"
multierror "github.com/hashicorp/go-multierror"
"istio.io/istio/mixer/pkg/config/store"
)
// Memstore is an on-memory store backend. Used only for testing.
type Memstore struct {
mu sync.Mutex
data map[store.Key]*store.BackEndResource
wch chan store.BackendEvent
donec chan struct{}
}
// NewMemstore creates a new Memstore instance.
func NewMemstore() *Memstore {
return &Memstore{data: map[store.Key]*store.BackEndResource{}, donec: make(chan struct{})}
}
// Stop implements store.Backend interface.
func (m *Memstore) Stop() {
close(m.donec)
}
// Init implements store.Backend interface.
func (m *Memstore) Init(kinds []string) error {
return nil
}
// Watch implements store.Backend interface.
func (m *Memstore) Watch() (<-chan store.BackendEvent, error) {
// Watch is not supported in the memstore, but sometimes it needs to be invoked.
c := make(chan store.BackendEvent)
go func() {
<-m.donec
close(c)
}()
m.mu.Lock()
defer m.mu.Unlock()
m.wch = c
return c, nil
}
// Get implements store.Backend interface.
func (m *Memstore) Get(key store.Key) (*store.BackEndResource, error) {
m.mu.Lock()
defer m.mu.Unlock()
r, ok := m.data[key]
if !ok {
return nil, store.ErrNotFound
}
return r, nil
}
// List implements store.Backend interface.
func (m *Memstore) List() map[store.Key]*store.BackEndResource {
return m.data
}
// Put adds a new resource to the memstore.
func (m *Memstore) Put(r *store.BackEndResource) {
m.mu.Lock()
defer m.mu.Unlock()
m.data[r.Key()] = r
if m.wch != nil {
m.wch <- store.BackendEvent{Type: store.Update, Key: r.Key(), Value: r}
}
}
// Delete removes a resource for the specified key from the memstore.
func (m *Memstore) Delete(k store.Key) {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.data, k)
if m.wch != nil {
m.wch <- store.BackendEvent{Type: store.Delete, Key: k}
}
}
// SetupStoreForTest creates an on-memory store backend, initializes its
// data with the specified specs, and returns a new store with the backend.
// Note that this store can't change, Watch does not emit any events.
func SetupStoreForTest(data ...string) (store.Store, error) {
m := &Memstore{data: map[store.Key]*store.BackEndResource{}, donec: make(chan struct{})}
var errs error
for i, d := range data {
for j, chunk := range strings.Split(d, "\n---\n") {
chunk = strings.TrimSpace(chunk)
if len(chunk) == 0 {
continue
}
r, err := store.ParseChunk([]byte(chunk))
if err != nil {
errs = multierror.Append(errs, fmt.Errorf("failed to parse at %d/%d: %v", i, j, err))
continue
}
if r == nil {
continue
}
m.data[r.Key()] = r
}
}
if errs != nil {
return nil, errs
}
return store.WithBackend(m), nil
}
| frankbu/istio | mixer/pkg/config/storetest/storetest.go | GO | apache-2.0 | 3,492 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_101) on Sun Jan 29 09:58:09 CET 2017 -->
<title>Uses of Class com.mxgraph.util.mxLine (mxGraph 3.7.0.1 API Specification)</title>
<meta name="date" content="2017-01-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.mxgraph.util.mxLine (mxGraph 3.7.0.1 API Specification)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../com/mxgraph/util/mxLine.html" title="class in com.mxgraph.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><p><b>mxGraph 3.7.0.1</b></p></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/mxgraph/util/class-use/mxLine.html" target="_top">Frames</a></li>
<li><a href="mxLine.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.mxgraph.util.mxLine" class="title">Uses of Class<br>com.mxgraph.util.mxLine</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../com/mxgraph/util/mxLine.html" title="class in com.mxgraph.util">mxLine</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.mxgraph.shape">com.mxgraph.shape</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.mxgraph.util">com.mxgraph.util</a></td>
<td class="colLast">
<div class="block">This package provides utility classes such as mxConstants, mxUtils, mxPoint
and mxRectangle as well as all classes for custom events and the undo
history.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.mxgraph.shape">
<!-- -->
</a>
<h3>Uses of <a href="../../../../com/mxgraph/util/mxLine.html" title="class in com.mxgraph.util">mxLine</a> in <a href="../../../../com/mxgraph/shape/package-summary.html">com.mxgraph.shape</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../com/mxgraph/shape/package-summary.html">com.mxgraph.shape</a> declared as <a href="../../../../com/mxgraph/util/mxLine.html" title="class in com.mxgraph.util">mxLine</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../com/mxgraph/util/mxLine.html" title="class in com.mxgraph.util">mxLine</a></code></td>
<td class="colLast"><span class="typeNameLabel">mxCurveLabelShape.LabelGlyphCache.</span><code><span class="memberNameLink"><a href="../../../../com/mxgraph/shape/mxCurveLabelShape.LabelGlyphCache.html#glyphGeometry">glyphGeometry</a></span></code>
<div class="block">A line parallel to the curve segment at which the element is to be
drawn</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../com/mxgraph/shape/package-summary.html">com.mxgraph.shape</a> that return <a href="../../../../com/mxgraph/util/mxLine.html" title="class in com.mxgraph.util">mxLine</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected <a href="../../../../com/mxgraph/util/mxLine.html" title="class in com.mxgraph.util">mxLine</a></code></td>
<td class="colLast"><span class="typeNameLabel">mxConnectorShape.</span><code><span class="memberNameLink"><a href="../../../../com/mxgraph/shape/mxConnectorShape.html#getMarkerVector-java.util.List-boolean-double-">getMarkerVector</a></span>(<a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a><<a href="../../../../com/mxgraph/util/mxPoint.html" title="class in com.mxgraph.util">mxPoint</a>> points,
boolean source,
double markerSize)</code>
<div class="block">Hook to override creation of the vector that the marker is drawn along
since it may not be the same as the vector between any two control
points</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>protected <a href="../../../../com/mxgraph/util/mxLine.html" title="class in com.mxgraph.util">mxLine</a></code></td>
<td class="colLast"><span class="typeNameLabel">mxCurveShape.</span><code><span class="memberNameLink"><a href="../../../../com/mxgraph/shape/mxCurveShape.html#getMarkerVector-java.util.List-boolean-double-">getMarkerVector</a></span>(<a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a><<a href="../../../../com/mxgraph/util/mxPoint.html" title="class in com.mxgraph.util">mxPoint</a>> points,
boolean source,
double markerSize)</code>
<div class="block">Hook to override creation of the vector that the marker is drawn along
since it may not be the same as the vector between any two control
points</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.mxgraph.util">
<!-- -->
</a>
<h3>Uses of <a href="../../../../com/mxgraph/util/mxLine.html" title="class in com.mxgraph.util">mxLine</a> in <a href="../../../../com/mxgraph/util/package-summary.html">com.mxgraph.util</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../com/mxgraph/util/package-summary.html">com.mxgraph.util</a> declared as <a href="../../../../com/mxgraph/util/mxLine.html" title="class in com.mxgraph.util">mxLine</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../com/mxgraph/util/mxLine.html" title="class in com.mxgraph.util">mxLine</a></code></td>
<td class="colLast"><span class="typeNameLabel">mxCurve.</span><code><span class="memberNameLink"><a href="../../../../com/mxgraph/util/mxCurve.html#INVALID_POSITION">INVALID_POSITION</a></span></code>
<div class="block">Indicates that an invalid position on a curve was requested</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../com/mxgraph/util/package-summary.html">com.mxgraph.util</a> that return <a href="../../../../com/mxgraph/util/mxLine.html" title="class in com.mxgraph.util">mxLine</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../com/mxgraph/util/mxLine.html" title="class in com.mxgraph.util">mxLine</a></code></td>
<td class="colLast"><span class="typeNameLabel">mxCurve.</span><code><span class="memberNameLink"><a href="../../../../com/mxgraph/util/mxCurve.html#getCurveParallel-java.lang.String-double-">getCurveParallel</a></span>(<a href="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> index,
double distance)</code>
<div class="block">Returns a unit vector parallel to the curve at the specified
distance along the curve.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../com/mxgraph/util/mxLine.html" title="class in com.mxgraph.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><p><b>mxGraph 3.7.0.1</b></p></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/mxgraph/util/class-use/mxLine.html" target="_top">Frames</a></li>
<li><a href="mxLine.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><font size=1>Copyright (c) 2010 <a href="http://www.mxgraph.com/"
target="_blank">Gaudenz Alder, David Benson</a>. All rights reserved.</font></small></p>
</body>
</html>
| tsxuehu/jgraphlearn | java/docs/com/mxgraph/util/class-use/mxLine.html | HTML | apache-2.0 | 11,805 |
package com.guapiweather.android;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.guapiweather.android", appContext.getPackageName());
}
}
| LJiLong/guapiweather | app/src/androidTest/java/com/guapiweather/android/ExampleInstrumentedTest.java | Java | apache-2.0 | 752 |
# Iridaea remuliformis R.W.Ricker SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Rhodophyta/Florideophyceae/Gigartinales/Gigartinaceae/Iridaea/Iridaea remuliformis/README.md | Markdown | apache-2.0 | 189 |
/*
* This file is part of jTransfo, a library for converting to and from transfer objects.
* Copyright (c) PROGS bvba, Belgium
*
* The program is available in open source according to the Apache License, Version 2.0.
* For full licensing details, see LICENSE.txt in the project root.
*/
package org.jtransfo.internal;
import org.jtransfo.JTransfoException;
import org.jtransfo.TypeConverter;
/**
* Converter class to copy one field to the domain class.
*/
public final class ToDomainConverter extends AbstractConverter {
private SyntheticField toField;
private SyntheticField[] domainFields;
private TypeConverter typeConverter;
/**
* Constructor.
*
* @param toField transfer object field
* @param domainFields domain object field
* @param typeConverter type converter
*/
public ToDomainConverter(SyntheticField toField, SyntheticField[] domainFields, TypeConverter typeConverter) {
this.toField = toField;
this.domainFields = domainFields;
this.typeConverter = typeConverter;
}
@Override
public void doConvert(Object source, Object firstTarget, String... tags)
throws JTransfoException, IllegalAccessException, IllegalArgumentException {
Object value = toField.get(source);
Object target = firstTarget;
for (int i = 0; i < domainFields.length - 1; i++) {
target = domainFields[i].get(target);
if (null == target) {
throw new JTransfoException(String.format("Cannot convert TO field %s to domain field %s, " +
"transitive field %s in path is null.", toField.getName(), domainFieldName(domainFields),
domainFields[i].getName()));
}
}
SyntheticField domainField = domainFields[domainFields.length - 1];
domainField.set(target, typeConverter.convert(value, domainField, target, tags));
}
@Override
public String accessExceptionMessage() {
return String.format("Cannot convert TO field %s to domain field %s, field cannot be accessed.",
toField.getName(), domainFieldName(domainFields));
}
@Override
public String argumentExceptionMessage() {
return String.format("Cannot convert TO field %s to domain field %s, field needs type conversion.",
toField.getName(), domainFieldName(domainFields));
}
}
| joachimvda/jtransfo | core/src/main/java/org/jtransfo/internal/ToDomainConverter.java | Java | apache-2.0 | 2,432 |
// LocatorAPI.h: interface for the CLocatorAPI class.
//
//////////////////////////////////////////////////////////////////////
#ifndef LocatorAPIH
#define LocatorAPIH
#pragma once
#pragma warning(push)
#pragma warning(disable:4995)
#include <io.h>
#pragma warning(pop)
#include "LocatorAPI_defs.h"
class XRCORE_API CStreamReader;
class XRCORE_API CLocatorAPI
{
friend class FS_Path;
public:
struct file
{
LPCSTR name; // low-case name
u32 vfs; // 0xffffffff - standart file
u32 crc; // contents CRC
u32 ptr; // pointer inside vfs
u32 size_real; //
u32 size_compressed;// if (size_real==size_compressed) - uncompressed
u32 modif; // for editor
};
private:
struct file_pred: public std::binary_function<file&, file&, bool>
{
IC bool operator() (const file& x, const file& y) const
{ return xr_strcmp(x.name,y.name)<0; }
};
struct archive
{
shared_str path;
void *hSrcFile, *hSrcMap;
u32 size;
};
DEFINE_MAP_PRED (LPCSTR,FS_Path*,PathMap,PathPairIt,pred_str);
PathMap pathes;
DEFINE_SET_PRED (file,files_set,files_it,file_pred);
DEFINE_VECTOR (archive,archives_vec,archives_it);
DEFINE_VECTOR (_finddata_t,FFVec,FFIt);
FFVec rec_files;
int m_iLockRescan ;
void rescan_path (LPCSTR full_path, BOOL bRecurse);
void check_pathes ();
files_set files ;
archives_vec archives ;
BOOL bNoRecurse ;
xrCriticalSection m_auth_lock ;
u64 m_auth_code ;
void Register (LPCSTR name, u32 vfs, u32 crc, u32 ptr, u32 size_real, u32 size_compressed, u32 modif);
void ProcessArchive (LPCSTR path, LPCSTR base_path=NULL);
void ProcessOne (LPCSTR path, void* F);
bool Recurse (LPCSTR path);
// bool CheckExistance (LPCSTR path);
files_it file_find_it (LPCSTR n);
public:
enum{
flNeedRescan = (1<<0),
flBuildCopy = (1<<1),
flReady = (1<<2),
flEBuildCopy = (1<<3),
flEventNotificator = (1<<4),
flTargetFolderOnly = (1<<5),
flCacheFiles = (1<<6),
flScanAppRoot = (1<<7),
flNeedCheck = (1<<8),
flDumpFileActivity = (1<<9),
};
Flags32 m_Flags ;
u32 dwAllocGranularity;
u32 dwOpenCounter;
private:
void check_cached_files (LPSTR fname, const file &desc, LPCSTR &source_name);
void file_from_cache_impl(IReader *&R, LPSTR fname, const file &desc);
void file_from_cache_impl(CStreamReader *&R, LPSTR fname, const file &desc);
template <typename T>
void file_from_cache (T *&R, LPSTR fname, const file &desc, LPCSTR &source_name);
void file_from_archive (IReader *&R, LPCSTR fname, const file &desc);
void file_from_archive (CStreamReader *&R, LPCSTR fname, const file &desc);
void copy_file_to_build (IWriter *W, IReader *r);
void copy_file_to_build (IWriter *W, CStreamReader *r);
template <typename T>
void copy_file_to_build (T *&R, LPCSTR source_name);
bool check_for_file (LPCSTR path, LPCSTR _fname, string_path& fname, const file *&desc);
template <typename T>
IC T *r_open_impl (LPCSTR path, LPCSTR _fname);
void ProcessExternalArch ();
public:
CLocatorAPI ();
~CLocatorAPI ();
void _initialize (u32 flags, LPCSTR target_folder=0, LPCSTR fs_name=0);
void _destroy ();
CStreamReader* rs_open (LPCSTR initial, LPCSTR N);
IReader* r_open (LPCSTR initial, LPCSTR N);
IC IReader* r_open (LPCSTR N){return r_open(0,N);}
void r_close (IReader* &S);
void r_close (CStreamReader* &fs);
IWriter* w_open (LPCSTR initial, LPCSTR N);
IC IWriter* w_open (LPCSTR N){return w_open(0,N);}
IWriter* w_open_ex (LPCSTR initial, LPCSTR N);
IC IWriter* w_open_ex (LPCSTR N){return w_open_ex(0,N);}
void w_close (IWriter* &S);
const file* exist (LPCSTR N);
const file* exist (LPCSTR path, LPCSTR name);
const file* exist (string_path& fn, LPCSTR path, LPCSTR name);
const file* exist (string_path& fn, LPCSTR path, LPCSTR name, LPCSTR ext);
BOOL can_write_to_folder (LPCSTR path);
BOOL can_write_to_alias (LPCSTR path);
BOOL can_modify_file (LPCSTR fname);
BOOL can_modify_file (LPCSTR path, LPCSTR name);
BOOL dir_delete (LPCSTR path,LPCSTR nm,BOOL remove_files);
BOOL dir_delete (LPCSTR full_path,BOOL remove_files){return dir_delete(0,full_path,remove_files);}
void file_delete (LPCSTR path,LPCSTR nm);
void file_delete (LPCSTR full_path){file_delete(0,full_path);}
void file_copy (LPCSTR src, LPCSTR dest);
void file_rename (LPCSTR src, LPCSTR dest,bool bOwerwrite=true);
int file_length (LPCSTR src);
u32 get_file_age (LPCSTR nm);
void set_file_age (LPCSTR nm, u32 age);
xr_vector<LPSTR>* file_list_open (LPCSTR initial, LPCSTR folder, u32 flags=FS_ListFiles);
xr_vector<LPSTR>* file_list_open (LPCSTR path, u32 flags=FS_ListFiles);
void file_list_close (xr_vector<LPSTR>* &lst);
bool path_exist (LPCSTR path);
FS_Path* get_path (LPCSTR path);
FS_Path* append_path (LPCSTR path_alias, LPCSTR root, LPCSTR add, BOOL recursive);
LPCSTR update_path (string_path& dest, LPCSTR initial, LPCSTR src);
int file_list (FS_FileSet& dest, LPCSTR path, u32 flags=FS_ListFiles, LPCSTR mask=0);
//. void update_path (xr_string& dest, LPCSTR initial, LPCSTR src);
//
void register_archieve (LPCSTR path);
void auth_generate (xr_vector<xr_string>& ignore, xr_vector<xr_string>& important);
u64 auth_get ();
void auth_runtime (void*);
// editor functions
void rescan_pathes ();
void lock_rescan ();
void unlock_rescan ();
};
extern XRCORE_API CLocatorAPI* xr_FS;
#define FS (*xr_FS)
#endif // LocatorAPIH
| OLR-xray/OLR-3.0 | src/xray/xrCore/LocatorAPI.h | C | apache-2.0 | 6,031 |
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2017, Arnaud Roques
*
* Project Info: http://plantuml.com
*
* This file is part of PlantUML.
*
* 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.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.hector;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class PinLinksContinuousSet {
private final Collection<PinLink> all = new ArrayList<PinLink>();
public Skeleton createSkeleton() {
final GrowingTree tree = new GrowingTree();
final Collection<PinLink> pendings = new ArrayList<PinLink>(all);
while (pendings.size() > 0) {
for (Iterator<PinLink> it = pendings.iterator(); it.hasNext();) {
final PinLink candidat = it.next();
if (tree.canBeAdded(candidat)) {
tree.add(candidat);
it.remove();
}
}
}
return tree.createSkeleton();
}
public void add(PinLink newPinLink) {
if (all.size() == 0) {
all.add(newPinLink);
return;
}
if (all.contains(newPinLink)) {
throw new IllegalArgumentException("already");
}
for (PinLink aLink : all) {
if (newPinLink.doesTouch(aLink)) {
all.add(newPinLink);
return;
}
}
throw new IllegalArgumentException("not connex");
}
public void addAll(PinLinksContinuousSet other) {
if (doesTouch(other) == false) {
throw new IllegalArgumentException();
}
this.all.addAll(other.all);
}
public boolean doesTouch(PinLink other) {
for (PinLink aLink : all) {
if (other.doesTouch(aLink)) {
return true;
}
}
return false;
}
public boolean doesTouch(PinLinksContinuousSet otherSet) {
for (PinLink otherLink : otherSet.all) {
if (doesTouch(otherLink)) {
return true;
}
}
return false;
}
}
| Banno/sbt-plantuml-plugin | src/main/java/net/sourceforge/plantuml/hector/PinLinksContinuousSet.java | Java | apache-2.0 | 2,436 |
describe("", function() {
var rootEl;
beforeEach(function() {
rootEl = browser.rootEl;
browser.get("build/docs/examples/example-example25/index-jquery.html");
});
it('should allow user expression testing', function() {
element(by.css('.expressions button')).click();
var lis = element(by.css('.expressions ul')).all(by.repeater('expr in exprs'));
expect(lis.count()).toBe(1);
expect(lis.get(0).getText()).toEqual('[ X ] 3*10|currency => $30.00');
});
}); | LADOSSIFPB/nutrif | nutrif-web/lib/angular/docs/ptore2e/example-example25/jquery_test.js | JavaScript | apache-2.0 | 492 |
/**
* Copyright (C) 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dashbuilder.dataprovider.backend.sql.dialect;
import java.util.HashMap;
import java.util.Map;
import org.dashbuilder.dataprovider.backend.sql.model.Column;
import org.dashbuilder.dataprovider.backend.sql.model.DynamicDateColumn;
import org.dashbuilder.dataset.group.DateIntervalType;
public class MySQLDialect extends DefaultDialect {
public static final String PATTERN_YEAR = "%Y";
public static final String PATTERN_MONTH = "%Y-%m";
public static final String PATTERN_DAY = "%Y-%m-%d";
public static final String PATTERN_HOUR = "%Y-%m-%d %H";
public static final String PATTERN_MINUTE = "%Y-%m-%d %H:%i";
public static final String PATTERN_SECOND = "%Y-%m-%d %H:%i:%s";
private static Map<DateIntervalType,String> datePatternMap = new HashMap<DateIntervalType, String>();
static {
datePatternMap.put(DateIntervalType.SECOND, PATTERN_SECOND);
datePatternMap.put(DateIntervalType.MINUTE, PATTERN_MINUTE);
datePatternMap.put(DateIntervalType.HOUR, PATTERN_HOUR);
datePatternMap.put(DateIntervalType.DAY, PATTERN_DAY);
datePatternMap.put(DateIntervalType.WEEK, PATTERN_DAY);
datePatternMap.put(DateIntervalType.MONTH, PATTERN_MONTH);
datePatternMap.put(DateIntervalType.QUARTER, PATTERN_MONTH);
datePatternMap.put(DateIntervalType.YEAR, PATTERN_YEAR);
datePatternMap.put(DateIntervalType.DECADE, PATTERN_YEAR);
datePatternMap.put(DateIntervalType.CENTURY, PATTERN_YEAR);
datePatternMap.put(DateIntervalType.MILLENIUM, PATTERN_YEAR);
}
@Override
public boolean allowAliasInStatements() {
return true;
}
@Override
public String getAliasForColumnSQL(String alias) {
return "AS `" + alias + "`";
}
@Override
public String getAliasForStatementSQL(String alias) {
return "`" + alias + "`";
}
@Override
public String getConcatFunctionSQL(Column[] columns) {
return super.getConcatFunctionSQL(columns, "CONCAT(", ")", ",");
}
@Override
public String getColumnCastSQL(Column column) {
String columnSQL = getColumnSQL(column);
return "CAST(" + columnSQL + " AS CHAR)";
}
@Override
public String getDynamicDateColumnSQL(DynamicDateColumn column) {
DateIntervalType type = column.getDateType();
if (!datePatternMap.containsKey(type)) {
throw new IllegalArgumentException("Group '" + column.getName() +
"' by the given date interval type is not supported: " + type);
}
String datePattern = datePatternMap.get(type);
String columnName = getColumnNameSQL(column.getName());
return "DATE_FORMAT(" + columnName + ", '" + datePattern + "')";
}
}
| porcelli-forks/dashbuilder | dashbuilder-backend/dashbuilder-dataset-sql/src/main/java/org/dashbuilder/dataprovider/backend/sql/dialect/MySQLDialect.java | Java | apache-2.0 | 3,373 |
/**
* Copyright (c) Anton Johansson <antoon.johansson@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.antonjohansson.counterstrike.domain.CounterStrikeOverview;
import com.speedment.internal.core.runtime.ApplicationMetadata;
import javax.annotation.Generated;
/**
* A {@link com.speedment.internal.core.runtime.ApplicationMetadata} class
* for the {@link com.speedment.config.Project} named CounterStrikeOverview.
* This class contains the meta data present at code generation time.
* <p>
* This Class or Interface has been automatically generated by Speedment. Any
* changes made to this Class or Interface will be overwritten.
*
* @author Speedment
*/
@Generated("Speedment")
public class CounterStrikeOverviewApplicationMetadata implements ApplicationMetadata {
private final static StringBuilder METADATA = new StringBuilder();
static {
METADATA.append("import com.speedment.config.parameters.*\n");
METADATA.append("\n");
METADATA.append("name = \"CounterStrikeOverview\";\n");
METADATA.append("packageLocation = \"src/main/java\";\n");
METADATA.append("packageName = \"com.antonjohansson.counterstrike.domain\";\n");
METADATA.append("enabled = true;\n");
METADATA.append("expanded = true;\n");
METADATA.append("dbms {\n");
METADATA.append(" ipAddress = \"127.0.0.1\";\n");
METADATA.append(" name = \"CounterStrikeOverviewTest\";\n");
METADATA.append(" port = 3306;\n");
METADATA.append(" typeName = \"MySQL\";\n");
METADATA.append(" username = \"root\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" schema {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.NONE;\n");
METADATA.append(" fieldStorageType = FieldStorageType.WRAPPER;\n");
METADATA.append(" name = \"CounterStrikeOverviewTest\";\n");
METADATA.append(" schemaName = \"CounterStrikeOverviewTest\";\n");
METADATA.append(" storageEngineType = StorageEngineType.ON_HEAP;\n");
METADATA.append(" defaultSchema = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" table {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"Account\";\n");
METADATA.append(" storageEngineType = StorageEngineType.INHERIT;\n");
METADATA.append(" tableName = \"Account\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = false;\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.Long.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"accountId\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.LongIdentityMapper.class;\n");
METADATA.append(" autoincrement = true;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.Long.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"steamId\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.LongIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.String.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"personaName\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.StringIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.String.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"realName\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.StringIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.String.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"profileURL\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.StringIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.String.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"authToken\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.StringIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.String.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"profileImageSmallURL\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.StringIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.String.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"profileImageMediumURL\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.StringIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.String.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"profileImageLargeURL\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.StringIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" primaryKeyColumn {\n");
METADATA.append(" name = \"accountId\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" index {\n");
METADATA.append(" name = \"PRIMARY\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" unique = true;\n");
METADATA.append(" indexColumn {\n");
METADATA.append(" name = \"accountId\";\n");
METADATA.append(" orderType = OrderType.ASC;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" index {\n");
METADATA.append(" name = \"steamId\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" unique = true;\n");
METADATA.append(" indexColumn {\n");
METADATA.append(" name = \"steamId\";\n");
METADATA.append(" orderType = OrderType.ASC;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" table {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"Map\";\n");
METADATA.append(" storageEngineType = StorageEngineType.INHERIT;\n");
METADATA.append(" tableName = \"Map\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = false;\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.Long.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"mapId\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.LongIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.String.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"mapName\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.StringIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" primaryKeyColumn {\n");
METADATA.append(" name = \"mapId\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" index {\n");
METADATA.append(" name = \"PRIMARY\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" unique = true;\n");
METADATA.append(" indexColumn {\n");
METADATA.append(" name = \"mapId\";\n");
METADATA.append(" orderType = OrderType.ASC;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" table {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"Strategy\";\n");
METADATA.append(" storageEngineType = StorageEngineType.INHERIT;\n");
METADATA.append(" tableName = \"Strategy\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = false;\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.Long.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"strategyId\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.LongIdentityMapper.class;\n");
METADATA.append(" autoincrement = true;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.String.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"strategyName\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.StringIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.String.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"description\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.StringIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.Long.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"mapId\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.LongIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.String.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"team\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.StringIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.Long.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"ownerId\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.LongIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.Long.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"originalId\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.LongIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = true;\n");
METADATA.append(" }\n");
METADATA.append(" primaryKeyColumn {\n");
METADATA.append(" name = \"strategyId\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" index {\n");
METADATA.append(" name = \"PRIMARY\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" unique = true;\n");
METADATA.append(" indexColumn {\n");
METADATA.append(" name = \"strategyId\";\n");
METADATA.append(" orderType = OrderType.ASC;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" index {\n");
METADATA.append(" name = \"mapId\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" unique = false;\n");
METADATA.append(" indexColumn {\n");
METADATA.append(" name = \"mapId\";\n");
METADATA.append(" orderType = OrderType.ASC;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" index {\n");
METADATA.append(" name = \"originalId\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" unique = false;\n");
METADATA.append(" indexColumn {\n");
METADATA.append(" name = \"originalId\";\n");
METADATA.append(" orderType = OrderType.ASC;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" index {\n");
METADATA.append(" name = \"ownerId\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" unique = false;\n");
METADATA.append(" indexColumn {\n");
METADATA.append(" name = \"ownerId\";\n");
METADATA.append(" orderType = OrderType.ASC;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" foreignKey {\n");
METADATA.append(" name = \"Strategy_ibfk_1\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" foreignKeyColumn {\n");
METADATA.append(" foreignColumnName = \"accountId\";\n");
METADATA.append(" foreignTableName = \"Account\";\n");
METADATA.append(" name = \"ownerId\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" foreignKey {\n");
METADATA.append(" name = \"Strategy_ibfk_2\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" foreignKeyColumn {\n");
METADATA.append(" foreignColumnName = \"mapId\";\n");
METADATA.append(" foreignTableName = \"Map\";\n");
METADATA.append(" name = \"mapId\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" foreignKey {\n");
METADATA.append(" name = \"Strategy_ibfk_3\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" foreignKeyColumn {\n");
METADATA.append(" foreignColumnName = \"strategyId\";\n");
METADATA.append(" foreignTableName = \"Strategy\";\n");
METADATA.append(" name = \"originalId\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" table {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"StrategyRating\";\n");
METADATA.append(" storageEngineType = StorageEngineType.INHERIT;\n");
METADATA.append(" tableName = \"StrategyRating\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = false;\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.Long.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"strategyId\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.LongIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.Long.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"accountId\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.LongIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.Short.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"rating\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.ShortIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" primaryKeyColumn {\n");
METADATA.append(" name = \"strategyId\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" primaryKeyColumn {\n");
METADATA.append(" name = \"accountId\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" index {\n");
METADATA.append(" name = \"PRIMARY\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" unique = true;\n");
METADATA.append(" indexColumn {\n");
METADATA.append(" name = \"strategyId\";\n");
METADATA.append(" orderType = OrderType.ASC;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" indexColumn {\n");
METADATA.append(" name = \"accountId\";\n");
METADATA.append(" orderType = OrderType.ASC;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" index {\n");
METADATA.append(" name = \"accountId\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" unique = false;\n");
METADATA.append(" indexColumn {\n");
METADATA.append(" name = \"accountId\";\n");
METADATA.append(" orderType = OrderType.ASC;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" foreignKey {\n");
METADATA.append(" name = \"StrategyRating_ibfk_1\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" foreignKeyColumn {\n");
METADATA.append(" foreignColumnName = \"strategyId\";\n");
METADATA.append(" foreignTableName = \"Strategy\";\n");
METADATA.append(" name = \"strategyId\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" foreignKey {\n");
METADATA.append(" name = \"StrategyRating_ibfk_2\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" foreignKeyColumn {\n");
METADATA.append(" foreignColumnName = \"accountId\";\n");
METADATA.append(" foreignTableName = \"Account\";\n");
METADATA.append(" name = \"accountId\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" table {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"Tag\";\n");
METADATA.append(" storageEngineType = StorageEngineType.INHERIT;\n");
METADATA.append(" tableName = \"Tag\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = false;\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.Long.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"tagId\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.LongIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" column {\n");
METADATA.append(" columnCompressionType = ColumnCompressionType.INHERIT;\n");
METADATA.append(" databaseType = java.lang.String.class;\n");
METADATA.append(" fieldStorageType = FieldStorageType.INHERIT;\n");
METADATA.append(" name = \"tagName\";\n");
METADATA.append(" typeMapper = com.speedment.internal.core.config.mapper.identity.StringIdentityMapper.class;\n");
METADATA.append(" autoincrement = false;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" nullable = false;\n");
METADATA.append(" }\n");
METADATA.append(" primaryKeyColumn {\n");
METADATA.append(" name = \"tagId\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" index {\n");
METADATA.append(" name = \"PRIMARY\";\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" unique = true;\n");
METADATA.append(" indexColumn {\n");
METADATA.append(" name = \"tagId\";\n");
METADATA.append(" orderType = OrderType.ASC;\n");
METADATA.append(" enabled = true;\n");
METADATA.append(" expanded = true;\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append(" }\n");
METADATA.append("}\n");
}
@Override
public String getMetadata() {
return METADATA.toString();
}
} | anton-johansson/counter-strike-overview | src/main/java/com/antonjohansson/counterstrike/domain/CounterStrikeOverview/CounterStrikeOverviewApplicationMetadata.java | Java | apache-2.0 | 38,726 |
# Nephrodium hirsutum Diels SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Dryopteridaceae/Nephrodium/Nephrodium hirsutum/README.md | Markdown | apache-2.0 | 175 |
export DISTRO_NAME=centos
export DIB_RELEASE=${DIB_RELEASE:-7}
export EFI_BOOT_DIR="EFI/centos"
# by default, enable DHCP configuration of eth0 & eth1 in network
# scripts for centos 7. See yum-minimal for full details. CentOS 8
# does not come with network-scripts by default so avoid this there.
if [[ "${DIB_RELEASE}" < "8" ]]; then
export DIB_YUM_MINIMAL_CREATE_INTERFACES=${DIB_YUM_MINIMAL_CREATE_INTERFACES:-1}
else
export DIB_YUM_MINIMAL_CREATE_INTERFACES=${DIB_YUM_MINIMAL_CREATE_INTERFACES:-0}
fi
| openstack/diskimage-builder | diskimage_builder/elements/centos-minimal/environment.d/10-centos-distro-name.bash | Shell | apache-2.0 | 517 |
var app = angular.module('mobile');
app.controller('CouponSelect', function ($scope, ShareSvc, UserCouponSvc) {
document.title = '我的优惠券';
ShareSvc.user().then(function (user) {
UserCouponSvc.listPaged(user._id, CouponStatus.Usable, 1).then(function (userCoupons) {
$scope.userCoupons = userCoupons.data;
});
});
}); | wade-yifeng/soofruit | mobile/coupon_select.ctrl.js | JavaScript | apache-2.0 | 367 |
#include "helpdialog.h"
#include "ui_helpdialog.h"
HelpDialog::HelpDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::HelpDialog)
{
ui->setupUi(this);
}
HelpDialog::~HelpDialog()
{
delete ui;
}
| mickelfeng/qt_learning | AwardRandom/helpdialog.cpp | C++ | apache-2.0 | 229 |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddImageToEvents extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
//
Schema::table('events', function (Blueprint $table) {
$table->string('image');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
| vsouto/watchoverme | database/migrations/2017_06_09_152803_add_image_to_events.php | PHP | apache-2.0 | 495 |
using Abp.Application.Navigation;
using Abp.Localization;
using Blog.Authorization;
namespace Blog.Web
{
/// <summary>
/// This class defines menus for the application.
/// It uses ABP's menu system.
/// When you add menu items here, they are automatically appear in angular application.
/// See .cshtml and .js files under App/Main/views/layout/header to know how to render menu.
/// </summary>
public class BlogNavigationProvider : NavigationProvider
{
public override void SetNavigation(INavigationProviderContext context)
{
context.Manager.MainMenu
.AddItem(
new MenuItemDefinition(
"Home",
new LocalizableString("HomePage", BlogConsts.LocalizationSourceName),
url: "#/",
icon: "fa fa-home"
)
).AddItem(
new MenuItemDefinition(
"Tenants",
L("Tenants"),
url: "#tenants",
icon: "fa fa-globe",
requiredPermissionName: PermissionNames.Pages_Tenants
)
).AddItem(
new MenuItemDefinition(
"Users",
L("Users"),
url: "#users",
icon: "fa fa-users",
requiredPermissionName: PermissionNames.Pages_Users
)
).AddItem(
new MenuItemDefinition(
"About",
new LocalizableString("About", BlogConsts.LocalizationSourceName),
url: "#/about",
icon: "fa fa-info"
)
);
}
private static ILocalizableString L(string name)
{
return new LocalizableString(name, BlogConsts.LocalizationSourceName);
}
}
}
| ngyat/ABP-DEMO | Blog.Web/App_Start/BlogNavigationProvider.cs | C# | apache-2.0 | 2,079 |
# Antimima lokenbergensis (L.Bolus) H.E.K.Hartmann SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Ruschia lokenbergensis L.Bolus
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Aizoaceae/Antimima/Antimima lokenbergensis/README.md | Markdown | apache-2.0 | 224 |
#!/bin/sh
set -e
set -o pipefail
DIRNAME=`dirname "$0"`
TEST_DIR=`cd "$DIRNAME"; pwd`
TEST_BEFORE_DIR=$TEST_DIR/before/dist
TEST_AFTER_DIR=$TEST_DIR/after
TOOL_DIR="$TEST_DIR/jboss-server-migration"
SOURCE_DIST_DIR="$1"
TARGET_DIST_DIR="$2"
if [ "x$SOURCE_DIST_DIR" != "x" ]; then
if [[ $SOURCE_DIST_DIR != /* ]]; then
SOURCE_DIST_DIR="$TEST_DIR/$SOURCE_DIST_DIR"
fi
else
echo "### Usage: ./server-migration-simple-test.sh SOURCE_DIST_DIR TARGET_DIST_DIR"
exit
fi
if [ ! -d $SOURCE_DIST_DIR ]; then
echo "### Source Server base directory $SOURCE_DIST_DIR does not exists!"
exit 1;
fi
echo "### Source Server base directory: $SOURCE_DIST_DIR"
if [ ! -d $TARGET_DIST_DIR ]; then
echo "### Target Server dist directory $TARGET_DIST_DIR does not exists!"
exit 1;
fi
echo "### Target Server dist directory: $TARGET_DIST_DIR"
echo "### Preparing JBoss Server Migration Tool binary..."
rm -Rf $TOOL_DIR
unzip $TEST_DIR/../dist/standalone/target/jboss-server-migration-*.zip -d $TEST_DIR
SOURCE_DIST_CMTOOL_DIR=$SOURCE_DIST_DIR/cmtool
SOURCE_DIST_CMTOOL_MODULES_SYSTEM_DIR=$SOURCE_DIST_DIR/modules/system/layers/base/cmtool
SOURCE_DIST_CMTOOL_MODULES_CUSTOM_DIR=$SOURCE_DIST_DIR/modules/cmtool
SOURCE_DIST_STANDALONE_CONFIG_DIR=$SOURCE_DIST_DIR/standalone/configuration
SOURCE_DIST_STANDALONE_CONTENT_DIR=$SOURCE_DIST_DIR/standalone/data/content
SOURCE_DIST_STANDALONE_DEPLOYMENTS_DIR=$SOURCE_DIST_DIR/standalone/deployments
SOURCE_DIST_DOMAIN_CONFIG_DIR=$SOURCE_DIST_DIR/domain/configuration
SOURCE_DIST_DOMAIN_CONTENT_DIR=$SOURCE_DIST_DIR/domain/data/content
SOURCE_DIST_VAULT_DIR=$SOURCE_DIST_DIR/vault
TARGET_DIST_CMTOOL_DIR=$TARGET_DIST_DIR/cmtool
TARGET_DIST_CMTOOL_MODULES_SYSTEM_DIR=$TARGET_DIST_DIR/modules/system/layers/base/cmtool
TARGET_DIST_CMTOOL_MODULES_CUSTOM_DIR=$TARGET_DIST_DIR/modules/cmtool
TARGET_DIST_STANDALONE_CONFIG_DIR=$TARGET_DIST_DIR/standalone/configuration
TARGET_DIST_STANDALONE_CONTENT_DIR=$TARGET_DIST_DIR/standalone/data/content
TARGET_DIST_STANDALONE_DEPLOYMENTS_DIR=$TARGET_DIST_DIR/standalone/deployments
TARGET_DIST_DOMAIN_CONFIG_DIR=$TARGET_DIST_DIR/domain/configuration
TARGET_DIST_DOMAIN_CONTENT_DIR=$TARGET_DIST_DIR/domain/data/content
TARGET_DIST_VAULT_DIR=$TARGET_DIST_DIR/vault
echo "### Ensuring servers are in clean state..."
rm -Rf $SOURCE_DIST_CMTOOL_DIR
rm -Rf $TARGET_DIST_CMTOOL_DIR
rm -Rf $SOURCE_DIST_CMTOOL_MODULES_SYSTEM_DIR
rm -Rf $SOURCE_DIST_CMTOOL_MODULES_CUSTOM_DIR
rm -Rf $TARGET_DIST_CMTOOL_MODULES_SYSTEM_DIR
rm -Rf $TARGET_DIST_CMTOOL_MODULES_CUSTOM_DIR
rm -Rf $SOURCE_DIST_VAULT_DIR
rm -Rf $TARGET_DIST_VAULT_DIR
for file in "$TEST_BEFORE_DIR"/content/*
do
rm -Rf $SOURCE_DIST_STANDALONE_CONTENT_DIR/${file##*/}
rm -Rf $SOURCE_DIST_DOMAIN_CONTENT_DIR/${file##*/}
rm -Rf $TARGET_DIST_STANDALONE_CONTENT_DIR/${file##*/}
rm -Rf $TARGET_DIST_DOMAIN_CONTENT_DIR/${file##*/}
done
for file in "$TEST_BEFORE_DIR"/standalone-deployments/*
do
rm -Rf $SOURCE_DIST_STANDALONE_DEPLOYMENTS_DIR/${file##*/}
rm -Rf $TARGET_DIST_STANDALONE_DEPLOYMENTS_DIR/${file##*/}
done
rm -Rf $SOURCE_DIST_STANDALONE_CONFIG_DIR/cmtool*
rm -Rf $SOURCE_DIST_DOMAIN_CONFIG_DIR/cmtool*
rm -Rf $TARGET_DIST_STANDALONE_CONFIG_DIR/cmtool*
rm -Rf $TARGET_DIST_DOMAIN_CONFIG_DIR/cmtool*
echo "### Installing test modules & deployments in source server..."
cp -Rf $TEST_BEFORE_DIR/cmtool $SOURCE_DIST_CMTOOL_DIR
cp -Rf $TEST_BEFORE_DIR/modules-system/cmtool $SOURCE_DIST_CMTOOL_MODULES_SYSTEM_DIR
cp -Rf $TEST_BEFORE_DIR/modules-custom/cmtool $SOURCE_DIST_CMTOOL_MODULES_CUSTOM_DIR
mkdir -p $SOURCE_DIST_STANDALONE_CONTENT_DIR
mkdir -p $SOURCE_DIST_DOMAIN_CONTENT_DIR
cp -Rf "$TEST_BEFORE_DIR"/content/ $SOURCE_DIST_STANDALONE_CONTENT_DIR/
cp -Rf "$TEST_BEFORE_DIR"/content/ $SOURCE_DIST_DOMAIN_CONTENT_DIR/
cp -Rf "$TEST_BEFORE_DIR"/standalone-deployments/ $SOURCE_DIST_STANDALONE_DEPLOYMENTS_DIR/
echo "### setting up vault in source server"
mkdir $SOURCE_DIST_VAULT_DIR
keytool -genseckey -alias vault -storetype jceks -keyalg AES -keysize 128 -storepass vault22 -keypass vault22 -validity 730 -keystore $SOURCE_DIST_VAULT_DIR/vault.keystore
$TARGET_DIST_DIR/bin/vault.sh --keystore $SOURCE_DIST_VAULT_DIR/vault.keystore --keystore-password vault22 --alias vault --vault-block vb --attribute password --sec-attr 0penS3sam3 --enc-dir $SOURCE_DIST_VAULT_DIR --iteration 120 --salt 1234abcd
echo "### Setting up cmtool-standalone.xml and cmtool-domain.xml"
cp $SOURCE_DIST_STANDALONE_CONFIG_DIR/standalone.xml $SOURCE_DIST_STANDALONE_CONFIG_DIR/cmtool-standalone.xml
sed -f $TEST_BEFORE_DIR/cmtool-standalone.xml.patch -i '' $SOURCE_DIST_STANDALONE_CONFIG_DIR/cmtool-standalone.xml
cp $SOURCE_DIST_DOMAIN_CONFIG_DIR/domain.xml $SOURCE_DIST_DOMAIN_CONFIG_DIR/cmtool-domain.xml
sed -f $TEST_BEFORE_DIR/cmtool-domain.xml.patch -i '' $SOURCE_DIST_DOMAIN_CONFIG_DIR/cmtool-domain.xml
echo "### Executing the migration..."
$TOOL_DIR/jboss-server-migration.sh -n -s $SOURCE_DIST_DIR --target $TARGET_DIST_DIR -Djboss.server.migration.deployments.migrate-deployments.skip="false" -Djboss.server.migration.modules.includes="cmtool.module1" -Djboss.server.migration.modules.excludes="cmtool.module2,cmtool.module3" | emmartins/wildfly-server-migration | testsuite/server-migration-simple-test.sh | Shell | apache-2.0 | 5,188 |
package mongo
import (
"gopkg.in/mgo.v2/bson"
"testing"
)
func BenchmarkNestedDocumentSerializationDocument(b *testing.B) {
document := NewDocument()
subdocument := NewDocument()
subdocument.Add("int", int32(10))
document.Add("string", "hello world")
document.Add("doc", subdocument)
type T1 struct {
Int int32 `bson:"int,omitempty"`
}
type T2 struct {
String string `bson:"string,omitempty"`
Doc *T1 `bson:"doc,omitempty"`
}
parser := NewBSON()
for n := 0; n < b.N; n++ {
parser.Marshall(document, nil, 0)
}
}
func BenchmarkNestedDocumentSerializationStruct(b *testing.B) {
type T1 struct {
Int int32 `bson:"int,omitempty"`
}
type T2 struct {
String string `bson:"string,omitempty"`
Doc *T1 `bson:"doc,omitempty"`
}
// parser := NewBSON()
obj := &T2{"hello world", &T1{10}}
parser := NewBSON()
for n := 0; n < b.N; n++ {
parser.Marshall(obj, nil, 0)
}
}
func BenchmarkNestedDocumentSerializationMGO(b *testing.B) {
type T1 struct {
Int int32 `bson:"int,omitempty"`
}
type T2 struct {
String string `bson:"string,omitempty"`
Doc *T1 `bson:"doc,omitempty"`
}
obj := &T2{"hello world", &T1{10}}
for n := 0; n < b.N; n++ {
bson.Marshal(obj)
}
}
func BenchmarkNestedDocumentSerializationStructOverFlow64bytes(b *testing.B) {
type T1 struct {
Int int32 `bson:"int,omitempty"`
}
type T2 struct {
String string `bson:"string,omitempty"`
Doc *T1 `bson:"doc,omitempty"`
}
// parser := NewBSON()
obj := &T2{"hello world hello world hello world hello world hello world hello world", &T1{10}}
parser := NewBSON()
for n := 0; n < b.N; n++ {
parser.Marshall(obj, nil, 0)
}
}
func BenchmarkNestedDocumentSerializationMGOverflow64Bytes(b *testing.B) {
type T1 struct {
Int int32 `bson:"int,omitempty"`
}
type T2 struct {
String string `bson:"string,omitempty"`
Doc *T1 `bson:"doc,omitempty"`
}
obj := &T2{"hello world hello world hello world hello world hello world hello world", &T1{10}}
for n := 0; n < b.N; n++ {
bson.Marshal(obj)
}
}
func BenchmarkNestedDocumentDeserialization(b *testing.B) {
type T1 struct {
Int int32 `bson:"int,omitempty"`
}
type T2 struct {
String string `bson:"string,omitempty"`
Doc *T1 `bson:"doc,omitempty"`
}
parser := NewBSON()
data := []byte{48, 0, 0, 0, 2, 115, 116, 114, 105, 110, 103, 0, 12, 0, 0, 0, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 0, 3, 100, 111, 99, 0, 14, 0, 0, 0, 16, 105, 110, 116, 0, 10, 0, 0, 0, 0, 0}
obj := &T2{}
for n := 0; n < b.N; n++ {
parser.Unmarshal(data, obj)
}
}
func BenchmarkNestedDocumentDeserializationMGO(b *testing.B) {
type T1 struct {
Int int32 `bson:"int,omitempty"`
}
type T2 struct {
String string `bson:"string,omitempty"`
Doc *T1 `bson:"doc,omitempty"`
}
data := []byte{48, 0, 0, 0, 2, 115, 116, 114, 105, 110, 103, 0, 12, 0, 0, 0, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 0, 3, 100, 111, 99, 0, 14, 0, 0, 0, 16, 105, 110, 116, 0, 10, 0, 0, 0, 0, 0}
obj := &T2{}
for n := 0; n < b.N; n++ {
bson.Unmarshal(data, obj)
}
}
type GetBSONBenchmarkT1 struct {
Int int32 `bson:"int,omitempty"`
}
func (p *GetBSONBenchmarkT1) GetBSON() (interface{}, error) {
return &GetBSONBenchmarkT2{"hello world"}, nil
}
type GetBSONBenchmarkT2 struct {
String string `bson:"string,omitempty"`
}
func BenchmarkGetBSONSerialization(b *testing.B) {
doc := &GetBSONT1{10}
parser := NewBSON()
for n := 0; n < b.N; n++ {
parser.Marshall(doc, nil, 0)
}
}
func BenchmarkGetBSONSerializationMGO(b *testing.B) {
doc := &GetBSONT1{10}
for n := 0; n < b.N; n++ {
bson.Marshal(doc)
}
}
| christkv/proxy | src/mongo/bson_benchmarks_test.go | GO | apache-2.0 | 3,650 |
# Display annotation
Display annotation from a feature service URL.

## Use case
Annotation is useful for displaying text that you don't want to move or resize when the map is panned or zoomed (unlike labels which will move and resize). You can use annotation to place text at a fixed size, position, orientation, font, and so on. You may choose to do this for cartographic reasons or because the exact placement of the text is important.
## How to use the sample
Pan and zoom to see names of waters and burns in a small region of Scotland.
## How it works
1. Create a `Map` with a light gray canvas and a viewpoint near the data.
2. Create an `AnnotationLayer` from a feature service URL.
3. Add both layers to the operational layers of the map and add it to a `MapView`.
## Relevant API
* AnnotationLayer
* FeatureLayer
* ServiceFeatureTable
## About the data
Data derived from [Ordnance Survey OpenRivers](https://www.ordnancesurvey.co.uk/business-government/products/open-map-rivers). Contains OS data © Crown copyright and database right 2018.
The annotation layer contains two sublayers of rivers in East Lothian, Scotland, which were set by the author to only be visible within the following scale ranges:
* Water (1:50,000 - 1:100,000) - A large stream, as defined in the Scots language
* Burn (1:25,000 - 1:75,000) - A brook or small stream, as defined in the Scots language
## Additional information
Annotation is only supported from feature services hosted on an [ArcGIS Enterprise](https://enterprise.arcgis.com/en/) server.
## Tags
annotation, cartography, labels, placement, reference scale, text, utility
| Esri/arcgis-runtime-samples-qt | ArcGISRuntimeSDKQt_CppSamples/Layers/DisplayAnnotation/README.md | Markdown | apache-2.0 | 1,657 |
# Copyright 2019 Verily Life Sciences LLC
#
# 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
#
# https://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.
"""Tests for hparams_lib."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from classifaedes import hparams_lib
import tensorflow.compat.v1 as tf
class HparamsLibTest(tf.test.TestCase):
def testIndentedSerialize(self):
"""Tests that our slightly customized serialization can be parsed.
hparams_lib._human_serialize() uses indented JSON to improve readability.
"""
hps1 = hparams_lib.defaults()
serialized = hparams_lib._human_serialize(hps1)
hps2 = hparams_lib.defaults()
hps2.parse_json(serialized)
self.assertDictEqual(hps1.values(), hps2.values())
if __name__ == '__main__':
tf.test.main()
| verilylifesciences/classifaedes | classifaedes/hparams_lib_test.py | Python | apache-2.0 | 1,292 |
# -*- coding: utf-8 -*-
#
# portal.py # # # # # # # # # #
# #
# Copyright 2016 Giorgio Ladu <giorgio.ladu >at< gmail.com> #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# # # # # # #
import config
print 'Status: 302 Found'
print 'Location: http://' + config.custom_url
print ''
| giorgioladu/Rapa | portal.py | Python | apache-2.0 | 987 |
package com.boyuyun.common.json;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import org.apache.commons.collections.CollectionUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.introspect.AnnotatedClass;
import org.codehaus.jackson.map.introspect.JacksonAnnotationIntrospector;
import org.codehaus.jackson.map.ser.FilterProvider;
import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.type.JavaType;
import com.dhcc.common.json.JsonUtil;
/**
* JSON操作类。
*
* @author 贺波
*
*/
public class ByyJsonUtil extends JsonUtil {
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
*
* @param obj 任意对象
* @param formatter 日期格式
* @param filterFields 忽略转json字段
* @return 返回obj -> json
*/
public static String serializeAllExcept(Object obj,SimpleDateFormat formatter, String... filterFields)
{
ObjectMapper mapper = new ObjectMapper();
try {
if(null == filterFields){
filterFields = new String[]{""};
}
FilterProvider filters = new SimpleFilterProvider().addFilter("jsonFilter",
SimpleBeanPropertyFilter.serializeAllExcept(filterFields));
mapper.setDateFormat(formatter);
mapper.setFilters(filters);
mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
private static final long serialVersionUID = 5848702269956278537L;
public Object findFilterId(AnnotatedClass ac)
{
@SuppressWarnings("deprecation")
Object id = super.findFilterId(ac);
if (id == null) {
id = ac.getName();
}
return id;
}
});
return mapper.writeValueAsString(obj);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Json.format error:" + obj, e);
}
}
/**
*
* @param obj 任意对象
* @param formater 日期格式 默认yyyy-MM-dd HH:mm:ss
* @param filterFields 忽略转json字段
* @return 返回json字符串
*/
public static String renderJson(final Object obj,String formater,String... filterFields){
if(null== formater || "".equals(formater.trim())){
formater = "yyyy-MM-dd HH:mm:ss";
}
SimpleDateFormat formatter = new SimpleDateFormat(formater);
return serializeAllExcept(obj,formatter, filterFields);
}
public static String renderJson(long total,List<?> rows,String formater,String... filterFields){
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("total", total);
jsonMap.put("rows", rows);
return renderJson(jsonMap, formater, filterFields);
}
/**
* 将list直接转换成json串
* @param rows
* @return
*/
public static String serialize(Object obj) {
//如果是JSONObject/JSONArray/Map/等还是调用原来的?
return serialize(obj, null, null);
}
//如果是JSONObject/JSONArray/Map/等还是调用原来的?
/**
* 将list直接转换成json串,并且指定过滤掉的字段
* @param rows
* @param ignoreFields
* @return
*/
public static String serialize(Object obj, String[] ignoreFields) {
return serialize(obj, ignoreFields, null);
// return renderJson(obj, null, ignoreFields);
}
/**
* 将list直接转换成json串,并且指定日期的转换格式
* @param rows
* @param dateFormat
* @return
*/
public static String serialize(Object obj, String dateFormat) {
return serialize(obj, null, dateFormat);
// return renderJson(obj, dateFormat, null);
}
/**
* 将list直接转换成json串,并且指定过滤掉的字段、日期的转换格式
* @param rows
* @param ignoreFields
* @param dateFormat
* @return
*/
public static String serialize(Object obj, String[] ignoreFields, String dateFormat) {
JsonConfig jsonConfig = new JsonConfig();
//1 处理日期格式
if(dateFormat==null || dateFormat.equals("")) {
dateFormat = "yyyy-MM-dd HH:mm:ss";//默认为年月日时分秒
}
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateTransform(dateFormat));
jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateTransform(dateFormat));
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
//2 处理需要过滤掉的字段
if(ignoreFields!=null && ignoreFields.length>0) {
Set<String> ignoreSet = new HashSet<String>();
CollectionUtils.addAll(ignoreSet, ignoreFields);
//下面这两个过滤必须添加
ignoreSet.add("handler");
ignoreSet.add("hibernateLazyInitializer");
Object[] tempArr = ignoreSet.toArray();
ignoreFields = new String[tempArr.length];
for(int i=0; i<tempArr.length; i++) {
ignoreFields[i] = tempArr[i].toString();
}
}else {
ignoreFields = new String[]{"handler","hibernateLazyInitializer"};
}
jsonConfig.setExcludes(ignoreFields);
//3 判断obj 是不是一个集合
if(obj instanceof List) {
return JSONArray.fromObject(obj, jsonConfig).toString();
}else {
return JSONObject.fromObject(obj, jsonConfig).toString();
}
}
/**
* 根据对象获取JSONObject对象
* @param obj 如果为list类型,则返回null
* @param ignoreFields
* @param dateFormat
* @return
* @date 2015-9-24 下午3:17:51
*/
public static JSONObject serializeToJSONObject(Object obj, String[] ignoreFields, String dateFormat) {
JsonConfig jsonConfig = new JsonConfig();
//1 处理日期格式
if(dateFormat==null || dateFormat.equals("")) {
dateFormat = "yyyy-MM-dd HH:mm:ss";//默认为年月日时分秒
}
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateTransform(dateFormat));
jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateTransform(dateFormat));
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
//2 处理需要过滤掉的字段
if(ignoreFields!=null && ignoreFields.length>0) {
Set<String> ignoreSet = new HashSet<String>();
CollectionUtils.addAll(ignoreSet, ignoreFields);
//下面这两个过滤必须添加
ignoreSet.add("handler");
ignoreSet.add("hibernateLazyInitializer");
Object[] tempArr = ignoreSet.toArray();
ignoreFields = new String[tempArr.length];
for(int i=0; i<tempArr.length; i++) {
ignoreFields[i] = tempArr[i].toString();
}
}else {
ignoreFields = new String[]{"handler","hibernateLazyInitializer"};
}
jsonConfig.setExcludes(ignoreFields);
//3 判断obj 是不是一个集合
if(obj instanceof List) {
return null;
}else {
return JSONObject.fromObject(obj, jsonConfig);
}
}
/**
* 根据对象获取JSONObject对象
* @param obj 如果为list类型,则返回null
* @param ignoreFields
* @param dateFormat
* @return
* @date 2015-9-24 下午3:17:51
*/
public static JSONArray serializeToJSONArray(Object obj, String[] ignoreFields, String dateFormat) {
JsonConfig jsonConfig = new JsonConfig();
//1 处理日期格式
if(dateFormat==null || dateFormat.equals("")) {
dateFormat = "yyyy-MM-dd HH:mm:ss";//默认为年月日时分秒
}
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateTransform(dateFormat));
jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateTransform(dateFormat));
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
//2 处理需要过滤掉的字段
if(ignoreFields!=null && ignoreFields.length>0) {
Set<String> ignoreSet = new HashSet<String>();
CollectionUtils.addAll(ignoreSet, ignoreFields);
//下面这两个过滤必须添加
ignoreSet.add("handler");
ignoreSet.add("hibernateLazyInitializer");
Object[] tempArr = ignoreSet.toArray();
ignoreFields = new String[tempArr.length];
for(int i=0; i<tempArr.length; i++) {
ignoreFields[i] = tempArr[i].toString();
}
}else {
ignoreFields = new String[]{"handler","hibernateLazyInitializer"};
}
jsonConfig.setExcludes(ignoreFields);
//3 判断obj 是不是一个集合
if(obj instanceof List) {
return JSONArray.fromObject(obj, jsonConfig);
}else {
return null;
}
}
/**
* 将list直接转换成json串,含分页
* @param total
* @param rows
* @return
*/
public static String serialize(long total, List rows) {
return serialize(total, rows, null, null);
// return renderJson(total, rows, null, null);
}
/**
* 将list直接转换成json串,含分页。 并且指定过滤掉的字段
* @param total
* @param rows
* @param ignoreFields
* @return
*/
public static String serialize(long total, List rows, String[] ignoreFields) {
return serialize(total, rows, ignoreFields, null);
// return renderJson(total, rows, null, ignoreFields);
}
/**
* 将list直接转换成json串,含分页。 并且指定过滤掉的字段
* @param total
* @param rows
* @param ignoreFields
* @return
*/
public static String serialize(long total, List rows, String dateFormat) {
return serialize(total, rows, null, dateFormat);
// return renderJson(total, rows, dateFormat, null);
}
/**
* 将list直接转换成json串,含分页。 并且指定过滤掉的字段、日期的转换格式
* @param total
* @param rows
* @param ignoreFields
* @return
*/
public static String serialize(long total, List rows, String[] ignoreFields, String dateFormat) {
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("total", total);
jsonMap.put("rows", rows);
JsonConfig jsonConfig = new JsonConfig();
//1 处理日期格式
if(dateFormat==null || dateFormat.equals("")) {
dateFormat = "yyyy-MM-dd";//默认为年月日
}
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateTransform(dateFormat));
jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateTransform(dateFormat));
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
//2 处理需要过滤掉的字段
if(ignoreFields!=null && ignoreFields.length>0) {
Set<String> ignoreSet = new HashSet<String>();
CollectionUtils.addAll(ignoreSet, ignoreFields);
//下面这两个过滤必须添加
ignoreSet.add("handler");
ignoreSet.add("hibernateLazyInitializer");
Object[] tempArr = ignoreSet.toArray();
ignoreFields = new String[tempArr.length];
for(int i=0; i<tempArr.length; i++) {
ignoreFields[i] = tempArr[i].toString();
}
}else {
ignoreFields = new String[]{"handler","hibernateLazyInitializer"};
}
jsonConfig.setExcludes(ignoreFields);
return JSONObject.fromObject(jsonMap, jsonConfig).toString();
}
/**
* 将Map集合转换成Json字符串(Date类型转换为通用格式[yyyy-MM-dd HH:mm:ss])
* @param jsonMap
* @return
* @date 2015-8-29 下午12:00:57
*/
public static String serialize(Map<?,?> jsonMap){
return serialize(jsonMap,null,null,"yyyy-MM-dd HH:mm:ss",null);
// return renderJson(jsonMap, null, null);
}
/**
* 将Map集合转换成Json字符串(Date类型转换为通用格式[yyyy-MM-dd HH:mm:ss])
* @param jsonMap
* @param filterFields 要过滤的字段数组
* @return
* @date 2015-8-29 下午12:01:08
*/
public static String serialize(Map<?,?> jsonMap,String []filterFields){
return serialize(jsonMap,filterFields,null,"yyyy-MM-dd HH:mm:ss",null);
// return renderJson(jsonMap, null, filterFields);
}
/**
* 转换Map对象为Json字符串
* @param jsonMap 要转换的Map对象
* @param filterFields 要过滤的字段
* @param enclosedType 要过滤的类型
* @param dateFormat 日期转换格式
* @param timeFormat 时间转换格式
* @return JSON字符串
* @date 2015-8-29 上午11:34:56
*/
public static String serialize(Map<?,?> jsonMap,String[] filterFields, Class enclosedType,String dateFormat,String timeFormat){
// 通过jsonconfig,过滤指定的的属性filterFields
JsonConfig jsonConfig = new JsonConfig();
if(filterFields!=null){
jsonConfig.setExcludes(filterFields);
}
// 通过jsonconfig,过滤指定的的属性filterFields
if(enclosedType!=null){
jsonConfig.setEnclosedType(enclosedType);
}
if(dateFormat!=null && !"".equals(dateFormat)){
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateTransform(dateFormat));
}
if(timeFormat!=null && !"".equals(timeFormat)){
jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateTransform(timeFormat));
}
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
return JSONObject.fromObject(jsonMap, jsonConfig).toString();
}
public static String getSuccessJson(String msg) {
return "{\"success\":\"true\",\"msg\":\"" + msg + "\"}";
}
public static String getFailJson(String msg) {
return "{\"success\":\"false\",\"msg\":\"" + msg + "\"}";
}
public static String getNoDataJson(String msg) {
return "{\"success\":\"false\",\"msg\":\"" + msg + "\",\"total\":0,\"rows\":[]}";
}
public static String getDeleteHtml(String title,String msg){
return "<html><meta charset=\"utf-8\"><title>"+title+"</title><body><div style=\"position:absolute;top:50%;text-align:center;width:100%;\">"+msg+"</div></body></html>";
}
/**
* 将对象转换成json字符串。
* <p>Title: pojoToJson</p>
* <p>Description: </p>
* @param data
* @return
*/
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将json结果集转化为对象
*
* @param jsonData json数据
* @param clazz 对象中的object类型
* @return
*/
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将json数据转换成pojo对象list
* <p>Title: jsonToList</p>
* <p>Description: </p>
* @param jsonData
* @param beanType
* @return
*/
public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| yunhai281/baseProject | src/main/java/com/boyuyun/common/json/ByyJsonUtil.java | Java | apache-2.0 | 16,571 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.qcert.camp.data;
import java.io.PrintWriter;
/**
* Represents the dfloat data constructor
*/
public class FloatData extends CampData {
private final double value;
public FloatData(double value) {
this.value = value;
}
/* (non-Javadoc)
* @see org.qcert.camp.CampAST#emit(java.io.PrintWriter)
*/
@Override
public void emit(PrintWriter pw) {
pw.append(String.valueOf(value));
}
/* (non-Javadoc)
* @see org.qcert.camp.data.CampData#getKind()
*/
@Override
public Kind getKind() {
return Kind.dfloat;
}
/**
* @return the value
*/
public double getValue() {
return value;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.valueOf(value);
}
/* (non-Javadoc)
* @see org.qcert.camp.CampAST#getOperands()
*/
@Override
protected Object[] getOperands() {
throw new IllegalStateException(); // emit is overridden, this should not be called
}
/* (non-Javadoc)
* @see org.qcert.camp.CampAST#getTag()
*/
@Override
protected String getTag() {
throw new IllegalStateException(); // emit is overridden, this should not be called
}
}
| querycert/qcert | compiler/parsingJava/jrulesParser/src/org/qcert/camp/data/FloatData.java | Java | apache-2.0 | 1,792 |
////////////////////////////////////////////////////////////////////////
//FAKE関数
//FAKE_VALUE_FUNC(int, external_function, int);
////////////////////////////////////////////////////////////////////////
class extendedkey: public testing::Test {
protected:
virtual void SetUp() {
//RESET_FAKE(external_function)
utl_log_init_stdout();
utl_dbg_malloc_cnt_reset();
btc_init(BTC_BLOCK_CHAIN_BTCMAIN, false);
}
virtual void TearDown() {
ASSERT_EQ(0, utl_dbg_malloc_cnt());
btc_term();
}
public:
static btc_extkey_t extkey;
static btc_extkey_t extkey_prev;
static uint8_t priv[BTC_SZ_PRIVKEY];
static uint8_t pub[BTC_SZ_PUBKEY];
static uint8_t pub_prev[BTC_SZ_PUBKEY];
public:
static void DumpBin(const uint8_t *pData, uint16_t Len)
{
for (uint16_t lp = 0; lp < Len; lp++) {
printf("%02x", pData[lp]);
}
printf("\n");
}
};
btc_extkey_t extendedkey::extkey;
btc_extkey_t extendedkey::extkey_prev;
uint8_t extendedkey::priv[BTC_SZ_PRIVKEY];
uint8_t extendedkey::pub[BTC_SZ_PUBKEY];
uint8_t extendedkey::pub_prev[BTC_SZ_PUBKEY];
////////////////////////////////////////////////////////////////////////
TEST_F(extendedkey, chain_m)
{
// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#test-vector-1
const uint8_t SEED[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
};
const char XPRIV0[] = "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi";
const char XPUB0[] = "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8";
uint8_t buf_extkey[BTC_SZ_EXTKEY];
char xaddr[BTC_SZ_EXTKEY_ADDR_MAX + 1];
bool b = btc_extkey_generate(&extkey, BTC_EXTKEY_PRIV, 0, 0, NULL, SEED, sizeof(SEED));
ASSERT_TRUE(b);
btc_extkey_print(&extkey);
memcpy(priv, extkey.key, BTC_SZ_PRIVKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey);
ASSERT_TRUE(b);
ASSERT_STREQ(XPRIV0, xaddr);
btc_extkey_print(&extkey);
extkey.type = BTC_EXTKEY_PUB;
btc_keys_priv2pub(extkey.key, extkey.key);
memcpy(pub, extkey.key, BTC_SZ_PUBKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey);
ASSERT_TRUE(b);
ASSERT_STREQ(XPUB0, xaddr);
btc_extkey_print(&extkey);
btc_extkey_t extkey2;
memset(&extkey2, 0, sizeof(extkey2));
b = btc_extkey_read_addr(&extkey2, XPRIV0);
ASSERT_TRUE(b);
ASSERT_EQ(BTC_EXTKEY_PRIV, extkey2.type);
ASSERT_EQ(0, extkey2.depth);
ASSERT_EQ(0, extkey2.child_number);
ASSERT_EQ(0, memcmp(priv, extkey2.key, sizeof(priv)));
memset(&extkey2, 0, sizeof(extkey2));
b = btc_extkey_read_addr(&extkey2, XPUB0);
ASSERT_TRUE(b);
ASSERT_EQ(BTC_EXTKEY_PUB, extkey2.type);
ASSERT_EQ(0, extkey2.depth);
ASSERT_EQ(0, extkey2.child_number);
ASSERT_EQ(0, memcmp(pub, extkey2.key, sizeof(pub)));
}
TEST_F(extendedkey, chain_m_0H)
{
const char XPRIV0H[] = "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7";
const char XPUB0H[] = "xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw";
uint8_t buf_extkey[BTC_SZ_EXTKEY];
char xaddr[BTC_SZ_EXTKEY_ADDR_MAX + 1];
//pub用
memcpy(&extkey_prev, &extkey, sizeof(extkey));
memcpy(pub_prev, pub, sizeof(pub));
bool b = btc_extkey_generate(&extkey, BTC_EXTKEY_PRIV, 1, BTC_EXTKEY_HARDENED | 0, priv, NULL, 0);
ASSERT_TRUE(b);
btc_extkey_print(&extkey);
memcpy(priv, extkey.key, BTC_SZ_PRIVKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey);
ASSERT_TRUE(b);
ASSERT_STREQ(XPRIV0H, xaddr);
btc_extkey_print(&extkey);
extkey.type = BTC_EXTKEY_PUB;
btc_keys_priv2pub(extkey.key, extkey.key);
memcpy(pub, extkey.key, BTC_SZ_PUBKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey);
ASSERT_TRUE(b);
ASSERT_STREQ(XPUB0H, xaddr);
btc_extkey_print(&extkey);
btc_extkey_t extkey2;
memset(&extkey2, 0, sizeof(extkey2));
b = btc_extkey_read_addr(&extkey2, XPRIV0H);
ASSERT_TRUE(b);
ASSERT_EQ(BTC_EXTKEY_PRIV, extkey2.type);
ASSERT_EQ(1, extkey2.depth);
ASSERT_EQ(0, memcmp(priv, extkey2.key, sizeof(priv)));
memset(&extkey2, 0, sizeof(extkey2));
b = btc_extkey_read_addr(&extkey2, XPUB0H);
ASSERT_TRUE(b);
ASSERT_EQ(BTC_EXTKEY_PUB, extkey2.type);
ASSERT_EQ(1, extkey2.depth);
ASSERT_EQ(0, memcmp(pub, extkey2.key, sizeof(pub)));
}
TEST_F(extendedkey, chain_m_0Hpub)
{
//const char XPUB0H[] = "xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw";
//hardenedからchild pubkeyはNG
memcpy(extkey_prev.key, pub_prev, sizeof(pub_prev));
bool b = btc_extkey_generate(&extkey_prev, BTC_EXTKEY_PUB, 1, BTC_EXTKEY_HARDENED | 0, pub_prev, NULL, 0);
ASSERT_FALSE(b);
}
TEST_F(extendedkey, chain_m_0H_1)
{
const char XPRIV0H1[] = "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs";
const char XPUB0H1[] = "xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ";
uint8_t buf_extkey[BTC_SZ_EXTKEY];
char xaddr[BTC_SZ_EXTKEY_ADDR_MAX + 1];
//pub用
memcpy(&extkey_prev, &extkey, sizeof(extkey));
memcpy(pub_prev, pub, sizeof(pub));
bool b = btc_extkey_generate(&extkey, BTC_EXTKEY_PRIV, 2, 1, priv, NULL, 0);
ASSERT_TRUE(b);
btc_extkey_print(&extkey);
memcpy(priv, extkey.key, BTC_SZ_PRIVKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey);
ASSERT_TRUE(b);
ASSERT_STREQ(XPRIV0H1, xaddr);
btc_extkey_print(&extkey);
extkey.type = BTC_EXTKEY_PUB;
btc_keys_priv2pub(extkey.key, extkey.key);
memcpy(pub, extkey.key, BTC_SZ_PUBKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey);
ASSERT_TRUE(b);
ASSERT_STREQ(XPUB0H1, xaddr);
btc_extkey_print(&extkey);
btc_extkey_t extkey2;
memset(&extkey2, 0, sizeof(extkey2));
b = btc_extkey_read_addr(&extkey2, XPRIV0H1);
ASSERT_TRUE(b);
ASSERT_EQ(BTC_EXTKEY_PRIV, extkey2.type);
ASSERT_EQ(2, extkey2.depth);
ASSERT_EQ(0, memcmp(priv, extkey2.key, sizeof(priv)));
memset(&extkey2, 0, sizeof(extkey2));
b = btc_extkey_read_addr(&extkey2, XPUB0H1);
ASSERT_TRUE(b);
ASSERT_EQ(BTC_EXTKEY_PUB, extkey2.type);
ASSERT_EQ(2, extkey2.depth);
ASSERT_EQ(0, memcmp(pub, extkey2.key, sizeof(pub)));
}
TEST_F(extendedkey, chain_m_0H_1pub)
{
const char XPUB0H1[] = "xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ";
uint8_t buf_extkey[BTC_SZ_EXTKEY];
char xaddr[BTC_SZ_EXTKEY_ADDR_MAX + 1];
bool b = btc_extkey_generate(&extkey_prev, BTC_EXTKEY_PUB, 2, 1, pub_prev, NULL, 0);
ASSERT_TRUE(b);
memcpy(pub, extkey.key, BTC_SZ_PUBKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey_prev);
ASSERT_TRUE(b);
ASSERT_STREQ(XPUB0H1, xaddr);
}
TEST_F(extendedkey, chain_m_0H_1_2H)
{
const char XPRIV0H12H[] = "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM";
const char XPUB0H12H[] = "xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5";
uint8_t buf_extkey[BTC_SZ_EXTKEY];
char xaddr[BTC_SZ_EXTKEY_ADDR_MAX + 1];
//pub用
memcpy(&extkey_prev, &extkey, sizeof(extkey));
memcpy(pub_prev, pub, sizeof(pub));
bool b = btc_extkey_generate(&extkey, BTC_EXTKEY_PRIV, 3, BTC_EXTKEY_HARDENED | 2, priv, NULL, 0);
ASSERT_TRUE(b);
btc_extkey_print(&extkey);
memcpy(priv, extkey.key, BTC_SZ_PRIVKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey);
ASSERT_TRUE(b);
ASSERT_STREQ(XPRIV0H12H, xaddr);
btc_extkey_print(&extkey);
extkey.type = BTC_EXTKEY_PUB;
btc_keys_priv2pub(extkey.key, extkey.key);
memcpy(pub, extkey.key, BTC_SZ_PUBKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey);
ASSERT_TRUE(b);
ASSERT_STREQ(XPUB0H12H, xaddr);
btc_extkey_print(&extkey);
btc_extkey_t extkey2;
memset(&extkey2, 0, sizeof(extkey2));
b = btc_extkey_read_addr(&extkey2, XPRIV0H12H);
ASSERT_TRUE(b);
ASSERT_EQ(BTC_EXTKEY_PRIV, extkey2.type);
ASSERT_EQ(3, extkey2.depth);
ASSERT_EQ(0, memcmp(priv, extkey2.key, sizeof(priv)));
memset(&extkey2, 0, sizeof(extkey2));
b = btc_extkey_read_addr(&extkey2, XPUB0H12H);
ASSERT_TRUE(b);
ASSERT_EQ(BTC_EXTKEY_PUB, extkey2.type);
ASSERT_EQ(3, extkey2.depth);
ASSERT_EQ(0, memcmp(pub, extkey2.key, sizeof(pub)));
}
TEST_F(extendedkey, chain_m_0H_1_2Hpub)
{
//const char XPUB0H12H[] = "xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5";
memcpy(extkey_prev.key, pub_prev, sizeof(pub_prev));
bool b = btc_extkey_generate(&extkey_prev, BTC_EXTKEY_PUB, 3, BTC_EXTKEY_HARDENED | 2, pub_prev, NULL, 0);
ASSERT_FALSE(b);
}
TEST_F(extendedkey, chain_m_0H_1_2H_2)
{
const char XPRIV0H12H2[] = "xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334";
const char XPUB0H12H2[] = "xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV";
uint8_t buf_extkey[BTC_SZ_EXTKEY];
char xaddr[BTC_SZ_EXTKEY_ADDR_MAX + 1];
//pub用
memcpy(&extkey_prev, &extkey, sizeof(extkey));
memcpy(pub_prev, pub, sizeof(pub));
bool b = btc_extkey_generate(&extkey, BTC_EXTKEY_PRIV, 4, 2, priv, NULL, 0);
ASSERT_TRUE(b);
btc_extkey_print(&extkey);
memcpy(priv, extkey.key, BTC_SZ_PRIVKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey);
ASSERT_TRUE(b);
ASSERT_STREQ(XPRIV0H12H2, xaddr);
btc_extkey_print(&extkey);
extkey.type = BTC_EXTKEY_PUB;
btc_keys_priv2pub(extkey.key, extkey.key);
memcpy(pub, extkey.key, BTC_SZ_PUBKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey);
ASSERT_TRUE(b);
ASSERT_STREQ(XPUB0H12H2, xaddr);
btc_extkey_print(&extkey);
btc_extkey_t extkey2;
memset(&extkey2, 0, sizeof(extkey2));
b = btc_extkey_read_addr(&extkey2, XPRIV0H12H2);
ASSERT_TRUE(b);
ASSERT_EQ(BTC_EXTKEY_PRIV, extkey2.type);
ASSERT_EQ(4, extkey2.depth);
ASSERT_EQ(0, memcmp(priv, extkey2.key, sizeof(priv)));
memset(&extkey2, 0, sizeof(extkey2));
b = btc_extkey_read_addr(&extkey2, XPUB0H12H2);
ASSERT_TRUE(b);
ASSERT_EQ(BTC_EXTKEY_PUB, extkey2.type);
ASSERT_EQ(4, extkey2.depth);
ASSERT_EQ(0, memcmp(pub, extkey2.key, sizeof(pub)));
}
TEST_F(extendedkey, chain_m_0H_1_2H_2pub)
{
const char XPUB0H12H2[] = "xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV";
uint8_t buf_extkey[BTC_SZ_EXTKEY];
char xaddr[BTC_SZ_EXTKEY_ADDR_MAX + 1];
bool b = btc_extkey_generate(&extkey_prev, BTC_EXTKEY_PUB, 4, 2, pub_prev, NULL, 0);
ASSERT_TRUE(b);
btc_extkey_print(&extkey_prev);
memcpy(pub, extkey.key, BTC_SZ_PUBKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey_prev);
ASSERT_TRUE(b);
ASSERT_STREQ(XPUB0H12H2, xaddr);
btc_extkey_print(&extkey_prev);
}
TEST_F(extendedkey, chain_m_0H_1_2H_2_1)
{
const char XPRIV0H12H21[] = "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76";
const char XPUB0H12H21[] = "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy";
uint8_t buf_extkey[BTC_SZ_EXTKEY];
char xaddr[BTC_SZ_EXTKEY_ADDR_MAX + 1];
//pub用
memcpy(&extkey_prev, &extkey, sizeof(extkey));
memcpy(pub_prev, pub, sizeof(pub));
bool b = btc_extkey_generate(&extkey, BTC_EXTKEY_PRIV, 5, 1000000000, priv, NULL, 0);
ASSERT_TRUE(b);
btc_extkey_print(&extkey);
memcpy(priv, extkey.key, BTC_SZ_PRIVKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey);
ASSERT_TRUE(b);
ASSERT_STREQ(XPRIV0H12H21, xaddr);
btc_extkey_print(&extkey);
extkey.type = BTC_EXTKEY_PUB;
btc_keys_priv2pub(extkey.key, extkey.key);
memcpy(pub, extkey.key, BTC_SZ_PUBKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey);
ASSERT_TRUE(b);
ASSERT_STREQ(XPUB0H12H21, xaddr);
btc_extkey_print(&extkey);
btc_extkey_t extkey2;
memset(&extkey2, 0, sizeof(extkey2));
b = btc_extkey_read_addr(&extkey2, XPRIV0H12H21);
ASSERT_TRUE(b);
ASSERT_EQ(BTC_EXTKEY_PRIV, extkey2.type);
ASSERT_EQ(5, extkey2.depth);
ASSERT_EQ(0, memcmp(priv, extkey2.key, sizeof(priv)));
memset(&extkey2, 0, sizeof(extkey2));
b = btc_extkey_read_addr(&extkey2, XPUB0H12H21);
ASSERT_TRUE(b);
ASSERT_EQ(BTC_EXTKEY_PUB, extkey2.type);
ASSERT_EQ(5, extkey2.depth);
ASSERT_EQ(0, memcmp(pub, extkey2.key, sizeof(pub)));
}
TEST_F(extendedkey, chain_m_0H_1_2H_2_1pub)
{
const char XPUB0H12H21[] = "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy";
uint8_t buf_extkey[BTC_SZ_EXTKEY];
char xaddr[BTC_SZ_EXTKEY_ADDR_MAX + 1];
bool b = btc_extkey_generate(&extkey_prev, BTC_EXTKEY_PUB, 5, 1000000000, pub_prev, NULL, 0);
ASSERT_TRUE(b);
btc_extkey_print(&extkey_prev);
memcpy(pub, extkey.key, BTC_SZ_PUBKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey_prev);
ASSERT_TRUE(b);
ASSERT_STREQ(XPUB0H12H21, xaddr);
btc_extkey_print(&extkey_prev);
}
//もう一度masterから初めて、前の値を引きずっていないか確認
TEST_F(extendedkey, chain_m_master2)
{
// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#test-vector-1
const uint8_t SEED[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
};
const char XPRIV0[] = "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi";
const char XPUB0[] = "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8";
uint8_t buf_extkey[BTC_SZ_EXTKEY];
char xaddr[BTC_SZ_EXTKEY_ADDR_MAX + 1];
bool b = btc_extkey_generate(&extkey, BTC_EXTKEY_PRIV, 0, 0, NULL, SEED, sizeof(SEED));
ASSERT_TRUE(b);
btc_extkey_print(&extkey);
memcpy(priv, extkey.key, BTC_SZ_PRIVKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey);
ASSERT_TRUE(b);
ASSERT_STREQ(XPRIV0, xaddr);
btc_extkey_print(&extkey);
extkey.type = BTC_EXTKEY_PUB;
btc_keys_priv2pub(extkey.key, extkey.key);
memcpy(pub, extkey.key, BTC_SZ_PUBKEY);
b = btc_extkey_create_data(buf_extkey, xaddr, &extkey);
ASSERT_TRUE(b);
ASSERT_STREQ(XPUB0, xaddr);
btc_extkey_print(&extkey);
btc_extkey_t extkey2;
memset(&extkey2, 0, sizeof(extkey2));
b = btc_extkey_read_addr(&extkey2, XPRIV0);
ASSERT_TRUE(b);
ASSERT_EQ(BTC_EXTKEY_PRIV, extkey2.type);
ASSERT_EQ(0, extkey2.depth);
ASSERT_EQ(0, extkey2.child_number);
ASSERT_EQ(0, memcmp(priv, extkey2.key, sizeof(priv)));
memset(&extkey2, 0, sizeof(extkey2));
b = btc_extkey_read_addr(&extkey2, XPUB0);
ASSERT_TRUE(b);
ASSERT_EQ(BTC_EXTKEY_PUB, extkey2.type);
ASSERT_EQ(0, extkey2.depth);
ASSERT_EQ(0, extkey2.child_number);
ASSERT_EQ(0, memcmp(pub, extkey2.key, sizeof(pub)));
}
TEST_F(extendedkey, read_addr_fail)
{
bool b;
//長い
const char XPUB0H12H21_LONG[] = "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHyaa";
b = btc_extkey_read_addr(&extkey, XPUB0H12H21_LONG);
ASSERT_FALSE(b);
}
TEST_F(extendedkey, read_fail_len)
{
bool b;
uint8_t buf_extkey[BTC_SZ_EXTKEY];
b = btc_extkey_create_data(buf_extkey, NULL, &extkey);
ASSERT_TRUE(b);
//短い
b = btc_extkey_read(&extkey, buf_extkey, sizeof(buf_extkey) - 1);
ASSERT_FALSE(b);
}
TEST_F(extendedkey, read_fail_data)
{
bool b;
uint8_t buf_extkey[BTC_SZ_EXTKEY];
b = btc_extkey_create_data(buf_extkey, NULL, &extkey);
ASSERT_TRUE(b);
buf_extkey[3] = ~buf_extkey[3]; //書き換え
b = btc_extkey_read(&extkey, buf_extkey, sizeof(buf_extkey));
ASSERT_FALSE(b);
}
TEST_F(extendedkey, read_fail_init)
{
bool b;
uint8_t buf_extkey[BTC_SZ_EXTKEY];
b = btc_extkey_create_data(buf_extkey, NULL, &extkey);
ASSERT_TRUE(b);
mInitialized = false;
b = btc_extkey_read(&extkey, buf_extkey, sizeof(buf_extkey));
ASSERT_FALSE(b);
}
TEST_F(extendedkey, create_fail)
{
bool b;
uint8_t buf_extkey[BTC_SZ_EXTKEY];
mInitialized = false;
b = btc_extkey_create_data(buf_extkey, NULL, &extkey);
ASSERT_FALSE(b);
}
// https://github.com/bitcoin/bips/blob/master/bip-0049.mediawiki#test-vectors
TEST_F(extendedkey, bip49)
{
const char MASTERSEED[] = "tprv8ZgxMBicQKsPe5YMU9gHen4Ez3ApihUfykaqUorj9t6FDqy3nP6eoXiAo2ssvpAjoLroQxHqr3R5nE3a5dU3DHTjTgJDd7zrbniJr6nrCzd";
const char XADDR_ACC0[] = "tprv8gRrNu65W2Msef2BdBSUgFdRTGzC8EwVXnV7UGS3faeXtuMVtGfEdidVeGbThs4ELEoayCAzZQ4uUji9DUiAs7erdVskqju7hrBcDvDsdbY";
const uint8_t ACC0IDX0[] = {
0xc9, 0xbd, 0xb4, 0x9c, 0xfb, 0xae, 0xdc, 0xa2,
0x1c, 0x4b, 0x1f, 0x3a, 0x78, 0x03, 0xc3, 0x46,
0x36, 0xb1, 0xd7, 0xdc, 0x55, 0xa7, 0x17, 0x13,
0x24, 0x43, 0xfc, 0x3f, 0x4c, 0x58, 0x67, 0xe8,
};
const char B58_ACC0IDX0[] = "2Mww8dCYPUpKHofjgcXcBCEGmniw9CoaiD2";
bool b;
uint8_t extkey_data[BTC_SZ_EXTKEY];
char extkey_xaddr[BTC_SZ_EXTKEY_ADDR_MAX + 1];
btc_extkey_t extkey;
btc_term();
btc_init(BTC_BLOCK_CHAIN_BTCTEST, false);
b = btc_extkey_read_addr(&extkey, MASTERSEED);
ASSERT_TRUE(b);
b = btc_extkey_bip49_prepare(&extkey, 0, BTC_EXTKEY_BIP_SKIP);
ASSERT_TRUE(b);
btc_extkey_create_data(extkey_data, extkey_xaddr, &extkey);
ASSERT_TRUE(b);
ASSERT_STREQ(XADDR_ACC0, extkey_xaddr);
b = btc_extkey_generate(&extkey, BTC_EXTKEY_PRIV, extkey.depth + 1, 0, extkey.key, NULL, 0);
ASSERT_TRUE(b);
b = btc_extkey_generate(&extkey, BTC_EXTKEY_PRIV, extkey.depth + 1, 0, extkey.key, NULL, 0);
ASSERT_TRUE(b);
ASSERT_TRUE(0 == memcmp(ACC0IDX0, extkey.key, BTC_SZ_PRIVKEY));
//prepareも使っておく
memset(&extkey, 0, sizeof(extkey));
btc_extkey_read_addr(&extkey, MASTERSEED);
b = btc_extkey_bip49_prepare(&extkey, 0, 0);
ASSERT_TRUE(b);
btc_extkey_t akey;
b = btc_extkey_bip_generate(&akey, &extkey, 0);
ASSERT_TRUE(0 == memcmp(ACC0IDX0, akey.key, BTC_SZ_PRIVKEY));
uint8_t pubkey[BTC_SZ_PUBKEY];
btc_keys_priv2pub(pubkey, akey.key);
char addr[BTC_SZ_ADDR_STR_MAX + 1];
b = btc_keys_pub2p2wpkh(addr, pubkey);
ASSERT_TRUE(b);
ASSERT_STREQ(B58_ACC0IDX0, addr);
}
| nayutaco/ptarmigan | btc/tests/testinc_extkey.cpp | C++ | apache-2.0 | 19,346 |
/*
* NamespaceTreeControl implementation.
*
* Copyright 2010 David Hedberg
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdarg.h>
#define COBJMACROS
#define NONAMELESSUNION
#define NONAMELESSSTRUCT
#include "winerror.h"
#include "windef.h"
#include "winbase.h"
#include "winuser.h"
#include "shellapi.h"
#include "wine/list.h"
#include "wine/debug.h"
#include "explorerframe_main.h"
WINE_DEFAULT_DEBUG_CHANNEL(nstc);
typedef struct nstc_root {
IShellItem *psi;
HTREEITEM htreeitem;
SHCONTF enum_flags;
NSTCROOTSTYLE root_style;
IShellItemFilter *pif;
struct list entry;
} nstc_root;
typedef struct {
INameSpaceTreeControl2 INameSpaceTreeControl2_iface;
IOleWindow IOleWindow_iface;
LONG ref;
HWND hwnd_main;
HWND hwnd_tv;
WNDPROC tv_oldwndproc;
NSTCSTYLE style;
NSTCSTYLE2 style2;
struct list roots;
INameSpaceTreeControlEvents *pnstce;
} NSTC2Impl;
static const DWORD unsupported_styles =
NSTCS_SINGLECLICKEXPAND | NSTCS_NOREPLACEOPEN | NSTCS_NOORDERSTREAM | NSTCS_FAVORITESMODE |
NSTCS_EMPTYTEXT | NSTCS_ALLOWJUNCTIONS | NSTCS_SHOWTABSBUTTON | NSTCS_SHOWDELETEBUTTON |
NSTCS_SHOWREFRESHBUTTON | NSTCS_SPRINGEXPAND | NSTCS_RICHTOOLTIP | NSTCS_NOINDENTCHECKS;
static const DWORD unsupported_styles2 =
NSTCS2_INTERRUPTNOTIFICATIONS | NSTCS2_SHOWNULLSPACEMENU | NSTCS2_DISPLAYPADDING |
NSTCS2_DISPLAYPINNEDONLY | NTSCS2_NOSINGLETONAUTOEXPAND | NTSCS2_NEVERINSERTNONENUMERATED;
static inline NSTC2Impl *impl_from_INameSpaceTreeControl2(INameSpaceTreeControl2 *iface)
{
return CONTAINING_RECORD(iface, NSTC2Impl, INameSpaceTreeControl2_iface);
}
static inline NSTC2Impl *impl_from_IOleWindow(IOleWindow *iface)
{
return CONTAINING_RECORD(iface, NSTC2Impl, IOleWindow_iface);
}
/* Forward declarations */
static LRESULT CALLBACK tv_wndproc(HWND hWnd, UINT uMessage, WPARAM wParam, LPARAM lParam);
/*************************************************************************
* NamespaceTree event wrappers
*/
static HRESULT events_OnGetDefaultIconIndex(NSTC2Impl *This, IShellItem *psi,
int *piDefaultIcon, int *piOpenIcon)
{
HRESULT ret;
LONG refcount;
if(!This->pnstce) return E_NOTIMPL;
refcount = IShellItem_AddRef(psi);
ret = INameSpaceTreeControlEvents_OnGetDefaultIconIndex(This->pnstce, psi, piDefaultIcon, piOpenIcon);
if(IShellItem_Release(psi) < refcount - 1)
ERR("ShellItem was released by client - please file a bug.\n");
return ret;
}
static HRESULT events_OnItemAdded(NSTC2Impl *This, IShellItem *psi, BOOL fIsRoot)
{
HRESULT ret;
LONG refcount;
if(!This->pnstce) return S_OK;
refcount = IShellItem_AddRef(psi);
ret = INameSpaceTreeControlEvents_OnItemAdded(This->pnstce, psi, fIsRoot);
if(IShellItem_Release(psi) < refcount - 1)
ERR("ShellItem was released by client - please file a bug.\n");
return ret;
}
static HRESULT events_OnItemDeleted(NSTC2Impl *This, IShellItem *psi, BOOL fIsRoot)
{
HRESULT ret;
LONG refcount;
if(!This->pnstce) return S_OK;
refcount = IShellItem_AddRef(psi);
ret = INameSpaceTreeControlEvents_OnItemDeleted(This->pnstce, psi, fIsRoot);
if(IShellItem_Release(psi) < refcount - 1)
ERR("ShellItem was released by client - please file a bug.\n");
return ret;
}
static HRESULT events_OnBeforeExpand(NSTC2Impl *This, IShellItem *psi)
{
HRESULT ret;
LONG refcount;
if(!This->pnstce) return S_OK;
refcount = IShellItem_AddRef(psi);
ret = INameSpaceTreeControlEvents_OnBeforeExpand(This->pnstce, psi);
if(IShellItem_Release(psi) < refcount - 1)
ERR("ShellItem was released by client - please file a bug.\n");
return ret;
}
static HRESULT events_OnAfterExpand(NSTC2Impl *This, IShellItem *psi)
{
HRESULT ret;
LONG refcount;
if(!This->pnstce) return S_OK;
refcount = IShellItem_AddRef(psi);
ret = INameSpaceTreeControlEvents_OnAfterExpand(This->pnstce, psi);
if(IShellItem_Release(psi) < refcount - 1)
ERR("ShellItem was released by client - please file a bug.\n");
return ret;
}
static HRESULT events_OnItemClick(NSTC2Impl *This, IShellItem *psi,
NSTCEHITTEST nstceHitTest, NSTCECLICKTYPE nstceClickType)
{
HRESULT ret;
LONG refcount;
if(!This->pnstce) return S_OK;
refcount = IShellItem_AddRef(psi);
ret = INameSpaceTreeControlEvents_OnItemClick(This->pnstce, psi, nstceHitTest, nstceClickType);
if(IShellItem_Release(psi) < refcount - 1)
ERR("ShellItem was released by client - please file a bug.\n");
return ret;
}
static HRESULT events_OnSelectionChanged(NSTC2Impl *This, IShellItemArray *psia)
{
if(!This->pnstce) return S_OK;
return INameSpaceTreeControlEvents_OnSelectionChanged(This->pnstce, psia);
}
static HRESULT events_OnKeyboardInput(NSTC2Impl *This, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if(!This->pnstce) return S_OK;
return INameSpaceTreeControlEvents_OnKeyboardInput(This->pnstce, uMsg, wParam, lParam);
}
/*************************************************************************
* NamespaceTree helper functions
*/
static DWORD treeview_style_from_nstcs(NSTC2Impl *This, NSTCSTYLE nstcs,
NSTCSTYLE nstcs_mask, DWORD *new_style)
{
DWORD old_style, tv_mask = 0;
TRACE("%p, %x, %x, %p\n", This, nstcs, nstcs_mask, new_style);
if(This->hwnd_tv)
old_style = GetWindowLongPtrW(This->hwnd_tv, GWL_STYLE);
else
old_style = /* The default */
WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
WS_TABSTOP | TVS_NOHSCROLL | TVS_NONEVENHEIGHT | TVS_INFOTIP |
TVS_EDITLABELS | TVS_TRACKSELECT;
if(nstcs_mask & NSTCS_HASEXPANDOS) tv_mask |= TVS_HASBUTTONS;
if(nstcs_mask & NSTCS_HASLINES) tv_mask |= TVS_HASLINES;
if(nstcs_mask & NSTCS_FULLROWSELECT) tv_mask |= TVS_FULLROWSELECT;
if(nstcs_mask & NSTCS_HORIZONTALSCROLL) tv_mask |= TVS_NOHSCROLL;
if(nstcs_mask & NSTCS_ROOTHASEXPANDO) tv_mask |= TVS_LINESATROOT;
if(nstcs_mask & NSTCS_SHOWSELECTIONALWAYS) tv_mask |= TVS_SHOWSELALWAYS;
if(nstcs_mask & NSTCS_NOINFOTIP) tv_mask |= TVS_INFOTIP;
if(nstcs_mask & NSTCS_EVENHEIGHT) tv_mask |= TVS_NONEVENHEIGHT;
if(nstcs_mask & NSTCS_DISABLEDRAGDROP) tv_mask |= TVS_DISABLEDRAGDROP;
if(nstcs_mask & NSTCS_NOEDITLABELS) tv_mask |= TVS_EDITLABELS;
if(nstcs_mask & NSTCS_CHECKBOXES) tv_mask |= TVS_CHECKBOXES;
*new_style = 0;
if(nstcs & NSTCS_HASEXPANDOS) *new_style |= TVS_HASBUTTONS;
if(nstcs & NSTCS_HASLINES) *new_style |= TVS_HASLINES;
if(nstcs & NSTCS_FULLROWSELECT) *new_style |= TVS_FULLROWSELECT;
if(!(nstcs & NSTCS_HORIZONTALSCROLL)) *new_style |= TVS_NOHSCROLL;
if(nstcs & NSTCS_ROOTHASEXPANDO) *new_style |= TVS_LINESATROOT;
if(nstcs & NSTCS_SHOWSELECTIONALWAYS) *new_style |= TVS_SHOWSELALWAYS;
if(!(nstcs & NSTCS_NOINFOTIP)) *new_style |= TVS_INFOTIP;
if(!(nstcs & NSTCS_EVENHEIGHT)) *new_style |= TVS_NONEVENHEIGHT;
if(nstcs & NSTCS_DISABLEDRAGDROP) *new_style |= TVS_DISABLEDRAGDROP;
if(!(nstcs & NSTCS_NOEDITLABELS)) *new_style |= TVS_EDITLABELS;
if(nstcs & NSTCS_CHECKBOXES) *new_style |= TVS_CHECKBOXES;
*new_style = (old_style & ~tv_mask) | (*new_style & tv_mask);
TRACE("old: %08x, new: %08x\n", old_style, *new_style);
return old_style^*new_style;
}
static IShellItem *shellitem_from_treeitem(NSTC2Impl *This, HTREEITEM hitem)
{
TVITEMEXW tvi;
tvi.mask = TVIF_PARAM;
tvi.lParam = 0;
tvi.hItem = hitem;
SendMessageW(This->hwnd_tv, TVM_GETITEMW, 0, (LPARAM)&tvi);
TRACE("ShellItem: %p\n", (void*)tvi.lParam);
return (IShellItem*)tvi.lParam;
}
/* Returns the root that the given treeitem belongs to. */
static nstc_root *root_for_treeitem(NSTC2Impl *This, HTREEITEM hitem)
{
HTREEITEM tmp, hroot = hitem;
nstc_root *root;
/* Work our way up the hierarchy */
for(tmp = hitem; tmp != NULL; hroot = tmp?tmp:hroot)
tmp = (HTREEITEM)SendMessageW(This->hwnd_tv, TVM_GETNEXTITEM, TVGN_PARENT, (LPARAM)hroot);
/* Search through the list of roots for a match */
LIST_FOR_EACH_ENTRY(root, &This->roots, nstc_root, entry)
if(root->htreeitem == hroot)
break;
TRACE("root is %p\n", root);
return root;
}
/* Find a shellitem in the tree, starting from the given node. */
static HTREEITEM search_for_shellitem(NSTC2Impl *This, HTREEITEM node,
IShellItem *psi)
{
IShellItem *psi_node;
HTREEITEM next, result = NULL;
HRESULT hr;
int cmpo;
TRACE("%p, %p, %p\n", This, node, psi);
/* Check this node */
psi_node = shellitem_from_treeitem(This, node);
hr = IShellItem_Compare(psi, psi_node, SICHINT_DISPLAY, &cmpo);
if(hr == S_OK)
return node;
/* Any children? */
next = (HTREEITEM)SendMessageW(This->hwnd_tv, TVM_GETNEXTITEM,
TVGN_CHILD, (LPARAM)node);
if(next)
{
result = search_for_shellitem(This, next, psi);
if(result) return result;
}
/* Try our next sibling. */
next = (HTREEITEM)SendMessageW(This->hwnd_tv, TVM_GETNEXTITEM,
TVGN_NEXT, (LPARAM)node);
if(next)
result = search_for_shellitem(This, next, psi);
return result;
}
static HTREEITEM treeitem_from_shellitem(NSTC2Impl *This, IShellItem *psi)
{
HTREEITEM root;
TRACE("%p, %p\n", This, psi);
root = (HTREEITEM)SendMessageW(This->hwnd_tv, TVM_GETNEXTITEM,
TVGN_ROOT, 0);
if(!root)
return NULL;
return search_for_shellitem(This, root, psi);
}
static int get_icon(LPCITEMIDLIST lpi, UINT extra_flags)
{
SHFILEINFOW sfi;
UINT flags = SHGFI_PIDL | SHGFI_SYSICONINDEX | SHGFI_SMALLICON;
SHGetFileInfoW((LPCWSTR)lpi, 0 ,&sfi, sizeof(SHFILEINFOW), flags | extra_flags);
return sfi.iIcon;
}
/* Insert a shellitem into the given place in the tree and return the
resulting treeitem. */
static HTREEITEM insert_shellitem(NSTC2Impl *This, IShellItem *psi,
HTREEITEM hParent, HTREEITEM hInsertAfter)
{
TVINSERTSTRUCTW tvins;
TVITEMEXW *tvi = &tvins.u.itemex;
HTREEITEM hinserted;
TRACE("%p (%p, %p)\n", psi, hParent, hInsertAfter);
tvi->mask = TVIF_PARAM | TVIF_CHILDREN | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_TEXT;
tvi->cChildren = I_CHILDRENCALLBACK;
tvi->iImage = tvi->iSelectedImage = I_IMAGECALLBACK;
tvi->pszText = LPSTR_TEXTCALLBACKW;
/* Every treeitem contains a pointer to the corresponding ShellItem. */
tvi->lParam = (LPARAM)psi;
tvins.hParent = hParent;
tvins.hInsertAfter = hInsertAfter;
hinserted = (HTREEITEM)SendMessageW(This->hwnd_tv, TVM_INSERTITEMW, 0,
(LPARAM)(LPTVINSERTSTRUCTW)&tvins);
if(hinserted)
IShellItem_AddRef(psi);
return hinserted;
}
/* Enumerates the children of the folder represented by hitem
* according to the settings for the root, and adds them to the
* treeview. Returns the number of children added. */
static UINT fill_sublevel(NSTC2Impl *This, HTREEITEM hitem)
{
IShellItem *psiParent = shellitem_from_treeitem(This, hitem);
nstc_root *root = root_for_treeitem(This, hitem);
LPITEMIDLIST pidl_parent;
IShellFolder *psf;
IEnumIDList *peidl;
UINT added = 0;
HRESULT hr;
hr = SHGetIDListFromObject((IUnknown*)psiParent, &pidl_parent);
if(SUCCEEDED(hr))
{
hr = IShellItem_BindToHandler(psiParent, NULL, &BHID_SFObject, &IID_IShellFolder, (void**)&psf);
if(SUCCEEDED(hr))
{
hr = IShellFolder_EnumObjects(psf, NULL, root->enum_flags, &peidl);
if(SUCCEEDED(hr))
{
LPITEMIDLIST pidl;
IShellItem *psi;
ULONG fetched;
while( S_OK == IEnumIDList_Next(peidl, 1, &pidl, &fetched) )
{
hr = SHCreateShellItem(NULL, psf , pidl, &psi);
ILFree(pidl);
if(SUCCEEDED(hr))
{
if(insert_shellitem(This, psi, hitem, NULL))
{
events_OnItemAdded(This, psi, FALSE);
added++;
}
IShellItem_Release(psi);
}
else
ERR("SHCreateShellItem failed with 0x%08x\n", hr);
}
IEnumIDList_Release(peidl);
}
else
ERR("EnumObjects failed with 0x%08x\n", hr);
IShellFolder_Release(psf);
}
else
ERR("BindToHandler failed with 0x%08x\n", hr);
ILFree(pidl_parent);
}
else
ERR("SHGetIDListFromObject failed with 0x%08x\n", hr);
return added;
}
static HTREEITEM get_selected_treeitem(NSTC2Impl *This)
{
return (HTREEITEM)SendMessageW(This->hwnd_tv, TVM_GETNEXTITEM, TVGN_CARET, 0);
}
static IShellItem *get_selected_shellitem(NSTC2Impl *This)
{
return shellitem_from_treeitem(This, get_selected_treeitem(This));
}
static void collapse_all(NSTC2Impl *This, HTREEITEM node)
{
HTREEITEM next;
/* Collapse this node first, and then first child/next sibling. */
SendMessageW(This->hwnd_tv, TVM_EXPAND, TVE_COLLAPSE, (LPARAM)node);
next = (HTREEITEM)SendMessageW(This->hwnd_tv, TVM_GETNEXTITEM, TVGN_CHILD, (LPARAM)node);
if(next) collapse_all(This, next);
next = (HTREEITEM)SendMessageW(This->hwnd_tv, TVM_GETNEXTITEM, TVGN_NEXT, (LPARAM)node);
if(next) collapse_all(This, next);
}
static HTREEITEM treeitem_from_point(NSTC2Impl *This, const POINT *pt, UINT *hitflag)
{
TVHITTESTINFO tviht;
tviht.pt.x = pt->x;
tviht.pt.y = pt->y;
tviht.hItem = NULL;
SendMessageW(This->hwnd_tv, TVM_HITTEST, 0, (LPARAM)&tviht);
if(hitflag) *hitflag = tviht.flags;
return tviht.hItem;
}
/*************************************************************************
* NamespaceTree window functions
*/
static LRESULT create_namespacetree(HWND hWnd, CREATESTRUCTW *crs)
{
NSTC2Impl *This = crs->lpCreateParams;
HIMAGELIST ShellSmallIconList;
DWORD treeview_style, treeview_ex_style;
TRACE("%p (%p)\n", This, crs);
SetWindowLongPtrW(hWnd, GWLP_USERDATA, (LPARAM)This);
This->hwnd_main = hWnd;
treeview_style_from_nstcs(This, This->style, 0xFFFFFFFF, &treeview_style);
This->hwnd_tv = CreateWindowExW(0, WC_TREEVIEWW, NULL, treeview_style,
0, 0, crs->cx, crs->cy,
hWnd, NULL, explorerframe_hinstance, NULL);
if(!This->hwnd_tv)
{
ERR("Failed to create treeview!\n");
return HRESULT_FROM_WIN32(GetLastError());
}
treeview_ex_style = TVS_EX_DRAWIMAGEASYNC | TVS_EX_RICHTOOLTIP |
TVS_EX_DOUBLEBUFFER | TVS_EX_NOSINGLECOLLAPSE;
if(This->style & NSTCS_AUTOHSCROLL)
treeview_ex_style |= TVS_EX_AUTOHSCROLL;
if(This->style & NSTCS_FADEINOUTEXPANDOS)
treeview_ex_style |= TVS_EX_FADEINOUTEXPANDOS;
if(This->style & NSTCS_PARTIALCHECKBOXES)
treeview_ex_style |= TVS_EX_PARTIALCHECKBOXES;
if(This->style & NSTCS_EXCLUSIONCHECKBOXES)
treeview_ex_style |= TVS_EX_EXCLUSIONCHECKBOXES;
if(This->style & NSTCS_DIMMEDCHECKBOXES)
treeview_ex_style |= TVS_EX_DIMMEDCHECKBOXES;
SendMessageW(This->hwnd_tv, TVM_SETEXTENDEDSTYLE, treeview_ex_style, 0xffff);
if(Shell_GetImageLists(NULL, &ShellSmallIconList))
{
SendMessageW(This->hwnd_tv, TVM_SETIMAGELIST,
(WPARAM)TVSIL_NORMAL, (LPARAM)ShellSmallIconList);
}
else
{
ERR("Failed to get the System Image List.\n");
}
INameSpaceTreeControl2_AddRef(&This->INameSpaceTreeControl2_iface);
/* Subclass the treeview to get the keybord events. */
This->tv_oldwndproc = (WNDPROC)SetWindowLongPtrW(This->hwnd_tv, GWLP_WNDPROC,
(ULONG_PTR)tv_wndproc);
if(This->tv_oldwndproc)
SetPropA(This->hwnd_tv, "PROP_THIS", This);
return TRUE;
}
static LRESULT resize_namespacetree(NSTC2Impl *This)
{
RECT rc;
TRACE("%p\n", This);
GetClientRect(This->hwnd_main, &rc);
MoveWindow(This->hwnd_tv, 0, 0, rc.right-rc.left, rc.bottom-rc.top, TRUE);
return TRUE;
}
static LRESULT destroy_namespacetree(NSTC2Impl *This)
{
TRACE("%p\n", This);
/* Undo the subclassing */
if(This->tv_oldwndproc)
{
SetWindowLongPtrW(This->hwnd_tv, GWLP_WNDPROC, (ULONG_PTR)This->tv_oldwndproc);
RemovePropA(This->hwnd_tv, "PROP_THIS");
}
INameSpaceTreeControl2_RemoveAllRoots(&This->INameSpaceTreeControl2_iface);
/* This reference was added in create_namespacetree */
INameSpaceTreeControl2_Release(&This->INameSpaceTreeControl2_iface);
return TRUE;
}
static LRESULT on_tvn_deleteitemw(NSTC2Impl *This, LPARAM lParam)
{
NMTREEVIEWW *nmtv = (NMTREEVIEWW*)lParam;
TRACE("%p\n", This);
IShellItem_Release((IShellItem*)nmtv->itemOld.lParam);
return TRUE;
}
static LRESULT on_tvn_getdispinfow(NSTC2Impl *This, LPARAM lParam)
{
NMTVDISPINFOW *dispinfo = (NMTVDISPINFOW*)lParam;
TVITEMEXW *item = (TVITEMEXW*)&dispinfo->item;
IShellItem *psi = shellitem_from_treeitem(This, item->hItem);
HRESULT hr;
TRACE("%p, %p (mask: %x)\n", This, dispinfo, item->mask);
if(item->mask & TVIF_CHILDREN)
{
SFGAOF sfgao;
hr = IShellItem_GetAttributes(psi, SFGAO_HASSUBFOLDER, &sfgao);
if(SUCCEEDED(hr))
item->cChildren = (sfgao & SFGAO_HASSUBFOLDER)?1:0;
else
item->cChildren = 1;
item->mask |= TVIF_DI_SETITEM;
}
if(item->mask & (TVIF_IMAGE|TVIF_SELECTEDIMAGE))
{
LPITEMIDLIST pidl;
hr = events_OnGetDefaultIconIndex(This, psi, &item->iImage, &item->iSelectedImage);
if(FAILED(hr))
{
hr = SHGetIDListFromObject((IUnknown*)psi, &pidl);
if(SUCCEEDED(hr))
{
item->iImage = item->iSelectedImage = get_icon(pidl, 0);
item->mask |= TVIF_DI_SETITEM;
ILFree(pidl);
}
else
ERR("Failed to get IDList (%08x).\n", hr);
}
}
if(item->mask & TVIF_TEXT)
{
LPWSTR display_name;
hr = IShellItem_GetDisplayName(psi, SIGDN_NORMALDISPLAY, &display_name);
if(SUCCEEDED(hr))
{
lstrcpynW(item->pszText, display_name, MAX_PATH);
item->mask |= TVIF_DI_SETITEM;
CoTaskMemFree(display_name);
}
else
ERR("Failed to get display name (%08x).\n", hr);
}
return TRUE;
}
static BOOL treenode_has_subfolders(NSTC2Impl *This, HTREEITEM node)
{
return SendMessageW(This->hwnd_tv, TVM_GETNEXTITEM, TVGN_CHILD, (LPARAM)node);
}
static LRESULT on_tvn_itemexpandingw(NSTC2Impl *This, LPARAM lParam)
{
NMTREEVIEWW *nmtv = (NMTREEVIEWW*)lParam;
IShellItem *psi;
TRACE("%p\n", This);
psi = shellitem_from_treeitem(This, nmtv->itemNew.hItem);
events_OnBeforeExpand(This, psi);
if(!treenode_has_subfolders(This, nmtv->itemNew.hItem))
{
/* The node has no children, try to find some */
if(!fill_sublevel(This, nmtv->itemNew.hItem))
{
TVITEMEXW tvi;
/* Failed to enumerate any children, remove the expando
* (if any). */
tvi.hItem = nmtv->itemNew.hItem;
tvi.mask = TVIF_CHILDREN;
tvi.cChildren = 0;
SendMessageW(This->hwnd_tv, TVM_SETITEMW, 0, (LPARAM)&tvi);
return TRUE;
}
}
return FALSE;
}
static LRESULT on_tvn_itemexpandedw(NSTC2Impl *This, LPARAM lParam)
{
NMTREEVIEWW *nmtv = (NMTREEVIEWW*)lParam;
IShellItem *psi;
TRACE("%p\n", This);
psi = shellitem_from_treeitem(This, nmtv->itemNew.hItem);
events_OnAfterExpand(This, psi);
return TRUE;
}
static LRESULT on_tvn_selchangedw(NSTC2Impl *This, LPARAM lParam)
{
NMTREEVIEWW *nmtv = (NMTREEVIEWW*)lParam;
IShellItemArray *psia;
IShellItem *psi;
HRESULT hr;
TRACE("%p\n", This);
/* Note: Only supports one selected item. */
psi = shellitem_from_treeitem(This, nmtv->itemNew.hItem);
hr = SHCreateShellItemArrayFromShellItem(psi, &IID_IShellItemArray, (void**)&psia);
if(SUCCEEDED(hr))
{
events_OnSelectionChanged(This, psia);
IShellItemArray_Release(psia);
}
return TRUE;
}
static LRESULT on_nm_click(NSTC2Impl *This, NMHDR *nmhdr)
{
TVHITTESTINFO tvhit;
IShellItem *psi;
HRESULT hr;
TRACE("%p (%p)\n", This, nmhdr);
GetCursorPos(&tvhit.pt);
ScreenToClient(This->hwnd_tv, &tvhit.pt);
SendMessageW(This->hwnd_tv, TVM_HITTEST, 0, (LPARAM)&tvhit);
if(tvhit.flags & (TVHT_NOWHERE|TVHT_ABOVE|TVHT_BELOW))
return TRUE;
/* TVHT_ maps onto the corresponding NSTCEHT_ */
psi = shellitem_from_treeitem(This, tvhit.hItem);
hr = events_OnItemClick(This, psi, tvhit.flags, NSTCECT_LBUTTON);
/* The expando should not be expanded unless
* double-clicked. */
if(tvhit.flags == TVHT_ONITEMBUTTON)
return TRUE;
if(SUCCEEDED(hr))
return FALSE;
else
return TRUE;
}
static LRESULT on_wm_mbuttonup(NSTC2Impl *This, WPARAM wParam, LPARAM lParam)
{
TVHITTESTINFO tvhit;
IShellItem *psi;
HRESULT hr;
TRACE("%p (%lx, %lx)\n", This, wParam, lParam);
tvhit.pt.x = (int)(short)LOWORD(lParam);
tvhit.pt.y = (int)(short)HIWORD(lParam);
SendMessageW(This->hwnd_tv, TVM_HITTEST, 0, (LPARAM)&tvhit);
/* Seems to generate only ONITEM and ONITEMICON */
if( !(tvhit.flags & (TVHT_ONITEM|TVHT_ONITEMICON)) )
return FALSE;
psi = shellitem_from_treeitem(This, tvhit.hItem);
hr = events_OnItemClick(This, psi, tvhit.flags, NSTCECT_MBUTTON);
if(SUCCEEDED(hr))
return FALSE;
else
return TRUE;
}
static LRESULT on_kbd_event(NSTC2Impl *This, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
IShellItem *psi;
HTREEITEM hitem;
TRACE("%p : %d, %lx, %lx\n", This, uMsg, wParam, lParam);
/* Handled by the client? */
if(FAILED(events_OnKeyboardInput(This, uMsg, wParam, lParam)))
return TRUE;
if(uMsg == WM_KEYDOWN)
{
switch(wParam)
{
case VK_DELETE:
psi = get_selected_shellitem(This);
FIXME("Deletion of file requested (shellitem: %p).\n", psi);
return TRUE;
case VK_F2:
hitem = get_selected_treeitem(This);
SendMessageW(This->hwnd_tv, TVM_EDITLABELW, 0, (LPARAM)hitem);
return TRUE;
}
}
/* Let the TreeView handle the key */
return FALSE;
}
static LRESULT CALLBACK tv_wndproc(HWND hWnd, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
NSTC2Impl *This = (NSTC2Impl*)GetPropA(hWnd, "PROP_THIS");
switch(uMessage) {
case WM_KEYDOWN:
case WM_KEYUP:
case WM_CHAR:
case WM_SYSKEYDOWN:
case WM_SYSKEYUP:
case WM_SYSCHAR:
if(on_kbd_event(This, uMessage, wParam, lParam))
return TRUE;
break;
case WM_MBUTTONUP: return on_wm_mbuttonup(This, wParam, lParam);
}
/* Pass the message on to the treeview */
return CallWindowProcW(This->tv_oldwndproc, hWnd, uMessage, wParam, lParam);
}
static LRESULT CALLBACK NSTC2_WndProc(HWND hWnd, UINT uMessage,
WPARAM wParam, LPARAM lParam)
{
NSTC2Impl *This = (NSTC2Impl*)GetWindowLongPtrW(hWnd, GWLP_USERDATA);
NMHDR *nmhdr;
switch(uMessage)
{
case WM_NCCREATE: return create_namespacetree(hWnd, (CREATESTRUCTW*)lParam);
case WM_SIZE: return resize_namespacetree(This);
case WM_DESTROY: return destroy_namespacetree(This);
case WM_NOTIFY:
nmhdr = (NMHDR*)lParam;
switch(nmhdr->code)
{
case NM_CLICK: return on_nm_click(This, nmhdr);
case TVN_DELETEITEMW: return on_tvn_deleteitemw(This, lParam);
case TVN_GETDISPINFOW: return on_tvn_getdispinfow(This, lParam);
case TVN_ITEMEXPANDINGW: return on_tvn_itemexpandingw(This, lParam);
case TVN_ITEMEXPANDEDW: return on_tvn_itemexpandedw(This, lParam);
case TVN_SELCHANGEDW: return on_tvn_selchangedw(This, lParam);
default: break;
}
break;
default: return DefWindowProcW(hWnd, uMessage, wParam, lParam);
}
return 0;
}
/**************************************************************************
* INameSpaceTreeControl2 Implementation
*/
static HRESULT WINAPI NSTC2_fnQueryInterface(INameSpaceTreeControl2* iface,
REFIID riid,
void **ppvObject)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
TRACE("%p (%s, %p)\n", This, debugstr_guid(riid), ppvObject);
*ppvObject = NULL;
if(IsEqualIID(riid, &IID_INameSpaceTreeControl2) ||
IsEqualIID(riid, &IID_INameSpaceTreeControl) ||
IsEqualIID(riid, &IID_IUnknown))
{
*ppvObject = This;
}
else if(IsEqualIID(riid, &IID_IOleWindow))
{
*ppvObject = &This->IOleWindow_iface;
}
if(*ppvObject)
{
IUnknown_AddRef((IUnknown*)*ppvObject);
return S_OK;
}
return E_NOINTERFACE;
}
static ULONG WINAPI NSTC2_fnAddRef(INameSpaceTreeControl2* iface)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
LONG ref = InterlockedIncrement(&This->ref);
TRACE("%p - ref %d\n", This, ref);
return ref;
}
static ULONG WINAPI NSTC2_fnRelease(INameSpaceTreeControl2* iface)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
LONG ref = InterlockedDecrement(&This->ref);
TRACE("%p - ref: %d\n", This, ref);
if(!ref)
{
TRACE("Freeing.\n");
HeapFree(GetProcessHeap(), 0, This);
EFRAME_UnlockModule();
return 0;
}
return ref;
}
static HRESULT WINAPI NSTC2_fnInitialize(INameSpaceTreeControl2* iface,
HWND hwndParent,
RECT *prc,
NSTCSTYLE nstcsFlags)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
WNDCLASSW wc;
DWORD window_style, window_ex_style;
INITCOMMONCONTROLSEX icex;
RECT rc;
static const WCHAR NSTC2_CLASS_NAME[] =
{'N','a','m','e','s','p','a','c','e','T','r','e','e',
'C','o','n','t','r','o','l',0};
TRACE("%p (%p, %p, %x)\n", This, hwndParent, prc, nstcsFlags);
if(nstcsFlags & unsupported_styles)
FIXME("0x%08x contains the unsupported style(s) 0x%08x\n",
nstcsFlags, nstcsFlags & unsupported_styles);
This->style = nstcsFlags;
icex.dwSize = sizeof( icex );
icex.dwICC = ICC_TREEVIEW_CLASSES;
InitCommonControlsEx( &icex );
if(!GetClassInfoW(explorerframe_hinstance, NSTC2_CLASS_NAME, &wc))
{
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = NSTC2_WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = explorerframe_hinstance;
wc.hIcon = 0;
wc.hCursor = LoadCursorW(0, (LPWSTR)IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = NSTC2_CLASS_NAME;
if (!RegisterClassW(&wc)) return E_FAIL;
}
/* NSTCS_TABSTOP and NSTCS_BORDER affects the host window */
window_style = WS_VISIBLE | WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS |
(nstcsFlags & NSTCS_BORDER ? WS_BORDER : 0);
window_ex_style = nstcsFlags & NSTCS_TABSTOP ? WS_EX_CONTROLPARENT : 0;
if(prc)
CopyRect(&rc, prc);
else
rc.left = rc.right = rc.top = rc.bottom = 0;
This->hwnd_main = CreateWindowExW(window_ex_style, NSTC2_CLASS_NAME, NULL, window_style,
rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top,
hwndParent, 0, explorerframe_hinstance, This);
if(!This->hwnd_main)
{
ERR("Failed to create the window.\n");
return HRESULT_FROM_WIN32(GetLastError());
}
return S_OK;
}
static HRESULT WINAPI NSTC2_fnTreeAdvise(INameSpaceTreeControl2* iface,
IUnknown *punk,
DWORD *pdwCookie)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
HRESULT hr;
TRACE("%p (%p, %p)\n", This, punk, pdwCookie);
*pdwCookie = 0;
/* Only one client supported */
if(This->pnstce)
return E_FAIL;
hr = IUnknown_QueryInterface(punk, &IID_INameSpaceTreeControlEvents,(void**)&This->pnstce);
if(SUCCEEDED(hr))
{
*pdwCookie = 1;
return hr;
}
return E_FAIL;
}
static HRESULT WINAPI NSTC2_fnTreeUnadvise(INameSpaceTreeControl2* iface,
DWORD dwCookie)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
TRACE("%p (%x)\n", This, dwCookie);
/* The cookie is ignored. */
if(This->pnstce)
{
INameSpaceTreeControlEvents_Release(This->pnstce);
This->pnstce = NULL;
}
return S_OK;
}
static HRESULT WINAPI NSTC2_fnInsertRoot(INameSpaceTreeControl2* iface,
int iIndex,
IShellItem *psiRoot,
SHCONTF grfEnumFlags,
NSTCROOTSTYLE grfRootStyle,
IShellItemFilter *pif)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
nstc_root *new_root;
struct list *add_after_entry;
HTREEITEM add_after_hitem;
int i;
TRACE("%p, %d, %p, %x, %x, %p\n", This, iIndex, psiRoot, grfEnumFlags, grfRootStyle, pif);
new_root = HeapAlloc(GetProcessHeap(), 0, sizeof(nstc_root));
if(!new_root)
return E_OUTOFMEMORY;
new_root->psi = psiRoot;
new_root->enum_flags = grfEnumFlags;
new_root->root_style = grfRootStyle;
new_root->pif = pif;
/* We want to keep the roots in the internal list and in the
* treeview in the same order. */
add_after_entry = &This->roots;
for(i = 0; i < max(0, iIndex) && list_next(&This->roots, add_after_entry); i++)
add_after_entry = list_next(&This->roots, add_after_entry);
if(add_after_entry == &This->roots)
add_after_hitem = TVI_FIRST;
else
add_after_hitem = LIST_ENTRY(add_after_entry, nstc_root, entry)->htreeitem;
new_root->htreeitem = insert_shellitem(This, psiRoot, TVI_ROOT, add_after_hitem);
if(!new_root->htreeitem)
{
WARN("Failed to add the root.\n");
HeapFree(GetProcessHeap(), 0, new_root);
return E_FAIL;
}
list_add_after(add_after_entry, &new_root->entry);
events_OnItemAdded(This, psiRoot, TRUE);
if(grfRootStyle & NSTCRS_HIDDEN)
{
TVITEMEXW tvi;
tvi.mask = TVIF_STATEEX;
tvi.uStateEx = TVIS_EX_FLAT;
tvi.hItem = new_root->htreeitem;
SendMessageW(This->hwnd_tv, TVM_SETITEMW, 0, (LPARAM)&tvi);
}
if(grfRootStyle & NSTCRS_EXPANDED)
SendMessageW(This->hwnd_tv, TVM_EXPAND, TVE_EXPAND,
(LPARAM)new_root->htreeitem);
return S_OK;
}
static HRESULT WINAPI NSTC2_fnAppendRoot(INameSpaceTreeControl2* iface,
IShellItem *psiRoot,
SHCONTF grfEnumFlags,
NSTCROOTSTYLE grfRootStyle,
IShellItemFilter *pif)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
UINT root_count;
TRACE("%p, %p, %x, %x, %p\n",
This, psiRoot, grfEnumFlags, grfRootStyle, pif);
root_count = list_count(&This->roots);
return NSTC2_fnInsertRoot(iface, root_count, psiRoot, grfEnumFlags, grfRootStyle, pif);
}
static HRESULT WINAPI NSTC2_fnRemoveRoot(INameSpaceTreeControl2* iface,
IShellItem *psiRoot)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
nstc_root *cursor, *root = NULL;
TRACE("%p (%p)\n", This, psiRoot);
if(!psiRoot)
return E_NOINTERFACE;
LIST_FOR_EACH_ENTRY(cursor, &This->roots, nstc_root, entry)
{
HRESULT hr;
int order;
hr = IShellItem_Compare(psiRoot, cursor->psi, SICHINT_DISPLAY, &order);
if(hr == S_OK)
{
root = cursor;
break;
}
}
TRACE("root %p\n", root);
if(root)
{
events_OnItemDeleted(This, root->psi, TRUE);
SendMessageW(This->hwnd_tv, TVM_DELETEITEM, 0, (LPARAM)root->htreeitem);
list_remove(&root->entry);
HeapFree(GetProcessHeap(), 0, root);
return S_OK;
}
else
{
WARN("No matching root found.\n");
return E_FAIL;
}
}
static HRESULT WINAPI NSTC2_fnRemoveAllRoots(INameSpaceTreeControl2* iface)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
nstc_root *cur1, *cur2;
UINT removed = 0;
TRACE("%p\n", This);
LIST_FOR_EACH_ENTRY_SAFE(cur1, cur2, &This->roots, nstc_root, entry)
{
NSTC2_fnRemoveRoot(iface, cur1->psi);
removed++;
}
if(removed)
return S_OK;
else
return E_INVALIDARG;
}
static HRESULT WINAPI NSTC2_fnGetRootItems(INameSpaceTreeControl2* iface,
IShellItemArray **ppsiaRootItems)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
IShellFolder *psf;
LPITEMIDLIST *array;
nstc_root *root;
UINT count, i;
HRESULT hr;
TRACE("%p (%p)\n", This, ppsiaRootItems);
count = list_count(&This->roots);
if(!count)
return E_INVALIDARG;
array = HeapAlloc(GetProcessHeap(), 0, sizeof(LPITEMIDLIST)*count);
i = 0;
LIST_FOR_EACH_ENTRY(root, &This->roots, nstc_root, entry)
SHGetIDListFromObject((IUnknown*)root->psi, &array[i++]);
SHGetDesktopFolder(&psf);
hr = SHCreateShellItemArray(NULL, psf, count, (PCUITEMID_CHILD_ARRAY)array,
ppsiaRootItems);
IShellFolder_Release(psf);
for(i = 0; i < count; i++)
ILFree(array[i]);
HeapFree(GetProcessHeap(), 0, array);
return hr;
}
static HRESULT WINAPI NSTC2_fnSetItemState(INameSpaceTreeControl2* iface,
IShellItem *psi,
NSTCITEMSTATE nstcisMask,
NSTCITEMSTATE nstcisFlags)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
TVITEMEXW tvi;
HTREEITEM hitem;
TRACE("%p (%p, %x, %x)\n", This, psi, nstcisMask, nstcisFlags);
hitem = treeitem_from_shellitem(This, psi);
if(!hitem) return E_INVALIDARG;
/* Passing both NSTCIS_SELECTED and NSTCIS_SELECTEDNOEXPAND results
in two TVM_SETITEMW's */
if((nstcisMask&nstcisFlags) & NSTCIS_SELECTED)
{
SendMessageW(This->hwnd_tv, TVM_SELECTITEM, TVGN_CARET, (LPARAM)hitem);
SendMessageW(This->hwnd_tv, TVM_ENSUREVISIBLE, 0, (LPARAM)hitem);
}
if((nstcisMask&nstcisFlags) & NSTCIS_SELECTEDNOEXPAND)
{
SendMessageW(This->hwnd_tv, TVM_SELECTITEM, TVGN_CARET|TVSI_NOSINGLEEXPAND, (LPARAM)hitem);
}
/* If NSTCIS_EXPANDED is among the flags, the mask is ignored. */
if((nstcisMask|nstcisFlags) & NSTCIS_EXPANDED)
{
WPARAM arg = nstcisFlags&NSTCIS_EXPANDED ? TVE_EXPAND:TVE_COLLAPSE;
SendMessageW(This->hwnd_tv, TVM_EXPAND, arg, (LPARAM)hitem);
}
if(nstcisMask & NSTCIS_DISABLED)
tvi.mask = TVIF_STATE | TVIF_STATEEX;
else if( ((nstcisMask^nstcisFlags) & (NSTCIS_SELECTED|NSTCIS_EXPANDED|NSTCIS_SELECTEDNOEXPAND)) ||
((nstcisMask|nstcisFlags) & NSTCIS_BOLD) ||
(nstcisFlags & NSTCIS_DISABLED) )
tvi.mask = TVIF_STATE;
else
tvi.mask = 0;
if(tvi.mask)
{
tvi.stateMask = tvi.state = 0;
tvi.stateMask |= ((nstcisFlags^nstcisMask)&NSTCIS_SELECTED) ? TVIS_SELECTED : 0;
tvi.stateMask |= (nstcisMask|nstcisFlags)&NSTCIS_BOLD ? TVIS_BOLD:0;
tvi.state |= (nstcisMask&nstcisFlags)&NSTCIS_BOLD ? TVIS_BOLD:0;
if((nstcisMask&NSTCIS_EXPANDED)^(nstcisFlags&NSTCIS_EXPANDED))
{
tvi.stateMask = 0;
}
tvi.uStateEx = (nstcisFlags&nstcisMask)&NSTCIS_DISABLED?TVIS_EX_DISABLED:0;
tvi.hItem = hitem;
SendMessageW(This->hwnd_tv, TVM_SETITEMW, 0, (LPARAM)&tvi);
}
return S_OK;
}
static HRESULT WINAPI NSTC2_fnGetItemState(INameSpaceTreeControl2* iface,
IShellItem *psi,
NSTCITEMSTATE nstcisMask,
NSTCITEMSTATE *pnstcisFlags)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
HTREEITEM hitem;
TVITEMEXW tvi;
TRACE("%p (%p, %x, %p)\n", This, psi, nstcisMask, pnstcisFlags);
hitem = treeitem_from_shellitem(This, psi);
if(!hitem)
return E_INVALIDARG;
*pnstcisFlags = 0;
tvi.hItem = hitem;
tvi.mask = TVIF_STATE;
tvi.stateMask = TVIS_SELECTED|TVIS_EXPANDED|TVIS_BOLD;
if(nstcisMask & NSTCIS_DISABLED)
tvi.mask |= TVIF_STATEEX;
SendMessageW(This->hwnd_tv, TVM_GETITEMW, 0, (LPARAM)&tvi);
*pnstcisFlags |= (tvi.state & TVIS_SELECTED)?NSTCIS_SELECTED:0;
*pnstcisFlags |= (tvi.state & TVIS_EXPANDED)?NSTCIS_EXPANDED:0;
*pnstcisFlags |= (tvi.state & TVIS_BOLD)?NSTCIS_BOLD:0;
*pnstcisFlags |= (tvi.uStateEx & TVIS_EX_DISABLED)?NSTCIS_DISABLED:0;
*pnstcisFlags &= nstcisMask;
return S_OK;
}
static HRESULT WINAPI NSTC2_fnGetSelectedItems(INameSpaceTreeControl2* iface,
IShellItemArray **psiaItems)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
IShellItem *psiselected;
HRESULT hr;
TRACE("%p (%p)\n", This, psiaItems);
psiselected = get_selected_shellitem(This);
if(!psiselected)
{
*psiaItems = NULL;
return E_FAIL;
}
hr = SHCreateShellItemArrayFromShellItem(psiselected, &IID_IShellItemArray,
(void**)psiaItems);
return hr;
}
static HRESULT WINAPI NSTC2_fnGetItemCustomState(INameSpaceTreeControl2* iface,
IShellItem *psi,
int *piStateNumber)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
FIXME("stub, %p (%p, %p)\n", This, psi, piStateNumber);
return E_NOTIMPL;
}
static HRESULT WINAPI NSTC2_fnSetItemCustomState(INameSpaceTreeControl2* iface,
IShellItem *psi,
int iStateNumber)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
FIXME("stub, %p (%p, %d)\n", This, psi, iStateNumber);
return E_NOTIMPL;
}
static HRESULT WINAPI NSTC2_fnEnsureItemVisible(INameSpaceTreeControl2* iface,
IShellItem *psi)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
HTREEITEM hitem;
TRACE("%p (%p)\n", This, psi);
hitem = treeitem_from_shellitem(This, psi);
if(hitem)
{
SendMessageW(This->hwnd_tv, TVM_ENSUREVISIBLE, 0, (WPARAM)hitem);
return S_OK;
}
return E_INVALIDARG;
}
static HRESULT WINAPI NSTC2_fnSetTheme(INameSpaceTreeControl2* iface,
LPCWSTR pszTheme)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
FIXME("stub, %p (%p)\n", This, pszTheme);
return E_NOTIMPL;
}
static HRESULT WINAPI NSTC2_fnGetNextItem(INameSpaceTreeControl2* iface,
IShellItem *psi,
NSTCGNI nstcgi,
IShellItem **ppsiNext)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
HTREEITEM hitem, hnext;
UINT tvgn;
TRACE("%p (%p, %x, %p)\n", This, psi, nstcgi, ppsiNext);
if(!ppsiNext) return E_POINTER;
if(!psi) return E_FAIL;
*ppsiNext = NULL;
hitem = treeitem_from_shellitem(This, psi);
if(!hitem)
return E_INVALIDARG;
switch(nstcgi)
{
case NSTCGNI_NEXT: tvgn = TVGN_NEXT; break;
case NSTCGNI_NEXTVISIBLE: tvgn = TVGN_NEXTVISIBLE; break;
case NSTCGNI_PREV: tvgn = TVGN_PREVIOUS; break;
case NSTCGNI_PREVVISIBLE: tvgn = TVGN_PREVIOUSVISIBLE; break;
case NSTCGNI_PARENT: tvgn = TVGN_PARENT; break;
case NSTCGNI_CHILD: tvgn = TVGN_CHILD; break;
case NSTCGNI_FIRSTVISIBLE: tvgn = TVGN_FIRSTVISIBLE; break;
case NSTCGNI_LASTVISIBLE: tvgn = TVGN_LASTVISIBLE; break;
default:
FIXME("Unknown nstcgi value %d\n", nstcgi);
return E_FAIL;
}
hnext = (HTREEITEM)SendMessageW(This->hwnd_tv, TVM_GETNEXTITEM, tvgn, (WPARAM)hitem);
if(hnext)
{
*ppsiNext = shellitem_from_treeitem(This, hnext);
IShellItem_AddRef(*ppsiNext);
return S_OK;
}
return E_FAIL;
}
static HRESULT WINAPI NSTC2_fnHitTest(INameSpaceTreeControl2* iface,
POINT *ppt,
IShellItem **ppsiOut)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
HTREEITEM hitem;
TRACE("%p (%p, %p)\n", This, ppsiOut, ppt);
if(!ppt || !ppsiOut)
return E_POINTER;
*ppsiOut = NULL;
hitem = treeitem_from_point(This, ppt, NULL);
if(hitem)
*ppsiOut = shellitem_from_treeitem(This, hitem);
if(*ppsiOut)
{
IShellItem_AddRef(*ppsiOut);
return S_OK;
}
return S_FALSE;
}
static HRESULT WINAPI NSTC2_fnGetItemRect(INameSpaceTreeControl2* iface,
IShellItem *psi,
RECT *prect)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
HTREEITEM hitem;
TRACE("%p (%p, %p)\n", This, psi, prect);
if(!psi || !prect)
return E_POINTER;
hitem = treeitem_from_shellitem(This, psi);
if(hitem)
{
*(HTREEITEM*)prect = hitem;
if(SendMessageW(This->hwnd_tv, TVM_GETITEMRECT, FALSE, (LPARAM)prect))
{
MapWindowPoints(This->hwnd_tv, HWND_DESKTOP, (POINT*)prect, 2);
return S_OK;
}
}
return E_INVALIDARG;
}
static HRESULT WINAPI NSTC2_fnCollapseAll(INameSpaceTreeControl2* iface)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
nstc_root *root;
TRACE("%p\n", This);
LIST_FOR_EACH_ENTRY(root, &This->roots, nstc_root, entry)
collapse_all(This, root->htreeitem);
return S_OK;
}
static HRESULT WINAPI NSTC2_fnSetControlStyle(INameSpaceTreeControl2* iface,
NSTCSTYLE nstcsMask,
NSTCSTYLE nstcsStyle)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
static const DWORD tv_style_flags =
NSTCS_HASEXPANDOS | NSTCS_HASLINES | NSTCS_FULLROWSELECT |
NSTCS_HORIZONTALSCROLL | NSTCS_ROOTHASEXPANDO |
NSTCS_SHOWSELECTIONALWAYS | NSTCS_NOINFOTIP | NSTCS_EVENHEIGHT |
NSTCS_DISABLEDRAGDROP | NSTCS_NOEDITLABELS | NSTCS_CHECKBOXES;
static const DWORD host_style_flags = NSTCS_TABSTOP | NSTCS_BORDER;
static const DWORD nstc_flags =
NSTCS_SINGLECLICKEXPAND | NSTCS_NOREPLACEOPEN | NSTCS_NOORDERSTREAM |
NSTCS_FAVORITESMODE | NSTCS_EMPTYTEXT | NSTCS_ALLOWJUNCTIONS |
NSTCS_SHOWTABSBUTTON | NSTCS_SHOWDELETEBUTTON | NSTCS_SHOWREFRESHBUTTON;
TRACE("%p (%x, %x)\n", This, nstcsMask, nstcsStyle);
/* Fail if there is an attempt to set an unknown style. */
if(nstcsMask & ~(tv_style_flags | host_style_flags | nstc_flags))
return E_FAIL;
if(nstcsMask & tv_style_flags)
{
DWORD new_style;
treeview_style_from_nstcs(This, nstcsStyle, nstcsMask, &new_style);
SetWindowLongPtrW(This->hwnd_tv, GWL_STYLE, new_style);
}
/* Flags affecting the host window */
if(nstcsMask & NSTCS_BORDER)
{
DWORD new_style = GetWindowLongPtrW(This->hwnd_main, GWL_STYLE);
new_style &= ~WS_BORDER;
new_style |= nstcsStyle & NSTCS_BORDER ? WS_BORDER : 0;
SetWindowLongPtrW(This->hwnd_main, GWL_STYLE, new_style);
}
if(nstcsMask & NSTCS_TABSTOP)
{
DWORD new_style = GetWindowLongPtrW(This->hwnd_main, GWL_EXSTYLE);
new_style &= ~WS_EX_CONTROLPARENT;
new_style |= nstcsStyle & NSTCS_TABSTOP ? WS_EX_CONTROLPARENT : 0;
SetWindowLongPtrW(This->hwnd_main, GWL_EXSTYLE, new_style);
}
if((nstcsStyle & nstcsMask) & unsupported_styles)
FIXME("mask & style (0x%08x) contains unsupported style(s): 0x%08x\n",
(nstcsStyle & nstcsMask),
(nstcsStyle & nstcsMask) & unsupported_styles);
This->style &= ~nstcsMask;
This->style |= (nstcsStyle & nstcsMask);
return S_OK;
}
static HRESULT WINAPI NSTC2_fnGetControlStyle(INameSpaceTreeControl2* iface,
NSTCSTYLE nstcsMask,
NSTCSTYLE *pnstcsStyle)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
TRACE("%p (%x, %p)\n", This, nstcsMask, pnstcsStyle);
*pnstcsStyle = (This->style & nstcsMask);
return S_OK;
}
static HRESULT WINAPI NSTC2_fnSetControlStyle2(INameSpaceTreeControl2* iface,
NSTCSTYLE2 nstcsMask,
NSTCSTYLE2 nstcsStyle)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
TRACE("%p (%x, %x)\n", This, nstcsMask, nstcsStyle);
if((nstcsStyle & nstcsMask) & unsupported_styles2)
FIXME("mask & style (0x%08x) contains unsupported style(s): 0x%08x\n",
(nstcsStyle & nstcsMask),
(nstcsStyle & nstcsMask) & unsupported_styles2);
This->style2 &= ~nstcsMask;
This->style2 |= (nstcsStyle & nstcsMask);
return S_OK;
}
static HRESULT WINAPI NSTC2_fnGetControlStyle2(INameSpaceTreeControl2* iface,
NSTCSTYLE2 nstcsMask,
NSTCSTYLE2 *pnstcsStyle)
{
NSTC2Impl *This = impl_from_INameSpaceTreeControl2(iface);
TRACE("%p (%x, %p)\n", This, nstcsMask, pnstcsStyle);
*pnstcsStyle = (This->style2 & nstcsMask);
return S_OK;
}
static const INameSpaceTreeControl2Vtbl vt_INameSpaceTreeControl2 = {
NSTC2_fnQueryInterface,
NSTC2_fnAddRef,
NSTC2_fnRelease,
NSTC2_fnInitialize,
NSTC2_fnTreeAdvise,
NSTC2_fnTreeUnadvise,
NSTC2_fnAppendRoot,
NSTC2_fnInsertRoot,
NSTC2_fnRemoveRoot,
NSTC2_fnRemoveAllRoots,
NSTC2_fnGetRootItems,
NSTC2_fnSetItemState,
NSTC2_fnGetItemState,
NSTC2_fnGetSelectedItems,
NSTC2_fnGetItemCustomState,
NSTC2_fnSetItemCustomState,
NSTC2_fnEnsureItemVisible,
NSTC2_fnSetTheme,
NSTC2_fnGetNextItem,
NSTC2_fnHitTest,
NSTC2_fnGetItemRect,
NSTC2_fnCollapseAll,
NSTC2_fnSetControlStyle,
NSTC2_fnGetControlStyle,
NSTC2_fnSetControlStyle2,
NSTC2_fnGetControlStyle2
};
/**************************************************************************
* IOleWindow Implementation
*/
static HRESULT WINAPI IOW_fnQueryInterface(IOleWindow *iface, REFIID riid, void **ppvObject)
{
NSTC2Impl *This = impl_from_IOleWindow(iface);
TRACE("%p\n", This);
return NSTC2_fnQueryInterface(&This->INameSpaceTreeControl2_iface, riid, ppvObject);
}
static ULONG WINAPI IOW_fnAddRef(IOleWindow *iface)
{
NSTC2Impl *This = impl_from_IOleWindow(iface);
TRACE("%p\n", This);
return NSTC2_fnAddRef(&This->INameSpaceTreeControl2_iface);
}
static ULONG WINAPI IOW_fnRelease(IOleWindow *iface)
{
NSTC2Impl *This = impl_from_IOleWindow(iface);
TRACE("%p\n", This);
return NSTC2_fnRelease(&This->INameSpaceTreeControl2_iface);
}
static HRESULT WINAPI IOW_fnGetWindow(IOleWindow *iface, HWND *phwnd)
{
NSTC2Impl *This = impl_from_IOleWindow(iface);
TRACE("%p (%p)\n", This, phwnd);
*phwnd = This->hwnd_main;
return S_OK;
}
static HRESULT WINAPI IOW_fnContextSensitiveHelp(IOleWindow *iface, BOOL fEnterMode)
{
NSTC2Impl *This = impl_from_IOleWindow(iface);
TRACE("%p (%d)\n", This, fEnterMode);
/* Not implemented */
return E_NOTIMPL;
}
static const IOleWindowVtbl vt_IOleWindow = {
IOW_fnQueryInterface,
IOW_fnAddRef,
IOW_fnRelease,
IOW_fnGetWindow,
IOW_fnContextSensitiveHelp
};
HRESULT NamespaceTreeControl_Constructor(IUnknown *pUnkOuter, REFIID riid, void **ppv)
{
NSTC2Impl *nstc;
HRESULT ret;
TRACE ("%p %s %p\n", pUnkOuter, debugstr_guid(riid), ppv);
if(!ppv)
return E_POINTER;
if(pUnkOuter)
return CLASS_E_NOAGGREGATION;
EFRAME_LockModule();
nstc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(NSTC2Impl));
nstc->ref = 1;
nstc->INameSpaceTreeControl2_iface.lpVtbl = &vt_INameSpaceTreeControl2;
nstc->IOleWindow_iface.lpVtbl = &vt_IOleWindow;
list_init(&nstc->roots);
ret = INameSpaceTreeControl2_QueryInterface(&nstc->INameSpaceTreeControl2_iface, riid, ppv);
INameSpaceTreeControl2_Release(&nstc->INameSpaceTreeControl2_iface);
TRACE("--(%p)\n", ppv);
return ret;
}
| howard5888/wine | wine-1.7.7/dlls/explorerframe/nstc.c | C | apache-2.0 | 51,137 |
console.warn( "THREE.LineGeometry: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/index.html#manual/en/introduction/Import-via-modules." );
/**
* @author WestLangley / http://github.com/WestLangley
*
*/
THREE.LineGeometry = function () {
THREE.LineSegmentsGeometry.call( this );
this.type = 'LineGeometry';
};
THREE.LineGeometry.prototype = Object.assign( Object.create( THREE.LineSegmentsGeometry.prototype ), {
constructor: THREE.LineGeometry,
isLineGeometry: true,
setPositions: function ( array ) {
// converts [ x1, y1, z1, x2, y2, z2, ... ] to pairs format
var length = array.length - 3;
var points = new Float32Array( 2 * length );
for ( var i = 0; i < length; i += 3 ) {
points[ 2 * i ] = array[ i ];
points[ 2 * i + 1 ] = array[ i + 1 ];
points[ 2 * i + 2 ] = array[ i + 2 ];
points[ 2 * i + 3 ] = array[ i + 3 ];
points[ 2 * i + 4 ] = array[ i + 4 ];
points[ 2 * i + 5 ] = array[ i + 5 ];
}
THREE.LineSegmentsGeometry.prototype.setPositions.call( this, points );
return this;
},
setColors: function ( array ) {
// converts [ r1, g1, b1, r2, g2, b2, ... ] to pairs format
var length = array.length - 3;
var colors = new Float32Array( 2 * length );
for ( var i = 0; i < length; i += 3 ) {
colors[ 2 * i ] = array[ i ];
colors[ 2 * i + 1 ] = array[ i + 1 ];
colors[ 2 * i + 2 ] = array[ i + 2 ];
colors[ 2 * i + 3 ] = array[ i + 3 ];
colors[ 2 * i + 4 ] = array[ i + 4 ];
colors[ 2 * i + 5 ] = array[ i + 5 ];
}
THREE.LineSegmentsGeometry.prototype.setColors.call( this, colors );
return this;
},
fromLine: function ( line ) {
var geometry = line.geometry;
if ( geometry.isGeometry ) {
this.setPositions( geometry.vertices );
} else if ( geometry.isBufferGeometry ) {
this.setPositions( geometry.attributes.position.array ); // assumes non-indexed
}
// set colors, maybe
return this;
},
copy: function ( /* source */ ) {
// todo
return this;
}
} );
| webmaster444/webmaster444.github.io | other/mypointcloud/three/examples/js/lines/LineGeometry.js | JavaScript | apache-2.0 | 2,196 |
from paypalrestsdk import BillingAgreement
import logging
BILLING_AGREEMENT_ID = "I-HT38K76XPMGJ"
try:
billing_agreement = BillingAgreement.find(BILLING_AGREEMENT_ID)
print("Billing Agreement [%s] has state %s" % (billing_agreement.id, billing_agreement.state))
suspend_note = {
"note": "Suspending the agreement"
}
if billing_agreement.suspend(suspend_note):
# Would expect state has changed to Suspended
billing_agreement = BillingAgreement.find(BILLING_AGREEMENT_ID)
print("Billing Agreement [%s] has state %s" % (billing_agreement.id, billing_agreement.state))
reactivate_note = {
"note": "Reactivating the agreement"
}
if billing_agreement.reactivate(reactivate_note):
# Would expect state has changed to Active
billing_agreement = BillingAgreement.find(BILLING_AGREEMENT_ID)
print("Billing Agreement [%s] has state %s" % (billing_agreement.id, billing_agreement.state))
else:
print(billing_agreement.error)
else:
print(billing_agreement.error)
except ResourceNotFound as error:
print("Billing Agreement Not Found")
| stafur/pyTRUST | paypal-rest-api-sdk-python/samples/subscription/billing_agreements/suspend_and_re_activate.py | Python | apache-2.0 | 1,184 |
#
# 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.
"""Unit tests for the utility functions used by the placement API."""
import fixtures
from oslo_middleware import request_id
import webob
from nova.api.openstack.placement import microversion
from nova.api.openstack.placement import util
from nova import objects
from nova import test
from nova.tests import uuidsentinel
class TestCheckAccept(test.NoDBTestCase):
"""Confirm behavior of util.check_accept."""
@staticmethod
@util.check_accept('application/json', 'application/vnd.openstack')
def handler(req):
"""Fake handler to test decorator."""
return True
def test_fail_no_match(self):
req = webob.Request.blank('/')
req.accept = 'text/plain'
error = self.assertRaises(webob.exc.HTTPNotAcceptable,
self.handler, req)
self.assertEqual(
'Only application/json, application/vnd.openstack is provided',
str(error))
def test_fail_complex_no_match(self):
req = webob.Request.blank('/')
req.accept = 'text/html;q=0.9,text/plain,application/vnd.aws;q=0.8'
error = self.assertRaises(webob.exc.HTTPNotAcceptable,
self.handler, req)
self.assertEqual(
'Only application/json, application/vnd.openstack is provided',
str(error))
def test_success_no_accept(self):
req = webob.Request.blank('/')
self.assertTrue(self.handler(req))
def test_success_simple_match(self):
req = webob.Request.blank('/')
req.accept = 'application/json'
self.assertTrue(self.handler(req))
def test_success_complex_any_match(self):
req = webob.Request.blank('/')
req.accept = 'application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
self.assertTrue(self.handler(req))
def test_success_complex_lower_quality_match(self):
req = webob.Request.blank('/')
req.accept = 'application/xml;q=0.9,application/vnd.openstack;q=0.8'
self.assertTrue(self.handler(req))
class TestExtractJSON(test.NoDBTestCase):
# Although the intent of this test class is not to test that
# schemas work, we may as well use a real one to ensure that
# behaviors are what we expect.
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"uuid": {"type": "string", "format": "uuid"}
},
"required": ["name"],
"additionalProperties": False
}
def test_not_json(self):
error = self.assertRaises(webob.exc.HTTPBadRequest,
util.extract_json,
'I am a string',
self.schema)
self.assertIn('Malformed JSON', str(error))
def test_malformed_json(self):
error = self.assertRaises(webob.exc.HTTPBadRequest,
util.extract_json,
'{"my bytes got left behind":}',
self.schema)
self.assertIn('Malformed JSON', str(error))
def test_schema_mismatch(self):
error = self.assertRaises(webob.exc.HTTPBadRequest,
util.extract_json,
'{"a": "b"}',
self.schema)
self.assertIn('JSON does not validate', str(error))
def test_type_invalid(self):
error = self.assertRaises(webob.exc.HTTPBadRequest,
util.extract_json,
'{"name": 1}',
self.schema)
self.assertIn('JSON does not validate', str(error))
def test_format_checker(self):
error = self.assertRaises(webob.exc.HTTPBadRequest,
util.extract_json,
'{"name": "hello", "uuid": "not a uuid"}',
self.schema)
self.assertIn('JSON does not validate', str(error))
def test_no_addtional_properties(self):
error = self.assertRaises(webob.exc.HTTPBadRequest,
util.extract_json,
'{"name": "hello", "cow": "moo"}',
self.schema)
self.assertIn('JSON does not validate', str(error))
def test_valid(self):
data = util.extract_json(
'{"name": "cow", '
'"uuid": "%s"}' % uuidsentinel.rp_uuid,
self.schema)
self.assertEqual('cow', data['name'])
self.assertEqual(uuidsentinel.rp_uuid, data['uuid'])
class TestJSONErrorFormatter(test.NoDBTestCase):
def setUp(self):
super(TestJSONErrorFormatter, self).setUp()
self.environ = {}
# TODO(jaypipes): Remove this when we get more than a single version
# in the placement API. The fact that we only had a single version was
# masking a bug in the utils code.
_versions = [
'1.0',
'1.1',
]
mod_str = 'nova.api.openstack.placement.microversion.VERSIONS'
self.useFixture(fixtures.MonkeyPatch(mod_str, _versions))
def test_status_to_int_code(self):
body = ''
status = '404 Not Found'
title = ''
result = util.json_error_formatter(
body, status, title, self.environ)
self.assertEqual(404, result['errors'][0]['status'])
def test_strip_body_tags(self):
body = '<h1>Big Error!</h1>'
status = '400 Bad Request'
title = ''
result = util.json_error_formatter(
body, status, title, self.environ)
self.assertEqual('Big Error!', result['errors'][0]['detail'])
def test_request_id_presence(self):
body = ''
status = '400 Bad Request'
title = ''
# no request id in environ, none in error
result = util.json_error_formatter(
body, status, title, self.environ)
self.assertNotIn('request_id', result['errors'][0])
# request id in environ, request id in error
self.environ[request_id.ENV_REQUEST_ID] = 'stub-id'
result = util.json_error_formatter(
body, status, title, self.environ)
self.assertEqual('stub-id', result['errors'][0]['request_id'])
def test_microversion_406_handling(self):
body = ''
status = '400 Bad Request'
title = ''
# Not a 406, no version info required.
result = util.json_error_formatter(
body, status, title, self.environ)
self.assertNotIn('max_version', result['errors'][0])
self.assertNotIn('min_version', result['errors'][0])
# A 406 but not because of microversions (microversion
# parsing was successful), no version info
# required.
status = '406 Not Acceptable'
version_obj = microversion.parse_version_string('2.3')
self.environ[microversion.MICROVERSION_ENVIRON] = version_obj
result = util.json_error_formatter(
body, status, title, self.environ)
self.assertNotIn('max_version', result['errors'][0])
self.assertNotIn('min_version', result['errors'][0])
# Microversion parsing failed, status is 406, send version info.
del self.environ[microversion.MICROVERSION_ENVIRON]
result = util.json_error_formatter(
body, status, title, self.environ)
self.assertEqual(microversion.max_version_string(),
result['errors'][0]['max_version'])
self.assertEqual(microversion.min_version_string(),
result['errors'][0]['min_version'])
class TestRequireContent(test.NoDBTestCase):
"""Confirm behavior of util.require_accept."""
@staticmethod
@util.require_content('application/json')
def handler(req):
"""Fake handler to test decorator."""
return True
def test_fail_no_content_type(self):
req = webob.Request.blank('/')
error = self.assertRaises(webob.exc.HTTPUnsupportedMediaType,
self.handler, req)
self.assertEqual(
'The media type None is not supported, use application/json',
str(error))
def test_fail_wrong_content_type(self):
req = webob.Request.blank('/')
req.content_type = 'text/plain'
error = self.assertRaises(webob.exc.HTTPUnsupportedMediaType,
self.handler, req)
self.assertEqual(
'The media type text/plain is not supported, use application/json',
str(error))
def test_success_content_type(self):
req = webob.Request.blank('/')
req.content_type = 'application/json'
self.assertTrue(self.handler(req))
class TestPlacementURLs(test.NoDBTestCase):
def setUp(self):
super(TestPlacementURLs, self).setUp()
self.resource_provider = objects.ResourceProvider(
name=uuidsentinel.rp_name,
uuid=uuidsentinel.rp_uuid)
def test_resource_provider_url(self):
environ = {}
expected_url = '/resource_providers/%s' % uuidsentinel.rp_uuid
self.assertEqual(expected_url, util.resource_provider_url(
environ, self.resource_provider))
def test_resource_provider_url_prefix(self):
# SCRIPT_NAME represents the mount point of a WSGI
# application when it is hosted at a path/prefix.
environ = {'SCRIPT_NAME': '/placement'}
expected_url = ('/placement/resource_providers/%s'
% uuidsentinel.rp_uuid)
self.assertEqual(expected_url, util.resource_provider_url(
environ, self.resource_provider))
def test_inventories_url(self):
environ = {}
expected_url = ('/resource_providers/%s/inventories'
% uuidsentinel.rp_uuid)
self.assertEqual(expected_url, util.inventory_url(
environ, self.resource_provider))
def test_inventory_url(self):
resource_class = 'DISK_GB'
environ = {}
expected_url = ('/resource_providers/%s/inventories/%s'
% (uuidsentinel.rp_uuid, resource_class))
self.assertEqual(expected_url, util.inventory_url(
environ, self.resource_provider, resource_class))
| sebrandon1/nova | nova/tests/unit/api/openstack/placement/test_util.py | Python | apache-2.0 | 10,993 |
<?php
include_once("config.php");
class CQueryManager
{
private $db_link_id;
public function __construct($database)
{
// Server Name, UserName, Password, Database Name
$this->db_link_id = mysql_connect(CConfig::HOST, CConfig::USER_NAME , CConfig::PASSWORD) or
die("Could not connect: " . mysql_error());
mysql_select_db($database, $this->db_link_id) or
die("Can not select database: " . mysql_error());
}
public function __destruct()
{
// Using mysql_close() isn't usually necessary,
// as non-persistent open links are automatically closed at the end of the script's execution.
/*
mysql_close($this->db_link_id) ;
*/
}
/*
* Get CId3Info array for given mp3 id.
*/
public function GetMp3Info($id)
{
$objId3 = new CId3Info(array()) ;
$result = mysql_query("select * from mp3_info where id='".$id."';", $this->db_link_id) or die("Get Mp3 Info Error: ".mysql_error($this->db_link_id)) ;
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$objId3->SetAlbum($row["album"]) ;
$objId3->SetArtist($row["artist"]) ;
$objId3->SetBitRate($row["bitrate"]) ;
$objId3->SetComposer($row["composer"]) ;
$objId3->SetDurationSec($row["duration_sec"]) ;
$objId3->SetFilePath($row["filepath"]) ;
$objId3->SetFileSize($row["filesize"]) ;
$objId3->SetGenre($row["genre"]) ;
$objId3->SetMood($row["mood"]) ;
$objId3->SetID($row["id"]) ;
$objId3->SetLanguage($row["language"]) ;
$objId3->SetLyrics($row["lyrics"]) ;
$objId3->SetPicturizedOn($row["picturizedon"]) ;
$objId3->SetStatus($row["status"]) ;
$objId3->SetTitle($row["title"]) ;
$objId3->SetUserId($row["user_id"]) ;
$objId3->SetYear($row["year"]) ;
}
mysql_free_result($result) ;
return $objId3 ;
}
/*
* Get CId3Info array for given mp3 id.
*/
public function RemoveMp3Entry($id)
{
// First get field's title.
$v_title = $this->GetFieldValue($id, "title") ;
// Get field's filepath as well.
$v_filepath = $this->GetFieldValue($id, "filepath") ;
// Now remove the entry from mp3_info.
// echo("delete from mp3_info where id='".$id."';") ;
mysql_query("delete from mp3_info where id='".$id."';", $this->db_link_id) or die("Remove Mp3 enrty Error: ".mysql_error($this->db_link_id)) ;
if( mysql_affected_rows($this->db_link_id) > 0 )
{
// Remove the entry from mp3_metaphone_info as well.
mysql_query("delete from mp3_metaphone_info where id='".$id."';", $this->db_link_id) ;
// Now remove file from the disk (@ for suppressing error/warning message).
@unlink($v_filepath) ;
}
return $v_title ;
}
/*
* Get CId3Info array for given mp3 id.
*/
public function GetFieldValue($id, $field)
{
$objId3 = new CId3Info(array()) ;
$result = mysql_query("select ".$field." from mp3_info where id='".$id."';", $this->db_link_id) or die("Get Field Value Error: ".mysql_error($this->db_link_id)) ;
$value = "" ;
if( mysql_num_rows($result) > 0 )
{
$row = mysql_fetch_array($result, MYSQL_ASSOC) ;
$value = $row[$field] ;
}
mysql_free_result($result) ;
return $value ;
}
/*
* Insert CId3Info object values into mp3_info.
*/
public function InsertIntoMp3Info(CId3Info $id3info)
{
$id = mysql_escape_string($id3info->GetID()) ;
$filepath = mysql_escape_string($id3info->GetFilePath()) ;
$filesize = mysql_escape_string($id3info->GetFileSize()) ;
$bitrate = mysql_escape_string($id3info->GetBitRate()) ;
$duration_sec = mysql_escape_string($id3info->GetDurationSec()) ;
$language = mysql_escape_string($id3info->GetLanguage()) ;
$status = mysql_escape_string($id3info->GetStatus()) ; // 0 : Private, 1 : Public, 2: Issued Private
$userid = mysql_escape_string($id3info->GetUserId()) ;
$title = mysql_escape_string($id3info->GetTitle()) ;
$artist = mysql_escape_string($id3info->GetArtist()) ;
$album = mysql_escape_string($id3info->GetAlbum()) ;
$lyrics = mysql_escape_string($id3info->GetLyrics()) ;
$year = mysql_escape_string($id3info->GetYear()) ;
$genre = mysql_escape_string($id3info->GetGenre()) ;
$mood = mysql_escape_string($id3info->GetMood()) ;
$composer = mysql_escape_string($id3info->GetComposer()) ;
$picturizedon = mysql_escape_string($id3info->GetPicturizedOn()) ;
$provider = mysql_escape_string($id3info->GetProvider()) ;
// Insert query for mp3_info table.
// echo("insert into mp3_info (id, filepath, filesize, bitrate, duration_sec, status, user_id, title, artist, album, lyrics, year, genre, composer, picturizedon) values ('".$id."', '".$filepath."', '".$filesize."', '".$bitrate."', '".$duration_sec."', '".$status."', '".$userid."', '".$title."', '".$artist."', '".$album."', '".$lyrics."', '".$year."', '".$genre."', '".$composer."', '".$picturizedon."') ; <BR/>") ;
$bResult = mysql_query("insert ignore into mp3_info (id, upload_date, filepath, filesize, bitrate, duration_sec, language, status, user_id, title, artist, album, lyrics, year, genre,mood, composer, picturizedon, provider) values ('".$id."', CURDATE(), '".$filepath."', '".$filesize."', '".$bitrate."', '".$duration_sec."', '".$language."', '".$status."', '".$userid."', '".$title."', '".$artist."', '".$album."', '".$lyrics."', '".$year."', '".$genre."','".$mood."', '".$composer."', '".$picturizedon."', '".$provider."') ;", $this->db_link_id) or die("mp3_info Insert Error: ".mysql_error($this->db_link_id));
// Insert query for mp3_metaphone_info table.
if($bResult)
{
$bResult = mysql_query("insert into mp3_metaphone_info (id, title, artist, album, lyrics, genre, composer, picturizedon) values ('".$id."', '".CUtils::GetMetaphone($title)."', '".CUtils::GetMetaphone($artist)."', '".CUtils::GetMetaphone($album)."', '".CUtils::GetMetaphone($lyrics)."', '".CUtils::GetMetaphone($genre)."','".CUtils::GetMetaphone($composer)."', '".CUtils::GetMetaphone($picturizedon)."') ;", $this->db_link_id) or die("mp3_metaphone_info Insert Error: ".mysql_error($this->db_link_id));
}
return $bResult ;
}
/*
* Update mp3_info table details.
*/
public function UpdateMp3Info(CId3Info $id3info)
{
$id = $id3info->GetID() ;
$language = $id3info->GetLanguage() ;
$title = $id3info->GetTitle() ;
$artist = $id3info->GetArtist() ;
$album = $id3info->GetAlbum() ;
$lyrics = $id3info->GetLyrics() ;
$year = $id3info->GetYear() ;
$genre = $id3info->GetGenre() ;
$mood = $id3info->GetMood() ;
$composer = $id3info->GetComposer() ;
$picturizedon = $id3info->GetPicturizedOn() ;
// Update query for mp3_info table.
// echo("update mp3_info set title='$title', artist='$artist', album='$album', lyrics='$lyrics', year='$year', genre='$genre', composer='$composer', picturizedon='$picturizedon', language='$language,' mood='$mood' where id='$id';<BR/>") ;
$bResult = mysql_query("update mp3_info set title='".$title."', artist='".$artist."', album='".$album."', lyrics='".$lyrics."', year='".$year."', genre='".$genre."', composer='".$composer."', picturizedon='".$picturizedon."', language='".$language."', mood='".$mood. "' where id='".$id."';", $this->db_link_id) or die("mp3_info Update Error: ".mysql_error($this->db_link_id)) ;
if($bResult)
{
$bResult = mysql_query("update mp3_metaphone_info set title='".CUtils::GetMetaphone($title)."', artist='".CUtils::GetMetaphone($artist)."', album='".CUtils::GetMetaphone($album)."', lyrics='".CUtils::GetMetaphone($lyrics)."', genre='".CUtils::GetMetaphone($genre)."', mood='".CUtils::GetMetaphone($mood)."' ,composer='".CUtils::GetMetaphone($composer)."', picturizedon='".CUtils::GetMetaphone($picturizedon)."' where id='".$id."';", $this->db_link_id) or die("mp3_metaphone_info Update Error: ".mysql_error($this->db_link_id));
}
return $bResult ;
}
/*
* Prepare Language options and select passed language.
*/
public function PrepareLangOptions($lang)
{
$result = mysql_query("select * from languages order by language asc;") ;
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if(strcasecmp(@trim($row["language"]), $lang) != 0)
{
printf("<option id=\"lang_%s\" value=\"%s\">%s</option>", $row["language"], $row["language"], $row["language"]);
}
else
{
printf("<option id=\"lang_%s\" value=\"%s\" selected=\"selected\">%s</option>", $row["language"], $row["language"], $row["language"]);
}
}
mysql_free_result($result);
}
/*
* Prepare Genre options and select passed Genre.
*/
public function PrepareGenreOptions($genre)
{
$result = mysql_query("select * from genres order by genre asc;") ;
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if(strcasecmp(@trim($row["genre"]), $genre) != 0)
{
printf("<option id=\"genre_%s\" value=\"%s\">%s</option>", $row["genre"], $row["genre"], $row["genre"]);
}
else
{
printf("<option id=\"genre_%s\" value=\"%s\" selected=\"selected\">%s</option>", $row["genre"], $row["genre"], $row["genre"]);
}
}
mysql_free_result($result);
}
public function PrepareMoodOptions($mood)
{
$result = mysql_query("select * from mood order by mood asc;") ;
//if(strcasecmp($mood,"Unknown")==0)
/*printf("<option value=\"%s\">%s</option>", $row["mood"], $row["mood"]);*/
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if(strcasecmp(@trim($row["mood"]), $mood) != 0)
{
printf("<option id=\"mood_%s\" value=\"%s\">%s</option>", $row["mood"], $row["mood"], $row["mood"]);
}
else
{
printf("<option id=\"mood_%s\" value=\"%s\" selected=\"selected\">%s</option>", $row["mood"], $row["mood"], $row["mood"]);
}
}
mysql_free_result($result);
}
/*
* Prepare Uploaded Mp3 listing for the user_id.
*/
public function PrepareMP3Listing($user_id, $pageno)
{
$count = mysql_query("select count(*) as cnt from mp3_info where user_id='".$user_id."' order by title asc;") ;
$arr = mysql_fetch_array($count, MYSQL_ASSOC);
$row_count = $arr["cnt"];
$this->PreparePaging($pageno,$row_count,"tab_manage_aud_mymp3.php","");
echo("<TABLE BORDER='0'>") ;
echo("<TR BGCOLOR=\"#CCCC99\" ALIGN=\"CENTER\"><TD><B>Index</B></TD><TD><B>Title</B></TD><TD><B>Album</B></TD><TD><B>Artist</B></TD><TD><B>Genre</B></TD><TD><B>Bit Rate</B></TD><TD><B>Duration (min)</B></TD><TD><B>Edit</B></TD><TD><B>Remove</B></TD></TR>") ;
$startlimit = ($pageno -1)* 10;
$endlimit = ($pageno -1)*10 +10;
$result = mysql_query("select * from mp3_info where user_id='".$user_id."' order by title asc limit " .$startlimit. "," . $endlimit . ";");
$i = 0 ;
$index = $startlimit + 1;
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if($i == 0)
{
echo("<TR BGCOLOR=\"#FFFFCC\" ALIGN=\"CENTER\">") ;
$i++ ;
}
else
{
echo("<TR BGCOLOR=\"#FFFF99\" ALIGN=\"CENTER\">") ;
$i-- ;
}
printf("<TD>%d</TD><TD>%s (<A HREF='javascript:;' onClick=\"parent.parent.SR.AddToPlaylistUrl('%s','%s');\">Add
</A>)</TD><TD>%s</TD><TD>%s</TD><TD>%s</TD><TD>%s kbps</TD><TD>%.2f</TD><TD><A HREF=\"tab_manage_aud_edit.php?id=%s&pg=1\">Edit</A></TD><TD><A HREF=\"tab_manage_aud_delete.php?id=%s&pg=1\">Remove</A></TD>", $index, $row["title"], $row["id"], mysql_real_escape_string($row["title"]), $row["album"], $row["artist"], $row["genre"], $row["bitrate"], $row["duration_sec"]/60, $row["id"], $row["id"]) ;
echo("</TR>") ;
$index++ ;
}
echo("</TABLE>") ;
mysql_free_result($result);
}
/*
* Prepare Today's Mp3 upload details.
*/
public function PrepareTodayUploadDetails($user_id,$pageno)
{
$count = mysql_query("select count(*) as cnt from mp3_info where upload_date=CURDATE() AND user_id='".$user_id."' order by title asc;") ;
$arr = mysql_fetch_array($count, MYSQL_ASSOC);
$row_count = $arr["cnt"];
$this->PreparePaging($pageno,$row_count,"tab_manage_aud_upload.php","");
$startlimit = ($pageno -1)*10;
$endlimit = ($pageno -1)*10 +10;
$i = 0 ;
$index = $startlimit + 1;
$result = mysql_query("select * from mp3_info where upload_date=CURDATE() AND user_id='".$user_id."' order by title asc limit " . $startlimit . "," . $endlimit . ";") or die("message" .mysql_error());
if(mysql_num_rows($result) > 0)
{
echo("<TABLE BORDER='0'>") ;
echo("<TR BGCOLOR=\"#CCCC99\" ALIGN=\"CENTER\"><TD><B>Index</B></TD><TD><B>Title</B></TD><TD><B>Album</B></TD><TD><B>Artist</B></TD><TD><B>Genre</B></TD><TD><B>Bit Rate</B></TD><TD><B>Duration (min)</B></TD><TD><B>Edit</B></TD><TD><B>Remove</B></TD></TR>") ;
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if($i == 0)
{
echo("<TR BGCOLOR=\"#FFFFCC\" ALIGN=\"CENTER\">") ;
$i++ ;
}
else
{
echo("<TR BGCOLOR=\"#FFFF99\" ALIGN=\"CENTER\">") ;
$i-- ;
}
printf("<TD>%d</TD><TD>%s (<A HREF='javascript:;' onClick=\"parent.parent.SR.AddToPlaylistUrl('%s','%s');\">Add
</A>)</TD><TD>%s</TD><TD>%s</TD><TD>%s</TD><TD>%s kbps</TD><TD>%.2f</TD><TD><A HREF=\"tab_manage_aud_edit.php?id=%s&pg=2\">Edit</A></TD><TD><A HREF=\"tab_manage_aud_delete.php?id=%s&pg=2\">Remove</A></TD>", $index, $row["title"], $row["id"], mysql_real_escape_string($row["title"]), $row["album"], $row["artist"], $row["genre"], $row["bitrate"], $row["duration_sec"]/60, $row["id"], $row["id"]) ;
echo("</TR>") ;
$index++ ;
}
echo("</TABLE>") ;
}
else
{
echo ("You have not uploaded any songs today :(") ;
}
mysql_free_result($result);
}
/*
* Prepare Today's Mp3 upload summary.
*/
public function PrepareTodayUploadSummary($user_id)
{
$result = mysql_query("select * from mp3_info where upload_date=CURDATE() AND user_id='".$user_id."' order by title asc;") ;
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$filesize += $row["filesize"] ;
}
printf("%.2f MB, Songs: %d", ($filesize/1048576), mysql_num_rows($result)) ;
}
else
{
echo ("You have not uploaded any songs today :(") ;
}
mysql_free_result($result);
}
/*
* Validate mp3_info table entries, if any entry exists whose corresponding file not found then remove the entry.
*/
private function ValidateMp3DBEntries()
{
// Execute search query.
$result = mysql_query("select id, filepath from mp3_info; ", $this->db_link_id) ;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$bResult = file_exists($row["filepath"]);
if( !$bResult )
{
mysql_query("delete from md3_info where id='".$row["id"]."' ;", $this->db_link_id) ;
if(mysql_affected_rows($this->db_link_id) > 0)
{
mysql_query("delete from md3_metaphone_info where id='".$row["id"]."' ;", $this->db_link_id) ;
}
}
}
mysql_free_result($result);
}
/*
* Scan the folder (File System) which contains all mp3 files and delete file which does'nt posses any corresponding entry in DB
*/
private function ValidateMp3FSEntries($dir)
{
$filepath_ary = scandir($dir) ;
/*
echo("<PRE>") ;
print_r($filepath_ary) ;
echo("</PRE>") ;
*/
foreach($filepath_ary as $file)
{
$pos = stripos($file, ".") ;
if($pos === false)
{
// This query will fetch a row from DB.
$result = mysql_query("select id from mp3_info where filepath LIKE '%".$file."%' ; ", $this->db_link_id) ;
if (mysql_num_rows($result) <= 0)
{
//echo("Removing File: ".$dir."/".$file) ;
unlink($dir."/".$file) ;
}
mysql_free_result($result) ;
}
}
}
/*
* Validate all mp3 entries from DB as well as from directory.
*/
public function ValidateMp3Entries($dir)
{
$this->ValidateMp3DBEntries() ;
$this->ValidateMp3FSEntries($dir) ;
}
/*
* Update analytics.top_search table.
*/
function UpdateTopSearch($srchtxt)
{
if(strlen($srchtxt) <=0 )
{
return 0 ;
}
// Server Name, UserName, Password, Database Name
$wordArray = str_word_count($srchtxt, 1, '0123456789');
$i = 0 ;
$srch_meta_txt = "" ;
foreach($wordArray as $word)
{
$word_meta_ary[$i] = metaphone($word);
$srch_meta_txt .= $word_meta_ary[$i];
if(count($wordArray) > $i+1)
{
$srch_meta_txt .= " ";
}
$i++;
}
//echo ($srch_meta_txt) ;
// ----------------------
//Debug Code
// ----------------------
/*echo ("<PRE>") ;
print_r($word_meta_ary) ;
echo ("</PRE>") ;*/
$query = "select meta_val, search_id from top_search where meta_val like '%".$srch_meta_txt."%'";
$fetch_result = mysql_query($query)or die("<BR>query fail: ".mysql_error());
//echo "<BR> result $result";
if (mysql_num_rows($fetch_result)==0)
{
$query = "insert into top_search (search_text,meta_val,count) values ('".$srchtxt."','".$srch_meta_txt."',1)";
$result = mysql_query($query) or die("query fail: ".mysql_error());
}
else
{
$match_result = array();
$i = 0;
while ($row = mysql_fetch_array($fetch_result, MYSQL_ASSOC))
{
$temp_ary = str_word_count($row["meta_val"], 1, '0123456789') ;
if(count($temp_ary) > 0)
{
$match_result[$i] = CUtils::CompWords($temp_ary, $word_meta_ary) ;
$i++;
}
}
$max_result = max($match_result) ;
//echo ($max_result) ;
if($max_result >= 66)
{
// echo ("Test 1 <BR/>") ;
$i = 0;
// - - - - - - - - - - - - - - - - - -
// Don't change the order of calling.
// - - - - - - - - - - - - - - - - - -
foreach($match_result as $result)
{
if($max_result == $result)
{
break;
}
$i++;
}
// echo ("Test 2 <BR/>") ;
mysql_data_seek($fetch_result, $i) ;
$row = mysql_fetch_array($fetch_result, MYSQL_ASSOC) ;
// print_r($row);
if($row)
{
mysql_query("update top_search set count=count+1 where search_id='".$row["search_id"]."'") or die ("Update fail: ".mysql_error());
}
// - - - - - - - - - - - - - - - - - -
}
else
{
$query = "insert into top_search (search_text,meta_val,count) values ('".$srchtxt."','".$srch_meta_txt."',1)";
$fetch_result = mysql_query($query) or die("query fail: ".mysql_error());
}
}
}
public function AddBookmark($user_id, $aud_id)
{
$bResult = 0 ;
$result = mysql_query("select bookmarks from bookmarks where user_id='".$user_id."' ;", $this->db_link_id) ;
if (mysql_num_rows($result) > 0)
{
//echo("Test 1.0<BR/>") ;
// Update bookmarks field for given user.
$row = mysql_fetch_array($result, MYSQL_ASSOC) ;
$bookmarks = $row["bookmarks"] + $aud_id + ";";
mysql_query("update bookmarks set bookmarks=CONCAT(bookmarks,'".$aud_id.";') where user_id='".$user_id."' ;", $this->db_link_id) ;
if(mysql_affected_rows($this->db_link_id) > 0)
{
//echo("Test 2.0<BR/>") ;
$bResult = 1 ;
}
}
else
{
//echo("Test 3.0<BR/>") ;
mysql_query("insert into bookmarks (user_id, bookmarks) values ('".$user_id."', '".$aud_id.";');", $this->db_link_id) ;
if(mysql_affected_rows($this->db_link_id) > 0)
{
//echo("Test 4.0<BR/>") ;
$bResult = 1 ;
}
}
mysql_free_result($result) ;
return $bResult ;
}
public function AddPlaylist($user_id, $pl_name, $comments, $playlist, &$bOverwrite, &$err_msg)
{
$bResult = 1 ;
//echo("Overwrite : ".$bOverwrite." Comparision : ".$check."<BR/>");
if($bOverwrite == 0)
{
//echo("Test 1<BR/>") ;
$result = mysql_query("select name, playlist from playlists where user_id='".$user_id."' ;", $this->db_link_id) ;
if (mysql_num_rows($result) > 0)
{
//echo("Test 2<BR/>") ;
// Check if playlist name already exists.
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
//echo("Test 3<BR/>") ;
if(strcasecmp($row["name"], $pl_name) == 0)
{
//echo("Test 4<BR/>") ;
$bResult = 0 ;
$bOverwrite = 1 ;
$err_msg = "Playlist '".$pl_name."' already exists." ;
break ;
}
}
if($bResult)
{
//echo("Test 5<BR/>") ;
$uuid = CUtils::uuid() ;
$query = sprintf("insert into playlists (playlist_id,user_id,name,playlist,comments) values ('%s','%s',LOWER('%s'),'%s','%s');", $uuid, $user_id, $pl_name, $playlist, $comments) ;
mysql_query($query, $this->db_link_id) ;
}
}
else
{
//echo("Test 6<BR/>") ;
$uuid = CUtils::uuid() ;
$query = sprintf("insert into playlists (playlist_id,user_id,name,playlist,comments) values ('%s','%s',LOWER('%s'),'%s','%s');", $uuid, $user_id, $pl_name, $playlist, $comments);
mysql_query($query, $this->db_link_id) or die("Error: ".mysql_error()) ;
}
mysql_free_result($result) ;
}
else
{
//echo("Test 7<BR/>") ;
$uuid = CUtils::uuid() ;
$query = sprintf("update playlists set playlist='%s',comments='%s' where name=LOWER('%s') AND user_id='%s';", $playlist, $comments, $pl_name, $user_id) ;
mysql_query($query, $this->db_link_id) ;
}
return $bResult ;
}
public function AlignLastWeekPlayCount($id)
{
mysql_query("update mp3_info set last_week_plays=last_week_plays-todays_plays where id='".$aud_id."' ;", $this->db_link_id) ;
}
public function AlignTodaysPlayCount($id)
{
mysql_query("update mp3_info set todays_plays=0 where id='".$aud_id."' AND DAY(last_played) <> DAY(NOW());", $this->db_link_id) ;
}
public function IncreasePlayCount($aud_id)
{
mysql_query("update mp3_info set plays=plays+1, last_week_plays=last_week_plays+1, todays_plays=todays_plays+1 where id='".$aud_id."' ;", $this->db_link_id) ;
}
public function GetDBFileCount()
{
$count = 0;
$result = mysql_query("select count(*) as count from mp3_info;", $this->db_link_id);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$count = $row["count"] ;
}
mysql_free_result($result) ;
return $count ;
}
public function GetDBAlbumCount()
{
$count = 0;
$result = mysql_query("select count(distinct album) as count from mp3_info;", $this->db_link_id);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$count = $row["count"] ;
}
mysql_free_result($result) ;
return $count ;
}
public function GetUserPlayList($user_id, $pageno)
{
$count = mysql_query("select count(*) as cnt from playlists where user_id= '".$user_id."';", $this->db_link_id);
$arr = mysql_fetch_array($count, MYSQL_ASSOC);
$row_count = $arr["cnt"];
$this->PreparePaging($pageno,$row_count,"tab_manage_aud_playlist.php","");
// display hyperlinks
$startlimit = ($pageno -1)* 10;
$endlimit = ($pageno -1)*10 +10;
$result = mysql_query("select * from playlists where user_id= '".$user_id."'limit ".$startlimit . "," .$endlimit. " ;", $this->db_link_id);
if( mysql_num_rows($result) > 0 )
{
echo("<TABLE BORDER='0' WIDTH=\"100%\">\n") ;
echo("<TR BGCOLOR=\"#CCCC99\" ALIGN=\"CENTER\"><TD><B>Index</B></TD><TD><B>Playlist Name</B></TD><TD><B>Comment</B></TD><TD><B>Load</B></TD><TD><B>Remove</B></TD></TR>\n") ;
$i = 0;
$index = 1;
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if($i == 0)
{
echo("<TR BGCOLOR=\"#FFFFCC\" ALIGN=\"CENTER\">") ;
$i++ ;
}
else
{
echo("<TR BGCOLOR=\"#FFFF99\" ALIGN=\"CENTER\">") ;
$i-- ;
}
$pid = $row["playlist_id"] ;
$pname = $row["name"];
$comment = $row["comments"];
if(empty($comment))
{
$comment = "<B>. . .</B>";
}
printf("<TD>%d</TD> <TD><A HREF='tab_manage_aud_playlist_info.php?pid=%s'>%s</A></TD><TD>%s</TD><TD> <INPUT TYPE='button' VALUE =' Load ' ID='APPEND' name='APPEND' OnClick =\"OnLoadPlaylist('%s');\" /></TD><TD><INPUT TYPE=\"button\" VALUE=\"Remove\" OnClick=\"OnRemovePlaylist('%s','%s',%d);\"/></TD></TR>\n", $index,$pid,$pname,$comment,$pid,$pid, $pname, $pageno);
$index++;
}
echo("</TABLE>") ;
}
mysql_free_result($result) ;
}
private function PreparePaging($pageno,$row_count,$href,$pid)
{
if($row_count > 10)
{
$page_count = ceil($row_count/10);
$remainder = $pageno%10;
if($remainder == 0)
{
$remainder++;
}
$startoffset = floor($pageno/10)*$remainder;
$endoffset = floor($pageno/10)*($remainder) + 10;
if($startoffset > 0)
{
$startoffset = ($startoffset + (5 - ($startoffset%5))) ;
$endoffset = ($endoffset + (5 - ($endoffset%5))) ;
}
if($endoffset >= $page_count )
{
$endoffset = $page_count;
}
if($pageno >= $page_count)
{
$pageno = $page_count;
}
if($pageno -1 != $startoffset)
{
printf("<B><A HREF=\"%s?pg=%d&pid=%s\">< Prev</A> ",$href,$pageno-1,$pid);
}
else
{
printf("<B><A >< Prev</A> ");
}
for($i = $startoffset; $i < $endoffset; $i++)
{
if($pageno-1 !=$i)
{
printf("<A HREF=\"%s?pg=%d&pid=%s\">{%d}</A> ",$href,$i+1,$pid, $i+1) ;
}
else
{
printf("<A>%d</A> ",$i+1) ;
}
}
if($pageno != $endoffset)
{
printf(" <A HREF=\"%s?pg=%d&pid=%s\">Next ></A></B></BR>",$href,$pageno+1,$pid);
}
else
{
printf(" <A>Next ></A></B></BR>");
}
}
}
public function PreparePlaylistInfo($playlist_id,$pageno)
{
$playlistresult = mysql_query("select * from playlists where playlist_id= '".$playlist_id."';", $this->db_link_id);
$row = mysql_fetch_array($playlistresult);
printf("<LEGEND> <B>Playlist : %s </B></LEGEND>",$row['name']);
$mp3idarray = explode(";",$row['playlist']);
$numsongs = count($mp3idarray);
$this->PreparePaging($pageno,$numsongs,"tab_manage_aud_playlist_info.php",$playlist_id);
$startlimit = ($pageno -1)* 10;
$endlimit = ($pageno -1)*10 + 10;
echo("<TABLE BORDER='0'>\n") ;
echo("<TR BGCOLOR=\"#CCCC99\" ALIGN=\"CENTER\"><TD><B>Index</B></TD><TD><B>Title</B></TD><TD><B>Album</B></TD><TD><B>Artist</B></TD><TD><B>Genre</B></TD><TD><B>Bit Rate</B></TD><TD><B>Duration (min)</B></TD><TD><B>Remove</B></TD></TR>\n") ;
$i = 0 ;
$index = 1 ;
foreach($mp3idarray as $mp3id)
{
$result = mysql_query("select * from mp3_info where id='".$mp3id."' order by title asc;", $this->db_link_id) or die("Test Error: ".mysql_error($this->db_link_id));
if($index > $startlimit && $index <= $endlimit)
{
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
if($i == 0)
{
echo("<TR BGCOLOR=\"#FFFFCC\" ALIGN=\"CENTER\">") ;
$i++ ;
}
else
{
echo("<TR BGCOLOR=\"#FFFF99\" ALIGN=\"CENTER\">") ;
$i-- ;
}
printf("<TD>%d</TD><TD>%s (<A HREF='javascript:;' onClick=\"parent.parent.SR.AddToPlaylistUrl('%s','%s');\">Add</A>)</TD><TD>%s</TD><TD>%s</TD><TD>%s</TD><TD>%s kbps</TD><TD>%.2f</TD><TD><INPUT TYPE=\"button\" VALUE=\"Remove\" OnClick=\"OnRemovePlaylistElmt('%s','%s','%s',%d);\"/></TD>\n",
$index, $row["title"], $row["id"], mysql_real_escape_string($row["title"]), $row["album"], $row["artist"], $row["genre"], $row["bitrate"], $row["duration_sec"]/60, $playlist_id, $row["id"], $row["title"], $pageno) ;
echo("</TR>") ;
}
}
$index++;
mysql_free_result($result);
}
echo("</TABLE>") ;
mysql_free_result($playlistresult);
}
public function PrepareBookMarksInfo($user_id,$pageno)
{
$playlistresult = mysql_query("select * from bookmarks where user_id= '".$user_id."';", $this->db_link_id);
$row = mysql_fetch_array($playlistresult);
$mp3idarray = explode(";",$row['bookmarks']);
$count = count($mp3idarray);
$this->PreparePaging($pageno,$count,"tab_manage_aud_bookmarks.php","");
$startlimit = ($pageno -1)* 10;
$endlimit = ($pageno -1)*10 + 10;
echo("<TABLE BORDER='0'>\n") ;
echo("<TR BGCOLOR=\"#CCCC99\" ALIGN=\"CENTER\"><TD><B>Index</B></TD><TD><B>Title</B></TD><TD><B>Album</B></TD><TD><B>Artist</B></TD><TD><B>Genre</B></TD><TD><B>Bit Rate</B></TD><TD><B>Duration (min)</B></TD><TD><B>Remove</B></TD></TR>\n") ;
$i = 0 ;
$index = 1 ;
foreach($mp3idarray as $mp3id)
{
$result = mysql_query("select * from mp3_info where id='".$mp3id."' order by title asc;") ;
if($index > $startlimit && $index <= $endlimit)
{
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
if($i == 0)
{
echo("<TR BGCOLOR=\"#FFFFCC\" ALIGN=\"CENTER\">") ;
$i++ ;
}
else
{
echo("<TR BGCOLOR=\"#FFFF99\" ALIGN=\"CENTER\">") ;
$i-- ;
}
printf("<TD>%d</TD><TD>%s (<A HREF='javascript:;' onClick=\"parent.parent.SR.AddToPlaylistUrl('%s','%s');\">Add</A>)</TD><TD>%s</TD><TD>%s</TD><TD>%s</TD><TD>%s kbps</TD><TD>%.2f</TD><TD><input type = 'button' value = 'Remove' onClick = \"OnRemoveBookmark('%s',%d,'%s');\"></TD>\n",
$index, $row["title"], $row["id"], mysql_real_escape_string($row["title"]), $row["album"], $row["artist"], $row["genre"], $row["bitrate"], $row["duration_sec"]/60,$row["id"],$pageno,mysql_real_escape_string($row["title"])) ;
echo("</TR>") ;
$index++ ;
}
}
mysql_free_result($result);
}
echo("</TABLE>") ;
mysql_free_result($playlistresult);
}
public function InsertSendToFriend($user_name, $user_email, $friends_name, $friends_email, $aud_id)
{
$query = sprintf("insert into send_to_friend (user_name, user_email, friend_name, friend_email, aud_id) values ('%s', '%s', '%s', '%s', '%s')", $user_name, $user_email, $friends_name, $friends_email, $aud_id);
mysql_query($query) ;
}
public function IncreaseVoteCount($aud_id)
{
$query = sprintf("update mp3_info set votes = votes + 1 where id='%s' ;", $aud_id);
mysql_query($query) ;
}
public function IsBookmarked($aud_id, $user_id)
{
$bResult = 0 ;
$result = mysql_query("select bookmarks from bookmarks where user_id='".$user_id."';", $this->db_link_id);
if (mysql_num_rows($result) > 0)
{
$row = mysql_fetch_array($result, MYSQL_ASSOC) ;
$bookmark_array = explode(";", $row["bookmarks"]) ;
if(in_array($aud_id, $bookmark_array))
{
$bResult = 1 ;
}
}
mysql_free_result($result);
return $bResult ;
}
public function RemovePlaylist($playlist_id)
{
$bResult = 0 ;
mysql_query("delete from playlists where playlist_id='".$playlist_id."';", $this->db_link_id) ;
if (mysql_affected_rows($this->db_link_id) > 0)
{
$bResult = 1 ;
}
return $bResult ;
}
public function RemovePlaylistElement($pid, $aud_id)
{
$result = mysql_query("select playlist from playlists where playlist_id='".$pid."';", $this->db_link_id);
if (mysql_num_rows($result) > 0)
{
//echo($aud_id."<BR/>") ;
$row = mysql_fetch_array($result, MYSQL_ASSOC) ;
$playlist_array = explode(";", $row["playlist"]) ;
/*echo("<PRE>");
print_r($playlist_array) ;
echo("</PRE>") ;*/
if(in_array($aud_id, $playlist_array))
{
//echo(array_search($aud_id, $playlist_array)) ;
array_splice($playlist_array, array_search($aud_id, $playlist_array), 1) ;
/*echo("<BR/><PRE>");
print_r($playlist_array) ;
echo("</PRE><BR/>") ;*/
$playlists = implode(';',$playlist_array);
$qry = sprintf("update playlists set playlist='%s' where playlist_id='%s';", $playlists, $pid) ;
mysql_query($qry, $this->db_link_id);
}
}
mysql_free_result($result);
}
public function RemoveBookmark($user_id, $aud_id)
{
$result = mysql_query("select bookmarks from bookmarks where user_id='".$user_id."';", $this->db_link_id);
if (mysql_num_rows($result) > 0)
{
$row = mysql_fetch_array($result, MYSQL_ASSOC) ;
$bookmark_array = explode(";", $row["bookmarks"]) ;
/*echo("<PRE>");
print_r($bookmark_array) ;
echo("</PRE>") ;*/
if(in_array($aud_id, $bookmark_array))
{
//echo(array_search($aud_id, $bookmark_array)) ;
array_splice($bookmark_array, array_search($aud_id, $bookmark_array), 1) ;
/*echo("<BR/><PRE>");
print_r($bookmark_array) ;
echo("</PRE><BR/>") ;*/
$bookmarks = implode(';',$bookmark_array);
$qry = sprintf("update bookmarks set bookmarks='%s' where user_id='%s';", $bookmarks, $user_id) ;
mysql_query($qry, $this->db_link_id);
}
}
mysql_free_result($result);
}
public function GetPlaylistInfo($pid, &$playlist_id_list, &$playlist_title_list)
{
$result = mysql_query("select playlist from playlists where playlist_id='".$pid."';", $this->db_link_id);
if (mysql_num_rows($result) > 0)
{
$row = mysql_fetch_array($result, MYSQL_ASSOC) ;
$playlist_ary = explode(";", $row["playlist"]) ;
$playlist_id_list = $row["playlist"] ;
$index = 1 ;
$row_count = count($playlist_ary) ;
foreach ($playlist_ary as $aud_id)
{
$mp3_result = mysql_query("select title from mp3_info where id='".$aud_id."';", $this->db_link_id) ;
while($mp3_row = mysql_fetch_array($mp3_result, MYSQL_ASSOC))
{
if($row_count != $index)
{
$playlist_title_list .= $mp3_row["title"] . ";" ;
}
else
{
$playlist_title_list .= $mp3_row["title"] ;
}
}
$index++ ;
mysql_free_result($mp3_result ) ;
}
}
mysql_free_result($result);
return true ;
}
public function GetAlbumSongList($albumname, &$album_songid_list, &$album_songtitle_list)
{
$albumname = urldecode($albumname);
$mp3_result = mysql_query("select id, title from mp3_info where album= '".$albumname."';", $this->db_link_id) or die("Query fail: " . mysql_error());
$numsongs = mysql_num_rows($mp3_result);
if($numsongs > 0)
{
$index = 1;
while($mp3_row = mysql_fetch_array($mp3_result, MYSQL_ASSOC))
{
if($numsongs != $index)
{
$album_songtitle_list .= $mp3_row["title"] . ";" ;
$album_songid_list .= $mp3_row["id"] . ";" ;
}
else
{
$album_songtitle_list .= $mp3_row["title"] ;
$album_songid_list .= $mp3_row["id"] ;
}
$index++ ;
}
mysql_free_result($mp3_result );
return 1 ;
}
else
{
mysql_free_result($mp3_result );
return 0;
}
}
public function InsertIntoMP3PlayLocation($mp3_id, $ip)
{
$bResult = mysql_query("insert into mp3_play_location (mp3_id, ip_addr) values ('$mp3_id', '$ip') ;", $this->db_link_id) or die("mp3_play_location Insert Error: ".mysql_error($this->db_link_id));
}
/*Check and Remove invalid entries*/
public function CheckandRemoveInvalid()
{
$cnt = 0;
$bFileExists = false;
$result = mysql_query("select * from mp3_info;");
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$AUDIO_ROOT = getcwd(). '/ect'; // 'F:/MGooS/donn/ect';
$MAXFOLDER = 10;
$totalrow++;
/*/home/mgooscom/public_html/donn/ect/00027293-6d8e-0b94-393a-d8487d47b92a */
$filepath =$row["filepath"];
list($blank,$home,$root,$public,$donn,$ect,$filename)= split('[/]',$filepath);
for($i=1; $i<$MAXFOLDER; $i++)
{
$physicalfilepath = $AUDIO_ROOT .$i. "/". $filename;
if(file_exists($physicalfilepath))
{
$bFileExists = true;
$ctr++;
break;
}
else
{
$bFileExists = false;
}
}
if(!$bFileExists)
{
$id = $row["id"];
mysql_query("delete from mp3_info where id='".$id."';", $this->db_link_id) or die("Remove Mp3 enrty Error: ".mysql_error($this->db_link_id));
if( mysql_affected_rows($this->db_link_id) > 0 )
{
// Remove the entry from mp3_metaphone_info as well.
mysql_query("delete from mp3_metaphone_info where id='".$id."';", $this->db_link_id) ;
// Now remove file from the disk (@ for suppressing error/warning message).
}
$cnt++; /* increase invalid count*/
}
}
mysql_free_result($result);
return $cnt;
}
public function MakeProperEntries()
{
$cnt = 0;
$bFileExists = false;
$result = mysql_query("select * from mp3_info;");
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$AUDIO_ROOT = getcwd(). '/ect'; //'F:/MGooS/donn/ect'; //getcwd(). '/ect'; //
$MAXFOLDER = 10;
$totalrow++;
/*/home/mgooscom/public_html/donn/ect/00027293-6d8e-0b94-393a-d8487d47b92a */
$filepath = $row["filepath"];
list($blank,$home,$root,$public,$donn,$ect,$filename)= split('[/]',$filepath);
for($i=1; $i<$MAXFOLDER; $i++)
{
$physicalfilepath = $AUDIO_ROOT .$i. "/". $filename;
if(file_exists($physicalfilepath))
{
$bFileExists = true;
$actualpath = '/'.$home.'/'. $root .'/'.$public.'/'.$donn.'/'.$ect . $i . '/' . $filename;
$id = $row["id"];
mysql_query("update mp3_info set filepath = '".$actualpath. "' where id='".$id."';", $this->db_link_id) or die("Remove Mp3 enrty Error: ".mysql_error($this->db_link_id));
if( mysql_affected_rows($this->db_link_id) > 0 )
{
$cnt++;
}
break;
}
}
}
mysql_free_result($result);
return $cnt;
}
public function removeinvalidfiles()
{
// open the current directory by opendir
$AUDIO_ROOT = getcwd(). '/ect'; //'F:/MGooS/donn/ect';
$serverroot = '/home/mgooscom/public_html/donn/';
$firstleveldir = 'ect';
$count = 0;
for($i=1; $i<10; $i++)
{
$physicalfilepath = $AUDIO_ROOT .$i. "/";
$handle=opendir($physicalfilepath);
while (($file = readdir($handle))!==false)
{
$dbfilepath = $serverroot. $firstleveldir . $i ."/" . $file;
$query = "select * from mp3_info where filepath= '".$dbfilepath."';";
echo($query); echo("</br>");
$result = mysql_query("select * from mp3_info where filepath= '".$dbfilepath."';", $this->db_link_id) or die("Query fail: " . mysql_error());
if (mysql_num_rows($result) == 0)
{
$count++;
}
}
closedir($handle);
}
return $count;
}
public function InsertIntoAdminMP3Info($file, $filesize,
$bitrate, $duration_sec,
$year, $genre, $mood,
$title, $artist,
$album, $lang)
{
//echo "inserting into admin mp3 info ".$file." ".$filesize." ".$bitrate." ".$duration_sec." ".$year." ".$genre." ".$mood." ".$title." ".$artist." ".$album." ".$lang;
mysql_query("insert into mp3_upload_info (file, title, artist, album, year, genre, mood, language, filesize, bitrate, duration_sec) values ('".$file."','".$title."','".$artist."','".$album."','".$year."','".$genre."','".$mood."','".$lang."','".$filesize."','".$bitrate."','".$duration_sec."') ;", $this->db_link_id) or die("mp3_info Insert Error: ".mysql_error($this->db_link_id));
}
public function SelectRowFromAdminMP3Info($index)
{
//echo "select * from mp3_upload_info limit ".$index.",".($index+1);
$mp3_row["result"] = 0;
$mp3_row["elements"] = 0;
$mp3_result = mysql_query("select * from mp3_upload_info limit ".$index.",".($index+1)) or die("mp3_upload_info select error: ".mysql_error($this->db_link_id));
if(mysql_num_rows($mp3_result) > 0)
{
$mp3_row = mysql_fetch_array($mp3_result, MYSQL_ASSOC);
mysql_free_result($mp3_result);
$mp3_row["result"] = 1;
$mp3_result = mysql_query("select count(*) as count from mp3_upload_info") or die("mp3_upload_info select count error: ".mysql_error($this->db_link_id));
$row = mysql_fetch_array($mp3_result, MYSQL_ASSOC);
$mp3_row["elements"] = $row["count"];
}
return $mp3_row;
}
public function ListAlphabet($alphabet, $columns, $tabbed = false)
{
$result = mysql_query("select distinct album from mp3_info where album like '".$alphabet."%' and provider <> 'http://www.mgoos.com'") or die("mp3_info select error: ".mysql_error($this->db_link_id));
$index = 0 ;
$url = "" ;
//$columns = 4 ;
echo "<TABLE WIDTH=\"100%\" BORDER=\"0\" CELLSPACING=\"2\" CELLPADDING=\"5\">" ;
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if($index == 0 || $index%$columns == 0)
{
echo "<TR ALIGN=\"Center\">" ;
}
if($tabbed)
{
$url = "tab_search_results.php?qry=".urlencode($row["album"])."&pg=1&ext=album&strict=true" ;
}
else
{
$url = "search_results.php?srchtxt=".urlencode($row["album"])."&ext=album&strict=true" ;
}
printf("<TD ALIGN=\"LEFT\"><B><A HREF=\"%s\">%s</A></B></TD>", $url, $row["album"]) ;
$index++ ;
if($index != 0 && $index%$columns == 0)
{
echo "</TR>" ;
}
}
echo "</TABLE>";
}
}
?> | mastishka/mgoos | database/queries_old.php | PHP | apache-2.0 | 41,106 |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* Copyright by the Board of Trustees of the University of Illinois. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the COPYING file, which can be found at the root of the source code *
* distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. *
* If you do not have access to either file, you may request a copy from *
* help@hdfgroup.org. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*
* Programmer: Quincey Koziol
* Thursday, September 30, 2004
*/
/****************/
/* Module Setup */
/****************/
#include "H5Dmodule.h" /* This source code file is part of the H5D module */
/***********/
/* Headers */
/***********/
#include "H5private.h" /* Generic Functions */
#include "H5Dpkg.h" /* Datasets */
#include "H5Eprivate.h" /* Error handling */
#include "H5Fprivate.h" /* Files */
#include "H5HLprivate.h" /* Local Heaps */
#include "H5MMprivate.h" /* Memory management */
#include "H5VMprivate.h" /* Vector and array functions */
/****************/
/* Local Macros */
/****************/
/******************/
/* Local Typedefs */
/******************/
/* Callback info for readvv operation */
typedef struct H5D_efl_readvv_ud_t {
const H5O_efl_t *efl; /* Pointer to efl info */
const H5D_t *dset; /* The dataset */
unsigned char *rbuf; /* Read buffer */
} H5D_efl_readvv_ud_t;
/* Callback info for writevv operation */
typedef struct H5D_efl_writevv_ud_t {
const H5O_efl_t *efl; /* Pointer to efl info */
const H5D_t *dset; /* The dataset */
const unsigned char *wbuf; /* Write buffer */
} H5D_efl_writevv_ud_t;
/********************/
/* Local Prototypes */
/********************/
/* Layout operation callbacks */
static herr_t H5D__efl_construct(H5F_t *f, H5D_t *dset);
static herr_t H5D__efl_io_init(const H5D_io_info_t *io_info, const H5D_type_info_t *type_info,
hsize_t nelmts, const H5S_t *file_space, const H5S_t *mem_space,
H5D_chunk_map_t *cm);
static ssize_t H5D__efl_readvv(const H5D_io_info_t *io_info,
size_t dset_max_nseq, size_t *dset_curr_seq, size_t dset_len_arr[], hsize_t dset_offset_arr[],
size_t mem_max_nseq, size_t *mem_curr_seq, size_t mem_len_arr[], hsize_t mem_offset_arr[]);
static ssize_t H5D__efl_writevv(const H5D_io_info_t *io_info,
size_t dset_max_nseq, size_t *dset_curr_seq, size_t dset_len_arr[], hsize_t dset_offset_arr[],
size_t mem_max_nseq, size_t *mem_curr_seq, size_t mem_len_arr[], hsize_t mem_offset_arr[]);
/* Helper routines */
static herr_t H5D__efl_read(const H5O_efl_t *efl, const H5D_t *dset, haddr_t addr, size_t size,
uint8_t *buf);
static herr_t H5D__efl_write(const H5O_efl_t *efl, const H5D_t *dset, haddr_t addr, size_t size,
const uint8_t *buf);
/*********************/
/* Package Variables */
/*********************/
/* External File List (EFL) storage layout I/O ops */
const H5D_layout_ops_t H5D_LOPS_EFL[1] = {{
H5D__efl_construct,
NULL,
H5D__efl_is_space_alloc,
NULL,
H5D__efl_io_init,
H5D__contig_read,
H5D__contig_write,
#ifdef H5_HAVE_PARALLEL
NULL,
NULL,
#endif /* H5_HAVE_PARALLEL */
H5D__efl_readvv,
H5D__efl_writevv,
NULL,
NULL,
NULL
}};
/*******************/
/* Local Variables */
/*******************/
/*-------------------------------------------------------------------------
* Function: H5D__efl_construct
*
* Purpose: Constructs new EFL layout information for dataset
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* Thursday, May 22, 2008
*
*-------------------------------------------------------------------------
*/
static herr_t
H5D__efl_construct(H5F_t *f, H5D_t *dset)
{
size_t dt_size; /* Size of datatype */
hssize_t stmp_size; /* Temporary holder for raw data size */
hsize_t tmp_size; /* Temporary holder for raw data size */
hsize_t max_points; /* Maximum elements */
hsize_t max_storage; /* Maximum storage size */
unsigned u; /* Local index variable */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_STATIC
/* Sanity checks */
HDassert(f);
HDassert(dset);
/*
* The maximum size of the dataset cannot exceed the storage size.
* Also, only the slowest varying dimension of a simple dataspace
* can be extendible (currently only for external data storage).
*/
/* Check for invalid dataset dimensions */
for(u = 1; u < dset->shared->ndims; u++)
if(dset->shared->max_dims[u] > dset->shared->curr_dims[u])
HGOTO_ERROR(H5E_DATASET, H5E_UNSUPPORTED, FAIL, "only the first dimension can be extendible")
/* Retrieve the size of the dataset's datatype */
if(0 == (dt_size = H5T_get_size(dset->shared->type)))
HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to determine datatype size")
/* Check for storage overflows */
max_points = H5S_get_npoints_max(dset->shared->space);
max_storage = H5O_efl_total_size(&dset->shared->dcpl_cache.efl);
if(H5S_UNLIMITED == max_points) {
if(H5O_EFL_UNLIMITED != max_storage)
HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unlimited dataspace but finite storage")
} /* end if */
else if((max_points * dt_size) < max_points)
HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "dataspace * type size overflowed")
else if((max_points * dt_size) > max_storage)
HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "dataspace size exceeds external storage size")
/* Compute the total size of dataset */
stmp_size = H5S_GET_EXTENT_NPOINTS(dset->shared->space);
HDassert(stmp_size >= 0);
tmp_size = (hsize_t)stmp_size * dt_size;
H5_CHECKED_ASSIGN(dset->shared->layout.storage.u.contig.size, hsize_t, tmp_size, hssize_t);
/* Get the sieve buffer size for this dataset */
dset->shared->cache.contig.sieve_buf_size = H5F_SIEVE_BUF_SIZE(f);
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5D__efl_construct() */
/*-------------------------------------------------------------------------
* Function: H5D__efl_is_space_alloc
*
* Purpose: Query if space is allocated for layout
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* Thursday, January 15, 2009
*
*-------------------------------------------------------------------------
*/
hbool_t
H5D__efl_is_space_alloc(const H5O_storage_t H5_ATTR_UNUSED *storage)
{
FUNC_ENTER_PACKAGE_NOERR
/* Sanity checks */
HDassert(storage);
/* EFL storage is currently always treated as allocated */
FUNC_LEAVE_NOAPI(TRUE)
} /* end H5D__efl_is_space_alloc() */
/*-------------------------------------------------------------------------
* Function: H5D__efl_io_init
*
* Purpose: Performs initialization before any sort of I/O on the raw data
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* Thursday, March 20, 2008
*
*-------------------------------------------------------------------------
*/
static herr_t
H5D__efl_io_init(const H5D_io_info_t *io_info, const H5D_type_info_t H5_ATTR_UNUSED *type_info,
hsize_t H5_ATTR_UNUSED nelmts, const H5S_t H5_ATTR_UNUSED *file_space, const H5S_t H5_ATTR_UNUSED *mem_space,
H5D_chunk_map_t H5_ATTR_UNUSED *cm)
{
FUNC_ENTER_STATIC_NOERR
H5MM_memcpy(&io_info->store->efl, &(io_info->dset->shared->dcpl_cache.efl), sizeof(H5O_efl_t));
FUNC_LEAVE_NOAPI(SUCCEED)
} /* end H5D__efl_io_init() */
/*-------------------------------------------------------------------------
* Function: H5D__efl_read
*
* Purpose: Reads data from an external file list. It is an error to
* read past the logical end of file, but reading past the end
* of any particular member of the external file list results in
* zeros.
*
* Return: SUCCEED/FAIL
*
* Programmer: Robb Matzke
* Wednesday, March 4, 1998
*
*-------------------------------------------------------------------------
*/
static herr_t
H5D__efl_read(const H5O_efl_t *efl, const H5D_t *dset, haddr_t addr, size_t size, uint8_t *buf)
{
int fd = -1;
size_t to_read;
#ifndef NDEBUG
hsize_t tempto_read;
#endif /* NDEBUG */
hsize_t skip = 0;
haddr_t cur;
ssize_t n;
size_t u; /* Local index variable */
char *full_name = NULL; /* File name with prefix */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_STATIC
/* Check args */
HDassert(efl && efl->nused > 0);
HDassert(H5F_addr_defined(addr));
HDassert(size < SIZET_MAX);
HDassert(buf || 0 == size);
/* Find the first efl member from which to read */
for (u=0, cur=0; u<efl->nused; u++) {
if(H5O_EFL_UNLIMITED == efl->slot[u].size || addr < cur + efl->slot[u].size) {
skip = addr - cur;
break;
} /* end if */
cur += efl->slot[u].size;
} /* end for */
/* Read the data */
while(size) {
HDassert(buf);
if(u >= efl->nused)
HGOTO_ERROR(H5E_EFL, H5E_OVERFLOW, FAIL, "read past logical end of file")
if(H5F_OVERFLOW_HSIZET2OFFT((hsize_t)efl->slot[u].offset + skip))
HGOTO_ERROR(H5E_EFL, H5E_OVERFLOW, FAIL, "external file address overflowed")
if(H5_combine_path(dset->shared->extfile_prefix, efl->slot[u].name, &full_name) < 0)
HGOTO_ERROR(H5E_EFL, H5E_NOSPACE, FAIL, "can't build external file name")
/* ITK --start */
#if defined(H5_HAVE_WIN32_API) && !defined(_MSC_VER)
/* With MinGW, pass the required third argument to the HDopen macro, which is ignored by _open. */
/* ITK --stop */
if((fd = HDopen(full_name, O_RDONLY, NULL)) < 0)
/* ITK --stop */
/* ITK --start */
#else
/* ITK --stop */
if((fd = HDopen(full_name, O_RDONLY)) < 0)
/* ITK --start */
#endif
/* ITK --stop */
HGOTO_ERROR(H5E_EFL, H5E_CANTOPENFILE, FAIL, "unable to open external raw data file")
if(HDlseek(fd, (HDoff_t)(efl->slot[u].offset + (HDoff_t)skip), SEEK_SET) < 0)
HGOTO_ERROR(H5E_EFL, H5E_SEEKERROR, FAIL, "unable to seek in external raw data file")
#ifndef NDEBUG
tempto_read = MIN((size_t)(efl->slot[u].size-skip), (hsize_t)size);
H5_CHECK_OVERFLOW(tempto_read, hsize_t, size_t);
to_read = (size_t)tempto_read;
#else /* NDEBUG */
to_read = MIN((size_t)(efl->slot[u].size - skip), (hsize_t)size);
#endif /* NDEBUG */
if((n = HDread(fd, buf, to_read)) < 0)
HGOTO_ERROR(H5E_EFL, H5E_READERROR, FAIL, "read error in external raw data file")
else if((size_t)n < to_read)
HDmemset(buf + n, 0, to_read - (size_t)n);
full_name = (char *)H5MM_xfree(full_name);
HDclose(fd);
fd = -1;
size -= to_read;
buf += to_read;
skip = 0;
u++;
} /* end while */
done:
if(full_name)
full_name = (char *)H5MM_xfree(full_name);
if(fd >= 0)
HDclose(fd);
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5D__efl_read() */
/*-------------------------------------------------------------------------
* Function: H5D__efl_write
*
* Purpose: Writes data to an external file list. It is an error to
* write past the logical end of file, but writing past the end
* of any particular member of the external file list just
* extends that file.
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Robb Matzke
* Wednesday, March 4, 1998
*
*-------------------------------------------------------------------------
*/
static herr_t
H5D__efl_write(const H5O_efl_t *efl, const H5D_t *dset, haddr_t addr, size_t size, const uint8_t *buf)
{
int fd = -1;
size_t to_write;
#ifndef NDEBUG
hsize_t tempto_write;
#endif /* NDEBUG */
haddr_t cur;
hsize_t skip = 0;
size_t u; /* Local index variable */
char *full_name = NULL; /* File name with prefix */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_STATIC
/* Check args */
HDassert(efl && efl->nused > 0);
HDassert(H5F_addr_defined(addr));
HDassert(size < SIZET_MAX);
HDassert(buf || 0 == size);
/* Find the first efl member in which to write */
for(u = 0, cur = 0; u < efl->nused; u++) {
if(H5O_EFL_UNLIMITED == efl->slot[u].size || addr < cur + efl->slot[u].size) {
skip = addr - cur;
break;
} /* end if */
cur += efl->slot[u].size;
} /* end for */
/* Write the data */
while(size) {
HDassert(buf);
if(u >= efl->nused)
HGOTO_ERROR(H5E_EFL, H5E_OVERFLOW, FAIL, "write past logical end of file")
if(H5F_OVERFLOW_HSIZET2OFFT((hsize_t)efl->slot[u].offset + skip))
HGOTO_ERROR(H5E_EFL, H5E_OVERFLOW, FAIL, "external file address overflowed")
if(H5_combine_path(dset->shared->extfile_prefix, efl->slot[u].name, &full_name) < 0)
HGOTO_ERROR(H5E_EFL, H5E_NOSPACE, FAIL, "can't build external file name")
if((fd = HDopen(full_name, O_CREAT | O_RDWR, H5_POSIX_CREATE_MODE_RW)) < 0) {
if(HDaccess(full_name, F_OK) < 0)
HGOTO_ERROR(H5E_EFL, H5E_CANTOPENFILE, FAIL, "external raw data file does not exist")
else
HGOTO_ERROR(H5E_EFL, H5E_CANTOPENFILE, FAIL, "unable to open external raw data file")
} /* end if */
if(HDlseek(fd, (HDoff_t)(efl->slot[u].offset + (HDoff_t)skip), SEEK_SET) < 0)
HGOTO_ERROR(H5E_EFL, H5E_SEEKERROR, FAIL, "unable to seek in external raw data file")
#ifndef NDEBUG
tempto_write = MIN(efl->slot[u].size - skip, (hsize_t)size);
H5_CHECK_OVERFLOW(tempto_write, hsize_t, size_t);
to_write = (size_t)tempto_write;
#else /* NDEBUG */
to_write = MIN((size_t)(efl->slot[u].size - skip), size);
#endif /* NDEBUG */
if((size_t)HDwrite(fd, buf, to_write) != to_write)
HGOTO_ERROR(H5E_EFL, H5E_READERROR, FAIL, "write error in external raw data file")
full_name = (char *)H5MM_xfree(full_name);
HDclose (fd);
fd = -1;
size -= to_write;
buf += to_write;
skip = 0;
u++;
} /* end while */
done:
if(full_name)
full_name = (char *)H5MM_xfree(full_name);
if(fd >= 0)
HDclose(fd);
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5D__efl_write() */
/*-------------------------------------------------------------------------
* Function: H5D__efl_readvv_cb
*
* Purpose: Callback operator for H5D__efl_readvv().
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* Thursday, Sept 30, 2010
*
*-------------------------------------------------------------------------
*/
static herr_t
H5D__efl_readvv_cb(hsize_t dst_off, hsize_t src_off, size_t len, void *_udata)
{
H5D_efl_readvv_ud_t *udata = (H5D_efl_readvv_ud_t *)_udata; /* User data for H5VM_opvv() operator */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_STATIC
/* Read data */
if(H5D__efl_read(udata->efl, udata->dset, dst_off, len, (udata->rbuf + src_off)) < 0)
HGOTO_ERROR(H5E_DATASET, H5E_READERROR, FAIL, "EFL read failed")
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5D__efl_readvv_cb() */
/*-------------------------------------------------------------------------
* Function: H5D__efl_readvv
*
* Purpose: Reads data from an external file list. It is an error to
* read past the logical end of file, but reading past the end
* of any particular member of the external file list results in
* zeros.
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* Wednesday, May 7, 2003
*
*-------------------------------------------------------------------------
*/
static ssize_t
H5D__efl_readvv(const H5D_io_info_t *io_info,
size_t dset_max_nseq, size_t *dset_curr_seq, size_t dset_len_arr[], hsize_t dset_off_arr[],
size_t mem_max_nseq, size_t *mem_curr_seq, size_t mem_len_arr[], hsize_t mem_off_arr[])
{
H5D_efl_readvv_ud_t udata; /* User data for H5VM_opvv() operator */
ssize_t ret_value = -1; /* Return value (Total size of sequence in bytes) */
FUNC_ENTER_STATIC
/* Check args */
HDassert(io_info);
HDassert(io_info->store->efl.nused > 0);
HDassert(io_info->u.rbuf);
HDassert(io_info->dset);
HDassert(io_info->dset->shared);
HDassert(dset_curr_seq);
HDassert(dset_len_arr);
HDassert(dset_off_arr);
HDassert(mem_curr_seq);
HDassert(mem_len_arr);
HDassert(mem_off_arr);
/* Set up user data for H5VM_opvv() */
udata.efl = &(io_info->store->efl);
udata.dset = io_info->dset;
udata.rbuf = (unsigned char *)io_info->u.rbuf;
/* Call generic sequence operation routine */
if((ret_value = H5VM_opvv(dset_max_nseq, dset_curr_seq, dset_len_arr, dset_off_arr,
mem_max_nseq, mem_curr_seq, mem_len_arr, mem_off_arr,
H5D__efl_readvv_cb, &udata)) < 0)
HGOTO_ERROR(H5E_DATASET, H5E_CANTOPERATE, FAIL, "can't perform vectorized EFL read")
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5D__efl_readvv() */
/*-------------------------------------------------------------------------
* Function: H5D__efl_writevv_cb
*
* Purpose: Callback operator for H5D__efl_writevv().
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* Thursday, Sept 30, 2010
*
*-------------------------------------------------------------------------
*/
static herr_t
H5D__efl_writevv_cb(hsize_t dst_off, hsize_t src_off, size_t len, void *_udata)
{
H5D_efl_writevv_ud_t *udata = (H5D_efl_writevv_ud_t *)_udata; /* User data for H5VM_opvv() operator */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_STATIC
/* Write data */
if(H5D__efl_write(udata->efl, udata->dset, dst_off, len, (udata->wbuf + src_off)) < 0)
HGOTO_ERROR(H5E_DATASET, H5E_WRITEERROR, FAIL, "EFL write failed")
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5D__efl_writevv_cb() */
/*-------------------------------------------------------------------------
* Function: H5D__efl_writevv
*
* Purpose: Writes data to an external file list. It is an error to
* write past the logical end of file, but writing past the end
* of any particular member of the external file list just
* extends that file.
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* Friday, May 2, 2003
*
*-------------------------------------------------------------------------
*/
static ssize_t
H5D__efl_writevv(const H5D_io_info_t *io_info,
size_t dset_max_nseq, size_t *dset_curr_seq, size_t dset_len_arr[], hsize_t dset_off_arr[],
size_t mem_max_nseq, size_t *mem_curr_seq, size_t mem_len_arr[], hsize_t mem_off_arr[])
{
H5D_efl_writevv_ud_t udata; /* User data for H5VM_opvv() operator */
ssize_t ret_value = -1; /* Return value (Total size of sequence in bytes) */
FUNC_ENTER_STATIC
/* Check args */
HDassert(io_info);
HDassert(io_info->store->efl.nused > 0);
HDassert(io_info->u.wbuf);
HDassert(io_info->dset);
HDassert(io_info->dset->shared);
HDassert(dset_curr_seq);
HDassert(dset_len_arr);
HDassert(dset_off_arr);
HDassert(mem_curr_seq);
HDassert(mem_len_arr);
HDassert(mem_off_arr);
/* Set up user data for H5VM_opvv() */
udata.efl = &(io_info->store->efl);
udata.dset = io_info->dset;
udata.wbuf = (const unsigned char *)io_info->u.wbuf;
/* Call generic sequence operation routine */
if((ret_value = H5VM_opvv(dset_max_nseq, dset_curr_seq, dset_len_arr, dset_off_arr,
mem_max_nseq, mem_curr_seq, mem_len_arr, mem_off_arr,
H5D__efl_writevv_cb, &udata)) < 0)
HGOTO_ERROR(H5E_DATASET, H5E_CANTOPERATE, FAIL, "can't perform vectorized EFL write")
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5D__efl_writevv() */
/*-------------------------------------------------------------------------
* Function: H5D__efl_bh_info
*
* Purpose: Retrieve the amount of heap storage used for External File
* List message
*
* Return: Success: Non-negative
* Failure: negative
*
* Programmer: Vailin Choi; August 2009
*
*-------------------------------------------------------------------------
*/
herr_t
H5D__efl_bh_info(H5F_t *f, H5O_efl_t *efl, hsize_t *heap_size)
{
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_PACKAGE
/* Check args */
HDassert(f);
HDassert(efl);
HDassert(H5F_addr_defined(efl->heap_addr));
HDassert(heap_size);
/* Get the size of the local heap for EFL's file list */
if(H5HL_heapsize(f, efl->heap_addr, heap_size) < 0)
HGOTO_ERROR(H5E_EFL, H5E_CANTINIT, FAIL, "unable to retrieve local heap info")
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5D__efl_bh_info() */
| vfonov/ITK | Modules/ThirdParty/HDF5/src/itkhdf5/src/H5Defl.c | C | apache-2.0 | 22,106 |
package ch.DB_BR_HJ.LebenslaufApp;
import java.util.ArrayList;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.media.Image;
import android.os.Parcel;
@SuppressLint("ParcelCreator")
public class CV {
public String id;
public int bezeichnung;
public String name;
public String adresse;
public Image foto;
public ArrayList<Berufserfahrung> beEr = new ArrayList<Berufserfahrung>();
public ArrayList<Bildung> bildung = new ArrayList<Bildung>();
public CV(Parcel in) {
id = UUID.randomUUID().toString();
}
public String getID() {
return id;
}
public void addBerufserfahrung(Berufserfahrung be) {
beEr.add(be);
}
public void deleteBerufserfahrung(int id) {
beEr.remove(id);
}
public void addBildung(Bildung bil) {
bildung.add(bil);
}
public void deleteBildung(int id) {
bildung.remove(id);
}
}
| jherzig/ESA_Lebenslauf-App | Lebenslauf-App/src/ch/DB_BR_HJ/LebenslaufApp/CV.java | Java | apache-2.0 | 902 |
package com.contactlab.api.samples.sendcampaignoperations;
import com.contactlab.api.ws.ClabService;
import com.contactlab.api.ws.ClabService_Service;
import com.contactlab.api.ws.domain.AuthToken;
import com.contactlab.api.ws.domain.SubscriberSourceFilter;
import static com.contactlab.api.samples.ConfigProperties.API_KEY;
import static com.contactlab.api.samples.ConfigProperties.USER_KEY;
public class AddSubscriberSourceFilter {
/* Example of Data Ids */
/**
* @see com.contactlab.api.samples.sendcampaignoperations.AddSubscriberSource to cerate subscriberSource with desired properties
*/
private static Integer SUBSCRIBER_SOURCE_ID = 3;
// https://explore.contactlab.com/developers/Contactsend/documentazione/SoapApi/addSubscriberSourceFilter/
public static void main(String[] args) {
// Clab Service Initialization
ClabService service = new ClabService_Service().getClabServicePort();
// borrow token
AuthToken token = service.borrowToken(API_KEY, USER_KEY);
// CALL WS SERVICE addSubscriberSourceFilter passing token and data
SubscriberSourceFilter subscriberSourceFilterCreated = service.addSubscriberSourceFilter(token,
getSubscriberSourceFilter(SUBSCRIBER_SOURCE_ID));
System.out.println("Created subscriber source filter with id [" + subscriberSourceFilterCreated.getIdentifier() + "]");
}
static SubscriberSourceFilter getSubscriberSourceFilter(Integer subscriberSourceId) {
SubscriberSourceFilter subscriberSourceFilter = new SubscriberSourceFilter();
subscriberSourceFilter.setName("Filter1");
subscriberSourceFilter.setSubscriberSourceIdentifier(subscriberSourceId);
subscriberSourceFilter.setContent("enabled = 1");
return subscriberSourceFilter;
}
}
| contactlab/soap-api-samples | java/src/main/java/com/contactlab/api/samples/sendcampaignoperations/AddSubscriberSourceFilter.java | Java | apache-2.0 | 1,835 |
#banner { background: url(/resources/images/home/course_banner_bg.jpg) repeat-x; }
#section_c .data-table td { border:1px solid #ff5000; background: #fce3c4; text-align:center; height:54px; position:relative; }
.course-join-btn { width:44px; height:47px; /*display:inline-block;*/ display:none; background:url(/resources/images/home/course_join_btn.png) no-repeat; position:absolute; right:0; bottom:0; } | xiaxiazhu119/zpgarden | ZP.Web/resources/css/home/home.course.css | CSS | apache-2.0 | 407 |
#include "AdSelector.h"
#include "AdClickPredictor.h"
#include "AdRecommender.h"
#include <search-manager/HitQueue.h>
#include <document-manager/DocumentManager.h>
#include <mining-manager/group-manager/GroupManager.h>
#include <la-manager/TitlePCAWrapper.h>
#include <glog/logging.h>
#include <boost/filesystem.hpp>
#include <boost/dynamic_bitset.hpp>
#define MAX_HISTORY_CTR_NUM 1024*1024*16
namespace bfs = boost::filesystem;
namespace sf1r
{
static const std::string linker("-");
static const std::string UnknownStr("Unknown");
static const double E_GREEDY_RATIO = 0.1;
static bool sort_tokens_func(const std::pair<std::string, double>& left, const std::pair<std::string, double>& right)
{
return left.second > right.second;
}
static inline void getValueStrFromPropId(faceted::PropValueTable* pvt,
const faceted::PropValueTable::PropIdList& propids, AdSelector::FeatureValueT& value_list)
{
//return boost::lexical_cast<std::string>(pvid) + "-";
value_list.clear();
// may have multi value.
std::vector<izenelib::util::UString> value;
for (size_t k = 0; k < propids.size(); ++k)
{
pvt->propValuePath(propids[k], value, false);
if (value.empty()) continue;
std::string valuestr;
value[0].convertString(valuestr, izenelib::util::UString::UTF_8);
value_list.push_back(valuestr);
}
}
AdSelector::AdSelector()
:history_ctr_data_(MAX_HISTORY_CTR_NUM/1024)
, random_eng_(std::time(NULL))
, random_gen_(random_eng_, DistributionT())
, need_refresh_(true)
, ad_segid_str_data_(Lux::IO::NONCLUSTER)
{
}
AdSelector::~AdSelector()
{
stop();
}
void AdSelector::loadDef(const std::string& file, FeatureMapT& def_features,
std::map<std::string, std::size_t>& init_counter)
{
std::ifstream ifs_def(file.c_str());
while(ifs_def.good())
{
std::string feature_name;
std::getline(ifs_def, feature_name);
if (!feature_name.empty())
{
def_features[feature_name] = FeatureValueT();
init_counter[feature_name] = 0;
}
}
if (def_features.empty())
{
throw std::runtime_error("no default features in file : " + file);
}
}
void AdSelector::init(const std::string& res_path,
const std::string& segments_data_path,
const std::string& rec_data_path,
bool enable_rec,
AdClickPredictor* pad_predictor,
faceted::GroupManager* grp_mgr,
DocumentManager* doc_mgr)
{
res_path_ = res_path;
segments_data_path_ = segments_data_path;
rec_data_path_ = rec_data_path;
ad_click_predictor_ = pad_predictor;
groupManager_ = grp_mgr;
doc_mgr_ = doc_mgr;
//
// load default all features from config file.
loadDef(res_path_ + "/all_user_feature_name.txt", default_full_features_[UserSeg], init_counter_[UserSeg]);
loadDef(res_path_ + "/all_ad_feature_name.txt", default_full_features_[AdSeg], init_counter_[AdSeg]);
load();
bfs::create_directories(segments_data_path_ + "/segid/");
ad_segid_mgr_.reset(new AdSegIDManager(segments_data_path_ + "/segid/"));
ad_segid_str_data_.set_noncluster_params(Lux::IO::Linked);
ad_segid_str_data_.set_lock_type(Lux::IO::LOCK_THREAD);
if (bfs::exists(segments_data_path_ + "ad_segid_str.data"))
{
ad_segid_str_data_.open(segments_data_path_ + "/ad_segid_str.data", Lux::IO::DB_RDWR);
}
else
{
ad_segid_str_data_.open(segments_data_path_ + "/ad_segid_str.data", Lux::IO::DB_CREAT);
}
all_segments_.resize(TotalSeg);
for (size_t i = 0; i < TotalSeg; ++i)
{
FeatureMapT& segments = all_segments_[i];
if (segments.empty())
{
segments = default_full_features_[i];
for(FeatureMapT::iterator it = segments.begin();
it != segments.end(); ++it)
{
it->second.push_back(UnknownStr);
}
}
else
{
// make sure the default full features is the same size with current loaded segments.
// remove old abandoned feature and add new added feature.
FeatureMapT::iterator allseg_it = segments.begin();
while(allseg_it != segments.end())
{
if (default_full_features_[i].find(allseg_it->first) == default_full_features_[i].end())
{
segments.erase(allseg_it++);
}
else
++allseg_it;
}
FeatureValueT tmp;
tmp.push_back(UnknownStr);
for(FeatureMapT::const_iterator it = default_full_features_[i].begin();
it != default_full_features_[i].end(); ++it)
{
if (segments.find(it->first) == segments.end())
{
segments[it->first] = tmp;
}
}
}
}
ctr_update_thread_ = boost::thread(boost::bind(&AdSelector::updateFunc, this));
if (enable_rec)
{
ad_feature_item_rec_.reset(new AdRecommender());
ad_feature_item_rec_->init(rec_data_path_, false);
}
}
void AdSelector::getDefaultFeatures(FeatureMapT& feature_name_list, SegType type)
{
feature_name_list = default_full_features_[type];
}
void AdSelector::load()
{
std::ifstream ifs(std::string(segments_data_path_ + "/clicked_ad.data").c_str());
if (ifs.good())
{
std::size_t num = 0;
ifs.read((char*)&num, sizeof(num));
std::vector<docid_t> clicked_list;
clicked_list.resize(num);
ifs.read((char*)&clicked_list[0], sizeof(clicked_list[0])*num);
for(size_t i = 0; i < clicked_list.size(); ++i)
{
clicked_ads_.set(clicked_list[i]);
}
}
LOG(INFO) << "clicked data loaded, total clicked num: " << clicked_ads_.count();
std::ifstream ifs_seg(std::string(segments_data_path_ + "/all_segments.data").c_str());
if (ifs_seg.good())
{
std::size_t len = 0;
ifs_seg.read((char*)&len, sizeof(len));
std::string data;
data.resize(len);
ifs_seg.read((char*)&data[0], len);
izenelib::util::izene_deserialization<std::vector<FeatureMapT> > izd(data.data(), data.size());
izd.read_image(all_segments_);
}
LOG(INFO) << "segments loaded: " << all_segments_.size();
std::ifstream ifs_segid_data(std::string(segments_data_path_ + "/ad_segid.data").c_str());
if (ifs_segid_data.good())
{
std::size_t len = 0;
ifs_segid_data.read((char*)&len, sizeof(len));
std::string data;
data.resize(len);
ifs_segid_data.read((char*)&data[0], len);
izenelib::util::izene_deserialization<std::vector<std::vector<SegIdT> > > izd(data.data(), data.size());
izd.read_image(ad_segid_data_);
}
LOG(INFO) << "ad_segid data loaded: " << ad_segid_data_.size();
}
void AdSelector::save()
{
std::ofstream ofs(std::string(segments_data_path_ + "/clicked_ad.data").c_str());
std::vector<docid_t> clicked_list;
for(std::size_t i = 0; i < clicked_ads_.size(); ++i)
{
if (clicked_ads_.test(i))
clicked_list.push_back(i);
}
std::size_t len = clicked_list.size();
ofs.write((const char*)&len, sizeof(len));
if (!clicked_list.empty())
ofs.write((const char*)&clicked_list[0], sizeof(clicked_list[0])*clicked_list.size());
ofs.flush();
std::ofstream ofs_seg(std::string(segments_data_path_ + "/all_segments.data").c_str());
len = 0;
char* buf = NULL;
izenelib::util::izene_serialization<std::vector<FeatureMapT> > izs(all_segments_);
izs.write_image(buf, len);
ofs_seg.write((const char*)&len, sizeof(len));
ofs_seg.write(buf, len);
ofs_seg.flush();
ad_segid_mgr_->flush();
{
boost::shared_lock<boost::shared_mutex> lock(ad_segid_mutex_);
std::ofstream ofs_segid_data(std::string(segments_data_path_ + "/ad_segid.data").c_str());
len = 0;
buf = NULL;
izenelib::util::izene_serialization<std::vector<std::vector<SegIdT> > > izs_segid_data(ad_segid_data_);
izs_segid_data.write_image(buf, len);
ofs_segid_data.write((const char*)&len, sizeof(len));
ofs_segid_data.write(buf, len);
ofs_segid_data.flush();
}
if (ad_feature_item_rec_)
ad_feature_item_rec_->save();
}
void AdSelector::stop()
{
ctr_update_thread_.interrupt();
ctr_update_thread_.join();
save();
ad_segid_str_data_.close();
}
// one ad may belong to multi segments.
void AdSelector::getAdSegmentStrList(docid_t ad_id, std::vector<std::string>& retstr_list)
{
if (ad_id > ad_segid_data_.size())
return;
boost::shared_lock<boost::shared_mutex> lock(ad_segid_mutex_);
const std::vector<SegIdT>& segids = ad_segid_data_[ad_id];
for(size_t i = 0; i < segids.size(); ++i)
{
Lux::IO::data_t *val_p = NULL;
bool ret = ad_segid_str_data_.get(segids[i], &val_p, Lux::IO::SYSTEM);
if (ret && val_p->size > 0)
{
retstr_list.push_back(std::string());
retstr_list.back().assign((const char*)val_p->data, val_p->size);
}
ad_segid_str_data_.clean_data(val_p);
}
}
void AdSelector::updateAdSegmentStr(docid_t ad_docid, const FeatureMapT& ad_feature, std::vector<SegIdT>& segids)
{
std::vector<std::string> seg_str_list;
seg_str_list.push_back("");
expandSegmentStr(seg_str_list, ad_feature);
segids.clear();
for(size_t j = 0; j < seg_str_list.size(); ++j)
{
if (seg_str_list[j].empty())
continue;
SegIdT segid;
ad_segid_mgr_->getDocIdByDocName(seg_str_list[j], segid, true);
segids.push_back(segid);
ad_segid_str_data_.put(segid, seg_str_list[j].data(), seg_str_list[j].size(), Lux::IO::OVERWRITE);
}
if (ad_docid >= ad_segid_data_.size())
{
boost::unique_lock<boost::shared_mutex> guard;
if (ad_docid >= ad_segid_data_.size())
ad_segid_data_.resize(ad_docid + 1);
}
boost::unique_lock<boost::shared_mutex> lock(ad_segid_mutex_);
ad_segid_data_[ad_docid].swap(segids);
}
void AdSelector::updateAdSegmentStr(const std::vector<docid_t>& ad_doclist, const std::vector<FeatureMapT>& ad_feature_list)
{
assert(ad_doclist.size() == ad_feature_list.size());
std::vector<SegIdT> segids;
for(size_t i = 0; i < ad_doclist.size(); ++i)
{
updateAdSegmentStr(ad_doclist[i], ad_feature_list[i], segids);
}
}
void AdSelector::getAdTagsForRec(docid_t id, std::vector<std::string>& tags)
{
if (doc_mgr_ == NULL)
return;
tags.clear();
// get the title of the ad doc.
std::string ad_title;
Document::doc_prop_value_strtype prop_value;
doc_mgr_->getPropertyValue(id, "Title", prop_value);
ad_title = propstr_to_str(prop_value);
std::vector<std::pair<std::string, float> > tokens, subtokens;
std::string brand;
std::string model;
TitlePCAWrapper::get()->pca(ad_title, tokens, brand, model, subtokens, false);
if (!brand.empty())
{
tags.push_back(brand);
}
if (!model.empty())
{
tags.push_back(model);
}
std::sort(tokens.begin(), tokens.end(), sort_tokens_func);
for (size_t i = 0; i < tokens.size(); ++i)
{
if (tokens[i].first.length() > 1)
tags.push_back(tokens[i].first);
if (tags.size() > 3)
break;
}
}
void AdSelector::updateAdFeatureItemsForRec(docid_t id, const FeatureMapT& features_map)
{
if (!ad_feature_item_rec_)
return;
std::vector<std::string> features;
for (FeatureMapT::const_iterator it = features_map.begin();
it != features_map.end(); ++it)
{
for (std::size_t i = 0; i < it->second.size(); ++i)
{
features.push_back(it->second[i]);
}
}
std::vector<std::string> tags;
getAdTagsForRec(id, tags);
features.insert(features.end(), tags.begin(), tags.end());
ad_feature_item_rec_->updateAdFeatures(boost::lexical_cast<std::string>(id), features);
}
void AdSelector::buildDocument(docid_t docid, const Document& doc)
{
}
void AdSelector::getAdFeatureList(docid_t ad_id, std::vector<std::pair<std::string, std::string> >& feature_list)
{
feature_list.clear();
PropSharedLockSet propSharedLockSet;
std::vector<faceted::PropValueTable*> pvt_list;
std::vector<std::string> prop_name;
const FeatureMapT& def_feature_names = default_full_features_[AdSeg];
for (FeatureMapT::const_iterator feature_it = def_feature_names.begin();
feature_it != def_feature_names.end(); ++feature_it)
{
faceted::PropValueTable* pvt = groupManager_->getPropValueTable(feature_it->first);
if (pvt)
propSharedLockSet.insertSharedLock(pvt);
pvt_list.push_back(pvt);
prop_name.push_back(feature_it->first);
}
faceted::PropValueTable::PropIdList propids;
FeatureValueT value_list;
for (std::size_t feature_index = 0; feature_index < pvt_list.size(); ++feature_index)
{
if (pvt_list[feature_index])
{
pvt_list[feature_index]->getPropIdList(ad_id, propids);
getValueStrFromPropId(pvt_list[feature_index], propids, value_list);
for (std::size_t i = 0; i < value_list.size(); ++i)
{
feature_list.push_back(std::make_pair(prop_name[feature_index], value_list[i]));
}
}
}
}
void AdSelector::miningAdSegmentStr(docid_t startid, docid_t endid)
{
if (groupManager_ == NULL)
return;
PropSharedLockSet propSharedLockSet;
std::vector<faceted::PropValueTable*> pvt_list;
std::vector<std::string> prop_name;
std::vector<std::set<std::string> > all_kinds_ad_segments;
const FeatureMapT& def_feature_names = default_full_features_[AdSeg];
for (FeatureMapT::const_iterator feature_it = def_feature_names.begin();
feature_it != def_feature_names.end(); ++feature_it)
{
faceted::PropValueTable* pvt = groupManager_->getPropValueTable(feature_it->first);
if (pvt)
propSharedLockSet.insertSharedLock(pvt);
pvt_list.push_back(pvt);
prop_name.push_back(feature_it->first);
}
all_kinds_ad_segments.resize(pvt_list.size());
faceted::PropValueTable::PropIdList propids;
FeatureValueT value_list;
std::vector<SegIdT> segids;
for (docid_t i = startid; i <= endid; ++i)
{
FeatureMapT ad_feature;
for (std::size_t feature_index = 0; feature_index < pvt_list.size(); ++feature_index)
{
if (pvt_list[feature_index])
{
pvt_list[feature_index]->getPropIdList(i, propids);
getValueStrFromPropId(pvt_list[feature_index], propids, value_list);
ad_feature[prop_name[feature_index]] = value_list;
all_kinds_ad_segments[feature_index].insert(value_list.begin(), value_list.end());
}
}
updateAdSegmentStr(i, ad_feature, segids);
updateAdFeatureItemsForRec(i, ad_feature);
if (i % 100000 == 0)
{
LOG(INFO) << "ad segment mining :" << i;
}
}
FeatureMapT::const_iterator it = def_feature_names.begin();
for (std::size_t i = 0; i < all_kinds_ad_segments.size(); ++i)
{
LOG(INFO) << "found total segments : " << all_kinds_ad_segments[i].size() << " for : " << it->first;
updateSegments(it->first, all_kinds_ad_segments[i], AdSeg);
}
}
void AdSelector::updateFunc()
{
sleep(10);
while(true)
{
try
{
computeHistoryCTR();
need_refresh_ = false;
save();
struct timespec ts;
ts.tv_sec = 10;
ts.tv_nsec = 0;
uint16_t times = 0;
while(times++ < 360)
{
boost::this_thread::interruption_point();
if (need_refresh_)
break;
nanosleep(&ts, NULL);
}
}
catch(boost::thread_interrupted&)
{
LOG(INFO) << "ad selector update thread exited.";
break;
}
catch(const std::exception& e)
{
LOG(WARNING) << "error in ad selector update thread : " << e.what();
}
}
}
void AdSelector::getAllPossibleSegStr(const FeatureMapT& segments,
std::map<std::string, std::size_t> segments_counter,
std::map<std::string, FeatureT>& all_keys)
{
assert(segments_counter.size() == segments.size());
std::map<std::string, std::size_t>::reverse_iterator counter_it = segments_counter.rbegin();
std::map<std::string, std::size_t>::reverse_iterator inc_counter_it = segments_counter.rbegin();
FeatureT segment_data;
while(inc_counter_it != segments_counter.rend())
{
std::string key;
segment_data.clear();
for(FeatureMapT::const_iterator segit = segments.begin();
segit != segments.end(); ++segit)
{
const std::string& value = segit->second[segments_counter[segit->first]];
if (value != UnknownStr)
{
key += value + linker;
segment_data.push_back(std::make_pair(segit->first, value));
}
}
all_keys[key] = segment_data;
FeatureMapT::const_iterator finded_it = segments.find(counter_it->first);
while (counter_it->second >= finded_it->second.size() - 1)
{
counter_it->second = 0;
++counter_it;
if (counter_it == segments_counter.rend())
break;
finded_it = segments.find(counter_it->first);
}
if (counter_it != segments_counter.rend())
++(counter_it->second);
else
break;
counter_it = inc_counter_it;
}
}
void AdSelector::computeHistoryCTR()
{
// Load new segments from files or from DMP server.
std::map<std::string, std::set<std::string> > distinct_values[all_segments_.size()];
for (size_t seg_index = 0; seg_index < all_segments_.size(); ++seg_index)
{
for(FeatureMapT::iterator it = all_segments_[seg_index].begin();
it != all_segments_[seg_index].end(); ++it)
{
distinct_values[seg_index][it->first].insert(it->second.begin(), it->second.end());
LOG(INFO) << "seg type: " << seg_index << ", seg_name:" << it->first << ", segment value num: " << it->second.size();
}
if (!updated_segments_[seg_index].empty())
{
boost::unique_lock<boost::mutex> lock(segment_mutex_);
LOG(INFO) << "update new segments : " << updated_segments_[seg_index].size();
for(FeatureMapT::const_iterator cit = updated_segments_[seg_index].begin();
cit != updated_segments_[seg_index].end(); ++cit)
{
LOG(INFO) << "key: " << cit->first << ", new value num : " << cit->second.size();
FeatureMapT::iterator seg_it = all_segments_[seg_index].find(cit->first);
if (seg_it == all_segments_[seg_index].end())
continue;
for(size_t i = 0; i < cit->second.size(); ++i)
{
if (distinct_values[seg_index][cit->first].find(cit->second[i]) == distinct_values[seg_index][cit->first].end())
{
seg_it->second.push_back(cit->second[i]);
distinct_values[seg_index][cit->first].insert(cit->second[i]);
}
}
}
updated_segments_[seg_index].clear();
}
}
LOG(INFO) << "begin compute history ctr.";
// update the history ctr every few hours.
// Compute the CTR for each user segment and each ad segment.
//
typedef std::map<std::string, FeatureT> AllSegKeyListT;
AllSegKeyListT all_fullkey[TotalSeg];
getAllPossibleSegStr(all_segments_[UserSeg], init_counter_[UserSeg], all_fullkey[UserSeg]);
getAllPossibleSegStr(all_segments_[AdSeg], init_counter_[AdSeg], all_fullkey[AdSeg]);
if (all_fullkey[UserSeg].size() * all_fullkey[AdSeg].size() > MAX_HISTORY_CTR_NUM/2)
{
LOG(WARNING) << "the full key for all history is too large, compute by need. "
<< all_fullkey[UserSeg].size() << ", " << all_fullkey[AdSeg].size();
updatePendingHistoryCTRData();
}
else
{
std::string history_ctr_file = segments_data_path_ + "/history_ctr.txt";
std::ofstream ofs_history(history_ctr_file.c_str());
for (AllSegKeyListT::const_iterator user_it = all_fullkey[UserSeg].begin();
user_it != all_fullkey[UserSeg].end(); ++user_it)
{
for (AllSegKeyListT::const_iterator ad_it = all_fullkey[AdSeg].begin();
ad_it != all_fullkey[AdSeg].end(); ++ad_it)
{
//std::string ad_seg_str;
SegIdT segid = 0;
if (!ad_it->first.empty())
{
ad_segid_mgr_->getDocIdByDocName(ad_it->first, segid, true);
//ad_seg_str = boost::lexical_cast<std::string>(segid);
}
double ctr_res = ad_click_predictor_->predict(user_it->second, ad_it->second);
const std::string& key = user_it->first;
if (segid >= history_ctr_data_[key].size())
{
history_ctr_data_[key].resize(segid + 1);
}
history_ctr_data_[key][segid] = ctr_res;
ofs_history << key << "-" << segid << " : " << ctr_res << std::endl;
}
}
ofs_history.flush();
}
LOG(INFO) << "update history ctr finished. total : " << history_ctr_data_.size();
}
void AdSelector::updatePendingHistoryCTRData()
{
std::vector<std::pair<FeatureT, std::vector<docid_t> > > tmp_pending_list;
{
boost::unique_lock<boost::mutex> guard(pending_list_lock_);
tmp_pending_list.swap(pending_compute_doclist_);
}
if (tmp_pending_list.empty())
return;
LOG(INFO) << "begin compute pending history ctr. " << tmp_pending_list.size();
std::map<std::string, FeatureT> ad_features;
getAllPossibleSegStr(all_segments_[AdSeg], init_counter_[AdSeg], ad_features);
std::string history_ctr_file = segments_data_path_ + "/history_ctr.txt";
std::ofstream ofs_history(history_ctr_file.c_str(), ios::app);
std::vector<std::string> value_list;
std::vector<std::string> ad_segstr_list;
for(size_t i = 0; i < tmp_pending_list.size(); ++i)
{
const FeatureT& user_info = tmp_pending_list[i].first;
const std::vector<docid_t>& docid_list = tmp_pending_list[i].second;
std::vector<std::string> user_seg_str;
getUserSegmentStr(user_seg_str, user_info);
for (size_t j = 0; j < docid_list.size(); ++j)
{
docid_t docid = docid_list[j];
ad_segstr_list.clear();
getAdSegmentStrList(docid, ad_segstr_list);
for (size_t l = 0; l < user_seg_str.size(); ++l)
{
for (size_t k = 0; k < ad_segstr_list.size(); ++k)
{
const std::string& ad_segstr = ad_segstr_list[k];
const std::string& key = user_seg_str[l];
SegIdT segid = 0;
if(!ad_segid_mgr_->getDocIdByDocName(ad_segstr, segid, false))
{
LOG(INFO) << "ad segstr not found: " << ad_segstr;
continue;
}
double result = ad_click_predictor_->predict(user_info, ad_features[ad_segstr]);
if (segid >= history_ctr_data_[key].size())
{
history_ctr_data_[key].resize(segid + 1);
}
history_ctr_data_[key][segid] = result;
ofs_history << key << "-" << segid << " : " << result << std::endl;
}
}
}
}
ofs_history.flush();
LOG(INFO) << "pending history ctr compute finished. " << history_ctr_data_.size();
}
void AdSelector::updateSegments(const std::string& segment_name, const std::set<std::string>& segments, SegType type)
{
boost::unique_lock<boost::mutex> lock(segment_mutex_);
need_refresh_ = true;
std::pair<FeatureMapT::iterator, bool> inserted_it = updated_segments_[type].insert(std::make_pair(segment_name, std::vector<std::string>()));
for(std::set<std::string>::const_iterator cit = segments.begin(); cit != segments.end(); ++cit)
{
inserted_it.first->second.push_back(*cit);
}
}
void AdSelector::updateSegments(const FeatureT& segments, SegType type)
{
boost::unique_lock<boost::mutex> lock(segment_mutex_);
for(FeatureT::const_iterator cit = segments.begin();
cit != segments.end(); ++cit)
{
//FeatureMapT::iterator uit = updated_segments_.find(cit->first);
//if (uit == updated_segments_.end())
// continue;
updated_segments_[type][cit->first].push_back(cit->second);
}
}
void AdSelector::updateClicked(docid_t ad_id)
{
clicked_ads_.set(ad_id);
}
void AdSelector::expandSegmentStr(std::vector<std::string>& seg_str_list, const std::vector<SegIdT>& ad_segid_list)
{
if (ad_segid_list.empty())
{
// ignored feature. Any feature value.
}
else if (ad_segid_list.size() == 1)
{
for(size_t i = 0; i < seg_str_list.size(); ++i)
{
seg_str_list[i] += boost::lexical_cast<std::string>(ad_segid_list[0]);
}
}
else
{
// for multi feature values we just get the highest ctr.
std::size_t oldsize = seg_str_list.size();
for(size_t i = 0; i < oldsize; ++i)
{
for(size_t j = 1; j < ad_segid_list.size(); ++j)
{
seg_str_list.push_back(seg_str_list[i]);
seg_str_list.back() += boost::lexical_cast<std::string>(ad_segid_list[j]);
}
seg_str_list[i] += boost::lexical_cast<std::string>(ad_segid_list[0]);
}
}
}
void AdSelector::expandSegmentStr(std::vector<std::string>& seg_str_list, const FeatureMapT& feature_list)
{
for(FeatureMapT::const_iterator it = feature_list.begin();
it != feature_list.end(); ++it)
{
if (it->second.empty())
{
// ignored feature. Any feature value.
}
else if (it->second.size() == 1)
{
for(size_t i = 0; i < seg_str_list.size(); ++i)
{
seg_str_list[i] += it->second[0] + linker;
}
}
else
{
// for multi feature values we just get the highest ctr.
std::size_t oldsize = seg_str_list.size();
for(size_t i = 0; i < oldsize; ++i)
{
for(size_t j = 1; j < it->second.size(); ++j)
{
seg_str_list.push_back(seg_str_list[i]);
seg_str_list.back() += it->second[j] + linker;
}
seg_str_list[i] += it->second[0] + linker;
}
}
}
}
void AdSelector::getUserSegmentStr(std::vector<std::string>& user_seg_str_list, const FeatureT& user_info)
{
FeatureMapT user_feature_list;
for (size_t i = 0; i < user_info.size(); ++i)
{
user_feature_list[user_info[i].first].push_back(user_info[i].second);
}
user_seg_str_list.push_back("");
expandSegmentStr(user_seg_str_list, user_feature_list);
}
bool AdSelector::getHistoryCTR(const std::vector<std::string>& user_seg_key,
const std::vector<SegIdT>& ad_segid_list, double& max_ctr) const
{
max_ctr = 0;
bool ret = false;
if (ad_segid_list.empty())
{
ret = true;
}
else
{
// for multi feature values we just get the highest ctr.
for(size_t i = 0; i < user_seg_key.size(); ++i)
{
HistoryCTRDataT::const_iterator it = history_ctr_data_.find(user_seg_key[i]);
if (it == history_ctr_data_.end())
continue;
for(size_t j = 0; j < ad_segid_list.size(); ++j)
{
if (ad_segid_list[j] >= it->second.size())
continue;
max_ctr = std::max(it->second[ad_segid_list[j]], max_ctr);
ret = true;
}
}
}
return ret;
}
void AdSelector::selectByRandSelectPolicy(std::size_t max_unclicked_retnum, std::vector<docid_t>& unclicked_doclist)
{
std::set<int> rand_index_list;
for(size_t i = 0; i < max_unclicked_retnum; ++i)
{
rand_index_list.insert(random_gen_());
}
std::vector<docid_t> tmp_doclist;
tmp_doclist.reserve(rand_index_list.size());
for(std::set<int>::const_iterator it = rand_index_list.begin();
it != rand_index_list.end(); ++it)
{
tmp_doclist.push_back(unclicked_doclist[(*it) % unclicked_doclist.size()]);
}
tmp_doclist.swap(unclicked_doclist);
}
bool AdSelector::selectFromRecommend(const FeatureT& user_info,
std::size_t max_return,
std::vector<std::string>& recommended_items,
std::vector<double>& score_list
)
{
if (ad_feature_item_rec_)
ad_feature_item_rec_->recommend("", user_info, max_return, recommended_items, score_list);
// select the ads from recommend system if no any search results.
return false;
}
// the ad feature should be full of all possible kinds of feature,
// this can be done while indexing the ad data.
bool AdSelector::select(const FeatureT& user_info,
std::size_t max_select,
std::vector<docid_t>& ad_doclist,
std::vector<double>& score_list,
PropSharedLockSet& propSharedLockSet)
{
//if (ad_feature_list.size() != ad_doclist.size())
//{
// LOG(ERROR) << "ad features not match doclist.";
// return false;
//}
if (ad_doclist.empty())
{
return false;
}
std::vector<std::string> user_seg_str;
getUserSegmentStr(user_seg_str, user_info);
std::size_t max_clicked_retnum = max_select/3 + 1;
std::size_t max_unclicked_retnum = max_select - max_clicked_retnum;
//std::map<docid_t, const FeatureMapT*> clicked_docfeature_list;
std::vector<docid_t> unclicked_doclist;
unclicked_doclist.reserve(ad_doclist.size());
std::size_t max_tmp_clicked_num = max_clicked_retnum * 2;
ScoreSortedHitQueue tmp_clicked_scorelist(max_tmp_clicked_num);
ScoreSortedHitQueue tmp_unclicked_scorelist(max_unclicked_retnum);
std::vector<docid_t> pending_compute_doclist;
// rank by random in e-greedy strategy.
bool random_select = false;
if (random_gen_() % 1000 < E_GREEDY_RATIO*1000)
{
random_select = true;
}
for(size_t i = 0; i < ad_doclist.size(); ++i)
{
const docid_t& docid = ad_doclist[i];
double score = 0;
if (clicked_ads_.test(docid))
{
// for clicked item, we filter the result first by the history ctr.
// we can also select by random from clicked ads in a little possible.
// It may avoid the possible noisy due to small sample size.
if (ad_doclist.size() > max_tmp_clicked_num)
{
//all_fullkey = user_seg_str;
//expandSegmentStr(all_fullkey, ad_segid_data_[docid]);
if(!getHistoryCTR(user_seg_str, ad_segid_data_[docid], score))
{
// history not found. pending to compute
// put it to unclicked this time to select by random.
unclicked_doclist.push_back(docid);
pending_compute_doclist.push_back(docid);
continue;
}
}
ScoreDoc item(docid, score);
tmp_clicked_scorelist.insert(item);
}
else
{
if(!random_select && getHistoryCTR(user_seg_str, ad_segid_data_[docid], score))
{
ScoreDoc item(docid, score);
tmp_unclicked_scorelist.insert(item);
}
else
unclicked_doclist.push_back(docid);
}
}
if (!pending_compute_doclist.empty())
{
boost::unique_lock<boost::mutex> guard(pending_list_lock_);
LOG(INFO) << "pending compute doclist : " << pending_compute_doclist.size();
pending_compute_doclist_.push_back(std::make_pair(user_info, std::vector<docid_t>()));
pending_compute_doclist_.back().second.swap(pending_compute_doclist);
need_refresh_ = true;
}
std::size_t scoresize = tmp_clicked_scorelist.size();
// rank the finally filtered clicked item by realtime CTR.
ScoreSortedHitQueue total_scorelist(max_clicked_retnum + tmp_unclicked_scorelist.size());
FeatureT ad_features;
std::vector<faceted::PropValueTable*> pvt_list;
const FeatureMapT& ad_full_features = default_full_features_[AdSeg];
for (FeatureMapT::const_iterator feature_it = ad_full_features.begin();
feature_it != ad_full_features.end(); ++feature_it)
{
faceted::PropValueTable* pvt = NULL;
if (groupManager_)
groupManager_->getPropValueTable(feature_it->first);
if (pvt)
propSharedLockSet.insertSharedLock(pvt);
pvt_list.push_back(pvt);
}
std::vector<std::string> value_list;
for(int i = scoresize - 1; i >= 0; --i)
{
ScoreDoc item;
item.docId = tmp_clicked_scorelist.pop().docId;
ad_features.clear();
faceted::PropValueTable::PropIdList propids;
std::size_t feature_index = 0;
for(FeatureMapT::const_iterator ad_it = ad_full_features.begin(); ad_it != ad_full_features.end(); ++ad_it)
{
if (pvt_list[feature_index])
{
pvt_list[feature_index]->getPropIdList(item.docId, propids);
getValueStrFromPropId(pvt_list[feature_index], propids, value_list);
for(std::size_t j = 0; j < value_list.size(); ++j)
{
ad_features.push_back(std::make_pair(ad_it->first, value_list[j]));
}
}
++feature_index;
}
item.score = ad_click_predictor_->predict(user_info, ad_features);
total_scorelist.insert(item);
}
max_unclicked_retnum -= tmp_unclicked_scorelist.size();
scoresize = tmp_unclicked_scorelist.size();
for(int i = scoresize - 1; i >=0; --i)
{
total_scorelist.insert(tmp_unclicked_scorelist.pop());
}
// random select some un-scored ads.
if (max_unclicked_retnum < unclicked_doclist.size())
{
selectByRandSelectPolicy(max_unclicked_retnum, unclicked_doclist);
}
scoresize = total_scorelist.size();
score_list.resize(ad_doclist.size());
std::size_t ret_i = 0;
double min_score = 0;
for(int i = scoresize - 1; i >= 0; --i)
{
const ScoreDoc& item = total_scorelist.pop();
ad_doclist[i] = item.docId;
score_list[i] = item.score;
if (item.score < min_score)
min_score = item.score;
++ret_i;
}
for(size_t i = 0; i < unclicked_doclist.size(); ++i)
{
ad_doclist[ret_i] = unclicked_doclist[i];
score_list[ret_i] = min_score - 1;
++ret_i;
}
ad_doclist.resize(ret_i);
score_list.resize(ad_doclist.size());
return !ad_doclist.empty();
}
bool AdSelector::selectForTest(const FeatureT& user_info,
std::size_t max_select,
std::vector<docid_t>& ad_doclist,
std::vector<double>& score_list)
{
PropSharedLockSet propSharedLockSet;
return select(user_info, max_select, ad_doclist, score_list, propSharedLockSet);
}
void AdSelector::trainOnlineRecommender(const std::string& user_str_id, const FeatureT& user_info,
const std::string& ad_docid, bool is_clicked)
{
if (!ad_feature_item_rec_)
return;
if (is_clicked)
{
LOG(INFO) << "training clicked data for recommend : " << user_str_id << ". adid: " << ad_docid;
}
ad_feature_item_rec_->update(user_str_id, user_info, ad_docid, is_clicked);
}
}
| izenecloud/sf1r-ad-delivery | source/core/ad-manager/AdSelector.cpp | C++ | apache-2.0 | 36,459 |
# Trifolium longipes var. rusbyi (Greene) H.D.Harr. VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Trifolium/Trifolium rusbyi/ Syn. Trifolium longipes rusbyi/README.md | Markdown | apache-2.0 | 206 |
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Semantics
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
<WorkItem(19819, "https://github.com/dotnet/roslyn/issues/19819")>
Public Sub UsingDeclarationSyntaxNotNull()
Dim source = <compilation>
<file name="c.vb">
<![CDATA[
Imports System
Module Module1
Class C1
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Throw New NotImplementedException()
End Sub
End Class
Sub S1()
Using D1 as New C1()
End Using
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(source, parseOptions:=TestOptions.RegularWithIOperationFeature)
CompilationUtils.AssertNoDiagnostics(comp)
Dim tree = comp.SyntaxTrees.Single()
Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single()
Dim op = DirectCast(comp.GetSemanticModel(tree).GetOperationInternal(node), IUsingStatement)
Assert.NotNull(op.Resources.Syntax)
Assert.Same(node.UsingStatement, op.Resources.Syntax)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
<WorkItem(19887, "https://github.com/dotnet/roslyn/issues/19887")>
Public Sub UsingDeclarationIncompleteUsingInvalidExpression()
Dim source = <compilation>
<file name="c.vb">
<![CDATA[
Imports System
Module Module1
Class C1
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Throw New NotImplementedException()
End Sub
End Class
Sub S1()
Using
End Using
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(source, parseOptions:=TestOptions.RegularWithIOperationFeature)
CompilationUtils.AssertTheseDiagnostics(comp,
<expected>
BC30201: Expression expected.
Using
~
</expected>)
Dim tree = comp.SyntaxTrees.Single()
Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single()
Dim op = DirectCast(comp.GetSemanticModel(tree).GetOperationInternal(node), IUsingStatement)
Assert.Equal(OperationKind.InvalidExpression, op.Resources.Kind)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub IUsingStatement_MultipleNewResources()
Dim source = <![CDATA[
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Using c1 As C = New C, c2 As C = New C'BIND:"Using c1 As C = New C, c2 As C = New C"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using c1 As ... End Using')
Resources:
IVariableDeclarationStatement (2 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Using c1 As ... s C = New C')
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c1')
Variables: Local_1: c1 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: '= New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c2')
Variables: Local_1: c2 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: '= New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using c1 As ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_SingleNewResource()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Using c1 As C = New C'BIND:"Using c1 As C = New C"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using c1 As ... End Using')
Resources:
IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Using c1 As C = New C')
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c1')
Variables: Local_1: c1 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: '= New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using c1 As ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_SingleAsNewResource()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Using c1 As New C'BIND:"Using c1 As New C"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using c1 As ... End Using')
Resources:
IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Using c1 As New C')
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c1')
Variables: Local_1: c1 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: 'As New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using c1 As ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_MultipleAsNewResources()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Using c1, c2 As New C'BIND:"Using c1, c2 As New C"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using c1, c ... End Using')
Resources:
IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Using c1, c2 As New C')
IVariableDeclaration (2 variables) (OperationKind.VariableDeclaration) (Syntax: 'c1, c2 As New C')
Variables: Local_1: c1 As Program.C
Local_2: c2 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: 'As New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using c1, c ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_SingleExistingResource()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Dim c1 As New C
Using c1'BIND:"Using c1"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using c1'BI ... End Using')
Resources:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using c1'BI ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_InvalidMultipleExistingResources()
Dim source = <![CDATA[
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Dim c1, c2 As New C
Using c1, c2'BIND:"Using c1, c2"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement, IsInvalid) (Syntax: 'Using c1, c ... End Using')
Resources:
IVariableDeclarationStatement (2 declarations) (OperationKind.VariableDeclarationStatement, IsInvalid) (Syntax: 'Using c1, c2')
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration, IsInvalid) (Syntax: 'c1')
Variables: Local_1: c1 As System.Object
Initializer:
null
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration, IsInvalid) (Syntax: 'c2')
Variables: Local_1: c2 As System.Object
Initializer:
null
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsInvalid, IsImplicit) (Syntax: 'Using c1, c ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: System.Object) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30616: Variable 'c1' hides a variable in an enclosing block.
Using c1, c2'BIND:"Using c1, c2"
~~
BC36011: 'Using' resource variable must have an explicit initialization.
Using c1, c2'BIND:"Using c1, c2"
~~
BC30616: Variable 'c2' hides a variable in an enclosing block.
Using c1, c2'BIND:"Using c1, c2"
~~
BC42104: Variable 'c1' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.WriteLine(c1)
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_NestedUsing()
Dim source = <![CDATA[
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Dim c1, c2 As New C
Using c1'BIND:"Using c1"
Using c2
Console.WriteLine(c1)
End Using
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using c1'BI ... End Using')
Resources:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using c1'BI ... End Using')
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using c2 ... End Using')
Resources:
ILocalReferenceExpression: c2 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c2')
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using c2 ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_MixedAsNewAndSingleInitializer()
Dim source = <![CDATA[
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Using c1 = New C, c2, c3 As New C'BIND:"Using c1 = New C, c2, c3 As New C"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using c1 = ... End Using')
Resources:
IVariableDeclarationStatement (2 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Using c1 = ... c3 As New C')
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c1')
Variables: Local_1: c1 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: '= New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
IVariableDeclaration (2 variables) (OperationKind.VariableDeclaration) (Syntax: 'c2, c3 As New C')
Variables: Local_1: c2 As Program.C
Local_2: c3 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: 'As New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using c1 = ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_InvalidNoInitializerOneVariable()
Dim source = <![CDATA[
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Dim c2 As New C
Using c1 = New C, c2'BIND:"Using c1 = New C, c2"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement, IsInvalid) (Syntax: 'Using c1 = ... End Using')
Resources:
IVariableDeclarationStatement (2 declarations) (OperationKind.VariableDeclarationStatement, IsInvalid) (Syntax: 'Using c1 = New C, c2')
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c1')
Variables: Local_1: c1 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: '= New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration, IsInvalid) (Syntax: 'c2')
Variables: Local_1: c2 As System.Object
Initializer:
null
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsInvalid, IsImplicit) (Syntax: 'Using c1 = ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30616: Variable 'c2' hides a variable in an enclosing block.
Using c1 = New C, c2'BIND:"Using c1 = New C, c2"
~~
BC36011: 'Using' resource variable must have an explicit initialization.
Using c1 = New C, c2'BIND:"Using c1 = New C, c2"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_InvalidNonDisposableResource()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Class C
End Class
Sub Main(args As String())
Using c1 As New C'BIND:"Using c1 As New C"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement, IsInvalid) (Syntax: 'Using c1 As ... End Using')
Resources:
IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement, IsInvalid) (Syntax: 'Using c1 As New C')
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration, IsInvalid) (Syntax: 'c1')
Variables: Local_1: c1 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer, IsInvalid) (Syntax: 'As New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C, IsInvalid) (Syntax: 'New C')
Arguments(0)
Initializer:
null
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsInvalid, IsImplicit) (Syntax: 'Using c1 As ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36010: 'Using' operand of type 'Program.C' must implement 'System.IDisposable'.
Using c1 As New C'BIND:"Using c1 As New C"
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_InvalidEmptyUsingResource()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main(args As String())
Using'BIND:"Using"
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement, IsInvalid) (Syntax: 'Using'BIND: ... End Using')
Resources:
IInvalidExpression (OperationKind.InvalidExpression, Type: null, IsInvalid) (Syntax: '')
Children(0)
Body:
IBlockStatement (0 statements) (OperationKind.BlockStatement, IsInvalid, IsImplicit) (Syntax: 'Using'BIND: ... End Using')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30201: Expression expected.
Using'BIND:"Using"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_InvalidNothingResources()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main(args As String())
Using Nothing'BIND:"Using Nothing"
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement, IsInvalid) (Syntax: 'Using Nothi ... End Using')
Resources:
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, Constant: null, IsInvalid, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralExpression (OperationKind.LiteralExpression, Type: null, Constant: null, IsInvalid) (Syntax: 'Nothing')
Body:
IBlockStatement (0 statements) (OperationKind.BlockStatement, IsInvalid, IsImplicit) (Syntax: 'Using Nothi ... End Using')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36010: 'Using' operand of type 'Object' must implement 'System.IDisposable'.
Using Nothing'BIND:"Using Nothing"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_UsingWithoutSavedReference()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main(args As String())
Using GetC()'BIND:"Using GetC()"
End Using
End Sub
Function GetC() As C
Return New C
End Function
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using GetC( ... End Using')
Resources:
IInvocationExpression (Function Program.GetC() As Program.C) (OperationKind.InvocationExpression, Type: Program.C) (Syntax: 'GetC()')
Instance Receiver:
null
Arguments(0)
Body:
IBlockStatement (0 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using GetC( ... End Using')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_UsingBlockSyntax_UsingStatementSyntax_WithDeclarationResource()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main(args As String())
Using c1 = New C, c2 = New C'BIND:"Using c1 = New C, c2 = New C"
End Using
End Sub
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationStatement (2 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Using c1 = ... c2 = New C')
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c1')
Variables: Local_1: c1 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: '= New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c2')
Variables: Local_1: c2 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: '= New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_UsingBlockSyntax_UsingStatementSyntax_WithExpressionResource()
Dim source = <compilation>
<file Name="a.vb">
<![CDATA[
Option Strict On
Imports System
Module Program
Sub Main(args As String())
Dim c1 As New C
Using c1'BIND:"Using c1"
Console.WriteLine()
End Using
End Sub
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Module]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(source, parseOptions:=TestOptions.RegularWithIOperationFeature)
CompilationUtils.AssertNoDiagnostics(comp)
Dim tree = comp.SyntaxTrees.Single()
Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single().UsingStatement
Assert.Null(comp.GetSemanticModel(node.SyntaxTree).GetOperation(node))
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(Skip:="https://github.com/dotnet/roslyn/issues/22362")>
Public Sub IUsingStatement_UsingStatementSyntax_VariablesSyntax()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main(args As String())
Using c1 = New C, c2 = New C'BIND:"c1 = New C"
End Using
End Sub
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Module]]>.Value
' This should be returning a variable declaration, but the associated variable declarator operation has a
' ModifiedIdentifierSyntax as the associated syntax node. Fixing is tracked by
' https://github.com/dotnet/roslyn/issues/22362
Dim expectedOperationTree = <![CDATA[
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_UsingStatementSyntax_Expression()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main(args As String())
Dim c1 As New C
Using c1'BIND:"c1"
Console.WriteLine()
End Using
End Sub
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_UsingBlockSyntax_StatementsSyntax()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main(args As String())
Using c1 = New C, c2 = New C
Console.WriteLine()'BIND:"Console.WriteLine()"
End Using
End Sub
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationExpression (Sub System.Console.WriteLine()) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ExpressionStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
End Class
End Namespace
| pdelvo/roslyn | src/Compilers/VisualBasic/Test/Semantic/IOperation/IOperationTests_IUsingStatement.vb | Visual Basic | apache-2.0 | 43,240 |
/*
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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.
*/
const ApiCreationComponent: ng.IComponentOptions = {
bindings: {
tags: '<',
tenants: '<',
groups: '<',
},
template: require('./api-creation.html'),
controller: 'ApiCreationController',
};
export default ApiCreationComponent;
| gravitee-io/gravitee-management-webui | src/management/api/creation/steps/api-creation.component.ts | TypeScript | apache-2.0 | 876 |
\documentclass{beamer}
\usepackage{verbatim} % comment enviroment
\graphicspath{{./images/}}
\newcommand{\dataframe}[1]
{
\begin{frame}
\frametitle{#1}
\begin{center}
\includegraphics[height=0.25\textheight]{#1Plot.png} \\
\includegraphics[height=0.25\textheight]{#1Singlescale.png} \\
\includegraphics[height=0.25\textheight]{#1Multiscale.png} \\
\end{center}
\end{frame}
}
\begin{document}
\begin{frame}
\begin{itemize}
\item Ran two LDDMM experiments with $\alpha = 0.02$
\begin{itemize}
\item \textbf{Multi-Scale} experiment ran at 800$\mu m$, 400$\mu m$, 200$\mu m$, 100$\mu m$ and then 50$\mu m$ level
\item \textbf{Single-Scale} experment ran at 50 $\mu m$ level.
\end{itemize}
\item Mutual Information (MI) was recorded at the end of each resolution level
\item Mutual Information has been normalized to $[0,1.0]$
\begin{itemize}
\item 1.0 = Worst case (No registration)
\item 0 = Best case (Template = Target)
\end{itemize}
\end{itemize}
\end{frame}
\dataframe{Cocaine174}
\dataframe{Cocaine175}
\dataframe{Cocaine178}
%\dataframe{Control181}
\dataframe{Control182}
\dataframe{Control189}
\dataframe{Control258}
\dataframe{Fear187}
\dataframe{Fear197}
\dataframe{Fear199}
\end{document}
| openconnectome/ndreg | results/clarityMultiscale/clarityMultiscaleResults.tex | TeX | apache-2.0 | 1,285 |
<?php
$member=get_member_account();
$openid =$member['openid'] ;
$orderid = intval($_GP['orderid']);
$order = mysqld_select("SELECT * FROM " . table('shop_order') . " WHERE id = :id and openid =:openid", array(':id' => $orderid,':openid'=>$openid));
$goodsstr="";
if(empty($order['id']))
{
message("未找到相关订单");
}
if($_GP['isok'] == '1'&&$order['paytypecode']=='weixin') {
message('支付成功!',WEBSITE_ROOT.mobile_url('myorder'),'success');
}
if (($order['paytype'] !=3 && $order['status'] >0)&&(!($order['paytype'] ==3&&$order['status'] ==1))) {
message('抱歉,您的订单已经付款或是被关闭,请重新进入付款!', mobile_url('myorder'), 'error');
}
$ordergoods = mysqld_selectall("SELECT goodsid,optionid,total FROM " . table('shop_order_goods') . " WHERE orderid = '{$orderid}'");
if (!empty($ordergoods)) {
$goodsids=array();
foreach ($ordergoods as $gooditem) {
$goodsids[]=$gooditem['goodsid'];
}
$goods = mysqld_selectall("SELECT id, title, thumb, marketprice, total,credit FROM " . table('shop_goods') . " WHERE id IN ('" . implode("','", $goodsids) . "')");
}
$goodtitle='';
if (!empty($goods)) {
foreach ($goods as $row) {
if(empty($goodtitle))
{
$goodtitle=$row['title'];
}
$_optionid=$ordergoods[$row['id']]['optionid'];
$optionidtitle ='';
if(!empty($_optionid))
{
$optionidtitle = mysqld_select("select title from " . table("shop_goods_option")." where id=:id",array('id'=>$_optionid));
$optionidtitle=$optionidtitle['title'];
}
$goodsstr .="{$row['title']} {$optionidtitle} X{$ordergoods[$row['id']]['total']}\n";
}
}
$paytypecode=$order['paytypecode'];
if(!empty($_GP['paymentcode']))
{
$paytypecode=$_GP['paymentcode'];
}
$payment = mysqld_select("select * from " . table("payment")." where enabled=1 and `code`=:code ",array('code'=>$paytypecode));
if(empty($payment['id']))
{
message("未找到付款方式,付款失败");
}
if(!empty($order['isverify'])&&empty($payment['online']))
{
message("核销产品订单只能在线付款!");
}
if($order['paytypecode']!=$paytypecode)
{
$paytype=$this->getPaytypebycode($paytypecode);
mysqld_update('shop_order', array('paytypecode'=>$payment['code'],'paytypename'=>$payment['name'],'paytype'=>$paytype),array('id'=>$orderid));
}
require(WEB_ROOT.'/system/modules/plugin/payment/'.$paytypecode.'/payaction.php');
exit; | jaydom/weishang | system/shopwap/class/mobile/pay.php | PHP | apache-2.0 | 3,183 |
namespace artesanatoCapixaba
{
partial class cadastroTipoProduto
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.boxInfo = new System.Windows.Forms.GroupBox();
this.btnDeletar = new System.Windows.Forms.Button();
this.boxProduto = new System.Windows.Forms.GroupBox();
this.gridTipoDeProduto = new System.Windows.Forms.DataGridView();
this.txtSigla = new System.Windows.Forms.TextBox();
this.btnCriarTipoDeProduto = new System.Windows.Forms.Button();
this.lblSigla = new System.Windows.Forms.Label();
this.txtProduto = new System.Windows.Forms.TextBox();
this.lblTProduto = new System.Windows.Forms.Label();
this.boxInfo.SuspendLayout();
this.boxProduto.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.gridTipoDeProduto)).BeginInit();
this.SuspendLayout();
//
// boxInfo
//
this.boxInfo.BackColor = System.Drawing.Color.Snow;
this.boxInfo.Controls.Add(this.btnDeletar);
this.boxInfo.Controls.Add(this.boxProduto);
this.boxInfo.Controls.Add(this.txtSigla);
this.boxInfo.Controls.Add(this.btnCriarTipoDeProduto);
this.boxInfo.Controls.Add(this.lblSigla);
this.boxInfo.Controls.Add(this.txtProduto);
this.boxInfo.Controls.Add(this.lblTProduto);
this.boxInfo.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.boxInfo.Location = new System.Drawing.Point(12, 12);
this.boxInfo.Name = "boxInfo";
this.boxInfo.Size = new System.Drawing.Size(540, 246);
this.boxInfo.TabIndex = 1;
this.boxInfo.TabStop = false;
this.boxInfo.Text = "Cadastro de Tipo do Produto";
//
// btnDeletar
//
this.btnDeletar.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
this.btnDeletar.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnDeletar.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnDeletar.Location = new System.Drawing.Point(13, 200);
this.btnDeletar.Name = "btnDeletar";
this.btnDeletar.Size = new System.Drawing.Size(174, 31);
this.btnDeletar.TabIndex = 4;
this.btnDeletar.Text = "D E L E T A R";
this.btnDeletar.UseVisualStyleBackColor = false;
this.btnDeletar.Click += new System.EventHandler(this.btnDeletar_Click);
//
// boxProduto
//
this.boxProduto.Controls.Add(this.gridTipoDeProduto);
this.boxProduto.Location = new System.Drawing.Point(215, 25);
this.boxProduto.Name = "boxProduto";
this.boxProduto.Size = new System.Drawing.Size(313, 205);
this.boxProduto.TabIndex = 12;
this.boxProduto.TabStop = false;
this.boxProduto.Text = "Produtos";
//
// gridTipoDeProduto
//
this.gridTipoDeProduto.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.gridTipoDeProduto.Location = new System.Drawing.Point(6, 22);
this.gridTipoDeProduto.Name = "gridTipoDeProduto";
this.gridTipoDeProduto.Size = new System.Drawing.Size(301, 174);
this.gridTipoDeProduto.TabIndex = 5;
//
// txtSigla
//
this.txtSigla.Location = new System.Drawing.Point(13, 113);
this.txtSigla.Name = "txtSigla";
this.txtSigla.Size = new System.Drawing.Size(174, 26);
this.txtSigla.TabIndex = 2;
this.txtSigla.Leave += new System.EventHandler(this.txtSigla_Leave);
//
// btnCriarTipoDeProduto
//
this.btnCriarTipoDeProduto.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
this.btnCriarTipoDeProduto.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnCriarTipoDeProduto.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnCriarTipoDeProduto.Location = new System.Drawing.Point(13, 154);
this.btnCriarTipoDeProduto.Name = "btnCriarTipoDeProduto";
this.btnCriarTipoDeProduto.Size = new System.Drawing.Size(174, 31);
this.btnCriarTipoDeProduto.TabIndex = 3;
this.btnCriarTipoDeProduto.Text = "C R I A R";
this.btnCriarTipoDeProduto.UseVisualStyleBackColor = false;
this.btnCriarTipoDeProduto.Click += new System.EventHandler(this.btnCriarTipoDeProduto_Click);
//
// lblSigla
//
this.lblSigla.AutoSize = true;
this.lblSigla.Location = new System.Drawing.Point(9, 91);
this.lblSigla.Name = "lblSigla";
this.lblSigla.Size = new System.Drawing.Size(55, 19);
this.lblSigla.TabIndex = 9;
this.lblSigla.Text = "Sigla:";
//
// txtProduto
//
this.txtProduto.Location = new System.Drawing.Point(13, 51);
this.txtProduto.Name = "txtProduto";
this.txtProduto.Size = new System.Drawing.Size(174, 26);
this.txtProduto.TabIndex = 1;
this.txtProduto.Leave += new System.EventHandler(this.txtProduto_Leave);
//
// lblTProduto
//
this.lblTProduto.AutoSize = true;
this.lblTProduto.Location = new System.Drawing.Point(9, 29);
this.lblTProduto.Name = "lblTProduto";
this.lblTProduto.Size = new System.Drawing.Size(140, 19);
this.lblTProduto.TabIndex = 0;
this.lblTProduto.Text = "Tipo do Produto:";
//
// cadastroTipoProduto
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.Snow;
this.ClientSize = new System.Drawing.Size(565, 274);
this.Controls.Add(this.boxInfo);
this.Name = "cadastroTipoProduto";
this.Text = "Artesanato Capixaba - Cadastro de Tipo do Produto";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.cadastroTipoProduto_FormClosed);
this.boxInfo.ResumeLayout(false);
this.boxInfo.PerformLayout();
this.boxProduto.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.gridTipoDeProduto)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox boxInfo;
private System.Windows.Forms.Button btnDeletar;
private System.Windows.Forms.GroupBox boxProduto;
private System.Windows.Forms.DataGridView gridTipoDeProduto;
private System.Windows.Forms.TextBox txtSigla;
private System.Windows.Forms.Button btnCriarTipoDeProduto;
private System.Windows.Forms.Label lblSigla;
private System.Windows.Forms.TextBox txtProduto;
private System.Windows.Forms.Label lblTProduto;
}
} | joaosito00/artesanatoCapixaba | artesanatoCapixaba/cadastroTipoProduto.Designer.cs | C# | apache-2.0 | 8,328 |
package sample.failurewall
import scala.concurrent.Future
case class Response(status: Int, body: String)
class HttpClient {
def get(url: String): Future[Response] = {
println(url)
url match {
case "not url" => Future.failed(new IllegalArgumentException)
case "https://400.failure/" => Future.successful(Response(400, "BAD_REQUEST"))
case "https://500.failure/" => Future.successful(Response(500, "INTERNAL_SERVER_ERROR"))
case "https://maintenance.failure/" => Future.successful(Response(503, "MAINTENANCE"))
case _ => Future.successful(Response(200, "OK"))
}
}
}
| failurewall/failurewall | failurewall-sample/src/main/scala/sample/failurewall/HttpClient.scala | Scala | apache-2.0 | 613 |
package consensus
import (
"context"
"errors"
"fmt"
"runtime/debug"
"sync"
"time"
cstypes "github.com/tendermint/tendermint/internal/consensus/types"
"github.com/tendermint/tendermint/internal/eventbus"
"github.com/tendermint/tendermint/internal/p2p"
sm "github.com/tendermint/tendermint/internal/state"
"github.com/tendermint/tendermint/libs/bits"
tmevents "github.com/tendermint/tendermint/libs/events"
"github.com/tendermint/tendermint/libs/log"
"github.com/tendermint/tendermint/libs/service"
tmtime "github.com/tendermint/tendermint/libs/time"
tmcons "github.com/tendermint/tendermint/proto/tendermint/consensus"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/tendermint/tendermint/types"
)
var (
_ service.Service = (*Reactor)(nil)
_ p2p.Wrapper = (*tmcons.Message)(nil)
)
// GetChannelDescriptor produces an instance of a descriptor for this
// package's required channels.
func getChannelDescriptors() map[p2p.ChannelID]*p2p.ChannelDescriptor {
return map[p2p.ChannelID]*p2p.ChannelDescriptor{
StateChannel: {
ID: StateChannel,
MessageType: new(tmcons.Message),
Priority: 8,
SendQueueCapacity: 64,
RecvMessageCapacity: maxMsgSize,
RecvBufferCapacity: 128,
},
DataChannel: {
// TODO: Consider a split between gossiping current block and catchup
// stuff. Once we gossip the whole block there is nothing left to send
// until next height or round.
ID: DataChannel,
MessageType: new(tmcons.Message),
Priority: 12,
SendQueueCapacity: 64,
RecvBufferCapacity: 512,
RecvMessageCapacity: maxMsgSize,
},
VoteChannel: {
ID: VoteChannel,
MessageType: new(tmcons.Message),
Priority: 10,
SendQueueCapacity: 64,
RecvBufferCapacity: 128,
RecvMessageCapacity: maxMsgSize,
},
VoteSetBitsChannel: {
ID: VoteSetBitsChannel,
MessageType: new(tmcons.Message),
Priority: 5,
SendQueueCapacity: 8,
RecvBufferCapacity: 128,
RecvMessageCapacity: maxMsgSize,
},
}
}
const (
StateChannel = p2p.ChannelID(0x20)
DataChannel = p2p.ChannelID(0x21)
VoteChannel = p2p.ChannelID(0x22)
VoteSetBitsChannel = p2p.ChannelID(0x23)
maxMsgSize = 1048576 // 1MB; NOTE: keep in sync with types.PartSet sizes.
blocksToContributeToBecomeGoodPeer = 10000
votesToContributeToBecomeGoodPeer = 10000
listenerIDConsensus = "consensus-reactor"
)
// NOTE: Temporary interface for switching to block sync, we should get rid of v0.
// See: https://github.com/tendermint/tendermint/issues/4595
type BlockSyncReactor interface {
SwitchToBlockSync(context.Context, sm.State) error
GetMaxPeerBlockHeight() int64
// GetTotalSyncedTime returns the time duration since the blocksync starting.
GetTotalSyncedTime() time.Duration
// GetRemainingSyncTime returns the estimating time the node will be fully synced,
// if will return 0 if the blocksync does not perform or the number of block synced is
// too small (less than 100).
GetRemainingSyncTime() time.Duration
}
//go:generate ../../scripts/mockery_generate.sh ConsSyncReactor
// ConsSyncReactor defines an interface used for testing abilities of node.startStateSync.
type ConsSyncReactor interface {
SwitchToConsensus(sm.State, bool)
SetStateSyncingMetrics(float64)
SetBlockSyncingMetrics(float64)
}
// Reactor defines a reactor for the consensus service.
type Reactor struct {
service.BaseService
logger log.Logger
state *State
eventBus *eventbus.EventBus
Metrics *Metrics
mtx sync.RWMutex
peers map[types.NodeID]*PeerState
waitSync bool
readySignal chan struct{} // closed when the node is ready to start consensus
stateCh *p2p.Channel
dataCh *p2p.Channel
voteCh *p2p.Channel
voteSetBitsCh *p2p.Channel
peerUpdates *p2p.PeerUpdates
}
// NewReactor returns a reference to a new consensus reactor, which implements
// the service.Service interface. It accepts a logger, consensus state, references
// to relevant p2p Channels and a channel to listen for peer updates on. The
// reactor will close all p2p Channels when stopping.
func NewReactor(
ctx context.Context,
logger log.Logger,
cs *State,
channelCreator p2p.ChannelCreator,
peerUpdates *p2p.PeerUpdates,
eventBus *eventbus.EventBus,
waitSync bool,
metrics *Metrics,
) (*Reactor, error) {
chans := getChannelDescriptors()
stateCh, err := channelCreator(ctx, chans[StateChannel])
if err != nil {
return nil, err
}
dataCh, err := channelCreator(ctx, chans[DataChannel])
if err != nil {
return nil, err
}
voteCh, err := channelCreator(ctx, chans[VoteChannel])
if err != nil {
return nil, err
}
voteSetBitsCh, err := channelCreator(ctx, chans[VoteSetBitsChannel])
if err != nil {
return nil, err
}
r := &Reactor{
logger: logger,
state: cs,
waitSync: waitSync,
peers: make(map[types.NodeID]*PeerState),
eventBus: eventBus,
Metrics: metrics,
stateCh: stateCh,
dataCh: dataCh,
voteCh: voteCh,
voteSetBitsCh: voteSetBitsCh,
peerUpdates: peerUpdates,
readySignal: make(chan struct{}),
}
r.BaseService = *service.NewBaseService(logger, "Consensus", r)
if !r.waitSync {
close(r.readySignal)
}
return r, nil
}
// OnStart starts separate go routines for each p2p Channel and listens for
// envelopes on each. In addition, it also listens for peer updates and handles
// messages on that p2p channel accordingly. The caller must be sure to execute
// OnStop to ensure the outbound p2p Channels are closed.
func (r *Reactor) OnStart(ctx context.Context) error {
r.logger.Debug("consensus wait sync", "wait_sync", r.WaitSync())
// start routine that computes peer statistics for evaluating peer quality
//
// TODO: Evaluate if we need this to be synchronized via WaitGroup as to not
// leak the goroutine when stopping the reactor.
go r.peerStatsRoutine(ctx)
r.subscribeToBroadcastEvents()
if !r.WaitSync() {
if err := r.state.Start(ctx); err != nil {
return err
}
}
go r.processStateCh(ctx)
go r.processDataCh(ctx)
go r.processVoteCh(ctx)
go r.processVoteSetBitsCh(ctx)
go r.processPeerUpdates(ctx)
return nil
}
// OnStop stops the reactor by signaling to all spawned goroutines to exit and
// blocking until they all exit, as well as unsubscribing from events and stopping
// state.
func (r *Reactor) OnStop() {
r.unsubscribeFromBroadcastEvents()
r.state.Stop()
if !r.WaitSync() {
r.state.Wait()
}
}
// WaitSync returns whether the consensus reactor is waiting for state/block sync.
func (r *Reactor) WaitSync() bool {
r.mtx.RLock()
defer r.mtx.RUnlock()
return r.waitSync
}
// SwitchToConsensus switches from block-sync mode to consensus mode. It resets
// the state, turns off block-sync, and starts the consensus state-machine.
func (r *Reactor) SwitchToConsensus(ctx context.Context, state sm.State, skipWAL bool) {
r.logger.Info("switching to consensus")
// we have no votes, so reconstruct LastCommit from SeenCommit
if state.LastBlockHeight > 0 {
r.state.reconstructLastCommit(state)
}
// NOTE: The line below causes broadcastNewRoundStepRoutine() to broadcast a
// NewRoundStepMessage.
r.state.updateToState(ctx, state)
r.mtx.Lock()
r.waitSync = false
close(r.readySignal)
r.mtx.Unlock()
r.Metrics.BlockSyncing.Set(0)
r.Metrics.StateSyncing.Set(0)
if skipWAL {
r.state.doWALCatchup = false
}
if err := r.state.Start(ctx); err != nil {
panic(fmt.Sprintf(`failed to start consensus state: %v
conS:
%+v
conR:
%+v`, err, r.state, r))
}
d := types.EventDataBlockSyncStatus{Complete: true, Height: state.LastBlockHeight}
if err := r.eventBus.PublishEventBlockSyncStatus(ctx, d); err != nil {
r.logger.Error("failed to emit the blocksync complete event", "err", err)
}
}
// String returns a string representation of the Reactor.
//
// NOTE: For now, it is just a hard-coded string to avoid accessing unprotected
// shared variables.
//
// TODO: improve!
func (r *Reactor) String() string {
return "ConsensusReactor"
}
// StringIndented returns an indented string representation of the Reactor.
func (r *Reactor) StringIndented(indent string) string {
r.mtx.RLock()
defer r.mtx.RUnlock()
s := "ConsensusReactor{\n"
s += indent + " " + r.state.StringIndented(indent+" ") + "\n"
for _, ps := range r.peers {
s += indent + " " + ps.StringIndented(indent+" ") + "\n"
}
s += indent + "}"
return s
}
// GetPeerState returns PeerState for a given NodeID.
func (r *Reactor) GetPeerState(peerID types.NodeID) (*PeerState, bool) {
r.mtx.RLock()
defer r.mtx.RUnlock()
ps, ok := r.peers[peerID]
return ps, ok
}
func (r *Reactor) broadcastNewRoundStepMessage(ctx context.Context, rs *cstypes.RoundState) error {
return r.stateCh.Send(ctx, p2p.Envelope{
Broadcast: true,
Message: makeRoundStepMessage(rs),
})
}
func (r *Reactor) broadcastNewValidBlockMessage(ctx context.Context, rs *cstypes.RoundState) error {
psHeader := rs.ProposalBlockParts.Header()
return r.stateCh.Send(ctx, p2p.Envelope{
Broadcast: true,
Message: &tmcons.NewValidBlock{
Height: rs.Height,
Round: rs.Round,
BlockPartSetHeader: psHeader.ToProto(),
BlockParts: rs.ProposalBlockParts.BitArray().ToProto(),
IsCommit: rs.Step == cstypes.RoundStepCommit,
},
})
}
func (r *Reactor) broadcastHasVoteMessage(ctx context.Context, vote *types.Vote) error {
return r.stateCh.Send(ctx, p2p.Envelope{
Broadcast: true,
Message: &tmcons.HasVote{
Height: vote.Height,
Round: vote.Round,
Type: vote.Type,
Index: vote.ValidatorIndex,
},
})
}
// subscribeToBroadcastEvents subscribes for new round steps and votes using the
// internal pubsub defined in the consensus state to broadcast them to peers
// upon receiving.
func (r *Reactor) subscribeToBroadcastEvents() {
err := r.state.evsw.AddListenerForEvent(
listenerIDConsensus,
types.EventNewRoundStepValue,
func(ctx context.Context, data tmevents.EventData) error {
if err := r.broadcastNewRoundStepMessage(ctx, data.(*cstypes.RoundState)); err != nil {
return err
}
select {
case r.state.onStopCh <- data.(*cstypes.RoundState):
return nil
case <-ctx.Done():
return ctx.Err()
default:
return nil
}
},
)
if err != nil {
r.logger.Error("failed to add listener for events", "err", err)
}
err = r.state.evsw.AddListenerForEvent(
listenerIDConsensus,
types.EventValidBlockValue,
func(ctx context.Context, data tmevents.EventData) error {
return r.broadcastNewValidBlockMessage(ctx, data.(*cstypes.RoundState))
},
)
if err != nil {
r.logger.Error("failed to add listener for events", "err", err)
}
err = r.state.evsw.AddListenerForEvent(
listenerIDConsensus,
types.EventVoteValue,
func(ctx context.Context, data tmevents.EventData) error {
return r.broadcastHasVoteMessage(ctx, data.(*types.Vote))
},
)
if err != nil {
r.logger.Error("failed to add listener for events", "err", err)
}
}
func (r *Reactor) unsubscribeFromBroadcastEvents() {
r.state.evsw.RemoveListener(listenerIDConsensus)
}
func makeRoundStepMessage(rs *cstypes.RoundState) *tmcons.NewRoundStep {
return &tmcons.NewRoundStep{
Height: rs.Height,
Round: rs.Round,
Step: uint32(rs.Step),
SecondsSinceStartTime: int64(time.Since(rs.StartTime).Seconds()),
LastCommitRound: rs.LastCommit.GetRound(),
}
}
func (r *Reactor) sendNewRoundStepMessage(ctx context.Context, peerID types.NodeID) error {
return r.stateCh.Send(ctx, p2p.Envelope{
To: peerID,
Message: makeRoundStepMessage(r.state.GetRoundState()),
})
}
func (r *Reactor) gossipDataForCatchup(ctx context.Context, rs *cstypes.RoundState, prs *cstypes.PeerRoundState, ps *PeerState) {
logger := r.logger.With("height", prs.Height).With("peer", ps.peerID)
if index, ok := prs.ProposalBlockParts.Not().PickRandom(); ok {
// ensure that the peer's PartSetHeader is correct
blockMeta := r.state.blockStore.LoadBlockMeta(prs.Height)
if blockMeta == nil {
logger.Error(
"failed to load block meta",
"our_height", rs.Height,
"blockstore_base", r.state.blockStore.Base(),
"blockstore_height", r.state.blockStore.Height(),
)
time.Sleep(r.state.config.PeerGossipSleepDuration)
return
} else if !blockMeta.BlockID.PartSetHeader.Equals(prs.ProposalBlockPartSetHeader) {
logger.Info(
"peer ProposalBlockPartSetHeader mismatch; sleeping",
"block_part_set_header", blockMeta.BlockID.PartSetHeader,
"peer_block_part_set_header", prs.ProposalBlockPartSetHeader,
)
time.Sleep(r.state.config.PeerGossipSleepDuration)
return
}
part := r.state.blockStore.LoadBlockPart(prs.Height, index)
if part == nil {
logger.Error(
"failed to load block part",
"index", index,
"block_part_set_header", blockMeta.BlockID.PartSetHeader,
"peer_block_part_set_header", prs.ProposalBlockPartSetHeader,
)
time.Sleep(r.state.config.PeerGossipSleepDuration)
return
}
partProto, err := part.ToProto()
if err != nil {
logger.Error("failed to convert block part to proto", "err", err)
time.Sleep(r.state.config.PeerGossipSleepDuration)
return
}
logger.Debug("sending block part for catchup", "round", prs.Round, "index", index)
_ = r.dataCh.Send(ctx, p2p.Envelope{
To: ps.peerID,
Message: &tmcons.BlockPart{
Height: prs.Height, // not our height, so it does not matter.
Round: prs.Round, // not our height, so it does not matter
Part: *partProto,
},
})
return
}
time.Sleep(r.state.config.PeerGossipSleepDuration)
}
func (r *Reactor) gossipDataRoutine(ctx context.Context, ps *PeerState) {
logger := r.logger.With("peer", ps.peerID)
timer := time.NewTimer(0)
defer timer.Stop()
OUTER_LOOP:
for {
if !r.IsRunning() {
return
}
select {
case <-ctx.Done():
return
default:
}
rs := r.state.GetRoundState()
prs := ps.GetRoundState()
// Send proposal Block parts?
if rs.ProposalBlockParts.HasHeader(prs.ProposalBlockPartSetHeader) {
if index, ok := rs.ProposalBlockParts.BitArray().Sub(prs.ProposalBlockParts.Copy()).PickRandom(); ok {
part := rs.ProposalBlockParts.GetPart(index)
partProto, err := part.ToProto()
if err != nil {
logger.Error("failed to convert block part to proto", "err", err)
return
}
logger.Debug("sending block part", "height", prs.Height, "round", prs.Round)
if err := r.dataCh.Send(ctx, p2p.Envelope{
To: ps.peerID,
Message: &tmcons.BlockPart{
Height: rs.Height, // this tells peer that this part applies to us
Round: rs.Round, // this tells peer that this part applies to us
Part: *partProto,
},
}); err != nil {
return
}
ps.SetHasProposalBlockPart(prs.Height, prs.Round, index)
continue OUTER_LOOP
}
}
// if the peer is on a previous height that we have, help catch up
blockStoreBase := r.state.blockStore.Base()
if blockStoreBase > 0 && 0 < prs.Height && prs.Height < rs.Height && prs.Height >= blockStoreBase {
heightLogger := logger.With("height", prs.Height)
// If we never received the commit message from the peer, the block parts
// will not be initialized.
if prs.ProposalBlockParts == nil {
blockMeta := r.state.blockStore.LoadBlockMeta(prs.Height)
if blockMeta == nil {
heightLogger.Error(
"failed to load block meta",
"blockstoreBase", blockStoreBase,
"blockstoreHeight", r.state.blockStore.Height(),
)
timer.Reset(r.state.config.PeerGossipSleepDuration)
select {
case <-timer.C:
case <-ctx.Done():
return
}
} else {
ps.InitProposalBlockParts(blockMeta.BlockID.PartSetHeader)
}
// Continue the loop since prs is a copy and not effected by this
// initialization.
continue OUTER_LOOP
}
r.gossipDataForCatchup(ctx, rs, prs, ps)
continue OUTER_LOOP
}
// if height and round don't match, sleep
if (rs.Height != prs.Height) || (rs.Round != prs.Round) {
timer.Reset(r.state.config.PeerGossipSleepDuration)
select {
case <-timer.C:
case <-ctx.Done():
return
}
continue OUTER_LOOP
}
// By here, height and round match.
// Proposal block parts were already matched and sent if any were wanted.
// (These can match on hash so the round doesn't matter)
// Now consider sending other things, like the Proposal itself.
// Send Proposal && ProposalPOL BitArray?
if rs.Proposal != nil && !prs.Proposal {
// Proposal: share the proposal metadata with peer.
{
propProto := rs.Proposal.ToProto()
logger.Debug("sending proposal", "height", prs.Height, "round", prs.Round)
if err := r.dataCh.Send(ctx, p2p.Envelope{
To: ps.peerID,
Message: &tmcons.Proposal{
Proposal: *propProto,
},
}); err != nil {
return
}
// NOTE: A peer might have received a different proposal message, so
// this Proposal msg will be rejected!
ps.SetHasProposal(rs.Proposal)
}
// ProposalPOL: lets peer know which POL votes we have so far. The peer
// must receive ProposalMessage first. Note, rs.Proposal was validated,
// so rs.Proposal.POLRound <= rs.Round, so we definitely have
// rs.Votes.Prevotes(rs.Proposal.POLRound).
if 0 <= rs.Proposal.POLRound {
pPol := rs.Votes.Prevotes(rs.Proposal.POLRound).BitArray()
pPolProto := pPol.ToProto()
logger.Debug("sending POL", "height", prs.Height, "round", prs.Round)
if err := r.dataCh.Send(ctx, p2p.Envelope{
To: ps.peerID,
Message: &tmcons.ProposalPOL{
Height: rs.Height,
ProposalPolRound: rs.Proposal.POLRound,
ProposalPol: *pPolProto,
},
}); err != nil {
return
}
}
continue OUTER_LOOP
}
// nothing to do -- sleep
timer.Reset(r.state.config.PeerGossipSleepDuration)
select {
case <-timer.C:
case <-ctx.Done():
return
}
continue OUTER_LOOP
}
}
// pickSendVote picks a vote and sends it to the peer. It will return true if
// there is a vote to send and false otherwise.
func (r *Reactor) pickSendVote(ctx context.Context, ps *PeerState, votes types.VoteSetReader) (bool, error) {
vote, ok := ps.PickVoteToSend(votes)
if !ok {
return false, nil
}
r.logger.Debug("sending vote message", "ps", ps, "vote", vote)
if err := r.voteCh.Send(ctx, p2p.Envelope{
To: ps.peerID,
Message: &tmcons.Vote{
Vote: vote.ToProto(),
},
}); err != nil {
return false, err
}
if err := ps.SetHasVote(vote); err != nil {
return false, err
}
return true, nil
}
func (r *Reactor) gossipVotesForHeight(
ctx context.Context,
rs *cstypes.RoundState,
prs *cstypes.PeerRoundState,
ps *PeerState,
) (bool, error) {
logger := r.logger.With("height", prs.Height).With("peer", ps.peerID)
// if there are lastCommits to send...
if prs.Step == cstypes.RoundStepNewHeight {
if ok, err := r.pickSendVote(ctx, ps, rs.LastCommit); err != nil {
return false, err
} else if ok {
logger.Debug("picked rs.LastCommit to send")
return true, nil
}
}
// if there are POL prevotes to send...
if prs.Step <= cstypes.RoundStepPropose && prs.Round != -1 && prs.Round <= rs.Round && prs.ProposalPOLRound != -1 {
if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil {
if ok, err := r.pickSendVote(ctx, ps, polPrevotes); err != nil {
return false, err
} else if ok {
logger.Debug("picked rs.Prevotes(prs.ProposalPOLRound) to send", "round", prs.ProposalPOLRound)
return true, nil
}
}
}
// if there are prevotes to send...
if prs.Step <= cstypes.RoundStepPrevoteWait && prs.Round != -1 && prs.Round <= rs.Round {
if ok, err := r.pickSendVote(ctx, ps, rs.Votes.Prevotes(prs.Round)); err != nil {
return false, err
} else if ok {
logger.Debug("picked rs.Prevotes(prs.Round) to send", "round", prs.Round)
return true, nil
}
}
// if there are precommits to send...
if prs.Step <= cstypes.RoundStepPrecommitWait && prs.Round != -1 && prs.Round <= rs.Round {
if ok, err := r.pickSendVote(ctx, ps, rs.Votes.Precommits(prs.Round)); err != nil {
return false, err
} else if ok {
logger.Debug("picked rs.Precommits(prs.Round) to send", "round", prs.Round)
return true, nil
}
}
// if there are prevotes to send...(which are needed because of validBlock mechanism)
if prs.Round != -1 && prs.Round <= rs.Round {
if ok, err := r.pickSendVote(ctx, ps, rs.Votes.Prevotes(prs.Round)); err != nil {
return false, err
} else if ok {
logger.Debug("picked rs.Prevotes(prs.Round) to send", "round", prs.Round)
return true, nil
}
}
// if there are POLPrevotes to send...
if prs.ProposalPOLRound != -1 {
if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil {
if ok, err := r.pickSendVote(ctx, ps, polPrevotes); err != nil {
return false, err
} else if ok {
logger.Debug("picked rs.Prevotes(prs.ProposalPOLRound) to send", "round", prs.ProposalPOLRound)
return true, nil
}
}
}
return false, nil
}
func (r *Reactor) gossipVotesRoutine(ctx context.Context, ps *PeerState) {
logger := r.logger.With("peer", ps.peerID)
// XXX: simple hack to throttle logs upon sleep
logThrottle := 0
timer := time.NewTimer(0)
defer timer.Stop()
for {
if !r.IsRunning() {
return
}
select {
case <-ctx.Done():
return
default:
}
rs := r.state.GetRoundState()
prs := ps.GetRoundState()
switch logThrottle {
case 1: // first sleep
logThrottle = 2
case 2: // no more sleep
logThrottle = 0
}
// if height matches, then send LastCommit, Prevotes, and Precommits
if rs.Height == prs.Height {
if ok, err := r.gossipVotesForHeight(ctx, rs, prs, ps); err != nil {
return
} else if ok {
continue
}
}
// special catchup logic -- if peer is lagging by height 1, send LastCommit
if prs.Height != 0 && rs.Height == prs.Height+1 {
if ok, err := r.pickSendVote(ctx, ps, rs.LastCommit); err != nil {
return
} else if ok {
logger.Debug("picked rs.LastCommit to send", "height", prs.Height)
continue
}
}
// catchup logic -- if peer is lagging by more than 1, send Commit
blockStoreBase := r.state.blockStore.Base()
if blockStoreBase > 0 && prs.Height != 0 && rs.Height >= prs.Height+2 && prs.Height >= blockStoreBase {
// Load the block commit for prs.Height, which contains precommit
// signatures for prs.Height.
if commit := r.state.blockStore.LoadBlockCommit(prs.Height); commit != nil {
if ok, err := r.pickSendVote(ctx, ps, commit); err != nil {
return
} else if ok {
logger.Debug("picked Catchup commit to send", "height", prs.Height)
continue
}
}
}
if logThrottle == 0 {
// we sent nothing -- sleep
logThrottle = 1
logger.Debug(
"no votes to send; sleeping",
"rs.Height", rs.Height,
"prs.Height", prs.Height,
"localPV", rs.Votes.Prevotes(rs.Round).BitArray(), "peerPV", prs.Prevotes,
"localPC", rs.Votes.Precommits(rs.Round).BitArray(), "peerPC", prs.Precommits,
)
} else if logThrottle == 2 {
logThrottle = 1
}
timer.Reset(r.state.config.PeerGossipSleepDuration)
select {
case <-ctx.Done():
return
case <-timer.C:
}
}
}
// NOTE: `queryMaj23Routine` has a simple crude design since it only comes
// into play for liveness when there's a signature DDoS attack happening.
func (r *Reactor) queryMaj23Routine(ctx context.Context, ps *PeerState) {
timer := time.NewTimer(0)
defer timer.Stop()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
for {
if !ps.IsRunning() {
return
}
select {
case <-ctx.Done():
return
case <-timer.C:
}
if !ps.IsRunning() {
return
}
rs := r.state.GetRoundState()
prs := ps.GetRoundState()
// TODO create more reliable coppies of these
// structures so the following go routines don't race
wg := &sync.WaitGroup{}
if rs.Height == prs.Height {
wg.Add(1)
go func(rs *cstypes.RoundState, prs *cstypes.PeerRoundState) {
defer wg.Done()
// maybe send Height/Round/Prevotes
if maj23, ok := rs.Votes.Prevotes(prs.Round).TwoThirdsMajority(); ok {
if err := r.stateCh.Send(ctx, p2p.Envelope{
To: ps.peerID,
Message: &tmcons.VoteSetMaj23{
Height: prs.Height,
Round: prs.Round,
Type: tmproto.PrevoteType,
BlockID: maj23.ToProto(),
},
}); err != nil {
cancel()
}
}
}(rs, prs)
if prs.ProposalPOLRound >= 0 {
wg.Add(1)
go func(rs *cstypes.RoundState, prs *cstypes.PeerRoundState) {
defer wg.Done()
// maybe send Height/Round/ProposalPOL
if maj23, ok := rs.Votes.Prevotes(prs.ProposalPOLRound).TwoThirdsMajority(); ok {
if err := r.stateCh.Send(ctx, p2p.Envelope{
To: ps.peerID,
Message: &tmcons.VoteSetMaj23{
Height: prs.Height,
Round: prs.ProposalPOLRound,
Type: tmproto.PrevoteType,
BlockID: maj23.ToProto(),
},
}); err != nil {
cancel()
}
}
}(rs, prs)
}
wg.Add(1)
go func(rs *cstypes.RoundState, prs *cstypes.PeerRoundState) {
defer wg.Done()
// maybe send Height/Round/Precommits
if maj23, ok := rs.Votes.Precommits(prs.Round).TwoThirdsMajority(); ok {
if err := r.stateCh.Send(ctx, p2p.Envelope{
To: ps.peerID,
Message: &tmcons.VoteSetMaj23{
Height: prs.Height,
Round: prs.Round,
Type: tmproto.PrecommitType,
BlockID: maj23.ToProto(),
},
}); err != nil {
cancel()
}
}
}(rs, prs)
}
// Little point sending LastCommitRound/LastCommit, these are fleeting and
// non-blocking.
if prs.CatchupCommitRound != -1 && prs.Height > 0 {
wg.Add(1)
go func(rs *cstypes.RoundState, prs *cstypes.PeerRoundState) {
defer wg.Done()
if prs.Height <= r.state.blockStore.Height() && prs.Height >= r.state.blockStore.Base() {
// maybe send Height/CatchupCommitRound/CatchupCommit
if commit := r.state.LoadCommit(prs.Height); commit != nil {
if err := r.stateCh.Send(ctx, p2p.Envelope{
To: ps.peerID,
Message: &tmcons.VoteSetMaj23{
Height: prs.Height,
Round: commit.Round,
Type: tmproto.PrecommitType,
BlockID: commit.BlockID.ToProto(),
},
}); err != nil {
cancel()
}
}
}
}(rs, prs)
}
waitSignal := make(chan struct{})
go func() { defer close(waitSignal); wg.Wait() }()
select {
case <-waitSignal:
timer.Reset(r.state.config.PeerQueryMaj23SleepDuration)
case <-ctx.Done():
return
}
}
}
// processPeerUpdate process a peer update message. For new or reconnected peers,
// we create a peer state if one does not exist for the peer, which should always
// be the case, and we spawn all the relevant goroutine to broadcast messages to
// the peer. During peer removal, we remove the peer for our set of peers and
// signal to all spawned goroutines to gracefully exit in a non-blocking manner.
func (r *Reactor) processPeerUpdate(ctx context.Context, peerUpdate p2p.PeerUpdate) {
r.logger.Debug("received peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
r.mtx.Lock()
defer r.mtx.Unlock()
switch peerUpdate.Status {
case p2p.PeerStatusUp:
// Do not allow starting new broadcasting goroutines after reactor shutdown
// has been initiated. This can happen after we've manually closed all
// peer goroutines, but the router still sends in-flight peer updates.
if !r.IsRunning() {
return
}
ps, ok := r.peers[peerUpdate.NodeID]
if !ok {
ps = NewPeerState(r.logger, peerUpdate.NodeID)
r.peers[peerUpdate.NodeID] = ps
}
if !ps.IsRunning() {
// Set the peer state's closer to signal to all spawned goroutines to exit
// when the peer is removed. We also set the running state to ensure we
// do not spawn multiple instances of the same goroutines and finally we
// set the waitgroup counter so we know when all goroutines have exited.
ps.SetRunning(true)
ctx, ps.cancel = context.WithCancel(ctx)
go func() {
select {
case <-ctx.Done():
return
case <-r.readySignal:
}
// do nothing if the peer has
// stopped while we've been waiting.
if !ps.IsRunning() {
return
}
// start goroutines for this peer
go r.gossipDataRoutine(ctx, ps)
go r.gossipVotesRoutine(ctx, ps)
go r.queryMaj23Routine(ctx, ps)
// Send our state to the peer. If we're block-syncing, broadcast a
// RoundStepMessage later upon SwitchToConsensus().
if !r.WaitSync() {
go func() { _ = r.sendNewRoundStepMessage(ctx, ps.peerID) }()
}
}()
}
case p2p.PeerStatusDown:
ps, ok := r.peers[peerUpdate.NodeID]
if ok && ps.IsRunning() {
// signal to all spawned goroutines for the peer to gracefully exit
go func() {
r.mtx.Lock()
delete(r.peers, peerUpdate.NodeID)
r.mtx.Unlock()
ps.SetRunning(false)
ps.cancel()
}()
}
}
}
// handleStateMessage handles envelopes sent from peers on the StateChannel.
// An error is returned if the message is unrecognized or if validation fails.
// If we fail to find the peer state for the envelope sender, we perform a no-op
// and return. This can happen when we process the envelope after the peer is
// removed.
func (r *Reactor) handleStateMessage(ctx context.Context, envelope *p2p.Envelope, msgI Message) error {
ps, ok := r.GetPeerState(envelope.From)
if !ok || ps == nil {
r.logger.Debug("failed to find peer state", "peer", envelope.From, "ch_id", "StateChannel")
return nil
}
switch msg := envelope.Message.(type) {
case *tmcons.NewRoundStep:
r.state.mtx.RLock()
initialHeight := r.state.state.InitialHeight
r.state.mtx.RUnlock()
if err := msgI.(*NewRoundStepMessage).ValidateHeight(initialHeight); err != nil {
r.logger.Error("peer sent us an invalid msg", "msg", msg, "err", err)
return err
}
ps.ApplyNewRoundStepMessage(msgI.(*NewRoundStepMessage))
case *tmcons.NewValidBlock:
ps.ApplyNewValidBlockMessage(msgI.(*NewValidBlockMessage))
case *tmcons.HasVote:
if err := ps.ApplyHasVoteMessage(msgI.(*HasVoteMessage)); err != nil {
r.logger.Error("applying HasVote message", "msg", msg, "err", err)
return err
}
case *tmcons.VoteSetMaj23:
r.state.mtx.RLock()
height, votes := r.state.Height, r.state.Votes
r.state.mtx.RUnlock()
if height != msg.Height {
return nil
}
vsmMsg := msgI.(*VoteSetMaj23Message)
// peer claims to have a maj23 for some BlockID at <H,R,S>
err := votes.SetPeerMaj23(msg.Round, msg.Type, ps.peerID, vsmMsg.BlockID)
if err != nil {
return err
}
// Respond with a VoteSetBitsMessage showing which votes we have and
// consequently shows which we don't have.
var ourVotes *bits.BitArray
switch vsmMsg.Type {
case tmproto.PrevoteType:
ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(vsmMsg.BlockID)
case tmproto.PrecommitType:
ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(vsmMsg.BlockID)
default:
panic("bad VoteSetBitsMessage field type; forgot to add a check in ValidateBasic?")
}
eMsg := &tmcons.VoteSetBits{
Height: msg.Height,
Round: msg.Round,
Type: msg.Type,
BlockID: msg.BlockID,
}
if votesProto := ourVotes.ToProto(); votesProto != nil {
eMsg.Votes = *votesProto
}
if err := r.voteSetBitsCh.Send(ctx, p2p.Envelope{
To: envelope.From,
Message: eMsg,
}); err != nil {
return err
}
default:
return fmt.Errorf("received unknown message on StateChannel: %T", msg)
}
return nil
}
// handleDataMessage handles envelopes sent from peers on the DataChannel. If we
// fail to find the peer state for the envelope sender, we perform a no-op and
// return. This can happen when we process the envelope after the peer is
// removed.
func (r *Reactor) handleDataMessage(ctx context.Context, envelope *p2p.Envelope, msgI Message) error {
logger := r.logger.With("peer", envelope.From, "ch_id", "DataChannel")
ps, ok := r.GetPeerState(envelope.From)
if !ok || ps == nil {
r.logger.Debug("failed to find peer state")
return nil
}
if r.WaitSync() {
logger.Info("ignoring message received during sync", "msg", fmt.Sprintf("%T", msgI))
return nil
}
switch msg := envelope.Message.(type) {
case *tmcons.Proposal:
pMsg := msgI.(*ProposalMessage)
ps.SetHasProposal(pMsg.Proposal)
select {
case <-ctx.Done():
return ctx.Err()
case r.state.peerMsgQueue <- msgInfo{pMsg, envelope.From, tmtime.Now()}:
}
case *tmcons.ProposalPOL:
ps.ApplyProposalPOLMessage(msgI.(*ProposalPOLMessage))
case *tmcons.BlockPart:
bpMsg := msgI.(*BlockPartMessage)
ps.SetHasProposalBlockPart(bpMsg.Height, bpMsg.Round, int(bpMsg.Part.Index))
r.Metrics.BlockParts.With("peer_id", string(envelope.From)).Add(1)
select {
case r.state.peerMsgQueue <- msgInfo{bpMsg, envelope.From, tmtime.Now()}:
return nil
case <-ctx.Done():
return ctx.Err()
}
default:
return fmt.Errorf("received unknown message on DataChannel: %T", msg)
}
return nil
}
// handleVoteMessage handles envelopes sent from peers on the VoteChannel. If we
// fail to find the peer state for the envelope sender, we perform a no-op and
// return. This can happen when we process the envelope after the peer is
// removed.
func (r *Reactor) handleVoteMessage(ctx context.Context, envelope *p2p.Envelope, msgI Message) error {
logger := r.logger.With("peer", envelope.From, "ch_id", "VoteChannel")
ps, ok := r.GetPeerState(envelope.From)
if !ok || ps == nil {
r.logger.Debug("failed to find peer state")
return nil
}
if r.WaitSync() {
logger.Info("ignoring message received during sync", "msg", msgI)
return nil
}
switch msg := envelope.Message.(type) {
case *tmcons.Vote:
r.state.mtx.RLock()
height, valSize, lastCommitSize := r.state.Height, r.state.Validators.Size(), r.state.LastCommit.Size()
r.state.mtx.RUnlock()
vMsg := msgI.(*VoteMessage)
ps.EnsureVoteBitArrays(height, valSize)
ps.EnsureVoteBitArrays(height-1, lastCommitSize)
if err := ps.SetHasVote(vMsg.Vote); err != nil {
return err
}
select {
case r.state.peerMsgQueue <- msgInfo{vMsg, envelope.From, tmtime.Now()}:
return nil
case <-ctx.Done():
return ctx.Err()
}
default:
return fmt.Errorf("received unknown message on VoteChannel: %T", msg)
}
}
// handleVoteSetBitsMessage handles envelopes sent from peers on the
// VoteSetBitsChannel. If we fail to find the peer state for the envelope sender,
// we perform a no-op and return. This can happen when we process the envelope
// after the peer is removed.
func (r *Reactor) handleVoteSetBitsMessage(ctx context.Context, envelope *p2p.Envelope, msgI Message) error {
logger := r.logger.With("peer", envelope.From, "ch_id", "VoteSetBitsChannel")
ps, ok := r.GetPeerState(envelope.From)
if !ok || ps == nil {
r.logger.Debug("failed to find peer state")
return nil
}
if r.WaitSync() {
logger.Info("ignoring message received during sync", "msg", msgI)
return nil
}
switch msg := envelope.Message.(type) {
case *tmcons.VoteSetBits:
r.state.mtx.RLock()
height, votes := r.state.Height, r.state.Votes
r.state.mtx.RUnlock()
vsbMsg := msgI.(*VoteSetBitsMessage)
if height == msg.Height {
var ourVotes *bits.BitArray
switch msg.Type {
case tmproto.PrevoteType:
ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(vsbMsg.BlockID)
case tmproto.PrecommitType:
ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(vsbMsg.BlockID)
default:
panic("bad VoteSetBitsMessage field type; forgot to add a check in ValidateBasic?")
}
ps.ApplyVoteSetBitsMessage(vsbMsg, ourVotes)
} else {
ps.ApplyVoteSetBitsMessage(vsbMsg, nil)
}
default:
return fmt.Errorf("received unknown message on VoteSetBitsChannel: %T", msg)
}
return nil
}
// handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
// It will handle errors and any possible panics gracefully. A caller can handle
// any error returned by sending a PeerError on the respective channel.
//
// NOTE: We process these messages even when we're block syncing. Messages affect
// either a peer state or the consensus state. Peer state updates can happen in
// parallel, but processing of proposals, block parts, and votes are ordered by
// the p2p channel.
//
// NOTE: We block on consensus state for proposals, block parts, and votes.
func (r *Reactor) handleMessage(ctx context.Context, chID p2p.ChannelID, envelope *p2p.Envelope) (err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("panic in processing message: %v", e)
r.logger.Error(
"recovering from processing message panic",
"err", err,
"stack", string(debug.Stack()),
)
}
}()
// We wrap the envelope's message in a Proto wire type so we can convert back
// the domain type that individual channel message handlers can work with. We
// do this here once to avoid having to do it for each individual message type.
// and because a large part of the core business logic depends on these
// domain types opposed to simply working with the Proto types.
protoMsg := new(tmcons.Message)
if err := protoMsg.Wrap(envelope.Message); err != nil {
return err
}
msgI, err := MsgFromProto(protoMsg)
if err != nil {
return err
}
r.logger.Debug("received message", "ch_id", chID, "message", msgI, "peer", envelope.From)
switch chID {
case StateChannel:
err = r.handleStateMessage(ctx, envelope, msgI)
case DataChannel:
err = r.handleDataMessage(ctx, envelope, msgI)
case VoteChannel:
err = r.handleVoteMessage(ctx, envelope, msgI)
case VoteSetBitsChannel:
err = r.handleVoteSetBitsMessage(ctx, envelope, msgI)
default:
err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
}
return err
}
// processStateCh initiates a blocking process where we listen for and handle
// envelopes on the StateChannel. Any error encountered during message
// execution will result in a PeerError being sent on the StateChannel. When
// the reactor is stopped, we will catch the signal and close the p2p Channel
// gracefully.
func (r *Reactor) processStateCh(ctx context.Context) {
iter := r.stateCh.Receive(ctx)
for iter.Next(ctx) {
envelope := iter.Envelope()
if err := r.handleMessage(ctx, r.stateCh.ID, envelope); err != nil {
r.logger.Error("failed to process message", "ch_id", r.stateCh.ID, "envelope", envelope, "err", err)
if serr := r.stateCh.SendError(ctx, p2p.PeerError{
NodeID: envelope.From,
Err: err,
}); serr != nil {
return
}
}
}
}
// processDataCh initiates a blocking process where we listen for and handle
// envelopes on the DataChannel. Any error encountered during message
// execution will result in a PeerError being sent on the DataChannel. When
// the reactor is stopped, we will catch the signal and close the p2p Channel
// gracefully.
func (r *Reactor) processDataCh(ctx context.Context) {
iter := r.dataCh.Receive(ctx)
for iter.Next(ctx) {
envelope := iter.Envelope()
if err := r.handleMessage(ctx, r.dataCh.ID, envelope); err != nil {
r.logger.Error("failed to process message", "ch_id", r.dataCh.ID, "envelope", envelope, "err", err)
if serr := r.dataCh.SendError(ctx, p2p.PeerError{
NodeID: envelope.From,
Err: err,
}); serr != nil {
return
}
}
}
}
// processVoteCh initiates a blocking process where we listen for and handle
// envelopes on the VoteChannel. Any error encountered during message
// execution will result in a PeerError being sent on the VoteChannel. When
// the reactor is stopped, we will catch the signal and close the p2p Channel
// gracefully.
func (r *Reactor) processVoteCh(ctx context.Context) {
iter := r.voteCh.Receive(ctx)
for iter.Next(ctx) {
envelope := iter.Envelope()
if err := r.handleMessage(ctx, r.voteCh.ID, envelope); err != nil {
r.logger.Error("failed to process message", "ch_id", r.voteCh.ID, "envelope", envelope, "err", err)
if serr := r.voteCh.SendError(ctx, p2p.PeerError{
NodeID: envelope.From,
Err: err,
}); serr != nil {
return
}
}
}
}
// processVoteCh initiates a blocking process where we listen for and handle
// envelopes on the VoteSetBitsChannel. Any error encountered during message
// execution will result in a PeerError being sent on the VoteSetBitsChannel.
// When the reactor is stopped, we will catch the signal and close the p2p
// Channel gracefully.
func (r *Reactor) processVoteSetBitsCh(ctx context.Context) {
iter := r.voteSetBitsCh.Receive(ctx)
for iter.Next(ctx) {
envelope := iter.Envelope()
if err := r.handleMessage(ctx, r.voteSetBitsCh.ID, envelope); err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return
}
r.logger.Error("failed to process message", "ch_id", r.voteSetBitsCh.ID, "envelope", envelope, "err", err)
if serr := r.voteSetBitsCh.SendError(ctx, p2p.PeerError{
NodeID: envelope.From,
Err: err,
}); serr != nil {
return
}
}
}
}
// processPeerUpdates initiates a blocking process where we listen for and handle
// PeerUpdate messages. When the reactor is stopped, we will catch the signal and
// close the p2p PeerUpdatesCh gracefully.
func (r *Reactor) processPeerUpdates(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case peerUpdate := <-r.peerUpdates.Updates():
r.processPeerUpdate(ctx, peerUpdate)
}
}
}
func (r *Reactor) peerStatsRoutine(ctx context.Context) {
for {
if !r.IsRunning() {
r.logger.Info("stopping peerStatsRoutine")
return
}
select {
case msg := <-r.state.statsMsgQueue:
ps, ok := r.GetPeerState(msg.PeerID)
if !ok || ps == nil {
r.logger.Debug("attempt to update stats for non-existent peer", "peer", msg.PeerID)
continue
}
switch msg.Msg.(type) {
case *VoteMessage:
if numVotes := ps.RecordVote(); numVotes%votesToContributeToBecomeGoodPeer == 0 {
r.peerUpdates.SendUpdate(ctx, p2p.PeerUpdate{
NodeID: msg.PeerID,
Status: p2p.PeerStatusGood,
})
}
case *BlockPartMessage:
if numParts := ps.RecordBlockPart(); numParts%blocksToContributeToBecomeGoodPeer == 0 {
r.peerUpdates.SendUpdate(ctx, p2p.PeerUpdate{
NodeID: msg.PeerID,
Status: p2p.PeerStatusGood,
})
}
}
case <-ctx.Done():
return
}
}
}
func (r *Reactor) GetConsensusState() *State {
return r.state
}
func (r *Reactor) SetStateSyncingMetrics(v float64) {
r.Metrics.StateSyncing.Set(v)
}
func (r *Reactor) SetBlockSyncingMetrics(v float64) {
r.Metrics.BlockSyncing.Set(v)
}
| tendermint/tendermint | internal/consensus/reactor.go | GO | apache-2.0 | 42,921 |
/**
* Copyright 2012 Batis Degryll Ludo
* @file DaemonClickIH.h
* @since 2018-01-22
* @date 2018-02-25
* @author Batis Degrill Ludo
* @brief Input handler capable of run a daemon if given coords are inside a given area.
*/
#ifndef ZBE_EVENTS_HANDLERS_INPUT_DAEMONCLICKINPUTHANDLER_H
#define ZBE_EVENTS_HANDLERS_INPUT_DAEMONCLICKINPUTHANDLER_H
#include <memory>
#include <algorithm>
#include "ZBE/core/io/Input.h"
#include "ZBE/core/events/handlers/InputHandler.h"
#include "ZBE/core/tools/shared/Value.h"
#include "ZBE/core/tools/math/Region.h"
#include "ZBE/core/tools/math/math.h"
#include "ZBE/core/daemons/Daemon.h"
#include "ZBE/core/system/system.h"
namespace zbe {
/**
* brief Input handler capable of run a daemon if given coords are inside a given area.
*/
class ZBEAPI DaemonClickIH : public InputHandler {
public:
/** \brief Constructs a DaemonClickIH from its raw data
* \param area area to use.
* \param xvalue Value where mouse x will be readed.
* \param yvalue Value where mouse y will be readed.
* \param daemon daemon to be executed when condition are met.
*/
DaemonClickIH() : a(), xval(nullptr), yval(nullptr), d(nullptr) {}
/** \brief Constructs a DaemonClickIH from its raw data
* \param area area to use.
* \param xvalue Value where mouse x will be readed.
* \param yvalue Value where mouse y will be readed.
* \param daemon daemon to be executed when condition are met.
*/
DaemonClickIH(Region2D area, std::shared_ptr<Value<double> > xvalue, std::shared_ptr<Value<double> > yvalue, std::shared_ptr<Daemon> daemon) : a(area), xval(xvalue), yval(yvalue), d(daemon) {}
/** \brief Set Value<double> where x pointer coor will be found
* \param xvalue where x pointer coor will be found.
*/
void setXValue(std::shared_ptr<Value<double> > xvalue) {
this->xval = xvalue;
}
/** \brief Set Value<double> where y pointer coor will be found
* \param yvalue where y pointer coor will be found.
*/
void setYValue(std::shared_ptr<Value<double> > yvalue) {
this->yval = yvalue;
}
/** \brief Set the area where the daemon will be launch.
* \param area where the daemon will be launch.
*/
void setArea(Region2D area) {
this->a = area;
}
/** \brief Set the Daemon to run.
* \param daemon the Daemon to run.
*/
void setDaemon(std::shared_ptr<Daemon> daemon) {
this->d = daemon;
}
/** \brief exec daemon if click is inside given area.
* \param state input state.
*/
void run(uint32_t, float state) {
if(!almost_equal(state, ZBE_KEYUP)){
return;
}
double x = xval->get();
double y = yval->get();
double minx = std::min(a.p.x, a.p.x + a.v.x);
double miny = std::min(a.p.y, a.p.y + a.v.y);
double maxx = std::max(a.p.x, a.p.x + a.v.x);
double maxy = std::max(a.p.y, a.p.y + a.v.y);
if(x > minx && x < maxx && y > miny && y < maxy) {
d->run();
}
}
private:
Region2D a;
std::shared_ptr<Value<double> > xval;
std::shared_ptr<Value<double> > yval;
std::shared_ptr<Daemon> d;
};
} // namespace zbe
#endif // ZBE_EVENTS_HANDLERS_INPUT_DAEMONCLICKINPUTHANDLER_H
| Degryll/ZBE | include/ZBE/events/handlers/input/DaemonClickIH.h | C | apache-2.0 | 3,059 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AssemblyInfoFileConfig - FAKE - F# Make</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull">
<script src="https://code.jquery.com/jquery-1.8.0.js"></script>
<script src="https://code.jquery.com/ui/1.8.23/jquery-ui.js"></script>
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" />
<script type="text/javascript" src="http://fsharp.github.io/FAKE/content/tips.js"></script>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="masthead">
<ul class="nav nav-pills pull-right">
<li><a href="http://fsharp.org">fsharp.org</a></li>
<li><a href="http://github.com/fsharp/fake">github page</a></li>
</ul>
<h3 class="muted"><a href="http://fsharp.github.io/FAKE/index.html">FAKE - F# Make</a></h3>
</div>
<hr />
<div class="row">
<div class="span9" id="main">
<h1>AssemblyInfoFileConfig</h1>
<div class="xmldoc">
<p>Represents options for configuring the emission of AssemblyInfo</p>
</div>
<h3>Constructors</h3>
<table class="table table-bordered member-list">
<thead>
<tr><td>Constructor</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '811', 811)" onmouseover="showTip(event, '811', 811)">
new(generateClass, useNamespace)
</code>
<div class="tip" id="811">
<strong>Signature:</strong> (generateClass:bool * useNamespace:string option) -> AssemblyInfoFileConfig<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoFile.fs#L13-13" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
</tbody>
</table>
<h3>Instance members</h3>
<table class="table table-bordered member-list">
<thead>
<tr><td>Instance member</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '812', 812)" onmouseover="showTip(event, '812', 812)">
GenerateClass
</code>
<div class="tip" id="812">
<strong>Signature:</strong> bool<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoFile.fs#L18-18" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '813', 813)" onmouseover="showTip(event, '813', 813)">
GenerateClass
</code>
<div class="tip" id="813">
<strong>Signature:</strong> bool<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoFile.fs#L18-18" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '814', 814)" onmouseover="showTip(event, '814', 814)">
UseNamespace
</code>
<div class="tip" id="814">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoFile.fs#L19-19" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '815', 815)" onmouseover="showTip(event, '815', 815)">
UseNamespace
</code>
<div class="tip" id="815">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoFile.fs#L19-19" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
</tbody>
</table>
<h3>Static members</h3>
<table class="table table-bordered member-list">
<thead>
<tr><td>Static member</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '816', 816)" onmouseover="showTip(event, '816', 816)">
Default
</code>
<div class="tip" id="816">
<strong>Signature:</strong> AssemblyInfoFileConfig<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoFile.fs#L23-23" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '817', 817)" onmouseover="showTip(event, '817', 817)">
Default
</code>
<div class="tip" id="817">
<strong>Signature:</strong> AssemblyInfoFileConfig<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoFile.fs#L23-23" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
</tbody>
</table>
</div>
<div class="span3">
<a href="http://fsharp.github.io/FAKE/index.html">
<img src="http://fsharp.github.io/FAKE/pics/logo.png" style="width:140px;height:140px;margin:10px 0px 0px 35px;border-style:none;" />
</a>
<ul class="nav nav-list" id="menu">
<li class="nav-header">FAKE - F# Make</li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/index.html">Home page</a></li>
<li class="divider"></li>
<li><a href="https://www.nuget.org/packages/FAKE">Get FAKE - F# Make via NuGet</a></li>
<li><a href="http://github.com/fsharp/fake">Source Code on GitHub</a></li>
<li><a href="http://github.com/fsharp/fake/blob/master/License.txt">License (MS-PL)</a></li>
<li><a href="http://fsharp.github.io/FAKE/RELEASE_NOTES.html">Release Notes</a></li>
<li><a href="http://fsharp.github.io/FAKE//contributing.html">Contributing to FAKE - F# Make</a></li>
<li><a href="http://fsharp.github.io/FAKE/users.html">Who is using FAKE?</a></li>
<li><a href="http://stackoverflow.com/questions/tagged/f%23-fake">Ask a question</a></li>
<li class="nav-header">Tutorials</li>
<li><a href="http://fsharp.github.io/FAKE/gettingstarted.html">Getting started</a></li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/nuget.html">NuGet package restore</a></li>
<li><a href="http://fsharp.github.io/FAKE/fxcop.html">Using FxCop in a build</a></li>
<li><a href="http://fsharp.github.io/FAKE/assemblyinfo.html">Generating AssemblyInfo</a></li>
<li><a href="http://fsharp.github.io/FAKE/create-nuget-package.html">Create NuGet packages</a></li>
<li><a href="http://fsharp.github.io/FAKE/specifictargets.html">Running specific targets</a></li>
<li><a href="http://fsharp.github.io/FAKE/commandline.html">Running FAKE from command line</a></li>
<li><a href="http://fsharp.github.io/FAKE/fsc.html">Using the F# compiler from FAKE</a></li>
<li><a href="http://fsharp.github.io/FAKE/customtasks.html">Creating custom tasks</a></li>
<li><a href="http://fsharp.github.io/FAKE/teamcity.html">TeamCity integration</a></li>
<li><a href="http://fsharp.github.io/FAKE/canopy.html">Running canopy tests</a></li>
<li><a href="http://fsharp.github.io/FAKE/octopusdeploy.html">Octopus Deploy</a></li>
<li><a href="http://fsharp.github.io/FAKE/typescript.html">TypeScript support</a></li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/deploy.html">Fake.Deploy</a></li>
<li class="nav-header">Reference</li>
<li><a href="http://fsharp.github.io/FAKE/apidocs/index.html">API Reference</a></li>
</ul>
</div>
</div>
</div>
<a href="http://github.com/fsharp/fake"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a>
</body>
</html>
| mwissman/MingleTransitionMonitor | MingleTransitionMonitor/packages/FAKE.3.9.8/docs/apidocs/fake-assemblyinfofile-assemblyinfofileconfig.html | HTML | apache-2.0 | 10,453 |
#import <Foundation/Foundation.h>
// Represents a non-blocking future value. Products, functions, and actors, given to the methods on this class, are executed concurrently, and the
// Promise serves as a handle on the result of the computation.
@interface FKPromise : NSObject {
}
// Waits if necessary for the computation to complete, and then retrieves its result.
- (id)claim;
// Waits if necessary for the computation to complete, and then retrieves its result.
- (id)claim:(NSTimeInterval)timeout;
@end
| tjweir/functionalkit | Source/Main/FK/FKPromise.h | C | apache-2.0 | 512 |
package com.cisco.axl.api._8;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for LPickupGroupMember complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="LPickupGroupMember">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence minOccurs="0">
* <element name="priority" type="{http://www.cisco.com/AXL/API/8.0}XInteger" minOccurs="0"/>
* <choice minOccurs="0">
* <element name="pickupGroupName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* <element name="pickupDnAndPartition" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence minOccurs="0">
* <element name="dnPattern" type="{http://www.cisco.com/AXL/API/8.0}String255" minOccurs="0"/>
* <element name="routePartitionName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </choice>
* </sequence>
* <attribute name="uuid" type="{http://www.cisco.com/AXL/API/8.0}XUUID" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LPickupGroupMember", propOrder = {
"priority",
"pickupGroupName",
"pickupDnAndPartition"
})
public class LPickupGroupMember {
protected String priority;
protected XFkType pickupGroupName;
protected LPickupGroupMember.PickupDnAndPartition pickupDnAndPartition;
@XmlAttribute
protected String uuid;
/**
* Gets the value of the priority property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPriority() {
return priority;
}
/**
* Sets the value of the priority property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPriority(String value) {
this.priority = value;
}
/**
* Gets the value of the pickupGroupName property.
*
* @return
* possible object is
* {@link XFkType }
*
*/
public XFkType getPickupGroupName() {
return pickupGroupName;
}
/**
* Sets the value of the pickupGroupName property.
*
* @param value
* allowed object is
* {@link XFkType }
*
*/
public void setPickupGroupName(XFkType value) {
this.pickupGroupName = value;
}
/**
* Gets the value of the pickupDnAndPartition property.
*
* @return
* possible object is
* {@link LPickupGroupMember.PickupDnAndPartition }
*
*/
public LPickupGroupMember.PickupDnAndPartition getPickupDnAndPartition() {
return pickupDnAndPartition;
}
/**
* Sets the value of the pickupDnAndPartition property.
*
* @param value
* allowed object is
* {@link LPickupGroupMember.PickupDnAndPartition }
*
*/
public void setPickupDnAndPartition(LPickupGroupMember.PickupDnAndPartition value) {
this.pickupDnAndPartition = value;
}
/**
* Gets the value of the uuid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUuid() {
return uuid;
}
/**
* Sets the value of the uuid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUuid(String value) {
this.uuid = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence minOccurs="0">
* <element name="dnPattern" type="{http://www.cisco.com/AXL/API/8.0}String255" minOccurs="0"/>
* <element name="routePartitionName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"dnPattern",
"routePartitionName"
})
public static class PickupDnAndPartition {
protected String dnPattern;
protected XFkType routePartitionName;
/**
* Gets the value of the dnPattern property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDnPattern() {
return dnPattern;
}
/**
* Sets the value of the dnPattern property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDnPattern(String value) {
this.dnPattern = value;
}
/**
* Gets the value of the routePartitionName property.
*
* @return
* possible object is
* {@link XFkType }
*
*/
public XFkType getRoutePartitionName() {
return routePartitionName;
}
/**
* Sets the value of the routePartitionName property.
*
* @param value
* allowed object is
* {@link XFkType }
*
*/
public void setRoutePartitionName(XFkType value) {
this.routePartitionName = value;
}
}
}
| ox-it/cucm-http-api | src/main/java/com/cisco/axl/api/_8/LPickupGroupMember.java | Java | apache-2.0 | 6,398 |
/*
* Copyright 2013-2014 Grzegorz Ligas <ligasgr@gmail.com> and other contributors
* (see the CONTRIBUTORS file).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.xquery.util;
import org.w3c.dom.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;
/**
* User: ligasgr
* Date: 27/09/13
* Time: 15:42
*/
public class DelegatingNode implements Document {
private final Document originalDocument;
public DelegatingNode(Document originalDocument) {
this.originalDocument = originalDocument;
}
@Override
public Node cloneNode(boolean b) {
return originalDocument.cloneNode(b);
}
@Override
public void normalize() {
originalDocument.normalize();
}
@Override
public boolean isSupported(String feature, String version) {
return originalDocument.isSupported(feature, version);
}
@Override
public String getNamespaceURI() {
return originalDocument.getNamespaceURI();
}
@Override
public String getPrefix() {
return originalDocument.getPrefix();
}
@Override
public void setPrefix(String prefix) throws DOMException {
originalDocument.setPrefix(prefix);
}
@Override
public String getLocalName() {
return originalDocument.getLocalName();
}
@Override
public boolean hasAttributes() {
return originalDocument.hasAttributes();
}
@Override
public String getBaseURI() {
return originalDocument.getBaseURI();
}
@Override
public short compareDocumentPosition(Node other) throws DOMException {
return originalDocument.compareDocumentPosition(other);
}
@Override
public short getNodeType() {
return originalDocument.getNodeType();
}
@Override
public Node getParentNode() {
return originalDocument.getParentNode();
}
@Override
public NodeList getChildNodes() {
return originalDocument.getChildNodes();
}
@Override
public Node getFirstChild() {
return originalDocument.getFirstChild();
}
@Override
public Node getLastChild() {
return originalDocument.getLastChild();
}
@Override
public Node getPreviousSibling() {
return originalDocument.getPreviousSibling();
}
@Override
public Node getNextSibling() {
return originalDocument.getNextSibling();
}
@Override
public NamedNodeMap getAttributes() {
return originalDocument.getAttributes();
}
@Override
public Document getOwnerDocument() {
return originalDocument.getOwnerDocument();
}
@Override
public String getNodeName() {
return originalDocument.getNodeName();
}
@Override
public String getNodeValue() throws DOMException {
return originalDocument.getNodeValue();
}
@Override
public void setNodeValue(String nodeValue) throws DOMException {
originalDocument.setNodeValue(nodeValue);
}
@Override
public Node insertBefore(Node node, Node node2) throws DOMException {
return originalDocument.insertBefore(node, node2);
}
@Override
public Node removeChild(Node node) throws DOMException {
return originalDocument.removeChild(node);
}
@Override
public Node appendChild(Node newChild) throws DOMException {
return originalDocument.appendChild(newChild);
}
@Override
public boolean hasChildNodes() {
return originalDocument.hasChildNodes();
}
@Override
public Node replaceChild(Node node, Node node2) throws DOMException {
return originalDocument.replaceChild(node, node2);
}
@Override
public String getTextContent() throws DOMException {
return originalDocument.getTextContent();
}
@Override
public void setTextContent(String s) throws DOMException {
originalDocument.setTextContent(s);
}
@Override
public boolean isSameNode(Node other) {
return originalDocument.isSameNode(other);
}
@Override
public String lookupPrefix(String namespaceURI) {
return originalDocument.lookupPrefix(namespaceURI);
}
@Override
public boolean isDefaultNamespace(String namespaceURI) {
return originalDocument.isDefaultNamespace(namespaceURI);
}
@Override
public String lookupNamespaceURI(String prefix) {
return originalDocument.lookupNamespaceURI(prefix);
}
@Override
public boolean isEqualNode(Node arg) {
return originalDocument.isEqualNode(arg);
}
@Override
public Object getFeature(String s, String s2) {
return originalDocument.getFeature(s, s2);
}
@Override
public Object setUserData(String key, Object data, UserDataHandler handler) {
return originalDocument.setUserData(key, data, handler);
}
@Override
public Object getUserData(String key) {
return originalDocument.getUserData(key);
}
@Override
public String toString() {
DOMSource domSource = new DOMSource(originalDocument);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = null;
try {
transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
return originalDocument.toString();
}
@Override
public DocumentType getDoctype() {
return originalDocument.getDoctype();
}
@Override
public DOMImplementation getImplementation() {
return originalDocument.getImplementation();
}
@Override
public Element getDocumentElement() {
return originalDocument.getDocumentElement();
}
@Override
public Element createElement(String tagName) throws DOMException {
return originalDocument.createElement(tagName);
}
@Override
public DocumentFragment createDocumentFragment() {
return originalDocument.createDocumentFragment();
}
@Override
public Text createTextNode(String data) {
return originalDocument.createTextNode(data);
}
@Override
public Comment createComment(String data) {
return originalDocument.createComment(data);
}
@Override
public CDATASection createCDATASection(String data) throws DOMException {
return originalDocument.createCDATASection(data);
}
@Override
public ProcessingInstruction createProcessingInstruction(String target, String data) throws DOMException {
return originalDocument.createProcessingInstruction(target, data);
}
@Override
public Attr createAttribute(String name) throws DOMException {
return originalDocument.createAttribute(name);
}
@Override
public EntityReference createEntityReference(String name) throws DOMException {
return originalDocument.createEntityReference(name);
}
@Override
public NodeList getElementsByTagName(String tagname) {
return originalDocument.getElementsByTagName(tagname);
}
@Override
public Node importNode(Node importedNode, boolean deep) throws DOMException {
return originalDocument.importNode(importedNode, deep);
}
@Override
public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException {
return originalDocument.createElementNS(namespaceURI, qualifiedName);
}
@Override
public Attr createAttributeNS(String namespaceURI, String qualifiedName) throws DOMException {
return originalDocument.createAttributeNS(namespaceURI, qualifiedName);
}
@Override
public NodeList getElementsByTagNameNS(String namespaceURI, String localName) {
return originalDocument.getElementsByTagNameNS(namespaceURI, localName);
}
@Override
public Element getElementById(String elementId) {
return originalDocument.getElementById(elementId);
}
@Override
public String getInputEncoding() {
return originalDocument.getInputEncoding();
}
@Override
public String getXmlEncoding() {
return originalDocument.getXmlEncoding();
}
@Override
public boolean getXmlStandalone() {
return originalDocument.getXmlStandalone();
}
@Override
public void setXmlStandalone(boolean xmlStandalone) throws DOMException {
originalDocument.setXmlStandalone(xmlStandalone);
}
@Override
public String getXmlVersion() {
return originalDocument.getXmlVersion();
}
@Override
public void setXmlVersion(String xmlVersion) throws DOMException {
originalDocument.setXmlVersion(xmlVersion);
}
@Override
public boolean getStrictErrorChecking() {
return originalDocument.getStrictErrorChecking();
}
@Override
public void setStrictErrorChecking(boolean strictErrorChecking) {
originalDocument.setStrictErrorChecking(strictErrorChecking);
}
@Override
public String getDocumentURI() {
return originalDocument.getDocumentURI();
}
@Override
public void setDocumentURI(String documentURI) {
originalDocument.setDocumentURI(documentURI);
}
@Override
public Node adoptNode(Node source) throws DOMException {
return originalDocument.adoptNode(source);
}
@Override
public DOMConfiguration getDomConfig() {
return originalDocument.getDomConfig();
}
@Override
public void normalizeDocument() {
originalDocument.normalizeDocument();
}
@Override
public Node renameNode(Node n, String namespaceURI, String qualifiedName) throws DOMException {
return originalDocument.renameNode(n, namespaceURI, qualifiedName);
}
}
| ligasgr/intellij-xquery | src/test/java/org/intellij/xquery/util/DelegatingNode.java | Java | apache-2.0 | 10,886 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>388B</title>
<!-- Bootstrap Core -->
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link href="/css/clean-blog.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.5.2/animate.min.css">
<!-- jQuery -->
<script src="/js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="/js/jquery.plate.js"></script>
<script src="/js/popper.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/js/wow.min.js"></script>
<script>
new WOW().init();
</script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a href="/index.html" class="navbar-brand">
Haifeng Jin's Blog
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="/index.html">
Home
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/technology/index.html">
Technology
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/codeforces/index.html">
Competitive
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/chinese/index.html">
Chinese
</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Contact
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="https://www.linkedin.com/in/HaifengJin">
Linkedin
</a>
<a class="dropdown-item" href="https://github.com/jhfjhfj1">
GitHub
</a>
<a class="dropdown-item" href="https://scholar.google.com/citations?user=OAj0lr0AAAAJ&hl=en">
Google Scholar
</a>
<a class="dropdown-item" href="mailto:jin@tamu.edu">
E-mail
</a>
</div>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" onkeydown="if(event.keyCode==13) googlesearch();" name="search-key-words" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" onclick="googlesearch()">Search</button>
</form>
</div>
</nav>
<script type="text/javascript">
function googlesearch() {
console.log('google call');
var key = document.getElementsByName("search-key-words")[0].value;
var link = "http://www.google.com/search?domains=haifengjin.com&sitesearch=haifengjin.com&q=" + key;
window.open(link);
document.getElementsByName("search-key-words")[0].value = ""
}
</script>
<div id="listener-contained" class="listener pointer">
<style>
</style>
<header class="intro-header" id="header" style="background-image: url('/img/codeforces.jpg')">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="site-heading">
<div id="plate-contained" class="plate">
<h1>Tutorial</h1>
<span class="subheading">The Art of Competitive Programming</span>
</div>
</div>
</div>
</div>
</div>
</header>
</div>
<script>
$('#listener-contained').plate({
element: ['#plate-contained']
});
</script>
<div class="container" style="margin-top: 50px">
<div class="row">
<!-- Blog Post Content Column -->
<div class="col-lg-8">
<!-- Blog Post -->
<!-- Title -->
<h2>388B</h2>
<hr>
<!-- Date/Time -->
<div class="glyphicon glyphicon-time"></div>
<span>
Posted on 22 Dec 2014
</span>
<div class="float-right">
<span class="badge badge-default">constructive algorithms</span>
</div>
<hr>
<!-- Post Content -->
<script type="text/javascript"
src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<div class="blog-content" >
<h3 id="solution">Solution</h3>
<p><br /></p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#include <cstdio>
using namespace std;
#define D(x)
const int MAX_N = 100;
int num;
bool ans[MAX_N][MAX_N];
void connect(int a, int b)
{
ans[a][b] = ans[b][a] = true;
}
int main()
{
//init
connect(1, 3);
connect(1, 4);
for (int i = 1; i < 30; i++)
{
connect(i * 2 + 1, i * 2 + 3);
connect(i * 2 + 1, i * 2 + 4);
connect(i * 2 + 2, i * 2 + 3);
connect(i * 2 + 2, i * 2 + 4);
}
for (int i = 1; i <= 30; i++)
{
connect(62 + i, 63 + i);
}
connect(93, 2);
//input
scanf("%d", &num);
//work
int temp = 0;
while (num > 0)
{
if (num & 1)
{
connect(temp * 2 + 1, 63 + temp);
if (temp != 0)
{
connect(temp * 2 + 2, 63 + temp);
}
}
temp++;
num >>= 1;
}
//output
printf("%d\n", 93);
for (int i = 1; i <= 93; i++)
{
for (int j = 1; j <= 93; j++)
{
if (ans[i][j])
putchar('Y');
else
putchar('N');
}
putchar('\n');
}
return 0;
}
</code></pre></div></div>
</div>
<hr>
<!-- Disqus -->
<!-- Comment -->
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'jhfjhfj1'; // required: replace example with your forum shortname
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<!-- End Nested Comment -->
</div>
<!-- Blog Sidebar Widgets Column -->
<div class="col-md-4" id="side_bar">
<div><p></p></div>
<!-- Side Widget Well -->
<div class="card">
<div class="card-header"><big>Introduction</big></div>
<div class="card-body">
<p>Here are some write-ups for the competitive programming problems I solved.</p>
</div>
</div>
<div><p></p></div>
<div class="card">
<div class="card-header"><big>Code Library</big></div>
<div class="card-body">
<p>My <a href="https://github.com/jhfjhfj1/codelib">code library link</a> on GitHub.</p>
</div>
</div>
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
<hr>
<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-44322747-2', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
| jhfjhfj1/jhfjhfj1.github.io | codeforces/2014/12/22/388B.html | HTML | apache-2.0 | 8,981 |
/**
* Copyright 2013-2014 Guoqiang Chen, Shanghai, China. All rights reserved.
*
* Email: subchen@gmail.com
* URL: http://subchen.github.io/
*
* 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 jetbrick.lang;
import java.nio.charset.Charset;
public final class CharsetUtils {
public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
public static final Charset UTF_8 = Charset.forName("UTF-8");
public static final Charset UTF_16 = Charset.forName("UTF-16");
public static final Charset UTF_16BE = Charset.forName("UTF-16BE");
public static final Charset UTF_16LE = Charset.forName("UTF-16LE");
public static final Charset GB2312 = Charset.forName("GB2312");
public static final Charset GBK = Charset.forName("GBK");
public static final Charset GB18030 = Charset.forName("GB18030");
}
| subchen/jetbrick-all-1x | jetbrick-commons/src/main/java/jetbrick/lang/CharsetUtils.java | Java | apache-2.0 | 1,354 |
/*
* Copyright (c) 2010-2019 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.task.quartzimpl.tracing;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.util.CloneUtil;
import com.evolveum.midpoint.prism.xml.XmlTypeConverter;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.repo.api.SystemConfigurationChangeDispatcher;
import com.evolveum.midpoint.repo.api.SystemConfigurationChangeListener;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.result.CompiledTracingProfile;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.schema.util.TestNameHolder;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.task.api.TaskManager;
import com.evolveum.midpoint.task.api.Tracer;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.MiscUtil;
import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* Manages tracing requests.
*/
@Component
public class TracerImpl implements Tracer, SystemConfigurationChangeListener {
private static final Trace LOGGER = TraceManager.getTrace(TracerImpl.class);
private static final String MACRO_TIMESTAMP = "timestamp";
private static final String MACRO_OPERATION_NAME = "operationName";
private static final String MACRO_OPERATION_NAME_SHORT = "operationNameShort";
private static final String MACRO_TEST_NAME = "testName";
private static final String MACRO_TEST_NAME_SHORT = "testNameShort";
private static final String MACRO_FOCUS_NAME = "focusName";
private static final String MACRO_MILLISECONDS = "milliseconds";
private static final String MACRO_RANDOM = "random";
// To be used during tests to check for MID-5851
public static boolean checkHashCodeEqualsRelation = false;
@Autowired private PrismContext prismContext;
@Autowired private TaskManager taskManager;
@Autowired private SystemConfigurationChangeDispatcher systemConfigurationChangeDispatcher;
@Autowired
@Qualifier("cacheRepositoryService")
private transient RepositoryService repositoryService;
private SystemConfigurationType systemConfiguration; // can be null during some tests
private static final String OP_STORE_TRACE = TracerImpl.class.getName() + ".storeTrace";
private static final String MIDPOINT_HOME = System.getProperty("midpoint.home");
private static final String TRACE_DIR = MIDPOINT_HOME + "trace/";
private static final String ZIP_ENTRY_NAME = "trace.xml";
private static final String DEFAULT_FILE_NAME_PATTERN = "trace-%{timestamp}";
@PostConstruct
public void init() {
systemConfigurationChangeDispatcher.registerListener(this);
}
@PreDestroy
public void shutdown() {
systemConfigurationChangeDispatcher.unregisterListener(this);
}
@Override
public void storeTrace(Task task, OperationResult result, @Nullable OperationResult parentResult) {
OperationResult thisOpResult;
if (parentResult != null) {
thisOpResult = parentResult.createMinorSubresult(OP_STORE_TRACE);
} else {
thisOpResult = new OperationResult(OP_STORE_TRACE);
}
try {
CompiledTracingProfile compiledTracingProfile = result.getTracingProfile();
TracingProfileType tracingProfile = compiledTracingProfile.getDefinition();
result.clearTracingProfile();
if (!Boolean.FALSE.equals(tracingProfile.isCreateTraceFile())) {
boolean zip = !Boolean.FALSE.equals(tracingProfile.isCompressOutput());
Map<String, String> templateParameters = createTemplateParameters(task, result); // todo evaluate lazily if needed
File file = createFileName(zip, tracingProfile, templateParameters);
try {
long start = System.currentTimeMillis();
TracingOutputType tracingOutput = createTracingOutput(task, result, tracingProfile);
String xml = prismContext.xmlSerializer().serializeRealValue(tracingOutput);
if (zip) {
MiscUtil.writeZipFile(file, ZIP_ENTRY_NAME, xml, StandardCharsets.UTF_8);
LOGGER.info("Trace was written to {} ({} chars uncompressed) in {} milliseconds", file, xml.length(),
System.currentTimeMillis() - start);
} else {
try (PrintWriter pw = new PrintWriter(new FileWriter(file))) {
pw.write(xml);
LOGGER.info("Trace was written to {} ({} chars) in {} milliseconds", file, xml.length(),
System.currentTimeMillis() - start);
}
}
if (!Boolean.FALSE.equals(tracingProfile.isCreateRepoObject())) {
ReportOutputType reportOutputObject = new ReportOutputType(prismContext)
.name(createObjectName(tracingProfile, templateParameters))
.archetypeRef(SystemObjectsType.ARCHETYPE_TRACE.value(), ArchetypeType.COMPLEX_TYPE)
.filePath(file.getAbsolutePath())
.nodeRef(ObjectTypeUtil.createObjectRef(taskManager.getLocalNode(), prismContext));
repositoryService.addObject(reportOutputObject.asPrismObject(), null, thisOpResult);
}
} catch (IOException | SchemaException | ObjectAlreadyExistsException | RuntimeException e) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't write trace ({})", e, file);
throw new SystemException(e);
}
}
} catch (Throwable t) {
thisOpResult.recordFatalError(t);
throw t;
} finally {
thisOpResult.computeStatusIfUnknown();
}
}
private TracingOutputType createTracingOutput(Task task, OperationResult result, TracingProfileType tracingProfile) {
TracingOutputType output = new TracingOutputType(prismContext);
output.beginMetadata()
.createTimestamp(XmlTypeConverter.createXMLGregorianCalendar(System.currentTimeMillis()))
.profile(tracingProfile);
output.setEnvironment(createTracingEnvironmentDescription(task, tracingProfile));
OperationResultType resultBean = result.createOperationResultType();
List<TraceDictionaryType> embeddedDictionaries = extractDictionaries(result);
TraceDictionaryType dictionary = extractDictionary(embeddedDictionaries, resultBean);
output.setDictionary(dictionary);
result.setExtractedDictionary(dictionary);
output.setResult(resultBean);
return output;
}
private List<TraceDictionaryType> extractDictionaries(OperationResult result) {
return result.getResultStream()
.filter(r -> r.getExtractedDictionary() != null)
.map(OperationResult::getExtractedDictionary)
.collect(Collectors.toList());
}
@NotNull
private TracingEnvironmentType createTracingEnvironmentDescription(Task task, TracingProfileType tracingProfile) {
TracingEnvironmentType environment = new TracingEnvironmentType(prismContext);
if (!Boolean.TRUE.equals(tracingProfile.isHideDeploymentInformation())) {
DeploymentInformationType deployment = systemConfiguration != null ? systemConfiguration.getDeploymentInformation() : null;
if (deployment != null) {
DeploymentInformationType deploymentClone = deployment.clone();
deploymentClone.setSubscriptionIdentifier(null);
environment.setDeployment(deploymentClone);
}
}
NodeType localNode = taskManager.getLocalNode();
if (localNode != null) {
NodeType selectedNodeInformation = new NodeType(prismContext);
selectedNodeInformation.setName(localNode.getName());
selectedNodeInformation.setNodeIdentifier(localNode.getNodeIdentifier());
selectedNodeInformation.setBuild(CloneUtil.clone(localNode.getBuild()));
selectedNodeInformation.setClustered(localNode.isClustered());
environment.setNodeRef(ObjectTypeUtil.createObjectRefWithFullObject(selectedNodeInformation, prismContext));
}
TaskType taskClone = task.getClonedTaskObject().asObjectable();
if (taskClone.getResult() != null) {
taskClone.getResult().getPartialResults().clear();
}
environment.setTaskRef(ObjectTypeUtil.createObjectRefWithFullObject(taskClone, prismContext));
return environment;
}
// Extracting from JAXB objects currently does not work because RawType.getValue fails for
// raw versions of ObjectReferenceType holding full object
private static class ExtractingVisitor implements Visitor {
private final long started = System.currentTimeMillis();
private final TraceDictionaryType dictionary;
private final int dictionaryId;
private final PrismContext prismContext;
private int comparisons = 0;
private int objectsChecked = 0;
private int objectsAdded = 0;
private ExtractingVisitor(TraceDictionaryType dictionary, int dictionaryId, PrismContext prismContext) {
this.dictionary = dictionary;
this.dictionaryId = dictionaryId;
this.prismContext = prismContext;
}
// @Override
// public void visit(JaxbVisitable visitable) {
// JaxbVisitable.visitPrismStructure(visitable, this);
// }
@Override
public void visit(Visitable visitable) {
// if (visitable instanceof PrismPropertyValue) {
// PrismPropertyValue<?> pval = ((PrismPropertyValue) visitable);
// Object realValue = pval.getRealValue();
// if (realValue instanceof JaxbVisitable) {
// ((JaxbVisitable) realValue).accept(this);
// }
// } else
if (visitable instanceof PrismReferenceValue) {
PrismReferenceValue refVal = (PrismReferenceValue) visitable;
//noinspection unchecked
PrismObject<? extends ObjectType> object = refVal.getObject();
if (object != null && !object.isEmpty()) {
String qualifiedEntryId = findOrCreateEntry(object);
refVal.setObject(null);
refVal.setOid(SchemaConstants.TRACE_DICTIONARY_PREFIX + qualifiedEntryId);
if (object.getDefinition() != null) {
refVal.setTargetType(object.getDefinition().getTypeName());
}
}
}
}
private String findOrCreateEntry(PrismObject<? extends ObjectType> object) {
long started = System.currentTimeMillis();
int maxEntryId = 0;
objectsChecked++;
PrismObject<? extends ObjectType> objectToStore = stripFetchResult(object);
for (TraceDictionaryEntryType entry : dictionary.getEntry()) {
PrismObject dictionaryObject = entry.getObject().asReferenceValue().getObject();
if (Objects.equals(objectToStore.getOid(), dictionaryObject.getOid()) &&
Objects.equals(objectToStore.getVersion(), dictionaryObject.getVersion())) {
comparisons++;
boolean equals = objectToStore.equals(dictionaryObject);
if (equals) {
if (checkHashCodeEqualsRelation) {
checkHashCodes(objectToStore, dictionaryObject);
}
LOGGER.trace("Found existing entry #{}:{}: {} [in {} ms]", entry.getOriginDictionaryId(),
entry.getIdentifier(), objectToStore, System.currentTimeMillis() - started);
return entry.getOriginDictionaryId() + ":" + entry.getIdentifier();
} else {
LOGGER.trace("Found object with the same OID {} and same version '{}' but with different content",
objectToStore.getOid(), objectToStore.getVersion());
}
}
if (entry.getIdentifier() > maxEntryId) {
// We intentionally ignore context for entries.
maxEntryId = entry.getIdentifier();
}
}
int newEntryId = maxEntryId + 1;
LOGGER.trace("Inserting object as entry #{}:{}: {} [in {} ms]", dictionaryId, newEntryId, objectToStore,
System.currentTimeMillis()-started);
dictionary.beginEntry()
.identifier(newEntryId)
.originDictionaryId(dictionaryId)
.object(ObjectTypeUtil.createObjectRefWithFullObject(objectToStore, prismContext));
objectsAdded++;
return dictionaryId + ":" + newEntryId;
}
// These objects are equal. They hashcodes should be also. This is a helping hand given to tests. See MID-5851.
private void checkHashCodes(PrismObject object1, PrismObject object2) {
int hash1 = object1.hashCode();
int hash2 = object2.hashCode();
if (hash1 != hash2) {
System.out.println("Hash 1 = " + hash1);
System.out.println("Hash 2 = " + hash2);
System.out.println("Object 1:\n" + object1.debugDump());
System.out.println("Object 2:\n" + object2.debugDump());
//noinspection unchecked
System.out.println("Diff:\n" + DebugUtil.debugDump(object1.diff(object2)));
throw new AssertionError("Objects " + object1 + " and " + object2 + " are equal but their hashcodes are different");
}
}
@NotNull
private PrismObject<? extends ObjectType> stripFetchResult(PrismObject<? extends ObjectType> object) {
PrismObject<? extends ObjectType> objectToStore;
if (object.asObjectable().getFetchResult() != null) {
objectToStore = object.clone();
objectToStore.asObjectable().setFetchResult(null);
} else {
objectToStore = object;
}
return objectToStore;
}
private void logDiagnosticInformation() {
LOGGER.trace("Extracted dictionary: {} objects added in {} ms ({} total), using {} object comparisons while checking {} objects",
objectsAdded, System.currentTimeMillis()-started, dictionary.getEntry().size(), comparisons, objectsChecked);
}
}
private TraceDictionaryType extractDictionary(List<TraceDictionaryType> embeddedDictionaries, OperationResultType resultBean) {
TraceDictionaryType dictionary = new TraceDictionaryType(prismContext);
embeddedDictionaries.forEach(embeddedDictionary ->
dictionary.getEntry().addAll(CloneUtil.cloneCollectionMembers(embeddedDictionary.getEntry())));
int newDictionaryId = generateDictionaryId(embeddedDictionaries);
dictionary.setIdentifier(newDictionaryId);
ExtractingVisitor extractingVisitor = new ExtractingVisitor(dictionary, newDictionaryId, prismContext);
extractDictionary(resultBean, extractingVisitor);
extractingVisitor.logDiagnosticInformation();
return dictionary;
}
private int generateDictionaryId(List<TraceDictionaryType> embedded) {
int max = embedded.stream()
.map(TraceDictionaryType::getIdentifier)
.max(Integer::compareTo)
.orElse(0);
return max + 1;
}
private void extractDictionary(OperationResultType resultBean, ExtractingVisitor extractingVisitor) {
resultBean.getTrace().forEach(trace -> trace.asPrismContainerValue().accept(extractingVisitor));
resultBean.getPartialResults().forEach(partialResult -> extractDictionary(partialResult, extractingVisitor));
}
private Map<String, String> createTemplateParameters(Task task, OperationResult result) {
Map<String, String> rv = new HashMap<>();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");
rv.put(MACRO_TIMESTAMP, df.format(new Date()));
String operationName = result.getOperation();
rv.put(MACRO_OPERATION_NAME, operationName);
rv.put(MACRO_OPERATION_NAME_SHORT, shorten(operationName));
String testName;
if (TestNameHolder.getCurrentTestName() != null) {
testName = TestNameHolder.getCurrentTestName();
} else {
testName = task.getResult().getOperation();
}
rv.put(MACRO_TEST_NAME, testName); // e.g. com.evolveum.midpoint.model.intest.TestIteration.test532GuybrushModifyDescription or simply TestIteration.test532GuybrushModifyDescription
rv.put(MACRO_TEST_NAME_SHORT, shorten(testName));
rv.put(MACRO_FOCUS_NAME, getFocusName(result));
rv.put(MACRO_MILLISECONDS, getMilliseconds(result));
rv.put(MACRO_RANDOM, String.valueOf((long) (Math.random() * 1000000000000000L)));
return rv;
}
private String shorten(String qualifiedName) {
if (qualifiedName != null) {
int secondLastDotIndex = StringUtils.lastOrdinalIndexOf(qualifiedName, ".", 2);
return secondLastDotIndex >= 0 ? qualifiedName.substring(secondLastDotIndex+1) : qualifiedName;
} else {
return null;
}
}
private String getFocusName(OperationResult result) {
ClockworkRunTraceType trace = result.getFirstTrace(ClockworkRunTraceType.class);
if (trace != null && trace.getFocusName() != null) {
return trace.getFocusName();
} else {
return "unknown";
}
}
private String getMilliseconds(OperationResult result) {
if (result.getMicroseconds() != null) {
return String.valueOf(result.getMicroseconds() / 1000);
} else if (result.getStart() != null && result.getEnd() != null) {
return String.valueOf(result.getEnd() - result.getStart());
} else {
return "unknown";
}
}
private String createObjectName(TracingProfileType profile, Map<String, String> parameters) {
String pattern;
if (profile.getObjectNamePattern() != null) {
pattern = profile.getObjectNamePattern();
} else if (profile.getFileNamePattern() != null) {
pattern = profile.getFileNamePattern();
} else {
pattern = DEFAULT_FILE_NAME_PATTERN;
}
return expandMacros(pattern, parameters);
}
@NotNull
private File createFileName(boolean zip, TracingProfileType profile, Map<String, String> parameters) {
File traceDir = new File(TRACE_DIR);
if (!traceDir.exists() || !traceDir.isDirectory()) {
if (!traceDir.mkdir()) {
LOGGER.warn("Attempted to create trace directory but failed: {}", traceDir);
}
}
String pattern = profile.getFileNamePattern() != null ? profile.getFileNamePattern() : DEFAULT_FILE_NAME_PATTERN;
return new File(traceDir, normalizeFileName(expandMacros(pattern, parameters)) + (zip ? ".zip" : ".xml"));
}
private String normalizeFileName(String name) {
return name.replaceAll("[^a-zA-Z0-9 .-]", "_");
}
private String expandMacros(String pattern, Map<String, String> parameters) {
StringBuilder sb = new StringBuilder();
for (int current = 0;;) {
int i = pattern.indexOf("%{", current);
if (i < 0) {
sb.append(pattern.substring(current));
return sb.toString();
}
sb.append(pattern, current, i);
int j = pattern.indexOf("}", i);
if (j < 0) {
LOGGER.warn("Missing '}' in pattern '{}'", pattern);
return sb.toString() + " - error - " + parameters.get(MACRO_RANDOM);
} else {
String macroName = pattern.substring(i+2, j);
String value = parameters.get(macroName);
if (value == null) {
LOGGER.warn("Unknown parameter '{}' in pattern '{}'", macroName, pattern);
}
sb.append(value);
}
current = j+1;
}
}
@Override
public TracingProfileType resolve(TracingProfileType tracingProfile, OperationResult result) throws SchemaException {
if (tracingProfile == null) {
return null;
} else if (tracingProfile.getRef().isEmpty()) {
return tracingProfile;
} else {
List<String> resolutionPath = new ArrayList<>();
return resolveProfile(tracingProfile, getTracingConfiguration(), resolutionPath);
}
}
@NotNull
private TracingProfileType resolveProfile(TracingProfileType tracingProfile, TracingConfigurationType tracingConfiguration,
List<String> resolutionPath) throws SchemaException {
if (tracingProfile.getRef().isEmpty()) {
return tracingProfile;
} else {
TracingProfileType rv = new TracingProfileType();
for (String ref : tracingProfile.getRef()) {
merge(rv, getResolvedProfile(ref, tracingConfiguration, resolutionPath));
}
merge(rv, tracingProfile);
rv.getRef().clear();
return rv;
}
}
private TracingProfileType getResolvedProfile(String ref, TracingConfigurationType tracingConfiguration,
List<String> resolutionPath) throws SchemaException {
if (resolutionPath.contains(ref)) {
throw new IllegalStateException("A cycle in tracing profile resolution path: " + resolutionPath + " -> " + ref);
}
resolutionPath.add(ref);
TracingProfileType profile = findProfile(ref, tracingConfiguration);
resolutionPath.remove(resolutionPath.size()-1);
TracingProfileType rv = resolveProfile(profile, tracingConfiguration, resolutionPath);
LOGGER.info("Resolved '{}' into:\n{}", ref, rv.asPrismContainerValue().debugDump());
return rv;
}
private TracingProfileType findProfile(String name, TracingConfigurationType tracingConfiguration) throws SchemaException {
List<TracingProfileType> matching = tracingConfiguration.getProfile().stream()
.filter(p -> name.equals(p.getName()))
.collect(Collectors.toList());
if (matching.isEmpty()) {
throw new SchemaException("Tracing profile '" + name + "' is referenced but not defined. Known names: "
+ tracingConfiguration.getProfile().stream().map(TracingProfileType::getName).collect(Collectors.joining(", ")));
} else if (matching.size() == 1) {
return matching.get(0);
} else {
throw new SchemaException("More than one profile with the name '" + name + "' exist.");
}
}
// fixme experimental ... not thought out very much - this method will probably work only for non-overlapping profiles
private void merge(TracingProfileType summary, TracingProfileType delta) throws SchemaException {
//noinspection unchecked
summary.asPrismContainerValue().mergeContent(delta.asPrismContainerValue(), Collections.emptyList());
}
@Override
public boolean update(@Nullable SystemConfigurationType value) {
systemConfiguration = value;
return true;
}
@Override
public TracingProfileType getDefaultProfile() {
TracingConfigurationType tracingConfiguration = getTracingConfiguration();
if (tracingConfiguration == null || tracingConfiguration.getProfile().isEmpty()) {
return new TracingProfileType(prismContext);
} else {
List<TracingProfileType> defaultProfiles = tracingConfiguration.getProfile().stream()
.filter(p -> Boolean.TRUE.equals(p.isDefault()))
.collect(Collectors.toList());
if (defaultProfiles.isEmpty()) {
return tracingConfiguration.getProfile().get(0);
} else if (defaultProfiles.size() == 1) {
return defaultProfiles.get(0);
} else {
LOGGER.warn("More than one default tracing profile configured; selecting the first one");
return defaultProfiles.get(0);
}
}
}
@Override
public CompiledTracingProfile compileProfile(TracingProfileType profile, OperationResult result) throws SchemaException {
TracingProfileType resolvedProfile = resolve(profile, result);
return CompiledTracingProfile.create(resolvedProfile, prismContext);
}
@Nullable
private TracingConfigurationType getTracingConfiguration() {
return systemConfiguration != null && systemConfiguration.getInternals() != null ?
systemConfiguration.getInternals().getTracing() :
null;
}
}
| bshp/midPoint | repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/tracing/TracerImpl.java | Java | apache-2.0 | 26,762 |
/*
* ******************************************************************************
* Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Calls;
using Ds3.Models;
using Ds3.Runtime;
using System.Linq;
using System.Net;
using System.Xml.Linq;
namespace Ds3.ResponseParsers
{
internal class GetDataReplicationRulesSpectraS3ResponseParser : IResponseParser<GetDataReplicationRulesSpectraS3Request, GetDataReplicationRulesSpectraS3Response>
{
public GetDataReplicationRulesSpectraS3Response Parse(GetDataReplicationRulesSpectraS3Request request, IWebResponse response)
{
using (response)
{
ResponseParseUtilities.HandleStatusCode(response, (HttpStatusCode)200);
using (var stream = response.GetResponseStream())
{
return new GetDataReplicationRulesSpectraS3Response(
ModelParsers.ParseDataReplicationRuleList(
XmlExtensions.ReadDocument(stream).ElementOrThrow("Data")),
ResponseParseUtilities.ParseIntHeader("page-truncated", response.Headers),
ResponseParseUtilities.ParseIntHeader("total-result-count", response.Headers)
);
}
}
}
}
} | rpmoore/ds3_net_sdk | Ds3/ResponseParsers/GetDataReplicationRulesSpectraS3ResponseParser.cs | C# | apache-2.0 | 1,986 |
package com.example
import com.google.inject.Stage
import com.twitter.finatra.http.EmbeddedHttpServer
import com.twitter.inject.Test
class ExampleStartupTest extends Test {
val server = new EmbeddedHttpServer(
stage = Stage.PRODUCTION,
twitterServer = new ExampleServer)
test("server#startup") {
server.assertHealthy()
}
}
| twitter/finatra-activator-seed | src/test/scala/com/example/ExampleStartupTest.scala | Scala | apache-2.0 | 345 |
require 'AWS/S3'
require 'pp'
class S3Adapter
def self.get_s3(account)
return if account.nil?
return if account.aws_access_key.blank? or account.aws_secret_key.blank?
keys = [ account.aws_access_key, account.aws_secret_key ]
AWS::S3.new(*keys)
end
def self.get_owner_id(account)
s3 = get_s3(account)
s3.get_owner_id
end
def self.create_bucket(account, bucket)
s3 = get_s3(account)
s3.create_bucket(bucket) unless bucket_exists?(account, bucket)
end
def self.put_object(account, bucket, key, content, policy = 'private')
s3 = get_s3(account)
create_bucket(account, bucket)
# canned policy may be: 'private', 'public-read', 'public-read-write', 'authenticated-read'
opts = {
:data => content,
:policy => policy,
}
obj = s3.create_object(bucket, key, opts)
end
def self.grant_read(account, bucket, key='', readers=[])
s3 = get_s3(account)
owner_id = s3.get_owner_id
grants = [ owner_id => 'FULL_CONTROL' ]
# pull the owner out to avoid overwriting full control rule
rs = readers.collect{|r| r unless r.s3_user_id == owner_id }.compact
rs.each do |r|
grants << { r.s3_user_id => 'READ' }
end
s3.set_acl(owner_id, bucket, key, grants)
end
def self.get_acl(account, bucket, key='')
s3 = get_s3(account)
s3.get_acl(bucket, key)
end
def self.list_buckets(account)
get_s3(account).list_buckets
end
def self.bucket_exists?(account, bucket)
list_buckets(account)[:buckets].any? { |b| b[:name] == bucket } rescue false
end
end
| vadimj/nimbul | app/models/s3_adapter.rb | Ruby | apache-2.0 | 1,746 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.