repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
aws-samples/bcs-disaster-recovery-portal-common
|
main/java/aws/proserve/bcs/dr/vpc/VpcProject.java
|
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
package aws.proserve.bcs.dr.vpc;
import aws.proserve.bcs.dr.project.SubProject;
import java.util.List;
public class VpcProject extends SubProject<VpcItem> {
/**
* @apiNote need to override to pass the reified type information for DynamoDB converter.
*/
@Override
public List<VpcItem> getItems() {
return super.getItems();
}
@Override
public void setItems(List<VpcItem> items) {
super.setItems(items);
}
}
|
wfxiang08/curator
|
curator-x-rpc/src/main/java/org/apache/curator/x/rpc/connections/CuratorEntry.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.x.rpc.connections;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.common.collect.Queues;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.x.rpc.idl.exceptions.ExceptionType;
import org.apache.curator.x.rpc.idl.exceptions.RpcException;
import org.apache.curator.x.rpc.idl.structs.CuratorProjection;
import org.apache.curator.x.rpc.idl.structs.RpcCuratorEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
public class CuratorEntry implements Closeable
{
private final Logger log = LoggerFactory.getLogger(getClass());
private final CuratorFramework client;
private final BlockingQueue<RpcCuratorEvent> events = Queues.newLinkedBlockingQueue();
private final AtomicReference<State> state = new AtomicReference<State>(State.OPEN);
private final Map<String, Entry> things = Maps.newConcurrentMap();
public static <T> T mustGetThing(CuratorEntry entry, String id, Class<T> clazz)
{
T thing = entry.getThing(id, clazz);
Preconditions.checkNotNull(thing, "No item of type " + clazz.getSimpleName() + " found with id " + id);
return thing;
}
private static class Entry
{
final Object thing;
final Closer closer;
private Entry(Object thing, Closer closer)
{
this.thing = thing;
this.closer = closer;
}
}
private enum State
{
OPEN,
CLOSED
}
public CuratorEntry(CuratorFramework client)
{
this.client = client;
}
@Override
public void close()
{
if ( state.compareAndSet(State.OPEN, State.CLOSED) )
{
for ( Map.Entry<String, Entry> mapEntry : things.entrySet() )
{
Entry entry = mapEntry.getValue();
if ( entry.closer != null )
{
log.debug(String.format("Closing left over thing. Type: %s - Id: %s", entry.thing.getClass(), mapEntry.getKey()));
entry.closer.close();
}
}
things.clear();
client.close();
events.clear();
}
}
public RpcCuratorEvent pollForEvent(long maxWaitMs) throws InterruptedException
{
if ( state.get() == State.OPEN )
{
return events.poll(maxWaitMs, TimeUnit.MILLISECONDS);
}
return null;
}
public void addEvent(RpcCuratorEvent event)
{
if ( state.get() == State.OPEN )
{
events.offer(event);
}
}
public static CuratorEntry mustGetEntry(ConnectionManager connectionManager, CuratorProjection projection) throws RpcException
{
CuratorEntry entry = connectionManager.get(projection.id);
if ( entry == null )
{
throw new RpcException(ExceptionType.GENERAL, null, null, "No CuratorProjection found with the id: " + projection.id);
}
return entry;
}
public CuratorFramework getClient()
{
return (state.get() == State.OPEN) ? client : null;
}
public String addThing(Object thing, Closer closer)
{
return addThing(newId(), thing, closer);
}
public static String newId()
{
return UUID.randomUUID().toString();
}
public <T> T getThing(String id, Class<T> clazz)
{
Entry entry = (id != null) ? things.get(id) : null;
return cast(clazz, entry);
}
public boolean closeThing(String id)
{
Entry entry = (id != null) ? things.remove(id) : null;
if ( entry != null )
{
entry.closer.close();
}
return false;
}
private <T> String addThing(String id, T thing, Closer closer)
{
things.put(id, new Entry(thing, closer));
return id;
}
private <T> T cast(Class<T> clazz, Entry entry)
{
if ( entry != null )
{
return clazz.cast(entry.thing);
}
return null;
}
}
|
DragonJoker/Ashes
|
include/ashespp/Descriptor/DescriptorSetPool.hpp
|
/*
This file belongs to Ashes.
See LICENSE file in root folder.
*/
#ifndef ___AshesPP_DescriptorSetPool_HPP___
#define ___AshesPP_DescriptorSetPool_HPP___
#pragma once
#include "ashespp/Descriptor/DescriptorPool.hpp"
#include <vector>
namespace ashes
{
/**
*\brief
* Descriptor set pool helper.
*/
class DescriptorSetPool
{
public:
/**
*\brief
* Constructor.
*\param[in] device
* The logical device.
*\param[in] layout
* The layout from which the pool will be created.
*\param[in] maxSets
* The maximum sets count that can be created from this pool.
*\param[in] automaticFree
* Tells if the pool automatically frees the sets it has allocated, during its own destruction.
*/
DescriptorSetPool( Device const & device
, DescriptorSetLayout const & layout
, uint32_t maxSets
, bool automaticFree );
/**
*\brief
* Constructor.
*\param[in] device
* The logical device.
*\param[in] layout
* The layout from which the pool will be created.
*\param[in] maxSets
* The maximum sets count that can be created from this pool.
*\param[in] automaticFree
* Tells if the pool automatically frees the sets it has allocated, during its own destruction.
*/
DescriptorSetPool( Device const & device
, std::string const & debugName
, DescriptorSetLayout const & layout
, uint32_t maxSets
, bool automaticFree );
/**
*\brief
* Creates a descriptor set matching the layout defined for this pool.
*\param[in] bindingPoint
* The binding point for the set.
*\return
* The created descriptor set.
*/
DescriptorSetPtr createDescriptorSet( uint32_t bindingPoint = 0u )const;
/**
*\brief
* Creates a descriptor set matching the layout defined for this pool.
*\param[in] bindingPoint
* The binding point for the set.
*\return
* The created descriptor set.
*/
DescriptorSetPtr createDescriptorSet( std::string const & debugName
, uint32_t bindingPoint = 0u )const;
void freeDescriptorSet( DescriptorSetPtr set )const;
/**
*\return
* The descriptor set layout.
*/
inline DescriptorSetLayout const & getLayout()const
{
return m_layout;
}
/**
*\return
* The descriptor set layout.
*/
inline DescriptorPool const & getPool()const
{
return *m_pool;
}
/**
*\brief
* VkDescriptorPool implicit cast operator.
*/
inline operator VkDescriptorPool const & ()const
{
return *m_pool;
}
private:
DescriptorSetLayout const & m_layout;
DescriptorPoolPtr m_pool;
};
}
#endif
|
trickMin/portal
|
gateway-api/src/main/java/org/hango/cloud/gdashboard/api/meta/swagger/SwaggerApiInfo.java
|
package org.hango.cloud.gdashboard.api.meta.swagger;
import org.hango.cloud.gdashboard.api.meta.ApiBody;
import org.hango.cloud.gdashboard.api.meta.ApiHeader;
import org.hango.cloud.gdashboard.api.meta.ApiInfo;
import org.hango.cloud.gdashboard.api.meta.ApiStatusCode;
import java.util.List;
public class SwaggerApiInfo {
/**
* ApiInfo基本信息
*/
private ApiInfo apiInfo;
/**
* api request 请求header
*/
private List<ApiHeader> apiRequestHeader;
/**
* api response 请求header
*/
private List<ApiHeader> apiResponseHeader;
/**
* api request body
*/
private List<ApiBody> apiRequestBody;
/**
* api response body
*/
private List<ApiBody> apiResponseBody;
/**
* api query string
*/
private List<ApiBody> apiQueryString;
/**
* api status code
*/
private List<ApiStatusCode> apiStatusCodes;
public ApiInfo getApiInfo() {
return apiInfo;
}
public void setApiInfo(ApiInfo apiInfo) {
this.apiInfo = apiInfo;
}
public List<ApiHeader> getApiRequestHeader() {
return apiRequestHeader;
}
public void setApiRequestHeader(List<ApiHeader> apiRequestHeader) {
this.apiRequestHeader = apiRequestHeader;
}
public List<ApiHeader> getApiResponseHeader() {
return apiResponseHeader;
}
public void setApiResponseHeader(List<ApiHeader> apiResponseHeader) {
this.apiResponseHeader = apiResponseHeader;
}
public List<ApiBody> getApiRequestBody() {
return apiRequestBody;
}
public void setApiRequestBody(List<ApiBody> apiRequestBody) {
this.apiRequestBody = apiRequestBody;
}
public List<ApiBody> getApiResponseBody() {
return apiResponseBody;
}
public void setApiResponseBody(List<ApiBody> apiResponseBody) {
this.apiResponseBody = apiResponseBody;
}
public List<ApiBody> getApiQueryString() {
return apiQueryString;
}
public void setApiQueryString(List<ApiBody> apiQueryString) {
this.apiQueryString = apiQueryString;
}
public List<ApiStatusCode> getApiStatusCodes() {
return apiStatusCodes;
}
public void setApiStatusCodes(List<ApiStatusCode> apiStatusCodes) {
this.apiStatusCodes = apiStatusCodes;
}
}
|
Shehanka/RentLio-1
|
RentLioCommon/src/com/chamodshehanka/rentLioCommon/services/custom/AdminService.java
|
package com.chamodshehanka.rentLioCommon.services.custom;
import com.chamodshehanka.rentLioCommon.dto.AdminDTO;
import com.chamodshehanka.rentLioCommon.observer.AdminObserver;
import com.chamodshehanka.rentLioCommon.services.SuperService;
import java.util.List;
/**
* @author chamodshehanka on 3/13/2018
* @project RentLio
**/
public interface AdminService extends SuperService{
public boolean addAdmin(AdminDTO adminDTO) throws Exception;
public boolean updateAdmin(AdminDTO adminDTO) throws Exception;
public boolean deleteAdmin(String adminId) throws Exception;
public AdminDTO findByIdAdmin(String adminId) throws Exception;
public List<AdminDTO> getAllAdmins() throws Exception;
public boolean addAdminObserver(AdminObserver adminObserver) throws Exception;
public boolean removeAdminObserver(AdminObserver adminObserver) throws Exception;
}
|
MarkOSIndustries/distroboy
|
parquet/src/main/java/com/markosindustries/distroboy/parquet/ParquetGroupInspector.java
|
<filename>parquet/src/main/java/com/markosindustries/distroboy/parquet/ParquetGroupInspector.java
package com.markosindustries.distroboy.parquet;
import java.util.AbstractList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.apache.parquet.example.data.Group;
public class ParquetGroupInspector {
private final Group group;
public ParquetGroupInspector(Group group) {
this.group = group;
}
public Group getGroup() {
return group;
}
public boolean isRepeated(String fieldName) {
return group.getFieldRepetitionCount(fieldName) > 1;
}
public boolean isPresent(String fieldName) {
return group.getFieldRepetitionCount(fieldName) > 0;
}
public boolean isPrimitive(String fieldName) {
return group.getType().getType(fieldName).isPrimitive();
}
public ParquetGroupInspector inspectGroup(String fieldName) {
int fieldIndex = group.getType().getFieldIndex(fieldName);
if (group.getType().getType(fieldIndex).isPrimitive()) {
throw new RuntimeException(
"Parquet field " + fieldName + " is a Primitive type, but was accessed as a Group type");
}
return new ParquetGroupInspector(group.getGroup(fieldIndex, 0));
}
public List<ParquetGroupInspector> inspectRepeatedGroup(String fieldName) {
int fieldIndex = group.getType().getFieldIndex(fieldName);
if (group.getType().getType(fieldIndex).isPrimitive()) {
throw new RuntimeException(
"Parquet field " + fieldName + " is a Primitive type, but was accessed as a Group type");
}
int valueCount = group.getFieldRepetitionCount(fieldIndex);
return new AbstractList<>() {
@Override
public ParquetGroupInspector get(int index) {
return new ParquetGroupInspector(group.getGroup(fieldIndex, index));
}
@Override
public int size() {
return valueCount;
}
};
}
public <T> T getPrimitive(
String fieldName, Function<Group, BiFunction<Integer, Integer, T>> getPrimitiveAccessor) {
int fieldIndex = group.getType().getFieldIndex(fieldName);
if (!group.getType().getType(fieldIndex).isPrimitive()) {
throw new RuntimeException(
"Parquet field " + fieldName + " is a Group type, but was accessed as a Primitive");
}
return getPrimitiveAccessor.apply(group).apply(fieldIndex, 0);
}
public <T> List<T> getRepeatedPrimitive(
String fieldName, Function<Group, BiFunction<Integer, Integer, T>> getPrimitiveAccessor) {
int fieldIndex = group.getType().getFieldIndex(fieldName);
if (!group.getType().getType(fieldIndex).isPrimitive()) {
throw new RuntimeException(
"Parquet field " + fieldName + " is a Group type, but was accessed as a Primitive");
}
int valueCount = group.getFieldRepetitionCount(fieldIndex);
return new AbstractList<>() {
@Override
public T get(int index) {
return getPrimitiveAccessor.apply(group).apply(fieldIndex, index);
}
@Override
public int size() {
return valueCount;
}
};
}
}
|
lemkova/Yorozuya
|
library/ATF/_qry_case_load_guildbattle_totalrecord.hpp
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
struct _qry_case_load_guildbattle_totalrecord
{
unsigned int dwGuildSerial;
unsigned int dwTotWinCnt;
unsigned int dwTotLoseCnt;
unsigned int dwTotDrawCnt;
public:
int size();
};
static_assert(ATF::checkSize<_qry_case_load_guildbattle_totalrecord, 16>(), "_qry_case_load_guildbattle_totalrecord");
END_ATF_NAMESPACE
|
MaxNoe/pyhexgrid
|
setup.py
|
<gh_stars>1-10
from setuptools import setup
setup(
name='pyhexgrid',
description='A numpy aware package for hexagonale grids',
url='http://github.com/maxnoe/pyhexgrid',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['hexgrid'],
version='0.1.1',
install_requires=[
'numpy',
'pandas',
],
setup_requires=['pytest-runner'],
tests_require=['pytest>=3.0.0'],
zip_safe=False,
)
|
whitespur/zheshiyigeniubidexiangmu
|
admin/src/main/java/com/github/misterchangray/controller/TickerController.java
|
<gh_stars>100-1000
package com.github.misterchangray.controller;
import com.github.misterchangray.common.ResultSet;
import com.github.misterchangray.common.utils.MapBuilder;
import com.github.misterchangray.controller.common.Const;
import com.github.misterchangray.controller.common.OrgsInfoEnum;
import com.github.misterchangray.service.common.MongoDbService;
import com.github.misterchangray.service.platform.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
/**
* 获取并处理K线数据
*/
@Controller
@RequestMapping("/v1/ticker")
public class TickerController {
@Autowired
OKEXService OKEXService;
@Autowired
BiAnService biAnService;
@Autowired
MongoDbService mongoDbService;
@Autowired
HuoBiService huoBiService;
@Autowired
Big1Service big1Service;
@Autowired
OTCBTCService OTCBTCService;
@Autowired
FcoinService fcoinDataService;
@Autowired
BitfinexService bitfinexService;
@Autowired
ZbSiteService zbSiteService;
@Autowired
BitzService bitzService;
@Autowired
CoinbaseProService coinbaseProService;
@Autowired
DigiFinexService digiFinexService;
@Autowired
BiboxService biboxService;
@Autowired
KrakenService krakenService;
//获取最小价格
@ResponseBody
@RequestMapping(method = RequestMethod.GET, value = "lastPrice")
public ResultSet<String> getLastPrice(@RequestParam("type" ) String type) {
MapBuilder data = MapBuilder.build();
data.add(OrgsInfoEnum.OKEX.getOrgName(), OKEXService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.BiAn.getOrgName(), biAnService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.HuoBi.getOrgName(), huoBiService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.Big1.getOrgName(), big1Service.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.OTCBTC.getOrgName(), OTCBTCService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.Fcoin.getOrgName(), fcoinDataService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.Bitfinex.getOrgName(), bitfinexService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.Zb_site.getOrgName(), zbSiteService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.Bit_z.getOrgName(), bitzService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.CoinbasePro.getOrgName(), coinbaseProService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.DigiFinex.getOrgName(), digiFinexService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.Bibox.getOrgName(), biboxService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.Kraken.getOrgName(), krakenService.getTickerSpot(type).getLast());
return ResultSet.build().setData(data);
}
@ResponseBody
@RequestMapping(method = RequestMethod.GET, value = "lastPriceAll")
public ResultSet<String> getLastPrice() {
MapBuilder res = MapBuilder.build();
for(String type : Const.types) {
MapBuilder data = MapBuilder.build();
data.add(OrgsInfoEnum.OKEX.getOrgName(), OKEXService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.BiAn.getOrgName(), biAnService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.HuoBi.getOrgName(), huoBiService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.Big1.getOrgName(), big1Service.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.OTCBTC.getOrgName(), OTCBTCService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.Fcoin.getOrgName(), fcoinDataService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.Bitfinex.getOrgName(), bitfinexService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.Zb_site.getOrgName(), zbSiteService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.Bit_z.getOrgName(), bitzService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.CoinbasePro.getOrgName(), coinbaseProService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.DigiFinex.getOrgName(), digiFinexService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.Bibox.getOrgName(), biboxService.getTickerSpot(type).getLast());
data.add(OrgsInfoEnum.Kraken.getOrgName(), krakenService.getTickerSpot(type).getLast());
res.put(type, data);
}
return ResultSet.build().setData(res);
}
}
|
mirza-jahangeer/NCache-Samples
|
java/spring/src/main/java/com/alachisoft/ncache/springbootsample/bookstore/Book.java
|
package com.alachisoft.ncache.springbootsample.bookstore;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
@Entity
@org.hibernate.annotations.NamedQuery(name = "Book.findBookByIsbn",
query = "select b from Book b where b.isbn = ?1")
public class Book implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private long isbn;
private String title;
public Book(){}
public long getIsbn() {
return isbn;
}
public void setId(Integer id) {
this.id = id;
}
public void setIsbn(long isbn) {
this.isbn = isbn;
}
public Integer getId() {
return id;
}
public Book(long isbn, String title, String subTitle,
String author, Date publishedDate, String publisher,
long pages, String description, String webURL) {
this.isbn = isbn;
this.title = title;
this.subTitle = subTitle;
this.author = author;
this.publishedDate = publishedDate;
this.publisher = publisher;
this.pages = pages;
this.description = description;
this.webURL = webURL;
}
private String subTitle;
private String author;
private Date publishedDate;
private String publisher;
private long pages;
@Column(length=3000)
private String description;
private String webURL;
public long getISBN() {
return isbn;
}
public void setISBN(long isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public long getPages() {
return pages;
}
public void setPages(long pages) {
this.pages = pages;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getWebURL() {
return webURL;
}
public void setWebURL(String webURL) {
this.webURL = webURL;
}
}
|
usnationalarchives/catalog-source
|
OpaArchLib/src/main/java/gov/nara/opa/common/valueobject/annotation/tags/TagValueObjectHelper.java
|
<reponame>usnationalarchives/catalog-source
package gov.nara.opa.common.valueobject.annotation.tags;
import java.sql.Timestamp;
import java.util.Date;
import org.apache.commons.codec.digest.DigestUtils;
public class TagValueObjectHelper {
public static TagValueObject createTagForInsert(Integer accountId,
String naId, String objectId, String text, Integer pageNum) {
TagValueObject tag = new TagValueObject();
tag.setAccountId(accountId);
tag.setAnnotation(text);
tag.setAnnotationMD5(DigestUtils.md5Hex(text));
// tag.setAnnotationTS(TimestampUtils.getCurrentTimeInUtc());
tag.setAnnotationTS(new Timestamp(new Date().getTime()));
tag.setNaId(naId);
tag.setObjectId(objectId);
tag.setStatus(true);
tag.setPageNum(pageNum);
// TODO what should we do about Opa ID?
return tag;
}
}
|
Testiduk/gitlabhq
|
app/models/terraform/state_version.rb
|
<filename>app/models/terraform/state_version.rb<gh_stars>1000+
# frozen_string_literal: true
module Terraform
class StateVersion < ApplicationRecord
include FileStoreMounter
belongs_to :terraform_state, class_name: 'Terraform::State', optional: false
belongs_to :created_by_user, class_name: 'User', optional: true
belongs_to :build, class_name: 'Ci::Build', optional: true, foreign_key: :ci_build_id
scope :ordered_by_version_desc, -> { order(version: :desc) }
scope :with_files_stored_locally, -> { where(file_store: Terraform::StateUploader::Store::LOCAL) }
scope :preload_state, -> { includes(:terraform_state) }
default_value_for(:file_store) { StateUploader.default_store }
mount_file_store_uploader StateUploader
delegate :project_id, :uuid, to: :terraform_state, allow_nil: true
end
end
Terraform::StateVersion.prepend_mod_with('Terraform::StateVersion')
|
xloem/DIY-LAPTOP
|
SOFTWARE/A64-TERES/linux-a64/drivers/soc/allwinner/pm/mem_tmstmp.h
|
<reponame>xloem/DIY-LAPTOP
/*
*********************************************************************************************************
* LINUX-KERNEL
* AllWinner Linux Platform Develop Kits
* Kernel Module
*
* (c) Copyright 2011-2015, gq.yang China
* All Rights Reserved
*
* File : mem_tmstmp.h
* By : gq.yang
* Version : v1.0
* Date : 2012-11-31 15:23
* Descript:
* Update : date auther ver notes
*********************************************************************************************************
*/
#ifndef __MEM_TMSTMP_H__
#define __MEM_TMSTMP_H__
typedef struct __MEM_TMSTMP_REG
{
// offset:0x00
volatile __u32 Ctl;
volatile __u32 reserved0[7];
// offset:0x20
volatile __u32 Cluster0CtrlReg1;
} __mem_tmstmp_reg_t;
//for super standby;
__s32 mem_tmstmp_save(__mem_tmstmp_reg_t *ptmstmp_state);
__s32 mem_tmstmp_restore(__mem_tmstmp_reg_t *ptmstmp_state);
#endif //__MEM_TMSTMP_H__
|
williamBoss/new_mtms_java
|
ruoyi-service-api/mtms-api/src/main/java/com/ruoyi/mtms/domain/PastMedicalHistory.java
|
package com.ruoyi.mtms.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.ruoyi.mtms.base.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* ${TODO}
* @author KING
* @date 2020/9/9 21:19
* @version V1.0
*/
/**
* 既往病史与评估关系表
*/
@ApiModel(value = "com-ruoyi-mtms-domain-PastMedicalHistory")
@Data
@EqualsAndHashCode(callSuper = true)
@TableName(value = "mtms_past_medical_history")
public class PastMedicalHistory extends BaseEntity {
/**
* 既往病史id
*/
@TableId(value = "history_id", type = IdType.AUTO)
@ApiModelProperty(value = "既往病史id")
private Integer historyId;
/**
* 评估id
*/
@TableField(value = "assessment_id")
@ApiModelProperty(value = "评估id")
private Integer assessmentId;
/**
* 患者id
*/
@TableField(value = "patient_id")
@ApiModelProperty(value = "患者id")
private Integer patientId;
/**
* 既往病史病种id
*/
@TableField(value = "disease_id")
@ApiModelProperty(value = "既往病史病种id")
private Integer diseaseId;
}
|
scala-bones/db-prototyping
|
jdbc/src/it/scala/com/bones/si/jdbc/load/integration/LoadColumnTest.scala
|
package com.bones.si.jdbc.load.integration
import com.bones.si.jdbc.load.{DatabaseQuery, LoadColumn}
import com.bones.si.jdbc.{DataType, Nullable, YesNo}
import org.scalatest.matchers.must.Matchers
class LoadColumnTest extends IntegrationFixture with Matchers {
test("load public columns") { f =>
val query = DatabaseQuery.everything.schemas("public").catalogs("test")
val result = LoadColumn.load(query, f.con)
val a = result.filter(_.tableName == "wrapper_table_a").toArray
val b = result.filter(_.tableName == "wrapper_table_b").toArray
val ar = result.filter(_.tableName == "b").toArray
a(0).catalogName mustEqual None
a(0).schemaName mustEqual Some("public")
a(0).tableName mustEqual "wrapper_table_a"
a(0).name mustEqual "id"
a(0).dataType mustEqual DataType.Integer
a(0).typeName mustEqual "serial"
a(0).columnSize mustEqual 10
a(0).decimalDigits mustEqual Some(0)
a(0).remarks mustEqual None
a(0).columnDefault mustEqual Some("nextval('wrapper_table_a_id_seq'::regclass)")
a(0).characterOctetLength mustEqual 10
a(0).ordinalPosition mustEqual 1
a(0).isNullable mustEqual YesNo.No
a(0).sourceDataType mustEqual Some(0)
a(0).isAutoIncrement mustEqual YesNo.Yes
a(0).isGeneratedColumn mustEqual YesNo.Unknown
a(0).nullable mustEqual Nullable.ColumnNoNulls
a(1).dataType mustEqual DataType.BigInt
a(1).typeName mustEqual "bigserial"
a(2).dataType mustEqual DataType.Bit
a(2).typeName mustEqual "bit"
a(2).columnSize mustEqual 1
a(3).dataType mustEqual DataType.Bit
a(3).typeName mustEqual "bit"
a(3).columnSize mustEqual 5
a(3).isNullable mustEqual YesNo.Yes
a(3).nullable mustEqual Nullable.ColumnNullable
a(4).dataType mustEqual DataType.VarChar
a(4).typeName mustEqual "text"
a(4).columnSize mustEqual 2147483647
a(5).dataType mustEqual DataType.Char
a(5).typeName mustEqual "bpchar"
a(5).columnSize mustEqual 1
a(6).dataType mustEqual DataType.VarChar
a(6).typeName mustEqual "varchar"
a(6).columnSize mustEqual 255
a(7).dataType mustEqual DataType.Date
a(7).typeName mustEqual "date"
a(8).dataType mustEqual DataType.Double
a(8).typeName mustEqual "float8"
a(9).dataType mustEqual DataType.Integer
a(9).typeName mustEqual "int4"
a(10).dataType mustEqual DataType.Numeric
a(10).typeName mustEqual "numeric"
a(11).dataType mustEqual DataType.Real
a(11).typeName mustEqual "float4"
a(12).dataType mustEqual DataType.SmallInt
a(12).typeName mustEqual "int2"
a(13).dataType mustEqual DataType.VarChar
a(13).typeName mustEqual "text"
a(14).dataType mustEqual DataType.Time
a(14).typeName mustEqual "time"
a(15).dataType mustEqual DataType.Time
a(15).typeName mustEqual "timetz"
a(16).dataType mustEqual DataType.Timestamp
a(16).typeName mustEqual "timestamp"
a(17).dataType mustEqual DataType.Timestamp
a(17).typeName mustEqual "timestamptz"
a(18).dataType mustEqual DataType.SqlXml
a(18).typeName mustEqual "xml"
b(0).dataType mustEqual DataType.Integer
b(0).typeName mustEqual "serial"
b(1).dataType mustEqual DataType.Integer
b(1).typeName mustEqual "int4"
}
}
|
wahello/openshift-installer
|
terraform/aws/vendor/github.com/hashicorp/terraform-provider-aws/internal/service/ec2/transit_gateway_route_table_propagation.go
|
package ec2
import (
"fmt"
"log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/aws-sdk-go-base/tfawserr"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
)
func ResourceTransitGatewayRouteTablePropagation() *schema.Resource {
return &schema.Resource{
Create: resourceTransitGatewayRouteTablePropagationCreate,
Read: resourceTransitGatewayRouteTablePropagationRead,
Delete: resourceTransitGatewayRouteTablePropagationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"resource_id": {
Type: schema.TypeString,
Computed: true,
},
"resource_type": {
Type: schema.TypeString,
Computed: true,
},
"transit_gateway_attachment_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.NoZeroValues,
},
"transit_gateway_route_table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.NoZeroValues,
},
},
}
}
func resourceTransitGatewayRouteTablePropagationCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).EC2Conn
transitGatewayAttachmentID := d.Get("transit_gateway_attachment_id").(string)
transitGatewayRouteTableID := d.Get("transit_gateway_route_table_id").(string)
input := &ec2.EnableTransitGatewayRouteTablePropagationInput{
TransitGatewayAttachmentId: aws.String(transitGatewayAttachmentID),
TransitGatewayRouteTableId: aws.String(transitGatewayRouteTableID),
}
_, err := conn.EnableTransitGatewayRouteTablePropagation(input)
if err != nil {
return fmt.Errorf("error enabling EC2 Transit Gateway Route Table (%s) propagation (%s): %s", transitGatewayRouteTableID, transitGatewayAttachmentID, err)
}
d.SetId(fmt.Sprintf("%s_%s", transitGatewayRouteTableID, transitGatewayAttachmentID))
if _, err := WaitTransitGatewayRouteTablePropagationStateEnabled(conn, transitGatewayRouteTableID, transitGatewayAttachmentID); err != nil {
return fmt.Errorf("error waiting for EC2 Transit Gateway Route Table (%s) propagation (%s) to enable: %w", transitGatewayRouteTableID, transitGatewayAttachmentID, err)
}
return resourceTransitGatewayRouteTablePropagationRead(d, meta)
}
func resourceTransitGatewayRouteTablePropagationRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).EC2Conn
transitGatewayRouteTableID, transitGatewayAttachmentID, err := DecodeTransitGatewayRouteTablePropagationID(d.Id())
if err != nil {
return err
}
transitGatewayPropagation, err := FindTransitGatewayRouteTablePropagation(conn, transitGatewayRouteTableID, transitGatewayAttachmentID)
if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, ErrCodeInvalidRouteTableIDNotFound) {
log.Printf("[WARN] EC2 Transit Gateway Route Table (%s) not found, removing from state", transitGatewayRouteTableID)
d.SetId("")
return nil
}
if err != nil {
return fmt.Errorf("error reading EC2 Transit Gateway Route Table (%s) Propagation (%s): %s", transitGatewayRouteTableID, transitGatewayAttachmentID, err)
}
if transitGatewayPropagation == nil {
if d.IsNewResource() {
return fmt.Errorf("error reading EC2 Transit Gateway Route Table (%s) Propagation (%s): not found after creation", transitGatewayRouteTableID, transitGatewayAttachmentID)
}
log.Printf("[WARN] EC2 Transit Gateway Route Table (%s) Propagation (%s) not found, removing from state", transitGatewayRouteTableID, transitGatewayAttachmentID)
d.SetId("")
return nil
}
d.Set("resource_id", transitGatewayPropagation.ResourceId)
d.Set("resource_type", transitGatewayPropagation.ResourceType)
d.Set("transit_gateway_attachment_id", transitGatewayPropagation.TransitGatewayAttachmentId)
d.Set("transit_gateway_route_table_id", transitGatewayRouteTableID)
return nil
}
func resourceTransitGatewayRouteTablePropagationDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).EC2Conn
transitGatewayRouteTableID, transitGatewayAttachmentID, err := DecodeTransitGatewayRouteTablePropagationID(d.Id())
if err != nil {
return err
}
input := &ec2.DisableTransitGatewayRouteTablePropagationInput{
TransitGatewayAttachmentId: aws.String(transitGatewayAttachmentID),
TransitGatewayRouteTableId: aws.String(transitGatewayRouteTableID),
}
log.Printf("[DEBUG] Disabling EC2 Transit Gateway Route Table (%s) Propagation (%s): %s", transitGatewayRouteTableID, transitGatewayAttachmentID, input)
_, err = conn.DisableTransitGatewayRouteTablePropagation(input)
if tfawserr.ErrMessageContains(err, "InvalidRouteTableID.NotFound", "") {
return nil
}
if err != nil {
return fmt.Errorf("error disabling EC2 Transit Gateway Route Table (%s) Propagation (%s): %s", transitGatewayRouteTableID, transitGatewayAttachmentID, err)
}
if _, err := WaitTransitGatewayRouteTablePropagationStateDisabled(conn, transitGatewayRouteTableID, transitGatewayAttachmentID); err != nil {
return fmt.Errorf("error waiting for EC2 Transit Gateway Route Table (%s) propagation (%s) to disable: %w", transitGatewayRouteTableID, transitGatewayAttachmentID, err)
}
return nil
}
|
malu17/alx-higher_level_programming
|
0x08-python-more_classes/test/6-main.py
|
<filename>0x08-python-more_classes/test/6-main.py
#!/usr/bin/python3
Rectangle = __import__('6-rectangle').Rectangle
my_rectangle_1 = Rectangle(2, 4)
my_rectangle_2 = Rectangle(2, 4)
print("{:d} instances of Rectangle".format(Rectangle.number_of_instances))
del my_rectangle_1
print("{:d} instances of Rectangle".format(Rectangle.number_of_instances))
del my_rectangle_2
print("{:d} instances of Rectangle".format(Rectangle.number_of_instances))
|
ginosian/margin-crawler-parser
|
margin-entity-tools/margin-entity-tools-mongo/src/main/java/com/margin/entity/DummyMongoEntity.java
|
<reponame>ginosian/margin-crawler-parser
package com.margin.entity;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
@Document(collection = "dummy")
@Getter
@Setter
public class DummyMongoEntity {
@Id
private String _id;
@Field(value = "name")
private Long name;
}
|
phatblat/macOSPrivateFrameworks
|
PrivateFrameworks/SystemMigrationNetworking/SMNTimeCapsuleBrowser.h
|
<reponame>phatblat/macOSPrivateFrameworks
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "NSObject.h"
#import "NSNetServiceBrowserDelegate.h"
#import "NSNetServiceDelegate.h"
@class NSMutableArray, NSMutableDictionary, NSNetServiceBrowser, NSObject<OS_dispatch_queue>, NSSet, NSString;
@interface SMNTimeCapsuleBrowser : NSObject <NSNetServiceBrowserDelegate, NSNetServiceDelegate>
{
CDUnknownBlockType _capsuleAppearedBlock;
CDUnknownBlockType _remoteDiskAppearedBlock;
CDUnknownBlockType _disappearedBlock;
CDUnknownBlockType _modelIDFoundBlock;
NSNetServiceBrowser *_adiskServiceBrowser;
NSSet *_btmmDomains;
NSMutableDictionary *_serviceToModelIDMap;
NSMutableDictionary *_serviceToTxtRecordMap;
NSMutableDictionary *_serviceAdditionalInfoToHostnameMap;
NSMutableDictionary *_serviceToAdditionalInfoServiceMap;
NSObject<OS_dispatch_queue> *_serviceMapQueue;
NSMutableArray *_resolvingServices;
}
@property(retain) NSMutableArray *resolvingServices; // @synthesize resolvingServices=_resolvingServices;
@property(retain) NSObject<OS_dispatch_queue> *serviceMapQueue; // @synthesize serviceMapQueue=_serviceMapQueue;
@property(retain) NSMutableDictionary *serviceToAdditionalInfoServiceMap; // @synthesize serviceToAdditionalInfoServiceMap=_serviceToAdditionalInfoServiceMap;
@property(retain) NSMutableDictionary *serviceAdditionalInfoToHostnameMap; // @synthesize serviceAdditionalInfoToHostnameMap=_serviceAdditionalInfoToHostnameMap;
@property(retain) NSMutableDictionary *serviceToTxtRecordMap; // @synthesize serviceToTxtRecordMap=_serviceToTxtRecordMap;
@property(retain) NSMutableDictionary *serviceToModelIDMap; // @synthesize serviceToModelIDMap=_serviceToModelIDMap;
@property(retain) NSSet *btmmDomains; // @synthesize btmmDomains=_btmmDomains;
@property(retain) NSNetServiceBrowser *adiskServiceBrowser; // @synthesize adiskServiceBrowser=_adiskServiceBrowser;
@property(copy) CDUnknownBlockType modelIDFoundBlock; // @synthesize modelIDFoundBlock=_modelIDFoundBlock;
@property(copy) CDUnknownBlockType disappearedBlock; // @synthesize disappearedBlock=_disappearedBlock;
@property(copy) CDUnknownBlockType remoteDiskAppearedBlock; // @synthesize remoteDiskAppearedBlock=_remoteDiskAppearedBlock;
@property(copy) CDUnknownBlockType capsuleAppearedBlock; // @synthesize capsuleAppearedBlock=_capsuleAppearedBlock;
- (void).cxx_destruct;
- (void)netService:(id)arg1 didNotResolve:(id)arg2;
- (void)netService:(id)arg1 didUpdateTXTRecordData:(id)arg2;
- (void)netServiceDidResolveAddress:(id)arg1;
- (void)netServiceBrowser:(id)arg1 didRemoveService:(id)arg2 moreComing:(BOOL)arg3;
- (void)netServiceBrowser:(id)arg1 didFindService:(id)arg2 moreComing:(BOOL)arg3;
- (id)_dictionaryFromAirPortDiskData:(id)arg1;
- (void)dealloc;
- (void)stop;
- (void)start;
- (id)initWithCapsuleAppearedBlock:(CDUnknownBlockType)arg1 remoteDiskAppearedBlock:(CDUnknownBlockType)arg2 modelIDFoundBlock:(CDUnknownBlockType)arg3 andDisappearedBlock:(CDUnknownBlockType)arg4;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
|
nkapinos/chorus
|
spec/javascripts/views/multiple_selection_sidebar_menu_spec.js
|
<reponame>nkapinos/chorus
describe("chorus.views.MultipleSelectionSidebar", function() {
var dialogConstructor = chorus.dialogs.ChangePassword;
var method = 'enable';
var actionName = 'add_data';
var methodActionName = 'enable';
beforeEach(function() {
this.modalSpy = stubModals();
this.selectEvent = "arbitrarily:anything";
var actionProvider = function () {
return [
{name: actionName, target: dialogConstructor},
{name: methodActionName, target: method}
];
};
this.view = new chorus.views.MultipleSelectionSidebarMenu({
actionProvider: actionProvider,
selectEvent: this.selectEvent
});
this.view.render();
$('#jasmine_content').append(this.view.el);
});
context("when no models are selected", function() {
it("shows no actions", function() {
expect(this.view.$('.actions')).not.toBeVisible();
});
});
describe("context-aware actions", function () {
var actionProviderSpy;
beforeEach(function () {
this.collection = new chorus.collections.Base([new chorus.models.Base()]);
actionProviderSpy = jasmine.createSpy('actionProvider');
this.view = new chorus.views.MultipleSelectionSidebarMenu({
actionProvider: actionProviderSpy,
selectEvent: this.selectEvent
});
});
it("pass the collection to the action provider for context", function () {
expect(actionProviderSpy).not.toHaveBeenCalledWith(this.view.selectedModels);
chorus.PageEvents.trigger(this.selectEvent, this.collection);
expect(actionProviderSpy).toHaveBeenCalledWith(this.collection);
});
});
context("when two models are selected", function() {
beforeEach(function() {
var twoModels = [new chorus.models.Base(), new chorus.models.Base()];
this.collection = new chorus.collections.Base(twoModels);
spyOn(this.collection, 'invoke');
});
it("is visible", function() {
chorus.PageEvents.trigger(this.selectEvent, this.collection);
expect(this.view.$el).toBeVisible();
});
it("shows the number of models selected", function() {
chorus.PageEvents.trigger(this.selectEvent, this.collection);
expect(this.view.$('label')).toContainTranslation('sidebar.selected', {count: 2});
});
it("renders custom actions", function() {
chorus.PageEvents.trigger(this.selectEvent, this.collection);
expect(this.view.$("li")).toContainTranslation('actions.'+actionName);
});
describe("clicking a method action", function () {
beforeEach(function () {
chorus.PageEvents.trigger(this.selectEvent, this.collection);
});
it("invokes the method on the selectedModels", function () {
expect(this.collection.invoke).not.toHaveBeenCalled();
this.view.$("."+methodActionName).click();
expect(this.collection.invoke).toHaveBeenCalledWith(method);
});
itBehavesLike.aDialogLauncher("."+actionName, dialogConstructor);
});
describe("and then no models are selected", function () {
beforeEach(function () {
this.collection = new chorus.collections.Base([]);
});
it("shows no actions", function() {
chorus.PageEvents.trigger(this.selectEvent, this.collection);
expect(this.view.$el).not.toHaveClass('hidden');
});
});
});
});
|
divshot/deposit
|
lib/injector-comment-regex.js
|
<reponame>divshot/deposit
module.exports = function () {
return /inject:((?:[a-z][a-z]+))/i;
};
|
Dream5366/StS-DuelistMod
|
DuelistMod/src/main/java/duelistmod/powers/duelistPowers/CyberEltaninPower.java
|
<reponame>Dream5366/StS-DuelistMod
package duelistmod.powers.duelistPowers;
import com.badlogic.gdx.graphics.Texture;
import com.megacrit.cardcrawl.core.*;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.localization.PowerStrings;
import duelistmod.DuelistMod;
import duelistmod.abstracts.*;
// Passive no-effect power, just lets Toon Monsters check for playability
public class CyberEltaninPower extends DuelistPower
{
public AbstractCreature source;
public static final String POWER_ID = DuelistMod.makeID("CyberEltaninPower");
private static final PowerStrings powerStrings = CardCrawlGame.languagePack.getPowerStrings(POWER_ID);
public static final String NAME = powerStrings.NAME;
public static final String[] DESCRIPTIONS = powerStrings.DESCRIPTIONS;
public static final String IMG = DuelistMod.makePowerPath("PlaceholderPower.png");
public CyberEltaninPower(int dmgMod, int turns)
{
this.name = NAME;
this.ID = POWER_ID;
this.owner = AbstractDungeon.player;
this.type = PowerType.BUFF;
this.isTurnBased = false;
this.canGoNegative = false;
this.img = new Texture(IMG);
this.source = AbstractDungeon.player;
this.amount = dmgMod;
this.amount2 = turns;
this.updateDescription();
}
@Override
public void atEndOfTurn(boolean isPlayer)
{
if (this.amount2 > 0) { this.amount2--; updateDescription(); }
if (this.amount2 < 1) { DuelistCard.removePower(this, this.owner); }
}
@Override
public void updateDescription()
{
if (this.amount < 0) { this.amount = 0; }
if (this.amount2 == 1) { this.description = DESCRIPTIONS[0] + (this.amount * 10) + DESCRIPTIONS[1] + this.amount2 + DESCRIPTIONS[2]; }
else { this.description = DESCRIPTIONS[0] + (this.amount * 10) + DESCRIPTIONS[1] + this.amount2 + DESCRIPTIONS[3]; }
}
}
|
hyukjae87/robovm-ios-bindings
|
parse/src/org/robovm/bindings/parse/PFQuery.java
|
package org.robovm.bindings.parse;
import org.robovm.apple.foundation.NSArray;
import org.robovm.apple.foundation.NSError;
import org.robovm.apple.foundation.NSObject;
import org.robovm.objc.annotation.Block;
import org.robovm.objc.annotation.Method;
import org.robovm.objc.annotation.NativeClass;
import org.robovm.objc.block.VoidBlock2;
/** A class that defines a query that is used to query for PFObjects. */
@NativeClass
public class PFQuery extends NSObject {
// Returns a PFQuery for a given class.
// @param className The class to query on.
// @return A PFQuery object.
// */
// + (PFQuery *)queryWithClassName:(NSString *)className;
//
// /*!
// Creates a PFQuery with the constraints given by predicate.
//
// The following types of predicates are supported:
// * Simple comparisons such as =, !=, <, >, <=, >=, and BETWEEN with a key and a constant.
// * Containment predicates, such as "x IN {1, 2, 3}".
// * Key-existence predicates, such as "x IN SELF".
// * BEGINSWITH expressions.
// * Compound predicates with AND, OR, and NOT.
// * SubQueries with "key IN %@", subquery.
//
// The following types of predicates are NOT supported:
// * Aggregate operations, such as ANY, SOME, ALL, or NONE.
// * Regular expressions, such as LIKE, MATCHES, CONTAINS, or ENDSWITH.
// * Predicates comparing one key to another.
// * Complex predicates with many ORed clauses.
//
// */
// + (PFQuery *)queryWithClassName:(NSString *)className predicate:(NSPredicate *)predicate;
//
// /*!
// Initializes the query with a class name.
// @param newClassName The class name.
// */
// - (instancetype)initWithClassName:(NSString *)newClassName;
//
// /*!
// The class name to query for
// */
// @property (nonatomic, strong) NSString *parseClassName;
//
// /** @name Adding Basic Constraints */
//
// /*!
// Make the query include PFObjects that have a reference stored at the provided key.
// This has an effect similar to a join. You can use dot notation to specify which fields in
// the included object are also fetch.
// @param key The key to load child PFObjects for.
// */
// - (void)includeKey:(NSString *)key;
//
// /*!
// Make the query restrict the fields of the returned PFObjects to include only the provided keys.
// If this is called multiple times, then all of the keys specified in each of the calls will be included.
// @param keys The keys to include in the result.
// */
// - (void)selectKeys:(NSArray *)keys;
//
// /*!
// Add a constraint that requires a particular key exists.
// @param key The key that should exist.
// */
// - (void)whereKeyExists:(NSString *)key;
//
// /*!
// Add a constraint that requires a key not exist.
// @param key The key that should not exist.
// */
// - (void)whereKeyDoesNotExist:(NSString *)key;
//
/** Add a constraint to the query that requires a particular key's object to be equal to the provided object.
* @param key The key to be constrained.
* @param object The object that must be equalled. */
@Method(selector = "whereKey:equalTo:")
public native void whereKeyEqualsTo (String key, NSObject object);
// /*!
// Add a constraint to the query that requires a particular key's object to be less than the provided object.
// @param key The key to be constrained.
// @param object The object that provides an upper bound.
// */
// - (void)whereKey:(NSString *)key lessThan:(id)object;
//
// /*!
// Add a constraint to the query that requires a particular key's object to be less than or equal to the provided object.
// @param key The key to be constrained.
// @param object The object that must be equalled.
// */
// - (void)whereKey:(NSString *)key lessThanOrEqualTo:(id)object;
//
// /*!
// Add a constraint to the query that requires a particular key's object to be greater than the provided object.
// @param key The key to be constrained.
// @param object The object that must be equalled.
// */
// - (void)whereKey:(NSString *)key greaterThan:(id)object;
//
// /*!
// Add a constraint to the query that requires a particular key's object to be greater than or equal to the provided object.
// @param key The key to be constrained.
// @param object The object that must be equalled.
// */
// - (void)whereKey:(NSString *)key greaterThanOrEqualTo:(id)object;
//
// /*!
// Add a constraint to the query that requires a particular key's object to be not equal to the provided object.
// @param key The key to be constrained.
// @param object The object that must not be equalled.
// */
// - (void)whereKey:(NSString *)key notEqualTo:(id)object;
//
// /*!
// Add a constraint to the query that requires a particular key's object to be contained in the provided array.
// @param key The key to be constrained.
// @param array The possible values for the key's object.
// */
// - (void)whereKey:(NSString *)key containedIn:(NSArray *)array;
//
// /*!
// Add a constraint to the query that requires a particular key's object not be contained in the provided array.
// @param key The key to be constrained.
// @param array The list of values the key's object should not be.
// */
// - (void)whereKey:(NSString *)key notContainedIn:(NSArray *)array;
//
// /*!
// Add a constraint to the query that requires a particular key's array contains every element of the provided array.
// @param key The key to be constrained.
// @param array The array of values to search for.
// */
// - (void)whereKey:(NSString *)key containsAllObjectsInArray:(NSArray *)array;
//
// /** @name Adding Location Constraints */
//
// /*!
// Add a constraint to the query that requires a particular key's coordinates (specified via PFGeoPoint) be near
// a reference point. Distance is calculated based on angular distance on a sphere. Results will be sorted by distance
// from reference point.
// @param key The key to be constrained.
// @param geopoint The reference point. A PFGeoPoint.
// */
// - (void)whereKey:(NSString *)key nearGeoPoint:(PFGeoPoint *)geopoint;
//
// /*!
// Add a constraint to the query that requires a particular key's coordinates (specified via PFGeoPoint) be near
// a reference point and within the maximum distance specified (in miles). Distance is calculated based on
// a spherical coordinate system. Results will be sorted by distance (nearest to farthest) from the reference point.
// @param key The key to be constrained.
// @param geopoint The reference point. A PFGeoPoint.
// @param maxDistance Maximum distance in miles.
// */
// - (void)whereKey:(NSString *)key nearGeoPoint:(PFGeoPoint *)geopoint withinMiles:(double)maxDistance;
//
// /*!
// Add a constraint to the query that requires a particular key's coordinates (specified via PFGeoPoint) be near
// a reference point and within the maximum distance specified (in kilometers). Distance is calculated based on
// a spherical coordinate system. Results will be sorted by distance (nearest to farthest) from the reference point.
// @param key The key to be constrained.
// @param geopoint The reference point. A PFGeoPoint.
// @param maxDistance Maximum distance in kilometers.
// */
// - (void)whereKey:(NSString *)key nearGeoPoint:(PFGeoPoint *)geopoint withinKilometers:(double)maxDistance;
//
// /*!
// Add a constraint to the query that requires a particular key's coordinates (specified via PFGeoPoint) be near
// a reference point and within the maximum distance specified (in radians). Distance is calculated based on
// angular distance on a sphere. Results will be sorted by distance (nearest to farthest) from the reference point.
// @param key The key to be constrained.
// @param geopoint The reference point. A PFGeoPoint.
// @param maxDistance Maximum distance in radians.
// */
// - (void)whereKey:(NSString *)key nearGeoPoint:(PFGeoPoint *)geopoint withinRadians:(double)maxDistance;
//
// /*!
// Add a constraint to the query that requires a particular key's coordinates (specified via PFGeoPoint) be
// contained within a given rectangular geographic bounding box.
// @param key The key to be constrained.
// @param southwest The lower-left inclusive corner of the box.
// @param northeast The upper-right inclusive corner of the box.
// */
// - (void)whereKey:(NSString *)key withinGeoBoxFromSouthwest:(PFGeoPoint *)southwest toNortheast:(PFGeoPoint *)northeast;
//
// /** @name Adding String Constraints */
//
// /*!
// Add a regular expression constraint for finding string values that match the provided regular expression.
// This may be slow for large datasets.
// @param key The key that the string to match is stored in.
// @param regex The regular expression pattern to match.
// */
// - (void)whereKey:(NSString *)key matchesRegex:(NSString *)regex;
//
// /*!
// Add a regular expression constraint for finding string values that match the provided regular expression.
// This may be slow for large datasets.
// @param key The key that the string to match is stored in.
// @param regex The regular expression pattern to match.
// @param modifiers Any of the following supported PCRE modifiers:<br><code>i</code> - Case insensitive search<br><code>m</code> -
// Search across multiple lines of input
// */
// - (void)whereKey:(NSString *)key matchesRegex:(NSString *)regex modifiers:(NSString *)modifiers;
//
// /*!
// Add a constraint for finding string values that contain a provided substring.
// This will be slow for large datasets.
// @param key The key that the string to match is stored in.
// @param substring The substring that the value must contain.
// */
// - (void)whereKey:(NSString *)key containsString:(NSString *)substring;
//
// /*!
// Add a constraint for finding string values that start with a provided prefix.
// This will use smart indexing, so it will be fast for large datasets.
// @param key The key that the string to match is stored in.
// @param prefix The substring that the value must start with.
// */
// - (void)whereKey:(NSString *)key hasPrefix:(NSString *)prefix;
//
// /*!
// Add a constraint for finding string values that end with a provided suffix.
// This will be slow for large datasets.
// @param key The key that the string to match is stored in.
// @param suffix The substring that the value must end with.
// */
// - (void)whereKey:(NSString *)key hasSuffix:(NSString *)suffix;
//
// /** @name Adding Subqueries */
//
// /*!
// Returns a PFQuery that is the or of the passed in PFQuerys.
// @param queries The list of queries to or together.
// @result a PFQuery that is the or of the passed in PFQuerys.
// */
// + (PFQuery *)orQueryWithSubqueries:(NSArray *)queries;
//
// /*!
// Adds a constraint that requires that a key's value matches a value in another key
// in objects returned by a sub query.
// @param key The key that the value is stored
// @param otherKey The key in objects in the returned by the sub query whose value should match
// @param query The query to run.
// */
// - (void)whereKey:(NSString *)key matchesKey:(NSString *)otherKey inQuery:(PFQuery *)query;
//
// /*!
// Adds a constraint that requires that a key's value NOT match a value in another key
// in objects returned by a sub query.
// @param key The key that the value is stored
// @param otherKey The key in objects in the returned by the sub query whose value should match
// @param query The query to run.
// */
// - (void)whereKey:(NSString *)key doesNotMatchKey:(NSString *)otherKey inQuery:(PFQuery *)query;
//
// /*!
// Add a constraint that requires that a key's value matches a PFQuery constraint.
// This only works where the key's values are PFObjects or arrays of PFObjects.
// @param key The key that the value is stored in
// @param query The query the value should match
// */
// - (void)whereKey:(NSString *)key matchesQuery:(PFQuery *)query;
//
// /*!
// Add a constraint that requires that a key's value to not match a PFQuery constraint.
// This only works where the key's values are PFObjects or arrays of PFObjects.
// @param key The key that the value is stored in
// @param query The query the value should not match
// */
// - (void)whereKey:(NSString *)key doesNotMatchQuery:(PFQuery *)query;
//
// #pragma mark -
// #pragma mark Sorting
//
// /** @name Sorting */
//
// /*!
// Sort the results in ascending order with the given key.
// @param key The key to order by.
// */
// - (void)orderByAscending:(NSString *)key;
//
// /*!
// Also sort in ascending order by the given key. The previous keys provided will
// precedence over this key.
// @param key The key to order bye
// */
// - (void)addAscendingOrder:(NSString *)key;
//
// /*!
// Sort the results in descending order with the given key.
// @param key The key to order by.
// */
// - (void)orderByDescending:(NSString *)key;
// /*!
// Also sort in descending order by the given key. The previous keys provided will
// precedence over this key.
// @param key The key to order bye
// */
// - (void)addDescendingOrder:(NSString *)key;
//
// /*!
// Sort the results in descending order with the given descriptor.
// @param sortDescriptor The NSSortDescriptor to order by.
// */
// - (void)orderBySortDescriptor:(NSSortDescriptor *)sortDescriptor;
//
// /*!
// Sort the results in descending order with the given descriptors.
// @param sortDescriptors An NSArray of NSSortDescriptor instances to order by.
// */
// - (void)orderBySortDescriptors:(NSArray *)sortDescriptors;
//
// #pragma mark -
// #pragma mark Get methods
//
// /** @name Getting Objects by ID */
//
// /*!
// Returns a PFObject with a given class and id.
// @param objectClass The class name for the object that is being requested.
// @param objectId The id of the object that is being requested.
// @result The PFObject if found. Returns nil if the object isn't found, or if there was an error.
// */
// + (PFObject *)getObjectOfClass:(NSString *)objectClass
// objectId:(NSString *)objectId;
//
// /*!
// Returns a PFObject with a given class and id and sets an error if necessary.
// @param error Pointer to an NSError that will be set if necessary.
// @result The PFObject if found. Returns nil if the object isn't found, or if there was an error.
// */
// + (PFObject *)getObjectOfClass:(NSString *)objectClass
// objectId:(NSString *)objectId
// error:(NSError **)error;
//
// /*!
// Returns a PFObject with the given id.
//
// This mutates the PFQuery.
//
// @param objectId The id of the object that is being requested.
// @result The PFObject if found. Returns nil if the object isn't found, or if there was an error.
// */
// - (PFObject *)getObjectWithId:(NSString *)objectId;
//
// /*!
// Returns a PFObject with the given id and sets an error if necessary.
//
// This mutates the PFQuery
//
// @param error Pointer to an NSError that will be set if necessary.
// @result The PFObject if found. Returns nil if the object isn't found, or if there was an error.
// */
// - (PFObject *)getObjectWithId:(NSString *)objectId error:(NSError **)error;
//
// /*!
// Gets a PFObject asynchronously and calls the given block with the result.
//
// This mutates the PFQuery
//
// @param block The block to execute. The block should have the following argument signature: (NSArray *object, NSError *error)
// */
// - (void)getObjectInBackgroundWithId:(NSString *)objectId
// block:(PFObjectResultBlock)block;
//
// /*!
// Gets a PFObject asynchronously.
//
// This mutates the PFQuery
//
// @param objectId The id of the object being requested.
// @param target The target for the callback selector.
// @param selector The selector for the callback. It should have the following signature: (void)callbackWithResult:(PFObject
// *)result error:(NSError *)error. result will be nil if error is set and vice versa.
// */
// - (void)getObjectInBackgroundWithId:(NSString *)objectId
// target:(id)target
// selector:(SEL)selector;
//
// #pragma mark -
// #pragma mark Getting Users
//
// /*! @name Getting User Objects */
//
// /*!
// Returns a PFUser with a given id.
// @param objectId The id of the object that is being requested.
// @result The PFUser if found. Returns nil if the object isn't found, or if there was an error.
// */
// + (PFUser *)getUserObjectWithId:(NSString *)objectId;
//
// /*!
// Returns a PFUser with a given class and id and sets an error if necessary.
// @param error Pointer to an NSError that will be set if necessary.
// @result The PFUser if found. Returns nil if the object isn't found, or if there was an error.
// */
// + (PFUser *)getUserObjectWithId:(NSString *)objectId
// error:(NSError **)error;
//
// /*!
// Deprecated. Please use [PFUser query] instead.
// */
// + (PFQuery *)queryForUser PARSE_DEPRECATED("Use [PFUser query] instead.");
//
// #pragma mark -
// #pragma mark Find methods
//
// /** @name Getting all Matches for a Query */
//
// /*!
// Finds objects based on the constructed query.
// @result Returns an array of PFObjects that were found.
// */
// - (NSArray *)findObjects;
//
// /*!
// Finds objects based on the constructed query and sets an error if there was one.
// @param error Pointer to an NSError that will be set if necessary.
// @result Returns an array of PFObjects that were found.
// */
// - (NSArray *)findObjects:(NSError **)error;
//
/** Finds objects asynchronously and calls the given block with the results.
* @param block The block to execute. The block should have the following argument signature:(NSArray *objects, NSError
* *error) */
@Method(selector = "findObjectsInBackgroundWithBlock:")
public native void findObjectsInBackground (@Block VoidBlock2<NSArray<NSObject>, NSError> block);
// /*!
// Finds objects asynchronously and calls the given callback with the results.
// @param target The object to call the selector on.
// @param selector The selector to call. It should have the following signature: (void)callbackWithResult:(NSArray *)result
// error:(NSError *)error. result will be nil if error is set and vice versa.
// */
// - (void)findObjectsInBackgroundWithTarget:(id)target selector:(SEL)selector;
//
// /** @name Getting the First Match in a Query */
//
// /*!
// Gets an object based on the constructed query.
//
// This mutates the PFQuery.
//
// @result Returns a PFObject, or nil if none was found.
// */
// - (PFObject *)getFirstObject;
//
// /*!
// Gets an object based on the constructed query and sets an error if any occurred.
//
// This mutates the PFQuery.
//
// @param error Pointer to an NSError that will be set if necessary.
// @result Returns a PFObject, or nil if none was found.
// */
// - (PFObject *)getFirstObject:(NSError **)error;
//
// /*!
// Gets an object asynchronously and calls the given block with the result.
//
// This mutates the PFQuery.
//
// @param block The block to execute. The block should have the following argument signature:(PFObject *object, NSError *error)
// result will be nil if error is set OR no object was found matching the query. error will be nil if result is set OR if the
// query succeeded, but found no results.
// */
// - (void)getFirstObjectInBackgroundWithBlock:(PFObjectResultBlock)block;
//
// /*!
// Gets an object asynchronously and calls the given callback with the results.
//
// This mutates the PFQuery.
//
// @param target The object to call the selector on.
// @param selector The selector to call. It should have the following signature: (void)callbackWithResult:(PFObject *)result
// error:(NSError *)error. result will be nil if error is set OR no object was found matching the query. error will be nil if
// result is set OR if the query succeeded, but found no results.
// */
// - (void)getFirstObjectInBackgroundWithTarget:(id)target selector:(SEL)selector;
//
// #pragma mark -
// #pragma mark Count methods
//
// /** @name Counting the Matches in a Query */
//
// /*!
// Counts objects based on the constructed query.
// @result Returns the number of PFObjects that match the query, or -1 if there is an error.
// */
// - (NSInteger)countObjects;
//
// /*!
// Counts objects based on the constructed query and sets an error if there was one.
// @param error Pointer to an NSError that will be set if necessary.
// @result Returns the number of PFObjects that match the query, or -1 if there is an error.
// */
// - (NSInteger)countObjects:(NSError **)error;
//
// /*!
// Counts objects asynchronously and calls the given block with the counts.
// @param block The block to execute. The block should have the following argument signature:
// (int count, NSError *error)
// */
// - (void)countObjectsInBackgroundWithBlock:(PFIntegerResultBlock)block;
//
// /*!
// Counts objects asynchronously and calls the given callback with the count.
// @param target The object to call the selector on.
// @param selector The selector to call. It should have the following signature: (void)callbackWithResult:(NSNumber *)result
// error:(NSError *)error. */
// - (void)countObjectsInBackgroundWithTarget:(id)target selector:(SEL)selector;
//
// #pragma mark -
// #pragma mark Cancel methods
//
// /** @name Cancelling a Query */
//
// /*!
// Cancels the current network request (if any). Ensures that callbacks won't be called.
// */
// - (void)cancel;
//
// #pragma mark -
// #pragma mark Pagination properties
//
// /** @name Paginating Results */
// /*!
// A limit on the number of objects to return. The default limit is 100, with a
// maximum of 1000 results being returned at a time.
//
// Note: If you are calling findObject with limit=1, you may find it easier to use getFirst instead.
// */
// @property (nonatomic, assign) NSInteger limit;
//
// /*!
// The number of objects to skip before returning any.
// */
// @property (nonatomic, assign) NSInteger skip;
//
// #pragma mark -
// #pragma mark Cache methods
//
// /** @name Controlling Caching Behavior */
//
// /*!
// The cache policy to use for requests.
// */
// @property (assign, readwrite) PFCachePolicy cachePolicy;
//
// /* !
// The age after which a cached value will be ignored
// */
// @property (assign, readwrite) NSTimeInterval maxCacheAge;
//
// /*!
// Returns whether there is a cached result for this query.
// @result YES if there is a cached result for this query, and NO otherwise.
// */
// - (BOOL)hasCachedResult;
//
// /*!
// Clears the cached result for this query. If there is no cached result, this is a noop.
// */
// - (void)clearCachedResult;
//
// /*!
// Clears the cached results for all queries.
// */
// + (void)clearAllCachedResults;
//
// #pragma mark - Advanced Settings
//
// /** @name Advanced Settings */
//
// /*!
// Whether or not performance tracing should be done on the query.
// This should not be set in most cases.
// */
// @property (nonatomic, assign) BOOL trace;
//
}
|
TheSench/solr-streams-dsl
|
src/main/java/com/github/thesench/solr/dsl/stream/expr/evaluators/Sqrt.java
|
package com.github.thesench.solr.dsl.stream.expr.evaluators;
import com.github.thesench.solr.dsl.stream.expr.params.Field;
public class Sqrt {
private Sqrt() {}
/**
* @see <a href="https://solr.apache.org/guide/8_10/stream-evaluator-reference.html#sqrt">Stream Evaluator Reference: sqrt</a>
* @param fieldName
* @return
*/
public static NumberEvaluator sqrt(String fieldName) {
return (NumberEvaluator) new NumberEvaluator("sqrt").withParameter(fieldName);
}
/**
* @see <a href="https://solr.apache.org/guide/8_10/stream-evaluator-reference.html#sqrt">Stream Evaluator Reference: sqrt</a>
* @param field
* @return
*/
public static NumberEvaluator sqrt(Field field) {
return (NumberEvaluator) new NumberEvaluator("sqrt").withParameter(field.toString());
}
/**
* @see <a href="https://solr.apache.org/guide/8_10/stream-evaluator-reference.html#sqrt">Stream Evaluator Reference: sqrt</a>
* @param rawNumber
* @return
*/
public static NumberEvaluator sqrt(int rawNumber) {
return (NumberEvaluator) new NumberEvaluator("sqrt").withParameter(Integer.toString(rawNumber));
}
/**
* @see <a href="https://solr.apache.org/guide/8_10/stream-evaluator-reference.html#sqrt">Stream Evaluator Reference: sqrt</a>
* @param rawNumber
* @return
*/
public static NumberEvaluator sqrt(long rawNumber) {
return (NumberEvaluator) new NumberEvaluator("sqrt").withParameter(Long.toString(rawNumber));
}
/**
* @see <a href="https://solr.apache.org/guide/8_10/stream-evaluator-reference.html#sqrt">Stream Evaluator Reference: sqrt</a>
* @param rawNumber
* @return
*/
public static NumberEvaluator sqrt(double rawNumber) {
return (NumberEvaluator) new NumberEvaluator("sqrt").withParameter(Double.toString(rawNumber));
}
/**
* @see <a href="https://solr.apache.org/guide/8_10/stream-evaluator-reference.html#sqrt">Stream Evaluator Reference: sqrt</a>
* @param rawNumber
* @return
*/
public static NumberEvaluator sqrt(float rawNumber) {
return (NumberEvaluator) new NumberEvaluator("sqrt").withParameter(Float.toString(rawNumber));
}
/**
* @see <a href="https://solr.apache.org/guide/8_10/stream-evaluator-reference.html#sqrt">Stream Evaluator Reference: sqrt</a>
* @param numberEvaluator
* @return
*/
public static NumberEvaluator sqrt(NumberEvaluator numberEvaluator) {
return (NumberEvaluator) new NumberEvaluator("sqrt").withParameter(numberEvaluator);
}
}
|
sonald/sos
|
user/libc/stdio.h
|
<gh_stars>10-100
#ifndef _SOS_STDIO_H
#define _SOS_STDIO_H
#include <types.h>
#include <stdarg.h>
int vprintf(const char* fmt, va_list args);
int printf(const char* fmt, ...);
#endif
|
didi/ALITA
|
alita-api/src/main/java/com/alita/service/impl/AlitaPageServiceImpl.java
|
<reponame>didi/ALITA<filename>alita-api/src/main/java/com/alita/service/impl/AlitaPageServiceImpl.java
package com.alita.service.impl;
import com.alita.common.bo.AlitaPageBO;
import com.alita.common.po.AlitaPage;
import com.alita.mysql.mapper.AlitaPageMapper;
import com.alita.service.AlitaPageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Preconditions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.stream.Collectors;
/**
* 页面表 服务实现类
*
* @author Lydia
* @since 2020-01-05
*/
@Service
public class AlitaPageServiceImpl implements AlitaPageService {
@Autowired
private AlitaPageMapper alitaPageMapper;
@Override
public AlitaPageBO getById(Long id) {
AlitaPage alitaPage = alitaPageMapper.selectById(id);
if (alitaPage != null && alitaPage.getStatus() == 1) {
AlitaPageBO alitaPageBO = AlitaPageBO.builder().build();
BeanUtils.copyProperties(alitaPage, alitaPageBO);
return alitaPageBO;
}
return null;
}
@Override
public Long add(AlitaPageBO alitaPageBO) {
AlitaPage alitaPage = new AlitaPage();
BeanUtils.copyProperties(alitaPageBO, alitaPage);
alitaPageMapper.insert(alitaPage);
return alitaPage.getId();
}
@Override
public Boolean update(AlitaPageBO alitaPageBO) {
AlitaPage alitaPage = new AlitaPage();
BeanUtils.copyProperties(alitaPageBO, alitaPage);
return alitaPageMapper.updateById(alitaPage) > 0;
}
@Override
public Boolean delete(Long id) {
AlitaPage alitaPage = alitaPageMapper.selectById(id);
Preconditions.checkArgument(alitaPage != null, "页面不存在");
alitaPage.setStatus(0);
alitaPageMapper.updateById(alitaPage);
return alitaPageMapper.updateById(alitaPage) > 0;
}
@Override
public List<AlitaPageBO> list(AlitaPageBO alitaPageBO) {
AlitaPage alitaPage = new AlitaPage();
BeanUtils.copyProperties(alitaPageBO, alitaPage);
QueryWrapper<AlitaPage> queryWrapper = new QueryWrapper<>();
queryWrapper.setEntity(alitaPage);
queryWrapper.lambda().eq(AlitaPage::getStatus, 1);
List<AlitaPage> alitaPageList = alitaPageMapper.selectList(queryWrapper);
if (!CollectionUtils.isEmpty(alitaPageList)) {
return alitaPageList.stream().map(po->{
AlitaPageBO bo = new AlitaPageBO();
BeanUtils.copyProperties(po, bo);
return bo;
}).collect(Collectors.toList());
}
return null;
}
}
|
JosephClay/StormJS
|
src/Extensions.js
|
<reponame>JosephClay/StormJS<gh_stars>1-10
// Extension ########################################################################
Events.extend = Cache.extend = AjaxCall.extend = DataContext.extend = Model.extend = Collection.extend = Comparator.extend = View.extend = Module.extend = Extend;
|
pleuvoir/sms-gateway
|
sms-channel-service/src/main/java/io/github/pleuvoir/message/dao/biz/MsgChannelDao.java
|
<gh_stars>1-10
package io.github.pleuvoir.message.dao.biz;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import io.github.pleuvoir.message.model.po.PubMsgChannelPO;
public interface MsgChannelDao extends BaseMapper<PubMsgChannelPO> {
}
|
gaudeon/games-jams-and-phasers-presentation
|
src/jam-01/js/states/JSONLevelState.js
|
var FruitNinja = FruitNinja || {};
FruitNinja.JSONLevelState = function () {
"use strict";
Phaser.State.call(this);
this.prefab_classes = {
};
};
FruitNinja.JSONLevelState.prototype = Object.create(Phaser.State.prototype);
FruitNinja.JSONLevelState.prototype.constructor = FruitNinja.JSONLevelState;
FruitNinja.JSONLevelState.prototype.init = function (level_data) {
"use strict";
this.level_data = level_data;
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = true;
};
FruitNinja.JSONLevelState.prototype.create = function () {
"use strict";
var group_name, prefab_name;
// create groups
this.groups = {};
this.level_data.groups.forEach(function (group_name) {
this.groups[group_name] = this.game.add.group();
}, this);
// create prefabs
this.prefabs = {};
for (prefab_name in this.level_data.prefabs) {
if (this.level_data.prefabs.hasOwnProperty(prefab_name)) {
// create prefab
this.create_prefab(prefab_name, this.level_data.prefabs[prefab_name]);
}
}
};
FruitNinja.JSONLevelState.prototype.create_prefab = function (prefab_name, prefab_data) {
"use strict";
var prefab_position, prefab;
// create object according to its type
if (this.prefab_classes.hasOwnProperty(prefab_data.type)) {
if (prefab_data.position.x > 0 && prefab_data.position.x <= 1) {
// position as percentage
prefab_position = new Phaser.Point(prefab_data.position.x * this.game.world.width,
prefab_data.position.y * this.game.world.height);
} else {
// position as absolute number
prefab_position = prefab_data.position;
}
prefab = new this.prefab_classes[prefab_data.type](this, prefab_name, prefab_position, prefab_data.properties);
}
};
|
Prajna/mach
|
kernel/chips/audio_defs.h
|
<reponame>Prajna/mach
/*
* Mach Operating System
* Copyright (c) 1993 Carnegie Mellon University
* All Rights Reserved.
*
* Permission to use, copy, modify and distribute this software and its
* documentation is hereby granted, provided that both the copyright
* notice and this permission notice appear in all copies of the
* software, derivative works or modified versions, and any portions
* thereof, and that both notices appear in supporting documentation.
*
* CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
* CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
* ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
*
* Carnegie Mellon requests users of this software to return to
*
* Software Distribution Coordinator or <EMAIL>
* School of Computer Science
* Carnegie Mellon University
* Pittsburgh PA 15213-3890
*
* any improvements or extensions that they make and grant Carnegie Mellon
* the rights to redistribute these changes.
*/
/*
* HISTORY
* $Log: audio_defs.h,v $
* Revision 2.2 93/03/18 10:37:04 mrt
* Started, from Berkeley's driver.
* [93/03/09 af]
*
/*-
* Copyright (c) 1991, 1992 The Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the Computer Systems
* Engineering Group at Lawrence Berkeley Laboratory.
* 4. The name of the Laboratory may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Header: audio_defs.h,v 2.2 93/03/18 10:37:04 mrt Exp $ (LBL)
*/
#define AUCB_SIZE 4096
#define AUCB_MOD(k) ((k) & (AUCB_SIZE - 1))
#define AUCB_INIT(cb) ((cb)->cb_head = (cb)->cb_tail = (cb)->cb_drops = \
(cb)->cb_pdrops = 0)
#define AUCB_EMPTY(cb) ((cb)->cb_head == (cb)->cb_tail)
#define AUCB_FULL(cb) (AUCB_MOD((cb)->cb_tail + 1) == (cb)->cb_head)
#define AUCB_LEN(cb) (AUCB_MOD((cb)->cb_tail - (cb)->cb_head))
#define MAXBLKSIZE (AUCB_SIZE / 2)
#define DEFBLKSIZE 128
#ifndef LOCORE
/*
* Our own circular buffers, used if not doing DMA.
* [af: with some work we could use the circbuf.c code instead]
*/
typedef struct au_cb {
int cb_head; /* queue head */
int cb_tail; /* queue tail */
int cb_thresh; /* threshold for wakeup */
unsigned int cb_waking; /* needs wakeup at softint level */
unsigned int cb_pause; /* io paused */
unsigned int cb_drops; /* missed samples from over/underrun */
unsigned int cb_pdrops; /* sun compat -- paused samples */
unsigned char cb_data[AUCB_SIZE]; /* data buffer */
} au_cb_t;
/*
* Handle on a bi-directional stream of samples
*/
typedef struct au_io {
unsigned int au_stamp; /* time stamp */
int au_lowat; /* xmit low water mark (for wakeup) */
int au_hiwat; /* xmit high water mark (for wakeup) */
int au_blksize; /* recv block (chunk) size */
int au_backlog; /* # samples of xmit backlog to gen. */
struct au_cb au_rb; /* read (recv) buffer */
struct au_cb au_wb; /* write (xmit) buffer */
} au_io_t;
/*
* Interface to specific chips
*/
typedef struct {
void (*init)();
void (*close)();
void (*setport)();
int (*getport)();
void (*setgains)();
void (*getgains)();
io_return_t (*setstate)();
io_return_t (*getstate)();
} audio_switch_t;
/*
* Callbacks into audio module, and interface to kernel
*/
void audio_attach( void *, audio_switch_t *, void **);
boolean_t audio_hwintr( void *, unsigned int, unsigned int *);
extern io_return_t audio_open( int, int, io_req_t );
extern io_return_t audio_close( int );
extern io_return_t audio_read( int, io_req_t );
extern io_return_t audio_write( int, io_req_t );
extern io_return_t audio_get_status( int, dev_flavor_t, dev_status_t, natural_t *);
extern io_return_t audio_set_status( int, dev_flavor_t, dev_status_t, natural_t);
#endif
|
xexceed/rexOS
|
include/common/graphicscontext.h
|
<gh_stars>1-10
#ifndef __REXOS__COMMON__GRAPHICSCONTEXT_H
#define __REXOS__COMMON__GRAPHICSCONTEXT_H
#include <drivers/vga.h>
namespace rexos {
namespace common {
typedef drivers::VideoGraphicsArray GraphicsContext;
}
}
#endif
|
LeastAuthority/txkube
|
src/txkube/testing/test/__init__.py
|
<reponame>LeastAuthority/txkube<filename>src/txkube/testing/test/__init__.py
# Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
Tests for ``txkube.testing``.
"""
|
cfogg/python-client
|
tests/models/test_token.py
|
"""Split model tests module."""
from splitio.models import token
from splitio.models.grammar.condition import Condition
class TokenTests(object):
"""Token model tests."""
raw_false = {'pushEnabled': False}
def test_from_raw_false(self):
"""Test token model parsing."""
parsed = token.from_raw(self.raw_false)
assert parsed == None
raw_empty = {
'pushEnabled': True,
'token': '',
}
def test_from_raw_empty(self):
"""Test token model parsing."""
parsed = token.from_raw(self.raw_empty)
assert parsed == None
raw_ok = {
'pushEnabled': True,
'token': '<KEY>',
}
def test_from_raw(self):
"""Test token model parsing."""
parsed = token.from_raw(self.raw_ok)
assert isinstance(parsed, token.Token)
assert parsed.push_enabled == True
assert parsed.iat == 1602084527
assert parsed.exp == 1602088127
assert parsed.channels['NzM2MDI5Mzc0_MTgyNTg1MTgwNg==_segments'] == ['subscribe']
assert parsed.channels['NzM2MDI5Mzc0_MTgyNTg1MTgwNg==_splits'] == ['subscribe']
assert parsed.channels['control_pri'] == ['subscribe', 'channel-metadata:publishers']
assert parsed.channels['control_sec'] == ['subscribe', 'channel-metadata:publishers']
|
johan--/cartodb
|
lib/assets/test/spec/cartodb/common/url_shortener.spec.js
|
var $ = require('jquery');
var UrlShortener = require('../../../../javascripts/cartodb/common/url_shortener');
describe('common/url_shortener', function() {
beforeEach(function() {
cdb.config.set('bitly_key', 'hello');
cdb.config.set('bitly_login', 'hello');
this.urlShortener = new UrlShortener();
this.successSpy = jasmine.createSpy('success');
this.errorSpy = jasmine.createSpy('error');
});
describe('.fetch', function() {
describe('when given URL has already been requested', function() {
beforeEach(function() {
spyOn(this.urlShortener.localStorage, 'search').and.returnValue('http://cdb.io/1DD3v0H');
this.urlShortener.fetch('original url', { success: this.successSpy });
});
it('should call success with cached URL', function() {
expect(this.successSpy).toHaveBeenCalledWith('http://cdb.io/1DD3v0H');
});
});
describe('when given has not yet been shortened', function() {
beforeEach(function() {
spyOn($, 'ajax');
this.urlShortener.fetch('http://cartodb.com/user/user/viz/a5209d8e-ecb8-11e4-9caf-080027880ca6/public_map', {
success: this.successSpy,
error: this.errorSpy
});
this.args = $.ajax.calls.argsFor(0)[0];
});
it('should have called bitly to shorten the URL', function() {
expect(this.args.url).toContain('bitly.com');
expect(this.args.type).toEqual('GET');
expect(this.args.async).toEqual(false);
expect(this.args.dataType).toEqual('jsonp');
expect(this.args.url).toContain('http%3A%2F%2Fcartodb.com%2Fuser%2Fuser%2Fviz%2Fa5209d8e-ecb8-11e4-9caf-080027880ca6%2Fpublic_map');
});
describe('when shortening succeeds', function() {
beforeEach(function() {
spyOn(this.urlShortener.localStorage, 'add');
this.res = {
status_code: 200,
data: {
long_url: 'http://cartodb.com/user/user/viz/a5209d8e-ecb8-11e4-9caf-080027880ca6/public_map',
url: 'http://cdb.io/1DD3v0H',
hash: '1DD3v0H',
global_hash: '1DD3v0I',
new_hash: 0
}
};
this.args.success(this.res);
});
it('should persist the URL', function() {
expect(this.urlShortener.localStorage.add).toHaveBeenCalledWith({
'http://cartodb.com/user/user/viz/a5209d8e-ecb8-11e4-9caf-080027880ca6/public_map': 'http://cdb.io/1DD3v0H'
});
});
it('should call the success callback', function() {
expect(this.successSpy).toHaveBeenCalledWith('http://cdb.io/1DD3v0H');
});
it('should call error callback with original URL if there is no url', function() {
this.args.success({});
expect(this.errorSpy).toHaveBeenCalledWith('http://cartodb.com/user/user/viz/a5209d8e-ecb8-11e4-9caf-080027880ca6/public_map');
});
});
describe('when shortening fails', function() {
beforeEach(function() {
this.args.error(new Error('something failed'));
});
it('should call error callback with original URL', function() {
expect(this.errorSpy).toHaveBeenCalledWith('http://cartodb.com/user/user/viz/a5209d8e-ecb8-11e4-9caf-080027880ca6/public_map');
});
});
});
});
afterEach(function() {
cdb.config.unset('bitly_login');
cdb.config.unset('bitly_key');
this.urlShortener.localStorage.destroy();
});
});
|
ooibc88/Hyperledger-Fabric-
|
ustore_home/include/proto/config.pb.h
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: config.proto
#ifndef PROTOBUF_INCLUDED_config_2eproto
#define PROTOBUF_INCLUDED_config_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 3006001
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
#define PROTOBUF_INTERNAL_EXPORT_protobuf_config_2eproto
namespace protobuf_config_2eproto {
// Internal implementation detail -- do not use these members.
struct TableStruct {
static const ::google::protobuf::internal::ParseTableField entries[];
static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
static const ::google::protobuf::internal::ParseTable schema[1];
static const ::google::protobuf::internal::FieldMetadata field_metadata[];
static const ::google::protobuf::internal::SerializationTable serialization_table[];
static const ::google::protobuf::uint32 offsets[];
};
void AddDescriptors();
} // namespace protobuf_config_2eproto
namespace ustore {
class Config;
class ConfigDefaultTypeInternal;
extern ConfigDefaultTypeInternal _Config_default_instance_;
} // namespace ustore
namespace google {
namespace protobuf {
template<> ::ustore::Config* Arena::CreateMaybeMessage<::ustore::Config>(Arena*);
} // namespace protobuf
} // namespace google
namespace ustore {
// ===================================================================
class Config : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:ustore.Config) */ {
public:
Config();
virtual ~Config();
Config(const Config& from);
inline Config& operator=(const Config& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
Config(Config&& from) noexcept
: Config() {
*this = ::std::move(from);
}
inline Config& operator=(Config&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const ::google::protobuf::Descriptor* descriptor();
static const Config& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Config* internal_default_instance() {
return reinterpret_cast<const Config*>(
&_Config_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
void Swap(Config* other);
friend void swap(Config& a, Config& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline Config* New() const final {
return CreateMaybeMessage<Config>(NULL);
}
Config* New(::google::protobuf::Arena* arena) const final {
return CreateMaybeMessage<Config>(arena);
}
void CopyFrom(const ::google::protobuf::Message& from) final;
void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Config& from);
void MergeFrom(const Config& from);
void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(Config* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// optional string data_dir = 1 [default = "ustore_data"];
bool has_data_dir() const;
void clear_data_dir();
static const int kDataDirFieldNumber = 1;
const ::std::string& data_dir() const;
void set_data_dir(const ::std::string& value);
#if LANG_CXX11
void set_data_dir(::std::string&& value);
#endif
void set_data_dir(const char* value);
void set_data_dir(const char* value, size_t size);
::std::string* mutable_data_dir();
::std::string* release_data_dir();
void set_allocated_data_dir(::std::string* data_dir);
// optional string data_file_pattern = 2 [default = "ustore"];
bool has_data_file_pattern() const;
void clear_data_file_pattern();
static const int kDataFilePatternFieldNumber = 2;
const ::std::string& data_file_pattern() const;
void set_data_file_pattern(const ::std::string& value);
#if LANG_CXX11
void set_data_file_pattern(::std::string&& value);
#endif
void set_data_file_pattern(const char* value);
void set_data_file_pattern(const char* value, size_t size);
::std::string* mutable_data_file_pattern();
::std::string* release_data_file_pattern();
void set_allocated_data_file_pattern(::std::string* data_file_pattern);
// optional string access_log_dir = 3 [default = ""];
bool has_access_log_dir() const;
void clear_access_log_dir();
static const int kAccessLogDirFieldNumber = 3;
const ::std::string& access_log_dir() const;
void set_access_log_dir(const ::std::string& value);
#if LANG_CXX11
void set_access_log_dir(::std::string&& value);
#endif
void set_access_log_dir(const char* value);
void set_access_log_dir(const char* value, size_t size);
::std::string* mutable_access_log_dir();
::std::string* release_access_log_dir();
void set_allocated_access_log_dir(::std::string* access_log_dir);
// optional string worker_file = 10 [default = "conf/workers.lst"];
bool has_worker_file() const;
void clear_worker_file();
static const int kWorkerFileFieldNumber = 10;
const ::std::string& worker_file() const;
void set_worker_file(const ::std::string& value);
#if LANG_CXX11
void set_worker_file(::std::string&& value);
#endif
void set_worker_file(const char* value);
void set_worker_file(const char* value, size_t size);
::std::string* mutable_worker_file();
::std::string* release_worker_file();
void set_allocated_worker_file(::std::string* worker_file);
// optional bool enable_dist_store = 5 [default = false];
bool has_enable_dist_store() const;
void clear_enable_dist_store();
static const int kEnableDistStoreFieldNumber = 5;
bool enable_dist_store() const;
void set_enable_dist_store(bool value);
// optional int32 max_segments = 4 [default = 64];
bool has_max_segments() const;
void clear_max_segments();
static const int kMaxSegmentsFieldNumber = 4;
::google::protobuf::int32 max_segments() const;
void set_max_segments(::google::protobuf::int32 value);
// optional bool get_chunk_bypass_worker = 6 [default = true];
bool has_get_chunk_bypass_worker() const;
void clear_get_chunk_bypass_worker();
static const int kGetChunkBypassWorkerFieldNumber = 6;
bool get_chunk_bypass_worker() const;
void set_get_chunk_bypass_worker(bool value);
// optional int32 recv_threads = 21 [default = 2];
bool has_recv_threads() const;
void clear_recv_threads();
static const int kRecvThreadsFieldNumber = 21;
::google::protobuf::int32 recv_threads() const;
void set_recv_threads(::google::protobuf::int32 value);
// optional int32 http_port = 50 [default = 60000];
bool has_http_port() const;
void clear_http_port();
static const int kHttpPortFieldNumber = 50;
::google::protobuf::int32 http_port() const;
void set_http_port(::google::protobuf::int32 value);
// @@protoc_insertion_point(class_scope:ustore.Config)
private:
void set_has_data_dir();
void clear_has_data_dir();
void set_has_data_file_pattern();
void clear_has_data_file_pattern();
void set_has_access_log_dir();
void clear_has_access_log_dir();
void set_has_max_segments();
void clear_has_max_segments();
void set_has_enable_dist_store();
void clear_has_enable_dist_store();
void set_has_get_chunk_bypass_worker();
void clear_has_get_chunk_bypass_worker();
void set_has_worker_file();
void clear_has_worker_file();
void set_has_recv_threads();
void clear_has_recv_threads();
void set_has_http_port();
void clear_has_http_port();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
public:
static ::google::protobuf::internal::ExplicitlyConstructed< ::std::string> _i_give_permission_to_break_this_code_default_data_dir_;
private:
::google::protobuf::internal::ArenaStringPtr data_dir_;
public:
static ::google::protobuf::internal::ExplicitlyConstructed< ::std::string> _i_give_permission_to_break_this_code_default_data_file_pattern_;
private:
::google::protobuf::internal::ArenaStringPtr data_file_pattern_;
::google::protobuf::internal::ArenaStringPtr access_log_dir_;
public:
static ::google::protobuf::internal::ExplicitlyConstructed< ::std::string> _i_give_permission_to_break_this_code_default_worker_file_;
private:
::google::protobuf::internal::ArenaStringPtr worker_file_;
bool enable_dist_store_;
::google::protobuf::int32 max_segments_;
bool get_chunk_bypass_worker_;
::google::protobuf::int32 recv_threads_;
::google::protobuf::int32 http_port_;
friend struct ::protobuf_config_2eproto::TableStruct;
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// Config
// optional string data_dir = 1 [default = "ustore_data"];
inline bool Config::has_data_dir() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void Config::set_has_data_dir() {
_has_bits_[0] |= 0x00000001u;
}
inline void Config::clear_has_data_dir() {
_has_bits_[0] &= ~0x00000001u;
}
inline void Config::clear_data_dir() {
data_dir_.ClearToDefaultNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_data_dir_.get());
clear_has_data_dir();
}
inline const ::std::string& Config::data_dir() const {
// @@protoc_insertion_point(field_get:ustore.Config.data_dir)
return data_dir_.GetNoArena();
}
inline void Config::set_data_dir(const ::std::string& value) {
set_has_data_dir();
data_dir_.SetNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_data_dir_.get(), value);
// @@protoc_insertion_point(field_set:ustore.Config.data_dir)
}
#if LANG_CXX11
inline void Config::set_data_dir(::std::string&& value) {
set_has_data_dir();
data_dir_.SetNoArena(
&::ustore::Config::_i_give_permission_to_break_this_code_default_data_dir_.get(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:ustore.Config.data_dir)
}
#endif
inline void Config::set_data_dir(const char* value) {
GOOGLE_DCHECK(value != NULL);
set_has_data_dir();
data_dir_.SetNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_data_dir_.get(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:ustore.Config.data_dir)
}
inline void Config::set_data_dir(const char* value, size_t size) {
set_has_data_dir();
data_dir_.SetNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_data_dir_.get(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:ustore.Config.data_dir)
}
inline ::std::string* Config::mutable_data_dir() {
set_has_data_dir();
// @@protoc_insertion_point(field_mutable:ustore.Config.data_dir)
return data_dir_.MutableNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_data_dir_.get());
}
inline ::std::string* Config::release_data_dir() {
// @@protoc_insertion_point(field_release:ustore.Config.data_dir)
if (!has_data_dir()) {
return NULL;
}
clear_has_data_dir();
return data_dir_.ReleaseNonDefaultNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_data_dir_.get());
}
inline void Config::set_allocated_data_dir(::std::string* data_dir) {
if (data_dir != NULL) {
set_has_data_dir();
} else {
clear_has_data_dir();
}
data_dir_.SetAllocatedNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_data_dir_.get(), data_dir);
// @@protoc_insertion_point(field_set_allocated:ustore.Config.data_dir)
}
// optional string data_file_pattern = 2 [default = "ustore"];
inline bool Config::has_data_file_pattern() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void Config::set_has_data_file_pattern() {
_has_bits_[0] |= 0x00000002u;
}
inline void Config::clear_has_data_file_pattern() {
_has_bits_[0] &= ~0x00000002u;
}
inline void Config::clear_data_file_pattern() {
data_file_pattern_.ClearToDefaultNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_data_file_pattern_.get());
clear_has_data_file_pattern();
}
inline const ::std::string& Config::data_file_pattern() const {
// @@protoc_insertion_point(field_get:ustore.Config.data_file_pattern)
return data_file_pattern_.GetNoArena();
}
inline void Config::set_data_file_pattern(const ::std::string& value) {
set_has_data_file_pattern();
data_file_pattern_.SetNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_data_file_pattern_.get(), value);
// @@protoc_insertion_point(field_set:ustore.Config.data_file_pattern)
}
#if LANG_CXX11
inline void Config::set_data_file_pattern(::std::string&& value) {
set_has_data_file_pattern();
data_file_pattern_.SetNoArena(
&::ustore::Config::_i_give_permission_to_break_this_code_default_data_file_pattern_.get(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:ustore.Config.data_file_pattern)
}
#endif
inline void Config::set_data_file_pattern(const char* value) {
GOOGLE_DCHECK(value != NULL);
set_has_data_file_pattern();
data_file_pattern_.SetNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_data_file_pattern_.get(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:ustore.Config.data_file_pattern)
}
inline void Config::set_data_file_pattern(const char* value, size_t size) {
set_has_data_file_pattern();
data_file_pattern_.SetNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_data_file_pattern_.get(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:ustore.Config.data_file_pattern)
}
inline ::std::string* Config::mutable_data_file_pattern() {
set_has_data_file_pattern();
// @@protoc_insertion_point(field_mutable:ustore.Config.data_file_pattern)
return data_file_pattern_.MutableNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_data_file_pattern_.get());
}
inline ::std::string* Config::release_data_file_pattern() {
// @@protoc_insertion_point(field_release:ustore.Config.data_file_pattern)
if (!has_data_file_pattern()) {
return NULL;
}
clear_has_data_file_pattern();
return data_file_pattern_.ReleaseNonDefaultNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_data_file_pattern_.get());
}
inline void Config::set_allocated_data_file_pattern(::std::string* data_file_pattern) {
if (data_file_pattern != NULL) {
set_has_data_file_pattern();
} else {
clear_has_data_file_pattern();
}
data_file_pattern_.SetAllocatedNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_data_file_pattern_.get(), data_file_pattern);
// @@protoc_insertion_point(field_set_allocated:ustore.Config.data_file_pattern)
}
// optional string access_log_dir = 3 [default = ""];
inline bool Config::has_access_log_dir() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void Config::set_has_access_log_dir() {
_has_bits_[0] |= 0x00000004u;
}
inline void Config::clear_has_access_log_dir() {
_has_bits_[0] &= ~0x00000004u;
}
inline void Config::clear_access_log_dir() {
access_log_dir_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_access_log_dir();
}
inline const ::std::string& Config::access_log_dir() const {
// @@protoc_insertion_point(field_get:ustore.Config.access_log_dir)
return access_log_dir_.GetNoArena();
}
inline void Config::set_access_log_dir(const ::std::string& value) {
set_has_access_log_dir();
access_log_dir_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:ustore.Config.access_log_dir)
}
#if LANG_CXX11
inline void Config::set_access_log_dir(::std::string&& value) {
set_has_access_log_dir();
access_log_dir_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:ustore.Config.access_log_dir)
}
#endif
inline void Config::set_access_log_dir(const char* value) {
GOOGLE_DCHECK(value != NULL);
set_has_access_log_dir();
access_log_dir_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:ustore.Config.access_log_dir)
}
inline void Config::set_access_log_dir(const char* value, size_t size) {
set_has_access_log_dir();
access_log_dir_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:ustore.Config.access_log_dir)
}
inline ::std::string* Config::mutable_access_log_dir() {
set_has_access_log_dir();
// @@protoc_insertion_point(field_mutable:ustore.Config.access_log_dir)
return access_log_dir_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* Config::release_access_log_dir() {
// @@protoc_insertion_point(field_release:ustore.Config.access_log_dir)
if (!has_access_log_dir()) {
return NULL;
}
clear_has_access_log_dir();
return access_log_dir_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void Config::set_allocated_access_log_dir(::std::string* access_log_dir) {
if (access_log_dir != NULL) {
set_has_access_log_dir();
} else {
clear_has_access_log_dir();
}
access_log_dir_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), access_log_dir);
// @@protoc_insertion_point(field_set_allocated:ustore.Config.access_log_dir)
}
// optional int32 max_segments = 4 [default = 64];
inline bool Config::has_max_segments() const {
return (_has_bits_[0] & 0x00000020u) != 0;
}
inline void Config::set_has_max_segments() {
_has_bits_[0] |= 0x00000020u;
}
inline void Config::clear_has_max_segments() {
_has_bits_[0] &= ~0x00000020u;
}
inline void Config::clear_max_segments() {
max_segments_ = 64;
clear_has_max_segments();
}
inline ::google::protobuf::int32 Config::max_segments() const {
// @@protoc_insertion_point(field_get:ustore.Config.max_segments)
return max_segments_;
}
inline void Config::set_max_segments(::google::protobuf::int32 value) {
set_has_max_segments();
max_segments_ = value;
// @@protoc_insertion_point(field_set:ustore.Config.max_segments)
}
// optional bool enable_dist_store = 5 [default = false];
inline bool Config::has_enable_dist_store() const {
return (_has_bits_[0] & 0x00000010u) != 0;
}
inline void Config::set_has_enable_dist_store() {
_has_bits_[0] |= 0x00000010u;
}
inline void Config::clear_has_enable_dist_store() {
_has_bits_[0] &= ~0x00000010u;
}
inline void Config::clear_enable_dist_store() {
enable_dist_store_ = false;
clear_has_enable_dist_store();
}
inline bool Config::enable_dist_store() const {
// @@protoc_insertion_point(field_get:ustore.Config.enable_dist_store)
return enable_dist_store_;
}
inline void Config::set_enable_dist_store(bool value) {
set_has_enable_dist_store();
enable_dist_store_ = value;
// @@protoc_insertion_point(field_set:ustore.Config.enable_dist_store)
}
// optional bool get_chunk_bypass_worker = 6 [default = true];
inline bool Config::has_get_chunk_bypass_worker() const {
return (_has_bits_[0] & 0x00000040u) != 0;
}
inline void Config::set_has_get_chunk_bypass_worker() {
_has_bits_[0] |= 0x00000040u;
}
inline void Config::clear_has_get_chunk_bypass_worker() {
_has_bits_[0] &= ~0x00000040u;
}
inline void Config::clear_get_chunk_bypass_worker() {
get_chunk_bypass_worker_ = true;
clear_has_get_chunk_bypass_worker();
}
inline bool Config::get_chunk_bypass_worker() const {
// @@protoc_insertion_point(field_get:ustore.Config.get_chunk_bypass_worker)
return get_chunk_bypass_worker_;
}
inline void Config::set_get_chunk_bypass_worker(bool value) {
set_has_get_chunk_bypass_worker();
get_chunk_bypass_worker_ = value;
// @@protoc_insertion_point(field_set:ustore.Config.get_chunk_bypass_worker)
}
// optional string worker_file = 10 [default = "conf/workers.lst"];
inline bool Config::has_worker_file() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void Config::set_has_worker_file() {
_has_bits_[0] |= 0x00000008u;
}
inline void Config::clear_has_worker_file() {
_has_bits_[0] &= ~0x00000008u;
}
inline void Config::clear_worker_file() {
worker_file_.ClearToDefaultNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_worker_file_.get());
clear_has_worker_file();
}
inline const ::std::string& Config::worker_file() const {
// @@protoc_insertion_point(field_get:ustore.Config.worker_file)
return worker_file_.GetNoArena();
}
inline void Config::set_worker_file(const ::std::string& value) {
set_has_worker_file();
worker_file_.SetNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_worker_file_.get(), value);
// @@protoc_insertion_point(field_set:ustore.Config.worker_file)
}
#if LANG_CXX11
inline void Config::set_worker_file(::std::string&& value) {
set_has_worker_file();
worker_file_.SetNoArena(
&::ustore::Config::_i_give_permission_to_break_this_code_default_worker_file_.get(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:ustore.Config.worker_file)
}
#endif
inline void Config::set_worker_file(const char* value) {
GOOGLE_DCHECK(value != NULL);
set_has_worker_file();
worker_file_.SetNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_worker_file_.get(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:ustore.Config.worker_file)
}
inline void Config::set_worker_file(const char* value, size_t size) {
set_has_worker_file();
worker_file_.SetNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_worker_file_.get(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:ustore.Config.worker_file)
}
inline ::std::string* Config::mutable_worker_file() {
set_has_worker_file();
// @@protoc_insertion_point(field_mutable:ustore.Config.worker_file)
return worker_file_.MutableNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_worker_file_.get());
}
inline ::std::string* Config::release_worker_file() {
// @@protoc_insertion_point(field_release:ustore.Config.worker_file)
if (!has_worker_file()) {
return NULL;
}
clear_has_worker_file();
return worker_file_.ReleaseNonDefaultNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_worker_file_.get());
}
inline void Config::set_allocated_worker_file(::std::string* worker_file) {
if (worker_file != NULL) {
set_has_worker_file();
} else {
clear_has_worker_file();
}
worker_file_.SetAllocatedNoArena(&::ustore::Config::_i_give_permission_to_break_this_code_default_worker_file_.get(), worker_file);
// @@protoc_insertion_point(field_set_allocated:ustore.Config.worker_file)
}
// optional int32 recv_threads = 21 [default = 2];
inline bool Config::has_recv_threads() const {
return (_has_bits_[0] & 0x00000080u) != 0;
}
inline void Config::set_has_recv_threads() {
_has_bits_[0] |= 0x00000080u;
}
inline void Config::clear_has_recv_threads() {
_has_bits_[0] &= ~0x00000080u;
}
inline void Config::clear_recv_threads() {
recv_threads_ = 2;
clear_has_recv_threads();
}
inline ::google::protobuf::int32 Config::recv_threads() const {
// @@protoc_insertion_point(field_get:ustore.Config.recv_threads)
return recv_threads_;
}
inline void Config::set_recv_threads(::google::protobuf::int32 value) {
set_has_recv_threads();
recv_threads_ = value;
// @@protoc_insertion_point(field_set:ustore.Config.recv_threads)
}
// optional int32 http_port = 50 [default = 60000];
inline bool Config::has_http_port() const {
return (_has_bits_[0] & 0x00000100u) != 0;
}
inline void Config::set_has_http_port() {
_has_bits_[0] |= 0x00000100u;
}
inline void Config::clear_has_http_port() {
_has_bits_[0] &= ~0x00000100u;
}
inline void Config::clear_http_port() {
http_port_ = 60000;
clear_has_http_port();
}
inline ::google::protobuf::int32 Config::http_port() const {
// @@protoc_insertion_point(field_get:ustore.Config.http_port)
return http_port_;
}
inline void Config::set_http_port(::google::protobuf::int32 value) {
set_has_http_port();
http_port_ = value;
// @@protoc_insertion_point(field_set:ustore.Config.http_port)
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// @@protoc_insertion_point(namespace_scope)
} // namespace ustore
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_INCLUDED_config_2eproto
|
makaram99/cute-os
|
docs/html/search/all_4.js
|
<reponame>makaram99/cute-os
var searchData=
[
['error_5fbusy_30',['ERROR_BUSY',['../_s_t_d___t_y_p_e_s_8h.html#aa5a5124474a705e6cf7e43f113ac10fb',1,'STD_TYPES.h']]],
['error_5fillegal_5fparam_31',['ERROR_ILLEGAL_PARAM',['../_s_t_d___t_y_p_e_s_8h.html#afb1d42f0ea0b554fbc07047128e0b14b',1,'STD_TYPES.h']]],
['error_5fno_32',['ERROR_NO',['../_s_t_d___t_y_p_e_s_8h.html#a2e537466d7029353e207af831498b7f8',1,'STD_TYPES.h']]],
['error_5fnot_5finitialized_33',['ERROR_NOT_INITIALIZED',['../_s_t_d___t_y_p_e_s_8h.html#a605e0ff46555922872461535eca0d0b9',1,'STD_TYPES.h']]],
['error_5fnull_5fpointer_34',['ERROR_NULL_POINTER',['../_s_t_d___t_y_p_e_s_8h.html#ab42bd75b80154413643a683d091f1224',1,'STD_TYPES.h']]],
['error_5fout_5fof_5frange_35',['ERROR_OUT_OF_RANGE',['../_s_t_d___t_y_p_e_s_8h.html#a7102651296c0417a05f0117c66c18de5',1,'STD_TYPES.h']]],
['error_5ft_36',['ERROR_t',['../_s_t_d___t_y_p_e_s_8h.html#ab0e1f6a25bfc1b579842f3e54c2b1cd0',1,'STD_TYPES.h']]],
['error_5ftimeout_37',['ERROR_TIMEOUT',['../_s_t_d___t_y_p_e_s_8h.html#ad58fd51c3e56b5d9555ce48be5cc53bd',1,'STD_TYPES.h']]],
['error_5fyes_38',['ERROR_YES',['../_s_t_d___t_y_p_e_s_8h.html#ac804fdda39e617c8699964c7b8e363d9',1,'STD_TYPES.h']]]
];
|
athisun/ArrowPoint-Telemetry
|
src/main/java/com/prohelion/service/impl/MeasurementDataAggregator.java
|
package com.prohelion.service.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.prohelion.model.MeasurementData;
public class MeasurementDataAggregator {
private static final Logger LOG = LoggerFactory.getLogger(MeasurementDataAggregator.class);
public MeasurementData collect(List<MeasurementData> payloads) {
LOG.debug("Received " + payloads.size() + " in the aggregator for id " + payloads.get(0).getDataPointCanId() );
// Returns just the last and hence most recent element
return payloads.get(payloads.size() - 1);
}
}
|
RuiDTLima/diffuzz
|
evaluation/github_authmreloaded_unsafe/src/test/java/fr/xephi/authme/settings/SpawnLoaderTest.java
|
package fr.xephi.authme.settings;
import ch.jalu.injector.testing.BeforeInjecting;
import ch.jalu.injector.testing.DelayedInjectionRunner;
import ch.jalu.injector.testing.InjectDelayed;
import com.google.common.io.Files;
import fr.xephi.authme.TestHelper;
import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.service.PluginHookService;
import fr.xephi.authme.settings.properties.RestrictionSettings;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.file.YamlConfiguration;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import java.io.File;
import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Test for {@link SpawnLoader}.
*/
@RunWith(DelayedInjectionRunner.class)
public class SpawnLoaderTest {
@InjectDelayed
private SpawnLoader spawnLoader;
@Mock
private Settings settings;
@Mock
private PluginHookService pluginHookService;
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@DataFolder
private File testFolder;
@BeforeInjecting
public void setup() throws IOException {
// Copy test config into a new temporary folder
testFolder = temporaryFolder.newFolder();
File source = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "settings/spawn-firstspawn.yml");
File destination = new File(testFolder, "spawn.yml");
Files.copy(source, destination);
// Create a settings mock with default values
given(settings.getProperty(RestrictionSettings.SPAWN_PRIORITY))
.willReturn("authme, essentials, multiverse, default");
}
@Test
public void shouldSetSpawn() {
// given
World world = mock(World.class);
given(world.getName()).willReturn("new_world");
Location newSpawn = new Location(world, 123, 45.0, -67.89);
// when
boolean result = spawnLoader.setSpawn(newSpawn);
// then
assertThat(result, equalTo(true));
YamlConfiguration configuration = YamlConfiguration.loadConfiguration(new File(testFolder, "spawn.yml"));
assertThat(configuration.getDouble("spawn.x"), equalTo(123.0));
assertThat(configuration.getDouble("spawn.y"), equalTo(45.0));
assertThat(configuration.getDouble("spawn.z"), equalTo(-67.89));
assertThat(configuration.getString("spawn.world"), equalTo("new_world"));
}
}
|
mmongy/clij2
|
src/main/java/net/haesleinhuepf/clij2/plugins/ReduceStack.java
|
<reponame>mmongy/clij2
package net.haesleinhuepf.clij2.plugins;
import net.haesleinhuepf.clij.clearcl.ClearCLBuffer;
import net.haesleinhuepf.clij.clearcl.interfaces.ClearCLImageInterface;
import net.haesleinhuepf.clij.macro.CLIJMacroPlugin;
import net.haesleinhuepf.clij.macro.CLIJOpenCLProcessor;
import net.haesleinhuepf.clij.macro.documentation.OffersDocumentation;
import net.haesleinhuepf.clij2.AbstractCLIJ2Plugin;
import net.haesleinhuepf.clij2.CLIJ2;
import net.haesleinhuepf.clij2.utilities.HasClassifiedInputOutput;
import net.haesleinhuepf.clij2.utilities.IsCategorized;
import org.scijava.plugin.Plugin;
/**
* Author: @haesleinhuepf
* May 2020
*/
@Plugin(type = CLIJMacroPlugin.class, name = "CLIJ2_reduceStack")
public class ReduceStack extends AbstractCLIJ2Plugin implements CLIJMacroPlugin, CLIJOpenCLProcessor, OffersDocumentation, IsCategorized, HasClassifiedInputOutput {
@Override
public String getInputType() {
return "Image";
}
@Override
public String getOutputType() {
return "Image";
}
@Override
public String getCategories() {
return "Transform";
}
@Override
public Object[] getDefaultValues() {
return new Object[]{null, null, 2, 0};
}
@Override
public boolean executeCL() {
return getCLIJ2().reduceStack( (ClearCLImageInterface)( args[0]), (ClearCLImageInterface)(args[1]), asInteger(args[2]), asInteger(args[3]));
}
public static boolean reduceStack(CLIJ2 clij2, ClearCLImageInterface src, ClearCLImageInterface dst, Integer factor, Integer offset) {
ClearCLBuffer temp = clij2.create(new long[]{src.getWidth(), src.getHeight()}, src.getNativeType());
int j = 0;
for (int i = 0; i < src.getDepth(); i += factor) {
clij2.copySlice(src, temp, i + offset);
clij2.copySlice(temp, dst, j);
j++;
}
return true;
}
@Override
public ClearCLBuffer createOutputBufferFromSource(ClearCLBuffer input) {
int factor = asInteger(args[2]);
return getCLIJ2().create(new long[]{input.getWidth(), input.getHeight(), input.getDepth() / factor}, input.getNativeType());
}
@Override
public String getParameterHelpText() {
return "Image input, ByRef Image destination, Number reduction_factor, Number offset";
}
@Override
public String getDescription() {
return "Reduces the number of slices in a stack by a given factor.\n" +
"With the offset you have control which slices stay: \n" +
"* With factor 3 and offset 0, slices 0, 3, 6,... are kept. " +
"* With factor 4 and offset 1, slices 1, 5, 9,... are kept.";
}
@Override
public String getAvailableForDimensions() {
return "2D, 3D";
}
}
|
tklebanoff/ComputeLibrary
|
documentation/classarm__compute_1_1_memory_group_resource_scope.js
|
var classarm__compute_1_1_memory_group_resource_scope =
[
[ "MemoryGroupResourceScope", "classarm__compute_1_1_memory_group_resource_scope.xhtml#a17a9e92a2c60aaa9e037faedc17e8be5", null ],
[ "MemoryGroupResourceScope", "classarm__compute_1_1_memory_group_resource_scope.xhtml#a4b173d900c8f147613ec73f6c3dbb31d", null ],
[ "MemoryGroupResourceScope", "classarm__compute_1_1_memory_group_resource_scope.xhtml#a165aa02a798e692698413deece7b91d2", null ],
[ "~MemoryGroupResourceScope", "classarm__compute_1_1_memory_group_resource_scope.xhtml#a21491a2d20822db81c534c7dfbb790cd", null ],
[ "operator=", "classarm__compute_1_1_memory_group_resource_scope.xhtml#a1ca1d6300c06d946e32c545008637f89", null ],
[ "operator=", "classarm__compute_1_1_memory_group_resource_scope.xhtml#aeca93b544ee94af3c3539f976a985c8e", null ]
];
|
marcosolina/covidstatus
|
src/main/java/com/marco/javacovidstatus/services/interfaces/downloaders/CovidDataDownloader.java
|
package com.marco.javacovidstatus.services.interfaces.downloaders;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
/**
* Abstract class to provide a common set of functionalities to download and
* process the data from the Ministry of Health repository
*
* @see <a href="https://github.com/pcm-dpc/COVID-19">Ministry of Health
* repository</a>
* @author Marco
*
*/
public abstract class CovidDataDownloader {
private WebClient webClient;
protected final LocalDate defaultStartData = LocalDate.of(2020, 2, 24);
public CovidDataDownloader(WebClient webClient) {
this.webClient = webClient;
}
/**
* It downloads the data
*
* @return
*/
public abstract boolean downloadData();
/**
* It returns the start date from when to start to download the data. This date
* should exclude the dates already download
*
* @return
*/
public abstract LocalDate getStartDate();
/**
* It calculates the percentage of the casualties. For the algorithm info kindly
* refer to the link
*
* @see <a href=
* "https://www.focus.it/scienza/salute/tasso-di-mortalita-covid-19">Algorithm</a>
* @param newCasualties
* @param newCasesFrom7DaysAgo
* @return
*/
protected float casualtiesPercentage(int newCasualties, int newCasesFrom7DaysAgo) {
if (newCasesFrom7DaysAgo == 0) {
return 0;
}
return ((float) newCasualties / newCasesFrom7DaysAgo) * 100;
}
/**
* It calculates the percentage of new infected people
*
* @param newTestsCorrente
* @param newTestsPrecedente
* @param newInfectionsCorrent
* @return
*/
protected float infectedPercentage(int todayNewTests, int previousNewTests, int todayNewInfections) {
if (todayNewInfections == 0) {
return 0;
}
int deltaTests = todayNewTests - previousNewTests;
int deltaInfections = todayNewInfections;
return ((float) deltaInfections / deltaTests) * 100;
}
/**
* Simplified call to {@link CovidDataDownloader#getCsvRows}
*
* @param url
* @return
*/
protected List<String> getCsvRows(String url) {
return getCsvRows(url, null, true);
}
/**
* It connects to the Ministry of Health Repository, reads the CSV file and it
* returns the list of rows included in the file. It will skip the columns
* labels row
*
* @param url
* @param headers
* @param removeColumnNamesLine
* @return
*/
protected List<String> getCsvRows(String url, Map<String, String> headers, boolean removeColumnNamesLine) {
/*
* Get the CSV file using an GET HTTP call
*/
ClientResponse response = null;
if (headers == null) {
response = webClient.get().uri(url).exchange().block();
} else {
response = webClient.get().uri(url).headers(httpHeaders -> headers.forEach(httpHeaders::set)).exchange()
.block();
}
if(response.statusCode() != HttpStatus.OK) {
return new ArrayList<>();
}
/*
* Read the response as a string
*/
String csv = response.bodyToMono(String.class).block();
List<String> listRows = new ArrayList<>(Arrays.asList(csv.split("\\n")));
if (removeColumnNamesLine && !listRows.isEmpty()) {
listRows.remove(0);// remove column names
}
return listRows;
}
}
|
c-jullien/lelisp
|
GELL/Cvirbitmap/virutil.c
|
<filename>GELL/Cvirbitmap/virutil.c
/* GELL 15.26: source file for the module: "virutil" */
/* translation done: "Tue Aug 24 93 10:48:45 " */
/* peephole-optimize-p: t */
/* optimize-local-labels-p: t */
#include "lelispc.h"
#include "virutil.h"
static Ptr GLvirutil_1() { /* #:color:make */
{ register Ptr aRet, rSp, rNil;
rSp = GIsp; rNil = GInil;
(--rSp)->Val = ((Ptr) GLvirutil_2);
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
GIa4 = (Ptr) 7;
{aRet = (GYvirutil[0] + 2)->Val; goto lRet;}
lRet: GIsp = rSp; return (aRet);}}
static Ptr GLvirutil_2() { /* 101 */
{ register Ptr aRet;
(GIa1 + 1)->Val = GYvirutil[1];
{aRet = (GIsp++)->Val; goto lRet;}
lRet: return (aRet);}}
static Ptr GLvirutil_3() { /* #:graph-env:make */
{ register Ptr aRet, *rLit, rSp, rNil;
rLit = GYvirutil; rSp = GIsp; rNil = GInil;
(--rSp)->Val = ((Ptr) GLvirutil_4);
(--rSp)->Val = (Ptr) 0;
(--rSp)->Val = (Ptr) 0;
(--rSp)->Val = (Ptr) 1;
(--rSp)->Val = (Ptr) 3;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = (Ptr) 0;
(--rSp)->Val = (Ptr) 0;
(--rSp)->Val = (Ptr) 0;
(--rSp)->Val = (Ptr) 0;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rLit[2];
GIa4 = (Ptr) 17;
{aRet = (rLit[0] + 2)->Val; goto lRet;}
lRet: GIsp = rSp; return (aRet);}}
static Ptr GLvirutil_4() { /* 101 */
{ register Ptr aRet;
(GIa1 + 1)->Val = GYvirutil[3];
{aRet = (GIsp++)->Val; goto lRet;}
lRet: return (aRet);}}
static Ptr GLvirutil_5() { /* #:event:make */
{ register Ptr aRet, rSp, rNil;
rSp = GIsp; rNil = GInil;
(--rSp)->Val = ((Ptr) GLvirutil_6);
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
GIa4 = (Ptr) 10;
{aRet = (GYvirutil[0] + 2)->Val; goto lRet;}
lRet: GIsp = rSp; return (aRet);}}
static Ptr GLvirutil_6() { /* 101 */
{ register Ptr aRet;
(GIa1 + 1)->Val = GYvirutil[4];
{aRet = (GIsp++)->Val; goto lRet;}
lRet: return (aRet);}}
static Ptr GLvirutil_7() { /* #:bitmap:make */
{ register Ptr aRet, rSp, rNil;
rSp = GIsp; rNil = GInil;
(--rSp)->Val = ((Ptr) GLvirutil_8);
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
GIa4 = (Ptr) 4;
{aRet = (GYvirutil[0] + 2)->Val; goto lRet;}
lRet: GIsp = rSp; return (aRet);}}
static Ptr GLvirutil_8() { /* 101 */
{ register Ptr aRet;
(GIa1 + 1)->Val = GYvirutil[5];
{aRet = (GIsp++)->Val; goto lRet;}
lRet: return (aRet);}}
static Ptr GLvirutil_9() { /* #:bitmap:bytemap:make */
{ register Ptr aRet, rSp, rNil;
rSp = GIsp; rNil = GInil;
(--rSp)->Val = ((Ptr) GLvirutil_10);
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
GIa4 = (Ptr) 4;
{aRet = (GYvirutil[0] + 2)->Val; goto lRet;}
lRet: GIsp = rSp; return (aRet);}}
static Ptr GLvirutil_10() { /* 101 */
{ register Ptr aRet;
(GIa1 + 1)->Val = GYvirutil[6];
{aRet = (GIsp++)->Val; goto lRet;}
lRet: return (aRet);}}
static Ptr GLvirutil_11() { /* #:bitmap:stipple:make */
{ register Ptr aRet, rSp, rNil;
rSp = GIsp; rNil = GInil;
(--rSp)->Val = ((Ptr) GLvirutil_12);
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
GIa4 = (Ptr) 5;
{aRet = (GYvirutil[0] + 2)->Val; goto lRet;}
lRet: GIsp = rSp; return (aRet);}}
static Ptr GLvirutil_12() { /* 101 */
{ register Ptr aRet;
(GIa1 + 1)->Val = GYvirutil[7];
{aRet = (GIsp++)->Val; goto lRet;}
lRet: return (aRet);}}
static Ptr GLvirutil_13() { /* #:image:rectangle:make */
{ register Ptr aRet, rSp;
rSp = GIsp;
(--rSp)->Val = ((Ptr) GLvirutil_14);
(--rSp)->Val = (Ptr) 0;
(--rSp)->Val = (Ptr) 0;
(--rSp)->Val = (Ptr) 1;
(--rSp)->Val = (Ptr) 1;
GIa4 = (Ptr) 4;
{aRet = (GYvirutil[0] + 2)->Val; goto lRet;}
lRet: GIsp = rSp; return (aRet);}}
static Ptr GLvirutil_14() { /* 101 */
{ register Ptr aRet;
(GIa1 + 1)->Val = GYvirutil[8];
{aRet = (GIsp++)->Val; goto lRet;}
lRet: return (aRet);}}
static Ptr GLvirutil_15() { /* #:image:rectangle:window:make */
{ register Ptr aRet, rSp, rNil;
rSp = GIsp; rNil = GInil;
(--rSp)->Val = ((Ptr) GLvirutil_16);
(--rSp)->Val = (Ptr) 0;
(--rSp)->Val = (Ptr) 0;
(--rSp)->Val = (Ptr) 1;
(--rSp)->Val = (Ptr) 1;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = (Ptr) 0;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
GIa4 = (Ptr) 18;
{aRet = (GYvirutil[0] + 2)->Val; goto lRet;}
lRet: GIsp = rSp; return (aRet);}}
static Ptr GLvirutil_16() { /* 101 */
{ register Ptr aRet;
(GIa1 + 1)->Val = GYvirutil[9];
{aRet = (GIsp++)->Val; goto lRet;}
lRet: return (aRet);}}
static Ptr GLvirutil_17() { /* #:menu:make */
{ register Ptr aRet, rSp, rNil;
rSp = GIsp; rNil = GInil;
(--rSp)->Val = ((Ptr) GLvirutil_18);
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
GIa4 = (Ptr) 4;
{aRet = (GYvirutil[0] + 2)->Val; goto lRet;}
lRet: GIsp = rSp; return (aRet);}}
static Ptr GLvirutil_18() { /* 101 */
{ register Ptr aRet;
(GIa1 + 1)->Val = GYvirutil[10];
{aRet = (GIsp++)->Val; goto lRet;}
lRet: return (aRet);}}
static Ptr GLvirutil_19() { /* #:menu:itemlist:make */
{ register Ptr aRet, rSp, rNil;
rSp = GIsp; rNil = GInil;
(--rSp)->Val = ((Ptr) GLvirutil_20);
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
GIa4 = (Ptr) 7;
{aRet = (GYvirutil[0] + 2)->Val; goto lRet;}
lRet: GIsp = rSp; return (aRet);}}
static Ptr GLvirutil_20() { /* 101 */
{ register Ptr aRet;
(GIa1 + 1)->Val = GYvirutil[11];
{aRet = (GIsp++)->Val; goto lRet;}
lRet: return (aRet);}}
static Ptr GLvirutil_21() { /* #:menu:item:make */
{ register Ptr aRet, rSp, rNil;
rSp = GIsp; rNil = GInil;
(--rSp)->Val = ((Ptr) GLvirutil_22);
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
GIa4 = (Ptr) 7;
{aRet = (GYvirutil[0] + 2)->Val; goto lRet;}
lRet: GIsp = rSp; return (aRet);}}
static Ptr GLvirutil_22() { /* 101 */
{ register Ptr aRet;
(GIa1 + 1)->Val = GYvirutil[12];
{aRet = (GIsp++)->Val; goto lRet;}
lRet: return (aRet);}}
static Ptr GLvirutil_23() { /* #:font-info:make */
{ register Ptr aRet, rSp, rNil;
rSp = GIsp; rNil = GInil;
(--rSp)->Val = ((Ptr) GLvirutil_24);
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
(--rSp)->Val = rNil;
GIa4 = (Ptr) 14;
{aRet = (GYvirutil[0] + 2)->Val; goto lRet;}
lRet: GIsp = rSp; return (aRet);}}
static Ptr GLvirutil_24() { /* 101 */
{ register Ptr aRet;
(GIa1 + 1)->Val = GYvirutil[13];
{aRet = (GIsp++)->Val; goto lRet;}
lRet: return (aRet);}}
static Ptr GLvirutil_25() { /* #:window:background */
{ register Ptr aRet, *rLit, rSp, rA1, rA2, rA4, rNil;
rLit = GYvirutil; rSp = GIsp; rA1 = GIa1; rA2 = GIa2; rA4 = GIa4; rNil = GInil;
if ((Fix) (rA4) >= (Fix) 1) goto l_101;
rA1 = rLit[14];
rA2 = (Ptr) 1;
{aRet = (rLit[15] + 2)->Val; goto lRet;}
l_101:
rA4 = (Ptr) ((UFix) ((Fix) (rA4) - (Fix) 1));
rA1 = rNil;
goto l_nlist_virutil_27;
l_nlist_virutil_26:
rA2 = (rSp++)->Val;
GIsp = rSp; GIa1 = rA1; GIa2 = rA2; GIa4 = rA4; rA1 = llrt_cons (rA2, rA1);
l_nlist_virutil_27:
{register Fix aux;
aux = (Fix) (rA4) - 1;
rA4 = (Ptr) ((UFix) aux);
if (aux >= 0) goto l_nlist_virutil_26;}
if (rA1 == rNil) goto l_102;
rA4 = (rSp->Val->Val + 2 + (Fix) 7)->Val;
if (rA4 == rNil) goto l_104;
rA4 = (rSp->Val->Val + 2 + (Fix) 7)->Val;
(rA4->Val + 2 + (Fix) 5)->Val = rA1->Val;
rA1 = rA1->Val;
rSp += (Fix) 1;
{aRet = (rSp++)->Val; goto lRet;}
l_104:
rA1 = rNil;
rSp += (Fix) 1;
{aRet = (rSp++)->Val; goto lRet;}
l_102:
rA4 = (rSp->Val->Val + 2 + (Fix) 7)->Val;
if (rA4 == rNil) goto l_106;
rA1 = (rSp->Val->Val + 2 + (Fix) 7)->Val;
rA1 = (rA1->Val + 2 + (Fix) 5)->Val;
rSp += (Fix) 1;
{aRet = (rSp++)->Val; goto lRet;}
l_106:
rA1 = rNil;
rSp += (Fix) 1;
{aRet = (rSp++)->Val; goto lRet;}
lRet: GIsp = rSp; GIa1 = rA1; GIa2 = rA2; GIa4 = rA4; return (aRet);}}
static Ptr GLvirutil_28() { /* current-display */
{ register Ptr aRet, *rLit, rSp, rA1, rA4, rNil;
rLit = GYvirutil; rSp = GIsp; rA1 = GIa1; rA4 = GIa4; rNil = GInil;
(--rSp)->Val = rA4;
rA1 = rSp->Val;
if (rA1 != (Ptr) 0) goto l_102;
rA1 = rLit[16]->Val;
{rA4 = (rSp++)->Val; rSp += (Fix) rA4; aRet = (rSp++)->Val; goto lRet;}
l_102:
if (rA1 != (Ptr) 1) {aRet = ((Ptr) GLvirutil_29); goto lRet;}
rA4 = rSp->Val;
rA4 = (rSp + (Fix) (rA4))->Val;
if (rA4 != rNil) goto l_104;
rLit[16]->Val = rNil;
rA1 = rNil;
{rA4 = (rSp++)->Val; rSp += (Fix) rA4; aRet = (rSp++)->Val; goto lRet;}
l_104:
rA4 = rSp->Val;
rA4 = (rSp + (Fix) (rA4))->Val;
if (rA4 != rNil) goto l_107;
rA4 = rSp->Val;
GIa3 = (rSp + (Fix) (rA4))->Val;
GIa2 = rLit[17];
rA1 = rLit[18];
GIsp = rSp; GIa1 = rA1; GIa4 = rA4; rA1 = llrt_call_error ();
l_107:
rA4 = rSp->Val;
rA1 = (rSp + (Fix) (rA4))->Val;
GIa2 = rLit[19];
(--rSp)->Val = ((Ptr) GLvirutil_31);
{aRet = (rLit[20] + 2)->Val; goto lRet;}
lRet: GIsp = rSp; GIa1 = rA1; GIa4 = rA4; return (aRet);}}
static Ptr GLvirutil_31() { /* call_virutil_30 */
{ register Ptr aRet, *rLit, rSp, rA1, rA4, rNil;
rLit = GYvirutil; rSp = GIsp; rA1 = GIa1; rA4 = GIa4; rNil = GInil;
if (rA1 == rNil) goto l_110;
rA4 = rSp->Val;
rA4 = (rSp + (Fix) (rA4))->Val;
rA4 = (rA4->Val + 2 + (Fix) 6)->Val;
if (rA4 != rNil) goto l_109;
l_110:
rA4 = rSp->Val;
GIa3 = (rSp + (Fix) (rA4))->Val;
GIa2 = rLit[21];
rA1 = rLit[18];
GIsp = rSp; GIa1 = rA1; GIa4 = rA4; rA1 = llrt_call_error ();
l_109:
rA4 = rSp->Val;
rA4 = (rSp + (Fix) (rA4))->Val;
if (rLit[16]->Val == rA4) {aRet = ((Ptr) GLvirutil_32); goto lRet;}
rA4 = rSp->Val;
rA4 = (rSp + (Fix) (rA4))->Val;
rLit[16]->Val = rA4;
(--rSp)->Val = ((Ptr) GLvirutil_32);
(--rSp)->Val = rLit[18];
(--rSp)->Val = rA4;
rA4 = (Ptr) 2;
{aRet = (rLit[22] + 2)->Val; goto lRet;}
lRet: GIsp = rSp; GIa1 = rA1; GIa4 = rA4; return (aRet);}}
static Ptr GLvirutil_32() { /* 112 */
{ register Ptr aRet, rSp;
rSp = GIsp;
GIa1 = GYvirutil[16]->Val;
{GIa4 = (rSp++)->Val; rSp += (Fix) GIa4; aRet = (rSp++)->Val; goto lRet;}
lRet: GIsp = rSp; return (aRet);}}
static Ptr GLvirutil_29() { /* 103 */
{ register Ptr aRet, *rLit, rSp;
rLit = GYvirutil; rSp = GIsp;
GIa3 = rSp->Val;
GIa2 = rLit[23];
GIa1 = rLit[18];
GIsp = rSp; GIa1 = llrt_call_error ();
l_101:
GIa4 = (rSp++)->Val;
rSp += (Fix) (GIa4);
{aRet = (rSp++)->Val; goto lRet;}
lRet: GIsp = rSp; return (aRet);}}
static Ptr GDvirutil_33() { /* trace #:color:make */
{ register Ptr aRet;
aRet = llrt_jmpd (GYvirutil,24,25,26);
lRet: return (aRet);}}
static Ptr GDvirutil_34() { /* trace #:graph-env:make */
{ register Ptr aRet;
aRet = llrt_jmpd (GYvirutil,27,25,26);
lRet: return (aRet);}}
static Ptr GDvirutil_35() { /* trace #:event:make */
{ register Ptr aRet;
aRet = llrt_jmpd (GYvirutil,28,25,26);
lRet: return (aRet);}}
static Ptr GDvirutil_36() { /* trace #:bitmap:make */
{ register Ptr aRet;
aRet = llrt_jmpd (GYvirutil,29,25,26);
lRet: return (aRet);}}
static Ptr GDvirutil_37() { /* trace #:bitmap:bytemap:make */
{ register Ptr aRet;
aRet = llrt_jmpd (GYvirutil,30,25,26);
lRet: return (aRet);}}
static Ptr GDvirutil_38() { /* trace #:bitmap:stipple:make */
{ register Ptr aRet;
aRet = llrt_jmpd (GYvirutil,31,25,26);
lRet: return (aRet);}}
static Ptr GDvirutil_39() { /* trace #:image:rectangle:make */
{ register Ptr aRet;
aRet = llrt_jmpd (GYvirutil,32,25,26);
lRet: return (aRet);}}
static Ptr GDvirutil_40() { /* trace #:image:rectangle:window:make */
{ register Ptr aRet;
aRet = llrt_jmpd (GYvirutil,33,25,26);
lRet: return (aRet);}}
static Ptr GDvirutil_41() { /* trace #:menu:make */
{ register Ptr aRet;
aRet = llrt_jmpd (GYvirutil,34,25,26);
lRet: return (aRet);}}
static Ptr GDvirutil_42() { /* trace #:menu:itemlist:make */
{ register Ptr aRet;
aRet = llrt_jmpd (GYvirutil,35,25,26);
lRet: return (aRet);}}
static Ptr GDvirutil_43() { /* trace #:menu:item:make */
{ register Ptr aRet;
aRet = llrt_jmpd (GYvirutil,36,25,26);
lRet: return (aRet);}}
static Ptr GDvirutil_44() { /* trace #:font-info:make */
{ register Ptr aRet;
aRet = llrt_jmpd (GYvirutil,37,25,26);
lRet: return (aRet);}}
static Ptr GDvirutil_45() { /* trace #:window:background */
{ register Ptr aRet;
aRet = llrt_jmpd (GYvirutil,14,25,38);
lRet: return (aRet);}}
static Ptr GDvirutil_46() { /* trace current-display */
{ register Ptr aRet;
aRet = llrt_jmpd (GYvirutil,18,25,38);
lRet: return (aRet);}}
|
kunka/SoftRender
|
ui/Cube.cpp
|
//
// Created by huangkun on 26/03/2018.
//
#include "Cube.h"
#include <glad/glad.h>
static float vertices[] = {
-0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f
};
Cube::Cube() {
}
Cube *Cube::create() {
Cube *ret = new Cube();
if (ret && ret->init()) {
}
return ret;
}
Cube::~Cube() {
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
}
bool Cube::init() {
const char *vs = "#version 330 core\
layout (location = 0) in vec3 aPos;\
layout (location = 1) in vec2 aTexCoord;\
out vec2 TexCoord;\
uniform mat4 model; \
uniform mat4 view; \
uniform mat4 projection; \
void main()\
{\
gl_Position = projection * view * model * vec4(aPos, 1.0);\
TexCoord = vec2(aTexCoord.x, 1.0-aTexCoord.y);\
}";
const char *fs = "#version 330 core\
out vec4 FragColor;\
\
in vec2 TexCoord;\
uniform sampler2D texture1;\
uniform sampler2D texture2;\
void main()\
{\
vec2 coord = TexCoord;\
FragColor = mix(texture(texture1, TexCoord), texture(texture2, coord) , 0.5);\
}";
shader.loadStr(vs, fs);
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void *) 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
return true;
}
//void Cube::draw() {
//
//}
|
Nic30/pclass-vectorized
|
benchmarks/hash_table_cls.h
|
#pragma once
#include <unordered_map>
#include <map>
#include <stdint.h>
#include <vector>
#include <array>
#include <pcv/common/range.h>
/*
* RFC like classifier based on hash tables
* */
class HashTableBasedCls {
public:
using rule_id_t = uint32_t;
using priority_t = uint32_t;
using key_vec_t = std::array<uint16_t, 2>;
struct rule_value_t {
priority_t priority;
rule_id_t rule_id;
rule_value_t() :
priority(0), rule_id(-1) {
}
rule_value_t(priority_t _priority, size_t _id) :
priority(_priority), rule_id(_id) {
}
};
struct rule_spec_t {
std::array<pcv::Range1d<uint16_t>, 2> filter;
rule_value_t value;
};
struct pair_hash {
template<class T1, class T2>
std::size_t operator()(const std::pair<T1, T2> &pair) const {
return std::hash<T1>()(pair.first) ^ std::hash<T2>()(pair.second);
}
};
// any in range to start of range
std::unordered_map<uint16_t, uint16_t> data[2];
std::unordered_map<std::pair<uint16_t, uint16_t>, rule_value_t, pair_hash> cross_product;
uint16_t data_2_next_id;
HashTableBasedCls() :
data_2_next_id(0) {
}
void insert(const rule_spec_t & r) {
// for each colliding range check all records witch are using this range in cross production table
// and update them
auto f0 = r.filter[0];
assert(f0.high == f0.low);
auto _f0 = data[0].find(f0.low);
if (_f0 != data[0].end())
data[0][f0.low] = f0.low;
auto f1 = r.filter[1];
for (ssize_t l = f1.low; l <= (ssize_t) f1.high; l++) {
auto _f1 = data[1].find(l);
uint16_t f1_val;
if (_f1 == data[1].end()) {
f1_val = data_2_next_id;
data_2_next_id++;
data[1][l] = f1_val;
} else {
f1_val = _f1->second;
}
cross_product[ { f0.low, f1_val }] = r.value;
}
}
rule_value_t search(const key_vec_t & val) {
auto k0 = data[0].find(val[0]);
if (k0 == data[0].end())
return rule_value_t();
auto k1 = data[1].find(val[1]);
if (k1 == data[1].end())
return rule_value_t();
auto res = cross_product.find( { k0->second, k1->second });
if (res == cross_product.end())
return rule_value_t();
return res->second;
}
};
|
paulwratt/cin-5.34.00
|
cint/src/Type.cxx
|
/* /% C++ %/ */
/***********************************************************************
* cint (C/C++ interpreter)
************************************************************************
* Source file Type.cxx
************************************************************************
* Description:
* Extended Run Time Type Identification API
************************************************************************
* Author <NAME>
* Copyright(c) 1995~2005 <NAME>
*
* For the licensing terms see the file COPYING
*
************************************************************************/
#include "Api.h"
#include "common.h"
#include "FastAllocString.h"
#if __GNUC__ <= 4 && __GNUC_MINOR__ < 80
#define THREAD_LOCAL_OR_STATIC static
#else
#if __cplusplus >= 201103L
#define THREAD_LOCAL_OR_STATIC thread_local
#else
#define THREAD_LOCAL_OR_STATIC static
#endif
#endif
/*********************************************************************
* class G__TypeInfo
*
*********************************************************************/
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo::G__TypeInfo(const char *typenamein):
G__ClassInfo(), type(0), typenum(-1), reftype(0), isconst(0)
{
Init(typenamein);
}
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo::G__TypeInfo():
G__ClassInfo(), type(0), typenum(-1), reftype(0), isconst(0)
{}
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo::G__TypeInfo(G__value buf):
G__ClassInfo(), type(0), typenum(-1), reftype(0), isconst(0)
{
Init(buf);
}
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo::~G__TypeInfo() {}
#ifndef __MAKECINT__
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo::G__TypeInfo(const Cint::G__TypeInfo& rhs)
: G__ClassInfo(rhs)
{
type = rhs.type;
typenum = rhs.typenum;
reftype = rhs.reftype;
isconst = rhs.isconst;
}
///////////////////////////////////////////////////////////////////////////
Cint::G__TypeInfo& Cint::G__TypeInfo::operator=(const Cint::G__TypeInfo& rhs)
{
if (this != &rhs) {
type = rhs.type;
typenum = rhs.typenum;
reftype = rhs.reftype;
isconst = rhs.isconst;
}
return *this;
}
#endif // __MAKECINT__
///////////////////////////////////////////////////////////////////////////
void Cint::G__TypeInfo::Init(G__value& buf) {
type = buf.type;
typenum = buf.typenum;
tagnum = buf.tagnum;
if(type!='d' && type!='f') reftype=buf.obj.reftype.reftype;
else reftype=0;
isconst = buf.isconst;
}
///////////////////////////////////////////////////////////////////////////
void Cint::G__TypeInfo::Init(struct G__var_array *var,int ig15) {
type = var->type[ig15];
typenum = var->p_typetable[ig15];
tagnum = var->p_tagtable[ig15];
reftype = var->reftype[ig15];
isconst = var->constvar[ig15];
}
///////////////////////////////////////////////////////////////////////////
void Cint::G__TypeInfo::Init(const char *typenamein)
{
G__value buf;
buf = G__string2type_body(typenamein,2);
type = buf.type;
tagnum = buf.tagnum;
typenum = buf.typenum;
reftype = buf.obj.reftype.reftype;
isconst = buf.obj.i;
class_property = 0;
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::operator==(const G__TypeInfo& a)
{
if(type==a.type && tagnum==a.tagnum && typenum==a.typenum &&
reftype==a.reftype) {
return(1);
}
else {
return(0);
}
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::operator!=(const G__TypeInfo& a)
{
if(type==a.type && tagnum==a.tagnum && typenum==a.typenum &&
reftype==a.reftype) {
return(0);
}
else {
return(1);
}
}
///////////////////////////////////////////////////////////////////////////
const char* Cint::G__TypeInfo::TrueName()
{
THREAD_LOCAL_OR_STATIC G__FastAllocString *buf_ptr = new G__FastAllocString(G__ONELINE);
G__FastAllocString &buf(*buf_ptr);
buf = G__type2string((int)type,(int)tagnum,-1,(int)reftype,(int)isconst);
return(buf);
}
///////////////////////////////////////////////////////////////////////////
const char* Cint::G__TypeInfo::Name()
{
THREAD_LOCAL_OR_STATIC G__FastAllocString *buf_ptr = new G__FastAllocString(G__ONELINE);
G__FastAllocString &buf(*buf_ptr);
buf = G__type2string((int)type,(int)tagnum,(int)typenum,(int)reftype
,(int)isconst);
return(buf);
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Size() const
{
G__value buf;
buf.type=(int)type;
buf.tagnum=(int)tagnum;
buf.typenum=(int)typenum;
buf.ref=reftype;
if(isupper(type)) {
buf.obj.reftype.reftype=reftype;
return(sizeof(void*));
}
return(G__sizeof(&buf));
}
///////////////////////////////////////////////////////////////////////////
long Cint::G__TypeInfo::Property()
{
long property = 0;
if(-1!=typenum) property|=G__BIT_ISTYPEDEF;
if(-1==tagnum) property|=G__BIT_ISFUNDAMENTAL;
else {
if(strcmp(G__struct.name[tagnum],"G__longlong")==0 ||
strcmp(G__struct.name[tagnum],"G__ulonglong")==0 ||
strcmp(G__struct.name[tagnum],"G__longdouble")==0) {
property|=G__BIT_ISFUNDAMENTAL;
if(-1!=typenum &&
(strcmp(G__newtype.name[typenum],"long long")==0 ||
strcmp(G__newtype.name[typenum],"unsigned long long")==0 ||
strcmp(G__newtype.name[typenum],"long double")==0)) {
property &= (~G__BIT_ISTYPEDEF);
}
}
else {
if(G__ClassInfo::IsValid()) property|=G__ClassInfo::Property();
}
}
if(isupper((int)type)) property|=G__BIT_ISPOINTER;
if(reftype==G__PARAREFERENCE||reftype>G__PARAREF)
property|=G__BIT_ISREFERENCE;
if(isconst&G__CONSTVAR) property|=G__BIT_ISCONSTANT;
if(isconst&G__PCONSTVAR) property|=G__BIT_ISPCONSTANT;
return(property);
}
///////////////////////////////////////////////////////////////////////////
void* Cint::G__TypeInfo::New() {
if(G__ClassInfo::IsValid()) {
return(G__ClassInfo::New());
}
else {
size_t size;
void *p;
size = Size();
p = new char[size];
return(p);
}
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::IsValid() {
if(G__ClassInfo::IsValid()) {
return(1);
}
else if(type) {
return(1);
}
else {
return(0);
}
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Typenum() const { return(typenum); }
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Type() const { return(type); }
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Reftype() const { return(reftype); }
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Isconst() const { return(isconst); }
///////////////////////////////////////////////////////////////////////////
G__value Cint::G__TypeInfo::Value() const {
G__value buf;
buf.type=type;
buf.tagnum=tagnum;
buf.typenum=typenum;
buf.isconst=(G__SIGNEDCHAR_T)isconst;
buf.obj.reftype.reftype = reftype;
buf.obj.i = 1;
buf.ref = 0;
return(buf);
}
///////////////////////////////////////////////////////////////////////////
int Cint::G__TypeInfo::Next()
{
return 0;
}
|
inklesspen1scripter/ultramine_core
|
src/main/java/net/minecraft/block/BlockCactus.java
|
<reponame>inklesspen1scripter/ultramine_core
package net.minecraft.block;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.Random;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.init.Blocks;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.EnumPlantType;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.common.IPlantable;
public class BlockCactus extends Block implements IPlantable
{
@SideOnly(Side.CLIENT)
private IIcon field_150041_a;
@SideOnly(Side.CLIENT)
private IIcon field_150040_b;
private static final String __OBFID = "CL_00000210";
protected BlockCactus()
{
super(Material.cactus);
this.setTickRandomly(true);
this.setCreativeTab(CreativeTabs.tabDecorations);
}
public void updateTick(World p_149674_1_, int p_149674_2_, int p_149674_3_, int p_149674_4_, Random p_149674_5_)
{
if (p_149674_1_.isAirBlock(p_149674_2_, p_149674_3_ + 1, p_149674_4_))
{
int l;
for (l = 1; p_149674_1_.getBlock(p_149674_2_, p_149674_3_ - l, p_149674_4_) == this; ++l)
{
;
}
if (l < 3)
{
int i1 = p_149674_1_.getBlockMetadata(p_149674_2_, p_149674_3_, p_149674_4_);
if (i1 == 15)
{
p_149674_1_.setBlock(p_149674_2_, p_149674_3_ + 1, p_149674_4_, this);
p_149674_1_.setBlockMetadataWithNotify(p_149674_2_, p_149674_3_, p_149674_4_, 0, 4);
this.onNeighborBlockChange(p_149674_1_, p_149674_2_, p_149674_3_ + 1, p_149674_4_, this);
}
else
{
p_149674_1_.setBlockMetadataWithNotify(p_149674_2_, p_149674_3_, p_149674_4_, i1 + 1, 4);
}
}
}
}
public AxisAlignedBB getCollisionBoundingBoxFromPool(World p_149668_1_, int p_149668_2_, int p_149668_3_, int p_149668_4_)
{
float f = 0.0625F;
return AxisAlignedBB.getBoundingBox((double)((float)p_149668_2_ + f), (double)p_149668_3_, (double)((float)p_149668_4_ + f), (double)((float)(p_149668_2_ + 1) - f), (double)((float)(p_149668_3_ + 1) - f), (double)((float)(p_149668_4_ + 1) - f));
}
@SideOnly(Side.CLIENT)
public AxisAlignedBB getSelectedBoundingBoxFromPool(World p_149633_1_, int p_149633_2_, int p_149633_3_, int p_149633_4_)
{
float f = 0.0625F;
return AxisAlignedBB.getBoundingBox((double)((float)p_149633_2_ + f), (double)p_149633_3_, (double)((float)p_149633_4_ + f), (double)((float)(p_149633_2_ + 1) - f), (double)(p_149633_3_ + 1), (double)((float)(p_149633_4_ + 1) - f));
}
@SideOnly(Side.CLIENT)
public IIcon getIcon(int p_149691_1_, int p_149691_2_)
{
return p_149691_1_ == 1 ? this.field_150041_a : (p_149691_1_ == 0 ? this.field_150040_b : this.blockIcon);
}
public boolean renderAsNormalBlock()
{
return false;
}
public boolean isOpaqueCube()
{
return false;
}
public int getRenderType()
{
return 13;
}
public boolean canPlaceBlockAt(World p_149742_1_, int p_149742_2_, int p_149742_3_, int p_149742_4_)
{
return !super.canPlaceBlockAt(p_149742_1_, p_149742_2_, p_149742_3_, p_149742_4_) ? false : this.canBlockStay(p_149742_1_, p_149742_2_, p_149742_3_, p_149742_4_);
}
public void onNeighborBlockChange(World p_149695_1_, int p_149695_2_, int p_149695_3_, int p_149695_4_, Block p_149695_5_)
{
if (!this.canBlockStay(p_149695_1_, p_149695_2_, p_149695_3_, p_149695_4_))
{
p_149695_1_.func_147480_a(p_149695_2_, p_149695_3_, p_149695_4_, true);
}
}
public boolean canBlockStay(World p_149718_1_, int p_149718_2_, int p_149718_3_, int p_149718_4_)
{
if (p_149718_1_.getBlock(p_149718_2_ - 1, p_149718_3_, p_149718_4_).getMaterial().isSolid())
{
return false;
}
else if (p_149718_1_.getBlock(p_149718_2_ + 1, p_149718_3_, p_149718_4_).getMaterial().isSolid())
{
return false;
}
else if (p_149718_1_.getBlock(p_149718_2_, p_149718_3_, p_149718_4_ - 1).getMaterial().isSolid())
{
return false;
}
else if (p_149718_1_.getBlock(p_149718_2_, p_149718_3_, p_149718_4_ + 1).getMaterial().isSolid())
{
return false;
}
else
{
Block block = p_149718_1_.getBlock(p_149718_2_, p_149718_3_ - 1, p_149718_4_);
return block.canSustainPlant(p_149718_1_, p_149718_2_, p_149718_3_ - 1, p_149718_4_, ForgeDirection.UP, this);
}
}
public void onEntityCollidedWithBlock(World p_149670_1_, int p_149670_2_, int p_149670_3_, int p_149670_4_, Entity p_149670_5_)
{
p_149670_5_.attackEntityFrom(DamageSource.cactus, 1.0F);
}
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister p_149651_1_)
{
this.blockIcon = p_149651_1_.registerIcon(this.getTextureName() + "_side");
this.field_150041_a = p_149651_1_.registerIcon(this.getTextureName() + "_top");
this.field_150040_b = p_149651_1_.registerIcon(this.getTextureName() + "_bottom");
}
@Override
public EnumPlantType getPlantType(IBlockAccess world, int x, int y, int z)
{
return EnumPlantType.Desert;
}
@Override
public Block getPlant(IBlockAccess world, int x, int y, int z)
{
return this;
}
@Override
public int getPlantMetadata(IBlockAccess world, int x, int y, int z)
{
return -1;
}
}
|
PacktPublishing/Mastering-Postgis
|
Chapter07/resources/ext-6.2.0-gpl/ext-6.2.0/templates/admin-dashboard/classic/src/view/charts/Charts.js
|
Ext.define('Admin.view.charts.Charts', {
extend: 'Ext.container.Container',
xtype: 'charts',
requires: [
'Admin.view.charts.Area',
'Admin.view.charts.Bar',
'Admin.view.charts.ChartsModel',
'Admin.view.charts.Gauge',
'Admin.view.charts.Pie3D',
'Admin.view.charts.Polar',
'Admin.view.charts.Stacked',
'Ext.ux.layout.ResponsiveColumn'
],
viewModel: {
type: 'charts'
},
layout: 'responsivecolumn',
defaults: {
defaults: {
animation : !Ext.isIE9m && Ext.os.is.Desktop
}
},
items: [
{
xtype: 'chartsareapanel',
userCls: 'big-50 small-100'
},
{
xtype: 'chartspie3dpanel',
userCls: 'big-50 small-100'
},
{
xtype: 'chartspolarpanel',
userCls: 'big-50 small-100'
},
{
xtype: 'chartsstackedpanel',
userCls: 'big-50 small-100'
},
{
xtype: 'chartsbarpanel',
userCls: 'big-50 small-100'
},
{
xtype: 'chartsgaugepanel',
userCls: 'big-50 small-100'
}
]
});
|
cadovid/Pandemia2019
|
src/java/player/Player.java
|
<filename>src/java/player/Player.java<gh_stars>1-10
package player;
import java.util.*;
import java.io.BufferedReader;
import java.io.FileReader;
import city.City;
import card.*;
import _aux.Options;
import _aux.CustomTypes;
/*
Player class
Represents a player object. Contains relevant information about its status
*/
public class Player {
public String alias;
public City city;
private Role prole;
public HashMap<String, CityCard> hand = new HashMap<String, CityCard>();
public boolean turn = false;
// Constructors
public Player(String alias) {
this.alias = alias;
}
public Player(String alias, City c, Role r) {
this.alias = alias;
this.city = c;
this.prole = r;
// Cross-reference. Role has a reference to the assigned player, so do the city
// in which is in
this.prole.bindPlayer(this);
this.city.putPlayer(this);
}
/*
* parsePlayers Initializes players from a datafile. Expected format (csv):
* <Alias>;<role>;<city>;
*
* Alias must be unique. It'll be used as identifier.
**
* PARAMETERS: datafile: String; path to file. roles: Role map; map containing
* existing roles. Will be used to maintain coherence with the game objects
* cities: City map; map containing existing cities. Will be used to maintain
* coherence with the game objects
*
*/
public static Hashtable<String, Player> parsePlayers(String datafile, Hashtable<String, Role> roles,
Hashtable<String, City> cities) {
Hashtable<String, Player> players = new Hashtable<String, Player>();
try {
BufferedReader br = new BufferedReader(new FileReader(datafile));
String line;
String[] player_data;
String player_alias;
String player_role_alias;
String player_city_alias;
Role player_role;
City player_city;
// Reads player data from subsequent lines (Must follow the expected disease
// format)
while ((line = br.readLine()) != null) {
player_data = line.split(";");
// Gets data from splitted line elements
player_alias = player_data[0];
player_role_alias = player_data[1];
player_city_alias = player_data[2];
// Checks game object coherence
if (players.containsKey(player_alias)) {
if (Options.LOG.ordinal() >= CustomTypes.LogLevel.WARN.ordinal())
System.out.printf("[Player] WARN: Player alias \"%s\" duplicated. Ignoring...\n", player_alias);
continue;
}
if (!roles.containsKey(player_role_alias)) {
if (Options.LOG.ordinal() >= CustomTypes.LogLevel.WARN.ordinal())
System.out.printf(
"[Player] WARN: Invalid role \"%s\" specified for player \"%s\". Ignoring...\n",
player_role_alias, player_alias);
continue;
}
if (!cities.containsKey(player_city_alias)) {
if (Options.LOG.ordinal() >= CustomTypes.LogLevel.WARN.ordinal())
System.out.printf(
"[Player] WARN: Invalid location \"%s\" specified for player \"%s\". Ignoring...\n",
player_city_alias, player_alias);
continue;
}
// Resolves fully quaalified Role and City objects by the alias int he file
player_role = roles.get(player_role_alias);
player_city = cities.get(player_city_alias);
// Creates Player object and adds it to the dictionary
Player player = new Player(player_alias, player_city, player_role);
players.put(player_alias, player);
if (Options.LOG.ordinal() >= CustomTypes.LogLevel.INFO.ordinal())
System.out.printf("[Player] INFO: New player added\n");
if (Options.LOG.ordinal() >= CustomTypes.LogLevel.DUMP.ordinal())
player.dump();
}
br.close();
} catch (Exception e) {
System.out.printf("CRITICAL: Exception while parsing\n");
System.err.println(e.getMessage());
System.exit(0);
}
// Binds players to game
return players;
}
/*
* Resolves player order based on initial player hand (as per the original game)
*/
public static ArrayList<String> resolvePlayerOrder(Hashtable<String, Player> players) {
// Target player order & aux hashtable used to identify the highest card of each
// player
ArrayList<String> p_order = new ArrayList<String>();
Hashtable<String, Integer> p_bestCard = new Hashtable<String, Integer>();
// Evaluates every card in the player hand
for (Player p : players.values()) {
if (p.hand == null) {
if (Options.LOG.ordinal() >= CustomTypes.LogLevel.CRITICAL.ordinal())
System.out
.printf("[Player] CRITICAL: Cannot resolve player order. At least a player have no hand\n");
return null;
}
// Iterates every card in the player hand to find the city with the highest
// population
int highest_population = 0;
for (CityCard c : p.hand.values()) {
if (c.city != null) {
int c_population = c.city.population;
// Evaluates city population against the highest found value
if (c_population > highest_population) {
highest_population = c_population;
}
}
}
// Resolves player highest population
p_bestCard.put(p.alias, highest_population);
// Evaluates ordered list and checks the highest city population of every sorted
// player
int sorted_index = 0;
for (String sorted_p : p_order) {
if (p_bestCard.get(sorted_p) < highest_population) {
break;
}
sorted_index++;
}
// Appends player in the right order
p_order.add(sorted_index, p.alias);
}
/*
* // Dummy order Set<String> p_alias = players.keySet(); for (String alias :
* p_alias) { p_order.add(alias); }
*/
return p_order;
}
// Setters/Getters
public City getCity() {
return this.city;
}
public void setCity(City c) {
// Keeps conherence. A player can only be in a single city
if (this.city != null) {
this.city.players.remove(this.alias);
}
this.city = c;
c.players.put(this.alias, this);
}
public HashMap<String, CityCard> getHand() {
return this.hand;
}
public void setRole(Role r) {
this.prole = r;
// Cross-reference. Role has a reference to the assigned player
prole.bindPlayer(this);
}
public Role getRole() {
return this.prole;
}
public CityCard removeCard(String c) {
return this.hand.remove(c);
}
public void addCard(CityCard c) {
if (c.getCity() != null) {
this.hand.put(c.getCity().alias, c);
}
}
// Dummy method to print disease data
public void dump() {
System.out.printf(">>Printing player data (%s)\n", this.alias);
System.out.printf(".Current location: %s\n", this.city.name);
System.out.printf(".Role: %s\n", this.prole.name);
System.out.println();
}
}
|
phil-davis/robotframework
|
src/robot/utils/recommendations.py
|
# Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# 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 difflib
class RecommendationFinder(object):
def __init__(self, normalizer=None):
self.normalizer = normalizer or (lambda x: x)
def find_recommendations(self, name, candidates, max_matches=10):
"""Return a list of close matches to `name` from `candidates`."""
if not name or not candidates:
return []
norm_name = self.normalizer(name)
norm_candidates = self._get_normalized_candidates(candidates)
cutoff = self._calculate_cutoff(norm_name)
norm_matches = difflib.get_close_matches(norm_name,
norm_candidates,
n=max_matches,
cutoff=cutoff)
return self._get_original_candidates(norm_candidates, norm_matches)
@staticmethod
def format_recommendations(msg, recommendations):
"""Add recommendations to the given message.
The recommendation string looks like:
<msg> Did you mean:
<recommendations[0]>
<recommendations[1]>
<recommendations[2]>
"""
if recommendations:
msg += " Did you mean:"
for rec in recommendations:
msg += "\n %s" % rec
return msg
def _get_normalized_candidates(self, candidates):
norm_candidates = {}
# sort before normalization for consistent Python/Jython ordering
for cand in sorted(candidates):
norm = self.normalizer(cand)
norm_candidates.setdefault(norm, []).append(cand)
return norm_candidates
def _get_original_candidates(self, norm_candidates, norm_matches):
candidates = []
for norm_match in norm_matches:
candidates.extend(norm_candidates[norm_match])
return candidates
def _calculate_cutoff(self, string, min_cutoff=.5, max_cutoff=.85,
step=.03):
"""Calculate a cutoff depending on string length.
Default values determined by manual tuning until the results
"look right".
"""
cutoff = min_cutoff + len(string) * step
return min(cutoff, max_cutoff)
|
trc492/Frc2011Logomotion
|
code/WPILib/CAN/can_proto.h
|
<gh_stars>0
//*****************************************************************************
//
// can_proto.h - Definitions for the CAN protocol used to communicate with the
// BDC motor controller.
//
// Copyright (c) 2008 Texas Instruments Incorporated. All rights reserved.
// TI Information - Selective Disclosure
//
//*****************************************************************************
#ifndef __CAN_PROTO_H__
#define __CAN_PROTO_H__
//*****************************************************************************
//
// The masks of the fields that are used in the message identifier.
//
//*****************************************************************************
#define CAN_MSGID_FULL_M 0x1fffffff
#define CAN_MSGID_DEVNO_M 0x0000003f
#define CAN_MSGID_API_M 0x0000ffc0
#define CAN_MSGID_MFR_M 0x00ff0000
#define CAN_MSGID_DTYPE_M 0x1f000000
#define CAN_MSGID_DEVNO_S 0
#define CAN_MSGID_API_S 6
#define CAN_MSGID_MFR_S 16
#define CAN_MSGID_DTYPE_S 24
//*****************************************************************************
//
// The Reserved device number values in the Message Id.
//
//*****************************************************************************
#define CAN_MSGID_DEVNO_BCAST 0x00000000
//*****************************************************************************
//
// The Reserved system control API numbers in the Message Id.
//
//*****************************************************************************
#define CAN_MSGID_API_SYSHALT 0x00000000
#define CAN_MSGID_API_SYSRST 0x00000040
#define CAN_MSGID_API_DEVASSIGN 0x00000080
#define CAN_MSGID_API_DEVQUERY 0x000000c0
#define CAN_MSGID_API_HEARTBEAT 0x00000140
#define CAN_MSGID_API_SYNC 0x00000180
#define CAN_MSGID_API_UPDATE 0x000001c0
#define CAN_MSGID_API_FIRMVER 0x00000200
#define CAN_MSGID_API_ENUMERATE 0x00000240
#define CAN_MSGID_API_SYSRESUME 0x00000280
//*****************************************************************************
//
// The 32 bit values associated with the CAN_MSGID_API_STATUS request.
//
//*****************************************************************************
#define CAN_STATUS_CODE_M 0x0000ffff
#define CAN_STATUS_MFG_M 0x00ff0000
#define CAN_STATUS_DTYPE_M 0x1f000000
#define CAN_STATUS_CODE_S 0
#define CAN_STATUS_MFG_S 16
#define CAN_STATUS_DTYPE_S 24
//*****************************************************************************
//
// The Reserved manufacturer identifiers in the Message Id.
//
//*****************************************************************************
#define CAN_MSGID_MFR_NI 0x00010000
#define CAN_MSGID_MFR_LM 0x00020000
#define CAN_MSGID_MFR_DEKA 0x00030000
//*****************************************************************************
//
// The Reserved device type identifiers in the Message Id.
//
//*****************************************************************************
#define CAN_MSGID_DTYPE_BCAST 0x00000000
#define CAN_MSGID_DTYPE_ROBOT 0x01000000
#define CAN_MSGID_DTYPE_MOTOR 0x02000000
#define CAN_MSGID_DTYPE_RELAY 0x03000000
#define CAN_MSGID_DTYPE_GYRO 0x04000000
#define CAN_MSGID_DTYPE_ACCEL 0x05000000
#define CAN_MSGID_DTYPE_USONIC 0x06000000
#define CAN_MSGID_DTYPE_GEART 0x07000000
#define CAN_MSGID_DTYPE_UPDATE 0x1f000000
//*****************************************************************************
//
// LM Motor Control API Classes API Class and ID masks.
//
//*****************************************************************************
#define CAN_MSGID_API_CLASS_M 0x0000fc00
#define CAN_MSGID_API_ID_M 0x000003c0
//*****************************************************************************
//
// LM Motor Control API Classes in the Message Id for non-broadcast.
// These are the upper 6 bits of the API field, the lower 4 bits determine
// the APIId.
//
//*****************************************************************************
#define CAN_API_MC_VOLTAGE 0x00000000
#define CAN_API_MC_SPD 0x00000400
#define CAN_API_MC_VCOMP 0x00000800
#define CAN_API_MC_POS 0x00000c00
#define CAN_API_MC_ICTRL 0x00001000
#define CAN_API_MC_STATUS 0x00001400
#define CAN_API_MC_CFG 0x00001c00
#define CAN_API_MC_ACK 0x00002000
//*****************************************************************************
//
// The Stellaris Motor Class Control Voltage API definitions.
//
//*****************************************************************************
#define LM_API_VOLT (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_VOLTAGE)
#define LM_API_VOLT_EN (LM_API_VOLT | (0 << CAN_MSGID_API_S))
#define LM_API_VOLT_DIS (LM_API_VOLT | (1 << CAN_MSGID_API_S))
#define LM_API_VOLT_SET (LM_API_VOLT | (2 << CAN_MSGID_API_S))
#define LM_API_VOLT_SET_RAMP (LM_API_VOLT | (3 << CAN_MSGID_API_S))
//##### FIRST BEGIN #####
#define LM_API_VOLT_T_EN (LM_API_VOLT | (4 << CAN_MSGID_API_S))
#define LM_API_VOLT_T_SET (LM_API_VOLT | (5 << CAN_MSGID_API_S))
//##### FIRST END #####
//*****************************************************************************
//
// The Stellaris Motor Class Control API definitions for LM_API_VOLT_SET_RAMP.
//
//*****************************************************************************
#define LM_API_VOLT_RAMP_DIS 0
//*****************************************************************************
//
// The Stellaris Motor Class Control API definitions for CAN_MSGID_API_SYNC.
//
//*****************************************************************************
#define LM_API_SYNC_PEND_NOW 0
//*****************************************************************************
//
// The Stellaris Motor Class Speed Control API definitions.
//
//*****************************************************************************
#define LM_API_SPD (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_SPD)
#define LM_API_SPD_EN (LM_API_SPD | (0 << CAN_MSGID_API_S))
#define LM_API_SPD_DIS (LM_API_SPD | (1 << CAN_MSGID_API_S))
#define LM_API_SPD_SET (LM_API_SPD | (2 << CAN_MSGID_API_S))
#define LM_API_SPD_PC (LM_API_SPD | (3 << CAN_MSGID_API_S))
#define LM_API_SPD_IC (LM_API_SPD | (4 << CAN_MSGID_API_S))
#define LM_API_SPD_DC (LM_API_SPD | (5 << CAN_MSGID_API_S))
#define LM_API_SPD_REF (LM_API_SPD | (6 << CAN_MSGID_API_S))
//##### FIRST BEGIN #####
#define LM_API_SPD_T_EN (LM_API_SPD | (7 << CAN_MSGID_API_S))
#define LM_API_SPD_T_SET (LM_API_SPD | (8 << CAN_MSGID_API_S))
//##### FIRST END #####
//*****************************************************************************
//
// The Stellaris Motor Control Voltage Compensation Control API definitions.
//
//*****************************************************************************
#define LM_API_VCOMP (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_VCOMP)
#define LM_API_VCOMP_EN (LM_API_VCOMP | (0 << CAN_MSGID_API_S))
#define LM_API_VCOMP_DIS (LM_API_VCOMP | (1 << CAN_MSGID_API_S))
#define LM_API_VCOMP_SET (LM_API_VCOMP | (2 << CAN_MSGID_API_S))
#define LM_API_VCOMP_IN_RAMP (LM_API_VCOMP | (3 << CAN_MSGID_API_S))
#define LM_API_VCOMP_COMP_RAMP (LM_API_VCOMP | (4 << CAN_MSGID_API_S))
//##### FIRST BEGIN #####
#define LM_API_VCOMP_T_EN (LM_API_VCOMP | (5 << CAN_MSGID_API_S))
#define LM_API_VCOMP_T_SET (LM_API_VCOMP | (6 << CAN_MSGID_API_S))
//##### FIRST END #####
//*****************************************************************************
//
// The Stellaris Motor Class Position Control API definitions.
//
//*****************************************************************************
#define LM_API_POS (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_POS)
#define LM_API_POS_EN (LM_API_POS | (0 << CAN_MSGID_API_S))
#define LM_API_POS_DIS (LM_API_POS | (1 << CAN_MSGID_API_S))
#define LM_API_POS_SET (LM_API_POS | (2 << CAN_MSGID_API_S))
#define LM_API_POS_PC (LM_API_POS | (3 << CAN_MSGID_API_S))
#define LM_API_POS_IC (LM_API_POS | (4 << CAN_MSGID_API_S))
#define LM_API_POS_DC (LM_API_POS | (5 << CAN_MSGID_API_S))
#define LM_API_POS_REF (LM_API_POS | (6 << CAN_MSGID_API_S))
//##### FIRST BEGIN #####
#define LM_API_POS_T_EN (LM_API_POS | (7 << CAN_MSGID_API_S))
#define LM_API_POS_T_SET (LM_API_POS | (8 << CAN_MSGID_API_S))
//##### FIRST END #####
//*****************************************************************************
//
// The Stellaris Motor Class Current Control API definitions.
//
//*****************************************************************************
#define LM_API_ICTRL (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_ICTRL)
#define LM_API_ICTRL_EN (LM_API_ICTRL | (0 << CAN_MSGID_API_S))
#define LM_API_ICTRL_DIS (LM_API_ICTRL | (1 << CAN_MSGID_API_S))
#define LM_API_ICTRL_SET (LM_API_ICTRL | (2 << CAN_MSGID_API_S))
#define LM_API_ICTRL_PC (LM_API_ICTRL | (3 << CAN_MSGID_API_S))
#define LM_API_ICTRL_IC (LM_API_ICTRL | (4 << CAN_MSGID_API_S))
#define LM_API_ICTRL_DC (LM_API_ICTRL | (5 << CAN_MSGID_API_S))
//##### FIRST BEGIN #####
#define LM_API_ICTRL_T_EN (LM_API_ICTRL | (6 << CAN_MSGID_API_S))
#define LM_API_ICTRL_T_SET (LM_API_ICTRL | (7 << CAN_MSGID_API_S))
//##### FIRST END #####
//*****************************************************************************
//
// The Stellaris Motor Class Firmware Update API definitions.
//
//*****************************************************************************
#define LM_API_UPD (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_UPDATE)
#define LM_API_UPD_PING (LM_API_UPD | (0 << CAN_MSGID_API_S))
#define LM_API_UPD_DOWNLOAD (LM_API_UPD | (1 << CAN_MSGID_API_S))
#define LM_API_UPD_SEND_DATA (LM_API_UPD | (2 << CAN_MSGID_API_S))
#define LM_API_UPD_RESET (LM_API_UPD | (3 << CAN_MSGID_API_S))
#define LM_API_UPD_ACK (LM_API_UPD | (4 << CAN_MSGID_API_S))
#define LM_API_HWVER (LM_API_UPD | (5 << CAN_MSGID_API_S))
#define LM_API_UPD_REQUEST (LM_API_UPD | (6 << CAN_MSGID_API_S))
//##### FIRST BEGIN #####
#define LM_API_UNTRUST_EN (LM_API_UPD | (11 << CAN_MSGID_API_S))
#define LM_API_TRUST_EN (LM_API_UPD | (12 << CAN_MSGID_API_S))
#define LM_API_TRUST_HEARTBEAT (LM_API_UPD | (13 << CAN_MSGID_API_S))
//##### FIRST END #####
//*****************************************************************************
//
// The Stellaris Motor Class Status API definitions.
//
//*****************************************************************************
#define LM_API_STATUS (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_STATUS)
#define LM_API_STATUS_VOLTOUT (LM_API_STATUS | (0 << CAN_MSGID_API_S))
#define LM_API_STATUS_VOLTBUS (LM_API_STATUS | (1 << CAN_MSGID_API_S))
#define LM_API_STATUS_CURRENT (LM_API_STATUS | (2 << CAN_MSGID_API_S))
#define LM_API_STATUS_TEMP (LM_API_STATUS | (3 << CAN_MSGID_API_S))
#define LM_API_STATUS_POS (LM_API_STATUS | (4 << CAN_MSGID_API_S))
#define LM_API_STATUS_SPD (LM_API_STATUS | (5 << CAN_MSGID_API_S))
#define LM_API_STATUS_LIMIT (LM_API_STATUS | (6 << CAN_MSGID_API_S))
#define LM_API_STATUS_FAULT (LM_API_STATUS | (7 << CAN_MSGID_API_S))
#define LM_API_STATUS_POWER (LM_API_STATUS | (8 << CAN_MSGID_API_S))
#define LM_API_STATUS_CMODE (LM_API_STATUS | (9 << CAN_MSGID_API_S))
#define LM_API_STATUS_VOUT (LM_API_STATUS | (10 << CAN_MSGID_API_S))
//*****************************************************************************
//
// These definitions are used with the byte that is returned from
// the status request for LM_API_STATUS_LIMIT.
//
//*****************************************************************************
#define LM_STATUS_LIMIT_FWD 0x01
#define LM_STATUS_LIMIT_REV 0x02
//*****************************************************************************
//
// LM Motor Control status codes returned due to the CAN_STATUS_CODE_M field.
//
//*****************************************************************************
#define LM_STATUS_FAULT_ILIMIT 0x01
#define LM_STATUS_FAULT_TLIMIT 0x02
#define LM_STATUS_FAULT_VLIMIT 0x04
//*****************************************************************************
//
// The Stellaris Motor Class Configuration API definitions.
//
//*****************************************************************************
#define LM_API_CFG (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_CFG)
#define LM_API_CFG_NUM_BRUSHES (LM_API_CFG | (0 << CAN_MSGID_API_S))
#define LM_API_CFG_ENC_LINES (LM_API_CFG | (1 << CAN_MSGID_API_S))
#define LM_API_CFG_POT_TURNS (LM_API_CFG | (2 << CAN_MSGID_API_S))
#define LM_API_CFG_BRAKE_COAST (LM_API_CFG | (3 << CAN_MSGID_API_S))
#define LM_API_CFG_LIMIT_MODE (LM_API_CFG | (4 << CAN_MSGID_API_S))
#define LM_API_CFG_LIMIT_FWD (LM_API_CFG | (5 << CAN_MSGID_API_S))
#define LM_API_CFG_LIMIT_REV (LM_API_CFG | (6 << CAN_MSGID_API_S))
#define LM_API_CFG_MAX_VOUT (LM_API_CFG | (7 << CAN_MSGID_API_S))
#define LM_API_CFG_FAULT_TIME (LM_API_CFG | (8 << CAN_MSGID_API_S))
//*****************************************************************************
//
// The Stellaris ACK API definition.
//
//*****************************************************************************
#define LM_API_ACK (CAN_MSGID_MFR_LM | CAN_MSGID_DTYPE_MOTOR | \
CAN_API_MC_ACK)
//*****************************************************************************
//
// The 8 bit values that can be returned by a call to LM_API_STATUS_HWVER.
//
//*****************************************************************************
#define LM_HWVER_UNKNOWN 0x00
#define LM_HWVER_JAG_1_0 0x01
#define LM_HWVER_JAG_2_0 0x02
//*****************************************************************************
//
// The 8 bit values that can be returned by a call to LM_API_STATUS_CMODE.
//
//*****************************************************************************
#define LM_STATUS_CMODE_VOLT 0x00
#define LM_STATUS_CMODE_CURRENT 0x01
#define LM_STATUS_CMODE_SPEED 0x02
#define LM_STATUS_CMODE_POS 0x03
#define LM_STATUS_CMODE_VCOMP 0x04
//*****************************************************************************
//
// The values that can specified as the position or speed reference. Not all
// values are valid for each reference; if an invalid reference is set, then
// none will be selected.
//
//*****************************************************************************
#define LM_REF_ENCODER 0x00
#define LM_REF_POT 0x01
#define LM_REF_INV_ENCODER 0x02
#define LM_REF_QUAD_ENCODER 0x03
#define LM_REF_NONE 0xff
//*****************************************************************************
//
// The flags that are used to indicate the currently active fault sources.
//
//*****************************************************************************
#define LM_FAULT_CURRENT 0x01
#define LM_FAULT_TEMP 0x02
#define LM_FAULT_VBUS 0x04
#define LM_FAULT_GATE_DRIVE 0x08
#endif // __CAN_PROTO_H__
|
QuVideoDeveloper/QVEditorKit-iOS
|
QVEditorKit/FrameWork/Editor/QVMediCameraEngine.framework/Versions/A/Headers/QVMediCameraEngineUtils.h
|
//
// QVMediCameraEngineUtils.h
// QVMediCameraEngine
//
// Created by 徐新元 on 2020/4/21.
//
#import <Foundation/Foundation.h>
#import "QVMediCameraFaceBeatyModel.h"
NS_ASSUME_NONNULL_BEGIN
@interface QVMediCameraEngineUtils : NSObject
+ (MRECT)ceDisplayPixelRectWithExportFrameSize:(MSIZE)ceExportFrameSize
renderSize:(MSIZE)ceRenderSize
renderOffset:(MSIZE)ceRenderOffset
deviceOrientation:(UIDeviceOrientation)deviceOrientation
previewView:(UIView *)previewView;
+ (MRECT)ceWorkRectWithDeviceFrameSize:(MSIZE)ceDeviceFrameSize
exportFrameSize:(MSIZE)ceExportFrameSize
deviceOrientation:(UIDeviceOrientation)deviceOrientation;
+ (XYCE_PROCESS_RECT_INFO)ceDisplayRectInfoWithExportFrameSize:(MSIZE)ceExportFrameSize
renderSize:(MSIZE)ceRenderSize
deviceOrientation:(UIDeviceOrientation)deviceOrientation;
+ (MSIZE)ceExportFrameSizeWithOutputResolutionSize:(CGSize)outputResolutionSize
deviceOrientation:(UIDeviceOrientation)deviceOrientation;
+ (QVMediCameraFaceBeatyModel *)faceBeautyModelWithTemplatePath:(NSString *)templatePath
templateID:(NSInteger)templateID
cXiaoYingEngine:(CXiaoYingEngine *)cXiaoYingEngine;
@end
NS_ASSUME_NONNULL_END
|
simonjjones/atc
|
engine/exec_engine_build_delegate_test.go
|
<gh_stars>1-10
package engine_test
import (
"errors"
"io"
"time"
"github.com/concourse/atc"
"github.com/concourse/atc/db"
. "github.com/concourse/atc/engine"
"github.com/concourse/atc/engine/fakes"
"github.com/concourse/atc/event"
"github.com/concourse/atc/exec"
"github.com/pivotal-golang/lager/lagertest"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("BuildDelegate", func() {
var (
fakeDB *fakes.FakeEngineDB
factory BuildDelegateFactory
buildID int
delegate BuildDelegate
logger *lagertest.TestLogger
location event.OriginLocation
)
BeforeEach(func() {
fakeDB = new(fakes.FakeEngineDB)
factory = NewBuildDelegateFactory(fakeDB)
buildID = 42
delegate = factory.Delegate(buildID)
logger = lagertest.NewTestLogger("test")
location = event.OriginLocation{
ParentID: 0,
ID: 3,
ParallelGroup: 1,
Hook: "some-hook",
}
})
Describe("InputDelegate", func() {
var (
getPlan atc.GetPlan
inputDelegate exec.GetDelegate
)
BeforeEach(func() {
getPlan = atc.GetPlan{
Name: "some-input",
Resource: "some-input-resource",
Pipeline: "some-pipeline",
Type: "some-type",
Version: atc.Version{"some": "version"},
Source: atc.Source{"some": "source"},
Params: atc.Params{"some": "params"},
}
inputDelegate = delegate.InputDelegate(logger, getPlan, location)
})
Describe("Completed", func() {
var versionInfo *exec.VersionInfo
BeforeEach(func() {
versionInfo = &exec.VersionInfo{
Version: atc.Version{"result": "version"},
Metadata: []atc.MetadataField{{"result", "metadata"}},
}
})
Context("when exit status is not 0", func() {
JustBeforeEach(func() {
inputDelegate.Completed(exec.ExitStatus(12), versionInfo)
})
It("saves the build's input", func() {
Ω(fakeDB.SaveBuildInputCallCount()).Should(Equal(1))
buildID, savedInput := fakeDB.SaveBuildInputArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedInput).Should(Equal(db.BuildInput{
Name: "some-input",
VersionedResource: db.VersionedResource{
PipelineName: "some-pipeline",
Resource: "some-input-resource",
Type: "some-type",
Version: db.Version{"result": "version"},
Metadata: []db.MetadataField{{"result", "metadata"}},
},
}))
})
It("saves a finish-get event", func() {
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
buildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedEvent).Should(Equal(event.FinishGet{
Origin: event.Origin{
Type: event.OriginTypeGet,
Name: "some-input",
Location: location,
},
Plan: event.GetPlan{
Name: "some-input",
Resource: "some-input-resource",
Type: "some-type",
Version: atc.Version{"some": "version"},
},
ExitStatus: 12,
FetchedVersion: versionInfo.Version,
FetchedMetadata: versionInfo.Metadata,
}))
})
})
Context("when the version is null", func() {
JustBeforeEach(func() {
inputDelegate.Completed(exec.ExitStatus(12), nil)
})
It("does not save the build's input", func() {
Ω(fakeDB.SaveBuildInputCallCount()).Should(Equal(0))
})
It("saves a finish-get event", func() {
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
buildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedEvent).Should(Equal(event.FinishGet{
Origin: event.Origin{
Type: event.OriginTypeGet,
Name: "some-input",
Location: location,
},
Plan: event.GetPlan{
Name: "some-input",
Resource: "some-input-resource",
Type: "some-type",
Version: atc.Version{"some": "version"},
},
ExitStatus: 12,
FetchedVersion: nil,
FetchedMetadata: nil,
}))
})
})
Describe("Finish", func() {
var (
finishErr error
aborted bool
succeeded exec.Success
)
Context("without error", func() {
BeforeEach(func() {
finishErr = nil
})
Context("when it was told it failed", func() {
BeforeEach(func() {
succeeded = false
aborted = false
})
It("finishes with status 'failed'", func() {
delegate.Finish(logger, finishErr, succeeded, aborted)
Ω(fakeDB.FinishBuildCallCount()).Should(Equal(1))
buildID, savedStatus := fakeDB.FinishBuildArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedStatus).Should(Equal(db.StatusFailed))
})
})
Context("when it was told it succeeded", func() {
BeforeEach(func() {
succeeded = true
})
It("finishes with status 'succeeded'", func() {
delegate.Finish(logger, finishErr, succeeded, aborted)
Ω(fakeDB.FinishBuildCallCount()).Should(Equal(1))
buildID, savedStatus := fakeDB.FinishBuildArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedStatus).Should(Equal(db.StatusSucceeded))
})
})
})
Context("when exit status is 0", func() {
BeforeEach(func() {
inputDelegate.Completed(exec.ExitStatus(0), versionInfo)
})
It("saves the build's input", func() {
Ω(fakeDB.SaveBuildInputCallCount()).Should(Equal(1))
buildID, savedInput := fakeDB.SaveBuildInputArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedInput).Should(Equal(db.BuildInput{
Name: "some-input",
VersionedResource: db.VersionedResource{
PipelineName: "some-pipeline",
Resource: "some-input-resource",
Type: "some-type",
Version: db.Version{"result": "version"},
Metadata: []db.MetadataField{{"result", "metadata"}},
},
}))
})
It("saves a finish-get event", func() {
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
buildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedEvent).Should(Equal(event.FinishGet{
Origin: event.Origin{
Type: event.OriginTypeGet,
Name: "some-input",
Location: location,
},
Plan: event.GetPlan{
Name: "some-input",
Resource: "some-input-resource",
Type: "some-type",
Version: atc.Version{"some": "version"},
},
FetchedVersion: versionInfo.Version,
FetchedMetadata: versionInfo.Metadata,
}))
})
Context("when the resource only occurs as an input", func() {
Describe("Finish", func() {
var (
finishErr error
aborted bool
succeeded exec.Success
)
Context("with success", func() {
BeforeEach(func() {
finishErr = nil
succeeded = true
aborted = false
})
It("saves the input as an implicit output", func() {
delegate.Finish(logger, finishErr, succeeded, aborted)
Ω(fakeDB.SaveBuildOutputCallCount()).Should(Equal(1))
buildID, savedOutput, explicit := fakeDB.SaveBuildOutputArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedOutput).Should(Equal(db.VersionedResource{
PipelineName: "some-pipeline",
Resource: "some-input-resource",
Type: "some-type",
Source: db.Source{"some": "source"},
Version: db.Version{"result": "version"},
Metadata: []db.MetadataField{{"result", "metadata"}},
}))
Ω(explicit).Should(BeFalse())
})
})
Context("with failure", func() {
disaster := errors.New("nope")
BeforeEach(func() {
finishErr = disaster
succeeded = false
})
It("does not save the input as an implicit output", func() {
delegate.Finish(logger, finishErr, succeeded, aborted)
Ω(fakeDB.SaveBuildOutputCallCount()).Should(BeZero())
})
})
})
})
Context("when the same resource occurs as an explicit output", func() {
var (
putPlan atc.PutPlan
outputDelegate exec.PutDelegate
)
BeforeEach(func() {
putPlan = atc.PutPlan{
Pipeline: "some-pipeline",
Resource: "some-input-resource",
Type: "some-type",
Source: atc.Source{"some": "source"},
Params: atc.Params{"some": "output-params"},
}
outputDelegate = delegate.OutputDelegate(logger, putPlan, location)
})
JustBeforeEach(func() {
outputDelegate.Completed(exec.ExitStatus(0), &exec.VersionInfo{
Version: atc.Version{"explicit": "version"},
Metadata: []atc.MetadataField{{"explicit", "metadata"}},
})
})
Describe("Finish", func() {
var (
finishErr error
succeeded exec.Success
)
BeforeEach(func() {
finishErr = nil
succeeded = true
})
It("only saves the explicit output", func() {
delegate.Finish(logger, finishErr, succeeded, aborted)
Ω(fakeDB.SaveBuildOutputCallCount()).Should(Equal(1))
buildID, savedOutput, explicit := fakeDB.SaveBuildOutputArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedOutput).Should(Equal(db.VersionedResource{
PipelineName: "some-pipeline",
Resource: "some-input-resource",
Type: "some-type",
Version: db.Version{"explicit": "version"},
Metadata: []db.MetadataField{{"explicit", "metadata"}},
}))
Ω(explicit).Should(BeTrue())
})
})
})
})
})
})
Describe("Failed", func() {
JustBeforeEach(func() {
inputDelegate.Failed(errors.New("nope"))
})
It("does not save the build's input", func() {
Ω(fakeDB.SaveBuildInputCallCount()).Should(BeZero())
})
It("saves an error event", func() {
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
buildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedEvent).Should(Equal(event.Error{
Origin: event.Origin{
Type: event.OriginTypeGet,
Name: "some-input",
Location: location,
},
Message: "nope",
}))
})
})
Describe("Stdout", func() {
var writer io.Writer
BeforeEach(func() {
writer = inputDelegate.Stdout()
})
It("saves log events with the input's origin", func() {
_, err := writer.Write([]byte("some stdout"))
Ω(err).ShouldNot(HaveOccurred())
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
savedBuildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(savedBuildID).Should(Equal(buildID))
Ω(savedEvent).Should(Equal(event.Log{
Origin: event.Origin{
Type: event.OriginTypeGet,
Name: "some-input",
Source: event.OriginSourceStdout,
Location: location,
},
Payload: "some stdout",
}))
})
})
Describe("Stderr", func() {
var writer io.Writer
BeforeEach(func() {
writer = inputDelegate.Stderr()
})
It("saves log events with the input's origin", func() {
_, err := writer.Write([]byte("some stderr"))
Ω(err).ShouldNot(HaveOccurred())
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
savedBuildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(savedBuildID).Should(Equal(buildID))
Ω(savedEvent).Should(Equal(event.Log{
Origin: event.Origin{
Type: event.OriginTypeGet,
Name: "some-input",
Source: event.OriginSourceStderr,
Location: location,
},
Payload: "some stderr",
}))
})
})
})
Describe("ExecutionDelegate", func() {
var (
taskPlan atc.TaskPlan
executionDelegate exec.TaskDelegate
)
BeforeEach(func() {
taskPlan = atc.TaskPlan{
Name: "some-task",
Privileged: true,
ConfigPath: "/etc/concourse/config.yml",
}
executionDelegate = delegate.ExecutionDelegate(logger, taskPlan, location)
})
Describe("Initializing", func() {
var taskConfig atc.TaskConfig
BeforeEach(func() {
taskConfig = atc.TaskConfig{
Run: atc.TaskRunConfig{
Path: "ls",
},
}
})
JustBeforeEach(func() {
executionDelegate.Initializing(taskConfig)
})
It("saves an initialize event", func() {
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
buildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedEvent).Should(Equal(event.InitializeTask{
TaskConfig: event.TaskConfig{
Run: event.TaskRunConfig{
Path: "ls",
},
},
Origin: event.Origin{
Type: event.OriginTypeTask,
Name: "some-task",
Location: location,
},
}))
})
})
Describe("Started", func() {
JustBeforeEach(func() {
executionDelegate.Started()
})
It("saves a start event", func() {
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
buildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedEvent).Should(BeAssignableToTypeOf(event.StartTask{}))
Ω(savedEvent.(event.StartTask).Time).Should(BeNumerically("~", time.Now().Unix(), 1))
Ω(savedEvent.(event.StartTask).Origin).Should(Equal(event.Origin{
Type: event.OriginTypeTask,
Name: "some-task",
Location: location,
}))
})
})
Describe("Finished", func() {
var exitStatus exec.ExitStatus
JustBeforeEach(func() {
executionDelegate.Finished(exitStatus)
})
Context("with a successful result", func() {
BeforeEach(func() {
exitStatus = 0
})
It("saves a finish event", func() {
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
buildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedEvent).Should(BeAssignableToTypeOf(event.FinishTask{}))
Ω(savedEvent.(event.FinishTask).ExitStatus).Should(Equal(0))
Ω(savedEvent.(event.FinishTask).Time).Should(BeNumerically("<=", time.Now().Unix(), 1))
Ω(savedEvent.(event.FinishTask).Origin).Should(Equal(event.Origin{
Type: event.OriginTypeTask,
Name: "some-task",
Location: location,
}))
})
Describe("Finish", func() {
var (
finishErr error
aborted bool
succeeded exec.Success
)
Context("with success", func() {
BeforeEach(func() {
finishErr = nil
succeeded = true
aborted = false
})
It("finishes with status 'succeeded'", func() {
delegate.Finish(logger, finishErr, succeeded, aborted)
Ω(fakeDB.FinishBuildCallCount()).Should(Equal(1))
buildID, savedStatus := fakeDB.FinishBuildArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedStatus).Should(Equal(db.StatusSucceeded))
})
})
Context("with failure", func() {
disaster := errors.New("nope")
BeforeEach(func() {
finishErr = disaster
succeeded = false
})
It("finishes with status 'errored'", func() {
delegate.Finish(logger, finishErr, succeeded, aborted)
Ω(fakeDB.FinishBuildCallCount()).Should(Equal(1))
buildID, savedStatus := fakeDB.FinishBuildArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedStatus).Should(Equal(db.StatusErrored))
})
})
})
})
Context("with a failed result", func() {
BeforeEach(func() {
exitStatus = 1
})
It("saves a finish event", func() {
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
buildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedEvent).Should(BeAssignableToTypeOf(event.FinishTask{}))
Ω(savedEvent.(event.FinishTask).ExitStatus).Should(Equal(1))
Ω(savedEvent.(event.FinishTask).Time).Should(BeNumerically("<=", time.Now().Unix(), 1))
Ω(savedEvent.(event.FinishTask).Origin).Should(Equal(event.Origin{
Type: event.OriginTypeTask,
Name: "some-task",
Location: location,
}))
})
})
})
Describe("Failed", func() {
JustBeforeEach(func() {
executionDelegate.Failed(errors.New("nope"))
})
It("does not save the build's input", func() {
Ω(fakeDB.SaveBuildInputCallCount()).Should(BeZero())
})
It("saves an error event", func() {
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
buildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedEvent).Should(Equal(event.Error{
Message: "nope",
Origin: event.Origin{
Type: event.OriginTypeTask,
Name: "some-task",
Location: location,
},
}))
})
})
Describe("Stdout", func() {
var writer io.Writer
BeforeEach(func() {
writer = executionDelegate.Stdout()
})
It("saves log events with the correct origin", func() {
_, err := writer.Write([]byte("some stdout"))
Ω(err).ShouldNot(HaveOccurred())
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
savedBuildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(savedBuildID).Should(Equal(buildID))
Ω(savedEvent).Should(Equal(event.Log{
Origin: event.Origin{
Type: event.OriginTypeTask,
Name: "some-task",
Source: event.OriginSourceStdout,
Location: location,
},
Payload: "some stdout",
}))
})
})
Describe("Stderr", func() {
var writer io.Writer
BeforeEach(func() {
writer = executionDelegate.Stderr()
})
It("saves log events with the correct origin", func() {
_, err := writer.Write([]byte("some stderr"))
Ω(err).ShouldNot(HaveOccurred())
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
savedBuildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(savedBuildID).Should(Equal(buildID))
Ω(savedEvent).Should(Equal(event.Log{
Origin: event.Origin{
Type: event.OriginTypeTask,
Name: "some-task",
Source: event.OriginSourceStderr,
Location: location,
},
Payload: "some stderr",
}))
})
})
})
Describe("OutputDelegate", func() {
var (
putPlan atc.PutPlan
outputDelegate exec.PutDelegate
)
BeforeEach(func() {
putPlan = atc.PutPlan{
Name: "some-output-name",
Resource: "some-output-resource",
Pipeline: "some-other-pipeline",
Type: "some-type",
Source: atc.Source{"some": "source"},
Params: atc.Params{"some": "params"},
}
outputDelegate = delegate.OutputDelegate(logger, putPlan, location)
})
Describe("Completed", func() {
var versionInfo *exec.VersionInfo
BeforeEach(func() {
versionInfo = &exec.VersionInfo{
Version: atc.Version{"result": "version"},
Metadata: []atc.MetadataField{{"result", "metadata"}},
}
})
Context("when the version info is nil", func() {
JustBeforeEach(func() {
outputDelegate.Completed(exec.ExitStatus(0), nil)
})
It("does not save the build's output", func() {
Ω(fakeDB.SaveBuildOutputCallCount()).Should(Equal(0))
})
It("saves an output event", func() {
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
buildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedEvent).Should(Equal(event.FinishPut{
Origin: event.Origin{
Type: event.OriginTypePut,
Name: "some-output-name",
Location: location,
},
Plan: event.PutPlan{
Name: "some-output-name",
Resource: "some-output-resource",
Type: "some-type",
},
ExitStatus: 0,
CreatedVersion: nil,
CreatedMetadata: nil,
}))
})
})
Context("when exit status is 0", func() {
JustBeforeEach(func() {
outputDelegate.Completed(exec.ExitStatus(0), versionInfo)
})
It("saves the build's output", func() {
Ω(fakeDB.SaveBuildOutputCallCount()).Should(Equal(1))
buildID, savedOutput, explicit := fakeDB.SaveBuildOutputArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedOutput).Should(Equal(db.VersionedResource{
PipelineName: "some-other-pipeline",
Resource: "some-output-resource",
Type: "some-type",
Version: db.Version{"result": "version"},
Metadata: []db.MetadataField{{"result", "metadata"}},
}))
Ω(explicit).Should(BeTrue())
})
It("saves an output event", func() {
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
buildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedEvent).Should(Equal(event.FinishPut{
Origin: event.Origin{
Type: event.OriginTypePut,
Name: "some-output-name",
Location: location,
},
Plan: event.PutPlan{
Name: "some-output-name",
Resource: "some-output-resource",
Type: "some-type",
},
CreatedVersion: versionInfo.Version,
CreatedMetadata: versionInfo.Metadata,
ExitStatus: 0,
}))
})
})
Context("when exit status is not 0", func() {
JustBeforeEach(func() {
outputDelegate.Completed(exec.ExitStatus(72), versionInfo)
})
It("saves the build's output", func() {
Ω(fakeDB.SaveBuildOutputCallCount()).Should(Equal(1))
buildID, savedOutput, explicit := fakeDB.SaveBuildOutputArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedOutput).Should(Equal(db.VersionedResource{
PipelineName: "some-other-pipeline",
Resource: "some-output-resource",
Type: "some-type",
Version: db.Version{"result": "version"},
Metadata: []db.MetadataField{{"result", "metadata"}},
}))
Ω(explicit).Should(BeTrue())
})
It("saves an output event", func() {
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
buildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedEvent).Should(Equal(event.FinishPut{
Origin: event.Origin{
Type: event.OriginTypePut,
Name: "some-output-name",
Location: location,
},
Plan: event.PutPlan{
Name: "some-output-name",
Resource: "some-output-resource",
Type: "some-type",
},
CreatedVersion: versionInfo.Version,
CreatedMetadata: versionInfo.Metadata,
ExitStatus: 72,
}))
})
})
Describe("Finish", func() {
var (
finishErr error
aborted bool
succeeded exec.Success
)
Context("without error", func() {
BeforeEach(func() {
finishErr = nil
})
Context("when it was told it succeeded", func() {
BeforeEach(func() {
succeeded = true
aborted = false
})
It("finishes with status 'failed'", func() {
delegate.Finish(logger, finishErr, succeeded, aborted)
Ω(fakeDB.FinishBuildCallCount()).Should(Equal(1))
buildID, savedStatus := fakeDB.FinishBuildArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedStatus).Should(Equal(db.StatusSucceeded))
})
})
Context("when it was told it failed", func() {
BeforeEach(func() {
succeeded = false
})
It("finishes with status 'failed'", func() {
delegate.Finish(logger, finishErr, succeeded, aborted)
Ω(fakeDB.FinishBuildCallCount()).Should(Equal(1))
buildID, savedStatus := fakeDB.FinishBuildArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedStatus).Should(Equal(db.StatusFailed))
})
})
})
})
})
Describe("Failed", func() {
JustBeforeEach(func() {
outputDelegate.Failed(errors.New("nope"))
})
It("does not save the build's input", func() {
Ω(fakeDB.SaveBuildInputCallCount()).Should(BeZero())
})
It("saves an error event", func() {
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
buildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedEvent).Should(Equal(event.Error{
Origin: event.Origin{
Type: event.OriginTypePut,
Name: "some-output-name",
Location: location,
},
Message: "nope",
}))
})
})
Describe("Stdout", func() {
var writer io.Writer
BeforeEach(func() {
writer = outputDelegate.Stdout()
})
It("saves log events with the output's origin", func() {
_, err := writer.Write([]byte("some stdout"))
Ω(err).ShouldNot(HaveOccurred())
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
savedBuildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(savedBuildID).Should(Equal(buildID))
Ω(savedEvent).Should(Equal(event.Log{
Origin: event.Origin{
Type: event.OriginTypePut,
Name: "some-output-name",
Source: event.OriginSourceStdout,
Location: location,
},
Payload: "some stdout",
}))
})
})
Describe("Stderr", func() {
var writer io.Writer
BeforeEach(func() {
writer = outputDelegate.Stderr()
})
It("saves log events with the output's origin", func() {
_, err := writer.Write([]byte("some stderr"))
Ω(err).ShouldNot(HaveOccurred())
Ω(fakeDB.SaveBuildEventCallCount()).Should(Equal(1))
savedBuildID, savedEvent := fakeDB.SaveBuildEventArgsForCall(0)
Ω(savedBuildID).Should(Equal(buildID))
Ω(savedEvent).Should(Equal(event.Log{
Origin: event.Origin{
Type: event.OriginTypePut,
Name: "some-output-name",
Source: event.OriginSourceStderr,
Location: location,
},
Payload: "some stderr",
}))
})
})
})
Describe("Aborted", func() {
var aborted bool
JustBeforeEach(func() {
aborted = true
})
Describe("Finish", func() {
var (
finishErr error
succeeded exec.Success
// aborted bool
)
Context("with success", func() {
BeforeEach(func() {
finishErr = nil
succeeded = true
})
It("finishes with status 'aborted'", func() {
delegate.Finish(logger, finishErr, succeeded, aborted)
Ω(fakeDB.FinishBuildCallCount()).Should(Equal(1))
buildID, savedStatus := fakeDB.FinishBuildArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedStatus).Should(Equal(db.StatusAborted))
})
})
Context("with failure", func() {
disaster := errors.New("nope")
BeforeEach(func() {
finishErr = disaster
succeeded = false
})
It("finishes with status 'aborted'", func() {
delegate.Finish(logger, finishErr, succeeded, aborted)
Ω(fakeDB.FinishBuildCallCount()).Should(Equal(1))
buildID, savedStatus := fakeDB.FinishBuildArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedStatus).Should(Equal(db.StatusAborted))
})
})
})
})
Describe("Timed out", func() {
Describe("Finish", func() {
var (
timeoutErr error
succeeded exec.Success
)
Context("With only a timeout error", func() {
BeforeEach(func() {
timeoutErr = exec.ErrStepTimedOut
succeeded = false
})
It("finishes with status 'failed'", func() {
delegate.Finish(logger, timeoutErr, succeeded, false)
Ω(fakeDB.FinishBuildCallCount()).Should(Equal(1))
buildID, savedStatus := fakeDB.FinishBuildArgsForCall(0)
Ω(buildID).Should(Equal(42))
Ω(savedStatus).Should(Equal(db.StatusFailed))
})
})
})
})
})
|
TMorozovsky/Generic_Tools_for_Frequent_Operations
|
gtfo_testing/static/are_addable.cpp
|
#include "gtfo/_impl/type_traits/are_addable.hpp"
#include "gtfo/_impl/type_traits/is_compound_addable.hpp"
#define GTFO_ARE_ADDABLE(t1,t2) ::gtfo::_tt::are_addable<t1,t2>::value
#define GTFO_IS_COMPOUND_ADDABLE(t1,t2) ::gtfo::_tt::is_compound_addable<t1,t2>::value
#ifdef __clang__
# define UNUSED __attribute__((unused))
#else
# define UNUSED
#endif
namespace
{
struct X { };
struct Y { };
inline UNUSED bool operator + (X, Y) { return true; }
inline UNUSED bool operator += (X, Y) { return true; }
inline UNUSED bool operator += (Y &, X) { return true; }
}
static_assert(GTFO_ARE_ADDABLE(int, int), "");
static_assert(GTFO_ARE_ADDABLE(int, int &), "");
static_assert(GTFO_ARE_ADDABLE(int, const volatile int &), "");
static_assert(GTFO_ARE_ADDABLE(int, float), "");
static_assert(GTFO_ARE_ADDABLE(int &, const volatile long double &), "");
static_assert(!GTFO_ARE_ADDABLE(float &, void *), "");
static_assert(GTFO_ARE_ADDABLE(X, Y &), "");
static_assert(GTFO_ARE_ADDABLE(X &, Y), "");
static_assert(GTFO_ARE_ADDABLE(X, Y), "");
static_assert(!GTFO_ARE_ADDABLE(X, X), "");
static_assert(!GTFO_ARE_ADDABLE(Y, X), "");
static_assert(!GTFO_IS_COMPOUND_ADDABLE(int, void), "");
static_assert( GTFO_IS_COMPOUND_ADDABLE(int, int), "");
static_assert( GTFO_IS_COMPOUND_ADDABLE(X, Y), "");
static_assert( GTFO_IS_COMPOUND_ADDABLE(Y, X), "");
|
oanc/org.anc.lapps.oauth
|
org.anc.lapps.oauth.masc-server/src/main/java/org/anc/lapps/oauth/web/UserData.java
|
package org.anc.lapps.oauth.web;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* @author <NAME>
*/
public class UserData
{
protected String username;
protected String password1;
protected String password2;
protected String email;
protected List<String> roles;
protected String authorities;
protected boolean editable;
public UserData()
{
roles = new ArrayList<>();
editable = true;
}
public void build()
{
StringBuilder buffer = new StringBuilder();
Iterator<String> iterator = roles.iterator();
if (iterator.hasNext())
{
buffer.append(iterator.next().replace("ROLE_", ""));
}
while (iterator.hasNext())
{
buffer.append(", ");
buffer.append(iterator.next().replace("ROLE_", ""));
}
authorities = buffer.toString();
}
public void setUsername(String username)
{
this.username = username;
if (username.equals("admin") || username.equals("anonymous"))
{
editable = false;
}
}
public String getUsername()
{
return username;
}
public String getPassword1()
{
return password1;
}
public void setPassword1(String password1)
{
this.password1 = <PASSWORD>;
}
public String getPassword2()
{
return password2;
}
public void setPassword2(String password2)
{
this.password2 = password2;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public List<String> getRoles() { return roles; }
public void setRoles(List<String> roles) { this.roles = roles; }
public void addRole(String role)
{
roles.add(role);
}
public void addRoles(List<String> roles)
{
roles.addAll(roles);
}
public String getAuthorities()
{
return authorities;
}
public boolean isEditable()
{
return editable;
}
}
|
miliracle/food-delivery
|
main.go
|
package main
import (
"fooddelivery/common"
"fooddelivery/component/appctx"
"fooddelivery/component/uploadprovider"
"fooddelivery/middleware"
"fooddelivery/module/image/imagetransport/ginimage"
"fooddelivery/module/restaurant/restauranttransport/ginrestaurent"
"fooddelivery/module/user/userstorage"
"fooddelivery/module/user/usertransport/ginuser"
"log"
"net/http"
"github.com/gin-gonic/gin"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func main() {
dbConStr := common.CONFIG.DB_URI
db, err := gorm.Open(mysql.Open(dbConStr), &gorm.Config{})
if err != nil {
log.Fatalln(err)
}
GCPCentificateFilePath := common.CONFIG.GOOGLE_APPLICATION_CREDENTIALS
CloudStorageBucketName := common.CONFIG.GOOGLE_CLOUD_STORAGE_BUCKET_NAME
uploadProvider, err := uploadprovider.NewGCPCloudStorageProvider(CloudStorageBucketName, GCPCentificateFilePath)
if err != nil {
log.Fatalln(err)
}
appCtx := appctx.NewAppContext(db, uploadProvider, common.CONFIG.SECRET_KEY)
if err := runService(appCtx); err != nil {
log.Fatalln(err)
}
}
func runService(appCtx appctx.AppContext) error {
userStore := userstorage.NewSQLStore(appCtx.GetMainDBConnection())
r := gin.Default()
r.Use(middleware.Recover(appCtx))
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
v1 := r.Group("/v1")
v1.POST("/register", ginuser.Register(appCtx))
v1.POST("/login", ginuser.Login(appCtx))
v1.GET("/profile", middleware.RequiredAuth(appCtx, userStore), ginuser.GetProfile(appCtx))
images := v1.Group("/images")
{
images.GET("", ginimage.ListImage(appCtx))
images.POST("", ginimage.UploadImage(appCtx))
images.DELETE("/:id", ginimage.DeleteImage(appCtx))
}
restaurants := v1.Group("/restaurants", middleware.RequiredAuth(appCtx, userStore))
{
restaurants.GET("", ginrestaurent.ListRestaurant(appCtx))
restaurants.POST("", ginrestaurent.CreateRestaurant(appCtx))
restaurants.GET("/:id", ginrestaurent.GetRestaurant(appCtx))
restaurants.PATCH("/:id", ginrestaurent.UpdateRestaurant(appCtx))
restaurants.DELETE("/:id", ginrestaurent.DeleteRestaurant(appCtx))
}
return r.Run()
}
|
EricRemmerswaal/tensorflow
|
tensorflow/python/kernel_tests/sparse_ops/sparse_tensor_dense_matmul_op_d9m_test.py
|
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========================================================================
"""Functional tests for deterministic SparseTensorDenseMatMul."""
import random
import numpy as np
from tensorflow.python.framework import config
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import errors
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import test_util
from tensorflow.python.ops import sparse_ops
from tensorflow.python.platform import test
def _gen_data(m, k, n, nnz, row_occupied_rate, data_type, seed):
"""Generate valid input data for tf.sparse.sparse_dense_matmul
returns sparse matrix a (type SparseTensor), dense matrix b (type Tensor)
Parameters:
m: row count of dense version of matrix a / row count of output matrix
k: col count of dense version of matrix a / row count of matrix b
n: col could of matrix b / col count of output matrix
nnz: number of non-zero elements in matrix a
row_occupied_rate: prob that row in a has one or more non-zero element
"""
random.seed(seed)
np.random.seed(seed)
occupied_rows = random.sample(range(m), int(m * row_occupied_rate))
sparse_input_dense_shape = [m, k]
dense_input_shape = (k, n)
indices = []
for _ in range(nnz):
row = random.choice(occupied_rows)
col = random.randint(0, k - 1)
indices.append([row, col])
def maybe_complex(x):
if x.dtype.kind == "c": # complex
return (x + 1j * x) / 2
return x
sparse_values = maybe_complex(
np.random.normal(size=len(indices)).astype(data_type))
dense_values = maybe_complex(
np.random.normal(size=dense_input_shape).astype(data_type))
sparse_input = sparse_tensor.SparseTensor(indices, sparse_values,
sparse_input_dense_shape)
dense_input = constant_op.constant(dense_values)
return sparse_input, dense_input
class SparseTensorDenseMatmulOpDeterminismExceptionsTest(test.TestCase):
"""Test d9m-unimplemented exceptions from SparseTensorDenseMatmulOp.
Test that tf.errors.UnimplementedError is thrown, as appropriate, by the
GPU-specific code-paths through SparseTensorDenseMatmulOp when deterministic
ops are enabled.
This test assumes that sparse_tensor_dense_matmul_op_test.py runs equivalent
test cases when deterministic ops are not enabled and will therefore detect
erroneous exception throwing in those cases.
"""
@test_util.run_gpu_only
@test_util.run_in_graph_and_eager_modes
def testExceptionThrowing(self):
with self.session(), test_util.force_gpu():
for data_type in [
np.float16, np.float32, np.float64, np.complex64, np.complex128
]:
sparse_input, dense_input = _gen_data(
m=5,
k=10,
n=7,
nnz=20,
row_occupied_rate=0.9,
data_type=data_type,
seed=456)
with self.assertRaisesRegex(
errors.UnimplementedError,
"A deterministic GPU implementation of SparseTensorDenseMatmulOp" +
" is not currently available."):
result = sparse_ops.sparse_tensor_dense_matmul(
sparse_input, dense_input)
self.evaluate(result)
class SparseTensorDenseMatmulOpDeterministicTest(test.TestCase):
"""Test that SparseTensorDenseMatul operates reproducibly (on CPU only)."""
@test_util.run_in_graph_and_eager_modes
def testForward(self):
for data_type in [
np.float16, np.float32, np.float64, np.complex64, np.complex128
]: # skipping int32 and bfloat16
sparse_input, dense_input = _gen_data(
m=2430,
k=615,
n=857,
nnz=(1 << 16) + 243,
row_occupied_rate=0.02,
data_type=data_type,
seed=123)
with self.session(), test_util.force_cpu():
result_a = sparse_ops.sparse_tensor_dense_matmul(
sparse_input, dense_input)
for _ in range(5):
result_b = sparse_ops.sparse_tensor_dense_matmul(
sparse_input, dense_input)
self.assertAllEqual(result_a, result_b)
if __name__ == "__main__":
# TODO(reedwm): Merge this file with sparse_tensor_dense_matmul_test.py
config.enable_op_determinism()
test.main()
|
jingcao80/Elastos
|
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/inputmethodservice/KeyboardView.cpp
|
<reponame>jingcao80/Elastos
//=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include <Elastos.CoreLibrary.Utility.h>
#include "Elastos.Droid.Content.h"
#include "Elastos.Droid.View.h"
#include "elastos/droid/inputmethodservice/KeyboardView.h"
#include "elastos/droid/graphics/CRect.h"
#include "elastos/droid/graphics/CBitmap.h"
#include "elastos/droid/graphics/CCanvas.h"
#include "elastos/droid/graphics/CRectF.h"
#include "elastos/droid/graphics/Typeface.h"
#include "elastos/droid/graphics/CPaint.h"
#include "elastos/droid/R.h"
#include "elastos/droid/view/ViewConfiguration.h"
#include "elastos/droid/view/MotionEvent.h"
#include "elastos/droid/view/CGestureDetector.h"
#include "elastos/droid/view/accessibility/CAccessibilityEventHelper.h"
#include "elastos/droid/view/accessibility/CAccessibilityManagerHelper.h"
#include "elastos/droid/provider/CSettingsSecure.h"
#include "elastos/droid/widget/CPopupWindow.h"
#include "elastos/droid/utility/CDisplayMetrics.h"
#include <elastos/core/Character.h>
#include <elastos/core/Math.h>
using Elastos::Droid::Content::IContentResolver;
using Elastos::Droid::Graphics::BitmapConfig_ARGB_8888;
using Elastos::Droid::Graphics::CRectF;
using Elastos::Droid::Graphics::CRect;
using Elastos::Droid::Graphics::CCanvas;
using Elastos::Droid::Graphics::CPaint;
using Elastos::Droid::Graphics::CBitmap;
using Elastos::Droid::Graphics::IBitmap;
using Elastos::Droid::Graphics::PorterDuffMode_CLEAR;
using Elastos::Droid::Graphics::RegionOp_REPLACE;
using Elastos::Droid::Graphics::Typeface;
using Elastos::Droid::Provider::ISettingsSecure;
using Elastos::Droid::Provider::CSettingsSecure;
using Elastos::Droid::R;
using Elastos::Droid::View::CGestureDetector;
using Elastos::Droid::View::IKeyEvent;
using Elastos::Droid::View::EIID_IView;
using Elastos::Droid::View::IViewOnClickListener;
using Elastos::Droid::View::EIID_IViewOnClickListener;
using Elastos::Droid::View::MotionEvent;
using Elastos::Droid::View::IGravity;
using Elastos::Droid::View::IViewGroupLayoutParams;
using Elastos::Droid::View::ILayoutInflater;
using Elastos::Droid::View::IInputEvent;
using Elastos::Droid::View::IGestureDetectorOnGestureListener;
using Elastos::Droid::View::ViewConfiguration;
using Elastos::Droid::View::Accessibility::IAccessibilityEventHelper;
using Elastos::Droid::View::Accessibility::CAccessibilityEventHelper;
using Elastos::Droid::View::Accessibility::IAccessibilityManagerHelper;
using Elastos::Droid::View::Accessibility::IAccessibilityEvent;
using Elastos::Droid::View::Accessibility::IAccessibilityRecord;
using Elastos::Droid::View::Accessibility::CAccessibilityManagerHelper;
using Elastos::Droid::Widget::CPopupWindow;
using Elastos::Droid::Utility::ITypedValue;
using Elastos::Droid::Utility::CDisplayMetrics;
using Elastos::Droid::Utility::IDisplayMetrics;
using Elastos::Core::Character;
using Elastos::Core::CString;
namespace Elastos {
namespace Droid {
namespace InputMethodService {
const Int32 KeyboardView::SwipeTracker::NUM_PAST = 4;
const Int32 KeyboardView::SwipeTracker::LONGEST_PAST_TIME = 200;
const Boolean KeyboardView::DEBUG = FALSE;
const Int32 KeyboardView::NOT_A_KEY = -1;
Int32 KeyboardView::KEY_DELETE[] = { IKeyboard::KEYCODE_DELETE };
Int32 KeyboardView::LONG_PRESSABLE_STATE_SET[] = { R::attr::state_long_pressable};
const Int32 KeyboardView::MSG_SHOW_PREVIEW = 1;
const Int32 KeyboardView::MSG_REMOVE_PREVIEW = 2;
const Int32 KeyboardView::MSG_REPEAT = 3;
const Int32 KeyboardView::MSG_LONGPRESS = 4;
const Int32 KeyboardView::DELAY_BEFORE_PREVIEW = 0;
const Int32 KeyboardView::DELAY_AFTER_PREVIEW = 70;
const Int32 KeyboardView::DEBOUNCE_TIME = 70;
const Int32 KeyboardView::REPEAT_INTERVAL = 50; // ~20 keys per second
const Int32 KeyboardView::REPEAT_START_DELAY = 400;
const Int32 KeyboardView::LONGPRESS_TIMEOUT = ViewConfiguration::GetLongPressTimeout();
const Int32 KeyboardView::MAX_NEARBY_KEYS = 12;
const Int32 KeyboardView::MULTITAP_INTERVAL = 800;
ECode KeyboardView::MyHandler::HandleMessage(
/* [in] */ IMessage* msg)
{
Int32 what, arg1;
msg->GetWhat(&what);
msg->GetArg1(&arg1);
switch(what) {
case KeyboardView::MSG_SHOW_PREVIEW:
mHost->ShowKey(arg1);
break;
case KeyboardView::MSG_REMOVE_PREVIEW:
IView::Probe(mHost->mPreviewText)->SetVisibility(IView::INVISIBLE);
break;
case KeyboardView::MSG_REPEAT:
if (mHost->RepeatKey()) {
Boolean result;
SendEmptyMessageDelayed(KeyboardView::MSG_REPEAT,
KeyboardView::REPEAT_INTERVAL, &result);
}
break;
case KeyboardView::MSG_LONGPRESS: {
AutoPtr<IInterface> obj;
msg->GetObj((IInterface**)&obj);
IMotionEvent* event = IMotionEvent::Probe(obj);
mHost->OpenPopupIfRequired(event);
break;
}
}
return NOERROR;
}
CAR_INTERFACE_IMPL(KeyboardView::_OnKeyboardActionListener, Object, IOnKeyboardActionListener);
KeyboardView::_OnKeyboardActionListener::_OnKeyboardActionListener(
/* [in] */ KeyboardView* host)
: mHost(host)
{}
KeyboardView::_OnKeyboardActionListener::~_OnKeyboardActionListener()
{}
ECode KeyboardView::_OnKeyboardActionListener::OnPress(
/* [in] */ Int32 primaryCode)
{
assert(mHost->mKeyboardActionListener != NULL);
return mHost->mKeyboardActionListener->OnPress(primaryCode);
}
ECode KeyboardView::_OnKeyboardActionListener::OnRelease(
/* [in] */ Int32 primaryCode)
{
assert(mHost->mKeyboardActionListener != NULL);
return mHost->mKeyboardActionListener->OnRelease(primaryCode);
}
ECode KeyboardView::_OnKeyboardActionListener::OnKey(
/* [in] */ Int32 primaryCode,
/* [in] */ ArrayOf<Int32>* keyCodes)
{
assert(mHost->mKeyboardActionListener != NULL);
mHost->mKeyboardActionListener->OnKey(primaryCode, keyCodes);
mHost->DismissPopupKeyboard();
return NOERROR;
}
ECode KeyboardView::_OnKeyboardActionListener::OnText(
/* [in] */ ICharSequence* text)
{
assert(mHost->mKeyboardActionListener != NULL);
mHost->mKeyboardActionListener->OnText(text);
mHost->DismissPopupKeyboard();
return NOERROR;
}
ECode KeyboardView::_OnKeyboardActionListener::SwipeLeft()
{
return NOERROR;
}
ECode KeyboardView::_OnKeyboardActionListener::SwipeRight()
{
return NOERROR;
}
ECode KeyboardView::_OnKeyboardActionListener::SwipeDown()
{
return NOERROR;
}
ECode KeyboardView::_OnKeyboardActionListener::SwipeUp()
{
return NOERROR;
}
KeyboardView::SwipeTracker::SwipeTracker()
{
mPastX = ArrayOf<Float>::Alloc(NUM_PAST);
mPastY = ArrayOf<Float>::Alloc(NUM_PAST);
mPastTime = ArrayOf<Int64>::Alloc(NUM_PAST);
mYVelocity = 0.0;
mXVelocity = 0.0;
}
KeyboardView::SwipeTracker::~SwipeTracker()
{
mPastX = NULL;
mPastY = NULL;
mPastTime = NULL;
}
void KeyboardView::SwipeTracker::Clear()
{
(*mPastTime)[0] = 0;
}
void KeyboardView::SwipeTracker::AddMovement(
/* [in] */ IMotionEvent* ev)
{
Int64 time = 0;
IInputEvent::Probe(ev)->GetEventTime(&time);
Int32 N = 0;
ev->GetHistorySize(&N);
Float x = 0.0, y = 0.0;
for (Int32 i=0; i<N; i++) {
ev->GetHistoricalX(i, &x);
ev->GetHistoricalY(i, &y);
Int64 tmpTime = 0;
ev->GetHistoricalEventTime(i, &tmpTime);
AddPoint(x, y, tmpTime);
}
ev->GetX(&x);
ev->GetY(&y);
AddPoint(x, y, time);
}
void KeyboardView::SwipeTracker::AddPoint(
/* [in] */ Float x,
/* [in] */ Float y,
/* [in] */ Int64 time)
{
Int32 drop = -1;
Int32 i = 0;
assert(mPastTime != NULL);
for (i=0; i<NUM_PAST; i++) {
if ((*mPastTime)[i] == 0) {
break;
}
else if ((*mPastTime)[i] < time - LONGEST_PAST_TIME) {
drop = i;
}
}
if (i == NUM_PAST && drop < 0) {
drop = 0;
}
if (drop == i) {
drop--;
}
if (drop >= 0) {
const Int32 start = drop + 1;
const Int32 count = NUM_PAST - drop - 1;
mPastX->Copy(0, mPastX, start, count);
mPastY->Copy(0, mPastY, start, count);
mPastTime->Copy(0, mPastTime, start, count);
i -= (drop+1);
}
(*mPastX)[i] = x;
(*mPastY)[i] = y;
(*mPastTime)[i] = time;
i++;
if (i < NUM_PAST) {
(*mPastTime)[i] = 0;
}
}
void KeyboardView::SwipeTracker::ComputeCurrentVelocity(
/* [in] */ Int32 units)
{
ComputeCurrentVelocity(units, Elastos::Core::Math::FLOAT_MAX_VALUE);
}
void KeyboardView::SwipeTracker::ComputeCurrentVelocity(
/* [in] */ Int32 units,
/* [in] */ Float maxVelocity)
{
Float oldestX = (*mPastX)[0];
Float oldestY = (*mPastY)[0];
Int64 oldestTime = (*mPastTime)[0];
Float accumX = 0;
Float accumY = 0;
Int32 N = 0;
while (N < NUM_PAST) {
if ((*mPastTime)[N] == 0) {
break;
}
N++;
}
for (Int32 i=1; i < N; i++) {
Int32 dur = (Int32)((*mPastTime)[i] - oldestTime);
if (dur == 0) {
continue;
}
Float dist = (*mPastX)[i] - oldestX;
Float vel = (dist / dur) * units; // pixels/frame.
if (accumX == 0) {
accumX = vel;
}
else {
accumX = (accumX + vel) * .5f;
}
dist = (*mPastY)[i] - oldestY;
vel = (dist / dur) * units; // pixels/frame.
if (accumY == 0) {
accumY = vel;
}
else {
accumY = (accumY + vel) * .5f;
}
}
mXVelocity = accumX < 0.0f ? Elastos::Core::Math::Max(accumX, -maxVelocity)
: Elastos::Core::Math::Min(accumX, maxVelocity);
mYVelocity = accumY < 0.0f ? Elastos::Core::Math::Max(accumY, -maxVelocity)
: Elastos::Core::Math::Min(accumY, maxVelocity);
}
Float KeyboardView::SwipeTracker::GetXVelocity()
{
return mXVelocity;
}
Float KeyboardView::SwipeTracker::GetYVelocity()
{
return mYVelocity;
}
KeyboardView::_SimpleOnGestureListener::_SimpleOnGestureListener(
/* [in] */ KeyboardView* host)
: mHost(host)
{}
KeyboardView::_SimpleOnGestureListener::~_SimpleOnGestureListener()
{}
ECode KeyboardView::_SimpleOnGestureListener::OnFling(
/* [in] */ IMotionEvent* e1,
/* [in] */ IMotionEvent* e2,
/* [in] */ Float velocityX,
/* [in] */ Float velocityY,
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
*res = TRUE;
if (mHost->mPossiblePoly) {
*res = FALSE;
return NOERROR;
}
const Float absX = Elastos::Core::Math::Abs(velocityX);
const Float absY = Elastos::Core::Math::Abs(velocityY);
Float tm1 = 0.0, tm2 = 0.0;
e2->GetX(&tm2);
e1->GetX(&tm1);
Float deltaX = tm2 - tm1;
e2->GetY(&tm2);
e1->GetY(&tm1);
Float deltaY = tm2 - tm1;
Int32 tmpI = 0;
Int32 travelX = (mHost->GetWidth(&tmpI), tmpI) / 2; // Half the keyboard width
Int32 travelY = (mHost->GetHeight(&tmpI), tmpI) / 2; // Half the keyboard height
mHost->mSwipeTracker->ComputeCurrentVelocity(1000);
const Float endingVelocityX = mHost->mSwipeTracker->GetXVelocity();
const Float endingVelocityY = mHost->mSwipeTracker->GetYVelocity();
Boolean sendDownKey = FALSE;
if (velocityX > mHost->mSwipeThreshold && absY < absX && deltaX > travelX) {
if (mHost->mDisambiguateSwipe && endingVelocityX < velocityX / 4) {
sendDownKey = TRUE;
}
else {
mHost->SwipeRight();
return NOERROR;
}
}
else if (velocityX < - mHost->mSwipeThreshold && absY < absX && deltaX < -travelX) {
if (mHost->mDisambiguateSwipe && endingVelocityX > velocityX / 4) {
sendDownKey = TRUE;
}
else {
mHost->SwipeLeft();
return NOERROR;
}
}
else if (velocityY < - mHost->mSwipeThreshold && absX < absY && deltaY < -travelY) {
if (mHost->mDisambiguateSwipe && endingVelocityY > velocityY / 4) {
sendDownKey = TRUE;
}
else {
mHost->SwipeUp();
return NOERROR;
}
}
else if (velocityY > mHost->mSwipeThreshold && absX < absY / 2 && deltaY > travelY) {
if (mHost->mDisambiguateSwipe && endingVelocityY < velocityY / 4) {
sendDownKey = TRUE;
}
else {
mHost->SwipeDown();
return NOERROR;
}
}
if (sendDownKey) {
Int64 time = 0;
IInputEvent::Probe(e1)->GetEventTime(&time);
mHost->DetectAndSendKey(mHost->mDownKey, mHost->mStartX, mHost->mStartY, time);
}
*res = FALSE;
return NOERROR;
}
CAR_INTERFACE_IMPL(KeyboardView::CloseButtonClickListener, Object, IViewOnClickListener)
KeyboardView::CloseButtonClickListener::CloseButtonClickListener(
/* [in] */ KeyboardView* host)
: mHost(host)
{}
ECode KeyboardView::CloseButtonClickListener::OnClick(
/* [in] */ IView* view)
{
mHost->DismissPopupKeyboard();
return NOERROR;
}
CAR_INTERFACE_IMPL(KeyboardView, View, IKeyboardView);
KeyboardView::KeyboardView()
: mCurrentKeyIndex(NOT_A_KEY)
, mLabelTextSize(0)
, mKeyTextSize(0)
, mKeyTextColor(0)
, mShadowRadius(0.0)
, mShadowColor(0)
, mBackgroundDimAmount(0.0)
, mPreviewTextSizeLarge(0)
, mPreviewOffset(0)
, mPreviewHeight(0)
, mMiniKeyboardOnScreen(FALSE)
, mMiniKeyboardOffsetX(0)
, mMiniKeyboardOffsetY(0)
, mKeys(NULL)
, mVerticalCorrection(0)
, mProximityThreshold(0)
, mPreviewCentered(FALSE)
, mShowPreview(TRUE)
, mShowTouchPoints(TRUE)
, mPopupPreviewX(0)
, mPopupPreviewY(0)
, mLastX(0)
, mLastY(0)
, mStartX(0)
, mStartY(0)
, mProximityCorrectOn(FALSE)
, mDownTime(0)
, mLastMoveTime(0)
, mLastKey(0)
, mLastCodeX(0)
, mLastCodeY(0)
, mCurrentKey(NOT_A_KEY)
, mDownKey(NOT_A_KEY)
, mLastKeyTime(0)
, mCurrentKeyTime(0)
, mKeyIndices(ArrayOf<Int32>::Alloc(12))
, mPopupX(0)
, mPopupY(0)
, mRepeatKeyIndex(NOT_A_KEY)
, mPopupLayout(0)
, mAbortKey(FALSE)
, mPossiblePoly(FALSE)
, mSwipeTracker(new SwipeTracker())
, mSwipeThreshold(0)
, mDisambiguateSwipe(FALSE)
, mOldPointerCount(1)
, mOldPointerX(0.0)
, mOldPointerY(0.0)
, mDistances(ArrayOf<Int32>::Alloc(MAX_NEARBY_KEYS))
, mLastSentIndex(0)
, mTapCount(0)
, mLastTapTime(0)
, mInMultiTap(FALSE)
, mDrawPending(FALSE)
, mKeyboardChanged(FALSE)
, mHeadsetRequiredToHearPasswordsAnnounced(FALSE)
, mOldEventTime(0)
, mUsedVelocity(FALSE)
{
}
ECode KeyboardView::constructor(
/* [in] */ IContext* context,
/* [in] */ IAttributeSet* attrs)
{
return constructor(context, attrs, R::attr::keyboardViewStyle);
}
ECode KeyboardView::constructor(
/* [in] */ IContext* context,
/* [in] */ IAttributeSet* attrs,
/* [in] */ Int32 defStyleAttr)
{
return constructor(context, attrs, defStyleAttr, 0);
}
ECode KeyboardView::constructor(
/* [in] */ IContext* context,
/* [in] */ IAttributeSet* attrs,
/* [in] */ Int32 defStyleAttr,
/* [in] */ Int32 defStyleRes)
{
View::constructor(context, attrs, defStyleAttr, defStyleRes);
CRect::New(0, 0, 0, 0, (IRect**)&mClipRegion);
CRectF::New((IRectF**)&mDirtyRect);
mHandler = new MyHandler(this);
mHandler->constructor();
mCoordinates = ArrayOf<Int32>::Alloc(2);
AutoPtr<ITypedArray> a;
AutoPtr<ArrayOf<Int32> > attrIds = TO_ATTRS_ARRAYOF(R::styleable::KeyboardView);
context->ObtainStyledAttributes(attrs, attrIds,
defStyleAttr, defStyleRes, (ITypedArray**)&a);
AutoPtr<IInterface> service;
FAIL_RETURN(context->GetSystemService(IContext::LAYOUT_INFLATER_SERVICE, (IInterface**)&service))
AutoPtr<ILayoutInflater> inflate = ILayoutInflater::Probe(service);
Int32 previewLayout = 0;
Int32 keyTextSize = 0;
Int32 n = 0;
a->GetIndexCount(&n);
for (Int32 i = 0; i < n; i++) {
Int32 attr = 0;
a->GetIndex(i, &attr);
switch (attr) {
case R::styleable::KeyboardView_keyBackground:
a->GetDrawable(attr, (IDrawable**)&mKeyBackground);
break;
case R::styleable::KeyboardView_verticalCorrection:
a->GetDimensionPixelOffset(attr, 0, &mVerticalCorrection);
break;
case R::styleable::KeyboardView_keyPreviewLayout:
a->GetResourceId(attr, 0, &previewLayout);
break;
case R::styleable::KeyboardView_keyPreviewOffset:
a->GetDimensionPixelOffset(attr, 0, &mPreviewOffset);
break;
case R::styleable::KeyboardView_keyPreviewHeight:
a->GetDimensionPixelSize(attr, 80, &mPreviewHeight);
break;
case R::styleable::KeyboardView_keyTextSize:
a->GetDimensionPixelSize(attr, 18, &mKeyTextSize);
break;
case R::styleable::KeyboardView_keyTextColor:
a->GetColor(attr, 0xFF000000, &mKeyTextColor);
break;
case R::styleable::KeyboardView_labelTextSize:
a->GetDimensionPixelSize(attr, 14, &mLabelTextSize);
break;
case R::styleable::KeyboardView_popupLayout:
a->GetResourceId(attr, 0, &mPopupLayout);
break;
case R::styleable::KeyboardView_shadowColor:
a->GetColor(attr, 0, &mShadowColor);
break;
case R::styleable::KeyboardView_shadowRadius:
a->GetFloat(attr, 0.0, &mShadowRadius);
break;
}
}
a->Recycle();
a = NULL;
mContext->ObtainStyledAttributes(attrIds, (ITypedArray**)&a);
a->GetFloat(R::styleable::Theme_backgroundDimAmount, 0.5f, &mBackgroundDimAmount);
a->Recycle();
CPopupWindow::New(context, (IPopupWindow**)&mPreviewPopup);
if (previewLayout != 0) {
AutoPtr<IView> tv;
inflate->Inflate(previewLayout, NULL, (IView**)&tv);
mPreviewText = ITextView::Probe(tv);
Float textSize = 0.0;
mPreviewText->GetTextSize(&textSize);
mPreviewTextSizeLarge = (Int32)textSize;
mPreviewPopup->SetContentView(IView::Probe(mPreviewText));
mPreviewPopup->SetBackgroundDrawable(NULL);
}
else {
mShowPreview = FALSE;
}
mPreviewPopup->SetTouchable(FALSE);
CPopupWindow::New(context, (IPopupWindow**)&mPopupKeyboard);
mPopupKeyboard->SetBackgroundDrawable(NULL);
//mPopupKeyboard.setClippingEnabled(FALSE);
mPopupParent = this;
//mPredicting = TRUE;
CPaint::New((IPaint**)&mPaint);
mPaint->SetAntiAlias(TRUE);
mPaint->SetTextSize(keyTextSize);
mPaint->SetTextAlign(Elastos::Droid::Graphics::PaintAlign_CENTER /*Align.CENTER*/);
mPaint->SetAlpha(255);
CRect::New(0, 0, 0, 0, (IRect**)&mPadding);
mMiniKeyboardCache = new HashMap<AutoPtr<IKeyboardKey>, AutoPtr<IView> >();
Boolean isPadding = FALSE;
mKeyBackground->GetPadding(mPadding, &isPadding);
AutoPtr<IResources> res;
GetResources((IResources**)&res);
AutoPtr<IDisplayMetrics> dis;
res->GetDisplayMetrics((IDisplayMetrics**)&dis);
Float density;
dis->GetDensity(&density);
mSwipeThreshold = (Int32) (500 * density);
res->GetBoolean(R::bool_::config_swipeDisambiguation,
&mDisambiguateSwipe);
AutoPtr<IAccessibilityManagerHelper> helper;
CAccessibilityManagerHelper::AcquireSingleton((IAccessibilityManagerHelper**)&helper);
helper->GetInstance(context, (IAccessibilityManager**)&mAccessibilityManager);
AutoPtr<IInterface> audioService;
context->GetSystemService(IContext::AUDIO_SERVICE, (IInterface**)&audioService);
mAudioManager = IAudioManager::Probe(audioService);
ResetMultiTap();
InitGestureDetector();
return NOERROR;
}
void KeyboardView::InitGestureDetector()
{
AutoPtr<IContext> context;
GetContext((IContext**)&context);
AutoPtr<IGestureDetectorOnGestureListener> listener = new _SimpleOnGestureListener(this);
CGestureDetector::New(context, listener, (IGestureDetector**)&mGestureDetector);
mGestureDetector->SetIsLongpressEnabled(FALSE);
}
ECode KeyboardView::SetOnKeyboardActionListener(
/* [in] */ IOnKeyboardActionListener* listener)
{
mKeyboardActionListener = listener;
return NOERROR;
}
ECode KeyboardView::GetOnKeyboardActionListener(
/* [out] */ IOnKeyboardActionListener** listener)
{
assert(listener != NULL);
*listener = mKeyboardActionListener;
REFCOUNT_ADD(*listener);
return NOERROR;
}
ECode KeyboardView::SetKeyboard(
/* [in] */ IKeyboard* keyboard)
{
if (mKeyboard != NULL) {
ShowPreview(NOT_A_KEY);
}
// Remove any pending messages
RemoveMessages();
mKeyboard = keyboard;
AutoPtr<IList> keys;
mKeyboard->GetKeys((IList**)&keys);
Int32 size = 0;
keys->GetSize(&size);
mKeys = ArrayOf<IKeyboardKey*>::Alloc(size);
for (Int32 pos = 0; pos < size; pos++) {
AutoPtr<IInterface> key;
keys->Get(pos, ((IInterface**)&key));
mKeys->Set(pos, IKeyboardKey::Probe(key));
}
RequestLayout();
// Hint to reallocate the buffer if the size changed
mKeyboardChanged = TRUE;
InvalidateAllKeys();
ComputeProximityThreshold(keyboard);
mMiniKeyboardCache->Clear(); // Not really necessary to do every time, but will free up views
// Switching to a different keyboard should abort any pending keys so that the key up
// doesn't get delivered to the old or new keyboard
mAbortKey = TRUE; // Until the next ACTION_DOWN
return NOERROR;
}
ECode KeyboardView::GetKeyboard(
/* [out] */ IKeyboard** keyboard)
{
assert(keyboard != NULL);
*keyboard = mKeyboard;
REFCOUNT_ADD(*keyboard);
return NOERROR;
}
ECode KeyboardView::SetShifted(
/* [in] */ Boolean shifted,
/* [out] */ Boolean* res)
{
assert(res != NULL);
if (mKeyboard != NULL) {
Boolean succeeded = FALSE;
if (mKeyboard->SetShifted(shifted, &succeeded), succeeded) {
// The whole keyboard probably needs to be redrawn
InvalidateAllKeys();
*res = TRUE;
return NOERROR;
}
}
*res = FALSE;
return NOERROR;
}
ECode KeyboardView::IsShifted(
/* [out] */ Boolean* shifted)
{
assert(shifted != NULL);
if (mKeyboard != NULL) {
return mKeyboard->IsShifted(shifted);
}
*shifted = FALSE;
return NOERROR;
}
ECode KeyboardView::SetPreviewEnabled(
/* [in] */ Boolean previewEnabled)
{
mShowPreview = previewEnabled;
return NOERROR;
}
ECode KeyboardView::IsPreviewEnabled(
/* [out] */ Boolean* res)
{
assert(res != NULL);
*res = mShowPreview;
return NOERROR;
}
ECode KeyboardView::SetVerticalCorrection(
/* [in] */ Int32 verticalOffset)
{
return NOERROR;
}
ECode KeyboardView::SetPopupParent(
/* [in] */ IView* v)
{
mPopupParent = v;
return NOERROR;
}
ECode KeyboardView::SetPopupOffset(
/* [in] */ Int32 x,
/* [in] */ Int32 y)
{
mMiniKeyboardOffsetX = x;
mMiniKeyboardOffsetY = y;
Boolean showing = FALSE;
mPreviewPopup->IsShowing(&showing);
if (showing) {
mPreviewPopup->Dismiss();
}
return NOERROR;
}
ECode KeyboardView::SetProximityCorrectionEnabled(
/* [in] */ Boolean enabled)
{
mProximityCorrectOn = enabled;
return NOERROR;
}
/**
* Returns TRUE if proximity correction is enabled.
*/
ECode KeyboardView::IsProximityCorrectionEnabled(
/* [out] */ Boolean* res)
{
assert(res != NULL);
*res = mProximityCorrectOn;
return NOERROR;
}
/**
* Popup keyboard close button clicked.
* @hide
*/
ECode KeyboardView::OnClick(
/* [in] */ IView* v)
{
DismissPopupKeyboard();
return NOERROR;
}
AutoPtr<ICharSequence> KeyboardView::AdjustCase(
/* [in] */ ICharSequence* label)
{
Boolean shifted;
if ((mKeyboard->IsShifted(&shifted), shifted) && label != NULL) {
Int32 len = 0;
Char32 c = 0;
label->GetLength(&len);
label->GetCharAt(0, &c);
if (len < 3 && Character::IsLowerCase(c)) {
String str;
label->ToString(&str);
str = str.ToUpperCase();
AutoPtr<ICharSequence> label2;
CString::New(str, (ICharSequence**)&label2);
return label2;
}
}
return label;
}
ECode KeyboardView::OnMeasure(
/* [in] */ Int32 widthMeasureSpec,
/* [in] */ Int32 heightMeasureSpec)
{
// Round up a little
if (mKeyboard == NULL) {
SetMeasuredDimension(mPaddingLeft + mPaddingRight, mPaddingTop + mPaddingBottom);
}
else {
Int32 mw = 0;
mKeyboard->GetMinWidth(&mw);
Int32 width = mw + mPaddingLeft + mPaddingRight;
if (View::MeasureSpec::GetSize(widthMeasureSpec) < width + 10) {
width = View::MeasureSpec::GetSize(widthMeasureSpec);
}
Int32 th = 0;
mKeyboard->GetHeight(&th);
SetMeasuredDimension(width, th + mPaddingTop + mPaddingBottom);
}
return NOERROR;
}
void KeyboardView::ComputeProximityThreshold(
/* [in] */ IKeyboard* keyboard)
{
if (keyboard == NULL) return;
if (mKeys == NULL) return;
Int32 length = mKeys->GetLength();
Int32 dimensionSum = 0;
for (Int32 i = 0; i < length; i++) {
IKeyboardKey* key = (*mKeys)[i];
Int32 keyW, keyH, keyG;
key->GetWidth(&keyW);
key->GetHeight(&keyH);
key->GetGap(&keyG);
dimensionSum += Elastos::Core::Math::Min(keyW, keyH) + keyG;
}
if (dimensionSum < 0 || length == 0) return;
mProximityThreshold = (Int32) (dimensionSum * 1.4f / length);
mProximityThreshold *= mProximityThreshold; // Square it
}
ECode KeyboardView::OnSizeChanged(
/* [in] */ Int32 w,
/* [in] */ Int32 h,
/* [in] */ Int32 oldw,
/* [in] */ Int32 oldh)
{
View::OnSizeChanged(w, h, oldw, oldh);
if (mKeyboard != NULL) {
((Keyboard*)mKeyboard.Get())->Resize(w, h);
}
// Release the buffer, if any and it will be reallocated on the next draw
mBuffer = NULL;
return NOERROR;
}
void KeyboardView::OnDraw(
/* [in] */ ICanvas* canvas)
{
View::OnDraw(canvas);
if (mDrawPending || mBuffer == NULL || mKeyboardChanged) {
OnBufferDraw();
}
canvas->DrawBitmap(mBuffer, 0.f, 0.f, NULL);
}
void KeyboardView::OnBufferDraw()
{
if (mBuffer == NULL || mKeyboardChanged) {
Int32 bufferW = 0, bufferH = 0;
if (mBuffer != NULL) {
mBuffer->GetWidth(&bufferW);
mBuffer->GetHeight(&bufferH);
}
Int32 sw = 0, sh = 0;
if (mBuffer == NULL || (mKeyboardChanged &&
(bufferW != (GetWidth(&sw), sw) || bufferH != (GetHeight(&sh), sh)))) {
// Make sure our bitmap is at least 1x1
const Int32 width = Elastos::Core::Math::Max(1, (GetWidth(&sw), sw));
const Int32 height = Elastos::Core::Math::Max(1, (GetHeight(&sh), sh));
mBuffer = NULL;
CBitmap::CreateBitmap(width, height,
BitmapConfig_ARGB_8888, (IBitmap**)&mBuffer);
mCanvas = NULL;
CCanvas::New(mBuffer, (ICanvas**)&mCanvas);
}
InvalidateAllKeys();
mKeyboardChanged = FALSE;
}
Boolean isNotEmpty = FALSE;
mCanvas->ClipRect(mDirtyRect, RegionOp_REPLACE, &isNotEmpty);
if (mKeyboard == NULL) return;
const Int32 kbdPaddingLeft = mPaddingLeft;
const Int32 kbdPaddingTop = mPaddingTop;
mPaint->SetColor(mKeyTextColor);
Boolean drawSingleKey = FALSE;
Boolean isNonEmpty = FALSE;
if (mInvalidatedKey != NULL && (mCanvas->GetClipBounds(mClipRegion, &isNonEmpty), isNonEmpty)) {
// Is clipRegion completely contained within the invalidated key?
Int32 keyX, keyY, keyW, keyH;
mInvalidatedKey->GetX(&keyX);
mInvalidatedKey->GetY(&keyY);
mInvalidatedKey->GetWidth(&keyW);
mInvalidatedKey->GetHeight(&keyH);
CRect* clipRegion = (CRect*)mClipRegion.Get();
if (keyX + kbdPaddingLeft - 1 <= clipRegion->mLeft &&
keyY + kbdPaddingTop - 1 <= clipRegion->mTop &&
keyX + keyW + kbdPaddingLeft + 1 >= clipRegion->mRight &&
keyY + keyH + kbdPaddingTop + 1 >= clipRegion->mBottom) {
drawSingleKey = TRUE;
}
}
mCanvas->DrawColor(0x00000000, PorterDuffMode_CLEAR);
CRect* padding = (CRect*)mPadding.Get();
const Int32 keyCount = mKeys->GetLength();
for (Int32 i = 0; i < keyCount; i++) {
AutoPtr<IKeyboardKey> key = (*mKeys)[i];
if (drawSingleKey && mInvalidatedKey != key) {
continue;
}
AutoPtr< ArrayOf<Int32> > drawableState;
key->GetCurrentDrawableState((ArrayOf<Int32>**)&drawableState);
Boolean isStateful = FALSE;
mKeyBackground->SetState(drawableState.Get(), &isStateful);
// Switch the character to uppercase if shift is pressed
String label;
AutoPtr<ICharSequence> l;
key->GetLabel((ICharSequence**)&l);
if (l != NULL) {
AdjustCase(l)->ToString(&label);
}
Int32 keyW, keyH;
key->GetWidth(&keyW);
key->GetHeight(&keyH);
AutoPtr<IRect> bounds;
mKeyBackground->GetBounds((IRect**)&bounds);
if (keyW != ((CRect*)bounds.Get())->mRight ||
keyH != ((CRect*)bounds.Get())->mBottom) {
mKeyBackground->SetBounds(0, 0, keyW, keyH);
}
Int32 keyX, keyY;
key->GetX(&keyX);
key->GetY(&keyY);
mCanvas->Translate(keyX + kbdPaddingLeft, keyY + kbdPaddingTop);
mKeyBackground->Draw(mCanvas);
if (!label.IsNull()) {
// For characters, use large font. For labels like "Done", use small font.
if (label.GetLength() > 1 /*&& ((CKeyboardKey*)key.Get())->mCodes->GetLength() < 2*/) {
mPaint->SetTextSize(mLabelTextSize);
mPaint->SetTypeface(Typeface::DEFAULT_BOLD);
}
else {
mPaint->SetTextSize(mKeyTextSize);
mPaint->SetTypeface(Typeface::DEFAULT);
}
// Draw a drop shadow for the text
mPaint->SetShadowLayer(mShadowRadius, 0, 0, mShadowColor);
// Draw the text
Float textSize = 0.0, tmpDescent = 0.0;
mPaint->GetTextSize(&textSize);
mPaint->Descent(&tmpDescent);
mCanvas->DrawText(label,
(keyW - padding->mLeft - padding->mRight) / 2 + padding->mLeft,
(keyH - padding->mTop - padding->mBottom) / 2 + (textSize - tmpDescent) / 2 + padding->mTop,
mPaint);
// Turn off drop shadow
mPaint->SetShadowLayer(0, 0, 0, 0);
}
else {
AutoPtr<IDrawable> icon;
key->GetIcon((IDrawable**)&icon);
if (icon != NULL) {
Int32 intrinsicWidth = 0, intrinsicHeight = 0;
icon->GetIntrinsicWidth(&intrinsicWidth);
icon->GetIntrinsicHeight(&intrinsicHeight);
const Int32 drawableX = (keyW - padding->mLeft - padding->mRight
- intrinsicWidth) / 2 + padding->mLeft;
const Int32 drawableY = (keyH - padding->mTop - padding->mBottom
- intrinsicHeight) / 2 + padding->mTop;
mCanvas->Translate(drawableX, drawableY);
icon->SetBounds(0, 0, intrinsicWidth, intrinsicHeight);
icon->Draw(mCanvas);
mCanvas->Translate(-drawableX, -drawableY);
}
}
mCanvas->Translate(-keyX - kbdPaddingLeft, -keyY - kbdPaddingTop);
}
mInvalidatedKey = NULL;
// Overlay a dark rectangle to dim the keyboard
if (mMiniKeyboardOnScreen) {
Int32 sw = 0, sh = 0;
GetWidth(&sw);
GetHeight(&sh);
mPaint->SetColor((Int32)(mBackgroundDimAmount * 0xFF) << 24);
mCanvas->DrawRect(0, 0, sw, sh, mPaint);
}
if (DEBUG && mShowTouchPoints) {
mPaint->SetAlpha(128);
mPaint->SetColor(0xFFFF0000);
mCanvas->DrawCircle(mStartX, mStartY, 3, mPaint);
mCanvas->DrawLine(mStartX, mStartY, mLastX, mLastY, mPaint);
mPaint->SetColor(0xFF0000FF);
mCanvas->DrawCircle(mLastX, mLastY, 3, mPaint);
mPaint->SetColor(0xFF00FF00);
mCanvas->DrawCircle((mStartX + mLastX) / 2, (mStartY + mLastY) / 2, 2, mPaint);
}
mDrawPending = FALSE;
mDirtyRect->SetEmpty();
}
Int32 KeyboardView::GetKeyIndices(
/* [in] */ Int32 x,
/* [in] */ Int32 y,
/* [in] */ ArrayOf<Int32>* allKeys)
{
Int32 primaryIndex = NOT_A_KEY;
Int32 closestKey = NOT_A_KEY;
Int32 closestKeyDist = mProximityThreshold + 1;
for (Int32 i = 0; i < mDistances->GetLength(); i++) {
(*mDistances)[i] = Elastos::Core::Math::INT32_MAX_VALUE;
}
AutoPtr< ArrayOf<Int32> > nearestKeyIndices;
mKeyboard->GetNearestKeys(x, y, (ArrayOf<Int32>**)&nearestKeyIndices);
const Int32 keyCount = nearestKeyIndices->GetLength();
for (Int32 i = 0; i < keyCount; i++) {
AutoPtr<IKeyboardKey> key = (*mKeys)[(*nearestKeyIndices)[i]];
Int32 dist = 0;
Boolean isInside = FALSE;
key->IsInside(x, y, &isInside);
if (isInside) {
primaryIndex = (*nearestKeyIndices)[i];
}
key->SquaredDistanceFrom(x, y, &dist);
AutoPtr< ArrayOf<Int32> > codes;
key->GetCodes((ArrayOf<Int32>**)&codes);
if (((mProximityCorrectOn
&& dist < mProximityThreshold)
|| isInside)
&& (*codes.Get())[0] > 32) {
// Find insertion point
const Int32 nCodes = codes->GetLength();
if (dist < closestKeyDist) {
closestKeyDist = dist;
closestKey = (*nearestKeyIndices)[i];
}
if (allKeys == NULL) continue;
for (Int32 j = 0; j < mDistances->GetLength(); j++) {
if ((*mDistances)[j] > dist) {
// Make space for nCodes codes
mDistances->Copy(j + nCodes, mDistances, j, (mDistances->GetLength() - j - nCodes));
allKeys->Copy(j + nCodes, allKeys, j, (allKeys->GetLength() - j - nCodes));
for (Int32 c = 0; c < nCodes; c++) {
(*allKeys)[j + c] = (*codes.Get())[c];
(*mDistances)[j + c] = dist;
}
break;
}
}
}
}
if (primaryIndex == NOT_A_KEY) {
primaryIndex = closestKey;
}
return primaryIndex;
}
void KeyboardView::DetectAndSendKey(
/* [in] */ Int32 index,
/* [in] */ Int32 x,
/* [in] */ Int32 y,
/* [in] */ Int64 eventTime)
{
if (index != NOT_A_KEY && index < mKeys->GetLength()) {
AutoPtr<IKeyboardKey> key = (*mKeys)[index];
AutoPtr<ICharSequence> text;
key->GetText((ICharSequence**)&text);
if (text != NULL) {
mKeyboardActionListener->OnText(text);
mKeyboardActionListener->OnRelease(NOT_A_KEY);
}
else {
AutoPtr< ArrayOf<Int32> > _codes;
key->GetCodes((ArrayOf<Int32>**)&_codes);
Int32 code = (*_codes.Get())[0];
//TextEntryState.keyPressedAt(key, x, y);
AutoPtr<ArrayOf<Int32> > codes = ArrayOf<Int32>::Alloc(MAX_NEARBY_KEYS);
for (Int32 i = 0; i < MAX_NEARBY_KEYS; ++i) {
(*codes)[i] = NOT_A_KEY;
}
GetKeyIndices(x, y, codes);
// Multi-tap
if (mInMultiTap) {
if (mTapCount != -1) {
AutoPtr<ArrayOf<Int32> > tmpArr = ArrayOf<Int32>::Alloc(1);
(*tmpArr)[0] = KEY_DELETE[0];
mKeyboardActionListener->OnKey(IKeyboard::KEYCODE_DELETE, tmpArr);
}
else {
mTapCount = 0;
}
code = (*_codes.Get())[mTapCount];
}
mKeyboardActionListener->OnKey(code, codes);
mKeyboardActionListener->OnRelease(code);
}
mLastSentIndex = index;
mLastTapTime = eventTime;
}
}
/**
* Handle multi-tap keys by producing the key label for the current multi-tap state.
*/
AutoPtr<ICharSequence> KeyboardView::GetPreviewText(
/* [in] */ IKeyboardKey* key)
{
if (mInMultiTap) {
// Multi-tap
AutoPtr< ArrayOf<Int32> > codes;
key->GetCodes((ArrayOf<Int32>**)&codes);
// mPreviewLabel.SetLength(0);
mPreviewLabel += (Char32)(*codes.Get())[mTapCount < 0 ? 0 : mTapCount];
AutoPtr<ICharSequence> text;
CString::New(mPreviewLabel.ToString(), (ICharSequence**)&text);
return AdjustCase(text);
}
else {
AutoPtr<ICharSequence> label;
key->GetLabel((ICharSequence**)&label);
return AdjustCase(label);
}
}
void KeyboardView::ShowPreview(
/* [in] */ Int32 keyIndex)
{
Int32 oldKeyIndex = mCurrentKeyIndex;
mCurrentKeyIndex = keyIndex;
// Release the old key and press the new key
if (oldKeyIndex != mCurrentKeyIndex) {
if (oldKeyIndex != NOT_A_KEY && mKeys->GetLength() > oldKeyIndex) {
AutoPtr<IKeyboardKey> oldKey = (*mKeys)[oldKeyIndex];
oldKey->OnReleased(mCurrentKeyIndex == NOT_A_KEY);
InvalidateKey(oldKeyIndex);
AutoPtr<ArrayOf<Int32> > codes;
oldKey->GetCodes((ArrayOf<Int32>**)&codes);
Int32 keyCode = (*codes)[0];
SendAccessibilityEventForUnicodeCharacter(
IAccessibilityEvent::TYPE_VIEW_HOVER_EXIT, keyCode);
// TODO: We need to implement AccessibilityNodeProvider for this view.
SendAccessibilityEventForUnicodeCharacter(
IAccessibilityEvent::TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED, keyCode);
}
if (mCurrentKeyIndex != NOT_A_KEY && mKeys->GetLength() > mCurrentKeyIndex) {
AutoPtr<IKeyboardKey> newKey = (*mKeys)[mCurrentKeyIndex];
newKey->OnPressed();
InvalidateKey(mCurrentKeyIndex);
AutoPtr<ArrayOf<Int32> > codes;
newKey->GetCodes((ArrayOf<Int32>**)&codes);
Int32 keyCode = (*codes)[0];
SendAccessibilityEventForUnicodeCharacter(
IAccessibilityEvent::TYPE_VIEW_HOVER_ENTER, keyCode);
// TODO: We need to implement AccessibilityNodeProvider for this view.
SendAccessibilityEventForUnicodeCharacter(
IAccessibilityEvent::TYPE_VIEW_ACCESSIBILITY_FOCUSED, keyCode);
}
}
// If key changed and preview is on ...
if (oldKeyIndex != mCurrentKeyIndex && mShowPreview) {
mHandler->RemoveMessages(MSG_SHOW_PREVIEW);
Boolean showing = FALSE;
if (mPreviewPopup->IsShowing(&showing), showing) {
if (keyIndex == NOT_A_KEY) {
Boolean result;
mHandler->SendEmptyMessageDelayed(MSG_REMOVE_PREVIEW,
DELAY_AFTER_PREVIEW, &result);
}
}
if (keyIndex != NOT_A_KEY) {
mPreviewPopup->IsShowing(&showing);
Int32 v = 0;
IView::Probe(mPreviewText)->GetVisibility(&v);
if (showing && v == IView::VISIBLE) {
// Show right away, if it's already visible and finger is moving around
ShowKey(keyIndex);
}
else {
AutoPtr<IMessage> msg;
mHandler->ObtainMessage(MSG_REMOVE_PREVIEW, keyIndex, 0, (IMessage**)&msg);
Boolean result;
mHandler->SendMessageDelayed(msg, DELAY_BEFORE_PREVIEW, &result);
}
}
}
}
void KeyboardView::ShowKey(
/* [in] */ Int32 keyIndex)
{
if (keyIndex < 0 || keyIndex >= mKeys->GetLength()) return;
AutoPtr<IKeyboardKey> key = (*mKeys)[keyIndex];
AutoPtr<IDrawable> icon;
key->GetIcon((IDrawable**)&icon);
if (icon != NULL) {
AutoPtr<IDrawable> iconPreview;
key->GetIconPreview((IDrawable**)&iconPreview);
mPreviewText->SetCompoundDrawables(NULL, NULL, NULL,
iconPreview != NULL ? iconPreview : icon);
mPreviewText->SetText((ICharSequence*)NULL);
}
else {
mPreviewText->SetCompoundDrawables(NULL, NULL, NULL, NULL);
AutoPtr<ICharSequence> text = GetPreviewText(key);
mPreviewText->SetText(text);
AutoPtr<ICharSequence> label;
key->GetLabel((ICharSequence**)&label);
Int32 len = 0;
label->GetLength(&len);
AutoPtr< ArrayOf<Int32> > codes;
key->GetCodes((ArrayOf<Int32>**)&codes);
if (len > 1 && codes->GetLength() < 2) {
mPreviewText->SetTextSize(ITypedValue::COMPLEX_UNIT_PX, mKeyTextSize);
mPreviewText->SetTypeface(Typeface::DEFAULT_BOLD);
}
else {
mPreviewText->SetTextSize(ITypedValue::COMPLEX_UNIT_PX, mPreviewTextSizeLarge);
mPreviewText->SetTypeface(Typeface::DEFAULT);
}
}
IView::Probe(mPreviewText)->Measure(MeasureSpec::MakeMeasureSpec(0, MeasureSpec::UNSPECIFIED),
MeasureSpec::MakeMeasureSpec(0, MeasureSpec::UNSPECIFIED));
Int32 tmp = 0, tmpL = 0, tmpR = 0;
IView::Probe(mPreviewText)->GetMeasuredWidth(&tmp);
IView::Probe(mPreviewText)->GetPaddingLeft(&tmpL);
IView::Probe(mPreviewText)->GetPaddingRight(&tmpR);
Int32 keyW;
key->GetWidth(&keyW);
Int32 popupWidth = Elastos::Core::Math::Max(tmp, keyW + tmpL + tmpR);
const Int32 popupHeight = mPreviewHeight;
AutoPtr<IViewGroupLayoutParams> lp;
IView::Probe(mPreviewText)->GetLayoutParams((IViewGroupLayoutParams**)&lp);
if (lp != NULL) {
lp->SetWidth(popupWidth);
lp->SetHeight(popupHeight);
}
if (!mPreviewCentered) {
IView::Probe(mPreviewText)->GetPaddingLeft(&tmpL);
Int32 keyX, keyY;
key->GetX(&keyX);
key->GetY(&keyY);
mPopupPreviewX = keyX - tmpL + mPaddingLeft;
mPopupPreviewY = keyY - popupHeight + mPreviewOffset;
}
else {
// TODO: Fix this if centering is brought back
IView::Probe(mPreviewText)->GetMeasuredWidth(&tmp);
mPopupPreviewX = 160 - tmp / 2;
IView::Probe(mPreviewText)->GetMeasuredHeight(&tmp);
mPopupPreviewY = - tmp;
}
mHandler->RemoveMessages(MSG_REMOVE_PREVIEW);
GetLocationInWindow(mCoordinates);
(*mCoordinates)[0] += mMiniKeyboardOffsetX; // Offset may be zero
(*mCoordinates)[1] += mMiniKeyboardOffsetY; // Offset may be zero
// Set the preview background state
AutoPtr<IDrawable> drawable;
IView::Probe(mPreviewText)->GetBackground((IDrawable**)&drawable);
AutoPtr< ArrayOf<Int32> >tmpArr;
Int32 resId;
key->GetPopupResId(&resId);
if (resId != 0) {
tmpArr = ArrayOf<Int32>::Alloc(1);
(*tmpArr)[0] = LONG_PRESSABLE_STATE_SET[0];
}
else {
tmpArr = ArrayOf<Int32>::Alloc(0);
}
Boolean isStateful = FALSE;
drawable->SetState(tmpArr, &isStateful);
mPopupPreviewX += (*mCoordinates)[0];
mPopupPreviewY += (*mCoordinates)[1];
// If the popup cannot be shown above the key, put it on the side
GetLocationOnScreen(mCoordinates);
if (mPopupPreviewY + (*mCoordinates)[1] < 0) {
// If the key you're pressing is on the left side of the keyboard, show the popup on
// the right, offset by enough to see at least one key to the left/right.
Int32 keyX, keyW;
key->GetX(&keyX);
key->GetWidth(&keyW);
Int32 tmp = 0;
GetWidth(&tmp);
if (keyX + keyW <= tmp / 2) {
mPopupPreviewX += (Int32)(keyW * 2.5);
}
else {
mPopupPreviewX -= (Int32)(keyW * 2.5);
}
mPopupPreviewY += popupHeight;
}
Boolean showing = FALSE;
if (mPreviewPopup->IsShowing(&showing), showing) {
mPreviewPopup->Update(mPopupPreviewX, mPopupPreviewY,
popupWidth, popupHeight);
}
else {
mPreviewPopup->SetWidth(popupWidth);
mPreviewPopup->SetHeight(popupHeight);
mPreviewPopup->ShowAtLocation(mPopupParent, IGravity::NO_GRAVITY,
mPopupPreviewX, mPopupPreviewY);
}
IView::Probe(mPreviewText)->SetVisibility(IView::VISIBLE);
}
void KeyboardView::SendAccessibilityEventForUnicodeCharacter(
/* [in] */ Int32 eventType,
/* [in] */ Int32 code)
{
Boolean enabled = FALSE;
if (mAccessibilityManager->IsEnabled(&enabled), enabled) {
AutoPtr<IAccessibilityEventHelper> helper;
CAccessibilityEventHelper::AcquireSingleton((IAccessibilityEventHelper**)&helper);
AutoPtr<IAccessibilityEvent> event;
helper->Obtain(eventType, (IAccessibilityEvent**)&event);
OnInitializeAccessibilityEvent(event);
// This is very efficient since the properties are cached.
AutoPtr<IContentResolver> cr;
mContext->GetContentResolver((IContentResolver**)&cr);
AutoPtr<ISettingsSecure> ss;
CSettingsSecure::AcquireSingleton((ISettingsSecure**)&ss);
Int32 value;
ss->GetInt32(cr, ISettingsSecure::ACCESSIBILITY_SPEAK_PASSWORD, 0, &value);
Boolean speakPassword = value != 0;
// Add text only if password announcement is enabled or if headset is
// used to avoid leaking passwords.
String text;
Boolean bval1, bval2;
if (speakPassword
|| (mAudioManager->IsBluetoothA2dpOn(&bval1), bval1)
|| (mAudioManager->IsWiredHeadsetOn(&bval2), bval2))
{
switch (code) {
case IKeyboard::KEYCODE_ALT:
mContext->GetString(R::string::keyboardview_keycode_alt, &text);
break;
case IKeyboard::KEYCODE_CANCEL:
mContext->GetString(R::string::keyboardview_keycode_cancel, &text);
break;
case IKeyboard::KEYCODE_DELETE:
mContext->GetString(R::string::keyboardview_keycode_delete, &text);
break;
case IKeyboard::KEYCODE_DONE:
mContext->GetString(R::string::keyboardview_keycode_done, &text);
break;
case IKeyboard::KEYCODE_MODE_CHANGE:
mContext->GetString(R::string::keyboardview_keycode_mode_change, &text);
break;
case IKeyboard::KEYCODE_SHIFT:
mContext->GetString(R::string::keyboardview_keycode_shift, &text);
break;
case '\n':
mContext->GetString(R::string::keyboardview_keycode_enter, &text);
break;
default: {
StringBuilder info;
info.AppendChar(code);
text = info.ToString();
}
}
}
else if (!mHeadsetRequiredToHearPasswordsAnnounced) {
// We want the waring for required head set to be send with both the
// hover enter and hover exit event, so set the flag after the exit.
if (eventType == IAccessibilityEvent::TYPE_VIEW_HOVER_EXIT) {
mHeadsetRequiredToHearPasswordsAnnounced = true;
}
mContext->GetString(R::string::keyboard_headset_required_to_hear_password, &text);
}
else {
mContext->GetString(R::string::keyboard_password_character_no_headset, &text);
}
AutoPtr<ICharSequence> seq;
CString::New(text, (ICharSequence**)&seq);
AutoPtr<IList> bc;
IAccessibilityRecord::Probe(event)->GetText((IList**)&bc);
bc->Add(seq);
mAccessibilityManager->SendAccessibilityEvent(event);
}
}
ECode KeyboardView::InvalidateAllKeys()
{
Int32 w = 0, h = 0;
GetWidth(&w);
GetHeight(&h);
mDirtyRect->Union(0, 0, w, h);
mDrawPending = TRUE;
Invalidate();
return NOERROR;
}
ECode KeyboardView::InvalidateKey(
/* [in] */ Int32 keyIndex)
{
if (mKeys == NULL) return NOERROR;
if (keyIndex < 0 || keyIndex >= mKeys->GetLength()) {
return NOERROR;
}
IKeyboardKey* key = (*mKeys)[keyIndex];
mInvalidatedKey = key;
Int32 keyX, keyY, keyW, keyH;
key->GetX(&keyX);
key->GetY(&keyY);
key->GetWidth(&keyW);
key->GetHeight(&keyH);
mDirtyRect->Union(keyX + mPaddingLeft, keyY + mPaddingTop,
keyX + keyW + mPaddingLeft, keyY + keyH + mPaddingTop);
OnBufferDraw();
Invalidate(keyX + mPaddingLeft, keyY + mPaddingTop,
keyX + keyW + mPaddingLeft, keyY + keyH + mPaddingTop);
return NOERROR;
}
Boolean KeyboardView::OpenPopupIfRequired(
/* [in] */ IMotionEvent* me)
{
// Check if we have a popup layout specified first.
if (mPopupLayout == 0) {
return FALSE;
}
assert(mKeys != NULL);
if (mCurrentKey < 0 || mCurrentKey >= mKeys->GetLength()) {
return FALSE;
}
AutoPtr<IKeyboardKey> popupKey = (*mKeys)[mCurrentKey];
Boolean result = FALSE;
OnLongPress(popupKey, &result);
if (result) {
mAbortKey = TRUE;
ShowPreview(NOT_A_KEY);
}
return result;
}
ECode KeyboardView::OnLongPress(
/* [in] */ IKeyboardKey* popupKey,
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
Int32 popupKeyboardId = 0;
popupKey->GetPopupResId(&popupKeyboardId);
if (popupKeyboardId != 0) {
mMiniKeyboardContainer = (*mMiniKeyboardCache)[popupKey];
if (mMiniKeyboardContainer == NULL) {
AutoPtr<IContext> context;
GetContext((IContext**)&context);
AutoPtr<IInterface> service;
FAIL_RETURN(context->GetSystemService(IContext::LAYOUT_INFLATER_SERVICE, (IInterface**)&service))
AutoPtr<ILayoutInflater> inflater = ILayoutInflater::Probe(service);
inflater->Inflate(mPopupLayout, NULL, (IView**)&mMiniKeyboardContainer);
AutoPtr<IView> tempView;
mMiniKeyboardContainer->FindViewById(R::id::keyboardView, (IView**)&tempView);
mMiniKeyboard = IKeyboardView::Probe(tempView);
AutoPtr<IView> closeButton;
mMiniKeyboardContainer->FindViewById(R::id::closeButton, (IView**)&closeButton);
if (closeButton != NULL) {
AutoPtr<IViewOnClickListener> closeListener = new CloseButtonClickListener(this);
closeButton->SetOnClickListener(closeListener);
}
AutoPtr<_OnKeyboardActionListener> listener = new _OnKeyboardActionListener(this);
mMiniKeyboard->SetOnKeyboardActionListener(listener);
//mInputView.setSuggest(mSuggest);
AutoPtr<Keyboard> keyboard;
AutoPtr<ICharSequence> popupCharacters;
popupKey->GetPopupCharacters((ICharSequence**)&popupCharacters);
if (popupCharacters != NULL) {
Int32 l = 0, r = 0;
GetPaddingLeft(&l);
GetPaddingRight(&r);
keyboard = new Keyboard();
keyboard->constructor(context, popupKeyboardId, popupCharacters, -1, l + r);
}
else {
keyboard = new Keyboard();
keyboard->constructor(context, popupKeyboardId);
}
((KeyboardView*)mMiniKeyboard.Get())->SetKeyboard((IKeyboard*)keyboard);
((KeyboardView*)mMiniKeyboard.Get())->SetPopupParent(this);
Int32 w = 0, h = 0;
GetWidth(&w);
GetHeight(&h);
mMiniKeyboardContainer->Measure(
View::MeasureSpec::MakeMeasureSpec(w, View::MeasureSpec::AT_MOST),
View::MeasureSpec::MakeMeasureSpec(h, View::MeasureSpec::AT_MOST));
(*mMiniKeyboardCache)[popupKey] = mMiniKeyboardContainer;
}
else {
AutoPtr<IView> tempView;
mMiniKeyboardContainer->FindViewById(R::id::keyboardView, (IView**)&tempView);
mMiniKeyboard = IKeyboardView::Probe(tempView);
}
GetLocationInWindow(mCoordinates);
Int32 keyX, keyY, keyW;
popupKey->GetX(&keyX);
popupKey->GetY(&keyY);
popupKey->GetWidth(&keyW);
mPopupX = keyX + mPaddingLeft;
mPopupY = keyY + mPaddingTop;
Int32 meauseredW = 0, meauseredH = 0;
mMiniKeyboardContainer->GetMeasuredWidth(&meauseredW);
mPopupX = mPopupX + keyW - meauseredW;
mMiniKeyboardContainer->GetMeasuredHeight(&meauseredH);
mPopupY = mPopupY - meauseredH;
Int32 paddingRight = 0, paddingBottom = 0;
mMiniKeyboardContainer->GetPaddingRight(&paddingRight);
Int32 x = mPopupX + paddingRight + (*mCoordinates)[0];
mMiniKeyboardContainer->GetPaddingBottom(&paddingBottom);
Int32 y = mPopupY + paddingBottom + (*mCoordinates)[1];
mMiniKeyboard->SetPopupOffset(x < 0 ? 0 : x, y);
Boolean shifted = FALSE;
IsShifted(&shifted);
Boolean temp = FALSE;
mMiniKeyboard->SetShifted(shifted, &temp);
mPopupKeyboard->SetContentView(IView::Probe(mMiniKeyboardContainer));
mPopupKeyboard->SetWidth(meauseredW);
mPopupKeyboard->SetHeight(meauseredH);
mPopupKeyboard->ShowAtLocation(this, IGravity::NO_GRAVITY, x, y);
mMiniKeyboardOnScreen = TRUE;
//mMiniKeyboard.onTouchEvent(getTranslatedEvent(me));
InvalidateAllKeys();
*res = TRUE;
return NOERROR;
}
*res = FALSE;
return NOERROR;
}
ECode KeyboardView::OnHoverEvent(
/* [in] */ IMotionEvent* event,
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
Boolean enabled = TRUE;
Int32 count = 0;
if ((mAccessibilityManager->IsTouchExplorationEnabled(&enabled), enabled)
&& (event->GetPointerCount(&count), count) == 1) {
Int32 action = 0;
event->GetAction(&action);
switch (action) {
case IMotionEvent::ACTION_HOVER_ENTER: {
event->SetAction(IMotionEvent::ACTION_DOWN);
} break;
case IMotionEvent::ACTION_HOVER_MOVE: {
event->SetAction(IMotionEvent::ACTION_MOVE);
} break;
case IMotionEvent::ACTION_HOVER_EXIT: {
event->SetAction(IMotionEvent::ACTION_UP);
} break;
}
return OnTouchEvent(event, res);
}
*res = TRUE;
return NOERROR;
}
ECode KeyboardView::OnTouchEvent(
/* [in] */ IMotionEvent* me,
/* [out] */ Boolean* res)
{
VALIDATE_NOT_NULL(res);
// Convert multi-pointer up/down events to single up/down events to
// deal with the typical multi-pointer behavior of two-thumb typing
Int32 pointerCount = 0;
me->GetPointerCount(&pointerCount);
Int32 action = 0;
me->GetAction(&action);
Boolean result = FALSE;
Int64 now = 0;
IInputEvent::Probe(me)->GetEventTime(&now);
if (pointerCount != mOldPointerCount) {
if (pointerCount == 1) {
// Send a down event for the latest pointer
Float tX = 0.0, tY = 0.0;
me->GetX(&tX);
me->GetY(&tY);
Int32 tState = 0;
me->GetMetaState(&tState);
AutoPtr<IMotionEvent> down;
MotionEvent::Obtain(now, now, IKeyEvent::ACTION_DOWN,
tX, tY, tState, (IMotionEvent**)&down);
result = OnModifiedTouchEvent(down, FALSE);
IInputEvent::Probe(down)->Recycle();
// If it's an up action, then deliver the up as well.
if (action == IKeyEvent::ACTION_UP) {
result = OnModifiedTouchEvent(me, TRUE);
}
}
else {
Int32 tState = 0;
me->GetMetaState(&tState);
// Send an up event for the last pointer
AutoPtr<IMotionEvent> up;
MotionEvent::Obtain(now, now, IKeyEvent::ACTION_UP,
mOldPointerX, mOldPointerY, tState, (IMotionEvent**)&up);
result = OnModifiedTouchEvent(up, TRUE);
IInputEvent::Probe(up)->Recycle();
}
}
else {
if (pointerCount == 1) {
result = OnModifiedTouchEvent(me, FALSE);
me->GetX(&mOldPointerX);
me->GetY(&mOldPointerY);
}
else {
// Don't do anything when 2 pointers are down and moving.
result = TRUE;
}
}
mOldPointerCount = pointerCount;
*res = result;
return NOERROR;
}
Boolean KeyboardView::OnModifiedTouchEvent(
/* [in] */ IMotionEvent* me,
/* [in] */ Boolean possiblePoly)
{
Float tmpX = 0, tmpY = 0;
me->GetX(&tmpX);
me->GetY(&tmpY);
Int32 touchX = (Int32) tmpX - mPaddingLeft;
Int32 touchY = (Int32) tmpY - mPaddingTop;
if (touchY >= -mVerticalCorrection) {
touchY += mVerticalCorrection;
}
Int32 action = 0;
me->GetAction(&action);
Int64 eventTime = 0;
IInputEvent::Probe(me)->GetEventTime(&eventTime);
Int32 keyIndex = GetKeyIndices(touchX, touchY, NULL);
mPossiblePoly = possiblePoly;
// Track the last few movements to look for spurious swipes.
if (action == IKeyEvent::ACTION_DOWN) mSwipeTracker->Clear();
mSwipeTracker->AddMovement(me);
// Ignore all motion events until a DOWN.
if (mAbortKey
&& action != IKeyEvent::ACTION_DOWN && action != IMotionEvent::ACTION_CANCEL) {
return TRUE;
}
Boolean tmp = FALSE;
if (mGestureDetector->OnTouchEvent(me, &tmp), tmp) {
ShowPreview(NOT_A_KEY);
mHandler->RemoveMessages(MSG_REPEAT);
mHandler->RemoveMessages(MSG_LONGPRESS);
return TRUE;
}
// Needs to be called after the gesture detector gets a turn, as it may have
// displayed the mini keyboard
if (mMiniKeyboardOnScreen && action != IMotionEvent::ACTION_CANCEL) {
return TRUE;
}
switch (action) {
case IKeyEvent::ACTION_DOWN: {
mAbortKey = FALSE;
mStartX = touchX;
mStartY = touchY;
mLastCodeX = touchX;
mLastCodeY = touchY;
mLastKeyTime = 0;
mCurrentKeyTime = 0;
mLastKey = NOT_A_KEY;
mCurrentKey = keyIndex;
mDownKey = keyIndex;
IInputEvent::Probe(me)->GetEventTime(&mDownTime);
mLastMoveTime = mDownTime;
CheckMultiTap(eventTime, keyIndex);
if (keyIndex != NOT_A_KEY) {
AutoPtr< ArrayOf<Int32> > codes;
(*mKeys)[keyIndex]->GetCodes((ArrayOf<Int32>**)&codes);
mKeyboardActionListener->OnPress((*codes.Get())[0]);
}
else {
mKeyboardActionListener->OnPress(0);
}
if (mCurrentKey >= 0) {
Boolean repeatable;
(*mKeys)[mCurrentKey]->IsRepeatable(&repeatable);
if (repeatable) {
mRepeatKeyIndex = mCurrentKey;
AutoPtr<IMessage> msg;
mHandler->ObtainMessage(MSG_REPEAT, (IMessage**)&msg);
Boolean result;
mHandler->SendMessageDelayed(msg, REPEAT_START_DELAY, &result);
RepeatKey();
// Delivering the key could have caused an abort
if (mAbortKey) {
mRepeatKeyIndex = NOT_A_KEY;
break;
}
}
}
if (mCurrentKey != NOT_A_KEY) {
AutoPtr<IMessage> msg;
mHandler->ObtainMessage(MSG_LONGPRESS, me, (IMessage**)&msg);
Boolean result;
mHandler->SendMessageDelayed(msg, LONGPRESS_TIMEOUT, &result);
}
ShowPreview(keyIndex);
break;
}
case IMotionEvent::ACTION_MOVE: {
Boolean continueLongPress = FALSE;
if (keyIndex != NOT_A_KEY) {
if (mCurrentKey == NOT_A_KEY) {
mCurrentKey = keyIndex;
mCurrentKeyTime = eventTime - mDownTime;
}
else {
if (keyIndex == mCurrentKey) {
mCurrentKeyTime += eventTime - mLastMoveTime;
continueLongPress = TRUE;
}
else if (mRepeatKeyIndex == NOT_A_KEY) {
ResetMultiTap();
mLastKey = mCurrentKey;
mLastCodeX = mLastX;
mLastCodeY = mLastY;
mLastKeyTime = mCurrentKeyTime + eventTime - mLastMoveTime;
mCurrentKey = keyIndex;
mCurrentKeyTime = 0;
}
}
}
if (!continueLongPress) {
// Cancel old longpress
mHandler->RemoveMessages(MSG_LONGPRESS);
// Start new longpress if key has changed
if (keyIndex != NOT_A_KEY) {
AutoPtr<IMessage> msg;
mHandler->ObtainMessage(MSG_LONGPRESS, me, (IMessage**)&msg);
Boolean result;
mHandler->SendMessageDelayed(msg, LONGPRESS_TIMEOUT, &result);
}
}
ShowPreview(mCurrentKey);
mLastMoveTime = eventTime;
break;
}
case IKeyEvent::ACTION_UP: {
RemoveMessages();
if (keyIndex == mCurrentKey) {
mCurrentKeyTime += eventTime - mLastMoveTime;
}
else {
ResetMultiTap();
mLastKey = mCurrentKey;
mLastKeyTime = mCurrentKeyTime + eventTime - mLastMoveTime;
mCurrentKey = keyIndex;
mCurrentKeyTime = 0;
}
if (mCurrentKeyTime < mLastKeyTime && mCurrentKeyTime < DEBOUNCE_TIME
&& mLastKey != NOT_A_KEY) {
mCurrentKey = mLastKey;
touchX = mLastCodeX;
touchY = mLastCodeY;
}
ShowPreview(NOT_A_KEY);
for (Int32 i = 0; i < mKeyIndices->GetLength(); ++i) {
(*mKeyIndices)[i] = NOT_A_KEY;
}
// If we're not on a repeating key (which sends on a DOWN event)
if (mRepeatKeyIndex == NOT_A_KEY && !mMiniKeyboardOnScreen && !mAbortKey) {
DetectAndSendKey(mCurrentKey, touchX, touchY, eventTime);
}
InvalidateKey(keyIndex);
mRepeatKeyIndex = NOT_A_KEY;
break;
}
case IMotionEvent::ACTION_CANCEL: {
RemoveMessages();
DismissPopupKeyboard();
mAbortKey = TRUE;
ShowPreview(NOT_A_KEY);
InvalidateKey(mCurrentKey);
break;
}
}
mLastX = touchX;
mLastY = touchY;
return TRUE;
}
Boolean KeyboardView::RepeatKey()
{
IKeyboardKey* key = (*mKeys)[mRepeatKeyIndex];
Int32 keyX, keyY;
key->GetX(&keyX);
key->GetY(&keyY);
DetectAndSendKey(mCurrentKey, keyX, keyY, mLastTapTime);
return TRUE;
}
void KeyboardView::SwipeRight()
{
assert(mKeyboardActionListener != NULL);
mKeyboardActionListener->SwipeRight();
}
void KeyboardView::SwipeLeft()
{
assert(mKeyboardActionListener != NULL);
mKeyboardActionListener->SwipeLeft();
}
void KeyboardView::SwipeUp()
{
assert(mKeyboardActionListener != NULL);
mKeyboardActionListener->SwipeUp();
}
void KeyboardView::SwipeDown()
{
assert(mKeyboardActionListener != NULL);
mKeyboardActionListener->SwipeDown();
}
ECode KeyboardView::Closing()
{
assert(mPreviewPopup != NULL);
Boolean showing = FALSE;
if (mPreviewPopup->IsShowing(&showing), showing) {
mPreviewPopup->Dismiss();
}
RemoveMessages();
DismissPopupKeyboard();
mBuffer = NULL;
mCanvas = NULL;
mMiniKeyboardCache->Clear();
return NOERROR;
}
void KeyboardView::RemoveMessages()
{
mHandler->RemoveMessages(MSG_REPEAT);
mHandler->RemoveMessages(MSG_LONGPRESS);
mHandler->RemoveMessages(MSG_SHOW_PREVIEW);
}
ECode KeyboardView::OnDetachedFromWindow()
{
View::OnDetachedFromWindow();
Closing();
return NOERROR;
}
void KeyboardView::DismissPopupKeyboard()
{
assert(mPopupKeyboard != NULL);
Boolean showing = FALSE;
if (mPopupKeyboard->IsShowing(&showing), showing) {
mPopupKeyboard->Dismiss();
mMiniKeyboardOnScreen = FALSE;
InvalidateAllKeys();
}
}
ECode KeyboardView::HandleBack(
/* [out] */ Boolean* res)
{
assert(res != NULL && mPopupKeyboard != NULL);
Boolean showing = FALSE;
if (mPopupKeyboard->IsShowing(&showing), showing) {
DismissPopupKeyboard();
*res = TRUE;
return NOERROR;
}
*res = FALSE;
return NOERROR;
}
void KeyboardView::ResetMultiTap()
{
mLastSentIndex = NOT_A_KEY;
mTapCount = 0;
mLastTapTime = -1;
mInMultiTap = FALSE;
}
void KeyboardView::CheckMultiTap(
/* [in] */ Int64 eventTime,
/* [in] */ Int32 keyIndex)
{
if (keyIndex == NOT_A_KEY) return;
IKeyboardKey* key = (*mKeys)[keyIndex];
AutoPtr< ArrayOf<Int32> > codes;
key->GetCodes((ArrayOf<Int32>**)&codes);
if (codes->GetLength() > 1) {
mInMultiTap = TRUE;
if (eventTime < mLastTapTime + MULTITAP_INTERVAL
&& keyIndex == mLastSentIndex) {
mTapCount = (mTapCount + 1) % codes->GetLength();
return;
}
else {
mTapCount = -1;
return;
}
}
if (eventTime > mLastTapTime + MULTITAP_INTERVAL || keyIndex != mLastSentIndex) {
ResetMultiTap();
}
}
} // namespace InputMethodService
} // namespace Droid
} // namespace Elastos
|
bosuyun/apaas-community
|
platform-process/src/main/java/com/bosuyun/platform/process/eventbus/message/DataOpMessage.java
|
<filename>platform-process/src/main/java/com/bosuyun/platform/process/eventbus/message/DataOpMessage.java
package com.bosuyun.platform.process.eventbus.message;
import com.bosuyun.platform.common.exception.BizzException;
import com.bosuyun.platform.common.misc.DataNode;
import com.bosuyun.platform.common.misc.DataNodeList;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
import static com.bosuyun.platform.common.utils.JsonUtils.toJsonString;
/**
* 数据操作
* <p>
* Created by liuyuancheng on 2021/6/19 <br/>
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class DataOpMessage extends EventMessage {
/**
* 操作
*/
private String action;
/**
* 数据数据
*/
private DataNodeList inputData;
/**
* update前的老数据
*/
private DataNodeList formerData;
/**
* 要更新的字段
*/
private List<String> updateFields;
private final static String DATA_OP_UPDATE = "update";
private final static String DATA_OP_QUERY = "query";
private final static String DATA_OP_INSERT = "insert";
private final static String DATA_OP_INSERT_MANY = "insertMany";
private final static String DATA_OP_DELETE = "delete";
private final static String DATA_OP_UNDO_DELETE = "undoDelete";
private final static String DATA_OP_DELETE_MANY = "deleteMany";
{
setMessageType(this.getClass().getSimpleName());
}
public DataOpMessage update() {
this.setAction(DATA_OP_UPDATE);
return this;
}
public DataOpMessage insert() {
this.action = DATA_OP_INSERT;
return this;
}
public DataOpMessage insertMany() {
this.action =DATA_OP_INSERT_MANY;
return this;
}
public DataOpMessage undoDelete() {
this.action =DATA_OP_UNDO_DELETE;
return this;
}
public DataOpMessage delete() {
this.action = DATA_OP_DELETE;
return this;
}
public DataOpMessage deleteMany() {
this.action = DATA_OP_DELETE_MANY;
return this;
}
public DataOpMessage query() {
this.action = DATA_OP_QUERY;
return this;
}
public DataOpMessage setInputData(DataNodeList data) {
this.inputData = data;
return this;
}
public DataOpMessage setInputData(DataNode data) {
this.inputData = new DataNodeList(data);
return this;
}
public DataOpMessage setFormerData(DataNodeList data) {
this.formerData = data;
return this;
}
public DataOpMessage setFormerData(DataNode data) {
if (!this.action.equals(DATA_OP_UPDATE)) {
throw new BizzException("updateFields only support for update action.");
}
if (this.inputData.size() > 1) {
throw new BizzException("Only support update 1 item, or dose not set oldData.");
}
this.formerData = new DataNodeList(data);
return this;
}
/**
* 被更新的字段
*
* @param updateFields
* @return
*/
public DataOpMessage setUpdateFields(List<String> updateFields) {
if (!this.action.equals(DATA_OP_UPDATE)) {
throw new BizzException("updateFields only support for update action.");
}
this.updateFields = updateFields;
return this;
}
@Override
public String toString() {
return toJsonString(this);
}
}
|
ak47wyh/paascloud-store
|
paascloud-common/paascloud-security-core/src/main/java/com/paascloud/security/core/social/weixin/connect/WeixinAccessGrant.java
|
/*
* Copyright (c) 2018. paascloud.net All Rights Reserved.
* 项目名称:paascloud快速搭建企业级分布式微服务平台
* 类名称:WeixinAccessGrant.java
* 创建人:刘兆明
* 联系方式:<EMAIL>
* 开源地址: https://github.com/paascloud
* 博客地址: http://blog.paascloud.net
* 项目官网: http://paascloud.net
*/
package com.paascloud.security.core.social.weixin.connect;
import org.springframework.social.oauth2.AccessGrant;
/**
* 微信的access_token信息。与标准OAuth2协议不同,微信在获取access_token时会同时返回openId,并没有单独的通过accessToke换取openId的服务
* <p>
* 所以在这里继承了标准AccessGrant,添加了openId字段,作为对微信access_token信息的封装。
*
* @author <EMAIL>
*/
public class WeixinAccessGrant extends AccessGrant {
private static final long serialVersionUID = -7243374526633186782L;
private String openId;
/**
* Instantiates a new Weixin access grant.
*/
public WeixinAccessGrant() {
super("");
}
/**
* Instantiates a new Weixin access grant.
*
* @param accessToken the access token
* @param scope the scope
* @param refreshToken the refresh token
* @param expiresIn the expires in
*/
public WeixinAccessGrant(String accessToken, String scope, String refreshToken, Long expiresIn) {
super(accessToken, scope, refreshToken, expiresIn);
}
/**
* Gets open id.
*
* @return the openId
*/
public String getOpenId() {
return openId;
}
/**
* Sets open id.
*
* @param openId the openId to set
*/
public void setOpenId(String openId) {
this.openId = openId;
}
}
|
GMHDBJD/ticdc
|
engine/pkg/externalresource/resourcemeta/model/model.go
|
<filename>engine/pkg/externalresource/resourcemeta/model/model.go<gh_stars>10-100
// Copyright 2022 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package model
import (
"path"
"strings"
pb "github.com/pingcap/tiflow/engine/enginepb"
"github.com/pingcap/tiflow/engine/model"
derror "github.com/pingcap/tiflow/engine/pkg/errors"
ormModel "github.com/pingcap/tiflow/engine/pkg/orm/model"
"github.com/pingcap/tiflow/engine/pkg/tenant"
)
type (
// WorkerID alias worker id string
WorkerID = string
// ResourceID should be in the form of `/<type>/<unique-name>`, currently
// only local type is available.
ResourceID = string
// JobID alias job id string
JobID = string
// ExecutorID alias model.ExecutorID
ExecutorID = model.ExecutorID
)
// ResourceUpdateColumns is used in gorm update
var ResourceUpdateColumns = []string{
"updated_at",
"project_id",
"id",
"job_id",
"worker_id",
"executor_id",
"deleted",
}
// ResourceMeta is the records stored in the metastore.
type ResourceMeta struct {
ormModel.Model
ProjectID tenant.ProjectID `json:"project-id" gorm:"column:project_id;type:varchar(64) not null"`
ID ResourceID `json:"id" gorm:"column:id;type:varchar(64) not null;uniqueIndex:uidx_rid;index:idx_rji,priority:2;index:idx_rei,priority:2"`
Job JobID `json:"job" gorm:"column:job_id;type:varchar(64) not null;index:idx_rji,priority:1"`
Worker WorkerID `json:"worker" gorm:"column:worker_id;type:varchar(64) not null"`
Executor ExecutorID `json:"executor" gorm:"column:executor_id;type:varchar(64) not null;index:idx_rei,priority:1"`
GCPending bool `json:"gc-pending" gorm:"column:gc_pending;type:BOOLEAN"`
// TODO soft delete has not be implemented, because it requires modifying too many
// unit tests in engine/pkg/orm
Deleted bool `json:"deleted" gorm:"column:deleted;type:BOOLEAN"`
}
// GetID implements dataset.DataEntry
func (m *ResourceMeta) GetID() string {
return m.ID
}
// ToQueryResourceResponse converts the ResourceMeta to pb.QueryResourceResponse
func (m *ResourceMeta) ToQueryResourceResponse() *pb.QueryResourceResponse {
return &pb.QueryResourceResponse{
CreatorExecutor: string(m.Executor),
JobId: m.Job,
CreatorWorkerId: m.Worker,
}
}
// Map is used in gorm update
func (m *ResourceMeta) Map() map[string]interface{} {
return map[string]interface{}{
"project_id": m.ProjectID,
"id": m.ID,
"job_id": m.Job,
"worker_id": m.Worker,
"executor_id": m.Executor,
"deleted": m.Deleted,
}
}
// ResourceType represents the type of the resource
type ResourceType string
// ResourceName is the ResourceID with its type prefix removed.
// For example, the resource name of `/local/resource-1` is `resource-1`.
type ResourceName = string
// Define all supported resource types
const (
ResourceTypeLocalFile = ResourceType("local")
ResourceTypeS3 = ResourceType("s3")
)
// ParseResourcePath returns the ResourceType and the path suffix.
func ParseResourcePath(rpath ResourceID) (ResourceType, ResourceName, error) {
if !strings.HasPrefix(rpath, "/") {
return "", "", derror.ErrIllegalResourcePath.GenWithStackByArgs(rpath)
}
rpath = strings.TrimPrefix(rpath, "/")
segments := strings.Split(rpath, "/")
if len(segments) == 0 {
return "", "", derror.ErrIllegalResourcePath.GenWithStackByArgs(rpath)
}
var resourceType ResourceType
switch segments[0] {
case "local":
resourceType = ResourceTypeLocalFile
case "s3":
resourceType = ResourceTypeS3
default:
return "", "", derror.ErrIllegalResourcePath.GenWithStackByArgs(rpath)
}
suffix := path.Join(segments[1:]...)
return resourceType, suffix, nil
}
|
clouserw/olympia
|
apps/addons/management/commands/import_missing_gp_favorites.py
|
from getpass import getpass
from optparse import make_option
from time import time
from django.core.management.base import BaseCommand
from django.db import IntegrityError, connection as django_connection
import MySQLdb as mysql
from users.models import UserProfile
class Command(BaseCommand):
"""
Import from the personas database:
`host`: the host of the personas database
`database`: the personas database, eg: personas
`user`: the user of the personas database
"""
option_list = BaseCommand.option_list + (
make_option('--host', action='store',
dest='host', help='The host of MySQL'),
make_option('--db', action='store',
dest='db', help='The database in MySQL'),
make_option('--user', action='store',
dest='user', help='The database user'),
)
def connect(self, **options):
options = dict([(k, v) for k, v in options.items() if k in
['host', 'db', 'user'] and v])
options['passwd'] = getpass('MySQL Password: ')
self.connection = mysql.connect(**options)
self.cursor = self.connection.cursor()
self.cursor_z = django_connection.cursor()
self.users = {}
self.addons = {}
def count_favorites(self):
self.cursor.execute('SELECT count(username) FROM favorites')
return self.cursor.fetchone()[0]
def get_favorite_collection(self, collection_id, addon_id):
self.cursor_z.execute('SELECT id FROM addons_collections '
'WHERE collection_id = %s AND addon_id = %s '
'LIMIT 1', (collection_id, addon_id))
try:
return self.cursor_z.fetchone()[0]
except TypeError:
return None
def get_user_by_gp_username(self, gp_username):
if gp_username not in self.users:
self.cursor.execute('SELECT email FROM users WHERE username = %s',
gp_username)
email = self.cursor.fetchone()[0]
try:
profile = UserProfile.objects.get(email=email)
self.users[gp_username] = (profile,
profile.favorites_collection().id)
except UserProfile.DoesNotExist:
print('[ERROR] Could not find user with GP username "%s"' %
gp_username)
self.users[gp_username] = None, None
profile = self.users.get(gp_username)
return profile
def get_addon_id_from_persona_id(self, persona_id):
if persona_id not in self.addons:
self.cursor_z.execute(
'SELECT addon_id FROM personas WHERE persona_id = %s',
persona_id)
try:
self.addons[persona_id] = self.cursor_z.fetchone()[0]
except:
print('[ERROR] Could not find add-on with persona_id "%s"' %
persona_id)
self.addons[persona_id] = None
addon_id = self.addons.get(persona_id)
return addon_id
def do_import(self, limit, offset):
added, ignored, errored = 0, 0, 0
self.cursor.execute(
'SELECT username, id, added FROM favorites '
'ORDER BY username, id LIMIT %s OFFSET %s' % (limit, offset))
favorites = self.cursor.fetchall()
for gp_username, persona_id, date_added in favorites:
profile, faves_id = self.get_user_by_gp_username(gp_username)
if not profile:
print('[ERROR] Could not add favourite "%s" because of bad '
'username "%s"' % (persona_id, gp_username))
errored += 1
continue
addon_id = self.get_addon_id_from_persona_id(persona_id)
if not addon_id:
print('[ERROR] Could not add favourite "%s" because of bad '
'persona_id' % persona_id)
errored += 1
continue
coll = self.get_favorite_collection(collection_id=faves_id,
addon_id=addon_id)
if coll:
print '[IGNORED] Favourite already exists: %s' % coll
ignored += 1
continue
data = {
'date_added': date_added,
'addon_id': addon_id,
'persona_id': persona_id,
'collection_id': faves_id,
'user_id': profile.id
}
try:
self.cursor_z.execute("""
INSERT INTO addons_collections
(created, modified, addon_id, collection_id, user_id)
VALUES (%(date_added)s, %(date_added)s, %(addon_id)s,
%(collection_id)s, %(user_id)s)
""", data)
print '[ADDED] Favourite added: %s' % data
added += 1
except IntegrityError, e:
print '[ERROR] Could not add favourite: %s\n%s' % (data, e)
errored += 1
return added, ignored, errored
def handle(self, *args, **options):
t_total_start = time()
self.connect(**options)
print "You're running a script to associate more favourites!"
total_added, total_ignored, total_errored = 0, 0, 0
count = self.count_favorites()
print 'Found %s users. Grab some tea and chillax, bro.' % count
step = 2500
start = options.get('start', 0)
print 'Starting at offset: %s' % start
for offset in xrange(start, count, step):
t_start = time()
added, ignored, errored = self.do_import(offset, step)
total_added += added
total_ignored += ignored
total_errored += errored
t_average = (1 / ((time() - t_total_start) /
(offset - start + step)))
print "> %.2fs for %s favourites. Averaging %.2f favourites/s" % (
time() - t_start, step, t_average)
print '\nDone. Total time: %s seconds' % (time() - t_start)
print 'Favourites added: %s' % added
print 'Bad favourites: %s' % errored
print 'Already favourited: %s' % ignored
|
gsosad/Programacion-I
|
actividades/sesion1/albertogomez/actividad2/main.cpp
|
#include <iostream>
using namespace std;
class Mascota{
public:
//constructor
Mascota(string _nombre, string _especie, unsigned short int _edad)
{
nombre = _nombre;
especie = _especie;
edad = _edad;
}
//variables miembro (atributos)
string nombre;
string especie;
unsigned short edad;
Mascota (){}
};
class Persona{
public:
//constructor
Persona(string _nombre, unsigned short int _peso, Mascota _mascota)
{
nombre = _nombre;
peso = _peso;
mascota = _mascota;
}
//variables miembro (atributos)
string nombre;
unsigned short peso;
Mascota mascota;
};
int main()
{
Mascota perro("Hachiko","<NAME>", 5);
Persona chico("Alberto", 85, perro);
cout << "Hola " << chico.nombre <<" tu mascota favorita es un " << chico.mascota.especie << " y se llama " << chico.mascota.nombre << endl;
return 0;
};
|
morind/warp10-platform-dmn
|
warp10/src/main/java/io/warp10/script/functions/SORTBY.java
|
//
// Copyright 2016 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package io.warp10.script.functions;
import io.warp10.continuum.gts.GTSHelper;
import io.warp10.continuum.gts.GeoTimeSerie;
import io.warp10.continuum.gts.MetadataTextComparator;
import io.warp10.continuum.store.thrift.data.Metadata;
import io.warp10.script.NamedWarpScriptFunction;
import io.warp10.script.WarpScriptStack.Macro;
import io.warp10.script.WarpScriptStackFunction;
import io.warp10.script.WarpScriptException;
import io.warp10.script.WarpScriptStack;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Sort a list of GTS according to a macro
*/
public class SORTBY extends NamedWarpScriptFunction implements WarpScriptStackFunction {
private static final Comparator<GeoTimeSerie> LAST_COMPARATOR = new Comparator<GeoTimeSerie>() {
private final Comparator<Metadata> INNER_COMP = new MetadataTextComparator(null);
@Override
public int compare(GeoTimeSerie o1, GeoTimeSerie o2) {
//
// Empty GTS are at the end
//
if (0 == o1.size()) {
if (0 == o2.size()) {
//
// If both GTS are empty, order them by their class/labels
//
return INNER_COMP.compare(o1.getMetadata(), o2.getMetadata());
} else {
return 1;
}
}
if (0 == o2.size()) {
return -1;
}
//
// Sort GTS if needed in reverse order
//
GTSHelper.sort(o1, true);
GTSHelper.sort(o2, true);
Object last1 = GTSHelper.valueAtIndex(o1, 0);
Object last2 = GTSHelper.valueAtIndex(o2, 0);
int res = 0;
if (last1 instanceof Long && last2 instanceof Long) {
res = ((Long) last1).compareTo((Long) last2);
} else if (last1 instanceof Double && last2 instanceof Double) {
res = ((Double) last1).compareTo((Double) last2);
} else if (last1 instanceof String && last2 instanceof String) {
res = ((String) last1).compareTo((String) last2);
} else if (last1 instanceof Boolean && last2 instanceof Boolean) {
if (((Boolean) last1).equals((Boolean) last2)) {
res = 0;
} else if (Boolean.TRUE.equals(last1)) {
return 1;
} else {
return -1;
}
} else if (last1 instanceof Long && last2 instanceof Double || last1 instanceof Double && last2 instanceof Long) {
res = ((Double)((Number) last1).doubleValue()).compareTo((Double)((Number) last2).doubleValue());
} else {
// In last resort, compare the String representations
res = last1.toString().compareTo(last2.toString());
}
if (0 != res) {
return res;
}
//
// Compare last ticks if values are identical
//
long tick1 = GTSHelper.tickAtIndex(o1, 0);
long tick2 = GTSHelper.tickAtIndex(o2, 0);
if (tick1 > tick2) {
return -1;
} else if (tick1 < tick2) {
return 1;
}
//
// Compare metadatas if values and last ticks are identical
//
return INNER_COMP.compare(o1.getMetadata(), o2.getMetadata());
}
};
public SORTBY(String name) {
super(name);
}
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
Object top = stack.pop();
if (!(top instanceof Macro)) {
throw new WarpScriptException(getName() + " expects a macro on top of the stack.");
}
Macro macro = (Macro) top;
top = stack.pop();
//
// Check if list on the top of the stack is a list of GTS
//
if (!(top instanceof List)) {
throw new WarpScriptException(getName() + " operates on a list of Geo Time Series.");
}
for (Object o: ((List) top)) {
if (!(o instanceof GeoTimeSerie)) {
throw new WarpScriptException(getName() + " operates on a list of Geo Time Series.");
}
}
//
// Generate the result of the macro for the various GTS
//
final Map<GeoTimeSerie,Object> values = new HashMap<GeoTimeSerie,Object>();
String type = null;
for (Object gts: (List) top) {
stack.push(gts);
stack.exec(macro);
Object value = stack.pop();
String valtype = null;
if (value instanceof Long) {
valtype = "LONG";
} else if (value instanceof Double) {
valtype = "DOUBLE";
} else if (value instanceof String) {
valtype = "STRING";
}
if (null == value || null == valtype || (null != type && (!type.equals(valtype)))) {
throw new WarpScriptException(getName() + " expects its macro to return a non null double,long or string in a consistent manner.");
}
type = valtype;
values.put((GeoTimeSerie) gts, value);
}
final String valtype = type;
Collections.sort((List<GeoTimeSerie>) top, new Comparator<GeoTimeSerie>() {
@Override
public int compare(GeoTimeSerie o1, GeoTimeSerie o2) {
if ("LONG".equals(valtype)) {
return ((Long) values.get(o1)).compareTo((Long) values.get(o2));
} else if ("DOUBLE".equals(valtype)) {
return ((Double) values.get(o1)).compareTo((Double) values.get(o2));
} else if ("STRING".equals(valtype)) {
return ((String) values.get(o1)).compareTo((String) values.get(o2));
} else {
return 0;
}
}
});
stack.push(top);
return stack;
}
}
|
ebabel-eu/lion
|
packages/collapsible/index.js
|
<reponame>ebabel-eu/lion<filename>packages/collapsible/index.js
export { LionCollapsible } from './src/LionCollapsible.js';
|
vividos/OldStuff
|
C64/src/d64view/source/doctempl.cpp
|
<gh_stars>1-10
/*
d64view - a d64 disk image viewer
Copyright (c) 2002,2003,2016 <NAME>
*/
/*! \file doctempl.cpp
\brief custom document template
checking for already openend files
*/
// needed includes
#include "common.hpp"
#include "doctempl.hpp"
// d64view_doc_template methods
wxDocument* d64view_doc_template::CreateDocument(const wxString& path, long flags)
{
// search through all documents if it is already open
wxList& doclist = m_documentManager->GetDocuments();
size_t max = doclist.GetCount();
for(size_t n=0; n<max; n++)
{
wxDocument* doc = reinterpret_cast<wxDocument*>(doclist.Item(n)->GetData());
if (doc->GetFilename()==path)
{
// activate first view, don't create document
wxView* view = doc->GetFirstView();
view->Activate(true);
return NULL;
}
}
return wxDocTemplate::CreateDocument(path,flags);
}
|
WIZARD-CXY/pl
|
lintcode/binarytreezigzagtravesal.cpp
|
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: A list of lists of integer include
* the zigzag level order traversal of its nodes' values
*/
public:
vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
// write your code here
vector<vector<int> > res;
if(root==NULL){
return res;
}
queue<TreeNode*> qq;
qq.push(root);
int count=1;
int level=1;
vector<int> tmp;
while(!qq.empty()){
TreeNode* p=qq.front();
qq.pop();
tmp.push_back(p->val);
count--;
if(p->left){
qq.push(p->left);
}
if(p->right){
qq.push(p->right);
}
if(count==0){
if(level&1){
res.push_back(tmp);
}else{
reverse(tmp.begin(),tmp.end());
res.push_back(tmp);
}
tmp.clear();
level++;
count=qq.size();
}
}
return res;
}
};
|
Amareshwari/incubator-lens
|
lens-ml-lib/src/main/java/org/apache/lens/ml/algo/spark/lr/LogisticRegressionAlgo.java
|
<reponame>Amareshwari/incubator-lens
/**
* 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.lens.ml.algo.spark.lr;
import java.util.Map;
import org.apache.lens.ml.algo.api.AlgoParam;
import org.apache.lens.ml.algo.api.Algorithm;
import org.apache.lens.ml.algo.spark.BaseSparkAlgo;
import org.apache.lens.ml.algo.spark.BaseSparkClassificationModel;
import org.apache.lens.server.api.error.LensException;
import org.apache.spark.mllib.classification.LogisticRegressionModel;
import org.apache.spark.mllib.classification.LogisticRegressionWithSGD;
import org.apache.spark.mllib.regression.LabeledPoint;
import org.apache.spark.rdd.RDD;
/**
* The Class LogisticRegressionAlgo.
*/
@Algorithm(name = "spark_logistic_regression", description = "Spark logistic regression algo")
public class LogisticRegressionAlgo extends BaseSparkAlgo {
/** The iterations. */
@AlgoParam(name = "iterations", help = "Max number of iterations", defaultValue = "100")
private int iterations;
/** The step size. */
@AlgoParam(name = "stepSize", help = "Step size", defaultValue = "1.0d")
private double stepSize;
/** The min batch fraction. */
@AlgoParam(name = "minBatchFraction", help = "Fraction for batched learning", defaultValue = "1.0d")
private double minBatchFraction;
/**
* Instantiates a new logistic regression algo.
*
* @param name the name
* @param description the description
*/
public LogisticRegressionAlgo(String name, String description) {
super(name, description);
}
/*
* (non-Javadoc)
*
* @see org.apache.lens.ml.spark.algos.BaseSparkAlgo#parseAlgoParams(java.util.Map)
*/
@Override
public void parseAlgoParams(Map<String, String> params) {
iterations = getParamValue("iterations", 100);
stepSize = getParamValue("stepSize", 1.0d);
minBatchFraction = getParamValue("minBatchFraction", 1.0d);
}
/*
* (non-Javadoc)
*
* @see org.apache.lens.ml.spark.algos.BaseSparkAlgo#trainInternal(java.lang.String, org.apache.spark.rdd.RDD)
*/
@Override
protected BaseSparkClassificationModel trainInternal(String modelId, RDD<LabeledPoint> trainingRDD)
throws LensException {
LogisticRegressionModel lrModel = LogisticRegressionWithSGD.train(trainingRDD, iterations, stepSize,
minBatchFraction);
return new LogitRegressionClassificationModel(modelId, lrModel);
}
}
|
tiwariut/journal
|
routes/auth.js
|
<gh_stars>0
const express = require('express');
const validator = require('express-joi-validator');
const multer = require('multer');
const upload = multer({ dest: 'public/uploads/' });
const {
login,
logout,
getMe,
updateDetails,
updatePassword
} = require('../controllers/auth');
const {
loginSchema,
updateDetailsSchema,
updatePasswordSchema
} = require('../validations/auth');
const router = express.Router();
const { protect } = require('../middleware/auth');
router.post('/login', validator(loginSchema), login);
router.put('/logout', protect, logout);
router.get('/me', protect, getMe);
router.put(
'/updatedetails',
protect,
validator(updateDetailsSchema),
updateDetails
);
router.put(
'/updatepassword',
protect,
validator(updatePasswordSchema),
updatePassword
);
module.exports = router;
|
vuexp/vuexp
|
tests/e2e/pageObjects/components/searchBarPage.js
|
const checkScreenshot = require('../../commonCommands/checkScreenshotCommand');
module.exports = {
url: function() {
return this.api.launchUrl;
},
elements: {
searchBarBackground: '#searchbar__docs',
searchTextInputField: '.vxp-searchbar__search-input',
hintTextInputField: '#searchbar__hint__input',
textOutputField: '#searchbar__text__input',
hintColorDropdown: '#searchbar__textFieldHintColor__input',
hintColor_blue: '#searchbar__textFieldHintColor__input option[value="blue"]',
backgroundColorDropdown: '#searchbar__textFieldBackgroundColor__input',
backgroundColor_red: '#searchbar__textFieldBackgroundColor__input option[value="red"]',
showLastEventFields: '#searchbar_event_label',
submitButton: '.vxp-label.vxp-searchbar__search-icon',
clearButton: '.vxp-label.vxp-searchbar__clear-icon',
},
commands: [
checkScreenshot(),
{
checkInitialElements: function() {
this.expect.element('@searchTextInputField').to.be.visible;
this.expect.element('@hintTextInputField').to.be.visible;
this.expect.element('@textOutputField').to.be.visible;
this.expect.element('@hintColorDropdown').to.be.visible;
this.expect.element('@backgroundColorDropdown').to.be.visible;
this.expect.element('@showLastEventFields').to.be.visible;
return this;
},
setHintToSearchBar: function(text) {
return this.waitForElementVisible('@hintTextInputField', 10000)
.clearValue('@hintTextInputField')
.setValue('@hintTextInputField', text);
},
setSearchTextToSearchBar: function(text) {
return this.waitForElementVisible('@searchTextInputField', 10000)
.clearValue('@searchTextInputField')
.setValue('@searchTextInputField', text);
},
setBackgroundColor: function() {
return this.waitForElementVisible('@backgroundColorDropdown', 10000)
.click('@backgroundColorDropdown')
.waitForElementVisible('@backgroundColor_red', 10000)
.click('@backgroundColor_red');
},
setHintColor: function() {
return this.waitForElementVisible('@hintColorDropdown', 10000)
.click('@hintColorDropdown')
.waitForElementVisible('@hintColor_blue', 10000)
.click('@hintColor_blue');
},
clickSubmitButton() {
return this.waitForElementVisible('@submitButton', 10000).click('@submitButton');
},
clickClearButton() {
return this.waitForElementVisible('@clearButton', 10000).click('@clearButton');
},
perform: function(callback) {
this.api.perform(callback);
return this;
},
},
],
};
|
Greedylightning/LeetCode_Second
|
Array/ContainsDuplicate2.java
|
import java.util.Map;
class ContainsDuplicate2{
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> temp = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++){
if(temp.containsKey(nums[i]) && Math.abs(i - temp.get(nums[i])) <= k) return true;
temp.put(nums[i], i);
}
return false;
}
}
|
r0hack/WavesGUI
|
src/modules/ui/directives/transaction/types/exchange/Exchange.js
|
(function () {
'use strict';
/**
* @param {User} user
* @param {app.utils} utils
* @return {Exchange}
*/
const controller = function (user, utils) {
class Exchange {
/**
* {object}
*/
props = null;
$postLink() {
this.typeName = this.props.typeName;
this.amountAssetName = this.getAssetName(this.props.amount.asset);
this.priceAssetName = this.getAssetName(this.props.price.asset);
this.isScamAmount = !!user.scam[this.props.amount.asset];
this.isScamPrice = !!user.scam[this.props.price.asset];
this.amountParams = {
sign: this.typeName === 'exchange-buy' ? '+' : '–',
amount: this.props.amount.toFormat(),
name: this.props.amount.asset.name
};
this.priceParams = {
sign: this.typeName === 'exchange-buy' ? '-' : '+',
amount: utils.getExchangeTotalPrice(this.props.amount, this.props.price),
name: this.props.price.asset.name
};
}
/**
* @param {{id: string, name: string}} asset
* @return {string}
*/
getAssetName(asset) {
try {
return !user.scam[asset.id] ? asset.name : '';
} catch (e) {
return '';
}
}
}
return new Exchange();
};
controller.$inject = [
'user',
'utils'
];
angular.module('app.ui').component('wExchangeData', {
bindings: {
props: '<'
},
templateUrl: 'modules/ui/directives/transaction/types/exchange/exchange.html',
controller
});
})();
|
AlexTexis/platziCoursesFrontend
|
src/services/configurationFetch.js
|
<reponame>AlexTexis/platziCoursesFrontend
//abort suscription api fetch
const abortController = new AbortController()
export const configGet = () => ({
method : 'GET',
headers : new Headers({
'Content-Type' : 'application/json'
}),
signal : abortController.signal
})
export const configPost = (input) => ({
method : 'POST',
headers : new Headers({
'Content-Type' : 'application/json'
}),
body : JSON.stringify(input),
signal : abortController.signal
})
export const configPut = (input) => ({
method : 'PUT',
headers : new Headers({
'Content-Type' : 'application/json'
}),
body : JSON.stringify(input),
signal : abortController.signal
})
export const configDelete = () => ({
method : 'DELETE',
headers : new Headers({
'Content-Type' : 'application/json'
}),
signal : abortController.signal
})
|
npocmaka/Windows-Server-2003
|
admin/activec/designer/vb98ctls/mssnapr/mssnapr/tls.h
|
//=--------------------------------------------------------------------------=
// tls.h
//=--------------------------------------------------------------------------=
// Copyright (c) 1999, Microsoft Corp.
// All Rights Reserved
// Information Contained Herein Is Proprietary and Confidential.
//=--------------------------------------------------------------------------=
//
// CTls class definition
//
// This object manages TLS on behalf of all objects in the designer runtime.
//
//=--------------------------------------------------------------------------=
#ifndef _TLS_DEFINED_
#define _TLS_DEFINED_
// Any code in the designer runtime that needs TLS needs to reserve a slot
// by adding a #define for itself (e.g. TLS_SLOT_PPGWRAP) and incrementing
// TLS_SLOT_COUNT. To use TLS call CTls::Set and CTls::Get rather than the
// Win32 TlsSetValue/TlsGetValue.
#define TLS_SLOT_PPGWRAP 0
#define TLS_SLOT_COUNT 1
class CTls
{
public:
static void Initialize();
static void Destroy();
static HRESULT Set(UINT uiSlot, void *pvData);
static HRESULT Get(UINT uiSlot, void **ppvData);
private:
static DWORD m_adwTlsIndexes[TLS_SLOT_COUNT];
static BOOL m_fAllocedTls;
};
#endif // _TLS_DEFINED_
|
rbourdon/rorybourdon
|
components/layout.js
|
import Head from "next/head";
import { ThemeContext } from "styled-components";
import { motion } from "framer-motion";
import { useContext } from "react";
function Layout({ children }) {
const theme = useContext(ThemeContext);
return (
<motion.div
style={{
backgroundColor: theme.primary_light,
overflow: "hidden",
width: "100%",
}}
>
<Head>
<link rel="manifest" href="/site.webmanifest" />
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5" />
<meta name="msapplication-TileColor" content="#00aba9" />
<meta name="theme-color" content="#ffffff" />
<meta name="author" content="<NAME>" />
<meta charSet="utf-8" />
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<script
dangerouslySetInnerHTML={{
__html: `
(function () {
var currentTheme;
function changeTheme(inputTheme) {
if (inputTheme === "dark") {
const theme = themeConfig.dark;
for (let key in theme) {
setCSSVar(key, theme[key]);
}
localStorage.setItem("theme", inputTheme);
} else {
const theme = themeConfig.light;
for (let key in theme) {
setCSSVar(key, theme[key]);
}
localStorage.setItem("theme", inputTheme);
}
}
function setCSSVar(property, color) {
document.documentElement.style.setProperty(property, color);
}
try {
const sysDark = window.matchMedia('(prefers-color-scheme: dark)').matches === true;
const savedTheme = localStorage.getItem("theme");
if (savedTheme) {
currentTheme = savedTheme;
}
else if (sysDark)
{
currentTheme = "dark";
}
else
{
currentTheme = "light";
}
var themeConfig = {
dark: {
"--color-name": "dark",
"--color-primary": "hsla(270, 8.74%, 85.88%, 1)",
"--color-primary_verylight": "hsla(hsla(270, 8.64%, 91%, 1))",
"--color-primary_light": "hsla(270, 8.64%, 88.52%, 1)",
"--color-primary_superdark": "hsla(266.67, 5.89%, 18.63%, 1)",
"--color-primary_verydark": "hsla(266.67, 6.89%, 28.63%, 1)",
"--color-primary_mediumdark": "hsla(270, 4.74%, 55.88%, 1)",
"--color-primary_slightlydark": "hsla(270, 8.74%, 75.88%, 1)",
"--color-primary_dark": "hsla(270, 5.89%, 40.71%, 1)",
"--color-yellow": "hsla(57.71, 43.12%, 60.08%, 1)",
"--color-green": "hsla(77, 55.36%, 55.2%, 1)",
"--color-teal": "hsla(179, 45.6%, 50.37%, 1)",
"--color-orange": "hsl(348, 61.7%, 55.61%, 1)",
"--color-blue": "hsla(209.16, 52.72%, 47.98%, 1)",
"--color-purple": "hsla(298.33, 36.78%, 55.98%, 1)",
"--color-red": "hsla(351.89, 42.07%, 47.02%, 1)",
"--color-shadow_key": "hsla(270, 6%, 10%, 0.5)",
"--color-shadow_ambient": "hsla(270, 6%, 10%, 0.3)",
},
light: {
"--color-name": "light",
"--color-primary": "hsla(270, 8.74%, 85.88%, 1)",
"--color-primary_verylight": "hsla(hsla(270, 8.64%, 91%, 1))",
"--color-primary_light": "hsla(270, 8.64%, 88.52%, 1)",
"--color-primary_superdark": "hsla(266.67, 5.89%, 18.63%, 1)",
"--color-primary_verydark": "hsla(266.67, 6.89%, 28.63%, 1)",
"--color-primary_mediumdark": "hsla(270, 4.74%, 55.88%, 1)",
"--color-primary_slightlydark": "hsla(270, 8.74%, 75.88%, 1)",
"--color-primary_dark": "hsla(270, 5.89%, 40.71%, 1)",
"--color-yellow": "hsla(57.71, 43.12%, 60.08%, 1)",
"--color-green": "hsla(77, 55.36%, 55.2%, 1)",
"--color-teal": "hsla(179, 45.6%, 50.37%, 1)",
"--color-orange": "hsl(348, 61.7%, 55.61%, 1)",
"--color-blue": "hsla(209.16, 52.72%, 47.98%, 1)",
"--color-purple": "hsla(298.33, 36.78%, 55.98%, 1)",
"--color-red": "hsla(351.89, 42.07%, 47.02%, 1)",
"--color-shadow_key": "hsla(270, 6%, 10%, 0.15)",
"--color-shadow_ambient": "hsla(270, 6%, 10%, 0.1)",
},
};
changeTheme(currentTheme);
} catch (err) {
console.log(new Error("accessing theme has been denied"));
}
})();
`,
}}
/>
</Head>
{children}
</motion.div>
);
}
export default Layout;
|
gdefacci/briscola
|
ddd-briscola-web/src/main/scala/com/github/gdefacci/briscola/presentation/game/GamePresentationAdapter.scala
|
package com.github.gdefacci.briscola.presentation.game
import com.github.gdefacci.briscola.{game => model}
import com.github.gdefacci.briscola.player.PlayerId
import com.github.gdefacci.briscola.web.util.PresentationAdapter
import com.github.gdefacci.briscola.presentation.player.PlayerRoutes
import com.github.gdefacci.briscola.presentation.PlayerGameEvent
import com.github.gdefacci.briscola.presentation.PlayerActiveGameState
class GamePresentationAdapter(gameRoutes: GameRoutes, playerRoutes: PlayerRoutes) {
lazy val cardAdapter = PresentationAdapter((card:model.Card) =>
Card(card.number, card.seed, card.points) )
implicit lazy val playerStateAdapter = PresentationAdapter((ps: model.PlayerState) =>
PlayerState(playerRoutes.PlayerById.encode(ps.id), ps.cards.map(cardAdapter(_)), Score(ps.score.cards.map( c => cardAdapter(c))) ))
implicit lazy val playerFinalStateAdapter = PresentationAdapter((ps: model.PlayerFinalState) =>
PlayerFinalState(playerRoutes.PlayerById.encode(ps.id), ps.points, Score(ps.score.cards.map(cardAdapter(_))) ))
lazy val playerLeftAdapter = PresentationAdapter((ps: model.PlayerLeft) =>
PlayerLeft(playerRoutes.PlayerById.encode(ps.player), ps.reason))
lazy val dropReasonAdapter = PresentationAdapter((ps: model.DropReason) => ps match {
case pl:model.PlayerLeft => playerLeftAdapter(pl)
})
lazy val teamScoreAdapter = PresentationAdapter((ts:model.TeamScore) => {
TeamScore(
ts.team.name,
ts.team.players.map(pid => playerRoutes.PlayerById.encode(pid)),
ts.score.cards.map(cardAdapter(_)),
ts.score.points )
})
lazy val droppedGameStateAdapter = PresentationAdapter((gm: model.DroppedGameState) =>
DroppedGameState(
gameRoutes.GameById.encode(gm.id),
cardAdapter(gm.briscolaCard),
gm.teams.map(tms => tms.teams.toSeq.map( t => gameRoutes.Team.encode(gm.id, t.name))),
gm.moves.map(m => Move(playerRoutes.PlayerById.encode(m.player.id), cardAdapter(m.card))),
gm.nextPlayers.map(p => playerRoutes.PlayerById.encode(p.id)),
dropReasonAdapter(gm.dropReason)))
implicit lazy val finalGameStateAdapter = PresentationAdapter((gm: model.FinalGameState) => {
val teamResult = for (teamOrderByPoint <- gm.teamScoresOrderByPoints; winnerTeam <- gm.winnerTeam) yield(
TeamsGameResult(teamOrderByPoint.map(teamScoreAdapter(_)), teamScoreAdapter(winnerTeam))
)
val gmr = teamResult.getOrElse(PlayersGameResult(gm.playersOrderByPoints.map(playerFinalStateAdapter(_)), playerFinalStateAdapter(gm.winner)))
FinalGameState(
gameRoutes.GameById.encode(gm.id),
cardAdapter(gm.briscolaCard), gmr)
})
def toActiveGameState(gm: model.ActiveGameState, player: Option[PlayerId]): ActiveGameState =
ActiveGameState(
gameRoutes.GameById.encode(gm.id),
cardAdapter(gm.briscolaCard),
gm.teams.map(tms => tms.teams.toSeq.map( t => gameRoutes.Team.encode(gm.id, t.name))),
gm.moves.map(m => Move(playerRoutes.PlayerById.encode(m.player.id), cardAdapter(m.card))),
gm.nextPlayers.map(p => playerRoutes.PlayerById.encode(p.id)),
playerRoutes.PlayerById.encode(gm.currentPlayer.id),
gm.isLastHandTurn, gm.isLastGameTurn,
gm.players.map(p => playerRoutes.PlayerById.encode(p.id)),
player.map(pid => gameRoutes.Player.encode(gm.id, pid)),
gm.deckCardsNumber)
def toGameState(gm: model.GameState, player: Option[PlayerId]): GameState = gm match {
case model.EmptyGameState => EmptyGameState
case gm: model.ActiveGameState => toActiveGameState(gm, player)
case gm: model.DroppedGameState => droppedGameStateAdapter(gm)
case gm: model.FinalGameState => finalGameStateAdapter(gm)
}
implicit lazy val gameStateAdapter = PresentationAdapter((gm: model.GameState) => toGameState(gm, None))
implicit lazy val playerGameEventAdater = PresentationAdapter[PlayerGameEvent, BriscolaEvent]((ev:PlayerGameEvent) => ev.event match {
case model.GameStarted(gm) => GameStarted(toActiveGameState(gm, Some(ev.playerId)))
case model.GameDropped(dropReason) => GameDropped(gameRoutes.GameById.encode(ev.gameId), dropReasonAdapter(dropReason) )
case model.CardPlayed(pid, crd) => CardPlayed(
gameRoutes.GameById.encode(ev.gameId),
playerRoutes.PlayerById.encode(pid),
cardAdapter(crd))
})
implicit lazy val playerActiveGameStateAdapter = PresentationAdapter( (pags:PlayerActiveGameState) =>
toActiveGameState(pags.game, Some(pags.playerId))
)
}
|
r7h2/testing_01
|
demos/z-rest-demo-02/z-rest-demo-02/src/main/java/com/example/zrestdemo02/controller/GreetingController.java
|
<gh_stars>0
package com.example.zrestdemo02.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.zrestdemo02.Dog;
@RestController
@RequestMapping("/apis")
public class GreetingController {
@GetMapping("/greetings")
public String getDogs() {
return "Greetings!";
}
@GetMapping("/greetings/{greetingId}")
public Greeting displayGreeting() {
return new Greeting("hello, there");
}
}
|
lajos-kiss/webauthn4j
|
webauthn4j-core/src/main/java/com/webauthn4j/data/SignatureAlgorithm.java
|
/*
* Copyright 2002-2018 the original author or 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.webauthn4j.data;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.io.Serializable;
import java.util.Objects;
import static com.webauthn4j.data.MessageDigestAlgorithm.*;
public class SignatureAlgorithm implements Serializable {
public static final String SHA_256_WITH_ECDSA = "SHA256withECDSA";
public static final String SHA_384_WITH_ECDSA = "SHA384withECDSA";
public static final String SHA_512_WITH_ECDSA = "SHA512withECDSA";
public static final String SHA_1_WITH_RSA = "SHA1withRSA";
public static final String SHA_256_WITH_RSA = "SHA256withRSA";
public static final String SHA_384_WITH_RSA = "SHA384withRSA";
public static final String SHA_512_WITH_RSA = "SHA512withRSA";
public static final SignatureAlgorithm ES256 = new SignatureAlgorithm(SHA_256_WITH_ECDSA, SHA256);
public static final SignatureAlgorithm ES384 = new SignatureAlgorithm(SHA_384_WITH_ECDSA, SHA384);
public static final SignatureAlgorithm ES512 = new SignatureAlgorithm(SHA_512_WITH_ECDSA, SHA512);
public static final SignatureAlgorithm RS1 = new SignatureAlgorithm(SHA_1_WITH_RSA, SHA1);
public static final SignatureAlgorithm RS256 = new SignatureAlgorithm(SHA_256_WITH_RSA, SHA256);
public static final SignatureAlgorithm RS384 = new SignatureAlgorithm(SHA_384_WITH_RSA, SHA384);
public static final SignatureAlgorithm RS512 = new SignatureAlgorithm(SHA_512_WITH_RSA, SHA512);
private final String jcaName;
private final MessageDigestAlgorithm messageDigestAlgorithm;
private SignatureAlgorithm(@NonNull String jcaName, @NonNull MessageDigestAlgorithm messageDigestAlgorithm) {
this.jcaName = jcaName;
this.messageDigestAlgorithm = messageDigestAlgorithm;
}
public static SignatureAlgorithm create(@NonNull String jcaName) {
switch (jcaName) {
case SHA_256_WITH_ECDSA:
return ES256;
case SHA_384_WITH_ECDSA:
return ES384;
case SHA_512_WITH_ECDSA:
return ES512;
case SHA_1_WITH_RSA:
return RS1;
case SHA_256_WITH_RSA:
return RS256;
case SHA_384_WITH_RSA:
return RS384;
case SHA_512_WITH_RSA:
return RS512;
default:
throw new IllegalArgumentException(String.format("jcaName %s is not supported.", jcaName));
}
}
public static SignatureAlgorithm create(@NonNull String jcaName, @NonNull String messageDigestJcaName) {
return new SignatureAlgorithm(jcaName, MessageDigestAlgorithm.create(messageDigestJcaName));
}
@SuppressWarnings("unused")
@JsonCreator
private static @NonNull SignatureAlgorithm deserialize(String value) throws InvalidFormatException {
try {
return create(value);
} catch (IllegalArgumentException e) {
throw new InvalidFormatException(null, "value is out of range", value, SignatureAlgorithm.class);
}
}
@JsonValue
public @NonNull String getJcaName() {
return jcaName;
}
public @NonNull MessageDigestAlgorithm getMessageDigestAlgorithm() {
return messageDigestAlgorithm;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SignatureAlgorithm that = (SignatureAlgorithm) o;
return Objects.equals(jcaName, that.jcaName) &&
Objects.equals(messageDigestAlgorithm, that.messageDigestAlgorithm);
}
@Override
public int hashCode() {
return Objects.hash(jcaName, messageDigestAlgorithm);
}
@Override
public String toString() {
switch (jcaName) {
case SHA_256_WITH_ECDSA:
return "ES256";
case SHA_384_WITH_ECDSA:
return "ES384";
case SHA_512_WITH_ECDSA:
return "ES512";
case SHA_1_WITH_RSA:
return "RS1";
case SHA_256_WITH_RSA:
return "RS256";
case SHA_384_WITH_RSA:
return "RS384";
case SHA_512_WITH_RSA:
return "RS512";
default:
return "Unknown jcaName: " + jcaName;
}
}
}
|
naver/webgraphics
|
mozilla/gfx/vr/gfxVROculus050.h
|
<gh_stars>1-10
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef GFX_VR_OCULUS_050_H
#define GFX_VR_OCULUS_050_H
#include "nsTArray.h"
#include "nsThreadUtils.h"
#include "mozilla/EnumeratedArray.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/RefPtr.h"
#include "gfxVR.h"
#include "ovr_capi_dynamic050.h"
namespace mozilla {
namespace gfx {
namespace impl {
class HMDInfoOculus050 : public VRHMDInfo {
public:
explicit HMDInfoOculus050(ovr050::ovrHmd aHMD, bool aDebug, int aDeviceID);
bool SetFOV(const VRFieldOfView& aFOVLeft, const VRFieldOfView& aFOVRight,
double zNear, double zFar) override;
VRHMDSensorState GetSensorState(double timeOffset) override;
void ZeroSensor() override;
bool KeepSensorTracking() override;
void NotifyVsync(const TimeStamp& aVsyncTimestamp) override;
void FillDistortionConstants(uint32_t whichEye,
const IntSize& textureSize, const IntRect& eyeViewport,
const Size& destViewport, const Rect& destRect,
VRDistortionConstants& values) override;
void Destroy();
bool GetIsDebug() const;
int GetDeviceID() const;
protected:
virtual ~HMDInfoOculus050() {
Destroy();
MOZ_COUNT_DTOR_INHERITED(HMDInfoOculus050, VRHMDInfo);
}
bool StartSensorTracking();
void StopSensorTracking();
// must match the size of VRDistortionVertex
struct DistortionVertex {
float pos[2];
float texR[2];
float texG[2];
float texB[2];
float genericAttribs[4];
};
ovr050::ovrHmd mHMD;
ovr050::ovrFovPort mFOVPort[2];
uint32_t mTracking;
bool mDebug; // True if this is a debug HMD
int mDeviceID; // ID of device passed to ovrHmd_Create
uint32_t mSensorTrackingFramesRemaining;
};
} // namespace impl
class VRHMDManagerOculus050 : public VRHMDManager
{
public:
static already_AddRefed<VRHMDManagerOculus050> Create();
virtual bool Init() override;
virtual void Destroy() override;
virtual void GetHMDs(nsTArray<RefPtr<VRHMDInfo> >& aHMDResult) override;
protected:
VRHMDManagerOculus050()
: mOculusInitialized(false)
{ }
nsTArray<RefPtr<impl::HMDInfoOculus050> > mOculusHMDs;
bool mOculusInitialized;
RefPtr<nsIThread> mOculusThread;
};
} // namespace gfx
} // namespace mozilla
#endif /* GFX_VR_OCULUS_050_H */
|
Josecc/voila
|
src/components/Tutorial/Tutorial.js
|
<reponame>Josecc/voila<gh_stars>0
import React, { Component } from 'react';
import styles from './Tutorial.css';
import withStyles from '../../decorators/withStyles';
@withStyles(styles)
class Tutorial extends Component {
constructor(props){
super(props);
}
render() {
if(this.props.uploadTutorial){
return (
<div className="Tutorial">
<iframe width="100%" height="400px" className="edgeFrame" src="/edge/crop/Crop.html" />
</div>
);
}
return (
<div className="Tutorial">
<iframe width="100%" height="400px" className="edgeFrame" src="/edge/crop/Crop.html" />
</div>
);
}
}
export default Tutorial;
|
andreas-loeffler/Rummikub
|
src/main/scala/rummikub/model/StrategyComponents/strategyBaseImpl/StatePattern.scala
|
<filename>src/main/scala/rummikub/model/StrategyComponents/strategyBaseImpl/StatePattern.scala<gh_stars>0
package Rummikub.model.StrategyComponents.strategyBaseImpl
import Rummikub.model.StrategyComponents.StateInterface
object StatePattern extends StateInterface {
def handle(x: Boolean): Unit = {
x match {
case true => offState
case false => onState
}
}
def onState = println("1 Game live, pls wait")
def offState = println("No current game")
}
|
denise-sanders/mongosh
|
packages/java-shell/src/test/resources/literal/array.js
|
<gh_stars>100-1000
// before
db.coll.insertOne({"_id": 1, v: [1, 2, "hello \n world"]});
// command checkResultClass
[1, 2, "hello \n world"]
// command checkResultClass
db.coll.find().toArray()[0].v;
// clear
db.coll.drop();
|
mukeshkumargupta/data-structure-java-tutorials
|
src/com/interview/tree/CountGoodNodesinBinaryTree.java
|
<filename>src/com/interview/tree/CountGoodNodesinBinaryTree.java
package com.interview.tree;
/*
* https://leetcode.com/problems/count-good-nodes-in-binary-tree/
* Category: Medium, Must Do, dfs
* Hint: Here solved as dfs, try to solve post order traversal like how size of tree calculated
* https://www.youtube.com/watch?v=rbqbmCABEhU
* Related:
* https://leetcode.com/problems/trapping-rain-water-ii/ Hard, VVImp
* https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/ Medium
* https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/ Medium
* 1448. Count Good Nodes in Binary Tree
Medium
2230
74
Add to List
Share
Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
Example 1:
Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Nodes in blue are good.
Root Node (3) is always a good node.
Node 4 -> (3,4) is the maximum value in the path starting from the root.
Node 5 -> (3,4,5) is the maximum value in the path
Node 3 -> (3,1,3) is the maximum value in the path.
Example 2:
Input: root = [3,3,null,4,2]
Output: 3
Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.
Example 3:
Input: root = [1]
Output: 1
Explanation: Root is considered as good.
Constraints:
The number of nodes in the binary tree is in the range [1, 10^5].
Each node's value is between [-10^4, 10^4].
Accepted
156,973
Submissions
215,081
*/
public class CountGoodNodesinBinaryTree {
public void goodNodesUtil(TreeNode root, TreeNode maxNode,int[] count) {
if (root == null) {
return;
}
if (maxNode == null) {//root node is always good node
count[0] += 1;
} else {
if (root.val >= maxNode.val) {
count[0] += 1;
}
}
TreeNode findMaxNode = null;
if (maxNode == null) {
findMaxNode = root;
} else {
findMaxNode = root.val > maxNode.val ? root : maxNode;
}
//DFS
goodNodesUtil(root.left, findMaxNode, count);
goodNodesUtil(root.right, findMaxNode, count);
}
public int goodNodes(TreeNode root) {
/*
* Runtime: 3 ms, faster than 65.70% of Java online submissions for Count Good Nodes in Binary Tree.
Memory Usage: 59.5 MB, less than 70.66% of Java online submissions for Count Good Nodes in Binary Tree.
*/
if (root == null) {
return 0;
}
int[] count = new int[1];
goodNodesUtil(root, null, count);
return count[0];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
|
rydockman/YouPick
|
node_modules/@iconify-icons/clarity/src/certificate-solid.js
|
let data = {
"body": "<path d=\"M19 30H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h28a2 2 0 0 1 2 2v10.37a8.34 8.34 0 0 0-13.49 9.79l-.93 1.14zM7 12v1.6h17V12zm0 5.6h11V16H7zm0 7h10V23H7z\" class=\"clr-i-solid clr-i-solid-path-1\" fill=\"currentColor\"/><path d=\"M33.83 23.59a6.37 6.37 0 1 0-10.77 4.59l-1.94 2.37l.9 3.61l3.66-4.46a6.26 6.26 0 0 0 3.55 0l3.66 4.46l.9-3.61l-1.94-2.37a6.34 6.34 0 0 0 1.98-4.59zm-10.74 0a4.37 4.37 0 1 1 4.37 4.31a4.35 4.35 0 0 1-4.36-4.31z\" class=\"clr-i-solid clr-i-solid-path-2\" fill=\"currentColor\"/>",
"width": 36,
"height": 36
};
export default data;
|
heitaoflower/Lumos
|
Lumos/src/Core/OS/FileSystem.cpp
|
<filename>Lumos/src/Core/OS/FileSystem.cpp
#include "lmpch.h"
#include "FileSystem.h"
namespace Lumos
{
bool (*FileSystem::FileExistsFunc)(const String&) = NULL;
bool (*FileSystem::FolderExistsFunc)(const String&) = NULL;
i64 (*FileSystem::GetFileSizeFunc)(const String&) = NULL;
u8* (*FileSystem::ReadFileFunc)(const String&) = NULL;
bool (*FileSystem::ReadFileBufferFunc)(const String&, void*, i64) = NULL;
bool (*FileSystem::WriteFileFunc)(const String&, u8*) = NULL;
bool (*FileSystem::WriteTextFileFunc)(const String&, const String&) = NULL;
}
|
mistydew/RSSearch
|
depends/boost/intrusive/unordered_set.hpp
|
/////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright <NAME> 2004-2006.
// (C) Copyright <NAME> 2006-2014
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTRUSIVE_UNORDERED_SET_HPP
#define BOOST_INTRUSIVE_UNORDERED_SET_HPP
#include <boost/intrusive/detail/config_begin.hpp>
#include <boost/intrusive/intrusive_fwd.hpp>
#include <boost/intrusive/hashtable.hpp>
#include <boost/move/utility_core.hpp>
#include <boost/static_assert.hpp>
#if defined(BOOST_HAS_PRAGMA_ONCE)
# pragma once
#endif
namespace boost {
namespace intrusive {
//! The class template unordered_set is an intrusive container, that mimics most of
//! the interface of std::tr1::unordered_set as described in the C++ TR1.
//!
//! unordered_set is a semi-intrusive container: each object to be stored in the
//! container must contain a proper hook, but the container also needs
//! additional auxiliary memory to work: unordered_set needs a pointer to an array
//! of type `bucket_type` to be passed in the constructor. This bucket array must
//! have at least the same lifetime as the container. This makes the use of
//! unordered_set more complicated than purely intrusive containers.
//! `bucket_type` is default-constructible, copyable and assignable
//!
//! The template parameter \c T is the type to be managed by the container.
//! The user can specify additional options and if no options are provided
//! default options are used.
//!
//! The container supports the following options:
//! \c base_hook<>/member_hook<>/value_traits<>,
//! \c constant_time_size<>, \c size_type<>, \c hash<> and \c equal<>
//! \c bucket_traits<>, \c power_2_buckets<> and \c cache_begin<>.
//!
//! unordered_set only provides forward iterators but it provides 4 iterator types:
//! iterator and const_iterator to navigate through the whole container and
//! local_iterator and const_local_iterator to navigate through the values
//! stored in a single bucket. Local iterators are faster and smaller.
//!
//! It's not recommended to use non constant-time size unordered_sets because several
//! key functions, like "empty()", become non-constant time functions. Non
//! constant-time size unordered_sets are mainly provided to support auto-unlink hooks.
//!
//! unordered_set, unlike std::unordered_set, does not make automatic rehashings nor
//! offers functions related to a load factor. Rehashing can be explicitly requested
//! and the user must provide a new bucket array that will be used from that moment.
//!
//! Since no automatic rehashing is done, iterators are never invalidated when
//! inserting or erasing elements. Iterators are only invalidated when rehasing.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)
template<class T, class ...Options>
#else
template<class ValueTraits, class VoidOrKeyOfValue, class VoidOrKeyHash, class VoidOrKeyEqual, class SizeType, class BucketTraits, std::size_t BoolFlags>
#endif
class unordered_set_impl
: public hashtable_impl<ValueTraits, VoidOrKeyOfValue, VoidOrKeyHash, VoidOrKeyEqual, BucketTraits, SizeType, BoolFlags|hash_bool_flags::unique_keys_pos>
{
/// @cond
private:
typedef hashtable_impl<ValueTraits, VoidOrKeyOfValue, VoidOrKeyHash, VoidOrKeyEqual, BucketTraits, SizeType, BoolFlags|hash_bool_flags::unique_keys_pos> table_type;
template<class Iterator, class MaybeConstThis, class KeyType, class KeyHasher, class KeyEqual>
static std::pair<Iterator,Iterator> priv_equal_range(MaybeConstThis &c, const KeyType& key, KeyHasher hash_func, KeyEqual equal_func)
{
Iterator const it = c.find(key, hash_func, equal_func);
std::pair<Iterator,Iterator> ret(it, it);
if(it != c.end())
++ret.second;
return ret;
}
//! This class is
//! movable
BOOST_MOVABLE_BUT_NOT_COPYABLE(unordered_set_impl)
typedef table_type implementation_defined;
/// @endcond
public:
typedef typename implementation_defined::value_type value_type;
typedef typename implementation_defined::key_type key_type;
typedef typename implementation_defined::key_of_value key_of_value;
typedef typename implementation_defined::value_traits value_traits;
typedef typename implementation_defined::bucket_traits bucket_traits;
typedef typename implementation_defined::pointer pointer;
typedef typename implementation_defined::const_pointer const_pointer;
typedef typename implementation_defined::reference reference;
typedef typename implementation_defined::const_reference const_reference;
typedef typename implementation_defined::difference_type difference_type;
typedef typename implementation_defined::size_type size_type;
typedef typename implementation_defined::key_equal key_equal;
typedef typename implementation_defined::hasher hasher;
typedef typename implementation_defined::bucket_type bucket_type;
typedef typename implementation_defined::bucket_ptr bucket_ptr;
typedef typename implementation_defined::iterator iterator;
typedef typename implementation_defined::const_iterator const_iterator;
typedef typename implementation_defined::insert_commit_data insert_commit_data;
typedef typename implementation_defined::local_iterator local_iterator;
typedef typename implementation_defined::const_local_iterator const_local_iterator;
typedef typename implementation_defined::node_traits node_traits;
typedef typename implementation_defined::node node;
typedef typename implementation_defined::node_ptr node_ptr;
typedef typename implementation_defined::const_node_ptr const_node_ptr;
typedef typename implementation_defined::node_algorithms node_algorithms;
public:
//! @copydoc ::boost::intrusive::hashtable::hashtable(const bucket_traits &,const hasher &,const key_equal &,const value_traits &)
explicit unordered_set_impl( const bucket_traits &b_traits
, const hasher & hash_func = hasher()
, const key_equal &equal_func = key_equal()
, const value_traits &v_traits = value_traits())
: table_type(b_traits, hash_func, equal_func, v_traits)
{}
//! @copydoc ::boost::intrusive::hashtable::hashtable(bool,Iterator,Iterator,const bucket_traits &,const hasher &,const key_equal &,const value_traits &)
template<class Iterator>
unordered_set_impl( Iterator b
, Iterator e
, const bucket_traits &b_traits
, const hasher & hash_func = hasher()
, const key_equal &equal_func = key_equal()
, const value_traits &v_traits = value_traits())
: table_type(true, b, e, b_traits, hash_func, equal_func, v_traits)
{}
//! @copydoc ::boost::intrusive::hashtable::hashtable(hashtable&&)
unordered_set_impl(BOOST_RV_REF(unordered_set_impl) x)
: table_type(BOOST_MOVE_BASE(table_type, x))
{}
//! @copydoc ::boost::intrusive::hashtable::operator=(hashtable&&)
unordered_set_impl& operator=(BOOST_RV_REF(unordered_set_impl) x)
{ return static_cast<unordered_set_impl&>(table_type::operator=(BOOST_MOVE_BASE(table_type, x))); }
#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
//! @copydoc ::boost::intrusive::hashtable::~hashtable()
~unordered_set_impl();
//! @copydoc ::boost::intrusive::hashtable::begin()
iterator begin();
//! @copydoc ::boost::intrusive::hashtable::begin()const
const_iterator begin() const;
//! @copydoc ::boost::intrusive::hashtable::cbegin()const
const_iterator cbegin() const;
//! @copydoc ::boost::intrusive::hashtable::end()
iterator end();
//! @copydoc ::boost::intrusive::hashtable::end()const
const_iterator end() const;
//! @copydoc ::boost::intrusive::hashtable::cend()const
const_iterator cend() const;
//! @copydoc ::boost::intrusive::hashtable::hash_function()const
hasher hash_function() const;
//! @copydoc ::boost::intrusive::hashtable::key_eq()const
key_equal key_eq() const;
//! @copydoc ::boost::intrusive::hashtable::empty()const
bool empty() const;
//! @copydoc ::boost::intrusive::hashtable::size()const
size_type size() const;
//! @copydoc ::boost::intrusive::hashtable::hashtable
void swap(unordered_set_impl& other);
//! @copydoc ::boost::intrusive::hashtable::clone_from(const hashtable&,Cloner,Disposer)
template <class Cloner, class Disposer>
void clone_from(const unordered_set_impl &src, Cloner cloner, Disposer disposer);
#else
using table_type::clone_from;
#endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
//! @copydoc ::boost::intrusive::hashtable::clone_from(hashtable&&,Cloner,Disposer)
template <class Cloner, class Disposer>
void clone_from(BOOST_RV_REF(unordered_set_impl) src, Cloner cloner, Disposer disposer)
{ table_type::clone_from(BOOST_MOVE_BASE(table_type, src), cloner, disposer); }
//! @copydoc ::boost::intrusive::hashtable::insert_unique(reference)
std::pair<iterator, bool> insert(reference value)
{ return table_type::insert_unique(value); }
//! @copydoc ::boost::intrusive::hashtable::insert_unique(Iterator,Iterator)
template<class Iterator>
void insert(Iterator b, Iterator e)
{ table_type::insert_unique(b, e); }
//! @copydoc ::boost::intrusive::hashtable::insert_unique_check(const key_type&,insert_commit_data&)
std::pair<iterator, bool> insert_check(const key_type &key, insert_commit_data &commit_data)
{ return table_type::insert_unique_check(key, commit_data); }
//! @copydoc ::boost::intrusive::hashtable::insert_unique_check(const KeyType&,KeyHasher,KeyEqual,insert_commit_data&)
template<class KeyType, class KeyHasher, class KeyEqual>
std::pair<iterator, bool> insert_check
(const KeyType &key, KeyHasher hasher, KeyEqual key_value_equal, insert_commit_data &commit_data)
{ return table_type::insert_unique_check(key, hasher, key_value_equal, commit_data); }
//! @copydoc ::boost::intrusive::hashtable::insert_unique_commit
iterator insert_commit(reference value, const insert_commit_data &commit_data)
{ return table_type::insert_unique_commit(value, commit_data); }
#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
//! @copydoc ::boost::intrusive::hashtable::erase(const_iterator)
void erase(const_iterator i);
//! @copydoc ::boost::intrusive::hashtable::erase(const_iterator,const_iterator)
void erase(const_iterator b, const_iterator e);
//! @copydoc ::boost::intrusive::hashtable::erase(const key_type &)
size_type erase(const key_type &key);
//! @copydoc ::boost::intrusive::hashtable::erase(const KeyType&,KeyHasher,KeyEqual)
template<class KeyType, class KeyHasher, class KeyEqual>
size_type erase(const KeyType& key, KeyHasher hash_func, KeyEqual equal_func);
//! @copydoc ::boost::intrusive::hashtable::erase_and_dispose(const_iterator,Disposer)
template<class Disposer>
BOOST_INTRUSIVE_DOC1ST(void
, typename detail::disable_if_convertible<Disposer BOOST_INTRUSIVE_I const_iterator>::type)
erase_and_dispose(const_iterator i, Disposer disposer);
//! @copydoc ::boost::intrusive::hashtable::erase_and_dispose(const_iterator,const_iterator,Disposer)
template<class Disposer>
void erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer);
//! @copydoc ::boost::intrusive::hashtable::erase_and_dispose(const key_type &,Disposer)
template<class Disposer>
size_type erase_and_dispose(const key_type &key, Disposer disposer);
//! @copydoc ::boost::intrusive::hashtable::erase_and_dispose(const KeyType&,KeyHasher,KeyEqual,Disposer)
template<class KeyType, class KeyHasher, class KeyEqual, class Disposer>
size_type erase_and_dispose(const KeyType& key, KeyHasher hash_func, KeyEqual equal_func, Disposer disposer);
//! @copydoc ::boost::intrusive::hashtable::clear
void clear();
//! @copydoc ::boost::intrusive::hashtable::clear_and_dispose
template<class Disposer>
void clear_and_dispose(Disposer disposer);
//! @copydoc ::boost::intrusive::hashtable::count(const key_type &)const
size_type count(const key_type &key) const;
//! @copydoc ::boost::intrusive::hashtable::count(const KeyType&,KeyHasher,KeyEqual)const
template<class KeyType, class KeyHasher, class KeyEqual>
size_type count(const KeyType& key, KeyHasher hash_func, KeyEqual equal_func) const;
//! @copydoc ::boost::intrusive::hashtable::find(const key_type &)
iterator find(const key_type &key);
//! @copydoc ::boost::intrusive::hashtable::find(const KeyType &,KeyHasher,KeyEqual)
template<class KeyType, class KeyHasher, class KeyEqual>
iterator find(const KeyType& key, KeyHasher hash_func, KeyEqual equal_func);
//! @copydoc ::boost::intrusive::hashtable::count(const key_type &)const
const_iterator find(const key_type &key) const;
//! @copydoc ::boost::intrusive::hashtable::find(const KeyType &,KeyHasher,KeyEqual)const
template<class KeyType, class KeyHasher, class KeyEqual>
const_iterator find(const KeyType& key, KeyHasher hash_func, KeyEqual equal_func) const;
#endif
//! @copydoc ::boost::intrusive::hashtable::equal_range(const key_type&)
std::pair<iterator,iterator> equal_range(const key_type &key)
{ return this->equal_range(key, this->hash_function(), this->key_eq()); }
//! @copydoc ::boost::intrusive::hashtable::equal_range(const KeyType &,KeyHasher,KeyEqual)
template<class KeyType, class KeyHasher, class KeyEqual>
std::pair<iterator,iterator> equal_range(const KeyType& key, KeyHasher hash_func, KeyEqual equal_func)
{ return this->priv_equal_range<iterator>(*this, key, hash_func, equal_func); }
//! @copydoc ::boost::intrusive::hashtable::equal_range(const key_type&)const
std::pair<const_iterator, const_iterator>
equal_range(const key_type &key) const
{ return this->equal_range(key, this->hash_function(), this->key_eq()); }
//! @copydoc ::boost::intrusive::hashtable::equal_range(const KeyType &,KeyHasher,KeyEqual)const
template<class KeyType, class KeyHasher, class KeyEqual>
std::pair<const_iterator, const_iterator>
equal_range(const KeyType& key, KeyHasher hash_func, KeyEqual equal_func) const
{ return this->priv_equal_range<const_iterator>(*this, key, hash_func, equal_func); }
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)
//! @copydoc ::boost::intrusive::hashtable::iterator_to(reference)
iterator iterator_to(reference value);
//! @copydoc ::boost::intrusive::hashtable::iterator_to(const_reference)const
const_iterator iterator_to(const_reference value) const;
//! @copydoc ::boost::intrusive::hashtable::s_local_iterator_to(reference)
static local_iterator s_local_iterator_to(reference value);
//! @copydoc ::boost::intrusive::hashtable::s_local_iterator_to(const_reference)
static const_local_iterator s_local_iterator_to(const_reference value);
//! @copydoc ::boost::intrusive::hashtable::local_iterator_to(reference)
local_iterator local_iterator_to(reference value);
//! @copydoc ::boost::intrusive::hashtable::local_iterator_to(const_reference)
const_local_iterator local_iterator_to(const_reference value) const;
//! @copydoc ::boost::intrusive::hashtable::bucket_count
size_type bucket_count() const;
//! @copydoc ::boost::intrusive::hashtable::bucket_size
size_type bucket_size(size_type n) const;
//! @copydoc ::boost::intrusive::hashtable::bucket(const key_type&)const
size_type bucket(const key_type& k) const;
//! @copydoc ::boost::intrusive::hashtable::bucket(const KeyType&,KeyHasher)const
template<class KeyType, class KeyHasher>
size_type bucket(const KeyType& k, KeyHasher hash_func) const;
//! @copydoc ::boost::intrusive::hashtable::bucket_pointer
bucket_ptr bucket_pointer() const;
//! @copydoc ::boost::intrusive::hashtable::begin(size_type)
local_iterator begin(size_type n);
//! @copydoc ::boost::intrusive::hashtable::begin(size_type)const
const_local_iterator begin(size_type n) const;
//! @copydoc ::boost::intrusive::hashtable::cbegin(size_type)const
const_local_iterator cbegin(size_type n) const;
//! @copydoc ::boost::intrusive::hashtable::end(size_type)
local_iterator end(size_type n);
//! @copydoc ::boost::intrusive::hashtable::end(size_type)const
const_local_iterator end(size_type n) const;
//! @copydoc ::boost::intrusive::hashtable::cend(size_type)const
const_local_iterator cend(size_type n) const;
//! @copydoc ::boost::intrusive::hashtable::rehash(const bucket_traits &)
void rehash(const bucket_traits &new_bucket_traits);
//! @copydoc ::boost::intrusive::hashtable::incremental_rehash(bool)
bool incremental_rehash(bool grow = true);
//! @copydoc ::boost::intrusive::hashtable::incremental_rehash(const bucket_traits &)
bool incremental_rehash(const bucket_traits &new_bucket_traits);
//! @copydoc ::boost::intrusive::hashtable::split_count
size_type split_count() const;
//! @copydoc ::boost::intrusive::hashtable::suggested_upper_bucket_count
static size_type suggested_upper_bucket_count(size_type n);
//! @copydoc ::boost::intrusive::hashtable::suggested_lower_bucket_count
static size_type suggested_lower_bucket_count(size_type n);
#endif // #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
friend bool operator==(const unordered_set_impl &x, const unordered_set_impl &y)
{
if(table_type::constant_time_size && x.size() != y.size()){
return false;
}
//Find each element of x in y
for (const_iterator ix = x.cbegin(), ex = x.cend(), ey = y.cend(); ix != ex; ++ix){
const_iterator iy = y.find(key_of_value()(*ix));
if (iy == ey || !(*ix == *iy))
return false;
}
return true;
}
friend bool operator!=(const unordered_set_impl &x, const unordered_set_impl &y)
{ return !(x == y); }
friend bool operator<(const unordered_set_impl &x, const unordered_set_impl &y)
{ return ::boost::intrusive::algo_lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); }
friend bool operator>(const unordered_set_impl &x, const unordered_set_impl &y)
{ return y < x; }
friend bool operator<=(const unordered_set_impl &x, const unordered_set_impl &y)
{ return !(y < x); }
friend bool operator>=(const unordered_set_impl &x, const unordered_set_impl &y)
{ return !(x < y); }
};
//! Helper metafunction to define an \c unordered_set that yields to the same type when the
//! same options (either explicitly or implicitly) are used.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class ...Options>
#else
template<class T, class O1 = void, class O2 = void
, class O3 = void, class O4 = void
, class O5 = void, class O6 = void
, class O7 = void, class O8 = void
, class O9 = void, class O10= void
>
#endif
struct make_unordered_set
{
/// @cond
typedef typename pack_options
< hashtable_defaults,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4, O5, O6, O7, O8, O9, O10
#else
Options...
#endif
>::type packed_options;
typedef typename detail::get_value_traits
<T, typename packed_options::proto_value_traits>::type value_traits;
typedef typename make_bucket_traits
<T, true, packed_options>::type bucket_traits;
typedef unordered_set_impl
< value_traits
, typename packed_options::key_of_value
, typename packed_options::hash
, typename packed_options::equal
, typename packed_options::size_type
, bucket_traits
, (std::size_t(true)*hash_bool_flags::unique_keys_pos)
| (std::size_t(packed_options::constant_time_size)*hash_bool_flags::constant_time_size_pos)
| (std::size_t(packed_options::power_2_buckets)*hash_bool_flags::power_2_buckets_pos)
| (std::size_t(packed_options::cache_begin)*hash_bool_flags::cache_begin_pos)
| (std::size_t(packed_options::compare_hash)*hash_bool_flags::compare_hash_pos)
| (std::size_t(packed_options::incremental)*hash_bool_flags::incremental_pos)
> implementation_defined;
/// @endcond
typedef implementation_defined type;
};
#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class O1, class O2, class O3, class O4, class O5, class O6, class O7, class O8, class O9, class O10>
#else
template<class T, class ...Options>
#endif
class unordered_set
: public make_unordered_set<T,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4, O5, O6, O7, O8, O9, O10
#else
Options...
#endif
>::type
{
typedef typename make_unordered_set
<T,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4, O5, O6, O7, O8, O9, O10
#else
Options...
#endif
>::type Base;
//Assert if passed value traits are compatible with the type
BOOST_STATIC_ASSERT((detail::is_same<typename Base::value_traits::value_type, T>::value));
BOOST_MOVABLE_BUT_NOT_COPYABLE(unordered_set)
public:
typedef typename Base::value_traits value_traits;
typedef typename Base::bucket_traits bucket_traits;
typedef typename Base::iterator iterator;
typedef typename Base::const_iterator const_iterator;
typedef typename Base::bucket_ptr bucket_ptr;
typedef typename Base::size_type size_type;
typedef typename Base::hasher hasher;
typedef typename Base::key_equal key_equal;
explicit unordered_set ( const bucket_traits &b_traits
, const hasher & hash_func = hasher()
, const key_equal &equal_func = key_equal()
, const value_traits &v_traits = value_traits())
: Base(b_traits, hash_func, equal_func, v_traits)
{}
template<class Iterator>
unordered_set ( Iterator b
, Iterator e
, const bucket_traits &b_traits
, const hasher & hash_func = hasher()
, const key_equal &equal_func = key_equal()
, const value_traits &v_traits = value_traits())
: Base(b, e, b_traits, hash_func, equal_func, v_traits)
{}
unordered_set(BOOST_RV_REF(unordered_set) x)
: Base(BOOST_MOVE_BASE(Base, x))
{}
unordered_set& operator=(BOOST_RV_REF(unordered_set) x)
{ return static_cast<unordered_set&>(this->Base::operator=(BOOST_MOVE_BASE(Base, x))); }
template <class Cloner, class Disposer>
void clone_from(const unordered_set &src, Cloner cloner, Disposer disposer)
{ Base::clone_from(src, cloner, disposer); }
template <class Cloner, class Disposer>
void clone_from(BOOST_RV_REF(unordered_set) src, Cloner cloner, Disposer disposer)
{ Base::clone_from(BOOST_MOVE_BASE(Base, src), cloner, disposer); }
};
#endif
//! The class template unordered_multiset is an intrusive container, that mimics most of
//! the interface of std::tr1::unordered_multiset as described in the C++ TR1.
//!
//! unordered_multiset is a semi-intrusive container: each object to be stored in the
//! container must contain a proper hook, but the container also needs
//! additional auxiliary memory to work: unordered_multiset needs a pointer to an array
//! of type `bucket_type` to be passed in the constructor. This bucket array must
//! have at least the same lifetime as the container. This makes the use of
//! unordered_multiset more complicated than purely intrusive containers.
//! `bucket_type` is default-constructible, copyable and assignable
//!
//! The template parameter \c T is the type to be managed by the container.
//! The user can specify additional options and if no options are provided
//! default options are used.
//!
//! The container supports the following options:
//! \c base_hook<>/member_hook<>/value_traits<>,
//! \c constant_time_size<>, \c size_type<>, \c hash<> and \c equal<>
//! \c bucket_traits<>, \c power_2_buckets<> and \c cache_begin<>.
//!
//! unordered_multiset only provides forward iterators but it provides 4 iterator types:
//! iterator and const_iterator to navigate through the whole container and
//! local_iterator and const_local_iterator to navigate through the values
//! stored in a single bucket. Local iterators are faster and smaller.
//!
//! It's not recommended to use non constant-time size unordered_multisets because several
//! key functions, like "empty()", become non-constant time functions. Non
//! constant-time size unordered_multisets are mainly provided to support auto-unlink hooks.
//!
//! unordered_multiset, unlike std::unordered_set, does not make automatic rehashings nor
//! offers functions related to a load factor. Rehashing can be explicitly requested
//! and the user must provide a new bucket array that will be used from that moment.
//!
//! Since no automatic rehashing is done, iterators are never invalidated when
//! inserting or erasing elements. Iterators are only invalidated when rehasing.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)
template<class T, class ...Options>
#else
template<class ValueTraits, class VoidOrKeyOfValue, class VoidOrKeyHash, class VoidOrKeyEqual, class SizeType, class BucketTraits, std::size_t BoolFlags>
#endif
class unordered_multiset_impl
: public hashtable_impl<ValueTraits, VoidOrKeyOfValue, VoidOrKeyHash, VoidOrKeyEqual, BucketTraits, SizeType, BoolFlags>
{
/// @cond
private:
typedef hashtable_impl<ValueTraits, VoidOrKeyOfValue, VoidOrKeyHash, VoidOrKeyEqual, BucketTraits, SizeType, BoolFlags> table_type;
/// @endcond
//Movable
BOOST_MOVABLE_BUT_NOT_COPYABLE(unordered_multiset_impl)
typedef table_type implementation_defined;
public:
typedef typename implementation_defined::value_type value_type;
typedef typename implementation_defined::key_type key_type;
typedef typename implementation_defined::value_traits value_traits;
typedef typename implementation_defined::bucket_traits bucket_traits;
typedef typename implementation_defined::pointer pointer;
typedef typename implementation_defined::const_pointer const_pointer;
typedef typename implementation_defined::reference reference;
typedef typename implementation_defined::const_reference const_reference;
typedef typename implementation_defined::difference_type difference_type;
typedef typename implementation_defined::size_type size_type;
typedef typename implementation_defined::key_equal key_equal;
typedef typename implementation_defined::hasher hasher;
typedef typename implementation_defined::bucket_type bucket_type;
typedef typename implementation_defined::bucket_ptr bucket_ptr;
typedef typename implementation_defined::iterator iterator;
typedef typename implementation_defined::const_iterator const_iterator;
typedef typename implementation_defined::insert_commit_data insert_commit_data;
typedef typename implementation_defined::local_iterator local_iterator;
typedef typename implementation_defined::const_local_iterator const_local_iterator;
typedef typename implementation_defined::node_traits node_traits;
typedef typename implementation_defined::node node;
typedef typename implementation_defined::node_ptr node_ptr;
typedef typename implementation_defined::const_node_ptr const_node_ptr;
typedef typename implementation_defined::node_algorithms node_algorithms;
public:
//! @copydoc ::boost::intrusive::hashtable::hashtable(const bucket_traits &,const hasher &,const key_equal &,const value_traits &)
explicit unordered_multiset_impl ( const bucket_traits &b_traits
, const hasher & hash_func = hasher()
, const key_equal &equal_func = key_equal()
, const value_traits &v_traits = value_traits())
: table_type(b_traits, hash_func, equal_func, v_traits)
{}
//! @copydoc ::boost::intrusive::hashtable::hashtable(bool,Iterator,Iterator,const bucket_traits &,const hasher &,const key_equal &,const value_traits &)
template<class Iterator>
unordered_multiset_impl ( Iterator b
, Iterator e
, const bucket_traits &b_traits
, const hasher & hash_func = hasher()
, const key_equal &equal_func = key_equal()
, const value_traits &v_traits = value_traits())
: table_type(false, b, e, b_traits, hash_func, equal_func, v_traits)
{}
//! <b>Effects</b>: to-do
//!
unordered_multiset_impl(BOOST_RV_REF(unordered_multiset_impl) x)
: table_type(BOOST_MOVE_BASE(table_type, x))
{}
//! <b>Effects</b>: to-do
//!
unordered_multiset_impl& operator=(BOOST_RV_REF(unordered_multiset_impl) x)
{ return static_cast<unordered_multiset_impl&>(table_type::operator=(BOOST_MOVE_BASE(table_type, x))); }
#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
//! @copydoc ::boost::intrusive::hashtable::~hashtable()
~unordered_multiset_impl();
//! @copydoc ::boost::intrusive::hashtable::begin()
iterator begin();
//! @copydoc ::boost::intrusive::hashtable::begin()const
const_iterator begin() const;
//! @copydoc ::boost::intrusive::hashtable::cbegin()const
const_iterator cbegin() const;
//! @copydoc ::boost::intrusive::hashtable::end()
iterator end();
//! @copydoc ::boost::intrusive::hashtable::end()const
const_iterator end() const;
//! @copydoc ::boost::intrusive::hashtable::cend()const
const_iterator cend() const;
//! @copydoc ::boost::intrusive::hashtable::hash_function()const
hasher hash_function() const;
//! @copydoc ::boost::intrusive::hashtable::key_eq()const
key_equal key_eq() const;
//! @copydoc ::boost::intrusive::hashtable::empty()const
bool empty() const;
//! @copydoc ::boost::intrusive::hashtable::size()const
size_type size() const;
//! @copydoc ::boost::intrusive::hashtable::hashtable
void swap(unordered_multiset_impl& other);
//! @copydoc ::boost::intrusive::hashtable::clone_from(const hashtable&,Cloner,Disposer)
template <class Cloner, class Disposer>
void clone_from(const unordered_multiset_impl &src, Cloner cloner, Disposer disposer);
#else
using table_type::clone_from;
#endif // #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
//! @copydoc ::boost::intrusive::hashtable::clone_from(hashtable&&,Cloner,Disposer)
template <class Cloner, class Disposer>
void clone_from(BOOST_RV_REF(unordered_multiset_impl) src, Cloner cloner, Disposer disposer)
{ table_type::clone_from(BOOST_MOVE_BASE(table_type, src), cloner, disposer); }
//! @copydoc ::boost::intrusive::hashtable::insert_equal(reference)
iterator insert(reference value)
{ return table_type::insert_equal(value); }
//! @copydoc ::boost::intrusive::hashtable::insert_equal(Iterator,Iterator)
template<class Iterator>
void insert(Iterator b, Iterator e)
{ table_type::insert_equal(b, e); }
#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
//! @copydoc ::boost::intrusive::hashtable::erase(const_iterator)
void erase(const_iterator i);
//! @copydoc ::boost::intrusive::hashtable::erase(const_iterator,const_iterator)
void erase(const_iterator b, const_iterator e);
//! @copydoc ::boost::intrusive::hashtable::erase(const key_type &)
size_type erase(const key_type &key);
//! @copydoc ::boost::intrusive::hashtable::erase(const KeyType&,KeyHasher,KeyEqual)
template<class KeyType, class KeyHasher, class KeyEqual>
size_type erase(const KeyType& key, KeyHasher hash_func, KeyEqual equal_func);
//! @copydoc ::boost::intrusive::hashtable::erase_and_dispose(const_iterator,Disposer)
template<class Disposer>
BOOST_INTRUSIVE_DOC1ST(void
, typename detail::disable_if_convertible<Disposer BOOST_INTRUSIVE_I const_iterator>::type)
erase_and_dispose(const_iterator i, Disposer disposer);
//! @copydoc ::boost::intrusive::hashtable::erase_and_dispose(const_iterator,const_iterator,Disposer)
template<class Disposer>
void erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer);
//! @copydoc ::boost::intrusive::hashtable::erase_and_dispose(const key_type &,Disposer)
template<class Disposer>
size_type erase_and_dispose(const key_type &key, Disposer disposer);
//! @copydoc ::boost::intrusive::hashtable::erase_and_dispose(const KeyType&,KeyHasher,KeyEqual,Disposer)
template<class KeyType, class KeyHasher, class KeyEqual, class Disposer>
size_type erase_and_dispose(const KeyType& key, KeyHasher hash_func, KeyEqual equal_func, Disposer disposer);
//! @copydoc ::boost::intrusive::hashtable::clear
void clear();
//! @copydoc ::boost::intrusive::hashtable::clear_and_dispose
template<class Disposer>
void clear_and_dispose(Disposer disposer);
//! @copydoc ::boost::intrusive::hashtable::count(const key_type &)const
size_type count(const key_type &key) const;
//! @copydoc ::boost::intrusive::hashtable::count(const KeyType&,KeyHasher,KeyEqual)const
template<class KeyType, class KeyHasher, class KeyEqual>
size_type count(const KeyType& key, KeyHasher hash_func, KeyEqual equal_func) const;
//! @copydoc ::boost::intrusive::hashtable::find(const key_type &)
iterator find(const key_type &key);
//! @copydoc ::boost::intrusive::hashtable::find(const KeyType &,KeyHasher,KeyEqual)
template<class KeyType, class KeyHasher, class KeyEqual>
iterator find(const KeyType& key, KeyHasher hash_func, KeyEqual equal_func);
//! @copydoc ::boost::intrusive::hashtable::count(const key_type &)const
const_iterator find(const key_type &key) const;
//! @copydoc ::boost::intrusive::hashtable::find(const KeyType &,KeyHasher,KeyEqual)const
template<class KeyType, class KeyHasher, class KeyEqual>
const_iterator find(const KeyType& key, KeyHasher hash_func, KeyEqual equal_func) const;
//! @copydoc ::boost::intrusive::hashtable::equal_range(const key_type&)
std::pair<iterator,iterator> equal_range(const key_type &key);
//! @copydoc ::boost::intrusive::hashtable::equal_range(const KeyType &,KeyHasher,KeyEqual)
template<class KeyType, class KeyHasher, class KeyEqual>
std::pair<iterator,iterator> equal_range(const KeyType& key, KeyHasher hash_func, KeyEqual equal_func);
//! @copydoc ::boost::intrusive::hashtable::equal_range(const key_type&)const
std::pair<const_iterator, const_iterator>
equal_range(const key_type &key) const;
//! @copydoc ::boost::intrusive::hashtable::equal_range(const KeyType &,KeyHasher,KeyEqual)const
template<class KeyType, class KeyHasher, class KeyEqual>
std::pair<const_iterator, const_iterator>
equal_range(const KeyType& key, KeyHasher hash_func, KeyEqual equal_func) const;
//! @copydoc ::boost::intrusive::hashtable::iterator_to(reference)
iterator iterator_to(reference value);
//! @copydoc ::boost::intrusive::hashtable::iterator_to(const_reference)const
const_iterator iterator_to(const_reference value) const;
//! @copydoc ::boost::intrusive::hashtable::s_local_iterator_to(reference)
static local_iterator s_local_iterator_to(reference value);
//! @copydoc ::boost::intrusive::hashtable::s_local_iterator_to(const_reference)
static const_local_iterator s_local_iterator_to(const_reference value);
//! @copydoc ::boost::intrusive::hashtable::local_iterator_to(reference)
local_iterator local_iterator_to(reference value);
//! @copydoc ::boost::intrusive::hashtable::local_iterator_to(const_reference)
const_local_iterator local_iterator_to(const_reference value) const;
//! @copydoc ::boost::intrusive::hashtable::bucket_count
size_type bucket_count() const;
//! @copydoc ::boost::intrusive::hashtable::bucket_size
size_type bucket_size(size_type n) const;
//! @copydoc ::boost::intrusive::hashtable::bucket(const key_type&)const
size_type bucket(const key_type& k) const;
//! @copydoc ::boost::intrusive::hashtable::bucket(const KeyType&,KeyHasher)const
template<class KeyType, class KeyHasher>
size_type bucket(const KeyType& k, KeyHasher hash_func) const;
//! @copydoc ::boost::intrusive::hashtable::bucket_pointer
bucket_ptr bucket_pointer() const;
//! @copydoc ::boost::intrusive::hashtable::begin(size_type)
local_iterator begin(size_type n);
//! @copydoc ::boost::intrusive::hashtable::begin(size_type)const
const_local_iterator begin(size_type n) const;
//! @copydoc ::boost::intrusive::hashtable::cbegin(size_type)const
const_local_iterator cbegin(size_type n) const;
//! @copydoc ::boost::intrusive::hashtable::end(size_type)
local_iterator end(size_type n);
//! @copydoc ::boost::intrusive::hashtable::end(size_type)const
const_local_iterator end(size_type n) const;
//! @copydoc ::boost::intrusive::hashtable::cend(size_type)const
const_local_iterator cend(size_type n) const;
//! @copydoc ::boost::intrusive::hashtable::rehash(const bucket_traits &)
void rehash(const bucket_traits &new_bucket_traits);
//! @copydoc ::boost::intrusive::hashtable::incremental_rehash(bool)
bool incremental_rehash(bool grow = true);
//! @copydoc ::boost::intrusive::hashtable::incremental_rehash(const bucket_traits &)
bool incremental_rehash(const bucket_traits &new_bucket_traits);
//! @copydoc ::boost::intrusive::hashtable::split_count
size_type split_count() const;
//! @copydoc ::boost::intrusive::hashtable::suggested_upper_bucket_count
static size_type suggested_upper_bucket_count(size_type n);
//! @copydoc ::boost::intrusive::hashtable::suggested_lower_bucket_count
static size_type suggested_lower_bucket_count(size_type n);
#endif // #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
};
//! Helper metafunction to define an \c unordered_multiset that yields to the same type when the
//! same options (either explicitly or implicitly) are used.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class ...Options>
#else
template<class T, class O1 = void, class O2 = void
, class O3 = void, class O4 = void
, class O5 = void, class O6 = void
, class O7 = void, class O8 = void
, class O9 = void, class O10= void
>
#endif
struct make_unordered_multiset
{
/// @cond
typedef typename pack_options
< hashtable_defaults,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4, O5, O6, O7, O8, O9, O10
#else
Options...
#endif
>::type packed_options;
typedef typename detail::get_value_traits
<T, typename packed_options::proto_value_traits>::type value_traits;
typedef typename make_bucket_traits
<T, true, packed_options>::type bucket_traits;
typedef unordered_multiset_impl
< value_traits
, typename packed_options::key_of_value
, typename packed_options::hash
, typename packed_options::equal
, typename packed_options::size_type
, bucket_traits
, (std::size_t(false)*hash_bool_flags::unique_keys_pos)
| (std::size_t(packed_options::constant_time_size)*hash_bool_flags::constant_time_size_pos)
| (std::size_t(packed_options::power_2_buckets)*hash_bool_flags::power_2_buckets_pos)
| (std::size_t(packed_options::cache_begin)*hash_bool_flags::cache_begin_pos)
| (std::size_t(packed_options::compare_hash)*hash_bool_flags::compare_hash_pos)
| (std::size_t(packed_options::incremental)*hash_bool_flags::incremental_pos)
> implementation_defined;
/// @endcond
typedef implementation_defined type;
};
#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class O1, class O2, class O3, class O4, class O5, class O6, class O7, class O8, class O9, class O10>
#else
template<class T, class ...Options>
#endif
class unordered_multiset
: public make_unordered_multiset<T,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4, O5, O6, O7, O8, O9, O10
#else
Options...
#endif
>::type
{
typedef typename make_unordered_multiset
<T,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4, O5, O6, O7, O8, O9, O10
#else
Options...
#endif
>::type Base;
//Assert if passed value traits are compatible with the type
BOOST_STATIC_ASSERT((detail::is_same<typename Base::value_traits::value_type, T>::value));
BOOST_MOVABLE_BUT_NOT_COPYABLE(unordered_multiset)
public:
typedef typename Base::value_traits value_traits;
typedef typename Base::bucket_traits bucket_traits;
typedef typename Base::iterator iterator;
typedef typename Base::const_iterator const_iterator;
typedef typename Base::bucket_ptr bucket_ptr;
typedef typename Base::size_type size_type;
typedef typename Base::hasher hasher;
typedef typename Base::key_equal key_equal;
explicit unordered_multiset( const bucket_traits &b_traits
, const hasher & hash_func = hasher()
, const key_equal &equal_func = key_equal()
, const value_traits &v_traits = value_traits())
: Base(b_traits, hash_func, equal_func, v_traits)
{}
template<class Iterator>
unordered_multiset( Iterator b
, Iterator e
, const bucket_traits &b_traits
, const hasher & hash_func = hasher()
, const key_equal &equal_func = key_equal()
, const value_traits &v_traits = value_traits())
: Base(b, e, b_traits, hash_func, equal_func, v_traits)
{}
unordered_multiset(BOOST_RV_REF(unordered_multiset) x)
: Base(BOOST_MOVE_BASE(Base, x))
{}
unordered_multiset& operator=(BOOST_RV_REF(unordered_multiset) x)
{ return static_cast<unordered_multiset&>(this->Base::operator=(BOOST_MOVE_BASE(Base, x))); }
template <class Cloner, class Disposer>
void clone_from(const unordered_multiset &src, Cloner cloner, Disposer disposer)
{ Base::clone_from(src, cloner, disposer); }
template <class Cloner, class Disposer>
void clone_from(BOOST_RV_REF(unordered_multiset) src, Cloner cloner, Disposer disposer)
{ Base::clone_from(BOOST_MOVE_BASE(Base, src), cloner, disposer); }
};
#endif
} //namespace intrusive
} //namespace boost
#include <boost/intrusive/detail/config_end.hpp>
#endif //BOOST_INTRUSIVE_UNORDERED_SET_HPP
|
mikiec84/figaro
|
Figaro/src/main/scala/com/cra/figaro/algorithm/structured/Bounds.scala
|
<gh_stars>100-1000
/*
* Bounds.scala
* Definition of lower and upper bounds.
*
* Created By: <NAME> (<EMAIL>)
* Creation Date: March 1, 2015
*
* Copyright 2017 <NAME> and Charles River Analytics, Inc.
* See http://www.cra.com or email <EMAIL> for information.
*
* See http://www.github.com/p2t2/figaro for a copy of the software license.
*/
package com.cra.figaro.algorithm.structured
sealed abstract class Bounds
case object Lower extends Bounds
case object Upper extends Bounds
|
martinkro/tutorial-qt
|
Beautiful/Process/src/custompushbutton.cpp
|
<filename>Beautiful/Process/src/custompushbutton.cpp<gh_stars>1-10
#include "custompushbutton.h"
CustomPushButton::CustomPushButton(QWidget *parent)
: QPushButton(parent), m_bgpic("")
{
isPressed = false;
m_status = NORMAL;
}
/*
* Repaint the button according to different status.
*/
void CustomPushButton::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QString pixmapPath;
switch (m_status)
{
case NORMAL:
pixmapPath = m_bgpic;
break;
case HOVER:
pixmapPath = m_bgpic+"_hover";
break;
case PRESSED:
pixmapPath = m_bgpic+"_pressed";
break;
default:
pixmapPath = m_bgpic;
break;
}
// draw the button background
painter.drawPixmap(rect(), QPixmap(pixmapPath));
}
void CustomPushButton::mousePressEvent(QMouseEvent *event)
{
// only when the left button is pressed we force the repaint
if (event->button() == Qt::LeftButton)
{
isPressed = true;
m_status = PRESSED;
update();
}
}
void CustomPushButton::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton && isPressed)
{
isPressed = false;
update();
emit clicked();
}
}
void CustomPushButton::enterEvent(QEvent* event)
{
isPressed = false;
m_status = HOVER;
}
void CustomPushButton::leaveEvent(QEvent* event)
{
isPressed = false;
m_status = NORMAL;
}
void CustomPushButton::setButtonBgrd(const QString& filename)
{
m_bgpic = filename;
// resize the button to fit the background picture.
setFixedSize(QPixmap(m_bgpic).size());
}
|
mschwartz/creative-engine
|
src/Controls/DesktopControls/DesktopControls.cpp
|
<gh_stars>0
#include "DesktopControls.h"
#ifdef CONTROLLER_SUPPORT
#include <SDL.h>
#endif
DesktopControls::DesktopControls() : ControlsBase() {
#ifdef CONTROLLER_SUPPORT
SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER | SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC);
haptic = ENull;
ctrl = ENull;
for (TInt i = 0; i < SDL_NumJoysticks(); ++i) {
if (!SDL_IsGameController(i)) {
continue;
}
ctrl = SDL_GameControllerOpen(i);
haptic = SDL_HapticOpenFromJoystick(SDL_GameControllerGetJoystick(ctrl));
break;
#ifndef PRODUCTION
SDL_Log("Found a compatible controller named \'%s\'", SDL_GameControllerNameForIndex(i));
SDL_Log("Controller %i is mapped as \"%s\".", i, SDL_GameControllerMapping(ctrl));
#endif
}
#endif
}
DesktopControls::~DesktopControls() {
#ifdef CONTROLLER_SUPPORT
if (haptic) {
SDL_HapticClose(haptic);
}
SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER | SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC);
#endif
}
void DesktopControls::Rumble(TFloat aStrength, TInt aTime) {
#ifdef CONTROLLER_SUPPORT
if (haptic == ENull || SDL_NumJoysticks() == 0) {
return;
}
// Initialize simple rumble
SDL_HapticRumbleInit(haptic);
SDL_HapticRumblePlay(haptic, aStrength, aTime);
#endif
}
TBool DesktopControls::Poll() {
SDL_Event e;
while (SDL_PollEvent(&e)) {
TUint16 keys = bKeys;
if (e.type == SDL_QUIT) {
keys |= BUTTONQ;
}
// Controllers
#ifdef CONTROLLER_SUPPORT
if (SDL_NumJoysticks() > 0) {
if (SDL_GameControllerGetAxis(ctrl, SDL_CONTROLLER_AXIS_LEFTY) > CONTROLLER_AXIS_MIN || SDL_GameControllerGetButton(ctrl, SDL_CONTROLLER_BUTTON_DPAD_DOWN)) {
keys |= JOYDOWN;
} else {
keys &= ~JOYDOWN;
}
if (SDL_GameControllerGetAxis(ctrl, SDL_CONTROLLER_AXIS_LEFTY) < -CONTROLLER_AXIS_MIN || SDL_GameControllerGetButton(ctrl, SDL_CONTROLLER_BUTTON_DPAD_UP)) {
keys |= JOYUP;
} else {
keys &= ~JOYUP;
}
if (SDL_GameControllerGetAxis(ctrl, SDL_CONTROLLER_AXIS_LEFTX) > CONTROLLER_AXIS_MIN || SDL_GameControllerGetButton(ctrl, SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) {
keys |= JOYRIGHT;
} else {
keys &= ~JOYRIGHT;
}
if (SDL_GameControllerGetAxis(ctrl, SDL_CONTROLLER_AXIS_LEFTX) < -CONTROLLER_AXIS_MIN || SDL_GameControllerGetButton(ctrl, SDL_CONTROLLER_BUTTON_DPAD_LEFT)) {
keys |= JOYLEFT;
} else {
keys &= ~JOYLEFT;
}
if (e.type == SDL_CONTROLLERBUTTONDOWN) {
switch (e.cbutton.button) {
case SDL_CONTROLLER_BUTTON_A:
keys |= BUTTONB;
break;
case SDL_CONTROLLER_BUTTON_B:
keys |= BUTTONA;
break;
case SDL_CONTROLLER_BUTTON_X:
keys |= BUTTON_MENU;
break;
case SDL_CONTROLLER_BUTTON_Y:
keys |= BUTTON_SOUND;
break;
case SDL_CONTROLLER_BUTTON_BACK:
keys |= BUTTON_SELECT;
break;
case SDL_CONTROLLER_BUTTON_START:
keys |= BUTTON_START;
break;
}
}
if (e.type == SDL_CONTROLLERBUTTONUP) {
switch (e.cbutton.button) {
case SDL_CONTROLLER_BUTTON_A:
keys &= ~BUTTONB;
break;
case SDL_CONTROLLER_BUTTON_B:
keys &= ~BUTTONA;
break;
case SDL_CONTROLLER_BUTTON_X:
keys &= ~BUTTON_MENU;
break;
case SDL_CONTROLLER_BUTTON_Y:
keys &= ~BUTTON_SOUND;
break;
case SDL_CONTROLLER_BUTTON_BACK:
keys &= ~BUTTON_SELECT;
break;
case SDL_CONTROLLER_BUTTON_START:
keys &= ~BUTTON_START;
break;
}
}
}
#endif
// Keyboard
if (e.type == SDL_KEYDOWN) {
switch (e.key.keysym.scancode) {
// QUIT button, will never be set on target
case SDL_SCANCODE_Q:
keys |= BUTTONQ;
break;
case SDL_SCANCODE_1:
keys |= BUTTON1;
break;
case SDL_SCANCODE_2:
keys |= BUTTON2;
break;
case SDL_SCANCODE_3:
keys |= BUTTON3;
break;
case SDL_SCANCODE_4:
case SDL_SCANCODE_RETURN:
keys |= BUTTON4;
break;
case SDL_SCANCODE_RALT:
case SDL_SCANCODE_LCTRL:
case SDL_SCANCODE_X:
keys |= BUTTONA;
break;
case SDL_SCANCODE_SPACE:
case SDL_SCANCODE_Z:
case SDL_SCANCODE_RCTRL:
case SDL_SCANCODE_LALT:
keys |= BUTTONB;
break;
case SDL_SCANCODE_K:
case SDL_SCANCODE_UP:
keys |= JOYUP;
break;
case SDL_SCANCODE_J:
case SDL_SCANCODE_DOWN:
keys |= JOYDOWN;
break;
case SDL_SCANCODE_H:
case SDL_SCANCODE_LEFT:
keys |= JOYLEFT;
break;
case SDL_SCANCODE_L:
case SDL_SCANCODE_RIGHT:
keys |= JOYRIGHT;
break;
default:
break;
}
}
if (e.type == SDL_KEYUP) {
switch (e.key.keysym.scancode) {
// QUIT button, will never be set on target
case SDL_SCANCODE_Q:
keys &= ~BUTTONQ;
break;
case SDL_SCANCODE_1:
keys &= ~BUTTON1;
break;
case SDL_SCANCODE_2:
keys &= ~BUTTON2;
break;
case SDL_SCANCODE_3:
keys &= ~BUTTON3;
break;
case SDL_SCANCODE_4:
case SDL_SCANCODE_RETURN:
keys &= ~BUTTON4;
break;
case SDL_SCANCODE_RALT:
case SDL_SCANCODE_LCTRL:
case SDL_SCANCODE_Z:
keys &= ~BUTTONB;
break;
case SDL_SCANCODE_SPACE:
case SDL_SCANCODE_X:
case SDL_SCANCODE_RCTRL:
case SDL_SCANCODE_LALT:
keys &= ~BUTTONA;
break;
case SDL_SCANCODE_K:
case SDL_SCANCODE_UP:
keys &= ~JOYUP;
break;
case SDL_SCANCODE_J:
case SDL_SCANCODE_DOWN:
keys &= ~JOYDOWN;
break;
case SDL_SCANCODE_H:
case SDL_SCANCODE_LEFT:
keys &= ~JOYLEFT;
break;
case SDL_SCANCODE_L:
case SDL_SCANCODE_RIGHT:
keys &= ~JOYRIGHT;
break;
default:
break;
}
}
// cKeys are journaled if journaling is on!
dKeys |= (keys ^ cKeys) & keys;
cKeys = keys;
bKeys = keys;
// if (e.type == SDL_MOUSEBUTTONDOWN) {
// quit = true;
// }
}
return false;
}
|
zhouyium/AtCoder
|
HHKBPC2020/TaskD.cpp
|
//https://atcoder.jp/contests/hhkb2020/tasks/hhkb2020_c
//HHKB Programming Contest 2020
//D - Squares
//https://blog.csdn.net/justidle/article/details/109024249
/*数学题*/
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MO = 1e9+7;
int main() {
int t;
cin>>t;
while (t--) {
LL n, a, b;
cin>>n>>a>>b;
LL ans = 0;
LL d=n-a-b;
if (d>=0) {
LL x=(d+1)*(d+2)%MO;
LL y=n-a+1;
LL z=n-b+1;
ans=2*x*(y*z%MO)%MO-x*x%MO;
ans=(ans+MO)%MO;
}
cout<<ans<<"\n";
}
return 0;
}
|
windystrife/UnrealEngine_NVIDIAGameWork
|
Engine/Source/Runtime/Engine/Classes/DeviceProfiles/DeviceProfileManager.h
|
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
DeviceProfileManager.h: Declares the FDeviceProfileManager class.
=============================================================================*/
#pragma once
#include "CoreMinimal.h"
#include "UObject/ObjectMacros.h"
#include "UObject/Object.h"
#include "DeviceProfileManager.generated.h"
class UDeviceProfile;
// Delegate used to refresh the UI when the profiles change
DECLARE_MULTICAST_DELEGATE( FOnDeviceProfileManagerUpdated );
/**
* Implements a helper class that manages all profiles in the Device
*/
UCLASS( config=DeviceProfiles, transient )
class ENGINE_API UDeviceProfileManager : public UObject
{
public:
GENERATED_BODY()
/**
* Startup and select the active device profile
* Then Init the CVars from this profile and it's Device profile parent tree.
*/
static void InitializeCVarsForActiveDeviceProfile(bool bPushSettings=false);
/**
* Create a copy of a device profile from a copy.
*
* @param ProfileName - The profile name.
* @param ProfileToCopy - The profile to copy name.
*
* @return the created profile.
*/
UDeviceProfile* CreateProfile(const FString& ProfileName, const FString& ProfileType, const FString& ParentName=TEXT(""), const TCHAR* ConfigPlatform=nullptr);
/**
* Delete a profile.
*
* @param Profile - The profile to delete.
*/
void DeleteProfile( UDeviceProfile* Profile );
/**
* Find a profile based on the name.
*
* @param ProfileName - The profile name to find.
* @return The found profile.
*/
UDeviceProfile* FindProfile( const FString& ProfileName );
/**
* Get the device profile .ini name.
*
* @return the device profile .ini name.
*/
const FString GetDeviceProfileIniName() const;
/**
* Load the device profiles from the config file.
*/
void LoadProfiles();
/**
* Returns a delegate that is invoked when manager is updated.
*
* @return The delegate.
*/
FOnDeviceProfileManagerUpdated& OnManagerUpdated();
/**
* Save the device profiles.
*/
void SaveProfiles(bool bSaveToDefaults = false);
/**
* Get the selected device profile
*
* @return The selected profile.
*/
UDeviceProfile* GetActiveProfile() const;
/**
* Get a list of all possible parent profiles for a given device profile
*
* @param ChildProfile - The profile we are looking for potential parents
* @param PossibleParentProfiles - The list of profiles which would be suitable as a parent for the given profile
*/
void GetAllPossibleParentProfiles(const UDeviceProfile* ChildProfile, OUT TArray<UDeviceProfile*>& PossibleParentProfiles) const;
/**
* Get the selected device profile name, either the platform name, or the name
* provided by a Device Profile Selector Module.
*
* @return The selected profile.
*/
static const FString GetActiveProfileName();
private:
/**
* Set the active device profile - set via the device profile blueprint.
*
* @param DeviceProfileName - The profile name.
*/
void SetActiveDeviceProfile( UDeviceProfile* DeviceProfile );
/**
* Override CVar value change callback
*/
void HandleDeviceProfileOverrideChange();
/** Handle restoing CVars set in HandleDeviceProfileOverrideChange */
void HandleDeviceProfileOverridePop();
public:
static class UDeviceProfileManager* DeviceProfileManagerSingleton;
static UDeviceProfileManager& Get(bool bFromPostCDOContruct = false);
virtual void PostCDOContruct() override
{
Get(true); // get this taken care of now
}
public:
// Holds the collection of managed profiles.
UPROPERTY( EditAnywhere, Category=Properties )
TArray< UObject* > Profiles;
private:
// Holds a delegate to be invoked profiles are updated.
FOnDeviceProfileManagerUpdated ManagerUpdatedDelegate;
// Holds the selected device profile
UDeviceProfile* ActiveDeviceProfile;
// Holds the device profile .ini location
static FString DeviceProfileFileName;
// values of CVars set in HandleDeviceProfileOverrideChange, to be popped later
TMap<FString, FString> PushedSettings;
};
|
sistcoop/asyubl
|
src/main/java/org/easyubl/utils/RepresentationToModel.java
|
<gh_stars>0
package org.easyubl.utils;
import org.openfact.common.util.MultivaluedHashMap;
import org.openfact.component.ComponentModel;
import org.openfact.components.utils.ComponentUtil;
import org.openfact.keys.KeyProvider;
import org.openfact.models.ComponentProvider;
import org.openfact.models.ModelException;
import org.openfact.models.CompanyModel;
import org.openfact.models.search.SearchCriteriaFilterOperator;
import org.openfact.models.search.SearchCriteriaModel;
import org.openfact.provider.ProviderConfigProperty;
import org.openfact.representations.idm.ComponentExportRepresentation;
import org.openfact.representations.idm.ComponentRepresentation;
import org.openfact.representations.idm.OrganizationRepresentation;
import org.openfact.representations.idm.PostalAddressRepresentation;
import org.openfact.representations.idm.search.PagingRepresentation;
import org.openfact.representations.idm.search.SearchCriteriaFilterOperatorRepresentation;
import org.openfact.representations.idm.search.SearchCriteriaFilterRepresentation.FilterValueType;
import org.openfact.representations.idm.search.SearchCriteriaRepresentation;
import javax.ejb.Stateless;
import javax.inject.Inject;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
@Stateless
public class RepresentationToModel {
@Inject
private ComponentUtil componentUtil;
@Inject
private ComponentProvider componentProvider;
@Inject
private DefaultKeyProviders defaultKeyProviders;
public SearchCriteriaModel toModel(SearchCriteriaRepresentation rep) {
SearchCriteriaModel model = new SearchCriteriaModel();
// filters
Function<SearchCriteriaFilterOperatorRepresentation, SearchCriteriaFilterOperator> operatorFunction = f -> {
return SearchCriteriaFilterOperator.valueOf(f.toString());
};
BiFunction<Object, FilterValueType, Object> valueFunction = (value, type) -> {
if (type == null) return value;
Object result = null;
switch (type) {
case LONG:
result = (long) value;
break;
case STRING:
result = (String) value;
break;
case DATE:
result = LocalDateTime.parse((String) value, DateTimeFormatter.ISO_DATE);
break;
case DATETIME:
result = LocalDateTime.parse((String) value, DateTimeFormatter.ISO_DATE_TIME);
break;
default:
result = value;
break;
}
return result;
};
rep.getFilters().forEach(f -> {
model.addFilter(f.getName(), valueFunction.apply(f.getValue(), f.getType()),
operatorFunction.apply(f.getOperator()));
});
// sorter
rep.getOrders().forEach(f -> model.addOrder(f.getName(), f.isAscending()));
// paging
if (rep.getPaging() != null) {
PagingRepresentation paging = rep.getPaging();
model.setPageSize(paging.getPageSize());
model.setPage(paging.getPage());
}
return model;
}
public void importOrganization(OrganizationRepresentation rep, CompanyModel newOrganization) throws ModelException {
newOrganization.setName(rep.getOrganization());
generalUpdateOrganization(newOrganization, rep);
/*
* Postal address
*/
if (rep.getPostalAddress() != null) {
updatePostalAddress(newOrganization, rep);
}
/*
* Events
*/
if (rep.getEventsEnabled() != null) {
newOrganization.setEventsEnabled(rep.getEventsEnabled());
}
if (rep.getEventsExpiration() != null) {
newOrganization.setEventsExpiration(rep.getEventsExpiration());
}
if (rep.getEventsListeners() != null) {
newOrganization.setEventsListeners(new HashSet<>(rep.getEventsListeners()));
}
if (rep.getAdminEventsEnabled() != null) {
newOrganization.setAdminEventsEnabled(rep.getAdminEventsEnabled());
}
if (rep.getAdminEventsDetailsEnabled() != null) {
newOrganization.setAdminEventsDetailsEnabled(rep.getAdminEventsDetailsEnabled());
}
if (rep.getComponents() != null) {
MultivaluedHashMap<String, ComponentExportRepresentation> components = rep.getComponents();
String parentId = newOrganization.getId();
importComponents(newOrganization, components, parentId, componentProvider);
}
/*
* Certificate
*/
if (componentProvider.getComponents(newOrganization, newOrganization.getId(), KeyProvider.class.getName()).isEmpty()) {
if (rep.getPrivateKey() != null) {
defaultKeyProviders.createProviders(newOrganization, rep.getPrivateKey(), rep.getCertificate());
} else {
defaultKeyProviders.createProviders(newOrganization);
}
}
/*
* Attributes
*/
if (rep.getAttributes() != null) {
for (Map.Entry<String, String> attr : rep.getAttributes().entrySet()) {
newOrganization.setAttribute(attr.getKey(), attr.getValue());
}
}
}
public void updateOrganization(OrganizationRepresentation rep, CompanyModel organization) throws ModelException {
if (rep.getOrganization() != null) {
renameOrganization(organization, rep.getOrganization());
}
// Import attributes first, so the stuff saved directly on
// representation (displayName, bruteForce etc) has bigger priority
if (rep.getAttributes() != null) {
Set<String> attrsToRemove = new HashSet<>(organization.getAttributes().keySet());
attrsToRemove.removeAll(rep.getAttributes().keySet());
for (Map.Entry<String, String> entry : rep.getAttributes().entrySet()) {
organization.setAttribute(entry.getKey(), entry.getValue());
}
for (String attr : attrsToRemove) {
organization.removeAttribute(attr);
}
}
generalUpdateOrganization(organization, rep);
/*
* Postal address
*/
if (rep.getPostalAddress() != null) {
updatePostalAddress(organization, rep);
}
/*
* Events
*/
if (rep.getEventsEnabled() != null) {
organization.setEventsEnabled(rep.getEventsEnabled());
}
if (rep.getEventsExpiration() != null) {
organization.setEventsExpiration(rep.getEventsExpiration());
}
if (rep.getEventsListeners() != null) {
organization.setEventsListeners(new HashSet<>(rep.getEventsListeners()));
}
if (rep.getEnabledEventTypes() != null) {
organization.setEnabledEventTypes(new HashSet<>(rep.getEnabledEventTypes()));
}
if (rep.getAdminEventsEnabled() != null) {
organization.setAdminEventsEnabled(rep.getAdminEventsEnabled());
}
if (rep.getAdminEventsDetailsEnabled() != null) {
organization.setAdminEventsDetailsEnabled(rep.getAdminEventsDetailsEnabled());
}
}
public void renameOrganization(CompanyModel organization, String name) {
if (name.equals(organization.getName())) {
return;
}
organization.setName(name);
}
public void generalUpdateOrganization(CompanyModel organization, OrganizationRepresentation rep) {
/*
* General information
*/
if (rep.getDescription() != null) {
organization.setDescription(rep.getDescription());
}
if (rep.getEnabled() != null) {
organization.setEnabled(rep.getEnabled());
}
if (rep.getAssignedIdentificationId() != null) {
organization.setAssignedIdentificationId(rep.getAssignedIdentificationId());
}
if (rep.getAdditionalAccountId() != null) {
organization.setAdditionalAccountId(rep.getAdditionalAccountId());
}
if (rep.getSupplierName() != null) {
organization.setSupplierName(rep.getSupplierName());
}
if (rep.getRegistrationName() != null) {
organization.setRegistrationName(rep.getRegistrationName());
}
/*
* Themes
*/
if (rep.getEmailTheme() != null) {
organization.setEmailTheme(rep.getEmailTheme());
}
if (rep.getReportTheme() != null) {
organization.setReportTheme(rep.getReportTheme());
}
/*
* Internationalization
*/
if (rep.getInternationalizationEnabled() != null) {
organization.setInternationalizationEnabled(rep.getInternationalizationEnabled());
}
if (rep.getSupportedLocales() != null) {
organization.setSupportedLocales(new HashSet<>(rep.getSupportedLocales()));
}
if (rep.getDefaultLocale() != null) {
organization.setDefaultLocale(rep.getDefaultLocale());
}
/*
* Tasks schedule
*/
if (rep.isTasksEnabled() != null) {
organization.setTaskEnabled(rep.isTasksEnabled());
}
if (rep.getTaskFirstTime() != null) {
organization.setTaskFirstTime(rep.getTaskFirstTime());
}
if (rep.getTaskDelay() != null) {
organization.setTaskDelay(rep.getTaskDelay());
}
/*
* Currencies
*/
if (rep.getDefaultCurrency() != null) {
organization.setDefaultCurrency(rep.getDefaultCurrency());
}
if (rep.getSupportedCurrencies() != null) {
organization.setSupportedCurrencies(new HashSet<String>(new HashSet<>(rep.getSupportedCurrencies())));
}
/*
* Smtp server
*/
if (rep.getSmtpServer() != null) {
organization.setSmtpConfig(new HashMap<String, String>(rep.getSmtpServer()));
}
}
public void updatePostalAddress(CompanyModel organization, OrganizationRepresentation rep) {
if (rep.getPostalAddress() != null) {
PostalAddressRepresentation postalAddressRep = rep.getPostalAddress();
if (postalAddressRep.getPostalAddressId() != null) {
organization.setPostalAddressId(postalAddressRep.getPostalAddressId());
}
if (postalAddressRep.getCountryIdentificationCode() != null) {
organization.setCountryIdentificationCode(postalAddressRep.getCountryIdentificationCode());
}
if (postalAddressRep.getCountrySubentity() != null) {
organization.setCountrySubentity(postalAddressRep.getCountrySubentity());
}
if (postalAddressRep.getCityName() != null) {
organization.setCityName(postalAddressRep.getCityName());
}
if (postalAddressRep.getCitySubdivisionName() != null) {
organization.setCitySubdivisionName(postalAddressRep.getCitySubdivisionName());
}
if (postalAddressRep.getDistrict() != null) {
organization.setDistrict(postalAddressRep.getDistrict());
}
if (postalAddressRep.getStreetName() != null) {
organization.setStreetName(postalAddressRep.getStreetName());
}
}
}
public ComponentModel toModel(ComponentRepresentation rep) {
ComponentModel model = new ComponentModel();
model.setParentId(rep.getParentId());
model.setProviderType(rep.getProviderType());
model.setProviderId(rep.getProviderId());
model.setConfig(new MultivaluedHashMap<>());
model.setName(rep.getName());
model.setSubType(rep.getSubType());
if (rep.getConfig() != null) {
Set<String> keys = new HashSet<>(rep.getConfig().keySet());
for (String k : keys) {
List<String> values = rep.getConfig().get(k);
if (values != null) {
ListIterator<String> itr = values.listIterator();
while (itr.hasNext()) {
String v = itr.next();
if (v == null || v.trim().isEmpty()) {
itr.remove();
}
}
if (!values.isEmpty()) {
model.getConfig().put(k, values);
}
}
}
}
return model;
}
public void updateComponent(ComponentRepresentation rep, ComponentModel component, boolean internal) {
if (rep.getName() != null) {
component.setName(rep.getName());
}
if (rep.getParentId() != null) {
component.setParentId(rep.getParentId());
}
if (rep.getProviderType() != null) {
component.setProviderType(rep.getProviderType());
}
if (rep.getProviderId() != null) {
component.setProviderId(rep.getProviderId());
}
if (rep.getSubType() != null) {
component.setSubType(rep.getSubType());
}
Map<String, ProviderConfigProperty> providerConfiguration = null;
if (!internal) {
providerConfiguration = componentUtil.getComponentConfigProperties(component);
}
if (rep.getConfig() != null) {
Set<String> keys = new HashSet<>(rep.getConfig().keySet());
for (String k : keys) {
if (!internal && !providerConfiguration.containsKey(k)) {
break;
}
List<String> values = rep.getConfig().get(k);
if (values == null || values.isEmpty() || values.get(0) == null
|| values.get(0).trim().isEmpty()) {
component.getConfig().remove(k);
} else {
ListIterator<String> itr = values.listIterator();
while (itr.hasNext()) {
String v = itr.next();
if (v == null || v.trim().isEmpty() || v.equals(ComponentRepresentation.SECRET_VALUE)) {
itr.remove();
}
}
if (!values.isEmpty()) {
component.getConfig().put(k, values);
}
}
}
}
}
protected void importComponents(CompanyModel newOrganization, MultivaluedHashMap<String, ComponentExportRepresentation> components, String parentId, ComponentProvider componentProvider) throws ModelException {
for (Map.Entry<String, List<ComponentExportRepresentation>> entry : components.entrySet()) {
String providerType = entry.getKey();
for (ComponentExportRepresentation compRep : entry.getValue()) {
ComponentModel component = new ComponentModel();
component.setId(compRep.getId());
component.setName(compRep.getName());
component.setConfig(compRep.getConfig());
component.setProviderType(providerType);
component.setProviderId(compRep.getProviderId());
component.setSubType(compRep.getSubType());
component.setParentId(parentId);
component = componentProvider.addComponentModel(newOrganization, component);
if (compRep.getSubComponents() != null) {
importComponents(newOrganization, compRep.getSubComponents(), component.getId(), componentProvider);
}
}
}
}
}
|
yongmin86k/project__boomtown
|
client/src/components/ItemsGrid/index.js
|
import ItemsGrid from './ItemsGrid'
export default ItemsGrid;
|
RobertTheNerd/sc2geeks
|
web-api/website/www.website/src/main/java/com/sc2geeks/front/ui/SearchUrlHelper.java
|
package com.sc2geeks.front.ui;
import api.sc2geeks.entity.*;
import com.sc2geeks.commons.web.UrlUTF8Encoder;
import com.sc2geeks.front.IRefinementInfoProvider;
import com.sc2geeks.front.RefinementSetting;
import com.sc2geeks.front.WebsiteConfig;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* User: robert
* Date: 4/27/12
* Time: 5:01 AM
* To change this template use File | Settings | File Templates.
*/
public class SearchUrlHelper extends PageUrlHelper
{
private static WebsiteConfig websiteConfig = WebsiteConfig.getInstance();
private LinkedHashMap<String, String> fieldValueMap;
private RefinementField fieldToShowAllValues = null;
protected Set<RefinementField> filterFields;
IRefinementInfoProvider leftNavRefinementProvider;
IRefinementInfoProvider showAllRefinementProvider;
boolean legacyUrlDetected = false;
private SearchInput searchInput;
private String urlString;
public SearchUrlHelper(String namespace, String actionPath, String queryString,
IRefinementInfoProvider leftNavRefinementProvider,
IRefinementInfoProvider showAllRefinementProvider)
{
super(namespace, actionPath, queryString);
this.leftNavRefinementProvider = leftNavRefinementProvider;
this.showAllRefinementProvider = showAllRefinementProvider;
parseSearchInput();
// rewrite actionPath;
this.actionPath = regenerateActionPath(null);
}
public SearchInput getSearchInput()
{
return searchInput;
}
public Set<RefinementField> getFilterFields()
{
return filterFields;
}
public String removeFields(RefinementField... fields)
{
if (fields.length == 0)
return toString();
String actionPath, queryString;
actionPath = generateActionPath(fields);
queryString = generateQueryString(QueryStringManager.Param_Page, QueryStringManager.Param_ShowAllFor);
return generateWholeUrl(actionPath, queryString);
}
public String removeAllFields()
{
String actionPath, queryString;
actionPath = "";
queryString = generateQueryString(QueryStringManager.Param_Page, QueryStringManager.Param_ShowAllFor);
return generateWholeUrl(actionPath, queryString);
}
public String addField(RefinementField field, String value)
{
String actionPath, queryString;
actionPath = generateActionPath(field, value);
queryString = generateQueryString(QueryStringManager.Param_Page, QueryStringManager.Param_ShowAllFor);
return generateWholeUrl(actionPath, queryString);
}
public boolean isLegacyUrlDetected()
{
return legacyUrlDetected;
}
protected String getBaseUrl()
{
return PageUrlBuilder.getPage(PageUrlAlias.ReplaySearch);
}
private void parseSearchInput()
{
// normal search or list nav values
String navName = getQueryStringValue(QueryStringManager.Param_ShowAllFor);
if (StringUtils.isNotBlank(navName))
{
RefinementSetting setting = websiteConfig.getRefinementSettingByUrlPrefix(navName);
if (setting != null)
fieldToShowAllValues = setting.getRefinementField();
}
searchInput = new SearchInput();
searchInput.setSearchType(fieldToShowAllValues != null ? SearchType.RefinementOnly : SearchType.WithRefinement);
// get all filters
if (!StringUtils.isBlank(actionPath))
{
String[] parts = StringUtils.removeEnd(StringUtils.removeStart(actionPath, "/"), "/").split("/");
fieldValueMap = new LinkedHashMap<String, String>(parts.length);
for (String part : parts)
{
String[] fieldValue = part.split("-", 2);
String val = fieldValue.length > 1 ? UrlUTF8Encoder.decode(fieldValue[1]) : null;
if (fieldValue[0].compareToIgnoreCase(QueryStringManager.Param_Search) == 0)
{
// found legacy url
legacyUrlDetected = true;
if (StringUtils.isNotBlank(val))
{
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put(QueryStringManager.Param_Search, val);
map.putAll(queryStringMap);
queryStringMap = map;
}
}
else
{
fieldValueMap.put(fieldValue[0].toLowerCase().trim(), val);
}
}
} else
{
fieldValueMap = new LinkedHashMap<String, String>();
}
searchInput.setSearchTerms(queryStringMap.get(QueryStringManager.Param_Search));
parseSearchFilters();
// pagination
String page = getQueryStringValue(QueryStringManager.Param_Page);
String pageSize = getQueryStringValue(QueryStringManager.Param_PageSize);
if (StringUtils.isNotBlank(page))
{
try
{
searchInput.setCurrentPage(Integer.parseInt(page));
} catch (Exception e)
{
}
}
if (StringUtils.isNotBlank(pageSize))
{
try
{
searchInput.setPageSize(Integer.parseInt(pageSize));
} catch (Exception e)
{
}
}
// refinement
parseRefinementInfo();
}
private void parseSearchFilters()
{
parseLegacyFilter();
if (fieldValueMap == null || fieldValueMap.size() == 0)
return;
List<SearchFilter> searchFilters = searchInput.getSearchFilters() == null ?
new ArrayList<SearchFilter>(fieldValueMap.size()) : searchInput.getSearchFilters();
filterFields = new HashSet<RefinementField>(fieldValueMap.size());
for (String paramName : fieldValueMap.keySet())
{
RefinementSetting setting = websiteConfig.getRefinementSettingByUrlPrefix(paramName);
if (setting == null)
continue;
SearchFilter filter = new SearchFilter();
filter.setRefinementField(setting.getRefinementField());
filter.setValues(convertStringToList(fieldValueMap.get(paramName)));
searchFilters.add(filter);
filterFields.add(filter.getRefinementField());
}
searchInput.setSearchFilters(searchFilters);
}
private void parseLegacyFilter()
{
if (queryStringMap == null)
return;
List<SearchFilter> searchFilters = searchInput.getSearchFilters() == null ?
new ArrayList<SearchFilter>(fieldValueMap.size()) : searchInput.getSearchFilters();
for (String paramName : queryStringMap.keySet())
{
if (!paramName.startsWith("f."))
continue;
String legacyName = StringUtils.removeStart(paramName, "f.");
if (StringUtils.isBlank(legacyName))
continue;
RefinementSetting setting = websiteConfig.getRefinementSettingByLegacyParameter(legacyName);
if (setting == null)
continue;
SearchFilter filter = new SearchFilter();
filter.setRefinementField(setting.getRefinementField());
filter.setValues(convertStringToList(queryStringMap.get(paramName)));
searchFilters.add(filter);
if (filterFields == null)
filterFields = new HashSet<RefinementField>();
filterFields.add(filter.getRefinementField());
legacyUrlDetected = true;
}
searchInput.setSearchFilters(searchFilters);
}
private void parseRefinementInfo()
{
if (websiteConfig.getRefinementSettings() == null)
return;
List<RefinementInfo> refinementInfoList = new ArrayList<RefinementInfo>();
if (fieldToShowAllValues != null && showAllRefinementProvider != null)
{
RefinementInfo info = showAllRefinementProvider.getRefinementInfo(this.fieldToShowAllValues);
info.setMaxCount(0);
refinementInfoList.add(info);
} else if (leftNavRefinementProvider != null)
{
for (RefinementSetting setting : websiteConfig.getRefinementSettings())
{
if (filterFields != null && filterFields.contains(setting.getRefinementField()))
continue;
RefinementInfo info = leftNavRefinementProvider.getRefinementInfo(setting.getRefinementField());
if (info == null)
continue;
info.setMaxCount(info.getMaxCount() == 0 ? 0 : info.getMaxCount() + websiteConfig.getLeftNavTolerateCount() + 1);
refinementInfoList.add(info);
}
}
searchInput.setRefinementFields(refinementInfoList);
}
private static List<String> convertStringToList(String input)
{
if (StringUtils.isBlank(input))
return null;
String[] parts = input.split(",");
if (parts == null || parts.length == 0)
return null;
return Arrays.asList(parts);
}
private static String convertListToString(List<String> input)
{
StringBuilder sb = new StringBuilder();
for (String str : input)
{
sb.append(str).append(",");
}
return StringUtils.removeEnd(sb.toString(), ",");
}
private String generateActionPath(RefinementField... fieldsToRemove)
{
if (fieldsToRemove.length == 0)
{
return generateActionPath((HashSet<String>) null);
} else
{
HashSet<String> prefixSet = new HashSet<String>(fieldsToRemove.length);
for (RefinementField field : fieldsToRemove)
{
String prefix = websiteConfig.getRefinementUrlPrefix(field);
if (prefix != null)
prefixSet.add(prefix.toLowerCase());
}
return generateActionPath(prefixSet);
}
}
private String generateActionPath(HashSet<String> prefixSet)
{
String path;
if (prefixSet == null || prefixSet.size() == 0)
{
path = actionPath;
} else
{
path = regenerateActionPath(prefixSet);
}
return path;
}
private String regenerateActionPath(HashSet<String> prefixSet)
{
StringBuilder sb = new StringBuilder();
for (String prefix : fieldValueMap.keySet())
{
String name, value;
value = fieldValueMap.get(prefix);
if (StringUtils.isBlank(value))
continue;
if (prefixSet != null && prefixSet.contains(prefix.toLowerCase()))
continue;
RefinementSetting setting = websiteConfig.getRefinementSettingByUrlPrefix(prefix);
if (setting == null)
continue;
name = websiteConfig.getRefinementUrlPrefix(setting.getRefinementField());
sb.append(name).append("-").append(UrlUTF8Encoder.encode(value)).append("/");
}
return sb.toString();
}
// todo: figure out & fix
private String generateActionPath(RefinementField field, String value)
{
String path = generateActionPath();
String prefix = websiteConfig.getRefinementUrlPrefix(field);
if (StringUtils.isBlank(prefix))
return path;
if (StringUtils.isNotBlank(path))
path = StringUtils.removeEndIgnoreCase(path, "." + websiteConfig.getDefaultExtension());
if (!path.endsWith("/"))
path = path + "/";
return path + prefix + "-" + UrlUTF8Encoder.encode(value);
}
public String toString()
{
if (urlString == null && searchInput != null)
{
boolean isRoot = true;
StringBuilder sb = new StringBuilder();
sb.append(PageUrlBuilder.getPage(PageUrlAlias.ReplaySearch));
// deal with filter
if (searchInput.getSearchFilters() != null && searchInput.getSearchFilters().size() > 0)
{
for (SearchFilter filter : searchInput.getSearchFilters())
{
String path = getSearchFilterPath(filter.getRefinementField(), convertListToString(filter.getValues()));
if (StringUtils.isBlank(path))
continue;
sb.append(path).append("/");
}
isRoot = false;
}
if (isRoot)
{
sb.append("index." + websiteConfig.getDefaultExtension());
} else
{
sb = new StringBuilder(StringUtils.removeEnd(sb.toString(), "/")).append(".").append(websiteConfig.getDefaultExtension());
}
// deal with query string parameter, in specific order. hmm, maybe needs revision
copyQueryStringParameter(sb, QueryStringManager.Param_Search);
copyQueryStringParameter(sb, QueryStringManager.Param_Page);
copyQueryStringParameter(sb, QueryStringManager.Param_PageSize);
copyQueryStringParameter(sb, QueryStringManager.Param_ShowAllFor);
urlString = sb.toString();
}
return urlString;
}
private StringBuilder copyQueryStringParameter(StringBuilder sb, String param)
{
if (queryStringMap != null && queryStringMap.containsKey(param))
{
if (sb.toString().endsWith("." + websiteConfig.getDefaultExtension()))
sb.append("?");
else
sb.append("&");
sb.append(param).append("=").append(UrlUTF8Encoder.encode(queryStringMap.get(param)));
}
return sb;
}
private static String getSearchFilterPath(RefinementField field, String value)
{
String prefix = websiteConfig.getRefinementUrlPrefix(field);
if (StringUtils.isBlank(prefix))
{
return null;
}
return prefix + "-" + UrlUTF8Encoder.encode(value);
}
}
|
samuelpordeus/ruby_detective
|
lib/ruby_detective/ui_generator.rb
|
require "erb"
module RubyDetective
class UIGenerator
def self.generate
# Variable used inside the template
classes_data_as_json = JSONBuilder.build
template_path = File.join(File.dirname(__FILE__), "../../views/template.html.erb")
erb_template = File.read(template_path)
ui_source_code = ERB.new(erb_template).result(binding)
output_file_path = 'ruby_detective.html'
File.delete(output_file_path) if File.exist?(output_file_path)
File.open(output_file_path, 'w') { |file| file << ui_source_code }
end
end
end
|
devon-ye/demos-parent
|
language/java/src/main/java/org/devon/clazz/reflect/ClassDemo02.java
|
package org.devon.clazz.reflect;
public class ClassDemo02 {
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
Class c1 = int.class;
Class c2 = String.class;
Class c3 = Double.class;
Class c4 = double.class;
Class c5 = void.class;
Class c6 = args.getClass();
System.out.println("c1=" + c1 + " c2=" + c2 + " c3=" + c3 + " c4=" + c4 + " c5=" + c5 + " c6=" + c6);
}
}
|
litecoin-foundation/forkmonitor
|
db/migrate/20190126162003_create_lags.rb
|
<reponame>litecoin-foundation/forkmonitor
# frozen_string_literal: true
class CreateLags < ActiveRecord::Migration[5.2]
def change
create_table :lags do |t|
t.references :node_a, references: :node, index: true
t.references :node_b, references: :node, index: true
t.timestamps
end
end
end
|
shakilakhtar/designpatterns
|
src/com/mycomp/dp/visitor/ex1/VisitorDemo.java
|
package com.mycomp.dp.visitor.ex1;
public class VisitorDemo {
static public void main(String[] args) {
Car car = new Car();
car.accept(new CarElementPrintVisitor());
car.accept(new CarElementDoVisitor());
}
}
|
hyanwong/eol
|
db/migrate/20130122175125_create_crop_activity.rb
|
<filename>db/migrate/20130122175125_create_crop_activity.rb
class CreateCropActivity < ActiveRecord::Migration
def self.up
Activity.find_or_create('crop')
end
def self.down
# Nothing to do.
end
end
|
Pratham82/Java-Programming
|
Day16/Multiplication.java
|
<reponame>Pratham82/Java-Programming
package Day16;
public class Multiplication {
public void Multi2Int(int A, int B){
System.out.println("Multiplication of two numbers: "+(A*B));
}
public void Multi2Float(float A, float B){
System.out.println("Multiplication of two floats: "+(A*B));
}
}
|
Tomius/oglwrap
|
shader_source.h
|
<filename>shader_source.h
// Copyright (c) <NAME>
/** @file shader_source.h
@brief Implements GLSL shader source loading and manipulating facilities.
*/
#ifndef OGLWRAP_SHADER_SOURCE_H_
#define OGLWRAP_SHADER_SOURCE_H_
#include <string>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include "./config.h"
#include "./define_internal_macros.h"
namespace OGLWRAP_NAMESPACE_NAME {
/**
* @brief A class that can load shader sources in from files, and do some
* preprocessing on them.
*/
class ShaderSource {
std::string src_, filename_;
public:
/// Default constructor.
ShaderSource() : filename_("Unnamed shader") { }
/// Loads in the shader from a file.
/** @param file - The path to the file. */
explicit ShaderSource(const std::string& file) {
loadFromFile(file);
}
/// Returns the source.
std::string const& source() const { return src_; }
/// Returns the source.
std::string& source() { return src_; }
/// Adds a string as the shader source.
/** @param source_string - The source string. */
void set_source(const std::string& source_string) {
src_ = source_string;
}
/// Loads in the shader from a file.
/** @param file - The path to the file. */
void loadFromFile(const std::string& file) {
filename_ = file;
std::ifstream shader_file((OGLWRAP_DEFAULT_SHADER_PATH + file).c_str());
if (!shader_file.is_open()) {
throw std::runtime_error("Shader file '" +
(OGLWRAP_DEFAULT_SHADER_PATH + file) + "' not found.");
}
std::stringstream shader_string;
shader_string << shader_file.rdbuf();
// Remove the EOF from the end of the string.
src_ = shader_string.str();
if (src_[src_.length() - 1] == EOF) {
src_.pop_back();
}
}
/// Returns the file's name that was loaded in.
const std::string& source_file() const { return filename_; }
void set_source_file(const std::string& file) {
filename_ = file;
}
template<typename T>
/// Inserts a value for a defined preprocessor in the shader.
/** @param macro_name - The name of the macro.
* @param value - The value to insert. */
void insertMacroValue(const std::string& macro_name, const T& value) {
size_t macro_pos = src_.find("#define " + macro_name);
#if OGLWRAP_DEBUG
if (macro_pos == std::string::npos) {
throw std::invalid_argument(
"ShaderSource::insert_macro_value is called for '" + filename_ +
"', but the shader doesn't have any macro named " + macro_name);
}
#endif
size_t macro_end = src_.find('\n', macro_pos);
std::stringstream sstream;
sstream << src_.substr(0, macro_pos+strlen("#define ")+macro_name.length());
sstream << ' ' << value << src_.substr(macro_end);
src_ = sstream.str();
}
};
} // namespace oglwrap
#include "./undefine_internal_macros.h"
#endif // OGLWRAP_SHADER_SOURCE_H_
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.