repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
shaokeyibb/Minecraft-Plugin-YinwuChat-RELOADED
src/main/java/org/lintx/plugins/yinwuchat/json/Message.java
package org.lintx.plugins.yinwuchat.json; import java.util.ArrayList; import java.util.List; public class Message { public String player = ""; public String chat = ""; public List<String> items = null; public List<HandleConfig> handles = new ArrayList<>(); }
cjh1/ParaView
Utilities/mpi4py/Library/compat/deinompi.h
<reponame>cjh1/ParaView<filename>Utilities/mpi4py/Library/compat/deinompi.h #ifndef PyMPI_COMPAT_DEINOMPI_H #define PyMPI_COMPAT_DEINOMPI_H /* ---------------------------------------------------------------- */ static int PyMPI_DEINOMPI_argc = 0; static char **PyMPI_DEINOMPI_argv = 0; static char *PyMPI_DEINOMPI_args[2] = {0, 0}; static void PyMPI_DEINOMPI_FixArgs(int **argc, char ****argv) { if ((argc[0]==(int *)0) || (argv[0]==(char ***)0)) { #ifdef Py_PYTHON_H #if PY_MAJOR_VERSION >= 3 PyMPI_DEINOMPI_args[0] = (char *) "python"; #else PyMPI_DEINOMPI_args[0] = Py_GetProgramName(); #endif PyMPI_DEINOMPI_argc = 1; #endif PyMPI_DEINOMPI_argv = PyMPI_DEINOMPI_args; argc[0] = &PyMPI_DEINOMPI_argc; argv[0] = &PyMPI_DEINOMPI_argv; } } static int PyMPI_DEINOMPI_MPI_Init(int *argc, char ***argv) { PyMPI_DEINOMPI_FixArgs(&argc, &argv); return MPI_Init(argc, argv); } #undef MPI_Init #define MPI_Init PyMPI_DEINOMPI_MPI_Init static int PyMPI_DEINOMPI_MPI_Init_thread(int *argc, char ***argv, int required, int *provided) { PyMPI_DEINOMPI_FixArgs(&argc, &argv); return MPI_Init_thread(argc, argv, required, provided); } #undef MPI_Init_thread #define MPI_Init_thread PyMPI_DEINOMPI_MPI_Init_thread /* ---------------------------------------------------------------- */ #endif /* !PyMPI_COMPAT_DEINOMPI_H */
LAzzam2/stockr-client
gulp/tasks/build/build-scripts.js
'use strict'; var gulp = require( 'gulp' ); var connect = require( 'gulp-connect' ); var mainBowerFiles = require( 'main-bower-files' ); var inject = require( 'gulp-inject' ); var angularFilesort = require( 'gulp-angular-filesort' ); var ngAnnotate = require( 'gulp-ng-annotate' ); var uglify = require( 'gulp-uglify' ); var order = require( 'gulp-order' ); var concat = require( 'gulp-concat' ); var streamqueue = require( 'streamqueue' ); var filter = require( 'gulp-filter' ); var path = require( '../../paths.js' ); // Build process. gulp.task( 'build-scripts', [ 'eslint' ], function( ) { return streamqueue( { objectMode: true }, // Select and order bower components. gulp.src( mainBowerFiles( { paths: { bowerDirectory: path.to.bower.source, bowerrc: path.to.bower.config, bowerJson: path.to.bower.manifest } } ), { base: path.to.bower.source } ) .pipe( order( [ 'angular/angular.js', '*' ] ) ) .pipe( filter( '**/*.js' ) ), // Select and order source scripts. gulp.src( path.to.scripts.source ) .pipe( ngAnnotate( { remove: true, add: true, single_quotes: true } ) ) .pipe( angularFilesort( ) ) ) // Then concatenate and uglify them. .pipe( concat( path.to.main.script.file ) ) .pipe( uglify( ) ) .pipe( gulp.dest( path.to.destination ) ); } );
Nobergan/js-scripts
repeta/14_events/js/input.js
/* * События input и change * Чекбоксы и свойство checked */ const btnRef = document.querySelector('.js-button'); const inputRef = document.querySelector('.js-input'); const licenseRef = document.querySelector('.js-license'); const nameLabelRef = document.querySelector('.js-button > span'); inputRef.addEventListener('focus', handleInputFocus); inputRef.addEventListener('blur', handleInputBlur); inputRef.addEventListener('input', handleInputChange); licenseRef.addEventListener('change', handleLicenseChange); function handleInputFocus () { console.log('TAKE FOCUS!!!'); } function handleInputBlur() { console.log('LOSE FOCUS!!!'); } function handleInputChange(event) { nameLabelRef.textContent = event.target.value; } function handleLicenseChange(event) { btnRef.disabled = !event.target.checked; // console.log(btnRef.disabled); }
dustinpianalto/geeksbot_web
geeksbot_web/rcon/models.py
from django.db import models from django.core.exceptions import ObjectDoesNotExist from rest_framework import status from guilds.models import Guild from dmessages.models import Message from users.models import User from channels.models import Channel from .utils import create_error_response from .utils import create_success_response # Create your models here. class RconServer(models.Model): guild = models.ForeignKey(Guild, on_delete=models.CASCADE) name = models.CharField(max_length=50) ip = models.GenericIPAddressField() port = models.PositiveIntegerField() password = models.CharField(max_length=50) monitor_chat = models.BooleanField() monitor_chat_channel = models.ForeignKey( Channel, on_delete=models.DO_NOTHING, related_name="+", null=True, blank=True, default=None ) alerts_channel = models.ForeignKey( Channel, on_delete=models.DO_NOTHING, related_name="+", null=True, blank=True, default=None ) info_channel = models.ForeignKey( Channel, on_delete=models.DO_NOTHING, related_name="+", null=True, blank=True, default=None ) info_message = models.ForeignKey( Message, on_delete=models.DO_NOTHING, related_name="+", null=True, blank=True, default=None ) settings_message = models.ForeignKey( Message, on_delete=models.DO_NOTHING, related_name="+", null=True, blank=True, default=None ) whitelist = models.ManyToManyField(User, blank=True) def update_server(self, data): if data.get('name'): self.name = data.get('name') if data.get('ip'): self.ip = data.get('ip') if data.get('port'): self.port = data.get('port') if data.get('password'): self.password = data.get('password') if data.get('monitor_chat'): self.monitor_chat = data.get('monitor_chat') if 'monitor_chat_channel' in data.keys(): self.monitor_chat_channel = Channel.get_channel_by_id(data.get('monitor_chat_channel')) if 'alerts_channel' in data.keys(): self.alerts_channel = Channel.get_channel_by_id(data.get('alerts_channel')) if 'info_channel' in data.keys(): self.alerts_channel = Channel.get_channel_by_id(data.get('info_channel')) if 'info_message' in data.keys(): self.info_message = Message.get_message_by_id(data.get('info_message')) if 'settings_message' in data.keys(): self.settings_message = Message.get_message_by_id(data.get('settings_message')) self.save() return create_success_response(self, status.HTTP_202_ACCEPTED, many=False) def add_whitelist(self, user_id): user = User.get_user_by_id(user_id) if not isinstance(user, User): return create_error_response("User Does Not Exist", status=status.HTTP_404_NOT_FOUND) if not user.steam_id: return create_error_response("User does not have a Steam 64ID attached to their account", status=status.HTTP_406_NOT_ACCEPTABLE) self.whitelist.add(user) return create_error_response("User has been added to the whitelist", status=status.HTTP_200_OK) def remove_from_whitelist(self, user_id): user = User.get_user_by_id(user_id) if not isinstance(user, User): return create_error_response("User Does Not Exist", status=status.HTTP_404_NOT_FOUND) self.whitelist.remove(user) return create_error_response("User has been removed from the whitelist", status=status.HTTP_200_OK) @classmethod def add_new_server(cls, data): guild_id = data.get('guild') name = data.get('name') ip = data.get('ip') port = data.get('port') password = data.get('password') if not (guild_id and name and ip and port and password): return create_error_response("One or more of the required fields are missing", status=status.HTTP_400_BAD_REQUEST) guild = Guild.get_guild_by_id(guild_id) if not isinstance(guild, Guild): return create_error_response("Guild Does Not Exist", status=status.HTTP_404_NOT_FOUND) server = cls( guild=guild, name=name, ip=ip, port=port, password=password, monitor_chat=data.get('monitor_chat', False) ) server.save() return create_success_response(server, status.HTTP_201_CREATED, many=False) @classmethod def get_server(cls, guild_id, name): guild_servers = cls.get_guild_servers(guild_id) if guild_servers: try: return guild_servers.get(name=name) except ObjectDoesNotExist: return None return None @classmethod def get_guild_servers(cls, guild_id): guild = Guild.get_guild_by_id(guild_id) if not isinstance(guild, Guild): return None return cls.objects.filter(guild=guild) def __str__(self): return f"{self.guild.id} | {self.name}"
jwasinger/corewar-ui
src/features/signup/actions.js
<reponame>jwasinger/corewar-ui import { action } from '../../actions/creator' export const SUBSCRIBE_REQUESTED = 'signup/SUBSCRIBE_REQUESTED' export const SUBSCRIPTION_RESPONSE = 'signup/SUBSCRIPTION_RESPONSE' export const subscribe = email => action(SUBSCRIBE_REQUESTED, { email })
Galenika/Externalit
csgo_external/csgo_external/sdk/csgo/engine.h
#pragma once #include "../sdk.h" namespace sdk { namespace csgo { class cengine { private: uint32_t client_state(); public: cengine() = default; vec3 get_viewang(); void set_viewang(vec3 ang); const char* get_mapdir(); const char* get_mapname(); const char* get_gamedir(); void full_update(); }; extern cengine* c_engine; }; }
wannabearockstar/intellij-scala
testdata/parameterInfo/functionParameterInfo/simple/ScalaLibrary.scala
<filename>testdata/parameterInfo/functionParameterInfo/simple/ScalaLibrary.scala import scala.collection.mutable.ArrayBuffer val buffer = new ArrayBuffer[Int] buffer.append(/*caret*/) //elems: Int*
eltanin-os/tertium
src/utf8/checkrune.c
<filename>src/utf8/checkrune.c #include <tertium/cpu.h> #include <tertium/std.h> ctype_status c_utf8_checkrune(ctype_rune r) { if (r > C_RUNEMAX || (r & 0xFFFE) == 0xFFFE || (r >= 0xD800 && r <= 0xDFFF) || (r >= 0xFDD0 && r <= 0xFDEF) || (r > 0x10FFFF)) return -1; return 0; }
oonsamyi/flow
tests/cli_renderer_color/haste_dupes/dupe2.js
<gh_stars>1000+ /** * @providesModule dupe * @format * @flow */
jszeluga/dbeaver
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/registry/DataSourceDescriptorManager.java
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2019 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.registry; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.model.DBPDataSource; import org.jkiss.dbeaver.model.DBPDataSourceFolder; import org.jkiss.dbeaver.model.DBPObject; import org.jkiss.dbeaver.model.app.DBPDataSourceRegistry; import org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration; import org.jkiss.dbeaver.model.edit.DBECommandContext; import org.jkiss.dbeaver.model.edit.DBEObjectMaker; import org.jkiss.dbeaver.model.impl.DBSObjectCache; import org.jkiss.dbeaver.model.impl.edit.AbstractObjectManager; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.dbeaver.ui.actions.datasource.DataSourceHandler; import org.jkiss.dbeaver.ui.dialogs.connection.CreateConnectionDialog; import org.jkiss.dbeaver.ui.dialogs.connection.NewConnectionWizard; import java.util.Map; /** * DataSourceDescriptorManager */ public class DataSourceDescriptorManager extends AbstractObjectManager<DataSourceDescriptor> implements DBEObjectMaker<DataSourceDescriptor, DBPObject> { @Override public long getMakerOptions(DBPDataSource dataSource) { return 0; } @Nullable @Override public DBSObjectCache<? extends DBSObject, DataSourceDescriptor> getObjectsCache(DataSourceDescriptor object) { return null; } @Override public boolean canCreateObject(DBPObject parent) { return true; } @Override public boolean canDeleteObject(DataSourceDescriptor object) { return true; } @Override public DataSourceDescriptor createNewObject(DBRProgressMonitor monitor, DBECommandContext commandContext, DBPObject parent, Object copyFrom) { if (copyFrom != null) { DataSourceDescriptor dsTpl = (DataSourceDescriptor)copyFrom; DBPDataSourceRegistry registry; DBPDataSourceFolder folder = null; if (parent instanceof DataSourceRegistry) { registry = (DBPDataSourceRegistry) parent; } else if (parent instanceof DBPDataSourceFolder) { folder = (DBPDataSourceFolder)parent; registry = folder.getDataSourceRegistry(); } else { registry = dsTpl.getRegistry(); } DataSourceDescriptor dataSource = new DataSourceDescriptor( registry, DataSourceDescriptor.generateNewId(dsTpl.getDriver()), dsTpl.getDriver(), new DBPConnectionConfiguration(dsTpl.getConnectionConfiguration())); dataSource.copyFrom(dsTpl); if (folder != null) { dataSource.setFolder(folder); } else { dataSource.setFolder(dsTpl.getFolder()); } // Generate new name String origName = dsTpl.getName(); String newName = origName; for (int i = 0; ; i++) { if (registry.findDataSourceByName(newName) == null) { break; } newName = origName + " " + (i + 1); } dataSource.setName(newName); registry.addDataSource(dataSource); } else { UIUtils.asyncExec(new Runnable() { @Override public void run() { CreateConnectionDialog dialog = new CreateConnectionDialog( UIUtils.getActiveWorkbenchWindow(), new NewConnectionWizard()); dialog.open(); } }); } return null; } @Override public void deleteObject(DBECommandContext commandContext, final DataSourceDescriptor object, Map<String, Object> options) { Runnable remover = new Runnable() { @Override public void run() { object.getRegistry().removeDataSource(object); } }; if (object.isConnected()) { DataSourceHandler.disconnectDataSource(object, remover); } else { remover.run(); } } }
Passarinho4/udash-core
rest/src/main/scala/io/udash/rest/SttpRestClient.scala
<filename>rest/src/main/scala/io/udash/rest/SttpRestClient.scala package io.udash package rest import com.avsystem.commons._ import com.avsystem.commons.annotation.explicitGenerics import com.avsystem.commons.meta.Mapping import com.softwaremill.sttp.Uri.QueryFragment.KeyValue import com.softwaremill.sttp.Uri.QueryFragmentEncoding import com.softwaremill.sttp._ import io.udash.rest.raw._ import scala.concurrent.Future object SttpRestClient { def defaultBackend(): SttpBackend[Future, Nothing] = DefaultSttpBackend() @explicitGenerics def apply[RestApi: RawRest.AsRealRpc : RestMetadata](baseUri: String)( implicit backend: SttpBackend[Future, Nothing] ): RestApi = RawRest.fromHandleRequest[RestApi](asHandleRequest(baseUri)) /** * Creates a [[io.udash.rest.raw.RawRest.HandleRequest HandleRequest]] function which sends REST requests to * a specified base URI using default HTTP client implementation (sttp). */ def asHandleRequest(baseUri: String)(implicit backend: SttpBackend[Future, Nothing]): RawRest.HandleRequest = asHandleRequest(uri"$baseUri") private def toSttpRequest(baseUri: Uri, request: RestRequest): Request[String, Nothing] = { val uri = baseUri |> (u => u.copy(path = u.path ++ request.parameters.path.map(_.value))) |> (u => u.copy(queryFragments = u.queryFragments ++ request.parameters.query.iterator.map { case (k, QueryValue(v)) => KeyValue(k, v, QueryFragmentEncoding.All, QueryFragmentEncoding.All) }.toList )) val contentTypeHeader = request.body.mimeTypeOpt.map { mimeType => (HeaderNames.ContentType, s"$mimeType;charset=utf-8") } val paramHeaders = request.parameters.headers.iterator.map { case (n, HeaderValue(v)) => (n, v) }.toList sttp.copy[Id, String, Nothing]( method = Method(request.method.name), uri = uri, headers = contentTypeHeader.toList ++ paramHeaders, body = request.body.contentOpt.map(StringBody(_, "utf-8")).getOrElse(NoBody) ) } private def fromSttpResponse(sttpResp: Response[String]): RestResponse = RestResponse( sttpResp.code, Mapping( sttpResp.headers.iterator.map { case (n, v) => (n, HeaderValue(v)) }.toList, caseInsensitive = true ), sttpResp.contentType.fold(HttpBody.empty) { contentType => val mimeType = contentType.split(";", 2).head HttpBody(sttpResp.body.fold(identity, identity), mimeType) } ) private def asHandleRequest(baseUri: Uri)(implicit backend: SttpBackend[Future, Nothing]): RawRest.HandleRequest = RawRest.safeHandle(request => { val sttpReq = toSttpRequest(baseUri, request) callback => sttpReq.send().onCompleteNow(respTry => callback(respTry.map(fromSttpResponse))) }) }
FCS-holding/acc_lib
compression_xilinx/L2/src/lz4_p2p_decompress_kernel.cpp
/* * (c) Copyright 2019 Xilinx, Inc. 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. * */ /** * @file xil_lz4_decompress_kernel.cpp * @brief Source for LZ4 decompression kernel. * * This file is part of XF Compression Library. */ #include "lz4_p2p_decompress_kernel.hpp" #define MAX_OFFSET 65536 #define HISTORY_SIZE MAX_OFFSET const int c_gmemBurstSize = (2 * GMEM_BURST_SIZE); #define BIT 8 #define READ_STATE 0 #define MATCH_STATE 1 #define LOW_OFFSET_STATE 2 #define LOW_OFFSET 8 // This should be bigger than Pipeline Depth to handle inter dependency false case typedef ap_uint<BIT> uintV_t; void lz4CoreDec(hls::stream<xf::compression::uintMemWidth_t>& inStreamMemWidth, hls::stream<xf::compression::uintMemWidth_t>& outStreamMemWidth, const uint32_t _input_size, const uint32_t _output_size, const uint32_t _input_start_idx) { uint32_t input_size = _input_size; uint32_t output_size = _output_size; uint32_t input_size1 = input_size; uint32_t output_size1 = output_size; uint32_t input_start_idx = _input_start_idx; hls::stream<uintV_t> instreamV("instreamV"); hls::stream<xf::compression::compressd_dt> decompressd_stream("decompressd_stream"); hls::stream<uintV_t> decompressed_stream("decompressed_stream"); #pragma HLS STREAM variable = instreamV depth = 8 #pragma HLS STREAM variable = decompressd_stream depth = 8 #pragma HLS STREAM variable = decompressed_stream depth = 8 #pragma HLS RESOURCE variable = instreamV core = FIFO_SRL #pragma HLS RESOURCE variable = decompressd_stream core = FIFO_SRL #pragma HLS RESOURCE variable = decompressed_stream core = FIFO_SRL bool uncomp_flag = 0; if (input_size == output_size) uncomp_flag = 1; #pragma HLS dataflow xf::compression::streamDownsizerP2P<uint32_t, GMEM_DWIDTH, 8>(inStreamMemWidth, instreamV, input_size, input_start_idx); xf::compression::lz4DecompressSimple(instreamV, decompressd_stream, input_size1, uncomp_flag); xf::compression::lzDecompress<HISTORY_SIZE, READ_STATE, MATCH_STATE, LOW_OFFSET_STATE, LOW_OFFSET>( decompressd_stream, decompressed_stream, output_size); xf::compression::streamUpsizer<uint32_t, 8, GMEM_DWIDTH>(decompressed_stream, outStreamMemWidth, output_size1); } void lz4Dec(const xf::compression::uintMemWidth_t* in, xf::compression::uintMemWidth_t* out, const uint32_t input_idx[PARALLEL_BLOCK], const uint32_t input_size[PARALLEL_BLOCK], const uint32_t output_size[PARALLEL_BLOCK], const uint32_t input_size1[PARALLEL_BLOCK], const uint32_t output_size1[PARALLEL_BLOCK], const uint32_t output_idx[PARALLEL_BLOCK]) { hls::stream<xf::compression::uintMemWidth_t> inStreamMemWidth[PARALLEL_BLOCK]; hls::stream<xf::compression::uintMemWidth_t> outStreamMemWidth[PARALLEL_BLOCK]; #pragma HLS STREAM variable = inStreamMemWidth_0 depth = c_gmemBurstSize #pragma HLS STREAM variable = outStreamMemWidth_0 depth = c_gmemBurstSize #pragma HLS RESOURCE variable = inStreamMemWidth_0 core = FIFO_SRL #pragma HLS RESOURCE variable = outStreamMemWidth_0 core = FIFO_SRL #pragma HLS dataflow // Transfer data from global memory to kernel xf::compression::mm2sNbRoundOff<GMEM_DWIDTH, GMEM_BURST_SIZE, PARALLEL_BLOCK>(in, input_idx, inStreamMemWidth, input_size); for (uint8_t i = 0; i < PARALLEL_BLOCK; i++) { #pragma HLS UNROLL // lz4CoreDec is instantiated based on the PARALLEL_BLOCK lz4CoreDec(inStreamMemWidth[i], outStreamMemWidth[i], input_size1[i], output_size1[i], input_idx[i]); } // Transfer data from kernel to global memory xf::compression::s2mmNb<uint32_t, GMEM_BURST_SIZE, GMEM_DWIDTH, PARALLEL_BLOCK>(out, output_idx, outStreamMemWidth, output_size); } //} // namespace end extern "C" { void xilLz4P2PDecompress(const xf::compression::uintMemWidth_t* in, xf::compression::uintMemWidth_t* out, dt_blockInfo* decompress_block_info, dt_chunkInfo* decompress_chunk_info, uint32_t block_size_in_kb, uint32_t compute_unit, uint8_t total_no_cu, uint32_t num_blocks) { #pragma HLS INTERFACE m_axi port = in offset = slave bundle = gmem #pragma HLS INTERFACE m_axi port = out offset = slave bundle = gmem #pragma HLS INTERFACE m_axi port = decompress_block_info offset = slave bundle = gmem #pragma HLS INTERFACE m_axi port = decompress_chunk_info offset = slave bundle = gmem #pragma HLS INTERFACE s_axilite port = in bundle = control #pragma HLS INTERFACE s_axilite port = out bundle = control #pragma HLS INTERFACE s_axilite port = decompress_block_info bundle = control #pragma HLS INTERFACE s_axilite port = decompress_chunk_info bundle = control #pragma HLS INTERFACE s_axilite port = block_size_in_kb bundle = control #pragma HLS INTERFACE s_axilite port = compute_unit bundle = control #pragma HLS INTERFACE s_axilite port = total_no_cu bundle = control #pragma HLS INTERFACE s_axilite port = num_blocks bundle = control #pragma HLS INTERFACE s_axilite port = return bundle = control #pragma HLS data_pack variable = in #pragma HLS data_pack variable = out #pragma HLS data_pack variable = decompress_block_info #pragma HLS data_pack variable = decompress_chunk_info uint32_t max_block_size = block_size_in_kb * 1024; uint32_t compress_size[PARALLEL_BLOCK]; uint32_t compress_size1[PARALLEL_BLOCK]; uint32_t block_size[PARALLEL_BLOCK]; uint32_t block_size1[PARALLEL_BLOCK]; uint32_t input_idx[PARALLEL_BLOCK]; uint32_t output_idx[PARALLEL_BLOCK]; #pragma HLS ARRAY_PARTITION variable = input_idx dim = 0 complete #pragma HLS ARRAY_PARTITION variable = output_idx dim = 0 complete #pragma HLS ARRAY_PARTITION variable = compress_size dim = 0 complete #pragma HLS ARRAY_PARTITION variable = compress_size1 dim = 0 complete #pragma HLS ARRAY_PARTITION variable = block_size dim = 0 complete #pragma HLS ARRAY_PARTITION variable = block_size1 dim = 0 complete uint32_t curr_no_blocks = decompress_chunk_info->numBlocksPerCU[compute_unit]; int offset = num_blocks * compute_unit; // printf ("In decode compute unit %d no_blocks %d\n", D_COMPUTE_UNIT, curr_no_blocks); for (uint32_t i = 0; i < curr_no_blocks; i += PARALLEL_BLOCK) { uint32_t nblocks = PARALLEL_BLOCK; if ((i + PARALLEL_BLOCK) > curr_no_blocks) { nblocks = curr_no_blocks - i; } for (uint32_t j = 0; j < PARALLEL_BLOCK; j++) { dt_blockInfo bInfo = decompress_block_info[i + j + offset]; if (j < nblocks) { uint32_t iSize = bInfo.compressedSize; uint32_t oSize = bInfo.blockSize; compress_size[j] = iSize; block_size[j] = oSize; compress_size1[j] = iSize; block_size1[j] = oSize; input_idx[j] = bInfo.blockStartIdx; // printf("iSize:%d\toSize:%d\tblockIdx:%d\n", iSize, oSize, input_idx[j]); output_idx[j] = (i + j) * max_block_size; } else { compress_size[j] = 0; block_size[j] = 0; compress_size1[j] = 0; block_size1[j] = 0; input_idx[j] = 0; output_idx[j] = 0; } } lz4Dec(in, out, input_idx, compress_size, block_size, compress_size1, block_size1, output_idx); } } }
drproduck/Element-Analytics
Element_Analytics/apps/edit/views.py
from django.shortcuts import render, redirect from django.contrib.auth.forms import UserChangeForm from apps.edit.forms import EditProfileForm from django.contrib.auth.decorators import login_required # Create your views here. @login_required def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance = request.user) if form.is_valid(): form.save() return redirect('/userprof/') else: form = EditProfileForm(instance=request.user) args = {'form': form} return render(request,'edit/edit.djt', args)
Purg/SMQTK
python/smqtk/algorithms/classifier/_classifier_collection.py
<reponame>Purg/SMQTK import threading import six from smqtk.exceptions import MissingLabelError from smqtk.utils import SmqtkObject from smqtk.utils.configuration \ import Configurable, make_default_config, from_config_dict, to_config_dict from smqtk.utils.dict import merge_dict from ._defaults import DFLT_CLASSIFIER_FACTORY from ._interface_classifier import Classifier class ClassifierCollection (SmqtkObject, Configurable): """ A collection of descriptively-labeled classifier instances for the purpose of applying all stored classifiers to one or more input descriptor elements. TODO: [optionally?] map a classification element factory per classifier. """ EXAMPLE_KEY = '__example_label__' @classmethod def get_default_config(cls): c = super(ClassifierCollection, cls).get_default_config() # We list the label-classifier mapping on one level, so remove the # nested map parameter that can optionally be used in the constructor. del c['classifiers'] # Add slot of a list of classifier plugin specifications c[cls.EXAMPLE_KEY] = make_default_config(Classifier.get_impls()) return c @classmethod def from_config(cls, config_dict, merge_default=True): """ Instantiate a new instance of this class given the configuration JSON-compliant dictionary encapsulating initialization arguments. This method should not be called via super unless an instance of the class is desired. :param config_dict: JSON compliant dictionary encapsulating a configuration. :type config_dict: dict :param merge_default: Merge the given configuration on top of the default provided by ``get_default_config``. :type merge_default: bool :return: Constructed instance from the provided config. :rtype: ClassifierCollection """ if merge_default: config_dict = merge_dict(cls.get_default_config(), config_dict) classifier_map = {} # Copying list of keys so we can update the dictionary as we loop. for label in list(config_dict.keys()): # Skip the example section. if label == cls.EXAMPLE_KEY: continue classifier_config = config_dict[label] classifier = from_config_dict(classifier_config, Classifier.get_impls()) classifier_map[label] = classifier # Don't merge back in "example" default return super(ClassifierCollection, cls).from_config( {'classifiers': classifier_map}, merge_default=False ) def __init__(self, classifiers=None, **labeled_classifiers): """ :param classifiers: Optional dictionary of semantic label keys and Classifier instance values. :type classifiers: dict[str, Classifier] :param labeled_classifiers: Key-word arguments may be provided where the key used is considered the semantic label of the provided Classifier instance. :type labeled_classifiers: Classifier """ self._label_to_classifier_lock = threading.RLock() self._label_to_classifier = {} # Go though classifiers map and key-word arguments, check that values # are actually classifiers. if classifiers is not None: for label, classifier in six.iteritems(classifiers): if not isinstance(classifier, Classifier): raise ValueError("Found a non-Classifier instance value " "for key '%s'" % label) self._label_to_classifier[label] = classifier for label, classifier in six.iteritems(labeled_classifiers): if not isinstance(classifier, Classifier): raise ValueError("Found a non-Classifier instance value " "for key '%s'" % label) elif label in self._label_to_classifier: raise ValueError("Duplicate classifier label '%s' provided " "in key-word arguments." % label) self._label_to_classifier[label] = classifier def __enter__(self): """ :rtype: IqrSession """ self._label_to_classifier_lock.acquire() return self # noinspection PyUnusedLocal def __exit__(self, exc_type, exc_val, exc_tb): self._label_to_classifier_lock.release() def get_config(self): with self._label_to_classifier_lock: c = dict((label, to_config_dict(classifier)) for label, classifier in six.iteritems(self._label_to_classifier)) return c def size(self): with self._label_to_classifier_lock: return len(self._label_to_classifier) __len__ = size def labels(self): """ :return: Set of labels for currently collected classifiers. :rtype: set[str] """ with self._label_to_classifier_lock: return set(self._label_to_classifier.keys()) def add_classifier(self, label, classifier): """ Add a classifier instance with associated descriptive label to this collection. :param label: String descriptive label for the classifier. :type label: str :param classifier: Classifier instance to collect. :type classifier: Classifier :raises ValueError: Classifier provided is not actually a classifier instance, or if the label provided already exists in this collection. :return: Self. :rtype: self """ if not isinstance(classifier, Classifier): raise ValueError("Not given a Classifier instance (given type" " %s)." % type(classifier)) with self._label_to_classifier_lock: if label in self._label_to_classifier: raise ValueError("Duplicate label provided: '%s'" % label) self._label_to_classifier[label] = classifier return self def get_classifier(self, label): """ Get the classifier instance for a given label. :param label: Label of the classifier to get. :type label: str :raises KeyError: No classifier for the given label. :return: Classifier instance. :rtype: Classifier """ with self._label_to_classifier_lock: return self._label_to_classifier[label] def remove_classifier(self, label): """ Remove a label-classifier pair from this collection. :param label: Label of the classifier to remove. :type label: str :raises KeyError: The given label does not reference a classifier in this collection. :return: Self. :rtype: self """ with self._label_to_classifier_lock: del self._label_to_classifier[label] def classify(self, descriptor, labels=None, factory=DFLT_CLASSIFIER_FACTORY, overwrite=False): """ Apply all stored classifiers to the given descriptor element. We return a dictionary mapping the label of a stored classifier to the classifier element result produced by that classifier via the provided classification element factory. :param descriptor: Descriptor element to classify. :type descriptor: smqtk.representation.DescriptorElement :param labels: One or more labels of stored classifiers to use for classifying the given descriptor. If None, use all stored classifiers. :type labels: Iterable[str] :param factory: Classification element factory. :type factory: ClassificationElementFactory :param overwrite: Force re-computation of the classification of the input descriptor. :type overwrite: bool :raises smqtk.exceptions.MissingLabelError: Some or all of the requested labels are missing. :return: Result dictionary of classifier labels to classification elements. :rtype: dict[str, smqtk.representation.ClassificationElement] """ d_classifications = {} with self._label_to_classifier_lock: # TODO(paul.tunison): Parallelize? if labels is not None: # If we're missing some of the requested labels, complain missing_labels = set(labels) - self.labels() if missing_labels: raise MissingLabelError(missing_labels) for label in labels: classifier = self._label_to_classifier[label] d_classifications[label] = classifier.classify_one_element( descriptor, factory=factory, overwrite=overwrite ) else: for label, classifier in six.iteritems( self._label_to_classifier): d_classifications[label] = classifier.classify_one_element( descriptor, factory=factory, overwrite=overwrite ) return d_classifications # TODO(paul.tunison): Classify many descriptors method when the need # arises (see updated vectorized Classifier API).
sam6321/DDFC-OVA-Dicsord-Bot
Commands/music.js
<gh_stars>0 const MusicContext = require("../music/context.js"); exports.description = "Plays music from Youtube. Has three subcommands: 'play', 'skip', and 'list'"; exports.info = "Plays music from Youtube.\n'play' - Specify a Youtube video URL to play. If a video is already playing, it will be added to the queue.\n'skip' - Vote to skip the current video.\n'list' - List all videos that are currently in the queue"; exports.usage = "*music play (url), *music skip, *music list"; exports.category = "music"; let contexts = {}; exports.call = async function (messageContext) { if(!messageContext.guild) { await messageContext.send("Can't access music commands outside of a guild."); return; } let musicContext = contexts[messageContext.id]; if(!musicContext) { // This guild doesn't have a context, so get one for it. musicContext = new MusicContext(messageContext.guild); contexts[messageContext.id] = musicContext; } musicContext.run(messageContext); };
ZhangUranus/partner-fq
hot-deploy/partner/src/org/ofbiz/partner/scm/purplan/PurPlanBalance.java
package org.ofbiz.partner.scm.purplan; import java.math.BigDecimal; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.entity.Delegator; import org.ofbiz.entity.GenericValue; /** * 提供采购申请单查询供应商物料可入库余额 * 提供余额表更新 * * * @author Mark * */ public class PurPlanBalance { public static final String module = PurPlanBalance.class.getName(); private Object updateLock=new Object();//余额表更新锁 private static PurPlanBalance instance=null; private PurPlanBalance(){ } public static PurPlanBalance getInstance(){ if(instance==null){ instance=new PurPlanBalance(); } return instance; } /** * 获取可以入库余额 * @param supplierId * @param materialId * @return */ public BigDecimal getBalance(String supplierId,String materialId) throws Exception{ if(supplierId==null||materialId==null){ throw new Exception("supplierId or materialId is null"); } //查找供应商可入库余额表 Delegator delegator=org.ofbiz.partner.scm.common.Utils.getDefaultDelegator(); GenericValue gv=delegator.findOne("PurPlanBalance", UtilMisc.toMap("supplierId", supplierId, "materialId", materialId), false); if(gv!=null){ return gv.getBigDecimal("balance"); } return null; } /** * 更新供应商可入库余额表 * @param supplierId * @param materialId * @param volume * @throws Exception */ public void updateInWarehouse(String supplierId,String materialId,BigDecimal volume) throws Exception{ synchronized (updateLock) { if(supplierId==null||materialId==null||volume==null){ throw new Exception("supplierId or materialId or volume is null"); } //查找供应商可入库余额表 Delegator delegator=org.ofbiz.partner.scm.common.Utils.getDefaultDelegator(); GenericValue gv=delegator.findOne("PurPlanBalance", UtilMisc.toMap("supplierId", supplierId, "materialId", materialId), false); if(gv!=null){ BigDecimal balance=gv.getBigDecimal("balance"); BigDecimal result=balance.add(volume); if(result.compareTo(BigDecimal.ZERO)<0){ throw new Exception("供应商入库数量不能大于待验收数量,请重新输入!"); } gv.set("balance", result); delegator.store(gv); }else{//新增记录 gv=delegator.makeValue("PurPlanBalance"); gv.set("supplierId", supplierId); gv.set("materialId", materialId); if(volume.compareTo(BigDecimal.ZERO)<0){ throw new Exception("供应商入库数量不能大于待验收数量,请重新输入!"); } gv.set("balance", volume); delegator.create(gv); } } } }
jacobgoh101/fcc-voting-backend
dist/middleware/index.js
<filename>dist/middleware/index.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _express = require("express"); exports.default = function (_ref) { var config = _ref.config, db = _ref.db; var routes = (0, _express.Router)(); // add middleware here return routes; }; //# sourceMappingURL=index.js.map
codahale/voldemort-sets
src/main/java/com/codahale/voldemort/sets/ReverseSortedLongSet.java
package com.codahale.voldemort.sets; import java.util.Comparator; public class ReverseSortedLongSet extends SortedLongSet { private static final Comparator<Long> REVERSE = new Comparator<Long>() { @Override public int compare(Long o1, Long o2) { return o2.compareTo(o1); } }; @Override protected Comparator<Long> getComparator() { return REVERSE; } }
ahnitz/pegasus
src/tools/pegasus-kickstart/mylist.c
<filename>src/tools/pegasus-kickstart/mylist.c /* * This file or a portion of this file is licensed under the terms of * the Globus Toolkit Public License, found in file GTPL, or at * http://www.globus.org/toolkit/download/license.html. This notice must * appear in redistributions of this file, with or without modification. * * Redistributions of this Software, with or without modification, must * reproduce the GTPL in: (1) the Software, or (2) the Documentation or * some other similar material which is provided with the Software (if * any). * * Copyright 1999-2004 University of Chicago and The University of * Southern California. All rights reserved. */ #include <ctype.h> #include <errno.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include "mylist.h" #ifndef ITEM_MAGIC #define ITEM_MAGIC 0xcd82bd08 #endif #ifndef LIST_MAGIC #define LIST_MAGIC 0xbae21bdb #endif int mylist_item_init(mylist_item_p item, const char* data) { /* purpose: initial a data item. * paramtr: item (OUT): item pointer to initialize * data (IN): string to copy into item * returns: 0 on success, * EINVAL if arguments are NULL * ENOMEM if allocation failed */ char* s; /* sanity check */ if (item == NULL || data == NULL) { return EINVAL; } memset(item, 0, sizeof(mylist_item_t)); item->magic = ITEM_MAGIC; if ((item->pfn = strdup(data)) == NULL) { return ENOMEM; } if ((s = strchr(item->pfn, '='))) { *s++ = '\0'; item->lfn = item->pfn; item->pfn = s; } else { item->lfn = NULL; } return 0; } int mylist_item_done(mylist_item_p item) { /* purpose: free allocated space of an item * paramtr: item (IO): area to free * returns: 0 on success, * EINVAL if the magic failed, or NULL argument */ /* sanity check */ if (item == NULL || item->magic != ITEM_MAGIC) { return EINVAL; } /* free item */ if (item->lfn) { free((void*) item->lfn); } else if (item->pfn) { free((void*) item->pfn); } memset(item, 0, sizeof(mylist_item_t)); return 0; } int mylist_init(mylist_p list) { /* sanity check */ if (list == NULL) { return EINVAL; } memset(list, 0, sizeof(mylist_t)); list->magic = LIST_MAGIC; return 0; } int mylist_add(mylist_p list, const char* data) { int status; mylist_item_p temp; /* sanity check */ if (list == NULL || list->magic != LIST_MAGIC) { return EINVAL; } /* allocate item space */ if ((temp = malloc(sizeof(mylist_item_t))) == NULL) { return ENOMEM; } if ((status = mylist_item_init(temp, data)) != 0) { free((void*) temp); return status; } /* add item to list */ if (list->count) { list->tail->next = temp; list->tail = temp; } else { list->head = list->tail = temp; } list->count++; return 0; } int mylist_done(mylist_p list) { /* sanity check */ if (list == NULL || list->magic != LIST_MAGIC) { return EINVAL; } if (list->count) { /* traverse list */ int status; mylist_item_p temp; while ((temp = list->head) != NULL) { list->head = list->head->next; if ((status=mylist_item_done(temp)) != 0) return status; free((void*) temp); } } memset(list, 0, sizeof(mylist_t)); return 0; } int mylist_fill(mylist_p list, const char* fn) { /* purpose: Add each line in the specified file to the list * paramtr: list (IO): list to modify * fn (IN): name of the file to read * returns: 0 on success, */ FILE* file; char* line, *s; int result = 0; size_t size = getpagesize(); /* sanity check */ if (list == NULL || list->magic != LIST_MAGIC) { return EINVAL; } /* try to open file */ if ((file=fopen(fn, "r")) == NULL) { return errno; } /* allocate line buffer */ if ((line=(char*)malloc(size)) == NULL) { fclose(file); return ENOMEM; } /* read lines from file */ while (fgets(line, size, file)) { /* FIXME: unhandled overly long lines */ /* comments */ if ((s = strchr(line, '#'))) { *s-- = '\0'; } else { s = line + strlen(line) - 1; } /* chomp */ while (s > line && isspace(*s)) { *s-- = '\0'; } /* skip empty lines */ if (*line == 0) { continue; } if ((result = mylist_add(list, line)) != 0) { break; } } /* done with file */ fclose(file); free((void*) line); return result; }
BastianBlokland/novus
src/parse/node_expr_switch.cpp
<filename>src/parse/node_expr_switch.cpp<gh_stars>10-100 #include "parse/node_expr_switch.hpp" #include "utilities.hpp" namespace parse { SwitchExprNode::SwitchExprNode(std::vector<NodePtr> ifClauses, NodePtr elseClause) : m_ifClauses{std::move(ifClauses)}, m_elseClause{std::move(elseClause)} {} auto SwitchExprNode::operator==(const Node& rhs) const noexcept -> bool { const auto r = dynamic_cast<const SwitchExprNode*>(&rhs); if (r == nullptr || !nodesEqual(m_ifClauses, r->m_ifClauses)) { return false; } if (hasElse() != r->hasElse()) { return false; } return m_elseClause == nullptr || *m_elseClause == *r->m_elseClause; } auto SwitchExprNode::operator!=(const Node& rhs) const noexcept -> bool { return !SwitchExprNode::operator==(rhs); } auto SwitchExprNode::operator[](unsigned int i) const -> const Node& { if (i < m_ifClauses.size()) { return *m_ifClauses[i]; } if (i == m_ifClauses.size() && hasElse()) { return *m_elseClause; } throw std::out_of_range{"No child at given index"}; } auto SwitchExprNode::getChildCount() const -> unsigned int { return m_ifClauses.size() + (hasElse() ? 1 : 0); } auto SwitchExprNode::getSpan() const -> input::Span { return input::Span::combine( m_ifClauses.front()->getSpan(), hasElse() ? m_elseClause->getSpan() : m_ifClauses.back()->getSpan()); } auto SwitchExprNode::hasElse() const -> bool { return m_elseClause != nullptr; } auto SwitchExprNode::accept(NodeVisitor* visitor) const -> void { visitor->visit(*this); } auto SwitchExprNode::print(std::ostream& out) const -> std::ostream& { return out << "switch"; } // Factories. auto switchExprNode(std::vector<NodePtr> ifClauses, NodePtr elseClause) -> NodePtr { if (ifClauses.empty()) { throw std::invalid_argument{"Atleast one if clause is required"}; } if (anyNodeNull(ifClauses)) { throw std::invalid_argument{"Switch cannot contain a null if-clause"}; } return std::unique_ptr<SwitchExprNode>{ new SwitchExprNode{std::move(ifClauses), std::move(elseClause)}}; } } // namespace parse
forest-watcher/forest-watcher
app/components/settings/gfw-layers/layer-download/styles.js
import Theme from 'config/theme'; import { StyleSheet } from 'react-native'; export default StyleSheet.create({ container: { backgroundColor: Theme.background.main, flex: 1 }, contentContainer: { paddingTop: 12, flex: 1 }, error: { fontSize: 12, fontWeight: '400', fontFamily: Theme.font, color: Theme.colors.carnation, paddingBottom: 24, paddingHorizontal: 24 }, heading: { ...Theme.sectionHeaderText, marginLeft: 24, marginTop: 24, marginBottom: 28 }, list: { flex: 1 }, listContent: { paddingTop: 10, paddingBottom: 10 }, rowContainer: { paddingVertical: 18 }, row: { alignItems: 'center', flex: 1, flexDirection: 'row', justifyContent: 'space-between' }, rowIcon: { height: 28, width: 28 }, rowLabel: { flexShrink: 1, fontFamily: Theme.font, color: Theme.fontColors.secondary, fontSize: 12 }, rowSubtitleLabel: { flexShrink: 1, fontFamily: Theme.font, color: Theme.fontColors.secondary, fontSize: 12, opacity: 0.6 }, rowTitleLabel: { flexShrink: 1, fontFamily: Theme.font, color: Theme.fontColors.secondary, fontSize: 16 } });
KMU-embedded/mosbench-ext
metis/tools/mergedir.c
/* * inverted index */ #include <sys/time.h> #include <sys/types.h> #include <sys/mman.h> #include <fcntl.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> #include <dirent.h> #include <errno.h> #include <pthread.h> #include <ctype.h> #include <assert.h> #include "lib/mr-sched.h" struct split_state; struct dirlist { char *pn; struct dirent **dirlist; int n; struct split_state *s; struct dirlist *next; }; struct split_state { struct dirlist *head; struct dirlist **end; pthread_mutex_t mu; }; static int nfiles = 0; static int nsplitted = 0; static int dirfilter(const struct dirent *de); static void eprint(const char *errstr, ...); static void linkdir(struct split_state *s, const char *pn, const char *dn); static void map(map_arg_t * ma); static int splitter(void *arg, uint64_t split_size, map_arg_t * ma); static uint64_t usec(void); static int dirfilter(const struct dirent *de) { if (strcmp(".", de->d_name) && strcmp("..", de->d_name)) return 1; return 0; } static void linkdir(struct split_state *s, const char *pn, const char *dn) { struct dirent **entlist; char *pn2; int n; assert(pn2 = malloc(strlen(pn) + strlen(dn) + 2)); pn2[0] = 0; strcat(pn2, pn); if (dn[0]) { strcat(pn2, dn); strcat(pn2, "/"); } n = scandir(pn2, &entlist, dirfilter, 0); if (n < 0) { free(pn2); return; } struct dirlist *dl; assert(dl = malloc(sizeof(*dl))); dl->pn = pn2; dl->dirlist = entlist; dl->n = n; dl->next = 0; dl->s = s; if (!s->head) s->head = dl; if (s->end) *s->end = dl; s->end = &dl->next; } static uint64_t total_size = 0; static void map(map_arg_t * ma) { enterapp(); char *fn = ma->data; int fd; char *buf, *end; off_t n; int r; struct stat st; char sample[128]; fd = open(fn, O_RDONLY); if (fd < 0) { leaveapp(); return; } r = read(fd, sample, sizeof(sample)); if (r < 0) { close(fd); leaveapp(); return; } /* try to skip binary files */ for (int i = 0; i < r; i++) if (!sample[i]) { close(fd); leaveapp(); return; } if (fstat(fd, &st) < 0) { close(fd); exit(EXIT_FAILURE); } n = st.st_size; buf = mmap(0, n, PROT_READ, MAP_PRIVATE, fd, 0); if (buf == MAP_FAILED) { close(fd); leaveapp(); return; } char *org_buf = buf; end = buf + n; total_size += n; munmap(org_buf, n); close(fd); leaveapp(); } static int splitter(void *arg, uint64_t split_size, map_arg_t * ma) { struct split_state *s = (struct split_state *) arg; enterapp(); pthread_mutex_lock(&s->mu); if (debug && nsplitted >= nfiles) { pthread_mutex_unlock(&s->mu); leaveapp(); return 0; } struct dirlist *dl = s->head; while (dl) { if (dl->n == 0) { struct dirlist *old = dl; dl = old->next; s->head = dl; free(old->pn); free(old); continue; } --dl->n; if (dl->dirlist[dl->n]->d_type == DT_DIR) { linkdir(s, dl->pn, dl->dirlist[dl->n]->d_name); } else { char *fn; assert(fn = malloc(strlen(dl->pn) + strlen(dl->dirlist[dl->n]->d_name) + 1)); fn[0] = 0; strcat(fn, dl->pn); strcat(fn, dl->dirlist[dl->n]->d_name); ma->data = fn; ma->length = 1; if (debug) { nsplitted++; if (nsplitted == nfiles) { return 0; } } return 1; } } pthread_mutex_unlock(&s->mu); leaveapp(); return 0; } static uint64_t usec(void) { struct timeval tv; gettimeofday(&tv, 0); return (uint64_t) tv.tv_sec * 1000000 + tv.tv_usec; } int main(int ac, char **av) { final_data_kvs_t der; struct split_state split_arg; int c, i, j; int np = 0; char *root; if (ac < 2) eprint("usage: %s root nfiles [optional]\n" "optional:\n" "-p <cpus> : how many cpus to use\n", av[0]); i = strlen(av[1]); if (av[1][i - 1] == '/') { assert(root = malloc(i + 1)); memcpy(root, av[1], i); root[i] = 0; } else { assert(root = malloc(i + 2)); memcpy(root, av[1], i); root[i] = '/'; root[i + 1] = 0; } nfiles = atoi(av[2]); nsplitted = 0; while ((c = getopt(ac, av, "p:s")) != -1) { switch (c) { case 'p': np = atoi(optarg); break; default: eprint("bad optional: %c\n", c); } } memset(&der, 0, sizeof(der)); memset(&param, 0, sizeof(param)); memset(&split_arg, 0, sizeof(split_arg)); pthread_mutex_init(&split_arg.mu, 0); linkdir(&split_arg, root, ""); free(root); param.nr_cpus = np; param.app_arg.app_type = app_type_mapgroup; param.app_arg.mapgroup.final_results = &der; if (with_keycopy) param.keycopy = keycopy; param.map_func = map; param.split_func = splitter; param.split_arg = &split_arg; param.key_cmp = compare; start = usec(); if (mr_run_scheduler(&param) < 0) eprint("mr_run_scheduler failed\n"); end = usec(); print_phase_time(); printf("%" PRIu64 " usec\n", end - start); uint64_t vals = 0; for (i = 0; i < der.length; i++) { keyvals_len_t *k = &((keyvals_len_t *) der.data)[i]; vals += k->len; } printf("length: %zu %ld MB input, %ld MB vals\n", der.length, total_size / (1024 * 1024), vals * 8 / (1024 * 1024)); if (debug) return 0; for (i = 0; i < der.length; i++) { keyvals_len_t *k = &((keyvals_len_t *) der.data)[i]; char **files = (char **) k->vals; printf(" + %s\n", (char *) k->key); for (j = 0; j < k->len; j++) printf(" - %s\n", files[j]); } }
gift-surg/GiftCloudServerBuilder
plugin-resources/webapp/xnat/java/org/nrg/xnat/restlet/actions/PullScanDataFromHeaders.java
/* * org.nrg.xnat.restlet.actions.PullScanDataFromHeaders * XNAT http://www.xnat.org * Copyright (c) 2014, Washington University School of Medicine * All Rights Reserved * * Released under the Simplified BSD. * * Last modified 7/30/13 2:58 PM */ package org.nrg.xnat.restlet.actions; import org.apache.log4j.Logger; import org.nrg.xdat.base.BaseElement; import org.nrg.xdat.om.XnatImagescandata; import org.nrg.xdat.om.XnatImagesessiondata; import org.nrg.xdat.om.XnatProjectdata; import org.nrg.xdat.security.XDATUser; import org.nrg.xft.XFTItem; import org.nrg.xft.db.MaterializedView; import org.nrg.xft.event.EventMetaI; import org.nrg.xft.schema.Wrappers.XMLWrapper.SAXReader; import org.nrg.xft.utils.SaveItemHelper; import org.nrg.xft.utils.ValidationUtils.ValidationResults; import org.nrg.xnat.archive.XNATSessionBuilder; import org.nrg.xnat.exceptions.MultipleScanException; import org.nrg.xnat.exceptions.ValidationException; import org.nrg.xnat.restlet.util.XNATRestConstants; import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; import java.util.Calendar; import java.util.concurrent.Callable; /** * @author <NAME> <<EMAIL>> * */ public class PullScanDataFromHeaders implements Callable<Boolean> { static Logger logger = Logger.getLogger(PullScanDataFromHeaders.class); private final XnatImagescandata tempMR; private final XDATUser user; private final boolean allowDataDeletion, isInPrearchive; private final EventMetaI c; public PullScanDataFromHeaders(final XnatImagescandata scan, final XDATUser user, boolean allowDataDeletion, boolean isInPrearchive, EventMetaI c) { this.tempMR = scan; this.user = user; this.allowDataDeletion = allowDataDeletion; this.isInPrearchive = isInPrearchive; this.c = c; } /** * This method will pull header values from DICOM (or ECAT) and update the * scan xml accordingly. It assumes the files are already in the archive and * properly referenced from the session xml. This would usually be run after * you've added the files via the REST API. WARNINGS: This method will not * update session level parameters This method will fail if the scan * directory contains more than one scan or session. * * @throws IOException * : Error accessing files * @throws SAXException * : Error parsing generated xml * @throws MultipleSessionException * @throws MultipleScanException * @throws ValidationException * : Scan invalid according to schema requirements (including * xdat tags) * @throws Exception */ public Boolean call() throws IOException, SAXException, MultipleScanException, ValidationException, Exception { final File scanDir = new File(tempMR.deriveScanDir()); // build timestamped file for SessionBuilder output. final String timestamp = (new java.text.SimpleDateFormat( XNATRestConstants.PREARCHIVE_TIMESTAMP)).format(Calendar .getInstance().getTime()); final File xml = new File(scanDir, tempMR.getId() + "_" + timestamp + ".xml"); // run DICOM builder final XNATSessionBuilder builder = new XNATSessionBuilder(scanDir, xml, tempMR.getImageSessionData().getProject(), isInPrearchive); builder.call(); if (!xml.exists() || xml.length() == 0) { new Exception("Unable to locate DICOM or ECAT files"); } final SAXReader reader = new SAXReader(user); final XFTItem temp2 = reader.parse(xml.getAbsolutePath()); final XnatImagesessiondata newmr = (XnatImagesessiondata) BaseElement .GetGeneratedItem(temp2); XnatImagescandata newscan = null; if (newmr.getScans_scan().size() > 1) { throw new MultipleScanException(); } else { newscan = (XnatImagescandata) newmr.getScans_scan().get(0); } newscan.copyValuesFrom(tempMR); newscan.setImageSessionId(tempMR.getImageSessionId()); newscan.setId(tempMR.getId()); newscan.setXnatImagescandataId(tempMR.getXnatImagescandataId()); if (!allowDataDeletion) { while (newscan.getFile().size() > 0) newscan.removeFile(0); } final ValidationResults vr = newmr.validate(); if (vr != null && !vr.isValid()) { throw new ValidationException(vr.toString()); } else { final XnatImagesessiondata mr = tempMR.getImageSessionData(); final XnatProjectdata proj = mr.getProjectData(); if (SaveItemHelper.authorizedSave(newscan, user, false, allowDataDeletion, c)) { try { MaterializedView.DeleteByUser(user); if (proj.getArcSpecification().getQuarantineCode() != null && proj.getArcSpecification().getQuarantineCode() .equals(1)) { mr.quarantine(user); } } catch (Exception e) { logger.error("", e); } } } return Boolean.TRUE; } }
softwareinmotion/submarine
lib/tasks/ci.rake
<reponame>softwareinmotion/submarine if Rails.env == 'ci' require 'ci/reporter/rake/rspec' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new(:rspec) task :rspec => 'ci:setup:rspec' end
JLLeitschuh/tapestry3
tapestry-framework/src/org/apache/tapestry/script/LetRule.java
// Copyright 2004 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry.script; import org.apache.tapestry.Tapestry; import org.apache.tapestry.util.xml.RuleDirectedParser; import org.xml.sax.Attributes; /** * Constructs an {@link org.apache.tapestry.script.LetToken} * from a &lt;let&gt; element, which may contain full content. * * @author <NAME> * @version $Id$ * @since 3.0 */ class LetRule extends AbstractTokenRule { public void startElement(RuleDirectedParser parser, Attributes attributes) { String key = getAttribute(attributes, "key"); String unique = getAttribute(attributes, "unique"); boolean uniqueFlag = unique != null && unique.equals("yes"); parser.validate(key, Tapestry.SIMPLE_PROPERTY_NAME_PATTERN, "ScriptParser.invalid-key"); LetToken token = new LetToken(key, uniqueFlag, parser.getLocation()); addToParent(parser, token); parser.push(token); } public void endElement(RuleDirectedParser parser) { parser.pop(); } }
PigsCanFlyLabs/message-backend
admin-service/src/test/scala/ca/pigscanfly/routes/AdminServiceSpec.scala
<reponame>PigsCanFlyLabs/message-backend<gh_stars>1-10 package ca.pigscanfly.routes import akka.actor.ActorRef import akka.http.scaladsl.model.HttpMethods.{DELETE, POST} import akka.http.scaladsl.model.HttpProtocols.`HTTP/1.0` import akka.http.scaladsl.model.headers.{Authorization, OAuth2BearerToken} import akka.http.scaladsl.model._ import akka.http.scaladsl.server.Route import akka.http.scaladsl.testkit.ScalatestRouteTest import akka.stream.ActorMaterializer import ca.pigscanfly.actor.AdminActor import ca.pigscanfly.cache.RoleAuthorizationCache import ca.pigscanfly.components._ import ca.pigscanfly.dao.{AdminDAO, UserDAO} import org.mockito.MockitoSugar import org.scalatest.{Matchers, WordSpec} import slick.jdbc.H2Profile import scala.concurrent.Future import scala.concurrent.duration.{FiniteDuration, _} class AdminServiceSpec extends WordSpec with Matchers with ScalatestRouteTest with AdminService with MockitoSugar { val driver = H2Profile import driver.api.Database implicit val db: driver.api.Database = mock[Database] implicit val schema: String = "" implicit val userDAO: UserDAO = mock[UserDAO] implicit val adminDAO: AdminDAO = mock[AdminDAO] override implicit val materializer: ActorMaterializer = ActorMaterializer() val futureAwaitTime: FiniteDuration = 10.minute val superAdminToken: String = createJwtTokenWithRole("<EMAIL>", "<PASSWORD>") val superAdminAuth: Authorization = Authorization(OAuth2BearerToken(superAdminToken)) val adminToken: String = createJwtTokenWithRole("<EMAIL>", "admin") val adminAuth: Authorization = Authorization(OAuth2BearerToken(adminToken)) val userToken: String = createJwtTokenWithRole("<EMAIL>", "user") val userAuth: Authorization = Authorization(OAuth2BearerToken(userToken)) implicit val futureAwaitDuration: FiniteDuration = FiniteDuration(futureAwaitTime.length, futureAwaitTime.unit) val adminActor: ActorRef = system.actorOf( AdminActor .props(adminDAO, userDAO), "adminActor") val route: Route = adminUserRoutes(adminActor) val rolesResourceAccessDB = Seq(RolesResourceAccessDB("admin", "admin_permissions", 1), RolesResourceAccessDB("super_admin", "super_admin_permissions,admin_permissions", 2)) val resourcePermissionsDB = Seq(ResourcePermissionsDB("admin_permissions", "get-user-details,create-user,update-user,disable-user"), ResourcePermissionsDB("super_admin_permissions", "delete-user,create-admin-user")) override def getUserDetails(command: ActorRef, deviceId: Long): Future[HttpResponse] = Future.successful(HttpResponse.apply()) override def createAdmin(command: ActorRef, admin: AdminLogin): Future[HttpResponse] = Future.successful(HttpResponse.apply()) override def createUser(command: ActorRef, user: User): Future[HttpResponse] = Future.successful(HttpResponse.apply()) override def updateUser(command: ActorRef, user: User): Future[HttpResponse] = Future.successful(HttpResponse.apply()) override def disableUser(command: ActorRef, request: DisableUserRequest): Future[HttpResponse] = Future.successful(HttpResponse.apply()) override def deleteUser(command: ActorRef, request: DeleteUserRequest): Future[HttpResponse] = Future.successful(HttpResponse.apply()) override def adminLogin(command: ActorRef, adminLogin: AdminLogin): Future[HttpResponse] = Future.successful(HttpResponse.apply()) "return OK if super admin sends request" in { when(adminDAO.getResourcePermissions) thenReturn Future((rolesResourceAccessDB, resourcePermissionsDB)) Get("/admin/get-user-details?deviceId=100").addHeader(superAdminAuth) ~> route ~> check { status shouldEqual StatusCodes.OK } HttpRequest( POST, uri = "/admin/create-admin-user", entity = HttpEntity( ContentTypes.`application/json`, """{ | "email": "email", | "password": "password", | "role":"admin" |}""".stripMargin), headers = List(superAdminAuth), protocol = `HTTP/1.0`) ~> route ~> check { status shouldBe StatusCodes.OK } HttpRequest( POST, uri = "/admin/create-user", entity = HttpEntity( ContentTypes.`application/json`, """{ | "deviceId": "10003", | "phone": "9684356", | "email": "email", | "isDisabled":false |}""".stripMargin), headers = List(superAdminAuth), protocol = `HTTP/1.0`) ~> route ~> check { status shouldBe StatusCodes.OK } HttpRequest( POST, uri = "/admin/update-user", entity = HttpEntity( ContentTypes.`application/json`, """{ | "deviceId": "10003", | "phone": "9684356", | "email": "email", | "isDisabled":false |}""".stripMargin), headers = List(superAdminAuth), protocol = `HTTP/1.0`) ~> route ~> check { status shouldBe StatusCodes.OK } HttpRequest( POST, uri = "/admin/disable-user", entity = HttpEntity( ContentTypes.`application/json`, """{ | "deviceId": "10036", | "email": "email", | "isDisabled":true |}""".stripMargin), headers = List(superAdminAuth), protocol = `HTTP/1.0`) ~> route ~> check { status shouldBe StatusCodes.OK } HttpRequest( DELETE, uri = "/admin/delete-user", entity = HttpEntity( ContentTypes.`application/json`, """{ | "deviceId": "10036", | "email": "email" |}""".stripMargin), headers = List(superAdminAuth), protocol = `HTTP/1.0`) ~> route ~> check { status shouldBe StatusCodes.OK } } "return OK for login request" in { HttpRequest( POST, uri = "/admin/login", entity = HttpEntity( ContentTypes.`application/json`, """{ | "email": "email", | "password": "password", | "role":"admin" |}""".stripMargin), headers = List(), protocol = `HTTP/1.0`) ~> route ~> check { status shouldBe StatusCodes.OK } } "return OK if admin sends request" in { when(adminDAO.getResourcePermissions) thenReturn Future((rolesResourceAccessDB, resourcePermissionsDB)) Get("/admin/get-user-details?deviceId=100").addHeader(adminAuth) ~> route ~> check { status shouldEqual StatusCodes.OK } HttpRequest( POST, uri = "/admin/create-user", entity = HttpEntity( ContentTypes.`application/json`, """{ | "deviceId": "10003", | "phone": "9684356", | "email": "email", | "isDisabled":false |}""".stripMargin), headers = List(adminAuth), protocol = `HTTP/1.0`) ~> route ~> check { status shouldBe StatusCodes.OK } HttpRequest( POST, uri = "/admin/update-user", entity = HttpEntity( ContentTypes.`application/json`, """{ | "deviceId": "10003", | "phone": "9684356", | "email": "email", | "isDisabled":false |}""".stripMargin), headers = List(adminAuth), protocol = `HTTP/1.0`) ~> route ~> check { status shouldBe StatusCodes.OK } HttpRequest( POST, uri = "/admin/disable-user", entity = HttpEntity( ContentTypes.`application/json`, """{ | "deviceId": "10036", | "email": "email", | "isDisabled":true |}""".stripMargin), headers = List(adminAuth), protocol = `HTTP/1.0`) ~> route ~> check { status shouldBe StatusCodes.OK } } "return Unauthorized if admin sends request" in { HttpRequest( DELETE, uri = "/admin/delete-user", entity = HttpEntity( ContentTypes.`application/json`, """{ | "deviceId": "10036", | "email": "email" |}""".stripMargin), headers = List(adminAuth), protocol = `HTTP/1.0`) ~> route ~> check { status shouldBe StatusCodes.Unauthorized } HttpRequest( POST, uri = "/admin/create-admin-user", entity = HttpEntity( ContentTypes.`application/json`, """{ | "email": "email", | "password": "password", | "role":"admin" |}""".stripMargin), headers = List(adminAuth), protocol = `HTTP/1.0`) ~> route ~> check { status shouldBe StatusCodes.Unauthorized } } "return Unauthorized if user sends request" in { when(adminDAO.getResourcePermissions) thenReturn Future((rolesResourceAccessDB, resourcePermissionsDB)) Get("/admin/get-user-details?deviceId=100").addHeader(userAuth) ~> route ~> check { status shouldEqual StatusCodes.Unauthorized } HttpRequest( POST, uri = "/admin/create-admin-user", entity = HttpEntity( ContentTypes.`application/json`, """{ | "email": "email", | "password": "password", | "role":"admin" |}""".stripMargin), headers = List(userAuth), protocol = `HTTP/1.0`) ~> route ~> check { status shouldBe StatusCodes.Unauthorized } HttpRequest( POST, uri = "/admin/create-user", entity = HttpEntity( ContentTypes.`application/json`, """{ | "deviceId": "10003", | "phone": "9684356", | "email": "email", | "isDisabled":false |}""".stripMargin), headers = List(userAuth), protocol = `HTTP/1.0`) ~> route ~> check { status shouldBe StatusCodes.Unauthorized } HttpRequest( POST, uri = "/admin/update-user", entity = HttpEntity( ContentTypes.`application/json`, """{ | "deviceId": "10003", | "phone": "9684356", | "email": "email", | "isDisabled":false |}""".stripMargin), headers = List(userAuth), protocol = `HTTP/1.0`) ~> route ~> check { status shouldBe StatusCodes.Unauthorized } HttpRequest( POST, uri = "/admin/disable-user", entity = HttpEntity( ContentTypes.`application/json`, """{ | "deviceId": "10036", | "email": "email", | "isDisabled":true |}""".stripMargin), headers = List(userAuth), protocol = `HTTP/1.0`) ~> route ~> check { status shouldBe StatusCodes.Unauthorized } HttpRequest( DELETE, uri = "/admin/delete-user", entity = HttpEntity( ContentTypes.`application/json`, """{ | "deviceId": "10036", | "email": "email" |}""".stripMargin), headers = List(userAuth), protocol = `HTTP/1.0`) ~> route ~> check { status shouldBe StatusCodes.Unauthorized } } override implicit val routeCache: RoleAuthorizationCache = new RoleAuthorizationCache(adminDAO) }
sheldonhull/git-town
src/dialog/config.go
<gh_stars>0 package dialog import ( "fmt" "strings" "github.com/fatih/color" "github.com/git-town/git-town/v7/src/git" ) // EnsureIsConfigured has the user to confgure the main branch and perennial branches if needed. func EnsureIsConfigured(repo *git.ProdRepo) error { if repo.Config.MainBranch() == "" { fmt.Println("Git Town needs to be configured") fmt.Println() err := ConfigureMainBranch(repo) if err != nil { return err } return ConfigurePerennialBranches(repo) } return nil } // ConfigureMainBranch has the user to confgure the main branch. func ConfigureMainBranch(repo *git.ProdRepo) error { localBranches, err := repo.Silent.LocalBranches() if err != nil { return err } newMainBranch, err := askForBranch(askForBranchOptions{ branchNames: localBranches, prompt: mainBranchPrompt(repo), defaultBranchName: repo.Config.MainBranch(), }) if err != nil { return err } return repo.Config.SetMainBranch(newMainBranch) } // ConfigurePerennialBranches has the user to confgure the perennial branches. func ConfigurePerennialBranches(repo *git.ProdRepo) error { branchNames, err := repo.Silent.LocalBranchesWithoutMain() if err != nil { return err } if len(branchNames) == 0 { return nil } newPerennialBranches, err := askForBranches(askForBranchesOptions{ branchNames: branchNames, prompt: perennialBranchesPrompt(repo), defaultBranchNames: repo.Config.PerennialBranches(), }) if err != nil { return err } return repo.Config.SetPerennialBranches(newPerennialBranches) } // Helpers func mainBranchPrompt(repo *git.ProdRepo) (result string) { result += "Please specify the main development branch:" currentMainBranch := repo.Config.MainBranch() if currentMainBranch != "" { coloredBranchName := color.New(color.Bold).Add(color.FgCyan).Sprintf(currentMainBranch) result += fmt.Sprintf(" (current value: %s)", coloredBranchName) } return } func perennialBranchesPrompt(repo *git.ProdRepo) (result string) { result += "Please specify perennial branches:" currentPerennialBranches := repo.Config.PerennialBranches() if len(currentPerennialBranches) > 0 { coloredBranchNames := color.New(color.Bold).Add(color.FgCyan).Sprintf(strings.Join(currentPerennialBranches, ", ")) result += fmt.Sprintf(" (current value: %s)", coloredBranchNames) } return }
Mart100/Midoxus-site
recreation/color.js
<reponame>Mart100/Midoxus-site<gh_stars>1-10 class Color { constructor(r, g, b, a) { this.r = r != undefined ? r : 255 this.g = g != undefined ? g : 255 this.b = b != undefined ? b : 255 this.a = a != undefined ? a : 255 } random() { this.r = Math.floor(Math.random()*255) this.g = Math.floor(Math.random()*255) this.b = Math.floor(Math.random()*255) this.a = 255 return this } clone() { return new Color(this.r, this.g, this.b, this.a) } blend(color2, opacity) { this.r = this.r*(1-opacity)+color2.r*opacity this.g = this.g*(1-opacity)+color2.g*opacity this.b = this.b*(1-opacity)+color2.b*opacity return this } }
UWICompSociety/computing-society-web-app
node_modules/cssnext/node_modules/caniuse-api/node_modules/lodash.memoize/node_modules/lodash._keyprefix/index.js
<filename>node_modules/cssnext/node_modules/caniuse-api/node_modules/lodash.memoize/node_modules/lodash._keyprefix/index.js<gh_stars>1-10 /** * Lo-Dash 2.4.2 (Custom Build) <http://lodash.com/> * Build: `lodash modularize modern exports="npm" -o ./npm/` * Copyright 2012-2014 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2013 <NAME>, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */ var keyPrefix = '__1335248838000__'; module.exports = keyPrefix;
jasonoscar88/Photon-v2
Engine/Source/FileIO/SDL/SdlResourcePack.cpp
<reponame>jasonoscar88/Photon-v2 #include "FileIO/SDL/SdlResourcePack.h" #include "FileIO/SDL/SdlParser.h" #include "Core/SampleGenerator/SampleGenerator.h" #include "Core/Filmic/TSamplingFilm.h" #include <iostream> namespace ph { SdlResourcePack::SdlResourcePack() : visualWorld(), renderOption(), m_camera(nullptr), m_sampleGenerator(nullptr), m_renderer(nullptr) {} void SdlResourcePack::update(const real deltaS) { const std::string& coreResourceName = SdlParser::CORE_DATA_NAME(); m_camera = resources.getResource<Camera> (coreResourceName, DataTreatment::REQUIRED()); m_sampleGenerator = resources.getResource<SampleGenerator>(coreResourceName, DataTreatment::REQUIRED()); m_renderer = resources.getResource<Renderer> (coreResourceName, DataTreatment::REQUIRED()); if(!m_camera || !m_sampleGenerator || !m_renderer) { std::cerr << "warning: at Description::update(), data incomplete" << std::endl; return; } m_cookSettings = resources.getResource<CookSettings>(coreResourceName); if(!m_cookSettings) { m_cookSettings = std::make_shared<CookSettings>(); } visualWorld.setCameraPosition(m_camera->getPosition()); visualWorld.setCookSettings(m_cookSettings); const auto& actors = resources.getActors(); for(const auto& actor : actors) { visualWorld.addActor(actor); } visualWorld.cook(); const real aspectRatio = static_cast<real>(m_renderer->getRenderWidthPx()) / m_renderer->getRenderHeightPx(); m_camera->setAspectRatio(aspectRatio); } }// end namespace ph
tceulema/Emuchron
firmware/clock/perftest.c
//***************************************************************************** // Filename : 'perftest.c' // Title : Test suite code for MONOCHRON glcd graphics performance tests //***************************************************************************** // // This module is not a clock but instead is a high level glcd graphics // performance test suite to be run on Monochron clock hardware and in the // Emuchron emulator. // The main purpose of this test suite is to get insight in the performance of // high and low level glcd graphics functions. The test suite is used to verify // whether (perceived) performance improvements in these glcd graphics // functions actually deliver or not, and whether new/optimized graphics code // is worth any (substantial) increase in atmel glcd object size. // // When building Monochron firmware, this module should be the only 'clock' in // the Monochron[] array as it is designed to run indefinitely. Again, this is // a test tool and not a functional clock. On Monochron, once the cycle() // method of this 'clock' is called, it will never return control to main(). // In contrast with Monochron, in the emulator at the root level in a module, // a 'q' keypress will exit the test suite and returns to the mchron caller // function. In most cases this will be the mchron command prompt. // // The code also runs in the Emuchron emulator, but as the emulator runs on // most likely an Intel/AMD class cpu, its speed performance results are // irrelevant. However, information related to commands and bytes sent to and // lcd data read from the controllers, and user calls to set the lcd cursor are // useful metrics that are not retrieved while running the test on Monochron. // Therefore, most insight in performance is gained by combining the statistics // test results from the Emuchron emulator and test run time from the actual // Monochron hardware. // // Running a test using the glut device, a test usually completes within a // second. Running a test using the ncurses device a test will take much longer // to complete but still less than on actual hardware. From a glcd and // controller statistics point of view it does not matter which lcd device is // used. It is therefor recommended to use the glut device only since it runs // in its own thread and is therefor so much faster than the ncurses device. // // Note that this module requires the analog clock module to build as its // functionality is used by a test in the glcdLine suite. // // The following high level glcd graphics functions are tested: // - glcdBitmap // - glcdCircle2 // - glcdDot // - glcdLine // - glcdFillCircle2 (specific use of glcdFillRectangle2) // - glcdFillRectangle2 // - glcdPutStr3 // - glcdPutStr3v // - glcdPutStr // - glcdRectangle (specific use of glcdFillRectangle2) // // A test suite consists of one or more tests. A single test consists of // generating many function calls to the function to be tested. // The user interface to a test suite is split-up into the following elements: // Part 1: Main entry for a test suite. // - Press a button to enter the test suite or skip to the next suite (that may // be a restart at the first suite). // Part 2: The following steps are repeated for each test in a test suite: // - Press a button to start or skip the test. // - Upon test start, sync on current time. // - Generate many function calls to the glcd function. The test itself should // last about two minutes on an actual Monochron clock. Keep track of // relevant test statistics. // - A test can be interrupted by a button press or a keyboard press. // - Upon completing/aborting a test sync on current time and present test // statistics. // - Press a button to rerun the test or continue with the next test. // - When all tests are completed exit the current suite and continue with the // next suite, or restart at the first suite. // // WARNING: The code in this module bypasses the defined Monochron clock plugin // framework for the greater good of providing a proper user interface and // obtaining proper test results. // Code in this module should not be replicated into clock modules that rely on // the stability of the defined clock plugin framework. It's your choice. // #ifdef EMULIN #include <stdio.h> #endif #include <math.h> #include "../global.h" #include "../glcd.h" #include "../anim.h" #include "../ks0108.h" #include "../ks0108conf.h" #include "../monomain.h" #include "../buttons.h" #ifdef EMULIN #include "../emulator/mchronutil.h" #endif #include "analog.h" #include "perftest.h" // Refer to appendix B in Emuchron_Manual.pdf [support]. // The test loop numbers below have been recalibrated several times. // Last calibration: Emuchron v5.0 using avr-gcc 5.4.0 (Debian 10). // The test loop numbers make every test run on Monochron hardware complete in // about 2 minutes. #define PERF_DOT_1 70 #define PERF_DOT_2 84 #define PERF_LINE_1 11897 #define PERF_LINE_2 30 #define PERF_CIRCLE2_1 461 #define PERF_CIRCLE2_2 897 #define PERF_FILLCIRCLE2_1 314 #define PERF_FILLCIRCLE2_2 1010 #define PERF_RECTANGLE2_1 942 #define PERF_RECTANGLE2_2 600 #define PERF_FILLRECTANGLE2_1 1332 #define PERF_FILLRECTANGLE2_2 6890 #define PERF_FILLRECTANGLE2_3 4172 #define PERF_FILLRECTANGLE2_4 4046 #define PERF_PUTSTR3_1 1206 #define PERF_PUTSTR3_2 2366 #define PERF_PUTSTR3_3 1124 #define PERF_PUTSTR3_4 2367 #define PERF_PUTSTR3_5 2185 #define PERF_PUTSTR3V_1 953 #define PERF_PUTSTR3V_2 2313 #define PERF_PUTSTR3V_3 1115 #define PERF_PUTSTR3V_4 2692 #define PERF_PUTSTR_1 6010 #define PERF_BITMAP_1 16200 #define PERF_BITMAP_2 1801 // Defines on button press action flavors #define PERF_WAIT_CONTINUE 0 #define PERF_WAIT_ENTER_SKIP 1 #define PERF_WAIT_START_SKIP 2 #define PERF_WAIT_RESTART_END 3 // Structure defining the admin data for test statistics typedef struct { char *text; u08 testId; u08 startSec; u08 startMin; u08 startHour; u08 endSec; u08 endMin; u08 endHour; u16 loopsDone; long elementsDrawn; } testStats_t; static const uint32_t __attribute__ ((progmem)) image[] = // 32x32 bitmap image { 0x7075f7df,0xbfeeffbf,0xdfdf7f7f,0xe73f9cff,0xf8ffe3ff,0xffffffff,0x1fffffff,0x03ffffff, 0x007fffff,0x000fffff,0xc001ffff,0xf8003fff,0xfe0007ff,0xfe0000ff,0xfe1c003f,0xfe1f801f, 0xfe1ff01f,0xfe1f801f,0xfe1c003f,0xfe0000ff,0xfe0007ff,0xf8003fff,0xc001ffff,0x000fffff, 0x007fffff,0x03ffffff,0x1fffffff,0xfe7e7fff,0xfdbdbfff,0xfbdbdfff,0x03dbc01f,0xdbdbdfff }; // Functional date/time/init variables extern volatile uint8_t mcClockOldTS, mcClockOldTM, mcClockOldTH; extern volatile uint8_t mcClockNewTS, mcClockNewTM, mcClockNewTH; extern volatile uint8_t mcClockOldDD, mcClockOldDM, mcClockOldDY; extern volatile uint8_t mcClockNewDD, mcClockNewDM, mcClockNewDY; extern volatile uint8_t mcClockInit; // Functional alarm variables extern volatile uint8_t mcAlarmSwitch; extern volatile uint8_t mcAlarming; extern volatile uint8_t mcUpdAlarmSwitch; // Functional color variables extern volatile uint8_t mcBgColor, mcFgColor; // The internal RTC clock time and button press indicators extern volatile rtcDateTime_t rtcDateTimeNext; extern volatile uint8_t rtcTimeEvent; extern volatile uint8_t btnPressed; // Generic test utility function prototypes static u08 perfButtonGet(void); static u08 perfButtonWait(u08 type); static void perfLongValToStr(long value, char valString[]); static u08 perfSuiteWelcome(char *label); static void perfTestBegin(void); static u08 perfTestEnd(u08 interruptTest); static u08 perfTestInit(char *label, u08 testId); static void perfTestTimeInit(void); static u08 perfTestTimeNext(void); static void perfTextInit(u08 length); static void perfTextToggle(void); // The actual performance test function prototypes static u08 perfTestBitmap(void); static u08 perfTestCircle2(void); static u08 perfTestDot(void); static u08 perfTestFillCircle2(void); static u08 perfTestFillRectangle2(void); static u08 perfTestLine(void); static u08 perfTestPutStr3(void); static u08 perfTestPutStr3v(void); static u08 perfTestPutStr(void); static u08 perfTestRectangle(void); // Runtime environment for the performance test static testStats_t testStats; // Text strings for glcdPutStr/glcdPutStr3/glcdPutStr3v tests static char textLineA[33]; static char textLineY[33]; static char *textLine; // Time counter for glcdLine-01 static u16 secCount; // // Function: perfCycle // // Run the performance test indefinitely // void perfCycle(void) { #ifdef EMULIN int myKbMode = KB_MODE_LINE; // In emulator switch to keyboard scan mode if needed myKbMode = kbModeGet(); if (myKbMode == KB_MODE_LINE) kbModeSet(KB_MODE_SCAN); #endif // Repeat forever while (1) { if (perfTestDot() == MC_TRUE) break; if (perfTestLine() == MC_TRUE) break; if (perfTestCircle2() == MC_TRUE) break; if (perfTestFillCircle2() == MC_TRUE) break; if (perfTestRectangle() == MC_TRUE) break; if (perfTestFillRectangle2() == MC_TRUE) break; if (perfTestPutStr3() == MC_TRUE) break; if (perfTestPutStr3v() == MC_TRUE) break; if (perfTestPutStr() == MC_TRUE) break; if (perfTestBitmap() == MC_TRUE) break; } #ifdef EMULIN // This only happens in the emulator glcdClearScreen(); glcdPutStr2(1, 58, FONT_5X5P, "quit performance test"); // Return to line mode if needed if (myKbMode == KB_MODE_LINE) kbModeSet(KB_MODE_LINE); #endif } // // Function: perfInit // // Initialize the lcd display for the performance test suite // void perfInit(u08 mode) { DEBUGP("Init Perftest"); // Give welcome screen glcdPutStr2(1, 1, FONT_5X5P, "monochron glcd performance test"); #ifdef EMULIN printf("\nTo exit performance test clock press 'q' on any main test suite prompt\n\n"); #endif // Wait for button press perfButtonWait(PERF_WAIT_CONTINUE); } // // Function: perfTestBitmap // // Performance test of glcdBitmap() // static u08 perfTestBitmap(void) { u08 button; u08 interruptTest; int i,j; u08 x; u08 y; // Give test suite welcome screen button = perfSuiteWelcome("glcdBitmap"); if (button == 'q') return MC_TRUE; else if (button != BTN_PLUS) return MC_FALSE; // Test 1: Move around a 32x32 bitmap around the display, triggering both // glcdBuffer y-line reads and full lcd byte y-line writes, by mapping image // data onto lcd bytes. By varying the y position in every draw, the bitmap // data mapping onto lcd byte y-lines will vary with every bitmap draw. Also, // the foreground and background draw color is constantly swapped. button = perfTestInit("glcdBitmap", 1); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Paint bitmaps with varying x and y location, and color x = 2; y = 0; interruptTest = MC_FALSE; perfTestBegin(); for (i = 0; i < PERF_BITMAP_1; i++) { // Do the actual bitmap paint starting on (x,y) glcdColorSet(y & 0x1); glcdBitmap(x, y, 0, 0, 32, 32, ELM_DWORD, DATA_PMEM, (void *)image); #ifdef EMULIN ctrlLcdFlush(); #endif // Determine next (x,y) y++; if (y > 32) { y = 0; x++; if (x == 93) x = 2; } // Do statistics testStats.loopsDone++; testStats.elementsDrawn++; // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } glcdColorSetFg(); // End test and report statistics button = perfTestEnd(interruptTest); } // Test 2: Draw the same bitmap, but now line by line. This tests the bit y // offset in dword data. By varying the y position in every draw, the bitmap // data mapping onto an lcd byte y-line will vary with every bitmap line // draw. Also, the foreground and background draw color is constantly // swapped. button = perfTestInit("glcdBitmap", 2); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Paint bitmaps with varying x and y location, and color y = 0; interruptTest = MC_FALSE; perfTestBegin(); for (i = 0; i < PERF_BITMAP_2; i++) { // Do the actual bitmap paint starting on (x,y) glcdColorSet(y & 0x1); for (j = 0; j < 32; j++) glcdBitmap(15, y + j, 0, j, 32, 1, ELM_DWORD, DATA_PMEM, (void *)image); #ifdef EMULIN ctrlLcdFlush(); #endif // Determine next y y++; if (y > 32) y = 0; // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 32; // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } glcdColorSetFg(); // End test and report statistics button = perfTestEnd(interruptTest); } return MC_FALSE; } // // Function: perfTestCircle2 // // Performance test of glcdCircle2() // static u08 perfTestCircle2(void) { u08 button; u08 interruptTest; int i,j; int counter = 0; u08 x,y; // Give test suite welcome screen button = perfSuiteWelcome("glcdCircle2"); if (button == 'q') return MC_TRUE; else if (button != BTN_PLUS) return MC_FALSE; // Test 1: Non-overlapping circles, each with different draw types. button = perfTestInit("glcdCircle2", 1); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Paint circles with various radius values and paint options interruptTest = MC_FALSE; perfTestBegin(); for (i = 0; i < PERF_CIRCLE2_1; i++) { // Do the actual paint for (j = 0; j < 32; j++) { glcdCircle2(64, 32, j, counter % 3); #ifdef EMULIN ctrlLcdFlush(); #endif counter++; } // Undo paint counter = counter - 32; glcdColorSetBg(); for (j = 0; j < 32; j++) { glcdCircle2(64, 32, j, counter % 3); #ifdef EMULIN ctrlLcdFlush(); #endif counter++; } glcdColorSetFg(); // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + j * 2; // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } // End test and report statistics button = perfTestEnd(interruptTest); } // Test 2: Non-overlapping small circles, with remove redraw in phase 2. // The circles are identical to the ones drawn in puzzle.c, allowing a good // real-life measurement of draw optimizations. button = perfTestInit("glcdCircle2", 2); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Paint full circles with same radius values at different locations interruptTest = MC_FALSE; perfTestBegin(); for (i = 0; i < PERF_CIRCLE2_2; i++) { for (x = 9; x < 120; x = x + 12) { // Paint small circles for (y = 8; y < 58; y = y + 12) glcdCircle2(x, y, 5, 0); #ifdef EMULIN ctrlLcdFlush(); #endif } glcdColorSetBg(); for (x = 9; x < 120; x = x + 12) { // Clear small circles for (y = 8; y < 58; y = y + 12) glcdCircle2(x, y, 5, 0); #ifdef EMULIN ctrlLcdFlush(); #endif } glcdColorSetFg(); // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 10 * 5 * 2; // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } // End test and report statistics button = perfTestEnd(interruptTest); } return MC_FALSE; } // // Function: perfTestDot // // Performance test of glcdDot() // static u08 perfTestDot(void) { u08 button; u08 interruptTest; int i; u08 j,x,y; // Give test suite welcome screen button = perfSuiteWelcome("glcdDot"); if (button == 'q') return MC_TRUE; else if (button != BTN_PLUS) return MC_FALSE; // Test 1: Paint dots where each dot inverts the current color. // Will have a 100% lcd byte efficiency. button = perfTestInit("glcdDot", 1); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Fill screen with dots with a 100% replace rate interruptTest = MC_FALSE; perfTestBegin(); for (i = 0; i < PERF_DOT_1; i++) { // Paint the dots for (j = 0; j < 8; j++) { for (x = 0; x < GLCD_XPIXELS; x++) { for (y = j; y < GLCD_YPIXELS; y = y + 8) glcdDot(x, y); #ifdef EMULIN ctrlLcdFlush(); #endif } } // Clear the dots glcdColorSetBg(); for (j = 0; j < 8; j++) { for (x = 0; x < GLCD_XPIXELS; x++) { for (y = j; y < GLCD_YPIXELS; y = y + 8) glcdDot(x, y); #ifdef EMULIN ctrlLcdFlush(); #endif } } glcdColorSetFg(); // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 2 * GLCD_XPIXELS * GLCD_YPIXELS; // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } // End test and report statistics button = perfTestEnd(interruptTest); } // Test 2: Paint dots where, on average, each dot is inverted once in every // two update cycles. button = perfTestInit("glcdDot", 2); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Fill screen with dots with a 50% replace rate interruptTest = MC_FALSE; perfTestBegin(); for (i = 0; i < PERF_DOT_2; i++) { glcdColorSet((i + 1) & 0x1); // Paint the dots for (j = 0; j < 8; j++) { for (x = 0; x < GLCD_XPIXELS; x++) { for (y = j; y < GLCD_YPIXELS; y = y + 8) glcdDot(x, y); #ifdef EMULIN ctrlLcdFlush(); #endif } } // Repaint the dots for (j = 0; j < 8; j++) { for (x = 0; x < GLCD_XPIXELS; x++) { for (y = j; y < GLCD_YPIXELS; y = y + 8) glcdDot(x, y); #ifdef EMULIN ctrlLcdFlush(); #endif } } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 2 * GLCD_XPIXELS * GLCD_YPIXELS; // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } glcdColorSetFg(); // End test and report statistics button = perfTestEnd(interruptTest); } return MC_FALSE; } // // Function: perfTestLine // // Performance test of glcdLine() // static u08 perfTestLine(void) { u08 button; u08 interruptTest; u08 xA, yA, xB, yB; int i, j; // Give test suite welcome screen button = perfSuiteWelcome("glcdLine"); if (button == 'q') return MC_TRUE; else if (button != BTN_PLUS) return MC_FALSE; // Test 1: Draw analog clock updates. This gives a real-life measurement of // draw optimizations. button = perfTestInit("glcdLine", 1); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); perfTestTimeInit(); analogHmsInit(DRAW_INIT_FULL); mcUpdAlarmSwitch = MC_TRUE; mcAlarmSwitch = MC_TRUE; // Draw lines using the analog clock layout interruptTest = MC_FALSE; perfTestBegin(); do { // Paint all generated seconds using lines in analog clock analogCycle(); #ifdef EMULIN ctrlLcdFlush(); #endif // Do statistics testStats.elementsDrawn = testStats.elementsDrawn + 3; // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } mcClockInit = MC_FALSE; mcUpdAlarmSwitch = MC_FALSE; // Do statistics testStats.loopsDone++; } while (perfTestTimeNext() == MC_FALSE); // End test and report statistics button = perfTestEnd(interruptTest); } // Test 2: Lines of varying length and draw angle. button = perfTestInit("glcdLine", 2); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Paint lines of varying length and draw angle interruptTest = MC_FALSE; perfTestBegin(); for (i = 0; i < PERF_LINE_2; i++) { for (j = 0; j < 30 * 29; j = j + 1) { // Get begin and end points of line xA = (u08)(sin(2 * M_PI / 30 * (j % 30)) * 30 + 64); yA = (u08)(-cos(2 * M_PI / 30 * (j % 30)) * 30 + 32); xB = (u08)(sin(2 * M_PI / 29 * (j % 29)) * 30 + 64); yB = (u08)(-cos(2 * M_PI / 29 * (j % 29)) * 30 + 32); // Draw and remove the line glcdLine(xA, yA, xB, yB); #ifdef EMULIN ctrlLcdFlush(); #endif glcdColorSetBg(); glcdLine(xA, yA, xB, yB); glcdColorSetFg(); #ifdef EMULIN ctrlLcdFlush(); #endif } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + j * 2; // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } // End test and report statistics button = perfTestEnd(interruptTest); } return MC_FALSE; } // // Function: perfTestFillCircle2 // // Performance test of glcdFillCircle2() // static u08 perfTestFillCircle2(void) { u08 button; u08 interruptTest; u08 pattern; u08 color; u08 x, y; int i,j; int counter = 0; // Give test suite welcome screen button = perfSuiteWelcome("glcdFillCircle2"); if (button == 'q') return MC_TRUE; else if (button != BTN_PLUS) return MC_FALSE; // Test 1: Overlapping filled circles, each with different fill types. button = perfTestInit("glcdFillCircle2", 1); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Paint circles with various radius values and paint options interruptTest = MC_FALSE; perfTestBegin(); for (i = 0; i < PERF_FILLCIRCLE2_1; i++) { // Do the actual paint for (j = 0; j < 32; j++) { // Filltype inverse is not supported so skip that one if (counter % 6 == 4) counter++; glcdColorSet((j + counter) % 2); glcdFillCircle2(64, 32, j, counter % 6); #ifdef EMULIN ctrlLcdFlush(); #endif counter++; } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + j; // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } glcdColorSetFg(); // End test and report statistics button = perfTestEnd(interruptTest); } // Test 2: Non-overlapping small filled circles. // The circles are identical to the ones drawn in puzzle.c, allowing a good // real-life measurement of draw optimizations. button = perfTestInit("glcdFillCircle2", 2); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Paint filled circles with same radius values at different locations interruptTest = MC_FALSE; pattern = 0; color = mcFgColor; glcdColorSet(color); perfTestBegin(); for (i = 0; i < PERF_FILLCIRCLE2_2; i++) { for (x = 9; x < 120; x = x + 12) { // Paint small circles for (y = 8; y < 58; y = y + 12) glcdFillCircle2(x, y, 5, pattern); #ifdef EMULIN ctrlLcdFlush(); #endif } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 10 * 5; // Set draw parameters for next iteration if (pattern == 3) { // Skip pattern inverse and pattern clear and restart. However, at // restarting swap draw color. pattern = 0; if (color == mcFgColor) color = mcBgColor; else color = mcFgColor; glcdColorSet(color); } else { pattern++; } // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } glcdColorSetFg(); // End test and report statistics button = perfTestEnd(interruptTest); } return MC_FALSE; } // // Function: perfTestFillRectangle2 // // Performance test of glcdFillRectangle2() // static u08 perfTestFillRectangle2(void) { u08 button; u08 interruptTest; int i,x,y; u08 dx,dy; // Give test suite welcome screen button = perfSuiteWelcome("glcdFillRectangle2"); if (button == 'q') return MC_TRUE; else if (button != BTN_PLUS) return MC_FALSE; // Test 1: Replacing filled rectangles of varying small size, each with // different fill types. // It is the 'c' implementation of the rectangle5.txt test script with a // twist on paint color that varies per test cycle. button = perfTestInit("glcdFillRectangle2", 1); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); glcdRectangle(3, 6, 122, 57); // Paint rectangles of varying size and fill options interruptTest = MC_FALSE; perfTestBegin(); for (i = 0; i < PERF_FILLRECTANGLE2_1; i++) { glcdColorSet(i % 2); dx = 1; // Vary on x axis for (x = 0; x < 14; x++) { dy = 1; // Vary on y axis for (y = 0; y < 9; y++) { glcdFillRectangle2(x + dx + 4, y + dy + 7, x + 1, y + 1, (x + y) % 3, (x + y + i) % 6); dy = y + dy + 1; #ifdef EMULIN ctrlLcdFlush(); #endif } dx = x + dx + 1; } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + x * y; // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } glcdColorSetFg(); // End test and report statistics button = perfTestEnd(interruptTest); } // Test 2: Painting large filled rectangles where a first paints a subset // area of a second one. button = perfTestInit("glcdFillRectangle2", 2); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Paint overlapping filled rectangles of varying fill options interruptTest = MC_FALSE; perfTestBegin(); x = 0; y = 0; for (i = 0; i < PERF_FILLRECTANGLE2_2; i++) { glcdColorSet(((i / 5) + 1) & 0x1); // Swap fill values 3 and 5 and ignore 4 if (x % 6 == 3) { y = 5; } else if (x % 6 == 4) { x++; y = 3; } else { y = x % 6; } glcdFillRectangle2(4, 4, 50, 35, ALIGN_AUTO, y); glcdFillRectangle2(27, 17, 50, 45, ALIGN_AUTO, y); #ifdef EMULIN ctrlLcdFlush(); #endif x++; // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 2; // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } glcdColorSetFg(); // End test and report statistics button = perfTestEnd(interruptTest); } // Test 3: Painting large filled overlapping rectangles. button = perfTestInit("glcdFillRectangle2", 3); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Paint overlapping filled rectangles of varying fill options interruptTest = MC_FALSE; perfTestBegin(); x = 0; y = 0; for (i = 0; i < PERF_FILLRECTANGLE2_3; i++) { glcdColorSet(((i / 5) + 1) & 0x1); // Swap fill values 3 and 5 and ignore 4 if (x % 6 == 3) { y = 5; } else if (x % 6 == 4) { x++; y = 3; } else { y = x % 6; } glcdFillRectangle2(1, 1, 126, 60, i % 3, y); #ifdef EMULIN ctrlLcdFlush(); #endif x++; // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 1; // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } glcdColorSetFg(); // End test and report statistics button = perfTestEnd(interruptTest); } // Test 4: Painting large filled overlapping rectangles. // Only use HALF/THIRD fill types to test specific draw logic. button = perfTestInit("glcdFillRectangle2", 4); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Paint overlapping filled rectangles of varying fill options interruptTest = MC_FALSE; perfTestBegin(); x = 0; y = 0; for (i = 0; i < PERF_FILLRECTANGLE2_4; i++) { glcdColorSet(i & 0x1); glcdFillRectangle2(1, 1, 126, 60, (i * 5) % 3, i % 3 + 1); #ifdef EMULIN ctrlLcdFlush(); #endif // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 1; // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } glcdColorSetFg(); // End test and report statistics button = perfTestEnd(interruptTest); } return MC_FALSE; } // // Function: perfTestPutStr3 // // Performance test of glcdPutStr3() // static u08 perfTestPutStr3(void) { u08 button; u08 interruptTest; int i; u08 y; // Give test suite welcome screen button = perfSuiteWelcome("glcdPutStr3"); if (button == 'q') return MC_TRUE; else if (button != BTN_PLUS) return MC_FALSE; // Test 1: Draw text lines crossing a y-pixel byte. This is the most common // use for this function. Use the 5x7m font. button = perfTestInit("glcdPutStr3", 1); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Fill screen text strings crossing y-pixel bytes interruptTest = MC_FALSE; perfTextInit(21); perfTestBegin(); for (i = 0; i < PERF_PUTSTR3_1; i++) { // Paint strings for (y = 3; y < GLCD_YPIXELS - 8; y = y + 8) { glcdPutStr3(1, y, FONT_5X7M, textLine, 1, 1); #ifdef EMULIN ctrlLcdFlush(); #endif } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 7; // Toggle text string perfTextToggle(); // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } // End test and report statistics button = perfTestEnd(interruptTest); } // Test 2: Draw text lines with font scaling, causing y-pixel byte crossings // and full lcd bytes to be written. Use the 5x7m font. button = perfTestInit("glcdPutStr3", 2); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Fill screen text strings crossing y-pixel bytes interruptTest = MC_FALSE; perfTextInit(7); perfTestBegin(); for (i = 0; i < PERF_PUTSTR3_2; i++) { // Paint strings for (y = 0; y < GLCD_YPIXELS - 21; y = y + 21) { glcdPutStr3(2, y, FONT_5X7M, textLine, 3, 3); #ifdef EMULIN ctrlLcdFlush(); #endif } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 3; // Toggle text string perfTextToggle(); // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } // End test and report statistics button = perfTestEnd(interruptTest); } // Test 3: Draw text lines crossing a y-pixel byte. Use the 5x5p font. button = perfTestInit("glcdPutStr3", 3); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Fill screen text strings crossing y-pixel bytes interruptTest = MC_FALSE; perfTextInit(31); perfTestBegin(); for (i = 0; i < PERF_PUTSTR3_3; i++) { // Paint strings for (y = 1; y < GLCD_YPIXELS - 6; y = y + 6) { glcdPutStr3(2, y, FONT_5X5P, textLine, 1, 1); #ifdef EMULIN ctrlLcdFlush(); #endif } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 10; // Toggle text string perfTextToggle(); // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } // End test and report statistics button = perfTestEnd(interruptTest); } // Test 4: Draw text lines with font scaling, causing y-pixel byte crossings // and full lcd bytes to be written. Use the 5x5p font. button = perfTestInit("glcdPutStr3", 4); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Fill screen text strings crossing y-pixel bytes interruptTest = MC_FALSE; perfTextInit(10); perfTestBegin(); for (i = 0; i < PERF_PUTSTR3_4; i++) { // Paint strings for (y = 1; y < GLCD_YPIXELS - 15; y = y + 15) { glcdPutStr3(4, y, FONT_5X5P, textLine, 3, 3); #ifdef EMULIN ctrlLcdFlush(); #endif } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 4; // Toggle text string perfTextToggle(); // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } // End test and report statistics button = perfTestEnd(interruptTest); } // Test 5: Draw text lines fitting in a single y-pixel byte. // Use the 5x7m font. button = perfTestInit("glcdPutStr3", 5); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Fill screen text strings that fit in a y-pixel byte interruptTest = MC_FALSE; perfTextInit(21); perfTestBegin(); for (i = 0; i < PERF_PUTSTR3_5; i++) { // Paint strings for (y = 0; y <= GLCD_YPIXELS - 8; y = y + 8) { glcdPutStr3(1, y, FONT_5X7M, textLine, 1, 1); #ifdef EMULIN ctrlLcdFlush(); #endif } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 7; // Toggle text string perfTextToggle(); // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } // End test and report statistics button = perfTestEnd(interruptTest); } return MC_FALSE; } // // Function: perfTestPutStr3v // // Performance test of glcdPutStr3v() // static u08 perfTestPutStr3v(void) { u08 button; u08 interruptTest; int i; u08 x; // Give test suite welcome screen button = perfSuiteWelcome("glcdPutStr3v"); if (button == 'q') return MC_TRUE; else if (button != BTN_PLUS) return MC_FALSE; // Test 1: Draw text lines bottom-up without font scaling. // This is the most common use for this function. Use font 5x5p. button = perfTestInit("glcdPutStr3v", 1); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Fill screen text strings crossing y-pixel bytes interruptTest = MC_FALSE; perfTextInit(15); perfTestBegin(); for (i = 0; i < PERF_PUTSTR3V_1; i++) { // Paint strings for (x = 1; x < GLCD_XPIXELS - 6; x = x + 6) { glcdPutStr3v(x, 61, FONT_5X5P, ORI_VERTICAL_BU, textLine, 1, 1); #ifdef EMULIN ctrlLcdFlush(); #endif } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 21; // Toggle text string perfTextToggle(); // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } // End test and report statistics button = perfTestEnd(interruptTest); } // Test 2: Draw text lines bottom-up with font scaling. // Use font 5x7m. button = perfTestInit("glcdPutStr3v", 2); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Fill screen text strings crossing y-pixel bytes interruptTest = MC_FALSE; perfTextInit(5); perfTestBegin(); for (i = 0; i < PERF_PUTSTR3V_2; i++) { // Paint strings for (x = 1; x < GLCD_XPIXELS - 21; x = x + 21) { glcdPutStr3v(x, 60, FONT_5X7M, ORI_VERTICAL_BU, textLine, 3, 2); #ifdef EMULIN ctrlLcdFlush(); #endif } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 6; // Toggle text string perfTextToggle(); // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } // End test and report statistics button = perfTestEnd(interruptTest); } // Test 3: Draw text lines top-down without font scaling. // This is the most common use for this function. Use font 5x7m. button = perfTestInit("glcdPutStr3v", 3); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Fill screen text strings crossing y-pixel bytes interruptTest = MC_FALSE; perfTextInit(10); perfTestBegin(); for (i = 0; i < PERF_PUTSTR3V_3; i++) { // Paint strings for (x = 7; x < GLCD_XPIXELS; x = x + 9) { glcdPutStr3v(x, 2, FONT_5X7M, ORI_VERTICAL_TD, textLine, 1, 1); #ifdef EMULIN ctrlLcdFlush(); #endif } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 14; // Toggle text string perfTextToggle(); // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } // End test and report statistics button = perfTestEnd(interruptTest); } // Test 4: Draw text lines top-down with font scaling. // Use font 5x5p. button = perfTestInit("glcdPutStr3v", 4); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Fill screen with text strings crossing y-pixel bytes interruptTest = MC_FALSE; perfTextInit(7); perfTestBegin(); for (i = 0; i < PERF_PUTSTR3V_4; i++) { // Paint strings for (x = 17; x < GLCD_XPIXELS; x = x + 18) { glcdPutStr3v(x, 4, FONT_5X5P, ORI_VERTICAL_TD, textLine, 3, 2); #ifdef EMULIN ctrlLcdFlush(); #endif } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 7; // Toggle text string perfTextToggle(); // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } // End test and report statistics button = perfTestEnd(interruptTest); } return MC_FALSE; } // // Function: perfTestPutStr // // Performance test of glcdPutStr() // static u08 perfTestPutStr(void) { u08 button; u08 interruptTest; int i; u08 y; // Give test suite welcome screen button = perfSuiteWelcome("glcdPutStr"); if (button == 'q') return MC_TRUE; else if (button != BTN_PLUS) return MC_FALSE; // Test 1: Draw text lines, being the most common use for this function. button = perfTestInit("glcdPutStr", 1); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Fill screen text strings interruptTest = MC_FALSE; perfTextInit(21); perfTestBegin(); for (i = 0; i < PERF_PUTSTR_1; i++) { // Paint strings for (y = 0; y < GLCD_CONTROLLER_YPAGES; y++) { glcdSetAddress(1, y); glcdPutStr(textLine); #ifdef EMULIN ctrlLcdFlush(); #endif } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 8; // Toggle text string perfTextToggle(); // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } // End test and report statistics button = perfTestEnd(interruptTest); } return MC_FALSE; } // // Function: perfTestRectangle // // Performance test of glcdRectangle() // static u08 perfTestRectangle(void) { u08 button; u08 interruptTest; int i,x,y; u08 dx,dy; // Give test suite welcome screen button = perfSuiteWelcome("glcdRectangle"); if (button == 'q') return MC_TRUE; else if (button != BTN_PLUS) return MC_FALSE; // Test 1: Painting small rectangles of varying size. // It is the 'c' implementation of the rectangle1.txt test script. button = perfTestInit("glcdRectangle", 1); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); glcdRectangle(3, 6, 122, 57); // Paint rectangles of varying size and fill options interruptTest = MC_FALSE; perfTestBegin(); for (i = 0; i < PERF_RECTANGLE2_1; i++) { glcdColorSet(i % 2); dx = 1; // Vary on x axis for (x = 0; x < 14; x++) { dy = 1; // Vary on y axis for (y = 0; y < 9; y++) { glcdRectangle(x + dx + 4, y + dy + 7, x + 1, y + 1); dy = y + dy + 1; #ifdef EMULIN ctrlLcdFlush(); #endif } dx = x + dx + 1; } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + x * y; // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } glcdColorSetFg(); // End test and report statistics button = perfTestEnd(interruptTest); } // Test 2: Painting larger rectangles button = perfTestInit("glcdRectangle", 2); while (button == BTN_PLUS) { // Prepare display for test glcdClearScreen(); // Paint rectangles of varying fill options interruptTest = MC_FALSE; perfTestBegin(); x = 0; y = 0; for (i = 0; i < PERF_RECTANGLE2_2; i++) { glcdColorSet(i & 0x1); for (y = 1; y < 64; y = y + 2) { glcdRectangle(64 - y, 32 - y / 2, y * 2, y); #ifdef EMULIN ctrlLcdFlush(); #endif } // Do statistics testStats.loopsDone++; testStats.elementsDrawn = testStats.elementsDrawn + 32; // Check for keypress interrupt button = perfButtonGet(); if (button != 0) { interruptTest = MC_TRUE; break; } } glcdColorSetFg(); // End test and report statistics button = perfTestEnd(interruptTest); } return MC_FALSE; } // // Function: perfButtonGet // // Get button when pressed // static u08 perfButtonGet(void) { #ifndef EMULIN u08 button; // Get and clear (if any) button button = btnPressed; btnPressed = BTN_NONE; return button; #else // Accept any keypress when pressed return (u08)kbKeypressScan(MC_FALSE); #endif } // // Function: perfButtonWait // // Wait for any button to be pressed // static u08 perfButtonWait(u08 type) { u08 button = 0; // Give wait message glcdFillRectangle2(0, 58, 127, 5, ALIGN_TOP, FILL_BLANK); if (type == PERF_WAIT_CONTINUE) glcdPutStr2(1, 58, FONT_5X5P, "press button to continue"); else if (type == PERF_WAIT_ENTER_SKIP) glcdPutStr2(1, 58, FONT_5X5P, "+ = enter, set/menu = skip"); else if (type == PERF_WAIT_START_SKIP) glcdPutStr2(1, 58, FONT_5X5P, "+ = start, set/menu = skip"); else // type == PERF_WAIT_RESTART_END glcdPutStr2(1, 58, FONT_5X5P, "+ = restart, set/menu = end"); #ifdef EMULIN ctrlLcdFlush(); #endif // Clear any button pressed and wait for button btnPressed = BTN_NONE; #ifndef EMULIN // Get any button from Monochron while (btnPressed == BTN_NONE); button = btnPressed; btnPressed = BTN_NONE; #else // Get +,s,m,q, others default to MENU button char ch = waitKeypress(MC_FALSE); if (ch >= 'A' && ch <= 'Z') ch = ch - 'A' + 'a'; if (ch == '+') button = BTN_PLUS; else if (ch == 's') button = BTN_SET; else if (ch == 'm') button = BTN_MENU; else if (ch == 'q') button = 'q'; else button = BTN_MENU; #endif return button; } // // Function: perfLongValToStr // // Make a string out of a positive long integer value // static void perfLongValToStr(long value, char valString[]) { u08 index = 0; u08 i; char temp; long valTemp = value; // Create string in reverse order while (valTemp > 0 || index == 0) { valString[index] = valTemp % 10 + '0'; valTemp = valTemp / 10; index++; } valString[index] = '\0'; // Reverse string for (i = 0; i < (index + 1) / 2; i++) { temp = valString[i]; valString[i] = valString[index - i - 1]; valString[index - i - 1] = temp; } } // // Function: perfSuiteWelcome // // Provide welcome of test suite // static u08 perfSuiteWelcome(char *label) { u08 length; // Give test suite welcome screen glcdClearScreen(); length = glcdPutStr2(1, 1, FONT_5X5P, "Test suite: "); glcdPutStr2(length + 1, 1, FONT_5X5P, label); // Wait for button press: continue or skip all tests // + = continue // s/m = skip // q = quit (emulator only) return perfButtonWait(PERF_WAIT_ENTER_SKIP); } // // Function: perfTestBegin // // Clear previous test statistics and mark test start time // static void perfTestBegin(void) { #ifdef EMULIN // In case we're using glut, give the lcd device some time to catch up _delay_ms(250); // Reset glcd/controller statistics ctrlStatsReset(CTRL_STATS_GLCD | CTRL_STATS_CTRL); #endif // Clear previous test statistics testStats.endSec = 0; testStats.endMin = 0; testStats.endHour = 0; testStats.loopsDone = 0; testStats.elementsDrawn = 0; // Resync time after which we'll wait for the next second to occur // for a more consistent duration measurement rtcMchronTimeInit(); rtcTimeEvent = MC_FALSE; #ifndef EMULIN while (rtcTimeEvent == MC_FALSE); #else while (rtcTimeEvent == MC_FALSE) { _delay_ms(25); monoTimer(); } #endif // Mark test start time testStats.startSec = rtcDateTimeNext.timeSec; testStats.startMin = rtcDateTimeNext.timeMin; testStats.startHour = rtcDateTimeNext.timeHour; } // // Function: perfTestEnd // // Mark test end time and report final test statistics // static u08 perfTestEnd(u08 interruptTest) { char number[20]; u08 length; u16 duration; // Clear any button press btnPressed = BTN_NONE; // Mark test end time rtcMchronTimeInit(); testStats.endSec = rtcDateTimeNext.timeSec; testStats.endMin = rtcDateTimeNext.timeMin; testStats.endHour = rtcDateTimeNext.timeHour; #ifdef EMULIN // In case we're using glut, give the lcd device some time to catch up _delay_ms(250); // Give test end result and glcd/controller statistics printf("test : %s - %02d\n", testStats.text, testStats.testId); if (interruptTest == MC_FALSE) printf("status : %s\n", "completed"); else printf("status : %s\n", "aborted"); ctrlStatsPrint(CTRL_STATS_GLCD | CTRL_STATS_CTRL); #endif // Give test statistics screen glcdClearScreen(); glcdColorSetFg(); glcdPutStr2(1, 1, FONT_5X5P, "test:"); length = glcdPutStr2(29, 1, FONT_5X5P, testStats.text); length = length + glcdPutStr2(length + 29, 1, FONT_5X5P, " - "); animValToStr(testStats.testId, number); glcdPutStr2(length + 29, 1, FONT_5X5P, number); glcdPutStr2(1, 7, FONT_5X5P, "status:"); if (interruptTest == MC_FALSE) glcdPutStr2(29, 7, FONT_5X5P, "completed"); else glcdPutStr2(29, 7, FONT_5X5P, "aborted"); // Test duration if (testStats.endMin < testStats.startMin) testStats.endMin = testStats.endMin + 60; duration = (u16)(testStats.endMin) * 60 + testStats.endSec - ((u16)(testStats.startMin) * 60 + testStats.startSec); glcdPutStr2(1, 13, FONT_5X5P, "time:"); animValToStr(duration / 60, number); glcdPutStr2(29, 13, FONT_5X5P, number); glcdPutStr2(37, 13, FONT_5X5P, ":"); animValToStr(duration % 60, number); glcdPutStr2(39, 13, FONT_5X5P, number); // Cycles glcdPutStr2(1, 19, FONT_5X5P, "cycles:"); perfLongValToStr(testStats.loopsDone, number); glcdPutStr2(29, 19, FONT_5X5P, number); // Elements drawn glcdPutStr2(1, 25, FONT_5X5P, "draws:"); perfLongValToStr(testStats.elementsDrawn, number); glcdPutStr2(29, 25, FONT_5X5P, number); // Wait for button press return perfButtonWait(PERF_WAIT_RESTART_END); } // // Function: perfTestInit // // Init test id and provide test prompt // static u08 perfTestInit(char *label, u08 testId) { u08 length; char strTestId[3]; // Init test id testStats.text = label; testStats.testId = testId; // Provide prompt to run or skip test glcdClearScreen(); length = glcdPutStr2(1, 1, FONT_5X5P, label); length = length + glcdPutStr2(length + 1, 1, FONT_5X5P, " - "); animValToStr(testId, strTestId); glcdPutStr2(length + 1, 1, FONT_5X5P, strTestId); return perfButtonWait(PERF_WAIT_START_SKIP); } // // Function: perfTestTimeInit // // Initialize functional Monochron time. // static void perfTestTimeInit(void) { mcClockOldTS = mcClockNewTS = mcClockOldTM = mcClockNewTM = 0; mcClockOldTH = mcClockNewTH = 0; mcClockOldDD = mcClockNewDD = mcClockOldDM = mcClockNewDM = 1; mcClockOldDY = mcClockNewDY = 15; secCount = PERF_LINE_1; mcAlarming = MC_FALSE; } // // Function: perfTestTimeNext // // Get next timestamp up to 1 hour after start // static u08 perfTestTimeNext(void) { mcClockOldTS = mcClockNewTS; mcClockOldTM = mcClockNewTM; mcClockOldTH = mcClockNewTH; mcClockOldDD = mcClockNewDD; mcClockOldDM = mcClockNewDM; mcClockOldDY = mcClockNewDY; secCount--; if (secCount == 0) return MC_TRUE; if (mcClockNewTS != 59) { // Next second mcClockNewTS++; } else if (mcClockNewTM != 59) { // Next minute mcClockNewTS = 0; mcClockNewTM++; } else { // Next hour mcClockNewTS = 0; mcClockNewTM = 0; mcClockNewTH++; } return MC_FALSE; } // // Function: perfTextInit // // Create text strings with 'A' and 'Y' characters. // These characters are chosen as in the 5x5p font they both have width 3, // which is more or less average. // Also set the first text string to be used in a perf test. // static void perfTextInit(u08 length) { u08 i; // Generate 'A' and 'Y' strings of requested length for (i = 0; i < length; i++) { textLineA[i] = 'A'; textLineY[i] = 'Y'; } textLineA[i] = '\0'; textLineY[i] = '\0'; // Initialise the first string to be used in a test textLine = textLineA; } // // Function: perfTextToggle // // Toggle the text string to be used in a perf test. // static void perfTextToggle(void) { if (textLine == textLineA) textLine = textLineY; else textLine = textLineA; }
stefpetrov/Software-University
Data Types and Variables/08.Calculator.js
function solve(num1, operator, num2) { if (operator === "+") { console.log((num1 + num2).toFixed(2)); } else if (operator === "-") { console.log((num1 - num2).toFixed(2)); } else if (operator === "*") { console.log((num1 * num2).toFixed(2)); } else if (operator === "/") { console.log((num1 / num2).toFixed(2)); } } solve(5, "+", 10);
jnhu76/mxtasking
src/db/index/blinktree/node_iterator.h
#pragma once #include "node.h" #include <mx/resource/resource.h> namespace db::index::blinktree { /** * Iterator for iterating over nodes of a tree. */ template <typename K, typename V> class NodeIterator { public: NodeIterator() = default; explicit NodeIterator(Node<K, V> *root) : _current_node(root), _first_node_in_level(root) {} ~NodeIterator() = default; Node<K, V> *&operator*() { return _current_node; } NodeIterator<K, V> &operator++() { if (_current_node->right_sibling()) { _current_node = _current_node->right_sibling().template get<Node<K, V>>(); } else if (_current_node->is_inner()) { _first_node_in_level = _first_node_in_level->separator(0).template get<Node<K, V>>(); _current_node = _first_node_in_level; } else { _current_node = nullptr; } return *this; } bool operator!=(const NodeIterator<K, V> &other) const { return _current_node != other._current_node; } private: Node<K, V> *_current_node = nullptr; Node<K, V> *_first_node_in_level = nullptr; }; } // namespace db::index::blinktree
javalibrary/netifi-httpgateway
netifi-httpgateway/src/main/java/com/netifi/httpgateway/rsocket/BrokerClientRSocketSupplier.java
/** * Copyright 2018 Netifi Inc. * * <p>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 * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.netifi.httpgateway.rsocket; import com.netifi.broker.BrokerClient; import com.netifi.common.tags.Tag; import com.netifi.common.tags.Tags; import com.netifi.httpgateway.util.HttpUtil; import io.netty.handler.codec.http.HttpHeaders; import io.rsocket.RSocket; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class BrokerClientRSocketSupplier implements RSocketSupplier { private final BrokerClient brokerClient; private final ConcurrentHashMap<String, RSocket> rsockets; @Autowired public BrokerClientRSocketSupplier(BrokerClient brokerClient) { this.brokerClient = brokerClient; this.rsockets = new ConcurrentHashMap<>(); } @Override public RSocket apply(String rSocketKey, HttpHeaders headers) { String overrideGroup = headers.get(HttpUtil.OVERRIDE_GROUP); String overrideDestination = headers.get(HttpUtil.OVERRIDE_DESTINATION); List<String> allAsString = headers.getAllAsString(HttpUtil.OVERRIDE_TAG); Tags tags = toTags(allAsString); if (overrideGroup != null && !overrideGroup.isEmpty()) { if (overrideDestination != null && !overrideDestination.isEmpty()) { return rsockets.computeIfAbsent( overrideGroup, g -> brokerClient.destination(overrideDestination, overrideGroup)); } return rsockets.computeIfAbsent( overrideGroup, s -> brokerClient.groupServiceSocket(overrideGroup, tags)); } return rsockets.computeIfAbsent( rSocketKey, s -> brokerClient.groupServiceSocket(rSocketKey, tags)); } private Tags toTags(List<String> allAsString) { if (allAsString == null || allAsString.isEmpty()) { return Tags.empty(); } else { List<Tag> collect = allAsString .stream() .map( s -> { String[] split = s.split(":"); return Tag.of(split[0], split[1]); }) .collect(Collectors.toList()); return Tags.of(collect); } } }
Whitemane/fluid-engine-dev
src/python/size.cpp
// Copyright (c) 2018 <NAME> // // I am making my contributions/submissions to this project solely in my // personal capacity and am not conveying any rights to any intellectual // property of any third parties. #include "size.h" #include "pybind11_utils.h" #include <jet/size2.h> #include <jet/size3.h> namespace py = pybind11; using namespace jet; void addSize2(pybind11::module& m) { py::class_<Size2>(m, "Size2") // CTOR .def("__init__", [](Size2& instance, size_t x, size_t y) { new (&instance) Size2(x, y); }, R"pbdoc( Constructs Size2 This method constructs 2D size with x and y. )pbdoc", py::arg("x") = 0, py::arg("y") = 0) .def_readwrite("x", &Size2::x) .def_readwrite("y", &Size2::y) .def("__eq__", [](const Size2& instance, py::object obj) { Size2 other = objectToSize2(obj); return instance == other; }); } void addSize3(pybind11::module& m) { py::class_<Size3>(m, "Size3") // CTOR .def("__init__", [](Size3& instance, size_t x, size_t y, size_t z) { new (&instance) Size3(x, y, z); }, R"pbdoc( Constructs Size3 This method constructs 3D size with x, y, and z. )pbdoc", py::arg("x") = 0, py::arg("y") = 0, py::arg("z") = 0) .def_readwrite("x", &Size3::x) .def_readwrite("y", &Size3::y) .def_readwrite("z", &Size3::z) .def("__eq__", [](const Size3& instance, py::object obj) { Size3 other = objectToSize3(obj); return instance == other; }); }
Prodaxis/kie-wb-common
kie-wb-common-screens/kie-wb-common-library/kie-wb-common-library-client/src/test/java/org/kie/workbench/common/screens/library/client/settings/sections/branchmanagement/RoleItemPresenterTest.java
<reponame>Prodaxis/kie-wb-common /* * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.screens.library.client.settings.sections.branchmanagement; import org.guvnor.structure.organizationalunit.config.RolePermissions; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class RoleItemPresenterTest { @Mock private RoleItemPresenter.View view; private RoleItemPresenter presenter; private RolePermissions rolePermissions; private BranchManagementPresenter branchManagementPresenter; @Before public void setup() { presenter = new RoleItemPresenter(view); rolePermissions = new RolePermissions("myRole", true, true, true, true); branchManagementPresenter = mock(BranchManagementPresenter.class); presenter.setup(rolePermissions, branchManagementPresenter); } @Test public void setupTest() { verify(view).init(presenter); assertSame(rolePermissions, presenter.rolePermissions); assertSame(branchManagementPresenter, presenter.parentPresenter); verify(view).setRoleName("myRole"); verify(view).setCanRead(true); verify(view).setCanWrite(true); verify(view).setCanDelete(true); verify(view).setCanDeploy(true); } @Test public void setCanReadTest() { presenter.setCanRead(false); assertFalse(rolePermissions.canRead()); verify(branchManagementPresenter).fireChangeEvent(); } @Test public void setCanWriteTest() { presenter.setCanWrite(false); assertFalse(rolePermissions.canWrite()); verify(branchManagementPresenter).fireChangeEvent(); } @Test public void setCanDeleteTest() { presenter.setCanDelete(false); assertFalse(rolePermissions.canDelete()); verify(branchManagementPresenter).fireChangeEvent(); } @Test public void setCanBuildTest() { presenter.setCanDeploy(false); assertFalse(rolePermissions.canDeploy()); verify(branchManagementPresenter).fireChangeEvent(); } }
GlobalTechnology/gma_android
measurements-app/src/main/java/com/expidevapps/android/measurements/support/v4/content/TrainingLoaderBroadcastReceiver.java
<filename>measurements-app/src/main/java/com/expidevapps/android/measurements/support/v4/content/TrainingLoaderBroadcastReceiver.java<gh_stars>1-10 package com.expidevapps.android.measurements.support.v4.content; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.Loader; import org.ccci.gto.android.common.support.v4.content.LoaderBroadcastReceiver; import java.util.Collections; import java.util.HashSet; import java.util.Set; import static com.expidevapps.android.measurements.Constants.EXTRA_MINISTRY_ID; import static com.expidevapps.android.measurements.Constants.EXTRA_TRAINING_IDS; /** * Created by matthewfrederick on 2/24/15. */ public class TrainingLoaderBroadcastReceiver extends LoaderBroadcastReceiver { @Nullable private final String mMinistryId; @NonNull private final Set<Long> mIds; public TrainingLoaderBroadcastReceiver(@NonNull Loader loader, @NonNull final long... ids) { this(loader, null, ids); } public TrainingLoaderBroadcastReceiver(@NonNull final Loader loader, @Nullable final String ministryId, @NonNull final long... ids) { super(loader); mMinistryId = ministryId; if (ids.length == 0) { mIds = Collections.emptySet(); } else { mIds = new HashSet<>(ids.length); for (final long id : ids) { mIds.add(id); } } } @Override public void onReceive(@NonNull final Context context, @NonNull final Intent intent) { final boolean ministryMatch = mMinistryId == null || mMinistryId.equals(intent.getStringExtra(EXTRA_MINISTRY_ID)); boolean idsMatch = mIds.isEmpty(); if (!idsMatch) { final long[] ids = intent.getLongArrayExtra(EXTRA_TRAINING_IDS); for (final long id : ids) { idsMatch = mIds.contains(ids); if (idsMatch) break; } } if (ministryMatch && idsMatch) super.onReceive(context, intent); } }
Stibbons/sonarr-sub-downloader-docker
cfgtree/tests/test_dictxparth.py
# coding: utf-8 # Standard Libraries from unittest import TestCase # Third Party Libraries from cfgtree.dictxpath import delete_node_by_xpath from cfgtree.dictxpath import get_node_by_xpath from cfgtree.dictxpath import set_node_by_xpath class DictXpathTests(TestCase): def test_get_node_by_path(self): mapping = {'level1': {'level2': {'level3': 42}}} expected = 42 actual = get_node_by_xpath(mapping, 'level1.level2.level3') self.assertEqual(expected, actual) self.assertRaisesRegex( KeyError, (r"Invalid 'level1.unknown' selector: 'unknown' doesn't match anything. " r"Available keys: \['level2'\]"), get_node_by_xpath, mapping, 'level1.unknown') actual = get_node_by_xpath( mapping, 'level1.unknown', default="default value", ignore_errors=True) self.assertEqual(actual, "default value") def test_get_node_by_path_empty_mapping(self): empty_map = {} self.assertRaises(KeyError, get_node_by_xpath, empty_map, 'level1') self.assertRaises(KeyError, get_node_by_xpath, empty_map, 'level1.other') self.assertEqual( get_node_by_xpath(empty_map, 'level1', default="default value", ignore_errors=True), "default value") self.assertEqual( get_node_by_xpath(empty_map, '', default="default value", ignore_errors=True), "default value") def test_get_node_by_path_invalid_first_level(self): mapping = {"level1": {}} self.assertRaises(KeyError, get_node_by_xpath, mapping, 'invalid_level1') self.assertEqual( get_node_by_xpath( mapping, 'invalid_level1', default="default value", ignore_errors=True), "default value") def test_get_node_by_path_mapping_not_dict(self): mapping_no_a_dict = "simple string!" self.assertEqual( get_node_by_xpath(mapping_no_a_dict, '', default="default value", ignore_errors=True), "default value") self.assertRaises( KeyError, get_node_by_xpath, mapping_no_a_dict, 'level1.unknown', ignore_errors=False, ) def test_get_node_by_path_incomplete_mapping(self): mapping = {'level1': {'level2': {}}} self.assertRaises(KeyError, get_node_by_xpath, mapping, 'level1.level2.level3') self.assertRaises(KeyError, get_node_by_xpath, mapping, 'level1.unknown') # test with tailing "." at the end of path self.assertRaises(KeyError, get_node_by_xpath, mapping, 'level1.') self.assertEqual( get_node_by_xpath( mapping, 'level1.level2', default="default value", ignore_errors=True), {}) self.assertEqual( get_node_by_xpath( mapping, 'level1.unknown', default="default value", ignore_errors=True), "default value") # test with tailing "." at the end of path self.assertEqual( get_node_by_xpath(mapping, 'level1.', default="default value", ignore_errors=True), "default value") def test_set_node_by_path(self): mapping = {'level1': {'level2': {'level3': None}}} expected = 42 set_node_by_xpath(mapping, 'level1.level2.level3', expected) actual = get_node_by_xpath(mapping, 'level1.level2.level3') self.assertEqual(expected, actual) set_node_by_xpath(mapping, 'level1.unknown', expected) actual = get_node_by_xpath(mapping, 'level1.unknown') self.assertEqual(expected, actual) self.assertRaises(KeyError, set_node_by_xpath, mapping, 'level1.invalid.level3', '') expected = 'extended' set_node_by_xpath(mapping, 'level1.missing.level3', expected, extend=True) actual = get_node_by_xpath(mapping, 'level1.missing.level3') self.assertEqual(expected, actual) def test_delete_node_by_path(self): mapping = {'level1': {'level2': {'level3': 42}}} expected = 42 actual = delete_node_by_xpath(mapping, 'level1.level2.level3') self.assertEqual(expected, actual) self.assertFalse('level3' in mapping['level1']['level2']) self.assertRaises(KeyError, delete_node_by_xpath, mapping, 'level1.invalid.level3') self.assertIsNone( delete_node_by_xpath(mapping, 'level1.invalid.level3', ignore_errors=True)) def test_get_node_by_path_with_list_selector(self): mapping = {'level1': {'level_2_is_a_list': ['item1', 'item2']}} actual = get_node_by_xpath( mapping, 'level1.level_2_is_a_list[1]', handle_list_selector=True) self.assertEqual('item2', actual) def test_get_node_w_lst_selctr_sub_list(self): mapping = { 'level1': { 'level_2_is_a_list': [ { 'item1': { 'k1': 'v1' } }, { 'item2': { 'k2': 'v2' } }, ] } } actual = get_node_by_xpath( mapping, 'level1.level_2_is_a_list[1].item2.k2', handle_list_selector=True) self.assertEqual('v2', actual) def test_get_w_bad_lst_selctr_n_default_val(self): mapping = {'level1': {'level_2_is_a_list': ['item1', 'item2']}} actual = get_node_by_xpath( mapping, 'level1.level_2_is_a_list[1]', handle_list_selector=True, default="N/A") self.assertEqual('item2', actual) self.assertRaisesRegex( KeyError, (r"Invalid \'level1.level_2_is_a_list\[99\]\' selector: " r"item index \'99\' of \'level_2_is_a_list\' is outside of the list boundaries. " r"Length is: 2"), get_node_by_xpath, mapping, 'level1.level_2_is_a_list[99]', handle_list_selector=True, default="N/A")
ajaycb/webrtc-rooms
janus-api/plugins/datasync/question_data.js
import { userInfo } from "os"; import EventEmitter from "events"; class Question { constructor(qd, id, title, type, options = {}) { this.qd = qd; let reply_to = qd.room.user.id; this.question = { id, title, type, options, reply_to }; this.answers = {}; } ask() { this.qd.room.text_room.send("question", { action: "ask", question: this.question, }); } close(opts = {}) { this.qd.room.text_room.send("question", { action: "close", question_id: this.question.id, opts, }); this.qd.active_question = null; } update_answer(from, answer) { this.answers[from] = answer; console.warn("updated", this.answers); this.qd.emit("update_answer"); } answerStats() { return Object.values(this.answers).reduce((acc, curr) => { acc[curr] = (acc[curr] || 0) + 1; return acc; }, {}); } } class Answer { constructor(qd, question) { this.qd = qd; this.question = question; } answer(answer) { this.qd.room.text_room.send_to("question", this.question.reply_to, { action: "answer", answer, question_id: this.question.id, }); } } class QuestionData extends EventEmitter { constructor(room) { super(); this.room = room; this.room.on("question_data_received", ({ from, payload }) => { if (from !== "" + room.user.id && payload.action) { console.warn( "recd", from, payload, this.active_question && this.active_question.question ); let action = payload.action; //sent to respondents if (action === "ask") { this.active_answer = new Answer(this, payload.question); this.emit("ask", this.active_answer); } if ( action === "close" && this.active_answer && payload.question_id === this.active_answer.question.id ) { this.emit("close", payload.question_id); this.active_answer = null; } //recd an answer from the respondent if ( action === "answer" && this.active_question && this.active_question.question.id === payload.question_id ) { this.active_question.update_answer(from, payload.answer); } } }); } create(id, title, type, options = {}) { this.active_question = new Question(this, id, title, type, options); return this.active_question; } } export default QuestionData;
MukundSonaiya/DemoWith0xMonorepo
packages/sol-cov/lib/src/constants.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // tslint:disable:number-literal-format exports.constants = { NEW_CONTRACT: 'NEW_CONTRACT', PUSH1: 0x60, PUSH2: 0x61, PUSH32: 0x7f, TIMESTAMP: 0x42, }; //# sourceMappingURL=constants.js.map
PimentaPeps/ArcTouch-Code-Challenge
app/src/main/java/com/code/arctouch/arctouchcodechallenge/upcomingmovies/ScrollChildSwipeRefreshLayout.java
<filename>app/src/main/java/com/code/arctouch/arctouchcodechallenge/upcomingmovies/ScrollChildSwipeRefreshLayout.java<gh_stars>0 package com.code.arctouch.arctouchcodechallenge.upcomingmovies; import android.content.Context; import android.support.v4.view.ViewCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.util.AttributeSet; import android.view.View; /** * Extends {@link SwipeRefreshLayout} to support non-direct descendant scrolling views. * <p> * {@link SwipeRefreshLayout} works as expected when a scroll view is a direct child: it triggers * the refresh only when the view is on top. This class adds a way (@link #setScrollUpChild} to * define which view controls this behavior. */ public class ScrollChildSwipeRefreshLayout extends SwipeRefreshLayout { private View mScrollUpChild; public ScrollChildSwipeRefreshLayout(Context context) { super(context); } public ScrollChildSwipeRefreshLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean canChildScrollUp() { if (mScrollUpChild != null) { return ViewCompat.canScrollVertically(mScrollUpChild, -1); } return super.canChildScrollUp(); } public void setScrollUpChild(View view) { mScrollUpChild = view; } }
jgradim/psc-web
src/constants/technologies.js
<gh_stars>1-10 export default [ { "label": "Android" , "value": "Android" } , { "label": "C" , "value": "C" } , { "label": "C#" , "value": "C#" } , { "label": "C++" , "value": "C++" } , { "label": "CSS" , "value": "CSS" } , { "label": "Django" , "value": "Django" } , { "label": "Flask" , "value": "Flask" } , { "label": "Go" , "value": "Go" } , { "label": "HTML" , "value": "HTML" } , { "label": "Java" , "value": "Java" } , { "label": "Javascript" , "value": "Javascript" } , { "label": "JSON" , "value": "JSON" } , { "label": "Lua" , "value": "Lua" } , { "label": "NodeJS" , "value": "NodeJS" } , { "label": ".NET" , "value": ".NET" } , { "label": "Objective-C" , "value": "Objective-C" } , { "label": "Perl" , "value": "Perl" } , { "label": "PHP" , "value": "PHP" } , { "label": "Python" , "value": "Python" } , { "label": "ReactJS" , "value": "ReactJS" } , { "label": "Ruby" , "value": "Ruby" } , { "label": "Ruby on Rails" , "value": "Ruby on Rails" } , { "label": "Rust" , "value": "Rust" } , { "label": "Scala" , "value": "Scala" } , { "label": "SQL" , "value": "SQL" } , { "label": "Swift" , "value": "Swift" } , { "label": "XML" , "value": "XML" } , ];
codekat1/liboqs
src/kem/ntruprime/pqclean_sntrup761_clean/crypto_encode_761xint16.h
<reponame>codekat1/liboqs #ifndef PQCLEAN_SNTRUP761_CLEAN_CRYPTO_ENCODE_761XINT16_H #define PQCLEAN_SNTRUP761_CLEAN_CRYPTO_ENCODE_761XINT16_H #include <stdint.h> #define PQCLEAN_SNTRUP761_CLEAN_crypto_encode_761xint16_STRBYTES 1522 #define PQCLEAN_SNTRUP761_CLEAN_crypto_encode_761xint16_ITEMS 761 #define PQCLEAN_SNTRUP761_CLEAN_crypto_encode_761xint16_ITEMBYTES 2 void PQCLEAN_SNTRUP761_CLEAN_crypto_encode_761xint16(unsigned char *s, const void *v); #endif
npocmaka/Windows-Server-2003
sdktools/mep/src/pick.c
<reponame>npocmaka/Windows-Server-2003<filename>sdktools/mep/src/pick.c /*** pick.c - pick a piece of text and put it into the put buffer * * Copyright <C> 1988, Microsoft Corporation * * Revision History: * 26-Nov-1991 mz Strip off near/far * *************************************************************************/ #include "mep.h" #define DEBFLAG PICK flagType zpick ( CMDDATA argData, ARG * pArg, flagType fMeta ) { buffer pbuf; /* LINEARG illegal */ /* BOXARG illegal */ switch (pArg->argType) { case NOARG: pick (0, pArg->arg.noarg.y, 0, pArg->arg.noarg.y, LINEARG); return TRUE; case TEXTARG: if (pFilePick != pFileHead) { DelFile (pFilePick, TRUE); } strcpy ((char *) pbuf, pArg->arg.textarg.pText); PutLine ((LINE)0, pbuf, pFilePick); kindpick = BOXARG; return TRUE; /* NULLARG is converted into TEXTARG */ case LINEARG: pick (0, pArg->arg.linearg.yStart, 0, pArg->arg.linearg.yEnd, LINEARG); return TRUE; case BOXARG: pick (pArg->arg.boxarg.xLeft, pArg->arg.boxarg.yTop, pArg->arg.boxarg.xRight, pArg->arg.boxarg.yBottom, BOXARG); return TRUE; case STREAMARG: pick (pArg->arg.streamarg.xStart, pArg->arg.streamarg.yStart, pArg->arg.streamarg.xEnd, pArg->arg.streamarg.yEnd, STREAMARG); return TRUE; } return FALSE; argData; fMeta; } void pick ( COL xstart, LINE ystart, COL xend, LINE yend, int kind ) { if (pFilePick != pFileHead) { DelFile (pFilePick, TRUE); } kindpick = kind; switch (kind) { case LINEARG: CopyLine (pFileHead, pFilePick, ystart, yend, (LINE)0); break; case BOXARG: CopyBox (pFileHead, pFilePick, xstart, ystart, xend, yend, (COL)0, (LINE)0); break; case STREAMARG: CopyStream (pFileHead, pFilePick, xstart, ystart, xend, yend, (COL)0, (LINE)0); break; } } flagType put ( CMDDATA argData, ARG *pArg, flagType fMeta ) { flagType fTmp = FALSE; int i; buffer putbuf; pathbuf filebuf; FILEHANDLE fh; PFILE pFileTmp; char *pBuf; switch (pArg->argType) { case BOXARG: case LINEARG: case STREAMARG: delarg (pArg); break; case TEXTARG: strcpy ((char *) buf, pArg->arg.textarg.pText); DelFile (pFilePick, TRUE); if (pArg->arg.textarg.cArg > 1) { pBuf = whiteskip (buf); if (*pBuf == '!') { findpath ("$TMP:z.$", filebuf, TRUE); fTmp = TRUE; sprintf (putbuf, "%s >%s", pBuf+1, filebuf); zspawnp (putbuf, TRUE); pBuf = filebuf; } if (*pBuf != '<') { CanonFilename (pBuf, putbuf); } else { strcpy (putbuf, pBuf); } // // If we find the file in the existing file history, read it in, if not already // in, and just to a copy operation on the desired text. // if ((pFileTmp = FileNameToHandle (putbuf, pBuf)) != NULL) { if (!TESTFLAG (FLAGS (pFileTmp), REAL)) { if (!FileRead(pFileTmp->pName,pFileTmp, FALSE)) { printerror ("Cannot read %s", pFileTmp->pName); return FALSE; } } CopyLine (pFileTmp, pFilePick, (LINE)0, pFileTmp->cLines-1, (LINE)0); } else { if ((fh = MepFOpen(putbuf, ACCESSMODE_READ, SHAREMODE_RW, FALSE)) == NULL) { printerror ("%s does not exist", pBuf); return FALSE; } readlines (pFilePick, fh); MepFClose (fh); } if (fTmp) { _unlink (filebuf); } kindpick = LINEARG; } else { PutLine ((LINE)0, buf, pFilePick); kindpick = BOXARG; } break; } switch (kindpick) { case LINEARG: CopyLine (pFilePick, pFileHead, (LINE)0, pFilePick->cLines-1, YCUR (pInsCur)); break; case BOXARG: i = LineLength ((LINE)0, pFilePick); CopyBox (pFilePick, pFileHead, 0, (LINE)0, i-1, pFilePick->cLines-1, XCUR (pInsCur), YCUR (pInsCur)); break; case STREAMARG: i = LineLength (pFilePick->cLines-1, pFilePick); CopyStream (pFilePick, pFileHead, 0, (LINE)0, i, pFilePick->cLines-1, XCUR (pInsCur), YCUR (pInsCur)); break; } return TRUE; argData; fMeta; } /*** CopyLine - copy lines between files * * If the source file is NULL, then we insert blank lines. * * Input: * pFileSrc = source file handle * pFileDst = destination file handle * yStart = first line to be copied * yEnd = last line to be copied * yDst = location of destination of copy * *************************************************************************/ void CopyLine ( PFILE pFileSrc, PFILE pFileDst, LINE yStart, LINE yEnd, LINE yDst ) { linebuf L_buf; struct lineAttr * rgla = (struct lineAttr *)ZEROMALLOC (sizeof(linebuf)/sizeof(char) * sizeof(struct lineAttr)); if (pFileSrc != pFileDst) { if (yStart <= yEnd) { InsLine (TRUE, yDst, yEnd - yStart + 1, pFileDst); if (pFileSrc != NULL) { MarkCopyLine (pFileSrc, pFileDst, yStart, yEnd, yDst); while (yStart <= yEnd) { gettextline (TRUE, yStart++, L_buf, pFileSrc, ' '); puttextline (TRUE, TRUE, yDst++, L_buf, pFileDst); if (getcolorline (TRUE, yStart-1, rgla, pFileSrc)) { putcolorline (TRUE, yDst-1, rgla, pFileDst); } } } } } FREE (rgla); } /*** CopyBox - copy a box from one place to another * * If the source file is NULL, then we insert blank space. We copy the box * defined by the LOGICAL box xLeft-xRight and yTop-yBottom inclusive. * * Input: * pFileSrc = source file handle * pFileDst = destination file handle * xLeft = column location of beginning of copy * yTop = line location of beginning of copy * xRight = column location of end of copy * yBottom = line location of end of copy * xDst = column location of destination of copy * yDst = line location of destination of copy * *************************************************************************/ void CopyBox ( PFILE pFileSrc, PFILE pFileDst, COL xLeft, LINE yTop, COL xRight, LINE yBottom, COL xDst, LINE yDst ) { int cbDst; /* count of bytes in destination*/ int cbMove; /* count of bytes to move around*/ linebuf dstbuf; /* buffer for result */ char *pDst; /* physical pointer to dest */ char *pSrcLeft; /* physical pointer to src left */ char *pSrcRight; /* physical pointer to src right+1*/ linebuf L_srcbuf; /* buffer for source line */ struct lineAttr rgla[sizeof(linebuf)]; flagType fColor; /* * Do not allow overlapped copies. */ if ((pFileSrc == pFileDst) && (( fInRange ((LINE)xLeft, (LINE)xDst, (LINE)xRight) && fInRange (yTop, yDst, yBottom)) || ( fInRange ((LINE)xLeft, (LINE)(xDst + xRight - xLeft), (LINE)xRight) && fInRange (yTop, yDst + yBottom - yTop, yBottom)) ) ) { return; } /* * If valid left and right coordinates for box, then for each line... */ if (xLeft <= xRight) { /* * Let the Marker update any affected marks. */ MarkCopyBox (pFileSrc, pFileDst, xLeft, yTop, xRight, yBottom, xDst, yDst); while (yTop <= yBottom) { if (!pFileSrc) { // // File is not a file, just insert spaces. // if (!fInsSpace (xDst, yDst, xRight - xLeft + 1, pFileDst, dstbuf)) { LengthCheck (yDst, 0, NULL); } pDst = pLog (dstbuf, xDst, TRUE); } else { // // When source IS a file, we: // - get both source and destination lines // - ensure that the source line is detabbed (only way to ensure proper // alignment in the copy. // - get phsical pointers to right and left of source. // - get phsical pointer to destination // - get length of physical move and current destination // - physical length check the potential destination result // - open up a hole in the destination line for the source // - copy the source range into the destination // - perform logical length check. // fInsSpace (xRight+1, yTop, 0, pFileSrc, fRealTabs ? dstbuf : L_srcbuf); if (fRealTabs) { Untab (fileTab, dstbuf, strlen(dstbuf), L_srcbuf, ' '); } fInsSpace (xDst, yDst, 0, pFileDst, dstbuf); pSrcLeft = pLog (L_srcbuf, xLeft, TRUE); pSrcRight = pLog (L_srcbuf, xRight, TRUE) + 1; pDst = pLog (dstbuf, xDst, TRUE); cbMove = (int)(pSrcRight - pSrcLeft); cbDst = strlen (dstbuf); if (cbDst + cbMove > sizeof(linebuf)) { LengthCheck (yDst, 0, NULL); } else { memmove (pDst + cbMove, pDst, strlen(dstbuf) - (int)(pDst - dstbuf) + 1); memmove (pDst, pSrcLeft, cbMove); if (cbLog(dstbuf) > sizeof(linebuf)) { LengthCheck (yDst, 0, NULL); *pLog (dstbuf, sizeof(linebuf) - 1, TRUE) = 0; } } } if (fColor = GetColor (yDst, rgla, pFileDst)) { if (pFileSrc) { CopyColor (pFileSrc, pFileDst, yTop, xLeft, cbMove, yDst, xDst); } else { ShiftColor (rgla, (int)(pDst - dstbuf), xRight - xLeft + 1); ColorToLog (rgla, dstbuf); } } PutLine (yDst, dstbuf, pFileDst); if (fColor) { PutColor (yDst, rgla, pFileDst); } yDst++; yTop++; } } } /*** CopyStream - copy a stream of text (including end-of-lines) * * If source file is NULL, then we insert blank space. We copy starting at * xStart/yStart and copy through to the character before xEnd/yEnd. This * means that to copy line Y INCLUDING the line separator, we specify * (xStart,yStart) = (0,Y) and (xEnd,yEnd) = (0, Y+1) * * Input: * pFileSrc = source file handle * pFileDst = destination file handle * xStart = column location of beginning of copy * yStart = line location of beginning of copy * xEnd = column location of end of copy * yEnd = line location of end of copy * xDst = column location of destination of copy * yDst = line location of destination of copy * *************************************************************************/ void CopyStream ( PFILE pFileSrc, PFILE pFileDst, COL xStart, LINE yStart, COL xEnd, LINE yEnd, COL xDst, LINE yDst ) { linebuf dstbuf; /* buffer for result */ char *pDst; linebuf L_srcbuf; /* buffer for source line */ LINE yDstLast; /* * validate copy...must be different files, and coordinates must make sense. */ if (!(pFileSrc != pFileDst && (yStart < yEnd || (yStart == yEnd && xStart < xEnd)))) { return; } /* * Special case a single-line stream as a box copy */ if (yStart == yEnd) { CopyBox (pFileSrc, pFileDst, xStart, yStart, xEnd-1, yEnd, xDst, yDst); return; } /* * Valid stream copy. First, copy the intermediate lines. */ CopyLine (pFileSrc, pFileDst, yStart+1, yEnd, yDst+1); /* * Form last line of destination stream. Copy last part of dest line onto * last part of last source line. Make sure that each copy of the * source/dest is correct length */ fInsSpace (xDst, yDst, 0, pFileDst, dstbuf); /* dddddeeeeee */ if (pFileSrc != NULL) { fInsSpace (xEnd, yEnd, 0, pFileSrc, L_srcbuf);/* AAAABBBBB */ } else { memset ((char *) L_srcbuf, ' ', xEnd); } pDst = pLog (dstbuf,xDst, TRUE); yDstLast = yDst + yEnd - yStart; LengthCheck (yDstLast, xEnd, pDst); strcpy ( pLog(L_srcbuf,xEnd,TRUE), pDst); /* AAAAeeeeee */ PutLine (yDstLast, L_srcbuf, pFileDst); /* * Form first line of destination stream. Copy last part of first source * line onto last part of dest line */ if (pFileSrc != NULL) { fInsSpace (xStart, yStart, 0, pFileSrc, L_srcbuf);/* CCCCCDDDDD*/ LengthCheck (yDst, xDst, L_srcbuf + xStart); strcpy (pDst, pLog(L_srcbuf,xStart,TRUE)); /* dddddDDDDD*/ } else { *pDst = 0; } PutLine (yDst, dstbuf, pFileDst); /* * To update marks, we first adjust any marks at yDst, then add new * marks from the src. */ MarkCopyBox (pFileDst, pFileDst, xDst, yDst, sizeof(linebuf), yDst, xEnd-1, yDstLast); MarkCopyBox (pFileSrc, pFileDst, 0, yEnd, xEnd, yEnd, 0, yDstLast); MarkCopyBox (pFileSrc, pFileDst, xStart, yStart, sizeof(linebuf), yStart, xDst, yDst); }
duchaochen/cyfm
cyfm-web/src/main/java/com/ppcxy/cyfm/bus/system/service/JoinSystemService.java
<reponame>duchaochen/cyfm package com.ppcxy.cyfm.bus.system.service; import com.ppcxy.common.service.BaseService; import com.ppcxy.cyfm.bus.system.entity.JoinSystem; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class JoinSystemService extends BaseService<JoinSystem, Long> { }
kstepanmpmg/mldb
testing/pyplugin_static_folder/main.py
<reponame>kstepanmpmg/mldb # This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved. from mldb import mldb endpoint = mldb.plugin.args[0] folder = mldb.plugin.args[1] mldb.log("Trying with enpoint '%s' -> '%s'" % (endpoint, folder)) mldb.plugin.serve_static_folder(endpoint, folder)
fallahn/crogine
editor/src/LayoutState.cpp
<reponame>fallahn/crogine /*----------------------------------------------------------------------- <NAME> 2020 - 2021 http://trederia.blogspot.com crogine editor - Zlib license. This software is provided 'as-is', without any express or implied warranty.In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions : 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. -----------------------------------------------------------------------*/ #include "LayoutState.hpp" #include "SharedStateData.hpp" #include "Messages.hpp" #include "LayoutConsts.hpp" #include "UIConsts.hpp" #include <crogine/ecs/components/Camera.hpp> #include <crogine/ecs/components/Transform.hpp> #include <crogine/ecs/components/Sprite.hpp> #include <crogine/ecs/components/Drawable2D.hpp> #include <crogine/ecs/systems/CameraSystem.hpp> #include <crogine/ecs/systems/SpriteSystem2D.hpp> #include <crogine/ecs/systems/TextSystem.hpp> #include <crogine/ecs/systems/RenderSystem2D.hpp> #include <crogine/graphics/Image.hpp> #include <crogine/util/Constants.hpp> #include <crogine/detail/glm/gtc/matrix_transform.hpp> namespace { } LayoutState::LayoutState(cro::StateStack& stack, cro::State::Context context, SharedStateData& sd) : cro::State (stack, context), m_modelScene (context.appInstance.getMessageBus()), m_uiScene (context.appInstance.getMessageBus()), m_thumbScene (context.appInstance.getMessageBus()), m_sharedData (sd), m_layoutSize (le::DefaultLayoutSize), m_nextResourceID(1), m_selectedSprite(0), m_selectedFont (0) { context.mainWindow.loadResources([this]() { addSystems(); loadAssets(); createScene(); initUI(); }); #ifdef CRO_DEBUG_ loadFont("assets/fonts/ProggyClean.ttf"); #endif } //public bool LayoutState::handleEvent(const cro::Event& evt) { if (cro::ui::wantsMouse() || cro::ui::wantsKeyboard()) { return true; } m_modelScene.forwardEvent(evt); m_uiScene.forwardEvent(evt); return true; } void LayoutState::handleMessage(const cro::Message& msg) { if (msg.id == cro::Message::WindowMessage) { const auto& data = msg.getData<cro::Message::WindowEvent>(); if (data.event == SDL_WINDOWEVENT_SIZE_CHANGED) { updateLayout(data.data0, data.data1); //m_viewportRatio = updateView(m_scene.getActiveCamera(), DefaultFarPlane, m_fov); } } else if (msg.id == cro::Message::ConsoleMessage) { const auto& data = msg.getData<cro::Message::ConsoleEvent>(); if (data.type == cro::Message::ConsoleEvent::LinePrinted) { switch (data.level) { default: case cro::Message::ConsoleEvent::Info: m_messageColour = { 0.f,1.f,0.f,1.f }; break; case cro::Message::ConsoleEvent::Warning: m_messageColour = { 1.f,0.5f,0.f,1.f }; break; case cro::Message::ConsoleEvent::Error: m_messageColour = { 1.f,0.f,0.f,1.f }; break; } } } m_modelScene.forwardMessage(msg); m_uiScene.forwardMessage(msg); } bool LayoutState::simulate(float dt) { //updates message colour const float colourIncrease = dt;// *0.5f; m_messageColour.w = std::min(1.f, m_messageColour.w + colourIncrease); m_messageColour.x = std::min(1.f, m_messageColour.x + colourIncrease); m_messageColour.y = std::min(1.f, m_messageColour.y + colourIncrease); m_messageColour.z = std::min(1.f, m_messageColour.z + colourIncrease); m_modelScene.simulate(dt); m_uiScene.simulate(dt); return true; } void LayoutState::render() { auto& rt = cro::App::getWindow(); m_modelScene.render(rt); m_uiScene.render(rt); } //private void LayoutState::addSystems() { auto& mb = getContext().appInstance.getMessageBus(); m_uiScene.addSystem<cro::SpriteSystem2D>(mb); m_uiScene.addSystem<cro::TextSystem>(mb); m_uiScene.addSystem<cro::CameraSystem>(mb); m_uiScene.addSystem<cro::RenderSystem2D>(mb); m_thumbScene.addSystem<cro::SpriteSystem2D>(mb); m_thumbScene.addSystem<cro::TextSystem>(mb); m_thumbScene.addSystem<cro::CameraSystem>(mb); m_thumbScene.addSystem<cro::RenderSystem2D>(mb); } void LayoutState::loadAssets() { cro::Image img; img.create(2, 2, cro::Colour::Magenta); m_backgroundTexture.loadFromImage(img); } void LayoutState::createScene() { //TODO decide if we want a 3D scene and ditch it if we don't. //this is called when the window is resized to automatically update the camera's matrices/viewport auto camEnt = m_modelScene.getActiveCamera(); updateView3D(camEnt.getComponent<cro::Camera>()); camEnt.getComponent<cro::Camera>().resizeCallback = std::bind(&LayoutState::updateView3D, this, std::placeholders::_1); //load a background texture. User can load a screen shot of their game for instance //to aid with lining up the the layout with their scene. auto entity = m_uiScene.createEntity(); entity.addComponent<cro::Transform>().setPosition({ 0.f, 0.f, -10.f }); entity.getComponent<cro::Transform>().setScale(m_layoutSize / 2.f); entity.addComponent<cro::Drawable2D>(); entity.addComponent<cro::Sprite>(m_backgroundTexture); m_backgroundEntity = entity; camEnt = m_uiScene.getActiveCamera(); updateView2D(camEnt.getComponent<cro::Camera>()); camEnt.getComponent<cro::Camera>().resizeCallback = std::bind(&LayoutState::updateView2D, this, std::placeholders::_1); //this is used to render the thumbnail previews in the browser //so the camera can be set once and left as it's not affected by resizing the window camEnt = m_thumbScene.getActiveCamera(); camEnt.getComponent<cro::Camera>().setOrthographic(0.f, static_cast<float>(uiConst::ThumbTextureSize), 0.f, static_cast<float>(uiConst::ThumbTextureSize), -0.1f, 1.f); } void LayoutState::updateView2D(cro::Camera& cam2D) { glm::vec2 size(cro::App::getWindow().getSize()); float infoHeight = (uiConst::InfoBarHeight / size.y); float titleHeight = (uiConst::TitleHeight / size.y); cam2D.viewport.left = uiConst::InspectorWidth; cam2D.viewport.width = 1.f - uiConst::InspectorWidth; cam2D.viewport.bottom = uiConst::BrowserHeight + infoHeight; cam2D.viewport.height = 1.f - cam2D.viewport.bottom - titleHeight; size.x -= (size.x * uiConst::InspectorWidth); size.y -= (size.y * (uiConst::BrowserHeight + infoHeight + titleHeight)); auto windowRatio = size.x / size.y; auto viewRatio = m_layoutSize.x / m_layoutSize.y; if (windowRatio > viewRatio) { //side bars float sizeW = cam2D.viewport.width * (viewRatio / windowRatio); float offset = (cam2D.viewport.width - sizeW) / 2.f; cam2D.viewport.width = sizeW; cam2D.viewport.left += offset; } else { //top/bottom bars float sizeH = cam2D.viewport.height * (windowRatio / viewRatio); float offset = (cam2D.viewport.height - sizeH) / 2.f; cam2D.viewport.height = sizeH; cam2D.viewport.bottom += offset; } cam2D.setOrthographic(0.f, m_layoutSize.x, 0.f, m_layoutSize.y, -0.1f, 11.f); m_backgroundEntity.getComponent<cro::Transform>().setScale( m_layoutSize / m_backgroundEntity.getComponent<cro::Sprite>().getSize()); } void LayoutState::updateView3D(cro::Camera& cam3D) { glm::vec2 size(cro::App::getWindow().getSize()); size.y = ((size.x / 16.f) * 9.f) / size.y; size.x = 1.f; //90 deg in x (glm expects fov in y) cam3D.setPerspective(50.6f * cro::Util::Const::degToRad, 16.f / 9.f, 0.1f, 140.f); cam3D.viewport.bottom = (1.f - size.y) / 2.f; cam3D.viewport.height = size.y; }
HoEmpire/slambook2
3rdparty/meshlab-master/src/plugins_experimental/edit_ocme/src/ocme/ocme_debug.cpp
<reponame>HoEmpire/slambook2<gh_stars>1-10 #include "ocme_definition.h" #include "impostor_definition.h" void OCME::Verify(){ /* */ CellsIterator ci; { lgn->Append("CHECK IF: ecd/rd exists for each cell");lgn->Push(); for(ci = cells.begin(); ci != cells.end(); ++ci){ RAssert( (*ci).second->ecd); RAssert( (*ci).second->rd); } } { lgn->Append("CHECK IF: load/unload work");lgn->Push(); for(ci = cells.begin(); ci != cells.end(); ++ci){ Chain<OVertex> * vert = (*ci).second->vert; Chain<OFace> * face = (*ci).second->face; vert->LoadAll(); face->LoadAll(); vert->FreeAll(); face->FreeAll(); } } { lgn->Append("CHECK IF: faces point to vertex inside the cells");lgn->Push(); for(ci = cells.begin(); ci != cells.end(); ++ci){ Chain<OVertex> * vert = (*ci).second->vert; Chain<OFace> * face = (*ci).second->face; for(unsigned int fi = 0 ; fi < face->Size();++fi) for(unsigned int vi = 0 ; vi <3;++vi) RAssert((*face)[fi][vi] < vert->Size()); } } { lgn->Append("CHECK IF: dependent cells exist and dependence is symmetric");lgn->Push(); std::set<CellKey>::iterator cki; for(ci = cells.begin(); ci != cells.end(); ++ci) for(cki = (*ci).second->dependence_set.begin(); cki != (*ci).second->dependence_set.end(); ++cki) { Cell * c = GetCell((*cki),false); if(!c){ sprintf(lgn->Buf(),"%d %d %d %d does not exist",(*cki).x,(*cki).y,(*cki).z,(*cki).h); lgn->Push(); }else { if(c->dependence_set.find((*ci).second->key)== c->dependence_set.end()) sprintf(lgn->Buf(),"%d %d %d %d Asymmetric",(*cki).x,(*cki).y,(*cki).z,(*cki).h); } } } { lgn->Append("CHECK IF: pointers to boundary (uniquely) refer to existing vertices");lgn->Push(); std::set<CellKey>::iterator cki; for(ci = cells.begin(); ci != cells.end(); ++ci){ std::set<unsigned int> bv; Chain<OVertex> * vert = (*ci).second->vert; Chain<BorderIndex > * border = (*ci).second->border; for(unsigned int bi = 0 ; bi < border->Size();++bi) { if((*border)[bi].vi > vert->Size()){ sprintf(lgn->Buf(),"(vi,bi)= (%d,%d) , vs = %d",(*border)[bi].vi,(*border)[bi].bi,vert->Size()); lgn->Push(); } std::pair<std::set<unsigned int>::iterator, bool > res = bv.insert((*border)[bi].vi); if(!res.second){ Cell * c = (*ci).second; sprintf(lgn->Buf(),"%d %d %d %d :: ii %d, vi %d , bv.size() %d", c->key.x,c->key.y,c->key.z,c->key.h, bi,(*border)[bi].vi,bv.size()); lgn->Push(); } } } } } void OCME::ComputeStatistics(){ lgn->off = false; std::vector<unsigned int> distr,distrD; unsigned int max_tri = 0; unsigned int max_dep = 0; CellsIterator ci; stat = Statistics(); unsigned int com =0; { stat.n_cells = cells.size(); for(ci = cells.begin(); ci != cells.end(); ++ci){ distr.push_back( ((*ci).second->face->Size())); distrD.push_back( (*ci).second->dependence_set.size()); if (max_tri< (*ci).second->face->Size()) max_tri = (*ci).second->face->Size(); if (max_dep< (*ci).second->dependence_set.size()) max_dep = (*ci).second->dependence_set.size(); stat.n_triangles += (*ci).second->face->Size(); stat.n_vertices += (*ci).second->vert->Size(); stat.n_proxies += (*ci).second->impostor->centroids.data.size(); com += (*ci).second->impostor->positionsV.size(); } } sprintf(lgn->Buf(),"n_cells %d, n_tri %d, n_vert %d, n_pro(compact) %d,n_pro(sparse) %d", stat.n_cells,stat.n_triangles,stat.n_vertices,com,stat.n_proxies ); lgn->Push(); { std::sort(distr.begin(),distr.end()); unsigned int j =0; for(unsigned int i = 1; i < 100;++i){ unsigned int h = 0; while(distr[j]< max_tri*i/100.f){++j;++h;} sprintf(lgn->Buf(),"%f, %d",max_tri*i/100.f,h); lgn->Push(); } } sprintf(lgn->Buf(),"-------------------------------------");lgn->Push(); { std::sort(distrD.begin(),distrD.end()); unsigned int j =0; for(unsigned int i = 1; i < 20;++i){ unsigned int h = 0; while(distrD[j]< max_dep*i/20.f){++j;++h;} sprintf(lgn->Buf(),"%f, %d",max_dep*i/20.f,h); lgn->Push(); } } } bool OCME::CheckFaceVertDeletions(Cell *c){ return true; c->ecd->deleted_face.SetAsVectorOfBool(); c->ecd->deleted_vertex.SetAsVectorOfBool(); for(unsigned int fi = 0; fi < c->face->Size(); ++fi) if(!c->ecd->deleted_face.IsMarked(fi)) { OFace of = (*(c->face))[fi]; for(unsigned int vpi = 0; vpi < 3; ++vpi) RAssert(!c->ecd->deleted_vertex.IsMarked(of[vpi])); } return true; } bool OCME::CheckFaceVertexAdj(Cell *c){ for(unsigned int fi = 0; fi < c->face->Size(); ++fi){ OFace of = (*(c->face))[fi]; for(unsigned int vpi = 0; vpi < 3; ++vpi){ if( (*(c->vert)).Size() <= of[vpi]) { sprintf(lgn->Buf(),"wrong face-vert adj cell: %d %d %d %d", c->key);lgn->Push(); sprintf(lgn->Buf(),"wrong face-vert adj face: %d", fi);lgn->Push(); sprintf(lgn->Buf(),"wrong face-vert adj ov[]: %d %d %d ",of[0],of[1],of[2]);lgn->Push(); return false;} // if( 0 > of[vpi] ) // { lgn->Append("negative face-vert adj ");lgn->Push(); return false;} } } return true; } bool OCME:: CheckDependentSet(std::vector<Cell*> & ){return true; } bool OCME:: BorderExists(Cell* c,unsigned int vi){ for(unsigned int vii = 0; vii < c->border->Size(); ++vii) if((*c->border)[vii].vi == vi) return true; return false; }
ShanghaiWuDun/rust-nasl
c/base/cvss.c
/* Copyright (C) 2012-2018 Greenbone Networks GmbH * * SPDX-License-Identifier: GPL-2.0-or-later * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA. */ /** * @file * @brief CVSS utility functions * * This file contains utility functions for handling CVSS. * Namels a calculator for the CVSS base score from a CVSS base * vector. * * The base equation is the foundation of CVSS scoring. The base equation is: * BaseScore6 = round_to_1_decimal(((0.6*Impact)+(0.4*Exploitability)–1.5)*f(Impact)) * Impact = 10.41*(1-(1-ConfImpact)*(1-IntegImpact)*(1-AvailImpact)) * Exploitability = 20* AccessVector*AccessComplexity*Authentication * * f(impact)= 0 if Impact=0, 1.176 otherwise * AccessVector = case AccessVector of * requires local access: 0.395 * adjacent network accessible: 0.646 * network accessible: 1.0 * AccessComplexity = case AccessComplexity of * high: 0.35 * medium: 0.61 * low: 0.71 * Authentication = case Authentication of * requires multiple instances of authentication: 0.45 * requires single instance of authentication: 0.56 * requires no authentication: 0.704 * ConfImpact = case ConfidentialityImpact of * none: 0.0 * partial: 0.275 * complete: 0.660 * IntegImpact = case IntegrityImpact of * none: 0.0 * partial: 0.275 * complete: 0.660 * AvailImpact = case AvailabilityImpact of * none: 0.0 * partial: 0.275 * complete: 0.660 */ #include <string.h> #include <glib.h> /* AccessVector (AV) Constants */ #define AV_NETWORK 1.0 #define AV_ADJACENT_NETWORK 0.646 #define AV_LOCAL 0.395 /* AccessComplexity (AC) Constants */ #define AC_LOW 0.71 #define AC_MEDIUM 0.61 #define AC_HIGH 0.35 /* Authentication (Au) Constants */ #define Au_MULTIPLE_INSTANCES 0.45 #define Au_SINGLE_INSTANCE 0.56 #define Au_NONE 0.704 /* ConfidentialityImpact (C) Constants */ #define C_NONE 0.0 #define C_PARTIAL 0.275 #define C_COMPLETE 0.660 /* IntegrityImpact (I) Constants */ #define I_NONE 0.0 #define I_PARTIAL 0.275 #define I_COMPLETE 0.660 /* AvailabilityImpact (A) Constants */ #define A_NONE 0.0 #define A_PARTIAL 0.275 #define A_COMPLETE 0.660 enum base_metrics { A, I, C, Au, AC, AV }; /** * @brief Describe a CVSS impact element. */ struct impact_item { const char *name; /**< Impact element name */ double nvalue; /**< Numerical value */ }; /** * @brief Describe a CVSS metrics. */ struct cvss { double conf_impact; /**< Confidentiality impact. */ double integ_impact; /**< Integrity impact. */ double avail_impact; /**< Availability impact. */ double access_vector; /**< Access vector. */ double access_complexity; /**< Access complexity. */ double authentication; /**< Authentication. */ }; static const struct impact_item impact_map[][3] = { [A] = { {"N", A_NONE}, {"P", A_PARTIAL}, {"C", A_COMPLETE}, }, [I] = { {"N", I_NONE}, {"P", I_PARTIAL}, {"C", I_COMPLETE}, }, [C] = { {"N", C_NONE}, {"P", C_PARTIAL}, {"C", C_COMPLETE}, }, [Au] = { {"N", Au_NONE}, {"M", Au_MULTIPLE_INSTANCES}, {"S", Au_SINGLE_INSTANCE}, }, [AV] = { {"N", AV_NETWORK}, {"A", AV_ADJACENT_NETWORK}, {"L", AV_LOCAL}, }, [AC] = { {"L", AC_LOW}, {"M", AC_MEDIUM}, {"H", AC_HIGH}, }, }; /** * @brief Determine base metric enumeration from a string. * * @param[in] str Base metric in string form, for example "A". * @param[out] res Where to write the desired value. * * @return 0 on success, -1 on error. */ static int toenum (const char *str, enum base_metrics *res) { int rc = 0; /* let's be optimistic */ if (g_strcmp0 (str, "A") == 0) *res = A; else if (g_strcmp0 (str, "I") == 0) *res = I; else if (g_strcmp0 (str, "C") == 0) *res = C; else if (g_strcmp0 (str, "Au") == 0) *res = Au; else if (g_strcmp0 (str, "AU") == 0) *res = Au; else if (g_strcmp0 (str, "AV") == 0) *res = AV; else if (g_strcmp0 (str, "AC") == 0) *res = AC; else rc = -1; return rc; } /** * @brief Calculate Impact Sub Score. * * @param[in] cvss Contains the subscores associated * to the metrics. * * @return The resulting subscore. */ static double get_impact_subscore (const struct cvss *cvss) { return (10.41 * (1 - (1 - cvss->conf_impact) * (1 - cvss->integ_impact) * (1 - cvss->avail_impact))); } /** * @brief Calculate Exploitability Sub Score. * * @param[in] cvss Contains the subscores associated * to the metrics. * * @return The resulting subscore. */ static double get_exploitability_subscore (const struct cvss *cvss) { return (20 * cvss->access_vector * cvss->access_complexity * cvss->authentication); } /** * @brief Set impact score from string representation. * * @param[in] value The literal value associated to the metric. * @param[in] metric The enumeration constant identifying the metric. * @param[out] cvss The structure to update with the score. * * @return 0 on success, -1 on error. */ static inline int set_impact_from_str (const char *value, enum base_metrics metric, struct cvss *cvss) { int i; for (i = 0; i < 3; i++) { const struct impact_item *impact; impact = &impact_map[metric][i]; if (g_strcmp0 (impact->name, value) == 0) { switch (metric) { case A: cvss->avail_impact = impact->nvalue; break; case I: cvss->integ_impact = impact->nvalue; break; case C: cvss->conf_impact = impact->nvalue; break; case Au: cvss->authentication = impact->nvalue; break; case AV: cvss->access_vector = impact->nvalue; break; case AC: cvss->access_complexity = impact->nvalue; break; default: return -1; } return 0; } } return -1; } /** * @brief Final CVSS score computation helper. * * @param[in] cvss The CVSS structure that contains the * different metrics and associated scores. * * @return the CVSS score, as a double. */ static double __get_cvss_score (struct cvss *cvss) { double impact = 1.176; double impact_sub; double exploitability_sub; impact_sub = get_impact_subscore (cvss); exploitability_sub = get_exploitability_subscore (cvss); if (impact_sub < 0.1) impact = 0.0; return (((0.6 * impact_sub) + (0.4 * exploitability_sub) - 1.5) * impact) + 0.0; } /** * @brief Calculate CVSS Score. * * @param cvss_str Base vector string from which to compute score. * * @return The resulting score. -1 upon error during parsing. */ double get_cvss_score_from_base_metrics (const char *cvss_str) { struct cvss cvss; char *token, *base_str, *base_metrics; memset (&cvss, 0x00, sizeof (struct cvss)); if (cvss_str == NULL) return -1.0; base_str = base_metrics = g_strdup_printf ("%s/", cvss_str); while ((token = strchr (base_metrics, '/')) != NULL) { char *token2 = strtok (base_metrics, ":"); char *metric_name = token2; char *metric_value; enum base_metrics mval; int rc; *token++ = '\0'; if (metric_name == NULL) goto ret_err; metric_value = strtok (NULL, ":"); if (metric_value == NULL) goto ret_err; rc = toenum (metric_name, &mval); if (rc) goto ret_err; if (set_impact_from_str (metric_value, mval, &cvss)) goto ret_err; base_metrics = token; } g_free (base_str); return __get_cvss_score (&cvss); ret_err: g_free (base_str); return (double) -1; }
hdm/mac-tracker
data/js/5c/b2/9e/00/00/00.24.js
<gh_stars>10-100 macDetailCallback("5cb29e000000/24",[{"d":"2019-12-25","t":"add","s":"ieee-oui.csv","a":"160 Park Avenue Florham Park NJ US 07932","c":"US","o":"ASCO Power Technologies"}]);
securesonic/safekiddo-backend
src/modules/httpd/serverStatus.h
/* * serverStatus.h * * Created on: Jul 21, 2014 * Author: witkowski */ #ifndef SERVERSTATUS_H_ #define SERVERSTATUS_H_ #include <ctime> #include <mutex> namespace safekiddo { namespace webservice { class ServerStatus { private: std::mutex mutable mutex; time_t const maxTimeBetweenEvents; size_t const maxProblemEvents; size_t counter; time_t lastProblem; public: ServerStatus( time_t maxTimeBetweenEvents = 60, size_t maxProblemEvents = 5); void reportProblem(); bool statusOk() const; }; } // namespace webservice } // namespace safekiddo #endif /* SERVERSTATUS_H_ */
illeagalName/su-sunday-cloud
sunday-modules/sunday-job-service/src/main/java/com/haier/job/schedule/CrawlerTask.java
<reponame>illeagalName/su-sunday-cloud package com.haier.job.schedule; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Lists; import com.haier.api.bot.RemoteBotService; import com.haier.core.util.DataUtils; import com.haier.core.util.HttpUtils; import com.haier.core.util.StringUtils; import com.haier.job.domain.Hitokoto; import com.haier.job.mapper.HitokotoMapper; import com.xxl.job.core.context.XxlJobHelper; import com.xxl.job.core.handler.annotation.XxlJob; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.Pair; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * @Description: TODO(这里用一句话描述这个类的作用) * @Author Ami * @Date 2021/10/28 17:16 */ @Component @Slf4j @RefreshScope public class CrawlerTask { @Value("${hitokoto.url}") String hitokotoUrl; @Resource HitokotoMapper hitokotoMapper; @Resource RemoteBotService remoteBotService; /** * hitokoto(一言)、en(中英文)、social(社会语录)、soup(毒鸡汤)、fart(彩虹屁)、zha(渣男语录) */ final List<Pair<String, String>> HITOKOTO_TYPES = Lists.newArrayList(Pair.of("一言", "hitokoto"), Pair.of("中英文", "en"), Pair.of("社会语录", "social"), Pair.of("毒鸡汤", "soup"), Pair.of("彩虹屁", "fart"), Pair.of("渣男语录", "zha")); @XxlJob("getHitokotoInfo") public void getHitokotoInfo() { XxlJobHelper.log("执行器进入逻辑处理getHitokotoInfo"); // XxlJobHelper.handleFail(""),XxlJobHelper.handleSuccess("") //获取页面传递的参数 String param = XxlJobHelper.getJobParam(); List<Hitokoto> hitokotos = new ArrayList<>(); HITOKOTO_TYPES.forEach(type -> { String s = HttpUtils.doGet(StringUtils.stringFormat(hitokotoUrl, type)); JSONObject result = JSON.parseObject(s); if (Objects.nonNull(result) && Objects.equals(result.getInteger("code"), 200)) { String content = result.getString("content"); Hitokoto hitokoto = new Hitokoto(); hitokoto.setType(type.getRight()); hitokoto.setContent(content); hitokotos.add(hitokoto); if (type.getLeft().equals("毒鸡汤")) { remoteBotService.sendMessage(type.getLeft().concat(" - ").concat(content)); } } XxlJobHelper.log("type : {} 异常", type); }); if (DataUtils.isNotEmpty(hitokotos)) { hitokotoMapper.batchInsertHitokotos(hitokotos); } XxlJobHelper.handleSuccess("执行完毕"); } @XxlJob("privateDomain") public void privateDomain() { remoteBotService.joke(); XxlJobHelper.handleSuccess("执行完毕"); } @XxlJob("readWorld") public void readWorld() { remoteBotService.readWorld(); XxlJobHelper.handleSuccess("执行完毕"); } @XxlJob("takeMadinglin") public void takeMadinglin() { remoteBotService.takePills("到了吃吗丁啉的时间了," + LocalDateTime.now()); XxlJobHelper.handleSuccess("执行完毕"); } @XxlJob("takeDaxi") public void takeDaxi() { remoteBotService.takePills("到了吃铝碳酸镁(达喜)的时间了," + LocalDateTime.now()); XxlJobHelper.handleSuccess("执行完毕"); } }
keyko-io/eventeum
core/src/main/java/io/keyko/monitoring/agent/core/dto/message/ContractEventFilterRemoved.java
package io.keyko.monitoring.agent.core.dto.message; import io.keyko.monitoring.agent.core.dto.event.filter.ContractEventFilter; import lombok.NoArgsConstructor; @NoArgsConstructor public class ContractEventFilterRemoved extends AbstractMessage<ContractEventFilter> { public static final String TYPE = "EVENT_FILTER_REMOVED"; public ContractEventFilterRemoved(ContractEventFilter filter) { super(filter.getId(), TYPE, filter); } }
thesaravanakumar/competative-programming
codeforces/800/1085A-Right-LeftCipher.cpp
<gh_stars>0 #include <bits/stdc++.h> #define ll long long int #define w(t) int t; cin>>t; while(t--) #define F first #define S second #define pb push_back #define mp make_pair #define pii pair<int,int> #define mii map<int,int> #define sp(x,y) fixed<<setprecision(y)<<x using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); string s; cin >> s; int len=s.size(); int n=(len-1)/2; cout << s[n]; for(int i=1;i<=n;i++){ cout << s[n+i] << s[n-i]; } if(s.size()%2==0){ cout << s[s.size()-1]; } return 0; }
efbiz/ability-exam
manager/src/main/java/org/efbiz/ablility/exam/manager/service/QuestionHistoryService.java
package org.efbiz.ablility.exam.manager.service; import java.util.List; import java.util.Map; import org.efbiz.ability.exam.common.domain.exam.UserQuestionHistory; import org.efbiz.ability.exam.common.domain.question.QuestionStatistic; public interface QuestionHistoryService { /** * 插入试题历史 * * @param historyList */ public void addUserQuestionHist(List<UserQuestionHistory> historyList); /** * 插入试题历史 * * @param history */ public void addUserQuestionHist(UserQuestionHistory... history); /** * 获取用户的试题练习历史 * * @param userId * @param fieldId * * @return Map<知识点 , List < UserQuestionHistory>> */ public Map<Integer, List<UserQuestionHistory>> getUserQuestionHist(int userId, int fieldId); /** * 根据fieldId,pointId分组统计练习历史试题数量 * * @param fieldId * @param userId * * @return */ public Map<Integer, QuestionStatistic> getQuestionHistStaticByFieldId(int fieldId, int userId); /** * 根据fieldId,pointId,typeId分组统计练习历史试题数量 * * @param fieldId * @param userId * * @return */ public Map<Integer, Map<Integer, QuestionStatistic>> getTypeQuestionHistStaticByFieldId( int fieldId, int userId); }
flavoi/diven
diventi/ebooks/migrations/0014_book_book_product.py
<gh_stars>1-10 # Generated by Django 2.1.7 on 2019-05-03 05:27 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('products', '0018_delete_section'), ('ebooks', '0013_remove_chapter_chapter_product'), ] operations = [ migrations.AddField( model_name='book', name='book_product', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='products.Product', verbose_name='product'), ), ]
willroberts/duelyst
app/ui/managers/news_manager.js
<filename>app/ui/managers/news_manager.js // See: https://coderwall.com/p/myzvmg for why managers are created this way var _NewsManager = {}; _NewsManager.instance = null; _NewsManager.getInstance = function () { if (this.instance == null) { this.instance = new NewsManager(); } return this.instance; }; _NewsManager.current = _NewsManager.getInstance; module.exports = _NewsManager; var Promise = require("bluebird"); var CONFIG = require('app/common/config'); var Logger = require('app/common/logger'); var SDK = require('app/sdk'); var Manager = require("./manager"); var NotificationsManager = require("./notifications_manager"); var NavigationManager = require("./navigation_manager"); var NotificationModel = require('app/ui/models/notification'); var DuelystFirebase = require('app/ui/extensions/duelyst_firebase'); var Analytics = require('app/common/analytics'); var moment = require('moment'); var ProfileManager = require("./profile_manager"); var NewsManager = Manager.extend({ newsItemsIndexCollection: null, readNewsItemsCollection: null, unreadNewsItemsCollection: null, lastReadItemAt: null, /* region CONNECT */ onBeforeConnect:function() { Manager.prototype.onBeforeConnect.call(this); ProfileManager.getInstance().onReady() .bind(this) .then(function () { var userId = ProfileManager.getInstance().get('id') this.newsItemsIndexCollection = new DuelystFirebase.Collection(null, { firebase: new Firebase(process.env.FIREBASE_URL).child("news").child("index").limitToLast(10) }); this.readNewsItemsCollection = new DuelystFirebase.Collection(null, { firebase: new Firebase(process.env.FIREBASE_URL).child("user-news").child(userId).child("read").limitToLast(20) }); // what to do when we're ready this.onReady().then(function(){ if (this.readNewsItemsCollection.last()) { this.lastReadItemAt = this.readNewsItemsCollection.last().get("read_at"); } var unreadItems = this.newsItemsIndexCollection.filter(function(newsItem) { return !this.readNewsItemsCollection.get(newsItem.get("id")); }.bind(this)); this.unreadNewsItems = new Backbone.Collection(unreadItems); }.bind(this)); this._markAsReadyWhenModelsAndCollectionsSynced([this.newsItemsIndexCollection,this.readNewsItemsCollection]); }) }, /* endregion CONNECT */ markNewsItemAsRead:function(item) { var itemModel = item; if (typeof item == "string") { itemModel = this.newsItemsIndexCollection.get(item) } this.lastReadItemAt = moment().valueOf() if (itemModel) { var key = itemModel.get("id"); var priority = itemModel.get("created_at"); if (!this.readNewsItemsCollection.get(key)) { this.readNewsItemsCollection.add({ "id":key, "read_at":Firebase.ServerValue.TIMESTAMP, ".priority":priority }); } } }, getFirstUnreadAnnouncement:function() { var unread = this.unreadNewsItems.filter(function(newsItem) { return (newsItem.get("type") == "announcement" && newsItem.get("created_at") > this.lastReadItemAt); }.bind(this)); var announcement = _.last(unread); // only show announcements from AFTER the user registered if (announcement && announcement.get("created_at") > ProfileManager.getInstance().profile.get("created_at")) return announcement else return null }, getFirstUnreadAnnouncementContentAsync:function(callback) { var announcement = this.getFirstUnreadAnnouncement(); if (announcement) { var fbRef = new Firebase(process.env.FIREBASE_URL).child("news/content/"+announcement.get("id")); var content = new DuelystFirebase.Model(null,{ firebase: fbRef }); return content.onSyncOrReady(); } else { return Promise.reject(new Error("no unread announcements")); } } });
fluxxlabs/haml
test/hamlit/helpers_test.rb
describe Haml::Helpers do describe '.preserve' do it 'works without block' do result = Haml::Helpers.preserve("hello\nworld") assert_equal 'hello&#x000A;world', result end end end
L0laapk3/RLBotPack
RLBotPack/Rocketnoodles/src/physics/control/__init__.py
from physics.control.base import BaseController from physics.control.steer import PointPD __all__ = ["BaseController", "PointPD"]
restjohn/disconnected-content-explorer-android
app/src/main/java/mil/nga/dice/JavaScriptAPI.java
package mil.nga.dice; import android.app.Activity; import android.app.Dialog; import android.content.IntentSender; import android.location.Location; import android.os.Bundle; import android.util.Log; import android.webkit.WebView; import com.fangjian.WebViewJavascriptBridge; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.ErrorDialogFragment; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.location.LocationServices; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import mil.nga.dice.report.Report; import mil.nga.dice.report.ReportManager; /** */ public class JavaScriptAPI implements ConnectionCallbacks, OnConnectionFailedListener { private static final String TAG = "JavaScriptAPI"; public static JavaScriptAPI addTo(WebView webView, Report report, Activity context) { return new JavaScriptAPI(context, report, webView); } private Activity mActivity; private Report mReport; private WebView mWebView; private File exportDirectory = new File(ReportManager.getInstance().getReportsDir(), "export"); private WebViewJavascriptBridge bridge; private GoogleApiClient mGoogleApiClient; private JavaScriptAPI(Activity a, Report r, WebView w) { mActivity = a; mReport = r; mWebView = w; buildGoogleApiClient(); mGoogleApiClient.connect(); Log.i(TAG, "Configuring JavascriptBridge"); bridge = new WebViewJavascriptBridge(mActivity, mWebView, new UserServerHandler()); bridge.registerHandler("getLocation", new WebViewJavascriptBridge.WVJBHandler() { @Override public void handle(String data, WebViewJavascriptBridge.WVJBResponseCallback jsCallback) { Log.i(TAG, "Bridge received a call to getLocation"); if (jsCallback != null) { Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (location != null) { // get the users location and send it back jsCallback.callback("{\"success\":true,\"lat\":\"" + location.getLatitude() + "\",\"lon\":\"" + location.getLongitude() + "\"}"); } else { jsCallback.callback("{\"success\":false,\"message\":\"DICE could not determine your location. Ensure location services are enabled on your device.\"}"); } } } }); bridge.registerHandler("saveToFile", new WebViewJavascriptBridge.WVJBHandler() { @Override public void handle(String data, WebViewJavascriptBridge.WVJBResponseCallback jsCallback) { Log.i(TAG, "Bridge received a call to export data"); if (jsCallback != null) { File export = new File(exportDirectory, mReport.getTitle() + "_export.json"); if (!exportDirectory.exists()) { exportDirectory.mkdir(); } try { export.createNewFile(); FileOutputStream fOut = new FileOutputStream(export); fOut.write(data.getBytes()); fOut.flush(); fOut.close(); jsCallback.callback("{\"success\":true,\"message\":\"Exported your data to the DICE folder on your SD card.\"}"); } catch (IOException e) { e.printStackTrace(); jsCallback.callback("{\"success\":false,\"message\":\"There was a problem exporting your data, please try again.\"}"); // TODO: send an error object back through the webview so the user can handle it } } } }); } public void removeFromWebView() { mGoogleApiClient.disconnect(); mGoogleApiClient = null; mWebView = null; bridge = null; } class UserServerHandler implements WebViewJavascriptBridge.WVJBHandler { @Override public void handle(String data, WebViewJavascriptBridge.WVJBResponseCallback jsCallback) { Log.i(TAG, "DICE Android received a message from Javascript"); if (jsCallback != null) { jsCallback.callback("Response from DICE"); } } } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(mActivity.getApplicationContext()) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } @Override public void onConnected(Bundle bundle) { } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } }
hyperon-io/dictionary-engine
src/main/java/pl/decerto/hyperon/demo/dictionary/dom/DictionaryDom.java
<filename>src/main/java/pl/decerto/hyperon/demo/dictionary/dom/DictionaryDom.java<gh_stars>0 package pl.decerto.hyperon.demo.dictionary.dom; import java.util.Set; import pl.decerto.hyperon.runtime.model.HyperonDomainObject; import pl.decerto.hyperon.demo.dictionary.dict.Dictionary; import pl.decerto.hyperon.demo.dictionary.dict.impl.DictionaryFactory; import pl.decerto.hyperon.demo.dictionary.dict.impl.DictionaryLevelsExtractor; /** * Represents domain of dictionary with output levels */ public class DictionaryDom extends AbstractDictionaryDom { DictionaryDom(HyperonDomainObject domObj) { super(domObj); } @Override protected DictionaryType getType() { return DictionaryType.VALUES; } public Dictionary getDictionary() { return DictionaryFactory.create(getParamValue()); } public Set<String> getDictionaryLevels() { return DictionaryLevelsExtractor.extract(getParamValue()); } public Dictionary getDictionary(String level) { return DictionaryFactory.create(getParamValue(), level); } }
jbdelcuv/openenclave
host/sgx/hostverify_report.c
<filename>host/sgx/hostverify_report.c // Copyright (c) Open Enclave SDK contributors. // Licensed under the MIT License. #include <openenclave/bits/report.h> #include <openenclave/bits/result.h> #include <openenclave/host.h> #include <openenclave/host_verify.h> #include <openenclave/internal/raise.h> #include "../../common/sgx/quote.h" #include "sgxquoteprovider.h" oe_result_t oe_verify_remote_report( const uint8_t* report, size_t report_size, const uint8_t* endorsement, size_t endorsement_size, oe_report_t* parsed_report) { oe_result_t result = OE_UNEXPECTED; oe_report_t oe_report = {0}; oe_report_header_t* header = (oe_report_header_t*)report; if (report == NULL) OE_RAISE(OE_INVALID_PARAMETER); if (report_size == 0 || report_size > OE_MAX_REPORT_SIZE) OE_RAISE(OE_INVALID_PARAMETER); // The two host side attestation API's are oe_get_report and // oe_verify_report. Initialize the quote provider in both these APIs. OE_CHECK(oe_initialize_quote_provider()); // Ensure that the report is parseable before using the header. OE_CHECK(oe_parse_report(report, report_size, &oe_report)); if (header->report_type != OE_REPORT_TYPE_SGX_REMOTE) OE_RAISE(OE_UNSUPPORTED); // Quote attestation can be done entirely on the host side. OE_CHECK(oe_verify_sgx_quote( header->report, header->report_size, endorsement, endorsement_size, NULL)); // Optionally return parsed report. if (parsed_report != NULL) OE_CHECK(oe_parse_report(report, report_size, parsed_report)); result = OE_OK; done: return result; }
scopely/deck
app/scripts/modules/oracle/securityGroup/securityGroup.transformer.js
'use strict'; const angular = require('angular'); import { NETWORK_READ_SERVICE } from '@spinnaker/core'; import _ from 'lodash'; module.exports = angular .module('spinnaker.oraclebmcs.securityGroup.transformer', [NETWORK_READ_SERVICE]) .factory('oraclebmcsSecurityGroupTransformer', function(networkReader) { const provider = 'oraclebmcs'; function normalizeSecurityGroup(securityGroup) { return networkReader.listNetworksByProvider(provider).then(_.partial(addVcnNameToSecurityGroup, securityGroup)); } function addVcnNameToSecurityGroup(securityGroup, vcns) { const matches = vcns.find(vcn => vcn.id === securityGroup.network); securityGroup.vpcName = matches.length ? matches[0].name : ''; } return { normalizeSecurityGroup: normalizeSecurityGroup, }; });
he0119/smart-home
home/board/models.py
from django.conf import settings from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Topic(models.Model): """话题""" class Meta: verbose_name = "话题" verbose_name_plural = "话题" title = models.CharField(max_length=200, verbose_name="标题") description = models.TextField(verbose_name="说明") # TODO: 下个版本调整这个字段名称,并设置默认值 # is_closed, default=False is_open = models.BooleanField(verbose_name="进行中") closed_at = models.DateTimeField(null=True, blank=True, verbose_name="关闭时间") user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="topics", verbose_name="创建者", ) created_at = models.DateTimeField(auto_now_add=True, verbose_name="发布时间") edited_at = models.DateTimeField(verbose_name="修改时间") is_pin = models.BooleanField(default=False, verbose_name="置顶") def __str__(self): return self.title class Comment(MPTTModel): """评论""" class Meta: verbose_name = "评论" verbose_name_plural = "评论" topic = models.ForeignKey( Topic, on_delete=models.CASCADE, related_name="comments", verbose_name="话题" ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="comments", verbose_name="评论者", ) body = models.TextField(verbose_name="内容") created_at = models.DateTimeField(auto_now_add=True, verbose_name="发布时间") edited_at = models.DateTimeField(auto_now=True, verbose_name="修改时间") parent = TreeForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="children", verbose_name="属于", ) reply_to = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name="repliers", verbose_name="回复给", ) def __str__(self): return self.body[:20]
r0wbrt/codec2
unittest/tcontphase.c
<gh_stars>0 /*---------------------------------------------------------------------------*\ FILE........: tcontphase.c AUTHOR......: <NAME> DATE CREATED: 11/9/09 Test program for developing continuous phase track synthesis algorithm. However while developing this it was discovered that synthesis_mixed() worked just as well. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2009 <NAME> All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ #define N 80 /* frame size */ #define F 160 /* frames to synthesis */ #define P 10 /* LPC order */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "sine.h" #include "dump.h" #include "synth.h" #include "phase.h" int frames; float ak[] = { 1.000000, -1.455836, 1.361841, -0.879267, 0.915985, -1.002202, 0.944103, -0.743094, 1.053356, -0.817491, 0.431222 }; /*---------------------------------------------------------------------------*\ switch_present() Searches the command line arguments for a "switch". If the switch is found, returns the command line argument where it ws found, else returns NULL. \*---------------------------------------------------------------------------*/ int switch_present(sw,argc,argv) char sw[]; /* switch in string form */ int argc; /* number of command line arguments */ char *argv[]; /* array of command line arguments in string form */ { int i; /* loop variable */ for(i=1; i<argc; i++) if (!strcmp(sw,argv[i])) return(i); return 0; } /*---------------------------------------------------------------------------*\ MAIN \*---------------------------------------------------------------------------*/ int main(argc,argv) int argc; char *argv[]; { FILE *fout; short buf[N]; int i,j; int dump; float phi_prev[MAX_AMP]; float Wo_prev, ex_phase, G; //float ak[P+1]; COMP H[MAX_AMP]; float f0; if (argc < 3) { printf("\nusage: %s OutputRawSpeechFile F0\n", argv[0]); exit(1); } /* Output file */ if ((fout = fopen(argv[1],"wb")) == NULL) { printf("Error opening output speech file: %s\n",argv[1]); exit(1); } f0 = atof(argv[2]); dump = switch_present("--dump",argc,argv); if (dump) dump_on(argv[dump+1]); init_decoder(); for(i=0; i<MAX_AMP; i++) phi_prev[i] = 0.0; Wo_prev = 0.0; model.Wo = PI*(f0/4000.0); G = 1000.0; model.L = floor(PI/model.Wo); //aks_to_H(&model, ak, G , H, P); //for(i=1; i<=model.L; i++) model.A[i] = sqrt(H[i].real*H[i].real + H[i].imag*H[i].imag); //printf("L = %d\n", model.L); //model.L = 10; for(i=1; i<=model.L; i++) { model.A[i] = 1000/model.L; model.phi[i] = 0; H[i].real = 1.0; H[i].imag = 0.0; } //ak[0] = 1.0; //for(i=1; i<=P; i++) // ak[i] = 0.0; frames = 0; for(j=0; j<F; j++) { frames++; #ifdef SWAP /* lets make phases bounce around from frame to frame. This could happen if H[m] is varying, for example due to frame to frame Wo variations, or non-stationary speech. Continous model generally results in smooth phase track under these circumstances. */ if (j%2){ H[1].real = 1.0; H[1].imag = 0.0; model.phi[1] = 0.0; } else { H[1].real = 0.0; H[1].imag = 1.0; model.phi[1] = PI/2; } #endif //#define CONT #ifdef CONT synthesise_continuous_phase(Pn, &model, Sn_, 1, &Wo_prev, phi_prev); #else phase_synth_zero_order(5.0, H, &Wo_prev, &ex_phase); synthesise_mixed(Pn,&model,Sn_,1); #endif for(i=0; i<N; i++) buf[i] = Sn_[i]; fwrite(buf,sizeof(short),N,fout); } fclose(fout); if (dump) dump_off(); return 0; }
schnatterer/smeagol
src/main/java/com/cloudogu/smeagol/wiki/domain/PageModifiedEvent.java
package com.cloudogu.smeagol.wiki.domain; /** * Domain event which is fired whenever a page was modified. */ public class PageModifiedEvent { private final Page page; public PageModifiedEvent(Page page) { this.page = page; } public Page getPage() { return page; } }
Ami-Solution/amishop
src/containers/Map/Markers/ShopMarker/index.js
export { default } from './ShopMarker';
usgs/neversink_workflow
source/PEST++/src/libs/Eigen/test/simplicial_cholesky.cpp
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2011 <NAME> <<EMAIL>> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "sparse_solver.h" template<typename T> void test_simplicial_cholesky_T() { SimplicialCholesky<SparseMatrix<T>, Lower> chol_colmajor_lower_amd; SimplicialCholesky<SparseMatrix<T>, Upper> chol_colmajor_upper_amd; SimplicialLLT<SparseMatrix<T>, Lower> llt_colmajor_lower_amd; SimplicialLLT<SparseMatrix<T>, Upper> llt_colmajor_upper_amd; SimplicialLDLT<SparseMatrix<T>, Lower> ldlt_colmajor_lower_amd; SimplicialLDLT<SparseMatrix<T>, Upper> ldlt_colmajor_upper_amd; SimplicialLDLT<SparseMatrix<T>, Lower, NaturalOrdering<int> > ldlt_colmajor_lower_nat; SimplicialLDLT<SparseMatrix<T>, Upper, NaturalOrdering<int> > ldlt_colmajor_upper_nat; check_sparse_spd_solving(chol_colmajor_lower_amd); check_sparse_spd_solving(chol_colmajor_upper_amd); check_sparse_spd_solving(llt_colmajor_lower_amd); check_sparse_spd_solving(llt_colmajor_upper_amd); check_sparse_spd_solving(ldlt_colmajor_lower_amd); check_sparse_spd_solving(ldlt_colmajor_upper_amd); check_sparse_spd_determinant(chol_colmajor_lower_amd); check_sparse_spd_determinant(chol_colmajor_upper_amd); check_sparse_spd_determinant(llt_colmajor_lower_amd); check_sparse_spd_determinant(llt_colmajor_upper_amd); check_sparse_spd_determinant(ldlt_colmajor_lower_amd); check_sparse_spd_determinant(ldlt_colmajor_upper_amd); check_sparse_spd_solving(ldlt_colmajor_lower_nat); check_sparse_spd_solving(ldlt_colmajor_upper_nat); } void test_simplicial_cholesky() { CALL_SUBTEST_1(test_simplicial_cholesky_T<double>()); CALL_SUBTEST_2(test_simplicial_cholesky_T<std::complex<double> >()); }
NeJan2020/kindling
collector/model/subscribe.pb.go
<filename>collector/model/subscribe.pb.go // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: subscribe.proto package model import ( fmt "fmt" proto "github.com/gogo/protobuf/proto" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package type SubEvent struct { Address []byte `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` Pid uint32 `protobuf:"varint,2,opt,name=pid,proto3" json:"pid,omitempty"` Labels []*Label `protobuf:"bytes,4,rep,name=labels,proto3" json:"labels,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *SubEvent) Reset() { *m = SubEvent{} } func (m *SubEvent) String() string { return proto.CompactTextString(m) } func (*SubEvent) ProtoMessage() {} func (*SubEvent) Descriptor() ([]byte, []int) { return fileDescriptor_38d2980c9543da44, []int{0} } func (m *SubEvent) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_SubEvent.Unmarshal(m, b) } func (m *SubEvent) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_SubEvent.Marshal(b, m, deterministic) } func (m *SubEvent) XXX_Merge(src proto.Message) { xxx_messageInfo_SubEvent.Merge(m, src) } func (m *SubEvent) XXX_Size() int { return xxx_messageInfo_SubEvent.Size(m) } func (m *SubEvent) XXX_DiscardUnknown() { xxx_messageInfo_SubEvent.DiscardUnknown(m) } var xxx_messageInfo_SubEvent proto.InternalMessageInfo func (m *SubEvent) GetAddress() []byte { if m != nil { return m.Address } return nil } func (m *SubEvent) GetPid() uint32 { if m != nil { return m.Pid } return 0 } func (m *SubEvent) GetLabels() []*Label { if m != nil { return m.Labels } return nil } type Label struct { Category string `protobuf:"bytes,1,opt,name=category,proto3" json:"category,omitempty"` Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Label) Reset() { *m = Label{} } func (m *Label) String() string { return proto.CompactTextString(m) } func (*Label) ProtoMessage() {} func (*Label) Descriptor() ([]byte, []int) { return fileDescriptor_38d2980c9543da44, []int{1} } func (m *Label) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Label.Unmarshal(m, b) } func (m *Label) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Label.Marshal(b, m, deterministic) } func (m *Label) XXX_Merge(src proto.Message) { xxx_messageInfo_Label.Merge(m, src) } func (m *Label) XXX_Size() int { return xxx_messageInfo_Label.Size(m) } func (m *Label) XXX_DiscardUnknown() { xxx_messageInfo_Label.DiscardUnknown(m) } var xxx_messageInfo_Label proto.InternalMessageInfo func (m *Label) GetCategory() string { if m != nil { return m.Category } return "" } func (m *Label) GetName() string { if m != nil { return m.Name } return "" } func init() { proto.RegisterType((*SubEvent)(nil), "model.SubEvent") proto.RegisterType((*Label)(nil), "model.Label") } func init() { proto.RegisterFile("subscribe.proto", fileDescriptor_38d2980c9543da44) } var fileDescriptor_38d2980c9543da44 = []byte{ // 176 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2f, 0x2e, 0x4d, 0x2a, 0x4e, 0x2e, 0xca, 0x4c, 0x4a, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0xcd, 0xcd, 0x4f, 0x49, 0xcd, 0x51, 0x8a, 0xe1, 0xe2, 0x08, 0x2e, 0x4d, 0x72, 0x2d, 0x4b, 0xcd, 0x2b, 0x11, 0x92, 0xe0, 0x62, 0x4f, 0x4c, 0x49, 0x29, 0x4a, 0x2d, 0x2e, 0x96, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x09, 0x82, 0x71, 0x85, 0x04, 0xb8, 0x98, 0x0b, 0x32, 0x53, 0x24, 0x98, 0x14, 0x18, 0x35, 0x78, 0x83, 0x40, 0x4c, 0x21, 0x15, 0x2e, 0xb6, 0x9c, 0xc4, 0xa4, 0xd4, 0x9c, 0x62, 0x09, 0x16, 0x05, 0x66, 0x0d, 0x6e, 0x23, 0x1e, 0x3d, 0xb0, 0x79, 0x7a, 0x3e, 0x20, 0xc1, 0x20, 0xa8, 0x9c, 0x92, 0x39, 0x17, 0x2b, 0x58, 0x40, 0x48, 0x8a, 0x8b, 0x23, 0x39, 0xb1, 0x24, 0x35, 0x3d, 0xbf, 0xa8, 0x12, 0x6c, 0x36, 0x67, 0x10, 0x9c, 0x2f, 0x24, 0xc4, 0xc5, 0x92, 0x97, 0x98, 0x9b, 0x0a, 0x36, 0x9d, 0x33, 0x08, 0xcc, 0x76, 0x12, 0x8c, 0xe2, 0x07, 0x9b, 0xa7, 0x0f, 0x77, 0x76, 0x12, 0x1b, 0xd8, 0xdd, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x71, 0x42, 0xae, 0x26, 0xca, 0x00, 0x00, 0x00, }
halorgium/rack-client
examples/rubyurl.rb
$:.unshift File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require 'rack/client' require 'json' require 'pp' client = Rack::Client.new('http://rubyurl.com/') client.post('/api/links.json', :website_url => 'http://istwitterdown.com/').body.each do |json| puts JSON.parse(json)['link']['permalink'] end
dingmike/testCnnShop
platform-shop/src/main/java/com/platform/dao/CnnLearnTypeDao.java
<filename>platform-shop/src/main/java/com/platform/dao/CnnLearnTypeDao.java package com.platform.dao; import com.platform.entity.CnnLearnTypeEntity; /** * Dao * * @author admin * @email <EMAIL> * @date 2018-07-04 20:11:47 */ public interface CnnLearnTypeDao extends BaseDao<CnnLearnTypeEntity> { }
francis-pouatcha/forgelab
adpharma/adpharma.server/src/main/java/org/adorsys/adpharma/server/jpa/DeliveryStattisticsDataSearchInput.java
<reponame>francis-pouatcha/forgelab<filename>adpharma/adpharma.server/src/main/java/org/adorsys/adpharma/server/jpa/DeliveryStattisticsDataSearchInput.java package org.adorsys.adpharma.server.jpa; import java.util.Date; public class DeliveryStattisticsDataSearchInput { private Integer years ; private Supplier supplier ; private Date fromDate ; private Date toDate ; private Boolean groupByCip = Boolean.FALSE ; public Integer getYears() { return years; } public void setYears(Integer years) { this.years = years; } public Supplier getDeliverySupplier() { return supplier; } public void setDeliverySupplier(Supplier supplier) { this.supplier = supplier; } public Supplier getSupplier() { return supplier; } public void setSupplier(Supplier supplier) { this.supplier = supplier; } public Date getFromDate() { return fromDate; } public void setFromDate(Date fromDate) { this.fromDate = fromDate; } public Date getToDate() { return toDate; } public void setToDate(Date toDate) { this.toDate = toDate; } public Boolean getGroupByCip() { return groupByCip; } public void setGroupByCip(Boolean groupByCip) { this.groupByCip = groupByCip; } }
AmmarQaseem/CPI-Pipeline-test
scripts/ppi-benchmark/Converters/learning-format-api/src/main/java/org/learningformat/api/JSRE_Tranformer.java
package org.learningformat.api; import jargs.gnu.CmdLineParser; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.learningformat.impl.DefaultElementFactory; import org.learningformat.transform.JSRE_ExampleWriter; import org.learningformat.transform.SvmLightTreeKernelTransformer; import org.learningformat.util.FileHelper; import org.learningformat.util.PorterStemmer; import org.learningformat.xml.CorpusListener; import org.learningformat.xml.Parser; public class JSRE_Tranformer implements CorpusListener { private static String outBaseDir = "jsre-corpus"; private static String inFile; private static String splitDir; private static String corpus; private static String lemmaFile; //"/home/philippe/Desktop/svm/otherMethods/jsre/corpus/out/tst.txt.txp"; static CmdLineParser cmdParser = new CmdLineParser(); static CmdLineParser.Option inFileOption = cmdParser.addStringOption('i', "in"); static CmdLineParser.Option outBaseDirOption = cmdParser.addStringOption('o',"outdir"); static CmdLineParser.Option splitOption = cmdParser.addStringOption('s', "split"); static CmdLineParser.Option lemmaOption = cmdParser.addStringOption('l', "lemma"); static CmdLineParser.Option corpusOption = cmdParser.addStringOption('c', "corpus"); static CmdLineParser.Option stemmerOption = cmdParser.addBooleanOption('\0', "porter"); static CmdLineParser.Option tokenizerOption = cmdParser.addStringOption('t', "tokenizer"); static CmdLineParser.Option skipTrainOption = cmdParser.addBooleanOption('\0', "skip-train"); static int selfIntact; static int intact; static int notSelf; static boolean skipTrain = false; private final Map<String, Integer> folds; //Mapping between folds private final String tokenizer; private final static int desiredFoldsCount = 10; private final Writer[] test = new Writer[desiredFoldsCount]; private final Writer[] train = new Writer[desiredFoldsCount]; private final JSRE_ExampleWriter exampleWriter; /** Pre-computed leamma's. */ protected HashMap<String, String > lemmata; /** Stemmer used if {@link lemmata} is <code>null</code>. If <code>null</code>, the {@link Token#getText()} is used as lemma. */ protected PorterStemmer stemmer; private static boolean doStemming; /** * Implement lemmatization fallback * @author illes * */ public class Lemmatizer { public String lemmatize(String token) { String lemma = null; if (lemmata != null) lemma = lemmata.get(token); else if (stemmer != null) lemma = stemmer.stem(token); // never return null return lemma != null ? lemma : token; } } public static void main(String[] args) throws Exception{ parseArgs(args); File inputFile = new File(inFile); FileHelper.checkFile(inputFile); Reader in = null; Charset encoding = Charset.forName("UTF-8"); //Get corpusName and getFolds... String corpusName = corpus != null ? corpus : inputFile.getName().replaceFirst("\\.xml", ""); //corpusName = corpusName.substring(0, corpusName.indexOf('-'));//Just at the moment Map<String, Integer> folds = SvmLightTreeKernelTransformer.readFolds(splitDir, corpusName/*, 0*/);// Last parameter not necessary? FileHelper.checkDir(new File(outBaseDir)); File outDir = new File(new File(outBaseDir), corpusName); // System.out.println(baseDir + File.separator + corpusName + "-folds"); outDir.mkdirs(); FileHelper.checkDir(outDir); final String tokenizer = (String) cmdParser.getOptionValue(tokenizerOption, "split" /*LearningFormatConstants.CHARNIAK_LEASE_TOKENIZER*/); JSRE_Tranformer ec = new JSRE_Tranformer( tokenizer, folds, outDir, lemmaFile, doStemming); in = FileHelper.getBufferedFileReader(inputFile, encoding); Parser parser = new Parser( Collections.singleton(tokenizer), Collections.<String>emptySet(), Collections.<String>emptySet(), new DefaultElementFactory(), ec); parser.setImmediatelyRemoveDocuments(true); // be GC friendly parser.process(in); in.close(); } //Here happens the magic private void close() throws IOException { IOException error = null; for (Writer w : test) { try { w.close(); } catch (IOException e) { error = e; } } for (Writer w : train) { try { w.close(); } catch (IOException e) { error = e; } } if (error != null) throw error; } //Flush all writers @Override public void endCorpus() { System.out.println(selfIntact +"\t" +intact +"\t" +notSelf); try { close(); } catch (Exception e) { throw new RuntimeException("Error closing some writers", e); } } @Override public void endDocument() { } //Here happens the magic @Override public void processSentence(Sentence sentence) { List<Pair> pairs = sentence.getAllPairs(); if (pairs != null) { //Has the sentence a pair Set<String> uniquePairs = new HashSet<String>(pairs.size()); //For each Pair: for (Pair pair : pairs) { intact++; String e1Id = pair.getE1().getId(); String e2Id = pair.getE2().getId(); if (!e1Id.equals(e2Id)) { // Only no self-interacting pairs (makes little sense on tree and other structures) String key = e1Id.compareTo(e2Id) > 0 ? e1Id + '|' + e2Id : e2Id + '|' + e1Id; // Generates a unique key. notSelf++; if (!uniquePairs.contains(key)) { uniquePairs.add(key); String docid = sentence.getDocument().getId(); Integer fold = folds.get(docid); //This document is used in which fold? if (fold == null) { throw new IllegalStateException( "no fold found for doc '" + docid + "'"); } try { // exampleWriter.write(pair, sentence, writers[fold.intValue()]);//Exception String example = exampleWriter.getOutput(pair, sentence, new Lemmatizer()); test[fold.intValue()].append(example); for(int j=0; j<desiredFoldsCount; j++) if(fold.intValue()!=j) train[j].append(example); } catch (IOException e) { throw new RuntimeException("Error while writing JSRE test/train example.", e); } } } else selfIntact++; } } } @Override public void startCorpus(Corpus corpus) { // do nothing } @Override public void startDocument(Document document) { } //Class constructor public JSRE_Tranformer(String tokenizer, Map<String, Integer> folds, File dirOut, String lemma, boolean doPorterStemming) throws FileNotFoundException { super(); this.tokenizer = tokenizer; this.folds = folds; if (doPorterStemming) stemmer = new PorterStemmer(); if (lemma != null) lemmata = Lemma.readLemma(lemma); final Charset encoding = Charset.forName("UTF-8"); this.exampleWriter = createExampleWriter(); // create output files for (int i = 0; i < test.length; i++) { test[i] = FileHelper.getBufferedFileWriter(new File(dirOut, "test" + i + ".txt"), encoding); train[i] = skipTrain ? new FileHelper.NullWriter() : FileHelper.getBufferedFileWriter(new File(dirOut, "train" + i + ".txt"), encoding); } } protected JSRE_ExampleWriter createExampleWriter() { return new JSRE_ExampleWriter(tokenizer); } private static void printUsage() { System.err.println( "Usage:\n" + "\t[-i, --in ] FILE Input file\n" + "\t[-o, --outdir ] DIR Output dir\n" + "\t[-s, --split ] DIR Directory of splits\n" + "\t[-t, --tokenizer ] NAME Tokenizer (for POS tags) \n" + "\t[ --skip-train] Do not write train examples\n" + "\t[-c, --corpus ] NAME Corpus name (should match file and folders)\n" + "\t[-l, --lemma ] FILE Precomputed lemmata\n" + "\t[-t, --tokenizer ] NAME Tokenizer (for POS tags) \n" + "\t[ --porter ] Use stemmer\n" ); } private static void parseArgs(String args[]) { try { cmdParser.parse(args); } catch ( CmdLineParser.OptionException e ) { System.err.print(e.getMessage()); e.printStackTrace(); printUsage(); System.exit(2); } inFile = (String) cmdParser.getOptionValue(inFileOption, inFile); outBaseDir = (String) cmdParser.getOptionValue(outBaseDirOption, outBaseDir); splitDir = (String) cmdParser.getOptionValue(splitOption, splitDir); lemmaFile = (String) cmdParser.getOptionValue(lemmaOption, lemmaFile); doStemming = (Boolean) cmdParser.getOptionValue(stemmerOption, Boolean.FALSE); corpus = (String) cmdParser.getOptionValue(corpusOption, null); skipTrain = (Boolean) cmdParser.getOptionValue(skipTrainOption, Boolean.FALSE); if (inFile == null || outBaseDir == null || splitDir == null) { System.err.println("A required argument (corpus, in, outdir, split) is missing and has no default value."); printUsage(); System.exit(2); } } }
crowdbotics-apps/royal-cloud-33498
utils/ValidateEmail.js
export const validateEmail = value => { const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; const isValid = pattern.test(String(value).toLowerCase()); return isValid; };
mathewjames-dev/NodeJSMultiplayerGame
app/database/authQueries.js
/*** * * Back-end Auth Database Component File * ***/ const bcrypt = require('bcrypt'); const Database = require('./database'); const UserModel = require('./models/user'); const InventoryModel = require('./models/inventory'); const saltRounds = 10; class AuthQueries extends Database { constructor() { super(); } async retrieveUser(username) { try { const user = UserModel.findOne({ 'username': username }).exec(); return user; } catch (err) { console.error(err); } } async createUser(data, callback) { bcrypt.hash(data.password, saltRounds, (err, hash) => { var userModel = new UserModel({ username: data.username, password: <PASSWORD>, firstLogin: true, health: 100, maxHealth: 100, mapId: 2, spriteId: 1 }); userModel.save((err, user) => { if (err) callback(false); var inventoryModel = new InventoryModel({ userId: user._id, maxSize: 8 }).save((err, inventory) => { if (err) throw Error; callback(user); }) }) }); } async authenticateUser(data, callback) { try { let user = await this.retrieveUser(data.username); if (user) { bcrypt.compare(data.password, user.password, (error, response) => { if (response) { callback(user); } else { callback(false); } }); } else { console.error('Unable to retrieve user for that username from the database.'); throw new Error; } } catch (err) { console.error(err); } } } module.exports = AuthQueries;
freebird-airlines/WhirlyGlobe
android/library/WhirlyGlobeLib/src/BaseInfo.cpp
<filename>android/library/WhirlyGlobeLib/src/BaseInfo.cpp /* * BaseInfo.mm * WhirlyGlobeLib * * Created by <NAME> on 7/6/15. * Copyright 2011-2016 mousebird consulting * * 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 "BaseInfo.h" #import "Drawable.h" #import "BasicDrawable.h" #import "BasicDrawableInstance.h" using namespace WhirlyKit; using namespace Eigen; namespace WhirlyKit { BaseInfo::BaseInfo() : minVis(DrawVisibleInvalid), maxVis(DrawVisibleInvalid), minVisBand(DrawVisibleInvalid), maxVisBand(DrawVisibleInvalid), minViewerDist(DrawVisibleInvalid), maxViewerDist(DrawVisibleInvalid), viewerCenter(DrawVisibleInvalid,DrawVisibleInvalid,DrawVisibleInvalid), fade(0.0), fadeIn(0.0), fadeOut(0.0), fadeOutTime(0.0), drawPriority(0), drawOffset(0.0), enable(true), startEnable(0.0), endEnable(0.0), programID(EmptyIdentity) { } BaseInfo::BaseInfo(const Dictionary &dict) { minVis = dict.getDouble("minVis",DrawVisibleInvalid); maxVis = dict.getDouble("maxVis",DrawVisibleInvalid); minVisBand = dict.getDouble("minVisBand",DrawVisibleInvalid); maxVisBand = dict.getDouble("maxVisBand",DrawVisibleInvalid); minViewerDist = dict.getDouble("minviewerdist",DrawVisibleInvalid); maxViewerDist = dict.getDouble("maxviewerdist",DrawVisibleInvalid); viewerCenter.x() = dict.getDouble("viewablecenterx",DrawVisibleInvalid); viewerCenter.y() = dict.getDouble("viewablecentery",DrawVisibleInvalid); viewerCenter.z() = dict.getDouble("viewablecenterz",DrawVisibleInvalid); fade = dict.getDouble("fade",0.0); fadeIn = fade; fadeOut = fade; fadeIn = dict.getDouble("fadein",fadeIn); fadeOut = dict.getDouble("fadeout",fadeOut); fadeOutTime = dict.getDouble("fadeouttime",0.0); drawPriority = dict.getInt("priority",0); drawPriority = dict.getInt("drawPriority",drawPriority); drawOffset = dict.getDouble("drawOffset",0.0); enable = dict.getBool("enable",true); startEnable = dict.getDouble("enablestart",0.0); endEnable = dict.getDouble("enableend",0.0); SimpleIdentity shaderID = dict.getInt("shader",EmptyIdentity); programID = dict.getInt("program",shaderID); // Note: Porting // Uniforms to be passed to shader #if 0 // Note: Should add the rest of the types NSDictionary *uniformDict = desc[@"shaderuniforms"]; if (uniformDict) { for (NSString *key in uniformDict.allKeys) { id val = uniformDict[key]; if ([val isKindOfClass:[NSNumber class]]) { SingleVertexAttribute valAttr; valAttr.name = [key cStringUsingEncoding:NSASCIIStringEncoding]; NSNumber *num = val; valAttr.type = BDFloatType; valAttr.data.floatVal = [val floatValue]; _uniforms.insert(valAttr); } else if ([val isKindOfClass:[UIColor class]]) { SingleVertexAttribute valAttr; valAttr.name = [key cStringUsingEncoding:NSASCIIStringEncoding]; UIColor *col = val; valAttr.type = BDChar4Type; RGBAColor color = [col asRGBAColor]; valAttr.data.color[0] = color.r; valAttr.data.color[1] = color.g; valAttr.data.color[2] = color.b; valAttr.data.color[3] = color.a; _uniforms.insert(valAttr); } } } #endif } // Really Android? Really? template <typename T> std::string to_string(T value) { std::ostringstream os ; os << value ; return os.str() ; } std::string BaseInfo::toString() { std::string outStr = (std::string)"minVis = " + to_string(minVis) + ";" + " maxVis = " + to_string(maxVis) + ";" + " minVisBand = " + to_string(minVisBand) + ";" + " maxVisBand = " + to_string(maxVisBand) + ";" + " minViewerDist = " + to_string(minViewerDist) + ";" + " maxViewerDist = " + to_string(maxViewerDist) + ";" + " viewerCenter = (" + to_string(viewerCenter.x()) + "," + to_string(viewerCenter.y()) + "," + to_string(viewerCenter.z()) + ");" + " drawOffset = " + to_string(drawOffset) + ";" + " drawPriority = " + to_string(drawPriority) + ";" + " enable = " + (enable ? "yes" : "no") + ";" + " fade = " + to_string(fade) + ";" + " fadeIn = " + to_string(fadeIn) + ";" + " fadeOut = " + to_string(fadeOut) + ";" + " fadeOutTime = " + to_string(fadeOutTime) + ";" + " startEnable = " + to_string(startEnable) + ";" + " endEnable = " + to_string(endEnable) + ";" + " programID = " + to_string(programID) + ";"; return outStr; } void BaseInfo::setupBasicDrawable(BasicDrawable *drawable) const { drawable->setOnOff(enable); drawable->setEnableTimeRange(startEnable, endEnable); drawable->setDrawPriority(drawPriority); drawable->setVisibleRange(minVis,maxVis); drawable->setViewerVisibility(minViewerDist,maxViewerDist,viewerCenter); drawable->setProgram(programID); drawable->setUniforms(uniforms); } void BaseInfo::setupBasicDrawableInstance(BasicDrawableInstance *drawInst) { drawInst->setEnable(enable); drawInst->setEnableTimeRange(startEnable, endEnable); drawInst->setDrawPriority(drawPriority); drawInst->setVisibleRange(minVis,maxVis); drawInst->setViewerVisibility(minViewerDist,maxViewerDist,viewerCenter); drawInst->setUniforms(uniforms); } }
parafernalia/parafa-cookiecutter-react
src/reducers/homeReducer.js
import initialState from './initialState' import * as types from '../actions/actionTypes' export default function homeReducer(state = initialState.home, action) { switch (action.type) { case types.DATA_REQUEST: return { ...state, error: null } case types.DATA_SUCCESS: return { ...state, data: action.data.splice(0, 10) } case types.DATA_FAILURE: return { ...state, error: action.error } default: return state } }
smlobo/anet
src/main/java/mil/dds/anet/database/mappers/PersonMapper.java
<reponame>smlobo/anet package mil.dds.anet.database.mappers; import java.sql.ResultSet; import java.sql.SQLException; import mil.dds.anet.beans.Person; import mil.dds.anet.beans.Person.PersonStatus; import mil.dds.anet.beans.Person.Role; import mil.dds.anet.beans.Position; import mil.dds.anet.utils.DaoUtils; import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.statement.StatementContext; public class PersonMapper implements RowMapper<Person> { @Override public Person map(ResultSet rs, StatementContext ctx) throws SQLException { Person p = fillInFields(new Person(), rs); if (MapperUtils.containsColumnNamed(rs, "positions_uuid")) { p.setPosition(PositionMapper.fillInFields(new Position(), rs)); } if (MapperUtils.containsColumnNamed(rs, "totalCount")) { ctx.define("totalCount", rs.getInt("totalCount")); } return p; } public static <T extends Person> T fillInFields(T a, ResultSet r) throws SQLException { // This hits when we do a join but there's no Person record. if (r.getObject("people_uuid") == null) { return null; } DaoUtils.setCommonBeanFields(a, r, "people"); a.setName(r.getString("people_name")); a.setStatus(MapperUtils.getEnumIdx(r, "people_status", PersonStatus.class)); a.setRole(MapperUtils.getEnumIdx(r, "people_role", Role.class)); a.setEmailAddress(r.getString("people_emailAddress")); a.setPhoneNumber(r.getString("people_phoneNumber")); a.setCountry(r.getString("people_country")); a.setGender(r.getString("people_gender")); a.setEndOfTourDate(DaoUtils.getInstantAsLocalDateTime(r, "people_endOfTourDate")); a.setRank(r.getString("people_rank")); a.setBiography(r.getString("people_biography")); a.setDomainUsername(r.getString("people_domainUsername")); a.setPendingVerification(r.getBoolean("people_pendingVerification")); return a; } }
cragkhit/elasticsearch
references/bcb_chosen_clones/selected#2391775#310#320.java
void write(OutputStream os) throws IOException { ZipOutputStream zos = new ZipOutputStream(os); ListIterator iterator = entryList.listIterator(); while (iterator.hasNext()) { Entry entry = (Entry) iterator.next(); ZipEntry ze = entry.zipEntry; zos.putNextEntry(ze); zos.write(entry.bytes); } zos.close(); }
FredyKcrez/JAVA
G8_Herencia1_EmpleadoComision/src/ejemploherencia1/PruebaEmpleadoPorComision.java
/* * Guía de laboratorio 08 - Programación 3 - 2012 * Ejemplo 1: Herencia de la clase Object. */ package ejemploherencia1; /** * @date 02/07/2018 * @author <NAME> */ public class PruebaEmpleadoPorComision { public static void main(String[] args) { EmpleadoPorComision empleado = new EmpleadoPorComision( // crea instancia de objeto EmpleadoPorComision "Juan", "Perez", "222-22-2222", 10000, .06 ); // obtiene datos del empleado por comisión System.out.println( "Informacion del empleado obtenida por los" + " metodos set: \n" ); System.out.printf( "%s %s\n", "El primer nombre es", empleado.getPrimerNombre() ); System.out.printf( "%s %s\n", "El apellido paterno es", empleado.getApellidoPaterno() ); System.out.printf( "%s %s\n", "El numero de seguro social es", empleado.getNumeroSeguroSocial() ); System.out.printf( "%s %.2f\n", "Las ventas brutas son", empleado.getVentasTotales() ); System.out.printf( "%s %.2f\n", "La tarifa de comision es", empleado.getTarifaComision() ); empleado.setVentasTotales( 500 ); // establece las ventas Brutas empleado.setTarifaComision( .1 ); // establece la tarifa de comisión System.out.printf( "\n%s:\n\n%s\n", "Informacion actualizada del " + "empleado, obtenida mediante toString", empleado ); } }
m-socha/sana.protocol_builder
src-backbone/app/js/collections/abstractElements.js
const ElementCollection = require('collections/elements'); const AbstractElement = require('models/abstractElement'); module.exports = ElementCollection.extend({ model: AbstractElement, });
bczhc2/test
app/src/main/java/pers/zhc/tools/clipboard/Clip.java
<reponame>bczhc2/test package pers.zhc.tools.clipboard; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.os.Bundle; import androidx.annotation.Nullable; import android.widget.Button; import android.widget.EditText; import pers.zhc.tools.BaseActivity; import pers.zhc.tools.R; import pers.zhc.tools.utils.ToastUtils; import java.util.Objects; public class Clip extends BaseActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.clip_activity); Button btn = findViewById(R.id.copy); EditText et = findViewById(R.id.copy_et); btn.setOnClickListener(v -> { String s = et.getText().toString(); ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { ClipData cd = ClipData.newHtmlText("", getString(R.string.html_content), s); try { Objects.requireNonNull(cm).setPrimaryClip(cd); ToastUtils.show(this, getString(R.string.copying_success)); } catch (Exception e) { e.printStackTrace(); ToastUtils.show(this, R.string.copying_failure); } } else { ToastUtils.show(this, getString(R.string.html_clipboard_unsupported)); } }); } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(0, R.anim.slide_out_bottom); } }
foteiniBeligianni/samoa
samoa-threads/src/test/java/com/yahoo/labs/samoa/topology/impl/ThreadsProcessingItemTest.java
<reponame>foteiniBeligianni/samoa<filename>samoa-threads/src/test/java/com/yahoo/labs/samoa/topology/impl/ThreadsProcessingItemTest.java /* * #%L * SAMOA * %% * Copyright (C) 2013 Yahoo! Inc. * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.yahoo.labs.samoa.topology.impl; import static org.junit.Assert.*; import java.util.List; import java.util.concurrent.ExecutorService; import mockit.Expectations; import mockit.Mocked; import mockit.NonStrictExpectations; import mockit.Tested; import org.junit.Before; import org.junit.Test; import com.yahoo.labs.samoa.core.ContentEvent; import com.yahoo.labs.samoa.core.Processor; import com.yahoo.labs.samoa.utils.PartitioningScheme; import com.yahoo.labs.samoa.utils.StreamDestination; /** * @author <NAME> * */ public class ThreadsProcessingItemTest { @Tested private ThreadsProcessingItem pi; @Mocked private ThreadsEngine unused; @Mocked private ExecutorService threadPool; @Mocked private ThreadsEventRunnable task; @Mocked private Processor processor, processorReplica; @Mocked private ThreadsStream stream; @Mocked private StreamDestination destination; @Mocked private ContentEvent event; private final int parallelism = 4; private final int counter = 2; private ThreadsProcessingItemInstance instance; @Before public void setUp() throws Exception { new NonStrictExpectations() { { processor.newProcessor(processor); result=processorReplica; } }; pi = new ThreadsProcessingItem(processor, parallelism); } @Test public void testConstructor() { assertSame("Processor was not set correctly.",processor,pi.getProcessor()); assertEquals("Parallelism was not set correctly.",parallelism,pi.getParallelism(),0); } @Test public void testConnectInputShuffleStream() { new Expectations() { { destination = new StreamDestination(pi, parallelism, PartitioningScheme.SHUFFLE); stream.addDestination(destination); } }; pi.connectInputShuffleStream(stream); } @Test public void testConnectInputKeyStream() { new Expectations() { { destination = new StreamDestination(pi, parallelism, PartitioningScheme.GROUP_BY_KEY); stream.addDestination(destination); } }; pi.connectInputKeyStream(stream); } @Test public void testConnectInputAllStream() { new Expectations() { { destination = new StreamDestination(pi, parallelism, PartitioningScheme.BROADCAST); stream.addDestination(destination); } }; pi.connectInputAllStream(stream); } @Test public void testSetupInstances() { new Expectations() { { for (int i=0; i<parallelism; i++) { processor.newProcessor(processor); result=processor; processor.onCreate(anyInt); } } }; pi.setupInstances(); List<ThreadsProcessingItemInstance> instances = pi.getProcessingItemInstances(); assertNotNull("List of PI instances is null.",instances); assertEquals("Number of instances does not match parallelism.",parallelism,instances.size(),0); for(int i=0; i<instances.size();i++) { assertNotNull("Instance "+i+" is null.",instances.get(i)); assertEquals("Instance "+i+" is not a ThreadsWorkerProcessingItem.",ThreadsProcessingItemInstance.class,instances.get(i).getClass()); } } @Test(expected=IllegalStateException.class) public void testProcessEventError() { pi.processEvent(event, counter); } @Test public void testProcessEvent() { new Expectations() { { for (int i=0; i<parallelism; i++) { processor.newProcessor(processor); result=processor; processor.onCreate(anyInt); } } }; pi.setupInstances(); instance = pi.getProcessingItemInstances().get(counter); new NonStrictExpectations() { { ThreadsEngine.getThreadWithIndex(anyInt); result=threadPool; } }; new Expectations() { { task = new ThreadsEventRunnable(instance, event); threadPool.submit(task); } }; pi.processEvent(event, counter); } }
hellolliu/behave-students
behave-db/src/main/java/org/java/behave/db/dao/BehaveTeacherQuestionMapper.java
package org.java.behave.db.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import org.java.behave.db.domain.BehaveTeacherQuestion; import org.java.behave.db.domain.BehaveTeacherQuestionExample; public interface BehaveTeacherQuestionMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated */ long countByExample(BehaveTeacherQuestionExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated */ int deleteByExample(BehaveTeacherQuestionExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated */ int deleteByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated */ int insert(BehaveTeacherQuestion record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated */ int insertSelective(BehaveTeacherQuestion record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ BehaveTeacherQuestion selectOneByExample(BehaveTeacherQuestionExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ BehaveTeacherQuestion selectOneByExampleSelective(@Param("example") BehaveTeacherQuestionExample example, @Param("selective") BehaveTeacherQuestion.Column ... selective); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ List<BehaveTeacherQuestion> selectByExampleSelective(@Param("example") BehaveTeacherQuestionExample example, @Param("selective") BehaveTeacherQuestion.Column ... selective); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated */ List<BehaveTeacherQuestion> selectByExample(BehaveTeacherQuestionExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ BehaveTeacherQuestion selectByPrimaryKeySelective(@Param("id") Integer id, @Param("selective") BehaveTeacherQuestion.Column ... selective); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated */ BehaveTeacherQuestion selectByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ BehaveTeacherQuestion selectByPrimaryKeyWithLogicalDelete(@Param("id") Integer id, @Param("andLogicalDeleted") boolean andLogicalDeleted); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated */ int updateByExampleSelective(@Param("record") BehaveTeacherQuestion record, @Param("example") BehaveTeacherQuestionExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated */ int updateByExample(@Param("record") BehaveTeacherQuestion record, @Param("example") BehaveTeacherQuestionExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated */ int updateByPrimaryKeySelective(BehaveTeacherQuestion record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated */ int updateByPrimaryKey(BehaveTeacherQuestion record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ int logicalDeleteByExample(@Param("example") BehaveTeacherQuestionExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table behave_teacher_question * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ int logicalDeleteByPrimaryKey(Integer id); }
zealoussnow/chromium
ui/ozone/platform/wayland/host/shell_object_factory.cc
<filename>ui/ozone/platform/wayland/host/shell_object_factory.cc // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/ozone/platform/wayland/host/shell_object_factory.h" #include "base/logging.h" #include "ui/ozone/platform/wayland/host/wayland_connection.h" #include "ui/ozone/platform/wayland/host/xdg_popup_wrapper_impl.h" #include "ui/ozone/platform/wayland/host/xdg_surface_wrapper_impl.h" #include "ui/ozone/platform/wayland/host/xdg_toplevel_wrapper_impl.h" #include "ui/ozone/platform/wayland/host/zxdg_popup_v6_wrapper_impl.h" #include "ui/ozone/platform/wayland/host/zxdg_surface_v6_wrapper_impl.h" #include "ui/ozone/platform/wayland/host/zxdg_toplevel_v6_wrapper_impl.h" namespace ui { ShellObjectFactory::ShellObjectFactory() = default; ShellObjectFactory::~ShellObjectFactory() = default; std::unique_ptr<ShellToplevelWrapper> ShellObjectFactory::CreateShellToplevelWrapper(WaylandConnection* connection, WaylandWindow* wayland_window) { if (connection->shell()) { auto surface = std::make_unique<XDGSurfaceWrapperImpl>(wayland_window, connection); if (!surface->Initialize()) return nullptr; auto toplevel = std::make_unique<XDGToplevelWrapperImpl>( std::move(surface), wayland_window, connection); return toplevel->Initialize() ? std::move(toplevel) : nullptr; } else if (connection->shell_v6()) { auto surface = std::make_unique<ZXDGSurfaceV6WrapperImpl>(wayland_window, connection); if (!surface->Initialize()) return nullptr; auto toplevel = std::make_unique<ZXDGToplevelV6WrapperImpl>( std::move(surface), wayland_window, connection); return toplevel->Initialize() ? std::move(toplevel) : nullptr; } LOG(WARNING) << "Shell protocol is not available."; return nullptr; } std::unique_ptr<ShellPopupWrapper> ShellObjectFactory::CreateShellPopupWrapper( WaylandConnection* connection, WaylandWindow* wayland_window, const ShellPopupParams& params) { if (connection->shell()) { auto surface = std::make_unique<XDGSurfaceWrapperImpl>(wayland_window, connection); if (!surface->Initialize()) return nullptr; auto popup = std::make_unique<XDGPopupWrapperImpl>( std::move(surface), wayland_window, connection); return popup->Initialize(params) ? std::move(popup) : nullptr; } else if (connection->shell_v6()) { auto surface = std::make_unique<ZXDGSurfaceV6WrapperImpl>(wayland_window, connection); if (!surface->Initialize()) return nullptr; auto popup = std::make_unique<ZXDGPopupV6WrapperImpl>( std::move(surface), wayland_window, connection); return popup->Initialize(params) ? std::move(popup) : nullptr; } LOG(WARNING) << "Shell protocol is not available."; return nullptr; } } // namespace ui
ericsorenson/ef-cms
web-client/src/presenter/computeds/FeatureFlags/featureFlagHelper.test.js
<reponame>ericsorenson/ef-cms import { applicationContextForClient as applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { featureFlagHelper as featureFlagHelperComputed } from './featureFlagHelper'; import { runCompute } from 'cerebral/test'; import { withAppContextDecorator } from '../../../withAppContext'; describe('featureFlagHelper', () => { describe('isSearchEnabled', () => { it('returns isSearchEnabled true when the advanced_document_search feature is enabled', () => { applicationContext.isFeatureEnabled.mockReturnValue(true); const featureFlagHelper = withAppContextDecorator( featureFlagHelperComputed, { ...applicationContext, }, ); expect(runCompute(featureFlagHelper, {})).toMatchObject({ isSearchEnabled: true, }); }); it('returns isSearchEnabled false when the advanced_document_search is NOT enabled', () => { applicationContext.isFeatureEnabled.mockReturnValue(false); const featureFlagHelper = withAppContextDecorator( featureFlagHelperComputed, { ...applicationContext, }, ); expect(runCompute(featureFlagHelper, {})).toMatchObject({ isSearchEnabled: false, }); }); }); });
jsoagger/transdev-base-reactui-template
template/src/_components/Wizard/Wizard.js
<filename>template/src/_components/Wizard/Wizard.js import React from 'react'; import { Modal } from 'react-bootstrap' import Button from 'react-bootstrap/Button' /** * */ class Wizard extends React.Component{ constructor(props){ super(props); this.state = { modalShow: false, } this.hideWizard = this.hideWizard.bind(this); this.setModalShow = this.setModalShow.bind(this); } setModalShow(val){ if(val === false){ this.hideWizard() } this.setState({ modalShow: val }) } hideWizard(){ if(this.props.onWizardHide){ this.props.onWizardHide() } } modal(){ } render(){ var buttonIconComp = this.props.buttonIconComp ? this.props.buttonIconComp : <i className={this.props.buttonIcon}>&nbsp;</i> return ( <> <Button disabled={this.props.disabled} block={this.props.buttonBlock} hidden={this.props.hideButtonIf} onClick={() => this.setModalShow(true)}> {buttonIconComp} {this.props.buttonTitle} </Button> <MyVerticallyCenteredModal {...this.props} show={this.state.modalShow} onHide={() => this.setModalShow(false)}/> </> ); } } export default Wizard; function MyVerticallyCenteredModal(props) { var content = '<p>No content</p>' var size = props.dialogSize ? props.dialogSize : 'lg' var hideFooter = props.hideFooter === true; var hideHeader = props.hideHeader === true; if(props.dialogContentProvider){ content = props.dialogContentProvider(props.onHide, props.additionalParams) } return ( <Modal {...props} centered size={size} dialogClassName={props.dialogClassName} aria-labelledby="contained-modal-title-vcenter" scrollable="true"> <Modal.Header closeButton> <h3>{props.dialogTitle}</h3> </Modal.Header> <Modal.Body>{content}</Modal.Body> {!hideFooter && <Modal.Footer> <Button variant="secondary" onClick={props.onHide}>Close</Button> </Modal.Footer> } </Modal> ); }
TaoReiches/Tao
Game/BattleLogic/TW_UserDataDefine.h
#pragma once /********************************************** * Author: <NAME> Copyright reserved * Contact: <EMAIL> **********************************************/ enum class UserDataKey { UDK_NONE, UDK_MonsterAI, UDK_MonsterAITime, UDK_MonsterPosX, UDK_MonsterPosY, UDK_MonsterReturn, };
smsubham/Data-Structure-Algorithms-Questions
Data Structure/Binary Tree/1161. Maximum Level Sum of a Binary Tree - BFS.py
<filename>Data Structure/Binary Tree/1161. Maximum Level Sum of a Binary Tree - BFS.py #https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxLevelSum(self, root: Optional[TreeNode]) -> int: maxValue,level,maxLevel = -float('inf'),0,0 queue = collections.deque() queue.append(root) while queue: level +=1 currentLevelSum =0 for _ in range(len(queue)): node = queue.popleft() currentLevelSum += node.val if node.left: queue.append(node.left) if node.right: queue.append(node.right) if maxValue < currentLevelSum: maxValue,maxLevel = currentLevelSum, level return maxLevel
SeanShubin/parser
domain/src/main/scala/com/seanshubin/parser/domain/SequenceRule.scala
package com.seanshubin.parser.domain import com.seanshubin.parser.domain.MatchResult.{MatchFailure, MatchSuccess} import com.seanshubin.parser.domain.ParseTree.ParseTreeBranch case class SequenceRule[A](ruleLookup: RuleLookup[A], thisRuleName: String, ruleNames: String*) extends Rule[A] { override def apply(cursor: Cursor[RowCol[A]]): MatchResult[A] = { def loop(soFar: List[MatchSuccess[A]], remaining: List[String], cursor: Cursor[RowCol[A]]): List[MatchResult[A]] = { if (remaining.isEmpty) soFar else { val rule = ruleLookup.lookupRuleByName(remaining.head) val matchResult = rule.apply(cursor) matchResult match { case x: MatchSuccess[A] => loop(x :: soFar, remaining.tail, x.cursor) case x: MatchFailure[A] => List(x) } } } val allResults = loop(Nil, ruleNames.toList, cursor) allResults.head match { case MatchSuccess(newCursor, _) => val children = allResults.flatMap { case MatchSuccess(_, parseTree) => Some(parseTree) case _ => None } MatchSuccess(newCursor, ParseTreeBranch(thisRuleName, children.reverse)) case x: MatchFailure[A] => val sequenceString = ruleNames.mkString(", ") MatchFailure(cursor, thisRuleName, s"expected sequence: $sequenceString") } } }
polivbr/pulumi-azure-native
sdk/go/azure/timeseriesinsights/gen1Environment.go
<gh_stars>0 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package timeseriesinsights import ( "context" "reflect" "github.com/pkg/errors" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" ) // An environment is a set of time-series data available for query, and is the top level Azure Time Series Insights resource. Gen1 environments have data retention limits. // API Version: 2020-05-15. type Gen1Environment struct { pulumi.CustomResourceState // The time the resource was created. CreationTime pulumi.StringOutput `pulumi:"creationTime"` // The fully qualified domain name used to access the environment data, e.g. to query the environment's events or upload reference data for the environment. DataAccessFqdn pulumi.StringOutput `pulumi:"dataAccessFqdn"` // An id used to access the environment data, e.g. to query the environment's events or upload reference data for the environment. DataAccessId pulumi.StringOutput `pulumi:"dataAccessId"` // ISO8601 timespan specifying the minimum number of days the environment's events will be available for query. DataRetentionTime pulumi.StringOutput `pulumi:"dataRetentionTime"` // The kind of the environment. // Expected value is 'Gen1'. Kind pulumi.StringOutput `pulumi:"kind"` // Resource location Location pulumi.StringOutput `pulumi:"location"` // Resource name Name pulumi.StringOutput `pulumi:"name"` // The list of event properties which will be used to partition data in the environment. Currently, only a single partition key property is supported. PartitionKeyProperties TimeSeriesIdPropertyResponseArrayOutput `pulumi:"partitionKeyProperties"` // Provisioning state of the resource. ProvisioningState pulumi.StringOutput `pulumi:"provisioningState"` // The sku determines the type of environment, either Gen1 (S1 or S2) or Gen2 (L1). For Gen1 environments the sku determines the capacity of the environment, the ingress rate, and the billing rate. Sku SkuResponseOutput `pulumi:"sku"` // An object that represents the status of the environment, and its internal state in the Time Series Insights service. Status EnvironmentStatusResponseOutput `pulumi:"status"` // The behavior the Time Series Insights service should take when the environment's capacity has been exceeded. If "PauseIngress" is specified, new events will not be read from the event source. If "PurgeOldData" is specified, new events will continue to be read and old events will be deleted from the environment. The default behavior is PurgeOldData. StorageLimitExceededBehavior pulumi.StringPtrOutput `pulumi:"storageLimitExceededBehavior"` // Resource tags Tags pulumi.StringMapOutput `pulumi:"tags"` // Resource type Type pulumi.StringOutput `pulumi:"type"` } // NewGen1Environment registers a new resource with the given unique name, arguments, and options. func NewGen1Environment(ctx *pulumi.Context, name string, args *Gen1EnvironmentArgs, opts ...pulumi.ResourceOption) (*Gen1Environment, error) { if args == nil { return nil, errors.New("missing one or more required arguments") } if args.DataRetentionTime == nil { return nil, errors.New("invalid value for required argument 'DataRetentionTime'") } if args.Kind == nil { return nil, errors.New("invalid value for required argument 'Kind'") } if args.ResourceGroupName == nil { return nil, errors.New("invalid value for required argument 'ResourceGroupName'") } if args.Sku == nil { return nil, errors.New("invalid value for required argument 'Sku'") } args.Kind = pulumi.String("Gen1") aliases := pulumi.Aliases([]pulumi.Alias{ { Type: pulumi.String("azure-nextgen:timeseriesinsights:Gen1Environment"), }, { Type: pulumi.String("azure-native:timeseriesinsights/v20170228preview:Gen1Environment"), }, { Type: pulumi.String("azure-nextgen:timeseriesinsights/v20170228preview:Gen1Environment"), }, { Type: pulumi.String("azure-native:timeseriesinsights/v20171115:Gen1Environment"), }, { Type: pulumi.String("azure-nextgen:timeseriesinsights/v20171115:Gen1Environment"), }, { Type: pulumi.String("azure-native:timeseriesinsights/v20180815preview:Gen1Environment"), }, { Type: pulumi.String("azure-nextgen:timeseriesinsights/v20180815preview:Gen1Environment"), }, { Type: pulumi.String("azure-native:timeseriesinsights/v20200515:Gen1Environment"), }, { Type: pulumi.String("azure-nextgen:timeseriesinsights/v20200515:Gen1Environment"), }, { Type: pulumi.String("azure-native:timeseriesinsights/v20210630preview:Gen1Environment"), }, { Type: pulumi.String("azure-nextgen:timeseriesinsights/v20210630preview:Gen1Environment"), }, }) opts = append(opts, aliases) var resource Gen1Environment err := ctx.RegisterResource("azure-native:timeseriesinsights:Gen1Environment", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // GetGen1Environment gets an existing Gen1Environment resource's state with the given name, ID, and optional // state properties that are used to uniquely qualify the lookup (nil if not required). func GetGen1Environment(ctx *pulumi.Context, name string, id pulumi.IDInput, state *Gen1EnvironmentState, opts ...pulumi.ResourceOption) (*Gen1Environment, error) { var resource Gen1Environment err := ctx.ReadResource("azure-native:timeseriesinsights:Gen1Environment", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // Input properties used for looking up and filtering Gen1Environment resources. type gen1EnvironmentState struct { } type Gen1EnvironmentState struct { } func (Gen1EnvironmentState) ElementType() reflect.Type { return reflect.TypeOf((*gen1EnvironmentState)(nil)).Elem() } type gen1EnvironmentArgs struct { // ISO8601 timespan specifying the minimum number of days the environment's events will be available for query. DataRetentionTime string `pulumi:"dataRetentionTime"` // Name of the environment EnvironmentName *string `pulumi:"environmentName"` // The kind of the environment. // Expected value is 'Gen1'. Kind string `pulumi:"kind"` // The location of the resource. Location *string `pulumi:"location"` // The list of event properties which will be used to partition data in the environment. Currently, only a single partition key property is supported. PartitionKeyProperties []TimeSeriesIdProperty `pulumi:"partitionKeyProperties"` // Name of an Azure Resource group. ResourceGroupName string `pulumi:"resourceGroupName"` // The sku determines the type of environment, either Gen1 (S1 or S2) or Gen2 (L1). For Gen1 environments the sku determines the capacity of the environment, the ingress rate, and the billing rate. Sku Sku `pulumi:"sku"` // The behavior the Time Series Insights service should take when the environment's capacity has been exceeded. If "PauseIngress" is specified, new events will not be read from the event source. If "PurgeOldData" is specified, new events will continue to be read and old events will be deleted from the environment. The default behavior is PurgeOldData. StorageLimitExceededBehavior *string `pulumi:"storageLimitExceededBehavior"` // Key-value pairs of additional properties for the resource. Tags map[string]string `pulumi:"tags"` } // The set of arguments for constructing a Gen1Environment resource. type Gen1EnvironmentArgs struct { // ISO8601 timespan specifying the minimum number of days the environment's events will be available for query. DataRetentionTime pulumi.StringInput // Name of the environment EnvironmentName pulumi.StringPtrInput // The kind of the environment. // Expected value is 'Gen1'. Kind pulumi.StringInput // The location of the resource. Location pulumi.StringPtrInput // The list of event properties which will be used to partition data in the environment. Currently, only a single partition key property is supported. PartitionKeyProperties TimeSeriesIdPropertyArrayInput // Name of an Azure Resource group. ResourceGroupName pulumi.StringInput // The sku determines the type of environment, either Gen1 (S1 or S2) or Gen2 (L1). For Gen1 environments the sku determines the capacity of the environment, the ingress rate, and the billing rate. Sku SkuInput // The behavior the Time Series Insights service should take when the environment's capacity has been exceeded. If "PauseIngress" is specified, new events will not be read from the event source. If "PurgeOldData" is specified, new events will continue to be read and old events will be deleted from the environment. The default behavior is PurgeOldData. StorageLimitExceededBehavior pulumi.StringPtrInput // Key-value pairs of additional properties for the resource. Tags pulumi.StringMapInput } func (Gen1EnvironmentArgs) ElementType() reflect.Type { return reflect.TypeOf((*gen1EnvironmentArgs)(nil)).Elem() } type Gen1EnvironmentInput interface { pulumi.Input ToGen1EnvironmentOutput() Gen1EnvironmentOutput ToGen1EnvironmentOutputWithContext(ctx context.Context) Gen1EnvironmentOutput } func (*Gen1Environment) ElementType() reflect.Type { return reflect.TypeOf((*Gen1Environment)(nil)) } func (i *Gen1Environment) ToGen1EnvironmentOutput() Gen1EnvironmentOutput { return i.ToGen1EnvironmentOutputWithContext(context.Background()) } func (i *Gen1Environment) ToGen1EnvironmentOutputWithContext(ctx context.Context) Gen1EnvironmentOutput { return pulumi.ToOutputWithContext(ctx, i).(Gen1EnvironmentOutput) } type Gen1EnvironmentOutput struct{ *pulumi.OutputState } func (Gen1EnvironmentOutput) ElementType() reflect.Type { return reflect.TypeOf((*Gen1Environment)(nil)) } func (o Gen1EnvironmentOutput) ToGen1EnvironmentOutput() Gen1EnvironmentOutput { return o } func (o Gen1EnvironmentOutput) ToGen1EnvironmentOutputWithContext(ctx context.Context) Gen1EnvironmentOutput { return o } func init() { pulumi.RegisterOutputType(Gen1EnvironmentOutput{}) }
hmcts/document-management-store-api-gateway-web
app/user/user-id-extractor.js
const extract = (request) => { const pattern = /^\/[^\/]+\/[^\/]+\/([^\/]+)\/.+$/ // eslint-disable-line no-useless-escape const match = request.originalUrl.match(pattern) || [] return match[1] } exports.extract = extract
dbiir/pard
pard-parser/src/main/java/cn/edu/ruc/iir/pard/sql/tree/Insert.java
<reponame>dbiir/pard package cn.edu.ruc.iir.pard.sql.tree; import java.util.List; import java.util.Objects; import java.util.Optional; import static com.google.common.base.MoreObjects.toStringHelper; /** * pard * * @author guodong */ public class Insert extends Statement { private final QualifiedName target; private final Query query; private final Optional<List<String>> columns; public Insert(QualifiedName target, Optional<List<String>> columns, Query query) { this(null, target, columns, query); } public Insert(Location location, QualifiedName target, Optional<List<String>> columns, Query query) { super(location); this.target = target; this.columns = columns; this.query = query; } public QualifiedName getTarget() { return target; } public Query getQuery() { return query; } public Optional<List<String>> getColumns() { return columns; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitInsert(this, context); } @Override public List<? extends Node> getChildren() { return null; } @Override public int hashCode() { return Objects.hash(target, columns, query); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if ((obj == null) || (getClass() != obj.getClass())) { return false; } Insert o = (Insert) obj; return Objects.equals(target, o.target) && Objects.equals(columns, o.columns) && Objects.equals(query, o.query); } @Override public String toString() { return toStringHelper(this) .add("target", target) .add("columns", columns) .add("query", query) .toString(); } }
tuvapp/tuvappcom
myvenv/lib/python3.5/site-packages/factory/compat.py
# -*- coding: utf-8 -*- # Copyright (c) 2010 <NAME> # Copyright (c) 2011-2015 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Compatibility tools""" import datetime import decimal import sys PY2 = (sys.version_info[0] == 2) if PY2: # pragma: no cover def is_string(obj): return isinstance(obj, (str, unicode)) from StringIO import StringIO as BytesIO else: # pragma: no cover def is_string(obj): return isinstance(obj, str) from io import BytesIO try: # pragma: no cover # Python >= 3.2 UTC = datetime.timezone.utc except AttributeError: # pragma: no cover try: # Fallback to pytz from pytz import UTC except ImportError: # Ok, let's write our own. class _UTC(datetime.tzinfo): """The UTC tzinfo.""" def utcoffset(self, dt): return datetime.timedelta(0) def tzname(self, dt): return "UTC" def dst(self, dt): return datetime.timedelta(0) def localize(self, dt): dt.astimezone(self) UTC = _UTC()
thefire/geode
geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionMessage.java
<reponame>thefire/geode /* * 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.geode.distributed.internal; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import org.apache.logging.log4j.Logger; import org.apache.geode.CancelException; import org.apache.geode.InternalGemFireException; import org.apache.geode.SystemFailure; import org.apache.geode.annotations.Immutable; import org.apache.geode.distributed.internal.deadlock.MessageDependencyMonitor; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.distributed.internal.membership.gms.api.Message; import org.apache.geode.internal.Assert; import org.apache.geode.internal.cache.EventID; import org.apache.geode.internal.logging.log4j.LogMarker; import org.apache.geode.internal.sequencelog.MessageLogger; import org.apache.geode.internal.serialization.DeserializationContext; import org.apache.geode.internal.serialization.SerializationContext; import org.apache.geode.internal.serialization.Version; import org.apache.geode.internal.tcp.Connection; import org.apache.geode.internal.util.Breadcrumbs; import org.apache.geode.logging.internal.log4j.api.LogService; /** * <P> * A <code>DistributionMessage</code> carries some piece of information to a distribution manager. * </P> * * <P> * Messages that don't have strict ordering requirements should extend * {@link org.apache.geode.distributed.internal.PooledDistributionMessage}. Messages that must be * processed serially in the order they were received can extend * {@link org.apache.geode.distributed.internal.SerialDistributionMessage}. To customize the * sequentialness/thread requirements of a message, extend DistributionMessage and implement * getExecutor(). * </P> */ public abstract class DistributionMessage implements Message<InternalDistributedMember>, Cloneable { /** * WARNING: setting this to true may break dunit tests. * <p> * see org.apache.geode.cache30.ClearMultiVmCallBkDUnitTest */ private static final boolean INLINE_PROCESS = !Boolean.getBoolean("DistributionManager.enqueueOrderedMessages"); private static final Logger logger = LogService.getLogger(); // common flags used by operation messages /** Keep this compatible with the other GFE layer PROCESSOR_ID flags. */ protected static final short HAS_PROCESSOR_ID = 0x1; /** Flag set when this message carries a transactional member in context. */ protected static final short HAS_TX_MEMBERID = 0x2; /** Flag set when this message carries a transactional context. */ protected static final short HAS_TX_ID = 0x4; /** Flag set when this message is a possible duplicate. */ protected static final short POS_DUP = 0x8; /** Indicate time statistics capturing as part of this message processing */ protected static final short ENABLE_TIMESTATS = 0x10; /** If message sender has set the processor type to be used explicitly. */ protected static final short HAS_PROCESSOR_TYPE = 0x20; /** the unreserved flags start for child classes */ protected static final short UNRESERVED_FLAGS_START = (HAS_PROCESSOR_TYPE << 1); private final InternalDistributedMember[] EMPTY_RECIPIENTS_ARRAY = new InternalDistributedMember[0]; private final List<InternalDistributedMember> ALL_RECIPIENTS_LIST = Collections.singletonList(null); private final InternalDistributedMember[] ALL_RECIPIENTS_ARRAY = {null}; @Immutable protected static final InternalDistributedMember ALL_RECIPIENTS = null; //////////////////// Instance Fields //////////////////// /** The sender of this message */ protected transient InternalDistributedMember sender; /** A set of recipients for this message, not serialized */ private transient InternalDistributedMember[] recipients = null; /** A timestamp, in nanos, associated with this message. Not serialized. */ private transient long timeStamp; /** The number of bytes used to read this message, for statistics only */ private transient int bytesRead = 0; /** true if message should be multicast; ignores recipients */ private transient boolean multicast = false; /** true if messageBeingReceived stats need decrementing when done with msg */ private transient boolean doDecMessagesBeingReceived = false; /** * This field will be set if we can send a direct ack for this message. */ private transient ReplySender acker = null; /** * True if the P2P reader that received this message is a SHARED reader. */ private transient boolean sharedReceiver; ////////////////////// Constructors ////////////////////// protected DistributionMessage() { this.timeStamp = DistributionStats.getStatTime(); } ////////////////////// Static Helper Methods ////////////////////// /** * Get the next bit mask position while checking that the value should not exceed maximum byte * value. */ protected static int getNextByteMask(final int mask) { return getNextBitMask(mask, (Byte.MAX_VALUE) + 1); } /** * Get the next bit mask position while checking that the value should not exceed given maximum * value. */ protected static int getNextBitMask(int mask, final int maxValue) { mask <<= 1; if (mask > maxValue) { Assert.fail("exhausted bit flags with all available bits: 0x" + Integer.toHexString(mask) + ", max: 0x" + Integer.toHexString(maxValue)); } return mask; } public static byte getNumBits(final int maxValue) { byte numBits = 1; while ((1 << numBits) <= maxValue) { numBits++; } return numBits; } ////////////////////// Instance Methods ////////////////////// public void setDoDecMessagesBeingReceived(boolean v) { this.doDecMessagesBeingReceived = v; } public void setReplySender(ReplySender acker) { this.acker = acker; } public ReplySender getReplySender(DistributionManager dm) { if (acker != null) { return acker; } else { return dm; } } public boolean isDirectAck() { return acker != null; } /** * If true then this message most be sent on an ordered channel. If false then it can be * unordered. * * @since GemFire 5.5 */ public boolean orderedDelivery() { final int processorType = getProcessorType(); switch (processorType) { case OperationExecutors.SERIAL_EXECUTOR: // no need to use orderedDelivery for PR ops particularly when thread // does not own resources // case DistributionManager.PARTITIONED_REGION_EXECUTOR: return true; case OperationExecutors.REGION_FUNCTION_EXECUTION_EXECUTOR: // allow nested distributed functions to be executed from within the // execution of a function return false; default: InternalDistributedSystem ids = InternalDistributedSystem.getAnyInstance(); return (ids != null && ids.threadOwnsResources()); } } /** * Sets the intended recipient of the message. If recipient is Message.ALL_RECIPIENTS * then the * message will be sent to all distribution managers. */ public void setRecipient(InternalDistributedMember recipient) { if (this.recipients != null) { throw new IllegalStateException( "Recipients can only be set once"); } this.recipients = new InternalDistributedMember[] {recipient}; } /** * Causes this message to be send using multicast if v is true. * * @since GemFire 5.0 */ public void setMulticast(boolean v) { this.multicast = v; } /** * Return true if this message should be sent using multicast. * * @since GemFire 5.0 */ public boolean getMulticast() { return this.multicast; } /** * Return true of this message should be sent via UDP instead of the direct-channel. This is * typically only done for messages that are broadcast to the full membership set. */ public boolean sendViaUDP() { return false; } /** * Sets the intended recipient of the message. If recipient set contains * Message.ALL_RECIPIENTS * then the message will be sent to all distribution managers. */ @Override public void setRecipients(Collection recipients) { this.recipients = (InternalDistributedMember[]) recipients .toArray(EMPTY_RECIPIENTS_ARRAY); } @Override public void registerProcessor() { // override if direct-ack is supported } @Override public boolean isHighPriority() { return false; } @Override public List<InternalDistributedMember> getRecipients() { InternalDistributedMember[] recipients = getRecipientsArray(); if (recipients == null || recipients.length == 1 && recipients[0] == ALL_RECIPIENTS) { return ALL_RECIPIENTS_LIST; } return Arrays.asList(recipients); } public void resetRecipients() { this.recipients = null; this.multicast = false; } /** * Returns the intended recipient(s) of this message. If the message is intended to delivered to * all distribution managers, then the array will contain ALL_RECIPIENTS. If the recipients have * not been set null is returned. */ public InternalDistributedMember[] getRecipientsArray() { if (this.multicast || this.recipients == null) { return ALL_RECIPIENTS_ARRAY; } return this.recipients; } /** * Returns true if message will be sent to everyone. */ public boolean forAll() { return (this.recipients == null) || (this.multicast) || ((this.recipients.length > 0) && (this.recipients[0] == ALL_RECIPIENTS)); } public String getRecipientsDescription() { if (forAll()) { return "recipients: ALL"; } else { StringBuffer sb = new StringBuffer(100); sb.append("recipients: <"); for (int i = 0; i < this.recipients.length; i++) { if (i != 0) { sb.append(", "); } sb.append(this.recipients[i]); } sb.append(">"); return sb.toString(); } } /** * Returns the sender of this message. Note that this value is not set until this message is * received by a distribution manager. */ public InternalDistributedMember getSender() { return this.sender; } /** * Sets the sender of this message. This method is only invoked when the message is * <B>received</B> by a <code>DistributionManager</code>. */ @Override public void setSender(InternalDistributedMember _sender) { this.sender = _sender; } /** * Return the Executor in which to process this message. */ protected Executor getExecutor(ClusterDistributionManager dm) { return dm.getExecutors().getExecutor(getProcessorType(), sender); } public abstract int getProcessorType(); /** * Processes this message. This method is invoked by the receiver of the message. * * @param dm the distribution manager that is processing the message. */ protected abstract void process(ClusterDistributionManager dm); /** * Scheduled action to take when on this message when we are ready to process it. */ protected void scheduleAction(final ClusterDistributionManager dm) { if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) { logger.trace(LogMarker.DM_VERBOSE, "Processing '{}'", this); } String reason = dm.getCancelCriterion().cancelInProgress(); if (reason != null) { // throw new ShutdownException(reason); if (logger.isDebugEnabled()) { logger.debug("ScheduleAction: cancel in progress ({}); skipping<{}>", reason, this); } return; } if (MessageLogger.isEnabled()) { MessageLogger.logMessage(this, getSender(), dm.getDistributionManagerId()); } MessageDependencyMonitor.processingMessage(this); long time = 0; if (DistributionStats.enableClockStats) { time = DistributionStats.getStatTime(); dm.getStats().incMessageProcessingScheduleTime(time - getTimestamp()); } setBreadcrumbsInReceiver(); try { DistributionMessageObserver observer = DistributionMessageObserver.getInstance(); if (observer != null) { observer.beforeProcessMessage(dm, this); } process(dm); if (observer != null) { observer.afterProcessMessage(dm, this); } } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Cancelled caught processing {}: {}", this, e.getMessage(), e); } } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable t) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); logger.fatal(String.format("Uncaught exception processing %s", this), t); } finally { if (doDecMessagesBeingReceived) { dm.getStats().decMessagesBeingReceived(this.bytesRead); } dm.getStats().incProcessedMessages(1L); if (DistributionStats.enableClockStats) { dm.getStats().incProcessedMessagesTime(time); } Breadcrumbs.clearBreadcrumb(); MessageDependencyMonitor.doneProcessing(this); } } /** * Schedule this message's process() method in a thread determined by getExecutor() */ protected void schedule(final ClusterDistributionManager dm) { boolean inlineProcess = INLINE_PROCESS && getProcessorType() == OperationExecutors.SERIAL_EXECUTOR && !isPreciousThread(); boolean forceInline = this.acker != null || getInlineProcess() || Connection.isDominoThread(); if (inlineProcess && !forceInline && isSharedReceiver()) { // If processing this message notify a serial gateway sender then don't do it inline. if (mayNotifySerialGatewaySender(dm)) { inlineProcess = false; } } inlineProcess |= forceInline; if (inlineProcess) { dm.getStats().incNumSerialThreads(1); try { scheduleAction(dm); } finally { dm.getStats().incNumSerialThreads(-1); } } else { // not inline try { getExecutor(dm).execute(new SizeableRunnable(this.getBytesRead()) { @Override public void run() { scheduleAction(dm); } @Override public String toString() { return "Processing {" + DistributionMessage.this.toString() + "}"; } }); } catch (RejectedExecutionException ex) { if (!dm.shutdownInProgress()) { // fix for bug 32395 logger.warn(String.format("%s schedule() rejected", this.toString()), ex); } } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable t) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); logger.fatal(String.format("Uncaught exception processing %s", this), t); // I don't believe this ever happens (DJP May 2007) throw new InternalGemFireException( "Unexpected error scheduling message", t); } } // not inline } protected boolean mayNotifySerialGatewaySender(ClusterDistributionManager dm) { // subclasses should override this method if processing them may notify a serial gateway sender. return false; } /** * returns true if the current thread should not be used for inline processing. i.e., it is a * "precious" resource */ public static boolean isPreciousThread() { String thrname = Thread.currentThread().getName(); // return thrname.startsWith("Geode UDP"); return thrname.startsWith("unicast receiver") || thrname.startsWith("multicast receiver"); } /** most messages should not force in-line processing */ public boolean getInlineProcess() { return false; } /** * sets the breadcrumbs for this message into the current thread's name */ public void setBreadcrumbsInReceiver() { if (Breadcrumbs.ENABLED) { String sender = null; String procId = ""; long pid = getProcessorId(); if (pid != 0) { procId = " processorId=" + pid; } if (Thread.currentThread().getName().startsWith(Connection.THREAD_KIND_IDENTIFIER)) { sender = procId; } else { sender = "sender=" + getSender() + procId; } if (sender.length() > 0) { Breadcrumbs.setReceiveSide(sender); } Object evID = getEventID(); if (evID != null) { Breadcrumbs.setEventId(evID); } } } /** * sets breadcrumbs in a thread that is sending a message to another member */ public void setBreadcrumbsInSender() { if (Breadcrumbs.ENABLED) { String procId = ""; long pid = getProcessorId(); if (pid != 0) { procId = "processorId=" + pid; } if (this.recipients != null && this.recipients.length <= 10) { // set a limit on recipients Breadcrumbs.setSendSide(procId + " recipients=" + Arrays.toString(this.recipients)); } else { if (procId.length() > 0) { Breadcrumbs.setSendSide(procId); } } Object evID = getEventID(); if (evID != null) { Breadcrumbs.setEventId(evID); } } } public EventID getEventID() { return null; } /** * This method resets the state of this message, usually releasing objects and resources it was * using. It is invoked after the message has been sent. Note that classes that override this * method should always invoke the inherited method (<code>super.reset()</code>). */ public void reset() { resetRecipients(); this.sender = null; } /** * Writes the contents of this <code>DistributionMessage</code> to the given output. Note that * classes that override this method should always invoke the inherited method * (<code>super.toData()</code>). */ @Override public void toData(DataOutput out, SerializationContext context) throws IOException { // context.getSerializer().writeObject(this.recipients, out); // no need to serialize; filled in // later // ((IpAddress)this.sender).toData(out); // no need to serialize; filled in later // out.writeLong(this.timeStamp); } /** * Reads the contents of this <code>DistributionMessage</code> from the given input. Note that * classes that override this method should always invoke the inherited method * (<code>super.fromData()</code>). */ @Override public void fromData(DataInput in, DeserializationContext context) throws IOException, ClassNotFoundException { // this.recipients = (Set)context.getDeserializer().readObject(in); // no to deserialize; filled // in later // this.sender = DataSerializer.readIpAddress(in); // no to deserialize; filled in later // this.timeStamp = (long)in.readLong(); } /** * Returns a timestamp, in nanos, associated with this message. */ public long getTimestamp() { return timeStamp; } /** * Sets the timestamp of this message to the current time (in nanos). * * @return the number of elapsed nanos since this message's last timestamp */ public long resetTimestamp() { if (DistributionStats.enableClockStats) { long now = DistributionStats.getStatTime(); long result = now - this.timeStamp; this.timeStamp = now; return result; } else { return 0; } } public void setBytesRead(int bytesRead) { this.bytesRead = bytesRead; } public int getBytesRead() { return bytesRead; } public void setSharedReceiver(boolean v) { this.sharedReceiver = v; } public boolean isSharedReceiver() { return this.sharedReceiver; } /** * * @return null if message is not conflatable. Otherwise return a key that can be used to identify * the entry to conflate. * @since GemFire 4.2.2 */ public ConflationKey getConflationKey() { return null; // by default conflate nothing; override in subclasses } /** * @return the ID of the reply processor for this message, or zero if none * @since GemFire 5.7 */ public int getProcessorId() { return 0; } /** * Severe alert processing enables suspect processing at the ack-wait-threshold and issuing of a * severe alert at the end of the ack-severe-alert-threshold. Some messages should not support * this type of processing (e.g., GII, or DLockRequests) * * @return whether severe-alert processing may be performed on behalf of this message */ public boolean isSevereAlertCompatible() { return false; } /** * Returns true if the message is for internal-use such as a meta-data region. * * @return true if the message is for internal-use such as a meta-data region * @since GemFire 7.0 */ public boolean isInternal() { return false; } @Override public boolean dropMessageWhenMembershipIsPlayingDead() { return containsRegionContentChange(); } /** * does this message carry state that will alter the content of one or more cache regions? This is * used to track the flight of content changes through communication channels */ public boolean containsRegionContentChange() { return false; } /** returns the class name w/o package information. useful in logging */ public String getShortClassName() { String cname = getClass().getName(); return cname.substring(getClass().getPackage().getName().length() + 1); } @Override public String toString() { String cname = getShortClassName(); final StringBuilder sb = new StringBuilder(cname); sb.append('@').append(Integer.toHexString(System.identityHashCode(this))); sb.append(" processorId=").append(getProcessorId()); sb.append(" sender=").append(getSender()); return sb.toString(); } @Override public Version[] getSerializationVersions() { return null; } }
collectiveidea/bender
spec/factories/pour.rb
<gh_stars>1-10 FactoryBot.define do factory :pour do volume { rand * 16 } started_at { 5.seconds.ago } finished_at { Time.now } duration { rand * 30 } keg user end end
co2meal/-bnpy-dev
bnpy/suffstats/SuffStatBag.py
import copy import numpy as np from ParamBag import ParamBag class SuffStatBag(object): """ Container object for additive sufficient statistics in bnpy. Uses ParamBag as internal representation. Tracks three possible sets of parameters, each with own ParamBag: * sufficient statistics fields * (optional) precomputed ELBO terms * (optional) precomputed terms for potential merges """ def __init__(self, K=0, **kwargs): self.kwargs = kwargs self._Fields = ParamBag(K=K, **kwargs) def setUIDs(self, uIDs): if len(uIDs) != self.K: raise ValueError('Bad UIDs') self.uIDs = np.asarray(uIDs, dtype=np.int32) def getCountVec(self): ''' Return vector of counts for each active topic/component ''' if 'N' in self._Fields._FieldDims: return self.N elif 'SumWordCounts' in self._Fields._FieldDims: return self.SumWordCounts raise ValueError('Counts not available') def copy(self, includeELBOTerms=True, includeMergeTerms=True): if not includeELBOTerms: E = self.removeELBOTerms() if not includeMergeTerms: M = self.removeMergeTerms() copySS = copy.deepcopy(self) if not includeELBOTerms: self.restoreELBOTerms(E) if not includeMergeTerms: self.restoreMergeTerms(M) return copySS def setField(self, key, value, dims=None): self._Fields.setField(key, value, dims=dims) def setAllFieldsToZeroAndRemoveNonELBOTerms(self): self._Fields.setAllFieldsToZero() self.setELBOFieldsToZero() self.removeMergeTerms() self.removeSelectionTerms() def setELBOFieldsToZero(self): if self.hasELBOTerms(): self._ELBOTerms.setAllFieldsToZero() def setMergeFieldsToZero(self): if self.hasMergeTerms(): self._MergeTerms.setAllFieldsToZero() if hasattr(self, 'mPairIDs'): delattr(self, 'mPairIDs') def reorderComps(self, order): ''' Rearrange internal order of components ''' assert self.K == order.size self._Fields.reorderComps(order) if self.hasELBOTerms(): self._ELBOTerms.reorderComps(order) if self.hasMergeTerms(): self._MergeTerms.reorderComps(order) if self.hasSelectionTerms(): self._SelectTerms.reorderComps(order) if hasattr(self, 'uIDs'): self.uIDs = self.uIDs[order] if hasattr(self, 'mPairIDs'): del self.mPairIDs def removeField(self, key): return self._Fields.removeField(key) def removeELBOandMergeTerms(self): E = self.removeELBOTerms() M = self.removeMergeTerms() return E, M def restoreELBOandMergeTerms(self, E, M): self.restoreELBOTerms(E) self.restoreMergeTerms(M) def removeELBOTerms(self): if not self.hasELBOTerms(): return None _ELBOTerms = self._ELBOTerms del self._ELBOTerms return _ELBOTerms def removeMergeTerms(self): if hasattr(self, 'mPairIDs'): del self.mPairIDs if not self.hasMergeTerms(): return None MergeTerms = self._MergeTerms del self._MergeTerms return MergeTerms def restoreELBOTerms(self, ELBOTerms): if ELBOTerms is not None: self._ELBOTerms = ELBOTerms def restoreMergeTerms(self, MergeTerms): if MergeTerms is not None: self._MergeTerms = MergeTerms def removeSelectionTerms(self): if not self.hasSelectionTerms(): return None STerms = self._SelectTerms del self._SelectTerms return STerms def restoreSelectionTerms(self, STerms): if STerms is not None: self._SelectTerms = STerms def hasAmpFactor(self): return hasattr(self, 'ampF') def applyAmpFactor(self, ampF): self.ampF = ampF for key in self._Fields._FieldDims: arr = getattr(self._Fields, key) if arr.ndim == 0: # Edge case: in-place updates don't work with # de-referenced 0-d arrays setattr(self._Fields, key, arr * ampF) else: arr *= ampF def hasELBOTerms(self): return hasattr(self, '_ELBOTerms') def hasELBOTerm(self, key): if not hasattr(self, '_ELBOTerms'): return False return hasattr(self._ELBOTerms, key) def getELBOTerm(self, key): return getattr(self._ELBOTerms, key) def setELBOTerm(self, key, value, dims=None): if not hasattr(self, '_ELBOTerms'): self._ELBOTerms = ParamBag(K=self.K, **self.kwargs) self._ELBOTerms.setField(key, value, dims=dims) def hasMergeTerms(self): return hasattr(self, '_MergeTerms') def hasMergeTerm(self, key): if not hasattr(self, '_MergeTerms'): return False return hasattr(self._MergeTerms, key) def getMergeTerm(self, key): return getattr(self._MergeTerms, key) def setMergeTerm(self, key, value, dims=None): if not hasattr(self, '_MergeTerms'): self._MergeTerms = ParamBag(K=self.K, **self.kwargs) self._MergeTerms.setField(key, value, dims=dims) def hasSelectionTerm(self, key): if not hasattr(self, '_SelectTerms'): return False return hasattr(self._SelectTerms, key) def hasSelectionTerms(self): return hasattr(self, '_SelectTerms') def getSelectionTerm(self, key): return getattr(self._SelectTerms, key) def setSelectionTerm(self, key, value, dims=None): if not hasattr(self, '_SelectTerms'): self._SelectTerms = ParamBag(K=self.K) self._SelectTerms.setField(key, value, dims=dims) def multiMergeComps(self, kdel, alph): ''' Blend comp kdel into all remaining comps k ''' if self.K <= 1: raise ValueError('Must have at least 2 components to merge.') for key, dims in self._Fields._FieldDims.items(): if dims is not None and dims != (): arr = getattr(self._Fields, key) for k in xrange(self.K): if k == kdel: continue arr[k] += alph[k] * arr[kdel] if self.hasELBOTerms() and self.hasMergeTerms(): Ndel = getattr(self._Fields, 'N')[kdel] Halph = -1 * np.inner(alph, np.log(alph + 1e-100)) Hplus = self.getMergeTerm('ElogqZ')[kdel] gap = Ndel * Halph - Hplus for k in xrange(self.K): if k == kdel: continue arr = getattr(self._ELBOTerms, 'ElogqZ') arr[k] -= gap * alph[k] self._Fields.removeComp(kdel) if self.hasELBOTerms(): self._ELBOTerms.removeComp(kdel) if self.hasMergeTerms(): self._MergeTerms.removeComp(kdel) if self.hasSelectionTerms(): self._SelectTerms.removeComp(kdel) def mergeComps(self, kA, kB): ''' Merge components kA, kB into a single component ''' if self.K <= 1: raise ValueError('Must have at least 2 components to merge.') if kB == kA: raise ValueError('Distinct component ids required.') for key, dims in self._Fields._FieldDims.items(): if dims is not None and dims != (): arr = getattr(self._Fields, key) if self.hasMergeTerm(key) and dims == ('K'): # some special terms need to be precomputed arr[kA] = getattr(self._MergeTerms, key)[kA, kB] elif dims == ('K', 'K'): # special case for HMM transition matrix arr[kA] += arr[kB] arr[:, kA] += arr[:, kB] elif dims[0] == 'K': # applies to vast majority of all fields arr[kA] += arr[kB] elif len(dims) > 1 and dims[1] == 'K': arr[:, kA] += arr[:, kB] if hasattr(self, 'mPairIDs'): # Find the right row that corresponds to input kA, kB mPairIDs = self.mPairIDs rowID = np.flatnonzero(np.logical_and(kA == mPairIDs[:, 0], kB == mPairIDs[:, 1])) if not rowID.size == 1: raise ValueError( 'Bad search for correct mPairID.\n' + str(rowID)) rowID = rowID[0] if self.hasELBOTerms(): for key, dims in self._ELBOTerms._FieldDims.items(): if not self.hasMergeTerm(key): continue arr = getattr(self._ELBOTerms, key) mArr = getattr(self._MergeTerms, key) mdims = self._MergeTerms._FieldDims[key] if mdims[0] == 'M': mArr = mArr[rowID] if mArr.ndim == 2 and mArr.shape[0] == 2: arr[kA, :] = mArr[0] arr[:, kA] = mArr[1] elif mArr.ndim <= 1 and mArr.size == 1: arr[kA] = mArr else: raise NotImplementedError('TODO') elif dims[0] == 'K': if mArr.ndim == 2: arr[kA] = mArr[kA, kB] else: arr[kA] += mArr[kB] if self.hasMergeTerms(): for key, dims in self._MergeTerms._FieldDims.items(): mArr = getattr(self._MergeTerms, key) if dims == ('K', 'K'): mArr[kA, kA + 1:] = np.nan mArr[:kA, kA] = np.nan elif dims == ('K'): mArr[kA] = np.nan elif dims[0] == 'M' and key == 'Htable': if len(dims) == 3 and dims[-1] == 'K': mArr[:, :, kA] = 0 if self.hasSelectionTerms(): for key, dims in self._SelectTerms._FieldDims.items(): mArr = getattr(self._SelectTerms, key) if dims == ('K', 'K'): ab = mArr[kB, kB] + 2 * mArr[kA, kB] + mArr[kA, kA] mArr[kA, :] += mArr[kB, :] mArr[:, kA] += mArr[:, kB] mArr[kA, kA] = ab elif dims == ('K'): mArr[kA] = mArr[kA] + mArr[kB] if hasattr(self, 'mPairIDs'): # Remove any other pairs associated with kA or kB keepRowIDs = ((mPairIDs[:, 0] != kA) * (mPairIDs[:, 1] != kA) * (mPairIDs[:, 0] != kB) * (mPairIDs[:, 1] != kB)) keepRowIDs = np.flatnonzero(keepRowIDs) M = len(keepRowIDs) self.M = M self._MergeTerms.M = M # Remove any other pairs related to kA, kB for key, dims in self._MergeTerms._FieldDims.items(): mArr = getattr(self._MergeTerms, key) if dims[0] == 'M': mArr = mArr[keepRowIDs] self._MergeTerms.setField(key, mArr, dims=dims) # Reindex mPairIDs mPairIDs = mPairIDs[keepRowIDs] mPairIDs[mPairIDs[:, 0] > kB, 0] -= 1 mPairIDs[mPairIDs[:, 1] > kB, 1] -= 1 self.mPairIDs = mPairIDs if hasattr(self, 'uIDs'): self.uIDs = np.delete(self.uIDs, kB) self._Fields.removeComp(kB) if self.hasELBOTerms(): self._ELBOTerms.removeComp(kB) if self.hasMergeTerms(): self._MergeTerms.removeComp(kB) if self.hasSelectionTerms(): self._SelectTerms.removeComp(kB) def insertComps(self, SS): self._Fields.insertComps(SS) if hasattr(self, '_ELBOTerms'): self._ELBOTerms.insertEmptyComps(SS.K) if hasattr(self, '_MergeTerms'): self._MergeTerms.insertEmptyComps(SS.K) if hasattr(self, '_SelectTerms'): self._SelectTerms.insertEmptyComps(SS.K) def insertEmptyComps(self, Kextra): self._Fields.insertEmptyComps(Kextra) if hasattr(self, '_ELBOTerms'): self._ELBOTerms.insertEmptyComps(Kextra) if hasattr(self, '_MergeTerms'): self._MergeTerms.insertEmptyComps(Kextra) if hasattr(self, '_SelectTerms'): self._SelectTerms.insertEmptyComps(Kextra) def removeComp(self, k): if hasattr(self, 'uIDs'): self.uIDs = np.delete(self.uIDs, k) self._Fields.removeComp(k) if hasattr(self, '_ELBOTerms'): self._ELBOTerms.removeComp(k) if hasattr(self, '_MergeTerms'): self._MergeTerms.removeComp(k) if hasattr(self, '_SelectTerms'): self._SelectTerms.removeComp(k) def getComp(self, k, doCollapseK1=True): SS = SuffStatBag(K=1, D=self.D) SS._Fields = self._Fields.getComp(k, doCollapseK1=doCollapseK1) return SS def __add__(self, PB): if self.K != PB.K or self.D != PB.D: raise ValueError('Dimension mismatch') SSsum = SuffStatBag(K=self.K, D=self.D) SSsum._Fields = self._Fields + PB._Fields if hasattr(self, '_ELBOTerms') and hasattr(PB, '_ELBOTerms'): SSsum._ELBOTerms = self._ELBOTerms + PB._ELBOTerms elif hasattr(PB, '_ELBOTerms'): SSsum._ELBOTerms = PB._ELBOTerms.copy() if hasattr(self, '_MergeTerms') and hasattr(PB, '_MergeTerms'): SSsum._MergeTerms = self._MergeTerms + PB._MergeTerms elif hasattr(PB, '_MergeTerms'): SSsum._MergeTerms = PB._MergeTerms.copy() if hasattr(self, '_SelectTerms') and hasattr(PB, '_SelectTerms'): SSsum._SelectTerms = self._SelectTerms + PB._SelectTerms if not hasattr(self, 'mPairIDs') and hasattr(PB, 'mPairIDs'): SSsum.mPairIDs = PB.mPairIDs return SSsum def __iadd__(self, PB): if self.K != PB.K or self.D != PB.D: raise ValueError('Dimension mismatch') self._Fields += PB._Fields if hasattr(self, '_ELBOTerms') and hasattr(PB, '_ELBOTerms'): self._ELBOTerms += PB._ELBOTerms elif hasattr(PB, '_ELBOTerms'): self._ELBOTerms = PB._ELBOTerms.copy() if hasattr(self, '_MergeTerms') and hasattr(PB, '_MergeTerms'): self._MergeTerms += PB._MergeTerms elif hasattr(PB, '_MergeTerms'): self._MergeTerms = PB._MergeTerms.copy() if hasattr(self, '_SelectTerms') and hasattr(PB, '_SelectTerms'): self._SelectTerms += PB._SelectTerms if not hasattr(self, 'mPairIDs') and hasattr(PB, 'mPairIDs'): self.mPairIDs = PB.mPairIDs return self def __sub__(self, PB): if self.K != PB.K or self.D != PB.D: raise ValueError('Dimension mismatch') SSsum = SuffStatBag(K=self.K, D=self.D) SSsum._Fields = self._Fields - PB._Fields if hasattr(self, '_ELBOTerms') and hasattr(PB, '_ELBOTerms'): SSsum._ELBOTerms = self._ELBOTerms - PB._ELBOTerms if hasattr(self, '_MergeTerms') and hasattr(PB, '_MergeTerms'): SSsum._MergeTerms = self._MergeTerms - PB._MergeTerms return SSsum def __isub__(self, PB): if self.K != PB.K or self.D != PB.D: raise ValueError('Dimension mismatch') self._Fields -= PB._Fields if hasattr(self, '_ELBOTerms') and hasattr(PB, '_ELBOTerms'): self._ELBOTerms -= PB._ELBOTerms if hasattr(self, '_MergeTerms') and hasattr(PB, '_MergeTerms'): self._MergeTerms -= PB._MergeTerms return self def __getattr__(self, key): _Fields = object.__getattribute__(self, "_Fields") _dict = object.__getattribute__(self, "__dict__") if key == "_Fields": return _Fields elif hasattr(_Fields, key): return getattr(_Fields, key) elif key == '__deepcopy__': # workaround to allow copying return None elif key in _dict: return _dict[key] # Field named 'key' doesnt exist. errmsg = "'SuffStatBag' object has no attribute '%s'" % (key) raise AttributeError(errmsg) ''' def __getstate__(self): F = self._Fields E = None M = None S = None if self.hasELBOTerms(): E = self._ELBOTerms if self.hasMergeTerms(): M = self._MergeTerms if self.hasSelectionTerms(): S = self._SelectTerms return F, E, M, S def __setstate__(self, state): F, E, M, S = state self._Fields = F if E is not None: self._ELBOTerms = E if M is not None: self._MergeTerms = M if S is not None: self._SelectTerms = S self.K = F.K '''
ITISFoundation/osparc-iseg
Thirdparty/Gc/Algo/Geometry/DistanceTransform.cpp
<filename>Thirdparty/Gc/Algo/Geometry/DistanceTransform.cpp /* This file is part of Graph Cut (Gc) combinatorial optimization library. Copyright (C) 2008-2010 Centre for Biomedical Image Analysis (CBIA) Copyright (C) 2008-2010 <NAME> This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Gc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Graph Cut library. If not, see <http://www.gnu.org/licenses/>. */ /** @file Distance transform algorithms. @author <NAME> <<EMAIL>> @date 2010 */ #include <limits> #include "../../Energy/Neighbourhood.h" #include "../../Data/BorderIterator.h" #include "../../System/ArgumentException.h" #include "DistanceTransform.h" namespace Gc { namespace Algo { namespace Geometry { namespace DistanceTransform { /******************************************************************************/ template <Size N, class T> static void Scan(System::Collection::Array<N, T> & map, const Energy::Neighbourhood<N, Int32> & nb) { // Calculate neighbour offsets System::Collection::Array<1, Int32> ofs; map.Indexes(nb, ofs); // Check if we're doing forward or backward scan bool forward = ofs[0] < 0; // Get neighbourhood extent Math::Algebra::Vector<N, Size> bleft, bright; nb.Extent(bleft, bright); // Create data iterator Data::BorderIterator<N> iter(map.Dimensions(), bleft, bright); iter.Start(!forward); // Scan forward or backward Math::Algebra::Vector<N, Size> ncur; T * p = &map[forward ? 0 : (map.Elements() - 1)]; Int32 addp = forward ? 1 : -1; Size bsize; while (!iter.IsFinished()) { ncur = iter.CurPos(); if (iter.NextBlock(bsize)) // Border, we have to check boundaries { while (bsize-- > 0) { for (Size i = 0; i < nb.Elements(); i++) { if (map.IsNeighbourInside(ncur, nb[i])) { T nd = p[ofs[i]] + 1; if (*p > nd) { *p = nd; } } } p += addp; iter.NextPos(ncur); } } else // Safe zone, no need to check boundaries { while (bsize-- > 0) { for (Size i = 0; i < nb.Elements(); i++) { if (*p > p[ofs[i]] + 1) { *p = p[ofs[i]] + 1; } } p += addp; } } } } /******************************************************************************/ template <Size N, class DATA, class T> void CityBlock(const System::Collection::Array<N, DATA> & mask, DATA zero_val, System::Collection::Array<N, T> & map) { // Generate neighbourhood Energy::Neighbourhood<N, Int32> nb; nb.Elementary(); // Init map map.Resize(mask.Dimensions()); for (Size i = 0; i < mask.Elements(); i++) { map[i] = (mask[i] == zero_val) ? 0 : (std::numeric_limits<T>::max() - 1); } // Forward and backward scan if (!mask.IsEmpty()) { Scan(map, nb.Negative()); Scan(map, nb.Positive()); } } /******************************************************************************/ // Explicit instantiations /** @cond */ template void GC_DLL_EXPORT CityBlock(const System::Collection::Array<2, bool> & mask, bool zero_val, System::Collection::Array<2, Uint16> & map); template void GC_DLL_EXPORT CityBlock(const System::Collection::Array<2, bool> & mask, bool zero_val, System::Collection::Array<2, Uint32> & map); template void GC_DLL_EXPORT CityBlock(const System::Collection::Array<2, bool> & mask, bool zero_val, System::Collection::Array<2, Uint64> & map); template void GC_DLL_EXPORT CityBlock(const System::Collection::Array<3, bool> & mask, bool zero_val, System::Collection::Array<3, Uint16> & map); template void GC_DLL_EXPORT CityBlock(const System::Collection::Array<3, bool> & mask, bool zero_val, System::Collection::Array<3, Uint32> & map); template void GC_DLL_EXPORT CityBlock(const System::Collection::Array<3, bool> & mask, bool zero_val, System::Collection::Array<3, Uint64> & map); template void GC_DLL_EXPORT CityBlock(const System::Collection::Array<2, Uint8> & mask, Uint8 zero_val, System::Collection::Array<2, Uint16> & map); template void GC_DLL_EXPORT CityBlock(const System::Collection::Array<2, Uint8> & mask, Uint8 zero_val, System::Collection::Array<2, Uint32> & map); template void GC_DLL_EXPORT CityBlock(const System::Collection::Array<2, Uint8> & mask, Uint8 zero_val, System::Collection::Array<2, Uint64> & map); template void GC_DLL_EXPORT CityBlock(const System::Collection::Array<3, Uint8> & mask, Uint8 zero_val, System::Collection::Array<3, Uint16> & map); template void GC_DLL_EXPORT CityBlock(const System::Collection::Array<3, Uint8> & mask, Uint8 zero_val, System::Collection::Array<3, Uint32> & map); template void GC_DLL_EXPORT CityBlock(const System::Collection::Array<3, Uint8> & mask, Uint8 zero_val, System::Collection::Array<3, Uint64> & map); /** @endcond */ /******************************************************************************/ template <Size N, class DATA, class T> void ChessBoard(const System::Collection::Array<N, DATA> & mask, DATA zero_val, System::Collection::Array<N, T> & map) { // Generate neighbourhood Energy::Neighbourhood<N, Int32> nb; nb.Box(Math::Algebra::Vector<N, Size>(1), false, false); // Init map map.Resize(mask.Dimensions()); for (Size i = 0; i < mask.Elements(); i++) { map[i] = (mask[i] == zero_val) ? 0 : (std::numeric_limits<T>::max() - 1); } // Forward and backward scan if (!mask.IsEmpty()) { Scan(map, nb.Negative()); Scan(map, nb.Positive()); } } /******************************************************************************/ // Explicit instantiations /** @cond */ template void GC_DLL_EXPORT ChessBoard(const System::Collection::Array<2, bool> & mask, bool zero_val, System::Collection::Array<2, Uint16> & map); template void GC_DLL_EXPORT ChessBoard(const System::Collection::Array<2, bool> & mask, bool zero_val, System::Collection::Array<2, Uint32> & map); template void GC_DLL_EXPORT ChessBoard(const System::Collection::Array<2, bool> & mask, bool zero_val, System::Collection::Array<2, Uint64> & map); template void GC_DLL_EXPORT ChessBoard(const System::Collection::Array<3, bool> & mask, bool zero_val, System::Collection::Array<3, Uint16> & map); template void GC_DLL_EXPORT ChessBoard(const System::Collection::Array<3, bool> & mask, bool zero_val, System::Collection::Array<3, Uint32> & map); template void GC_DLL_EXPORT ChessBoard(const System::Collection::Array<3, bool> & mask, bool zero_val, System::Collection::Array<3, Uint64> & map); template void GC_DLL_EXPORT ChessBoard(const System::Collection::Array<2, Uint8> & mask, Uint8 zero_val, System::Collection::Array<2, Uint16> & map); template void GC_DLL_EXPORT ChessBoard(const System::Collection::Array<2, Uint8> & mask, Uint8 zero_val, System::Collection::Array<2, Uint32> & map); template void GC_DLL_EXPORT ChessBoard(const System::Collection::Array<2, Uint8> & mask, Uint8 zero_val, System::Collection::Array<2, Uint64> & map); template void GC_DLL_EXPORT ChessBoard(const System::Collection::Array<3, Uint8> & mask, Uint8 zero_val, System::Collection::Array<3, Uint16> & map); template void GC_DLL_EXPORT ChessBoard(const System::Collection::Array<3, Uint8> & mask, Uint8 zero_val, System::Collection::Array<3, Uint32> & map); template void GC_DLL_EXPORT ChessBoard(const System::Collection::Array<3, Uint8> & mask, Uint8 zero_val, System::Collection::Array<3, Uint64> & map); /** @endcond */ /******************************************************************************/ template <Size N, class DATA, class T> void CityBlockLocal(const System::Collection::Array<N, DATA> & mask, DATA val, System::Collection::Array<N, T> & map) { if (mask.Dimensions() != map.Dimensions()) { throw System::ArgumentException(__FUNCTION__, __LINE__, "Mask and map dimensions " "do not match."); } // Generate neighbourhood Energy::Neighbourhood<N, Int32> nb; nb.Elementary(); // Init temporary map System::Collection::Array<N, T> temp_map; temp_map.Resize(mask.Dimensions()); for (Size i = 0; i < mask.Elements(); i++) { temp_map[i] = (mask[i] != val) ? 0 : (std::numeric_limits<T>::max() - 1); } // Forward and backward scan if (!mask.IsEmpty()) { Scan(temp_map, nb.Negative()); Scan(temp_map, nb.Positive()); } // Copy distances to output for (Size i = 0; i < mask.Elements(); i++) { if (mask[i] == val) { map[i] = temp_map[i]; } } } /******************************************************************************/ // Explicit instantiations /** @cond */ template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<2, bool> & mask, bool val, System::Collection::Array<2, Uint16> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<2, bool> & mask, bool val, System::Collection::Array<2, Uint32> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<2, bool> & mask, bool val, System::Collection::Array<2, Uint64> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<3, bool> & mask, bool val, System::Collection::Array<3, Uint16> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<3, bool> & mask, bool val, System::Collection::Array<3, Uint32> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<3, bool> & mask, bool val, System::Collection::Array<3, Uint64> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<2, Uint8> & mask, Uint8 val, System::Collection::Array<2, Uint16> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<2, Uint8> & mask, Uint8 val, System::Collection::Array<2, Uint32> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<2, Uint8> & mask, Uint8 val, System::Collection::Array<2, Uint64> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<3, Uint8> & mask, Uint8 val, System::Collection::Array<3, Uint16> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<3, Uint8> & mask, Uint8 val, System::Collection::Array<3, Uint32> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<3, Uint8> & mask, Uint8 val, System::Collection::Array<3, Uint64> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<2, Uint16> & mask, Uint16 val, System::Collection::Array<2, Uint16> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<2, Uint16> & mask, Uint16 val, System::Collection::Array<2, Uint32> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<2, Uint16> & mask, Uint16 val, System::Collection::Array<2, Uint64> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<3, Uint16> & mask, Uint16 val, System::Collection::Array<3, Uint16> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<3, Uint16> & mask, Uint16 val, System::Collection::Array<3, Uint32> & map); template void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<3, Uint16> & mask, Uint16 val, System::Collection::Array<3, Uint64> & map); /** @endcond */ /******************************************************************************/ template <Size N, class DATA, class T> void ChessBoardLocal(const System::Collection::Array<N, DATA> & mask, DATA val, System::Collection::Array<N, T> & map) { if (mask.Dimensions() != map.Dimensions()) { throw System::ArgumentException(__FUNCTION__, __LINE__, "Mask and map dimensions " "do not match."); } // Generate neighbourhood Energy::Neighbourhood<N, Int32> nb; nb.Box(Math::Algebra::Vector<N, Size>(1), false, false); // Init temporary map System::Collection::Array<N, T> temp_map; temp_map.Resize(mask.Dimensions()); for (Size i = 0; i < mask.Elements(); i++) { temp_map[i] = (mask[i] != val) ? 0 : (std::numeric_limits<T>::max() - 1); } // Forward and backward scan if (!mask.IsEmpty()) { Scan(temp_map, nb.Negative()); Scan(temp_map, nb.Positive()); } // Copy distances to output for (Size i = 0; i < mask.Elements(); i++) { if (mask[i] == val) { map[i] = temp_map[i]; } } } /******************************************************************************/ // Explicit instantiations /** @cond */ template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<2, bool> & mask, bool val, System::Collection::Array<2, Uint16> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<2, bool> & mask, bool val, System::Collection::Array<2, Uint32> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<2, bool> & mask, bool val, System::Collection::Array<2, Uint64> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<3, bool> & mask, bool val, System::Collection::Array<3, Uint16> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<3, bool> & mask, bool val, System::Collection::Array<3, Uint32> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<3, bool> & mask, bool val, System::Collection::Array<3, Uint64> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<2, Uint8> & mask, Uint8 val, System::Collection::Array<2, Uint16> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<2, Uint8> & mask, Uint8 val, System::Collection::Array<2, Uint32> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<2, Uint8> & mask, Uint8 val, System::Collection::Array<2, Uint64> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<3, Uint8> & mask, Uint8 val, System::Collection::Array<3, Uint16> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<3, Uint8> & mask, Uint8 val, System::Collection::Array<3, Uint32> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<3, Uint8> & mask, Uint8 val, System::Collection::Array<3, Uint64> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<2, Uint16> & mask, Uint16 val, System::Collection::Array<2, Uint16> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<2, Uint16> & mask, Uint16 val, System::Collection::Array<2, Uint32> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<2, Uint16> & mask, Uint16 val, System::Collection::Array<2, Uint64> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<3, Uint16> & mask, Uint16 val, System::Collection::Array<3, Uint16> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<3, Uint16> & mask, Uint16 val, System::Collection::Array<3, Uint32> & map); template void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<3, Uint16> & mask, Uint16 val, System::Collection::Array<3, Uint64> & map); /** @endcond */ /******************************************************************************/ } } } } // namespace Gc::Algo::Geometry::DistanceTransform
reiern70/wicket-bootstrap
bootstrap-core/src/main/java/de/agilecoders/wicket/core/settings/IBootstrapSettings.java
<reponame>reiern70/wicket-bootstrap package de.agilecoders.wicket.core.settings; import org.apache.wicket.request.resource.ResourceReference; /** * Settings interface for bootstrap settings. * * @author miha */ public interface IBootstrapSettings { /** * The version of Bootstrap */ String VERSION = "3.1.1"; /** * The url to the JavaScript resource at a CDN network */ String JS_CDN_PATTERN = "//netdna.bootstrapcdn.com/bootstrap/%s/js/bootstrap.min.js"; /** * @param version The version of Twitter Bootstrap. CDN resources use it to construct their urls * @return same instance for chaining */ IBootstrapSettings setVersion(String version); /** * @return The version of Twitter Bootstrap. CDN resources use it to construct their urls */ String getVersion(); /** * @return True, if bootstrap resources should be added to each page automatically */ boolean autoAppendResources(); /** * @return the base twitter bootstrap css resource reference */ ResourceReference getCssResourceReference(); /** * @return the base twitter bootstrap JavaScript resource reference */ ResourceReference getJsResourceReference(); /** * @param reference a reference to the base twitter bootstrap css library. * Defaults to the embedded bootstrap.css * @return same instance for chaining */ IBootstrapSettings setCssResourceReference(ResourceReference reference); /** * @param reference a reference to the base twitter bootstrap JavaScript library. * Defaults to the embedded bootstrap.js * @return same instance for chaining */ IBootstrapSettings setJsResourceReference(ResourceReference reference); /** * @return javascript resource filter name */ String getJsResourceFilterName(); /** * set value to true, if bootstrap resources should be added to each page automatically * * @param value true, if bootstrap resources should be added to each page automatically * @return same instance for chaining */ IBootstrapSettings setAutoAppendResources(boolean value); /** * sets the filter name for all bootstrap js resource references * * @param name javascript resource filter name * @return same instance for chaining */ IBootstrapSettings setJsResourceFilterName(String name); /** * if true, all necessary exceptions will be added to security manager to allow * fonts and less files. (default is true) * * @param activate true, if security manger should be updated while installing these settings * @return same instance for chaining */ IBootstrapSettings setUpdateSecurityManager(boolean activate); /** * if true, all necessary exceptions will be added to security manager to allow * fonts and less files. (default is true) * * @return true, if security manger should be updated while installing these settings */ boolean updateSecurityManager(); /** * The {@link ActiveThemeProvider} provides access to the active theme * * @param themeProvider The {@link ActiveThemeProvider} instance * @return same instance for chaining */ IBootstrapSettings setActiveThemeProvider(ActiveThemeProvider themeProvider); /** * @return The {@link ActiveThemeProvider} instance */ ActiveThemeProvider getActiveThemeProvider(); /** * @return The {@link ThemeProvider} instance */ ThemeProvider getThemeProvider(); /** * The {@link ThemeProvider} instance provides access to all available themes. * * @param themeProvider The {@link ThemeProvider} instance * @return same instance for chaining */ IBootstrapSettings setThemeProvider(ThemeProvider themeProvider); /** * @return true, if the resources for the themes should be loaded from a CDN network */ boolean useCdnResources(); /** * @param useCdnResources a flag indicating whether the resources for the themes should be loaded from a CDN network * @return this instance */ IBootstrapSettings useCdnResources(boolean useCdnResources); }