repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
Albocoder/KOOBE
|
s2e/source/s2e-linux-kernel/decree-cgc-cfe/drivers/staging/fsl_pme2/pme2_low.c
|
<gh_stars>10-100
/* Copyright 2008-2011 Freescale Semiconductor, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Freescale Semiconductor nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
*
* ALTERNATIVELY, this software may be distributed under the terms of the
* GNU General Public License ("GPL") as published by the Free Software
* Foundation, either version 2 of that License or (at your option) any
* later version.
*
* THIS SOFTWARE IS PROVIDED BY Freescale Semiconductor ``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 Freescale Semiconductor BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "pme2_private.h"
MODULE_AUTHOR("<NAME>");
MODULE_LICENSE("Dual BSD/GPL");
MODULE_DESCRIPTION("FSL PME2 (p4080) device usage");
#define PME_RESIDUE_SIZE 128
#define PME_RESIDUE_ALIGN 64
#define PME_FLOW_SIZE sizeof(struct pme_flow)
#define PME_FLOW_ALIGN 32
static struct kmem_cache *slab_residue;
static struct kmem_cache *slab_flow;
static struct kmem_cache *slab_fq;
/* Hack to support "pme_map()". The point of this is that dma_map_single() now
* requires a non-NULL device, so the idea is that address mapping must be
* device-sensitive. Now the PAMU IO-MMU already takes care of this, as can be
* seen by the device-tree structure generated by the hypervisor (each portal
* node has sub-nodes for each h/w end-point it provides access to, and each
* sub-node has its own LIODN configuration). So we just need to map cpu
* pointers to (guest-)physical address and the PAMU takes care of the rest, so
* this doesn't need to be portal-sensitive nor device-sensitive. */
static struct platform_device *pdev;
static int pme2_low_init(void)
{
int ret = -ENOMEM;
slab_residue = kmem_cache_create("pme2_residue", PME_RESIDUE_SIZE,
PME_RESIDUE_ALIGN, SLAB_HWCACHE_ALIGN, NULL);
if (!slab_residue)
goto end;
slab_flow = kmem_cache_create("pme2_flow", PME_FLOW_SIZE,
PME_FLOW_ALIGN, 0, NULL);
if (!slab_flow)
goto end;
slab_fq = kmem_cache_create("pme2_fqslab", sizeof(struct qman_fq),
__alignof__(struct qman_fq), SLAB_HWCACHE_ALIGN, NULL);
if (!slab_fq)
goto end;
ret = -ENODEV;
pdev = platform_device_alloc("pme", -1);
if (!pdev)
goto end;
if (dma_set_mask(&pdev->dev, DMA_BIT_MASK(40)))
goto end;
if (platform_device_add(pdev))
goto end;
return 0;
end:
if (pdev) {
platform_device_put(pdev);
pdev = NULL;
}
if (slab_flow) {
kmem_cache_destroy(slab_flow);
slab_flow = NULL;
}
if (slab_residue) {
kmem_cache_destroy(slab_residue);
slab_residue = NULL;
}
if (slab_fq) {
kmem_cache_destroy(slab_fq);
slab_fq = NULL;
}
return ret;
}
static void pme2_low_exit(void)
{
platform_device_del(pdev);
platform_device_put(pdev);
pdev = NULL;
kmem_cache_destroy(slab_fq);
kmem_cache_destroy(slab_flow);
kmem_cache_destroy(slab_residue);
slab_fq = slab_flow = slab_residue = NULL;
}
module_init(pme2_low_init);
module_exit(pme2_low_exit);
struct qman_fq *slabfq_alloc(void)
{
return kmem_cache_alloc(slab_fq, GFP_KERNEL);
}
void slabfq_free(struct qman_fq *fq)
{
kmem_cache_free(slab_fq, fq);
}
/***********************/
/* low-level functions */
/***********************/
struct pme_hw_residue *pme_hw_residue_new(void)
{
return kmem_cache_alloc(slab_residue, GFP_KERNEL);
}
EXPORT_SYMBOL(pme_hw_residue_new);
void pme_hw_residue_free(struct pme_hw_residue *p)
{
kmem_cache_free(slab_residue, p);
}
EXPORT_SYMBOL(pme_hw_residue_free);
struct pme_hw_flow *pme_hw_flow_new(void)
{
struct pme_flow *flow = kmem_cache_zalloc(slab_flow, GFP_KERNEL);
return (struct pme_hw_flow *)flow;
}
EXPORT_SYMBOL(pme_hw_flow_new);
void pme_hw_flow_free(struct pme_hw_flow *p)
{
kmem_cache_free(slab_flow, p);
}
EXPORT_SYMBOL(pme_hw_flow_free);
static const struct pme_flow default_sw_flow = {
.sos = 1,
.srvm = 0,
.esee = 1,
.ren = 0,
.rlen = 0,
.seqnum_hi = 0,
.seqnum_lo = 0,
.sessionid = 0x7ffffff,
.rptr_hi = 0,
.rptr_lo = 0,
.clim = 0xffff,
.mlim = 0xffff
};
void pme_sw_flow_init(struct pme_flow *flow)
{
memcpy(flow, &default_sw_flow, sizeof(*flow));
}
EXPORT_SYMBOL(pme_sw_flow_init);
void pme_initfq(struct qm_mcc_initfq *initfq, struct pme_hw_flow *flow, u8 qos,
u8 rbpid, u32 rfqid)
{
struct pme_context_a *pme_a =
(struct pme_context_a *)&initfq->fqd.context_a;
struct pme_context_b *pme_b =
(struct pme_context_b *)&initfq->fqd.context_b;
initfq->we_mask = QM_INITFQ_WE_DESTWQ | QM_INITFQ_WE_CONTEXTA |
QM_INITFQ_WE_CONTEXTB;
initfq->fqd.dest.channel = qm_channel_pme;
initfq->fqd.dest.wq = qos;
if (flow) {
dma_addr_t fcp = flow_map((struct pme_flow *)flow);
pme_a->mode = pme_mode_flow;
pme_context_a_set64(pme_a, fcp);
} else {
pme_a->mode = pme_mode_direct;
pme_context_a_set64(pme_a, 0);
}
pme_b->rbpid = rbpid;
pme_b->rfqid = rfqid;
}
EXPORT_SYMBOL(pme_initfq);
void pme_fd_cmd_nop(struct qm_fd *fd)
{
struct pme_cmd_nop *nop = (struct pme_cmd_nop *)&fd->cmd;
nop->cmd = pme_cmd_nop;
}
EXPORT_SYMBOL(pme_fd_cmd_nop);
void pme_fd_cmd_fcw(struct qm_fd *fd, u8 flags, struct pme_flow *flow,
struct pme_hw_residue *residue)
{
dma_addr_t f;
struct pme_cmd_flow_write *fcw = (struct pme_cmd_flow_write *)&fd->cmd;
BUG_ON(!flow);
BUG_ON((unsigned long)flow & 31);
fcw->cmd = pme_cmd_flow_write;
fcw->flags = flags;
if (flags & PME_CMD_FCW_RES) {
if (residue) {
dma_addr_t rptr = residue_map(residue);
BUG_ON(!residue);
BUG_ON((unsigned long)residue & 63);
pme_flow_rptr_set64(flow, rptr);
} else
pme_flow_rptr_set64(flow, 0);
}
f = flow_map(flow);
qm_fd_addr_set64(fd, f);
fd->format = qm_fd_contig;
fd->offset = 0;
fd->length20 = sizeof(*flow);
}
EXPORT_SYMBOL(pme_fd_cmd_fcw);
void pme_fd_cmd_fcr(struct qm_fd *fd, struct pme_flow *flow)
{
dma_addr_t f;
struct pme_cmd_flow_read *fcr = (struct pme_cmd_flow_read *)&fd->cmd;
BUG_ON(!flow);
BUG_ON((unsigned long)flow & 31);
fcr->cmd = pme_cmd_flow_read;
f = flow_map(flow);
qm_fd_addr_set64(fd, f);
fd->format = qm_fd_contig;
fd->offset = 0;
fd->length20 = sizeof(*flow);
}
EXPORT_SYMBOL(pme_fd_cmd_fcr);
void pme_fd_cmd_pmtcc(struct qm_fd *fd)
{
struct pme_cmd_pmtcc *pmtcc = (struct pme_cmd_pmtcc *)&fd->cmd;
pmtcc->cmd = pme_cmd_pmtcc;
}
EXPORT_SYMBOL(pme_fd_cmd_pmtcc);
void pme_fd_cmd_scan(struct qm_fd *fd, u32 args)
{
struct pme_cmd_scan *scan = (struct pme_cmd_scan *)&fd->cmd;
fd->cmd = args;
scan->cmd = pme_cmd_scan;
}
EXPORT_SYMBOL(pme_fd_cmd_scan);
dma_addr_t pme_map(void *ptr)
{
return dma_map_single(&pdev->dev, ptr, 1, DMA_BIDIRECTIONAL);
}
EXPORT_SYMBOL(pme_map);
int pme_map_error(dma_addr_t dma_addr)
{
return dma_mapping_error(&pdev->dev, dma_addr);
}
EXPORT_SYMBOL(pme_map_error);
|
mass-project/mass_server
|
mass_flask_api/resources/auth.py
|
<reponame>mass-project/mass_server<filename>mass_flask_api/resources/auth.py
# from flask import request, jsonify
# from mass_flask_api.config import api_blueprint
# from mass_flask_core.models import User, UserAPIKey
#
#
# def request_auth_token():
# """
# ---
# post:
# description: Request an auth token for the given user credentials.
# parameters:
# - in: body
# name: body
# type: string
# responses:
# 200:
# description: The auth token is returned.
# 400:
# description: Invalid credentials given or the request is malformed.
# """
# json_data = request.get_json()
# if not json_data:
# return jsonify({'error': 'No JSON data provided. Make sure to set the content type of your request to: application/json'}), 400
# else:
# username = json_data.get('username')
# password = <PASSWORD>('password')
# user = User.objects(username=username).first()
# if not user:
# u = User(username=username, password=password)
# u.save()
# return jsonify({'error': 'Invalid credentials.'}), 400
# else:
# api_key = UserAPIKey.get_or_create(user)
# return jsonify({'api_key': api_key.generate_auth_token()}), 200
#
# api_blueprint.add_url_rule('/auth/request_auth_token/', view_func=request_auth_token, methods=['POST'])
# api_blueprint.apispec.add_path(path='/auth/request_auth_token/', view=request_auth_token)
|
RenanRibeiroDaSilva/Meu-Aprendizado-Python
|
Exercicios/Ex105.py
|
<reponame>RenanRibeiroDaSilva/Meu-Aprendizado-Python
""" Ex - 105 - Faça um programa que tenha uma função notas() que pode receber várias notas de alunos e vai
retornar um dicionário com as seguintes informações:
– Quantidade de notas
– A maior nota
– A menor nota
– A média da turma
– A situação (opcional)
"""
# Como eu fiz.
# Função:
def notasR(nota, ok=False):
"""
-> Função para analisar notas e situações de vários alunos
:param nota: uma lista de notas
:param ok: valor opcional, indicando deve ou não adicionar a situação.
:return: dicionário com várias informações da turma.
"""
notas = {}
cont = maior = menor = soma = media = 0
for n in range(0, len(nota)):
cont += 1
notas['qtdNotas'] = cont
for m in nota:
if m == 0 or maior < m:
maior = m
notas['maiNota'] = maior
cont = 0
for m in nota:
cont += 1
if cont == 1 or menor > m:
menor = m
notas['menNota'] = menor
for m in nota:
soma += m
notas['medNota'] = soma / len(nota)
media = soma / len(nota)
if ok:
if media >= 7:
notas['situação'] = 'APROVADO'
elif media >= 5:
notas['situação'] = 'de RECUPERAÇÃO'
elif media <= 4:
notas['situação'] = 'REPROVADO'
return notas
# Programa principal:
notLis = []
mosLis = []
while True:
print('-=' * 50)
n = float(input('Qual a nota do aluno: '))
notLis.append(n)
while True:
res = str(input('Quer adicionar mais uma nota? [S/N] ')).strip().upper()[0]
if res in 'SN':
break
print('\033[0;31mErro! Resposta inválida\033[m')
if res in 'N':
break
while True:
print('-=' * 50)
res = str(input('Quer ver a situação do aluno? [S/N] ')).strip().upper()[0]
if res in 'SN':
break
print('\033[0;31mErro! Resposta inválida\033[m')
if res in 'S':
mosLis.append(notasR(notLis, ok=True))
else:
mosLis.append(notasR(notLis))
print('-=' * 50)
print(f'Foram adicionadas {mosLis[0]["qtdNotas"]} notas.')
print(f'A maior nota do aluno foi {mosLis[0]["maiNota"]}.')
print(f'A menor nota do aluno foi {mosLis[0]["menNota"]}.')
print(f'A media foi {mosLis[0]["medNota"]:.1f}.')
if res in 'S':
print(f'E o aluno está {mosLis[0]["situação"]}.')
print('-=' * 50)
# Como o Guanabara fez.
def notas(*n, sit=False):
"""
-> Função para analisar notas e situações de vários alunos
:param n: uma ou mais notas dos alunos (aceita várias)
:param sit: valor opcional, indicando deve ou não adicionar a situação.
:return: dicionário com várias informações da turma.
"""
r = dict()
r['total'] = len(n)
r['maior'] = max(n)
r['menor'] = min(n)
r['média'] = sum(n)/len(n)
if sit:
if r['média'] >= 7:
r['situação'] = 'BOA'
elif r['média'] >= 5:
r['situação'] = 'RAZOÁVEL'
else:
r['situação'] = 'RUIM'
return r
# Programa principal
resp = notas(5.5, 2.5, 1.5, sit=True)
print(resp)
help(notas())
|
f4deb/cen-electronic
|
drivers/driverList.h
|
#ifndef DRIVER_LIST_H
#define DRIVER_LIST_H
#include "driver.h"
#include "../common/io/buffer.h"
#include "../common/io/inputStream.h"
#include "../common/io/outputStream.h"
/** The max limit of driver list. */
#define MAX_DRIVER 3
/**
* The struct defining a list of drivers.
*/
typedef struct {
/** An array of pointer on driver Descriptor. */
DriverDescriptor* drivers[MAX_DRIVER];
/** the size of the list. */
unsigned char size;
} DriverDescriptorList;
/**
* Add a driver Descriptor to the list.
* @param driverDescriptor the driver descriptor to add
*/
void addDriver(DriverDescriptor* driverDescriptor, TransmitMode transmitMode);
/**
* Get the driver descriptor of index.
* @param index the index in the array of descriptors
* @return the descriptor at the specified index
*/
DriverDescriptor* getDriver(int index);
/**
* Get the count of driver.
* @return the count of driver
*/
int getDriverCount();
/**
* Init the driver descriptor list.
*/
void initDrivers(Buffer *driverRequestBuffer, unsigned char (*driverRequestBufferArray)[], unsigned int requestLength,
Buffer *driverResponseBuffer, unsigned char (*driverResponseBufferArray)[], unsigned int responseLength);
/**
* Get an OutputStream to write argument and parameters
* for the driver.
*/
OutputStream* getDriverRequestOutputStream();
/**
* Get a InputStream for driver corresponding to the
* result.
*/
InputStream* getDriverResponseInputStream();
/**
* Get the buffer corresponding to the input of the driver.
*/
Buffer* getDriverRequestBuffer();
/**
* Get the buffer corresponding to the output of the driver.
*/
Buffer* getDriverResponseBuffer();
#endif
|
LDZZDL/CommercialCity
|
src/com/fjsf/web/viewobject/CustomerOrderView.java
|
package com.fjsf.web.viewobject;
import java.util.Date;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fjsf.web.bean.DeliveryAddressBean;
import com.fjsf.web.bean.ProductBean;
import com.fjsf.web.bean.ShopBean;
public class CustomerOrderView {
// 订单编号
private Integer orderId;
// 下单时间
@JsonFormat(pattern = "yyyy年MM月dd日 HH时mm分")
private Date orderMasterTime;
// 订单状态
private String orderMasterStatus;
// 产品信息
private List<ProductBean> listProductBean;
// 产品数量
private List<Integer> listQuantity;
// 商店信息
private ShopBean shopBean;
// 收货地址
private DeliveryAddressBean deliveryAddressBean;
public Integer getOrderId() {
return orderId;
}
public void setOrderId(Integer orderId) {
this.orderId = orderId;
}
public Date getOrderMasterTime() {
return orderMasterTime;
}
public void setOrderMasterTime(Date orderMasterTime) {
this.orderMasterTime = orderMasterTime;
}
public String getOrderMasterStatus() {
return orderMasterStatus;
}
public void setOrderMasterStatus(String orderMasterStatus) {
this.orderMasterStatus = orderMasterStatus;
}
public List<ProductBean> getListProductBean() {
return listProductBean;
}
public void setListProductBean(List<ProductBean> listProductBean) {
this.listProductBean = listProductBean;
}
public List<Integer> getListQuantity() {
return listQuantity;
}
public void setListQuantity(List<Integer> listQuantity) {
this.listQuantity = listQuantity;
}
public ShopBean getShopBean() {
return shopBean;
}
public void setShopBean(ShopBean shopBean) {
this.shopBean = shopBean;
}
public DeliveryAddressBean getDeliveryAddressBean() {
return deliveryAddressBean;
}
public void setDeliveryAddressBean(DeliveryAddressBean deliveryAddressBean) {
this.deliveryAddressBean = deliveryAddressBean;
}
public CustomerOrderView(Integer orderId, Date orderMasterTime, String orderMasterStatus,
List<ProductBean> listProductBean, List<Integer> listQuantity, ShopBean shopBean,
DeliveryAddressBean deliveryAddressBean) {
super();
this.orderId = orderId;
this.orderMasterTime = orderMasterTime;
this.orderMasterStatus = orderMasterStatus;
this.listProductBean = listProductBean;
this.listQuantity = listQuantity;
this.shopBean = shopBean;
this.deliveryAddressBean = deliveryAddressBean;
}
public CustomerOrderView() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "CustomerOrderView [orderId=" + orderId + ", orderMasterTime=" + orderMasterTime + ", orderMasterStatus="
+ orderMasterStatus + ", listProductBean=" + listProductBean + ", listQuantity=" + listQuantity
+ ", shopBean=" + shopBean + ", deliveryAddressBean=" + deliveryAddressBean + "]";
}
}
|
yyh1102/Teaching-Assistance-Application
|
frontend/vuex/modules/group/index.js
|
import Vue from 'vue';
import * as actions from './actions';
const state={
actionLoading:false, //表单提交loading
showGroup:false, //小组操作表单显示状态
groupList:[],
}
const mutations= {
updateGroupList(state,groupList){
state.groupList=groupList;
},
showActionGroup(state,signal){
state.showGroup = signal;
},
actionLoading(state,signal){
state.actionLoading=signal;
},
addGroup(state, newGroup){
state.groupList.push(newGroup);
},
deleteGroup(state,groupId){
state.groupList.forEach((item,index)=>{
if(item.group_id==groupId){
state.groupList.splice(index,1);
return;
}
})
}
};
export default {
state,
actions,
mutations
}
|
alinakazi/apache-royale-0.9.8-bin-js-swf
|
royale-compiler/compiler/src/main/java/org/apache/royale/compiler/internal/projects/ASProject.java
|
<reponame>alinakazi/apache-royale-0.9.8-bin-js-swf<filename>royale-compiler/compiler/src/main/java/org/apache/royale/compiler/internal/projects/ASProject.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.royale.compiler.internal.projects;
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.royale.compiler.asdoc.IASDocBundleDelegate;
import org.apache.royale.compiler.common.IFileSpecificationGetter;
import org.apache.royale.compiler.definitions.IDefinition;
import org.apache.royale.compiler.internal.projects.SourcePathManager.QNameFile;
import org.apache.royale.compiler.internal.units.CompilationUnitBase;
import org.apache.royale.compiler.internal.units.InvisibleCompilationUnit;
import org.apache.royale.compiler.internal.units.SourceCompilationUnitFactory;
import org.apache.royale.compiler.internal.workspaces.Workspace;
import org.apache.royale.compiler.problems.ICompilerProblem;
import org.apache.royale.compiler.projects.IASProject;
import org.apache.royale.compiler.units.ICompilationUnit;
import org.apache.royale.compiler.units.IInvisibleCompilationUnit;
import org.apache.royale.swc.ISWC;
import org.apache.royale.swc.ISWCFileEntry;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
/**
* Implementation base class to implement functionality common to all
* IASProject implementations. DefinitionPromises ( aka
* "provisional definitions" ) are added to the project scope in this class.
*/
public abstract class ASProject extends CompilerProject implements IASProject
{
/**
* Constructor
*
* @param workspace The Workspace in which this project lives.
* @param useAS3 Indicate whether or not the AS3 namespace should
* be opened in all compilation units in the project.
*/
public ASProject(Workspace workspace, boolean useAS3)
{
this(workspace, useAS3, IASDocBundleDelegate.NIL_DELEGATE);
}
public ASProject(Workspace workspace, boolean useAS3, IASDocBundleDelegate asDocBundleDelegate)
{
super(workspace, useAS3);
sourcePathManager = new SourcePathManager(this);
sourceListManager = new SourceListManager(this, sourcePathManager);
sourceCompilationUnitFactory = new SourceCompilationUnitFactory(this);
sourceCompilationUnitFactory.addHandler(ASSourceFileHandler.INSTANCE);
sourceCompilationUnitFactory.addHandler(FXGSourceFileHandler.INSTANCE);
libraryPathManager = new LibraryPathManager(this);
projectDependencies = new HashMap<IASProject, String>();
dependingProjects = new HashSet<IASProject>();
this.asDocBundleDelegate = asDocBundleDelegate;
}
private final SourceListManager sourceListManager;
private final SourcePathManager sourcePathManager;
private final SourceCompilationUnitFactory sourceCompilationUnitFactory;
private final LibraryPathManager libraryPathManager;
private final Map<IASProject, String> projectDependencies;
private final Set<IASProject> dependingProjects;
private final IASDocBundleDelegate asDocBundleDelegate;
private int compatibilityVersionMajor;
private int compatibilityVersionMinor;
private int compatibilityVersionRevision;
@Override
public List<ISWC> getLibraries()
{
final ImmutableList<ISWC> result = new ImmutableList.Builder<ISWC>()
.addAll(libraryPathManager.getLibrarySWCs())
.build();
return result;
}
@Override
public void attachInternalLibrarySourcePath(File library, File sourceDir)
{
libraryPathManager.setLibrarySourcePath(library, sourceDir);
}
@Override
public void attachExternalLibrarySourcePath(File library, File sourceDir)
{
// TODO: rename this and attachInternalLibraySourcePath to be
// just attachLibrarySourcePath.
libraryPathManager.setLibrarySourcePath(library, sourceDir);
}
@Override
public String getAttachedSourceDirectory(String libraryFilename)
{
String result = libraryPathManager.getAttachedSourceDirectory(libraryFilename);
return result;
}
@Override
public void setSourcePath(List<File> paths)
{
sourcePathManager.setSourcePath(paths.toArray(new File[paths.size()]));
}
@Override
public List<File> getSourcePath()
{
return sourcePathManager.getSourcePath();
}
/**
* Adds a file to the project if that file is on the project's
* source path.
* @param f The file to be added.
* @return true if any new {@link ICompilationUnit}'s were created
* as a result of this operation, false otherwise.
*/
public boolean addSourcePathFile(File f)
{
return sourcePathManager.addFile(f);
}
/**
* Test if a file is on the source path or not.
*
* @param f The file to test. May not be null.
* @return true if the file is on the source path, false otherwise.
*/
public boolean isFileOnSourcePath(File f)
{
return sourcePathManager.isFileOnSourcePath(f);
}
@Override
public void setIncludeSources(File files[]) throws InterruptedException
{
sourceListManager.setSourceList(files);
}
@Override
public void addIncludeSourceFile(File file) throws InterruptedException
{
addIncludeSourceFile(file, false);
}
@Override
public void addIncludeSourceFile(File file, boolean overrideSourcePath) throws InterruptedException
{
sourceListManager.addSource(file, overrideSourcePath);
}
@Override
public void removeIncludeSourceFile(File file) throws InterruptedException
{
sourceListManager.removeSource(file);
}
/**
* Removes a source file to the project, removing any references in the various
* managers - SourcePathManager, SourceListManager etc
*
* @see #addIncludeSourceFile(File)
* @param f File to remove.
*/
public void removeSourceFile(File f)
{
try
{
// TODO: this is mostly a place holder for now. Need
// to go through and cleanup the whole removal flow
// note that the assumption is that these functions
// will fail gracefully if the file is not included
// in the various managers
// remove any reference to this file in the
// source list manager
sourceListManager.removeSource(f);
// remove any reference to this file in the
// source path manager
sourcePathManager.removeFile(f);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public SourceCompilationUnitFactory getSourceCompilationUnitFactory()
{
return sourceCompilationUnitFactory;
}
/**
* Called by {@link SourcePathManager} or {@link LibraryPathManager} when the source
* or library path change.
* @param toRemove {@link ICompilationUnit}'s to remove from the project.
* @param toAdd {@link ICompilationUnit}'s to add to the project.
*/
void updateCompilationUnitsForPathChange(Collection<ICompilationUnit> toRemove, Collection<ICompilationUnit> toAdd)
{
assert toRemove != null;
assert toAdd != null;
removeCompilationUnits(toRemove);
addCompilationUnits(toAdd);
for (ICompilationUnit unit : toAdd)
{
for (IDefinition definitionPromise : unit.getDefinitionPromises())
{
getScope().addDefinition(definitionPromise);
}
}
}
@Override
public Set<IASProject> getDependingProjects()
{
return dependingProjects;
}
@Override
public void addProjectDependeny(IASProject project, String swcFilename)
{
assert (project instanceof ASProject) : "project dependency must be of type ASProject";
((ASProject)project).dependingProjects.add(this);
projectDependencies.put(project, swcFilename);
}
@Override
public void removeProjectDependeny(IASProject project)
{
assert (project instanceof ASProject) : "project dependency must be of type ASProject";
((ASProject)project).dependingProjects.remove(this);
projectDependencies.remove(project);
}
@Override
public void setDependencies(Map<IASProject, String> newIProjectsDependencies)
{
Set<IASProject> newProjectDependencies = ImmutableSet.<IASProject> copyOf(newIProjectsDependencies.keySet());
Set<IASProject> dependenciesToRemove = ImmutableSet.<IASProject> copyOf(Sets.difference(projectDependencies.keySet(), newProjectDependencies));
Set<IASProject> dependenciesToAdd = ImmutableSet.<IASProject> copyOf(Sets.difference(newProjectDependencies, projectDependencies.keySet()));
for (IASProject projectDependency : dependenciesToRemove)
{
removeProjectDependeny(projectDependency);
}
for (IASProject projectDependency : dependenciesToAdd)
{
String swcFilename = newIProjectsDependencies.get(projectDependency);
addProjectDependeny(projectDependency, swcFilename);
}
}
/**
* Called by {@link SourceListManager} when the include sources list is changed.
* @param toRemove {@link ICompilationUnit}'s to remove from the project.
* @param toAdd {@link ICompilationUnit}'s to add to the project.
*/
void sourceListChange(Collection<ICompilationUnit> toRemove, Collection<ICompilationUnit> toAdd) throws InterruptedException
{
// passing empty lists to removeCompilationUnits
// and addCompilationUnitsAndUpdateDefinitions *is* harmless
// but avoiding the call to sourcePathManager.sourceListChanged
// will prevent us from enumerating a bunch of directories on disk
if ((!toRemove.isEmpty()) || (!toAdd.isEmpty()))
{
removeCompilationUnits(toRemove);
addCompilationUnitsAndUpdateDefinitions(toAdd);
}
}
@Override
public void collectProblems(Collection<ICompilerProblem> problems)
{
sourcePathManager.collectProblems(problems);
sourceListManager.collectProblems(problems);
libraryPathManager.collectProblems(problems);
collectConfigProblems(problems);
}
/**
* Finds all the {@link ICompilationUnit}'s in this project whose root source file is the specified file.
*/
public void collectionCompilationUnitsForRootSourceFile(File rootSourceFile, Collection<ICompilationUnit> units)
{
sourcePathManager.collectionCompilationUnitsForRootSourceFile(rootSourceFile, units);
sourceListManager.collectionCompilationUnitsForRootSourceFile(rootSourceFile, units);
}
public boolean hasCompilationUnitForRootSourceFile(File rootSourceFile)
{
return sourcePathManager.hasCompilationUnitsForRootSourceFile(rootSourceFile) ||
sourceListManager.hasCompilationUnitsForRootSourceFile(rootSourceFile);
}
@Override
public boolean invalidateLibraries(Collection<File> swcFiles)
{
return libraryPathManager.invalidate(swcFiles);
}
@Override
public void invalidateLibrary(ISWC swc)
{
libraryPathManager.invalidate(swc);
}
@Override
public boolean handleAddedFile(File addedFile)
{
return addSourcePathFile(addedFile);
}
@Override
public String getSourceFileFromSourcePath(String file)
{
return sourcePathManager.getSourceFileFromSourcePath(file);
}
/**
* Iterate through the library path list looking for the specified file.
* @param file to look for
* @return ISWCFileEntry to the file, or null if file not found
*/
public ISWCFileEntry getSourceFileFromLibraryPath(String file)
{
return libraryPathManager.getFileEntryFromLibraryPath(file);
}
public IASDocBundleDelegate getASDocBundleDelegate()
{
return asDocBundleDelegate;
}
@Override
public void setLibraries(List<File> libraries)
{
assert libraries != null : "Libraries may not be null";
libraryPathManager.setLibraryPath(libraries.toArray(new File[libraries.size()]));
}
/**
* Sets the SDK compatibility version. For this release, the only valid value is 2.0.1.
*
* @param major The major version. For this release, this value must be 2.
* @param minor The minor version. For this release, this value must be 0.
* @param revision For this release, this value must be 1.
*/
public void setCompatibilityVersion(int major, int minor, int revision)
{
compatibilityVersionMajor = major;
compatibilityVersionMinor = minor;
compatibilityVersionRevision = revision;
clean();
}
@Override
public Integer getCompatibilityVersion()
{
int compatibilityVersion = (compatibilityVersionMajor << 24) + (compatibilityVersionMinor << 16) +
compatibilityVersionRevision;
return compatibilityVersion != 0 ? compatibilityVersion : null;
}
@Override
public String getCompatibilityVersionString()
{
int sum = compatibilityVersionMajor + compatibilityVersionMinor + compatibilityVersionRevision;
if (sum == 0)
return null;
return compatibilityVersionMajor + "." +
compatibilityVersionMinor + "." +
compatibilityVersionRevision;
}
@Override
public IInvisibleCompilationUnit createInvisibleCompilationUnit(String rootSourceFile, IFileSpecificationGetter fileSpecGetter)
{
QNameFile qNameFile = sourcePathManager.computeQNameForFilename(rootSourceFile);
if (qNameFile == null)
return null;
CompilationUnitBase invisibleCUDelegate = createInvisibleCompilationUnit(qNameFile);
if (invisibleCUDelegate == null)
return null;
return new InvisibleCompilationUnit(invisibleCUDelegate, fileSpecGetter);
}
@Override
public IInvisibleCompilationUnit createInvisibleCompilationUnit(String rootSourceFile, IFileSpecificationGetter fileSpecGetter, String qName)
{
QNameFile qNameFile = new QNameFile(qName, new File(rootSourceFile), null, 0);
CompilationUnitBase invisibleCUDelegate = createInvisibleCompilationUnit(qNameFile);
if (invisibleCUDelegate == null)
return null;
return new InvisibleCompilationUnit(invisibleCUDelegate, fileSpecGetter);
}
/**
* Create's a new {@link CompilationUnitBase} that is marked as being a
* delegate for an {@link InvisibleCompilationUnit}.
*
* @param qNameFile The qNameFile of the new {@link InvisibleCompilationUnit}.
* @return A new {@link CompilationUnitBase} that is marked as being a
* delegate for an {@link InvisibleCompilationUnit} or null if the specified
* file name is not on the source path.
*/
private CompilationUnitBase createInvisibleCompilationUnit(QNameFile qNameFile)
{
SourceCompilationUnitFactory compilationUnitFactory = getSourceCompilationUnitFactory();
if (!compilationUnitFactory.canCreateCompilationUnit(qNameFile.file))
return null;
CompilationUnitBase newCU = (CompilationUnitBase)getSourceCompilationUnitFactory().createCompilationUnit(
qNameFile.file, DefinitionPriority.BasePriority.SOURCE_PATH, 0, qNameFile.qName, qNameFile.locale);
assert newCU != null : "canCreateCompilationUnit should have returned false if createCompilationUnit returns null!";
addCompilationUnit(newCU);
return newCU;
}
@Override
public boolean isAssetEmbeddingSupported()
{
return true;
}
@Override
public boolean isSupportedSourceFileType(String fileExtension)
{
return sourceCompilationUnitFactory.canCreateCompilationUnitForFileType(fileExtension);
}
}
|
MTres19/openproject
|
modules/bim/spec/bcf/bcf_xml/issue_writer_spec.rb
|
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2020 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 <NAME>
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
require 'spec_helper'
describe ::OpenProject::Bim::BcfXml::IssueWriter do
let(:project) { FactoryBot.create(:project) }
let(:markup) do
<<-MARKUP
<Markup xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Header>
<File IfcProject="0M6o7Znnv7hxsbWgeu7oQq" IfcSpatialStructureElement="23B$bNeGHFQuMYJzvUX0FD" isExternal="false">
<Filename>IfcPile_01.ifc</Filename>
<Date>2014-10-27T16:27:27Z</Date>
<Reference>../IfcPile_01.ifc</Reference>
</File>
</Header>
<Topic Guid="63E78882-7C6A-4BF7-8982-FC478AFB9C97" TopicType="Structural" TopicStatus="Open">
<ReferenceLink>https://bim--it.net</ReferenceLink>
<Title>Maximum Content</Title>
<Priority>High</Priority>
<Index>0</Index>
<Labels>Structural</Labels>
<Labels>IT Development</Labels>
<CreationDate>2015-06-21T12:00:00Z</CreationDate>
<CreationAuthor><EMAIL></CreationAuthor>
<ModifiedDate>2015-06-21T14:22:47Z</ModifiedDate>
<ModifiedAuthor><EMAIL></ModifiedAuthor>
<AssignedTo><EMAIL></AssignedTo>
<Description>This is a topic with all information present.</Description>
<BimSnippet SnippetType="JSON">
<Reference>JsonElement.json</Reference>
<ReferenceSchema>http://json-schema.org</ReferenceSchema>
</BimSnippet>
<DocumentReference isExternal="true">
<ReferencedDocument>https://github.com/BuildingSMART/BCF-XML</ReferencedDocument>
<Description>GitHub BCF Specification</Description>
</DocumentReference>
<DocumentReference>
<ReferencedDocument>../markup.xsd</ReferencedDocument>
<Description>Markup.xsd Schema</Description>
</DocumentReference>
<RelatedTopic Guid="5019D939-62A4-45D9-B205-FAB602C98FE8" />
</Topic>
<Viewpoints Guid="8dc86298-9737-40b4-a448-98a9e953293a">
<Viewpoint>Viewpoint_8dc86298-9737-40b4-a448-98a9e953293a.bcfv</Viewpoint>
<Snapshot>Snapshot_8dc86298-9737-40b4-a448-98a9e953293a.png</Snapshot>
</Viewpoints>
<Viewpoints Guid="21dd4807-e9af-439e-a980-04d913a6b1ce">
<Viewpoint>Viewpoint_21dd4807-e9af-439e-a980-04d913a6b1ce.bcfv</Viewpoint>
<Snapshot>Snapshot_21dd4807-e9af-439e-a980-04d913a6b1ce.png</Snapshot>
</Viewpoints>
<Viewpoints Guid="81daa431-bf01-4a49-80a2-1ab07c177717">
<Viewpoint>Viewpoint_81daa431-bf01-4a49-80a2-1ab07c177717.bcfv</Viewpoint>
<Snapshot>Snapshot_81daa431-bf01-4a49-80a2-1ab07c177717.png</Snapshot>
</Viewpoints>
</Markup>
MARKUP
end
let(:bcf_issue) do
FactoryBot.create(:bcf_issue_with_comment,
work_package: work_package,
markup: markup)
end
let(:priority) { FactoryBot.create :priority_low }
let(:current_user) { FactoryBot.create(:user) }
let(:due_date) { DateTime.now }
let(:type) { FactoryBot.create :type, name: 'Issue' }
let(:work_package) do
FactoryBot.create(:work_package,
project_id: project.id,
priority: priority,
author: current_user,
assigned_to: current_user,
due_date: due_date,
type: type)
end
before do
allow(User).to receive(:current).and_return current_user
bcf_issue.comments.first.journal.update_attribute('journable_id', work_package.id)
FactoryBot.create(:work_package_journal, notes: "Some note created in OP.", journable_id: work_package.id)
end
shared_examples_for "writes Topic" do
it "updates the Topic node" do
work_package.reload
expect(subject.at('Markup')).to be_present
expect(subject.at('Topic')).to be_present
expect(subject.at('Topic/@Guid').content).to be_eql bcf_issue.uuid
expect(subject.at('Topic/@TopicStatus').content).to be_eql work_package.status.name
expect(subject.at('Topic/@TopicType').content).to be_eql 'Issue'
expect(subject.at('Topic/Title').content).to be_eql work_package.subject
expect(subject.at('Topic/CreationDate').content).to be_eql work_package.created_at.iso8601
expect(subject.at('Topic/ModifiedDate').content).to be_eql work_package.updated_at.iso8601
expect(subject.at('Topic/Description').content).to be_eql work_package.description
expect(subject.at('Topic/CreationAuthor').content).to be_eql work_package.author.mail
expect(subject.at('Topic/ReferenceLink').content).to be_eql url_helpers.work_package_url(work_package)
expect(subject.at('Topic/Priority').content).to be_eql work_package.priority.name
expect(subject.at('Topic/ModifiedAuthor').content).to be_eql work_package.journals.last.user.mail
expect(subject.at('Topic/AssignedTo').content).to be_eql work_package.assigned_to.mail
expect(subject.at('Topic/DueDate').content).to be_eql work_package.due_date.to_datetime.iso8601
end
end
def valid_markup?(doc)
schema = Nokogiri::XML::Schema(File.read(File.join(Rails.root, 'modules/bim/spec/bcf/bcf_xml/markup.xsd')))
errors = schema.validate(doc)
if errors.empty?
true
else
puts errors.map(&:message).join("\n")
false
end
end
shared_examples_for 'valid markup' do
it 'produces valid markup' do
expect(valid_markup? subject).to be_truthy
end
end
context 'no markup present yet' do
let(:markup) { nil }
subject { Nokogiri::XML(described_class.update_from!(work_package).markup) }
it_behaves_like 'writes Topic'
it_behaves_like 'valid markup'
end
context 'markup already present' do
subject { Nokogiri::XML(described_class.update_from!(work_package).markup) }
it_behaves_like 'writes Topic'
it_behaves_like 'valid markup'
it "maintains existing nodes and attributes untouched" do
expect(subject.at('Index').content).to be_eql "0"
expect(subject.at('BimSnippet')['SnippetType']).to be_eql "JSON"
end
it 'it exports all BCF comments' do
expect(subject.at('/Markup/Comment[1]/Comment').content).to eql("Some BCF comment.")
end
it 'creates BCF comments for comments that were created within OP.' do
expect(subject.at('/Markup/Comment[2]/Comment').content).to eql("Some note created in OP.")
expect(Bim::Bcf::Comment.count).to eql(2)
end
it 'replaces the BCF viewpoints names to use its uuid only' do
uuid = bcf_issue.viewpoints.first.uuid
viewpoint_node = subject.at("/Markup/Viewpoints[@Guid='#{uuid}']")
expect(viewpoint_node.at('Viewpoint').content).to eql("#{uuid}.xml")
expect(viewpoint_node.at('Snapshot').content).to eql("#{uuid}.jpg")
end
end
def url_helpers
@url_helpers ||= OpenProject::StaticRouting::StaticUrlHelpers.new
end
end
|
dme26/intravisor
|
runtime/musl-lkl/lkl/arch/s390/include/asm/processor.h
|
<reponame>dme26/intravisor<filename>runtime/musl-lkl/lkl/arch/s390/include/asm/processor.h<gh_stars>10-100
/* SPDX-License-Identifier: GPL-2.0 */
/*
* S390 version
* Copyright IBM Corp. 1999
* Author(s): <NAME> (<EMAIL>),
* <NAME> (<EMAIL>)
*
* Derived from "include/asm-i386/processor.h"
* Copyright (C) 1994, <NAME>
*/
#ifndef __ASM_S390_PROCESSOR_H
#define __ASM_S390_PROCESSOR_H
#include <linux/const.h>
#define CIF_MCCK_PENDING 0 /* machine check handling is pending */
#define CIF_ASCE_PRIMARY 1 /* primary asce needs fixup / uaccess */
#define CIF_ASCE_SECONDARY 2 /* secondary asce needs fixup / uaccess */
#define CIF_NOHZ_DELAY 3 /* delay HZ disable for a tick */
#define CIF_FPU 4 /* restore FPU registers */
#define CIF_IGNORE_IRQ 5 /* ignore interrupt (for udelay) */
#define CIF_ENABLED_WAIT 6 /* in enabled wait state */
#define CIF_MCCK_GUEST 7 /* machine check happening in guest */
#define CIF_DEDICATED_CPU 8 /* this CPU is dedicated */
#define _CIF_MCCK_PENDING _BITUL(CIF_MCCK_PENDING)
#define _CIF_ASCE_PRIMARY _BITUL(CIF_ASCE_PRIMARY)
#define _CIF_ASCE_SECONDARY _BITUL(CIF_ASCE_SECONDARY)
#define _CIF_NOHZ_DELAY _BITUL(CIF_NOHZ_DELAY)
#define _CIF_FPU _BITUL(CIF_FPU)
#define _CIF_IGNORE_IRQ _BITUL(CIF_IGNORE_IRQ)
#define _CIF_ENABLED_WAIT _BITUL(CIF_ENABLED_WAIT)
#define _CIF_MCCK_GUEST _BITUL(CIF_MCCK_GUEST)
#define _CIF_DEDICATED_CPU _BITUL(CIF_DEDICATED_CPU)
#ifndef __ASSEMBLY__
#include <linux/linkage.h>
#include <linux/irqflags.h>
#include <asm/cpu.h>
#include <asm/page.h>
#include <asm/ptrace.h>
#include <asm/setup.h>
#include <asm/runtime_instr.h>
#include <asm/fpu/types.h>
#include <asm/fpu/internal.h>
static inline void set_cpu_flag(int flag)
{
S390_lowcore.cpu_flags |= (1UL << flag);
}
static inline void clear_cpu_flag(int flag)
{
S390_lowcore.cpu_flags &= ~(1UL << flag);
}
static inline int test_cpu_flag(int flag)
{
return !!(S390_lowcore.cpu_flags & (1UL << flag));
}
/*
* Test CIF flag of another CPU. The caller needs to ensure that
* CPU hotplug can not happen, e.g. by disabling preemption.
*/
static inline int test_cpu_flag_of(int flag, int cpu)
{
struct lowcore *lc = lowcore_ptr[cpu];
return !!(lc->cpu_flags & (1UL << flag));
}
#define arch_needs_cpu() test_cpu_flag(CIF_NOHZ_DELAY)
/*
* Default implementation of macro that returns current
* instruction pointer ("program counter").
*/
#define current_text_addr() ({ void *pc; asm("basr %0,0" : "=a" (pc)); pc; })
static inline void get_cpu_id(struct cpuid *ptr)
{
asm volatile("stidp %0" : "=Q" (*ptr));
}
void s390_adjust_jiffies(void);
void s390_update_cpu_mhz(void);
void cpu_detect_mhz_feature(void);
extern const struct seq_operations cpuinfo_op;
extern int sysctl_ieee_emulation_warnings;
extern void execve_tail(void);
extern void __bpon(void);
/*
* User space process size: 2GB for 31 bit, 4TB or 8PT for 64 bit.
*/
#define TASK_SIZE_OF(tsk) (test_tsk_thread_flag(tsk, TIF_31BIT) ? \
(1UL << 31) : -PAGE_SIZE)
#define TASK_UNMAPPED_BASE (test_thread_flag(TIF_31BIT) ? \
(1UL << 30) : (1UL << 41))
#define TASK_SIZE TASK_SIZE_OF(current)
#define TASK_SIZE_MAX (-PAGE_SIZE)
#define STACK_TOP (test_thread_flag(TIF_31BIT) ? \
(1UL << 31) : (1UL << 42))
#define STACK_TOP_MAX (1UL << 42)
#define HAVE_ARCH_PICK_MMAP_LAYOUT
typedef unsigned int mm_segment_t;
/*
* Thread structure
*/
struct thread_struct {
unsigned int acrs[NUM_ACRS];
unsigned long ksp; /* kernel stack pointer */
unsigned long user_timer; /* task cputime in user space */
unsigned long guest_timer; /* task cputime in kvm guest */
unsigned long system_timer; /* task cputime in kernel space */
unsigned long hardirq_timer; /* task cputime in hardirq context */
unsigned long softirq_timer; /* task cputime in softirq context */
unsigned long sys_call_table; /* system call table address */
mm_segment_t mm_segment;
unsigned long gmap_addr; /* address of last gmap fault. */
unsigned int gmap_write_flag; /* gmap fault write indication */
unsigned int gmap_int_code; /* int code of last gmap fault */
unsigned int gmap_pfault; /* signal of a pending guest pfault */
/* Per-thread information related to debugging */
struct per_regs per_user; /* User specified PER registers */
struct per_event per_event; /* Cause of the last PER trap */
unsigned long per_flags; /* Flags to control debug behavior */
unsigned int system_call; /* system call number in signal */
unsigned long last_break; /* last breaking-event-address. */
/* pfault_wait is used to block the process on a pfault event */
unsigned long pfault_wait;
struct list_head list;
/* cpu runtime instrumentation */
struct runtime_instr_cb *ri_cb;
struct gs_cb *gs_cb; /* Current guarded storage cb */
struct gs_cb *gs_bc_cb; /* Broadcast guarded storage cb */
unsigned char trap_tdb[256]; /* Transaction abort diagnose block */
/*
* Warning: 'fpu' is dynamically-sized. It *MUST* be at
* the end.
*/
struct fpu fpu; /* FP and VX register save area */
};
/* Flag to disable transactions. */
#define PER_FLAG_NO_TE 1UL
/* Flag to enable random transaction aborts. */
#define PER_FLAG_TE_ABORT_RAND 2UL
/* Flag to specify random transaction abort mode:
* - abort each transaction at a random instruction before TEND if set.
* - abort random transactions at a random instruction if cleared.
*/
#define PER_FLAG_TE_ABORT_RAND_TEND 4UL
typedef struct thread_struct thread_struct;
/*
* Stack layout of a C stack frame.
*/
#ifndef __PACK_STACK
struct stack_frame {
unsigned long back_chain;
unsigned long empty1[5];
unsigned long gprs[10];
unsigned int empty2[8];
};
#else
struct stack_frame {
unsigned long empty1[5];
unsigned int empty2[8];
unsigned long gprs[10];
unsigned long back_chain;
};
#endif
#define ARCH_MIN_TASKALIGN 8
#define INIT_THREAD { \
.ksp = sizeof(init_stack) + (unsigned long) &init_stack, \
.fpu.regs = (void *) init_task.thread.fpu.fprs, \
}
/*
* Do necessary setup to start up a new thread.
*/
#define start_thread(regs, new_psw, new_stackp) do { \
regs->psw.mask = PSW_USER_BITS | PSW_MASK_EA | PSW_MASK_BA; \
regs->psw.addr = new_psw; \
regs->gprs[15] = new_stackp; \
execve_tail(); \
} while (0)
#define start_thread31(regs, new_psw, new_stackp) do { \
regs->psw.mask = PSW_USER_BITS | PSW_MASK_BA; \
regs->psw.addr = new_psw; \
regs->gprs[15] = new_stackp; \
crst_table_downgrade(current->mm); \
execve_tail(); \
} while (0)
/* Forward declaration, a strange C thing */
struct task_struct;
struct mm_struct;
struct seq_file;
struct pt_regs;
typedef int (*dump_trace_func_t)(void *data, unsigned long address, int reliable);
void dump_trace(dump_trace_func_t func, void *data,
struct task_struct *task, unsigned long sp);
void show_registers(struct pt_regs *regs);
void show_cacheinfo(struct seq_file *m);
/* Free all resources held by a thread. */
static inline void release_thread(struct task_struct *tsk) { }
/* Free guarded storage control block */
void guarded_storage_release(struct task_struct *tsk);
unsigned long get_wchan(struct task_struct *p);
#define task_pt_regs(tsk) ((struct pt_regs *) \
(task_stack_page(tsk) + THREAD_SIZE) - 1)
#define KSTK_EIP(tsk) (task_pt_regs(tsk)->psw.addr)
#define KSTK_ESP(tsk) (task_pt_regs(tsk)->gprs[15])
/* Has task runtime instrumentation enabled ? */
#define is_ri_task(tsk) (!!(tsk)->thread.ri_cb)
static inline unsigned long current_stack_pointer(void)
{
unsigned long sp;
asm volatile("la %0,0(15)" : "=a" (sp));
return sp;
}
static inline unsigned short stap(void)
{
unsigned short cpu_address;
asm volatile("stap %0" : "=Q" (cpu_address));
return cpu_address;
}
/*
* Give up the time slice of the virtual PU.
*/
#define cpu_relax_yield cpu_relax_yield
void cpu_relax_yield(void);
#define cpu_relax() barrier()
#define ECAG_CACHE_ATTRIBUTE 0
#define ECAG_CPU_ATTRIBUTE 1
static inline unsigned long __ecag(unsigned int asi, unsigned char parm)
{
unsigned long val;
asm volatile(".insn rsy,0xeb000000004c,%0,0,0(%1)" /* ecag */
: "=d" (val) : "a" (asi << 8 | parm));
return val;
}
static inline void psw_set_key(unsigned int key)
{
asm volatile("spka 0(%0)" : : "d" (key));
}
/*
* Set PSW to specified value.
*/
static inline void __load_psw(psw_t psw)
{
asm volatile("lpswe %0" : : "Q" (psw) : "cc");
}
/*
* Set PSW mask to specified value, while leaving the
* PSW addr pointing to the next instruction.
*/
static inline void __load_psw_mask(unsigned long mask)
{
unsigned long addr;
psw_t psw;
psw.mask = mask;
asm volatile(
" larl %0,1f\n"
" stg %0,%O1+8(%R1)\n"
" lpswe %1\n"
"1:"
: "=&d" (addr), "=Q" (psw) : "Q" (psw) : "memory", "cc");
}
/*
* Extract current PSW mask
*/
static inline unsigned long __extract_psw(void)
{
unsigned int reg1, reg2;
asm volatile("epsw %0,%1" : "=d" (reg1), "=a" (reg2));
return (((unsigned long) reg1) << 32) | ((unsigned long) reg2);
}
static inline void local_mcck_enable(void)
{
__load_psw_mask(__extract_psw() | PSW_MASK_MCHECK);
}
static inline void local_mcck_disable(void)
{
__load_psw_mask(__extract_psw() & ~PSW_MASK_MCHECK);
}
/*
* Rewind PSW instruction address by specified number of bytes.
*/
static inline unsigned long __rewind_psw(psw_t psw, unsigned long ilc)
{
unsigned long mask;
mask = (psw.mask & PSW_MASK_EA) ? -1UL :
(psw.mask & PSW_MASK_BA) ? (1UL << 31) - 1 :
(1UL << 24) - 1;
return (psw.addr - ilc) & mask;
}
/*
* Function to stop a processor until the next interrupt occurs
*/
void enabled_wait(void);
/*
* Function to drop a processor into disabled wait state
*/
static inline void __noreturn disabled_wait(unsigned long code)
{
psw_t psw;
psw.mask = PSW_MASK_BASE | PSW_MASK_WAIT | PSW_MASK_BA | PSW_MASK_EA;
psw.addr = code;
__load_psw(psw);
while (1);
}
/*
* Basic Machine Check/Program Check Handler.
*/
extern void s390_base_mcck_handler(void);
extern void s390_base_pgm_handler(void);
extern void s390_base_ext_handler(void);
extern void (*s390_base_mcck_handler_fn)(void);
extern void (*s390_base_pgm_handler_fn)(void);
extern void (*s390_base_ext_handler_fn)(void);
#define ARCH_LOW_ADDRESS_LIMIT 0x7fffffffUL
extern int memcpy_real(void *, void *, size_t);
extern void memcpy_absolute(void *, void *, size_t);
#define mem_assign_absolute(dest, val) do { \
__typeof__(dest) __tmp = (val); \
\
BUILD_BUG_ON(sizeof(__tmp) != sizeof(val)); \
memcpy_absolute(&(dest), &__tmp, sizeof(__tmp)); \
} while (0)
extern int s390_isolate_bp(void);
extern int s390_isolate_bp_guest(void);
#endif /* __ASSEMBLY__ */
#endif /* __ASM_S390_PROCESSOR_H */
|
oixhwotl/RecursoDeAndroidProgramming
|
REF/AndExam4_1/src/andexam/ver4_1/c32_map/OverlayWidget.java
|
package andexam.ver4_1.c32_map;
import andexam.ver4_1.*;
import android.graphics.*;
import android.os.*;
import android.widget.*;
import com.google.android.maps.*;
import com.google.android.maps.MapView.*;
public class OverlayWidget extends MapActivity {
MapView mMap;
protected boolean isRouteDisplayed() {
return false;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapviewtest);
mMap = (MapView)findViewById(R.id.mapview);
MapController mapControl = mMap.getController();
mapControl.setZoom(17);
mMap.setSatellite(false);
mMap.setBuiltInZoomControls(true);
GeoPoint pt = new GeoPoint(37554644, 126970700);
mapControl.setCenter(pt);
// 서울역 좌표에 표식 배치
ImageView dest = new ImageView(this);
dest.setImageResource(R.drawable.marker);
MapView.LayoutParams lp = new MapView.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
pt, MapView.LayoutParams.CENTER);
mMap.addView(dest, lp);
// 상단에 설명 문자열 배치
TextView title = new TextView(this);
title.setText("서울역");
title.setTextSize(40);
title.setTextColor(Color.BLACK);
MapView.LayoutParams lp2 = new MapView.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
10,10, MapView.LayoutParams.LEFT | MapView.LayoutParams.TOP);
mMap.addView(title, lp2);
}
}
|
MayuriLokhande/C_programs
|
Pointers/restrictKeyword.c
|
#include <stdio.h>
void operation(int* a, int*b, int*c)
{
*a+=*c;
*c+=*b;
}
int main()
{
int a=2,b=3, c=5;
operation(&a,&b,&c);
printf("%d %d %d\n",a,b,c);
return 0;
}
|
ihmcrobotics/ihmc-open-robotics-software
|
ihmc-robotics-toolkit/src/main/java/us/ihmc/robotics/graphics/YoGraphicPlanarRegionsList.java
|
package us.ihmc.robotics.graphics;
import java.awt.Color;
import java.util.*;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import us.ihmc.euclid.geometry.ConvexPolygon2D;
import us.ihmc.euclid.referenceFrame.ReferenceFrame;
import us.ihmc.euclid.transform.AffineTransform;
import us.ihmc.euclid.transform.RigidBodyTransform;
import us.ihmc.euclid.tuple3D.Point3D32;
import us.ihmc.euclid.tuple3D.Vector3D32;
import us.ihmc.graphicsDescription.*;
import us.ihmc.graphicsDescription.appearance.AppearanceDefinition;
import us.ihmc.graphicsDescription.appearance.YoAppearance;
import us.ihmc.graphicsDescription.instructions.Graphics3DAddMeshDataInstruction;
import us.ihmc.graphicsDescription.plotting.artifact.Artifact;
import us.ihmc.graphicsDescription.yoGraphics.RemoteYoGraphic;
import us.ihmc.graphicsDescription.yoGraphics.YoGraphic;
import us.ihmc.graphicsDescription.yoGraphics.YoGraphicJob;
import us.ihmc.robotics.geometry.PlanarRegion;
import us.ihmc.robotics.geometry.PlanarRegionsList;
import us.ihmc.yoVariables.euclid.referenceFrame.YoFramePoint2D;
import us.ihmc.yoVariables.euclid.referenceFrame.YoFramePoint3D;
import us.ihmc.yoVariables.euclid.referenceFrame.YoFramePose3D;
import us.ihmc.yoVariables.euclid.referenceFrame.YoFrameQuaternion;
import us.ihmc.yoVariables.registry.YoRegistry;
import us.ihmc.yoVariables.variable.YoBoolean;
import us.ihmc.yoVariables.variable.YoDouble;
import us.ihmc.yoVariables.variable.YoInteger;
import us.ihmc.yoVariables.variable.YoVariable;
/**
* {@link YoGraphic} that can display {@link PlanarRegionsList} locally, with SCS for instance, and remotely, with SCSVisualizer for instance.
* The implementation is complex because the overall number of vertices of a {@link PlanarRegionsList} tends to get really big overtime.
* Instead of creating a gazillion of {@link YoVariable}s to store all vertices of any given {@link PlanarRegionsList},
* a small buffer of vertices is used to update only a portion of the given {@link PlanarRegionsList}.
*
* <p>
* In addition to the complexity due to the constantly growing number of vertices, some synchronization has to be done when displaying this {@link YoGraphic} remotely.
* When the display thread is rendering at a slower pace than the {@link YoVariable}s are being updated, without any synchronization, only portions
* of the meshes will be rendered.
*
* <p>
* Usage of this {@code YoGraphic}:
* <li> {@link #submitPlanarRegionsListToRender(PlanarRegionsList)} informs that a new {@link PlanarRegionsList} is to be processed to get eventually rendered.
* The method does not change {@link YoVariable}s and does not compute any mesh. Up to {@value MAX_PLANAR_REGIONS_LIST_DEQUE_SIZE} {@link PlanarRegionsList} can be queued.
* Beyond that limit, new {@link PlanarRegionsList} will simply be ignored.
* <li> Once a {@link PlanarRegionsList} is submitted, {@link #processPlanarRegionsListQueue()} will pack a portion the {@link PlanarRegionsList} in this {@link #vertexBuffer}, {@link #currentRegionId}, and {@link #currentRegionPose}.
* Then {@link #update()} is called.
* <li> When rendering this {@link YoGraphic} locally, {@link #update()} simply computes the current mesh to be updated, if any.
* When rendering this {@link YoGraphic} remotely, {@link #update()} will in addition inform the WRITER version of the YoGraphic that it is ready to process a new mesh.
* This allows to amke sure that remote graphic are properly displayed.
*
* @author Sylvain
*
*/
public class YoGraphicPlanarRegionsList extends YoGraphic implements RemoteYoGraphic, GraphicsUpdatable
{
private static final int MAX_PLANAR_REGIONS_LIST_DEQUE_SIZE = 2;
private final YoGraphicJob yoGraphicJob;
private static final ReferenceFrame worldFrame = ReferenceFrame.getWorldFrame();
private final Random random = new Random(165165L);
/** Region Id based appearances. They are recycled to ensure continuity in coloring the regions over time. */
private final TIntObjectMap<AppearanceDefinition> regionIdToAppearance = new TIntObjectHashMap<>();
private final int vertexBufferSize;
private final int meshBufferSize;
/** When this is created as a {@link RemoteYoGraphic}, it is consider as a READER and thus turns on this flag to let the WRITER know that it has to synchronize.*/
private final YoBoolean waitForReader;
/** When this is created as a {@link RemoteYoGraphic}, it is consider as a READER and thus turns on this flag to let the WRITER know that it has processed the current mesh. */
private final YoBoolean hasReaderProcessedMesh;
/** When the writer is used to render the graphics, this is used to block the processing if planar regions until this flag turns to true. */
private final YoBoolean hasWriterProcessedMesh;
/**
* Buffer of vertices used to store one or more polygons to render.
* When more than one polygon is stored, each pair of polygons is separated by a vertex that is set to {@link Double#NaN}.
* All the polygons stored in this buffer are always part of the same {@link PlanarRegion} such that they have the same transform to world.
* <p>
* Any non used vertex is set to {@link Double#NaN}.
*/
private final List<YoFramePoint2D> vertexBuffer;
/**
* Corresponds the current mesh index in the {@link #meshBuffer} to be updated.
* When there is no mesh to render, {@link #currentMeshIndex} equals to {@code -1}.
*/
private final YoInteger currentMeshIndex;
/**
* Indicates the id of the region that the new mesh belongs to.
* It is used to find the corresponding {@link AppearanceDefinition}.
* When there is no mesh to render, {@link #currentRegionId} equals to {@code -1}.
*/
private final YoInteger currentRegionId;
/**
* Indicates that the current mesh to render is the last one of the current {@link PlanarRegionsList}.
* It is used to clear the unused part of the {@link #meshBuffer}.
*/
private final YoBoolean isPlanarRegionsListComplete;
/**
* Indicates that this {@link YoGraphic} is clearing the graphics and resetting its current state.
*/
private final YoBoolean clear;
/**
* Indicates the pose with respect to world of the region that the new mesh belongs to.
* It is used to transform the vertices so they're expressed in world.
* When there is no mesh to render, {@link #currentRegionId} equals to {@code -1}.
*/
private final YoFramePose3D currentRegionPose;
/**
* Stores custom colors for planar regions.
* When constructed without using custom colors, {@link #planarRegionsColorBuffer} is {@code null}
* and random colors are used.
*/
private final YoInteger[] planarRegionsColorBuffer;
private final Graphics3DObject graphics3dObject;
private final List<Graphics3DAddMeshDataInstruction> meshBuffer;
/**
* Create a {@link YoGraphic} for rendering {@link PlanarRegionsList}s.
*
* @param name
* @param vertexBufferSize
* @param meshBufferSize
* @param registry
*/
public YoGraphicPlanarRegionsList(String name, int vertexBufferSize, int meshBufferSize, YoRegistry registry)
{
this(name, vertexBufferSize, meshBufferSize, false, -1, registry);
}
/**
* Create a {@link YoGraphic} for rendering {@link PlanarRegionsList}s.
*
* @param name
* @param vertexBufferSize
* @param meshBufferSize
* @param registry
*/
public YoGraphicPlanarRegionsList(String name, int vertexBufferSize, int meshBufferSize, boolean useCustomColors, int numberOfPlanarRegions, YoRegistry registry)
{
super(name);
yoGraphicJob = YoGraphicJob.WRITER;
this.vertexBufferSize = vertexBufferSize;
this.meshBufferSize = meshBufferSize;
waitForReader = new YoBoolean(name + "WaitForReader", registry);
hasReaderProcessedMesh = new YoBoolean(name + "HasReaderProcessedMesh", registry);
hasWriterProcessedMesh = new YoBoolean(name + "HasWriterProcessedMesh", registry);
vertexBuffer = new ArrayList<>(vertexBufferSize);
for (int i = 0; i < vertexBufferSize; i++)
{
YoFramePoint2D vertex = new YoFramePoint2D(name + "Vertex" + i, worldFrame, registry);
vertex.setToNaN();
vertexBuffer.add(vertex);
}
currentMeshIndex = new YoInteger(name + "CurrentMeshIndex", registry);
currentRegionId = new YoInteger(name + "CurrentRegionId", registry);
isPlanarRegionsListComplete = new YoBoolean(name + "IsComplete", registry);
clear = new YoBoolean(name + "Clear", registry);
currentRegionPose = new YoFramePose3D(name + "CurrentRegionPose", worldFrame, registry);
clearYoVariables();
graphics3dObject = new Graphics3DObject();
graphics3dObject.setChangeable(true);
meshBuffer = new ArrayList<>(meshBufferSize);
for (int polygonIndex = 0; polygonIndex < meshBufferSize; polygonIndex++)
meshBuffer.add(graphics3dObject.addMeshData(null, YoAppearance.AliceBlue()));
if(useCustomColors)
{
planarRegionsColorBuffer = new YoInteger[numberOfPlanarRegions];
for(int i = 0; i < numberOfPlanarRegions; i++)
{
planarRegionsColorBuffer[i] = new YoInteger("customColor" + i, registry);
}
}
else
{
planarRegionsColorBuffer = null;
}
}
/**
* Create a YoGraphic for remote visualization.
* @param name name of this YoGraphic.
* @param yoVariables the list of YoVariables needed for this YoGraphic expected to be in the same order as packed in {@link #getVariables()}.
* @param constants the list of constants (variables that will never change) needed for this YoGraphic expected to be in the same order as packed in {@link #getConstants()}.
* @return a YoGraphic setup for remote visualization.
*/
public static YoGraphicPlanarRegionsList createAsRemoteYoGraphic(String name, YoVariable[] yoVariables, double[] constants)
{
return new YoGraphicPlanarRegionsList(name, yoVariables, constants);
}
/**
* This constructor is only for remote visualizer.
* It is automatically handled and should not be used for creating a new YoGraphic.
* For the latter, use the other constructor(s).
*/
private YoGraphicPlanarRegionsList(String name, YoVariable[] yoVariables, double[] constants)
{
super(name);
yoGraphicJob = YoGraphicJob.READER;
vertexBufferSize = (int)constants[0];
meshBufferSize = (int)constants[1];
vertexBuffer = new ArrayList<>(vertexBufferSize);
int variableIndex = 0;
waitForReader = (YoBoolean) yoVariables[variableIndex++];
hasReaderProcessedMesh = (YoBoolean) yoVariables[variableIndex++];
hasWriterProcessedMesh = (YoBoolean) yoVariables[variableIndex++];
for (int vertexIndex = 0; vertexIndex < vertexBufferSize; vertexIndex++)
{
YoDouble x = (YoDouble) yoVariables[variableIndex++];
YoDouble y = (YoDouble) yoVariables[variableIndex++];
YoFramePoint2D vertex = new YoFramePoint2D(x, y, worldFrame);
vertexBuffer.add(vertex);
}
currentMeshIndex = (YoInteger) yoVariables[variableIndex++];
currentRegionId = (YoInteger) yoVariables[variableIndex++];
isPlanarRegionsListComplete = (YoBoolean) yoVariables[variableIndex++];
clear = (YoBoolean) yoVariables[variableIndex++];
YoDouble x = (YoDouble) yoVariables[variableIndex++];
YoDouble y = (YoDouble) yoVariables[variableIndex++];
YoDouble z = (YoDouble) yoVariables[variableIndex++];
YoDouble qx = (YoDouble) yoVariables[variableIndex++];
YoDouble qy = (YoDouble) yoVariables[variableIndex++];
YoDouble qz = (YoDouble) yoVariables[variableIndex++];
YoDouble qs = (YoDouble) yoVariables[variableIndex++];
YoFramePoint3D position = new YoFramePoint3D(x, y, z, worldFrame);
YoFrameQuaternion orientation = new YoFrameQuaternion(qx, qy, qz, qs, worldFrame);
currentRegionPose = new YoFramePose3D(position, orientation);
graphics3dObject = new Graphics3DObject();
graphics3dObject.setChangeable(true);
meshBuffer = new ArrayList<>(meshBufferSize);
for (int polygonIndex = 0; polygonIndex < meshBufferSize; polygonIndex++)
meshBuffer.add(graphics3dObject.addMeshData(null, YoAppearance.AliceBlue()));
if(yoVariables.length > variableIndex)
{
int numberOfPlanarRegions = yoVariables.length - variableIndex;
planarRegionsColorBuffer = new YoInteger[numberOfPlanarRegions];
for(int i = 0; i < numberOfPlanarRegions; i++)
planarRegionsColorBuffer[i] = (YoInteger) yoVariables[variableIndex++];
}
else
{
planarRegionsColorBuffer = null;
}
}
/**
* Update the mesh that will display a portion of the {@link PlanarRegionsList} being processed.
* This method only reads the YoVariables to update the mesh.
*
* When used as a remote YoGraphic, only this method should be called.
*/
@Override
public void update()
{
switch (yoGraphicJob)
{
case READER:
{
// Notify the updater that a reader exists and the updater must synchronize.
waitForReader.set(true);
hasReaderProcessedMesh.set(true);
if (clear.getBooleanValue())
{
for (int meshIndex = 0; meshIndex < meshBufferSize; meshIndex++)
meshBuffer.get(meshIndex).setMesh(null);
clear.set(false);
return;
}
break;
}
case WRITER:
{
hasWriterProcessedMesh.set(true);
if (clear.getBooleanValue())
{
for (int meshIndex = 0; meshIndex < meshBufferSize; meshIndex++)
meshBuffer.get(meshIndex).setMesh(null);
if (!waitForReader.getBooleanValue())
clear.set(false);
return;
}
break;
}
default:
throw new RuntimeException("Unknown job: " + yoGraphicJob);
}
if (currentMeshIndex.getIntegerValue() == -1)
return;
MeshDataHolder polygonMesh = createCurrentMesh();
polygonMesh.setName("PlanarRegion");
AppearanceDefinition appearance = getCurrentAppearance();
Graphics3DAddMeshDataInstruction instructionToUpdate = meshBuffer.get(currentMeshIndex.getIntegerValue());
instructionToUpdate.setMesh(polygonMesh);
instructionToUpdate.setAppearance(appearance);
if (isPlanarRegionsListComplete.getBooleanValue())
{
// Clear the rest of meshes that are not needed.
for (int meshIndex = currentMeshIndex.getIntegerValue() + 1; meshIndex < meshBufferSize; meshIndex++)
meshBuffer.get(meshIndex).setMesh(null);
}
}
/**
* Retrieve or create a random {@link AppearanceDefinition} given the id of the region to which the current mesh belongs to.
* @return the mesh appearance.
*/
private AppearanceDefinition getCurrentAppearance()
{
AppearanceDefinition appearance;
if(planarRegionsColorBuffer != null)
{
int requestedColorRGB = planarRegionsColorBuffer[currentMeshIndex.getIntegerValue()].getIntegerValue();
appearance = YoAppearance.RGBColorFromHex(requestedColorRGB);
}
else if (regionIdToAppearance.containsKey(currentRegionId.getIntegerValue()))
{
appearance = regionIdToAppearance.get(currentRegionId.getIntegerValue());
}
else
{
appearance = YoAppearance.randomColor(random);
regionIdToAppearance.put(currentRegionId.getIntegerValue(), appearance);
}
return appearance;
}
/**
* @return a new mesh given the current values of the YoVariables. The mesh belongs to a single region but can contain several polygons.
*/
private MeshDataHolder createCurrentMesh()
{
ModifiableMeshDataHolder modifiableMeshDataHolder = new ModifiableMeshDataHolder();
int firstVertexIndex = 0;
boolean isDoneExtractingPolygons = false;
while (!isDoneExtractingPolygons)
{
int numberOfVertices = findPolygonSize(firstVertexIndex);
modifiableMeshDataHolder.add(createPolygonMesh(firstVertexIndex, numberOfVertices), true);
firstVertexIndex += numberOfVertices + 1;
if (firstVertexIndex >= vertexBufferSize)
{
isDoneExtractingPolygons = true;
}
else
{
isDoneExtractingPolygons = vertexBuffer.get(firstVertexIndex).containsNaN();
}
}
return modifiableMeshDataHolder.createMeshDataHolder();
}
/**
* Creates the mesh for a polygon which vertices are extracted from the {@link #vertexBuffer}.
* @param indexInVertexBuffer the index in the {@link #vertexBuffer} of the first vertex of the polygon.
* @param numberOfVertices teh polygon size.
* @return the polygon's mesh.
*/
private MeshDataHolder createPolygonMesh(int indexInVertexBuffer, int numberOfVertices)
{
if (numberOfVertices <= 0)
return null;
int numberOfTriangles = numberOfVertices - 2;
if (numberOfTriangles <= 0)
return null;
Point3D32[] vertices = new Point3D32[numberOfVertices];
TexCoord2f[] texturePoints = new TexCoord2f[numberOfVertices];
Vector3D32[] vertexNormals = new Vector3D32[numberOfVertices];
RigidBodyTransform transform = new RigidBodyTransform();
currentRegionPose.get(transform);
for (int vertexIndex = 0; vertexIndex < numberOfVertices; vertexIndex++)
{
Point3D32 vertex = new Point3D32();
vertex.set(vertexBuffer.get(vertexIndex + indexInVertexBuffer));
transform.transform(vertex);
vertices[vertexIndex] = vertex;
}
for (int vertexIndex = 0; vertexIndex < numberOfVertices; vertexIndex++)
{
Vector3D32 normal = new Vector3D32();
normal.setX((float) transform.getM02());
normal.setY((float) transform.getM12());
normal.setZ((float) transform.getM22());
vertexNormals[vertexIndex] = normal;
}
// no texture for now
for (int vertexIndex = 0; vertexIndex < numberOfVertices; vertexIndex++)
texturePoints[vertexIndex] = new TexCoord2f();
int[] triangleIndices = new int[3 * numberOfTriangles];
int index = 0;
for (int j = 2; j < numberOfVertices; j++)
{
triangleIndices[index++] = 0;
triangleIndices[index++] = j - 1;
triangleIndices[index++] = j;
}
return new MeshDataHolder(vertices, texturePoints, triangleIndices, vertexNormals);
}
/**
* Given the index of the first vertex of a polygon contained in the {@link #vertexBuffer},
* this method retrieves its size knowing that polygons are delimited by {@link Double#NaN} in the buffer.
* @param firstVertexIndex the index of the first vertex of a polygon contained in the buffer.
* @return the polygon's size.
*/
private int findPolygonSize(int firstVertexIndex)
{
for (int i = firstVertexIndex; i < vertexBuffer.size(); i++)
{
if (vertexBuffer.get(i).containsNaN())
return i - firstVertexIndex;
}
return vertexBuffer.size() - firstVertexIndex;
}
private final RigidBodyTransform regionTransform = new RigidBodyTransform();
private final Deque<PlanarRegionsList> planarRegionsListsDeque = new ArrayDeque<>();
/**
* Submit a new list of planar regions to eventually render.
* This method does NOT update any YoVariables and does not update any graphics.
* Once a list of planar regions is submitted, the method {@link #processPlanarRegionsListQueue()} has to be called every update tick in the caller.
* @param planarRegionsList the list of planar regions to be eventually rendered.
* @param requestedAppearance appearance to render the planar regions
*/
public void submitPlanarRegionsListToRender(PlanarRegionsList planarRegionsList, Color requestedColor)
{
for(int i = 0; i < planarRegionsList.getNumberOfPlanarRegions(); i++)
{
int index = i + currentMeshIndex.getIntegerValue();
if(index < 0 || index >= planarRegionsColorBuffer.length)
break;
planarRegionsColorBuffer[index].set(requestedColor.getRGB());
}
submitPlanarRegionsListToRender(planarRegionsList);
}
/**
* Submit a new list of planar regions to eventually render.
* This method does NOT update any YoVariables and does not update any graphics.
* Once a list of planar regions is submitted, the method {@link #processPlanarRegionsListQueue()} has to be called every update tick in the caller.
* @param planarRegionsList the list of planar regions to be eventually rendered.
*/
public void submitPlanarRegionsListToRender(PlanarRegionsList planarRegionsList)
{
if (planarRegionsList == null)
{
//TODO: Clear the viz when the planarRegionsList is null;
return;
}
if (planarRegionsListsDeque.size() > MAX_PLANAR_REGIONS_LIST_DEQUE_SIZE)
return;
// This YoGraphic modifies the planarRegionsList.
// A full depth copy has to be created to prevent changing the argument.
PlanarRegionsList copy = planarRegionsList.copy();
PlanarRegionsList filteredPlanarRegionsList = filterEmptyRegionsAndEmptyPolygons(copy);
if (filteredPlanarRegionsList != null)
planarRegionsListsDeque.addLast(filteredPlanarRegionsList);
}
/**
* Filter all the polygons and regions such that only polygon and regions with data remain.
* Simplifies the algorithm for updating the YoVariables in {@link #processPlanarRegionsListQueue()}.
* @param planarRegionsList the list of planar regions with non-empty regions and non-empty polygons.
* @return
*/
private PlanarRegionsList filterEmptyRegionsAndEmptyPolygons(PlanarRegionsList planarRegionsList)
{
for (int regionIndex = planarRegionsList.getNumberOfPlanarRegions() - 1; regionIndex >= 0; regionIndex--)
{
PlanarRegion planarRegion = planarRegionsList.getPlanarRegion(regionIndex);
for (int polygonIndex = planarRegion.getNumberOfConvexPolygons() - 1; polygonIndex >= 0; polygonIndex--)
{
if (planarRegion.getConvexPolygon(polygonIndex).isEmpty())
planarRegion.pollConvexPolygon(polygonIndex);
}
if (planarRegion.isEmpty())
planarRegionsList.pollPlanarRegion(regionIndex);
}
if (planarRegionsList.isEmpty())
return null;
return planarRegionsList;
}
public void clear()
{
clear.set(true);
planarRegionsListsDeque.clear();
clearYoVariables();
update();
}
/**
* Processes the queue of lists of planar regions to render and updates the graphics.
* This method need to called every update tick in the caller.
*/
public void processPlanarRegionsListQueue()
{
processPlanarRegionsListQueue(true);
}
public void processPlanarRegionsListQueue(boolean callUpdate)
{
if (waitForReader.getBooleanValue())
{
if (!hasReaderProcessedMesh.getBooleanValue())
{
return;
}
}
else
{
if (!hasWriterProcessedMesh.getBooleanValue())
{
return;
}
}
if (clear.getBooleanValue())
return;
if (planarRegionsListsDeque.isEmpty())
{
clearYoVariables();
return;
}
int currentIndex = currentMeshIndex.getIntegerValue();
if (currentIndex >= meshBufferSize - 1)
{
// Won't be able to process any additional polygons.
// Clear the current list of planar regions to update and reset the index.
currentIndex = -1;
planarRegionsListsDeque.removeFirst();
if (planarRegionsListsDeque.isEmpty())
{
clearYoVariables();
return;
}
}
PlanarRegionsList planarRegionsListToProcess = planarRegionsListsDeque.peekFirst();
PlanarRegion planarRegionToProcess = null;
ConvexPolygon2D polygonToProcess = null;
// Find the next polygon to update
while (polygonToProcess == null)
{
if (planarRegionsListToProcess == null || planarRegionsListToProcess.isEmpty())
{
// Done processing the list of planar regions.
// Reset the index as we start over the update.
currentIndex = -1;
planarRegionsListsDeque.removeFirst();
if (planarRegionsListsDeque.isEmpty())
{
clearYoVariables();
return;
}
else
{
planarRegionsListToProcess = planarRegionsListsDeque.peekFirst();
}
}
planarRegionToProcess = planarRegionsListToProcess.getLastPlanarRegion();
if (planarRegionToProcess.isEmpty())
{
// This region has been fully processed.
planarRegionsListToProcess.pollLastPlanarRegion();
// Get rid of the reference to this empty region.
planarRegionToProcess = null;
// Continue to make sure there is still something in the list of planar regions.
continue;
}
polygonToProcess = planarRegionToProcess.pollLastConvexPolygon();
if (polygonToProcess.getNumberOfVertices() > vertexBufferSize)
{
// The polygon has too many vertices, skip it.
polygonToProcess = null;
// Continue to make sure there is still something in the list of planar regions.
continue;
}
}
currentIndex++;
currentMeshIndex.set(currentIndex);
planarRegionToProcess.getTransformToWorld(regionTransform);
currentRegionPose.set(regionTransform);
currentRegionId.set(planarRegionToProcess.getRegionId());
boolean isDonePackingPolygons = false;
int vertexIndexOffset = 0;
while (!isDonePackingPolygons)
{
int numberOfVertices = polygonToProcess.getNumberOfVertices();
for (int vertexIndex = 0; vertexIndex < numberOfVertices; vertexIndex++)
{
vertexBuffer.get(vertexIndex + vertexIndexOffset).set(polygonToProcess.getVertex(vertexIndex));
}
vertexIndexOffset += numberOfVertices;
if (vertexIndexOffset >= vertexBufferSize)
{
isDonePackingPolygons = true;
}
else
{
// Set the vertex to NaN to mark the end of this polygon
vertexBuffer.get(vertexIndexOffset).setToNaN();
vertexIndexOffset++;
polygonToProcess = planarRegionToProcess.getLastConvexPolygon();
// Check if another polygon can be packed in the poolOfVertices
if (polygonToProcess == null)
{
isDonePackingPolygons = true;
}
else if (vertexIndexOffset + polygonToProcess.getNumberOfVertices() > vertexBufferSize)
{
isDonePackingPolygons = true;
}
else
{
polygonToProcess = planarRegionToProcess.pollLastConvexPolygon();
isDonePackingPolygons = false;
}
}
}
for (int vertexIndex = vertexIndexOffset; vertexIndex < vertexBufferSize; vertexIndex++)
{
vertexBuffer.get(vertexIndex).setToNaN();
}
if (planarRegionToProcess.isEmpty())
planarRegionsListToProcess.pollLastPlanarRegion();
isPlanarRegionsListComplete.set(planarRegionsListToProcess.isEmpty());
hasReaderProcessedMesh.set(false);
hasWriterProcessedMesh.set(false);
// Update the polygon mesh
if(callUpdate)
{
update();
}
}
/**
* @return the number of lists of planar regions to process by this YoGraphic.
*/
public int getQueueSize()
{
return planarRegionsListsDeque.size();
}
/**
* @return true when no list of planar regions has to be processed.
*/
public boolean isQueueEmpty()
{
return planarRegionsListsDeque.isEmpty();
}
/**
* Nothing is to be updated, the YoVariables have to be cleared so calling {@link #update()} does not do anything.
*/
private void clearYoVariables()
{
for (int vertexIndex = 0; vertexIndex < vertexBufferSize; vertexIndex++)
vertexBuffer.get(vertexIndex).setToNaN();
currentMeshIndex.set(-1);
currentRegionId.set(-1);
currentRegionPose.setToNaN();
}
/**
* @return The YoVariables needed to create a remote version of this YoGraphic.
*/
@Override
public YoVariable[] getVariables()
{
List<YoVariable> allVariables = new ArrayList<>();
allVariables.add(waitForReader);
allVariables.add(hasReaderProcessedMesh);
allVariables.add(hasWriterProcessedMesh);
for (int i = 0; i < vertexBufferSize; i++)
{
allVariables.add(vertexBuffer.get(i).getYoX());
allVariables.add(vertexBuffer.get(i).getYoY());
}
allVariables.add(currentMeshIndex);
allVariables.add(currentRegionId);
allVariables.add(isPlanarRegionsListComplete);
allVariables.add(clear);
allVariables.add(currentRegionPose.getYoX());
allVariables.add(currentRegionPose.getYoY());
allVariables.add(currentRegionPose.getYoZ());
allVariables.add(currentRegionPose.getYoQx());
allVariables.add(currentRegionPose.getYoQy());
allVariables.add(currentRegionPose.getYoQz());
allVariables.add(currentRegionPose.getYoQs());
return allVariables.toArray(new YoVariable[0]);
}
/**
* @return the constants needed to create a remote version of this YoGraphic.
*/
@Override
public double[] getConstants()
{
return new double[] {vertexBufferSize, meshBufferSize};
}
@Override
public AppearanceDefinition getAppearance()
{
// Does not matter as the appearance is generated internally
return YoAppearance.AliceBlue();
}
@Override
public Graphics3DObject getLinkGraphics()
{
return graphics3dObject;
}
@Override
protected void computeRotationTranslation(AffineTransform transform3d)
{ // Dealing with the transform here.
transform3d.setIdentity();
}
@Override
protected boolean containsNaN()
{ // Only used to determine if the graphics from this object is valid, and whether to display or hide.
return false;
}
/** {@inheritDoc} */
@Override
public YoGraphicPlanarRegionsList duplicate(YoRegistry newRegistry)
{
return new YoGraphicPlanarRegionsList(getName(), getVariables(), getConstants());
}
@Override
public Artifact createArtifact()
{
throw new RuntimeException("Implement Me!");
}
}
|
yeonghoey/baekjoon
|
15684/main.go
|
package main
import (
"bufio"
"fmt"
"os"
)
var ladder [30 + 1][10 + 1]bool
func main() {
reader := bufio.NewReader(os.Stdin)
nextInt := func() int {
var n int
_, _ = fmt.Fscan(reader, &n)
return n
}
n := nextInt()
m := nextInt()
h := nextInt()
for i := 0; i < m; i++ {
a := nextInt()
b := nextInt()
ladder[a][b] = true
}
answer := solve(n, m, h)
fmt.Println(answer)
}
func solve(n, m, h int) int {
answer := -1
for k := m % 2; k <= 3; k += 2 {
if track(n, h, k) {
answer = k
break
}
}
return answer
}
func track(n, h, k int) bool {
var try func(int, int, int) bool
try = func(a1, bnext, added int) bool {
if added >= k {
return run(n, h)
}
for a := a1; a <= h; a++ {
b1 := 1
if a == a1 {
b1 = bnext
}
for b := b1; b < n; b++ {
if ladder[a][b-1] || ladder[a][b+0] || ladder[a][b+1] {
continue
}
ladder[a][b] = true
ok := try(a, b+2, added+1)
ladder[a][b] = false
if ok {
return true
}
}
}
return false
}
return try(1, 1, 0)
}
func run(n, h int) bool {
ok := true
for b := 1; b <= n; b++ {
pos := b
for a := 1; a <= h; a++ {
if ladder[a][pos] {
pos++
} else if ladder[a][pos-1] {
pos--
}
}
if pos != b {
ok = false
break
}
}
return ok
}
|
uhop/dcl
|
tests/manual/test_modern1.js
|
<gh_stars>10-100
'use strict';
var dcl = require('../modern');
var A = dcl(null, {a: 1});
var x = new A;
console.log(x);
console.log(x instanceof A);
console.log(x.a);
var B = dcl(null, {
constructor: function () {
this.b = 2;
},
a: dcl.prop({value: 1})
});
var y = new B;
console.log(y);
console.log(y instanceof B);
console.log(y.a, y.b);
var C = dcl(null, dcl.prop({
constructor: {
value: function () {
this.b = 2;
}
},
a: {
value: 1
}
}));
var z = new C;
console.log(z);
console.log(z instanceof C);
console.log(z.a, z.b);
|
katitek/Code-Combat
|
3_GameDev1/075-Give_and_Take/giveAndTake.js
|
// Move to all the X-marks.
// Those fire-traps hurt!
game.spawnPlayerXY("samurai", 40, 50);
game.addSurviveGoal();
game.addMoveGoalXY(25,40);
game.spawnXY("fire-trap", 25, 40);
game.addMoveGoalXY(55,40);
game.spawnXY("fire-trap", 55, 40);
game.addMoveGoalXY(40,20);
game.spawnXY("fire-trap", 40, 20);
// Spawn some "potion-small" objects to heal the player!
game.spawnXY("potion-small", 55, 30);
game.spawnXY("potion-small", 32, 19);
|
mauriziokovacic/ACME
|
ACME/color/color2gray.py
|
from .color2float import *
def color2gray(C, weight=(1/3, 1/3, 1/3), dim=-1):
"""
Converts the given color in grayscale using the specified weights
Parameters
----------
C : Tensor
the (3,W,H,) or (N,3,) RGB color tensor
weight : list or tuple (optional)
the weighting factors for generating the grayscale image (default is (1/3, 1/3, 1/3))
dim : int (optional)
the dimension along the operation is performed (default is -1)
Returns
-------
Tensor
the (W,H,) or (N,) grayscale color tensor
"""
size = list(C.shape)
size[dim] = -1
alpha = torch.tensor(weight, dtype=torch.float, device=C.device)
return torch.sum(color2float(C) * alpha.expand(*size), dim=dim)
def color2gray_pal(C, dim=-1):
"""
Converts the given color in grayscale with PAL standard
Parameters
----------
C : Tensor
the (3,W,H,) or (N,3,) RGB color tensor
dim : int (optional)
the dimension along the operation is performed (default is -1)
Returns
-------
Tensor
the (W,H,) or (N,) grayscale color tensor
"""
return color2gray(C, weight=[0.299, 0.587, 0.114], dim=dim)
def color2gray_hdtv(C, dim=-1):
"""
Converts the given color in grayscale with HDTV standard
Parameters
----------
C : Tensor
the (3,W,H,) or (N,3,) RGB color tensor
dim : int (optional)
the dimension along the operation is performed (default is -1)
Returns
-------
Tensor
the (W,H,) or (N,) grayscale color tensor
"""
return color2gray(C, weight=[0.2126, 0.7152, 0.0722], dim=-1)
def color2gray_hdr(C, dim=-1):
"""
Converts the given color in grayscale with HDR standard
Parameters
----------
C : Tensor
the (3,W,H,) or (N,3,) RGB color tensor
dim : int (optional)
the dimension along the operation is performed (default is -1)
Returns
-------
Tensor
the (W,H,) or (N,) grayscale color tensor
"""
return color2gray(C, weight=[0.2627, 0.6780, 0.0593], dim=dim)
|
Abergard/VisualizationLibrary
|
src/examples/Qt4_example.cpp
|
<filename>src/examples/Qt4_example.cpp
/**************************************************************************************/
/* */
/* Visualization Library */
/* http://visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2020, <NAME> */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#include <vlCore/VisualizationLibrary.hpp>
#include <vlQt4/Qt4Widget.hpp>
#include "Applets/App_RotatingCube.hpp"
using namespace vl;
using namespace vlQt4;
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
/* init Visualization Library */
VisualizationLibrary::init();
/* setup the OpenGL context format */
OpenGLContextFormat format;
format.setDoubleBuffer(true);
format.setRGBABits( 8,8,8,0 );
format.setDepthBufferBits(24);
format.setStencilBufferBits(8);
format.setMultisampleSamples(16);
format.setMultisample(false);
format.setFullscreen(false);
//format.setOpenGLProfile( GLP_Core );
//format.setVersion( 3, 3 );
/* create the applet to be run */
ref<Applet> applet = new App_RotatingCube;
applet->initialize();
/* create a native Qt4 window */
ref<vlQt4::Qt4Widget> qt4_window = new vlQt4::Qt4Widget;
/* bind the applet so it receives all the GUI events related to the OpenGLContext */
qt4_window->addEventListener(applet.get());
/* target the window so we can render on it */
applet->rendering()->as<Rendering>()->renderer()->setFramebuffer( qt4_window->framebuffer() );
/* black background */
applet->rendering()->as<Rendering>()->camera()->viewport()->setClearColor( black );
/* define the camera position and orientation */
vec3 eye = vec3(0,10,35); // camera position
vec3 center = vec3(0,0,0); // point the camera is looking at
vec3 up = vec3(0,1,0); // up direction
mat4 view_mat = mat4::getLookAt(eye, center, up);
applet->rendering()->as<Rendering>()->camera()->setViewMatrix( view_mat );
/* Initialize the OpenGL context and window properties */
int x = 10;
int y = 10;
int width = 512;
int height= 512;
qt4_window->initQt4Widget( "Visualization Library on Qt 4 - Rotating Cube", format, NULL, x, y, width, height );
/* show the window */
qt4_window->show();
/* run the Win32 message loop */
int val = app.exec();
/* deallocate the window with all the OpenGL resources before shutting down Visualization Library */
qt4_window = NULL;
/* shutdown Visualization Library */
VisualizationLibrary::shutdown();
return val;
}
// Have fun!
|
valohai/valohai-yaml
|
valohai_yaml/objs/pipelines/node_action.py
|
from typing import Iterable, List, Set, Union
from ...lint import LintResult
from ...types import LintContext, SerializedDict
from ...utils import listify
from ..base import Item
WELL_KNOWN_WHENS = {
'node-complete', # Node completed (successfully)
'node-starting', # Node about to start
'node-error', # Node errored
}
WELL_KNOWN_THENS = {
'noop', # For testing
'stop-pipeline',
}
class NodeAction(Item):
"""Represents a node action."""
def __init__(
self,
*,
when: Union[str, Iterable[str]],
if_: Union[None, str, List[str]],
then: Union[None, str, List[str]]
) -> None:
self.when = {str(watom).lower() for watom in listify(when)} # type: Set[str]
self.if_ = listify(if_) # type: List[str]
self.then = listify(then) # type: List[str]
@classmethod
def parse(cls, data: SerializedDict) -> 'NodeAction':
data = data.copy()
data['if_'] = data.pop('if', [])
return super().parse(data)
def get_data(self) -> SerializedDict:
data = super().get_data()
data['if'] = data.pop('if_')
data['when'] = sorted(data.pop('when'))
return data
def lint(self, lint_result: LintResult, context: LintContext) -> None:
super().lint(lint_result, context)
for when in self.when:
if when not in WELL_KNOWN_WHENS:
lint_result.add_warning(
f'"when" value {self.when} is not well-known; the action might never be triggered'
)
for then in self.then:
if then not in WELL_KNOWN_THENS:
lint_result.add_warning(
f'"then" value {self.then} is not well-known; the action might do nothing'
)
|
opastushkov/codewars-solutions
|
CodeWars/Python/5 kyu/RGB To Hex Conversion/main.py
|
def f(num):
if num > 255: return 255
elif num < 0: return 0
else: return num
def rgb(r, g, b):
return '{:02X}{:02X}{:02X}'.format(f(r), f(g), f(b))
|
ghsecuritylab/bcwifi
|
release/src/router/aria2-1.18.1/src/HttpResponseCommand.h
|
<reponame>ghsecuritylab/bcwifi<gh_stars>10-100
/* <!-- copyright */
/*
* aria2 - The high speed download utility
*
* Copyright (C) 2006 <NAME>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
/* copyright --> */
#ifndef D_HTTP_RESPONSE_COMMAND_H
#define D_HTTP_RESPONSE_COMMAND_H
#include "AbstractCommand.h"
#include "TimeA2.h"
namespace aria2 {
class HttpConnection;
class HttpDownloadCommand;
class HttpResponse;
class SocketCore;
class StreamFilter;
#ifdef ENABLE_MESSAGE_DIGEST
class Checksum;
#endif // ENABLE_MESSAGE_DIGEST
// HttpResponseCommand receives HTTP response header from remote
// server. Because network I/O is non-blocking, execute() returns
// false when all response headers are not received. Subsequent calls
// of execute() receives remaining response headers and when all
// headers are received, it examines headers. If status code is 200
// or 206 and Range header satisfies requested range, it creates
// HttpDownloadCommand to receive response entity body. Otherwise, it
// creates HttpSkipResponseCommand to receive response entity body and
// returns true. Handling errors such as 404 or redirect is handled in
// HttpSkipResponseCommand.
class HttpResponseCommand : public AbstractCommand {
private:
std::shared_ptr<HttpConnection> httpConnection_;
bool handleDefaultEncoding(std::unique_ptr<HttpResponse> httpResponse);
bool handleOtherEncoding(std::unique_ptr<HttpResponse> httpResponse);
bool skipResponseBody(std::unique_ptr<HttpResponse> httpResponse);
std::unique_ptr<HttpDownloadCommand>
createHttpDownloadCommand(std::unique_ptr<HttpResponse> httpResponse,
std::unique_ptr<StreamFilter> streamFilter);
void updateLastModifiedTime(const Time& lastModified);
void poolConnection();
void onDryRunFileFound();
#ifdef ENABLE_MESSAGE_DIGEST
// Returns true if dctx and checksum has same hash type and hash
// value. If they have same hash type but different hash value,
// throws exception. Otherwise returns false.
bool checkChecksum(const std::shared_ptr<DownloadContext>& dctx,
const Checksum& checksum);
#endif // ENABLE_MESSAGE_DIGEST
protected:
bool executeInternal() CXX11_OVERRIDE;
bool shouldInflateContentEncoding(HttpResponse* httpResponse);
public:
HttpResponseCommand(cuid_t cuid,
const std::shared_ptr<Request>& req,
const std::shared_ptr<FileEntry>& fileEntry,
RequestGroup* requestGroup,
const std::shared_ptr<HttpConnection>& httpConnection,
DownloadEngine* e,
const std::shared_ptr<SocketCore>& s);
~HttpResponseCommand();
};
} // namespace aria2
#endif // D_HTTP_RESPONSE_COMMAND_H
|
WilliamDeveloper/udemy_cursos
|
react/curso_reactjs/aula20_basereact/projeto/src/components/H1/index.js
|
<filename>react/curso_reactjs/aula20_basereact/projeto/src/components/H1/index.js
import React, { useContext } from 'react';
import { GlobalContext } from '../../contexts/App';
// eslint-disable-next-line
export const H1 = () => {
const theContext = useContext(GlobalContext);
console.log(theContext);
const { contextState } = theContext;
return (
<h1>
{contextState.title} {contextState.counter}
</h1>
);
};
|
fquesnel/marathon
|
src/main/scala/mesosphere/marathon/util/Timeout.scala
|
package mesosphere.marathon
package util
import akka.actor.Scheduler
import mesosphere.util.DurationToHumanReadable
import akka.pattern.after
import scala.concurrent.duration.{Duration, FiniteDuration}
import scala.concurrent.{ExecutionContext, Future, blocking => blockingCall}
/**
* Function transformations to make a method timeout after a given duration.
*/
object Timeout {
/**
* Timeout a blocking call
* @param timeout The maximum duration the method may execute in
* @param name Name of the operation
* @param f The blocking call
* @param scheduler The akka scheduler
* @param ctx The execution context to execute 'f' in
* @tparam T The result type of 'f'
* @return The eventual result of calling 'f' or TimeoutException if it didn't complete in time.
*/
def blocking[T](timeout: FiniteDuration, name: Option[String] = None)(f: => T)(implicit
scheduler: Scheduler,
ctx: ExecutionContext): Future[T] =
apply(timeout, name)(Future(blockingCall(f))(ctx))(scheduler, ctx)
/**
* Timeout a non-blocking call.
* @param timeout The maximum duration the method may execute in
* @param name Name of the operation
* @param f The blocking call
* @param scheduler The akka scheduler
* @param ctx The execution context to execute 'f' in
* @tparam T The result type of 'f'
* @return The eventual result of calling 'f' or TimeoutException if it didn't complete
*/
def apply[T](timeout: Duration, name: Option[String] = None)(f: => Future[T])(implicit
scheduler: Scheduler,
ctx: ExecutionContext): Future[T] = {
require(timeout != Duration.Zero)
timeout match {
case duration: FiniteDuration =>
def t: Future[T] = after(duration, scheduler)(Future.failed(new TimeoutException(s"${name.getOrElse("None")} timed out after ${timeout.toHumanReadable}")))
Future.firstCompletedOf(Seq(f, t))
case _ => f
}
}
}
|
voltengine/volt
|
src/volt/gpu/d3d12/routine.hpp
|
<filename>src/volt/gpu/d3d12/routine.hpp
#pragma once
#include <volt/pch.hpp>
#include <volt/gpu/routine.hpp>
namespace volt::gpu::d3d12 {
template<command_types T>
class routine : public gpu::routine<T> {
public:
ID3D12GraphicsCommandList *command_list;
ID3D12CommandAllocator *allocator;
routine(std::shared_ptr<gpu::pool<T>> &&pool);
~routine();
void begin() override;
void end() override;
};
using rasterization_routine = routine<command_type::rasterization>;
using compute_routine = routine<command_type::compute>;
using copy_routine = routine<command_type::copy>;
}
|
hongtuan/datamonitor
|
app_server/controllers/datamgr.js
|
<filename>app_server/controllers/datamgr.js
var mongoose = require('mongoose');
var locDao = require('../../app_api/dao/locationdao.js');
//var ndDao = require('../../app_api/dao/nodedatadao.js');
var llDao = require('../../app_api/dao/locationlogdao.js');
module.exports.showNodeData = function(req, res) {
//console.log(req.body);
var lid = req.params.lid;
var nid = req.params.nid;
locDao.getDataAlertPolicy(lid,function(err,dataAlertPolicy){
if(err){
console.log(err);
res.status(406).json(err);
}
//console.log('showNodeData',lid,nid);
res.render('show_node_data',
{nid:nid,lid:lid,query:req.query,dap:dataAlertPolicy,
serverTimezoneOffset:req.app.locals.serverTimezoneOffset});
});
};
module.exports.synDataMgr = function(req, res) {
//console.log('In controllers:req.params.lid='+req.params.lid);
var lid = req.params.lid;
if (lid) {
llDao.getLocLogList(lid,llDao.logType.dataSync,300,function(err,dataSyncLogList){
res.render('syn_data_mgr', {
lid:lid,
isTaskRunning:req.app.locals.dataSyncTask[lid]?true:false,
dataSyncLogList:dataSyncLogList
});
});
}
};
module.exports.synDataLogGraph = function(req, res) {
//console.log('In controllers:req.params.lid='+req.params.lid);
var lid = req.params.lid;
if (lid) {
res.render('syn_data_log_graph', {lid:lid});
}
};
module.exports.inspectNode = function(req, res) {
//console.log('In controllers:req.params.lid='+req.params.lid);
var lid = req.params.lid;
llDao.getLocLogList(lid,llDao.logType.inspectNode,100,function(err,logList){
if(err){
console.error(err);
res.status(500).json(err);
}
res.render('inspect_node', {
lid:lid,
logList:logList
});
});
};
module.exports.showDataTime = function(req, res) {
//console.log('In controllers:req.params.lid='+req.params.lid);
res.render('nodes_data_time', {});
};
module.exports.showNodeDataDashboard = function(req, res) {
//console.log('In controllers:req.params.lid='+req.params.lid);
res.render('nd_dashboard', {});
};
module.exports.showAllData = function(req, res) {
//console.log('In controllers:req.params.lid='+req.params.lid);
var lid = req.params.lid;
//locDao.getDataAlertPolicy(lid,function(err,dataAlertPolicy){
locDao.getNodesInfoInLocation(lid,function(err,nodesInfo){
if(err){
console.log(err);
res.status(406).json(err);
return;
}
//var insta
var installedNodes = [];
for(var pid in nodesInfo.pidNodeMap){
var node = nodesInfo.pidNodeMap[pid];
if(node.nid && node.nid.length > 0){
installedNodes.push({ptag:node.ptag,pid:pid});//[pid] = node;
}
}
//sort installedNodes by ptag
installedNodes.sort(function (a, b) {
if (a.ptag > b.ptag) {
return 1;
}
if (a.ptag < b.ptag) {
return -1;
}
// a 必须等于 b
return 0;
});
//add newline here.
for(var i=0;i<installedNodes.length-1;i++){
var node = installedNodes[i],nextNode = installedNodes[i+1];
if(node.ptag.charAt(0)!=nextNode.ptag.charAt(0)){
node['newline'] = true;
}
}
res.render('nd_alldata', {lid:lid,query:req.query,dap:nodesInfo.dap,
installedNodes:installedNodes,
serverTimezoneOffset:req.app.locals.serverTimezoneOffset});
});
};
module.exports.showNodeAvgData = function(req, res) {
//console.log(req.body);
var lid = req.params.lid;
var nid = req.params.nid;
locDao.getDataAlertPolicy(lid,function(err,dataAlertPolicy){
if(err){
console.log(err);
res.status(406).json(err);
return;
}
var dapExt = [{name:'DC',desc:'dataCount'},...dataAlertPolicy];
res.render('node_avg_data',
{nid:nid,lid:lid,query:req.query,dap:dapExt,
serverTimezoneOffset:req.app.locals.serverTimezoneOffset});
});
};
module.exports.showAllDataAvg = function(req, res) {
//console.log('In controllers:req.params.lid='+req.params.lid);
var lid = req.params.lid;
//locDao.getDataAlertPolicy(lid,function(err,dataAlertPolicy){
locDao.getNodesInfoInLocation(lid,function(err,nodesInfo){
if(err){
console.log(err);
res.status(406).json(err);
return;
}
//var insta
var installedNodes = [];
for(var pid in nodesInfo.pidNodeMap){
var node = nodesInfo.pidNodeMap[pid];
if(node.nid && node.nid.length > 0){
installedNodes.push({ptag:node.ptag,pid:pid});//[pid] = node;
}
}
//sort installedNodes by ptag
installedNodes.sort(function (a, b) {
if (a.ptag > b.ptag) {
return 1;
}
if (a.ptag < b.ptag) {
return -1;
}
// a 必须等于 b
return 0;
});
//add newline here.
for(var i=0;i<installedNodes.length-1;i++){
var node = installedNodes[i],nextNode = installedNodes[i+1];
if(node.ptag.charAt(0)!=nextNode.ptag.charAt(0)){
node['newline'] = true;
}
}
var dapExt = [{name:'DC',desc:'dataCount'},...nodesInfo.dap];
res.render('nd_alldata_avg', {lid:lid,query:req.query,dap:dapExt,
installedNodes:installedNodes,
serverTimezoneOffset:req.app.locals.serverTimezoneOffset});
});
};
|
Sanmopre/Sea_Conquest
|
Project II Game/Motor2D/j1DialogSystem.cpp
|
<reponame>Sanmopre/Sea_Conquest
#include "j1App.h"
#include "j1GUIElements.h"
#include "j1Audio.h"
#include "j1Input.h"
#include "j1GUI.h"
#include "j1Textures.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1Player.h"
#include "j1DialogSystem.h"
j1DialogSystem::j1DialogSystem()
{
}
j1DialogSystem::~j1DialogSystem()
{
}
bool j1DialogSystem::Awake(pugi::xml_node& config)
{
return true;
}
bool j1DialogSystem::Start()
{
pirate.Label = App->gui->AddElement(GUItype::GUI_LABEL, nullptr, { 1040,450 }, { 0,0 }, true, false, { 0,0,40,40 }, "YOU ARE NOT PREPARED!!", this, false, false, SCROLL_TYPE::SCROLL_NONE, true);
pirate.Image = App->gui->AddElement(GUItype::GUI_IMAGE, nullptr, { 950,420 }, { 0,0 }, true, false, { 0, 0,300,80 }, "", this, false, false, SCROLL_TYPE::SCROLL_NONE, true, TEXTURE::DIALOG);
pirate_fun.Label = App->gui->AddElement(GUItype::GUI_LABEL, nullptr, { 1040,450 }, { 0,0 }, true, false, { 0,0,40,40 }, "THIS WILL BE FUN!!", this, false, false, SCROLL_TYPE::SCROLL_NONE, true);
pirate_fun.Image = App->gui->AddElement(GUItype::GUI_IMAGE, nullptr, { 950,420 }, { 0,0 }, true, false, { 0, 0,300,80 }, "", this, false, false, SCROLL_TYPE::SCROLL_NONE, true, TEXTURE::DIALOG);
no.Label = App->gui->AddElement(GUItype::GUI_LABEL, nullptr, { 1040,450 }, { 0,0 }, true, false, { 0,0,40,40 }, "NOOOOOO!!", this, false, false, SCROLL_TYPE::SCROLL_NONE, true);
no.Image = App->gui->AddElement(GUItype::GUI_IMAGE, nullptr, { 950,420 }, { 0,0 }, true, false, { 0, 0,300,80 }, "", this, false, false, SCROLL_TYPE::SCROLL_NONE, true, TEXTURE::DIALOG);
arrogance.Label = App->gui->AddElement(GUItype::GUI_LABEL, nullptr, { 1040,450 }, { 0,0 }, true, false, { 0,0,40,40 }, "SUCH ARROGANCE!", this, false, false, SCROLL_TYPE::SCROLL_NONE, true);
arrogance.Image = App->gui->AddElement(GUItype::GUI_IMAGE, nullptr, { 950,420 }, { 0,0 }, true, false, { 0, 0,300,80 }, "", this, false, false, SCROLL_TYPE::SCROLL_NONE, true, TEXTURE::DIALOG);
haha.Label = App->gui->AddElement(GUItype::GUI_LABEL, nullptr, { 1040,450 }, { 0,0 }, true, false, { 0,0,40,40 }, "HAHAHAHA!!", this, false, false, SCROLL_TYPE::SCROLL_NONE, true);
haha.Image = App->gui->AddElement(GUItype::GUI_IMAGE, nullptr, { 950,420 }, { 0,0 }, true, false, { 0, 0,300,80 }, "", this, false, false, SCROLL_TYPE::SCROLL_NONE, true, TEXTURE::DIALOG);
return true;
}
bool j1DialogSystem::Update(float dt)
{
if (App->input->GetKey(SDL_SCANCODE_9) == KEY_DOWN && show_dialog == false)
{
Display_Dialog(Dialog::PIRATE);
}
if (App->input->GetKey(SDL_SCANCODE_8) == KEY_DOWN && show_dialog == false)
{
Display_Dialog(Dialog::FUN);
}
if (App->input->GetKey(SDL_SCANCODE_7) == KEY_DOWN && show_dialog == false)
{
Display_Dialog(Dialog::ARROGANCE);
}
if (App->input->GetKey(SDL_SCANCODE_6) == KEY_DOWN && show_dialog == false)
{
Display_Dialog(Dialog::HAHA);
}
if (App->input->GetKey(SDL_SCANCODE_5) == KEY_DOWN && show_dialog == false)
{
Display_Dialog(Dialog::NO);
}
timer.counter += dt;
if (timer.counter >= timer.iterations) {
show_dialog = false;
in_timer = false;
}
else {
in_timer = true;
}
if (show_dialog == false)
Hide_Dialogs();
return true;
}
void j1DialogSystem::Display_Dialog(Dialog dialog)
{
timer.counter = 0;
switch (dialog) {
case Dialog::NONE:
break;
case Dialog::PIRATE:
App->audio->PlayFx(App->audio->you_are_not_prepared, 0);
pirate.Image->enabled = true;
pirate.Label->enabled = true;
Display_timer = 4.0f;
timer.iterations = Display_timer;
show_dialog = true;
break;
case Dialog::FUN:
App->audio->PlayFx(App->audio->this_will_be_fun, 0);
pirate_fun.Image->enabled = true;
pirate_fun.Label->enabled = true;
Display_timer = 2.8f;
timer.iterations = Display_timer;
show_dialog = true;
break;
case Dialog::HAHA:
App->audio->PlayFx(App->audio->ha, 0);
haha.Image->enabled = true;
haha.Label->enabled = true;
Display_timer = 3.8f;
timer.iterations = Display_timer;
show_dialog = true;
break;
case Dialog::ARROGANCE:
App->audio->PlayFx(App->audio->such_arrogance, 0);
arrogance.Image->enabled = true;
arrogance.Label->enabled = true;
Display_timer = 3.8f;
timer.iterations = Display_timer;
show_dialog = true;
break;
case Dialog::NO:
App->audio->PlayFx(App->audio->no, 0);
no.Image->enabled = true;
no.Label->enabled = true;
Display_timer = 3.0f;
timer.iterations = Display_timer;
show_dialog = true;
break;
}
}
void j1DialogSystem::Hide_Dialogs()
{
pirate.Image->enabled = false;
pirate.Label->enabled = false;
pirate_fun.Image->enabled = false;
pirate_fun.Label->enabled = false;
haha.Image->enabled = false;
haha.Label->enabled = false;
no.Image->enabled = false;
no.Label->enabled = false;
arrogance.Image->enabled = false;
arrogance.Label->enabled = false;
}
|
klmchp/incubator-nuttx
|
sched/pthread/pthread_condclockwait.c
|
/****************************************************************************
* sched/pthread/pthread_condclockwait.c
*
* 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <nuttx/compiler.h>
#include <stdint.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#include <time.h>
#include <errno.h>
#include <assert.h>
#include <debug.h>
#include <nuttx/irq.h>
#include <nuttx/wdog.h>
#include <nuttx/signal.h>
#include <nuttx/cancelpt.h>
#include "sched/sched.h"
#include "pthread/pthread.h"
#include "clock/clock.h"
#include "signal/signal.h"
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: pthread_cond_clockwait
*
* Description:
* A thread can perform a timed wait on a condition variable.
*
* Input Parameters:
* cond - the condition variable to wait on
* mutex - the mutex that protects the condition variable
* clockid - The timing source to use in the conversion
* abstime - wait until this absolute time
*
* Returned Value:
* OK (0) on success; A non-zero errno value is returned on failure.
*
* Assumptions:
* Timing is of resolution 1 msec, with +/-1 millisecond accuracy.
*
****************************************************************************/
int pthread_cond_clockwait(FAR pthread_cond_t *cond,
FAR pthread_mutex_t *mutex,
clockid_t clockid,
FAR const struct timespec *abstime)
{
irqstate_t flags;
int mypid = getpid();
int ret = OK;
int status;
sinfo("cond=0x%p mutex=0x%p abstime=0x%p\n", cond, mutex, abstime);
/* pthread_cond_clockwait() is a cancellation point */
enter_cancellation_point();
/* Make sure that non-NULL references were provided. */
if (!cond || !mutex)
{
ret = EINVAL;
}
/* Make sure that the caller holds the mutex */
else if (mutex->pid != mypid)
{
ret = EPERM;
}
/* If no wait time is provided, this function degenerates to
* the same behavior as pthread_cond_wait().
*/
else if (!abstime)
{
ret = pthread_cond_wait(cond, mutex);
}
else
{
#ifndef CONFIG_PTHREAD_MUTEX_UNSAFE
uint8_t mflags;
#endif
#ifdef CONFIG_PTHREAD_MUTEX_TYPES
uint8_t type;
int16_t nlocks;
#endif
sinfo("Give up mutex...\n");
/* We must disable pre-emption and interrupts here so that
* the time stays valid until the wait begins. This adds
* complexity because we assure that interrupts and
* pre-emption are re-enabled correctly.
*/
sched_lock();
flags = enter_critical_section();
/* Give up the mutex */
mutex->pid = INVALID_PROCESS_ID;
#ifndef CONFIG_PTHREAD_MUTEX_UNSAFE
mflags = mutex->flags;
#endif
#ifdef CONFIG_PTHREAD_MUTEX_TYPES
type = mutex->type;
nlocks = mutex->nlocks;
#endif
ret = pthread_mutex_give(mutex);
if (ret == 0)
{
status = nxsem_clockwait_uninterruptible(
&cond->sem, clockid, abstime);
if (status < 0)
{
ret = -status;
}
}
/* Restore interrupts (pre-emption will be enabled
* when we fall through the if/then/else)
*/
leave_critical_section(flags);
/* Reacquire the mutex (retaining the ret). */
sinfo("Re-locking...\n");
status = pthread_mutex_take(mutex, NULL, false);
if (status == OK)
{
mutex->pid = mypid;
#ifndef CONFIG_PTHREAD_MUTEX_UNSAFE
mutex->flags = mflags;
#endif
#ifdef CONFIG_PTHREAD_MUTEX_TYPES
mutex->type = type;
mutex->nlocks = nlocks;
#endif
}
else if (ret == 0)
{
ret = status;
}
/* Re-enable pre-emption (It is expected that interrupts
* have already been re-enabled in the above logic)
*/
sched_unlock();
}
leave_cancellation_point();
sinfo("Returning %d\n", ret);
return ret;
}
|
clickpaas/clickpaas-operator
|
pkg/controller/middleware/mongo/event.go
|
package mongo
const (
MongoEventReasonOnAdded = "mongoAdded"
MongoEventReasonOnDelete = "mongoDelete"
MongoEventReasonOnUpdate = "mongoUpdate"
)
|
WasmVM/wass
|
src/lib/parser/_Abbreviated.hpp
|
<reponame>WasmVM/wass
#ifndef GUARD_wass_parser__Abbreviated
#define GUARD_wass_parser__Abbreviated
#include <optional>
#include <string>
#include <utility>
#include <parser/ParserContext.hpp>
class AbbrImport: public std::optional<std::pair<std::string, std::string>>{
public:
AbbrImport(ParserContext& context);
};
class AbbrExport: public std::optional<std::string>{
public:
AbbrExport(ParserContext& context);
};
#endif
|
SayanGhoshBDA/code-backup
|
python/coursera_python/FUND_OF_COMP_RICE/FUND_OF_COMPUTING_RICE2/week1/iter_lists.py
|
def square_list1(numbers):
"""Returns a list of the squares of the numbers in the input."""
result = []
for n in numbers:
result.append(n ** 2)
return result
def square_list2(numbers):
"""Returns a list of the squares of the numbers in the input."""
return [n ** 2 for n in numbers]
print square_list1([4, 5, -2])
print square_list2([4, 5, -2])
def is_in_range(ball):
"""Returns whether the ball is in the desired range. """
return ball[0] >= 0 and ball[0] <= 100 and ball[1] >= 0 and ball[1] <= 100
def balls_in_range1(balls):
"""Returns a list of those input balls that are within the desired range."""
result = []
for ball in balls:
if is_in_range(ball):
result.append(ball)
return result
def balls_in_range2(balls):
return [ball for ball in balls if is_in_range(ball)]
print balls_in_range1([[-5,40], [30,20], [70,140], [60,50]])
print balls_in_range2([[-5,40], [30,20], [70,140], [60,50]])
|
RubenFern/Photodir-Front-React-PFM
|
src/components/app/public/PhotoUserPage.js
|
<gh_stars>1-10
import React, { useEffect, useRef } from 'react';
import { useParams } from 'react-router';
import { useHistory } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { NavBar } from '../../layout/NavBar';
import { Photo } from './Photo/Photo';
import { getUser } from '../../redux/actions/explore';
import { PrivateProfile } from './PrivateProfile';
import './../auth/PhotoItem.css';
export const PhotoUserPage = () =>
{
// Monto el componente. Si al entrar en la página se monta y seguidameete se desmonta el componete limpio el proceso
const mounted = useRef(true);
const history = useHistory();
const dispatch = useDispatch();
const { username, photo } = useParams();
const { private_profile } = useSelector(state => state.explore);
useEffect(() =>
{
if (mounted.current)
{
// Realizo las peticiones para obtener la información de usuario
dispatch(getUser(username, history));
}
// Desmonto el componente al salir
return () =>
{
mounted.current = false;
}
}, [dispatch, history, username]);
return (
<>
<NavBar />
{ (private_profile)
?
<PrivateProfile />
:
<div className="container">
<Photo user_name={username} photo={photo} />
</div> }
</>
)
}
|
AP-Atul/music_player_lite
|
src/app/src/main/java/com/atul/musicplayerlite/fragments/ArtistsFragment.java
|
<reponame>AP-Atul/music_player_lite
package com.atul.musicplayerlite.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.atul.musicplayerlite.R;
import com.atul.musicplayerlite.activities.SelectedArtistActivity;
import com.atul.musicplayerlite.adapter.ArtistAdapter;
import com.atul.musicplayerlite.helper.ListHelper;
import com.atul.musicplayerlite.listener.ArtistSelectListener;
import com.atul.musicplayerlite.model.Artist;
import com.atul.musicplayerlite.viewmodel.MainViewModel;
import com.atul.musicplayerlite.viewmodel.MainViewModelFactory;
import com.google.android.material.appbar.MaterialToolbar;
import java.util.ArrayList;
import java.util.List;
public class ArtistsFragment extends Fragment implements SearchView.OnQueryTextListener, ArtistSelectListener {
private final List<Artist> artistList = new ArrayList<>();
private MainViewModel viewModel;
private ArtistAdapter artistAdapter;
private List<Artist> unchangedList = new ArrayList<>();
private MaterialToolbar toolbar;
private SearchView searchView;
public ArtistsFragment() {
}
public static ArtistsFragment newInstance() {
return new ArtistsFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel = new ViewModelProvider(requireActivity(), new MainViewModelFactory(requireActivity())).get(MainViewModel.class);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_artists, container, false);
unchangedList = viewModel.getArtists(false);
artistList.clear();
artistList.addAll(unchangedList);
toolbar = view.findViewById(R.id.search_toolbar);
RecyclerView recyclerView = view.findViewById(R.id.artist_layout);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
artistAdapter = new ArtistAdapter(this, artistList);
recyclerView.setAdapter(artistAdapter);
setUpOptions();
return view;
}
private void setUpOptions() {
toolbar.setOnMenuItemClickListener(item -> {
int id = item.getItemId();
if (id == R.id.search) {
searchView = (SearchView) item.getActionView();
setUpSearchView();
return true;
} else if (id == R.id.menu_sort_asc) {
updateAdapter(ListHelper.sortArtistByName(artistList, false));
return true;
} else if (id == R.id.menu_sort_dec) {
updateAdapter(ListHelper.sortArtistByName(artistList, true));
return true;
} else if (id == R.id.menu_most_songs) {
updateAdapter(ListHelper.sortArtistBySongs(artistList, false));
return true;
} else if (id == R.id.menu_least_songs) {
updateAdapter(ListHelper.sortArtistBySongs(artistList, true));
return true;
} else if (id == R.id.menu_most_albums) {
updateAdapter(ListHelper.sortArtistByAlbums(artistList, false));
return true;
} else if (id == R.id.menu_least_albums) {
updateAdapter(ListHelper.sortArtistByAlbums(artistList, true));
return true;
}
return false;
});
toolbar.setNavigationOnClickListener(v -> {
if (searchView == null || searchView.isIconified())
requireActivity().finish();
});
}
private void setUpSearchView() {
searchView.setOnQueryTextListener(this);
}
@Override
public boolean onQueryTextSubmit(String query) {
updateAdapter(ListHelper.searchArtistByName(unchangedList, query.toLowerCase()));
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
updateAdapter(ListHelper.searchArtistByName(unchangedList, newText.toLowerCase()));
return true;
}
private void updateAdapter(List<Artist> list) {
artistList.clear();
artistList.addAll(list);
artistAdapter.notifyDataSetChanged();
}
@Override
public void selectedArtist(Artist artist) {
requireActivity().startActivity(new Intent(
getActivity(), SelectedArtistActivity.class
).putExtra("artist", artist));
}
}
|
Xecutor/zorroeditor
|
deps/glider/ui/Label.cpp
|
#include "Label.hpp"
#include "GLState.hpp"
#include "UIConfig.hpp"
namespace glider{
namespace ui{
Label::Label(const char* argCaption, const char* argName)
{
drawShadow=false;
caption.assignFont(uiConfig.getLabelFont());
caption.setColor(uiConfig.getColor("labelTextColor"));
captionShadow.assignFont(uiConfig.getLabelFont());
captionShadow.setPosition(Pos(1,1));
captionShadow.setColor(uiConfig.getColor("labelShadowColor"));
if(argCaption)
{
setCaption(argCaption);
}
if(argName)
{
setName(argName);
}
}
void Label::draw()
{
RelOffsetGuard rog(pos);
if(drawShadow)
{
captionShadow.draw();
}
caption.draw();
}
}
}
|
raymondmutebi/aapu
|
src/main/java/org/pahappa/systems/core/services/GeneralSearchUtils.java
|
/**
*
*/
package org.pahappa.systems.core.services;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.sers.webutils.model.RecordStatus;
import org.sers.webutils.model.security.User;
import org.sers.webutils.model.utils.SearchField;
import com.googlecode.genericdao.search.Filter;
import com.googlecode.genericdao.search.Search;
/**
* Contains the general search utility/helper functions used to query models
* from the DB.
*
* @author <NAME>.
*
*/
public class GeneralSearchUtils {
private static final int MINIMUM_CHARACTERS_FOR_SEARCH_TERM = 1;
public static boolean searchTermSatisfiesQueryCriteria(String query) {
if (StringUtils.isBlank(query)) {
return false;
}
return query.length() >= MINIMUM_CHARACTERS_FOR_SEARCH_TERM;
}
public static boolean generateSearchTerms(List<SearchField> searchFields, String query, List<Filter> filters) {
if (searchFields != null && !searchFields.isEmpty()) {
for (String token : query.replaceAll(" ", " ").split(" ")) {
String searchTerm = "%" + StringEscapeUtils(token) + "%";
Filter[] orFilters = new Filter[searchFields.size()];
int counter = 0;
for (SearchField searchField : searchFields) {
orFilters[counter] = Filter.like(searchField.getPath(), searchTerm);
counter++;
}
filters.add(Filter.or(orFilters));
}
return true;
}
return false;
}
public static boolean generateSearchTerms(String commaSeparatedsearchFields, String query, List<Filter> filters) {
if (StringUtils.isBlank(commaSeparatedsearchFields)) {
return false;
}
List<String> searchFields = Arrays.asList(commaSeparatedsearchFields.split(","));
if (searchFields != null && !searchFields.isEmpty()) {
for (String token : query.replaceAll(" ", " ").split(" ")) {
String searchTerm = "%" + StringEscapeUtils(token) + "%";
Filter[] orFilters = new Filter[searchFields.size()];
int counter = 0;
for (String searchField : searchFields) {
orFilters[counter] = Filter.like(searchField, searchTerm);
counter++;
}
filters.add(Filter.or(orFilters));
}
return true;
}
return false;
}
public static Search composeUsersSearch(List<SearchField> searchFields, String query) {
Search search = new Search();
search.addFilterEqual("recordStatus", RecordStatus.ACTIVE);
search.addSortAsc("username");
search.addFilterNotIn("username", User.DEFAULT_ADMIN);
if (StringUtils.isNotBlank(query) && GeneralSearchUtils.searchTermSatisfiesQueryCriteria(query)) {
ArrayList<Filter> filters = new ArrayList<Filter>();
GeneralSearchUtils.generateSearchTerms(searchFields, query, filters);
search.addFilterAnd(filters.toArray(new Filter[filters.size()]));
}
return search;
}
private static String StringEscapeUtils(String token) {
if (token == null) {
return null;
}
return StringUtils.replace(token, "'", "''");
}
}
|
gilbertwang1981/feign
|
gson/src/main/java/feign/gson/GsonDecoder.java
|
/**
* Copyright 2012-2021 The Feign 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 feign.gson;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.TypeAdapter;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.Collections;
import feign.Response;
import feign.codec.Decoder;
import static feign.Util.UTF_8;
import static feign.Util.ensureClosed;
public class GsonDecoder implements Decoder {
private final Gson gson;
public GsonDecoder(Iterable<TypeAdapter<?>> adapters) {
this(GsonFactory.create(adapters));
}
public GsonDecoder() {
this(Collections.<TypeAdapter<?>>emptyList());
}
public GsonDecoder(Gson gson) {
this.gson = gson;
}
@Override
public Object decode(Response response, Type type) throws IOException {
if (response.body() == null)
return null;
Reader reader = response.body().asReader(UTF_8);
try {
return gson.fromJson(reader, type);
} catch (JsonIOException e) {
if (e.getCause() != null && e.getCause() instanceof IOException) {
throw IOException.class.cast(e.getCause());
}
throw e;
} finally {
ensureClosed(reader);
}
}
}
|
xmos-jmccarthy/xcore_sdk
|
examples/freertos/person_detection/app/main.c
|
<filename>examples/freertos/person_detection/app/main.c<gh_stars>0
// Copyright 2020-2021 XMOS LIMITED.
// This Software is subject to the terms of the XMOS Public Licence: Version 1.
/* System headers */
#include <platform.h>
#include <xs1.h>
/* FreeRTOS headers */
#include "FreeRTOS.h"
#include "queue.h"
/* Library headers */
#include "rtos/drivers/intertile/api/rtos_intertile.h"
#include "rtos/drivers/gpio/api/rtos_gpio.h"
#include "rtos/drivers/spi/api/rtos_spi_master.h"
#include "rtos/drivers/i2c/api/rtos_i2c_master.h"
/* App headers */
#include "app_conf.h"
#include "board_init.h"
#include "spi_camera.h"
#include "person_detect_task.h"
#if ON_TILE(0)
static rtos_i2c_master_t i2c_master_ctx_s;
static rtos_spi_master_t spi_master_ctx_s;
static rtos_spi_master_device_t ov_device_ctx_s;
static rtos_gpio_t gpio_ctx_s;
static rtos_i2c_master_t *i2c_master_ctx = &i2c_master_ctx_s;
static rtos_spi_master_t *spi_master_ctx = &spi_master_ctx_s;
static rtos_spi_master_device_t *ov_device_ctx = &ov_device_ctx_s;
static rtos_gpio_t *gpio_ctx = &gpio_ctx_s;
#endif
static rtos_intertile_t intertile_ctx_s;
static rtos_intertile_t *intertile_ctx = &intertile_ctx_s;
static rtos_intertile_address_t person_detect_addr_s;
static rtos_intertile_address_t *person_detect_addr = &person_detect_addr_s;
void vApplicationMallocFailedHook( void )
{
rtos_printf("Malloc Failed on tile %d!\n", THIS_XCORE_TILE);
for(;;);
}
void vApplicationStackOverflowHook( TaskHandle_t pxTask, char* pcTaskName )
{
rtos_printf("\nStack Overflow!!! %d %s!\n", THIS_XCORE_TILE, pcTaskName);
configASSERT(0);
}
void vApplicationCoreInitHook(BaseType_t xCoreID)
{
#if ON_TILE(0)
rtos_printf("Initializing tile 0, core %d on core %d\n", xCoreID, portGET_CORE_ID());
#endif
#if ON_TILE(1)
rtos_printf("Initializing tile 1 core %d on core %d\n", xCoreID, portGET_CORE_ID());
#endif
}
void vApplicationDaemonTaskStartup(void *arg)
{
rtos_printf("Startup task running from tile %d on core %d\n", THIS_XCORE_TILE, portGET_CORE_ID());
rtos_intertile_start(
intertile_ctx);
person_detect_addr->intertile_ctx = intertile_ctx;
person_detect_addr->port = PERSON_DETECT_PORT;
#if ON_TILE(0)
{
rtos_printf("Starting GPIO driver\n");
rtos_gpio_start(gpio_ctx);
rtos_printf("Starting SPI driver\n");
rtos_spi_master_start(spi_master_ctx, configMAX_PRIORITIES-1);
rtos_printf("Starting i2c driver\n");
rtos_i2c_master_start(i2c_master_ctx);
QueueHandle_t qcam2ai = xQueueCreate( 1, sizeof( uint8_t* ) );
if( create_spi_camera_to_queue( ov_device_ctx, i2c_master_ctx, appconfSPI_CAMERA_TASK_PRIORITY, qcam2ai )
== pdTRUE )
{
rtos_printf("Starting person detect app task\n");
person_detect_app_task_create(person_detect_addr, gpio_ctx, appconfPERSON_DETECT_TASK_PRIORITY, qcam2ai);
}
else
{
debug_printf("Camera setup failed...\n");
}
}
#endif
#if ON_TILE(1)
{
rtos_printf("Starting model runner task\n");
person_detect_model_runner_task_create(person_detect_addr, appconfPERSON_DETECT_TASK_PRIORITY);
}
#endif
vTaskDelete(NULL);
}
#if ON_TILE(0)
void main_tile0(chanend_t c0, chanend_t c1, chanend_t c2, chanend_t c3)
{
(void) c0;
board_tile0_init(c1, intertile_ctx, i2c_master_ctx, spi_master_ctx, ov_device_ctx, gpio_ctx);
(void) c2;
(void) c3;
xTaskCreate((TaskFunction_t) vApplicationDaemonTaskStartup,
"vApplicationDaemonTaskStartup",
RTOS_THREAD_STACK_SIZE(vApplicationDaemonTaskStartup),
NULL,
appconfSTARTUP_TASK_PRIORITY,
NULL);
rtos_printf("start scheduler on tile 0\n");
vTaskStartScheduler();
return;
}
/* Workaround.
* extmem builds will fail to load since tile 1 was not given control in the tile 0 build
* TODO: Find a better solution
*/
#if USE_EXTMEM
__attribute__((section(".ExtMem_code")))
void main_tile1(chanend_t c0, chanend_t c1, chanend_t c2, chanend_t c3)
{
return;
}
#endif
#endif
#if ON_TILE(1)
void main_tile1(chanend_t c0, chanend_t c1, chanend_t c2, chanend_t c3)
{
board_tile1_init(c0, intertile_ctx);
(void) c1;
(void) c2;
(void) c3;
xTaskCreate((TaskFunction_t) vApplicationDaemonTaskStartup,
"vApplicationDaemonTaskStartup",
RTOS_THREAD_STACK_SIZE(vApplicationDaemonTaskStartup),
NULL,
appconfSTARTUP_TASK_PRIORITY,
NULL);
rtos_printf("start scheduler on tile 1\n");
vTaskStartScheduler();
return;
}
#endif
|
jbolda/finatr
|
src/elements/Header.js
|
import React from 'react';
import { NavLink } from 'react-router-dom';
import { MenuIcon, XIcon } from '@heroicons/react/outline';
import { Disclosure } from '@headlessui/react';
const navigation = [
{ name: 'Home', to: '/', end: true },
{ name: 'Examples', to: 'examples' },
{ name: 'Import/Export', to: 'import' },
{ name: 'Planning', to: 'planning' },
{ name: 'Cash Flow', to: 'flow' },
{ name: 'Account Breakdowns', to: 'accounts' },
{ name: 'Taxes (in alpha)', to: 'taxes' }
];
export const Header = () => {
return (
<Disclosure
as="nav"
className="bg-gray-50 shadow-sm"
data-tauri-drag-region="true"
>
{({ open }) => (
<>
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between h-16">
<div className="flex">
{/* for a logo whenever we reach that point
<div className="flex-shrink-0 flex items-center">
<img
className="block lg:hidden h-8 w-auto"
src=""
alt="finatr"
/>
<img
className="hidden lg:block h-8 w-auto"
src=""
alt="finatr"
/>
</div> */}
<div className="hidden sm:-my-px sm:ml-6 sm:flex sm:space-x-8">
{navigation.map((item) => (
<NavLink
key={item.to}
to={item.to}
activeClassName="inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium border-indigo-500 text-gray-900"
className="inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
end={item.end}
>
{item.name}
</NavLink>
))}
</div>
</div>
<div className="-mr-2 flex items-center sm:hidden">
<Disclosure.Button className="bg-white inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
<span className="sr-only">Open main menu</span>
{open ? (
<XIcon className="block h-6 w-6" aria-hidden="true" />
) : (
<MenuIcon className="block h-6 w-6" aria-hidden="true" />
)}
</Disclosure.Button>
</div>
</div>
</div>
<Disclosure.Panel className="sm:hidden">
<div className="pt-2 pb-3 space-y-1">
{navigation.map((item) => (
<NavLink
key={item.to}
to={item.to}
activeClassName="inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium border-indigo-500 text-gray-900"
className="inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
end={item.end}
>
{item.name}
</NavLink>
))}
</div>
</Disclosure.Panel>
</>
)}
</Disclosure>
);
};
|
embergardens/ember-gardens-com
|
src/templates/posts/index.js
|
import React from "react"
import Seo from '../../components/layout/Seo'
const Post = ({ pageContext }) => {
const post = pageContext.post
return (
<>
<Seo title={post.title} />
<h1>
{post.title}
</h1>
<div dangerouslySetInnerHTML={{__html: post.content}} />
</>
)
}
export default Post
|
CoprHD/sds-controller
|
apisvc/src/main/java/com/emc/storageos/api/service/impl/resource/utils/AsynchJobExecutorService.java
|
/*
* Copyright (c) 2012 EMC Corporation
* All Rights Reserved
*/
package com.emc.storageos.api.service.impl.resource.utils;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.emc.storageos.services.util.NamedScheduledThreadPoolExecutor;
public class AsynchJobExecutorService {
private int _asynchJobThreads;
public ScheduledExecutorService _workerThreads;
final private Logger _logger = LoggerFactory.getLogger(AsynchJobExecutorService.class);
public void setAsynchJobThreads(int n_threads) {
_asynchJobThreads = n_threads;
}
public int getAsynchJobThreads() {
return _asynchJobThreads;
}
public void start() {
_workerThreads = new NamedScheduledThreadPoolExecutor(AsynchJobExecutorService.class.getSimpleName(), _asynchJobThreads);
}
public ScheduledExecutorService getExecutorService() {
return _workerThreads;
}
public void stop() {
try {
_workerThreads.shutdown();
_workerThreads.awaitTermination(120, TimeUnit.SECONDS);
} catch (Exception e) {
_logger.error("TimeOut occured after waiting Client Threads to finish");
}
}
}
|
denfromufa/ironpython-stubs
|
stubs.min/Autodesk/Revit/DB/__init___parts/ParameterFilterUtilities.py
|
class ParameterFilterUtilities(object):
"""
Contains static utility functions for enumerating the categories and parameters that
are available for use by ParameterFilterElement objects.
"""
@staticmethod
def GetAllFilterableCategories():
"""
GetAllFilterableCategories() -> ICollection[ElementId]
Returns the set of categories that may be used in a ParameterFilterElement.
Returns: The set of all filterable categories.
"""
pass
@staticmethod
def GetFilterableParametersInCommon(aDoc,categories):
""" GetFilterableParametersInCommon(aDoc: Document,categories: ICollection[ElementId]) -> ICollection[ElementId] """
pass
@staticmethod
def GetInapplicableParameters(aDoc,categories,parameters):
""" GetInapplicableParameters(aDoc: Document,categories: ICollection[ElementId],parameters: IList[ElementId]) -> IList[ElementId] """
pass
@staticmethod
def IsParameterApplicable(element,parameter):
"""
IsParameterApplicable(element: Element,parameter: ElementId) -> bool
Used to determine whether the element supports the given parameter.
element: The element to query for support of the given parameter.
parameter: The parameter for which to query support.
Returns: True if the element supports the given parameter,false otherwise.
"""
pass
@staticmethod
def RemoveUnfilterableCategories(categories):
""" RemoveUnfilterableCategories(categories: ICollection[ElementId]) -> ICollection[ElementId] """
pass
__all__=[
'GetAllFilterableCategories',
'GetFilterableParametersInCommon',
'GetInapplicableParameters',
'IsParameterApplicable',
'RemoveUnfilterableCategories',
]
|
RyanJ93/lala.js
|
lib/Server/ServerProviderRepository.js
|
<filename>lib/Server/ServerProviderRepository.js
'use strict';
// Including Lala's modules.
const { Repository } = require('../Repository');
const {
InvalidArgumentException
} = require('../Exceptions');
/**
* Contains all the registered servers.
*/
class ServerProviderRepository extends Repository {
}
module.exports = ServerProviderRepository;
|
rura6502/repo.rura6502.github.io
|
Spring-boot Projects/tcp_to_websocket/src/main/java/io/github/rura6502/tcp_to_websocket/UdpHandler.java
|
<gh_stars>0
package io.github.rura6502.tcp_to_websocket;
import java.io.IOException;
import java.util.function.Consumer;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import lombok.RequiredArgsConstructor;
/**
* UdpHandler
*/
@RequiredArgsConstructor
public class UdpHandler
extends SimpleChannelInboundHandler<DatagramPacket> {
private final H264NALProcessor process;
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
// super.channelRead(ctx, msg);
ByteBuf buf = msg.content();
byte[] received = new byte[buf.readableBytes()];
buf.readBytes(received);
process.process(received);
// System.out.println("send bytes length : " + bytes.length);
// String getStr = buf.toString(Charset.forName("UTF8"));
// wsConf.getSessions().parallelStream().forEach(ws -> {
// try {
// ws.sendMessage(new TextMessage(getStr.getBytes()));
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// });
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// super.exceptionCaught(ctx, cause);
cause.printStackTrace();
ctx.close();
}
}
/**
* UdpHandler
*/
// @Component
// @RequiredArgsConstructor
// public class UdpHandler
// extends ChannelInboundHandlerAdapter {
// private final WebSocketConfiguration wsConf;
// // private final Consumer<byte[]> streamConsumer;
// @Override
// public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// // super.channelRead(ctx, msg);
// DatagramPacket packet = (DatagramPacket) msg;
// ByteBuf buf = packet.content();
// byte[] bytes = new byte[buf.readableBytes()];
// buf.readBytes(bytes);
// System.out.println("send bytes length : " + bytes.length);
// // wsConf.getSessions().parallelStream().forEach(session -> {
// // try {
// // session.sendMessage(new BinaryMessage(bytes));
// // } catch (IOException e) {
// // e.printStackTrace();
// // }
// // });
// // String getStr = buf.toString(Charset.forName("UTF8"));
// // wsConf.getSessions().parallelStream().forEach(ws -> {
// // try {
// // ws.sendMessage(new TextMessage(getStr.getBytes()));
// // } catch (IOException e) {
// // // TODO Auto-generated catch block
// // e.printStackTrace();
// // }
// // });
// }
// @Override
// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// // super.exceptionCaught(ctx, cause);
// cause.printStackTrace();
// ctx.close();
// }
// }
|
ducanhnguyen/cft4cpp-for-dummy
|
data-test/tsdv/Sample_for_R1_Static/Lib.cpp
|
<gh_stars>0
// Header file
#include "Lib.h"
int findMin(int a[], int n){
if (n <= 0)
throw std::exception();
int min = a[0];
for (int i = 1; i < n; i++)
if (a[i] < min)
min = a[i];
return min;
}
|
ampatspell/ember-cli-sketch
|
app/components/ui-block/sketch/stage/node/image/component.js
|
export { default } from 'ember-cli-sketch/components/ui-block/sketch/stage/node/image/component';
|
zzgchina888/msdn-code-gallery-microsoft
|
Official Windows Platform Sample/Windows 8.1 desktop samples/[C++]-Windows 8.1 desktop samples/Management Infrastructure API sample/C# and C++/Service/Provider/WindowsServiceManager.h
|
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
//
#include <MI.h>
MI_Result Invoke_GetWindowsServices(
_In_ MI_Context* context,
_In_opt_ const MSFT_WindowsServiceManager_GetWindowsServices* in);
|
lstumme/dashboard-mui
|
src/components/Sidebar/Sidebar.js
|
<filename>src/components/Sidebar/Sidebar.js<gh_stars>1-10
import React from 'react';
import { Link } from 'react-router-dom';
import clsx from 'clsx';
import { makeStyles } from '@material-ui/core/styles';
import {
Drawer,
Toolbar,
List,
ListItem,
ListItemText,
ListItemIcon
} from '@material-ui/core'
const drawerWidth = 240;
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
},
appBar: {
zIndex: theme.zIndex.drawer + 1,
},
drawer: {
width: drawerWidth,
flexShrink: 0,
whiteSpace: 'nowrap',
},
drawerPaper: {
width: drawerWidth,
},
// },
drawerOpen: {
width: drawerWidth,
transition: theme.transitions.create('width', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen,
}),
},
drawerClose: {
transition: theme.transitions.create('width', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
overflowX: 'hidden',
width: theme.spacing(7) + 1,
},
toolbar: {
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
padding: theme.spacing(0, 1),
// necessary for content to be below app bar
...theme.mixins.toolbar,
},
content: {
flexGrow: 1,
padding: theme.spacing(3),
},
}));
const Sidebar = (props) => {
const classes = useStyles();
const { state, routes } = props;
const [open, setOpen] = React.useState(true);
React.useEffect(() => {
setOpen(state);
}, [state]);
return (
<Drawer
variant="permanent"
className={clsx(classes.drawer, {
[classes.drawerOpen]: open,
[classes.drawerClose]: !open,
})}
classes={{
paper: clsx({
[classes.drawerOpen]: open,
[classes.drawerClose]: !open,
}),
}}>
<Toolbar />
<div>
<List>
{routes.map((route, index) => (
<Link to={route.path} style={{ textDecoration: 'none' }} key={route.name}>
<ListItem button key={route.name}>
<ListItemIcon>{route.icon}</ListItemIcon>
<ListItemText primary={route.name} />
</ListItem>
</Link>
))}
</List>
</div>
</Drawer>
);
};
export default Sidebar;
|
tormath1/jclouds
|
core/src/test/java/org/jclouds/util/Predicates2Test.java
|
<reponame>tormath1/jclouds
/*
* 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.jclouds.util;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.base.Stopwatch;
import com.google.common.base.Supplier;
import com.google.common.collect.Lists;
@Test(groups = "unit", singleThreaded = true)
public class Predicates2Test {
// Grace must be reasonably big; Thread.sleep can take a bit longer to wake up sometimes...
public static final int SLOW_BUILD_SERVER_GRACE = 250;
// Sometimes returns sooner than timer would predict (e.g. observed 2999ms, when expected 3000ms)
public static final int EARLY_RETURN_GRACE = 10;
private Stopwatch stopwatch;
@BeforeMethod
public void setUp() {
stopwatch = Stopwatch.createUnstarted();
}
@Test
void testRetryReturnsFalseOnIllegalStateExeception() {
ensureImmediateReturnFor(new IllegalStateException());
}
@Test
void testRetryReturnsFalseOnExecutionException() {
ensureImmediateReturnFor(new ExecutionException(new Exception("Simulated cause")));
}
@Test
void testRetryReturnsFalseOnTimeoutException() {
ensureImmediateReturnFor(new TimeoutException("Simulating exception"));
}
@Test(expectedExceptions = RuntimeException.class)
void testRetryPropagatesOnException() {
ensureImmediateReturnFor(new Exception("Simulating exception"));
}
private void ensureImmediateReturnFor(final Exception ex) {
Predicate<Supplier<String>> predicate = retry(
new Predicate<Supplier<String>>() {
public boolean apply(Supplier<String> input) {
return "goo".equals(input.get());
}
}, 3, 1, SECONDS);
stopwatch.start();
assertFalse(predicate.apply(new Supplier<String>() {
@Override
public String get() {
throw new RuntimeException(ex);
}
}));
long duration = stopwatch.elapsed(MILLISECONDS);
assertOrdered(duration, SLOW_BUILD_SERVER_GRACE);
}
@Test
void testRetryAlwaysFalseMillis() {
// maxWait=3; period=1; maxPeriod defaults to 1*10
// will call at 0, 1, 1+(1*1.5), 3
RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(Integer.MAX_VALUE);
Predicate<String> predicate = retry(rawPredicate, 3, 1, SECONDS);
stopwatch.start();
assertFalse(predicate.apply(""));
long duration = stopwatch.elapsed(MILLISECONDS);
assertOrdered(3000 - EARLY_RETURN_GRACE, duration, 3000 + SLOW_BUILD_SERVER_GRACE);
assertCallTimes(rawPredicate.callTimes, 0, 1000, 1000 + 1500, 3000);
}
@Test
void testRetryFirstTimeTrue() {
RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(1);
Predicate<String> predicate = retry(rawPredicate, 4, 1, SECONDS);
stopwatch.start();
assertTrue(predicate.apply(""));
long duration = stopwatch.elapsed(MILLISECONDS);
assertOrdered(0, duration, 0 + SLOW_BUILD_SERVER_GRACE);
assertCallTimes(rawPredicate.callTimes, 0);
}
@Test
void testRetryWillRunOnceOnNegativeTimeout() {
RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(1);
Predicate<String> predicate = retry(rawPredicate, -1, 1, SECONDS);
stopwatch.start();
assertTrue(predicate.apply(""));
long duration = stopwatch.elapsed(MILLISECONDS);
assertOrdered(0, duration, 0 + SLOW_BUILD_SERVER_GRACE);
assertCallTimes(rawPredicate.callTimes, 0);
}
@Test
void testRetryThirdTimeTrue() {
// maxWait=4; period=1; maxPeriod defaults to 1*10
// will call at 0, 1, 1+(1*1.5)
RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(3);
Predicate<String> predicate = retry(rawPredicate, 4, 1, SECONDS);
stopwatch.start();
assertTrue(predicate.apply(""));
long duration = stopwatch.elapsed(MILLISECONDS);
assertOrdered(2500 - EARLY_RETURN_GRACE, duration, 2500 + SLOW_BUILD_SERVER_GRACE);
assertCallTimes(rawPredicate.callTimes, 0, 1000, 1000 + 1500);
}
@Test
void testRetryThirdTimeTrueLimitedMaxInterval() {
// maxWait=3; period=1; maxPeriod=1
// will call at 0, 1, 1+1
RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(3);
Predicate<String> predicate = retry(rawPredicate, 3, 1, 1, SECONDS);
stopwatch.start();
assertTrue(predicate.apply(""));
long duration = stopwatch.elapsed(MILLISECONDS);
assertOrdered(2000 - EARLY_RETURN_GRACE, duration, 2000 + SLOW_BUILD_SERVER_GRACE);
assertCallTimes(rawPredicate.callTimes, 0, 1000, 2000);
}
public static class RepeatedAttemptsPredicate implements Predicate<String> {
final List<Long> callTimes = Lists.newArrayList();
private final int succeedOnAttempt;
private final Stopwatch stopwatch;
private int count = 0;
RepeatedAttemptsPredicate(int succeedOnAttempt) {
this.succeedOnAttempt = succeedOnAttempt;
this.stopwatch = Stopwatch.createUnstarted();
stopwatch.start();
}
@Override
public boolean apply(String input) {
callTimes.add(stopwatch.elapsed(MILLISECONDS));
return ++count == succeedOnAttempt;
}
}
@Test(enabled = false) // not a test, but picked up as such because public
public static void assertCallTimes(List<Long> actual, Integer... expected) {
Assert.assertEquals(actual.size(), expected.length, "actual=" + actual);
for (int i = 0; i < expected.length; i++) {
long callTime = actual.get(i);
assertOrdered(expected[i] - EARLY_RETURN_GRACE, callTime, expected[i] + SLOW_BUILD_SERVER_GRACE);
}
}
private static void assertOrdered(long... values) {
long prevVal = values[0];
for (long val : values) {
if (val < prevVal) {
fail(String.format("%s should be ordered", Arrays.toString(values)));
}
}
}
}
|
alaurent4/nighres
|
cbstools/cbstools-public/de/mpg/cbs/methods/MgdmFastAtlasSegmentation.java
|
package de.mpg.cbs.methods;
import java.io.*;
import java.util.*;
import gov.nih.mipav.view.*;
import gov.nih.mipav.model.structures.jama.*;
import de.mpg.cbs.libraries.*;
import de.mpg.cbs.structures.*;
import de.mpg.cbs.utilities.*;
/**
*
* This algorithm uses the MGDM framework to evolve a labeling
* according to internal (curvature) and external (vector field) forces
* note: for now, we are assuming isotropic voxels
*
* @version August 2011
* @author <NAME>
*
*
*/
public class MgdmFastAtlasSegmentation {
// image data
private float[][] image; // original images
private int nix,niy,niz; // image dimensions
private float rix,riy,riz; // image resolutions
private String[] modality; // image modality / contrast
private float[] imrange; // image intensity range (robust estimate)
private int nc; // number of channels
// atlas parameters
private SimpleShapeAtlas atlas;
private int nobj; // number of shapes
private byte[] objLabel; // label values in the original image
private int nax,nay,naz; // atlas dimensions
private float rax,ray,raz; // atlas resolutions
// gain functions
private float[][] bestgain; // best gain function
private byte[][] bestlabel; // corresponding labels
private float[][] bestgainHD; // best gain function (high-res version)
private byte[][] bestlabelHD; // corresponding labels (high-res version)
private static byte ngain; // total number of gain functions
private float pvsize; // window size
private float sigmaI, sigmaS;
private float[] sigmaN;
private float factor;
private float threshold1;
private float threshold2;
private float slope;
private int ngbsize;
private float alpha;
// data and membership buffers
private float[][] mgdmfunctions; // MGDM's pseudo level set mgdmfunctions
private byte[][] mgdmlabels; // MGDM's label maps
private byte[] segmentation; // MGDM's segmentation
private short[] counter;
private boolean[] mask; // masking regions not used in computations
private static byte nmgdm; // total number of MGDM mgdmlabels and mgdmfunctions
private BinaryHeap2D heap; // the heap used in fast marching
private CriticalPointLUT lut; // the LUT for critical points
private boolean checkComposed; // check if the objects are well-composed too (different LUTs)
private boolean checkTopology; // check if the objects are well-composed too (different LUTs)
// parameters
private double smoothweight, forceweight, divweight;
private double K0;
private double gaindist2 = 25.0;
private double stepsize = 0.4;
private float lowlevel = 0.1f;
private float landmineDist = 4.0f;
private float narrowBandDist = landmineDist+1.8f;
private float extraDist = narrowBandDist+1.0f;
private short maxcount = 5;
// computation variables to avoid re-allocating
// for levesetForces
double[] phi;
//double[] Dmx, Dmy, Dmz, Dpx, Dpy, Dpz;
double[] Dmx,Dmy,Dmz, Dpx, Dpy, Dpz;
double D0x,D0y,D0z;
double SD0x, SD0y, SD0z, GPhi;
double Dxx, Dyy, Dzz, Dxy, Dyz, Dzx;
double K, G, tmp;
double Div;
byte bestlb, gainlb;
double bestval, gainval;
float[] smoothfactor;
boolean done;
double[] distval;
// for homeomorphicLabeling
boolean[][][] obj = new boolean[3][3][3];
int Nconfiguration;
short[] lbs = new short[26];
boolean found;
// for minimumMarchingDistance
double s, s2;
int count;
double dist;
// useful constants & flags
private static final byte EMPTY = -1;
// convenience labels
public static final byte X=0;
public static final byte Y=1;
public static final byte Z=2;
// neighborhood flags (ordering is important!!!)
public static final byte pX = 0;
public static final byte pY = 1;
public static final byte pZ = 2;
public static final byte mX = 3;
public static final byte mY = 4;
public static final byte mZ = 5;
public static final byte pXpY = 6;
public static final byte pYpZ = 7;
public static final byte pZpX = 8;
public static final byte pXmY = 9;
public static final byte pYmZ = 10;
public static final byte pZmX = 11;
public static final byte mXpY = 12;
public static final byte mYpZ = 13;
public static final byte mZpX = 14;
public static final byte mXmY = 15;
public static final byte mYmZ = 16;
public static final byte mZmX = 17;
public static final byte pXpYpZ = 18;
public static final byte pXmYmZ = 19;
public static final byte pXmYpZ = 20;
public static final byte pXpYmZ = 21;
public static final byte mXpYpZ = 22;
public static final byte mXmYmZ = 23;
public static final byte mXmYpZ = 24;
public static final byte mXpYmZ = 25;
public static final byte NGB = 26;
public static final byte CTR = 26;
private static final byte[] ngbx = {+1, 0, 0, -1, 0, 0, +1, 0, +1, +1, 0, -1, -1, 0, +1, -1, 0, -1, +1, +1, +1, +1, -1, -1, -1, -1};
private static final byte[] ngby = { 0, +1, 0, 0, -1, 0, +1, +1, 0, -1, +1, 0, +1, -1, 0, -1, -1, 0, +1, -1, -1, +1, +1, -1, -1, +1};
private static final byte[] ngbz = { 0, 0, +1, 0, 0, -1, 0, +1, +1, 0, -1, +1, 0, +1, -1, 0, -1, -1, +1, -1, +1, -1, +1, -1, +1, -1};
private static int[] xoff;
private static int[] yoff;
private static int[] zoff;
// numerical quantities
private static final float INF=1e15f;
private static final float ZERO=1e-15f;
private static final float PI2 = (float)(Math.PI/2.0);
private final static float SQR2 = (float) Math.sqrt(2.0f);
private final static float SQR3 = (float) Math.sqrt(3.0f);
private final static float diagdist = 1/(2*SQR2);
private final static float cubedist = 1/(2*SQR3);
private static final float UNKNOWN = -1.0f;
// for debug and display
private static final boolean debug=false;
private static final boolean verbose=true;
/**
* constructors for different cases: with/out outliers, with/out selective constraints
*/
public MgdmFastAtlasSegmentation(float[][] img_, String[] mod_, float[] rng_, int nc_,
int nix_, int niy_, int niz_, float rix_, float riy_, float riz_,
SimpleShapeAtlas atlas_,
int nmgdm_, int ngain_,
float fw_, float sw_, float dw_, float k0_, float gd_,
String connectivityType_) {
image = img_;
imrange = rng_;
modality = mod_;
nc = nc_;
nix = nix_;
niy = niy_;
niz = niz_;
rix = rix_;
riy = riy_;
riz = riz_;
atlas = atlas_;
nobj = atlas.getNumber();
nax = atlas.getShapeDim()[0];
nay = atlas.getShapeDim()[1];
naz = atlas.getShapeDim()[2];
rax = atlas.getShapeRes()[0];
ray = atlas.getShapeRes()[1];
raz = atlas.getShapeRes()[2];
sigmaI = 0.2f;
sigmaN = new float[nc];
for (int c=0;c<nc;c++) sigmaN[c] = 0.02f;
sigmaS = 0.1f;
threshold1 = 0.0f;
threshold2 = 0.0f;
slope = 0.9f;
ngbsize = 0;
alpha = 0.1f;
pvsize = 0.5f;
nmgdm = (byte)nmgdm_;
ngain = (byte)ngain_;
forceweight = fw_;
smoothweight = sw_;
divweight = dw_;
K0 = k0_;
gaindist2 = gd_*gd_;
if (verbose) System.out.print("MGDMA parameters: "+fw_+" (force), "+sw_+" (smoothing), "+dw_+" (div), "+k0_+" (K0), "+(rax/rix)+" (scale), "+gd_+" (distance)\n");
smoothfactor = atlas.getRegularizationFactor();
objLabel = atlas.getLabels();
// 6-neighborhood: pre-compute the index offsets
xoff = new int[]{1, -1, 0, 0, 0, 0};
yoff = new int[]{0, 0, nax, -nax, 0, 0};
zoff = new int[]{0, 0, 0, 0, nax*nay, -nax*nay};
// init all the arrays in atlas space
try {
segmentation = new byte[nax*nay*naz];
mask = new boolean[nax*nay*naz];
counter = new short[nax*nay*naz];
mgdmfunctions = new float[nmgdm][nax*nay*naz];
mgdmlabels = new byte[nmgdm+1][nax*nay*naz];
phi = new double[27];
/*
Dx = new double[nmgdm+1];
Dy = new double[nmgdm+1];
Dz = new double[nmgdm+1];
*/
Dmx = new double[nmgdm+1];
Dmy = new double[nmgdm+1];
Dmz = new double[nmgdm+1];
Dpx = new double[nmgdm+1];
Dpy = new double[nmgdm+1];
Dpz = new double[nmgdm+1];
distval = new double[nmgdm+1];
// initalize the heap too so we don't have to do it multiple times
heap = new BinaryHeap2D(nax*nay+nay*naz+naz*nax, BinaryHeap2D.MINTREE);
// topology luts
checkTopology=true;
checkComposed=false;
if (connectivityType_.equals("26/6")) lut = new CriticalPointLUT("critical266LUT.raw.gz",200);
else if (connectivityType_.equals("6/26")) lut = new CriticalPointLUT("critical626LUT.raw.gz",200);
else if (connectivityType_.equals("18/6")) lut = new CriticalPointLUT("critical186LUT.raw.gz",200);
else if (connectivityType_.equals("6/18")) lut = new CriticalPointLUT("critical618LUT.raw.gz",200);
else if (connectivityType_.equals("6/6")) lut = new CriticalPointLUT("critical66LUT.raw.gz",200);
else if (connectivityType_.equals("wcs")) {
lut = new CriticalPointLUT("criticalWCLUT.raw.gz",200);
checkComposed=false;
}
else if (connectivityType_.equals("wco")) {
lut = new CriticalPointLUT("critical66LUT.raw.gz",200);
checkComposed=true;
}
else if (connectivityType_.equals("no")) {
lut = null;
checkTopology=false;
}
else {
lut = null;
checkTopology=false;
}
if (checkTopology) {
if (!lut.loadCompressedPattern()) {
finalize();
System.out.println("Problem loading the algorithm's LUT from: "+lut.getFilename());
BasicInfo.displayMessage("Problem loading the algorithm's LUT from: "+lut.getFilename()+"\n");
} else {
//if (debug) System.out.println("LUT loaded from: "+lut.getFilename());
}
}
} catch (OutOfMemoryError e){
finalize();
System.out.println(e.getMessage());
return;
}
if (debug) BasicInfo.displayMessage("initial MGDM decomposition\n");
// basic mask: remove two layers off the images (for avoiding limits)
for (int x=0; x<nax; x++) for (int y=0; y<nay; y++) for (int z = 0; z<naz; z++) {
if (x>1 && x<nax-2 && y>1 && y<nay-2 && z>1 && z<naz-2) mask[x+nax*y+nax*nay*z] = true;
else mask[x+nax*y+nax*nay*z] = false;
}
// init segmentation from atlas
for (int x=0;x<nax;x++) for (int y=0;y<nay;y++) for (int z=0;z<naz;z++) {
int xyz = x + nax*y + nax*nay*z;
int init = atlas.getTemplate()[xyz];
byte nlb = EMPTY;
for (byte n=0; n<nobj; n++) {
if (atlas.getLabels()[n]==init) {
nlb = n;
continue;
}
}
segmentation[xyz] = nlb;
counter[xyz] = 0;
}
if (debug) BasicInfo.displayMessage("initialization\n");
}
public void finalize() {
mgdmfunctions = null;
mgdmlabels = null;
segmentation = null;
lut = null;
heap = null;
}
/**
* clean up the computation arrays
*/
public final void cleanUp() {
mgdmfunctions = null;
mgdmlabels = null;
heap.finalize();
heap = null;
lut.finalize();
lut = null;
System.gc();
}
public final float[][] getFunctions() { return mgdmfunctions; }
public final byte[][] getLabels() { return mgdmlabels; }
public final byte[] getSegmentation() { return segmentation; }
public final float[][] getBestGainFunctionHD() { return bestgainHD; }
public final byte[][] getBestGainLabelHD() { return bestlabelHD; }
public final void setWeights(float fw_, float sw_) {
forceweight = fw_;
smoothweight = sw_;
if (verbose) System.out.print("MGDMA forces: "+fw_+" (force), "+sw_+" (smoothing)\n");
}
/**
* get a final segmentation
*/
public final byte[] exportSegmentationByte() {
byte[] seg = new byte[nix*niy*niz];
for (int x=0;x<nix;x++) for (int y=0;y<niy;y++) for (int z=0;z<niz;z++) {
int xyz = x + nix*y + nix*niy*z;
float[] XA = new float[3];
atlas.imageToShapeCoordinates(XA, x, y, z);
int lbl = ImageInterpolation.nearestNeighborInterpolation(mgdmlabels[0],(byte)-1,XA[0],XA[1],XA[2],nax,nay,naz);
if (lbl>-1) {
seg[xyz] = (byte)objLabel[lbl];
}
}
return seg;
}
public final byte[] getLabeledSegmentation() {
byte[] seg = new byte[nax*nay*naz];
for (int x=0;x<nax;x++) for (int y=0;y<nay;y++) for (int z=0;z<naz;z++) {
int xyz = x + nax*y + nax*nay*z;
int lbl = segmentation[xyz];
if (lbl>-1) {
seg[xyz] = (byte)objLabel[lbl];
} else {
seg[xyz] = 0;
}
}
return seg;
}
public final float[] exportAtlasSegmentation() {
float[] seg = new float[nix*niy*niz];
for (int x=0;x<nix;x++) for (int y=0;y<niy;y++) for (int z=0;z<niz;z++) {
int xyz = x + nix*y + nix*niy*z;
float[] XA = new float[3];
atlas.imageToShapeCoordinates(XA, x, y, z);
int xa = Numerics.round(XA[X]);
int ya = Numerics.round(XA[Y]);
int za = Numerics.round(XA[Z]);
if (xa>=0 && xa<nax && ya>=0 && ya<nay && za>=0 && za<naz) {
int xyza = xa + nax*ya + nax*nay*za;
int lbl = mgdmlabels[0][xyza];
if (lbl>-1) {
seg[xyz] = (float)objLabel[lbl];
}
} else {
seg[xyz] = 0;
}
}
return seg;
}
public final float[] exportAtlasBestGain() {
float[] seg = new float[nix*niy*niz];
for (int x=0;x<nix;x++) for (int y=0;y<niy;y++) for (int z=0;z<niz;z++) {
int xyz = x + nix*y + nix*niy*z;
float[] XA = new float[3];
atlas.imageToShapeCoordinates(XA, x, y, z);
int lbl = ImageInterpolation.nearestNeighborInterpolation(bestlabel[0],(byte)-1,XA[0],XA[1],XA[2],nax,nay,naz);
if (lbl>-1) {
seg[xyz] = (float)objLabel[lbl];
}
}
return seg;
}
public final int[][][] exportImageBestGain() {
int[][][] seg = new int[nix][niy][niz];
for (int x=0;x<nix;x++) for (int y=0;y<niy;y++) for (int z=0;z<niz;z++) {
int xyz = x + nix*y + nix*niy*z;
int lbl = bestlabelHD[0][xyz];
if (lbl>-1) {
seg[x][y][z] = objLabel[lbl];
}
}
return seg;
}
public final float[] exportAtlasGainLabels(int n) {
float[] seg = new float[nix*niy*niz];
for (int x=0;x<nix;x++) for (int y=0;y<niy;y++) for (int z=0;z<niz;z++) {
int xyz = x + nix*y + nix*niy*z;
float[] XA = new float[3];
atlas.imageToShapeCoordinates(XA, x, y, z);
int lbl = ImageInterpolation.nearestNeighborInterpolation(bestlabel[n],(byte)-1,XA[0],XA[1],XA[2],nax,nay,naz);
if (lbl>-1) {
seg[xyz] = (float)objLabel[lbl];
}
}
return seg;
}
public final float[] exportAtlasGainFunctions(int n) {
float[] seg = new float[nix*niy*niz];
for (int x=0;x<nix;x++) for (int y=0;y<niy;y++) for (int z=0;z<niz;z++) {
int xyz = x + nix*y + nix*niy*z;
float[] XA = new float[3];
atlas.imageToShapeCoordinates(XA, x, y, z);
seg[xyz] = ImageInterpolation.nearestNeighborInterpolation(bestgain[n],(byte)-1,XA[0],XA[1],XA[2],nax,nay,naz);
}
return seg;
}
public final float[] exportAtlasObjectGain(int n) {
float[] seg = new float[nix*niy*niz];
for (int x=0;x<nix;x++) for (int y=0;y<niy;y++) for (int z=0;z<niz;z++) {
int xyz = x + nix*y + nix*niy*z;
float[] XA = new float[3];
atlas.imageToShapeCoordinates(XA, x, y, z);
for (int g=0;g<=ngain;g++) {
int lb = ImageInterpolation.nearestNeighborInterpolation(bestlabel[g],(byte)-1,XA[0],XA[1],XA[2],nax,nay,naz);
if (lb==n) {
seg[xyz] = ImageInterpolation.nearestNeighborInterpolation(bestgain[g],(byte)0,XA[0],XA[1],XA[2],nax,nay,naz);
}
}
}
return seg;
}
public final short[] exportFrozenPointCounter() {
short[] seg = new short[nix*niy*niz];
for (int x=0;x<nix;x++) for (int y=0;y<niy;y++) for (int z=0;z<niz;z++) {
int xyz = x + nix*y + nix*niy*z;
float[] XA = new float[3];
atlas.imageToShapeCoordinates(XA, x, y, z);
seg[xyz] = ImageInterpolation.nearestNeighborInterpolation(counter,(short)0,XA[0],XA[1],XA[2],nax,nay,naz);
}
return seg;
}
/**
* compute the intensity priors given the atlas
*/
public final void computeAtlasBestGainFunction() {
bestgainHD = new float[ngain+1][nix*niy*niz];
bestlabelHD = new byte[ngain+1][nix*niy*niz];
byte mp2rage7T=-1;
byte t1map7T = -1;
byte mp2rage3T=-1;
byte t1map3T = -1;
byte mprage3T=-1;
byte t2sw7T=-1;
byte qsm7T=-1;
byte pv=-1;
byte filters=-1;
byte hcpt1w=-1;
byte hcpt2w=-1;
byte normmprage=-1;
for (byte n=0;n<nc;n++) {
if (modality[n].equals("Iso") || modality[n].equals("FlatImg") || modality[n].equals("Mp2rage7T") || modality[n].equals("MP2RAGE7T")) mp2rage7T=n;
else if (modality[n].equals("T1map") || modality[n].equals("T1map7T") || modality[n].equals("T1MAP7T")) t1map7T=n;
else if (modality[n].equals("T1w") || modality[n].equals("T1_SPGR") || modality[n].equals("T1_MPRAGE") || modality[n].equals("Mprage3T") || modality[n].equals("MPRAGE3T")) mprage3T=n;
else if (modality[n].equals("T2SW7T") || modality[n].equals("Flash7T")) t2sw7T=n;
else if (modality[n].equals("QSM7T") || modality[n].equals("qsm7T")) qsm7T=n;
else if (modality[n].equals("Mp2rage3T") || modality[n].equals("MP2RAGE3T")) mp2rage3T=n;
else if (modality[n].equals("T1map3T") || modality[n].equals("T1MAP3T")) t1map3T=n;
else if (modality[n].equals("PV") || modality[n].equals("PVDURA")) pv=n;
else if (modality[n].equals("Filters") || modality[n].equals("FILTER")) filters=n;
else if (modality[n].equals("HCPT1w") || modality[n].equals("HCPT1W")) hcpt1w=n;
else if (modality[n].equals("HCPT2w") || modality[n].equals("HCPT2W")) hcpt2w=n;
else if (modality[n].equals("NORMMPRAGE") || modality[n].equals("NormMPRAGE")) normmprage=n;
}
if (verbose) {
System.out.println("Modalities used in segmentation: ");
//System.out.print("(");
//for (byte n=0;n<nc-1;n++) System.out.print(modality[n]+", ");
//System.out.println(modality[nc-1]+")->");
if (mp2rage7T!=-1) System.out.println("MP2RAGE7T ("+mp2rage7T+")");
if (t1map7T!=-1) System.out.println("T1MAP7T ("+t1map7T+")");
if (mp2rage3T!=-1) System.out.println("MP2RAGE3T ("+mp2rage3T+")");
if (t1map3T!=-1) System.out.println("T1MAP3T ("+t1map3T+")");
if (mprage3T!=-1) System.out.println("MPRAGE3T ("+mprage3T+")");
if (t2sw7T!=-1) System.out.println("T2SW7T ("+t2sw7T+")");
if (qsm7T!=-1) System.out.println("QSM7T ("+qsm7T+")");
if (pv!=-1) System.out.println("PVDURA ("+pv+")");
if (filters!=-1) System.out.println("FILTERS ("+filters+")");
if (hcpt1w!=-1) System.out.println("HCPT1W ("+hcpt1w+")");
if (hcpt2w!=-1) System.out.println("HCPT2W ("+hcpt2w+")");
if (normmprage!=-1) System.out.println("NORMMPRAGE ("+normmprage+")");
}
// compute the local priors
float shape;
float[] intens = new float[nobj];
//float[] pvscore = new float[nobj];
float[] contrast = new float[3];
float val, diff, mindiff, maxdiff, proba;
float pvproba, pvval;
float filterproba, filterval;
float shapesum, shapemax;
float img;
int xyza, xyzi, xyzb;
int xa, ya, za;
float[] XA = new float[3];
for (int x=0;x<nix;x++) for (int y=0;y<niy;y++) for (int z=0;z<niz;z++) {
xyzi = x + nix*y + nix*niy*z;
atlas.imageToShapeCoordinates(XA, x, y, z);
xa = Numerics.round(XA[X]);
ya = Numerics.round(XA[Y]);
za = Numerics.round(XA[Z]);
for (int n=0;n<nobj;n++) {
intens[n] = -1.0f;
}
// just look at the given scale
// first: check for mask
boolean isMasked=true;
if (ImageInterpolation.nearestNeighborInterpolation(segmentation,(byte)0,XA[X],XA[Y],XA[Z],nax,nay,naz)!=0) isMasked = false;
if (ImageInterpolation.linearInterpolation(atlas.getShape(0),1.0f,XA[X],XA[Y],XA[Z],nax,nay,naz)<0.9f) isMasked = false;
if (mp2rage7T>-1 && image[mp2rage7T][xyzi]!=0) isMasked = false;
if (t1map7T>-1 && image[t1map7T][xyzi]!=0) isMasked = false;
if (mp2rage3T>-1 && image[mp2rage3T][xyzi]!=0) isMasked = false;
if (t1map3T>-1 && image[t1map3T][xyzi]!=0) isMasked = false;
if (mprage3T>-1 && image[mprage3T][xyzi]!=0) isMasked = false;
if (t2sw7T>-1 && image[t2sw7T][xyzi]!=0) isMasked = false;
if (qsm7T>-1 && image[qsm7T][xyzi]!=0) isMasked = false;
if (pv>-1 && image[pv][xyzi]!=0) isMasked = false;
if (filters>-1 && image[filters][xyzi]!=0) isMasked = false;
if (hcpt1w>-1 && image[hcpt1w][xyzi]!=0) isMasked = false;
if (hcpt2w>-1 && image[hcpt2w][xyzi]!=0) isMasked = false;
if (normmprage>-1 && image[normmprage][xyzi]!=0) isMasked = false;
// disable this?
//isMasked=false;
if (isMasked) {
bestlabelHD[0][xyzi] = 0;
bestgainHD[0][xyzi] = 1.0f;
for (int n=1;n<ngain+1;n++) {
bestlabelHD[n][xyzi] = EMPTY;
bestgainHD[n][xyzi] = -1.0f;
}
} else {
for (int n=0;n<nobj;n++) {
// compute the exisiting contrasts
if (mp2rage7T>-1) {
contrast[mp2rage7T] = -1.0f;
if (image[mp2rage7T][xyzi]!=0) {
for (int t=0;t<atlas.getMap(atlas.MP2RAGE7T)[n].length;t+=3) {
diff = Numerics.abs(image[mp2rage7T][xyzi]/imrange[mp2rage7T]-atlas.getMap(atlas.MP2RAGE7T)[n][t])/atlas.getMap(atlas.MP2RAGE7T)[n][t+1];
//contrast[iso] = Numerics.max(contrast[iso], atlas.getMap(atlas.ISO)[n][t+2]*(1.0f - diff*diff)/(1.0f + diff*diff) );
if (atlas.getMap(atlas.MP2RAGE7T)[n][t+2]>0)
contrast[mp2rage7T] = Numerics.max(contrast[mp2rage7T], (1.0f - diff*diff)/(1.0f + diff*diff) );
}
} else if (n==0) contrast[mp2rage7T] = 1.0f;
}
if (t1map7T>-1) {
contrast[t1map7T] = -1.0f;
if (image[t1map7T][xyzi]!=0) {
for (int t=0;t<atlas.getMap(atlas.T1MAP7T)[n].length;t+=3) {
diff = Numerics.abs(image[t1map7T][xyzi]/imrange[t1map7T]-atlas.getMap(atlas.T1MAP7T)[n][t])/atlas.getMap(atlas.T1MAP7T)[n][t+1];
//contrast[t1map] = Numerics.max(contrast[t1map], atlas.getMap(atlas.T1M)[n][t+2]*(1.0f - diff*diff)/(1.0f + diff*diff) );
if (atlas.getMap(atlas.T1MAP7T)[n][t+2]>0)
contrast[t1map7T] = Numerics.max(contrast[t1map7T], (1.0f - diff*diff)/(1.0f + diff*diff) );
}
} else if (n==0) contrast[t1map7T] = 1.0f;
}
if (mp2rage3T>-1) {
contrast[mp2rage3T] = -1.0f;
if (image[mp2rage3T][xyzi]!=0) {
for (int t=0;t<atlas.getMap(atlas.MP2RAGE3T)[n].length;t+=3) {
diff = Numerics.abs(image[mp2rage3T][xyzi]/imrange[mp2rage3T]-atlas.getMap(atlas.MP2RAGE3T)[n][t])/atlas.getMap(atlas.MP2RAGE3T)[n][t+1];
//contrast[iso] = Numerics.max(contrast[iso], atlas.getMap(atlas.ISO)[n][t+2]*(1.0f - diff*diff)/(1.0f + diff*diff) );
if (atlas.getMap(atlas.MP2RAGE3T)[n][t+2]>0)
contrast[mp2rage3T] = Numerics.max(contrast[mp2rage3T], (1.0f - diff*diff)/(1.0f + diff*diff) );
}
} else if (n==0) contrast[mp2rage3T] = 1.0f;
}
if (t1map3T>-1) {
contrast[t1map3T] = -1.0f;
if (image[t1map3T][xyzi]!=0) {
for (int t=0;t<atlas.getMap(atlas.T1MAP3T)[n].length;t+=3) {
diff = Numerics.abs(image[t1map3T][xyzi]/imrange[t1map3T]-atlas.getMap(atlas.T1MAP3T)[n][t])/atlas.getMap(atlas.T1MAP3T)[n][t+1];
//contrast[t1map] = Numerics.max(contrast[t1map], atlas.getMap(atlas.T1M)[n][t+2]*(1.0f - diff*diff)/(1.0f + diff*diff) );
if (atlas.getMap(atlas.T1MAP3T)[n][t+2]>0)
contrast[t1map3T] = Numerics.max(contrast[t1map3T], (1.0f - diff*diff)/(1.0f + diff*diff) );
}
} else if (n==0) contrast[t1map3T] = 1.0f;
}
if (mprage3T>-1) {
contrast[mprage3T] = -1.0f;
if (image[mprage3T][xyzi]!=0) {
for (int t=0;t<atlas.getMap(atlas.MPRAGE3T)[n].length;t+=3) {
diff = Numerics.abs(image[mprage3T][xyzi]/imrange[mprage3T]-atlas.getMap(atlas.MPRAGE3T)[n][t])/atlas.getMap(atlas.MPRAGE3T)[n][t+1];
//contrast[t1w] = Numerics.max(contrast[t1w], atlas.getMap(atlas.T1w)[n][t+2]*(1.0f - diff*diff)/(1.0f + diff*diff) );
if (atlas.getMap(atlas.MPRAGE3T)[n][t+2]>0)
contrast[mprage3T] = Numerics.max(contrast[mprage3T], (1.0f - diff*diff)/(1.0f + diff*diff) );
}
} else if (n==0) contrast[mprage3T] = 1.0f;
}
if (t2sw7T>-1) {
contrast[t2sw7T] = -1.0f;
if (image[t2sw7T][xyzi]!=0) {
for (int t=0;t<atlas.getMap(atlas.T2SW7T)[n].length;t+=3) {
diff = Numerics.abs(image[t2sw7T][xyzi]/imrange[t2sw7T]-atlas.getMap(atlas.T2SW7T)[n][t])/atlas.getMap(atlas.T2SW7T)[n][t+1];
//contrast[flair] = Numerics.max(contrast[flair], atlas.getMap(atlas.FLAIR)[n][t+2]*(1.0f - diff*diff)/(1.0f + diff*diff) );
if (atlas.getMap(atlas.T2SW7T)[n][t+2]>0)
contrast[t2sw7T] = Numerics.max(contrast[t2sw7T], (1.0f - diff*diff)/(1.0f + diff*diff) );
}
} else if (n==0) contrast[t2sw7T] = 1.0f;
}
if (hcpt1w>-1) {
contrast[hcpt1w] = -1.0f;
if (image[hcpt1w][xyzi]!=0) {
for (int t=0;t<atlas.getMap(atlas.HCPT1W)[n].length;t+=3) {
diff = Numerics.abs(image[hcpt1w][xyzi]/imrange[hcpt1w]-atlas.getMap(atlas.HCPT1W)[n][t])/atlas.getMap(atlas.HCPT1W)[n][t+1];
if (atlas.getMap(atlas.HCPT1W)[n][t+2]>0)
contrast[hcpt1w] = Numerics.max(contrast[hcpt1w], (1.0f - diff*diff)/(1.0f + diff*diff) );
}
} else if (n==0) contrast[hcpt1w] = 1.0f;
}
if (hcpt2w>-1) {
contrast[hcpt2w] = -1.0f;
if (image[hcpt2w][xyzi]!=0) {
for (int t=0;t<atlas.getMap(atlas.HCPT2W)[n].length;t+=3) {
diff = Numerics.abs(image[hcpt2w][xyzi]/imrange[hcpt2w]-atlas.getMap(atlas.HCPT2W)[n][t])/atlas.getMap(atlas.HCPT2W)[n][t+1];
if (atlas.getMap(atlas.HCPT2W)[n][t+2]>0)
contrast[hcpt2w] = Numerics.max(contrast[hcpt2w], (1.0f - diff*diff)/(1.0f + diff*diff) );
}
} else if (n==0) contrast[hcpt2w] = 1.0f;
}
if (normmprage>-1) {
contrast[normmprage] = -1.0f;
if (image[normmprage][xyzi]!=0) {
for (int t=0;t<atlas.getMap(atlas.NORMMPRAGE)[n].length;t+=3) {
diff = Numerics.abs(image[normmprage][xyzi]/imrange[normmprage]-atlas.getMap(atlas.NORMMPRAGE)[n][t])/atlas.getMap(atlas.NORMMPRAGE)[n][t+1];
if (atlas.getMap(atlas.NORMMPRAGE)[n][t+2]>0)
contrast[normmprage] = Numerics.max(contrast[normmprage], (1.0f - diff*diff)/(1.0f + diff*diff) );
}
} else if (n==0) contrast[normmprage] = 1.0f;
}
/*
if (t1pv>-1) {
proba = Numerics.min(1.0f,Numerics.abs(image[t1pv][xyzi]/imrange[t1pv]));
contrast[t1pv] = Numerics.max(-1.0f, (proba-atlas.getMap(atlas.pT1)[n][1])
/(proba + atlas.getMap(atlas.pT1)[n][1]*(1.0f-2.0f*proba) ) );
}
*/
pvproba = 0.0f;
pvval = 0.0f;
if (pv>-1) {
if (image[pv][xyzi]<0) {
pvproba = Numerics.min(1.0f, -image[pv][xyzi]/imrange[pv]);
pvval = atlas.getMap(atlas.PVDURA)[n][0];
} else {
pvproba = Numerics.min(1.0f, image[pv][xyzi]/imrange[pv]);
pvval = atlas.getMap(atlas.PVDURA)[n][1];
}
}
filterproba = 0.0f;
filterval = 0.0f;
if (filters>-1) {
if (image[filters][xyzi]>=0 && image[filters][xyzi]<=1) {
// first level
filterproba = image[filters][xyzi];
filterval = atlas.getMap(atlas.FILTER)[n][0];
} else if (image[filters][xyzi]>=2 && image[filters][xyzi]<=3) {
// second level
filterproba = image[filters][xyzi]-2.0f;
filterval = atlas.getMap(atlas.FILTER)[n][1];
} else if (image[filters][xyzi]>=4 && image[filters][xyzi]<=5) {
// third level
filterproba = image[filters][xyzi]-4.0f;
filterval = atlas.getMap(atlas.FILTER)[n][2];
}
}
// combine the intensities and probabilities
intens[n] = 1.0f;
if (mp2rage7T>-1) intens[n] = Numerics.min(intens[n], contrast[mp2rage7T]);
if (t1map7T>-1) intens[n] = Numerics.min(intens[n], contrast[t1map7T]);
if (mp2rage3T>-1) intens[n] = Numerics.min(intens[n], contrast[mp2rage3T]);
if (t1map3T>-1) intens[n] = Numerics.min(intens[n], contrast[t1map3T]);
if (mprage3T>-1) intens[n] = Numerics.min(intens[n], contrast[mprage3T]);
if (t2sw7T>-1) intens[n] = Numerics.min(intens[n], contrast[t2sw7T]);
if (qsm7T>-1) intens[n] = Numerics.min(intens[n], contrast[qsm7T]);
if (hcpt1w>-1) intens[n] = Numerics.min(intens[n], contrast[hcpt1w]);
if (hcpt2w>-1) intens[n] = Numerics.min(intens[n], contrast[hcpt2w]);
if (normmprage>-1) intens[n] = Numerics.min(intens[n], contrast[normmprage]);
if (pv>-1) if (pvval!=0) intens[n] = pvproba*pvval + (1.0f-pvproba)*intens[n];
if (filters>-1) if (filterval!=0) intens[n] = filterproba*filterval + (1.0f-filterproba)*intens[n];
}
for (int n=0;n<nobj;n++) {
if (n==0) val = ImageInterpolation.linearInterpolation(atlas.getShape(n),1.0f,XA[0],XA[1],XA[2],nax,nay,naz);
else val = ImageInterpolation.linearInterpolation(atlas.getShape(n),0.0f,XA[0],XA[1],XA[2],nax,nay,naz);
shape = (val - sigmaS)/(val + sigmaS - 2.0f*sigmaS*val);
// use gain composition
float den = (1.01f+intens[n]) + (1.01f+shape);
float ws = Numerics.bounded((1.01f+intens[n])/den,0,1);
float wi = Numerics.bounded((1.01f+shape)/den,0,1);
intens[n] = wi*intens[n] + ws*shape;
}
// keep only the ngain best
for (int n=0;n<ngain+1;n++) {
byte nmax=0;
// careful here: if (almost) all values are -1 to start, you have duplicate values
for (byte m=1;m<nobj;m++) if (intens[m]>intens[nmax]) {
nmax = m;
}
bestlabelHD[n][xyzi] = nmax;
bestgainHD[n][xyzi] = intens[nmax];
intens[nmax] = -2.0f;
}
}
}
// second pass: compute all the functions, then get best
float[][] allgains = new float[nobj][nax*nay*naz];
float[] warpcount = new float[nax*nay*naz];
for (int x=0;x<nax;x++) for (int y=0;y<nay;y++) for (int z=0;z<naz;z++) {
xyza = x + nax*y + nax*nay*z;
for (int n=0;n<nobj;n++) allgains[n][xyza] = 0.0f;
warpcount[xyza] = 0;
}
for (int x=0;x<nix;x++) for (int y=0;y<niy;y++) for (int z=0;z<niz;z++) {
xyzi = x + nix*y + nix*niy*z;
atlas.imageToShapeCoordinates(XA, x, y, z);
xa = Numerics.round(XA[X]);
ya = Numerics.round(XA[Y]);
za = Numerics.round(XA[Z]);
if (xa>=0 && xa<nax && ya>=0 && ya<nay && za>=0 && za<naz) {
xyza = xa + nax*ya + nax*nay*za;
warpcount[xyza]++;
for (int l=0;l<ngain+1;l++) {
if (bestlabelHD[l][xyzi]!=UNKNOWN) {
allgains[bestlabelHD[l][xyzi]][xyza] += 0.5f*(1.0f+bestgainHD[l][xyzi]);
}
}
}
}
for (int x=0;x<nax;x++) for (int y=0;y<nay;y++) for (int z=0;z<naz;z++) {
xyza = x + nax*y + nax*nay*z;
if (warpcount[xyza]>0) {
for (int n=0;n<nobj;n++) allgains[n][xyza] /= warpcount[xyza];
}
}
bestgain = new float[ngain+1][nax*nay*naz];
bestlabel = new byte[ngain+1][nax*nay*naz];
for (int x=0;x<nax;x++) for (int y=0;y<nay;y++) for (int z=0;z<naz;z++) {
xyza = x + nax*y + nax*nay*z;
if (warpcount[xyza]>0) {
for (int n=0;n<ngain+1;n++) {
byte nmax=0;
for (byte m=1;m<nobj;m++) if (allgains[m][xyza]>allgains[nmax][xyza]) {
nmax = m;
}
bestlabel[n][xyza] = nmax;
bestgain[n][xyza] = 2.0f*allgains[nmax][xyza]-1.0f;
allgains[nmax][xyza] = -1.0f;
}
} else {
for (int n=0;n<ngain+1;n++) {
bestgain[n][xyza] = -1.0f;
bestlabel[n][xyza] = -1;
}
}
}
allgains = null;
warpcount = null;
/* method above is better
// second pass for the atlas version
bestgain = new float[ngain+1][nax*nay*naz];
bestlabel = new byte[ngain+1][nax*nay*naz];
for (int x=0;x<nax;x++) for (int y=0;y<nay;y++) for (int z=0;z<naz;z++) {
xyza = x + nax*y + nax*nay*z;
for (int n=0;n<ngain+1;n++) {
bestgain[n][xyza] = -1.0f;
bestlabel[n][xyza] = -1;
}
}
for (int n=0;n<ngain+1;n++) {
// from the best to the last
for (int x=0;x<nix;x++) for (int y=0;y<niy;y++) for (int z=0;z<niz;z++) {
xyzi = x + nix*y + nix*niy*z;
atlas.imageToShapeCoordinates(XA, x, y, z);
xa = Numerics.round(XA[X]);
ya = Numerics.round(XA[Y]);
za = Numerics.round(XA[Z]);
if (xa>=0 && xa<nax && ya>=0 && ya<nay && za>=0 && za<naz) {
xyza = xa + nax*ya + nax*nay*za;
for (int l=0;l<ngain+1;l++) {
if (bestgainHD[l][xyzi]>bestgain[n][xyza]) {
// check if this label is already set
boolean found=false;
for (int m=0;m<n;m++) if (bestlabel[m][xyza]==bestlabelHD[l][xyzi]) {
found=true;
}
if (!found) {
// replace by the new one
bestlabel[n][xyza] = bestlabelHD[l][xyzi];
bestgain[n][xyza] = bestgainHD[l][xyzi];
}
}
}
// also set the mask for the background
if (segmentation[xyza]==0 && bestlabel[0][xyza]==0 && bestgain[0][xyza]==1 && bestgain[1][xyza]==-1) {
mask[xyza] = false;
}
}
}
}
*/
}
// probability diffusion
public final void diffuseBestGainFunctions(int iter, float scale, float factor) {
//mix with the neighbors?
float[] map = new float[nix*niy*niz];
float[] orig = new float[nix*niy*niz];
float[][] newgainHD = new float[ngain+1][nix*niy*niz];
byte[][] newlabelHD = new byte[ngain+1][nix*niy*niz];
boolean[] diffmask = new boolean[nix*niy*niz];
for (int m=0;m<ngain+1;m++) for (int xyzi=0;xyzi<nix*niy*niz;xyzi++) {
newlabelHD[m][xyzi] = EMPTY;
}
for (byte n=0;n<nobj;n++) {
BasicInfo.displayMessage("propagate gain for label "+n+"\n");
// get the gain ; normalize
for (int xyzi=0;xyzi<nix*niy*niz;xyzi++) {
float sum = 0.0f;
map[xyzi] = 0.0f;
for (int m=0;m<ngain+1;m++) {
if (bestlabelHD[m][xyzi]==n) map[xyzi] = 0.5f+0.5f*bestgainHD[m][xyzi];
//sum += 0.5f+0.5f*bestgainHD[m][xyzi];
}
// normalize over sum proba?
//map[xyzi] /= sum;
orig[xyzi] = map[xyzi];
if (orig[xyzi]==0 || orig[xyzi]==1) diffmask[xyzi] = false;
else diffmask[xyzi] = true;
}
// propagate the values : diffusion
float maxdiff = 1.0f;
for (int t=0;t<iter && maxdiff>0.05f;t++) {
BasicInfo.displayMessage(".");
maxdiff = 0.0f;
for (int x=1;x<nix-1;x++) for (int y=1;y<niy-1;y++) for (int z=1;z<niz-1;z++) {
int xyzi = x+nix*y+nix*niy*z;
if (diffmask[xyzi]) {
float den = diffusionWeightFunction(map[xyzi],orig[xyzi],scale);
float num = den*orig[xyzi];
float weight;
float prev = map[xyzi];
weight = factor/6.0f*diffusionWeightFunction(map[xyzi],map[xyzi-1],scale);
num += weight*map[xyzi-1];
den += weight;
weight = factor/6.0f*diffusionWeightFunction(map[xyzi],map[xyzi+1],scale);
num += weight*map[xyzi+1];
den += weight;
weight = factor/6.0f*diffusionWeightFunction(map[xyzi],map[xyzi-nix],scale);
num += weight*map[xyzi-nix];
den += weight;
weight = factor/6.0f*diffusionWeightFunction(map[xyzi],map[xyzi+nix],scale);
num += weight*map[xyzi+nix];
den += weight;
weight = factor/6.0f*diffusionWeightFunction(map[xyzi],map[xyzi-nix*niy],scale);
num += weight*map[xyzi-nix*niy];
den += weight;
weight = factor/6.0f*diffusionWeightFunction(map[xyzi],map[xyzi+nix*niy],scale);
num += weight*map[xyzi+nix*niy];
den += weight;
map[xyzi] = num/den;
maxdiff = Numerics.max(maxdiff, Numerics.abs(map[xyzi]-prev));
} else {
map[xyzi] = orig[xyzi];
}
}
BasicInfo.displayMessage("max diff. "+maxdiff+"\n");
}
// store in the gain if large enough
for (int xyzi=0;xyzi<nix*niy*niz;xyzi++) {
for (int m=0;m<ngain+1;m++) {
if (newlabelHD[m][xyzi]==EMPTY) {
newgainHD[m][xyzi] = 2.0f*map[xyzi]-1.0f;
newlabelHD[m][xyzi] = n;
m = ngain+1;
} else if (2.0f*map[xyzi]-1.0f>newgainHD[m][xyzi]) {
for (int p=ngain;p>m;p--) {
newgainHD[p][xyzi] = newgainHD[p-1][xyzi];
newlabelHD[p][xyzi] = newlabelHD[p-1][xyzi];
}
newgainHD[m][xyzi] = 2.0f*map[xyzi]-1.0f;
newlabelHD[m][xyzi] = n;
m=ngain+1;
}
}
}
}
// make a hard copy
for (int m=0;m<ngain+1;m++) for (int xyzi=0;xyzi<nix*niy*niz;xyzi++) {
bestgainHD[m][xyzi] = newgainHD[m][xyzi];
bestlabelHD[m][xyzi] = newlabelHD[m][xyzi];
}
newgainHD = null;
newlabelHD = null;
}
/*
// probability diffusion
public final void diffuseBestGainFunctions2(int iter, float scale) {
//mix with the neighbors?
float[][][] map = new float[nix][niy][niz];
float[][][] orig = new float[nix][niy][niz];
float[][] newgainHD = new float[ngain+1][nix*niy*niz];
byte[][] newlabelHD = new byte[ngain+1][nix*niy*niz];
boolean[][][] mask = new boolean[nix][niy][niz];
for (int m=0;m<ngain+1;m++) for (int xyzi=0;xyzi<nix*niy*niz;xyzi++) {
newlabelHD[m][xyzi] = EMPTY;
}
for (byte n=0;n<nobj;n++) {
BasicInfo.displayMessage("propagate gain for label "+n+"\n");
// get the gain ; normalize
for (int x=0;x<nix;x++) for (int y=0;y<niy;y++) for (int z=0;z<niz;z++) {
int xyzi = x+nix*y+nix*niy*z;
float sum = 0.0f;
map[x][y][z] = 0.0f;
for (int m=0;m<ngain+1;m++) {
if (bestlabelHD[m][xyzi]==n) map[x][y][z] = 0.5f+0.5f*bestgainHD[m][xyzi];
sum += 0.5f+0.5f*bestgainHD[m][xyzi];
}
// normalize over sum proba?
//map[x][y][z] /= sum;
orig[x][y][z] = map[x][y][z];
if (orig[x][y][z]==0 || orig[x][y][z]==1) mask[x][y][z] = false;
else mask[x][y][z] = true;
}
// propagate the values : diffusion
float maxdiff = 1.0f;
for (int t=0;t<iter && maxdiff>0.05f;t++) {
BasicInfo.displayMessage(".");
maxdiff = 0.0f;
for (int x=1;x<nix-1;x++) for (int y=1;y<niy-1;y++) for (int z=1;z<niz-1;z++) {
int xyzi = x+nix*y+nix*niy*z;
if (mask[x][y][z]) {
float den = diffusionWeightFunction(map[x][y][z],orig[x][y][z],scale);
float num = den*orig[x][y][z];
float weight;
float prev = map[x][y][z];
weight = diffusionWeightFunction(map[x][y][z],map[x-1][y][z],scale);
num += weight*map[x-1][y][z];
den += weight;
weight = diffusionWeightFunction(map[x][y][z],map[x+1][y][z],scale);
num += weight*map[x+1][y][z];
den += weight;
weight = diffusionWeightFunction(map[x][y][z],map[x][y-1][z],scale);
num += weight*map[x][y-1][z];
den += weight;
weight = diffusionWeightFunction(map[x][y][z],map[x][y+1][z],scale);
num += weight*map[x][y+1][z];
den += weight;
weight = diffusionWeightFunction(map[x][y][z],map[x][y][z-1],scale);
num += weight*map[x][y][z-1];
den += weight;
weight = diffusionWeightFunction(map[x][y][z],map[x][y][z+1],scale);
num += weight*map[x][y][z+1];
den += weight;
map[x][y][z] = num/den;
maxdiff = Numerics.max(maxdiff, Numerics.abs(map[x][y][z]-prev));
} else {
map[x][y][z] = orig[x][y][z];
}
}
BasicInfo.displayMessage("max diff. "+maxdiff+"\n");
}
// store in the gain if large enough
for (int x=0;x<nix;x++) for (int y=0;y<niy;y++) for (int z=0;z<niz;z++) {
int xyzi = x+nix*y+nix*niy*z;
for (int m=0;m<ngain+1;m++) {
if (newlabelHD[m][xyzi]==EMPTY) {
newgainHD[m][xyzi] = 2.0f*map[x][y][z]-1.0f;
newlabelHD[m][xyzi] = n;
m = ngain+1;
} else if (2.0f*map[x][y][z]-1.0f>newgainHD[m][xyzi]) {
for (int p=ngain;p>m;p--) {
newgainHD[p][xyzi] = newgainHD[p-1][xyzi];
newlabelHD[p][xyzi] = newlabelHD[p-1][xyzi];
}
newgainHD[m][xyzi] = 2.0f*map[x][y][z]-1.0f;
newlabelHD[m][xyzi] = n;
m=ngain+1;
}
}
}
}
// make a hard copy
for (int m=0;m<ngain+1;m++) for (int xyzi=0;xyzi<nix*niy*niz;xyzi++) {
bestgainHD[m][xyzi] = newgainHD[m][xyzi];
bestlabelHD[m][xyzi] = newlabelHD[m][xyzi];
}
newgainHD = null;
newlabelHD = null;
}
*/
private final float diffusionWeightFunction(float val, float ngb, float scale) {
//return 1.0f/(1.0f+Numerics.square( (val-ngb)/scale ));
//return 1.0f/(1.0f+Numerics.square(Numerics.min(1.0f-ngb, ngb)/scale));
//return 1.0f/(1.0f+Numerics.square( (val-ngb)/scale ))/(1.0f+Numerics.square(Numerics.min(1.0f-ngb, ngb)/scale));
return Numerics.square(Numerics.min(1.0f-val, val)/scale)/(1.0f+Numerics.square(Numerics.min(1.0f-val, val)/scale))
/(1.0f+Numerics.square( (val-ngb)/scale ))/(1.0f+Numerics.square(Numerics.min(1.0f-ngb, ngb)/scale));
}
public final void propagateBestGainFunctions(int iter, float scale) {
/* use the gain itself instead?*/
byte iso=-1;
byte t1map = -1;
for (byte n=0;n<nc;n++) {
if (modality[n].equals("Iso") || modality[n].equals("FlatImg")) iso=n;
else if (modality[n].equals("T1map")) t1map=n;
}
//mix with the neighbors?
float[] map = new float[nax*nay*naz];
float[] orig = new float[nax*nay*naz];
float[][] newgain = new float[ngain+1][nax*nay*naz];
byte[][] newlabel = new byte[ngain+1][nax*nay*naz];
float[][] weight = new float[6][nax*nay*naz];
boolean useBoth = true;
// init: create memberships
for (int xyza=0;xyza<nax*nay*naz;xyza++) {
float sum = 0.0f;
for (int m=0;m<ngain+1;m++) {
sum += 1.0f+bestgain[m][xyza];
}
for (int m=0;m<ngain+1;m++) {
bestgain[m][xyza] = (1.0f+bestgain[m][xyza])/sum;
}
weight[pX][xyza] = 2.0f;
weight[mX][xyza] = 2.0f;
weight[pY][xyza] = 2.0f;
weight[mY][xyza] = 2.0f;
weight[pZ][xyza] = 2.0f;
weight[mZ][xyza] = 2.0f;
}
// init: create a weight map
float[] XA = new float[3];
for (int x=1;x<nix-1;x++) for (int y=1;y<niy-1;y++) for (int z=1;z<niz-1;z++) {
int xyzi = x + nix*y + nix*niy*z;
atlas.imageToShapeCoordinates(XA, x, y, z);
int xa = Numerics.round(XA[X]);
int ya = Numerics.round(XA[Y]);
int za = Numerics.round(XA[Z]);
if (xa>=0 && xa<nax && ya>=0 && ya<nay && za>=0 && za<naz) {
int xyza = xa + nax*ya + nax*nay*za;
float wij = 1.0f/(1.0f + Numerics.square( (image[t1map][xyzi]-image[t1map][xyzi+1])/(scale*imrange[t1map]) ));
if (wij<weight[pX][xyza]) weight[pX][xyza] = wij;
wij = 1.0f/(1.0f + Numerics.square( (image[t1map][xyzi]-image[t1map][xyzi-1])/(scale*imrange[t1map]) ));
if (wij<weight[mX][xyza]) weight[mX][xyza] = wij;
wij = 1.0f/(1.0f + Numerics.square( (image[t1map][xyzi]-image[t1map][xyzi+nix])/(scale*imrange[t1map]) ));
if (wij<weight[pY][xyza]) weight[pY][xyza] = wij;
wij = 1.0f/(1.0f + Numerics.square( (image[t1map][xyzi]-image[t1map][xyzi-nix])/(scale*imrange[t1map]) ));
if (wij<weight[mY][xyza]) weight[mY][xyza] = wij;
wij = 1.0f/(1.0f + Numerics.square( (image[t1map][xyzi]-image[t1map][xyzi+nix*niy])/(scale*imrange[t1map]) ));
if (wij<weight[pZ][xyza]) weight[pZ][xyza] = wij;
wij = 1.0f/(1.0f + Numerics.square( (image[t1map][xyzi]-image[t1map][xyzi-nix*niy])/(scale*imrange[t1map]) ));
if (wij<weight[mZ][xyza]) weight[mZ][xyza] = wij;
}
}
for (int xyza=0;xyza<nax*nay*naz;xyza++) for (int d=0;d<6;d++) {
if (weight[d][xyza]==2) weight[d][xyza]=0;
}
for (byte n=0;n<nobj;n++) {
BasicInfo.displayMessage("propagate gain for label"+n+"\n");
// get the gain ; normalize
for (int xyza=0;xyza<nax*nay*naz;xyza++) {
for (int m=0;m<ngain+1;m++) if (bestlabel[m][xyza]==n) {
map[xyza] = bestgain[m][xyza];
orig[xyza] = map[xyza];
}
}
// propagate the values : diffusion
for (int t=0;t<iter;t++) {
BasicInfo.displayMessage(".");
for (int x=1;x<nax-1;x++) for (int y=1;y<nay-1;y++) for (int z=1;z<naz-1;z++) {
int xyza = x+nax*y+nax*nay*z;
float num = orig[xyza];
float den = 1.0f;
if (t1map>-1) {
if (useBoth || map[xyza-1]>map[xyza]) {
num += weight[mX][xyza]*(map[xyza-1]-map[xyza]);
den += weight[mX][xyza];
}
if (useBoth || map[xyza+1]>map[xyza]) {
num += weight[pX][xyza]*(map[xyza+1]-map[xyza]);
den += weight[pX][xyza];
}
if (useBoth || map[xyza-nax]>map[xyza]) {
num += weight[mY][xyza]*(map[xyza-nax]-map[xyza]);
den += weight[mY][xyza];
}
if (useBoth || map[xyza+nax]>map[xyza]) {
num += weight[pY][xyza]*(map[xyza+nax]-map[xyza]);
den += weight[pY][xyza];
}
if (useBoth || map[xyza-nax*nay]>map[xyza]) {
num += weight[mZ][xyza]*(map[xyza-nax*nay]-map[xyza]);
den += weight[mZ][xyza];
}
if (useBoth || map[xyza+nax*nay]>map[xyza]) {
num += weight[pZ][xyza]*(map[xyza+nax*nay]-map[xyza]);
den += weight[pZ][xyza];
}
}
map[xyza] = num/den;
}
}
// store in the gain if large enough
for (int xyza=0;xyza<nax*nay*naz;xyza++) {
for (int m=0;m<ngain+1;m++) {
if (map[xyza]>newgain[m][xyza]) {
for (int p=ngain;p>m;p--) {
newgain[p][xyza] = newgain[p-1][xyza];
newlabel[p][xyza] = newlabel[p-1][xyza];
}
newgain[m][xyza] = map[xyza];
newlabel[m][xyza] = n;
m=ngain+1;
}
}
}
}
bestgain = newgain;
bestlabel = newlabel;
}
/**
* Evolution using the narrow band scheme
* (the reinitialization is incorporated)
*/
public final void evolveNarrowBand(int iter, float mindiff) {
if (debug) System.out.print("level set evolution: narrow band\n");
// option flags (for testing)
boolean fullMarching=false;
// not needed at all, it seems (removed from code)
//boolean recomputeCritical=false;
// init decomposition
fastMarchingInitializationFromSegmentation(false, fullMarching);
// first estimate the narrow band size
int size = 0;
int boundarysize=0;
for (int xyz = 0; xyz<nax*nay*naz; xyz++) if (mask[xyz]) {
if (mgdmfunctions[0][xyz]<narrowBandDist && mgdmfunctions[0][xyz]!=UNKNOWN) size++;
if (Numerics.abs(mgdmfunctions[0][xyz])<1.0 && mgdmfunctions[0][xyz]!=UNKNOWN) boundarysize++;
}
// create the narrow band with initial estimates of size
NarrowBand narrowband = new NarrowBand(Numerics.ceil(1.25f*size), Numerics.ceil(0.1f*size));
BitSet landmines = new BitSet(Numerics.ceil(0.2f*size));
if (debug) System.out.print("init ("+size+")\n");
for (int xyz = 0; xyz<nax*nay*naz; xyz++) if (mask[xyz]) {
// the criterion for being in the narrow band is to have a short distance to closest boundaries
if (mgdmfunctions[0][xyz]<narrowBandDist && mgdmfunctions[0][xyz]!=UNKNOWN) {
narrowband.addPoint(xyz, mgdmlabels, mgdmfunctions);
// in addition, if close to the narrow band boundariy, set a landmine
if (mgdmfunctions[0][xyz]>=landmineDist) {
landmines.set(xyz,true);
}
}
}
int[] nswap = new int[nmgdm];
double[] forces = new double[nmgdm+1];
int newlb;
boolean reinitLM, reinitOL;
int ncounted;
// evolve until a landmine is closer than minDist of the boundaries
float diff = 1.0f;
for (int t=0;t<iter && (t<5 || diff>mindiff);t++) {
if (debug) System.out.print("iteration "+t+"\n");
if (verbose) System.out.print(t+": ");
reinitLM = false;
reinitOL = false;
for (int lb=0;lb<nmgdm;lb++) nswap[lb] = 0;
ncounted = 0;
for (int n=0; n<narrowband.currentsize;n++) {
int xyz = narrowband.id[n];
//if (debug) System.out.print(".");
// skip points that have seen little change
//if (true) {
if (counter[xyz]<maxcount) {
// evolve the MGDM functions
// compute the forces from current levelset values, update the narrow band from it
levelsetForces(xyz, forces);
//if (debug) System.out.print(":");
for (int lb=nmgdm-1;lb>=0;lb--) if (mgdmlabels[lb][xyz]!=EMPTY) {
// update the narrow band values, not the original data
narrowband.functions[lb][n] += Numerics.bounded(forces[lb] - forces[lb+1], -0.9f, 0.9f);
// change of sign ?
if (narrowband.functions[lb][n]<0) {
//if (debug) System.out.print(""+lb);
// try all possible labels: no, next label is the closest by definition
newlb = EMPTY;
if (mgdmlabels[lb+1][xyz]!=EMPTY && (lb>0 || homeomorphicLabeling(xyz, mgdmlabels[lb+1][xyz])))
newlb = lb+1;
if (newlb!=EMPTY) {
// for all levels
nswap[lb]++;
narrowband.labels[lb][n] = mgdmlabels[newlb][xyz];
narrowband.functions[lb][n] = -narrowband.functions[lb][n];
// never switch the last label
if (newlb<nmgdm) narrowband.labels[newlb][n] = mgdmlabels[lb][xyz];
// update the segmentation with first label
if (lb==0) {
segmentation[xyz] = mgdmlabels[newlb][xyz];
// check for boundary changes in the landmines : force reinitialization
if (landmines.get(xyz)) reinitLM = true;
// check for far labels getting mixed in: time to re-initialize
if (narrowband.labels[0][n]==mgdmlabels[nmgdm][xyz]) reinitOL = true;
}
} else {
// reset to low value ?
narrowband.functions[lb][n] = lowlevel;
// or to original value ?
//narrowband.functions[lb][n] -= Numerics.bounded(forces[lb] - forces[lb+1], -0.9f, 0.9f);
}
// reset the counter; also reset all the neighbors
if (lb==0) {
counter[xyz]=0;
for (int b=0;b<NGB;b++) {
int xyzn = xyz + ngbx[b] + ngby[b]*nax + ngbz[b]*nax*nay;
// reset all to zero?
counter[xyzn] = 0;
/*
if (counter[xyzn]>maxcount) counter[xyzn] = (short)(maxcount-1);
else if (counter[xyzn]>0) counter[xyzn]--;
*/
}
}
} else {
if (lb==0) counter[xyz]++;
}
}
} else {
counter[xyz]++;
ncounted++;
}
}
diff = (nswap[0]/(float)boundarysize);
if (debug) for (int lb=0;lb<nmgdm;lb++) System.out.print("changed labels ("+lb+"): "+nswap[lb]+" ("+(nswap[lb]/(float)boundarysize*100.0f)+" % of boundary)\n");
if (debug) System.out.print("frozen points: "+(ncounted/(float)narrowband.currentsize*100.0f)+" % of narrow band\n");
if (verbose) System.out.print("changed "+(nswap[0]/(float)boundarysize*100.0f)+" % of boundary "
+"(frozen points: "+(ncounted/(float)narrowband.currentsize*100.0f)+" % of narrow band)\n");
// once all the new values are computed, copy into original MGDM functions
for (int n=0; n<narrowband.currentsize;n++) {
int xyz = narrowband.id[n];
if (counter[xyz]<maxcount) {
for (int lb=0;lb<nmgdm;lb++) {
mgdmlabels[lb][xyz] = narrowband.labels[lb][n];
mgdmfunctions[lb][xyz] = narrowband.functions[lb][n];
}
}
}
// important to check for changes in labels (can get stuck otherwise)
if (t<iter-1 && (t<5 || diff>mindiff) && (reinitLM || reinitOL) ) {
//if (t<iter-1 && reinitLM) {
if (debug) System.out.print("re-initialization (LM: "+reinitLM+" | OL: "+reinitOL+" )\n");
if (verbose) System.out.print("(*)");
//resetIsosurfaceNarrowBand(narrowband);
resetIsosurfaceBoundary();
fastMarchingReinitialization(false, fullMarching, true);
// rebuild narrow band
narrowband.reset();
landmines.clear();
boundarysize = 0;
for (int xyz = 0; xyz<nax*nay*naz; xyz++) if (mask[xyz]) {
// the criterion for being in the narrow band is to have a shortdistance to closest boundaries
if (mgdmfunctions[0][xyz]<narrowBandDist && mgdmfunctions[0][xyz]!=UNKNOWN) {
narrowband.addPoint(xyz, mgdmlabels, mgdmfunctions);
if (mgdmfunctions[0][xyz]>=landmineDist) {
landmines.set(xyz,true);
}
if (Numerics.abs(mgdmfunctions[0][xyz])<1.0) {
boundarysize++;
}
}
}
}
}
// end of the evolution: recompute the level sets (disabled for debugging)
resetIsosurfaceBoundary();
fastMarchingReinitialization(false, fullMarching, false);
return;
}
/** specific forces applied to the level sets (application dependent) */
private final void levelsetForces(int xyz, double[] forces) {
// simple option: rebuild each level set locally
// note: we go back to the convention of usual level sets with negative value inside, positive value outside
for (int n=0;n<=nmgdm;n++) {
// label
byte lb = mgdmlabels[n][xyz];
// do the center point first
if (n==0) phi[CTR] = -mgdmfunctions[0][xyz];
else phi[CTR] = 0.0f;
for (int l=0;l<n;l++) {
phi[CTR] += mgdmfunctions[l][xyz];
}
// neighbors
for (int b=0;b<NGB;b++) {
int xyzn = xyz + ngbx[b] + ngby[b]*nax + ngbz[b]*nax*nay;
if (mask[xyzn] && mgdmlabels[0][xyzn]!=EMPTY && mgdmfunctions[0][xyzn]!=UNKNOWN) {
if (mgdmlabels[0][xyzn]==lb) phi[b] = -mgdmfunctions[0][xyzn];
else phi[b] = 0.0f;
for (int l=0;l<nmgdm && mgdmlabels[l][xyzn]!=lb && mgdmfunctions[l][xyzn]!=UNKNOWN;l++) {
phi[b] += mgdmfunctions[l][xyzn];
}
} else {
// filling in values outside the mask?? center value
phi[b] = phi[CTR];
}
}
// first derivatives
/*
Dmx[n] = phi[CTR] - phi[mX];
Dmy[n] = phi[CTR] - phi[mY];
Dmz[n] = phi[CTR] - phi[mZ];
Dpx[n] = phi[pX] - phi[CTR];
Dpy[n] = phi[pY] - phi[CTR];
Dpz[n] = phi[pZ] - phi[CTR];
D0x[n] = (phi[pX] - phi[mX])/2.0;
D0y[n] = (phi[pY] - phi[mY])/2.0;
D0z[n] = (phi[pZ] - phi[mZ])/2.0;
*/
Dmx[n] = phi[CTR] - phi[mX];
Dmy[n] = phi[CTR] - phi[mY];
Dmz[n] = phi[CTR] - phi[mZ];
Dpx[n] = phi[pX] - phi[CTR];
Dpy[n] = phi[pY] - phi[CTR];
Dpz[n] = phi[pZ] - phi[CTR];
D0x = (phi[pX] - phi[mX])/2.0;
D0y = (phi[pY] - phi[mY])/2.0;
D0z = (phi[pZ] - phi[mZ])/2.0;
// second derivatives
Dxx = phi[mX] + phi[pX] - 2.0*phi[CTR];
Dyy = phi[mY] + phi[pY] - 2.0*phi[CTR];
Dzz = phi[mZ] + phi[pZ] - 2.0*phi[CTR];
Dxy = (phi[mXmY] + phi[pXpY] - phi[mXpY] - phi[pXmY])/4.0;
Dyz = (phi[mYmZ] + phi[pYpZ] - phi[mYpZ] - phi[pYmZ])/4.0;
Dzx = (phi[mZmX] + phi[pZpX] - phi[mZpX] - phi[pZmX])/4.0;
// gradient norm
SD0x = D0x * D0x;
SD0y = D0y * D0y;
SD0z = D0z * D0z;
GPhi = Math.sqrt(SD0x + SD0y + SD0z);
// mean curvature
K = (Dyy + Dzz)*SD0x + (Dxx + Dzz)*SD0y + (Dxx + Dyy)*SD0z
- 2.0*(D0x*D0y*Dxy + D0y*D0z*Dyz + D0z*D0x*Dzx);
// gaussian curvature
G = (Dyy*Dzz - Dyz*Dyz)*SD0x + (Dzz*Dxx - Dzx*Dzx)*SD0y + (Dxx*Dyy - Dxy*Dxy)*SD0z
+ 2.0*(D0x*D0y*(Dyz*Dzx - Dxy*Dzz) + D0z*D0x*(Dxy*Dyz - Dzx*Dyy) + D0y*D0z*(Dxy*Dzx - Dyz*Dxx));
// curvature smoothing force:
if(GPhi > 0.0000001){
tmp = GPhi*GPhi;
K = K/(GPhi*tmp);
G = G/(tmp*tmp);
tmp = K*K - 2*G;
if(tmp > 0 ) K = K*G/tmp;
} else {
K = 0;
}
forces[n] = -smoothweight*stepsize*(K-K0)*GPhi;
// divergence-smoothing force:
forces[n] = -divweight*stepsize*(phi[CTR]*phi[CTR]/(1.0+phi[CTR]*phi[CTR]))*(Dxx+Dyy+Dzz);
// distance-based atenuation
/* one-sided? */
if (phi[CTR]<0) distval[n] = 1.0;
else distval[n] = 1.0/(1.0+phi[CTR]*phi[CTR]/gaindist2);
/* or two sided? not much difference it seems
distval[n] = 1.0/(1.0+phi[CTR]*phi[CTR]/gaindist2);
*/
}
// find the best target in the neighborhood to build the corresponding force
/*
bestlb = EMPTY;
gainval = 0.5f;
for (int n=0;n<=ngain && bestlb==EMPTY;n++) {
gainlb = bestlabel[n][xyz];
gainval = bestgain[n][xyz];
for (byte l=0;l<=nmgdm && bestlb==EMPTY;l++) {
if (mgdmlabels[l][xyz]==gainlb) {
bestlb = l;
}
}
}
*/
// (product of gain and proximity => must check all)
bestlb = EMPTY;
bestval = -1.0f;
done=false;
for (int n=0;n<=ngain && !done;n++) {
gainlb = bestlabel[n][xyz];
gainval = 0.5f + 0.5f*bestgain[n][xyz];
//if (gainval<=0) done = true;
for (byte l=0;l<=nmgdm && !done;l++) {
if (mgdmlabels[l][xyz]==gainlb && distval[l]*gainval>bestval) {
bestlb = l;
bestval = distval[l]*gainval;
}
}
}
/*
// use the difference with next best??
if (bestlb<ngain) gainval -= bestgain[bestlb+1][xyz];
else gainval += 1.0;
*/
/*
// only the first label?
gainlb = bestlabel[0][xyz];
for (byte l=0;l<=nmgdm && bestlb==EMPTY;l++) {
if (mgdmlabels[l][xyz]==gainlb) bestlb = l;
}
*/
// second pass for the data force
if (bestlb!=EMPTY) {
//if (bestlb!=EMPTY && gainval>0) { // use only positive forces??
for (int n=0;n<=nmgdm;n++) {
byte lb = mgdmlabels[n][xyz];
if (lb!=EMPTY) {
/*
// central differences?
forces[n] += forceweight/smoothfactor[lb]*stepsize*bestval*(D0x[bestlb]*D0x[n] + D0y[bestlb]*D0y[n] + D0z[bestlb]*D0z[n]);
*/
// upwind scheme?
forces[n] += forceweight/smoothfactor[lb]*stepsize*bestval
*(Numerics.max(Dpx[bestlb]+Dmx[bestlb],0)*Dmx[n] + Numerics.min(Dpx[bestlb]+Dmx[bestlb],0)*Dpx[n]
+Numerics.max(Dpy[bestlb]+Dmy[bestlb],0)*Dmy[n] + Numerics.min(Dpy[bestlb]+Dmy[bestlb],0)*Dpy[n]
+Numerics.max(Dpz[bestlb]+Dmz[bestlb],0)*Dmz[n] + Numerics.min(Dpz[bestlb]+Dmz[bestlb],0)*Dpz[n]);
// add a balloon term if prod ~ 0: not useful
} else {
// regularize more ? do nothing ?
//forces[n] += -forceweight*stepsize*0.5f;
}
}
} else {
// if best is not a neighbor, just shrink the label
// or should we just set things to zero then (and let the smoothness drive everything)?
// ->not good, creates static points
// increase smoothness in that location instead? do nothing?
/*
for (int n=0;n<=nmgdm;n++) {
forces[n] += -forceweight*stepsize*0.5f;
}
*/
}
/*
//just balloon forces??
for (int n=0;n<=nmgdm;n++) {
byte lb = mgdmlabels[n][xyz];
if (lb!=EMPTY) {
boolean found=false;
for (byte l=0;l<=nmgdm && !found;l++) if (lb==bestlabel[l][xyz]) {
found=true;
forces[n] += forceweight/smoothfactor[lb]*stepsize*bestgain[l][xyz];
}
if (!found) forces[n] += -1.0*forceweight/smoothfactor[lb]*stepsize;
}
}
*/
return;
}
/**
* critical relation detection: groups objects with relations
*/
private final boolean homeomorphicLabeling(int xyz, byte lb) {
// if we don't check, just exit
if (!checkTopology) return true;
// is the new segmentation homeomorphic ?
// inside the original object ?
if (segmentation[xyz]==lb) return true;
// does it change the topology of the new object ?
for (int i=-1;i<=1;i++) for (int j=-1;j<=1;j++) for (int l=-1;l<=1;l++) {
if (segmentation[xyz+i+j*nax+l*nax*nay]==lb) {
obj[1+i][1+j][1+l] = true;
} else {
obj[1+i][1+j][1+l] = false;
}
}
obj[1][1][1] = true;
if (checkComposed) if (!ObjectStatistics.isWellComposed(obj,1,1,1)) return false;
if (!lut.get(lut.keyFromPattern(obj,1,1,1))) return false;
// does it change the topology of the object it modifies ?
for (int i=-1;i<=1;i++) for (int j=-1;j<=1;j++) for (int l=-1;l<=1;l++) {
if (segmentation[xyz+i+j*nax+l*nax*nay]==segmentation[xyz]) {
obj[1+i][1+j][1+l] = true;
} else {
obj[1+i][1+j][1+l] = false;
}
}
obj[1][1][1] = false;
if (checkComposed) if (!ObjectStatistics.isWellComposed(obj,1,1,1)) return false;
if (!lut.get(lut.keyFromPattern(obj,1,1,1))) return false;
// does it change the topology of a relation between the modified object and its neighbors ?
Nconfiguration = 0;
for (int i=-1;i<=1;i++) for (int j=-1;j<=1;j++) for (int l=-1;l<=1;l++) {
if ( (i*i+j*j+l*l>0)
&& (segmentation[xyz+i+j*nax+l*nax*nay]!=lb)
&& (segmentation[xyz+i+j*nax+l*nax*nay]!=segmentation[xyz]) ) {
found = false;
for (int n=0;n<Nconfiguration;n++)
if (segmentation[xyz+i+j*nax+l*nax*nay]==lbs[n]) { found = true; break; }
if (!found) {
lbs[Nconfiguration] = segmentation[xyz+i+j*nax+l*nax*nay];
Nconfiguration++;
}
}
}
// pairs
for (int n=0;n<Nconfiguration;n++) {
// in relation with previous object
for (int i=-1;i<=1;i++) for (int j=-1;j<=1;j++) for (int l=-1;l<=1;l++) {
if ( (segmentation[xyz+i+j*nax+l*nax*nay]==segmentation[xyz])
|| (segmentation[xyz+i+j*nax+l*nax*nay]==lbs[n]) ) {
obj[1+i][1+j][1+l] = true;
} else {
obj[1+i][1+j][1+l] = false;
}
}
obj[1][1][1] = false;
if (!lut.get(lut.keyFromPattern(obj,1,1,1))) return false;
}
for (int n=0;n<Nconfiguration;n++) {
// in relation with new object
for (int i=-1;i<=1;i++) for (int j=-1;j<=1;j++) for (int l=-1;l<=1;l++) {
if ( (segmentation[xyz+i+j*nax+l*nax*nay]==lb)
|| (segmentation[xyz+i+j*nax+l*nax*nay]==lbs[n]) ) {
obj[1+i][1+j][1+l] = true;
} else {
obj[1+i][1+j][1+l] = false;
}
}
obj[1][1][1] = true;
if (!lut.get(lut.keyFromPattern(obj,1,1,1))) return false;
}
// triplets
for (int n=0;n<Nconfiguration;n++) {
for (int m=n+1;m<Nconfiguration;m++) {
// in relation with previous object
for (int i=-1;i<=1;i++) for (int j=-1;j<=1;j++) for (int l=-1;l<=1;l++) {
if ( (segmentation[xyz+i+j*nax+l*nax*nay]==segmentation[xyz])
|| (segmentation[xyz+i+j*nax+l*nax*nay]==lbs[n])
|| (segmentation[xyz+i+j*nax+l*nax*nay]==lbs[m]) ) {
obj[1+i][1+j][1+l] = true;
} else {
obj[1+i][1+j][1+l] = false;
}
}
obj[1][1][1] = false;
if (!lut.get(lut.keyFromPattern(obj,1,1,1))) return false;
}
}
for (int n=0;n<Nconfiguration;n++) {
for (int m=n+1;m<Nconfiguration;m++) {
// in relation with new object
for (int i=-1;i<=1;i++) for (int j=-1;j<=1;j++) for (int l=-1;l<=1;l++) {
if ( (segmentation[xyz+i+j*nax+l*nax*nay]==lb)
|| (segmentation[xyz+i+j*nax+l*nax*nay]==lbs[n])
|| (segmentation[xyz+i+j*nax+l*nax*nay]==lbs[m]) ) {
obj[1+i][1+j][1+l] = true;
} else {
obj[1+i][1+j][1+l] = false;
}
}
obj[1][1][1] = true;
if (!lut.get(lut.keyFromPattern(obj,1,1,1))) return false;
}
}
// else, it works
return true;
}
public final void fastMarchingInitializationFromSegmentation(boolean narrowBandOnly, boolean almostEverywhere) {
// initialize the quantities
for (int xyz = 0; xyz<nax*nay*naz; xyz++) {
// mgdm functions
for (int n = 0; n<nmgdm; n++) {
mgdmfunctions[n][xyz] = UNKNOWN;
mgdmlabels[n][xyz] = EMPTY;
}
mgdmlabels[nmgdm][xyz] = EMPTY;
}
// basic mask region: boundaries
for (int x=0;x<nax;x++) for (int y=0;y<nay;y++) for (int z=0;z<naz;z++) {
int xyz = x+nax*y+nax*nay*z;
if (x==0 || x==nax-1 || y==0 || y==nay-1 || z==0 || z==naz-1) mask[xyz] = false;
else mask[xyz] = true;
}
// computation variables
byte[] processed = new byte[nax*nay*naz]; // note: using a byte instead of boolean for the second pass
float[] nbdist = new float[6];
boolean[] nbflag = new boolean[6];
float curdist,newdist;
boolean done, isprocessed;
// compute the neighboring labels and corresponding distance functions (! not the MGDM functions !)
if (debug) BasicInfo.displayMessage("fast marching\n");
heap.reset();
// initialize the heap from boundaries
for (int xyz = 0; xyz<nax*nay*naz; xyz++) if (mask[xyz]) {
processed[xyz] = 0;
// search for boundaries
for (int k = 0; k<6; k++) {
int xyzn = xyz + xoff[k] + yoff[k] + zoff[k];
if (segmentation[xyzn]!=segmentation[xyz]) if (mask[xyzn]) {
// add to the heap
heap.addValue(0.5f,xyzn,segmentation[xyz]);
}
}
}
if (debug) BasicInfo.displayMessage("init\n");
// grow the labels and functions
while (heap.isNotEmpty()) {
// extract point with minimum distance
curdist = heap.getFirst();
int xyz = heap.getFirstId();
byte lb = heap.getFirstState();
heap.removeFirst();
// if more than nmgdm labels have been found already, this is done
if (processed[xyz]>=nmgdm) continue;
// if there is already a label for this object, this is done
done = false;
for (int n=0; n<processed[xyz]; n++)
if (mgdmlabels[n][xyz]==lb) done = true;
if (done) continue;
// update the distance functions at the current level
mgdmfunctions[processed[xyz]][xyz] = curdist;
mgdmlabels[processed[xyz]][xyz] = lb;
processed[xyz]++; // update the current level
// find new neighbors
for (int k = 0; k<6; k++) {
int xyzn = xyz + xoff[k] + yoff[k] + zoff[k];
if (mask[xyzn]) {
// must be in outside the object or its processed neighborhood
isprocessed = false;
if (segmentation[xyzn]==lb) isprocessed = true;
else {
for (int n=0; n<processed[xyzn]; n++)
if (mgdmlabels[n][xyzn]==lb) isprocessed = true;
}
if (!isprocessed) {
// compute new distance based on processed neighbors for the same object
for (int l=0; l<6; l++) {
nbdist[l] = UNKNOWN;
nbflag[l] = false;
int xyznb = xyzn + xoff[l] + yoff[l] + zoff[l];
// note that there is at most one value used here
for (int n=0; n<processed[xyznb]; n++) if (mask[xyznb]) if (mgdmlabels[n][xyznb]==lb) {
nbdist[l] = mgdmfunctions[n][xyznb];
nbflag[l] = true;
}
}
newdist = minimumMarchingDistance(nbdist, nbflag);
if ( (!narrowBandOnly && !almostEverywhere)
|| (narrowBandOnly && newdist<=narrowBandDist+extraDist)
|| (almostEverywhere && (segmentation[xyzn]!=0 || newdist<=narrowBandDist+extraDist) ) ) {
// add to the heap
heap.addValue(newdist,xyzn,lb);
}
}
}
}
}
// re-buidld a better mask region
for (int x=0;x<nax;x++) for (int y=0;y<nay;y++) for (int z=0;z<naz;z++) {
int xyz = x+nax*y+nax*nay*z;
if (x==0 || x==nax-1 || y==0 || y==nay-1 || z==0 || z==naz-1) mask[xyz] = false;
else if (segmentation[xyz]==EMPTY || (processed[xyz]==0 && segmentation[xyz]==0)) mask[xyz] = false;
else mask[xyz] = true;
}
// to create the MGDM functions, we need to copy the segmentation, forget the last labels
// and compute differences between distance functions
if (debug) BasicInfo.displayMessage("transform into MGDM functions\n");
for (int xyz = 0; xyz<nax*nay*naz; xyz++) if (mask[xyz]) {
// label permutation
for (int n=nmgdm;n>0;n--) {
mgdmlabels[n][xyz] = mgdmlabels[n-1][xyz];
}
mgdmlabels[0][xyz] = segmentation[xyz];
// distance function difference
for (int n = nmgdm-1; n>0; n--) {
mgdmfunctions[n][xyz] = Numerics.max(UNKNOWN, mgdmfunctions[n][xyz]
-mgdmfunctions[n-1][xyz]);
}
}
if (debug) BasicInfo.displayMessage("done\n");
return;
}
/**
* perform joint reinitialization for all labels
*/
public final void fastMarchingReinitialization(boolean narrowBandOnly, boolean almostEverywhere, boolean stopCounter) {
// computation variables
byte[] processed = new byte[nax*nay*naz]; // note: using a byte instead of boolean for the second pass
float[] nbdist = new float[6];
boolean[] nbflag = new boolean[6];
float curdist,newdist;
boolean done, isprocessed;
// compute the neighboring labels and corresponding distance functions (! not the MGDM functions !)
if (debug) BasicInfo.displayMessage("fast marching\n");
long start_time = System.currentTimeMillis();
heap.reset();
// initialize the heap from boundaries
for (int xyz = 0; xyz<nax*nay*naz; xyz++) if (mask[xyz]) {
// mgdm functions : reinit everiywhere
for (int n = 0; n<nmgdm; n++) {
if (n>0) mgdmfunctions[n][xyz] = UNKNOWN;
mgdmlabels[n][xyz] = EMPTY;
}
mgdmlabels[nmgdm][xyz] = EMPTY;
processed[xyz] = 0;
// not needed, should be kept the same
//segmentation[xyz] = mgdmlabels[0][xyz];
// search for boundaries
for (int k = 0; k<6; k++) {
int xyzn = xyz + xoff[k] + yoff[k] + zoff[k];
if (segmentation[xyzn]!=segmentation[xyz]) if (mask[xyzn]) {
// add to the heap with previous value
heap.addValue(mgdmfunctions[0][xyzn],xyzn,segmentation[xyz]);
}
}
}
if (debug) BasicInfo.displayMessage("init\n");
// grow the labels and functions
while (heap.isNotEmpty()) {
// extract point with minimum distance
curdist = heap.getFirst();
int xyz = heap.getFirstId();
byte lb = heap.getFirstState();
heap.removeFirst();
// if more than nmgdm labels have been found already, this is done
if (processed[xyz]>=nmgdm) continue;
// if there is already a label for this object, this is done
done = false;
for (int n=0; n<processed[xyz]; n++)
if (mgdmlabels[n][xyz]==lb) done = true;
if (done) continue;
// update the distance functions at the current level
mgdmfunctions[processed[xyz]][xyz] = curdist;
mgdmlabels[processed[xyz]][xyz] = lb;
processed[xyz]++; // update the current level
// find new neighbors
for (int k = 0; k<6; k++) {
int xyzn = xyz + xoff[k] + yoff[k] + zoff[k];
if (mask[xyzn] && (!stopCounter || counter[xyzn]<2*maxcount) ) {
// must be in outside the object or its processed neighborhood
isprocessed = false;
if (segmentation[xyzn]==lb) isprocessed = true;
else {
for (int n=0; n<processed[xyzn]; n++)
if (mgdmlabels[n][xyzn]==lb) isprocessed = true;
}
if (!isprocessed) {
// compute new distance based on processed neighbors for the same object
for (int l=0; l<6; l++) {
nbdist[l] = UNKNOWN;
nbflag[l] = false;
int xyznb = xyzn + xoff[l] + yoff[l] + zoff[l];
// note that there is at most one value used here
for (int n=0; n<processed[xyznb]; n++) if (mask[xyznb]) if (mgdmlabels[n][xyznb]==lb) {
nbdist[l] = mgdmfunctions[n][xyznb];
nbflag[l] = true;
}
}
newdist = minimumMarchingDistance(nbdist, nbflag);
if ( (!narrowBandOnly && !almostEverywhere)
|| (narrowBandOnly && newdist<=narrowBandDist+extraDist)
|| (almostEverywhere && (segmentation[xyzn]!=0 || newdist<=narrowBandDist+extraDist) ) ) {
// add to the heap
heap.addValue(newdist,xyzn,lb);
}
}
}
}
}
// to create the MGDM functions, we need to copy the segmentation, forget the last labels
// and compute differences between distance functions
if (debug) BasicInfo.displayMessage("transform into MGDM functions\n");
for (int xyz = 0; xyz<nax*nay*naz; xyz++) if (mask[xyz]) {
// label permutation
for (int n=nmgdm;n>0;n--) {
mgdmlabels[n][xyz] = mgdmlabels[n-1][xyz];
}
mgdmlabels[0][xyz] = segmentation[xyz];
// distance function difference
for (int n = nmgdm-1; n>0; n--) {
mgdmfunctions[n][xyz] = Numerics.max(UNKNOWN, mgdmfunctions[n][xyz]
-mgdmfunctions[n-1][xyz]);
}
}
if (debug) BasicInfo.displayMessage("done (time: " + (System.currentTimeMillis()-start_time)+")\n");
return;
}
/**
* the Fast marching distance computation
* (!assumes a 6D array with opposite coordinates stacked one after the other)
*
*/
public final float minimumMarchingDistance(float[] val, boolean[] flag) {
// s = a + b +c; s2 = a*a + b*b +c*c
s = 0;
s2 = 0;
count = 0;
for (int n=0; n<6; n+=2) {
if (flag[n] && flag[n+1]) {
tmp = Numerics.min(val[n], val[n+1]); // Take the smaller one if both are processed
s += tmp;
s2 += tmp*tmp;
count++;
} else if (flag[n]) {
s += val[n]; // Else, take the processed one
s2 += val[n]*val[n];
count++;
} else if (flag[n+1]) {
s += val[n+1];
s2 += val[n+1]*val[n+1];
count++;
}
}
// count must be greater than zero since there must be at least one processed pt in the neighbors
tmp = (s+Math.sqrt( (s*s-count*(s2-1.0f))))/count;
// The larger root
return (float)tmp;
}
/**
* the isosurface distance computation
* (!assumes a 6D array with opposite coordinates stacked one after the other)
* (the input values are all positive, the flags are true only if the isosurface crosses)
*/
public final float isoSurfaceDistance(double cur, float[] val, boolean[] flag) {
if (cur==0) return 0;
s = 0;
dist = 0;
for (int n=0; n<6; n+=2) {
if (flag[n] && flag[n+1]) {
tmp = Numerics.max(val[n], val[n+1]); // Take the largest distance (aka closest to current point) if both are across the boundariy
s = cur/(cur+tmp);
dist += 1.0/(s*s);
} else if (flag[n]) {
s = cur/(cur+val[n]); // Else, take the boundariy point
dist += 1.0/(s*s);
} else if (flag[n+1]) {
s = cur/(cur+val[n+1]);
dist += 1.0/(s*s);
}
}
// triangular (tetrahedral?) relationship of height in right triangles gives correct distance
tmp = Math.sqrt(1.0/dist);
// The larger root
return (float)tmp;
}
/**
* isosurface distance re-initialization at the boundariy
*/
private final void resetIsosurfaceBoundary() {
if (debug) System.out.print("fast marching evolution: iso-surface reinit\n");
float[] nbdist = new float[6];
boolean[] nbflag = new boolean[6];
boolean boundary;
float[] tmp = new float[nax*nay*naz];
boolean[] processed = new boolean[nax*nay*naz];
for (int xyz = 0; xyz<nax*nay*naz; xyz++) if (mask[xyz]) {
boundary = false;
for (int l=0; l<6; l++) {
nbdist[l] = UNKNOWN;
nbflag[l] = false;
int xyznb = xyz + xoff[l] + yoff[l] + zoff[l];
if (segmentation[xyznb]!=segmentation[xyz] && mask[xyznb]) {
// compute new distance based on processed neighbors for the same object
nbdist[l] = Numerics.abs(mgdmfunctions[0][xyznb]);
nbflag[l] = true;
boundary = true;
}
}
if (boundary) {
tmp[xyz] = isoSurfaceDistance(mgdmfunctions[0][xyz], nbdist, nbflag);
processed[xyz] = true;
}
}
// once all the new values are computed, copy into original GDM function (sign is not important here)
for (int xyz = 0; xyz<nax*nay*naz; xyz++) {
if (processed[xyz]) mgdmfunctions[0][xyz] = tmp[xyz];
else mgdmfunctions[0][xyz] = UNKNOWN;
}
return;
}
private static class NarrowBand {
public int[] id;
public byte[][] labels;
public float[][] functions;
public int currentsize;
public int capacity;
public int update;
/** init: create an array of a given size for efficient storage */
public NarrowBand(int size, int increase) {
capacity = size;
update = increase;
currentsize = 0;
id = new int[capacity];
labels = new byte[nmgdm+1][capacity];
functions = new float[nmgdm][capacity];
}
public void finalize() {
capacity = -1;
id = null;
labels = null;
functions = null;
}
public final void addPoint(int xyz, byte[][] mgdmlabels, float[][] mgdmfn) {
// check for size
if (currentsize>=capacity-1) {
capacity += update;
int[] oldid = id;
byte[][] oldlabels = labels;
float[][] oldfunctions = functions;
id = new int[capacity];
labels = new byte[nmgdm+1][capacity];
functions = new float[nmgdm][capacity];
for (int n=0;n<currentsize;n++) {
id[n] = oldid[n];
for (int l=0;l<nmgdm;l++) {
labels[l][n] = oldlabels[l][n];
functions[l][n] = oldfunctions[l][n];
}
labels[nmgdm][n] = oldlabels[nmgdm][n];
}
oldid = null; oldlabels = null; oldfunctions = null;
}
// add the new point (use the MGDM variables)
id[currentsize] = xyz;
for (int l=0;l<nmgdm;l++) {
labels[l][currentsize] = mgdmlabels[l][xyz];
functions[l][currentsize] = mgdmfn[l][xyz];
}
labels[nmgdm][currentsize] = mgdmlabels[nmgdm][xyz];
currentsize++;
}
public void reset() {
currentsize = 0;
}
}
}
|
UstymUkhman/APE
|
src/constraints/HingeConstraints.js
|
import Constraints from '@/constraints/Constraints';
import { HINGE_ACCELERATION } from '@/constants';
import { Vector3 } from 'three/src/math/Vector3';
import { Ammo } from '@/utils';
export default class HingeConstraints extends Constraints {
constructor (world, events) {
super(world, 'Hinge');
this.events = events;
}
addBody (bodyMesh, axis, pivot = new Vector3()) {
this.events.emit('getHingeBody',
bodyMesh.uuid, {
pivot: pivot,
axis: axis
}
);
return this._uuid;
}
addBodies (pinMesh, armMesh, axis, pinPivot = new Vector3(), armPivot = new Vector3()) {
this.events.emit('getHingeBodies',
pinMesh.uuid, armMesh.uuid, {
pinPivot: pinPivot,
armPivot: armPivot,
axis: axis
}
);
return this._uuid;
}
hingeBody (body, position) {
/* eslint-disable new-cap */
const hinge = new Ammo.btHingeConstraint(body,
new Ammo.btVector3(position.pivot.x, position.pivot.y, position.pivot.z),
new Ammo.btVector3(position.axis.x, position.axis.y, position.axis.z)
);
/* eslint-enable new-cap */
this.add(hinge);
}
hingeBodies (pin, arm, position) {
/* eslint-disable new-cap */
const armAxis = new Ammo.btVector3(position.axis.x, position.axis.y, position.axis.z);
const hinge = new Ammo.btHingeConstraint(
pin, arm,
new Ammo.btVector3(position.pinPivot.x, position.pinPivot.y, position.pinPivot.z),
new Ammo.btVector3(position.armPivot.x, position.armPivot.y, position.armPivot.z),
armAxis, armAxis, true
);
/* eslint-enable new-cap */
this.add(hinge);
}
setLimit (uuid, low = Math.PI, high = Math.PI, bias = 0, relaxation = 0) {
const constraint = this.getConstraintByUUID(uuid);
constraint.setLimit(low, high, 0, bias, relaxation);
}
enableMotor (uuid, velocity = 1, acceleration = HINGE_ACCELERATION) {
const constraint = this.getConstraintByUUID(uuid);
constraint.enableAngularMotor(true, velocity, acceleration);
}
disableMotor (uuid) {
const constraint = this.getConstraintByUUID(uuid);
constraint.enableMotor(false);
}
}
|
lol768/tabula
|
common/src/main/scala/uk/ac/warwick/tabula/data/convert/AssignmentFeedbackIdConverter.scala
|
package uk.ac.warwick.tabula.data.convert
import org.springframework.beans.factory.annotation.Autowired
import uk.ac.warwick.tabula.data.FeedbackDao
import uk.ac.warwick.tabula.data.model.{AssignmentFeedback, Feedback}
import uk.ac.warwick.tabula.system.TwoWayConverter
class AssignmentFeedbackIdConverter extends TwoWayConverter[String, AssignmentFeedback] {
@Autowired var service: FeedbackDao = _
override def convertRight(id: String): AssignmentFeedback = service.getAssignmentFeedback(id).orNull
override def convertLeft(feedback: AssignmentFeedback): String = (Option(feedback) map {_.id}).orNull
}
|
GeminiWy/ShapedExamProj
|
app/src/main/java/com/nd/shapedexamproj/util/RemoveHtmlImgUtil.java
|
<filename>app/src/main/java/com/nd/shapedexamproj/util/RemoveHtmlImgUtil.java
package com.nd.shapedexamproj.util;
import android.text.Html;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 移除HTML标签中的IMG获取到照片URL
*
* @author Xujs
*
*/
public class RemoveHtmlImgUtil {
private final String TAG = "RemoveHtmlImgUtil";
private final static String IMAGE_TAG = "<[img|IMG]+[^>]*src=\"(http:\\/\\/[^\"]+\\.[jpg|jpeg|bmp|gif|png|JPG|JPEG|BMP|GIF|PNG]+\\b)\"[^>]*/*>";
private final static String HTML_IMAGE_TAG = "<img src=";
public static List<String> getImageUrl(String content) {
ArrayList<String[]> data = new ArrayList<String[]>();
List<String> imageUrlList = new ArrayList<String>();
Pattern patternImage = Pattern.compile(IMAGE_TAG);
Matcher matcher = patternImage.matcher(content);
int pend = 0;
while (matcher.find()) {
String preContentTxt = content.substring(pend, matcher.start());
String imagePath = matcher.group(1);
pend = matcher.end();
preContentTxt = fixText(preContentTxt);
data.add(new String[] { imagePath,
Html.fromHtml(preContentTxt).toString() });
}
if (pend < content.length() && data.size() > 0) {
int size = data.size();
String[] lastData = data.get(size - 1);
String text = fixText(content.substring(pend, content.length())
.toString());
lastData[1] += Html.fromHtml(text);
}
for (String[] imagesUrlStr : data) {
imageUrlList.add(imagesUrlStr[0]);
}
return imageUrlList;
}
protected static String fixText(String text) {
if (text != null) {
text = text.trim().replaceAll("\\\\+", "");
text = text.replace("&", "&");
}
return text;
}
/**
* 获取评论内容 去除IMG 包含内容和表情
* 适用于包含<img src=标题的内容
* @param content
* @return
*/
public static String getContentValue(String mycontent) {
String contentValue = "";
int countValueNum = -1;
if(mycontent.contains(HTML_IMAGE_TAG)){
countValueNum = mycontent.indexOf(HTML_IMAGE_TAG);
contentValue = mycontent.substring(0, countValueNum);
System.out.println("xxxx countValueNum:" + countValueNum
+ " contentValue:" + contentValue);
}
return contentValue;
}
}
|
sahil839/RemotePC
|
Client/app/src/main/java/com/example/client/UpdateScreen.java
|
<filename>Client/app/src/main/java/com/example/client/UpdateScreen.java
package com.example.client;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.util.TimerTask;
import java.util.Timer;
public class UpdateScreen {
Activity screen_activity;
long delay = 0;
long period = 500;
UpdateScreen(Activity activity) {
screen_activity = activity;
RemoteScreen.updateScreenTimer = new Timer();
TimerTask updateScreenTask = new TimerTask() {
@Override
public void run() {
FileOutputStream fos = null;
String filename = "screen.jpeg";
try {
MakeConnection.screenOutputStream.writeObject("SEND_SCREEN");
fos = screen_activity.openFileOutput(filename, Context.MODE_PRIVATE);
byte buffer[] = new byte[4096];
int fileSize = (int) MakeConnection.screenInputStream.readObject();
int read = 0;
int remaining = fileSize;
while ((read = MakeConnection.screenInputStream.read(buffer, 0, Math.min(buffer.length, remaining))) > 0) {
remaining -= read;
fos.write(buffer, 0, read);
}
} catch (Exception e) {
RemoteScreen.updateScreenTimer.cancel();
RemoteScreen.updateScreenTimer.purge();
}
screen_activity.runOnUiThread(() -> {
Bitmap bitmap;
File imageFile = new File(screen_activity.getFilesDir(), filename);
String path = imageFile.getAbsolutePath();
bitmap = BitmapFactory.decodeFile(path);
if (bitmap != null) {
Matrix matrix = new Matrix();
matrix.postRotate(-90);
try {
Bitmap rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
RemoteScreen.screenView.setImageBitmap(rotated);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
RemoteScreen.updateScreenTimer.scheduleAtFixedRate(updateScreenTask, delay, period);
}
}
|
kozzztik/tulius
|
tulius/core/debug_mail/views.py
|
<filename>tulius/core/debug_mail/views.py
import os
import datetime
from django import http
from django.views import generic
from django.conf import settings
from django.core import exceptions
class RecipientsAPI(generic.View):
@staticmethod
def get(request, *args, **_kwargs):
if not request.user.is_superuser:
raise exceptions.PermissionDenied()
base_dir = settings.EMAIL_FILE_PATH
query = request.GET.get('q')
result = []
for file_name in os.listdir(base_dir):
path = os.path.join(base_dir, file_name)
if os.path.isdir(path) and ((not query) or query in file_name):
result.append({
'name': file_name,
'count': len(os.listdir(path))
})
return http.JsonResponse({'result': result})
class MailboxAPI(generic.View):
@staticmethod
def get(request, email, **_kwargs):
if not request.user.is_superuser:
raise exceptions.PermissionDenied()
base_dir = os.path.join(settings.EMAIL_FILE_PATH, email)
result = []
for entry in os.scandir(path=base_dir):
if entry.is_file():
timestamp = entry.stat().st_mtime_ns
result.append({
'name': entry.name,
'size': entry.stat().st_size,
'timestamp': timestamp,
'date': str(datetime.datetime.fromtimestamp(
timestamp / 1000000000))
})
result.sort(key=lambda x: x['timestamp'], reverse=True)
return http.JsonResponse({'result': result[:100]})
class MailAPI(generic.View):
@staticmethod
def get(request, email, pk, **_kwargs):
if not request.user.is_superuser:
raise exceptions.PermissionDenied()
file_name = os.path.join(settings.EMAIL_FILE_PATH, email, pk)
f = open(file_name, 'rb')
try:
data = f.read()
finally:
f.close()
return http.HttpResponse(data)
|
emfmesquita/BeyondHelp
|
src/contentscript/extensioncontentscript.js
|
import "./extensioncontentstyle.scss";
import $ from "jquery";
import C from "../Constants";
import CampaignCharactersService from "./characters/CampaignCharactersService";
import ConfigStorageService from "../services/storage/ConfigStorageService";
import Configuration from "../data/Configuration";
import ContentScriptService from "./ContentScriptService";
import ExtraMapRefsMode from "./maps/extrarefsmode/ExtraMapRefsMode";
import FavIconService from "./favicon/FavIconService";
import MapsService from "./maps/MapsService";
import MessageService from "../services/MessageService";
import MonstersService from "./monsters/MonstersService";
import MyCharactersService from "./characters/MyCharactersService";
import Opt from "../Options";
import PageScriptService from "../services/PageScriptService";
import PlayByPostService from "./playbypost/PlayByPostService";
import React from 'react';
import ReactDOM from 'react-dom';
import ReferencesService from "./references/ReferencesService";
import TOCService from "./tableofcontents/TOCService";
import TableRollService from "./tableroll/TableRollService";
import TinyMCEService from "./tinymce/TinyMCEService";
import TooltipsService from "./tooltips/TooltipsService";
const tooltipsInit = function (config: Configuration) {
// workaround for homebrew spell tooltips that sever removes classes
if (config[Opt.HomebrewTooltips]) TooltipsService.homebrewSpellTooltipWorkaround();
// inits custom tooltips (backgrounds and feats) and ref tooltips
TooltipsService.bhTooltipsInit();
};
// inits the table rollers
const tablesInit = function (config: Configuration) {
if (config[Opt.TableRolls]) TableRollService.init();
};
const init = function (config: Configuration) {
// render the add monster buttons and cr indicators
MonstersService.init(config);
tablesInit(config);
tooltipsInit(config);
};
// listen a row loaded message to add monster buttons and parse tables
MessageService.listen(C.RowLoadedMessage, () => ConfigStorageService.getConfig().then(init));
// listen the message of comment changed
MessageService.listen(C.CommentChangedMessage, () => ConfigStorageService.getConfig().then(config => {
tablesInit(config);
tooltipsInit(config);
}));
// listen the message of extra map refs changes
MessageService.listen(C.ExtraMapRefsChangesMessage, (message) => ConfigStorageService.getConfig().then(config => {
// checks if was this tab that sent the message
if (message.originalSender.tab && message.originalSender.tab.id === window.bhTabId) return;
if (config[Opt.MapRefs]) MapsService.reload(config);
}));
ConfigStorageService.getConfig().then((config: Configuration) => {
// discontinued
return;
ContentScriptService.init(config);
init(config);
// change fav icon of char page
if (config[Opt.CharacterFavIcon]) FavIconService.changeCharacterFavIcon();
// change my characters page
if (config[Opt.MyCharactersFolders]) MyCharactersService.init(config);
// change campaign page
if (config[Opt.CampaignCharactersFolders]) CampaignCharactersService.init();
// adds the Beyond Help plugin to tiny editors on page
if (config[Opt.EditorButton] || config[Opt.FullscreenButton]) TinyMCEService.init();
// handles errors loading tooltips
if (config[Opt.HomebrewTooltips]) TooltipsService.listenTooltipError();
// intits the Table of Contents on compendium Pages
if (config[Opt.ToC]) TOCService.init();
// inits map references
if (config[Opt.MapRefs]) MapsService.init(config);
// extra map references mode
if (config[Opt.ExtraMapRefsDrawingBundle]) ExtraMapRefsMode.init();
// inits the refs on compendium pages
if (config[Opt.RefButtons]) ReferencesService.init();
// inits campaign notes textarea on pbp pages
if (config[Opt.PbpNotes]) PlayByPostService.init();
});
|
nadeemnazeer3/dremio-oss
|
dac/ui/src/pages/ExplorePage/components/ExploreTable/JoinTables.js
|
/*
* Copyright (C) 2017-2018 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Component } from 'react';
import Immutable from 'immutable';
import Radium from 'radium';
import { connect } from 'react-redux';
import pureRender from 'pure-render-decorator';
import PropTypes from 'prop-types';
import EllipsedText from 'components/EllipsedText';
import { formLabel, formDescription } from 'uiTheme/radium/typography';
import { getJoinTable, getExploreState } from 'selectors/explore';
import { getViewState } from 'selectors/resources';
import Spinner from 'components/Spinner';
import { constructFullPath } from 'utils/pathUtils';
import { JOIN_TABLE_VIEW_ID } from 'components/Wizards/JoinWizard/JoinController';
import { accessEntity } from 'actions/resources/lru';
import { CUSTOM_JOIN } from 'constants/explorePage/joinTabs';
import { ExploreInfoHeader } from '../ExploreInfoHeader';
import ExploreTableController from './ExploreTableController';
const WIDTH_SCALE = 0.495;
@Radium
@pureRender
export class JoinTables extends Component {
static propTypes = {
pageType: PropTypes.string.isRequired,
dataset: PropTypes.instanceOf(Immutable.Map),
joinTableData: PropTypes.object,
exploreViewState: PropTypes.instanceOf(Immutable.Map),
joinViewState: PropTypes.instanceOf(Immutable.Map),
location: PropTypes.object,
sqlSize: PropTypes.number,
rightTreeVisible: PropTypes.bool,
accessEntity: PropTypes.func.isRequired,
joinDatasetFullPath: PropTypes.string,
joinVersion: PropTypes.string,
joinTab: PropTypes.string,
joinStep: PropTypes.number
};
componentWillReceiveProps(nextProps) {
// because we have two tables visible, it's possible to evict the left table by looking at enough different
// right tables. So accesss the left tableData every time the right tableData changes
if (nextProps.joinVersion !== this.props.joinVersion) {
nextProps.accessEntity('tableData', this.props.dataset.get('datasetVersion'));
}
}
shouldRenderSecondTable() {
const isOnCustomJoinSelectStep = this.props.joinTab === CUSTOM_JOIN && this.props.joinStep !== 2;
return isOnCustomJoinSelectStep && !this.props.exploreViewState.get('isInProgress');
}
renderSecondTable() {
if (!this.shouldRenderSecondTable()) {
return null;
}
const { joinTableData, joinViewState, rightTreeVisible, sqlSize, location } = this.props;
if ((!joinTableData || !joinTableData.get('columns').size) && !joinViewState.get('isFailed')) {
const customTableContent = joinViewState && joinViewState.get('isInProgress')
? (
<Spinner
style={styles.emptyTable}
iconStyle={{color: 'gray'}}
/>
)
: (
<div style={[styles.emptyTable, formDescription]}>
{la('Please add one or more join conditions to preview matching records.')}
</div>
);
return customTableContent;
}
return (
<ExploreTableController
isDumbTable
pageType={this.props.pageType}
dataset={this.props.dataset}
exploreViewState={joinViewState}
tableData={joinTableData}
widthScale={WIDTH_SCALE}
dragType='join'
location={location}
sqlSize={sqlSize}
rightTreeVisible={rightTreeVisible}
/>
);
}
render() {
const { location, sqlSize, rightTreeVisible, dataset, exploreViewState } = this.props;
const nameForDisplay = ExploreInfoHeader.getNameForDisplay(dataset);
const scale = this.shouldRenderSecondTable()
? WIDTH_SCALE
: 1;
const tableBlockStyle = !this.shouldRenderSecondTable() ? { maxWidth: '100%', width: 'calc(100% - 10px)'} : {};
return (
<div style={[styles.base]}>
<div style={[styles.tableBlock, tableBlockStyle]}>
<div style={styles.header}><EllipsedText text={nameForDisplay} /></div>
<ExploreTableController
pageType={this.props.pageType}
dataset={this.props.dataset}
dragType='groupBy'
widthScale={scale}
location={location}
sqlSize={sqlSize}
rightTreeVisible={rightTreeVisible}
exploreViewState={exploreViewState}
/>
</div>
<div style={[styles.tableBlock, { marginLeft: 5}, !this.shouldRenderSecondTable() ? { display: 'none'} : {} ]}>
<div style={[styles.header, !this.props.joinDatasetFullPath && {fontStyle: 'italic'}]}>
<EllipsedText text={this.props.joinDatasetFullPath || la('No table selected.')}/>
</div>
{this.renderSecondTable()}
</div>
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
const explorePageState = getExploreState(state);
return {
joinTableData: getJoinTable(state, ownProps),
joinViewState: getViewState(state, JOIN_TABLE_VIEW_ID),
joinDatasetFullPath: constructFullPath(explorePageState.join.getIn(['custom', 'joinDatasetPathList'])),
joinTab: explorePageState.join.get('joinTab'),
joinVersion: explorePageState.join.getIn(['custom', 'joinVersion']),
joinStep: explorePageState.join.get('step')
};
};
export default connect(mapStateToProps, {
accessEntity
})(JoinTables);
const styles = {
base: {
display: 'flex',
flexGrow: 1,
backgroundColor: '#F5FCFF'
},
tableBlock: {
display: 'flex',
maxWidth: 'calc(50% - 10px)',
minWidth: 'calc(50% - 10px)',
flexDirection: 'column',
position: 'relative'
},
header: {
...formLabel,
height: 25,
backgroundColor: '#F3F3F3',
zIndex: 1,
display: 'flex',
alignItems: 'center',
padding: '0 10px',
marginRight: -5, // hack for alignment
flexGrow: 0
},
emptyTable: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
minWidth: '100%',
minHeight: 300,
backgroundColor: '#F3F3F3',
border: '1px dotted gray',
zIndex: 1,
flexGrow: 1
},
spinner: {
width: 'calc(50% - 26px)',
height: 'calc(100% - 440px)',
backgroundColor: '#F3F3F3',
border: '1px dotted gray',
alignItems: 'center',
zIndex: 1,
flexGrow: 1
}
};
|
vadi2/codeql
|
javascript/ql/test/library-tests/Closure/tests/googModuleDefault.js
|
goog.module('x.y.z.googdefault');
exports = function fun() {};
|
pojkem/sds
|
pp/peers/pp.go
|
<reponame>pojkem/sds
package peers
import (
"net"
"github.com/stratosnet/sds/framework/core"
"github.com/stratosnet/sds/utils"
)
//todo: pp server should be move out of peers package
// PPServer
type PPServer struct {
*core.Server
}
var ppServ *PPServer
// GetPPServer
func GetPPServer() *PPServer {
return ppServ
}
func SetPPServer(pp *PPServer) {
ppServ = pp
}
// StartListenServer
func StartListenServer(port string) {
netListen, err := net.Listen("tcp4", port)
if err != nil {
utils.ErrorLog("StartListenServer", err)
}
spbServer := NewServer()
ppServ = spbServer
utils.Log("StartListenServer!!! ", port)
err = spbServer.Start(netListen)
if err != nil {
utils.ErrorLog("StartListenServer Error", err)
}
}
// NewServer returns a server.
func NewServer() *PPServer {
onConnectOption := core.OnConnectOption(func(conn core.WriteCloser) bool {
utils.Log("on connect")
return true
})
onErrorOption := core.OnErrorOption(func(conn core.WriteCloser) {
utils.Log("on error")
})
onCloseOption := core.OnCloseOption(func(conn core.WriteCloser) {
net := conn.(*core.ServerConn).GetName()
netID := conn.(*core.ServerConn).GetNetID()
removePeer(netID)
utils.DebugLog(net, netID, "offline")
})
bufferSize := core.BufferSizeOption(10000)
return &PPServer{
core.CreateServer(onConnectOption, onErrorOption, onCloseOption, bufferSize),
}
}
func removePeer(netID int64) {
f := func(k, v interface{}) bool {
if v == netID {
RegisterPeerMap.Delete(k)
return false
}
return true
}
RegisterPeerMap.Range(f)
}
|
overstock/swagger-core
|
modules/swagger-core/src/test/scala/converter/XMLGregorianCalendarTest.scala
|
package converter
import models._
import com.wordnik.swagger.annotations._
import com.wordnik.swagger.converter._
import com.wordnik.swagger.core.util._
import com.wordnik.swagger.model._
import org.joda.time.DateTime
import scala.collection.mutable.LinkedHashMap
import scala.annotation.meta.field
import javax.xml.datatype.XMLGregorianCalendar
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FlatSpec
import org.scalatest.Matchers
@RunWith(classOf[JUnitRunner])
class XMLGregorianCalendarTest extends FlatSpec with Matchers {
it should "read a model with XMLGregorianCalendar" in {
val models = ModelConverters.readAll(classOf[ModelWithCalendar])
models.size should be (1) // don't create a Joda DateTime object
val model = models.head
val nameProperty = model.properties("name")
nameProperty.`type` should be ("string")
nameProperty.position should be (2)
nameProperty.description should be (Some("name of the model"))
val dateTimeProperty = model.properties("createdAt")
dateTimeProperty.`type` should be ("Date")
dateTimeProperty.position should be (1)
dateTimeProperty.required should be (true)
dateTimeProperty.description should be (Some("creation timestamp"))
}
}
case class ModelWithCalendar (
@(ApiModelProperty @field)(value = "name of the model", position = 2) name: String,
@(ApiModelProperty @field)(value = "creation timestamp", required = true, position = 1) createdAt: XMLGregorianCalendar)
|
uk-gov-mirror/alphagov.finder-frontend
|
spec/factories/brexit_checker/notification.rb
|
<gh_stars>10-100
FactoryBot.define do
factory :brexit_checker_notification, class: BrexitChecker::Notification do
id { SecureRandom.uuid }
action_id { SecureRandom.uuid }
type { "addition" }
date { "2019-08-07" }
initialize_with { BrexitChecker::Notification.new(attributes) }
end
end
|
ilyasku/readdy
|
readdy/main/io/BloscFilter.cpp
|
/********************************************************************
* Copyright © 2018 Computational Molecular Biology Group, *
* Freie Universität Berlin (GER) *
* *
* Redistribution and use in source and binary forms, with or *
* without modification, are permitted provided that the *
* following conditions are met: *
* 1. Redistributions of source code must retain the above *
* copyright notice, this list of conditions and the *
* following disclaimer. *
* 2. Redistributions in binary form must reproduce the above *
* copyright notice, this list of conditions and the following *
* disclaimer in the documentation and/or other materials *
* provided with the distribution. *
* 3. Neither the name of the copyright holder nor the names of *
* its contributors may be used to endorse or promote products *
* derived from this software without specific *
* prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND *
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF *
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR *
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, *
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; *
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, *
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) *
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF *
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
********************************************************************/
/**
* << detailed description >>
*
* @file BloscFilter.cpp
* @brief << brief description >>
* @author clonker
* @date 06.09.17
* @copyright BSD-3
*/
#include "readdy/io/BloscFilter.h"
#include "blosc_filter.h"
namespace readdy::io {
bool BloscFilter::available() const {
return H5Zfilter_avail(FILTER_BLOSC) > 0;
}
void BloscFilter::activate(h5rd::PropertyList &plist) {
registerFilter();
unsigned int cd_values[7];
// compression level 0-9 (0 no compression, 9 highest compression)
cd_values[4] = compressionLevel;
// 0: shuffle not active, 1: shuffle active
cd_values[5] = shuffle ? 1 : 0;
// the compressor to use
switch (compressor) {
case BloscLZ: {
cd_values[6] = BLOSC_BLOSCLZ;
break;
}
case LZ4: {
cd_values[6] = BLOSC_LZ4;
break;
}
case LZ4HC: {
cd_values[6] = BLOSC_LZ4HC;
break;
}
case SNAPPY: {
cd_values[6] = BLOSC_SNAPPY;
break;
}
case ZLIB: {
cd_values[6] = BLOSC_ZLIB;
break;
}
case ZSTD: {
cd_values[6] = BLOSC_ZSTD;
break;
}
}
if (H5Pset_filter(plist.id(), FILTER_BLOSC, H5Z_FLAG_OPTIONAL, 7, cd_values) < 0) {
H5Eprint(H5Eget_current_stack(), stderr);
throw h5rd::Exception("Could not set blosc filter!");
}
}
void BloscFilter::registerFilter() {
static std::atomic_bool initialized{false};
if (!initialized.load()) {
char *version, *date;
register_blosc(&version, &date);
log::debug("registered blosc with version {} ({})", version, date);
initialized = true;
}
}
BloscFilter::BloscFilter(BloscFilter::Compressor compressor, unsigned int compressionLevel, bool shuffle) : compressor(
compressor), compressionLevel(compressionLevel), shuffle(shuffle) {
if (compressionLevel > 9) {
throw std::invalid_argument("Blosc only allows compression levels ranging from 0 to 9.");
}
}
}
|
sobolevn/putout
|
packages/plugin-simplify-ternary/test/fixture/identifier.js
|
var b = a ? a: m;
|
LeoRiether/Competicao-Programativa
|
implementations/ZAlgo_cversion.cpp
|
#include <stdio.h>
// #define printf(x...)
int strlen(const char* s) {
int i = -1;
while (s[++i]);
return i;
}
char* strbuild(char* dest, char* a, char* b) {
int k = 0;
for (int i = 0; a[i]; dest[k++] = a[i++]);
dest[k++] = '$';
for (int i = 0; b[i]; dest[k++] = b[i++]);
return dest+k;
}
void buildZ(int* z, char* s) {
z[0] = 0;
int n = strlen(s);
int l = 0, r = 0;
for (int i = 1; i < n; i++) {
z[i] = i+z[i-l] < r ? z[i-l] : 0;
while (i+z[i] < n && s[z[i]] == s[i+z[i]]) {
l = i; r = i+z[i]; z[i]++;
}
}
}
int main() {
int z[100005];
char pat[] = "ACBACDA";
char text[] = "ACBACDACBACBACDA"; // match on 0 and 6
char str[100005];
strbuild(str, pat, text);
int n = strlen(str);
buildZ(z, str);
printf("Z Array: ");
for (int i = 0; i < n; i++)
printf("%d ", z[i]);
puts("");
int plen = strlen(pat);
for (int i = 0; i < n; i++) {
if (z[i] == plen)
printf("Match found on %d.\n", i - plen-1);
}
return 0;
}
|
notow666/momo-cloud-permission
|
momo-permission-system-core/momo-permission-system-core-mapper/src/main/java/com/momo/mapper/res/aclmanager/SysEnterpriseRoleRes.java
|
<filename>momo-permission-system-core/momo-permission-system-core-mapper/src/main/java/com/momo/mapper/res/aclmanager/SysEnterpriseRoleRes.java
package com.momo.mapper.res.aclmanager;
import com.github.pagehelper.PageInfo;
import com.momo.mapper.dataobject.RoleDO;
import lombok.*;
/**
* @ProjectName: momo-cloud-permission
* @Package: com.momo.mapper.res.aclmanager
* @Description: TODO
* @Author: <NAME>
* @CreateDate: 2019/8/17 0017 10:57
* @UpdateDate: 2019/8/17 0017 10:57
* @Version: 1.0
* <p>Copyright: Copyright (c) 2019</p>
*/
@Getter
@Setter
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
//@EqualsAndHashCode(callSuper = true, of = {"id"})
public class SysEnterpriseRoleRes extends RoleDO {
//是否显示编辑按钮
private boolean editButtonShow = true;
//是否显示授权按钮
private boolean authorButtonShow = true;
//是否显示状态按钮
private boolean disabledFlagButtonShow = true;
private PageInfo<SysEnterpriseRoleRes> sysEnterpriseRoleResPageInfo;
//企业名称
private String sysEnterpriseName;
}
|
Vatsalparsaniya/c-
|
linked-lists/bubble-sort/list.c
|
<reponame>Vatsalparsaniya/c-
#include <stdio.h>
#include <stdlib.h>
#include "item.h"
#include "list.h"
link NEW(item key, link next) {
link x = malloc(sizeof(*x));
x->key = key;
x->next = next;
return x;
}
void list_compexch(link a, link b) {
link t;
if (item_less(b->next->key, a->next->key)) {
t = b->next;
b->next = b->next->next;
t->next = b;
a->next = t;
}
}
link list_init(int N) {
int i;
link x;
x = NEW(item_rand(), NULL);
for (i = 1; i < N; ++i) {
x = NEW(item_rand(), x);
}
x = NEW(item_dummy(), x);
return x;
}
void list_show(link h) {
for (; h->next != NULL; h = h->next) {
item_show(h->next->key);
}
printf("\n");
}
link list_sort(link h) {
link x, t, out = NULL;
while (h->next != NULL) {
for (x = h; x->next != NULL; x = x->next) {
if (x->next->next == NULL) {
t = x->next;
x->next = NULL;
t->next = out;
out = t;
break;
} else {
list_compexch(x, x->next);
}
}
}
h->next = out;
return h;
}
|
greensnow25/javaaz
|
chapter9/testTask/src/main/java/com/greensnow25/servlet/Delete.java
|
package com.greensnow25.servlet;
import com.greensnow25.repository.dao.AddressDAOImpl;
import com.greensnow25.repository.dao.UserDAOImpl;
import com.greensnow25.dataBase.CreateConnection;
import com.greensnow25.entity.Address;
import com.greensnow25.entity.User;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Public class Delete.
*
* @author greensnow25.
* @version 1.
* @since 18.10.2017.
*/
public class Delete extends HttpServlet {
/**
* connection pool.
*/
private CreateConnection connection;
@Override
public void init() throws ServletException {
this.connection = new CreateConnection();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
String role = (String) session.getAttribute("userRole");
String deleteName = req.getParameter("deleteUser");
if (role.equals("ADMIN")) {
try (Connection connection = this.connection.getConnection()) {
connection.setAutoCommit(false);
UserDAOImpl userDAO = new UserDAOImpl(connection);
AddressDAOImpl addressDAO = new AddressDAOImpl(connection);
User user = userDAO.getOneByName(deleteName);
int id = user.getId();
userDAO.delete(new User(deleteName, null, 0));
addressDAO.delete(new Address(null, null, id));
connection.commit();
req.getRequestDispatcher("/showTable").forward(req, resp);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
|
tejasvinu/hetu-core
|
presto-main/src/test/java/io/prestosql/utils/TestRangeUtil.java
|
<gh_stars>100-1000
/*
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. 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.
*/
package io.prestosql.utils;
import io.prestosql.spi.heuristicindex.IndexMetadata;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class TestRangeUtil
{
@Test
public void testSubArray()
throws Exception
{
long[] arr = {1, 2, 8, 10, 10, 12, 19};
List result = RangeUtil.subArray(createIndexList(arr), 7, 13);
assertEquals(6, result.size());
List expected = createIndexList(new long[] {2, 8, 10, 10, 12, 19});
assertTrue(compareIndexLists(expected, result));
result = RangeUtil.subArray(createIndexList(arr), 1, 10);
assertEquals(4, result.size());
List expected2 = createIndexList(new long[] {1, 2, 8, 10});
assertTrue(compareIndexLists(expected2, result));
}
@Test
public void testSubArray2()
throws Exception
{
long[] arr = {0, 20000, 40000, 60000, 80000, 100000, 120000};
List result = RangeUtil.subArray(createIndexList(arr), 1000, 60000);
List expected = createIndexList(new long[] {0, 20000, 40000, 60000});
assertTrue(compareIndexLists(expected, result));
}
@Test
public void testSubArray3()
throws Exception
{
long[] arr = {0, 20000};
List result = RangeUtil.subArray(createIndexList(arr), 0, 20000);
List expected = createIndexList(new long[] {0, 20000});
assertTrue(compareIndexLists(expected, result));
}
@Test
public void testSubArrayOutOfStartRange()
throws Exception
{
List<IndexMetadata> indices = createIndexList(new long[] {1, 2, 8, 10, 10, 12, 19});
List<IndexMetadata> result = RangeUtil.subArray(indices, 0, 19);
assertEquals(7, result.size());
assertTrue(compareIndexLists(indices, result));
}
@Test
public void testSubArrayOutOfEndRange()
throws Exception
{
List<IndexMetadata> indices = createIndexList(new long[] {1, 2, 8, 10, 10, 12, 19});
List<IndexMetadata> result = RangeUtil.subArray(indices, 1, 20);
assertEquals(7, result.size());
assertTrue(compareIndexLists(indices, result));
}
@Test
public void testFindStart()
throws Exception
{
/* Driver program to check above functions */
long[] arr = {1, 2, 8, 10, 10, 12, 19};
int n = arr.length;
List<IndexMetadata> indices = createIndexList(arr);
assertEquals(0, RangeUtil.ceilSearch(indices, 0, n - 1, 0));
assertEquals(0, RangeUtil.ceilSearch(indices, 0, n - 1, -1));
assertEquals(2, RangeUtil.ceilSearch(indices, 0, n - 1, 7));
assertEquals(2, RangeUtil.ceilSearch(indices, 0, n - 1, 8));
assertEquals(6, RangeUtil.ceilSearch(indices, 0, n - 1, 19));
assertEquals(-1, RangeUtil.ceilSearch(indices, 0, n - 1, 20));
}
@Test
public void testFindEnd()
throws Exception
{
/* Driver program to check above functions */
long[] arr = {1, 2, 8, 10, 10, 12, 19};
int n = arr.length;
List<IndexMetadata> indices = createIndexList(arr);
assertEquals(-1, RangeUtil.floorSearch(indices, 0, n - 1, 0));
assertEquals(-1, RangeUtil.floorSearch(indices, 0, n - 1, -1));
assertEquals(1, RangeUtil.floorSearch(indices, 0, n - 1, 7));
assertEquals(2, RangeUtil.floorSearch(indices, 0, n - 1, 8));
assertEquals(6, RangeUtil.floorSearch(indices, 0, n - 1, 19));
assertEquals(6, RangeUtil.floorSearch(indices, 0, n - 1, 20));
}
// Create fake ExternalIndex list given the array of start offsets
private List<IndexMetadata> createIndexList(long[] arr)
{
List<IndexMetadata> list = new ArrayList<>();
for (long i : arr) {
IndexMetadata index = new IndexMetadata(null, null, null, null, null, i, 0);
list.add(index);
}
return list;
}
// Compare 2 ExternalIndex lists
private boolean compareIndexLists(List<IndexMetadata> expected, List<IndexMetadata> actual)
throws Exception
{
for (int i = 0; i < expected.size(); i++) {
if (RangeUtil.getOrder(expected.get(i)) != RangeUtil.getOrder(actual.get(i))) {
return false;
}
}
return true;
}
}
|
darmstrong1/filecopier
|
filecopier-cfg/src/test/java/net/sf/fc/cfg/AppConfigTest.java
|
<filename>filecopier-cfg/src/test/java/net/sf/fc/cfg/AppConfigTest.java<gh_stars>0
package net.sf.fc.cfg;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import net.sf.fc.script.gen.options.Filter;
import net.sf.fc.script.gen.options.OptionsScript;
import net.sf.fc.script.gen.settings.LogLevel;
import net.sf.fc.script.gen.settings.Settings;
import org.junit.Test;
import javax.xml.bind.JAXBException;
import static net.sf.fc.cfg.TestUtil.getOptionsHelper;
import static net.sf.fc.cfg.TestUtil.getSettingsHelper;
import static net.sf.fc.cfg.TestUtil.createDefaultOptionsObject;
import static net.sf.fc.cfg.TestUtil.createDefaultSettings;
public class AppConfigTest {
@Test
public void testDirectoryStructure() {
try {
new AppConfig(getSettingsHelper(), getOptionsHelper());
assertTrue(new File(System.getProperty("filecopier.home")).exists());
assertTrue(new File(System.getProperty("filecopier.scripts")).exists());
assertTrue(new File(System.getProperty("filecopier.scripts.copy")).exists());
assertTrue(new File(System.getProperty("filecopier.scripts.restore")).exists());
assertTrue(new File(System.getProperty("filecopier.scripts.options")).exists());
assertTrue(new File(System.getProperty("filecopier.cfg")).exists());
assertTrue(new File(System.getProperty("filecopier.log")).exists());
} catch(JAXBException e) {
e.printStackTrace();
assertTrue(false);
} catch(IOException e) {
e.printStackTrace();
assertTrue(false);
}
}
@Test
public void testGetDefaultOptions() {
try {
AppConfig appCfg = new AppConfig(getSettingsHelper(), getOptionsHelper());
OptionsScript o = appCfg.getDefaultOptions();
assertEquals(createDefaultOptionsObject(), o);
} catch(JAXBException e) {
e.printStackTrace();
assertTrue(false);
} catch(IOException e) {
e.printStackTrace();
assertTrue(false);
}
}
@Test
public void testSetDefaultOptions() {
try {
AppConfig appCfg = new AppConfig(getSettingsHelper(), getOptionsHelper());
OptionsScript o = appCfg.getDefaultOptions();
Filter copyFilter = new Filter();
copyFilter.setValue("filter");
copyFilter.setCaseSensitive(true);
o.getSrcDirOptions().setFileCopyFilter(copyFilter);
o.setCopyAttributes(false);
appCfg.setDefaultOptions(o);
OptionsScript o2 = appCfg.getDefaultOptions();
assertEquals(o, o2);
} catch(JAXBException e) {
e.printStackTrace();
assertTrue(false);
} catch(IOException e) {
e.printStackTrace();
assertTrue(false);
}
}
@Test
public void testGetSettings() {
try {
AppConfig appCfg = new AppConfig(getSettingsHelper(), getOptionsHelper());
Settings s = appCfg.getSettings();
assertEquals(createDefaultSettings(), s);
} catch(JAXBException e) {
e.printStackTrace();
assertTrue(false);
} catch(IOException e) {
e.printStackTrace();
assertTrue(false);
}
}
@Test
public void testSetSettings() {
try {
AppConfig appCfg = new AppConfig(getSettingsHelper(), getOptionsHelper());
Settings s = appCfg.getSettings();
s.getMostRecentlyUsed().setLimit(8);
s.setLogLevel(LogLevel.DEBUG);
appCfg.setSettings(s);
Settings s2 = appCfg.getSettings();
assertEquals(s, s2);
} catch(JAXBException e) {
e.printStackTrace();
assertTrue(false);
} catch(IOException e) {
e.printStackTrace();
assertTrue(false);
}
}
@Test
public void testSaveSettingsToDisk() {
try {
AppConfig appCfg = new AppConfig(getSettingsHelper(), getOptionsHelper());
Settings s = appCfg.getSettings();
s.getMostRecentlyUsed().setLimit(8);
s.setLogLevel(LogLevel.DEBUG);
appCfg.setSettings(s);
appCfg.saveSettingsToDisk();
Settings s2 = getSettingsHelper().unmarshal(new File(System.getProperty("filecopier.cfg"), "settings.xml"));
assertEquals(s, s2);
} catch(JAXBException e) {
e.printStackTrace();
assertTrue(false);
} catch(IOException e) {
e.printStackTrace();
assertTrue(false);
}
}
@Test
public void testSaveDefaultOptionsToDisk() {
try {
AppConfig appCfg = new AppConfig(getSettingsHelper(), getOptionsHelper());
OptionsScript o = appCfg.getDefaultOptions();
Filter copyFilter = new Filter();
copyFilter.setValue("filter");
copyFilter.setCaseSensitive(true);
o.getSrcDirOptions().setFileCopyFilter(copyFilter);
o.setCopyAttributes(false);
appCfg.setDefaultOptions(o);
appCfg.saveDefaultOptionsToDisk();
OptionsScript o2 = getOptionsHelper().unmarshal(new File(System.getProperty("filecopier.cfg"), "defaultOptions.xml"));
assertEquals(o, o2);
} catch(JAXBException e) {
e.printStackTrace();
assertTrue(false);
} catch(IOException e) {
e.printStackTrace();
assertTrue(false);
}
}
}
|
bvaudour/carapace-bin
|
completers/resume-cli_completer/cmd/serve.go
|
<filename>completers/resume-cli_completer/cmd/serve.go
package cmd
import (
"github.com/rsteube/carapace"
"github.com/spf13/cobra"
)
var serveCmd = &cobra.Command{
Use: "serve",
Short: "",
Run: func(cmd *cobra.Command, args []string) {},
}
func init() {
carapace.Gen(serveCmd).Standalone()
serveCmd.Flags().StringP("dir", "d", "", "indicate a public directory path")
serveCmd.Flags().BoolP("help", "h", false, "display help for command")
serveCmd.Flags().StringP("port", "p", "", "port used (default: 4000)")
serveCmd.Flags().StringP("resume", "r", "", "resume file")
serveCmd.Flags().BoolP("silent", "s", false, "open browser")
serveCmd.Flags().StringP("theme", "t", "", "theme name")
rootCmd.AddCommand(serveCmd)
carapace.Gen(serveCmd).FlagCompletion(carapace.ActionMap{
"dir": carapace.ActionDirectories(),
"resume": carapace.ActionFiles(),
"theme": carapace.ActionValues(
"jsonresume-theme-class",
"jsonresume-theme-classy",
"jsonresume-theme-elegant",
"jsonresume-theme-flat",
"jsonresume-theme-kendall",
"jsonresume-theme-kwan",
"jsonresume-theme-md",
"jsonresume-theme-modern",
"jsonresume-theme-onepage",
"jsonresume-theme-paper",
"jsonresume-theme-short",
"jsonresume-theme-slick",
"jsonresume-theme-spartan",
"jsonresume-theme-stackoverflow",
),
})
}
|
tobanteAudio/taetl
|
etl/experimental/hardware/mcp23017/mcp23017.hpp
|
/// \copyright <NAME> 2019-2021
/// Distributed under the Boost Software License, Version 1.0.
/// See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt
#ifndef TETL_HARDWARE_MCP23017_MCP23017_HPP
#define TETL_HARDWARE_MCP23017_MCP23017_HPP
#include "etl/version.hpp"
#include "etl/cstdint.hpp"
#include "etl/warning.hpp"
namespace etl::experimental::hardware::mcp23017 {
// ports
enum struct port : etl::uint16_t {
a = 0x00,
b = 0x01,
};
// Address (A0-A2)
enum struct address : etl::uint16_t {
a20 = 0x20,
a21 = 0x21,
a22 = 0x22,
a23 = 0x23,
a24 = 0x24,
a25 = 0x25,
a26 = 0x26,
a27 = 0x27,
};
// registers
enum struct registers : etl::uint16_t {
io_direction_a = 0x00, // datasheet: IODIRA
io_direction_b = 0x01, // datasheet: IODIRB
IPOLA = 0x02,
IPOLB = 0x03,
GPINTENA = 0x04,
GPINTENB = 0x05,
DEFVALA = 0x06,
DEFVALB = 0x07,
INTCONA = 0x08,
INTCONB = 0x09,
// IOCON 0x0A
// IOCON 0x0B
GPPUA = 0x0C,
GPPUB = 0x0D,
INTFA = 0x0E,
INTFB = 0x0F,
INTCAPA = 0x10,
INTCAPB = 0x11,
GPIOA = 0x12,
GPIOB = 0x13,
OLATA = 0x14,
OLATB = 0x15,
};
// I/O Direction
// Default state: io_direction::all_output
enum struct io_direction : etl::uint8_t {
all_output = 0x00,
all_input = 0xFF,
input_O0 = 0x01,
input_O1 = 0x02,
input_O2 = 0x04,
input_O3 = 0x08,
input_O4 = 0x10,
input_O5 = 0x20,
input_O6 = 0x40,
input_O7 = 0x80,
};
// Input Polarity
// Default state: MCP23017_IPOL_ALL_NORMAL
enum struct io_polarity : etl::uint8_t {
all_normal = 0x00,
all_inverted = 0xFF,
inverted_O0 = 0x01,
inverted_O1 = 0x02,
inverted_O2 = 0x04,
inverted_O3 = 0x08,
inverted_O4 = 0x10,
inverted_O5 = 0x20,
inverted_O6 = 0x40,
inverted_O7 = 0x80,
};
// Pull-Up Resistor
// Default state: MCP23017_GPPU_ALL_DISABLED
enum struct pull_up_resistor : etl::uint8_t {
all_disabled = 0x00,
all_enabled = 0xFF,
enabled_O0 = 0x01,
enabled_O1 = 0x02,
enabled_O2 = 0x04,
enabled_O3 = 0x08,
enabled_O4 = 0x10,
enabled_O5 = 0x20,
enabled_O6 = 0x40,
enabled_O7 = 0x80,
};
template <typename Driver>
struct device {
public:
explicit device() = default;
~device() = default;
device(device&&) = delete;
device(device const&) = delete;
auto operator=(device&&) -> device& = delete;
auto operator=(device const&) -> device& = delete;
auto init() -> bool { return true; }
auto set_io_direction(port p, io_direction direction) -> void
{
etl::ignore_unused(p, direction);
}
};
} // namespace etl::experimental::hardware::mcp23017
#endif // TETL_HARDWARE_MCP23017_MCP23017_HPP
|
saiteja6030/cmm
|
application/assets/pages/scripts/module.js
|
<filename>application/assets/pages/scripts/module.js
var module = function() {
var handlemodule = function() {
$('#module_frm').validate({
errorElement: 'span', //default input error message container
errorClass: 'help-block', // default input error message class
focusInvalid: false, // do not focus the last invalid input
messages: {
project_id: {
required: 'Project cannot be empty'
},
'module_name[]':{
required: 'Module cannot be empty'
},
'stage_id[]':{
required: 'Stage cannot be empty'
},
'start_date[]':{
required: 'Start Date cannot be empty'
},
'estimated_hours[]':{
required: 'Estimated Hours cannot be empty'
},
module_name:{
required: 'Module cannot be empty'
},
stage_id:{
required: 'Stage cannot be empty'
},
start_date:{
required: 'Start Date cannot be empty'
},
estimated_hours:{
required: 'Estimated Hours cannot be empty'
}
},
rules:
{
project_id: {
required: true
},
'stage_id[]': {
required: true
},
'module_name[]': {
required: true
},
'estimated_hours[]': {
required: true,
number:true,
},
'start_date[]': {
required: true
},
'description[]': {
maxlength: 255
},
stage_id: {
required: true
},
module_name: {
required: true
},
estimated_hours: {
required: true,
number:true,
},
start_date: {
required: true
}
},
invalidHandler: function(event, validator) { //display error alert on form submit
//$('.alert-danger', $('.reset-form')).show();
},
highlight: function(element) { // hightlight error inputs
$(element)
.closest('.form-group').addClass('has-error'); // set error class to the control group
},
success: function(label, element) {
var icon = $(element).parent('.input-icon').children('i');
$(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
icon.removeClass("fa-warning").addClass("fa-check");
},
errorPlacement: function(error, element) {
var icon = $(element).parent('.input-icon').children('i');
icon.removeClass('fa-check').addClass("fa-warning");
icon.attr("data-original-title", error.text()).tooltip({'container': 'body'});
},
submitHandler: function(form) {
form.submit(); // form validation success, call ajax form submit
}
});
$('#module_frm input').keypress(function(e) {
//alert('1213');
if (e.which == 13) {
if ($('#module_frm').validate().form()) {
$('#module_frm').submit(); //form validation success, call ajax form submit
}
return false;
}
});
}
return {
//main function to initiate the module
init: function() {
handlemodule();
}
};
}();
jQuery(document).ready(function() {
module.init();
});
function validateDateRange(start_date, end_date)
{
start_date.datepicker().on('change', function(e) {
if(end_date.val()=="")
end_date.datepicker('setStartDate', $(this).val());
else
if($(this).val() > end_date.val())
end_date.datepicker('setDate', $(this).val());
});
end_date.datepicker().on('change', function(e) {
if(start_date.val()=="")
start_date.datepicker('setEndDate', $(this).val());
else
if($(this).val()!="" && $(this).val() < start_date.val())
start_date.datepicker('setDate', $(this).val());
});
}
$('.removerow:first').hide();
$('#add').click(function()
{
var ele = $('#mytable').find('tbody tr:last');
var ele_clone = ele.clone();
ele_clone.find('input, textarea').val('');
ele_clone.find('td div.form-group').removeClass('has-success has-error');
ele_clone.find('td div.form-group div.input-icon i').removeClass('fa-check fa-warning');
ele_clone.find(".removerow").show();
ele_clone.find(".removerow").click(function ()
{
$(this).closest('tr').remove();
});
validateDateRange(ele_clone.find('.start_date'), ele_clone.find('.end_date'));
ele.after(ele_clone);
})
validateDateRange($('.start_date'), $('.end_date'));
$('#moduleName').blur(function(){
var modulename = $(this).val();
var projectid = $('#project_id').val();
var stageid = $('#stage_id').val();
var tasklevelid = 1;
var task_id = $('#task_id').val();
if(task_id=='')
{
task_id = 0;
}
if(modulename!='')
{
$("#modulenameValidating").removeClass("hidden");
$("#moduleError").addClass("hidden");
$.ajax({
type:"POST",
url:SITE_URL+'is_moduleExist',
data:{module_name:modulename, project_id:projectid, stage_id:stageid,task_level_id:tasklevelid,task_id:task_id},
cache:false,
success:function(html){
$("#modulenameValidating").addClass("hidden");
if(html==1)
{
$('#moduleName').val('');
$('#moduleName').prev('i').removeClass('fa-check').addClass('fa-warning');
$('#moduleName').closest('div.form-group').removeClass('has-success').addClass('has-error');
$('#moduleError').html('Sorry <b>'+modulename+'</b> has already been taken');
$("#moduleError").removeClass("hidden");
return false;
}
else
{
$('#moduleError').html('');
$("#moduleError").addClass("hidden");
return false;
}
}
});
}
});
|
yiyidhuang/PythonCrashCrouse2nd
|
ex2-4.py
|
name = "Tomas"
print(name.upper())
print(name.lower())
print(name.title())
|
123099/QuestJobs
|
libs/javassist/src/test/test2/ArrayLenTest.java
|
<reponame>123099/QuestJobs<filename>libs/javassist/src/test/test2/ArrayLenTest.java
package test2;
public class ArrayLenTest {
public int length = 1;
}
|
yunqi/lighthouse
|
internal/packet/unsubscribe.go
|
/*
* Copyright 2021 chenquan
*
* 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 packet
import (
"bytes"
"fmt"
"github.com/yunqi/lighthouse/internal/xerror"
"io"
)
type (
Unsubscribe struct {
Version Version
FixedHeader *FixedHeader
PacketId PacketId
Topics []string
}
)
// NewUnsubscribe returns a Unsubscribe instance by the given FixHeader and io.Reader.
func NewUnsubscribe(fixedHeader *FixedHeader, version Version, r io.Reader) (*Unsubscribe, error) {
p := &Unsubscribe{FixedHeader: fixedHeader, Version: version}
//判断 标志位 flags 是否合法[MQTT-3.10.1-1]
if fixedHeader.Flags != FixedHeaderFlagUnsubscribe {
return nil, xerror.ErrMalformed
}
err := p.Decode(r)
if err != nil {
return nil, err
}
return p, err
}
func (u *Unsubscribe) Encode(w io.Writer) (err error) {
u.FixedHeader = &FixedHeader{PacketType: UNSUBSCRIBE, Flags: FixedHeaderFlagUnsubscribe}
buf := &bytes.Buffer{}
writeUint16(buf, u.PacketId)
for _, topic := range u.Topics {
writeBinary(buf, []byte(topic))
}
return encode(u.FixedHeader, buf, w)
}
func (u *Unsubscribe) Decode(r io.Reader) (err error) {
b := make([]byte, u.FixedHeader.RemainLength)
_, err = io.ReadFull(r, b)
if err != nil {
return xerror.ErrMalformed
}
bufr := bytes.NewBuffer(b)
u.PacketId, err = readUint16(bufr)
if err != nil {
return
}
// topics
for bufr.Len() != 0 {
topicFilter, err := UTF8DecodedStrings(true, bufr)
if err != nil {
return err
}
if !ValidTopicFilter(true, topicFilter) {
return xerror.ErrProtocol
}
u.Topics = append(u.Topics, string(topicFilter))
}
return
}
func (u *Unsubscribe) String() string {
return fmt.Sprintf("Unsubscribe - Version: %s, PacketId: %d, Topics: %v", u.Version, u.PacketId, u.Topics)
}
|
mensfeld/rhodes
|
neon/Helium/HeliumForWindows/Implementation/Common/Private/RelativeURLs.cpp
|
#include "RelativeURLs.h"
/**
* \author <NAME> (DCC, JRQ768)
* \date February 2010 - Initial Creation, DCC
* \date June 2010 - Moving to a common location for File Transfer and Engines
* to both use, DCC
*/
BOOL IsRelativeURL(LPCTSTR tcURL)
{
// The URL is relative if it starts with a '.'
if (tcURL && wcsnicmp(tcURL, L".", 1) == 0)
return TRUE;
else
return FALSE;
}
/**
* \author <NAME> (DCC, JRQ768)
* \date February 2010 - Initial Creation, DCC
* \date June 2010 - Moving to a common location for File Transfer and Engines
* to both use, DCC
*/
BOOL DereferenceURL(LPCTSTR tcRelativeURLConst, TCHAR* tcDereferencedURL,
TCHAR* tcCurrentURL, PBModule* pModule)
{
BOOL retVal = FALSE;
TCHAR tcRelativeURL[MAX_URL];
wcscpy(tcRelativeURL, tcRelativeURLConst);
if (tcRelativeURL)
{
// First work out how many levels we need to navigate up from the
// current URL (specified as ../)
int iLevelsUp = 0;
wchar_t* temp = wcsstr(tcRelativeURL, L"..");
while (temp != NULL && (wcslen(temp) >= 2))
{
iLevelsUp++;
temp = wcsstr(temp + 2, L"..");
}
// We now know how many levels up we want to go from the current URL.
// Starting at the end of the current URL search for '/' or '\' and
// work out if we can go up that many levels.
TCHAR* pSzCurrentURL = tcCurrentURL + wcslen(tcCurrentURL) - 1;
// We do not want to include the protocol slashs in our search
TCHAR tempProtocol[10];
memset(tempProtocol, 0, 10 * sizeof(TCHAR));
int iLengthOfProtocol = GetProtocolFromURL(tcCurrentURL, tempProtocol) + 3;
while (pSzCurrentURL != tcCurrentURL + iLengthOfProtocol - 1)
{
if (*pSzCurrentURL == L'/' || *pSzCurrentURL == L'\\')
{
iLevelsUp--;
if (iLevelsUp == -1)
{
// pSzCurrentURL is pointing to the end of the URL
// we want to use as our base
break;
}
}
pSzCurrentURL--;
}
// If we exit the while loop and 'levelsUp' is not -1 then there were
// insufficient backslashes in the current URL to go up the number
// of levels specified in the relative URL.
if (iLevelsUp != -1)
{
if (pModule)
{
#ifndef PB_ENGINE_IE_CE
#ifndef PB_ENGINE_IE_MOBILE
pModule->Log(PB_LOG_ERROR, L"Unable to work out relative URL",
_T(__FUNCTION__), __LINE__);
#endif
#endif
}
return FALSE;
}
// The actual URL we require is the juxtaposition of m_szCurrentURL
// up to the pSzCurrentURL with the first non . | / | \ charcter in
// the relative URL
int iFirstNonRelativeCharacter = wcsspn(tcRelativeURL, L"./\\");
if (iFirstNonRelativeCharacter == wcslen(tcRelativeURL))
{
// User specified relative string without filename, e.g. .././../
if (pModule)
{
#ifndef PB_ENGINE_IE_CE
#ifndef PB_ENGINE_IE_MOBILE
pModule->Log(PB_LOG_ERROR, L"Unable to work out relative URL Filename",
_T(__FUNCTION__), __LINE__);
#endif
#endif
}
return FALSE;
}
TCHAR* pSzRelativeURLFilePathAndName = tcRelativeURL;
pSzRelativeURLFilePathAndName += iFirstNonRelativeCharacter;
// Test the new URL is not too long
if ((pSzCurrentURL - tcCurrentURL + 1) +
wcslen(pSzRelativeURLFilePathAndName) > MAX_URL)
{
if (pModule)
{
#ifndef PB_ENGINE_IE_CE
#ifndef PB_ENGINE_IE_MOBILE
pModule->Log(PB_LOG_ERROR, L"Relative URL produces URL string longer than maximum allowed",
_T(__FUNCTION__), __LINE__);
#endif
#endif
}
return FALSE;
}
wcsncpy(tcDereferencedURL, tcCurrentURL, pSzCurrentURL - tcCurrentURL + 1);
wcscat(tcDereferencedURL, pSzRelativeURLFilePathAndName);
retVal = TRUE;
}
return retVal;
}
/**
* \author <NAME> (JMS, JNP837)
* \author <NAME> (DCC, JRQ768)
* \date December 2009 - Initial Creation, JMS
* \date December 2009 - Bug Fixes, DCC
* \date June 2010 - Moving to a common location for File Transfer and Engines
* to both use, DCC
*/
int GetProtocolFromURL(LPCTSTR tcURL, LPTSTR lpRetStr)
{
//search for a ":" or "@" between the "://" and the next "/"
// | |
// v v v v
//ftp://username:password@hostname:port/
TCHAR* ptcStart = wcsstr(tcURL, L"://");
if (ptcStart == NULL)
return 0; // Protocol not specified
ptcStart += 3;
wcsncpy(lpRetStr, tcURL, (ptcStart - tcURL));
lpRetStr[(ptcStart - tcURL)-3] = NULL;
return (ptcStart - tcURL) - 3;
}
|
cfrank/natwm
|
src/common/error.h
|
<filename>src/common/error.h
// Copyright 2020 <NAME>
// Licensed under BSD-3-Clause
// Refer to the license.txt file included in the root of the project
#pragma once
enum natwm_error {
MEMORY_ALLOCATION_ERROR = 1U << 0U, // Failed to allocate memory
NOT_FOUND_ERROR = 1U << 1U, // Failed to find what was requested
CAPACITY_ERROR = 1U << 2U, // Capacity exceeded
INVALID_INPUT_ERROR = 1U << 3U, // Bad input received
RESOLUTION_FAILURE = 1U << 4U, // Failure during function resolution
GENERIC_ERROR = 1U << 5U, // Catch-all error
NO_ERROR = 1U << 6U, // No error
};
const char *natwm_error_to_string(enum natwm_error error);
|
Oroles/Hlin-PasswordManager
|
Phone/app/src/main/java/com/example/oroles/hlin/ReceivedMessage/ReceivedHashValue.java
|
package com.example.oroles.hlin.ReceivedMessage;
import android.preference.PreferenceManager;
import com.example.oroles.hlin.Controllers.ReceivedProcessorController;
import com.example.oroles.hlin.Fragments.SettingsFragment;
import com.example.oroles.hlin.InterfacesControllers.IStore;
import com.example.oroles.hlin.Utils.Utils;
public class ReceivedHashValue extends ReceivedMessage {
public ReceivedHashValue(IStore store, ReceivedProcessorController receivedProcessorController, String message) {
super(store, receivedProcessorController, message);
}
@Override
public void execute() {
String hash = Utils.getHash(mMessage);
if (mStore.getEncryption().compareHash(hash)) {
mStore.getBluetoothConnection().notifyConnectedBluetoothListeners("Connected-Correct Hash");
mStore.getBluetoothConnection().write(
mStore.getSenderProcessor().createDecryptKey(
PreferenceManager.getDefaultSharedPreferences(mStore.getContext())
.getString(SettingsFragment.SALT_FOR_KEY, "0")
));
mStore.getBluetoothConnection().write(
mStore.getSenderProcessor().createLastTimeUsedRequest());
if (PreferenceManager.getDefaultSharedPreferences(mStore.getContext())
.getBoolean(SettingsFragment.CHECK_BLUETOOTH_CONNECTION, true)) {
mStore.getBluetoothIsAlive().startSending();
}
}
else {
String action = PreferenceManager.getDefaultSharedPreferences(mStore.getContext())
.getString(SettingsFragment.WRONG_DEVICE_ACTION, "Nothing");
if (action.equals("CloseConnection")) {
mStore.getBluetoothIsAlive().stopSending();
mStore.getBluetoothConnection().close();
mStore.getBluetoothConnection().notifyConnectedBluetoothListeners("Disconnected-Wrong Hash");
} else {
mStore.getBluetoothConnection().notifyConnectedBluetoothListeners("Wrong Hash");
}
}
}
}
|
yalaudah/SynapseML
|
core/src/main/scala/com/microsoft/azure/synapse/ml/core/contracts/Metrics.scala
|
// Copyright (C) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in project root for information.
package com.microsoft.azure.synapse.ml.core.contracts
// Case class matching
sealed abstract class Metric
// Just for clarity in the contract file
object ConvenienceTypes {
type UniqueName = String
type MetricTable = Map[UniqueName, Seq[Metric]]
}
import com.microsoft.azure.synapse.ml.core.contracts.ConvenienceTypes._
// One option
case class TypedMetric[T](name: UniqueName, value: T) extends Metric
// Other option (reflection friendly - do we need reflection?)
sealed abstract class TypenameMetric
case class DoubleMetric(name: UniqueName, value: Double) extends TypenameMetric
case class StringMetric(name: UniqueName, value: String) extends TypenameMetric
case class IntegralMetric(name: UniqueName, value: Long) extends TypenameMetric
case class TypenameMetricGroup(name: UniqueName, values: Map[UniqueName, Seq[TypenameMetric]])
/** Defines contract for Metric table, which is a metric name to list of values.
* @param data
*/
case class MetricData(data: Map[String, Seq[Double]], metricType: String, modelName: String)
object MetricData {
def create(data: Map[String, Double], metricType: String, modelName: String): MetricData = {
new MetricData(data.map(kvp => (kvp._1, List(kvp._2))), metricType, modelName)
}
def createTable(data: Map[String, Seq[Double]], metricType: String, modelName: String): MetricData = {
new MetricData(data, metricType, modelName)
}
}
|
ScalablyTyped/SlinkyTyped
|
t/tensorflow__tfjs-core/src/main/scala/typingsSlinky/tensorflowTfjsCore/kernelNamesMod/CumsumAttrs.scala
|
package typingsSlinky.tensorflowTfjsCore.kernelNamesMod
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait CumsumAttrs extends StObject {
var axis: Double = js.native
var exclusive: Boolean = js.native
var reverse: Boolean = js.native
}
object CumsumAttrs {
@scala.inline
def apply(axis: Double, exclusive: Boolean, reverse: Boolean): CumsumAttrs = {
val __obj = js.Dynamic.literal(axis = axis.asInstanceOf[js.Any], exclusive = exclusive.asInstanceOf[js.Any], reverse = reverse.asInstanceOf[js.Any])
__obj.asInstanceOf[CumsumAttrs]
}
@scala.inline
implicit class CumsumAttrsMutableBuilder[Self <: CumsumAttrs] (val x: Self) extends AnyVal {
@scala.inline
def setAxis(value: Double): Self = StObject.set(x, "axis", value.asInstanceOf[js.Any])
@scala.inline
def setExclusive(value: Boolean): Self = StObject.set(x, "exclusive", value.asInstanceOf[js.Any])
@scala.inline
def setReverse(value: Boolean): Self = StObject.set(x, "reverse", value.asInstanceOf[js.Any])
}
}
|
baserinia/FlowSolver
|
src/lin_sys.h
|
// Incompressible Flow lin_sys
// Copyright (C) 2005 <NAME>
//------------------------------------------------------------------------------
// Created on: 16 Apr 2004
// Last update: 12 Apr 2005
//------------------------------------------------------------------------------
#ifndef CLASS_NIFS_C_LIN_SYS_H
#define CLASS_NIFS_C_LIN_SYS_H
#include <vector>
#include "elem.h"
#include "matrix_block.h"
#include "vector_block.h"
namespace NIFS {
// linear system manipulator and lin_sys
class c_lin_sys {
public:
c_lin_sys() {}
~c_lin_sys() {}
void init_lin_sys( int eqn_num, int entry_num);
void push_entry( double val, int row, int col );
void push_rhs( double val, int row );
double get_x( int i ) { return m_x[i]; }
void init_lin_sys_block( int eqn_num_block, int entry_num_block, unsigned index_beg, unsigned index_end );
void push_entry_block( const matrix_block< double >& mat, int row_blk, int col_blk );
void push_rhs_block( const vector_block< double >& vec, int row_blk );
vector_block<double> get_x_block( int i );
double get_x_block_elem( int i, unsigned j );
int get_eqn_num() { return m_eqn_num; }
int get_entry_num() { return m_entry_num; }
void reset();
void solve_lin_sys();
void convert_compressed_column( void );
void print( void ); // test
void print_coef_mat( std::string cof_file_name );
void print_rhs_vec( std::string rhs_file_name );
private:
std::vector<double> m_b; // right hand side vector
std::vector<double> m_x; // solution vector
std::vector<double> m_A; // element value array
std::vector<int> m_r; // row array
std::vector<int> m_c; // compressed column array
std::vector<c_elem> m_elem; // full elements vector
unsigned m_eqn_num;
unsigned m_entry_num;
unsigned m_index_beg;
unsigned m_index_end;
unsigned m_block_size;
};
} // namespace NBCFD
#endif //--- CLASS_NIFS_C_LIN_SYS_H
|
luubinhan/sunshine
|
src/components/mystyle/layouts/Widget/WidgetBody.js
|
import React from 'react';
const WidgetBody = (props) => <div className="widget-body">{props.children}</div>
export default WidgetBody;
|
fedexu/BinanceBot
|
src/main/java/com/fedexu/binancebot/wss/macd/MacdObserver.java
|
package com.fedexu.binancebot.wss.macd;
import com.binance.api.client.domain.market.Candlestick;
import com.fedexu.binancebot.wss.talib.MacdValues;
import com.fedexu.binancebot.wss.talib.TaLibFunctions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import java.util.List;
import static com.fedexu.binancebot.wss.macd.MACD.*;
import static java.lang.Double.parseDouble;
@Service
public class MacdObserver {
Logger logger = LoggerFactory.getLogger(MacdObserver.class);
@Autowired
TaLibFunctions taLibFunctions;
@Autowired
private ApplicationEventPublisher publisher;
public void calculateMACD(List<Candlestick> candelsHistory) {
double[] out;
MacdValues values =
taLibFunctions.macd(candelsHistory.stream().mapToDouble(value -> parseDouble(value.getClose())).toArray(),
MACD_12.getValueId(), MACD_26.getValueId(), MACD_9.getValueId());
publisher.publishEvent(new MacdEvent(this,
parseDouble(candelsHistory.get(candelsHistory.size() - 1).getClose()),
values.getMacd(), values.getSignal(), values.getHist()));
}
}
|
waleedsamy/GPGMail
|
MailHeaders/Sierra/MailFW/MFLibraryUpgrader.h
|
//
// 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 "MCActivityTarget.h"
#import "MFActivityProgressUpdater.h"
@class ACAccountStore, MCActivityAggregate, MCActivityMonitor, MFSqliteHandle, NSArray, NSString;
@interface MFLibraryUpgrader : NSObject <MCActivityTarget, MFActivityProgressUpdater>
{
MFSqliteHandle *_handle; // 8 = 0x8
ACAccountStore *_accountStore; // 16 = 0x10
NSArray *_upgradeSteps; // 24 = 0x18
BOOL _readOnly; // 32 = 0x20
BOOL _shouldRecalculateConversations; // 33 = 0x21
BOOL _shouldUpdateSubjectPrefixes; // 34 = 0x22
BOOL _shouldResetSnippets; // 35 = 0x23
BOOL _shouldRecalculateMessageCounts; // 36 = 0x24
BOOL _shouldUpdateSpotlightAttributes; // 37 = 0x25
BOOL _shouldUpdateSpotlightAttributesWithMultipleRecipients; // 38 = 0x26
BOOL _shouldUpdateMailboxURLs; // 39 = 0x27
BOOL _shouldResetChangeIdentifierForGmailAccounts; // 40 = 0x28
BOOL _shouldNormalizeMailboxPaths; // 41 = 0x29
BOOL _shouldResetDynamicAccountConfiguration; // 42 = 0x2a
BOOL _shouldRemoveMailboxesWithAbsoluteURLs; // 43 = 0x2b
BOOL _shouldUpdateFavoritePersistentIDUnicodeComposition; // 44 = 0x2c
BOOL _shouldRemoveLocalPathsFromRulesAndSmartMailboxes; // 45 = 0x2d
BOOL _shouldUpdateUIDNext; // 46 = 0x2e
BOOL _shouldRemoveJunkColors; // 47 = 0x2f
BOOL _shouldReparseExchangeReferences; // 48 = 0x30
BOOL _shouldRecalculateAutomatedConversations; // 49 = 0x31
id <MFLibraryUpgraderDelegate> _delegate; // 56 = 0x38
MCActivityMonitor *_monitor; // 64 = 0x40
unsigned long long _initialLastWriteMinorVersion; // 72 = 0x48
unsigned long long _majorVersion; // 80 = 0x50
unsigned long long _minorVersion; // 88 = 0x58
MCActivityAggregate *_activity; // 96 = 0x60
struct sqlite3 *_upgraderDB; // 104 = 0x68
}
+ (id)log; // IMP=0x0000000000168df2
@property(nonatomic) struct sqlite3 *upgraderDB; // @synthesize upgraderDB=_upgraderDB;
@property(retain, nonatomic) MCActivityAggregate *activity; // @synthesize activity=_activity;
@property(nonatomic) unsigned long long minorVersion; // @synthesize minorVersion=_minorVersion;
@property(nonatomic) unsigned long long majorVersion; // @synthesize majorVersion=_majorVersion;
@property(nonatomic) unsigned long long initialLastWriteMinorVersion; // @synthesize initialLastWriteMinorVersion=_initialLastWriteMinorVersion;
@property(nonatomic) BOOL shouldRecalculateAutomatedConversations; // @synthesize shouldRecalculateAutomatedConversations=_shouldRecalculateAutomatedConversations;
@property(nonatomic) BOOL shouldReparseExchangeReferences; // @synthesize shouldReparseExchangeReferences=_shouldReparseExchangeReferences;
@property(nonatomic) BOOL shouldRemoveJunkColors; // @synthesize shouldRemoveJunkColors=_shouldRemoveJunkColors;
@property(nonatomic) BOOL shouldUpdateUIDNext; // @synthesize shouldUpdateUIDNext=_shouldUpdateUIDNext;
@property(nonatomic) BOOL shouldRemoveLocalPathsFromRulesAndSmartMailboxes; // @synthesize shouldRemoveLocalPathsFromRulesAndSmartMailboxes=_shouldRemoveLocalPathsFromRulesAndSmartMailboxes;
@property(nonatomic) BOOL shouldUpdateFavoritePersistentIDUnicodeComposition; // @synthesize shouldUpdateFavoritePersistentIDUnicodeComposition=_shouldUpdateFavoritePersistentIDUnicodeComposition;
@property(nonatomic) BOOL shouldRemoveMailboxesWithAbsoluteURLs; // @synthesize shouldRemoveMailboxesWithAbsoluteURLs=_shouldRemoveMailboxesWithAbsoluteURLs;
@property(nonatomic) BOOL shouldResetDynamicAccountConfiguration; // @synthesize shouldResetDynamicAccountConfiguration=_shouldResetDynamicAccountConfiguration;
@property(nonatomic) BOOL shouldNormalizeMailboxPaths; // @synthesize shouldNormalizeMailboxPaths=_shouldNormalizeMailboxPaths;
@property(nonatomic) BOOL shouldResetChangeIdentifierForGmailAccounts; // @synthesize shouldResetChangeIdentifierForGmailAccounts=_shouldResetChangeIdentifierForGmailAccounts;
@property(nonatomic) BOOL shouldUpdateMailboxURLs; // @synthesize shouldUpdateMailboxURLs=_shouldUpdateMailboxURLs;
@property(nonatomic) BOOL shouldUpdateSpotlightAttributesWithMultipleRecipients; // @synthesize shouldUpdateSpotlightAttributesWithMultipleRecipients=_shouldUpdateSpotlightAttributesWithMultipleRecipients;
@property(nonatomic) BOOL shouldUpdateSpotlightAttributes; // @synthesize shouldUpdateSpotlightAttributes=_shouldUpdateSpotlightAttributes;
@property(nonatomic) BOOL shouldRecalculateMessageCounts; // @synthesize shouldRecalculateMessageCounts=_shouldRecalculateMessageCounts;
@property(nonatomic) BOOL shouldResetSnippets; // @synthesize shouldResetSnippets=_shouldResetSnippets;
@property(nonatomic) BOOL shouldUpdateSubjectPrefixes; // @synthesize shouldUpdateSubjectPrefixes=_shouldUpdateSubjectPrefixes;
@property(nonatomic) BOOL shouldRecalculateConversations; // @synthesize shouldRecalculateConversations=_shouldRecalculateConversations;
@property(retain, nonatomic) MCActivityMonitor *monitor; // @synthesize monitor=_monitor;
@property(nonatomic) BOOL readOnly; // @synthesize readOnly=_readOnly;
@property(nonatomic) __weak id <MFLibraryUpgraderDelegate> delegate; // @synthesize delegate=_delegate;
- (void).cxx_destruct; // IMP=0x000000000018334a
- (void)upgradeSignaturesFromLion; // IMP=0x0000000000182f8e
- (void)upgradeSmartMailboxesFromLion; // IMP=0x0000000000182f60
- (void)upgradeRulesFromLion; // IMP=0x0000000000182f18
- (void)upgradeMailDataIfNecessary; // IMP=0x0000000000182d52
- (long long)_getSQLTableCount:(const char *)arg1 usingDB:(struct sqlite3 *)arg2; // IMP=0x0000000000182a0f
- (void)_stampCurrentMinorVersion:(unsigned long long)arg1; // IMP=0x00000000001829d2
- (void)_executeSQL:(id)arg1 updateMinorVersion:(unsigned long long)arg2; // IMP=0x0000000000182276
@property(readonly, nonatomic) NSArray *upgradeSteps;
- (unsigned long long)_lastWriteMinorVersion; // IMP=0x0000000000181b63
- (BOOL)_needsRun; // IMP=0x0000000000181961
- (void)_bootstrapVersioningEngine; // IMP=0x00000000001818c2
- (void)_getVersionInfo; // IMP=0x0000000000181772
- (void)_unlockWriterDB:(struct sqlite3 *)arg1; // IMP=0x0000000000181683
- (struct sqlite3 *)_getWriterDB; // IMP=0x00000000001814dc
- (void)_unlockReaderDB:(struct sqlite3 *)arg1; // IMP=0x00000000001814d6
- (struct sqlite3 *)_getReaderDB; // IMP=0x00000000001813ee
- (id)_handle; // IMP=0x00000000001813d9
- (void)_setHandle:(id)arg1; // IMP=0x00000000001812d6
- (void)resetProgressItemsWithTotal:(unsigned long long)arg1 andStatusMessage:(id)arg2; // IMP=0x00000000001811f5
- (void)incrementProgressIndicatorWithThreshold:(unsigned long long)arg1; // IMP=0x0000000000181107
- (void)incrementProgressIndicator; // IMP=0x000000000018107d
- (void)setProgressItemTotal:(unsigned long long)arg1; // IMP=0x0000000000181031
- (id)_systemAccountsWithAccountTypeIdentifiers:(id)arg1; // IMP=0x0000000000180da5
@property(readonly, nonatomic) ACAccountStore *accountStore;
- (id)_libraryIDsOfAutomatedMessages; // IMP=0x0000000000180906
- (void)_reparseReferencesForRowIDsByMailboxURL:(id)arg1; // IMP=0x000000000017ff41
- (id)_reparseExchangeReferences; // IMP=0x000000000017f82a
- (void)_removeJunkColors; // IMP=0x000000000017f4fd
- (void)_updateUIDNext; // IMP=0x000000000017ebee
- (void)_removeContainerLogs; // IMP=0x000000000017ebe2
- (void)_resetConfigureDynamically; // IMP=0x000000000017ebc9
- (void)_fakeLibraryUpgraderStep; // IMP=0x000000000017e9fa
- (void)_normalizeMailboxPathComponentsInMboxCache; // IMP=0x000000000017e9e1
- (void)_resetConversationsForExistingMessagesWithRowIDs:(id)arg1; // IMP=0x000000000017e96a
- (void)_resetSnippetColumn; // IMP=0x000000000017e901
- (BOOL)_calculateInternationalSubjectPrefixes; // IMP=0x000000000017e883
- (void)updateFavoritePersistentIDUnicodeComposition; // IMP=0x000000000017e34d
- (void)_updateMailboxURLUnicodeComposition; // IMP=0x000000000017ddcd
- (id)_copySpotlightAttributesWithDateSent:(int)arg1 dateReceived:(int)arg2 dateLastViewed:(int)arg3 read:(int)arg4 libraryFlags:(long long)arg5 messageID:(const char *)arg6 subject:(id)arg7 displayName:(id)arg8 senderName:(id)arg9 senderAddress:(id)arg10 recipientNames:(id)arg11 recipientAddresses:(id)arg12; // IMP=0x000000000017d77e
- (id)_urlV1V2StringForMailboxDirectory:(id)arg1 account:(id)arg2 levelFromAccountDirectory:(unsigned long long)arg3; // IMP=0x000000000017d54d
- (void)_getRecipientsForMessageWithLibraryID:(long long)arg1 recipientNames:(id)arg2 recipientAddresses:(id)arg3 dbHandle:(id)arg4; // IMP=0x000000000017d3a3
- (void)_setSpotlightAttributesForEMLXFilesInMailbox:(id)arg1 mailboxURLString:(id)arg2; // IMP=0x000000000017c691
- (void)_sendSpotlightAttributesByPath:(id)arg1; // IMP=0x000000000017c409
- (id)_accountsWithTypeIdentifiers:(id)arg1; // IMP=0x000000000017c140
- (id)_mailboxFileSystemPathsByV1V2DatabaseURL; // IMP=0x000000000017bcdc
- (void)_updateSpotlightAttributesWithMultipleRecipients; // IMP=0x000000000017b33a
- (void)_updateSpotlightAttributes; // IMP=0x000000000017aee3
- (void)_removeMailboxesWithAbsoluteURLs; // IMP=0x000000000017ae51
- (void)_resetChangeIdentifierForGmailAccounts; // IMP=0x000000000017aa7f
- (id)_fixAbsoluteMailboxURL:(id)arg1 mailAccounts:(id)arg2; // IMP=0x000000000017a42e
- (id)_fixCriteriaWithAbsoluteMailboxURLs:(id)arg1 mailAccounts:(id)arg2; // IMP=0x0000000000179f4e
- (id)_fixSmartMailboxWithAbsoluteMailboxURLs:(id)arg1 mailAccounts:(id)arg2; // IMP=0x0000000000179b53
- (id)_newSmartMailboxesRemovingLocalPathsFromSmartMailboxes:(id)arg1 accounts:(id)arg2; // IMP=0x00000000001798e1
- (id)_newRulesRemovingLocalPathsFromRules:(id)arg1 accounts:(id)arg2; // IMP=0x00000000001794db
- (void)_removeLocalPathsFromRulesAndSmartMailboxes; // IMP=0x00000000001791d2
- (void)_upgradeFromSUYosemiteDomeToElCapitan; // IMP=0x0000000000179176
- (void)_upgradeFromYosemiteToSUYosemiteDome:(unsigned long long)arg1; // IMP=0x0000000000179130
- (void)_upgradeFromSUMavericksDuneToYosemite; // IMP=0x00000000001790e6
- (void)_upgradeFromSUMavericksCarveToSUMavericksDune; // IMP=0x00000000001790cf
- (void)_upgradeFromSUMavericksBoardToSUMavericksCarve; // IMP=0x0000000000179097
- (void)_upgradeFromMavericksToSUMavericksBoard; // IMP=0x000000000017905f
- (void)_fixShadowEMLXFilesForAccount:(id)arg1; // IMP=0x000000000017782f
- (void)_fixShadowEMLXFiles; // IMP=0x0000000000177637
- (id)_mailboxV1V2URLStringsForAccount:(id)arg1; // IMP=0x0000000000177460
- (void)_upgradeFromSUMountainCalypsoToMavericks; // IMP=0x000000000017720e
- (void)_upgradeFromMountainLionToSUMountainCalypso; // IMP=0x00000000001771aa
- (id)_newRulesWithOnlyLastComponentForApplesScriptReferencesFromRules:(id)arg1; // IMP=0x0000000000176ee4
- (void)makeAppleScriptReferencesInRulesUseOnlyLastPathComponent; // IMP=0x0000000000176dbc
- (void)_fixEWSFoldersTable; // IMP=0x0000000000176c51
- (void)fixMailDownloadsMigrationKey; // IMP=0x0000000000176b8f
- (void)_startMigratorServiceForAppleScriptFilesAndRules; // IMP=0x0000000000176acd
- (void)upgradeAppleScriptFilesAndRules; // IMP=0x0000000000175e54
- (void)_startMigratorServiceForMailDownloads; // IMP=0x0000000000175d92
- (void)upgradeMailDownloadsFiles; // IMP=0x00000000001757e1
- (BOOL)_removeMessageTypeFromSmartMailbox:(id)arg1 localProperties:(id)arg2; // IMP=0x0000000000175072
- (void)_removeMessageTypeFromSmartMailboxes; // IMP=0x0000000000174d53
- (void)_removeMessageTypeFromRules; // IMP=0x0000000000174779
- (void)_combineVIPSendersPlists; // IMP=0x000000000017444a
- (void)_addFileExtensionToSignatures; // IMP=0x00000000001740ed
- (void)_changeSignatureBundleLayout; // IMP=0x0000000000173edb
- (void)_changeSignaturesLayout; // IMP=0x0000000000173924
- (void)_changeSmartMailboxesLayout; // IMP=0x00000000001729fd
- (void)_changeRulesLayout; // IMP=0x0000000000172597
- (void)_upgradeFromLionToMountainLion; // IMP=0x0000000000172314
- (void)_updateSmartMailboxUnreadMessagesForMailboxes:(id)arg1; // IMP=0x0000000000171961
- (void)_updateSmartMailboxUnreadMessages; // IMP=0x00000000001717c5
- (void)_migrateTasksToLocalCalendar; // IMP=0x0000000000170ca7
- (void)_upgradeFromSUSnowFeltToLion; // IMP=0x000000000017010e
- (void)_upgradeFromSnowLeopardToSUSnowFelt; // IMP=0x0000000000170043
- (void)_upgradeFromLeopardToSnowLeopard; // IMP=0x000000000016ffcd
- (void)_updateCoalescedAddressReferences; // IMP=0x000000000016e78b
- (void)_populateRecipientPosition; // IMP=0x000000000016dfc1
- (void)_upgradeFromTigerToLeopard; // IMP=0x000000000016dd8b
- (void)_useWALJournalingIfPossible; // IMP=0x000000000016dd22
- (void)_vacuum; // IMP=0x000000000016dbbf
- (void)_createNewDatabaseObjects; // IMP=0x000000000016db15
- (void)_upgradeSchema:(id)arg1; // IMP=0x000000000016d5fe
- (void)_upgradeV1V2Schema; // IMP=0x000000000016d056
- (void)_upgradeSchemaFromBackBooting:(id)arg1; // IMP=0x000000000016cb02
- (void)_dropTriggers; // IMP=0x000000000016c9c7
- (id)_upgradeStepsAndUpgradeStepsFromBackBooting:(id *)arg1 withHandle:(id)arg2; // IMP=0x000000000016b564
- (void)run; // IMP=0x0000000000169426
- (BOOL)_libraryIsTooNew; // IMP=0x00000000001693d4
- (BOOL)_canLibraryBeUpgraded; // IMP=0x000000000016920f
@property(readonly, nonatomic) long long libraryStatus;
- (void)dealloc; // IMP=0x0000000000168ea3
- (id)init; // IMP=0x0000000000168e51
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly, copy, nonatomic) NSString *displayName;
@property(readonly) unsigned long long hash;
@property(readonly, nonatomic) BOOL isSmartMailbox;
@property(readonly) Class superclass;
@end
|
abdul699/Machine_Coding
|
Snake-And-Ladders/services/GameBoardService.h
|
#pragma once
#include "../models/GameBoard.h"
// #include "../models/Player.h"
// #include "../models/Snake.h"
// #include "../models/Ladder.h"
#include "DiceService.h"
using namespace std;
class GameBoardService {
GameBoard gameBoard = GameBoard();
DiceService diceService = DiceService();
public:
bool hasCurrentPlayerWon(Player player);
void MoveCurrentPlayer(Player &player, int diceValue);
void setGame(list<Player> players, list<Ladder> ladders, list<Snake> snakes);
int getTotalValueAfterDiceRolls();
void startGame();
};
|
UBC-MDS/exploratory-data-viz
|
exercises/en/test_03_09a.py
|
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the message will be displayed
# Since we haven't started assigning charts to variable names yet,
# this might be the better way to test for the first exercise.
# Maybe even for later exercises.
assert 'alt.Chart' in __solution__, "Make sure you are calling the 'Chart' function?"
assert 'mark_area' in __solution__, "Make sure you are creating a density plot using 'mark_area'."
assert "island" in str(mass_density_plot.transform), "Make sure you are grouping by 'island'."
assert "body_mass_g" in str(mass_density_plot.transform), "Make sure you are computing the density values using the 'body_mass_g' column."
assert "density" in str(mass_density_plot.transform), "Make sure you are giving a name of 'densitys' to the KDE estimates"
assert "steps: 100" in str(mass_density_plot.transform), "Make sure you are using steps=100 when computing the KDE."
assert mass_density_plot.encoding.color.shorthand == 'island', "Make sure you are coloring by island."
assert mass_density_plot.encoding.x.shorthand == 'body_mass_g', "Make sure you are plotting 'body_mass_g' on the X-axis."
assert mass_density_plot.encoding.y.shorthand == 'density:Q', "Make sure you are plotting 'density' as quantititave on the X-axis."
assert not mass_density_plot.title is None, "Make sure you are providing a title for your plot."
assert not mass_density_plot.title.islower(), "Make sure the plot title is capitalized."
__msg__.good("You're correct, well done!")
|
francoishill/goangi2
|
utils/entityUtils/iOrmRepo.go
|
<reponame>francoishill/goangi2
package entityUtils
type iOrmRepo interface {
CheckEntityExistsWithPK(ormContext *OrmContext, entityObj interface{}) bool
BaseReadEntityUsingPK(ormContext *OrmContext, entityObj interface{}, relatedFieldsToLoad *RelatedFieldsToLoad)
BaseReadEntityUsingFields(ormContext *OrmContext, entityObj interface{}, relatedFieldsToLoad *RelatedFieldsToLoad, fields ...string) bool
CheckIfExistByField(ormContext *OrmContext, tableName, field string, value interface{}, skipId int64, caseSensitive bool) bool
BaseInsertEntity(
ormContext *OrmContext,
entityObj interface{})
BaseUpdateEntity(
ormContext *OrmContext,
baseEntity interface{},
modifiedEntity interface{},
onlyAllowTheseFieldsToSave ...string) []ChangedField
BaseDeleteEntity(
ormContext *OrmContext,
entityObj interface{})
BaseUpdateM2MByAddAndRemove(
ormContext *OrmContext,
entityObj interface{},
columnNameOfRelationship string,
removeListToRelationship,
addListToRelationship []interface{})
/*BaseListEntities_OrderBy_Limit_Offset__WhereM2MCountIsZero(
ormContext *OrmContext,
queryTableName string,
columnNameOfRelationship string,
orderByFields []string,
limit int64,
offset int64,
relatedFieldsToLoad *RelatedFieldsToLoad,
sliceToPopulatePointer interface{})*/
BaseCountM2M(
ormContext *OrmContext,
entityObj interface{},
columnNameOfRelationship string) int64
BaseM2MRelationExists(
ormContext *OrmContext,
entityObj interface{},
columnNameOfRelationship string,
relationEntity interface{}) bool
BaseListEntities_ANDFilters_OrderBy(
ormContext *OrmContext,
queryTableName string,
queryFilter *QueryFilter, //Map of FieldName + FieldValue
orderByFields []string,
relatedFieldsToLoad *RelatedFieldsToLoad,
sliceToPopulatePointer interface{})
BaseListEntities_ANDFilters_OrderBy_Limit_Offset(
ormContext *OrmContext,
queryTableName string,
queryFilter *QueryFilter, //Map of FieldName + FieldValue
orderByFields []string,
limit int64,
offset int64,
relatedFieldsToLoad *RelatedFieldsToLoad,
sliceToPopulatePointer interface{})
BaseExtractSpecifiedColumnNames(
ormContext *OrmContext,
queryTableName string,
queryFilter *QueryFilter,
orderByFields []string,
limit int64,
offset int64,
columnNamesToExtract []string) []map[string]interface{}
BaseCountEntities_ANDFilters(
ormContext *OrmContext,
queryTableName string,
queryFilter *QueryFilter) int64
BaseLoadRelatedFields(ormContext *OrmContext, m interface{}, fieldName string) int64
BaseErrorIsZeroRowsFound(err error) bool
}
var (
OrmRepo = iOrmRepo(new(beegoOrmRepo))
)
|
nexermaverick/foundation-lib-spa-core
|
dist/Models/ErrorPage.js
|
<reponame>nexermaverick/foundation-lib-spa-core
export default class ErrorPage {
constructor(code, info) {
this.name = `${code}: ${info}`;
this.contentType = ['errors', code.toString()];
this.contentLink = {
guidValue: '',
id: code,
providerName: 'ErrorPages',
url: '',
workId: 0
};
}
static get Error404() {
return new ErrorPage(404, 'Page not found');
}
static get Error500() {
return new ErrorPage(500, 'Unkown server error');
}
}
//# sourceMappingURL=ErrorPage.js.map
|
Eastwu5788/flask-redis
|
tests/test_cluster/test_list.py
|
<filename>tests/test_cluster/test_list.py
# !/usr/local/python/bin/python
# -*- coding: utf-8 -*-
# (C) <NAME>, 2021
# All rights reserved
# @Author: '<NAME> <<EMAIL>>'
# @Time: '2022/1/10 10:35 上午'
class TestList:
def test_lpush(self, cluster):
cluster.lpush("LIST:K1", "V1", "V2")
cluster.lpush("-LIST:K2", "T1", "T2")
assert cluster.lindex("LIST:K1", 0) == "V2"
assert cluster.lindex("LIST:K1", 1) == "V1"
assert cluster.lindex("-LIST:K2", 0) == "T2"
assert cluster.lindex("-LIST:K2", 1) == "T1"
cluster.delete("LIST:K1", "-LIST:K2")
def test_blpop(self, cluster):
cluster.lpush("LIST:K1", "V1", "V2")
cluster.lpush("-LIST:K2", "T1", "T2")
assert cluster.blpop("LIST:K1") == ("CLU:LIST:K1", "V2")
assert cluster.blpop("-LIST:K2") == ("LIST:K2", "T2")
cluster.delete("LIST:K1", "-LIST:K2")
def test_brpop(self, cluster):
cluster.lpush("LIST:K1", "V1", "V2")
cluster.lpush("-LIST:K2", "T1", "T2")
assert cluster.brpop("LIST:K1") == ("CLU:LIST:K1", "V1")
assert cluster.brpop("-LIST:K2") == ("LIST:K2", "T1")
cluster.delete("LIST:K1", "-LIST:K2")
def test_linsert(self, cluster):
cluster.lpush("LIST:K1", "V1")
cluster.lpush("-LIST:K2", "T1")
cluster.linsert("LIST:K1", "BEFORE", "V1", "V22")
cluster.linsert("-LIST:K2", "AFTER", "T1", "T333")
assert cluster.lindex("LIST:K1", 0) == "V22"
assert cluster.lindex("-LIST:K2", 1) == "T333"
cluster.delete("LIST:K1", "-LIST:K2")
def test_llen(self, cluster):
cluster.lpush("LIST:K1", "V1", "V2")
cluster.lpush("-LIST:K2", "T1", "T3", "T5")
assert cluster.llen("LIST:K1") == 2
assert cluster.llen("-LIST:K2") == 3
cluster.delete("LIST:K1", "-LIST:K2")
def test_lpop(self, cluster):
cluster.lpush("LIST:K1", "V1", "V2")
cluster.lpush("-LIST:K2", "T1", "T3", "T5")
cluster.lpop("LIST:K1")
cluster.lpop("-LIST:K2")
assert cluster.lindex("LIST:K1", 0) == "V1"
assert cluster.lindex("-LIST:K2", 0) == "T3"
cluster.delete("LIST:K1", "-LIST:K2")
def test_lpushx(self, cluster):
cluster.lpush("LIST:K1", "V1")
cluster.lpushx("LIST:K1", "V2")
cluster.lpushx("LIST:K3", "V3")
assert cluster.lindex("LIST:K1", 0) == "V2"
assert cluster.lindex("LIST:K3", 0) is None
cluster.lpush("-LIST:K4", "V4")
cluster.lpushx("-LIST:K4", "V6")
cluster.lpushx("-LIST:K5", "V5")
assert cluster.lindex("-LIST:K4", 0) == "V6"
assert cluster.lindex("-LIST:K5", 0) is None
cluster.delete("LIST:K1", "-LIST:K4")
def test_lrange(self, cluster):
cluster.lpush("LIST:K1", "V1", "V2", "V3")
cluster.lpush("-LIST:K2", "T1", "T3", "T5")
assert cluster.lrange("LIST:K1", 0, 1) == ["V3", "V2"]
assert cluster.lrange("-LIST:K2", 0, -2) == ["T5", "T3"]
cluster.delete("LIST:K1", "-LIST:K2")
def test_lrem(self, cluster):
cluster.lpush("LIST:K1", "V1", "V2", "V2")
cluster.lpush("-LIST:K2", "T1", "T3", "T3")
cluster.lrem("LIST:K1", 1, "V2")
cluster.lrem("-LIST:K2", 2, "T3")
assert cluster.lindex("LIST:K1", 0) == "V2"
assert cluster.lindex("-LIST:K2", 0) == "T1"
cluster.delete("LIST:K1", "-LIST:K2")
def test_lset(self, cluster):
cluster.lpush("LIST:K1", "V1", "V2")
cluster.lpush("-LIST:K2", "T1", "T3")
cluster.lset("LIST:K1", 0, "V9")
cluster.lset("-LIST:K2", 1, "T222")
assert cluster.lindex("LIST:K1", 0) == "V9"
assert cluster.lindex("-LIST:K2", 1) == "T222"
cluster.delete("LIST:K1", "-LIST:K2")
def test_ltrim(self, cluster):
cluster.lpush("LIST:K1", "V1", "V2", "V2")
cluster.lpush("-LIST:K2", "T1", "T3", "T3")
cluster.ltrim("LIST:K1", 0, 1)
cluster.ltrim("-LIST:K2", 0, 0)
assert cluster.llen("LIST:K1") == 2
assert cluster.llen("-LIST:K2") == 1
cluster.delete("LIST:K1", "-LIST:K2")
def test_rpop(self, cluster):
cluster.lpush("LIST:K1", "V1", "V2", "V2")
cluster.lpush("-LIST:K2", "T1", "T3", "T3")
assert cluster.rpop("LIST:K1", 2) == ["V1", "V2"]
assert cluster.rpop("-LIST:K2", 1) == ["T1"]
cluster.delete("LIST:K1", "-LIST:K2")
def test_rpoplpush(self, cluster):
cluster.lpush("-{LIST:K}:1", "V1", "V2")
cluster.lpush("-{LIST:K}:2", "T1", "T3")
cluster.rpoplpush("-{LIST:K}:1", "-{LIST:K}:2")
assert cluster.lindex("-{LIST:K}:1", -1) == "V2"
assert cluster.lindex("-{LIST:K}:2", 0) == "V1"
cluster.delete("-{LIST:K}:1", "-{LIST:K}:2")
def test_rpush(self, cluster):
cluster.lpush("LIST:K1", "V1", "V2")
cluster.lpush("-LIST:K2", "T1", "T3")
cluster.rpush("LIST:K1", "SS")
cluster.rpush("-LIST:K2", "TT")
assert cluster.lindex("LIST:K1", -1) == "SS"
assert cluster.lindex("-LIST:K2", -1) == "TT"
cluster.delete("LIST:K1", "-LIST:K2")
def test_rpushx(self, cluster):
cluster.lpush("LIST:K1", "V1")
cluster.lpush("-LIST:K2", "T1")
cluster.rpushx("LIST:K1", "SS")
cluster.rpushx("LIST:K8", "JJ")
cluster.rpushx("-LIST:K2", "TT")
cluster.rpushx("-LIST:K3", "KK")
assert cluster.lindex("LIST:K1", -1) == "SS"
assert cluster.lindex("-LIST:K2", -1) == "TT"
assert cluster.lindex("LIST:K8", -1) is None
assert cluster.lindex("-LIST:K3", -1) is None
cluster.delete("LIST:K1", "-LIST:K2")
def test_lpos(self, cluster):
cluster.rpush("LIST:K1", "V1", "V2", "V2")
cluster.rpush("-LIST:K2", "T1", "T3", "T3")
assert cluster.lpos("LIST:K1", "V2", -1, 2) == [2, 1]
assert cluster.lpos("-LIST:K2", "T3", -1, 2) == [2, 1]
cluster.delete("LIST:K1", "-LIST:K2")
def test_sort(self, cluster):
cluster.rpush("-{SORT:K}:1", "1", "6", "21", "24", "4", "6")
cluster.rpush("-{SORT:K}:2", "1", "42", "4", "5", "23", "5")
assert cluster.sort("-{SORT:K}:1") == ["1", "4", "6", "6", "21", "24"]
assert cluster.sort("-{SORT:K}:1", store="-{SORT:K}:3") == 6
assert cluster.llen("-{SORT:K}:3") == 6
assert cluster.sort("-{SORT:K}:2") == ["1", "4", "5", "5", "23", "42"]
assert cluster.sort("-{SORT:K}:2", store="-{SORT:K}:4")
assert cluster.llen("-{SORT:K}:4") == 6
cluster.delete("-{SORT:K}:1", "-{SORT:K}:2", "-{SORT:K}:3", "-{SORT:K}:4")
|
frc2881/2018RobotDrive
|
src/org/usfirst/frc2881/karlk/commands/SimpleIntakeCube.java
|
<reponame>frc2881/2018RobotDrive<filename>src/org/usfirst/frc2881/karlk/commands/SimpleIntakeCube.java
package org.usfirst.frc2881.karlk.commands;
import edu.wpi.first.wpilibj.command.CommandGroup;
import org.usfirst.frc2881.karlk.Robot;
import org.usfirst.frc2881.karlk.subsystems.IntakeSubsystem;
import org.usfirst.frc2881.karlk.subsystems.IntakeSubsystem.GrasperState;
import org.usfirst.frc2881.karlk.subsystems.LiftSubsystem.ClawState;
public class SimpleIntakeCube extends CommandGroup {
public SimpleIntakeCube() {
addSequential(new SetClaw(ClawState.OPEN));
addParallel(new SetRollers(-IntakeSubsystem.INTAKE_SPEED));
addSequential(new SetGrasper(GrasperState.CLOSED));
addSequential(new WaitForeverCommand());
}
@Override
protected void initialize() {
Robot.log("Simple Cube Intake has started");
}
@Override
protected void end() {
Robot.log("Simple Cube Intake has ended");
}
}
|
matoruru/purescript-react-material-ui-svgicon
|
src/MaterialUI/SVGIcon/Icon/WatchLaterOutlined.js
|
<reponame>matoruru/purescript-react-material-ui-svgicon
exports.watchLaterOutlinedImpl = require('@material-ui/icons/WatchLaterOutlined').default;
|
ndeana-21/cpp
|
cpp01/ex05/Brain.cpp
|
<reponame>ndeana-21/cpp<filename>cpp01/ex05/Brain.cpp
#include "Brain.hpp"
std::string Brain::identify(void) const {
std::stringstream stream_ptr;
stream_ptr << this;
return (stream_ptr.str());
}
void Brain::show_iq(void) const {
std::cout << "IQ: " << this->_iq << std::endl;
}
void Brain::set_iq(int new_iq) {
_iq = new_iq;
}
Brain::Brain(int iq) : _iq(iq) {}
Brain::Brain() : _iq(0) {}
Brain::~Brain() {}
|
mvsframework/mvs
|
src/3rdParty/include/amg/units.hpp
|
//
// Copyright © 2015 <NAME> <hcc |ä| gatech.edu>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef UNITS_H
#define UNITS_H
namespace AMG {
/** \brief The namespace for all units used in \c AMG
* This (headers only) namespace contains empty structs used in templates to
* indicate the units of the in-parameters and some related conversion
* functions.
*/
namespace Units {
//
// angular
//
/** \brief An empty struct used in templates to indicate the use of degrees*/
struct degree {};
/** \brief An empty struct used in templates to indicate the use of radians*/
struct radian {};
//
// linear
//
/** \brief An empty struct used in templates to indicate the use of meters*/
struct meter {};
/** \brief An empty struct used in templates to indicate the use of feet*/
struct foot {};
//
// Conversions
//
/** \brief Convert a degree value to a radian value
* The internal precision is double.
*/
template<typename T>
inline T degree2radian(const T& degreeValue)
{
return T(degreeValue*M_PIl/180.0);
};
/** \brief Convert a radian value to a degree value
* The internal precision is double.
*/
template<typename T>
inline T radian2degree(const T& radianValue)
{
return T(radianValue*180.0*M_1_PIl);
};
/** \brief Convert a foot value to a meter value
* The internal precision is double.
*/
template<typename T>
inline T feet2meter(const T& footValue)
{
return T(0.3048 * footValue);
};
/** \brief Convert a meter value to a foot value
* The internal precision is double.
*/
template<typename T>
inline T meter2feet(const T& meterValue)
{
return T( meterValue/0.3048);
};
} // end namespace Units
} // end namespace AMG
#endif // UNITS
|
displague/metal-ruby
|
spec/api/emails_api_spec.rb
|
<filename>spec/api/emails_api_spec.rb
=begin
#Metal API
#This is the API for Equinix Metal Product. Interact with your devices, user account, and projects.
The version of the OpenAPI document: 1.0.0
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.1.0-SNAPSHOT
=end
require 'spec_helper'
require 'json'
# Unit tests for OpenapiClient::EmailsApi
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe 'EmailsApi' do
before do
# run before each test
@api_instance = OpenapiClient::EmailsApi.new
end
after do
# run after each test
end
describe 'test an instance of EmailsApi' do
it 'should create an instance of EmailsApi' do
expect(@api_instance).to be_instance_of(OpenapiClient::EmailsApi)
end
end
# unit tests for create_email
# Create an email
# Add a new email address to the current user.
# @param email Email to create
# @param [Hash] opts the optional parameters
# @return [Email]
describe 'create_email test' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for delete_email
# Delete the email
# Deletes the email.
# @param id Email UUID
# @param [Hash] opts the optional parameters
# @return [nil]
describe 'delete_email test' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for find_email_by_id
# Retrieve an email
# Provides one of the user’s emails.
# @param id Email UUID
# @param [Hash] opts the optional parameters
# @option opts [Array<String>] :include Nested attributes to include. Included objects will return their full attributes. Attribute names can be dotted (up to 3 levels) to included deeply nested objects.
# @option opts [Array<String>] :exclude Nested attributes to exclude. Excluded objects will return only the href attribute. Attribute names can be dotted (up to 3 levels) to exclude deeply nested objects.
# @return [Email]
describe 'find_email_by_id test' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for update_email
# Update the email
# Updates the email.
# @param id Email UUID
# @param email email to update
# @param [Hash] opts the optional parameters
# @return [Email]
describe 'update_email test' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
|
rakhi2001/ecom7
|
Java/878.java
|
<filename>Java/878.java
__________________________________________________________________________________________________
sample 0 ms submission
//import java.util.HashMap;
class Solution {
public int nthMagicalNumber(int n, int a, int b) {
if (a == b) {
return (int)(((long) a) * n % 1_000_000_007);
}
if (a > b) {
a = b + a;
b = a - b;
a = a - b;
}
long nok = findNok(b, a);
long min = a;
long max = (a + b) * 1_000_000_007L;
while (min != max) {
long middle = (min + max) >> 1;
long iterations = middle / a + middle / b - middle / nok;
if (iterations < n)
min = middle;
else if (iterations > n)
max = middle;
else {
long result = Math.max( (middle / a) * a, (middle / b) * b);
return (int)(result % 1_000_000_007);
}
}
return 0;
}
long findNod(int a, int b) {
if (b == 0)
return a;
else
return findNod(b, a % b);
}
long findNok(int a, int b) {
return (a / findNod(a, b)) * b;
}
};
__________________________________________________________________________________________________
sample 31664 kb submission
class Solution {
public int nthMagicalNumber(int N, int A, int B) {
int MOD = 1_000_000_007;
int L = A / gcd(A, B) * B;
int M = L / A + L / B - 1;
int q = N / M, r = N % M;
long ans = (long) q * L % MOD;
if (r == 0)
return (int) ans;
int[] heads = new int[]{A, B};
for (int i = 0; i < r - 1; ++i) {
if (heads[0] <= heads[1])
heads[0] += A;
else
heads[1] += B;
}
ans += Math.min(heads[0], heads[1]);
return (int) (ans % MOD);
}
public int gcd(int x, int y) {
if (x == 0) return y;
return gcd(y % x, x);
}
}
__________________________________________________________________________________________________
|
yangxu02/SimpleProjectNote
|
app/src/main/java/org/htmlparser/filters/HasAttributeFilter.java
|
<filename>app/src/main/java/org/htmlparser/filters/HasAttributeFilter.java
// HTMLParser Library - A java-based parser for HTML
// http://htmlparser.org
// Copyright (C) 2006 <NAME>
//
// Revision Control Information
//
// $URL: https://htmlparser.svn.sourceforge.net/svnroot/htmlparser/tags/HTMLParserProject-2.1/parser/src/main/java/org/htmlparser/filters/HasAttributeFilter.java $
// $Author: derrickoswald $
// $Date: 2006-09-16 16:44:17 +0200 (Sat, 16 Sep 2006) $
// $Revision: 4 $
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Common Public License; either
// version 1.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// Common Public License for more details.
//
// You should have received a copy of the Common Public License
// along with this library; if not, the license is available from
// the Open Source Initiative (OSI) website:
// http://opensource.org/licenses/cpl1.0.php
package org.htmlparser.filters;
import java.util.Locale;
import org.htmlparser.Attribute;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Tag;
/**
* This class accepts all tags that have a certain attribute,
* and optionally, with a certain value.
*/
public class HasAttributeFilter implements NodeFilter
{
/**
* The attribute to check for.
*/
protected String mAttribute;
/**
* The value to check for.
*/
protected String mValue;
/**
* Creates a new instance of HasAttributeFilter.
* With no attribute name, this would always return <code>false</code>
* from {@link #accept}.
*/
public HasAttributeFilter ()
{
this ("", null);
}
/**
* Creates a new instance of HasAttributeFilter that accepts tags
* with the given attribute.
* @param attribute The attribute to search for.
*/
public HasAttributeFilter (String attribute)
{
this (attribute, null);
}
/**
* Creates a new instance of HasAttributeFilter that accepts tags
* with the given attribute and value.
* @param attribute The attribute to search for.
* @param value The value that must be matched,
* or null if any value will match.
*/
public HasAttributeFilter (String attribute, String value)
{
mAttribute = attribute.toUpperCase (Locale.ENGLISH);
mValue = value;
}
/**
* Get the attribute name.
* @return Returns the name of the attribute that is acceptable.
*/
public String getAttributeName ()
{
return (mAttribute);
}
/**
* Set the attribute name.
* @param name The name of the attribute to accept.
*/
public void setAttributeName (String name)
{
mAttribute = name;
}
/**
* Get the attribute value.
* @return Returns the value of the attribute that is acceptable.
*/
public String getAttributeValue ()
{
return (mValue);
}
/**
* Set the attribute value.
* @param value The value of the attribute to accept.
* If <code>null</code>, any tag with the attribute,
* no matter what it's value is acceptable.
*/
public void setAttributeValue (String value)
{
mValue = value;
}
/**
* Accept tags with a certain attribute.
* @param node The node to check.
* @return <code>true</code> if the node has the attribute
* (and value if that is being checked too), <code>false</code> otherwise.
*/
public boolean accept (Node node)
{
Tag tag;
Attribute attribute;
boolean ret;
ret = false;
if (node instanceof Tag)
{
tag = (Tag)node;
attribute = tag.getAttributeEx (mAttribute);
ret = null != attribute;
if (ret && (null != mValue))
ret = mValue.equals (attribute.getValue ());
}
return (ret);
}
}
|
danielkummer/nixon-pi
|
spec/web_app_spec.rb
|
require_relative 'spec_helper'
require_relative '../web/web_server'
require_relative 'support/active_record'
require 'sinatra'
require 'rack/test'
$environment = 'test'
set :environment, :test
# set :database, 'sqlite:///spec/db/settings.db'
describe 'The Nixon-Pi Web Application', exclude: true do
include Rack::Test::Methods
def app
NixonPi::WebServer
end
it 'has an index page' do
get '/'
last_response.should be_ok
last_response.body.should include 'github'
end
# todo
# get post delete actions
end
|
MiztaOak/dat257_team1
|
LFG/app/src/main/java/com/dat257/team1/LFG/viewmodel/CurrentActivitiesViewModel.java
|
package com.dat257.team1.LFG.viewmodel;
import com.dat257.team1.LFG.events.ActivityFeedEvent;
import com.dat257.team1.LFG.events.CurrentActivitiesEvent;
import com.dat257.team1.LFG.firebase.FireStoreHelper;
import com.dat257.team1.LFG.model.Activity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.ListenerRegistration;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.util.ArrayList;
import java.util.List;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.lifecycle.ViewModel;
public class CurrentActivitiesViewModel extends ViewModel implements LifecycleObserver {
private MutableLiveData<List<Activity>> mutableOwnedActivities;
private MutableLiveData<List<Activity>> mutableParticipatingActivities;
private ListenerRegistration listener;
public CurrentActivitiesViewModel() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
if(!EventBus.getDefault().isRegistered(this))
EventBus.getDefault().register(this);
listener = FireStoreHelper.getInstance().loadCurrentActivities();
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
if(listener != null) {
listener.remove();
listener = null;
}
EventBus.getDefault().unregister(this);
}
public MutableLiveData<List<Activity>> getMutableOwnedActivities() {
if (mutableOwnedActivities == null) {
mutableOwnedActivities = new MutableLiveData<List<Activity>>();
}
return mutableOwnedActivities;
}
public MutableLiveData<List<Activity>> getMutableParticipatingActivities() {
if (mutableParticipatingActivities == null) {
mutableParticipatingActivities = new MutableLiveData<List<Activity>>();
}
return mutableParticipatingActivities;
}
@Subscribe
public void handleEvent(CurrentActivitiesEvent event){
filterList(event.getActivityList());
}
/**
* Method that filters a list of activities into two lists the once that the current user owns
* and the once that they are participating in and stores them in the live data lists
*
* Author: <NAME>
* @param activities the list of activities that will be filtered
*/
private void filterList(List<Activity> activities){
List<Activity> ownedActivities = new ArrayList<>();
List<Activity> participatingActivities = new ArrayList<>();
String uID = FirebaseAuth.getInstance().getCurrentUser().getUid();
for(Activity activity: activities){
if(activity.getOwner().equals(uID))
ownedActivities.add(activity);
else if(activity.getParticipants().contains(uID))
participatingActivities.add(activity);
}
mutableOwnedActivities.setValue(ownedActivities);
mutableParticipatingActivities.setValue(participatingActivities);
}
}
|
rapiddweller/rd-lib-format
|
src/test/java/com/rapiddweller/format/util/OffsetDataSourceTest.java
|
<filename>src/test/java/com/rapiddweller/format/util/OffsetDataSourceTest.java
package com.rapiddweller.format.util;
import com.rapiddweller.common.CollectionUtil;
import com.rapiddweller.format.DataIterator;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/**
* Tests the {@link OffsetDataSource}.
* @author <NAME>
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class OffsetDataSourceTest {
@Test
public void testConstructor() {
ArrayList<Object> source = new ArrayList<>();
OffsetDataSource<Object> actualOffsetDataSource = new OffsetDataSource<Object>(
new DataSourceProxy(new DataSourceProxy(
new DataSourceProxy(new DataSourceProxy(new DataSourceFromIterable<>(source, Object.class))))),
2);
assertEquals(2, actualOffsetDataSource.offset);
assertTrue(actualOffsetDataSource.source instanceof DataSourceProxy);
Class<Object> expectedType = actualOffsetDataSource.type;
assertSame(expectedType, actualOffsetDataSource.getType());
}
@Test
public void testIterator() {
ArrayList<Object> source = new ArrayList<>();
DataIterator<Object> actualIteratorResult = (new OffsetDataSource<Object>(new DataSourceProxy(
new DataSourceProxy(new DataSourceProxy(new DataSourceFromIterable<>(source, Object.class)))), 2))
.iterator();
Class<Object> expectedType = ((DataIteratorFromJavaIterator<Object>) actualIteratorResult).type;
assertSame(expectedType, actualIteratorResult.getType());
}
@Test
public void testIterator2() {
ArrayList<Object> source = new ArrayList<>();
DataIterator<Object> actualIteratorResult = (new OffsetDataSource<Object>(
new DataSourceProxy(new DataSourceProxy(new DataSourceProxy(new OffsetDataSource(
new DataSourceProxy(
new DataSourceProxy(new DataSourceProxy(new DataSourceFromIterable<>(source, Object.class)))),
2)))),
2)).iterator();
Class<Object> expectedType = ((DataIteratorFromJavaIterator<Object>) actualIteratorResult).type;
assertSame(expectedType, actualIteratorResult.getType());
}
@Test
public void testToString() {
List<Integer> source = CollectionUtil.toList(1, 2, 3, 4);
DataSourceProxy s1 = new DataSourceProxy(new DataSourceFromIterable<>(source, Integer.class));
DataSourceProxy s2 = new DataSourceProxy(s1);
OffsetDataSource<Object> s4 = new OffsetDataSource<Object>(s2, 2);
assertEquals("OffsetDataSource[2, DataSourceProxy(DataSourceProxy(DataSourceFromIterable[[1, 2, 3, 4]]))]",
s4.toString());
}
@Test
public void testToString2() {
ArrayList<Object> source = new ArrayList<>();
DataSourceFromIterable<Object> s0 = new DataSourceFromIterable<>(source, Object.class);
DataSourceProxy s1 = new DataSourceProxy(s0);
DataSourceProxy s2 = new DataSourceProxy(s1);
OffsetDataSource s3 = new OffsetDataSource(s2, 2);
OffsetDataSource<Object> s4 = new OffsetDataSource<Object>(s3, 2);
assertEquals(
"OffsetDataSource[2, OffsetDataSource[2, DataSourceProxy(DataSourceProxy(DataSourceFromIterable[[]]))]]",
s4.toString());
}
}
|
zhusongm/AdaptiveCards
|
source/uwp/Renderer/lib/AdaptiveShowCardActionConfig.cpp
|
<filename>source/uwp/Renderer/lib/AdaptiveShowCardActionConfig.cpp
#include "pch.h"
#include "Util.h"
#include "AdaptiveSpacingDefinition.h"
#include "AdaptiveShowCardActionConfig.h"
using namespace Microsoft::WRL;
using namespace ABI::AdaptiveCards::XamlCardRenderer;
using namespace ABI::Windows::UI;
namespace AdaptiveCards { namespace XamlCardRenderer
{
HRESULT AdaptiveShowCardActionConfig::RuntimeClassInitialize() noexcept try
{
return S_OK;
} CATCH_RETURN;
HRESULT AdaptiveShowCardActionConfig::RuntimeClassInitialize(AdaptiveCards::ShowCardActionConfig ShowCardActionConfig) noexcept
{
m_sharedShowCardActionConfig = ShowCardActionConfig;
return S_OK;
}
_Use_decl_annotations_
HRESULT AdaptiveShowCardActionConfig::get_ActionMode(ABI::AdaptiveCards::XamlCardRenderer::ActionMode* value)
{
*value = static_cast<ABI::AdaptiveCards::XamlCardRenderer::ActionMode>(m_sharedShowCardActionConfig.actionMode);
return S_OK;
}
_Use_decl_annotations_
HRESULT AdaptiveShowCardActionConfig::put_ActionMode(ABI::AdaptiveCards::XamlCardRenderer::ActionMode value)
{
m_sharedShowCardActionConfig.actionMode = static_cast<AdaptiveCards::ActionMode>(value);
return S_OK;
}
_Use_decl_annotations_
HRESULT AdaptiveShowCardActionConfig::get_BackgroundColor(Color* value)
{
return GetColorFromString(m_sharedShowCardActionConfig.backgroundColor, value);
}
_Use_decl_annotations_
HRESULT AdaptiveShowCardActionConfig::put_BackgroundColor(Color /*value*/)
{
return E_NOTIMPL;
}
_Use_decl_annotations_
HRESULT AdaptiveShowCardActionConfig::get_Padding(IAdaptiveSpacingDefinition** spacingDefinition)
{
return MakeAndInitialize<AdaptiveSpacingDefinition>(spacingDefinition, m_sharedShowCardActionConfig.padding);
}
_Use_decl_annotations_
HRESULT AdaptiveShowCardActionConfig::put_Padding(IAdaptiveSpacingDefinition* /*value*/)
{
return E_NOTIMPL;
}
_Use_decl_annotations_
HRESULT AdaptiveShowCardActionConfig::get_InlineTopMargin(UINT32* inlineTopMargin)
{
*inlineTopMargin = m_sharedShowCardActionConfig.inlineTopMargin;
return S_OK;
}
_Use_decl_annotations_
HRESULT AdaptiveShowCardActionConfig::put_InlineTopMargin(UINT32 inlineTopMargin)
{
m_sharedShowCardActionConfig.inlineTopMargin = inlineTopMargin;
return S_OK;
}
}}
|
periannath/ONE
|
compiler/nnc/utils/prepare_inputs/jpeg2hdf5.py
|
from PIL import Image
import numpy as np
import h5py
import sys
import glob
import subprocess
import struct
import datetime
# Generates hdf5 files (and optionally binary files) from JPEGs
# -f - specifies framework to generate them for
# -t - specifies testcases directory (see it's structure in readme)
# -i - specifies input node name of the model that will use them (required by nnkit)
# -r - if files already exist, rewrites them
# -b - enable binary file generation
# -p - allow some sort of parallelism by processing only a subset of files,
# you need to specify number of processes and run as much of them
# manually with diferent numbers
#
# Example:
# python3 conv.py -f tfl -t inc_slim/testcases -i input -p 16 1
#
helpstr = 'Usage: -f (tfl | caf) ' + \
'-t <testcases_directory> ' + \
'[-i <input_layer_name>] ' + \
'[-r] [-b]' + \
'[-p <number_of_processes> <process number>]'
supported_frameworks = ['tfl', 'caf']
args = {}
# Defaults
args['-p'] = (1, 1)
args['-r'] = False
args['-b'] = False
argc = len(sys.argv)
for i in range(len(sys.argv)):
arg = sys.argv[i]
if arg == '-r' or arg == '-b':
args[arg] = True
elif arg == '-f' or arg == '-t' or arg == '-i':
if i + 1 >= argc or sys.argv[i + 1][0] == '-':
print(arg, " is missing it's value")
print(helpstr)
exit()
args[arg] = sys.argv[i + 1]
elif arg == '-p':
if i + 2 >= argc or sys.argv[i + 1][0] == '-' or sys.argv[i + 2][0] == '-':
print(arg, " is missing some of it's values")
print(helpstr)
exit()
args[arg] = (int(sys.argv[i + 1]), int(sys.argv[i + 2]))
elif arg[0] == '-':
print('Unsupported argument: ', arg)
exit()
if not ('-f' in args and '-t' in args):
print('Some arguments are not provided')
print(helpstr)
exit()
fw = args['-f']
if not fw in supported_frameworks:
print('Unsupported framework: ', fw)
exit()
indirname = args['-t']
if not '-i' in args:
if fw == 'caf':
inputname = 'data'
elif fw == 'tfl':
inputname = 'input'
else:
inputname = args['-i']
nproc, proc_num = args['-p']
remove_existing = args['-r']
gen_binary = args['-b']
print('started at', datetime.datetime.now())
testcases = glob.glob(indirname + '/testcase*/')
testcases.sort()
testcases = testcases[proc_num - 1::nproc]
number = 0
for testcase in testcases:
try:
infilename = glob.glob(testcase + 'input/*.JPEG')
if len(infilename) > 0:
number += 1
infilename = infilename[0]
outfilename = testcase + 'input/' + infilename.split('/')[-1] + '.hdf5'
binoutfilename = testcase + 'input/' + infilename.split('/')[-1] + '.dat'
found_hdf = len(glob.glob(outfilename)) != 0
found_bin = len(glob.glob(binoutfilename)) != 0
if not found_hdf or (not found_bin and gen_binary) or remove_existing:
with Image.open(infilename) as im:
#TODO: check if order is correct here and in other places
h = im.size[0]
w = im.size[1]
s = im.split()
if len(s) == 3:
r, g, b = s
else:
r = s[0]
g = s[0]
b = s[0]
rf = r.convert('F')
gf = g.convert('F')
bf = b.convert('F')
rfb = rf.tobytes()
gfb = gf.tobytes()
bfb = bf.tobytes()
made_hdf = False
if not found_hdf or remove_existing:
if fw == 'tfl':
reds = np.fromstring(rfb, count=(h * w), dtype='float32')
greens = np.fromstring(gfb, count=(h * w), dtype='float32')
blues = np.fromstring(bfb, count=(h * w), dtype='float32')
dset_shape = (1, h, w, 3)
narr = np.ndarray(shape=(0))
mixed_ch = []
for i in range(h * w):
mixed_ch += [
reds[i] / 255.0, greens[i] / 255.0, blues[i] / 255.0
]
narr = np.append(narr, mixed_ch)
elif fw == 'caf':
dset_shape = (1, 3, h, w)
narr = np.fromstring(
rfb + gfb + bfb, count=(3 * h * w), dtype='float32')
for i in range(3 * h * w):
narr[i] /= 255.0
if remove_existing:
subprocess.call(['rm', '-f', outfilename])
with h5py.File(outfilename) as f:
# nnkit hdf5_import asserts to use IEEE_F32BE, which is >f4 in numpy
dset = f.require_dataset(inputname, dset_shape, dtype='>f4')
dset[0] = np.reshape(narr, dset_shape)
made_hdf = True
if gen_binary and (not found_bin or remove_existing):
if fw == 'tfl' and made_hdf:
l = narr.tolist()
else:
reds = np.fromstring(rfb, count=(h * w), dtype='float32')
greens = np.fromstring(gfb, count=(h * w), dtype='float32')
blues = np.fromstring(bfb, count=(h * w), dtype='float32')
l = np.ndarray(shape=(0))
mixed_ch = []
for i in range(h * w):
mixed_ch += [
reds[i] / 255.0, greens[i] / 255.0, blues[i] / 255.0
]
l = np.append(l, mixed_ch)
l = l.tolist()
with open(binoutfilename, 'wb') as out:
out.write(struct.pack('f' * len(l), *l))
print(number, ': ' + testcase + ' Done')
else:
print(testcase, ' nothing to do')
else:
print(testcase, ' JPEG not found')
except:
print(testcase, " FAILED")
print('started at', ended.datetime.now())
|
DetoxDelight/PayPal-Ruby-SDK
|
spec/payouts_examples_spec.rb
|
<gh_stars>100-1000
require "spec_helper"
describe "Payouts", :integration => true do
PayoutVenmoAttributes = {
:sender_batch_header => {
:sender_batch_id => SecureRandom.hex(8)
},
:items => [
{
:recipient_type => 'PHONE',
:amount => {
:value => '1.0',
:currency => 'USD'
},
:note => 'Thanks for your patronage!',
:sender_item_id => '2014031400023',
:receiver => '5551232368',
:recipient_wallet => 'VENMO'
}
]
}
PayoutAttributes = {
:sender_batch_header => {
:sender_batch_id => SecureRandom.hex(8),
:email_subject => 'You have a Payout!'
},
:items => [
{
:recipient_type => 'EMAIL',
:amount => {
:value => '1.0',
:currency => 'USD'
},
:note => 'Thanks for your patronage!',
:sender_item_id => '2014031400023',
:receiver => '<EMAIL>'
}
]
}
it "create venmo payout" do
$payout = PayPal::SDK::REST::Payout.new(PayoutVenmoAttributes)
$payout_batch = $payout.create
expect($payout_batch).to be_truthy
end
it "create payout sync" do
$payout = PayPal::SDK::REST::Payout.new(PayoutAttributes)
$payout_batch = $payout.create(true)
expect($payout_batch).to be_truthy
end
it "get payout batch status" do
$result = PayPal::SDK::REST::Payout.get($payout_batch.batch_header.payout_batch_id)
expect($result).to be_a PayPal::SDK::REST::PayoutBatch
expect($payout_batch.batch_header.payout_batch_id).to eql $result.batch_header.payout_batch_id
end
it "get payout item status" do
$payout_item_details= PayoutItem.get($payout_batch.items[0].payout_item_id)
expect($payout_item_details).to be_a PayPal::SDK::REST::PayoutItemDetails
expect($payout_item_details.payout_item_id).to eql $payout_batch.items[0].payout_item_id
end
it "cancel unclaimed payouts" do
$payout_item_details= PayoutItem.cancel($payout_batch.items[0].payout_item_id)
expect($payout_item_details).to be_a PayPal::SDK::REST::PayoutItemDetails
expect($payout_item_details.payout_item_id).to eql $payout_batch.items[0].payout_item_id
expect($payout_item_details.transaction_status).to eql 'RETURNED'
end
end
|
kelvinfan001/coreos-assembler
|
gangplank/vendor/github.com/containers/libpod/pkg/domain/entities/system.go
|
package entities
import (
"time"
"github.com/spf13/cobra"
)
// ServiceOptions provides the input for starting an API Service
type ServiceOptions struct {
URI string // Path to unix domain socket service should listen on
Timeout time.Duration // duration of inactivity the service should wait before shutting down
Command *cobra.Command // CLI command provided. Used in V1 code
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.