code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Cqrs.NET: Properties Directory Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">Cqrs.NET
 <span id="projectnumber">2.0</span>
</div>
<div id="projectbrief">A lightweight enterprise framework to help write CQRS and Eventsourcing applications in C# and Azure</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('dir_705858b953ec1fc831a24a119d8dff47.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">Properties Directory Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a>
Files</h2></td></tr>
<tr class="memitem:Ninject_2Azure_2Cqrs_8Ninject_8Azure_8DocumentDb_2Properties_2AssemblyInfo_8cs"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>Ninject/Azure/Cqrs.Ninject.Azure.DocumentDb/Properties/AssemblyInfo.cs</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="dir_bcbb2cf9a3d3d83e5515c82071a07177.html">Framework</a></li><li class="navelem"><a class="el" href="dir_aeab9c509861352f3ed3b04436717e37.html">Ninject</a></li><li class="navelem"><a class="el" href="dir_144973b537f78713c042ca94e887150c.html">Azure</a></li><li class="navelem"><a class="el" href="dir_2580ae8bc6815dff0aae59825ce8c949.html">Cqrs.Ninject.Azure.DocumentDb</a></li><li class="navelem"><a class="el" href="dir_705858b953ec1fc831a24a119d8dff47.html">Properties</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li>
</ul>
</div>
</body>
</html>
|
cdmdotnet/CQRS
|
wiki/docs/2.0/html/dir_705858b953ec1fc831a24a119d8dff47.html
|
HTML
|
lgpl-2.1
| 4,755 |
//
// NCDBInvType.h
// Neocom
//
// Created by Artem Shimanski on 29.11.15.
// Copyright © 2015 Artem Shimanski. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@class NCDBCertCertificate, NCDBCertSkill, NCDBChrRace, NCDBDgmEffect, NCDBDgmTypeAttribute, NCDBDgmppHullType, NCDBDgmppItem, NCDBEveIcon, NCDBIndBlueprintType, NCDBIndProduct, NCDBIndRequiredMaterial, NCDBIndRequiredSkill, NCDBInvControlTower, NCDBInvControlTowerResource, NCDBInvGroup, NCDBInvMarketGroup, NCDBInvMetaGroup, NCDBInvTypeRequiredSkill, NCDBMapDenormalize, NCDBRamInstallationTypeContent, NCDBStaStation, NCDBTxtDescription, NCDBWhType;
NS_ASSUME_NONNULL_BEGIN
@interface NCDBInvType : NSManagedObject
// Insert code here to declare functionality of your managed object subclass
@end
NS_ASSUME_NONNULL_END
#import "NCDBInvType+CoreDataProperties.h"
|
mrdepth/EVEUniverse
|
Legacy/Old/Neocom/NCDBInvType.h
|
C
|
lgpl-2.1
| 879 |
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.observation.remote.converter;
import org.xwiki.component.annotation.Role;
import org.xwiki.observation.remote.LocalEventData;
import org.xwiki.observation.remote.RemoteEventData;
/**
* Convert a local event to a serializable remote event.
*
* @version $Id$
* @since 2.0M3
*/
@Role
public interface LocalEventConverter
{
/**
* @return the priority of the converter
*/
int getPriority();
/**
* Convert provided local event to remote event by filling the provided remote event object.
*
* @param localEvent the local event
* @param remoteEvent the remote event
* @return if the converter support this conversion it should return true after the conversion, otherwise false
*/
boolean toRemote(LocalEventData localEvent, RemoteEventData remoteEvent);
}
|
pbondoer/xwiki-platform
|
xwiki-platform-core/xwiki-platform-observation/xwiki-platform-observation-remote/src/main/java/org/xwiki/observation/remote/converter/LocalEventConverter.java
|
Java
|
lgpl-2.1
| 1,724 |
/*
* Copyright (C) 2014 Freie Universität Berlin
*
* This file is subject to the terms and conditions of the GNU Lesser General
* Public License v2.1. See the file LICENSE in the top level directory for more
* details.
*/
/**
* @ingroup cpu_nrf51822
* @{
*
* @file startup.c
* @brief Startup code and interrupt vector definition
*
* @author Hauke Petersen <[email protected]>
*
* @}
*/
#include <stdint.h>
#include "board.h"
/**
* memory markers as defined in the linker script
*/
extern uint32_t _sfixed;
extern uint32_t _efixed;
extern uint32_t _etext;
extern uint32_t _srelocate;
extern uint32_t _erelocate;
extern uint32_t _szero;
extern uint32_t _ezero;
extern uint32_t _sstack;
extern uint32_t _estack;
/**
* @brief functions for initializing the board, std-lib and kernel
*/
extern void board_init(void);
extern void kernel_init(void);
extern void __libc_init_array(void);
/**
* @brief This function is the entry point after a system reset
*
* After a system reset, the following steps are necessary and carried out:
* 1. load data section from flash to ram
* 2. overwrite uninitialized data section (BSS) with zeros
* 3. initialize the newlib
* 4. initialize the board (sync clock, setup std-IO)
* 5. initialize and start RIOTs kernel
*/
void reset_handler(void)
{
uint32_t *dst;
uint32_t *src = &_etext;
/* load data section from flash to ram */
for (dst = &_srelocate; dst < &_erelocate; ) {
*(dst++) = *(src++);
}
/* default bss section to zero */
for (dst = &_szero; dst < &_ezero; ) {
*(dst++) = 0;
}
/* initialize the board and startup the kernel */
board_init();
/* initialize std-c library (this should be done after board_init) */
__libc_init_array();
/* startup the kernel */
kernel_init();
}
/**
* @brief Default handler is called in case no interrupt handler was defined
*/
void dummy_handler(void)
{
while (1) {asm ("nop");}
}
void isr_nmi(void)
{
while (1) {asm ("nop");}
}
void isr_hard_fault(void)
{
LED_RED_ON;
while (1) {asm ("nop");}
}
/* Cortex-M specific interrupt vectors */
void isr_svc(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_pendsv(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_systick(void) __attribute__ ((weak, alias("dummy_handler")));
/* nRF51822qfaa specific interrupt vector */
void isr_power_clock(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_radio(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_uart0(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_spi0_twi0(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_spi1_twi1(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_gpiote(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_adc(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_timer0(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_timer1(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_timer2(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_rtc0(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_temp(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_rng(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_ecb(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_ccm_aar(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_wdt(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_rtc1(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_qdec(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_lpcomp(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_swi0(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_swi1(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_swi2(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_swi3(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_swi4(void) __attribute__ ((weak, alias("dummy_handler")));
void isr_swi5(void) __attribute__ ((weak, alias("dummy_handler")));
/* interrupt vector table */
__attribute__ ((section(".vectors")))
const void *interrupt_vector[] = {
/* Stack pointer */
(void*) (&_estack), /* pointer to the top of the empty stack */
/* Cortex-M handlers */
(void*) reset_handler, /* entry point of the program */
(void*) isr_nmi, /* non maskable interrupt handler */
(void*) isr_hard_fault, /* if you end up here its not good */
(void*) (0UL), /* reserved */
(void*) (0UL), /* reserved */
(void*) (0UL), /* reserved */
(void*) (0UL), /* reserved */
(void*) (0UL), /* reserved */
(void*) (0UL), /* reserved */
(void*) (0UL), /* reserved */
(void*) isr_svc, /* system call interrupt */
(void*) (0UL), /* reserved */
(void*) (0UL), /* reserved */
(void*) isr_pendsv, /* pendSV interrupt, used for task switching in RIOT */
(void*) isr_systick, /* SysTick interrupt, not used in RIOT */
/* nRF51 specific peripheral handlers */
(void*) isr_power_clock, /* power_clock */
(void*) isr_radio, /* radio */
(void*) isr_uart0, /* uart0 */
(void*) isr_spi0_twi0, /* spi0_twi0 */
(void*) isr_spi1_twi1, /* spi1_twi1 */
(void*) (0UL), /* reserved */
(void*) isr_gpiote, /* gpiote */
(void*) isr_adc, /* adc */
(void*) isr_timer0, /* timer0 */
(void*) isr_timer1, /* timer1 */
(void*) isr_timer2, /* timer2 */
(void*) isr_rtc0, /* rtc0 */
(void*) isr_temp, /* temp */
(void*) isr_rng, /* rng */
(void*) isr_ecb, /* ecb */
(void*) isr_ccm_aar, /* ccm_aar */
(void*) isr_wdt, /* wdt */
(void*) isr_rtc1, /* rtc1 */
(void*) isr_qdec, /* qdec */
(void*) isr_lpcomp, /* lpcomp */
(void*) isr_swi0, /* swi0 */
(void*) isr_swi1, /* swi1 */
(void*) isr_swi2, /* swi2 */
(void*) isr_swi3, /* swi3 */
(void*) isr_swi4, /* swi4 */
(void*) isr_swi5, /* swi5 */
(void*) (0UL), /* reserved */
(void*) (0UL), /* reserved */
(void*) (0UL), /* reserved */
(void*) (0UL), /* reserved */
(void*) (0UL), /* reserved */
(void*) (0UL), /* reserved */
};
|
ros2/ros2_embedded_riot
|
cpu/nrf51822/startup.c
|
C
|
lgpl-2.1
| 7,321 |
package mrriegel.rwl.gui;
import mrriegel.rwl.init.ModItems;
import mrriegel.rwl.inventory.IInventoryItem;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
public class CrySlot extends Slot {
IInventoryItem inv;
@Override
public void onSlotChanged() {
super.onSlotChanged();
inv.updateItems();
}
public CrySlot(IContainer con, IInventory inv, int p_i1824_2_,
int p_i1824_3_, int p_i1824_4_) {
super(inv, p_i1824_2_, p_i1824_3_, p_i1824_4_);
this.inv = (IInventoryItem) inv;
this.inv.setContainer(con);
}
@Override
public boolean isItemValid(ItemStack p) {
return p.getItem().equals(ModItems.cry);
}
}
|
MrRiegel/Kind-of-Magic
|
src/main/java/mrriegel/rwl/gui/CrySlot.java
|
Java
|
lgpl-2.1
| 702 |
/*
* This file is part of libnica.
*
* Copyright © 2016-2017 Intel Corporation
*
* libnica is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*/
#define _GNU_SOURCE
#include <check.h>
#include <malloc.h>
#include <stdlib.h>
#include "array.c"
#include "util.c"
START_TEST(nc_array_new_check)
{
NcArray *array = NULL;
array = nc_array_new();
fail_if(!array, "Failed to allocate new array");
fail_if(array->data, "array->data is not NULL after new");
fail_if(array->len != 0, "array->len is not 0 after new");
nc_array_free(&array, NULL);
}
END_TEST
START_TEST(nc_array_free_check)
{
NcArray *array = NULL;
nc_array_free(&array, NULL);
fail_if(array, "Free changed NULL array to non NULL");
/* Check to see if array free on NULL segfaults */
nc_array_free(NULL, NULL);
array = nc_array_new();
fail_if(!array, "Failed to allocate new array");
nc_array_free(&array, NULL);
fail_if(array, "Failed to set array to NULL");
}
END_TEST
static inline void nc_array_free_fun(void *p)
{
free(p);
}
START_TEST(nc_array_add_check)
{
NcArray *array = NULL;
int data1 = 1;
int data2 = 2;
int *data3 = NULL;
fail_if(nc_array_add(NULL, &data1), "Added data to NULL array");
array = nc_array_new();
fail_if(!array, "Failed to allocate new array");
fail_if(nc_array_add(array, NULL), "Added NULL data to array");
fail_if(!nc_array_add(array, &data1), "Failed to add data1 to array");
fail_if(!array->data, "Failed to allocate array->data");
fail_if(array->len != 1, "Failed to update array->len with the size of the array");
fail_if(*((int *)array->data[0]) != 1, "Failed to store correct data value to array");
array->len = (uint16_t)(0 - 1);
fail_if(nc_array_add(array, &data1), "Able to add more than max number of elements");
array->len = 1;
/* Test resize */
fail_if(!nc_array_add(array, &data2), "Failed to add second element to array");
fail_if(!array->data, "Failed to keep array->data");
fail_if(array->len != 2, "Failed to update array->len with new size");
fail_if(*((int *)array->data[0]) != 1, "Changed the first array element");
fail_if(*((int *)array->data[1]) != 2, "Failed to set the second array element");
nc_array_free(&array, NULL);
fail_if(array, "Failed to set array to NULL 1");
data3 = malloc(sizeof(int));
fail_if(!data3, "Failed to allocate data");
*data3 = 3;
array = nc_array_new();
fail_if(!array, "Failed to allocate new array");
fail_if(!nc_array_add(array, data3), "Failed to add pointer data");
fail_if(*((int *)array->data[0]) != 3,
"Failed to store correct pointer data value to array");
nc_array_free(&array, nc_array_free_fun);
fail_if(array, "Failed to set array to NULL 2");
}
END_TEST
START_TEST(nc_array_get_check)
{
NcArray *array = NULL;
int data1 = 1;
array = nc_array_new();
fail_if(!array, "Failed to allocate new array");
fail_if(nc_array_get(NULL, 0), "Got data from NULL array");
fail_if(nc_array_get(array, 0), "Got data from empty array");
fail_if(!nc_array_add(array, &data1), "Failed to add data1 to array");
fail_if(*((int *)nc_array_get(array, 0)) != 1, "Failed to get correct value for element 0");
fail_if(nc_array_get(array, 1), "Got data past end of array");
nc_array_free(&array, NULL);
fail_if(array, "Failed to set array to NULL");
}
END_TEST
START_TEST(nc_array_check)
{
NcArray *array = NULL;
char *value;
char *element;
void *f;
bool r;
array = nc_array_new();
fail_if(array == NULL, "Failed to allocate memory for NcArray");
element = strdup("test");
fail_if(!element, "Failed to allocate memory for array item");
r = nc_array_add(NULL, element);
fail_if(r, "Added element to NULL array");
r = nc_array_add(array, NULL);
fail_if(r, "Added NULL element to array");
r = nc_array_add(array, element);
fail_if(r == false, "Failed to add element to NcArray");
fail_if(array->len != 1, "Failed to get correct value for number of elements in array");
f = nc_array_get(NULL, 0);
fail_if(f, "Got value from NULL array");
f = nc_array_get(array, (uint16_t)(array->len + 1));
fail_if(f, "Got value from index bigger than maximum index");
value = (char *)nc_array_get(array, 0);
fail_if(value == NULL, "Failed to get value from NcArray");
fail_if(strcmp(value, "test") != 0, "Failed to retrieve the stored value");
nc_array_free(&array, nc_array_free_fun);
fail_if(array != NULL, "Failed to free NcArray");
}
END_TEST
static int sort_strings(const void *a, const void *b)
{
return strcmp(*(char **)a, *(char **)b);
}
static int sort_strings_reverse(const void *a, const void *b)
{
return strcmp(*(char **)b, *(char **)a);
}
START_TEST(nc_array_sort_check)
{
NcArray *array = NULL;
array = nc_array_new();
fail_if(!array, "Failed to allocate memory for NcArray");
fail_if(!nc_array_add(array, "gamma"), "Failed to add to array");
fail_if(!nc_array_add(array, "delta"), "Failed to add to array");
fail_if(!nc_array_add(array, "beta"), "Failed to add to array");
fail_if(!nc_array_add(array, "alpha"), "Failed to add to array");
fail_if(array->len != 4, "Array length invalid");
fail_if(!streq(nc_array_get(array, 0), "gamma"), "Invalid ordering in array #1");
fail_if(!streq(nc_array_get(array, 1), "delta"), "Invalid ordering in array #2");
fail_if(!streq(nc_array_get(array, 2), "beta"), "Invalid ordering in array #3");
fail_if(!streq(nc_array_get(array, 3), "alpha"), "Invalid ordering in array #4");
/* Alpha sort them */
nc_array_qsort(array, sort_strings);
fail_if(!streq(nc_array_get(array, 0), "alpha"), "Invalid sort ordering in array #1");
fail_if(!streq(nc_array_get(array, 1), "beta"), "Invalid sort ordering in array #2");
fail_if(!streq(nc_array_get(array, 2), "delta"), "Invalid sort ordering in array #3");
fail_if(!streq(nc_array_get(array, 3), "gamma"), "Invalid sort ordering in array #4");
/* Flip them back now */
nc_array_qsort(array, sort_strings_reverse);
fail_if(!streq(nc_array_get(array, 0), "gamma"), "Invalid reverse ordering in array #1");
fail_if(!streq(nc_array_get(array, 1), "delta"), "Invalid reverse ordering in array #2");
fail_if(!streq(nc_array_get(array, 2), "beta"), "Invalid reverse ordering in array #3");
fail_if(!streq(nc_array_get(array, 3), "alpha"), "Invalid reverse ordering in array #4");
nc_array_free(&array, NULL);
fail_if(array != NULL, "Failed to free NcArray");
}
END_TEST
int main(void)
{
int number_failed;
Suite *s;
SRunner *sr;
TCase *tc;
s = suite_create("nc_array");
tc = tcase_create("nc_array_functions");
tcase_add_test(tc, nc_array_new_check);
tcase_add_test(tc, nc_array_free_check);
tcase_add_test(tc, nc_array_add_check);
tcase_add_test(tc, nc_array_get_check);
tcase_add_test(tc, nc_array_check);
tcase_add_test(tc, nc_array_sort_check);
suite_add_tcase(s, tc);
sr = srunner_create(s);
srunner_run_all(sr, CK_VERBOSE);
number_failed = srunner_ntests_failed(sr);
srunner_free(sr);
return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
ikeydoherty/libthingamabob
|
tests/check-array.c
|
C
|
lgpl-2.1
| 8,294 |
<a href class="button" ngclipboard ngclipboard-success="onCopySuccess(e);" ngclipboard-error="onCopyError(e);" data-clipboard-action="copy" data-clipboard-target="#copytarget">
<img src="img/clippy.png" srcset="img/clippy.png 1x, img/clippy_2x.png 2x, img/clippy_3x.png 3x" style="vertical-align: middle;"/>
<span translate style="vertical-align: middle;">Copy</span>
</a>
|
mnaiman/duplicati
|
Duplicati/Server/webroot/ngax/templates/copy_clipboard_buttons.html
|
HTML
|
lgpl-2.1
| 381 |
/*
* vircgroup.h: methods for managing control cgroups
*
* Copyright (C) 2011-2015 Red Hat, Inc.
* Copyright IBM Corp. 2008
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "virutil.h"
#include "virbitmap.h"
#include "virenum.h"
struct _virCgroup;
typedef struct _virCgroup virCgroup;
typedef virCgroup *virCgroupPtr;
enum {
VIR_CGROUP_CONTROLLER_CPU,
VIR_CGROUP_CONTROLLER_CPUACCT,
VIR_CGROUP_CONTROLLER_CPUSET,
VIR_CGROUP_CONTROLLER_MEMORY,
VIR_CGROUP_CONTROLLER_DEVICES,
VIR_CGROUP_CONTROLLER_FREEZER,
VIR_CGROUP_CONTROLLER_BLKIO,
VIR_CGROUP_CONTROLLER_NET_CLS,
VIR_CGROUP_CONTROLLER_PERF_EVENT,
VIR_CGROUP_CONTROLLER_SYSTEMD,
VIR_CGROUP_CONTROLLER_LAST
};
VIR_ENUM_DECL(virCgroupController);
/* Items of this enum are used later in virCgroupNew to create
* bit array stored in int. Like this:
* 1 << VIR_CGROUP_CONTROLLER_CPU
* Make sure we will not overflow */
verify(VIR_CGROUP_CONTROLLER_LAST < 8 * sizeof(int));
typedef enum {
VIR_CGROUP_THREAD_VCPU = 0,
VIR_CGROUP_THREAD_EMULATOR,
VIR_CGROUP_THREAD_IOTHREAD,
VIR_CGROUP_THREAD_LAST
} virCgroupThreadName;
bool virCgroupAvailable(void);
int virCgroupNewSelf(virCgroupPtr *group)
ATTRIBUTE_NONNULL(1);
int virCgroupNewThread(virCgroupPtr domain,
virCgroupThreadName nameval,
int id,
bool create,
virCgroupPtr *group)
ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(5);
int virCgroupDelThread(virCgroupPtr cgroup,
virCgroupThreadName nameval,
int idx);
int virCgroupNewDetect(pid_t pid,
int controllers,
virCgroupPtr *group);
int
virCgroupNewDetectMachine(const char *name,
const char *drivername,
pid_t pid,
int controllers,
char *machinename,
virCgroupPtr *group)
ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2);
int virCgroupNewMachine(const char *name,
const char *drivername,
const unsigned char *uuid,
const char *rootdir,
pid_t pidleader,
bool isContainer,
size_t nnicindexes,
int *nicindexes,
const char *partition,
int controllers,
unsigned int maxthreads,
virCgroupPtr *group)
ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2)
ATTRIBUTE_NONNULL(3);
int virCgroupTerminateMachine(const char *name)
ATTRIBUTE_NONNULL(1);
bool virCgroupNewIgnoreError(void);
void virCgroupFree(virCgroupPtr *group);
bool virCgroupHasController(virCgroupPtr cgroup, int controller);
int virCgroupPathOfController(virCgroupPtr group,
unsigned int controller,
const char *key,
char **path);
int virCgroupAddProcess(virCgroupPtr group, pid_t pid);
int virCgroupAddMachineProcess(virCgroupPtr group, pid_t pid);
int virCgroupAddThread(virCgroupPtr group, pid_t pid);
int virCgroupSetBlkioWeight(virCgroupPtr group, unsigned int weight);
int virCgroupGetBlkioWeight(virCgroupPtr group, unsigned int *weight);
int virCgroupGetBlkioIoServiced(virCgroupPtr group,
long long *bytes_read,
long long *bytes_write,
long long *requests_read,
long long *requests_write);
int virCgroupGetBlkioIoDeviceServiced(virCgroupPtr group,
const char *path,
long long *bytes_read,
long long *bytes_write,
long long *requests_read,
long long *requests_write);
int virCgroupSetBlkioDeviceWeight(virCgroupPtr group,
const char *path,
unsigned int weight);
int virCgroupSetBlkioDeviceReadIops(virCgroupPtr group,
const char *path,
unsigned int riops);
int virCgroupSetBlkioDeviceWriteIops(virCgroupPtr group,
const char *path,
unsigned int wiops);
int virCgroupSetBlkioDeviceReadBps(virCgroupPtr group,
const char *path,
unsigned long long rbps);
int virCgroupSetBlkioDeviceWriteBps(virCgroupPtr group,
const char *path,
unsigned long long wbps);
int virCgroupGetBlkioDeviceWeight(virCgroupPtr group,
const char *path,
unsigned int *weight);
int virCgroupGetBlkioDeviceReadIops(virCgroupPtr group,
const char *path,
unsigned int *riops);
int virCgroupGetBlkioDeviceWriteIops(virCgroupPtr group,
const char *path,
unsigned int *wiops);
int virCgroupGetBlkioDeviceReadBps(virCgroupPtr group,
const char *path,
unsigned long long *rbps);
int virCgroupGetBlkioDeviceWriteBps(virCgroupPtr group,
const char *path,
unsigned long long *wbps);
int virCgroupSetMemory(virCgroupPtr group, unsigned long long kb);
int virCgroupGetMemoryStat(virCgroupPtr group,
unsigned long long *cache,
unsigned long long *activeAnon,
unsigned long long *inactiveAnon,
unsigned long long *activeFile,
unsigned long long *inactiveFile,
unsigned long long *unevictable);
int virCgroupGetMemoryUsage(virCgroupPtr group, unsigned long *kb);
int virCgroupSetMemoryHardLimit(virCgroupPtr group, unsigned long long kb);
int virCgroupGetMemoryHardLimit(virCgroupPtr group, unsigned long long *kb);
int virCgroupSetMemorySoftLimit(virCgroupPtr group, unsigned long long kb);
int virCgroupGetMemorySoftLimit(virCgroupPtr group, unsigned long long *kb);
int virCgroupSetMemSwapHardLimit(virCgroupPtr group, unsigned long long kb);
int virCgroupGetMemSwapHardLimit(virCgroupPtr group, unsigned long long *kb);
int virCgroupGetMemSwapUsage(virCgroupPtr group, unsigned long long *kb);
enum {
VIR_CGROUP_DEVICE_READ = 1,
VIR_CGROUP_DEVICE_WRITE = 2,
VIR_CGROUP_DEVICE_MKNOD = 4,
VIR_CGROUP_DEVICE_RW = VIR_CGROUP_DEVICE_READ | VIR_CGROUP_DEVICE_WRITE,
VIR_CGROUP_DEVICE_RWM = VIR_CGROUP_DEVICE_RW | VIR_CGROUP_DEVICE_MKNOD,
};
const char *virCgroupGetDevicePermsString(int perms);
int virCgroupDenyAllDevices(virCgroupPtr group);
int virCgroupAllowAllDevices(virCgroupPtr group, int perms);
int virCgroupAllowDevice(virCgroupPtr group,
char type,
int major,
int minor,
int perms);
int virCgroupAllowDevicePath(virCgroupPtr group,
const char *path,
int perms,
bool ignoreEacces);
int virCgroupDenyDevice(virCgroupPtr group,
char type,
int major,
int minor,
int perms);
int virCgroupDenyDevicePath(virCgroupPtr group,
const char *path,
int perms,
bool ignoreEacces);
int
virCgroupGetPercpuStats(virCgroupPtr group,
virTypedParameterPtr params,
unsigned int nparams,
int start_cpu,
unsigned int ncpus,
virBitmapPtr guestvcpus);
int
virCgroupGetDomainTotalCpuStats(virCgroupPtr group,
virTypedParameterPtr params,
int nparams);
int virCgroupSetCpuShares(virCgroupPtr group, unsigned long long shares);
int virCgroupGetCpuShares(virCgroupPtr group, unsigned long long *shares);
int virCgroupSetCpuCfsPeriod(virCgroupPtr group, unsigned long long cfs_period);
int virCgroupGetCpuCfsPeriod(virCgroupPtr group, unsigned long long *cfs_period);
int virCgroupSetCpuCfsQuota(virCgroupPtr group, long long cfs_quota);
int virCgroupGetCpuCfsQuota(virCgroupPtr group, long long *cfs_quota);
int virCgroupGetCpuacctUsage(virCgroupPtr group, unsigned long long *usage);
int virCgroupGetCpuacctPercpuUsage(virCgroupPtr group, char **usage);
int virCgroupGetCpuacctStat(virCgroupPtr group, unsigned long long *user,
unsigned long long *sys);
int virCgroupSetFreezerState(virCgroupPtr group, const char *state);
int virCgroupGetFreezerState(virCgroupPtr group, char **state);
int virCgroupSetCpusetMems(virCgroupPtr group, const char *mems);
int virCgroupGetCpusetMems(virCgroupPtr group, char **mems);
int virCgroupSetCpusetMemoryMigrate(virCgroupPtr group, bool migrate);
int virCgroupGetCpusetMemoryMigrate(virCgroupPtr group, bool *migrate);
int virCgroupSetCpusetCpus(virCgroupPtr group, const char *cpus);
int virCgroupGetCpusetCpus(virCgroupPtr group, char **cpus);
int virCgroupRemove(virCgroupPtr group);
int virCgroupKillRecursive(virCgroupPtr group, int signum);
int virCgroupKillPainfully(virCgroupPtr group);
int virCgroupBindMount(virCgroupPtr group,
const char *oldroot,
const char *mountopts);
bool virCgroupSupportsCpuBW(virCgroupPtr cgroup);
int virCgroupSetOwner(virCgroupPtr cgroup,
uid_t uid,
gid_t gid,
int controllers);
int virCgroupHasEmptyTasks(virCgroupPtr cgroup, int controller);
bool virCgroupControllerAvailable(int controller);
|
andreabolognani/libvirt
|
src/util/vircgroup.h
|
C
|
lgpl-2.1
| 10,973 |
/**
* LookupService.java
*
* Copyright (C) 2003 MaxMind LLC. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.maxmind.geoip;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.lang.*;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
/**
* Provides a lookup service for information based on an IP address. The location of
* a database file is supplied when creating a lookup service instance. The edition of
* the database determines what information is available about an IP address. See the
* DatabaseInfo class for further details.<p>
*
* The following code snippet demonstrates looking up the country that an IP
* address is from:
* <pre>
* // First, create a LookupService instance with the location of the database.
* LookupService lookupService = new LookupService("c:\\geoip.dat");
* // Assume we have a String ipAddress (in dot-decimal form).
* Country country = lookupService.getCountry(ipAddress);
* System.out.println("The country is: " + country.getName());
* System.out.println("The country code is: " + country.getCode());
* </pre>
*
* In general, a single LookupService instance should be created and then reused
* repeatedly.<p>
*
* <i>Tip:</i> Those deploying the GeoIP API as part of a web application may find it
* difficult to pass in a File to create the lookup service, as the location of the
* database may vary per deployment or may even be part of the web-application. In this
* case, the database should be added to the classpath of the web-app. For example, by
* putting it into the WEB-INF/classes directory of the web application. The following code
* snippet demonstrates how to create a LookupService using a database that can be found
* on the classpath:
*
* <pre>
* String fileName = getClass().getResource("/GeoIP.dat").toExternalForm().substring(6);
* LookupService lookupService = new LookupService(fileName);</pre>
*
* @author Matt Tucker ([email protected])
*/
public class LookupService {
/**
* Database file.
*/
private RandomAccessFile file = null;
private File databaseFile = null;
/**
* Information about the database.
*/
private DatabaseInfo databaseInfo = null;
/**
* The database type. Default is the country edition.
*/
byte databaseType = DatabaseInfo.COUNTRY_EDITION;
int databaseSegments[];
int recordLength;
String licenseKey;
int dnsService = 0;
int dboptions;
byte dbbuffer[];
byte index_cache[];
long mtime;
private final static int US_OFFSET = 1;
private final static int CANADA_OFFSET = 677;
private final static int WORLD_OFFSET = 1353;
private final static int FIPS_RANGE = 360;
private final static int COUNTRY_BEGIN = 16776960;
private final static int STATE_BEGIN_REV0 = 16700000;
private final static int STATE_BEGIN_REV1 = 16000000;
private final static int STRUCTURE_INFO_MAX_SIZE = 20;
private final static int DATABASE_INFO_MAX_SIZE = 100;
public final static int GEOIP_STANDARD = 0;
public final static int GEOIP_MEMORY_CACHE = 1;
public final static int GEOIP_CHECK_CACHE = 2;
public final static int GEOIP_INDEX_CACHE = 4;
public final static int GEOIP_UNKNOWN_SPEED = 0;
public final static int GEOIP_DIALUP_SPEED = 1;
public final static int GEOIP_CABLEDSL_SPEED = 2;
public final static int GEOIP_CORPORATE_SPEED = 3;
private final static int SEGMENT_RECORD_LENGTH = 3;
private final static int STANDARD_RECORD_LENGTH = 3;
private final static int ORG_RECORD_LENGTH = 4;
private final static int MAX_RECORD_LENGTH = 4;
private final static int MAX_ORG_RECORD_LENGTH = 300;
private final static int FULL_RECORD_LENGTH = 60;
private static final Country UNKNOWN_COUNTRY = new Country("--", "N/A");
private final static HashMap hashmapcountryCodetoindex = new HashMap(512);
private final static HashMap hashmapcountryNametoindex = new HashMap(512);
private final static String[] countryCode = {
"--","AP","EU","AD","AE","AF","AG","AI","AL","AM","AN","AO","AQ","AR",
"AS","AT","AU","AW","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ",
"BM","BN","BO","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF",
"CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CX","CY","CZ",
"DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI",
"FJ","FK","FM","FO","FR","FX","GA","GB","GD","GE","GF","GH","GI","GL",
"GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR",
"HT","HU","ID","IE","IL","IN","IO","IQ","IR","IS","IT","JM","JO","JP",
"KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC",
"LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","MG","MH","MK",
"ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY",
"MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM",
"PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY",
"QA","RE","RO","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ",
"SK","SL","SM","SN","SO","SR","ST","SV","SY","SZ","TC","TD","TF","TG",
"TH","TJ","TK","TM","TN","TO","TL","TR","TT","TV","TW","TZ","UA","UG",
"UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","YE",
"YT","RS","ZA","ZM","ME","ZW","A1","A2","O1","AX","GG","IM","JE","BL",
"MF"};
private final static String[] countryName = {
"N/A","Asia/Pacific Region","Europe","Andorra","United Arab Emirates",
"Afghanistan","Antigua and Barbuda","Anguilla","Albania","Armenia",
"Netherlands Antilles","Angola","Antarctica","Argentina","American Samoa",
"Austria","Australia","Aruba","Azerbaijan","Bosnia and Herzegovina",
"Barbados","Bangladesh","Belgium","Burkina Faso","Bulgaria","Bahrain",
"Burundi","Benin","Bermuda","Brunei Darussalam","Bolivia","Brazil","Bahamas",
"Bhutan","Bouvet Island","Botswana","Belarus","Belize","Canada",
"Cocos (Keeling) Islands","Congo, The Democratic Republic of the",
"Central African Republic","Congo","Switzerland","Cote D'Ivoire",
"Cook Islands","Chile","Cameroon","China","Colombia","Costa Rica","Cuba",
"Cape Verde","Christmas Island","Cyprus","Czech Republic","Germany",
"Djibouti","Denmark","Dominica","Dominican Republic","Algeria","Ecuador",
"Estonia","Egypt","Western Sahara","Eritrea","Spain","Ethiopia","Finland",
"Fiji","Falkland Islands (Malvinas)","Micronesia, Federated States of",
"Faroe Islands","France","France, Metropolitan","Gabon","United Kingdom",
"Grenada","Georgia","French Guiana","Ghana","Gibraltar","Greenland","Gambia",
"Guinea","Guadeloupe","Equatorial Guinea","Greece",
"South Georgia and the South Sandwich Islands","Guatemala","Guam",
"Guinea-Bissau","Guyana","Hong Kong","Heard Island and McDonald Islands",
"Honduras","Croatia","Haiti","Hungary","Indonesia","Ireland","Israel","India",
"British Indian Ocean Territory","Iraq","Iran, Islamic Republic of",
"Iceland","Italy","Jamaica","Jordan","Japan","Kenya","Kyrgyzstan","Cambodia",
"Kiribati","Comoros","Saint Kitts and Nevis",
"Korea, Democratic People's Republic of","Korea, Republic of","Kuwait",
"Cayman Islands","Kazakhstan","Lao People's Democratic Republic","Lebanon",
"Saint Lucia","Liechtenstein","Sri Lanka","Liberia","Lesotho","Lithuania",
"Luxembourg","Latvia","Libyan Arab Jamahiriya","Morocco","Monaco",
"Moldova, Republic of","Madagascar","Marshall Islands",
"Macedonia","Mali","Myanmar","Mongolia",
"Macau","Northern Mariana Islands","Martinique","Mauritania","Montserrat",
"Malta","Mauritius","Maldives","Malawi","Mexico","Malaysia","Mozambique",
"Namibia","New Caledonia","Niger","Norfolk Island","Nigeria","Nicaragua",
"Netherlands","Norway","Nepal","Nauru","Niue","New Zealand","Oman","Panama",
"Peru","French Polynesia","Papua New Guinea","Philippines","Pakistan",
"Poland","Saint Pierre and Miquelon","Pitcairn Islands","Puerto Rico","" +
"Palestinian Territory","Portugal","Palau","Paraguay","Qatar",
"Reunion","Romania","Russian Federation","Rwanda","Saudi Arabia",
"Solomon Islands","Seychelles","Sudan","Sweden","Singapore","Saint Helena",
"Slovenia","Svalbard and Jan Mayen","Slovakia","Sierra Leone","San Marino",
"Senegal","Somalia","Suriname","Sao Tome and Principe","El Salvador",
"Syrian Arab Republic","Swaziland","Turks and Caicos Islands","Chad",
"French Southern Territories","Togo","Thailand","Tajikistan","Tokelau",
"Turkmenistan","Tunisia","Tonga","Timor-Leste","Turkey","Trinidad and Tobago",
"Tuvalu","Taiwan","Tanzania, United Republic of","Ukraine","Uganda",
"United States Minor Outlying Islands","United States","Uruguay","Uzbekistan",
"Holy See (Vatican City State)","Saint Vincent and the Grenadines",
"Venezuela","Virgin Islands, British","Virgin Islands, U.S.","Vietnam",
"Vanuatu","Wallis and Futuna","Samoa","Yemen","Mayotte","Serbia",
"South Africa","Zambia","Montenegro","Zimbabwe","Anonymous Proxy",
"Satellite Provider","Other","Aland Islands","Guernsey","Isle of Man","Jersey",
"Saint Barthelemy","Saint Martin"};
/**
* Create a new distributed lookup service using the license key
*
* @param databaseFile String representation of the database file.
* @param licenseKey license key provided by Maxmind to access distributed service
*/
public LookupService(String databaseFile,String licenseKey) throws IOException {
this(new File(databaseFile));
this.licenseKey = licenseKey;
dnsService = 1;
}
/**
* Create a new distributed lookup service using the license key
*
* @param databaseFile the database file.
* @param licenseKey license key provided by Maxmind to access distributed service
*/
public LookupService(File databaseFile,String licenseKey) throws IOException {
this(databaseFile);
this.licenseKey = licenseKey;
dnsService = 1;
}
/**
* Create a new distributed lookup service using the license key
*
* @param options Resevered for future use
* @param licenseKey license key provided by Maxmind to access distributed service
*/
public LookupService(int options,String licenseKey) throws IOException {
this.licenseKey = licenseKey;
dnsService = 1;
init();
}
/**
* Create a new lookup service using the specified database file.
*
* @param databaseFile String representation of the database file.
* @throws java.io.IOException if an error occured creating the lookup service
* from the database file.
*/
public LookupService(String databaseFile) throws IOException {
this(new File(databaseFile));
}
/**
* Create a new lookup service using the specified database file.
*
* @param databaseFile the database file.
* @throws java.io.IOException if an error occured creating the lookup service
* from the database file.
*/
public LookupService(File databaseFile) throws IOException {
this.databaseFile = databaseFile;
this.file = new RandomAccessFile(databaseFile, "r");
init();
}
/**
* Create a new lookup service using the specified database file.
*
* @param databaseFile String representation of the database file.
* @param options database flags to use when opening the database
* GEOIP_STANDARD read database from disk
* GEOIP_MEMORY_CACHE cache the database in RAM and read it from RAM
* @throws java.io.IOException if an error occured creating the lookup service
* from the database file.
*/
public LookupService(String databaseFile, int options) throws IOException{
this(new File(databaseFile),options);
}
/**
* Create a new lookup service using the specified database file.
*
* @param databaseFile the database file.
* @param options database flags to use when opening the database
* GEOIP_STANDARD read database from disk
* GEOIP_MEMORY_CACHE cache the database in RAM and read it from RAM
* @throws java.io.IOException if an error occured creating the lookup service
* from the database file.
*/
public LookupService(File databaseFile, int options) throws IOException{
this.databaseFile = databaseFile;
this.file = new RandomAccessFile(databaseFile, "r");
dboptions = options;
init();
}
/**
* Reads meta-data from the database file.
*
* @throws java.io.IOException if an error occurs reading from the database file.
*/
private void init() throws IOException {
int i, j;
byte [] delim = new byte[3];
byte [] buf = new byte[SEGMENT_RECORD_LENGTH];
if (file == null) {
// distributed service only
for (i = 0; i < 233;i++){
hashmapcountryCodetoindex.put(countryCode[i],new Integer(i));
hashmapcountryNametoindex.put(countryName[i],new Integer(i));
}
return;
}
if ((dboptions & GEOIP_CHECK_CACHE) != 0) {
mtime = databaseFile.lastModified();
}
file.seek(file.length() - 3);
for (i = 0; i < STRUCTURE_INFO_MAX_SIZE; i++) {
file.read(delim);
if (delim[0] == -1 && delim[1] == -1 && delim[2] == -1) {
databaseType = file.readByte();
if (databaseType >= 106) {
// Backward compatibility with databases from April 2003 and earlier
databaseType -= 105;
}
// Determine the database type.
if (databaseType == DatabaseInfo.REGION_EDITION_REV0) {
databaseSegments = new int[1];
databaseSegments[0] = STATE_BEGIN_REV0;
recordLength = STANDARD_RECORD_LENGTH;
}else if (databaseType == DatabaseInfo.REGION_EDITION_REV1){
databaseSegments = new int[1];
databaseSegments[0] = STATE_BEGIN_REV1;
recordLength = STANDARD_RECORD_LENGTH;
}
else if (databaseType == DatabaseInfo.CITY_EDITION_REV0 ||
databaseType == DatabaseInfo.CITY_EDITION_REV1 ||
databaseType == DatabaseInfo.ORG_EDITION ||
databaseType == DatabaseInfo.ISP_EDITION ||
databaseType == DatabaseInfo.ASNUM_EDITION) {
databaseSegments = new int[1];
databaseSegments[0] = 0;
if (databaseType == DatabaseInfo.CITY_EDITION_REV0 ||
databaseType == DatabaseInfo.CITY_EDITION_REV1 ||
databaseType == DatabaseInfo.ASNUM_EDITION) {
recordLength = STANDARD_RECORD_LENGTH;
}
else {
recordLength = ORG_RECORD_LENGTH;
}
file.read(buf);
for (j = 0; j < SEGMENT_RECORD_LENGTH; j++) {
databaseSegments[0] += (unsignedByteToInt(buf[j]) << (j * 8));
}
}
break;
}
else {
file.seek(file.getFilePointer() - 4);
}
}
if ((databaseType == DatabaseInfo.COUNTRY_EDITION) |
(databaseType == DatabaseInfo.PROXY_EDITION) |
(databaseType == DatabaseInfo.NETSPEED_EDITION)) {
databaseSegments = new int[1];
databaseSegments[0] = COUNTRY_BEGIN;
recordLength = STANDARD_RECORD_LENGTH;
}
if ((dboptions & GEOIP_MEMORY_CACHE) == 1) {
int l = (int) file.length();
dbbuffer = new byte[l];
file.seek(0);
file.read(dbbuffer,0,l);
databaseInfo = this.getDatabaseInfo();
file.close();
}
if ((dboptions & GEOIP_INDEX_CACHE) != 0) {
int l = databaseSegments[0] * recordLength * 2;
index_cache = new byte[l];
if (index_cache != null){
file.seek(0);
file.read(index_cache,0,l);
}
} else {
index_cache = null;
}
}
/**
* Closes the lookup service.
*/
public void close() {
try {
if (file != null){
file.close();
}
file = null;
}
catch (Exception e) { }
}
/**
* Returns the country the IP address is in.
*
* @param ipAddress String version of an IP address, i.e. "127.0.0.1"
* @return the country the IP address is from.
*/
public Country getCountry(String ipAddress) {
InetAddress addr;
try {
addr = InetAddress.getByName(ipAddress);
}
catch (UnknownHostException e) {
return UNKNOWN_COUNTRY;
}
return getCountry(bytesToLong(addr.getAddress()));
}
/**
* Returns the country the IP address is in.
*
* @param ipAddress the IP address.
* @return the country the IP address is from.
*/
public Country getCountry(InetAddress ipAddress) {
return getCountry(bytesToLong(ipAddress.getAddress()));
}
/**
* Returns the country the IP address is in.
*
* @param ipAddress the IP address in long format.
* @return the country the IP address is from.
*/
public Country getCountry(long ipAddress) {
if (file == null && (dboptions & GEOIP_MEMORY_CACHE) == 0) {
throw new IllegalStateException("Database has been closed.");
}
int ret = seekCountry(ipAddress) - COUNTRY_BEGIN;
if (ret == 0) {
return UNKNOWN_COUNTRY;
}
else {
return new Country(countryCode[ret], countryName[ret]);
}
}
public int getID(String ipAddress) {
InetAddress addr;
try {
addr = InetAddress.getByName(ipAddress);
}
catch (UnknownHostException e) {
return 0;
}
return getID(bytesToLong(addr.getAddress()));
}
public int getID(InetAddress ipAddress) {
return getID(bytesToLong(ipAddress.getAddress()));
}
public int getID(long ipAddress) {
if (file == null && (dboptions & GEOIP_MEMORY_CACHE) == 0) {
throw new IllegalStateException("Database has been closed.");
}
int ret = seekCountry(ipAddress) - databaseSegments[0];
return ret;
}
/**
* Returns information about the database.
*
* @return database info.
*/
public DatabaseInfo getDatabaseInfo() {
if (databaseInfo != null) {
return databaseInfo;
}
try {
// Synchronize since we're accessing the database file.
synchronized (this) {
_check_mtime();
boolean hasStructureInfo = false;
byte [] delim = new byte[3];
// Advance to part of file where database info is stored.
file.seek(file.length() - 3);
for (int i=0; i<STRUCTURE_INFO_MAX_SIZE; i++) {
file.read(delim);
if (delim[0] == 255 && delim[1] == 255 && delim[2] == 255) {
hasStructureInfo = true;
break;
}
}
if (hasStructureInfo) {
file.seek(file.getFilePointer() - 3);
}
else {
// No structure info, must be pre Sep 2002 database, go back to end.
file.seek(file.length() - 3);
}
// Find the database info string.
for (int i=0; i<DATABASE_INFO_MAX_SIZE; i++) {
file.read(delim);
if (delim[0]==0 && delim[1]==0 && delim[2]==0) {
byte[] dbInfo = new byte[i];
file.read(dbInfo);
// Create the database info object using the string.
this.databaseInfo = new DatabaseInfo(new String(dbInfo));
return databaseInfo;
}
file.seek(file.getFilePointer() -4);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return new DatabaseInfo("");
}
synchronized void _check_mtime(){
try {
if ((dboptions & GEOIP_CHECK_CACHE) != 0){
long t = databaseFile.lastModified();
if (t != mtime){
/* GeoIP Database file updated */
/* refresh filehandle */
file.close();
file = new RandomAccessFile(databaseFile,"r");
databaseInfo = null;
init();
}
}
} catch (IOException e) {
System.out.println("file not found");
}
}
// for GeoIP City only
public Location getLocation(InetAddress addr) {
return getLocation(bytesToLong(addr.getAddress()));
}
// for GeoIP City only
public Location getLocation(String str) {
if (dnsService == 0) {
InetAddress addr;
try {
addr = InetAddress.getByName(str);
}
catch (UnknownHostException e) {
return null;
}
return getLocation(addr);
} else {
String str2 = getDnsAttributes(str);
return getLocationwithdnsservice(str2);
// TODO if DNS is not available, go to local file as backup
}
}
String getDnsAttributes(String ip) {
try {
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
// TODO don't specify ws1, instead use ns servers for s.maxmind.com
env.put("java.naming.provider.url","dns://ws1.maxmind.com/");
DirContext ictx = new InitialDirContext(env);
Attributes attrs = ictx.getAttributes(licenseKey + "." + ip + ".s.maxmind.com", new String[] {"txt"});
//System.out.println(attrs.get("txt").get());
String str = attrs.get("txt").get().toString();
return str;
}
catch(NamingException e) {
// TODO fix this to handle exceptions
System.out.println("DNS error");
return null;
}
}
public Location getLocationwithdnsservice(String str) {
Location record = new Location();
String key;
String value;
StringTokenizer st = new StringTokenizer(str,";=\"");
while (st.hasMoreTokens()) {
key = st.nextToken();
if (st.hasMoreTokens()) {
value = st.nextToken();
} else {
value = "";}
if (key.equals("co")) {
Integer i = (Integer)hashmapcountryCodetoindex.get(value);
record.countryCode = value;
record.countryName = countryName[i.intValue()];
}
if (key.equals("ci")) {
record.city = value;
}
if (key.equals("re")) {
record.region = value;
}
if (key.equals("zi")) {
record.postalCode = value;
}
// TODO, ISP and Organization
//if (key.equals("or")) {
//record.org = value;
//}
//if (key.equals("is")) {
//record.isp = value;
//}
if (key.equals("la")) {
try{
record.latitude = Float.parseFloat(value);
} catch(NumberFormatException e) {
record.latitude = 0;
}
}
if (key.equals("lo")) {
try{
record.longitude = Float.parseFloat(value);
} catch(NumberFormatException e) {
record.latitude = 0;
}
}
// dm depreciated use me ( metro_code ) instead
if (key.equals("dm") || key.equals("me")) {
try{
record.metro_code = record.dma_code = Integer.parseInt(value);
} catch(NumberFormatException e) {
record.metro_code = record.dma_code = 0;
}
}
if (key.equals("ac")) {
try{
record.area_code = Integer.parseInt(value);
} catch(NumberFormatException e) {
record.area_code = 0;
}
}
}
return record;
}
public synchronized Region getRegion(String str) {
InetAddress addr;
try {
addr = InetAddress.getByName(str);
}
catch (UnknownHostException e) {
return null;
}
return getRegion(bytesToLong(addr.getAddress()));
}
public synchronized Region getRegion(long ipnum) {
Region record = new Region();
int seek_region = 0;
if (databaseType == DatabaseInfo.REGION_EDITION_REV0) {
seek_region = seekCountry(ipnum) - STATE_BEGIN_REV0;
char ch[] = new char[2];
if (seek_region >= 1000) {
record.countryCode = "US";
record.countryName = "United States";
ch[0] = (char)(((seek_region - 1000)/26) + 65);
ch[1] = (char)(((seek_region - 1000)%26) + 65);
record.region = new String(ch);
} else {
record.countryCode = countryCode[seek_region];
record.countryName = countryName[seek_region];
record.region = "";
}
} else if (databaseType == DatabaseInfo.REGION_EDITION_REV1) {
seek_region = seekCountry(ipnum) - STATE_BEGIN_REV1;
char ch[] = new char[2];
if (seek_region < US_OFFSET) {
record.countryCode = "";
record.countryName = "";
record.region = "";
} else if (seek_region < CANADA_OFFSET) {
record.countryCode = "US";
record.countryName = "United States";
ch[0] = (char)(((seek_region - US_OFFSET)/26) + 65);
ch[1] = (char)(((seek_region - US_OFFSET)%26) + 65);
record.region = new String(ch);
} else if (seek_region < WORLD_OFFSET) {
record.countryCode = "CA";
record.countryName = "Canada";
ch[0] = (char)(((seek_region - CANADA_OFFSET)/26) + 65);
ch[1] = (char)(((seek_region - CANADA_OFFSET)%26) + 65);
record.region = new String(ch);
} else {
record.countryCode = countryCode[(seek_region - WORLD_OFFSET) / FIPS_RANGE];
record.countryName = countryName[(seek_region - WORLD_OFFSET) / FIPS_RANGE];
record.region = "";
}
}
return record;
}
public synchronized Location getLocation(long ipnum) {
int record_pointer;
byte record_buf[] = new byte[FULL_RECORD_LENGTH];
int record_buf_offset = 0;
Location record = new Location();
int str_length = 0;
int j, seek_country;
double latitude = 0, longitude = 0;
try {
seek_country = seekCountry(ipnum);
if (seek_country == databaseSegments[0]) {
return null;
}
record_pointer = seek_country + (2 * recordLength - 1) * databaseSegments[0];
if ((dboptions & GEOIP_MEMORY_CACHE) == 1) {
//read from memory
System.arraycopy(dbbuffer, record_pointer, record_buf, 0, Math.min(dbbuffer.length - record_pointer, FULL_RECORD_LENGTH));
} else {
//read from disk
file.seek(record_pointer);
file.read(record_buf);
}
// get country
record.countryCode = countryCode[unsignedByteToInt(record_buf[0])];
record.countryName = countryName[unsignedByteToInt(record_buf[0])];
record_buf_offset++;
// get region
while (record_buf[record_buf_offset + str_length] != '\0')
str_length++;
if (str_length > 0) {
record.region = new String(record_buf, record_buf_offset, str_length);
}
record_buf_offset += str_length + 1;
str_length = 0;
// get city
while (record_buf[record_buf_offset + str_length] != '\0')
str_length++;
if (str_length > 0) {
record.city = new String(record_buf, record_buf_offset, str_length, "ISO-8859-1");
}
record_buf_offset += str_length + 1;
str_length = 0;
// get postal code
while (record_buf[record_buf_offset + str_length] != '\0')
str_length++;
if (str_length > 0) {
record.postalCode = new String(record_buf, record_buf_offset, str_length);
}
record_buf_offset += str_length + 1;
// get latitude
for (j = 0; j < 3; j++)
latitude += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8));
record.latitude = (float) latitude/10000 - 180;
record_buf_offset += 3;
// get longitude
for (j = 0; j < 3; j++)
longitude += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8));
record.longitude = (float) longitude/10000 - 180;
record.dma_code = record.metro_code = 0;
record.area_code = 0;
if (databaseType == DatabaseInfo.CITY_EDITION_REV1) {
// get DMA code
int metroarea_combo = 0;
if (record.countryCode == "US") {
record_buf_offset += 3;
for (j = 0; j < 3; j++)
metroarea_combo += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8));
record.metro_code = record.dma_code = metroarea_combo/1000;
record.area_code = metroarea_combo % 1000;
}
}
}
catch (IOException e) {
System.err.println("IO Exception while seting up segments");
}
return record;
}
public String getOrg(InetAddress addr) {
return getOrg(bytesToLong(addr.getAddress()));
}
public String getOrg(String str) {
InetAddress addr;
try {
addr = InetAddress.getByName(str);
}
catch (UnknownHostException e) {
return null;
}
return getOrg(addr);
}
// GeoIP Organization and ISP Edition methods
public synchronized String getOrg(long ipnum) {
int seek_org;
int record_pointer;
int str_length = 0;
byte [] buf = new byte[MAX_ORG_RECORD_LENGTH];
String org_buf;
try {
seek_org = seekCountry(ipnum);
if (seek_org == databaseSegments[0]) {
return null;
}
record_pointer = seek_org + (2 * recordLength - 1) * databaseSegments[0];
if ((dboptions & GEOIP_MEMORY_CACHE) == 1) {
//read from memory
System.arraycopy(dbbuffer, record_pointer, buf, 0, Math.min(dbbuffer.length - record_pointer, MAX_ORG_RECORD_LENGTH));
} else {
//read from disk
file.seek(record_pointer);
file.read(buf);
}
while (buf[str_length] != '\0') {
str_length++;
}
org_buf = new String(buf, 0, str_length, "ISO-8859-1");
return org_buf;
}
catch (IOException e) {
System.out.println("IO Exception");
return null;
}
}
/**
* Finds the country index value given an IP address.
*
* @param ipAddress the ip address to find in long format.
* @return the country index.
*/
private synchronized int seekCountry(long ipAddress) {
byte [] buf = new byte[2 * MAX_RECORD_LENGTH];
int [] x = new int[2];
int offset = 0;
_check_mtime();
for (int depth = 31; depth >= 0; depth--) {
if ((dboptions & GEOIP_MEMORY_CACHE) == 1) {
//read from memory
for (int i = 0;i < 2 * MAX_RECORD_LENGTH;i++) {
buf[i] = dbbuffer[(2 * recordLength * offset)+i];
}
} else if ((dboptions & GEOIP_INDEX_CACHE) != 0) {
//read from index cache
for (int i = 0;i < 2 * MAX_RECORD_LENGTH;i++) {
buf[i] = index_cache[(2 * recordLength * offset)+i];
}
} else {
//read from disk
try {
file.seek(2 * recordLength * offset);
file.read(buf);
}
catch (IOException e) {
System.out.println("IO Exception");
}
}
for (int i = 0; i<2; i++) {
x[i] = 0;
for (int j = 0; j<recordLength; j++) {
int y = buf[i*recordLength+j];
if (y < 0) {
y+= 256;
}
x[i] += (y << (j * 8));
}
}
if ((ipAddress & (1 << depth)) > 0) {
if (x[1] >= databaseSegments[0]) {
return x[1];
}
offset = x[1];
}
else {
if (x[0] >= databaseSegments[0]) {
return x[0];
}
offset = x[0];
}
}
// shouldn't reach here
System.err.println("Error seeking country while seeking " + ipAddress);
return 0;
}
/**
* Returns the long version of an IP address given an InetAddress object.
*
* @param address the InetAddress.
* @return the long form of the IP address.
*/
private static long bytesToLong(byte [] address) {
long ipnum = 0;
for (int i = 0; i < 4; ++i) {
long y = address[i];
if (y < 0) {
y+= 256;
}
ipnum += y << ((3-i)*8);
}
return ipnum;
}
private static int unsignedByteToInt(byte b) {
return (int) b & 0xFF;
}
}
|
domdorn/geo-ip
|
src/main/java/com/maxmind/geoip/LookupService.java
|
Java
|
lgpl-2.1
| 33,946 |
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QSignalSpy>
#include <QTimer>
#include <QHostAddress>
#include <QDebug>
#include <QThread>
#include <QtCore/QLibraryInfo>
#include "../shared/debugutil_p.h"
#include "../../../shared/util.h"
#include "qqmlinspectorclient.h"
#include "qqmlenginedebugclient.h"
#define PORT 3776
#define STR_PORT "3776"
class tst_QQmlEngineDebugInspectorIntegration : public QQmlDataTest
{
Q_OBJECT
public:
tst_QQmlEngineDebugInspectorIntegration()
: m_process(0)
, m_connection(0)
, m_inspectorClient(0)
, m_engineDebugClient(0)
{
}
private:
QmlDebugObjectReference findRootObject();
QQmlDebugProcess *m_process;
QQmlDebugConnection *m_connection;
QQmlInspectorClient *m_inspectorClient;
QQmlEngineDebugClient *m_engineDebugClient;
private slots:
void init();
void cleanup();
void connect();
void clearObjectReferenceHashonReloadQml();
};
QmlDebugObjectReference tst_QQmlEngineDebugInspectorIntegration::findRootObject()
{
bool success = false;
m_engineDebugClient->queryAvailableEngines(&success);
QQmlDebugTest::waitForSignal(m_engineDebugClient, SIGNAL(result()));
m_engineDebugClient->queryRootContexts(m_engineDebugClient->engines()[0].debugId, &success);
QQmlDebugTest::waitForSignal(m_engineDebugClient, SIGNAL(result()));
int count = m_engineDebugClient->rootContext().contexts.count();
m_engineDebugClient->queryObject(
m_engineDebugClient->rootContext().contexts[count - 1].objects[0], &success);
QQmlDebugTest::waitForSignal(m_engineDebugClient, SIGNAL(result()));
return m_engineDebugClient->object();
}
void tst_QQmlEngineDebugInspectorIntegration::init()
{
const QString argument = "-qmljsdebugger=port:" STR_PORT ",block";
m_process = new QQmlDebugProcess(QLibraryInfo::location(QLibraryInfo::BinariesPath)
+ "/qmlscene", this);
m_process->start(QStringList() << argument << testFile("qtquick2.qml"));
QVERIFY2(m_process->waitForSessionStart(),
"Could not launch application, or did not get 'Waiting for connection'.");
QQmlDebugConnection *m_connection = new QQmlDebugConnection(this);
m_inspectorClient = new QQmlInspectorClient(m_connection);
m_engineDebugClient = new QQmlEngineDebugClient(m_connection);
m_connection->connectToHost(QLatin1String("127.0.0.1"), PORT);
bool ok = m_connection->waitForConnected();
QVERIFY(ok);
}
void tst_QQmlEngineDebugInspectorIntegration::cleanup()
{
if (QTest::currentTestFailed()) {
qDebug() << "Process State:" << m_process->state();
qDebug() << "Application Output:" << m_process->output();
}
delete m_process;
delete m_engineDebugClient;
delete m_inspectorClient;
}
void tst_QQmlEngineDebugInspectorIntegration::connect()
{
QTRY_COMPARE(m_inspectorClient->state(), QQmlDebugClient::Enabled);
QTRY_COMPARE(m_engineDebugClient->state(), QQmlDebugClient::Enabled);
}
void tst_QQmlEngineDebugInspectorIntegration::clearObjectReferenceHashonReloadQml()
{
QTRY_COMPARE(m_engineDebugClient->state(), QQmlDebugClient::Enabled);
bool success = false;
QmlDebugObjectReference rootObject = findRootObject();
const QString fileName = QFileInfo(rootObject.source.url.toString()).fileName();
int lineNumber = rootObject.source.lineNumber;
int columnNumber = rootObject.source.columnNumber;
m_engineDebugClient->queryObjectsForLocation(fileName, lineNumber,
columnNumber, &success);
QVERIFY(success);
QVERIFY(QQmlDebugTest::waitForSignal(m_engineDebugClient, SIGNAL(result())));
foreach (QmlDebugObjectReference child, rootObject.children) {
success = false;
lineNumber = child.source.lineNumber;
columnNumber = child.source.columnNumber;
m_engineDebugClient->queryObjectsForLocation(fileName, lineNumber,
columnNumber, &success);
QVERIFY(success);
QVERIFY(QQmlDebugTest::waitForSignal(m_engineDebugClient, SIGNAL(result())));
}
QTRY_COMPARE(m_inspectorClient->state(), QQmlDebugClient::Enabled);
QByteArray contents;
contents.append("import QtQuick 2.0\n"
"Text {"
"y: 10\n"
"text: \"test\"\n"
"}");
QHash<QString, QByteArray> changesHash;
changesHash.insert("test.qml", contents);
m_inspectorClient->reloadQml(changesHash);
QVERIFY(QQmlDebugTest::waitForSignal(m_inspectorClient, SIGNAL(responseReceived())));
lineNumber = rootObject.source.lineNumber;
columnNumber = rootObject.source.columnNumber;
success = false;
m_engineDebugClient->queryObjectsForLocation(fileName, lineNumber,
columnNumber, &success);
QVERIFY(success);
QVERIFY(QQmlDebugTest::waitForSignal(m_engineDebugClient, SIGNAL(result())));
foreach (QmlDebugObjectReference child, rootObject.children) {
success = false;
lineNumber = child.source.lineNumber;
columnNumber = child.source.columnNumber;
m_engineDebugClient->queryObjectsForLocation(fileName, lineNumber,
columnNumber, &success);
QVERIFY(success);
QVERIFY(QQmlDebugTest::waitForSignal(m_engineDebugClient, SIGNAL(result())));
}
}
QTEST_MAIN(tst_QQmlEngineDebugInspectorIntegration)
#include "tst_qqmlenginedebuginspectorintegration.moc"
|
jfaust/qtdeclarative
|
tests/auto/qml/debugger/qqmlenginedebuginspectorintegrationtest/tst_qqmlenginedebuginspectorintegration.cpp
|
C++
|
lgpl-2.1
| 7,498 |
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program 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) version 2.1, February 1999.
#
# 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
import sys
class Emacs(AutotoolsPackage):
"""The Emacs programmable text editor."""
homepage = "https://www.gnu.org/software/emacs"
url = "http://ftp.gnu.org/gnu/emacs/emacs-24.5.tar.gz"
version('26.1', '544d2ab5eb142e9ca69adb023d17bf4b')
version('25.3', '74ddd373dc52ac05ca7a8c63b1ddbf58')
version('25.2', '0a36d1cdbba6024d4dbbac027f87995f')
version('25.1', '95c12e6a9afdf0dcbdd7d2efa26ca42c')
version('24.5', 'd74b597503a68105e61b5b9f6d065b44')
variant('X', default=False, description="Enable an X toolkit")
variant(
'toolkit',
default='gtk',
values=('gtk', 'athena'),
description="Select an X toolkit (gtk, athena)"
)
variant('tls', default=False, description="Build Emacs with gnutls")
depends_on('pkgconfig', type='build')
depends_on('ncurses')
depends_on('pcre')
depends_on('zlib')
depends_on('libtiff', when='+X')
depends_on('libpng', when='+X')
depends_on('libxpm', when='+X')
depends_on('giflib', when='+X')
depends_on('libx11', when='+X')
depends_on('libxaw', when='+X toolkit=athena')
depends_on('gtkplus', when='+X toolkit=gtk')
depends_on('gnutls', when='+tls')
def configure_args(self):
spec = self.spec
toolkit = spec.variants['toolkit'].value
if '+X' in spec:
args = [
'--with-x',
'--with-x-toolkit={0}'.format(toolkit)
]
else:
args = ['--without-x']
# On OS X/macOS, do not build "nextstep/Emacs.app", because
# doing so throws an error at build-time
if sys.platform == 'darwin':
args.append('--without-ns')
if '+tls' in spec:
args.append('--with-gnutls')
else:
args.append('--without-gnutls')
return args
|
tmerrick1/spack
|
var/spack/repos/builtin/packages/emacs/package.py
|
Python
|
lgpl-2.1
| 3,112 |
/*
* Copyright (C) 2014 absurdworlds
* Copyright (C) 2016 Hedede <[email protected]>
*
* License LGPLv3 or later:
* GNU Lesser GPL version 3 <http://gnu.org/licenses/lgpl-3.0.html>
* This is free software: you are free to change and redistribute it.
* There is NO WARRANTY, to the extent permitted by law.
*/
#ifndef aw_fileformat_png_reader_h
#define aw_fileformat_png_reader_h
#include <aw/io/input_stream.h>
#include <aw/types/optional.h>
#include <vector>
namespace aw {
namespace png {
struct image {
std::vector<std::byte> data;
unsigned width, height;
};
optional<image> read(io::input_stream& stream) noexcept;
} // namespace png
} // namespace aw
#endif//aw_fileformat_png_reader_h
|
absurdworlds/awlib
|
include/aw/fileformat/png/reader.h
|
C
|
lgpl-3.0
| 705 |
<?php if (!defined('FLUX_ROOT')) exit; ?>
<h2>Viewing Monster</h2>
<?php if ($monster): ?>
<h3>
#<?php echo $monster->monster_id ?>: <?php echo htmlspecialchars($monster->name_english) ?>
<?php if ($monster->mvp_exp): ?>
<span class="mvp">(MVP)</span>
<?php endif ?>
</h3>
<table class="vertical-table">
<tr>
<th>Monster ID</th>
<td><?php echo $monster->monster_id ?></td>
<?php if ($image=$this->monsterImage($monster->monster_id)): ?>
<td rowspan="12" style="width:150px; text-align: center; vertical-alignment: middle">
<img src="<?php echo $image ?>" />
</td>
<?php endif ?>
<th>Sprite</th>
<td><?php echo htmlspecialchars($monster->sprite) ?></td>
</tr>
<tr>
<th>kRO Name</th>
<td><?php echo htmlspecialchars($monster->name_japanese) ?></td>
<th>Custom</th>
<td>
<?php if (preg_match('/mob_db2$/', $monster->origin_table)): ?>
Yes
<?php else: ?>
No
<?php endif ?>
</td>
</tr>
<tr>
<th>iRO Name</th>
<td><?php echo htmlspecialchars($monster->name_english) ?></td>
<th>HP</th>
<td><?php echo number_format($monster->hp) ?></td>
</tr>
<tr>
<th>Size</th>
<td>
<?php if ($size=Flux::monsterSizeName($monster->size)): ?>
<?php echo htmlspecialchars($size) ?>
<?php else: ?>
<span class="not-applicable">Unknown</span>
<?php endif ?>
</td>
<th>SP</th>
<td><?php echo number_format($monster->sp) ?></td>
</tr>
<tr>
<th>Race</th>
<td>
<?php if ($race=Flux::monsterRaceName($monster->race)): ?>
<?php echo htmlspecialchars($race) ?>
<?php else: ?>
<span class="not-applicable">Unknown</span>
<?php endif ?>
</td>
<th>Level</th>
<td><?php echo number_format($monster->level) ?></td>
</tr>
<tr>
<th>Element</th>
<td><?php echo Flux::elementName($monster->element) ?> (Lv <?php echo floor($monster->element_level) ?>)</td>
<th>Speed</th>
<td><?php echo number_format($monster->walk_speed) ?></td>
</tr>
<tr>
<th>Experience</th>
<td><?php echo number_format($monster->base_exp) ?></td>
<th>Attack</th>
<td><?php echo number_format($monster->attack) ?>~<?php echo number_format($monster->attack2) ?></td>
</tr>
<tr>
<th>Job Experience</th>
<td><?php echo number_format($monster->job_exp) ?></td>
<th>Defense</th>
<td><?php echo number_format($monster->defense) ?></td>
</tr>
<tr>
<th>MVP Experience</th>
<td><?php echo number_format($monster->mvp_exp) ?></td>
<th>Magic Defense</th>
<td><?php echo number_format($monster->magic_defense) ?></td>
</tr>
<tr>
<th>Attack Delay</th>
<td><?php echo number_format($monster->attack_delay) ?> ms</td>
<th>Attack Range</th>
<td><?php echo number_format($monster->attack_range) ?></td>
</tr>
<tr>
<th>Attack Motion</th>
<td><?php echo number_format($monster->attack_motion) ?> ms</td>
<th>Spell Range</th>
<td><?php echo number_format($monster->skill_range) ?></td>
</tr>
<tr>
<th>Delay Motion</th>
<td><?php echo number_format($monster->damage_motion) ?> ms</td>
<th>Vision Range</th>
<td><?php echo number_format($monster->chase_range) ?></td>
</tr>
<tr>
<th>Monster Mode</th>
<td colspan="<?php echo $image ? 4 : 3 ?>">
<ul class="monster-mode">
<?php foreach ($this->monsterMode($modes, $monster->ai) as $mode): ?>
<li><?php echo htmlspecialchars($mode) ?></li>
<?php endforeach ?>
</ul>
</td>
</tr>
<tr>
<th>Monster Stats</th>
<td colspan="<?php echo $image ? 4 : 3 ?>">
<table class="character-stats">
<tr>
<td><span class="stat-name">STR</span></td>
<td><span class="stat-value"><?php echo number_format((int)$monster->strength) ?></span></td>
<td><span class="stat-name">AGI</span></td>
<td><span class="stat-value"><?php echo number_format((int)$monster->agility) ?></span></td>
<td><span class="stat-name">VIT</span></td>
<td><span class="stat-value"><?php echo number_format((int)$monster->vitality) ?></span></td>
</tr>
<tr>
<td><span class="stat-name">INT</span></td>
<td><span class="stat-value"><?php echo number_format((int)$monster->intelligence) ?></span></td>
<td><span class="stat-name">DEX</span></td>
<td><span class="stat-value"><?php echo number_format((int)$monster->dexterity) ?></span></td>
<td><span class="stat-name">LUK</span></td>
<td><span class="stat-value"><?php echo number_format((int)$monster->luck) ?></span></td>
</tr>
</table>
</td>
</tr>
</table>
<h3><?php echo htmlspecialchars($monster->name_english) ?> Item Drops</h3>
<?php if ($itemDrops): ?>
<table class="vertical-table">
<tr>
<th>Item ID</th>
<th colspan="2">Item Name</th>
<th>Drop Chance</th>
<th>Can be stealed</th>
</tr>
<?php $mvpDrops = 0; ?>
<?php foreach ($itemDrops as $itemDrop): ?>
<tr class="item-drop-<?php echo $itemDrop['type'] ?>"
title="<strong><?php echo htmlspecialchars($itemDrop['name']) ?></strong> (<?php echo (float)$itemDrop['chance'] ?>%)">
<td align="right">
<?php if ($auth->actionAllowed('item', 'view')): ?>
<?php echo $this->linkToItem($itemDrop['id'], $itemDrop['id']) ?>
<?php else: ?>
<?php echo htmlspecialchars($itemDrop['id']) ?>
<?php endif ?>
</td>
<?php if ($image=$this->iconImage($itemDrop['id'])): ?>
<td><img src="<?php echo $image ?>" /></td>
<td>
<?php if ($itemDrop['type'] == 'mvp'): ?>
<?php ++$mvpDrops; ?>
<span class="mvp">MVP!</span>
<?php endif ?>
<?php echo htmlspecialchars($itemDrop['name']) ?>
</td>
<?php else: ?>
<td colspan="2">
<?php if ($itemDrop['type'] == 'mvp'): ?>
<?php ++$mvpDrops; ?>
<span class="mvp">MVP!</span>
<?php endif ?>
<?php echo htmlspecialchars($itemDrop['name']) ?>
</td>
<?php endif ?>
<td><?php echo (float)$itemDrop['chance'] ?>%</td>
<td><?php echo htmlspecialchars(Flux::message($itemDrop['nosteal'])) ?></td>
</tr>
<?php endforeach ?>
<?php if ($mvpDrops > 1): ?>
<tr>
<td colspan="5" align="center">
<p><em>Note: Only <strong>one</strong> MVP drop will be rewarded.</em></p>
</td>
</tr>
<?php endif ?>
</table>
<?php else: ?>
<p>No item drops found for <?php echo htmlspecialchars($monster->name_english) ?>.</p>
<?php endif ?>
<h3>Monster Skills for “<?php echo htmlspecialchars($monster->name_english) ?>”</h3>
<?php if ($mobSkills): ?>
<table class="vertical-table">
<tr>
<th>Name</th>
<th>Level</th>
<th>State</th>
<th>Rate</th>
<th>Cast Time</th>
<th>Delay</th>
<th>Cancelable</th>
<th>Target</th>
<th>Condition</th>
<th>Value</th>
</tr>
<?php foreach ($mobSkills as $skill): ?>
<tr>
<td><?php echo htmlspecialchars($skill->INFO) ?></td>
<td><?php echo htmlspecialchars($skill->SKILL_LV) ?></td>
<td><?php echo htmlspecialchars(ucfirst($skill->STATE)) ?></td>
<td><?php echo $skill->RATE/100 ?>%</td>
<td><?php echo $skill->CASTTIME/1000 ?>s</td>
<td><?php echo $skill->DELAY/1000 ?>s</td>
<td><?php echo htmlspecialchars(ucfirst($skill->CANCELABLE)) ?></td>
<td><?php echo htmlspecialchars(ucfirst($skill->TARGET)) ?></td>
<td><em><?php echo htmlspecialchars($skill->CONDITION) ?></em></td>
<td>
<?php if (!is_null($skill->CONDITION_VALUE) && trim($skill->CONDITION_VALUE) !== ''): ?>
<?php echo htmlspecialchars($skill->CONDITION_VALUE) ?>
<?php else: ?>
<span class="not-applicable">None</span>
<?php endif ?>
</td>
</tr>
<?php endforeach ?>
</table>
<?php else: ?>
<p>No skills found for <?php echo htmlspecialchars($monster->name_english) ?>.</p>
<?php endif ?>
<?php else: ?>
<p>No such monster was found. <a href="javascript:history.go(-1)">Go back</a>.</p>
<?php endif ?>
|
rathena/FluxCP
|
themes/default/monster/view.php
|
PHP
|
lgpl-3.0
| 7,600 |
// Copyright 2014 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package exec_test
import (
"path/filepath"
"syscall"
"github.com/juju/testing"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"github.com/juju/utils/exec"
)
type execSuite struct {
testing.IsolationSuite
}
var _ = gc.Suite(&execSuite{})
// longPath is copied over from the symlink package. This should be removed
// if we add it to gc or in some other convenience package
func longPath(path string) ([]uint16, error) {
pathp, err := syscall.UTF16FromString(path)
if err != nil {
return nil, err
}
longp := pathp
n, err := syscall.GetLongPathName(&pathp[0], &longp[0], uint32(len(longp)))
if err != nil {
return nil, err
}
if n > uint32(len(longp)) {
longp = make([]uint16, n)
n, err = syscall.GetLongPathName(&pathp[0], &longp[0], uint32(len(longp)))
if err != nil {
return nil, err
}
}
longp = longp[:n]
return longp, nil
}
func longPathAsString(path string) (string, error) {
longp, err := longPath(path)
if err != nil {
return "", err
}
return syscall.UTF16ToString(longp), nil
}
func (*execSuite) TestRunCommands(c *gc.C) {
newDir, err := longPathAsString(c.MkDir())
c.Assert(err, gc.IsNil)
for i, test := range []struct {
message string
commands string
workingDir string
environment []string
stdout string
stderr string
code int
}{
{
message: "test stdout capture",
commands: "echo 'testing stdout'",
stdout: "testing stdout\r\n",
}, {
message: "test stderr capture",
commands: "Write-Error 'testing stderr'",
stderr: "testing stderr\r\n",
}, {
message: "test return code",
commands: "exit 42",
code: 42,
}, {
message: "test working dir",
commands: "(pwd).Path",
workingDir: newDir,
stdout: filepath.FromSlash(newDir) + "\r\n",
}, {
message: "test environment",
commands: "echo $env:OMG_IT_WORKS",
environment: []string{"OMG_IT_WORKS=like magic"},
stdout: "like magic\r\n",
},
} {
c.Logf("%v: %s", i, test.message)
params := exec.RunParams{
Commands: test.commands,
WorkingDir: test.workingDir,
Environment: test.environment,
}
result, err := exec.RunCommands(params)
c.Assert(err, gc.IsNil)
c.Assert(string(result.Stdout), gc.Equals, test.stdout)
c.Assert(string(result.Stderr), jc.Contains, test.stderr)
c.Assert(result.Code, gc.Equals, test.code)
err = params.Run()
c.Assert(err, gc.IsNil)
c.Assert(params.Process(), gc.Not(gc.IsNil))
result, err = params.Wait()
c.Assert(err, gc.IsNil)
c.Assert(string(result.Stdout), gc.Equals, test.stdout)
c.Assert(string(result.Stderr), jc.Contains, test.stderr)
c.Assert(result.Code, gc.Equals, test.code)
}
}
func (*execSuite) TestExecUnknownCommand(c *gc.C) {
result, err := exec.RunCommands(
exec.RunParams{
Commands: "unknown-command",
},
)
c.Assert(err, gc.IsNil)
c.Assert(result.Stdout, gc.HasLen, 0)
c.Assert(string(result.Stderr), jc.Contains, "is not recognized as the name of a cmdlet")
// 1 is returned by RunCommands when powershell commands throw exceptions
c.Assert(result.Code, gc.Equals, 1)
}
|
cherylj/utils
|
exec/exec_windows_test.go
|
GO
|
lgpl-3.0
| 3,217 |
/*
* Method2_pairs.h
*
* Created on: 8 Jan, 2015
* Author: z
*/
#ifndef PARSING2_PROCESS_METHOD2_PAIRS_H_
#define PARSING2_PROCESS_METHOD2_PAIRS_H_
//method 2: the pairs(target function max(0,1+f(-)-f(+)))
// almost same as Method1
#include "Process.h"
class Method2_pairs: public Process{
protected:
REAL* data;
//REAL* target; --- don't need it
int current;
int end;
REAL* gradient;
protected:
virtual int each_get_mach_outdim(){return 1;}
virtual void each_prepare_data_oneiter();
virtual REAL* each_next_data(int*);
virtual void each_get_grad(int);
public:
Method2_pairs(string conf):Process(conf){
data = 0;
//target = 0;
gradient = 0;
}
};
#endif /* PARSING2_PROCESS_METHOD2_PAIRS_H_ */
|
zzsfornlp/nngdparser
|
src/process_graph/Method2_pairs.h
|
C
|
lgpl-3.0
| 730 |
#include <WinSock2.h>
#include <ws2tcpip.h>
#include <bwm801.h>
#include <sstream>
#include <cstring>
using namespace bwm801;
class winsock
{
public:
WSADATA m_wsaData;
bool m_bInitialized;
winsock(void)
{
m_bInitialized = false;
}
~winsock(void)
{
if (m_bInitialized)
WSACleanup();
}
void Initialize(void)
{
// Initialize Winsock
int iResult = WSAStartup(MAKEWORD(2, 2), &m_wsaData);
m_bInitialized = (iResult == 0);
}
};
winsock g_cWinsock;
class socket_info_win
{
public:
SOCKET m_iSocket_ID;
SOCKET m_iAccept_Socket_ID;
struct addrinfo * m_lpsAddress_Info;
int m_iLast_Error;
socket_info_win(void)
{
m_iAccept_Socket_ID = INVALID_SOCKET;
m_iSocket_ID = INVALID_SOCKET;
m_lpsAddress_Info = NULL;
m_iLast_Error = 0;
}
};
bool commsocket::Initialize_Server(stream_type i_eType, unsigned short i_usPort)
{
bool bError_Reported = false;
struct addrinfo hints;// , *res;
// int sockfd;
std::ostringstream szPort;
szPort << i_usPort;
socket_info_win * lpSock_Info = new socket_info_win;
m_lpvSystem_Info = (void *)lpSock_Info;
bool bError = (lpSock_Info == NULL);
// first, load up address structs with getaddrinfo():
m_eType = i_eType;
if (!bError)
{
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6, whichever
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // fill in my IP for me
bError = (getaddrinfo(NULL, szPort.str().c_str(), &hints, &(lpSock_Info->m_lpsAddress_Info)) == -1);
}
else if (!bError_Reported)
{
fprintf(stderr,"Error initializing port: failed to allocate socket information\n");
bError_Reported = true;
lpSock_Info->m_iLast_Error = errno;
}
// make a socket:
if (!bError)
{
lpSock_Info->m_iAccept_Socket_ID = socket(lpSock_Info->m_lpsAddress_Info->ai_family, lpSock_Info->m_lpsAddress_Info->ai_socktype, lpSock_Info->m_lpsAddress_Info->ai_protocol);
bError = lpSock_Info->m_iAccept_Socket_ID == -1;
}
else if (!bError_Reported)
{
fprintf(stderr,"Error initializing port: failed to get address information\n");
bError_Reported = true;
lpSock_Info->m_iLast_Error = errno;
}
// bind it to the port we passed in to getaddrinfo():
if (!bError)
{
bError = (bind(lpSock_Info->m_iAccept_Socket_ID, lpSock_Info->m_lpsAddress_Info->ai_addr, lpSock_Info->m_lpsAddress_Info->ai_addrlen) == -1);
}
else if (!bError_Reported)
{
fprintf(stderr,"Error initializing port: failed to open socket\n");
bError_Reported = true;
lpSock_Info->m_iLast_Error = errno;
}
if (!bError)
{
bError = (listen(lpSock_Info->m_iAccept_Socket_ID, 20) == -1);
}
else if (!bError_Reported)
{
fprintf(stderr,"Error initializing port: failed to bind\n");
bError_Reported = true;
lpSock_Info->m_iLast_Error = errno;
}
m_bIs_Initialized = !bError;
if (bError)
{
if (lpSock_Info)
delete lpSock_Info;
m_lpvSystem_Info = NULL;
if (!bError_Reported)
{
fprintf(stderr,"Error initializing port: failed to listen %i\n",errno);
bError_Reported = true;
lpSock_Info->m_iLast_Error = errno;
}
}
if (bError_Reported)
{
fprintf(stderr,"%s\n",strerror(errno));
}
return !bError;
}
bool commsocket::Initialize_Client(stream_type i_eType, const std::string &i_szServer_Addr, unsigned short i_usPort)
{
bool bError_Reported = false;
struct addrinfo hints;// , *res;
// int sockfd;
std::ostringstream szPort;
m_eType = i_eType;
szPort << i_usPort;
socket_info_win * lpSock_Info = new socket_info_win;
m_lpvSystem_Info = (void *)lpSock_Info;
bool bError = (lpSock_Info == NULL);
// first, load up address structs with getaddrinfo():
if (!bError)
{
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6, whichever
hints.ai_socktype = SOCK_STREAM;
bError = (getaddrinfo(i_szServer_Addr.c_str(), szPort.str().c_str(), &hints, &(lpSock_Info->m_lpsAddress_Info)) == -1);
}
else if (!bError_Reported)
{
fprintf(stderr,"Error initializing port: failed to allocate socket information\n");
bError_Reported = true;
lpSock_Info->m_iLast_Error = errno;
}
// make a socket:
if (!bError)
{
lpSock_Info->m_iSocket_ID = socket(lpSock_Info->m_lpsAddress_Info->ai_family, lpSock_Info->m_lpsAddress_Info->ai_socktype, lpSock_Info->m_lpsAddress_Info->ai_protocol);
bError = lpSock_Info->m_iSocket_ID == -1;
}
else if (!bError_Reported)
{
fprintf(stderr,"Error initializing port: failed to get addr info\n");
bError_Reported = true;
lpSock_Info->m_iLast_Error = errno;
}
// connect to the remote server we passed in to getaddrinfo():
if (!bError)
{
bError = (connect(lpSock_Info->m_iSocket_ID, lpSock_Info->m_lpsAddress_Info->ai_addr, lpSock_Info->m_lpsAddress_Info->ai_addrlen) == -1);
}
else if (!bError_Reported)
{
fprintf(stderr,"Error initializing port: failed to open socket\n");
bError_Reported = true;
lpSock_Info->m_iLast_Error = errno;
}
m_bIs_Initialized = !bError;
m_bIs_Connected = !bError;
if (bError)
{
delete lpSock_Info;
m_lpvSystem_Info = NULL;
if (!bError_Reported)
{
fprintf(stderr,"Error initializing port: failed to connect\n");
bError_Reported = true;
lpSock_Info->m_iLast_Error = errno;
}
}
else
lpSock_Info->m_iAccept_Socket_ID = lpSock_Info->m_iSocket_ID;
if (bError_Reported)
{
fprintf(stderr,"%s\n",strerror(errno));
}
return !bError;
}
int * g_lpiData_Container = NULL;
size_t g_zInt_Data_Container_Size = 0;
short * g_lpsData_Container = NULL;
size_t g_zShort_Data_Container_Size = 0;
bool commsocket::Send(const int *i_lpiData, size_t i_zNum_To_Send)
{
bool bSuccess = false;
if (m_bIs_Initialized && m_bIs_Connected && m_lpvSystem_Info)
{
socket_info_win * lpSock_Info = (socket_info_win *)m_lpvSystem_Info;
if (i_zNum_To_Send > g_zInt_Data_Container_Size)
{
if (g_lpiData_Container)
delete [] g_lpiData_Container;
g_lpiData_Container = new int[i_zNum_To_Send];
g_zInt_Data_Container_Size = i_zNum_To_Send;
}
for (unsigned int uiI = 0; uiI < i_zNum_To_Send; uiI++)
g_lpiData_Container[uiI] = htonl(i_lpiData[uiI]);
bSuccess = Send((const char *)g_lpiData_Container,i_zNum_To_Send * sizeof(int));
}
return bSuccess;
}
bool commsocket::Send(const short *i_lpiData, size_t i_zNum_To_Send)
{
bool bSuccess = false;
if (m_bIs_Initialized && m_bIs_Connected && m_lpvSystem_Info)
{
socket_info_win * lpSock_Info = (socket_info_win *)m_lpvSystem_Info;
if (i_zNum_To_Send > g_zShort_Data_Container_Size)
{
if (g_lpsData_Container)
delete [] g_lpsData_Container;
g_lpsData_Container = new short[i_zNum_To_Send];
g_zShort_Data_Container_Size = i_zNum_To_Send;
}
for (unsigned int uiI = 0; uiI < i_zNum_To_Send; uiI++)
g_lpsData_Container[uiI] = htons(i_lpiData[uiI]);
bSuccess = Send((const char *)g_lpsData_Container,sizeof(short) * i_zNum_To_Send);
}
return bSuccess;
}
bool commsocket::Send(const char * i_lplpcData, size_t i_zNum_To_Send)
{
bool bSuccess = false;
if (m_bIs_Initialized && m_bIs_Connected && m_lpvSystem_Info)
{
socket_info_win * lpSock_Info = (socket_info_win *)m_lpvSystem_Info;
size_t zSent = 0;
size_t zSent_Total = 0;
unsigned int uiTries = 0;
while (zSent != -1 && zSent_Total < i_zNum_To_Send && uiTries < m_uiMax_Tries)
{
unsigned int uiTransmit_Idx = zSent_Total;
zSent = send(lpSock_Info->m_iSocket_ID,&(i_lplpcData[uiTransmit_Idx]),i_zNum_To_Send - uiTransmit_Idx,0);
if (zSent == -1)
lpSock_Info->m_iLast_Error = errno;
else
{
// for (unsigned int uiI = 0; uiI < zSent; uiI++)
// {
// printf("Sent %x\n",i_lplpcData[uiTransmit_Idx + uiI]);
// }
zSent_Total += zSent;
uiTries++;
}
}
bSuccess = (zSent_Total == i_zNum_To_Send);
if (zSent == -1)
fprintf(stderr,"%s\n",strerror(errno));
}
return bSuccess;
}
bool commsocket::Send(const unsigned int *i_lpiData, size_t i_zNum_To_Send)
{
bool bSuccess = false;
if (m_bIs_Initialized && m_bIs_Connected && m_lpvSystem_Info)
{
socket_info_win * lpSock_Info = (socket_info_win *)m_lpvSystem_Info;
if (i_zNum_To_Send > g_zInt_Data_Container_Size)
{
if (g_lpiData_Container)
delete [] g_lpiData_Container;
g_lpiData_Container = new int[i_zNum_To_Send];
g_zInt_Data_Container_Size = i_zNum_To_Send;
}
for (unsigned int uiI = 0; uiI < i_zNum_To_Send; uiI++)
g_lpiData_Container[uiI] = htonl(i_lpiData[uiI]);
bSuccess = Send((const unsigned char *)g_lpiData_Container,i_zNum_To_Send * sizeof(int));
}
return bSuccess;
}
bool commsocket::Send(const unsigned short *i_lpiData, size_t i_zNum_To_Send)
{
bool bSuccess = false;
if (m_bIs_Initialized && m_bIs_Connected && m_lpvSystem_Info)
{
socket_info_win * lpSock_Info = (socket_info_win *)m_lpvSystem_Info;
if (i_zNum_To_Send > g_zShort_Data_Container_Size)
{
if (g_lpsData_Container)
delete [] g_lpsData_Container;
g_lpsData_Container = new short[i_zNum_To_Send];
g_zShort_Data_Container_Size = i_zNum_To_Send;
}
for (unsigned int uiI = 0; uiI < i_zNum_To_Send; uiI++)
g_lpsData_Container[uiI] = htons(i_lpiData[uiI]);
bSuccess = Send((const unsigned char *)g_lpsData_Container,sizeof(short) * i_zNum_To_Send);
}
return bSuccess;
}
bool commsocket::Send(const unsigned char * i_lplpcData, size_t i_zNum_To_Send)
{
bool bSuccess = false;
if (m_bIs_Initialized && m_bIs_Connected && m_lpvSystem_Info)
{
socket_info_win * lpSock_Info = (socket_info_win *)m_lpvSystem_Info;
size_t zSent = 0;
size_t zSent_Total = 0;
unsigned int uiTries = 0;
while (zSent != -1 && zSent_Total < i_zNum_To_Send && uiTries < m_uiMax_Tries)
{
unsigned int uiTransmit_Idx = zSent_Total;
zSent = send(lpSock_Info->m_iSocket_ID,(const char*)&(i_lplpcData[uiTransmit_Idx]),i_zNum_To_Send - uiTransmit_Idx,0);
if (zSent == -1)
lpSock_Info->m_iLast_Error = errno;
else
{
// printf("Sent");
// for (unsigned int uiI = 0; uiI < zSent; uiI++)
// {
// printf(" %x",i_lplpcData[uiTransmit_Idx + uiI]);
// }
// printf("\n");
zSent_Total += zSent;
uiTries++;
}
}
bSuccess = (zSent_Total == i_zNum_To_Send);
if (zSent == -1)
fprintf(stderr,"%s\n",strerror(errno));
}
return bSuccess;
}
bool commsocket::Receive(int * i_lpiData, size_t i_zNum_To_Receive)
{
bool bSuccess = false;
if (m_bIs_Initialized && m_bIs_Connected && m_lpvSystem_Info)
{
if (i_zNum_To_Receive > g_zInt_Data_Container_Size)
{
if (g_lpiData_Container)
delete [] g_lpiData_Container;
g_lpiData_Container = new int[i_zNum_To_Receive];
g_zInt_Data_Container_Size = i_zNum_To_Receive;
}
bSuccess = Receive((char *)g_lpiData_Container,i_zNum_To_Receive * sizeof(int));
if (bSuccess)
{
for (unsigned int uiI = 0; uiI < i_zNum_To_Receive; uiI++)
i_lpiData[uiI] = ntohl(g_lpiData_Container[uiI]);
}
}
return bSuccess;
}
bool commsocket::Receive(short * i_lpsData, size_t i_zNum_To_Receive)
{
bool bSuccess = false;
if (m_bIs_Initialized && m_bIs_Connected && m_lpvSystem_Info)
{
if (i_zNum_To_Receive > g_zShort_Data_Container_Size)
{
if (g_lpsData_Container)
delete [] g_lpsData_Container;
g_lpsData_Container = new short[i_zNum_To_Receive];
g_zShort_Data_Container_Size = i_zNum_To_Receive;
}
bSuccess = Receive((char *)g_lpsData_Container,i_zNum_To_Receive * sizeof(short));
if (bSuccess)
{
for (unsigned int uiI = 0; uiI < i_zNum_To_Receive; uiI++)
i_lpsData[uiI] = ntohs(g_lpsData_Container[uiI]);
}
}
return bSuccess;
}
bool commsocket::Receive(char * i_lpcData, size_t i_zNum_To_Receive)
{
bool bSuccess = false;
if (m_bIs_Initialized && m_bIs_Connected && m_lpvSystem_Info)
{
socket_info_win * lpSock_Info = (socket_info_win *)m_lpvSystem_Info;
size_t zSent = 0;
size_t zSent_Total = 0;
unsigned int uiTries = 0;
while (zSent != -1 && zSent_Total < i_zNum_To_Receive && uiTries < m_uiMax_Tries)
{
unsigned int uiTransmit_Idx = zSent_Total;
zSent = recv(lpSock_Info->m_iSocket_ID,&(i_lpcData[uiTransmit_Idx]),i_zNum_To_Receive - uiTransmit_Idx,0);
if (zSent == -1)
lpSock_Info->m_iLast_Error = errno;
else
{
zSent_Total += zSent;
uiTries++;
}
}
if (zSent == -1)
fprintf(stderr,"%s\n",strerror(errno));
if (uiTries >= m_uiMax_Tries)
fprintf(stderr,"Receive signed: max tries exceeded\n");
bSuccess = (zSent_Total == i_zNum_To_Receive);
}
return bSuccess;
}
bool commsocket::Receive(unsigned int * i_lpiData, size_t i_zNum_To_Receive)
{
bool bSuccess = false;
if (m_bIs_Initialized && m_bIs_Connected && m_lpvSystem_Info)
{
if (i_zNum_To_Receive > g_zInt_Data_Container_Size)
{
if (g_lpiData_Container)
delete [] g_lpiData_Container;
g_lpiData_Container = new int[i_zNum_To_Receive];
g_zInt_Data_Container_Size = i_zNum_To_Receive;
}
bSuccess = Receive((unsigned char *)g_lpiData_Container,i_zNum_To_Receive * sizeof(int));
if (bSuccess)
{
for (unsigned int uiI = 0; uiI < i_zNum_To_Receive; uiI++)
i_lpiData[uiI] = ntohl(g_lpiData_Container[uiI]);
}
}
return bSuccess;
}
bool commsocket::Receive(unsigned short * i_lpsData, size_t i_zNum_To_Receive)
{
bool bSuccess = false;
if (m_bIs_Initialized && m_bIs_Connected && m_lpvSystem_Info)
{
if (i_zNum_To_Receive > g_zShort_Data_Container_Size)
{
if (g_lpsData_Container)
delete [] g_lpsData_Container;
g_lpsData_Container = new short[i_zNum_To_Receive];
g_zShort_Data_Container_Size = i_zNum_To_Receive;
}
bSuccess = Receive((unsigned char *)g_lpsData_Container,i_zNum_To_Receive * sizeof(short));
if (bSuccess)
{
for (unsigned int uiI = 0; uiI < i_zNum_To_Receive; uiI++)
i_lpsData[uiI] = ntohs(g_lpsData_Container[uiI]);
}
}
return bSuccess;
}
bool commsocket::Receive(unsigned char * i_lpcData, size_t i_zNum_To_Receive)
{
bool bSuccess = false;
if (m_bIs_Initialized && m_bIs_Connected && m_lpvSystem_Info)
{
socket_info_win * lpSock_Info = (socket_info_win *)m_lpvSystem_Info;
size_t zSent = 0;
size_t zSent_Total = 0;
unsigned int uiTries = 0;
while (zSent_Total < i_zNum_To_Receive && uiTries < m_uiMax_Tries && zSent != -1)
{
unsigned int uiTransmit_Idx = zSent_Total;
zSent = recv(lpSock_Info->m_iSocket_ID,(char*)&(i_lpcData[uiTransmit_Idx]),i_zNum_To_Receive - uiTransmit_Idx,0);
if (zSent == -1)
lpSock_Info->m_iLast_Error = errno;
else
{
zSent_Total += zSent;
// printf("Recv");
// for (unsigned int uiI = 0; uiI < zSent; uiI++)
// {
// printf(" %x",i_lpcData[uiTransmit_Idx + uiI]);
// }
// printf("\n");
uiTries++;
}
}
if (uiTries >= m_uiMax_Tries)
fprintf(stderr,"Receive unsigned: max tries exceeded\n");
if (zSent == -1)
fprintf(stderr,"%s\n",strerror(errno));
bSuccess = (zSent != -1 && zSent_Total == i_zNum_To_Receive);
}
return bSuccess;
}
bool commsocket::Accept_Connections(void)
{
if (m_bIs_Initialized && m_lpvSystem_Info)
{
socket_info_win * lpSock_Info = (socket_info_win *)m_lpvSystem_Info;
int iAddr_Len = lpSock_Info->m_lpsAddress_Info->ai_addrlen;
lpSock_Info->m_iSocket_ID = accept(lpSock_Info->m_iAccept_Socket_ID, lpSock_Info->m_lpsAddress_Info->ai_addr, &iAddr_Len);
lpSock_Info->m_lpsAddress_Info->ai_addrlen = iAddr_Len;
if (lpSock_Info->m_iSocket_ID == -1)
{
if (errno != EWOULDBLOCK && errno != EAGAIN)
{
lpSock_Info->m_iLast_Error = errno;
fprintf(stderr,"%s\n",strerror(errno));
}
}
m_bIs_Connected |= (lpSock_Info->m_iSocket_ID != -1);
}
return m_bIs_Connected;
}
void commsocket::Close(void)
{
if (m_bIs_Connected)
{
socket_info_win * lpSock_Info = (socket_info_win *)m_lpvSystem_Info;
closesocket(lpSock_Info->m_iSocket_ID);
if (lpSock_Info->m_iSocket_ID != lpSock_Info->m_iAccept_Socket_ID)
closesocket(lpSock_Info->m_iAccept_Socket_ID);
WSACleanup();
m_bIs_Connected = false;
lpSock_Info->m_iAccept_Socket_ID = -1;
lpSock_Info->m_iSocket_ID = -1;
freeaddrinfo(lpSock_Info->m_lpsAddress_Info);
}
if (m_bIs_Initialized)
{
socket_info_win * lpSock_Info = (socket_info_win *)m_lpvSystem_Info;
delete [] lpSock_Info;
m_lpvSystem_Info = NULL;
m_bIs_Initialized = false;
}
}
int commsocket::Get_Error(void)
{
int iRet = 0;
if (m_bIs_Initialized && m_lpvSystem_Info)
{
socket_info_win * lpSock_Info = (socket_info_win *)m_lpvSystem_Info;
iRet = lpSock_Info->m_iLast_Error;
}
return iRet;
}
|
Astronaos/EngineMk1
|
src/win_bwm801_sockets.cpp
|
C++
|
lgpl-3.0
| 16,295 |
// -*- mode: c++; c-basic-style: "bsd"; c-basic-offset: 4; -*-
/*
* idlmm/IDLType.cpp
* Copyright (C) Cátedra SAES-UMU 2010 <[email protected]>
*
* EMF4CPP 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.
*
* EMF4CPP is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "IDLType.hpp"
#include <ecore/EObject.hpp>
#include <ecore/EClass.hpp>
#include "idlmm/IdlmmPackage.hpp"
#include <ecorecpp/mapping.hpp>
#ifdef ECORECPP_NOTIFICATION_API
#include <ecorecpp/notify.hpp>
#endif
using namespace ::idlmm;
// Default constructor
IDLType::IDLType()
{
/*PROTECTED REGION ID(IDLTypeImpl__IDLTypeImpl) START*/
// Please, enable the protected region if you add manually written code.
// To do this, add the keyword ENABLED before START.
/*PROTECTED REGION END*/
#ifdef ECORECPP_NOTIFICATION_API
m_eDeliver = false;
#endif
}
IDLType::~IDLType()
{
}
/*PROTECTED REGION ID(IDLType.cpp) START*/
// Please, enable the protected region if you add manually written code.
// To do this, add the keyword ENABLED before START.
/*PROTECTED REGION END*/
// Attributes
::idlmm::ETypeCode IDLType::getTypeCode() const
{
return m_typeCode;
}
void IDLType::setTypeCode(::idlmm::ETypeCode _typeCode)
{
#ifdef ECORECPP_NOTIFICATION_API
::idlmm::ETypeCode _old_typeCode = m_typeCode;
#endif
m_typeCode = _typeCode;
#ifdef ECORECPP_NOTIFICATION_API
if (eNotificationRequired())
{
::ecorecpp::notify::Notification notification(
::ecorecpp::notify::Notification::SET,
(::ecore::EObject_ptr) this,
(::ecore::EStructuralFeature_ptr) ::idlmm::IdlmmPackage::_instance()->getIDLType__typeCode(),
_old_typeCode,
m_typeCode
);
eNotify(¬ification);
}
#endif
}
// References
|
wurfkeks/emf4cpp
|
emf4cpp.tests/idlmm/idlmm/IDLType.cpp
|
C++
|
lgpl-3.0
| 2,350 |
#!/bin/sh
###
# Update script for the devevelopment environment virtual machine from current
# base box.
###
# we avoid the shared folder because of the symlink issue
cd ~
# Update the core apps
sudo cozy-monitor update data-system
sudo cozy-monitor update home
sudo cozy-monitor update proxy
# we stop everything
sudo supervisorctl stop cozy-controller
sudo pkill -9 node
# we start the updates
sudo npm install -g cozy-controller
sudo npm install -g cozy-monitor
sudo supervisorctl start cozy-controller
# Update the indexer
sudo supervisorctl stop cozy-indexer
cd /usr/local/var/cozy-indexer/cozy-data-indexer
sudo rm -rf indexes # to prevent issues
sudo git pull origin master
sudo virtualenv virtualenv
. virtualenv/bin/activate
sudo pip install -r requirements/common.txt --upgrade
sudo pip install -r requirements/production.txt --upgrade
sudo supervisorctl start cozy-indexer
|
tiagocardosos/cozy-setup
|
dev/update-devenv.sh
|
Shell
|
lgpl-3.0
| 892 |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>LowRes NX</title>
<style>
body {
background-color: #000;
margin: 0;
padding: 0;
}
.emscripten_border {
}
.emscripten {
display: block;
margin: auto;
}
</style>
</head>
<body>
<div class="emscripten_border">
<canvas class="emscripten" id="canvas" oncontextmenu="event.preventDefault()" onmousedown="window.focus()"></canvas>
</div>
<script type='text/javascript'>
var Module = {
canvas: document.getElementById('canvas'),
arguments: ["program.nx"],
print: function(t) {
console.log(t);
},
printErr: function(t) {
console.log(t);
}
};
function onKeyDown_blocker(event) {
event = event || window.event;
if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
if (event.preventDefault) event.preventDefault();
}
}
document.addEventListener('keydown', onKeyDown_blocker, false);
</script>
<script async type="text/javascript" src="LowResNX120.js"></script>
</body>
</html>
|
timoinutilis/lowres-nx
|
platform/web/embed/package/index.html
|
HTML
|
lgpl-3.0
| 1,378 |
//
// MNSProjectRestClient.h
//
// Copyright 2014 MediaNet Software
// This file is part of MNSJiraRESTClient.
//
// MNSJiraRESTClient 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.
//
// MNSJiraRESTClient 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 MNSJiraRESTClient. If not, see <http://www.gnu.org/licenses/>.
#import "MNSGenericRestClient.h"
#import "MNSProject.h"
@interface MNSProjectRestClient : MNSGenericRestClient
- (void)getProjectWithKey:(NSString *)key Success:(void (^)(MNSProject *projectDTO))success fail:(MNSRestClientFailBlock)fail;
- (void)getProjectWithUrl:(NSString *)url Success:(void (^)(MNSProject *projectDTO))success fail:(MNSRestClientFailBlock)fail;
- (void)getAllProjectsSuccess:(void (^)(NSArray *projects))success fail:(MNSRestClientFailBlock)fail;
@end
|
medianetsoftware/MNSJiraRESTClient
|
MNSJiraRESTClient/Source/Client/MNSProjectRestClient.h
|
C
|
lgpl-3.0
| 1,241 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module Options.Cabal where
import qualified Data.Set as S
import Control.Monad.M
import qualified Data.List as L
import Control.Monad
import qualified Distribution.PackageDescription.Parse as C
import qualified Distribution.Package as C
import qualified Distribution.Version as C
import qualified Distribution.PackageDescription as C
import Data.String.Util
import Control.Monad.IO.Class
import Data.Function (on)
import Data.Maybe
toPkgName :: C.Dependency -> String
toPkgName (C.Dependency (C.PackageName name) _) = name
vintersection :: C.Dependency -> C.Dependency -> Bool
vintersection (C.Dependency _ lv) (C.Dependency _ rv) =
not $ C.intersectVersionRanges lv rv == C.noVersion
-- | Post-condition: no version overlap
nub' :: [C.Dependency] -> [C.Dependency]
nub' = L.nubBy (\l r -> toPkgName l == toPkgName r && vintersection l r)
fromExclusions :: S.Set String -> [C.Dependency] -> M [C.Dependency]
fromExclusions exclusions deps = do
-- Print packages which were intended to be excluded, but
-- weren't found anyway.
unless (S.null unfound_exclusions) $
warning
. listing
. ("packages to exclude were not found:":)
. map toString
. S.toList
$ excluded
-- Print version overlapped (removed packages) if any.
unless (L.null overlapped) $
warning $
("removed the following packages from processing due version"
++ " range overlap:\n") ++ (indenting 2 . listing $ overlapped)
return disjoint
where
excluded = S.intersection (S.fromList $ map toPkgName deps) exclusions
unfound_exclusions = S.difference exclusions excluded
unexcluded = L.filter (not . flip S.member excluded . toPkgName) deps
sorted = L.sortBy (on compare toPkgName) unexcluded -- for readability
disjoint = nub' sorted
-- | Calculate the packages with overlapped ranges
overlapped = sorted L.\\ disjoint
-- | Given the defined exclusion set, return a list with the
-- following properties:
-- 1 version overlap is not a relation for deps's taken as a set
-- 2 unversioned packageId's satisfy cabal constraints
readPackages :: FilePath -> S.Set String -> M [C.Dependency]
readPackages cabal_path exclusions = do
parse_result <- liftIO $ C.parsePackageDescription <$> readFile cabal_path
case parse_result of
(C.ParseFailed fail_msg) ->
err . show $ fail_msg
(C.ParseOk warnings desc) -> do
unless (L.null warnings) . warning $
preposition
"warnings during parse" "of" "cabal file" "warnings"
(map show warnings)
msg $ "parsing cabal file: " ++ cabal_path
fromExclusions exclusions . toDeps $ desc
where
toDeps :: C.GenericPackageDescription -> [C.Dependency]
toDeps gpd =
concatMap ($ gpd) [
concatDeps . maybeToList . C.condLibrary,
concatDeps . map snd . C.condExecutables,
concatDeps . map snd . C.condTestSuites,
concatDeps . map snd . C.condBenchmarks
]
where
concatDeps :: [C.CondTree v [C.Dependency] a] -> [C.Dependency]
concatDeps = concatMap C.condTreeConstraints
|
jfeltz/dash-haskell
|
src/Options/Cabal.hs
|
Haskell
|
lgpl-3.0
| 3,255 |
import sys
def setup(core, actor, buff):
return
def run(core, actor, target, commandString):
core.buffService.addBuffToCreature(target, 'fs_force_run', actor)
return
|
agry/NGECore2
|
scripts/commands/forcerun.py
|
Python
|
lgpl-3.0
| 173 |
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) sources
.PHONY: help clean html web pickle htmlhelp latex changes linkcheck
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " pickle to make pickle files (usable by e.g. sphinx-web)"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " changes to make an overview over all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
clean:
-rm -rf build/*
html:
mkdir -p build/html build/doctrees
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html
@echo
@echo "Build finished. The HTML pages are in build/html."
pickle:
mkdir -p build/pickle build/doctrees
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle
@echo
@echo "Build finished; now you can process the pickle files or run"
@echo " sphinx-web build/pickle"
@echo "to start the sphinx-web server."
web: pickle
htmlhelp:
mkdir -p build/htmlhelp build/doctrees
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in build/htmlhelp."
latex:
mkdir -p build/latex build/doctrees
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex
@echo
@echo "Build finished; the LaTeX files are in build/latex."
@echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
"run these through (pdf)latex."
changes:
mkdir -p build/changes build/doctrees
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) build/changes
@echo
@echo "The overview file is in build/changes."
linkcheck:
mkdir -p build/linkcheck build/doctrees
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in build/linkcheck/output.txt."
|
nuigroup/pymt-widgets
|
doc/Makefile
|
Makefile
|
lgpl-3.0
| 2,253 |
#ifndef MATRIXORTHOGRAPHICNODE_H
#define MATRIXORTHOGRAPHICNODE_H
#include <fugio/node_interface.h>
#include <fugio/node_control_interface.h>
#include <fugio/pin_interface.h>
#include <fugio/core/variant_interface.h>
#include <fugio/nodecontrolbase.h>
class MatrixOrthographicNode : public fugio::NodeControlBase
{
Q_OBJECT
Q_CLASSINFO( "Author", "Alex May" )
Q_CLASSINFO( "Version", "1.0" )
Q_CLASSINFO( "Description", "Create an orthographic projection Matrix4" )
Q_CLASSINFO( "URL", WIKI_NODE_URL( "Orthographic_(Matrix4)" ) )
Q_CLASSINFO( "Contact", "http://www.bigfug.com/contact/" )
public:
Q_INVOKABLE explicit MatrixOrthographicNode( QSharedPointer<fugio::NodeInterface> pNode );
virtual ~MatrixOrthographicNode( void ) {}
//-------------------------------------------------------------------------
// NodeControlInterface
virtual void inputsUpdated( qint64 pTimeStamp );
private:
QSharedPointer<fugio::PinInterface> mPinInputLeft;
QSharedPointer<fugio::PinInterface> mPinInputRight;
QSharedPointer<fugio::PinInterface> mPinInputBottom;
QSharedPointer<fugio::PinInterface> mPinInputTop;
QSharedPointer<fugio::PinInterface> mPinInputNear;
QSharedPointer<fugio::PinInterface> mPinInputFar;
QSharedPointer<fugio::PinInterface> mPinOutputMatrix;
fugio::VariantInterface *mOutputMatrix;
};
#endif // MATRIXORTHOGRAPHICNODE_H
|
bigfug/Fugio
|
plugins/Math/matrixorthographicnode.h
|
C
|
lgpl-3.0
| 1,384 |
<?php
namespace Jobs;
use Database;
class MetadataDao extends \DataAccess_AbstractDao {
const TABLE = 'job_metadata' ;
const _query_metadata_by_job_id_key = "SELECT * FROM job_metadata WHERE id_job = :id_job AND `key` = :key ";
/**
* @param $id_job
* @param $key
*
* @return \DataAccess_IDaoStruct[]|MetadataStruct[]
*/
public function getByIdJob( $id_job, $key ) {
$stmt = $this->_getStatementForCache( self::_query_metadata_by_job_id_key );
$result = $this->_fetchObject( $stmt, new MetadataStruct() , [
'id_job' => $id_job,
'key' => $key
] );
return $result;
}
public function destroyCacheByJobId( $id_job, $key ){
$stmt = $this->_getStatementForCache( self::_query_metadata_by_job_id_key );
return $this->_destroyObjectCache( $stmt, [ 'id_job' => $id_job, 'key' => $key ] );
}
/**
* @param $id_job
* @param $password
*
* @return \DataAccess_IDaoStruct[]
*/
public function getByJobIdAndPassword( $id_job, $password ) {
$stmt = $this->_getStatementForCache(
"SELECT * FROM job_metadata WHERE " .
" id_job = :id_job " .
" AND password = :password "
);
$result = $this->_fetchObject( $stmt, new MetadataStruct() , array(
'id_job' => $id_job,
'password' => $password,
) );
return @$result;
}
/**
* @param $id_job
* @param $password
* @param $key
* @return MetadataStruct
*/
public function get( $id_job, $password, $key ) {
$stmt = $this->_getStatementForCache(
"SELECT * FROM job_metadata WHERE " .
" id_job = :id_job " .
" AND password = :password " .
" AND `key` = :key "
);
$result = $this->_fetchObject( $stmt, new MetadataStruct() , array(
'id_job' => $id_job,
'password' => $password,
'key' => $key
) );
return @$result[0];
}
/**
* @param $id_job
* @param $password
* @param $key
* @param $value
* @return MetadataStruct
*/
public function set($id_job, $password, $key, $value) {
$sql = "INSERT INTO job_metadata " .
" ( id_job, password, `key`, value ) " .
" VALUES " .
" ( :id_job, :password, :key, :value ) " .
" ON DUPLICATE KEY UPDATE value = :value " ;
$conn = Database::obtain()->getConnection();
$stmt = $conn->prepare( $sql );
$stmt->execute( array(
'id_job' => $id_job,
'password' => $password,
'key' => $key,
'value' => $value
) );
$this->destroyCacheByJobId( $id_job, $key );
return $this->get($id_job, $password, $key);
}
public function delete($id_job, $password, $key) {
$sql = "DELETE FROM job_metadata " .
" WHERE id_job = :id_job AND password = :password " .
" AND `key` = :key " ;
$conn = Database::obtain()->getConnection();
$stmt = $conn->prepare( $sql );
$stmt->execute( array(
'id_job' => $id_job,
'password' => $password,
'key' => $key,
) );
}
protected function _buildResult($array_result)
{
// TODO: Implement _buildResult() method.
}
}
|
Ostico/MateCat
|
lib/Model/Jobs/MetadataDao.php
|
PHP
|
lgpl-3.0
| 3,451 |
module SwiftNav.SBP.Acquisition where
import Control.Monad
import Control.Monad.Loops
import Data.Binary
import Data.Binary.Get
import Data.Binary.IEEE754
import Data.Binary.Put
import Data.ByteString
import Data.ByteString.Lazy hiding ( ByteString )
import Data.Int
import Data.Word
msgAcqResult :: Word16
msgAcqResult = 0x0014
data MsgAcqResult = MsgAcqResult
{ msgAcqResultSnr :: Float
, msgAcqResultCp :: Float
, msgAcqResultCf :: Float
, msgAcqResultSid :: Word32
} deriving ( Show, Read, Eq )
instance Binary MsgAcqResult where
get = do
msgAcqResultSnr <- getFloat32le
msgAcqResultCp <- getFloat32le
msgAcqResultCf <- getFloat32le
msgAcqResultSid <- getWord32le
return MsgAcqResult {..}
put MsgAcqResult {..} = do
putFloat32le msgAcqResultSnr
putFloat32le msgAcqResultCp
putFloat32le msgAcqResultCf
putWord32le msgAcqResultSid
msgAcqResultDepA :: Word16
msgAcqResultDepA = 0x0015
data MsgAcqResultDepA = MsgAcqResultDepA
{ msgAcqResultDepASnr :: Float
, msgAcqResultDepACp :: Float
, msgAcqResultDepACf :: Float
, msgAcqResultDepAPrn :: Word8
} deriving ( Show, Read, Eq )
instance Binary MsgAcqResultDepA where
get = do
msgAcqResultDepASnr <- getFloat32le
msgAcqResultDepACp <- getFloat32le
msgAcqResultDepACf <- getFloat32le
msgAcqResultDepAPrn <- getWord8
return MsgAcqResultDepA {..}
put MsgAcqResultDepA {..} = do
putFloat32le msgAcqResultDepASnr
putFloat32le msgAcqResultDepACp
putFloat32le msgAcqResultDepACf
putWord8 msgAcqResultDepAPrn
|
hankaiwen/libsbp
|
haskell/src/SwiftNav/SBP/Acquisition.hs
|
Haskell
|
lgpl-3.0
| 1,564 |
<?php
class shopFrontendCategoryAction extends shopFrontendAction
{
public function execute()
{
$category_model = new shopCategoryModel();
if (waRequest::param('category_id')) {
$category = $category_model->getById(waRequest::param('category_id'));
} else {
//$category = $category_model->getByField(waRequest::param('url_type') == 1 ? 'url' : 'full_url', waRequest::param('category_url'));
$category = $category_model->getByField(waRequest::param('url_type') == 1 ? 'url' : 'full_url', str_replace("/ttt","",waRequest::param('category_url')));
$k[]=129;
//$_GET['Tip']=$k;
// echo serialize($_GET);
//echo waRequest::param('category_url')."===";
}
$route = wa()->getRouting()->getDomain(null, true).'/'.wa()->getRouting()->getRoute('url');
if (!$category || ($category['route'] && $category['route'] != $route)) {
throw new waException('Category not found', 404);
}
if ($category['filter']) {
$filter_ids = explode(',', $category['filter']);
$feature_model = new shopFeatureModel();
$features = $feature_model->getById(array_filter($filter_ids, 'is_numeric'));
if ($features) {
$features = $feature_model->getValues($features);
}
$filters = array();
foreach ($filter_ids as $fid) {
if ($fid == 'price') {
$filters['price'] = true;
} elseif (isset($features[$fid])) {
$filters[$fid] = $features[$fid];
}
}
$this->view->assign('filters', $filters);
}
$category['subcategories'] = $category_model->getSubcategories($category, true);
$category_url = wa()->getRouteUrl('shop/frontend/category', array('category_url' => '%CATEGORY_URL%'));
foreach ($category['subcategories'] as &$sc) {
$sc['url'] = str_replace('%CATEGORY_URL%', waRequest::param('url_type') == 1 ? $sc['url'] : $sc['full_url'], $category_url);
}
unset($sc);
if ($category['parent_id']) {
$breadcrumbs = array();
$path = array_reverse($category_model->getPath($category['id']));
foreach ($path as $row) {
$breadcrumbs[] = array(
'url' => wa()->getRouteUrl('/frontend/category', array('category_url' => waRequest::param('url_type') == 1 ? $row['url'] : $row['full_url'])),
'name' => $row['name']
);
}
if ($breadcrumbs && $this->layout) {
$this->layout->assign('breadcrumbs', $breadcrumbs);
}
}
if ($category['type'] == shopCategoryModel::TYPE_DYNAMIC && !$category['sort_products']) {
$category['sort_products'] = 'create_datetime DESC';
}
$category_params_model = new shopCategoryParamsModel();
$category['params'] = $category_params_model->get($category['id']);
if ($this->getConfig()->getOption('can_use_smarty') && $category['description']) {
$category['description'] = wa()->getView()->fetch('string:'.$category['description']);
}
$this->view->assign('category', $category);
if ($category['sort_products'] && !waRequest::get('sort')) {
$sort = explode(' ', $category['sort_products']);
if (isset($sort[1])) {
$order = strtolower($sort[1]);
} else {
$order = 'asc';
}
$_GET['sort'] = $sort[0];
$_GET['order'] = $order;
} elseif (!$category['sort_products'] && !waRequest::get('sort')) {
$this->view->assign('active_sort', '');
}
$this->setCollection(new shopProductsCollection('category/'.$category['id']));
$title = $category['meta_title'] ? $category['meta_title'] : $category['name'];
wa()->getResponse()->setTitle($title);
wa()->getResponse()->setMeta('keywords', $category['meta_keywords']);
wa()->getResponse()->setMeta('description', $category['meta_description']);
/**
* @event frontend_category
* @return array[string]string $return[%plugin_id%] html output for category
*/
$this->view->assign('frontend_category', wa()->event('frontend_category'));
$this->setThemeTemplate('category.html');
}
}
|
dmitriyzhdankin/avantmarketcom
|
wa-apps/shop/lib/actions/frontend/shopFrontendCategory.action_222.php
|
PHP
|
lgpl-3.0
| 4,535 |
<?php
interface iCache
{
/**
* @param $key
* @param $value
* @param $exprie
* @return mixed
*/
public static function set($key, $value, $exprie = 60);
/**
* @param $key
* @return mixed
*/
public static function get($key);
}
|
YXcloud/YX_SMW
|
models/cache/iCache.php
|
PHP
|
lgpl-3.0
| 283 |
#define BOOST_TEST_MODULE TEST_MEMORY_REORDER_SCHEME_IMPL
#define BOOST_TEST_MAIN
#include "boost/test/included/unit_test.hpp"
#include <numeric>
#include <vector>
#include <iostream>
#include <bitset>
#include <map>
#include "array_fixtures.hpp"
// #include "encoders/memory_reorder_utils.hpp"
#include "encoders/raster_reorder_scheme_impl.hpp"
#include "traits.hpp"
typedef sqeazy::array_fixture<std::uint16_t> uint16_cube_of_8;
typedef sqeazy::array_fixture<std::uint16_t,32> uint16_cube_of_32;
namespace sqy = sqeazy;
namespace sqyd = sqy::detail;
template <typename iterator_t, typename shape_t>
void label_stack_by_tile(iterator_t _begin,
const shape_t& _shape,
std::uint32_t tile_size){
typedef typename std::iterator_traits<decltype(_shape.begin())>::value_type shape_value_type;
typedef typename std::remove_cv<shape_value_type>::type shape_value_t;
shape_t n_tiles_per_dim = _shape;
for(shape_value_t& el : n_tiles_per_dim){
el = el/tile_size;
}
shape_value_t ztile = 0;
shape_value_t ytile = 0;
shape_value_t xtile = 0;
shape_value_t tile_id = 0;
for(shape_value_t z = 0;z<_shape[sqeazy::row_major::z];++z){
ztile = z / tile_size;
for(shape_value_t y = 0;y<_shape[sqeazy::row_major::y];++y){
ytile = y / tile_size;
for(shape_value_t x = 0;x<_shape[sqeazy::row_major::x];++x){
xtile = x/ tile_size;
tile_id = ztile*n_tiles_per_dim[sqeazy::row_major::y]*n_tiles_per_dim[sqeazy::row_major::x]
+ ytile*n_tiles_per_dim[sqeazy::row_major::x]
+ xtile;
*(_begin++) = tile_id;
}
}
}
}
template <typename iterator_t, typename shape_t>
void encoded_tile_labels(iterator_t _begin,
const shape_t& _shape,
std::uint32_t tile_size){
typedef typename std::iterator_traits<decltype(_shape.begin())>::value_type shape_value_type;
typedef typename std::remove_cv<shape_value_type>::type shape_value_t;
for(shape_value_t el : _shape){
if(el % tile_size != 0){
std::cerr << "unable to generate encoded_tile_labels for shape ("
<< _shape[sqeazy::row_major::z] << "x" << _shape[sqeazy::row_major::y] << "x" << _shape[sqeazy::row_major::x]
<< ") at tile_size = " << tile_size << "\n";
return;
}
}
shape_t n_tiles_per_dim = _shape;
for(shape_value_t& el : n_tiles_per_dim){
el = el/tile_size;
}
shape_value_t n_elements_per_tile = std::pow(tile_size,_shape.size());
shape_value_t n_elements = std::accumulate(_shape.begin(), _shape.end(),1,std::multiplies<shape_value_t>());
iterator_t _end = _begin + n_elements;
shape_value_t tile_id =0;
for(;_begin!=_end;_begin+=n_elements_per_tile){
std::fill(_begin, _begin + n_elements_per_tile, tile_id);
tile_id+=1;
}
}
BOOST_FIXTURE_TEST_SUITE( basic , uint16_cube_of_8 )
BOOST_AUTO_TEST_CASE( constructs )
{
sqyd::reorder in_tiles_of(4);
BOOST_CHECK(in_tiles_of.tile_size == 4);
}
BOOST_AUTO_TEST_CASE( has_0_remainder )
{
sqyd::reorder in_tiles_of(4);
auto rem = in_tiles_of.remainder(dims);
auto expected = dims;
std::fill(expected.begin(), expected.end(),0);
BOOST_CHECK(!rem.empty());
BOOST_CHECK_EQUAL_COLLECTIONS(rem.begin(), rem.end(),
expected.begin(), expected.end());
}
BOOST_AUTO_TEST_CASE( has_non0_remainder )
{
sqyd::reorder in_tiles_of(6);
auto rem = in_tiles_of.remainder(dims);
auto expected = dims;
std::fill(expected.begin(), expected.end(),2);
BOOST_CHECK(!rem.empty());
BOOST_CHECK_EQUAL_COLLECTIONS(rem.begin(), rem.end(),
expected.begin(), expected.end());
}
BOOST_AUTO_TEST_CASE( on_const_value_buffer )
{
sqyd::reorder in_tiles_of(2);
auto rem = in_tiles_of.encode(constant_cube.cbegin(), constant_cube.cend(),
to_play_with.begin(),
dims);
BOOST_REQUIRE(rem == to_play_with.end());
BOOST_CHECK_EQUAL_COLLECTIONS(constant_cube.begin(), constant_cube.end(),
to_play_with.begin(), to_play_with.end());
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_FIXTURE_TEST_SUITE( on_ramp_forward , uint16_cube_of_8 )
BOOST_AUTO_TEST_CASE( tile_of_2 )
{
sqyd::reorder in_tiles_of(2);
label_stack_by_tile(incrementing_cube.begin(),dims,2);
auto rem = in_tiles_of.encode(incrementing_cube.cbegin(), incrementing_cube.cend(),
to_play_with.begin(),
dims);
BOOST_REQUIRE(rem == to_play_with.end());
std::vector<std::uint16_t> expected = constant_cube;
encoded_tile_labels(expected.begin(),
dims,
in_tiles_of.tile_size);
BOOST_CHECK_EQUAL_COLLECTIONS(to_play_with.begin(), to_play_with.begin()+expected.size(),
expected.begin(), expected.end());
}
BOOST_AUTO_TEST_CASE( tile_of_4 )
{
sqyd::reorder in_tiles_of(4);
auto rem = in_tiles_of.encode(incrementing_cube.cbegin(), incrementing_cube.cend(),
to_play_with.begin(),
dims);
BOOST_REQUIRE(rem == to_play_with.end());
std::vector<std::uint16_t> expected = {0,1,2,3,
8,9,10,11,
16,17,18,19,
24,25,26,27,
64,65,66,67,
72,73,74,75,
80,81,82,83,
88,89,90,91
};
BOOST_CHECK_EQUAL_COLLECTIONS(to_play_with.begin(), to_play_with.begin()+expected.size(),
expected.begin(), expected.end());
}
BOOST_AUTO_TEST_CASE( tile_of_4_labelled )
{
sqyd::reorder in_tiles_of(4);
label_stack_by_tile(incrementing_cube.begin(),dims,in_tiles_of.tile_size);
auto rem = in_tiles_of.encode(incrementing_cube.cbegin(), incrementing_cube.cend(),
to_play_with.begin(),
dims);
BOOST_REQUIRE(rem == to_play_with.end());
// std::vector<std::uint16_t> expected = {0,1,2,3,
// 8,9,10,11,
// 16,17,18,19,
// 24,25,26,27,
// 64,65,66,67,
// 72,73,74,75,
// 80,81,82,83,
// 88,89,90,91
// };
auto expected = constant_cube;
encoded_tile_labels(expected.begin(),
dims,
in_tiles_of.tile_size);
BOOST_CHECK_EQUAL_COLLECTIONS(to_play_with.begin(), to_play_with.begin()+expected.size(),
expected.begin(), expected.end());
}
BOOST_AUTO_TEST_CASE( tile_of_3 )
{
sqyd::reorder in_tiles_of(3);
auto rem = in_tiles_of.encode(incrementing_cube.cbegin(), incrementing_cube.cend(),
to_play_with.begin(),
dims);
BOOST_REQUIRE(rem == to_play_with.end());
std::vector<std::uint16_t> expected = {0,1,2,
8,9,10,
16,17,18,
64,65,66,
72,73,74,
80,81,82
};
BOOST_CHECK_EQUAL_COLLECTIONS(to_play_with.begin(), to_play_with.begin()+expected.size(),
expected.begin(), expected.end());
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_FIXTURE_TEST_SUITE( on_ramp_backward , uint16_cube_of_8 )
BOOST_AUTO_TEST_CASE( tile_of_2 )
{
sqyd::reorder in_tiles_of(2);
std::vector<std::uint16_t> expected = {0,1,
8,9,
64,65,
72,73};
std::fill(constant_cube.begin(), constant_cube.end(),0);
std::copy(expected.begin(), expected.end(),constant_cube.begin());
auto rem = in_tiles_of.decode(constant_cube.cbegin(), constant_cube.cend(),
to_play_with.begin(),
dims);
BOOST_REQUIRE(rem == to_play_with.end());
for(int i = 0;i<8;++i)
BOOST_CHECK_EQUAL(to_play_with[expected[i]],expected[i]);
}
BOOST_AUTO_TEST_CASE( tile_of_2_labelled )
{
sqyd::reorder in_tiles_of(2);
auto encoded = constant_cube;
std::fill(encoded.begin(), encoded.end(),0);
encoded_tile_labels(encoded.begin(),
dims,
in_tiles_of.tile_size);
auto expected = constant_cube;
std::fill(expected.begin(), expected.end(),0);
label_stack_by_tile(expected.begin(),dims,in_tiles_of.tile_size);
auto rem = in_tiles_of.decode(encoded.cbegin(), encoded.cend(),
to_play_with.begin(),
dims);
BOOST_REQUIRE(rem == to_play_with.end());
BOOST_CHECK_EQUAL_COLLECTIONS(to_play_with.begin(), to_play_with.end(),
expected.begin(), expected.end());
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_FIXTURE_TEST_SUITE( on_ramp_roundtrip , uint16_cube_of_8 )
BOOST_AUTO_TEST_CASE( tile_of_2 )
{
sqyd::reorder in_tiles_of(2);
auto rem = in_tiles_of.encode(incrementing_cube.cbegin(), incrementing_cube.cend(),
to_play_with.begin(),
dims);
BOOST_REQUIRE(rem == to_play_with.end());
auto decoded = constant_cube;
std::fill(decoded.begin(), decoded.end(),0);
rem = in_tiles_of.decode(to_play_with.cbegin(),to_play_with.cend(),
decoded.begin(),
dims);
BOOST_REQUIRE(rem == decoded.end());
BOOST_CHECK_EQUAL_COLLECTIONS(incrementing_cube.begin(), incrementing_cube.end(),
decoded.begin(), decoded.end());
}
BOOST_AUTO_TEST_CASE( tile_of_4 )
{
sqyd::reorder in_tiles_of(4);
auto rem = in_tiles_of.encode(incrementing_cube.cbegin(), incrementing_cube.cend(),
to_play_with.begin(),
dims);
BOOST_REQUIRE(rem == to_play_with.end());
auto decoded = constant_cube;
std::fill(decoded.begin(), decoded.end(),0);
rem = in_tiles_of.decode(to_play_with.cbegin(),to_play_with.cend(),
decoded.begin(),
dims);
BOOST_REQUIRE(rem == decoded.end());
BOOST_CHECK_EQUAL_COLLECTIONS(incrementing_cube.begin(), incrementing_cube.end(),
decoded.begin(), decoded.end());
}
BOOST_AUTO_TEST_CASE( tile_of_3 )
{
sqyd::reorder in_tiles_of(3);
auto rem = in_tiles_of.encode(incrementing_cube.cbegin(), incrementing_cube.cend(),
to_play_with.begin(),
dims);
BOOST_REQUIRE(rem == to_play_with.end());
auto decoded = constant_cube;
std::fill(decoded.begin(), decoded.end(),0);
rem = in_tiles_of.decode(to_play_with.cbegin(),to_play_with.cend(),
decoded.begin(),
dims);
BOOST_REQUIRE(rem == decoded.end());
BOOST_CHECK_EQUAL_COLLECTIONS(incrementing_cube.begin(), incrementing_cube.end(),
decoded.begin(), decoded.end());
}
BOOST_AUTO_TEST_CASE( scheme_tile_of_4 )
{
sqeazy::raster_reorder_scheme<value_type> scheme("tile_size=4");
std::vector<std::size_t> shape(dims.begin(), dims.end());
auto rem = scheme.encode(incrementing_cube.data(),
to_play_with.data(),
shape);
BOOST_REQUIRE(rem == (to_play_with.data() + to_play_with.size()));
auto decoded = constant_cube;
std::fill(decoded.begin(), decoded.end(),0);
auto rv = scheme.decode(to_play_with.data(),
decoded.data(),
shape);
BOOST_REQUIRE(rv == 0);
BOOST_CHECK_EQUAL_COLLECTIONS(incrementing_cube.begin(), incrementing_cube.end(),
decoded.begin(), decoded.end());
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_FIXTURE_TEST_SUITE( big_roundtrips , uint16_cube_of_32 )
BOOST_AUTO_TEST_CASE( tile_of_simd_fitted )
{
sqyd::reorder in_tiles_of(16/sizeof(value_type));
for(unsigned dim : dims)
BOOST_REQUIRE_EQUAL(dim % in_tiles_of.tile_size,0u);
auto rem = in_tiles_of.encode_full_simd(incrementing_cube.data(),
incrementing_cube.data()+size,
to_play_with.data(),
dims);
BOOST_CHECK(rem == (to_play_with.data()+size));
auto decoded = constant_cube;
std::fill(decoded.begin(), decoded.end(),0);
auto rv_decode = in_tiles_of.decode(to_play_with.cbegin(),to_play_with.cend(),
decoded.begin(),
dims);
BOOST_CHECK(rv_decode == decoded.end());
BOOST_CHECK_EQUAL_COLLECTIONS(incrementing_cube.begin(), incrementing_cube.end(),
decoded.begin(), decoded.end());
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_FIXTURE_TEST_SUITE( parallel_on_ramp_roundtrip , uint16_cube_of_8 )
BOOST_AUTO_TEST_CASE( tile_of_2 )
{
sqyd::reorder in_tiles_of(2);
auto rem = in_tiles_of.encode(incrementing_cube.cbegin(), incrementing_cube.cend(),
to_play_with.begin(),
dims,
std::thread::hardware_concurrency());
BOOST_REQUIRE(rem == to_play_with.end());
auto decoded = constant_cube;
std::fill(decoded.begin(), decoded.end(),0);
rem = in_tiles_of.decode(to_play_with.cbegin(),to_play_with.cend(),
decoded.begin(),
dims,
std::thread::hardware_concurrency()
);
BOOST_REQUIRE(rem == decoded.end());
BOOST_CHECK_EQUAL_COLLECTIONS(incrementing_cube.begin(), incrementing_cube.end(),
decoded.begin(), decoded.end());
}
BOOST_AUTO_TEST_CASE( tile_of_4 )
{
sqyd::reorder in_tiles_of(4);
auto rem = in_tiles_of.encode(incrementing_cube.cbegin(), incrementing_cube.cend(),
to_play_with.begin(),
dims,
std::thread::hardware_concurrency());
BOOST_REQUIRE(rem == to_play_with.end());
auto decoded = constant_cube;
std::fill(decoded.begin(), decoded.end(),0);
rem = in_tiles_of.decode(to_play_with.cbegin(),to_play_with.cend(),
decoded.begin(),
dims,
std::thread::hardware_concurrency());
BOOST_REQUIRE(rem == decoded.end());
BOOST_CHECK_EQUAL_COLLECTIONS(incrementing_cube.begin(), incrementing_cube.end(),
decoded.begin(), decoded.end());
}
BOOST_AUTO_TEST_CASE( tile_of_3 )
{
sqyd::reorder in_tiles_of(3);
auto rem = in_tiles_of.encode(incrementing_cube.cbegin(), incrementing_cube.cend(),
to_play_with.begin(),
dims,
std::thread::hardware_concurrency());
BOOST_REQUIRE(rem == to_play_with.end());
auto decoded = constant_cube;
std::fill(decoded.begin(), decoded.end(),0);
rem = in_tiles_of.decode(to_play_with.cbegin(),to_play_with.cend(),
decoded.begin(),
dims,
std::thread::hardware_concurrency());
BOOST_REQUIRE(rem == decoded.end());
BOOST_CHECK_EQUAL_COLLECTIONS(incrementing_cube.begin(), incrementing_cube.end(),
decoded.begin(), decoded.end());
}
BOOST_AUTO_TEST_CASE( scheme_tile_of_4 )
{
sqeazy::raster_reorder_scheme<value_type> scheme("tile_size=4");
scheme.set_n_threads(std::thread::hardware_concurrency());
std::vector<std::size_t> shape(dims.begin(), dims.end());
auto rem = scheme.encode(incrementing_cube.data(),
to_play_with.data(),
shape);
BOOST_REQUIRE(rem == (to_play_with.data() + to_play_with.size()));
auto decoded = constant_cube;
std::fill(decoded.begin(), decoded.end(),0);
auto rv = scheme.decode(to_play_with.data(),
decoded.data(),
shape);
BOOST_REQUIRE(rv == 0);
BOOST_CHECK_EQUAL_COLLECTIONS(incrementing_cube.begin(), incrementing_cube.end(),
decoded.begin(), decoded.end());
}
BOOST_AUTO_TEST_SUITE_END()
|
psteinb/sqeazy
|
src/cpp/tests/test_raster_reorder_scheme_impl.cpp
|
C++
|
lgpl-3.0
| 15,477 |
package com.mycompany.proyecto.controller;
import java.util.ArrayList;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.mycompany.proyecto.model.Pedido;
import com.mycompany.proyecto.model.PedidoDetalle;
import com.mycompany.proyecto.service.PedidoInsumoService;
import com.mycompany.proyecto.service.ProductoService;
/**
* Handles requests for the application home page.
* Anotando una clase Java como @Controller se convierte en un controlador,
* es decir, en una clase encargada de recibir las peticiones HttpServletRequest.
*
* El objeto Model simplemente es un mapa donde guardaremos los objetos
* que queremos pasar a la vista (es la M de MVC)
*
* Principal componente do framework <code>Spring MVC</code>, esse é o controller do cadastro de mercadorias.
*
* <p>Tem como responsabilidade: definir o mapeamento de navegação, acionar validadores e conversores de dados,
* fornecer e receber os dados da camada de visão (<code>JSP</code>).</p>
*
* <p>Os métodos de navegação, retornam a url definida no Tiles. Veja também o arquivo <code>views.xml</code>.</p>
*
* @author Rodrigo Garcete
* @since 21/11/2013
*/
@RequestMapping(value="/pedido")
@Controller
public class PedidoInsumoController {
private PedidoInsumoService pedidoInsumoService;
private ArrayList<PedidoDetalle> listaItems = new ArrayList<PedidoDetalle>();
@Autowired
public PedidoInsumoController(PedidoInsumoService is){
this.pedidoInsumoService = is;
}
@Autowired
private ProductoService productoService;
/**
*
* @param item
* @param bindingResult
*/
@RequestMapping(value = "/addItem", method = RequestMethod.POST)
public void addItemLista(@ModelAttribute(value = "item") PedidoDetalle item, BindingResult bindingResult){
if (!bindingResult.hasErrors()) {
//El id lo pasamos al Id del Insumo
item.getProducto().setCodigo(item.getId());
//cargamos el bean a la lista
System.out.println("paso x aqui add");
listaItems.add(item);
}
}
@RequestMapping(value = "/quitarItem", method = RequestMethod.POST)
public void quitarItemLista(@ModelAttribute(value = "item") PedidoDetalle item, BindingResult bindingResult){
if (!bindingResult.hasErrors()) {
//El id lo pasamos al Id del Insumo
//item.getInsumo().setCodigo(item.getId());
for (int i = 0; i < listaItems.size(); i++) {
PedidoDetalle pd = listaItems.get(i);
System.out.println("Item Id :" + item.getId());
System.out.println("Item Cantidad :" + item.getCantidad());
if (pd.getProducto().getCodigo().equals(item.getId()) &&
pd.getCantidad().equals(item.getCantidad())) {
System.out.println("paso para remover");
listaItems.remove(i); //remuevo de la lista por el indice
}
}
System.out.println("paso x aqui quitar");
}
}
/**
* Ponto de entrada da aplicação ("/").
* @param uiModel recebe a lista de mercadorias.
* @return url para a pagina de listagem de mercadorias.
*/
@RequestMapping(value="/listado",method = RequestMethod.GET)
public String listar(Model uiModel) {
uiModel.addAttribute("pedidos", pedidoInsumoService.getAll());
//log.debug("Consultando en la BD y mostrando todos los pedidos insumos");
listaItems.clear();
return "listaPedidoInsumos";
}
/**
* Método ejecutado antes de cargar la pantalla de insercion de insumos
* @param uiModel
* @return url de la pagina de insercion
*/
@RequestMapping(value="/form", method = RequestMethod.GET)
public String crearForm(Model uiModel) {
uiModel.addAttribute("pedido", new Pedido());
uiModel.addAttribute("productos", productoService.findByInsumo());
return "incluirPedidoInsumo";
}
/**
* Método ejecutado en la insercion de insumos.
* @param instancia de insumo con los datos cargados en la pantalla
* @param bindingResult componente utilizado para verificar problemas com validacion
* @param uiModel
* @return a url para listado, si algun error de validacion fue encontrado, regresa para la pagina de insercion.
*/
//@RequestMapping(value="/form", method = RequestMethod.POST)
public String crear(@Valid Pedido p, BindingResult bindingResult, Model uiModel) {
if (bindingResult.hasErrors()) {
uiModel.addAttribute("pedido", p);
return "incluirPedidoInsumo";
}
pedidoInsumoService.savePedido(p, listaItems);
return "redirect:/pedido/listado";
}
@RequestMapping(value="/form", method = RequestMethod.POST)
public String crear2(@Valid Pedido p, BindingResult bindingResult, Model uiModel) {
if (bindingResult.hasErrors()) {
uiModel.addAttribute("pedido", p);
return "incluirPedidoInsumo";
}
pedidoInsumoService.savePedido(p, listaItems);
return "redirect:/pedido/listado";
}
/**
* Método ejecutado antes de cargar la pantalla de edicion de insumos.
* @param id del insumo que va a ser editado.
* @param uiModel almacena el objeto insumo que debe ser modificado.
* @return url de la pagina de edicion.
*/
@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
public String editarForm(@PathVariable("id") Long id, Model uiModel) {
Pedido m = pedidoInsumoService.findById(id);
if (m != null) {
uiModel.addAttribute("pedido", m);
//log.debug("Listo para editar Pedido Insumo");
}
return "editarPedidoInsumo";
}
/**
*
* @param item
* @param bindingResult
*/
@RequestMapping(value = "/editItemPedido", method = RequestMethod.POST)
public void quitarItemPedido(@ModelAttribute(value = "item") PedidoDetalle item, BindingResult bindingResult){
if (!bindingResult.hasErrors()) {
//El id lo pasamos al Id del Insumo
//item.getInsumo().setCodigo(item.getId());
//cargamos el bean a la lista
//System.out.println("paso x aqui add");
//listaItems.add(item);
}
}
/**
* Método executado ao salvar a edição de mercadoria.
* @param mercadoria objeto com os dados enviados pela tela.
* @param bindingResult componente usado para verificar problemas com validação.
* @param uiModel
* @return a url para a listagem, se algum erro de validação for encontrado volta para a pagina de edição.
*/
@RequestMapping(value = "/edit/{id}", method = RequestMethod.PUT)
public String editar(@Valid Pedido pedidoInsumo, BindingResult bindingResult, Model uiModel) {
if (bindingResult.hasErrors()) {
uiModel.addAttribute("pedido", pedidoInsumo);
return "editarPedidoInsumo";
}
pedidoInsumoService.save(pedidoInsumo);
//log.debug("Insumo actualizado: " + pedidoInsumo.getCodigo());
return "redirect:/pedido/listado";
}
/**
* Método ejecutado para la eliminacion de insumos.
* @param id de insumo que debe ser eliminado.
* @param uiModel
* @return url de la pagina de listado.
*/
@RequestMapping(value = "/edit/{id}", method = RequestMethod.DELETE)
public String remover(@PathVariable("id") Long id, Model uiModel) {
Pedido m = pedidoInsumoService.findById(id);
if (m != null) {
pedidoInsumoService.remove(m);
//log.debug("Pedido Insumo removido: "+m.getCodigo());
}
return "redirect:/pedido/listado";
}
}
|
rorogarcete/app-proyecto
|
App-proyecto-Web/src/main/java/com/mycompany/proyecto/controller/PedidoInsumoController.java
|
Java
|
lgpl-3.0
| 7,591 |
package net.minecraft.block;
import net.minecraft.block.material.Material;
public abstract class BlockDirectional extends Block
{
protected BlockDirectional(int par1, Material par2Material)
{
super(par1, par2Material);
}
/**
* Returns the orentation value from the specified metadata
*/
public static int getDirection(int par0)
{
return par0 & 3;
}
}
|
HATB0T/RuneCraftery
|
forge/mcp/src/minecraft/net/minecraft/block/BlockDirectional.java
|
Java
|
lgpl-3.0
| 408 |
/* Change history:
* 20 Apr 2007 Marc Gravell Rollback dictionary on error;
* Assert ReflectionPermission for main creation
* (thanks/credit to Josh Smith for feedback/hints)
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Security;
using System.Security.Permissions;
namespace MediaBrowser.Theater.Presentation.Reflection
{
public sealed class HyperTypeDescriptionProvider : TypeDescriptionProvider
{
private static readonly Dictionary<Type, ICustomTypeDescriptor> Descriptors = new Dictionary<Type, ICustomTypeDescriptor>();
public HyperTypeDescriptionProvider() : this(typeof (object)) { }
public HyperTypeDescriptionProvider(Type type) : this(TypeDescriptor.GetProvider(type)) { }
public HyperTypeDescriptionProvider(TypeDescriptionProvider parent) : base(parent) { }
public static void Add(Type type)
{
TypeDescriptionProvider parent = TypeDescriptor.GetProvider(type);
TypeDescriptor.AddProvider(new HyperTypeDescriptionProvider(parent), type);
}
public static void Clear(Type type)
{
lock (Descriptors) {
Descriptors.Remove(type);
}
}
public static void Clear()
{
lock (Descriptors) {
Descriptors.Clear();
}
}
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
{
lock (Descriptors) {
ICustomTypeDescriptor descriptor;
if (!Descriptors.TryGetValue(objectType, out descriptor)) {
try {
descriptor = BuildDescriptor(objectType);
} catch {
return base.GetTypeDescriptor(objectType, instance);
}
}
return descriptor;
}
}
[SecuritySafeCritical]
[ReflectionPermission(SecurityAction.Assert, Unrestricted = true)]
private ICustomTypeDescriptor BuildDescriptor(Type objectType)
{
// NOTE: "descriptors" already locked here
// get the parent descriptor and add to the dictionary so that
// building the new descriptor will use the base rather than recursing
ICustomTypeDescriptor descriptor = base.GetTypeDescriptor(objectType, null);
Descriptors.Add(objectType, descriptor);
try {
// build a new descriptor from this, and replace the lookup
descriptor = new HyperTypeDescriptor(descriptor);
Descriptors[objectType] = descriptor;
return descriptor;
} catch {
// rollback and throw
// (perhaps because the specific caller lacked permissions;
// another caller may be successful)
Descriptors.Remove(objectType);
throw;
}
}
}
}
|
thogil/MBT
|
MediaBrowser.Theater/MediaBrowser.Theater.Presentation/Reflection/HyperTypeDescriptionProvider.cs
|
C#
|
lgpl-3.0
| 3,102 |
import sys
from java.util import Vector
def addTemplate(core):
mobileTemplates = Vector()
mobileTemplates.add('carrion_spat')
core.spawnService.addLairTemplate('corellia_carrion_spat_lair_1', mobileTemplates, 15, 'object/tangible/lair/base/poi_all_lair_nest_large_evil_fire_small.iff')
return
|
agry/NGECore2
|
scripts/mobiles/lairs/corellia_carrion_spat_lair_1.py
|
Python
|
lgpl-3.0
| 299 |
/**
* DataCleaner (community edition)
* Copyright (C) 2014 Free Software Foundation, Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.datacleaner.result.html;
import java.util.List;
import org.datacleaner.api.Renderable;
import org.datacleaner.api.Renderer;
import org.datacleaner.api.RendererPrecedence;
/**
* An extension of the renderer interface, useful for most simple HTML renderers.
*/
public abstract class HtmlRenderer<R extends Renderable> implements Renderer<R, HtmlFragment> {
@Override
public RendererPrecedence getPrecedence(R renderable) {
return RendererPrecedence.MEDIUM;
}
@Override
public HtmlFragment render(R result) {
final SimpleHtmlFragment fragment = new SimpleHtmlFragment();
return new HtmlFragment() {
@Override
public void initialize(HtmlRenderingContext context) {
handleFragment(fragment, result, context);
}
@Override
public List<HeadElement> getHeadElements() {
return fragment.getHeadElements();
}
@Override
public List<BodyElement> getBodyElements() {
return fragment.getBodyElements();
}
};
}
protected abstract void handleFragment(SimpleHtmlFragment frag, R result, HtmlRenderingContext context);
}
|
datacleaner/DataCleaner
|
components/html-rendering/src/main/java/org/datacleaner/result/html/HtmlRenderer.java
|
Java
|
lgpl-3.0
| 2,062 |
{strip}
<div class="t-dialog-wrapper is-full-screen t-delete-calendar-popup" id="t-calendar-delete">
<div class="t-dialog-background"></div>
<div class="t-dialog-block">
<header class="t-dialog-header">
<h2>[`Delete this calendar?`]</h2>
</header>
<div class="t-dialog-content">
{if $count_events <= 0}
<p>
[`This calendar is empty. No events will be deleted.`]
</p>
{else}
<p>
{sprintf(_w('%d event in this calendar will be deleted', '%d events in this calendar will be deleted', $count_events))}
</p>
{if $count_external_calendars > 0}
<p>
{sprintf(_w('%d connection to external calendars will be deleted', '%d connections to external calendars will be deleted', $count_external_calendars))}
</p>
{/if}
{/if}
</div>
<footer class="t-dialog-footer">
<div class="t-actions">
<input class="button red js-delete-calendar" type="button" value="[`Delete`]">
<span style="margin: 0 4px;">[`or`]</span>
<a class="js-close-dialog" href="javascript:void(0);">[`cancel`]</a>
</div>
</footer>
</div>
<script>
( function($) {
new CalendarDeleteDialog({
$wrapper: $("#t-calendar-delete"),
calendar_id: "{$calendar.id}"
});
})(jQuery);
</script>
</div>
{/strip}
|
webasyst/webasyst-framework
|
wa-apps/team/templates/actions-legacy/calendar/CalendarDeleteConfirm.html
|
HTML
|
lgpl-3.0
| 1,610 |
{% extends "./leanstorage_guide.tmpl" %}
{% set platform_name = "PHP" %}
{% set baseObjectName = "LeanObject" %}
{% set baseQueryClassName = "Query" %}
{% set fileObjectName = "File" %}
{% set geoPointObjectName = "GeoPoint" %}
{% set userObjectName = "User" %}
|
jwfing/docs
|
views/leanstorage_guide-php.md
|
Markdown
|
lgpl-3.0
| 262 |
/**
* Copyright (C) 2005-2015 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco 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.
*
* Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Dave Draper
*/
define(["intern!object",
"intern/chai!expect",
"intern/chai!assert",
"require",
"alfresco/TestCommon"],
function (registerSuite, expect, assert, require, TestCommon) {
var browser;
registerSuite({
name: "Video Previewer Tests",
setup: function() {
browser = this.remote;
return TestCommon.loadTestWebScript(this.remote, "/VideoPreview", "Video Previewer Tests").end();
},
beforeEach: function() {
browser.end();
},
"Tests": function () {
return browser.findByCssSelector(".alfresco-preview-AlfDocumentPreview > div.previewer.Video")
.then(null, function() {
assert(false, "Couldn't find video previewer node");
})
.end()
.findByCssSelector(".alfresco-preview-AlfDocumentPreview > div.previewer.Video video")
.then(null, function() {
assert(false, "Couldn't find video element");
});
},
"Post Coverage Results": function() {
TestCommon.alfPostCoverageResults(this, browser);
}
});
registerSuite({
name: "Audio Previewer Tests",
setup: function() {
browser = this.remote;
return TestCommon.loadTestWebScript(this.remote, "/AudioPreview", "Audio Previewer Tests").end();
},
beforeEach: function() {
browser.end();
},
"Tests": function () {
return browser.findByCssSelector(".alfresco-preview-AlfDocumentPreview > div.previewer.Audio")
.then(null, function() {
assert(false, "Couldn't find video previewer node");
})
.end()
.findByCssSelector(".alfresco-preview-AlfDocumentPreview > div.previewer.Audio audio")
.then(null, function() {
assert(false, "Couldn't find audio element");
});
},
"Post Coverage Results": function() {
TestCommon.alfPostCoverageResults(this, browser);
}
});
});
|
nzheyuti/Aikau
|
aikau/src/test/resources/alfresco/preview/PreviewerTests.js
|
JavaScript
|
lgpl-3.0
| 2,823 |
/*******************************************************************************
* Gisgraphy Project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
*
* Copyright 2008 Gisgraphy project
* David Masclet <[email protected]>
*
*
*******************************************************************************/
package com.gisgraphy.domain.geoloc.entity;
import javax.persistence.Entity;
import javax.persistence.Transient;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
/**
* Represents a {@link Mound}.
*
* @author <a href="mailto:[email protected]">David Masclet</a>
*/
@Entity
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Mound extends GisFeature {
/**
* Override the gisFeature value.<br>
* Default to true;<br>
* If this field is set to false, then the object won't be synchronized with
* the fullText search engine
*/
@Override
@Transient
public boolean isFullTextSearchable() {
return true;
}
/**
* Constructor that populate the {@link Mound} with the gisFeature fields<br>
*
* @param gisFeature
* The gisFeature from which we want to populate the
* {@link Mound}
*/
public Mound(GisFeature gisFeature) {
super(gisFeature);
}
/**
* Needed by CGLib
*/
public Mound() {
super();
}
}
|
delphiprogramming/gisgraphy
|
src/main/java/com/gisgraphy/domain/geoloc/entity/Mound.java
|
Java
|
lgpl-3.0
| 2,174 |
/*
* Copyright (c) 2014 Mastek Ltd. All rights reserved.
*
* This file is part of JBEAM. JBEAM 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.
*
* JBEAM 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 the specific language governing permissions and
* limitations.
*
* You should have received a copy of the GNU Lesser General Public
* License along with JBEAM. If not, see <http://www.gnu.org/licenses/>.
*/
package com.stgmastek.monitor.comm.client;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for instructionParameters complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="instructionParameters">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="slNo" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="value" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "instructionParameters", namespace = "http://services.server.comm.core.stgmastek.com/", propOrder = {
"name",
"slNo",
"type",
"value"
})
public class InstructionParameters {
protected String name;
protected Integer slNo;
protected String type;
protected String value;
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the slNo property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getSlNo() {
return slNo;
}
/**
* Sets the value of the slNo property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setSlNo(Integer value) {
this.slNo = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
}
|
MastekLtd/JBEAM
|
jbeam-core-components/jbeam-monitor-comm/src/main/java/com/stgmastek/monitor/comm/client/InstructionParameters.java
|
Java
|
lgpl-3.0
| 4,042 |
/**
* @file dataRepository.h
* @author Tomas Opazo T
* @date 2013
* @copyright GNU Public License.
*
*/
#ifndef STATE_REPO_H
#define STATE_REPO_H
#include "FreeRTOS.h"
#include "semphr.h"
#include "memSD.h"
#include "memEEPROM.h"
#include "cmdIncludes.h"
//#include "dataRepository.h"
//cmdXXX
#include "cmdTRX.h"
//#include "cmdDRP.h"
#include "cmdTHK.h"
#include "cmdPPC.h"
//***STATUS REPOSITORY**********************************************************
#define STA_PPC_OPMODE_NORMAL (0) /* Operacion normal*/
#define STA_PPC_OPMODE_SENDING_TM (1) /* Transceiver is TX */
#define STA_PPC_OPMODE_EXPFIS (1) /* expFis is running*/
#define STA_PPC_OPMODE_CAMERA (1) /* Camera is running */
//******************************************************************************
// BUS section
//******************************************************************************
/**
* Cubesat's State Variables
*/
typedef enum{
// Bus Hw status (connected trough the PC/104 to the OBC -PIC24-)
sta_RTC_isAlive=0,
sta_TRX_isAlive,
sta_EPS_isAlive,
sta_MemEEPROM_isAlive,
sta_MemSD_isAlive,
sta_AntSwitch_isOpen, // var number 6
//FLIGHT PLAN => (C&DH subsystem)
sta_fpl_index, // Indice del flight plan que sera editado
//PPC => (C&DH subsystem)
sta_ppc_opMode,
sta_ppc_lastResetSource,
sta_ppc_hoursAlive,
sta_ppc_hoursWithoutReset,
sta_ppc_resetCounter,
sta_ppc_wdt, // 1=WDT Active, 0=WDT Inactive
sta_ppc_osc, // holds Current Oscillator
sta_ppc_MB_nOE_USB_nINT_stat,
sta_ppc_MB_nOE_MHX_stat,
sta_ppc_MB_nON_MHX_stat,
sta_ppc_MB_nON_SD_stat,
//DEP => (C&DH subsystem)
sta_dep_ant_deployed, // 1=already deployed, 0=not deployed yet
sta_dep_ant_tries, // Number of tries to deploy antenna
sta_dep_year,
sta_dep_month,
sta_dep_week_day,
sta_dep_day_number,
sta_dep_hours,
sta_dep_minutes,
sta_dep_seconds,
//RTC => (C&DH subsystem)
sta_rtc_year,
sta_rtc_month,
sta_rtc_week_day,
sta_rtc_day_number,
sta_rtc_hours,
sta_rtc_minutes,
sta_rtc_seconds,
#if (SCH_EPS_ONBOARD==1)
//EPS => (Energy subsystem)
sta_eps_batt_temp_0,
sta_eps_batt_temp_1,
sta_eps_battery_voltage,
sta_eps_panel_current,
sta_eps_panel_voltage_1,
sta_eps_panel_voltage_2,
sta_eps_panel_voltage_3,
sta_eps_system_current,
#endif
/* Revisar de aqui hacia abajo si aun son necesarios !!! */
#if (SCH_TRX_ONBOARD==1)
//TRX => (Communication subsystem)
sta_trx_opmode, // Operation mode
sta_trx_count_tm, // number of sended TM
sta_trx_count_tc, // number of received TC
sta_trx_day_last_tc, // day of the last received tc (since 1/1/00)
sta_trx_beacon_period, // Beacon period in seconds
sta_trx_beacon_bat_lvl, // Batery voltage required to transmit beacon
sta_trx_rx_baud, // RX baudrate
sta_trx_tx_baud, // TX baudrate
#endif
//*************
sta_busStateVar_last_one //Elemento sin sentido, solo se utiliza para marcar el largo del arreglo
}STA_BusStateVar; // SUCHAI's most important variables
//void sta_set_stateVar(STA_StateVar indxVar, int value); //deprecated, OCt 2014
int sta_get_BusStateVar(STA_BusStateVar indxVar);
char *sta_BusStateVarToString(STA_BusStateVar var_i);
void sta_onReset_BusStateRepo(void);
//******************************************************************************
// PAYLOAD section
//******************************************************************************
typedef enum{
//PAYLOAD
// Payload Hw status (connected trough the PC/104 to the OBC -PIC24-)
sta_pay_lagmuirProbe_isAlive,
sta_pay_sensTemp_isAlive,
sta_pay_gps_isAlive,
sta_pay_expFis_isAlive,
sta_pay_camera_isAlive,
sta_pay_gyro_isAlive,
sta_pay_tmEstado_isAlive,
sta_pay_battery_isAlive,
sta_pay_debug_isAlive,
sta_pay_langmuirProbe_isDeployed,
// FP2 variables
sta_pay_langmuirProbe_state,
sta_pay_sensTemp_state,
sta_pay_gps_state,
sta_pay_expFis_state,
sta_pay_camera_state,
sta_pay_gyro_state,
sta_pay_tmEstado_state,
sta_pay_battery_state,
sta_pay_debug_state,
//*************
sta_payStateVar_last_one //Elemento sin sentido, solo se utiliza para marcar el largo del arreglo
}STA_PayStateVar; // SUCHAI's most important variables
int sta_get_PayStateVar(STA_PayStateVar indxVar);
char* sta_PayStateVarToString(STA_PayStateVar var_i);
STA_PayStateVar sta_DAT_Payload_Buff_to_STA_PayStateVar(DAT_Payload_Buff pay_i);
void sta_onReset_PayStateRepo(void);
//STA_StateVar sta_DAT_Payload_Buff_to_STA_StateVar(int pay_i);
#endif // STATE_REPO_H
|
spel-uchile/SUCHAI
|
System/include/stateRepository.h
|
C
|
lgpl-3.0
| 4,919 |
#!/usr/bin/env perl
if (!$::Driver) { use FindBin; exec("$FindBin::Bin/bootstrap.pl", @ARGV, $0); die; }
# DESCRIPTION: Verilator: Verilog Test driver/expect definition
#
# Copyright 2003 by Wilson Snyder. This program is free software; you
# can redistribute it and/or modify it under the terms of either the GNU
# Lesser General Public License Version 3 or the Perl Artistic License
# Version 2.0.
# SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0
scenarios(vlt_all => 1);
compile(
);
execute(
all_run_flags => ["+verilator+seed+5 +SEED=fffffff4"],
fails => 0,
);
execute(
all_run_flags => ["+verilator+seed+6 +SEED=fffffff2"],
fails => 0,
);
ok(1);
1;
|
verilator/verilator
|
test_regress/t/t_runflag_seed.pl
|
Perl
|
lgpl-3.0
| 696 |
// @deprecated use #include <driver/gpio.h>
#include <driver/gpio.h>
|
SmingHub/Sming
|
Sming/Arch/Host/Components/esp_hal/include/gpio.h
|
C
|
lgpl-3.0
| 69 |
/*
* This file is part of the OWL API.
*
* The contents of this file are subject to the LGPL License, Version 3.0.
*
* Copyright (C) 2011, The University of Manchester
*
* 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 3 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, see http://www.gnu.org/licenses/.
*
*
* Alternatively, the contents of this file may be used under the terms of the Apache License, Version 2.0
* in which case, the provisions of the Apache License Version 2.0 are applicable instead of those above.
*
* Copyright 2011, The University of Manchester
*
* 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.semanticweb.binaryowl.owlobject.serializer;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLDataMaxCardinality;
import org.semanticweb.owlapi.model.OWLDataPropertyExpression;
import org.semanticweb.owlapi.model.OWLDataRange;
/**
* Author: Matthew Horridge<br>
* Stanford University<br>
* Bio-Medical Informatics Research Group<br>
* Date: 25/04/2012
*/
public class OWLDataMaxCardinalityRestrictionSerializer extends OWLDataCardinalityRestrictionSerializer<OWLDataMaxCardinality> {
@Override
protected OWLDataMaxCardinality createRestriction(int cardinality, OWLDataPropertyExpression property, OWLDataRange filler, OWLDataFactory dataFactory) {
return dataFactory.getOWLDataMaxCardinality(cardinality, property, filler);
}
}
|
sesuncedu/binaryowl
|
src/main/java/org/semanticweb/binaryowl/owlobject/serializer/OWLDataMaxCardinalityRestrictionSerializer.java
|
Java
|
lgpl-3.0
| 2,459 |
import sys
def setup():
return
def run(core, actor, target, commandString):
target.transferContainer(actor,target,commandString)
return
|
agry/NGECore2
|
scripts/commands/resourcecontainertransfer.py
|
Python
|
lgpl-3.0
| 153 |
<?php
/**
* Runtime for xwysiwyg module
*
* $Id: runtime.php,v 1.2 2005/07/17 18:04:54 ykuendig Exp $
* @author Yves Kuendig <[email protected]>
* @module xwysiwyg
* @moduletype mixed module / hack
* @package phpwebsite = 0.9.3-4 +
*/
if (isset($GLOBALS['xwysiwyg_areas'])) {
require_once(PHPWS_SOURCE_DIR.'mod/xwysiwyg/class/xwysiwyg.php');//include the xwysiwyg code
$xwysiwyg = new PHPWS_xwysiwyg;
$GLOBALS['core']->js_func[] = $xwysiwyg->makeJS(); //build main-js
}
?>
|
CustomerFeedback/System-Files-Installable
|
myac/fckeditor/module-xwysiwyg-0.4.1/mod/xwysiwyg/inc/runtime.php
|
PHP
|
lgpl-3.0
| 493 |
import { ObjectType, RoleType } from '@allors/meta/system';
import { And, Predicate, Tree } from '@allors/data/system';
export interface SearchOptions {
objectType: ObjectType;
roleTypes: RoleType[];
predicates?: Predicate[];
post?: (and: And) => void;
include?: Tree | any;
}
|
Allors/platform
|
Core/Workspace/Typescript/libs/angular/core/src/export/search/SearchOptions.ts
|
TypeScript
|
lgpl-3.0
| 291 |
/**
* Created on Dec 12, 2015
* @author Lijing Wang [email protected]
*/
#pragma once
#include <ndn-cxx/face.hpp>
#include <ndn-cxx/security/key-chain.hpp>
namespace ndnpaxos {
class Consumer {
public:
Consumer();
Consumer(ndn::Name prefix);
Consumer(ndn::shared_ptr<ndn::Face>);
void consume(ndn::Name name);
private:
void onData(const ndn::Interest& interest, const ndn::Data& data);
void onTimeout(const ndn::Interest& interest);
ndn::shared_ptr<ndn::Face> face_;
ndn::Name prefix_;
};
}// namespace ndnpaxos
|
PhdLoLi/NDNPaxos
|
libndnpaxos/consumer.hpp
|
C++
|
lgpl-3.0
| 540 |
<?php
/**
* @copyright Copyright (c) Metaways Infosystems GmbH, 2011
* @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
* @package MShop
* @subpackage Plugin
*/
/**
* Simple example implementation of a plugin decorator.
*
* @package MShop
* @subpackage Plugin
*/
class MShop_Plugin_Provider_Decorator_Example extends MShop_Plugin_Provider_Decorator_Abstract
{
/**
* Subscribes itself to a publisher
*
* @param MW_Observer_Publisher_Interface $p Object implementing publisher interface
*/
public function register( MW_Observer_Publisher_Interface $p )
{
$this->_getProvider()->register( $p );
}
/**
* Receives a notification from a publisher object
*
* @param MW_Observer_Publisher_Interface $order Shop basket instance implementing publisher interface
* @param string $action Name of the action to listen for
* @param mixed $value Object or value changed in publisher
*/
public function update( MW_Observer_Publisher_Interface $order, $action, $value = null )
{
return $this->_getProvider()->update( $order, $action, $value );
}
}
|
inrivagmbh/aimeos-core
|
lib/mshoplib/src/MShop/Plugin/Provider/Decorator/Example.php
|
PHP
|
lgpl-3.0
| 1,086 |
#
# Copyright 2010 Red Hat, Inc.
#
# This 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.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this software; if not, write to the Free
# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA, or see the FSF site: http://www.fsf.org.
require 'spec_helper'
describe StorageVolumesHelper do
#Delete this example and add some real ones or delete this file
it "should be included in the object returned by #helper" do
included_modules = (class << helper; self; end).send :included_modules
included_modules.should include(StorageVolumesHelper)
end
end
|
auser/steamcannon
|
spec/helpers/storage_volumes_helper_spec.rb
|
Ruby
|
lgpl-3.0
| 1,123 |
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2004, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Foundation;
* either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ------------------
* KeyedObject2D.java
* ------------------
* (C) Copyright 2003, 2004, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* $Id: KeyedObjects2D.java,v 1.1 2004/08/31 15:21:49 mungady Exp $
*
* Changes
* -------
* 05-Feb-2003 : Version 1 (DG);
* 01-Mar-2004 : Added equals() and clone() methods and implemented Serializable (DG);
*
*/
package org.jfree.data;
import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* A data structure that stores zero, one or many objects, where each object is associated with
* two keys (a 'row' key and a 'column' key).
*
*/
public class KeyedObjects2D implements Cloneable, Serializable {
/** The row keys. */
private List rowKeys;
/** The column keys. */
private List columnKeys;
/** The row data. */
private List rows;
/**
* Creates a new instance (initially empty).
*/
public KeyedObjects2D() {
this.rowKeys = new java.util.ArrayList();
this.columnKeys = new java.util.ArrayList();
this.rows = new java.util.ArrayList();
}
/**
* Returns the row count.
*
* @return the row count.
*/
public int getRowCount() {
return this.rowKeys.size();
}
/**
* Returns the column count.
*
* @return the column count.
*/
public int getColumnCount() {
return this.columnKeys.size();
}
/**
* Returns the object for a given row and column.
*
* @param row the row index.
* @param column the column index.
*
* @return the object.
*/
public Object getObject(final int row, final int column) {
Object result = null;
final KeyedObjects rowData = (KeyedObjects) this.rows.get(row);
if (rowData != null) {
final Comparable columnKey = (Comparable) this.columnKeys.get(column);
if (columnKey != null) {
result = rowData.getObject(columnKey);
}
}
return result;
}
/**
* Returns the key for a given row.
*
* @param row the row index (zero based).
*
* @return the row index.
*/
public Comparable getRowKey(final int row) {
return (Comparable) this.rowKeys.get(row);
}
/**
* Returns the row index for a given key.
*
* @param key the key.
*
* @return the row index.
*/
public int getRowIndex(final Comparable key) {
return this.rowKeys.indexOf(key);
}
/**
* Returns the row keys.
*
* @return the row keys (never <code>null</code>).
*/
public List getRowKeys() {
return Collections.unmodifiableList(this.rowKeys);
}
/**
* Returns the key for a given column.
*
* @param column the column.
*
* @return the key.
*/
public Comparable getColumnKey(final int column) {
return (Comparable) this.columnKeys.get(column);
}
/**
* Returns the column index for a given key.
*
* @param key the key.
*
* @return the column index.
*/
public int getColumnIndex(final Comparable key) {
return this.columnKeys.indexOf(key);
}
/**
* Returns the column keys.
*
* @return the column keys (never <code>null</code>).
*/
public List getColumnKeys() {
return Collections.unmodifiableList(this.columnKeys);
}
/**
* Returns the object for the given row and column keys.
*
* @param rowKey the row key.
* @param columnKey the column key.
*
* @return the object.
*/
public Object getObject(final Comparable rowKey, final Comparable columnKey) {
Object result = null;
final int row = this.rowKeys.indexOf(rowKey);
if (row >= 0) {
final KeyedObjects rowData = (KeyedObjects) this.rows.get(row);
result = rowData.getObject(columnKey);
}
return result;
}
/**
* Adds an object to the table. Performs the same function as setObject(...).
*
* @param object the object.
* @param rowKey the row key.
* @param columnKey the column key.
*/
public void addObject(final Object object,
final Comparable rowKey,
final Comparable columnKey) {
setObject(object, rowKey, columnKey);
}
/**
* Adds or updates an object.
*
* @param object the object.
* @param rowKey the row key.
* @param columnKey the column key.
*/
public void setObject(final Object object,
final Comparable rowKey,
final Comparable columnKey) {
final KeyedObjects row;
final int rowIndex = this.rowKeys.indexOf(rowKey);
if (rowIndex >= 0) {
row = (KeyedObjects) this.rows.get(rowIndex);
}
else {
this.rowKeys.add(rowKey);
row = new KeyedObjects();
this.rows.add(row);
}
row.setObject(columnKey, object);
final int columnIndex = this.columnKeys.indexOf(columnKey);
if (columnIndex < 0) {
this.columnKeys.add(columnKey);
}
}
/**
* Removes an object.
*
* @param rowKey the row key.
* @param columnKey the column key.
*/
public void removeObject(final Comparable rowKey, final Comparable columnKey) {
setObject(null, rowKey, columnKey);
// actually, a null value is different to a value that doesn't exist at all.
// need to fix this code.
}
/**
* Removes a row.
*
* @param rowIndex the row index.
*/
public void removeRow(final int rowIndex) {
this.rowKeys.remove(rowIndex);
this.rows.remove(rowIndex);
}
/**
* Removes a row.
*
* @param rowKey the row key.
*/
public void removeRow(final Comparable rowKey) {
removeRow(getRowIndex(rowKey));
}
/**
* Removes a column.
*
* @param columnIndex the column index.
*/
public void removeColumn(final int columnIndex) {
final Comparable columnKey = getColumnKey(columnIndex);
removeColumn(columnKey);
}
/**
* Removes a column.
*
* @param columnKey the column key.
*/
public void removeColumn(final Comparable columnKey) {
final Iterator iterator = this.rows.iterator();
while (iterator.hasNext()) {
final KeyedObjects rowData = (KeyedObjects) iterator.next();
rowData.removeValue(columnKey);
}
this.columnKeys.remove(columnKey);
}
/**
* Tests this object for equality with an arbitrary object.
*
* @param obj the object to test (<code>null</code> permitted).
*
* @return a boolean.
*/
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof KeyedObjects2D)) {
return false;
}
final KeyedObjects2D ko2D = (KeyedObjects2D) obj;
if (!getRowKeys().equals(ko2D.getRowKeys())) {
return false;
}
if (!getColumnKeys().equals(ko2D.getColumnKeys())) {
return false;
}
final int rowCount = getRowCount();
if (rowCount != ko2D.getRowCount()) {
return false;
}
final int colCount = getColumnCount();
if (colCount != ko2D.getColumnCount()) {
return false;
}
for (int r = 0; r < rowCount; r++) {
for (int c = 0; c < colCount; c++) {
final Object v1 = getObject(r, c);
final Object v2 = ko2D.getObject(r, c);
if (v1 == null) {
if (v2 != null) {
return false;
}
}
else {
if (!v1.equals(v2)) {
return false;
}
}
}
}
return true;
}
/**
* Returns a hashcode for this object.
*
* @return a hashcode.
*/
public int hashCode() {
int result;
result = this.rowKeys.hashCode();
result = 29 * result + this.columnKeys.hashCode();
result = 29 * result + this.rows.hashCode();
return result;
}
/**
* Returns a clone.
*
* @return a clone.
*
* @throws CloneNotSupportedException this class will not throw this exception, but subclasses
* (if any) might.
*/
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
|
simeshev/parabuild-ci
|
3rdparty/jfreechart0921/source/org/jfree/data/KeyedObjects2D.java
|
Java
|
lgpl-3.0
| 10,159 |
//----------------------------------------------------------------------------
/** @file MoHexThreadState.hpp */
//----------------------------------------------------------------------------
#ifndef NEIGHBORTRACKER_HPP
#define NEIGHBORTRACKER_HPP
#include "BitsetIterator.hpp"
#include "HexColor.hpp"
#include "Groups.hpp"
#include "UnionFind.hpp"
_BEGIN_BENZENE_NAMESPACE_
class NeighborTracker
{
public:
void Init(const Groups& groups);
HexColor GetWinner() const;
bool GameOver() const;
void Play(const HexColor color, const HexPoint x,
const StoneBoard& brd);
bitset_t Threats(const HexColor color) const;
private:
bitset_t m_empty_nbs[BITSETSIZE];
UnionFind<BITSETSIZE> m_groups;
};
//----------------------------------------------------------------------------
_END_BENZENE_NAMESPACE_
#endif // NEIGHBORTRACKER_HPP
|
yotomyoto/benzene
|
src/hex/NeighborTracker.hpp
|
C++
|
lgpl-3.0
| 881 |
package org.red5.server;
/*
* RED5 Open Source Flash Server - http://www.osflash.org/red5
*
* Copyright (c) 2006-2009 by respective authors (see below). All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation; either version 2.1 of the License, or (at your option) any later
* version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.red5.server.api.IBasicScope;
import org.red5.server.api.IScope;
import org.red5.server.api.ScopeUtils;
import org.red5.server.api.event.IEvent;
import org.red5.server.api.event.IEventListener;
import org.red5.server.api.scheduling.IScheduledJob;
import org.red5.server.api.scheduling.ISchedulingService;
/**
* Generalizations of one of main Red5 object types, Scope.
* Basic scope is a persistable attribute store with event handling functionality
*
* @see org.red5.server.api.IScope
* @see org.red5.server.Scope
*/
public abstract class BasicScope extends PersistableAttributeStore implements IBasicScope {
/**
* Parent scope. Scopes can be nested.
*
* @see org.red5.server.api.IScope
*/
protected IScope parent;
/**
* List of event listeners
*/
protected Set<IEventListener> listeners;
/**
* Scope persistence storage type
*/
protected String persistenceClass;
/**
* Set to true to prevent the scope from being freed upon disconnect.
*/
protected boolean keepOnDisconnect = false;
/**
* Set to amount of time (in seconds) the scope will be kept before being freed,
* after the last disconnect.
*/
protected int keepDelay = 0;
/**
* Creates unnamed scope
*/
public BasicScope() {
this(null, "scope", null, false);
}
/**
* Constructor for basic scope
*
* @param parent Parent scope
* @param type Scope type
* @param name Scope name. Used to identify scopes in application, must be unique among scopes of one level
* @param persistent Whether scope is persistent
*/
public BasicScope(IScope parent, String type, String name, boolean persistent) {
super(type, name, null, persistent);
this.parent = parent;
this.listeners = new HashSet<IEventListener>();
}
/**
* {@inheritDoc}
*/
public boolean hasParent() {
return true;
}
/**
*{@inheritDoc}
*/
public IScope getParent() {
return parent;
}
/**
*{@inheritDoc}
*/
public int getDepth() {
return parent.getDepth() + 1;
}
/**
*{@inheritDoc}
*/
@Override
public String getPath() {
return parent.getPath() + '/' + parent.getName();
}
/**
* Sets the amount of time to keep the scope available after the
* last disconnect.
*
* @param keepDelay delay
*/
public void setKeepDelay(int keepDelay) {
this.keepDelay = keepDelay;
}
/**
* Add event listener to list of notified objects
* @param listener Listening object
*/
public void addEventListener(IEventListener listener) {
listeners.add(listener);
}
/**
* Remove event listener from list of listeners
* @param listener Listener to remove
*/
public void removeEventListener(IEventListener listener) {
listeners.remove(listener);
if (!keepOnDisconnect) {
if (ScopeUtils.isRoom(this) && listeners.isEmpty()) {
if (keepDelay > 0) {
// create a job to keep alive for n seconds
ISchedulingService schedulingService = (ISchedulingService) parent.getContext().getBean(
ISchedulingService.BEAN_NAME);
schedulingService.addScheduledOnceJob(keepDelay * 1000, new KeepAliveJob(this));
} else {
// delete empty rooms
parent.removeChildScope(this);
}
}
}
}
/**
* Return listeners list iterator
*
* @return Listeners list iterator
*/
public Iterator<IEventListener> getEventListeners() {
return listeners.iterator();
}
/**
* Returns true if there are event listeners attached to
* this scope.
*
* @return true if it has listeners; else false.
*/
public boolean hasEventListeners() {
return !listeners.isEmpty();
}
/**
* Handles event. To be implemented in subclass realization
*
* @param event Event context
* @return Event handling result
*/
public boolean handleEvent(IEvent event) {
// do nothing.
return false;
}
/**
* Notifies listeners on event. Current implementation is empty. To be implemented in subclass realization
* @param event Event to broadcast
*/
public void notifyEvent(IEvent event) {
}
/**
* Dispatches event (notifies all listeners)
*
* @param event Event to dispatch
*/
public void dispatchEvent(IEvent event) {
for (IEventListener listener : listeners) {
if (event.getSource() == null || event.getSource() != listener) {
listener.notifyEvent(event);
}
}
}
/**
* Getter for subscopes list iterator. Returns null because this is a base implementation
*
* @return Iterator for subscopes
*/
public Iterator<IBasicScope> iterator() {
return null;
}
/**
* Iterator for basic scope
*/
public static class EmptyBasicScopeIterator implements Iterator<IBasicScope> {
/** {@inheritDoc} */
public boolean hasNext() {
return false;
}
/** {@inheritDoc} */
public IBasicScope next() {
return null;
}
/** {@inheritDoc} */
public void remove() {
// nothing
}
}
/**
* Keeps the scope alive for a set number of seconds. This should
* fulfill the APPSERVER-165 improvement.
*/
private class KeepAliveJob implements IScheduledJob {
private IBasicScope scope = null;
KeepAliveJob(IBasicScope scope) {
this.scope = scope;
}
public void execute(ISchedulingService service) {
if (listeners.isEmpty()) {
// delete empty rooms
parent.removeChildScope(scope);
}
}
}
}
|
OpenCorrelate/red5load
|
red5/src/main/java/org/red5/server/BasicScope.java
|
Java
|
lgpl-3.0
| 6,682 |
#
# @BEGIN LICENSE
#
# Psi4: an open-source quantum chemistry software package
#
# Copyright (c) 2007-2022 The Psi4 Developers.
#
# The copyrights for code used from other parties are included in
# the corresponding files.
#
# This file is part of Psi4.
#
# Psi4 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, version 3.
#
# Psi4 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 Psi4; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# @END LICENSE
#
"""Module with non-generic exceptions classes."""
class QcdbException(Exception):
"""Error class for QCDB."""
pass
class FeatureNotImplemented(QcdbException):
"""Error called for functions defined but not yet implemented.
Also for functions defined that will never be implemented.
"""
def __init__(self, msg):
QcdbException.__init__(self, msg)
self.msg = msg
print('\nQcdbException: Feature %s is not yet implemented.\n\n' % (msg))
class ValidationError(QcdbException):
"""Error called for problems with syntax input file. Prints
error message *msg* to standard output stream.
"""
def __init__(self, msg):
QcdbException.__init__(self, msg)
self.msg = msg
print('\nQcdbException: %s\n\n' % (msg))
class IncompleteAtomError(QcdbException):
"""Error raised when not all variables in an atom specification
have been defined at compute time. May be a temporary situation
so message not printed but appears as traceback when error persists.
"""
def __init__(self, msg):
QcdbException.__init__(self, msg)
self.msg = msg
class ParsingValidationError(QcdbException):
"""Error called for problems with syntax from a QC output file. Prints
error message *msg* to standard output stream.
"""
def __init__(self, msg):
QcdbException.__init__(self, msg)
self.msg = msg
print('\nQcdbException: %s\n\n' % (msg))
class FragmentCountError(QcdbException):
"""Error called molecule has wrong number of fragments for method.
Prints error message *msg* to standard output stream.
"""
def __init__(self, msg):
QcdbException.__init__(self, msg)
self.msg = msg
#print('\nQcdbException: %s\n\n' % (msg))
class BasisSetFileNotFound(QcdbException):
"""
"""
def __init__(self, msg):
QcdbException.__init__(self, msg)
self.msg = msg
print('\nQcdbException BasisSetFileNotFound: %s\n\n' % (msg))
class BasisSetNotFound(QcdbException):
"""
"""
def __init__(self, msg, silent=False):
QcdbException.__init__(self, msg)
self.msg = msg
if not silent:
print('\nQcdbException BasisSetNotFound: %s\n\n' % (msg))
class BasisSetNotDefined(QcdbException):
"""
"""
def __init__(self, msg):
QcdbException.__init__(self, msg)
self.msg = msg
print('\nQcdbException BasisSetNotDefined: %s\n\n' % (msg))
class Dftd3Error(QcdbException):
"""
"""
def __init__(self, msg):
QcdbException.__init__(self, msg)
self.msg = msg
print('\nDftd3Error: %s\n\n' % (msg))
class TestComparisonError(QcdbException):
"""Error called when a test case fails due to a failed
compare_values() call. Prints error message *msg* to standard
output stream and output file.
"""
def __init__(self, msg):
QcdbException.__init__(self, msg)
self.msg = msg
print('\nQcdbException: %s\n\n' % msg)
class MoleculeFormatError(QcdbException):
"""Error called when a Molecule.from_string contains unparsable lines."""
def __init__(self, msg):
QcdbException.__init__(self, msg)
self.msg = msg
class FeatureDeprecated(QcdbException):
"""Error called for functions removed but still defined.
Should suggest a replacement.
"""
def __init__(self, msg):
QcdbException.__init__(self, msg)
self.msg = msg
print('\nFeature deprecated: {}\n\n'.format(msg))
class UpgradeHelper(QcdbException):
"""Error called on previously valid syntax that now isn't and a
simple syntax transition is possible.
It is much preferred to leave the old syntax valid for a release
cycle and have the old syntax raise a deprecation FutureWarning. For
cases where the syntax just has to jump, this can be used to trap
the old syntax at first error and suggest the new.
"""
def __init__(self, old, new, version, elaboration):
msg = "Using `{}` instead of `{}` is obsolete as of {}.{}".format(old, new, version, elaboration)
QcdbException.__init__(self, msg)
print('\nQcdbException: %s\n\n' % (msg))
|
psi4/psi4
|
psi4/driver/qcdb/exceptions.py
|
Python
|
lgpl-3.0
| 5,158 |
/*
[The "BSD licence"]
Copyright (c) 2005-2008 Terence Parr
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.antlr.tool;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.analysis.DecisionProbe;
/** Reports the condition that ANTLR's LL(*) analysis engine terminated
* early.
*/
public class GrammarAnalysisAbortedMessage extends Message {
public DecisionProbe probe;
public GrammarAnalysisAbortedMessage(DecisionProbe probe) {
super(ErrorManager.MSG_ANALYSIS_ABORTED);
this.probe = probe;
}
public String toString() {
GrammarAST decisionASTNode = probe.dfa.getDecisionASTNode();
line = decisionASTNode.getLine();
column = decisionASTNode.getColumn();
String fileName = probe.dfa.nfa.grammar.getFileName();
if ( fileName!=null ) {
file = fileName;
}
StringTemplate st = getMessageTemplate();
st.setAttribute("enclosingRule",
probe.dfa.getNFADecisionStartState().enclosingRule.name);
return super.toString(st);
}
}
|
pcingola/jFuzzyLogic
|
antlr_3_1_source/tool/GrammarAnalysisAbortedMessage.java
|
Java
|
lgpl-3.0
| 2,322 |
#pragma once
#include <cstdlib>
#include <ctime>
#include <cmath>
typedef unsigned int Seed;
class BasicRNG
{
public:
BasicRNG();
BasicRNG(Seed seed);
virtual ~BasicRNG();
inline Seed get_seed() const {return _seed;}
inline void set_seed(Seed seed) {_seed = seed;}
int operator()();
inline int get_int();
inline int get_int(int max_val, int min_val=0);
inline double get_double();
inline double get_double(int max_val, int min_val=0);
private:
Seed _seed;
};
inline int BasicRNG::get_int()
{
return rand();
}
inline double BasicRNG::get_double()
{
return rand()/(1.0*RAND_MAX);
}
inline int BasicRNG::get_int(int max_val, int min_val)
{
return min_val + std::ceil(rand()/(1.0*RAND_MAX)*(max_val-min_val));
}
inline double BasicRNG::get_double(int max_val, int min_val)
{
return min_val + rand()/(1.0*RAND_MAX)*(max_val-min_val);
}
|
ndoxx/SimuAlban
|
lib/DataProjection/include/BasicRNG.h
|
C
|
lgpl-3.0
| 962 |
//
// BOXViewController.h
// iBeaconInstallationBox
//
// Created by Danny Holmes on 4/10/14.
// Copyright (c) 2014 edu.EMDM.LSU. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "WebVC.h"
@interface BOXViewController : UIViewController <CLLocationManagerDelegate>
@end
|
lsuEMDM/flight
|
iOS app/iBeaconInstallationBox/BOXViewController.h
|
C
|
lgpl-3.0
| 322 |
<?php
/**
* Test class for MW_Cache_DB.
*
* @copyright Copyright (c) Metaways Infosystems GmbH, 2014
* @license LGPLv3, http://www.gnu.org/licenses/lgpl.html
*/
class MW_Cache_DBTest extends PHPUnit_Framework_TestCase
{
private $_dbm;
private $_config;
private $_object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*
* @access protected
*/
protected function setUp()
{
if( TestHelper::getConfig()->get( 'resource/db/adapter', false ) === false ) {
$this->markTestSkipped( 'No database configured' );
}
$this->_config = array( 'siteid' => 1 );
$this->_config['search'] = array(
'cache.id' => array( 'label' => 'Cache ID', 'code' => 'cache.id', 'internalcode' => 'id', 'type' => 'string', 'internaltype' => MW_DB_Statement_Abstract::PARAM_STR ),
'cache.siteid' => array( 'label' => 'Cache site ID', 'code' => 'cache.siteid', 'internalcode' => 'siteid', 'type' => 'integer', 'internaltype' => MW_DB_Statement_Abstract::PARAM_INT ),
'cache.value' => array( 'label' => 'Cached value', 'code' => 'cache.value', 'internalcode' => 'value', 'type' => 'string', 'internaltype' => MW_DB_Statement_Abstract::PARAM_STR ),
'cache.expire' => array( 'label' => 'Cache expiration date', 'code' => 'cache.expire', 'internalcode' => 'expire', 'type' => 'datetime', 'internaltype' => MW_DB_Statement_Abstract::PARAM_STR ),
'cache.tag.name' => array( 'label' => 'Cache tag name', 'code' => 'cache.tag.name', 'internalcode' => 'tname', 'type' => 'string', 'internaltype' => MW_DB_Statement_Abstract::PARAM_STR ),
);
$this->_config['sql'] = array(
'delete' => '
DELETE FROM "mw_cache_test" WHERE "siteid" = ? AND :cond
',
'deletebytag' => '
DELETE FROM "mw_cache_test" WHERE "siteid" = ? AND id IN (
SELECT "tid" FROM "mw_cache_tag_test" WHERE "tsiteid" = ? AND :cond
)
',
'get' => '
SELECT "id", "value", "expire" FROM "mw_cache_test" WHERE "siteid" = ? AND :cond
',
'getbytag' => '
SELECT "id", "value", "expire" FROM "mw_cache_test"
JOIN "mw_cache_tag_test" ON "tid" = "id"
WHERE siteid = ? AND tsiteid = ? AND :cond
',
'set' => '
INSERT INTO "mw_cache_test" ( "id", "siteid", "expire", "value" ) VALUES ( ?, ?, ?, ? )
',
'settag' => '
INSERT INTO "mw_cache_tag_test" ( "tid", "tsiteid", "tname" ) VALUES ( ?, ?, ? )
',
);
$this->_dbm = TestHelper::getDBManager();
$conn = $this->_dbm->acquire();
$sql = 'DROP TABLE IF EXISTS "mw_cache_tag_test"';
$conn->create( $sql )->execute()->finish();
$sql = 'DROP TABLE IF EXISTS "mw_cache_test"';
$conn->create( $sql )->execute()->finish();
$sql = '
CREATE TABLE IF NOT EXISTS "mw_cache_test" (
"id" VARCHAR(255) NOT NULL,
"siteid" INTEGER NULL,
"expire" DATETIME NULL,
"value" MEDIUMTEXT NOT NULL,
KEY ("expire"),
CONSTRAINT PRIMARY KEY ("id", "siteid")
);
';
$conn->create( $sql )->execute()->finish();
$sql = '
CREATE TABLE IF NOT EXISTS "mw_cache_tag_test" (
"tid" VARCHAR(255) NOT NULL,
"tsiteid" INTEGER NULL,
"tname" VARCHAR(255) NOT NULL,
CONSTRAINT UNIQUE ("tid", "tsiteid", "tname"),
CONSTRAINT FOREIGN KEY ("tid") REFERENCES "mw_cache_test" ("id") ON DELETE CASCADE
);
';
$conn->create( $sql )->execute()->finish();
$sql = 'INSERT INTO "mw_cache_test" ("id", "siteid", "expire", "value") VALUES (\'t:1\', 1, NULL, \'test 1\')';
$conn->create( $sql )->execute()->finish();
$sql = 'INSERT INTO "mw_cache_test" ("id", "siteid", "expire", "value") VALUES (\'t:2\', 1, \'2000-01-01 00:00:00\', \'test 2\')';
$conn->create( $sql )->execute()->finish();
$sql = 'INSERT INTO "mw_cache_tag_test" ("tid", "tsiteid", "tname") VALUES (\'t:1\', 1, \'tag:1\')';
$conn->create( $sql )->execute()->finish();
$this->_dbm->release( $conn );
$this->_object = new MW_Cache_DB( $this->_config, $this->_dbm );
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*
* @access protected
*/
protected function tearDown()
{
$this->_dbm = TestHelper::getDBManager();
$conn = $this->_dbm->acquire();
$conn->create( 'DROP TABLE "mw_cache_tag_test"' )->execute()->finish();
$conn->create( 'DROP TABLE "mw_cache_test"' )->execute()->finish();
$this->_dbm->release( $conn );
}
public function testConstructorNoConfig()
{
$this->setExpectedException( 'MW_Cache_Exception' );
new MW_Cache_DB( array(), $this->_dbm );
}
public function testConstructorNoSql()
{
$config = $this->_config;
unset( $config['sql'] );
$this->setExpectedException( 'MW_Cache_Exception' );
new MW_Cache_DB( $config, $this->_dbm );
}
public function testConstructorNoSearch()
{
$config = $this->_config;
unset( $config['search'] );
$this->setExpectedException( 'MW_Cache_Exception' );
new MW_Cache_DB( $config, $this->_dbm );
}
public function testConstructorIncompleteSql()
{
$config = $this->_config;
unset( $config['sql']['delete'] );
$this->setExpectedException( 'MW_Cache_Exception' );
new MW_Cache_DB( $config, $this->_dbm );
}
public function testConstructorIncompleteSearch()
{
$config = $this->_config;
unset( $config['search']['cache.id'] );
$this->setExpectedException( 'MW_Cache_Exception' );
new MW_Cache_DB( $config, $this->_dbm );
}
public function testCleanup()
{
$this->_object->cleanup();
$conn = $this->_dbm->acquire();
$result = $conn->create( 'SELECT "id" FROM "mw_cache_test"' )->execute();
$this->_dbm->release( $conn );
$this->assertEquals( array( 'id' => 't:1' ), $result->fetch() );
$this->assertFalse( $result->fetch() );
}
public function testDelete()
{
$this->_object->delete( 't:1' );
$conn = $this->_dbm->acquire();
$row = $conn->create( 'SELECT * FROM "mw_cache_tag_test"' )->execute()->fetch();
$this->_dbm->release( $conn );
$this->assertFalse( $row );
$conn = $this->_dbm->acquire();
$result = $conn->create( 'SELECT "id" FROM "mw_cache_test"' )->execute();
$this->_dbm->release( $conn );
$this->assertEquals( array( 'id' => 't:2' ), $result->fetch() );
$this->assertFalse( $result->fetch() );
}
public function testDeleteList()
{
$this->_object->deleteList( array( 't:1', 't:2' ) );
$conn = $this->_dbm->acquire();
$row = $conn->create( 'SELECT * FROM "mw_cache_test"' )->execute()->fetch();
$this->_dbm->release( $conn );
$this->assertFalse( $row );
}
public function testDeleteByTags()
{
$this->_object->deleteByTags( array( 'tag:1' ) );
$conn = $this->_dbm->acquire();
$row = $conn->create( 'SELECT * FROM "mw_cache_tag_test"' )->execute()->fetch();
$this->_dbm->release( $conn );
$this->assertFalse( $row );
$conn = $this->_dbm->acquire();
$result = $conn->create( 'SELECT "id" FROM "mw_cache_test"' )->execute();
$this->_dbm->release( $conn );
$this->assertEquals( array( 'id' => 't:2' ), $result->fetch() );
$this->assertFalse( $result->fetch() );
}
public function testFlush()
{
$this->_object->flush();
$conn = $this->_dbm->acquire();
$row = $conn->create( 'SELECT * FROM "mw_cache_tag_test"' )->execute()->fetch();
$this->_dbm->release( $conn );
$this->assertFalse( $row );
$conn = $this->_dbm->acquire();
$row = $conn->create( 'SELECT "id" FROM "mw_cache_test"' )->execute()->fetch();
$this->_dbm->release( $conn );
$this->assertFalse( $row );
}
public function testGet()
{
$this->assertEquals( 'test 1', $this->_object->get( 't:1' ) );
}
public function testGetExpired()
{
$this->assertEquals( null, $this->_object->get( 't:2' ) );
}
public function testGetList()
{
$this->assertEquals( array( 't:1' => 'test 1' ), $this->_object->getList( array( 't:1', 't:2' ) ) );
}
public function testGetListByTags()
{
$this->assertEquals( array( 't:1' => 'test 1' ), $this->_object->getListByTags( array( 'tag:1' ) ) );
}
public function testSet()
{
$this->_object->set( 't:3', 'test 3', array( 'tag:2', 'tag:3' ), '2100-00-00 00:00:00' );
$conn = $this->_dbm->acquire();
$result = $conn->create( 'SELECT "tname" FROM "mw_cache_tag_test" WHERE "tid" = \'t:3\' ORDER BY "tname"' )->execute();
$this->_dbm->release( $conn );
$this->assertEquals( array( 'tname' => 'tag:2' ), $result->fetch() );
$this->assertEquals( array( 'tname' => 'tag:3' ), $result->fetch() );
$this->assertFalse( $result->fetch() );
$conn = $this->_dbm->acquire();
$result = $conn->create( 'SELECT * FROM "mw_cache_test" WHERE "id" = \'t:3\'' )->execute();
$this->_dbm->release( $conn );
$expected = array(
'expire' => '2100-00-00 00:00:00',
'id' => 't:3',
'siteid' => 1,
'value' => 'test 3',
);
$this->assertEquals( $expected, $result->fetch() );
$this->assertFalse( $result->fetch() );
}
public function testSetList()
{
$pairs = array( 't:3' => 'test 3', 't:2' => 'test 4' );
$tags = array( 't:3' => array( 'tag:2', 'tag:3' ), 't:2' => array( 'tag:4' ) );
$expires = array( 't:3' => '2100-00-00 00:00:00' );
$this->_object->setList( $pairs, $tags, $expires );
$conn = $this->_dbm->acquire();
$result = $conn->create( 'SELECT "tname" FROM "mw_cache_tag_test" WHERE "tid" = \'t:3\' ORDER BY "tname"' )->execute();
$this->_dbm->release( $conn );
$this->assertEquals( array( 'tname' => 'tag:2' ), $result->fetch() );
$this->assertEquals( array( 'tname' => 'tag:3' ), $result->fetch() );
$this->assertFalse( $result->fetch() );
$conn = $this->_dbm->acquire();
$result = $conn->create( 'SELECT "tname" FROM "mw_cache_tag_test" WHERE "tid" = \'t:2\'' )->execute();
$this->_dbm->release( $conn );
$this->assertEquals( array( 'tname' => 'tag:4' ), $result->fetch() );
$this->assertFalse( $result->fetch() );
$conn = $this->_dbm->acquire();
$result = $conn->create( 'SELECT * FROM "mw_cache_test" WHERE "id" = \'t:3\'' )->execute();
$this->_dbm->release( $conn );
$expected = array(
'expire' => '2100-00-00 00:00:00',
'id' => 't:3',
'siteid' => 1,
'value' => 'test 3',
);
$this->assertEquals( $expected, $result->fetch() );
$this->assertFalse( $result->fetch() );
$conn = $this->_dbm->acquire();
$result = $conn->create( 'SELECT * FROM "mw_cache_test" WHERE "id" = \'t:2\'' )->execute();
$this->_dbm->release( $conn );
$expected = array(
'expire' => null,
'id' => 't:2',
'siteid' => 1,
'value' => 'test 4',
);
$this->assertEquals( $expected, $result->fetch() );
$this->assertFalse( $result->fetch() );
}
public function testSetException()
{
$this->setExpectedException( 'MW_Cache_Exception' );
$this->_object->set( array(), '' );
}
}
|
Yvler/aimeos-core
|
lib/mwlib/tests/MW/Cache/DBTest.php
|
PHP
|
lgpl-3.0
| 10,706 |
import sys
import maya.cmds as cmds
import maya.OpenMayaUI as mui
from maya.app.general.mayaMixin import MayaQWidgetDockableMixin
try:
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from PySide2 import __version__
from shiboken2 import wrapInstance
from RMPY.Tools.QT5.ui import FormFacialRig
except ImportError:
from PySide.QtCore import *
from PySide.QtGui import *
from PySide import __version__
from shiboken import wrapInstance
from RMPY.Tools.QT4.ui import FormFacialRig
import maya.mel as mel
import os
from RMPY import RMblendShapesTools
from RMPY import RMRigTools
from RMPY.FacialRig import FacialConfigurationNew as FacialConfiguration
from RMPY import RMParametersManager
Dictionaries = {
'lidShapes' :FacialConfiguration.lidShapes,#0
'EyeBallPupil' :FacialConfiguration.EyeBallPupil,#1
'Cristaline' :FacialConfiguration.Cristaline,#2
'EyeJawJoints' :FacialConfiguration.EyeJawJoints,#4
#'mouthSecondarys' :FacialConfiguration.mouthSecondarys,#3
'mouth' :FacialConfiguration.mouth,#5
'Cheeks' :FacialConfiguration.Cheeks,#6
'mouthMover' :FacialConfiguration.mouthMover,#7
'Nose' :FacialConfiguration.Nose,#8
'Furrow' :FacialConfiguration.Furrow,#9
#'secondaryEyeBrow' :FacialConfiguration.secondaryEyeBrow,#10
'EyeBrow' :FacialConfiguration.EyeBrow
}
def getMayaWindow():
ptr = mui.MQtUtil.mainWindow()
return wrapInstance(long(ptr), QMainWindow)
class main(MayaQWidgetDockableMixin,QDialog):
def __init__(self, parent=None):
super(main,self).__init__(parent=getMayaWindow())
self.ui=FormFacialRig.Ui_Form()
self.ui.setupUi(self)
self.setWindowTitle('FacialRig')
self.ui.CheckBtn.clicked.connect(self.CheckBtnPressed)
self.ui.ImportFacialInterfaceBtn.clicked.connect(self.ImportFacialInterfaceBtnPressed)
self.ui.DeleteAttributesBtn.clicked.connect(self.deleteAttributes)
self.ui.ListCBx.currentIndexChanged.connect(self.comboBoxChanged)
self.ui.renameRightBtn.clicked.connect(self.renameRightBtn)
self.ui.LinkAllBtn.clicked.connect(self.linkAllDictionaries)
self.ui.UsePrefixChkBx.stateChanged.connect(self.usePrefixChkBxStateChanged)
for eachItem in sorted(Dictionaries):
self.ui.ListCBx.addItem(eachItem)
self.ui.LinkSelectedBtn.clicked.connect(self.connectDictionary)
self.Manager = RMblendShapesTools.BSManager()
self.ui.PrefixLineEdit.textChanged.connect(self.CheckBtnPressed)
def usePrefixChkBxStateChanged(self):
if self.ui.UsePrefixChkBx.checkState() == QtCore.Qt.CheckState.Checked:
self.ui.PrefixLineEdit.setEnabled(True)
else:
self.ui.PrefixLineEdit.setDisabled(True)
self.CheckBtnPressed()
def renameRightBtn(self):
selection = cmds.ls(selection=True)
for i in selection:
cmds.rename (i , "R" + i[1:-1])
def comboBoxChanged(self):
self.CheckBtnPressed()
def connectDictionary(self):
if self.ui.PrefixLineEdit.isEnabled():
objectNamePrefix = self.ui.PrefixLineEdit.text()
else:
objectNamePrefix=''
linkDictionary = Dictionaries[self.ui.ListCBx.currentText()]
self.Manager.AppyBlendShapeDefinition(linkDictionary, objectPrefix = objectNamePrefix)
def linkAllDictionaries(self):
if self.ui.PrefixLineEdit.isEnabled():
objectNamePrefix = self.ui.PrefixLineEdit.text()
else:
objectNamePrefix=''
for eachDic in Dictionaries:
self.Manager.AppyBlendShapeDefinition(Dictionaries[eachDic], objectPrefix = objectNamePrefix)
def deleteAttributes(self):
selection = cmds.ls(selection = True)
for eachObject in selection:
RMParametersManager.deleteAttributes(eachObject)
def CheckBtnPressed(self):
if self.ui.PrefixLineEdit.isEnabled():
objectNamePrefix = self.ui.PrefixLineEdit.text()
else:
objectNamePrefix=''
self.ui.listWidget.clear()
eachDic = Dictionaries[self.ui.ListCBx.currentText()]
for eachDefinition in eachDic:
print eachDefinition
if eachDic[eachDefinition]['Type'] == 'blendShapeDefinition':
arrayPrefix =[]
if eachDic[eachDefinition]['isSymetrical'] == True:
arrayPrefix = ["L","R"]
else :
arrayPrefix = [""]
for eachPrefix in arrayPrefix:
for eachBlendShape in sorted(eachDic[eachDefinition]['blendShapes']):
if not cmds.objExists(eachPrefix + objectNamePrefix + eachBlendShape):
self.ui.listWidget.addItem(eachPrefix+ objectNamePrefix + eachBlendShape)
def ImportFacialInterfaceBtnPressed(self):
path = os.path.dirname(RMRigTools.__file__)
RMMel=os.path.split(path)
FinalPath = os.path.join(RMMel[0],"Python\FacialRig\RigShapes\FacialInterface.mb")
if os.path.isfile(FinalPath):
cmds.file( FinalPath, i=True, type="mayaBinary", ignoreVersion = True, mergeNamespacesOnClash=False, rpr="", pr = False)
else:
print "archivo de RigFacial No encontrado"
return None
if __name__ == '__main__':
w = main()
w.show()
|
rendermotion/RMPY
|
Tools/RMINTFacialRig.py
|
Python
|
lgpl-3.0
| 5,723 |
// Generated by using Rcpp::compileAttributes() -> do not edit by hand
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include "cellauto_types.h"
#include <Rcpp.h>
using namespace Rcpp;
// cpp_init_address
void cpp_init_address(Mats mats, int nrow, int ncol);
RcppExport SEXP cellauto_cpp_init_address(SEXP matsSEXP, SEXP nrowSEXP, SEXP ncolSEXP) {
BEGIN_RCPP
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Mats >::type mats(matsSEXP);
Rcpp::traits::input_parameter< int >::type nrow(nrowSEXP);
Rcpp::traits::input_parameter< int >::type ncol(ncolSEXP);
cpp_init_address(mats, nrow, ncol);
return R_NilValue;
END_RCPP
}
// cpp_update
void cpp_update(const IntegerVector changes, Mats mats, const bool lives);
RcppExport SEXP cellauto_cpp_update(SEXP changesSEXP, SEXP matsSEXP, SEXP livesSEXP) {
BEGIN_RCPP
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const IntegerVector >::type changes(changesSEXP);
Rcpp::traits::input_parameter< Mats >::type mats(matsSEXP);
Rcpp::traits::input_parameter< const bool >::type lives(livesSEXP);
cpp_update(changes, mats, lives);
return R_NilValue;
END_RCPP
}
// cpp_step
size_t cpp_step(IntegerVector born_at, IntegerVector lives_at, double grow, double decay, Mats mats, List counts);
RcppExport SEXP cellauto_cpp_step(SEXP born_atSEXP, SEXP lives_atSEXP, SEXP growSEXP, SEXP decaySEXP, SEXP matsSEXP, SEXP countsSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< IntegerVector >::type born_at(born_atSEXP);
Rcpp::traits::input_parameter< IntegerVector >::type lives_at(lives_atSEXP);
Rcpp::traits::input_parameter< double >::type grow(growSEXP);
Rcpp::traits::input_parameter< double >::type decay(decaySEXP);
Rcpp::traits::input_parameter< Mats >::type mats(matsSEXP);
Rcpp::traits::input_parameter< List >::type counts(countsSEXP);
rcpp_result_gen = Rcpp::wrap(cpp_step(born_at, lives_at, grow, decay, mats, counts));
return rcpp_result_gen;
END_RCPP
}
|
helmingstay/cellauto
|
src/RcppExports.cpp
|
C++
|
lgpl-3.0
| 2,095 |
/*
* TMF
* Copyright (C) TMF Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 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, see <http://www.gnu.org/licenses/>.
*/
#include "convolution.h"
using namespace df;
using namespace std;
ActorRegister<Convolution> Convolution::reg("Convolution");
Convolution::Convolution(const string& name) : Actor(name) {
input = createInputPort<df::Mat>("input");
output = createOutputPort<df::Mat>("output");
}
void Convolution::init() {
if (!propEmpty("kernel_size"))
kernel_size = getPropInt("kernel_size");
else
kernel_size = 3;
kernel = cv::Mat::ones( kernel_size, kernel_size, CV_32F ) /
(float)(kernel_size*kernel_size);
if (!propEmpty("kernel_val")) {
int kernel_val = getPropInt("kernel_val");
for (int i=0; i<kernel_size; i++)
for (int j=0; j<kernel_size; j++)
kernel.at<cv::Vec2f>(j,i)[0] = kernel_val /
(float)(kernel_size*kernel_size);
}
anchor = cv::Point(0,0);
delta = 0;
ddepth = -1;
/* Filter2D computes correlation.
* To get a convolution, the kernel
* needs to be flipped and the anchor
* needs to be set.
*/
cv::flip(kernel, kernel, 1);
}
void Convolution::run() {
anchor = cv::Point(kernel.cols - anchor.x - 1, kernel.rows - anchor.y -1);
df::Mat * in = consume(input);
df::Mat * out = produce(output);
cv::filter2D(*in->get(), *out->get(), ddepth, kernel, anchor, delta, cv::BORDER_DEFAULT);
log("sending frame "+to_string(stepno));
release(input);
release(output);
}
Convolution::~Convolution() {
destroyPort(input);
destroyPort(output);
}
|
ashafiei/tmf
|
src/dataflow/actors/machine-learning/convolution.cpp
|
C++
|
lgpl-3.0
| 2,143 |
/**
* Copyright (C) 2013 Inera AB (http://www.inera.se)
*
* This file is part of Inera Axel (http://code.google.com/p/inera-axel).
*
* Inera Axel 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.
*
* Inera Axel is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
/**
*
*/
package se.inera.axel.shs.broker.agreement.mongo;
import static org.testng.Assert.assertEquals;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import se.inera.axel.shs.broker.agreement.mongo.model.MongoShsAgreement;
import se.inera.axel.shs.broker.agreement.mongo.model.Product;
/**
* @author Jan Hallonstén, R2M
*
*/
@ContextConfiguration
public class MongoShsAgreementRepositoryIT extends
AbstractAgreementIT {
@Autowired
private MongoOperations mongoOperations;
@Autowired
private MongoShsAgreementRepository mongoShsAgreementRepository;
@Test
public void defaultProductIdAndFromShouldMatchAgreement1And2() {
List<MongoShsAgreement> agreements = mongoShsAgreementRepository.findByProductTypeIdAndFrom(TestObjectMother.DEFAULT_TEST_PRODUCT_ID, TestObjectMother.DEFAULT_TEST_FROM);
assertEquals(agreements.size(), 2);
}
@Test
public void agreementsShouldNotBeFoundWithNonExistingProductId() {
List<MongoShsAgreement> agreements = mongoShsAgreementRepository.findByProductTypeIdAndFrom("NonExisting", TestObjectMother.DEFAULT_TEST_FROM);
assertEquals(agreements.size(), 0);
}
@Test
public void findAgreement1WithFromAndTo() {
List<MongoShsAgreement> agreements = mongoShsAgreementRepository
.findByProductTypeIdAndFromAndTo(TestObjectMother.DEFAULT_TEST_PRODUCT_ID,TestObjectMother.DEFAULT_TEST_FROM, TestObjectMother.DEFAULT_TEST_TO);
assertEquals(agreements.size(), 1);
assertEquals(agreements.get(0).getUuid(), TestObjectMother.AGREEMENT_1);
}
@Test
public void openAgreementShouldMatchAnyCustomer() {
List<MongoShsAgreement> agreements = mongoShsAgreementRepository
.findByProductTypeIdAndFromAndTo(TestObjectMother.PRODUCT_ID_2, TestObjectMother.DEFAULT_TEST_FROM, "NonExisitingCustomer");
assertEquals(agreements.size(), 1);
assertEquals(agreements.get(0).getUuid(), TestObjectMother.AGREEMENT_3);
}
@BeforeClass
public void beforeClass() {
mongoOperations.dropCollection(MongoShsAgreement.class);
initDb();
}
private void initDb() {
MongoShsAgreement agreement = TestObjectMother.createShsAgreement();
mongoShsAgreementRepository.save(agreement);
agreement = TestObjectMother.createShsAgreement();
agreement.setUuid(TestObjectMother.AGREEMENT_2);
agreement.getShs().getCustomer().setValue(TestObjectMother.PRINCIPAL_3);
mongoShsAgreementRepository.save(agreement);
// Open agreement that allows any customer
agreement = TestObjectMother.createShsAgreement();
agreement.setUuid(TestObjectMother.AGREEMENT_3);
agreement.getShs().getProduct().clear();
Product product = new Product();
product.setValue(TestObjectMother.PRODUCT_ID_2);
agreement.getShs().getProduct().add(product);
agreement.getShs().setCustomer(null);
mongoShsAgreementRepository.save(agreement);
}
@AfterClass
public void afterClass() {
mongoOperations.dropCollection(MongoShsAgreement.class);
}
}
|
sklaxel/inera-axel
|
shs/shs-broker/shs-agreement-mongodb/src/test/java/se/inera/axel/shs/broker/agreement/mongo/MongoShsAgreementRepositoryIT.java
|
Java
|
lgpl-3.0
| 4,011 |
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.wsclient.issue;
import javax.annotation.Nullable;
import java.util.List;
/**
* This client is a wrapper over the web services related to issues
*
* @since 3.6
*/
public interface IssueClient {
/**
* Wrap the web service /api/issues/search in order to search for issues.
*/
Issues find(IssueQuery query);
/**
* Assign an existing issue to a user. A null assignee removes the assignee.
*
* @return the updated issue
*/
Issue assign(String issueKey, @Nullable String assignee);
/**
* Assign an existing issue to current user.
*
* @return the updated issue
*/
Issue assignToMe(String issueKey);
/**
* Change the severity of an existing issue. Supported values are "INFO", "MINOR",
* "MAJOR", "CRITICAL" and "BLOCKER".
*
* @return the updated issue
*/
Issue setSeverity(String issueKey, String severity);
/**
* Link an existing issue to an action plan. A null action plan unlinks the issue.
*/
Issue plan(String issueKey, @Nullable String actionPlan);
IssueComment addComment(String issueKey, String markdownText);
Issue create(NewIssue issue);
List<String> transitions(String issueKey);
Issue doTransition(String issueKey, String transition);
List<String> actions(String issueKey);
Issue doAction(String issueKey, String action);
/**
* Execute bulk change on a list of issues
*/
BulkChange bulkChange(BulkChangeQuery query);
/**
* @since 4.1
*
* @return the list of changes of an issue
*/
List<IssueChange> changes(String issueKey);
}
|
teryk/sonarqube
|
server/sonar-ws-client/src/main/java/org/sonar/wsclient/issue/IssueClient.java
|
Java
|
lgpl-3.0
| 2,464 |
<!DOCTYPE html>
<html>
<head>
<title>js-suface demo</title>
</head>
<body>
<div id="main-content">
</div>
<script src="../../node_modules/react/umd/react.production.min.js"></script>
<script src="../../node_modules/react-dom/umd/react-dom.production.min.js"></script>
<script src="../../node_modules/dyo/dist/dyo.umd.js"></script>
<script src="../../node_modules/js-spec/dist/js-spec.umd.production.js"></script>
<script src="../../build/demo.js"></script>
</body>
</html>
|
mcjazzyfunky/js-surface
|
boxroom/archive/backup-js-surface-2019-03-05_all-in-one-library/src/demo/index.html
|
HTML
|
lgpl-3.0
| 513 |
/*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program 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.
*
* 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
* Lesser 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@javax.annotation.ParametersAreNonnullByDefault
package org.sonar.api.batch.sensor.internal;
|
Builders-SonarSource/sonarqube-bis
|
sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/internal/package-info.java
|
Java
|
lgpl-3.0
| 939 |
package sample7_swingwaypoints;
import org.jxmapviewer.JXMapViewer;
import org.jxmapviewer.viewer.WaypointPainter;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Point2D;
/**
* "Paints" the Swing waypoints. In fact, just takes care of correct positioning of the representing button.
*
* @author Daniel Stahr
*/
public class SwingWaypointOverlayPainter extends WaypointPainter<SwingWaypoint> {
@Override
protected void doPaint(Graphics2D g, JXMapViewer jxMapViewer, int width, int height) {
for (SwingWaypoint swingWaypoint : getWaypoints()) {
Point2D point = jxMapViewer.getTileFactory().geoToPixel(
swingWaypoint.getPosition(), jxMapViewer.getZoom());
Rectangle rectangle = jxMapViewer.getViewportBounds();
int buttonX = (int)(point.getX() - rectangle.getX());
int buttonY = (int)(point.getY() - rectangle.getY());
JButton button = swingWaypoint.getButton();
button.setLocation(buttonX - button.getWidth() / 2, buttonY - button.getHeight() / 2);
}
}
}
|
richardeigenmann/jxmapviewer2
|
examples/src/sample7_swingwaypoints/SwingWaypointOverlayPainter.java
|
Java
|
lgpl-3.0
| 1,096 |
package org.fluttercode.datafactory.impl;
/*
* Copyright 2011, Andrew M Gibson
*
* www.andygibson.net
*
* This file is part of DataFactory
*
* DataValve 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.
*
* DataFactory 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 DataFactory. If not, see <http://www.gnu.org/licenses/>.
*
*/
import org.fluttercode.datafactory.NameDataValues;
public class DefaultNameDataValues implements NameDataValues {
private static String[] suffixes = { "II", "III", "Phd", "Jr", "Sr" };
private static String[] prefixes = { "Mr", "Mrs", "Ms" };
private static String[] firstNames = { "Aaron", "Abby", "Abigail", "Adam",
"Alan", "Albert", "Alex", "Alexandra", "Alexis", "Alice", "Alicia",
"Alisha", "Alissa", "Allen", "Allison", "Alyssa", "Amanda",
"Amber", "Amy", "Andrea", "Andrew", "Andy", "Angel", "Angela",
"Angie", "Anita", "Ann", "Anna", "Annette", "Anthony", "Antonio",
"April", "Arthur", "Ashley", "Audrey", "Austin", "Autumn", "Baby",
"Barb", "Barbara", "Becky", "Benjamin", "Beth", "Bethany", "Betty",
"Beverly", "Bill", "Billie", "Billy", "Blake", "Bob", "Bobbie",
"Bobby", "Bonnie", "Brad", "Bradley", "Brady", "Brandi", "Brandon",
"Brandy", "Breanna", "Brenda", "Brent", "Brett", "Brian",
"Brianna", "Brittany", "Brooke", "Brooklyn", "Bruce", "Bryan",
"Caleb", "Cameron", "Candy", "Carl", "Carla", "Carmen", "Carol",
"Carolyn", "Carrie", "Casey", "Cassandra", "Catherine", "Cathy",
"Chad", "Charlene", "Charles", "Charlie", "Charlotte", "Chase",
"Chasity", "Chastity", "Chelsea", "Cheryl", "Chester", "Cheyenne",
"Chris", "Christian", "Christina", "Christine", "Christoph",
"Christopher", "Christy", "Chuck", "Cindy", "Clara", "Clarence",
"Clayton", "Clifford", "Clint", "Cody", "Colton", "Connie",
"Corey", "Cory", "Courtney", "Craig", "Crystal", "Curtis",
"Cynthia", "Dakota", "Dale", "Dallas", "Dalton", "Dan", "Dana",
"Daniel", "Danielle", "Danny", "Darla", "Darlene", "Darrell",
"Darren", "Dave", "David", "Dawn", "Dean", "Deanna", "Debbie",
"Deborah", "Debra", "Denise", "Dennis", "Derek", "Derrick",
"Destiny", "Devin", "Diana", "Diane", "Dillon", "Dixie", "Dominic",
"Don", "Donald", "Donna", "Donnie", "Doris", "Dorothy", "Doug",
"Douglas", "Drew", "Duane", "Dustin", "Dusty", "Dylan", "Earl",
"Ed", "Eddie", "Edward", "Elaine", "Elizabeth", "Ellen", "Emily",
"Eric", "Erica", "Erika", "Erin", "Ernest", "Ethan", "Eugene",
"Eva", "Evelyn", "Everett", "Faith", "Father", "Felicia", "Floyd",
"Francis", "Frank", "Fred", "Gabriel", "Gage", "Gail", "Gary",
"Gene", "George", "Gerald", "Gina", "Ginger", "Glen", "Glenn",
"Gloria", "Grace", "Greg", "Gregory", "Haley", "Hannah", "Harley",
"Harold", "Harry", "Heath", "Heather", "Heidi", "Helen", "Herbert",
"Holly", "Hope", "Howard", "Hunter", "Ian", "Isaac", "Jack",
"Jackie", "Jacob", "Jade", "Jake", "James", "Jamie", "Jan", "Jane",
"Janet", "Janice", "Jared", "Jasmine", "Jason", "Jay", "Jean",
"Jeannie", "Jeff", "Jeffery", "Jeffrey", "Jenna", "Jennifer",
"Jenny", "Jeremiah", "Jeremy", "Jerry", "Jesse", "Jessica",
"Jessie", "Jill", "Jim", "Jimmy", "Joann", "Joanne", "Jodi",
"Jody", "Joe", "Joel", "Joey", "John", "Johnathan", "Johnny",
"Jon", "Jonathan", "Jonathon", "Jordan", "Joseph", "Josh",
"Joshua", "Joyce", "Juanita", "Judy", "Julia", "Julie", "Justin",
"Kaitlyn", "Karen", "Katelyn", "Katherine", "Kathleen", "Kathryn",
"Kathy", "Katie", "Katrina", "Kay", "Kayla", "Kaylee", "Keith",
"Kelly", "Kelsey", "Ken", "Kendra", "Kenneth", "Kenny", "Kevin",
"Kim", "Kimberly", "Kris", "Krista", "Kristen", "Kristin",
"Kristina", "Kristy", "Kyle", "Kylie", "Lacey", "Laken", "Lance",
"Larry", "Laura", "Lawrence", "Leah", "Lee", "Leonard", "Leroy",
"Leslie", "Levi", "Lewis", "Linda", "Lindsay", "Lindsey", "Lisa",
"Lloyd", "Logan", "Lois", "Loretta", "Lori", "Louis", "Lynn",
"Madison", "Mandy", "Marcus", "Margaret", "Maria", "Mariah",
"Marie", "Marilyn", "Marion", "Mark", "Marlene", "Marsha",
"Martha", "Martin", "Marty", "Marvin", "Mary", "Mary ann", "Mason",
"Matt", "Matthew", "Max", "Megan", "Melanie", "Melinda", "Melissa",
"Melody", "Michael", "Michelle", "Mickey", "Mike", "Mindy",
"Miranda", "Misty", "Mitchell", "Molly", "Monica", "Morgan",
"Mother", "Myron", "Nancy", "Natasha", "Nathan", "Nicholas",
"Nick", "Nicole", "Nina", "Noah", "Norma", "Norman", "Olivia",
"Paige", "Pam", "Pamela", "Pat", "Patricia", "Patrick", "Patty",
"Paul", "Paula", "Peggy", "Penny", "Pete", "Phillip", "Phyllis",
"Rachael", "Rachel", "Ralph", "Randall", "Randi", "Randy", "Ray",
"Raymond", "Rebecca", "Regina", "Renee", "Rex", "Rhonda",
"Richard", "Rick", "Ricky", "Rita", "Rob", "Robbie", "Robert",
"Roberta", "Robin", "Rochelle", "Rocky", "Rod", "Rodney", "Roger",
"Ron", "Ronald", "Ronda", "Ronnie", "Rose", "Roxanne", "Roy",
"Russ", "Russell", "Rusty", "Ruth", "Ryan", "Sabrina", "Sally",
"Sam", "Samantha", "Samuel", "Sandra", "Sandy", "Sara", "Sarah",
"Savannah", "Scott", "Sean", "Seth", "Shanda", "Shane", "Shanna",
"Shannon", "Sharon", "Shaun", "Shawn", "Shawna", "Sheila",
"Shelly", "Sher", "Sherri", "Sherry", "Shirley", "Sierra",
"Skyler", "Stacey", "Stacy", "Stanley", "Stephanie", "Stephen",
"Steve", "Steven", "Sue", "Summer", "Susan", "Sydney", "Tabatha",
"Tabitha", "Tamara", "Tammy", "Tara", "Tasha", "Tashia", "Taylor",
"Ted", "Teresa", "Terri", "Terry", "Tessa", "Thelma", "Theresa",
"Thomas", "Tia", "Tiffany", "Tim", "Timmy", "Timothy", "Tina",
"Todd", "Tom", "Tommy", "Toni", "Tony", "Tonya", "Tracey",
"Tracie", "Tracy", "Travis", "Trent", "Trevor", "Trey", "Trisha",
"Tristan", "Troy", "Tyler", "Tyrone", "Unborn", "Valerie",
"Vanessa", "Vernon", "Veronica", "Vicki", "Vickie", "Vicky",
"Victor", "Victoria", "Vincent", "Virginia", "Vivian", "Walter",
"Wanda", "Wayne", "Wendy", "Wesley", "Whitney", "William",
"Willie", "Wyatt", "Zachary" };
private static String[] lastNames = { "Abbott", "Acevedo", "Acosta",
"Adams", "Adkins", "Aguilar", "Aguirre", "Albert", "Alexander",
"Alford", "Allen", "Allison", "Alston", "Alvarado", "Alvarez",
"Anderson", "Andrews", "Anthony", "Armstrong", "Arnold", "Ashley",
"Atkins", "Atkinson", "Austin", "Avery", "Avila", "Ayala", "Ayers",
"Bailey", "Baird", "Baker", "Baldwin", "Ball", "Ballard", "Banks",
"Barber", "Smith", "Johnson", "Williams", "Jones", "Brown",
"Davis", "Miller", "Wilson", "Moore", "Taylor", "Thomas",
"Jackson", "Barker", "Barlow", "Barnes", "Barnett", "Barr",
"Barrera", "Barrett", "Barron", "Barry", "Bartlett", "Barton",
"Bass", "Bates", "Battle", "Bauer", "Baxter", "Beach", "Bean",
"Beard", "Beasley", "Beck", "Becker", "Bell", "Bender", "Benjamin",
"Bennett", "Benson", "Bentley", "Benton", "Berg", "Berger",
"Bernard", "Berry", "Best", "Bird", "Bishop", "Black", "Blackburn",
"Blackwell", "Blair", "Blake", "Blanchard", "Blankenship",
"Blevins", "Bolton", "Bond", "Bonner", "Booker", "Boone", "Booth",
"Bowen", "Bowers", "Bowman", "Boyd", "Boyer", "Boyle", "Bradford",
"Bradley", "Bradshaw", "Brady", "Branch", "Bray", "Brennan",
"Brewer", "Bridges", "Briggs", "Bright", "Britt", "Brock",
"Brooks", "Browning", "Bruce", "Bryan", "Bryant", "Buchanan",
"Buck", "Buckley", "Buckner", "Bullock", "Burch", "Burgess",
"Burke", "Burks", "Burnett", "Burns", "Burris", "Burt", "Burton",
"Bush", "Butler", "Byers", "Byrd", "Cabrera", "Cain", "Calderon",
"Caldwell", "Calhoun", "Callahan", "Camacho", "Cameron",
"Campbell", "Campos", "Cannon", "Cantrell", "Cantu", "Cardenas",
"Carey", "Carlson", "Carney", "Carpenter", "Carr", "Carrillo",
"Carroll", "Carson", "Carter", "Carver", "Case", "Casey", "Cash",
"Castaneda", "Castillo", "Castro", "Cervantes", "Chambers", "Chan",
"Chandler", "Chaney", "Chang", "Chapman", "Charles", "Chase",
"Chavez", "Chen", "Cherry", "Christensen", "Christian", "Church",
"Clark", "Clarke", "Clay", "Clayton", "Clements", "Clemons",
"Cleveland", "Cline", "Cobb", "Cochran", "Coffey", "Cohen", "Cole",
"Coleman", "Collier", "Collins", "Colon", "Combs", "Compton",
"Conley", "Conner", "Conrad", "Contreras", "Conway", "Cook",
"Cooke", "Cooley", "Cooper", "Copeland", "Cortez", "Cote",
"Cotton", "Cox", "Craft", "Craig", "Crane", "Crawford", "Crosby",
"Cross", "Cruz", "Cummings", "Cunningham", "Curry", "Curtis",
"Dale", "Dalton", "Daniel", "Daniels", "Daugherty", "Davenport",
"David", "Davidson", "Dawson", "Day", "Dean", "Decker", "Dejesus",
"Delacruz", "Delaney", "Deleon", "Delgado", "Dennis", "Diaz",
"Dickerson", "Dickinson", "Dillard", "Dillon", "Dixon", "Dodson",
"Dominguez", "Donaldson", "Donovan", "Dorsey", "Dotson", "Douglas",
"Downs", "Doyle", "Drake", "Dudley", "Duffy", "Duke", "Duncan",
"Dunlap", "Dunn", "Duran", "Durham", "Dyer", "Eaton", "Edwards",
"Elliott", "Ellis", "Ellison", "Emerson", "England", "English",
"Erickson", "Espinoza", "Estes", "Estrada", "Evans", "Everett",
"Ewing", "Farley", "Farmer", "Farrell", "Faulkner", "Ferguson",
"Fernandez", "Ferrell", "Fields", "Figueroa", "Finch", "Finley",
"Fischer", "Fisher", "Fitzgerald", "Fitzpatrick", "Fleming",
"Fletcher", "Flores", "Flowers", "Floyd", "Flynn", "Foley",
"Forbes", "Ford", "Foreman", "Foster", "Fowler", "Fox", "Francis",
"Franco", "Frank", "Franklin", "Franks", "Frazier", "Frederick",
"Freeman", "French", "Frost", "Fry", "Frye", "Fuentes", "Fuller",
"Fulton", "Gaines", "Gallagher", "Gallegos", "Galloway", "Gamble",
"Garcia", "Gardner", "Garner", "Garrett", "Garrison", "Garza",
"Gates", "Gay", "Gentry", "George", "Gibbs", "Gibson", "Gilbert",
"Giles", "Gill", "Gillespie", "Gilliam", "Gilmore", "Glass",
"Glenn", "Glover", "Goff", "Golden", "Gomez", "Gonzales",
"Gonzalez", "Good", "Goodman", "Goodwin", "Gordon", "Gould",
"Graham", "Grant", "Graves", "Gray", "Green", "Greene", "Greer",
"Gregory", "Griffin", "Griffith", "Grimes", "Gross", "Guerra",
"Guerrero", "Guthrie", "Gutierrez", "Guy", "Guzman", "Hahn",
"Hale", "Haley", "Hall", "Hamilton", "Hammond", "Hampton",
"Hancock", "Haney", "Hansen", "Hanson", "Hardin", "Harding",
"Hardy", "Harmon", "Harper", "Harris", "Harrington", "Harrison",
"Hart", "Hartman", "Harvey", "Hatfield", "Hawkins", "Hayden",
"Hayes", "Haynes", "Hays", "Head", "Heath", "Hebert", "Henderson",
"Hendricks", "Hendrix", "Henry", "Hensley", "Henson", "Herman",
"Hernandez", "Herrera", "Herring", "Hess", "Hester", "Hewitt",
"Hickman", "Hicks", "Higgins", "Hill", "Hines", "Hinton", "Hobbs",
"Hodge", "Hodges", "Hoffman", "Hogan", "Holcomb", "Holden",
"Holder", "Holland", "Holloway", "Holman", "Holmes", "Holt",
"Hood", "Hooper", "Hoover", "Hopkins", "Hopper", "Horn", "Horne",
"Horton", "House", "Houston", "Howard", "Howe", "Howell",
"Hubbard", "Huber", "Hudson", "Huff", "Huffman", "Hughes", "Hull",
"Humphrey", "Hunt", "Hunter", "Hurley", "Hurst", "Hutchinson",
"Hyde", "Ingram", "Irwin", "Jacobs", "Jacobson", "James", "Jarvis",
"Jefferson", "Jenkins", "Jennings", "Jensen", "Jimenez", "Johns",
"Johnston", "Jordan", "Joseph", "Joyce", "Joyner", "Juarez",
"Justice", "Kane", "Kaufman", "Keith", "Keller", "Kelley", "Kelly",
"Kemp", "Kennedy", "Kent", "Kerr", "Key", "Kidd", "Kim", "King",
"Kinney", "Kirby", "Kirk", "Kirkland", "Klein", "Kline", "Knapp",
"Knight", "Knowles", "Knox", "Koch", "Kramer", "Lamb", "Lambert",
"Lancaster", "Landry", "Lane", "Lang", "Langley", "Lara", "Larsen",
"Larson", "Lawrence", "Lawson", "Le", "Leach", "Leblanc", "Lee",
"Leon", "Leonard", "Lester", "Levine", "Levy", "Lewis", "Lindsay",
"Lindsey", "Little", "Livingston", "Lloyd", "Logan", "Long",
"Lopez", "Lott", "Love", "Lowe", "Lowery", "Lucas", "Luna",
"Lynch", "Lynn", "Lyons", "Macdonald", "Macias", "Mack", "Madden",
"Maddox", "Maldonado", "Malone", "Mann", "Manning", "Marks",
"Marquez", "Marsh", "Marshall", "Martin", "Martinez", "Mason",
"Massey", "Mathews", "Mathis", "Matthews", "Maxwell", "May",
"Mayer", "Maynard", "Mayo", "Mays", "McBride", "McCall",
"McCarthy", "McCarty", "McClain", "McClure", "McConnell",
"McCormick", "McCoy", "McCray", "McCullough", "McDaniel",
"McDonald", "McDowell", "McFadden", "McFarland", "McGee",
"McGowan", "McGuire", "McIntosh", "McIntyre", "McKay", "McKee",
"McKenzie", "McKinney", "McKnight", "McLaughlin", "McLean",
"McLeod", "McMahon", "McMillan", "McNeil", "McPherson", "Meadows",
"Medina", "Mejia", "Melendez", "Melton", "Mendez", "Mendoza",
"Mercado", "Mercer", "Merrill", "Merritt", "Meyer", "Meyers",
"Michael", "Middleton", "Miles", "Mills", "Miranda", "Mitchell",
"Molina", "Monroe", "Montgomery", "Montoya", "Moody", "Moon",
"Mooney", "Morales", "Moran", "Moreno", "Morgan", "Morin",
"Morris", "Morrison", "Morrow", "Morse", "Morton", "Moses",
"Mosley", "Moss", "Mueller", "Mullen", "Mullins", "Munoz",
"Murphy", "Murray", "Myers", "Nash", "Navarro", "Neal", "Nelson",
"Newman", "Newton", "Nguyen", "Nichols", "Nicholson", "Nielsen",
"Nieves", "Nixon", "Noble", "Noel", "Nolan", "Norman", "Norris",
"Norton", "Nunez", "Obrien", "Ochoa", "Oconnor", "Odom",
"Odonnell", "Oliver", "Olsen", "Olson", "O'neal", "O'neil",
"O'neill", "Orr", "Ortega", "Ortiz", "Osborn", "Osborne", "Owen",
"Owens", "Pace", "Pacheco", "Padilla", "Page", "Palmer", "Park",
"Parker", "Parks", "Parrish", "Parsons", "Pate", "Patel",
"Patrick", "Patterson", "Patton", "Paul", "Payne", "Pearson",
"Peck", "Pena", "Pennington", "Perez", "Perkins", "Perry",
"Peters", "Petersen", "Peterson", "Petty", "Phelps", "Phillips",
"Pickett", "Pierce", "Pittman", "Pitts", "Pollard", "Poole",
"Pope", "Porter", "Potter", "Potts", "Powell", "Powers", "Pratt",
"Preston", "Price", "Prince", "Pruitt", "Puckett", "Pugh", "Quinn",
"Ramirez", "Ramos", "Ramsey", "Randall", "Randolph", "Rasmussen",
"Ratliff", "Ray", "Raymond", "Reed", "Reese", "Reeves", "Reid",
"Reilly", "Reyes", "Reynolds", "Rhodes", "Rice", "Rich", "Richard",
"Richards", "Richardson", "Richmond", "Riddle", "Riggs", "Riley",
"Rios", "Rivas", "Rivera", "Rivers", "Roach", "Robbins",
"Roberson", "Roberts", "Robertson", "Robinson", "Robles", "Rocha",
"Rodgers", "Rodriguez", "Rodriquez", "Rogers", "Rojas", "Rollins",
"Roman", "Romero", "Rosa", "Rosales", "Rosario", "Rose", "Ross",
"Roth", "Rowe", "Rowland", "Roy", "Ruiz", "Rush", "Russell",
"Russo", "Rutledge", "Ryan", "Salas", "Salazar", "Salinas",
"Sampson", "Sanchez", "Sanders", "Sandoval", "Sanford", "Santana",
"Santiago", "Santos", "Sargent", "Saunders", "Savage", "Sawyer",
"Schmidt", "Schneider", "Schroeder", "Schultz", "Schwartz",
"Scott", "Sears", "Sellers", "Serrano", "Sexton", "Shaffer",
"Shannon", "Sharp", "Sharpe", "Shaw", "Shelton", "Shepard",
"Shepherd", "Sheppard", "Sherman", "Shields", "Short", "Silva",
"Simmons", "Simon", "Simpson", "Sims", "Singleton", "Skinner",
"Slater", "Sloan", "Small", "Snider", "Snow", "Snyder", "Solis",
"Solomon", "Sosa", "Soto", "Sparks", "Spears", "Spence", "Spencer",
"Stafford", "Stanley", "Stanton", "Stark", "Steele", "Stein",
"Stephens", "Stephenson", "Stevens", "Stevenson", "Stewart",
"Stokes", "Stone", "Stout", "Strickland", "Strong", "Stuart",
"Suarez", "Sullivan", "Summers", "Sutton", "Swanson", "Sweeney",
"Sweet", "Sykes", "Talley", "Tanner", "Tate", "Terrell", "Terry",
"Thompson", "Thornton", "Tillman", "Todd", "Torres", "Townsend",
"Tran", "Travis", "Trevino", "Trujillo", "Tucker", "Turner",
"Tyler", "Tyson", "Underwood", "Valdez", "Valencia", "Valentine",
"Valenzuela", "Vance", "Vang", "Vargas", "Vasquez", "Vaughan",
"Vaughn", "Vazquez", "Vega", "Velasquez", "Velazquez", "Velez",
"Van halen", "Vincent", "Vinson", "Wade", "Wagner", "Walker",
"Wall", "Wallace", "Waller", "Walls", "Walsh", "Walter", "Walters",
"Walton", "Ward", "Ware", "Warner", "Warren", "Washington",
"Waters", "Watkins", "Watson", "Watts", "Weaver", "Webb", "Weber",
"Webster", "Weeks", "Weiss", "Welch", "Wells", "West", "Wheeler",
"Whitaker", "White", "Whitehead", "Whitfield", "Whitley",
"Whitney", "Wiggins", "Wilcox", "Wilder", "Wiley", "Wilkerson",
"Wilkins", "Wilkinson", "William", "Williamson", "Willis",
"Winters", "Wise", "Witt", "Wolf", "Wolfe", "Wong", "Wood",
"Woodard", "Woods", "Woodward", "Wooten", "Workman", "Wright",
"Wyatt", "Wynn", "Yang", "Yates", "York", "Young", "Zamora",
"Zimmerman"
};
public String[] getFirstNames() {
return firstNames;
}
public String[] getLastNames() {
return lastNames;
}
public String[] getPrefixes() {
return prefixes;
}
public String[] getSuffixes() {
return suffixes;
}
}
|
tlereste/datafactory
|
src/main/java/org/fluttercode/datafactory/impl/DefaultNameDataValues.java
|
Java
|
lgpl-3.0
| 17,374 |
#include <CGAL/Combinatorial_map.h>
#include <CGAL/Combinatorial_map_constructors.h>
#include <CGAL/Combinatorial_map_operations.h>
#include <iostream>
#include <cstdlib>
typedef CGAL::Combinatorial_map<3> CMap_3;
typedef CMap_3::Dart_handle Dart_handle;
int main()
{
CMap_3 cm;
// Create one combinatorial hexahedron.
Dart_handle dh1 = CGAL::make_combinatorial_hexahedron(cm);
// Add two edges along two opposite facets.
CGAL_assertion( CGAL::is_insertable_cell_1_in_cell_2
(cm,dh1->beta(1),dh1->beta(0)) );
CGAL::insert_cell_1_in_cell_2(cm,dh1->beta(1),dh1->beta(0));
CGAL_assertion( cm.is_valid() );
Dart_handle dh2=dh1->beta(2)->beta(1)->beta(1)->beta(2);
CGAL_assertion( CGAL::is_insertable_cell_1_in_cell_2
(cm,dh2,dh2->beta(1)->beta(1)) );
CGAL::insert_cell_1_in_cell_2(cm,dh2,dh2->beta(1)->beta(1));
CGAL_assertion( cm.is_valid() );
// Insert a facet along these two new edges plus two initial edges
// of the hexahedron.
std::vector<Dart_handle> path;
path.push_back(dh1->beta(1));
path.push_back(dh1->beta(0)->beta(2)->beta(1));
path.push_back(dh2->beta(0));
path.push_back(dh2->beta(2)->beta(1));
CGAL_assertion( (CGAL::is_insertable_cell_2_in_cell_3
(cm,path.begin(),path.end())) );
Dart_handle dh3=CGAL::insert_cell_2_in_cell_3(cm,path.begin(),path.end());
CGAL_assertion( cm.is_valid() );
// Display the combinatorial map characteristics.
cm.display_characteristics(std::cout) << ", valid=" <<
cm.is_valid() << std::endl;
// We use the removal operations to get back to the initial hexahedron.
CGAL_assertion( (CGAL::is_removable<CMap_3, 2>(cm,dh3)) );
CGAL::remove_cell<CMap_3,2>(cm,dh3);
CGAL_assertion( cm.is_valid() );
CGAL_assertion( (CGAL::is_removable<CMap_3, 1>(cm,dh1->beta(1))) );
CGAL::remove_cell<CMap_3,1>(cm,dh1->beta(1));
CGAL_assertion( cm.is_valid() );
CGAL_assertion( (CGAL::is_removable<CMap_3, 1>(cm,dh2->beta(0))) );
CGAL::remove_cell<CMap_3,1>(cm,dh2->beta(0));
CGAL_assertion( cm.is_valid() );
// Display the combinatorial map characteristics.
cm.display_characteristics(std::cout) << ", valid="
<< cm.is_valid() << std::endl;
return EXIT_SUCCESS;
}
|
chrisvana/cgal_copy
|
examples/Combinatorial_map/map_3_operations.cpp
|
C++
|
lgpl-3.0
| 2,258 |
# Generated by Django 2.1 on 2018-11-23 15:56
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('abonapp', '0008_auto_20181115_1206'),
]
operations = [
migrations.DeleteModel(
name='AllPayLog',
),
]
|
nerosketch/djing
|
abonapp/migrations/0009_auto_20181123_1556.py
|
Python
|
unlicense
| 296 |
app.controller('dashboardController', function($scope, $http, $location) {
});
|
muthugit/tc
|
my/js/app/dashboardController.js
|
JavaScript
|
unlicense
| 81 |
<!doctype html>
<html lang="en" class=" js flexbox canvas canvastext webgl no-touch geolocation postmessage websqldatabase indexeddb hashchange history draganddrop websockets rgba hsla multiplebgs backgroundsize borderimage borderradius boxshadow textshadow opacity cssanimations csscolumns cssgradients cssreflections csstransforms csstransforms3d csstransitions fontface generatedcontent video audio localstorage sessionstorage webworkers applicationcache svg inlinesvg smil svgclippaths">
<head>
<meta charset="utf-8">
<title>Orbit</title>
<link href="../Foundation-5.3.3 MASTER/css/foundation.css" rel="stylesheet" type="text/css">
<link href="../slick-master/slick/slick.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="row">
<div class="large-3 columns">
<h1><img src="http://placehold.it/400x100&text=Logo"/></h1>
</div>
<div class="large-9 columns">
<ul class="right button-group">
<li><a href="#" class="button">Link 1</a></li>
<li><a href="#" class="button">Link 2</a></li>
<li><a href="#" class="button">Link 3</a></li>
<li><a href="#" class="button">Link 4</a></li>
</ul>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<div id="slider">
<img src="http://placehold.it/1000x400&text=[ img 1 ]"/>
</div>
<hr/>
</div>
</div>
<div class="slider single-item text-center">
<div><h3>1</h3></div>
<div><h3>2</h3></div>
<div><h3>3</h3></div>
<div><h3>4</h3></div>
<div><h3>5</h3></div>
<div><h3>6</h3></div>
</div>
<div class="row">
<div class="large-4 columns">
<img src="http://placehold.it/400x300&text=[img]"/>
<h4>This is a content section.</h4>
<p>Bacon ipsum dolor sit amet nulla ham qui sint exercitation eiusmod commodo, chuck duis velit. Aute in reprehenderit, dolore aliqua non est magna in labore pig pork biltong. Eiusmod swine spare ribs reprehenderit culpa. Boudin aliqua adipisicing rump corned beef.</p>
</div>
<div class="large-4 columns">
<img src="http://placehold.it/400x300&text=[img]"/>
<h4>This is a content section.</h4>
<p>Bacon ipsum dolor sit amet nulla ham qui sint exercitation eiusmod commodo, chuck duis velit. Aute in reprehenderit, dolore aliqua non est magna in labore pig pork biltong. Eiusmod swine spare ribs reprehenderit culpa. Boudin aliqua adipisicing rump corned beef.</p>
</div>
<div class="large-4 columns">
<img src="http://placehold.it/400x300&text=[img]"/>
<h4>This is a content section.</h4>
<p>Bacon ipsum dolor sit amet nulla ham qui sint exercitation eiusmod commodo, chuck duis velit. Aute in reprehenderit, dolore aliqua non est magna in labore pig pork biltong. Eiusmod swine spare ribs reprehenderit culpa. Boudin aliqua adipisicing rump corned beef.</p>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<div class="panel">
<h4>Get in touch!</h4>
<div class="row">
<div class="large-9 columns">
<p>We'd love to hear from you, you attractive person you.</p>
</div>
<div class="large-3 columns">
<a href="#" class="radius button right">Contact Us</a>
</div>
</div>
</div>
</div>
</div>
<footer class="row">
<div class="large-12 columns">
<hr/>
<div class="row">
<div class="large-6 columns">
<p>© Copyright no one at all. Go to town.</p>
</div>
<div class="large-6 columns">
<ul class="inline-list right">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
<li><a href="#">Link 4</a></li>
</ul>
</div>
</div>
</div>
</footer>
<script type="text/javascript" src="../slick-master/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="../slick-master/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript" src="../slick-master/slick/slick.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.slider single-item').slick({
slickgoto: 5
});
});
</script>
</body>
</html>
|
boarderdav/BucketBall_launch
|
grid_templates/Orbit.html
|
HTML
|
unlicense
| 4,333 |
# MdTranslator - minitest of
# reader / mdJson / module_associatedResource
# History:
# Stan Smith 2018-06-15 refactored to use mdJson construction helpers
# Stan Smith 2017-01-16 added parent class to run successfully within rake
# Stan Smith 2016-10-17 refactored for mdJson 2.0
# Stan Smith 2015-06-22 refactored setup to after removal of globals
# Stan Smith 2014-12-30 original script
require_relative 'mdjson_test_parent'
require 'adiwg/mdtranslator/readers/mdJson/modules/module_associatedResource'
class TestReaderMdJsonAssociatedResource < TestReaderMdJsonParent
# set variables for test
@@NameSpace = ADIWG::Mdtranslator::Readers::MdJson::AssociatedResource
# instance classes needed in script
TDClass = MdJsonHashWriter.new
# build mdJson test file in hash
mdHash = TDClass.associatedResource
mdHash[:resourceType] << { type: 'resource type two', name: 'resource name two'}
@@mdHash = mdHash
def test_associatedResource_schema
errors = TestReaderMdJsonParent.testSchema(@@mdHash, 'associatedResource.json')
assert_empty errors
end
def test_complete_associatedResource
TestReaderMdJsonParent.loadEssential
hIn = Marshal::load(Marshal.dump(@@mdHash))
hIn = JSON.parse(hIn.to_json)
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack(hIn, hResponse)
assert_equal 2, metadata[:resourceTypes].length
assert_equal 'association type', metadata[:associationType]
assert_equal 'initiative type', metadata[:initiativeType]
refute_empty metadata[:resourceCitation]
refute_empty metadata[:metadataCitation]
assert hResponse[:readerExecutionPass]
assert_empty hResponse[:readerExecutionMessages]
end
def test_associatedResource_empty_resourceType
TestReaderMdJsonParent.loadEssential
hIn = Marshal::load(Marshal.dump(@@mdHash))
hIn = JSON.parse(hIn.to_json)
hIn['resourceType'] = []
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack(hIn, hResponse)
refute_nil metadata
refute hResponse[:readerExecutionPass]
assert_equal 1, hResponse[:readerExecutionMessages].length
assert_includes hResponse[:readerExecutionMessages],
'ERROR: mdJson reader: associated resource resource type is missing'
end
def test_associatedResource_missing_resourceType
TestReaderMdJsonParent.loadEssential
hIn = Marshal::load(Marshal.dump(@@mdHash))
hIn = JSON.parse(hIn.to_json)
hIn.delete('resourceType')
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack(hIn, hResponse)
refute_nil metadata
refute hResponse[:readerExecutionPass]
assert_equal 1, hResponse[:readerExecutionMessages].length
refute_empty hResponse[:readerExecutionMessages]
assert_includes hResponse[:readerExecutionMessages],
'ERROR: mdJson reader: associated resource resource type is missing'
end
def test_associatedResource_empty_associationType
TestReaderMdJsonParent.loadEssential
hIn = Marshal::load(Marshal.dump(@@mdHash))
hIn = JSON.parse(hIn.to_json)
hIn['associationType'] = ''
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack(hIn, hResponse)
refute_nil metadata
refute hResponse[:readerExecutionPass]
assert_equal 1, hResponse[:readerExecutionMessages].length
assert_includes hResponse[:readerExecutionMessages],
'ERROR: mdJson reader: associated resource association type is missing'
end
def test_associatedResource_missing_associationType
TestReaderMdJsonParent.loadEssential
hIn = Marshal::load(Marshal.dump(@@mdHash))
hIn = JSON.parse(hIn.to_json)
hIn.delete('associationType')
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack(hIn, hResponse)
refute_nil metadata
refute hResponse[:readerExecutionPass]
assert_equal 1, hResponse[:readerExecutionMessages].length
assert_includes hResponse[:readerExecutionMessages],
'ERROR: mdJson reader: associated resource association type is missing'
end
def test_associatedResource_empty_citations
TestReaderMdJsonParent.loadEssential
hIn = Marshal::load(Marshal.dump(@@mdHash))
hIn = JSON.parse(hIn.to_json)
hIn['resourceCitation'] = {}
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack(hIn, hResponse)
refute_nil metadata
refute hResponse[:readerExecutionPass]
assert_equal 1, hResponse[:readerExecutionMessages].length
assert_includes hResponse[:readerExecutionMessages],
'ERROR: mdJson reader: associated resource citation is missing'
end
def test_associatedResource_missing_citations
TestReaderMdJsonParent.loadEssential
hIn = Marshal::load(Marshal.dump(@@mdHash))
hIn = JSON.parse(hIn.to_json)
hIn.delete('resourceCitation')
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack(hIn, hResponse)
refute_nil metadata
refute hResponse[:readerExecutionPass]
assert_equal 1, hResponse[:readerExecutionMessages].length
assert_includes hResponse[:readerExecutionMessages],
'ERROR: mdJson reader: associated resource citation is missing'
end
def test_associatedResource_empty_elements
TestReaderMdJsonParent.loadEssential
hIn = Marshal::load(Marshal.dump(@@mdHash))
hIn = JSON.parse(hIn.to_json)
hIn['initiativeType'] = ''
hIn['metadataCitation'] = {}
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack(hIn, hResponse)
refute_empty metadata[:resourceTypes]
assert_equal 'association type', metadata[:associationType]
assert_nil metadata[:initiativeType]
refute_empty metadata[:resourceCitation]
assert_empty metadata[:metadataCitation]
assert hResponse[:readerExecutionPass]
assert_empty hResponse[:readerExecutionMessages]
end
def test_associatedResource_missing_elements
TestReaderMdJsonParent.loadEssential
hIn = Marshal::load(Marshal.dump(@@mdHash))
hIn = JSON.parse(hIn.to_json)
hIn.delete('initiativeType')
hIn.delete('metadataCitation')
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack(hIn, hResponse)
refute_empty metadata[:resourceTypes]
assert_equal 'association type', metadata[:associationType]
assert_nil metadata[:initiativeType]
refute_empty metadata[:resourceCitation]
assert_empty metadata[:metadataCitation]
assert hResponse[:readerExecutionPass]
assert_empty hResponse[:readerExecutionMessages]
end
def test_empty_associatedResource_object
TestReaderMdJsonParent.loadEssential
hResponse = Marshal::load(Marshal.dump(@@responseObj))
metadata = @@NameSpace.unpack({}, hResponse)
assert_nil metadata
assert hResponse[:readerExecutionPass]
assert_equal 1, hResponse[:readerExecutionMessages].length
assert_includes hResponse[:readerExecutionMessages],
'WARNING: mdJson reader: associated resource object is empty'
end
end
|
adiwg/mdTranslator
|
test/readers/mdJson/tc_mdjson_associatedResource.rb
|
Ruby
|
unlicense
| 7,495 |
<form class="inbox-compose form-horizontal" id="fileupload" action="#" method="POST" enctype="multipart/form-data">
<div class="inbox-compose-btn">
<button class="btn blue"><i class="fa fa-check"></i>Send</button>
<button class="btn">Discard</button>
<button class="btn">Draft</button>
</div>
<div class="inbox-form-group mail-to">
<label class="control-label">To:</label>
<div class="controls controls-to">
<input type="text" class="form-control" name="to" value="[email protected], [email protected], [email protected]">
<span class="inbox-cc-bcc">
<span class="inbox-cc " style="display:none">
Cc
</span>
<span class="inbox-bcc">
Bcc
</span>
</span>
</div>
</div>
<div class="inbox-form-group input-cc">
<a href="javascript:;" class="close">
</a>
<label class="control-label">Cc:</label>
<div class="controls controls-cc">
<input type="text" name="cc" class="form-control" value="[email protected], [email protected]">
</div>
</div>
<div class="inbox-form-group input-bcc display-hide">
<a href="javascript:;" class="close">
</a>
<label class="control-label">Bcc:</label>
<div class="controls controls-bcc">
<input type="text" name="bcc" class="form-control">
</div>
</div>
<div class="inbox-form-group">
<label class="control-label">Subject:</label>
<div class="controls">
<input type="text" class="form-control" name="subject" value="Urgent - Financial Report for May, 2013">
</div>
</div>
<div class="inbox-form-group">
<div class="controls-row">
<textarea class="inbox-editor inbox-wysihtml5 form-control" name="message" rows="12"></textarea>
<!--blockquote content for reply message, the inner html of reply_email_content_body element will be appended into wysiwyg body. Please refer Inbox.js loadReply() function. -->
<div id="reply_email_content_body" class="hide">
<input type="text">
<br>
<br>
<blockquote>
Consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. <br>
<br>
Consectetuer adipiscing elit, sed diam nonummy nibh euismod exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. <br>
<br>
All the best,<br>
Lisa Nilson, CEO, Pixel Inc.
</blockquote>
</div>
</div>
</div>
<div class="inbox-compose-attachment">
<!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
<span class="btn green fileinput-button">
<i class="fa fa-plus"></i>
<span>
Add files...
</span>
<input type="file" name="files[]" multiple>
</span>
<!-- The table listing the files available for upload/download -->
<table role="presentation" class="table table-striped margin-top-10">
<tbody class="files">
</tbody>
</table>
</div>
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-upload fade">
<td class="name" width="30%"><span>{%=file.name%}</span></td>
<td class="size" width="40%"><span>{%=o.formatFileSize(file.size)%}</span></td>
{% if (file.error) { %}
<td class="error" width="20%" colspan="2"><span class="label label-danger">Error</span> {%=file.error%}</td>
{% } else if (o.files.valid && !i) { %}
<td>
<p class="size">{%=o.formatFileSize(file.size)%}</p>
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
<div class="progress-bar progress-bar-success" style="width:0%;"></div>
</div>
</td>
{% } else { %}
<td colspan="2"></td>
{% } %}
<td class="cancel" width="10%" align="right">{% if (!i) { %}
<button class="btn btn-sm red cancel">
<i class="fa fa-ban"></i>
<span>Cancel</span>
</button>
{% } %}</td>
</tr>
{% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-download fade">
{% if (file.error) { %}
<td class="name" width="30%"><span>{%=file.name%}</span></td>
<td class="size" width="40%"><span>{%=o.formatFileSize(file.size)%}</span></td>
<td class="error" width="30%" colspan="2"><span class="label label-danger">Error</span> {%=file.error%}</td>
{% } else { %}
<td class="name" width="30%">
<a href="{%=file.url%}" title="{%=file.name%}" data-gallery="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a>
</td>
<td class="size" width="40%"><span>{%=o.formatFileSize(file.size)%}</span></td>
<td colspan="2"></td>
{% } %}
<td class="delete" width="10%" align="right">
<button class="btn default btn-sm" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}"{% if (file.delete_with_credentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
<i class="fa fa-times"></i>
</button>
</td>
</tr>
{% } %}
</script>
<div class="inbox-compose-btn">
<button class="btn blue"><i class="fa fa-check"></i>Send</button>
<button class="btn">Discard</button>
<button class="btn">Draft</button>
</div>
</form>
|
J2MTecnologia/glacial_gerencial
|
dashboard/metronic_v2.0.2/admin/template_rtl/inbox_reply.html
|
HTML
|
unlicense
| 5,686 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Mapping - Legivel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="description" content=""/>
<meta name="author" content="Frank Joppe"/>
<script src="https://code.jquery.com/jquery-1.8.0.js"></script>
<script src="https://code.jquery.com/ui/1.8.23/jquery-ui.js"></script>
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet"/>
<link type="text/css" rel="stylesheet" href="Legivel/content/style.css" />
<script type="text/javascript" src="Legivel/content/tips.js"></script>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="masthead">
<ul class="nav nav-pills pull-right">
<li><a href="http://fsharp.org">fsharp.org</a></li>
<li><a href="https://github.com/fjoppe/Legivel">github page</a></li>
</ul>
<h3 class="muted"><a href="Legivel/index.html">Legivel</a></h3>
</div>
<hr />
<div class="row">
<div class="span9" id="main">
<h1>Mapping</h1>
<p>
<span>Namespace: Legivel.Customization</span><br />
</p>
<div class="xmldoc">
</div>
<!-- Render nested types and modules, if there are any -->
<h2>Nested types and modules</h2>
<div>
<table class="table table-bordered type-list">
<thead>
<tr><td>Type</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="type-name">
<a href="legivel-customization-mapping-dufieldmapping.html">DUFieldMapping</a>
</td>
<td class="xmldoc">
</td>
</tr>
<tr>
<td class="type-name">
<a href="legivel-customization-mapping-discriminatedunionmappinginfo.html">DiscriminatedUnionMappingInfo</a>
</td>
<td class="xmldoc">
<p>Mapper structure for a Discriminated Union - non-enum</p>
</td>
</tr>
<tr>
<td class="type-name">
<a href="legivel-customization-mapping-enumfieldmapping.html">EnumFieldMapping</a>
</td>
<td class="xmldoc">
</td>
</tr>
<tr>
<td class="type-name">
<a href="legivel-customization-mapping-enummappinginfo.html">EnumMappingInfo</a>
</td>
<td class="xmldoc">
<p>Mapper structure for a Discriminated Union, which compiles to an enum type</p>
</td>
</tr>
<tr>
<td class="type-name">
<a href="legivel-customization-mapping-error.html">Error</a>
</td>
<td class="xmldoc">
<p>Returned when deserialization contained errors</p>
</td>
</tr>
<tr>
<td class="type-name">
<a href="legivel-customization-mapping-listmappinginfo.html">ListMappingInfo</a>
</td>
<td class="xmldoc">
<p>Mapper structure for a List<'a> type</p>
</td>
</tr>
<tr>
<td class="type-name">
<a href="legivel-customization-mapping-mapmappinginfo.html">MapMappingInfo</a>
</td>
<td class="xmldoc">
</td>
</tr>
<tr>
<td class="type-name">
<a href="legivel-customization-mapping-optionalmappinginfo.html">OptionalMappingInfo</a>
</td>
<td class="xmldoc">
<p>Mapper structure for an Option<'a> type</p>
</td>
</tr>
<tr>
<td class="type-name">
<a href="legivel-customization-mapping-primitivemappinginfo.html">PrimitiveMappingInfo</a>
</td>
<td class="xmldoc">
<p>Mapper structure for all primitive types</p>
</td>
</tr>
<tr>
<td class="type-name">
<a href="legivel-customization-mapping-recordfieldmapping.html">RecordFieldMapping</a>
</td>
<td class="xmldoc">
<p>Contains the mapping of one record field</p>
</td>
</tr>
<tr>
<td class="type-name">
<a href="legivel-customization-mapping-recordmappinginfo.html">RecordMappingInfo</a>
</td>
<td class="xmldoc">
<p>Mapper structure for a record type</p>
</td>
</tr>
<tr>
<td class="type-name">
<a href="legivel-customization-mapping-result-1.html">Result<'tp></a>
</td>
<td class="xmldoc">
<p>Result of customized yaml to native mapping</p>
</td>
</tr>
<tr>
<td class="type-name">
<a href="legivel-customization-mapping-scalartonativemapping.html">ScalarToNativeMapping</a>
</td>
<td class="xmldoc">
<p>To register one yaml scalar to native mapping</p>
</td>
</tr>
<tr>
<td class="type-name">
<a href="legivel-customization-mapping-success-1.html">Success<'tp></a>
</td>
<td class="xmldoc">
<p>Returned when deserialization in succesful</p>
</td>
</tr>
</tbody>
</table>
<table class="table table-bordered module-list">
<thead>
<tr><td>Module</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="module-name">
<a href="legivel-customization-mapping-yamlmapped.html">YamlMapped</a>
</td>
<td class="xmldoc">
</td>
</tr>
</tbody>
</table>
</div>
<h3>Functions and values</h3>
<table class="table table-bordered member-list">
<thead>
<tr><td>Function or value</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '69', 69)" onmouseover="showTip(event, '69', 69)">
BuildInTryFindMappers po primitives
</code>
<div class="tip" id="69">
<strong>Signature:</strong> po:ProcessingOptions -> primitives:ScalarToNativeMapping list -> TryFindIdiomaticMapperForType list<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fjoppe/Legivel/tree/master/src/Legivel.Mapper/Customization.fs#L702-702" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
<p>All build-in TryFindMapper functions</p>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '70', 70)" onmouseover="showTip(event, '70', 70)">
CreateTypeMappings(...)
</code>
<div class="tip" id="70">
<strong>Signature:</strong> msgList:ProcessMessages -> tryFindMappers:TryFindIdiomaticMapperForType list -> nullTagUri:GlobalTag -> stringTagUri:GlobalTag -> TryFindMapperReturnType<br />
<strong>Type parameters:</strong> 'tp </div>
</td>
<td class="xmldoc">
<a href="https://github.com/fjoppe/Legivel/tree/master/src/Legivel.Mapper/Customization.fs#L739-739" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
<p>Creates a yaml-to-native-mapper for the given type 'tp</p>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '71', 71)" onmouseover="showTip(event, '71', 71)">
CustomDeserializeYaml(...)
</code>
<div class="tip" id="71">
<strong>Signature:</strong> tryFindMappers:TryFindIdiomaticMapperForType list -> mapYmlDocToNative:(ProcessMessages -> AllTryFindIdiomaticMappers -> IYamlToNativeMapping -> ParsedDocumentResult -> Result<'tp>) -> parseYmlToNative:(IYamlToNativeMapping -> AllTryFindIdiomaticMappers -> (ParsedDocumentResult -> Result<'tp>) -> GlobalTagSchema -> string -> Result<'tp> list) -> schema:GlobalTagSchema -> nullTagUri:GlobalTag -> stringTagUri:GlobalTag -> yml:string -> Result<'tp> list<br />
<strong>Type parameters:</strong> 'tp </div>
</td>
<td class="xmldoc">
<a href="https://github.com/fjoppe/Legivel/tree/master/src/Legivel.Mapper/Customization.fs#L798-798" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
<p>Customized yaml deserialization, where one can inject everything required</p>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '72', 72)" onmouseover="showTip(event, '72', 72)">
MapYamlDocumentToNative(...)
</code>
<div class="tip" id="72">
<strong>Signature:</strong> msgList:ProcessMessages -> mappers:AllTryFindIdiomaticMappers -> mapper:IYamlToNativeMapping -> pdr:ParsedDocumentResult -> Result<'tp><br />
<strong>Type parameters:</strong> 'tp </div>
</td>
<td class="xmldoc">
<a href="https://github.com/fjoppe/Legivel/tree/master/src/Legivel.Mapper/Customization.fs#L768-768" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
<p>Maps a (parsed) yaml document to a native type-instance, using the given mapper</p>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '73', 73)" onmouseover="showTip(event, '73', 73)">
ParseYamlToNative(...)
</code>
<div class="tip" id="73">
<strong>Signature:</strong> mapper:IYamlToNativeMapping -> foundMappers:AllTryFindIdiomaticMappers -> mapToNative:(ParsedDocumentResult -> Result<'tp>) -> schema:GlobalTagSchema -> yml:string -> Result<'tp> list<br />
<strong>Type parameters:</strong> 'tp </div>
</td>
<td class="xmldoc">
<a href="https://github.com/fjoppe/Legivel/tree/master/src/Legivel.Mapper/Customization.fs#L781-781" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
<p>Parses a yaml string, for the given yaml-schema and maps it to a native type instance</p>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '74', 74)" onmouseover="showTip(event, '74', 74)">
TagAssigner mapper foundMappers nl nd nt
</code>
<div class="tip" id="74">
<strong>Signature:</strong> mapper:IYamlToNativeMapping -> foundMappers:AllTryFindIdiomaticMappers -> nl:Node list -> nd:Node -> nt:EventNodeKind -> TagKind option<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fjoppe/Legivel/tree/master/src/Legivel.Mapper/Customization.fs#L714-714" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '75', 75)" onmouseover="showTip(event, '75', 75)">
YamlScalarToNativeMappings
</code>
<div class="tip" id="75">
<strong>Signature:</strong> ScalarToNativeMapping list<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fjoppe/Legivel/tree/master/src/Legivel.Mapper/Customization.fs#L47-47" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
<p>All yaml-scalar to native mappings</p>
</td>
</tr>
</tbody>
</table>
</div>
<div class="span3">
<img src="Legivel/img/logo.png" alt="F# Project" style="width:150px;margin:10px" />
<ul class="nav nav-list" id="menu" style="margin-top: 20px;">
<li class="nav-header">Legivel</li>
<li><a href="Legivel/index.html">Home page</a></li>
<li class="divider"></li>
<li><a href="http://nuget.org/packages/Legivel">Get Library via NuGet</a></li>
<li><a href="https://github.com/fjoppe/Legivel">Source Code on GitHub</a></li>
<li><a href="Legivel/license.html">License</a></li>
<li><a href="Legivel/release-notes.html">Release Notes</a></li>
<li class="nav-header">Getting started</li>
<li><a href="Legivel/tutorial.html">Sample tutorial</a></li>
<li class="nav-header">Documentation</li>
<li><a href="Legivel/reference/index.html">API Reference</a></li>
</ul>
</div>
</div>
</div>
<a href="https://github.com/fjoppe/Legivel"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"/></a>
</body>
</html>
|
fjoppe/Legivel
|
docs/reference/legivel-customization-mapping.html
|
HTML
|
unlicense
| 14,359 |
package glouton;
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.Test;
public class TestGlouton {
@Test
public void test() {
SacADos sac = new SacADos(30);
ArrayList<ObjetV> liste = new ArrayList<ObjetV>();
liste.add(new ObjetV(13, 7));
liste.add(new ObjetV(12, 4));
liste.add(new ObjetV(8, 3));
liste.add(new ObjetV(10, 3));
Trieur tri1 = new Trieur(liste, sac);
tri1.tri();
tri1.remplissage();
System.out.println(tri1.getObjets());
System.out.println(tri1.getSac().getObjets());
}
}
|
LilithMajor/AAV
|
PROJET_ALOG_V1_GLOUTON/src/glouton/TestGlouton.java
|
Java
|
unlicense
| 555 |
<HTML>
<BODY BGCOLOR="white">
<PRE>
<FONT color="green">001</FONT> /*<a name="line.1"></a>
<FONT color="green">002</FONT> * Licensed to the Apache Software Foundation (ASF) under one or more<a name="line.2"></a>
<FONT color="green">003</FONT> * contributor license agreements. See the NOTICE file distributed with<a name="line.3"></a>
<FONT color="green">004</FONT> * this work for additional information regarding copyright ownership.<a name="line.4"></a>
<FONT color="green">005</FONT> * The ASF licenses this file to You under the Apache License, Version 2.0<a name="line.5"></a>
<FONT color="green">006</FONT> * (the "License"); you may not use this file except in compliance with<a name="line.6"></a>
<FONT color="green">007</FONT> * the License. You may obtain a copy of the License at<a name="line.7"></a>
<FONT color="green">008</FONT> *<a name="line.8"></a>
<FONT color="green">009</FONT> * http://www.apache.org/licenses/LICENSE-2.0<a name="line.9"></a>
<FONT color="green">010</FONT> *<a name="line.10"></a>
<FONT color="green">011</FONT> * Unless required by applicable law or agreed to in writing, software<a name="line.11"></a>
<FONT color="green">012</FONT> * distributed under the License is distributed on an "AS IS" BASIS,<a name="line.12"></a>
<FONT color="green">013</FONT> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<a name="line.13"></a>
<FONT color="green">014</FONT> * See the License for the specific language governing permissions and<a name="line.14"></a>
<FONT color="green">015</FONT> * limitations under the License.<a name="line.15"></a>
<FONT color="green">016</FONT> */<a name="line.16"></a>
<FONT color="green">017</FONT> <a name="line.17"></a>
<FONT color="green">018</FONT> package org.apache.commons.net.ftp.parser;<a name="line.18"></a>
<FONT color="green">019</FONT> <a name="line.19"></a>
<FONT color="green">020</FONT> import java.util.HashMap;<a name="line.20"></a>
<FONT color="green">021</FONT> import java.util.List;<a name="line.21"></a>
<FONT color="green">022</FONT> import java.util.ListIterator;<a name="line.22"></a>
<FONT color="green">023</FONT> import java.util.regex.MatchResult;<a name="line.23"></a>
<FONT color="green">024</FONT> import java.util.regex.Matcher;<a name="line.24"></a>
<FONT color="green">025</FONT> import java.util.regex.Pattern;<a name="line.25"></a>
<FONT color="green">026</FONT> import java.util.regex.PatternSyntaxException;<a name="line.26"></a>
<FONT color="green">027</FONT> <a name="line.27"></a>
<FONT color="green">028</FONT> import org.apache.commons.net.ftp.FTPClientConfig;<a name="line.28"></a>
<FONT color="green">029</FONT> <a name="line.29"></a>
<FONT color="green">030</FONT> /**<a name="line.30"></a>
<FONT color="green">031</FONT> * Special implementation VMSFTPEntryParser with versioning turned on.<a name="line.31"></a>
<FONT color="green">032</FONT> * This parser removes all duplicates and only leaves the version with the highest<a name="line.32"></a>
<FONT color="green">033</FONT> * version number for each filename.<a name="line.33"></a>
<FONT color="green">034</FONT> *<a name="line.34"></a>
<FONT color="green">035</FONT> * This is a sample of VMS LIST output<a name="line.35"></a>
<FONT color="green">036</FONT> *<a name="line.36"></a>
<FONT color="green">037</FONT> * "1-JUN.LIS;1 9/9 2-JUN-1998 07:32:04 [GROUP,OWNER] (RWED,RWED,RWED,RE)",<a name="line.37"></a>
<FONT color="green">038</FONT> * "1-JUN.LIS;2 9/9 2-JUN-1998 07:32:04 [GROUP,OWNER] (RWED,RWED,RWED,RE)",<a name="line.38"></a>
<FONT color="green">039</FONT> * "DATA.DIR;1 1/9 2-JUN-1998 07:32:04 [GROUP,OWNER] (RWED,RWED,RWED,RE)",<a name="line.39"></a>
<FONT color="green">040</FONT> * <P><a name="line.40"></a>
<FONT color="green">041</FONT> *<a name="line.41"></a>
<FONT color="green">042</FONT> * @author <a href="[email protected]">Winston Ojeda</a><a name="line.42"></a>
<FONT color="green">043</FONT> * @author <a href="[email protected]">Stephane ESTE-GRACIAS</a><a name="line.43"></a>
<FONT color="green">044</FONT> * @version $Id: VMSVersioningFTPEntryParser.java 636854 2008-03-13 19:55:01Z sebb $<a name="line.44"></a>
<FONT color="green">045</FONT> *<a name="line.45"></a>
<FONT color="green">046</FONT> * @see org.apache.commons.net.ftp.FTPFileEntryParser FTPFileEntryParser (for usage instructions)<a name="line.46"></a>
<FONT color="green">047</FONT> */<a name="line.47"></a>
<FONT color="green">048</FONT> public class VMSVersioningFTPEntryParser extends VMSFTPEntryParser<a name="line.48"></a>
<FONT color="green">049</FONT> {<a name="line.49"></a>
<FONT color="green">050</FONT> <a name="line.50"></a>
<FONT color="green">051</FONT> private Matcher _preparse_matcher_;<a name="line.51"></a>
<FONT color="green">052</FONT> private Pattern _preparse_pattern_;<a name="line.52"></a>
<FONT color="green">053</FONT> private static final String PRE_PARSE_REGEX =<a name="line.53"></a>
<FONT color="green">054</FONT> "(.*);([0-9]+)\\s*.*";<a name="line.54"></a>
<FONT color="green">055</FONT> <a name="line.55"></a>
<FONT color="green">056</FONT> /**<a name="line.56"></a>
<FONT color="green">057</FONT> * Constructor for a VMSFTPEntryParser object. Sets the versioning member<a name="line.57"></a>
<FONT color="green">058</FONT> * to the supplied value.<a name="line.58"></a>
<FONT color="green">059</FONT> *<a name="line.59"></a>
<FONT color="green">060</FONT> * @exception IllegalArgumentException<a name="line.60"></a>
<FONT color="green">061</FONT> * Thrown if the regular expression is unparseable. Should not be seen<a name="line.61"></a>
<FONT color="green">062</FONT> * under normal conditions. It it is seen, this is a sign that<a name="line.62"></a>
<FONT color="green">063</FONT> * <code>REGEX</code> is not a valid regular expression.<a name="line.63"></a>
<FONT color="green">064</FONT> */<a name="line.64"></a>
<FONT color="green">065</FONT> public VMSVersioningFTPEntryParser()<a name="line.65"></a>
<FONT color="green">066</FONT> {<a name="line.66"></a>
<FONT color="green">067</FONT> this(null);<a name="line.67"></a>
<FONT color="green">068</FONT> }<a name="line.68"></a>
<FONT color="green">069</FONT> <a name="line.69"></a>
<FONT color="green">070</FONT> /**<a name="line.70"></a>
<FONT color="green">071</FONT> * This constructor allows the creation of a VMSVersioningFTPEntryParser <a name="line.71"></a>
<FONT color="green">072</FONT> * object with something other than the default configuration.<a name="line.72"></a>
<FONT color="green">073</FONT> *<a name="line.73"></a>
<FONT color="green">074</FONT> * @param config The {@link FTPClientConfig configuration} object used to <a name="line.74"></a>
<FONT color="green">075</FONT> * configure this parser.<a name="line.75"></a>
<FONT color="green">076</FONT> * @exception IllegalArgumentException<a name="line.76"></a>
<FONT color="green">077</FONT> * Thrown if the regular expression is unparseable. Should not be seen<a name="line.77"></a>
<FONT color="green">078</FONT> * under normal conditions. It it is seen, this is a sign that<a name="line.78"></a>
<FONT color="green">079</FONT> * <code>REGEX</code> is not a valid regular expression.<a name="line.79"></a>
<FONT color="green">080</FONT> * @since 1.4<a name="line.80"></a>
<FONT color="green">081</FONT> */<a name="line.81"></a>
<FONT color="green">082</FONT> public VMSVersioningFTPEntryParser(FTPClientConfig config)<a name="line.82"></a>
<FONT color="green">083</FONT> {<a name="line.83"></a>
<FONT color="green">084</FONT> super();<a name="line.84"></a>
<FONT color="green">085</FONT> configure(config);<a name="line.85"></a>
<FONT color="green">086</FONT> try<a name="line.86"></a>
<FONT color="green">087</FONT> {<a name="line.87"></a>
<FONT color="green">088</FONT> //_preparse_matcher_ = new Perl5Matcher();<a name="line.88"></a>
<FONT color="green">089</FONT> _preparse_pattern_ = Pattern.compile(PRE_PARSE_REGEX);<a name="line.89"></a>
<FONT color="green">090</FONT> }<a name="line.90"></a>
<FONT color="green">091</FONT> catch (PatternSyntaxException pse)<a name="line.91"></a>
<FONT color="green">092</FONT> {<a name="line.92"></a>
<FONT color="green">093</FONT> throw new IllegalArgumentException (<a name="line.93"></a>
<FONT color="green">094</FONT> "Unparseable regex supplied: " + PRE_PARSE_REGEX);<a name="line.94"></a>
<FONT color="green">095</FONT> }<a name="line.95"></a>
<FONT color="green">096</FONT> <a name="line.96"></a>
<FONT color="green">097</FONT> }<a name="line.97"></a>
<FONT color="green">098</FONT> <a name="line.98"></a>
<FONT color="green">099</FONT> <a name="line.99"></a>
<FONT color="green">100</FONT> <a name="line.100"></a>
<FONT color="green">101</FONT> private static class NameVersion {<a name="line.101"></a>
<FONT color="green">102</FONT> String name;<a name="line.102"></a>
<FONT color="green">103</FONT> int versionNumber;<a name="line.103"></a>
<FONT color="green">104</FONT> NameVersion(String name, String vers) {<a name="line.104"></a>
<FONT color="green">105</FONT> this.name = name;<a name="line.105"></a>
<FONT color="green">106</FONT> this.versionNumber = Integer.parseInt(vers);<a name="line.106"></a>
<FONT color="green">107</FONT> }<a name="line.107"></a>
<FONT color="green">108</FONT> }<a name="line.108"></a>
<FONT color="green">109</FONT> <a name="line.109"></a>
<FONT color="green">110</FONT> /**<a name="line.110"></a>
<FONT color="green">111</FONT> * Implement hook provided for those implementers (such as<a name="line.111"></a>
<FONT color="green">112</FONT> * VMSVersioningFTPEntryParser, and possibly others) which return<a name="line.112"></a>
<FONT color="green">113</FONT> * multiple files with the same name to remove the duplicates ..<a name="line.113"></a>
<FONT color="green">114</FONT> *<a name="line.114"></a>
<FONT color="green">115</FONT> * @param original Original list<a name="line.115"></a>
<FONT color="green">116</FONT> *<a name="line.116"></a>
<FONT color="green">117</FONT> * @return Original list purged of duplicates<a name="line.117"></a>
<FONT color="green">118</FONT> */<a name="line.118"></a>
<FONT color="green">119</FONT> @Override<a name="line.119"></a>
<FONT color="green">120</FONT> public List<String> preParse(List<String> original) {<a name="line.120"></a>
<FONT color="green">121</FONT> original = super.preParse(original);<a name="line.121"></a>
<FONT color="green">122</FONT> HashMap<String, NameVersion> existingEntries = new HashMap<String, NameVersion>();<a name="line.122"></a>
<FONT color="green">123</FONT> ListIterator<String> iter = original.listIterator();<a name="line.123"></a>
<FONT color="green">124</FONT> while (iter.hasNext()) {<a name="line.124"></a>
<FONT color="green">125</FONT> String entry = iter.next().trim();<a name="line.125"></a>
<FONT color="green">126</FONT> MatchResult result = null;<a name="line.126"></a>
<FONT color="green">127</FONT> _preparse_matcher_ = _preparse_pattern_.matcher(entry);<a name="line.127"></a>
<FONT color="green">128</FONT> if (_preparse_matcher_.matches()) {<a name="line.128"></a>
<FONT color="green">129</FONT> result = _preparse_matcher_.toMatchResult();<a name="line.129"></a>
<FONT color="green">130</FONT> String name = result.group(1);<a name="line.130"></a>
<FONT color="green">131</FONT> String version = result.group(2);<a name="line.131"></a>
<FONT color="green">132</FONT> NameVersion nv = new NameVersion(name, version);<a name="line.132"></a>
<FONT color="green">133</FONT> NameVersion existing = existingEntries.get(name);<a name="line.133"></a>
<FONT color="green">134</FONT> if (null != existing) {<a name="line.134"></a>
<FONT color="green">135</FONT> if (nv.versionNumber < existing.versionNumber) {<a name="line.135"></a>
<FONT color="green">136</FONT> iter.remove(); // removal removes from original list.<a name="line.136"></a>
<FONT color="green">137</FONT> continue;<a name="line.137"></a>
<FONT color="green">138</FONT> }<a name="line.138"></a>
<FONT color="green">139</FONT> }<a name="line.139"></a>
<FONT color="green">140</FONT> existingEntries.put(name, nv);<a name="line.140"></a>
<FONT color="green">141</FONT> }<a name="line.141"></a>
<FONT color="green">142</FONT> <a name="line.142"></a>
<FONT color="green">143</FONT> }<a name="line.143"></a>
<FONT color="green">144</FONT> // we've now removed all entries less than with less than the largest<a name="line.144"></a>
<FONT color="green">145</FONT> // version number for each name that were listed after the largest.<a name="line.145"></a>
<FONT color="green">146</FONT> // we now must remove those with smaller than the largest version number<a name="line.146"></a>
<FONT color="green">147</FONT> // for each name that were found before the largest<a name="line.147"></a>
<FONT color="green">148</FONT> while (iter.hasPrevious()) {<a name="line.148"></a>
<FONT color="green">149</FONT> String entry = iter.previous().trim();<a name="line.149"></a>
<FONT color="green">150</FONT> MatchResult result = null;<a name="line.150"></a>
<FONT color="green">151</FONT> _preparse_matcher_ = _preparse_pattern_.matcher(entry);<a name="line.151"></a>
<FONT color="green">152</FONT> if (_preparse_matcher_.matches()) {<a name="line.152"></a>
<FONT color="green">153</FONT> result = _preparse_matcher_.toMatchResult();<a name="line.153"></a>
<FONT color="green">154</FONT> String name = result.group(1);<a name="line.154"></a>
<FONT color="green">155</FONT> String version = result.group(2);<a name="line.155"></a>
<FONT color="green">156</FONT> NameVersion nv = new NameVersion(name, version);<a name="line.156"></a>
<FONT color="green">157</FONT> NameVersion existing = existingEntries.get(name);<a name="line.157"></a>
<FONT color="green">158</FONT> if (null != existing) {<a name="line.158"></a>
<FONT color="green">159</FONT> if (nv.versionNumber < existing.versionNumber) {<a name="line.159"></a>
<FONT color="green">160</FONT> iter.remove(); // removal removes from original list.<a name="line.160"></a>
<FONT color="green">161</FONT> }<a name="line.161"></a>
<FONT color="green">162</FONT> }<a name="line.162"></a>
<FONT color="green">163</FONT> }<a name="line.163"></a>
<FONT color="green">164</FONT> <a name="line.164"></a>
<FONT color="green">165</FONT> }<a name="line.165"></a>
<FONT color="green">166</FONT> return original;<a name="line.166"></a>
<FONT color="green">167</FONT> }<a name="line.167"></a>
<FONT color="green">168</FONT> <a name="line.168"></a>
<FONT color="green">169</FONT> <a name="line.169"></a>
<FONT color="green">170</FONT> @Override<a name="line.170"></a>
<FONT color="green">171</FONT> protected boolean isVersioning() {<a name="line.171"></a>
<FONT color="green">172</FONT> return true;<a name="line.172"></a>
<FONT color="green">173</FONT> }<a name="line.173"></a>
<FONT color="green">174</FONT> <a name="line.174"></a>
<FONT color="green">175</FONT> }<a name="line.175"></a>
<FONT color="green">176</FONT> <a name="line.176"></a>
<FONT color="green">177</FONT> /* Emacs configuration<a name="line.177"></a>
<FONT color="green">178</FONT> * Local variables: **<a name="line.178"></a>
<FONT color="green">179</FONT> * mode: java **<a name="line.179"></a>
<FONT color="green">180</FONT> * c-basic-offset: 4 **<a name="line.180"></a>
<FONT color="green">181</FONT> * indent-tabs-mode: nil **<a name="line.181"></a>
<FONT color="green">182</FONT> * End: **<a name="line.182"></a>
<FONT color="green">183</FONT> */<a name="line.183"></a>
</PRE>
</BODY>
</HTML>
|
larjen/modulaise
|
modulaise/lib/commons-net-2.0/apidocs/src-html/org/apache/commons/net/ftp/parser/VMSVersioningFTPEntryParser.html
|
HTML
|
unlicense
| 17,531 |
---
topic: "Progressive enhancement & accessibility"
desc: "Introduction to making JavaScript optional and not ruining accessibility by adding JavaScript."
clr: "2, 3, 5, 6, 7"
video_tutorials:
- title: "Progressive enhancement"
url: progressive-enhancement
highlight: true
- title: "Accessibility"
url: accessibility
- title: "Accessibility checklist"
url: accessibility-checklist
highlight: true
- title: "Accessibility testing checklist"
url: accessibility-testing-checklist
highlight: true
- title: "JavaScript, jQuery & accessibility"
url: javascript-jquery-accessibility
- title: "Advanced performance checklist"
url: advanced-performance-checklist
# slides:
# - title: "PE & a11y"
# url: pe-a11y
group_activities:
- title: "Index card Q&A"
url: "/courses/shared/index-card-qa/"
type: pencil
no-solution: true
tasks:
- title: "Performance Perfector"
url: "https://activities.learn-the-web.algonquindesign.ca/performance-perfector/"
type: activity
- type: blank
# - title: "Lazy-loading images"
# url: lazy-loading-images
# type: lesson
# submit: "Submit nothing."
# graded-as: false
# disabled: true
- title: "Accessibility testing"
url: "/courses/shared/accessibility-testing/"
submit: "Submit nothing."
pair: true
button: activity
type: basic
progressinator_id: portfolio-interim-a11y-testing
- title: "Final portfolio website"
url: "https://github.com/acgd-webdev-5/final-portfolio-website"
graded-as: final-portfolio
due: "Midnight, last day of class"
due_week: 15
due_time: "23:59"
submit: online
---
|
acgd-webdev-5/curriculum
|
week-13.md
|
Markdown
|
unlicense
| 1,670 |
using Microsoft.Phone.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TinderApp.Library.ViewModels;
namespace TinderApp.Library.Controls
{
public class CustomPhoneApplicationFrame : PhoneApplicationFrame
{
public CustomPhoneApplicationFrame()
{
_viewModel = new CustomPhoneApplicationFrameViewModel();
DataContext = _viewModel;
}
private readonly CustomPhoneApplicationFrameViewModel _viewModel;
public CustomPhoneApplicationFrameViewModel ViewModel
{
get { return _viewModel; }
}
public void LoggedIn()
{
_viewModel.ProfileImageBrushChanged();
}
}
}
|
arubaboracho/Tinder
|
TinderApp.Library/Controls/CustomPhoneApplicationFrame.cs
|
C#
|
unlicense
| 782 |
<?php
define('EmpireCMSAdmin','1');
require("../../class/connect.php");
require("../../class/db_sql.php");
require("../../class/functions.php");
require "../".LoadLang("pub/fun.php");
require("../../data/dbcache/class.php");
$link=db_connect();
$empire=new mysqlquery();
$editor=1;
//验证用户
$lur=is_login();
$logininid=$lur['userid'];
$loginin=$lur['username'];
$loginrnd=$lur['rnd'];
$loginlevel=$lur['groupid'];
$loginadminstyleid=$lur['adminstyleid'];
//推送信息
function PushInfoToZt($add,$userid,$username){
global $empire,$dbtbpre,$class_r;
$classid=(int)$add['classid'];
$tid=(int)$add['tid'];
$ztid=$add['ztid'];
$cid=$add['cid'];
$id=$add['id'];
$count=count($ztid);
if(!$count||!$id)
{
echo"<script>window.close();</script>";
exit();
}
//表名
$tbname='';
if($classid)
{
$tbname=$class_r[$classid]['tbname'];
}
elseif($tid)
{
$tbr=$empire->fetch1("select tbname from {$dbtbpre}enewstable where tid='$tid'");
$tbname=$tbr['tbname'];
}
if(!$tbname)
{
printerror('ErrorUrl','');
}
//ID
$id=eReturnInids($id);
$where='id in ('.$id.')';
$ztids='';
$zcids='';
for($i=0;$i<$count;$i++)
{
$true_ztid=(int)$ztid[$i];
if(!$true_ztid)
{
continue;
}
$true_cid=(int)$cid[$true_ztid];
if($true_cid<0)
{
$true_cid=0;
}
$ztids.=$dh.$true_ztid;
$dh=',';
AddMoreInfoToZt($true_ztid,$true_cid,$tbname,$where,1);
}
//操作日志
insert_dolog("classid=$classid&tid=$tid<br>ztid=".$ztids."<br>id=".$id);
echo"<script>alert('推送成功');window.close();</script>";
exit();
}
//返回所属选择专题
function ReturnZtToInfo($add,$userid,$username){
global $empire,$dbtbpre,$class_r;
$ztid=$add['ztid'];
$cid=$add['cid'];
$count=count($ztid);
if(!$count)
{
//echo"<script>window.close();</script>";
//exit();
}
$ztids='';
$zcids='';
$oldztids=$add['oldztids'];
$oldzcids=$add['oldcids'];
for($i=0;$i<$count;$i++)
{
$true_ztid=(int)$ztid[$i];
if(!$true_ztid)
{
continue;
}
$true_cid=(int)$cid[$true_ztid];
$ztids.=$dh.$true_ztid;
$dh=',';
$zcids.=$cdh.$true_cid;
$cdh=',';
}
?>
<script>
opener.document.add.ztids.value="<?=$ztids?>";
opener.document.add.zcids.value="<?=$zcids?>";
opener.document.add.oldztids.value="<?=$oldztids?>";
opener.document.add.oldzcids.value="<?=$oldzcids?>";
window.close();
</script>
<?php
exit();
}
$enews=$_POST['enews'];
if(empty($enews))
{$enews=$_GET['enews'];}
if($enews=='PushInfoToZt')//选择专题
{
if($_POST['sinfo'])
{
ReturnZtToInfo($_POST,$logininid,$loginin);
}
PushInfoToZt($_POST,$logininid,$loginin);
}
$add='';
//分类
$zcid=(int)$_GET['zcid'];
if($zcid)
{
$add.=" and zcid='$zcid'";
}
//栏目
$classid=(int)$_GET['classid'];
if($classid)
{
$classwhere=ReturnClass($class_r[$classid][featherclass]);
$add.=" and (classid=0 or classid='$classid' or (".$classwhere."))";
}
$sinfo=(int)$_GET['sinfo'];
//表ID
$tid=(int)$_GET['tid'];
//ID
$id=$_GET['id'];
if(empty($sinfo)&&!$id)
{
echo"<script>alert('请选择信息');window.close();</script>";
exit();
}
//信息
$info_ztids='';
$info_cids='';
if($sinfo&&$id)
{
$ztdh='';
$cdh='';
$id=(int)$id;
$infosql=$empire->query("select ztid,cid from {$dbtbpre}enewsztinfo where id='$id' and classid='$classid'");
while($infor=$empire->fetch($infosql))
{
$info_ztids.=$ztdh.$infor['ztid'];
$ztdh=',';
if($infor['cid'])
{
$info_cids.=$cdh.$infor['cid'];
}
else
{
$info_cids.=$cdh.'-'.$infor['ztid'];
}
$cdh=',';
}
}
elseif($sinfo&&empty($id))
{
$firstpost=1;
}
$time=time();
//专题
$query="select ztid,ztname from {$dbtbpre}enewszt where usezt=0 and (endtime=0 or endtime>$time)".$add." order by myorder,ztid desc";
$sql=$empire->query($query);
//分类
$zcstr="";
$zcsql=$empire->query("select classid,classname from {$dbtbpre}enewsztclass order by classid");
while($zcr=$empire->fetch($zcsql))
{
$select="";
if($zcr[classid]==$zcid)
{
$select=" selected";
}
$zcstr.="<option value='".$zcr[classid]."'".$select.">".$zcr[classname]."</option>";
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>推送信息到专题</title>
<link href="../adminstyle/<?=$loginadminstyleid?>/adminstyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<tr>
<td>位置: 推送信息到专题
<div align="right"> </div></td>
</tr>
</table>
<table width="100%" border="0" align="center" cellpadding="3" cellspacing="1">
<form name="searchform" method="GET" action="PushToZt.php">
<tr>
<td> 选择专题分类:
<select name="select" id="select" onchange=window.location='PushToZt.php?classid=<?=$classid?>&tid=<?=$tid?>&id=<?=$id?>&sinfo=<?=$sinfo?>&oldztids=<?=$info_ztids?>&oldcids=<?=$info_cids?>&zcid='+this.options[this.selectedIndex].value>
<option value="0">所有分类</option>
<?=$zcstr?>
</select></td>
</tr>
</form>
</table>
<form name="form1" method="post" action="PushToZt.php">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<tr>
<td>
<?php
if(empty($sinfo))
{
?>
推送信息ID:<?=$id?>
<?php
}
else
{
?>
推送信息:<script>document.write(opener.document.add.title.value);</script>
<?php
}
?>
</td>
</tr>
</table>
<table width="100%" border="0" align="center" cellpadding="3" cellspacing="1" class="tableborder">
<tr class="header">
<td width="74%" height="25"> 专题名称</td>
</tr>
<?
while($r=$empire->fetch($sql))
{
$check='';
if($info_ztids&&strstr(','.$info_ztids.',',','.$r[ztid].','))
{
$check=' checked';
}
?>
<tr bgcolor="#FFFFFF" id="chzt<?=$r[ztid]?>">
<td height="25"><input name="ztid[]" type="checkbox" id="ztid[]" value="<?=$r[ztid]?>"<?=$check?>>
<?=$r['ztname']?></td>
</tr>
<tr bgcolor="#FFFFFF">
<td height="25"><table width="98%" border="0" align="center" cellpadding="3" cellspacing="1">
<tr>
<td><input type="radio" name="cid[<?=$r['ztid']?>]" value="-<?=$r[ztid]?>"<?=empty($check)||$firstpost==1||($check&&$info_cids&&strstr(','.$info_cids.',',',-'.$r[ztid].','))?' checked':''?>> 不属专题子类</td>
</tr>
<?php
$csql=$empire->query("select cid,cname from {$dbtbpre}enewszttype where ztid='$r[ztid]'");
while($cr=$empire->fetch($csql))
{
?>
<tr>
<td><input type="radio" name="cid[<?=$r['ztid']?>]" value="<?=$cr[cid]?>"<?=$check&&$info_cids&&strstr(','.$info_cids.',',','.$cr[cid].',')?' checked':''?>> <?=$cr[cname]?></td>
</tr>
<?php
}
?>
</table></td>
</tr>
<?php
}
?>
<tr bgcolor="#FFFFFF">
<td height="25"><div align="center">
<input type="submit" name="Submit2" value="确定推送">
<input type="button" name="Submit3" value="取消" onclick="window.close();">
<input name="enews" type="hidden" id="enews" value="PushInfoToZt">
<input name="classid" type="hidden" id="classid" value="<?=$classid?>">
<input name="tid" type="hidden" id="tid" value="<?=$tid?>">
<input name="id" type="hidden" id="id" value="<?=$id?>">
<input name="sinfo" type="hidden" id="sinfo" value="<?=$sinfo?>">
<input name="oldztids" type="hidden" value="<?=$info_ztids?>">
<input name="oldcids" type="hidden" value="<?=$info_cids?>">
</div></td>
</tr>
</table>
</form>
</body>
</html>
<?
db_close();
$empire=null;
?>
|
liangpz521/b2b
|
e/admin/special/PushToZt.php
|
PHP
|
unlicense
| 7,570 |
'''
Scratchpad for test-based development.
LICENSING
-------------------------------------------------
hypergolix: A python Golix client.
Copyright (C) 2016 Muterra, Inc.
Contributors
------------
Nick Badger
[email protected] | [email protected] | nickbadger.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc.,
51 Franklin Street,
Fifth Floor,
Boston, MA 02110-1301 USA
------------------------------------------------------
'''
import unittest
import logging
import loopa
import random
import gc
from loopa import NoopLoop
from loopa.utils import await_coroutine_threadsafe
from queue import Empty
from golix import Ghid
from hypergolix.utils import ApiID
from hypergolix.utils import AppToken
from hypergolix.accounting import Account
from hypergolix.comms import _ConnectionBase
from hypergolix.core import Oracle
from hypergolix.ipc import IPCServerProtocol
from hypergolix.dispatch import Dispatcher
from hypergolix.dispatch import _Dispatchable
from hypergolix.exceptions import UnknownToken
from hypergolix.exceptions import ExistantAppError
# ###############################################
# Fixture imports
# ###############################################
from _fixtures.ghidutils import make_random_ghid
from _fixtures.identities import TEST_AGENT1
# ###############################################
# Fixture code and boilerplate
# ###############################################
logger = logging.getLogger(__name__)
class Reffable:
''' Noop class that supports being weakreffed.
'''
# ###############################################
# Testing
# ###############################################
class TestDispatcher(unittest.TestCase):
''' Test the Dispatcher, YO!
'''
@classmethod
def setUpClass(cls):
# Set up some reffable stuff so we can create fixture _Dispatchables
cls.golcore = Reffable()
cls.ghidproxy = Reffable()
cls.privateer = Reffable()
cls.percore = Reffable()
cls.librarian = Reffable()
# Set up the nooploop
cls.nooploop = NoopLoop(
debug = True,
threaded = True
)
cls.nooploop.start()
@classmethod
def tearDownClass(cls):
# Kill the running loop.
cls.nooploop.stop_threadsafe_nowait()
def setUp(self):
''' Perform test-specific setup.
'''
# Whoami isn't relevant here, so just ignore it.
self.oracle = Oracle.__fixture__()
self.ipc_protocol = IPCServerProtocol.__fixture__(whoami=None)
# Some assembly required
self.dispatch = Dispatcher()
self.dispatch.assemble(self.oracle, self.ipc_protocol)
self.account = Account.__fixture__(TEST_AGENT1)
self.dispatch.bootstrap(self.account)
def test_app_start(self):
''' Test starting an application, including token creation.
'''
# Create a new connection and start it.
conn = _ConnectionBase.__fixture__()
token = await_coroutine_threadsafe(
coro = self.dispatch.start_application(conn),
loop = self.nooploop._loop
)
self.assertTrue(isinstance(token, AppToken))
# For the same connection, make sure attempting to start a second app
# fails.
with self.assertRaises(ExistantAppError):
await_coroutine_threadsafe(
coro = self.dispatch.start_application(conn, AppToken.null()),
loop = self.nooploop._loop
)
# For a different connection, make sure attempting to start the same
# app also fails.
conn2 = _ConnectionBase.__fixture__()
with self.assertRaises(ExistantAppError):
await_coroutine_threadsafe(
coro = self.dispatch.start_application(conn2, token),
loop = self.nooploop._loop
)
# Now attempt to register a different, but unknown, token for the same
# connection.
unk_token = token
while unk_token == token:
unk_token = AppToken.pseudorandom()
with self.assertRaises(UnknownToken):
await_coroutine_threadsafe(
coro = self.dispatch.start_application(conn2, unk_token),
loop = self.nooploop._loop
)
# Finally, delete the original connection, and re-register the existing
# token under the new connection.
del conn
gc.collect()
token2 = await_coroutine_threadsafe(
coro = self.dispatch.start_application(conn2, token),
loop = self.nooploop._loop
)
self.assertEqual(token, token2)
def test_obj_tracking(self):
''' Test tracking and untracking an object for an application.
'''
# Create a new connection
conn = _ConnectionBase.__fixture__()
obj1 = _Dispatchable.__fixture__(
ghid = make_random_ghid(),
dynamic = True,
author = make_random_ghid(),
legroom = 7,
api_id = ApiID(bytes([random.randint(0, 255) for i in range(64)])),
state = bytes([random.randint(0, 255) for i in range(4)]),
golcore = self.golcore,
ghidproxy = self.ghidproxy,
privateer = self.privateer,
percore = self.percore,
librarian = self.librarian,
dispatch = self.dispatch,
ipc_protocol = self.ipc_protocol,
account = self.account
)
self.oracle.add_object(obj1.ghid, obj1)
obj2 = _Dispatchable.__fixture__(
ghid = make_random_ghid(),
dynamic = True,
author = make_random_ghid(),
legroom = 7,
api_id = ApiID(bytes([random.randint(0, 255) for i in range(64)])),
state = bytes([random.randint(0, 255) for i in range(4)]),
golcore = self.golcore,
ghidproxy = self.ghidproxy,
privateer = self.privateer,
percore = self.percore,
librarian = self.librarian,
dispatch = self.dispatch,
ipc_protocol = self.ipc_protocol,
account = self.account
)
self.oracle.add_object(obj2.ghid, obj2)
await_coroutine_threadsafe(
coro = self.dispatch.track_object(conn, obj1.ghid),
loop = self.nooploop._loop
)
await_coroutine_threadsafe(
coro = self.dispatch.untrack_object(conn, obj1.ghid),
loop = self.nooploop._loop
)
await_coroutine_threadsafe(
coro = self.dispatch.untrack_object(conn, obj2.ghid),
loop = self.nooploop._loop
)
def test_obj_registration_nonprivate(self):
''' Test registering a new, non-private object.
'''
# Create a new connection and object fixture
conn = _ConnectionBase.__fixture__()
obj = _Dispatchable.__fixture__(
ghid = make_random_ghid(),
dynamic = True,
author = make_random_ghid(),
legroom = 7,
api_id = ApiID(bytes([random.randint(0, 255) for i in range(64)])),
state = bytes([random.randint(0, 255) for i in range(4)]),
golcore = self.golcore,
ghidproxy = self.ghidproxy,
privateer = self.privateer,
percore = self.percore,
librarian = self.librarian,
dispatch = self.dispatch,
ipc_protocol = self.ipc_protocol,
account = self.account
)
self.oracle.add_object(obj.ghid, obj)
# Register a non-private object first
await_coroutine_threadsafe(
coro = self.dispatch.register_object(conn, obj.ghid, False),
loop = self.nooploop._loop
)
def test_obj_registration_private(self):
''' Test registering a new, private object.
'''
# Create a new connection and object fixture
conn = _ConnectionBase.__fixture__()
obj = _Dispatchable.__fixture__(
ghid = make_random_ghid(),
dynamic = True,
author = make_random_ghid(),
legroom = 7,
api_id = ApiID(bytes([random.randint(0, 255) for i in range(64)])),
state = bytes([random.randint(0, 255) for i in range(4)]),
golcore = self.golcore,
ghidproxy = self.ghidproxy,
privateer = self.privateer,
percore = self.percore,
librarian = self.librarian,
dispatch = self.dispatch,
ipc_protocol = self.ipc_protocol,
account = self.account
)
self.oracle.add_object(obj.ghid, obj)
# With no token, this should raise.
with self.assertRaises(UnknownToken):
await_coroutine_threadsafe(
coro = self.dispatch.register_object(conn, obj.ghid, True),
loop = self.nooploop._loop
)
# With token defined, we're good to go.
token = AppToken.pseudorandom()
self.dispatch._token_from_conn[conn] = token
await_coroutine_threadsafe(
coro = self.dispatch.register_object(conn, obj.ghid, True),
loop = self.nooploop._loop
)
def test_distr_share_1(self):
''' Test distributing a share with no APIs defined.
'''
# Create a new connection and object fixture
conn = _ConnectionBase.__fixture__()
obj = _Dispatchable.__fixture__(
ghid = make_random_ghid(),
dynamic = True,
author = make_random_ghid(),
legroom = 7,
api_id = ApiID(bytes([random.randint(0, 255) for i in range(64)])),
state = bytes([random.randint(0, 255) for i in range(4)]),
golcore = self.golcore,
ghidproxy = self.ghidproxy,
privateer = self.privateer,
percore = self.percore,
librarian = self.librarian,
dispatch = self.dispatch,
ipc_protocol = self.ipc_protocol,
account = self.account
)
self.oracle.add_object(obj.ghid, obj)
# No origin, no skip_conn
await_coroutine_threadsafe(
coro = self.dispatch.distribute_share(obj.ghid, None, None),
loop = self.nooploop._loop
)
with self.assertRaises(IndexError):
self.ipc_protocol.shares.pop()
# No origin, skip_conn=conn
await_coroutine_threadsafe(
coro = self.dispatch.distribute_share(obj.ghid, None, conn),
loop = self.nooploop._loop
)
with self.assertRaises(IndexError):
self.ipc_protocol.shares.pop()
# Origin, no skip_conn
origin = make_random_ghid()
await_coroutine_threadsafe(
coro = self.dispatch.distribute_share(obj.ghid, origin, None),
loop = self.nooploop._loop
)
with self.assertRaises(IndexError):
self.ipc_protocol.shares.pop()
def test_distr_share_2(self):
''' Test distributing a share with no APIs defined.
'''
# Create a new connection and object fixture
conn = _ConnectionBase.__fixture__()
obj = _Dispatchable.__fixture__(
ghid = make_random_ghid(),
dynamic = True,
author = make_random_ghid(),
legroom = 7,
api_id = ApiID(bytes([random.randint(0, 255) for i in range(64)])),
state = bytes([random.randint(0, 255) for i in range(4)]),
golcore = self.golcore,
ghidproxy = self.ghidproxy,
privateer = self.privateer,
percore = self.percore,
librarian = self.librarian,
dispatch = self.dispatch,
ipc_protocol = self.ipc_protocol,
account = self.account
)
self.oracle.add_object(obj.ghid, obj)
self.dispatch._conns_from_api.add(obj.api_id, conn)
# No origin, no skip_conn
await_coroutine_threadsafe(
coro = self.dispatch.distribute_share(obj.ghid, None, None),
loop = self.nooploop._loop
)
sharelog = self.ipc_protocol.shares.pop()
self.assertIs(sharelog.connection, conn)
self.assertEqual(sharelog.ghid, obj.ghid)
# No origin, skip_conn=conn
await_coroutine_threadsafe(
coro = self.dispatch.distribute_share(obj.ghid, None, conn),
loop = self.nooploop._loop
)
with self.assertRaises(IndexError):
self.ipc_protocol.shares.pop()
def test_distr_update_1(self):
''' Test distributing an update with no APIs defined.
'''
# Create a new connection and object fixture
conn = _ConnectionBase.__fixture__()
obj = _Dispatchable.__fixture__(
ghid = make_random_ghid(),
dynamic = True,
author = make_random_ghid(),
legroom = 7,
api_id = ApiID(bytes([random.randint(0, 255) for i in range(64)])),
state = bytes([random.randint(0, 255) for i in range(4)]),
golcore = self.golcore,
ghidproxy = self.ghidproxy,
privateer = self.privateer,
percore = self.percore,
librarian = self.librarian,
dispatch = self.dispatch,
ipc_protocol = self.ipc_protocol,
account = self.account
)
self.oracle.add_object(obj.ghid, obj)
# Not deleted, no skip_conn
await_coroutine_threadsafe(
coro = self.dispatch.distribute_update(obj.ghid, False, None),
loop = self.nooploop._loop
)
with self.assertRaises(IndexError):
self.ipc_protocol.updates.pop()
# Not deleted, skip_conn=conn
await_coroutine_threadsafe(
coro = self.dispatch.distribute_update(obj.ghid, False, conn),
loop = self.nooploop._loop
)
with self.assertRaises(IndexError):
self.ipc_protocol.updates.pop()
def test_distr_update_2(self):
''' Test distributing an update with APIs defined.
'''
# Create a new connection and object fixture
conn = _ConnectionBase.__fixture__()
obj = _Dispatchable.__fixture__(
ghid = make_random_ghid(),
dynamic = True,
author = make_random_ghid(),
legroom = 7,
api_id = ApiID(bytes([random.randint(0, 255) for i in range(64)])),
state = bytes([random.randint(0, 255) for i in range(4)]),
golcore = self.golcore,
ghidproxy = self.ghidproxy,
privateer = self.privateer,
percore = self.percore,
librarian = self.librarian,
dispatch = self.dispatch,
ipc_protocol = self.ipc_protocol,
account = self.account
)
self.oracle.add_object(obj.ghid, obj)
self.dispatch._update_listeners.add(obj.ghid, conn)
# No delete, no skip_conn
await_coroutine_threadsafe(
coro = self.dispatch.distribute_update(obj.ghid, False, None),
loop = self.nooploop._loop
)
updatelog = self.ipc_protocol.updates.pop()
self.assertEqual(updatelog, (conn, obj.ghid))
# No delete, skip_conn=conn
await_coroutine_threadsafe(
coro = self.dispatch.distribute_update(obj.ghid, False, conn),
loop = self.nooploop._loop
)
with self.assertRaises(IndexError):
self.ipc_protocol.updates.pop()
def test_distr_delete_1(self):
''' Test distributing a deletion with no APIs defined.
'''
# Create a new connection and object fixture
conn = _ConnectionBase.__fixture__()
obj = _Dispatchable.__fixture__(
ghid = make_random_ghid(),
dynamic = True,
author = make_random_ghid(),
legroom = 7,
api_id = ApiID(bytes([random.randint(0, 255) for i in range(64)])),
state = bytes([random.randint(0, 255) for i in range(4)]),
golcore = self.golcore,
ghidproxy = self.ghidproxy,
privateer = self.privateer,
percore = self.percore,
librarian = self.librarian,
dispatch = self.dispatch,
ipc_protocol = self.ipc_protocol,
account = self.account
)
self.oracle.add_object(obj.ghid, obj)
# Deleted, no skip_conn
await_coroutine_threadsafe(
coro = self.dispatch.distribute_update(obj.ghid, True, None),
loop = self.nooploop._loop
)
with self.assertRaises(IndexError):
self.ipc_protocol.deletes.pop()
# Deleted, skip_conn=conn
await_coroutine_threadsafe(
coro = self.dispatch.distribute_update(obj.ghid, True, conn),
loop = self.nooploop._loop
)
with self.assertRaises(IndexError):
self.ipc_protocol.deletes.pop()
def test_distr_delete_2(self):
''' Test distributing a deletion with APIs defined.
'''
# Create a new connection and object fixture
conn = _ConnectionBase.__fixture__()
obj = _Dispatchable.__fixture__(
ghid = make_random_ghid(),
dynamic = True,
author = make_random_ghid(),
legroom = 7,
api_id = ApiID(bytes([random.randint(0, 255) for i in range(64)])),
state = bytes([random.randint(0, 255) for i in range(4)]),
golcore = self.golcore,
ghidproxy = self.ghidproxy,
privateer = self.privateer,
percore = self.percore,
librarian = self.librarian,
dispatch = self.dispatch,
ipc_protocol = self.ipc_protocol,
account = self.account
)
self.oracle.add_object(obj.ghid, obj)
self.dispatch._update_listeners.add(obj.ghid, conn)
# Deleted, no skip_conn
await_coroutine_threadsafe(
coro = self.dispatch.distribute_update(obj.ghid, True, None),
loop = self.nooploop._loop
)
deletelog = self.ipc_protocol.deletes.pop()
self.assertEqual(deletelog, (conn, obj.ghid))
# Deleted, skip_conn=conn
await_coroutine_threadsafe(
coro = self.dispatch.distribute_update(obj.ghid, True, conn),
loop = self.nooploop._loop
)
with self.assertRaises(IndexError):
self.ipc_protocol.deletes.pop()
def test_distr_share_success_1(self):
''' Test share success distribution with no tokens.
'''
# Create a new connection and object fixture
recipient = make_random_ghid()
# conn = _ConnectionBase.__fixture__()
obj = _Dispatchable.__fixture__(
ghid = make_random_ghid(),
dynamic = True,
author = make_random_ghid(),
legroom = 7,
api_id = ApiID(bytes([random.randint(0, 255) for i in range(64)])),
state = bytes([random.randint(0, 255) for i in range(4)]),
golcore = self.golcore,
ghidproxy = self.ghidproxy,
privateer = self.privateer,
percore = self.percore,
librarian = self.librarian,
dispatch = self.dispatch,
ipc_protocol = self.ipc_protocol,
account = self.account
)
self.oracle.add_object(obj.ghid, obj)
await_coroutine_threadsafe(
coro = self.dispatch.distribute_share_success(
obj.ghid,
recipient,
set(),
),
loop = self.nooploop._loop
)
with self.assertRaises(IndexError):
self.ipc_protocol.share_successes.pop()
def test_distr_share_success_2(self):
''' Test share success distribution with dummy tokens.
'''
# Create a new connection and object fixture
recipient = make_random_ghid()
conn = _ConnectionBase.__fixture__()
obj = _Dispatchable.__fixture__(
ghid = make_random_ghid(),
dynamic = True,
author = make_random_ghid(),
legroom = 7,
api_id = ApiID(bytes([random.randint(0, 255) for i in range(64)])),
state = bytes([random.randint(0, 255) for i in range(4)]),
golcore = self.golcore,
ghidproxy = self.ghidproxy,
privateer = self.privateer,
percore = self.percore,
librarian = self.librarian,
dispatch = self.dispatch,
ipc_protocol = self.ipc_protocol,
account = self.account
)
self.oracle.add_object(obj.ghid, obj)
token = AppToken.pseudorandom()
self.dispatch._conn_from_token[token] = conn
await_coroutine_threadsafe(
coro = self.dispatch.distribute_share_success(
obj.ghid,
recipient,
{token},
),
loop = self.nooploop._loop
)
shsulog = self.ipc_protocol.share_successes.pop()
self.assertEqual(shsulog, (conn, obj.ghid, recipient))
def test_distr_share_failure_1(self):
''' Test share failure distribution with no tokens.
'''
# Create a new connection and object fixture
recipient = make_random_ghid()
# conn = _ConnectionBase.__fixture__()
obj = _Dispatchable.__fixture__(
ghid = make_random_ghid(),
dynamic = True,
author = make_random_ghid(),
legroom = 7,
api_id = ApiID(bytes([random.randint(0, 255) for i in range(64)])),
state = bytes([random.randint(0, 255) for i in range(4)]),
golcore = self.golcore,
ghidproxy = self.ghidproxy,
privateer = self.privateer,
percore = self.percore,
librarian = self.librarian,
dispatch = self.dispatch,
ipc_protocol = self.ipc_protocol,
account = self.account
)
self.oracle.add_object(obj.ghid, obj)
await_coroutine_threadsafe(
coro = self.dispatch.distribute_share_failure(
obj.ghid,
recipient,
set(),
),
loop = self.nooploop._loop
)
with self.assertRaises(IndexError):
self.ipc_protocol.share_failures.pop()
def test_distr_share_failure_2(self):
''' Test share failure distribution with dummy tokens.
'''
# Create a new connection and object fixture
recipient = make_random_ghid()
conn = _ConnectionBase.__fixture__()
obj = _Dispatchable.__fixture__(
ghid = make_random_ghid(),
dynamic = True,
author = make_random_ghid(),
legroom = 7,
api_id = ApiID(bytes([random.randint(0, 255) for i in range(64)])),
state = bytes([random.randint(0, 255) for i in range(4)]),
golcore = self.golcore,
ghidproxy = self.ghidproxy,
privateer = self.privateer,
percore = self.percore,
librarian = self.librarian,
dispatch = self.dispatch,
ipc_protocol = self.ipc_protocol,
account = self.account
)
self.oracle.add_object(obj.ghid, obj)
token = AppToken.pseudorandom()
self.dispatch._conn_from_token[token] = conn
await_coroutine_threadsafe(
coro = self.dispatch.distribute_share_failure(
obj.ghid,
recipient,
{token},
),
loop = self.nooploop._loop
)
shfalog = self.ipc_protocol.share_failures.pop()
self.assertEqual(shfalog, (conn, obj.ghid, recipient))
def test_startup_objs(self):
''' Test share failure distribution with dummy tokens.
'''
# Create a new connection and object fixture
ghid = make_random_ghid()
conn = _ConnectionBase.__fixture__()
conn_2 = _ConnectionBase.__fixture__()
token = AppToken.pseudorandom()
self.dispatch._token_from_conn[conn] = token
self.dispatch._all_known_tokens.add(token)
unk_token = token
while unk_token == token:
unk_token = AppToken.pseudorandom()
# With no registered token...
with self.assertRaises(UnknownToken):
await_coroutine_threadsafe(
coro = self.dispatch.register_startup(conn_2, ghid),
loop = self.nooploop._loop
)
# With registered token...
await_coroutine_threadsafe(
coro = self.dispatch.register_startup(conn, ghid),
loop = self.nooploop._loop
)
# Now try getting that back and ensure symmetry
self.assertEqual(
await_coroutine_threadsafe(
coro = self.dispatch.get_startup_obj(token),
loop = self.nooploop._loop
),
ghid
)
# Now try that again with a different, unknown token
with self.assertRaises(UnknownToken):
await_coroutine_threadsafe(
coro = self.dispatch.get_startup_obj(unk_token),
loop = self.nooploop._loop
)
# Now try deregistering it with the right token
await_coroutine_threadsafe(
coro = self.dispatch.deregister_startup(conn),
loop = self.nooploop._loop
)
# And again without one
with self.assertRaises(UnknownToken):
await_coroutine_threadsafe(
coro = self.dispatch.get_startup_obj(conn_2),
loop = self.nooploop._loop
)
# Note that _Dispatchable is tested in test_gao!
if __name__ == "__main__":
from hypergolix import logutils
logutils.autoconfig(loglevel='debug')
# from hypergolix.utils import TraceLogger
# with TraceLogger(interval=10):
# unittest.main()
unittest.main()
|
Muterra/py_hypergolix
|
tests/trashtest/trashtest_dispatching.py
|
Python
|
unlicense
| 27,440 |
/*
Simple DirectMedia Layer
Copyright (C) 1997-2014 Sam Lantinga <[email protected]>
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 "../../SDL_internal.h"
#if SDL_VIDEO_DRIVER_X11
#include "SDL_x11video.h"
#include "SDL_assert.h"
/* GLX implementation of SDL OpenGL support */
#if SDL_VIDEO_OPENGL_GLX
#include "SDL_loadso.h"
#include "SDL_x11opengles.h"
#if defined(__IRIX__)
/* IRIX doesn't have a GL library versioning system */
#define DEFAULT_OPENGL "libGL.so"
#elif defined(__MACOSX__)
#define DEFAULT_OPENGL "/usr/X11R6/lib/libGL.1.dylib"
#elif defined(__QNXNTO__)
#define DEFAULT_OPENGL "libGL.so.3"
#else
#define DEFAULT_OPENGL "libGL.so.1"
#endif
#ifndef GLX_NONE_EXT
#define GLX_NONE_EXT 0x8000
#endif
#ifndef GLX_ARB_multisample
#define GLX_ARB_multisample
#define GLX_SAMPLE_BUFFERS_ARB 100000
#define GLX_SAMPLES_ARB 100001
#endif
#ifndef GLX_EXT_visual_rating
#define GLX_EXT_visual_rating
#define GLX_VISUAL_CAVEAT_EXT 0x20
#define GLX_NONE_EXT 0x8000
#define GLX_SLOW_VISUAL_EXT 0x8001
#define GLX_NON_CONFORMANT_VISUAL_EXT 0x800D
#endif
#ifndef GLX_EXT_visual_info
#define GLX_EXT_visual_info
#define GLX_X_VISUAL_TYPE_EXT 0x22
#define GLX_DIRECT_COLOR_EXT 0x8003
#endif
#ifndef GLX_ARB_create_context
#define GLX_ARB_create_context
#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
#define GLX_CONTEXT_FLAGS_ARB 0x2094
#define GLX_CONTEXT_DEBUG_BIT_ARB 0x0001
#define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x0002
/* Typedef for the GL 3.0 context creation function */
typedef GLXContext(*PFNGLXCREATECONTEXTATTRIBSARBPROC) (Display * dpy,
GLXFBConfig config,
GLXContext
share_context,
Bool direct,
const int
*attrib_list);
#endif
#ifndef GLX_ARB_create_context_profile
#define GLX_ARB_create_context_profile
#define GLX_CONTEXT_PROFILE_MASK_ARB 0x9126
#define GLX_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
#define GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
#endif
#ifndef GLX_ARB_create_context_robustness
#define GLX_ARB_create_context_robustness
#define GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB 0x00000004
#define GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB 0x8256
#define GLX_NO_RESET_NOTIFICATION_ARB 0x8261
#define GLX_LOSE_CONTEXT_ON_RESET_ARB 0x8252
#endif
#ifndef GLX_EXT_create_context_es2_profile
#define GLX_EXT_create_context_es2_profile
#ifndef GLX_CONTEXT_ES2_PROFILE_BIT_EXT
#define GLX_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000002
#endif
#endif
#ifndef GLX_ARB_framebuffer_sRGB
#define GLX_ARB_framebuffer_sRGB
#ifndef GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB
#define GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20B2
#endif
#endif
#ifndef GLX_EXT_swap_control
#define GLX_SWAP_INTERVAL_EXT 0x20F1
#define GLX_MAX_SWAP_INTERVAL_EXT 0x20F2
#endif
#ifndef GLX_EXT_swap_control_tear
#define GLX_LATE_SWAPS_TEAR_EXT 0x20F3
#endif
#ifndef GLX_ARB_context_flush_control
#define GLX_ARB_context_flush_control
#define GLX_CONTEXT_RELEASE_BEHAVIOR_ARB 0x2097
#define GLX_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB 0x0000
#define GLX_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB 0x2098
#endif
#define OPENGL_REQUIRES_DLOPEN
#if defined(OPENGL_REQUIRES_DLOPEN) && defined(SDL_LOADSO_DLOPEN)
#include <dlfcn.h>
#define GL_LoadObject(X) dlopen(X, (RTLD_NOW|RTLD_GLOBAL))
#define GL_LoadFunction dlsym
#define GL_UnloadObject dlclose
#else
#define GL_LoadObject SDL_LoadObject
#define GL_LoadFunction SDL_LoadFunction
#define GL_UnloadObject SDL_UnloadObject
#endif
static void X11_GL_InitExtensions(_THIS);
int
X11_GL_LoadLibrary(_THIS, const char *path)
{
Display *display;
void *handle;
if (_this->gl_data) {
return SDL_SetError("OpenGL context already created");
}
/* Load the OpenGL library */
if (path == NULL) {
path = SDL_getenv("SDL_OPENGL_LIBRARY");
}
if (path == NULL) {
path = DEFAULT_OPENGL;
}
_this->gl_config.dll_handle = GL_LoadObject(path);
if (!_this->gl_config.dll_handle) {
#if defined(OPENGL_REQUIRES_DLOPEN) && defined(SDL_LOADSO_DLOPEN)
SDL_SetError("Failed loading %s: %s", path, dlerror());
#endif
return -1;
}
SDL_strlcpy(_this->gl_config.driver_path, path,
SDL_arraysize(_this->gl_config.driver_path));
/* Allocate OpenGL memory */
_this->gl_data =
(struct SDL_GLDriverData *) SDL_calloc(1,
sizeof(struct
SDL_GLDriverData));
if (!_this->gl_data) {
return SDL_OutOfMemory();
}
/* Load function pointers */
handle = _this->gl_config.dll_handle;
_this->gl_data->glXQueryExtension =
(Bool (*)(Display *, int *, int *))
GL_LoadFunction(handle, "glXQueryExtension");
_this->gl_data->glXGetProcAddress =
(void *(*)(const GLubyte *))
GL_LoadFunction(handle, "glXGetProcAddressARB");
_this->gl_data->glXChooseVisual =
(XVisualInfo * (*)(Display *, int, int *))
X11_GL_GetProcAddress(_this, "glXChooseVisual");
_this->gl_data->glXCreateContext =
(GLXContext(*)(Display *, XVisualInfo *, GLXContext, int))
X11_GL_GetProcAddress(_this, "glXCreateContext");
_this->gl_data->glXDestroyContext =
(void (*)(Display *, GLXContext))
X11_GL_GetProcAddress(_this, "glXDestroyContext");
_this->gl_data->glXMakeCurrent =
(int (*)(Display *, GLXDrawable, GLXContext))
X11_GL_GetProcAddress(_this, "glXMakeCurrent");
_this->gl_data->glXSwapBuffers =
(void (*)(Display *, GLXDrawable))
X11_GL_GetProcAddress(_this, "glXSwapBuffers");
_this->gl_data->glXQueryDrawable =
(void (*)(Display*,GLXDrawable,int,unsigned int*))
X11_GL_GetProcAddress(_this, "glXQueryDrawable");
if (!_this->gl_data->glXQueryExtension ||
!_this->gl_data->glXChooseVisual ||
!_this->gl_data->glXCreateContext ||
!_this->gl_data->glXDestroyContext ||
!_this->gl_data->glXMakeCurrent ||
!_this->gl_data->glXSwapBuffers) {
return SDL_SetError("Could not retrieve OpenGL functions");
}
display = ((SDL_VideoData *) _this->driverdata)->display;
if (!_this->gl_data->glXQueryExtension(display, &_this->gl_data->errorBase, &_this->gl_data->eventBase)) {
return SDL_SetError("GLX is not supported");
}
/* Initialize extensions */
X11_GL_InitExtensions(_this);
/* If we need a GL ES context and there's no
* GLX_EXT_create_context_es2_profile extension, switch over to X11_GLES functions
*/
if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES &&
! _this->gl_data->HAS_GLX_EXT_create_context_es2_profile ) {
#if SDL_VIDEO_OPENGL_EGL
X11_GL_UnloadLibrary(_this);
/* Better avoid conflicts! */
if (_this->gl_config.dll_handle != NULL ) {
GL_UnloadObject(_this->gl_config.dll_handle);
_this->gl_config.dll_handle = NULL;
}
_this->GL_LoadLibrary = X11_GLES_LoadLibrary;
_this->GL_GetProcAddress = X11_GLES_GetProcAddress;
_this->GL_UnloadLibrary = X11_GLES_UnloadLibrary;
_this->GL_CreateContext = X11_GLES_CreateContext;
_this->GL_MakeCurrent = X11_GLES_MakeCurrent;
_this->GL_SetSwapInterval = X11_GLES_SetSwapInterval;
_this->GL_GetSwapInterval = X11_GLES_GetSwapInterval;
_this->GL_SwapWindow = X11_GLES_SwapWindow;
_this->GL_DeleteContext = X11_GLES_DeleteContext;
return X11_GLES_LoadLibrary(_this, NULL);
#else
return SDL_SetError("SDL not configured with EGL support");
#endif
}
return 0;
}
void *
X11_GL_GetProcAddress(_THIS, const char *proc)
{
if (_this->gl_data->glXGetProcAddress) {
return _this->gl_data->glXGetProcAddress((const GLubyte *) proc);
}
return GL_LoadFunction(_this->gl_config.dll_handle, proc);
}
void
X11_GL_UnloadLibrary(_THIS)
{
/* Don't actually unload the library, since it may have registered
* X11 shutdown hooks, per the notes at:
* http://dri.sourceforge.net/doc/DRIuserguide.html
*/
#if 0
GL_UnloadObject(_this->gl_config.dll_handle);
_this->gl_config.dll_handle = NULL;
#endif
/* Free OpenGL memory */
SDL_free(_this->gl_data);
_this->gl_data = NULL;
}
static SDL_bool
HasExtension(const char *extension, const char *extensions)
{
const char *start;
const char *where, *terminator;
if (!extensions)
return SDL_FALSE;
/* Extension names should not have spaces. */
where = SDL_strchr(extension, ' ');
if (where || *extension == '\0')
return SDL_FALSE;
/* It takes a bit of care to be fool-proof about parsing the
* OpenGL extensions string. Don't be fooled by sub-strings,
* etc. */
start = extensions;
for (;;) {
where = SDL_strstr(start, extension);
if (!where)
break;
terminator = where + SDL_strlen(extension);
if (where == start || *(where - 1) == ' ')
if (*terminator == ' ' || *terminator == '\0')
return SDL_TRUE;
start = terminator;
}
return SDL_FALSE;
}
static void
X11_GL_InitExtensions(_THIS)
{
Display *display = ((SDL_VideoData *) _this->driverdata)->display;
const int screen = DefaultScreen(display);
const char *(*glXQueryExtensionsStringFunc) (Display *, int);
const char *extensions;
glXQueryExtensionsStringFunc =
(const char *(*)(Display *, int)) X11_GL_GetProcAddress(_this,
"glXQueryExtensionsString");
if (glXQueryExtensionsStringFunc) {
extensions = glXQueryExtensionsStringFunc(display, screen);
} else {
extensions = NULL;
}
/* Check for GLX_EXT_swap_control(_tear) */
_this->gl_data->HAS_GLX_EXT_swap_control_tear = SDL_FALSE;
if (HasExtension("GLX_EXT_swap_control", extensions)) {
_this->gl_data->glXSwapIntervalEXT =
(void (*)(Display*,GLXDrawable,int))
X11_GL_GetProcAddress(_this, "glXSwapIntervalEXT");
if (HasExtension("GLX_EXT_swap_control_tear", extensions)) {
_this->gl_data->HAS_GLX_EXT_swap_control_tear = SDL_TRUE;
}
}
/* Check for GLX_MESA_swap_control */
if (HasExtension("GLX_MESA_swap_control", extensions)) {
_this->gl_data->glXSwapIntervalMESA =
(int(*)(int)) X11_GL_GetProcAddress(_this, "glXSwapIntervalMESA");
_this->gl_data->glXGetSwapIntervalMESA =
(int(*)(void)) X11_GL_GetProcAddress(_this,
"glXGetSwapIntervalMESA");
}
/* Check for GLX_SGI_swap_control */
if (HasExtension("GLX_SGI_swap_control", extensions)) {
_this->gl_data->glXSwapIntervalSGI =
(int (*)(int)) X11_GL_GetProcAddress(_this, "glXSwapIntervalSGI");
}
/* Check for GLX_ARB_create_context */
if (HasExtension("GLX_ARB_create_context", extensions)) {
_this->gl_data->glXCreateContextAttribsARB =
(GLXContext (*)(Display*,GLXFBConfig,GLXContext,Bool,const int *))
X11_GL_GetProcAddress(_this, "glXCreateContextAttribsARB");
_this->gl_data->glXChooseFBConfig =
(GLXFBConfig *(*)(Display *, int, const int *, int *))
X11_GL_GetProcAddress(_this, "glXChooseFBConfig");
}
/* Check for GLX_EXT_visual_rating */
if (HasExtension("GLX_EXT_visual_rating", extensions)) {
_this->gl_data->HAS_GLX_EXT_visual_rating = SDL_TRUE;
}
/* Check for GLX_EXT_visual_info */
if (HasExtension("GLX_EXT_visual_info", extensions)) {
_this->gl_data->HAS_GLX_EXT_visual_info = SDL_TRUE;
}
/* Check for GLX_EXT_create_context_es2_profile */
if (HasExtension("GLX_EXT_create_context_es2_profile", extensions)) {
_this->gl_data->HAS_GLX_EXT_create_context_es2_profile = SDL_TRUE;
}
/* Check for GLX_ARB_context_flush_control */
if (HasExtension("GLX_ARB_context_flush_control", extensions)) {
_this->gl_data->HAS_GLX_ARB_context_flush_control = SDL_TRUE;
}
}
/* glXChooseVisual and glXChooseFBConfig have some small differences in
* the attribute encoding, it can be chosen with the for_FBConfig parameter.
*/
static int
X11_GL_GetAttributes(_THIS, Display * display, int screen, int * attribs, int size, Bool for_FBConfig)
{
int i = 0;
const int MAX_ATTRIBUTES = 64;
/* assert buffer is large enough to hold all SDL attributes. */
SDL_assert(size >= MAX_ATTRIBUTES);
/* Setup our GLX attributes according to the gl_config. */
if( for_FBConfig ) {
attribs[i++] = GLX_RENDER_TYPE;
attribs[i++] = GLX_RGBA_BIT;
} else {
attribs[i++] = GLX_RGBA;
}
attribs[i++] = GLX_RED_SIZE;
attribs[i++] = _this->gl_config.red_size;
attribs[i++] = GLX_GREEN_SIZE;
attribs[i++] = _this->gl_config.green_size;
attribs[i++] = GLX_BLUE_SIZE;
attribs[i++] = _this->gl_config.blue_size;
if (_this->gl_config.alpha_size) {
attribs[i++] = GLX_ALPHA_SIZE;
attribs[i++] = _this->gl_config.alpha_size;
}
if (_this->gl_config.double_buffer) {
attribs[i++] = GLX_DOUBLEBUFFER;
if( for_FBConfig ) {
attribs[i++] = True;
}
}
attribs[i++] = GLX_DEPTH_SIZE;
attribs[i++] = _this->gl_config.depth_size;
if (_this->gl_config.stencil_size) {
attribs[i++] = GLX_STENCIL_SIZE;
attribs[i++] = _this->gl_config.stencil_size;
}
if (_this->gl_config.accum_red_size) {
attribs[i++] = GLX_ACCUM_RED_SIZE;
attribs[i++] = _this->gl_config.accum_red_size;
}
if (_this->gl_config.accum_green_size) {
attribs[i++] = GLX_ACCUM_GREEN_SIZE;
attribs[i++] = _this->gl_config.accum_green_size;
}
if (_this->gl_config.accum_blue_size) {
attribs[i++] = GLX_ACCUM_BLUE_SIZE;
attribs[i++] = _this->gl_config.accum_blue_size;
}
if (_this->gl_config.accum_alpha_size) {
attribs[i++] = GLX_ACCUM_ALPHA_SIZE;
attribs[i++] = _this->gl_config.accum_alpha_size;
}
if (_this->gl_config.stereo) {
attribs[i++] = GLX_STEREO;
if( for_FBConfig ) {
attribs[i++] = True;
}
}
if (_this->gl_config.multisamplebuffers) {
attribs[i++] = GLX_SAMPLE_BUFFERS_ARB;
attribs[i++] = _this->gl_config.multisamplebuffers;
}
if (_this->gl_config.multisamplesamples) {
attribs[i++] = GLX_SAMPLES_ARB;
attribs[i++] = _this->gl_config.multisamplesamples;
}
if (_this->gl_config.framebuffer_srgb_capable) {
attribs[i++] = GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB;
attribs[i++] = True; /* always needed, for_FBConfig or not! */
}
if (_this->gl_config.accelerated >= 0 &&
_this->gl_data->HAS_GLX_EXT_visual_rating) {
attribs[i++] = GLX_VISUAL_CAVEAT_EXT;
attribs[i++] = _this->gl_config.accelerated ? GLX_NONE_EXT :
GLX_SLOW_VISUAL_EXT;
}
/* If we're supposed to use DirectColor visuals, and we've got the
EXT_visual_info extension, then add GLX_X_VISUAL_TYPE_EXT. */
if (X11_UseDirectColorVisuals() &&
_this->gl_data->HAS_GLX_EXT_visual_info) {
attribs[i++] = GLX_X_VISUAL_TYPE_EXT;
attribs[i++] = GLX_DIRECT_COLOR_EXT;
}
attribs[i++] = None;
SDL_assert(i <= MAX_ATTRIBUTES);
return i;
}
XVisualInfo *
X11_GL_GetVisual(_THIS, Display * display, int screen)
{
/* 64 seems nice. */
int attribs[64];
XVisualInfo *vinfo;
if (!_this->gl_data) {
/* The OpenGL library wasn't loaded, SDL_GetError() should have info */
return NULL;
}
X11_GL_GetAttributes(_this, display, screen, attribs, 64, SDL_FALSE);
vinfo = _this->gl_data->glXChooseVisual(display, screen, attribs);
if (!vinfo) {
SDL_SetError("Couldn't find matching GLX visual");
}
return vinfo;
}
#ifndef GLXBadContext
#define GLXBadContext 0
#endif
#ifndef GLXBadFBConfig
#define GLXBadFBConfig 9
#endif
#ifndef GLXBadProfileARB
#define GLXBadProfileARB 13
#endif
static int (*handler) (Display *, XErrorEvent *) = NULL;
static int errorBase = 0;
static int errorCode = 0;
static int
X11_GL_CreateContextErrorHandler(Display * d, XErrorEvent * e)
{
char *x11_error = NULL;
char x11_error_locale[256];
errorCode = e->error_code;
if (X11_XGetErrorText(d, errorCode, x11_error_locale, sizeof(x11_error_locale)) == Success)
{
x11_error = SDL_iconv_string("UTF-8", "", x11_error_locale, SDL_strlen(x11_error_locale)+1);
}
if (x11_error)
{
SDL_SetError("Could not create GL context: %s", x11_error);
SDL_free(x11_error);
}
else
{
SDL_SetError("Could not create GL context: %i (Base %i)\n", errorCode, errorBase);
}
return (0);
}
SDL_GLContext
X11_GL_CreateContext(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
int screen =
((SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata)->screen;
XWindowAttributes xattr;
XVisualInfo v, *vinfo;
int n;
GLXContext context = NULL, share_context;
if (_this->gl_config.share_with_current_context) {
share_context = (GLXContext)SDL_GL_GetCurrentContext();
} else {
share_context = NULL;
}
/* We do this to create a clean separation between X and GLX errors. */
X11_XSync(display, False);
errorBase = _this->gl_data->errorBase;
errorCode = Success;
handler = X11_XSetErrorHandler(X11_GL_CreateContextErrorHandler);
X11_XGetWindowAttributes(display, data->xwindow, &xattr);
v.screen = screen;
v.visualid = X11_XVisualIDFromVisual(xattr.visual);
vinfo = X11_XGetVisualInfo(display, VisualScreenMask | VisualIDMask, &v, &n);
if (vinfo) {
if (_this->gl_config.major_version < 3 &&
_this->gl_config.profile_mask == 0 &&
_this->gl_config.flags == 0) {
/* Create legacy context */
context =
_this->gl_data->glXCreateContext(display, vinfo, share_context, True);
} else {
/* max 10 attributes plus terminator */
int attribs[11] = {
GLX_CONTEXT_MAJOR_VERSION_ARB,
_this->gl_config.major_version,
GLX_CONTEXT_MINOR_VERSION_ARB,
_this->gl_config.minor_version,
0
};
int iattr = 4;
/* SDL profile bits match GLX profile bits */
if( _this->gl_config.profile_mask != 0 ) {
attribs[iattr++] = GLX_CONTEXT_PROFILE_MASK_ARB;
attribs[iattr++] = _this->gl_config.profile_mask;
}
/* SDL flags match GLX flags */
if( _this->gl_config.flags != 0 ) {
attribs[iattr++] = GLX_CONTEXT_FLAGS_ARB;
attribs[iattr++] = _this->gl_config.flags;
}
/* only set if glx extension is available */
if( _this->gl_data->HAS_GLX_ARB_context_flush_control ) {
attribs[iattr++] = GLX_CONTEXT_RELEASE_BEHAVIOR_ARB;
attribs[iattr++] =
_this->gl_config.release_behavior ?
GLX_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB :
GLX_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB;
}
attribs[iattr++] = 0;
/* Get a pointer to the context creation function for GL 3.0 */
if (!_this->gl_data->glXCreateContextAttribsARB) {
SDL_SetError("OpenGL 3.0 and later are not supported by this system");
} else {
int glxAttribs[64];
/* Create a GL 3.x context */
GLXFBConfig *framebuffer_config = NULL;
int fbcount = 0;
X11_GL_GetAttributes(_this,display,screen,glxAttribs,64,SDL_TRUE);
if (!_this->gl_data->glXChooseFBConfig
|| !(framebuffer_config =
_this->gl_data->glXChooseFBConfig(display,
DefaultScreen(display), glxAttribs,
&fbcount))) {
SDL_SetError("No good framebuffers found. OpenGL 3.0 and later unavailable");
} else {
context = _this->gl_data->glXCreateContextAttribsARB(display,
framebuffer_config[0],
share_context, True, attribs);
}
}
}
X11_XFree(vinfo);
}
X11_XSync(display, False);
X11_XSetErrorHandler(handler);
if (!context) {
if (errorCode == Success) {
SDL_SetError("Could not create GL context");
}
return NULL;
}
if (X11_GL_MakeCurrent(_this, window, context) < 0) {
X11_GL_DeleteContext(_this, context);
return NULL;
}
return context;
}
int
X11_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context)
{
Display *display = ((SDL_VideoData *) _this->driverdata)->display;
Window drawable =
(context ? ((SDL_WindowData *) window->driverdata)->xwindow : None);
GLXContext glx_context = (GLXContext) context;
if (!_this->gl_data) {
return SDL_SetError("OpenGL not initialized");
}
if (!_this->gl_data->glXMakeCurrent(display, drawable, glx_context)) {
return SDL_SetError("Unable to make GL context current");
}
return 0;
}
/*
0 is a valid argument to glxSwapInterval(MESA|EXT) and setting it to 0
will undo the effect of a previous call with a value that is greater
than zero (or at least that is what the docs say). OTOH, 0 is an invalid
argument to glxSwapIntervalSGI and it returns an error if you call it
with 0 as an argument.
*/
static int swapinterval = -1;
int
X11_GL_SetSwapInterval(_THIS, int interval)
{
int status = -1;
if ((interval < 0) && (!_this->gl_data->HAS_GLX_EXT_swap_control_tear)) {
SDL_SetError("Negative swap interval unsupported in this GL");
} else if (_this->gl_data->glXSwapIntervalEXT) {
Display *display = ((SDL_VideoData *) _this->driverdata)->display;
const SDL_WindowData *windowdata = (SDL_WindowData *)
SDL_GL_GetCurrentWindow()->driverdata;
Window drawable = windowdata->xwindow;
/*
* This is a workaround for a bug in NVIDIA drivers. Bug has been reported
* and will be fixed in a future release (probably 319.xx).
*
* There's a bug where glXSetSwapIntervalEXT ignores updates because
* it has the wrong value cached. To work around it, we just run a no-op
* update to the current value.
*/
int currentInterval = X11_GL_GetSwapInterval(_this);
_this->gl_data->glXSwapIntervalEXT(display, drawable, currentInterval);
_this->gl_data->glXSwapIntervalEXT(display, drawable, interval);
status = 0;
swapinterval = interval;
} else if (_this->gl_data->glXSwapIntervalMESA) {
status = _this->gl_data->glXSwapIntervalMESA(interval);
if (status != 0) {
SDL_SetError("glxSwapIntervalMESA failed");
} else {
swapinterval = interval;
}
} else if (_this->gl_data->glXSwapIntervalSGI) {
status = _this->gl_data->glXSwapIntervalSGI(interval);
if (status != 0) {
SDL_SetError("glxSwapIntervalSGI failed");
} else {
swapinterval = interval;
}
} else {
SDL_Unsupported();
}
return status;
}
int
X11_GL_GetSwapInterval(_THIS)
{
if (_this->gl_data->glXSwapIntervalEXT) {
Display *display = ((SDL_VideoData *) _this->driverdata)->display;
const SDL_WindowData *windowdata = (SDL_WindowData *)
SDL_GL_GetCurrentWindow()->driverdata;
Window drawable = windowdata->xwindow;
unsigned int allow_late_swap_tearing = 0;
unsigned int interval = 0;
if (_this->gl_data->HAS_GLX_EXT_swap_control_tear) {
_this->gl_data->glXQueryDrawable(display, drawable,
GLX_LATE_SWAPS_TEAR_EXT,
&allow_late_swap_tearing);
}
_this->gl_data->glXQueryDrawable(display, drawable,
GLX_SWAP_INTERVAL_EXT, &interval);
if ((allow_late_swap_tearing) && (interval > 0)) {
return -((int) interval);
}
return (int) interval;
} else if (_this->gl_data->glXGetSwapIntervalMESA) {
return _this->gl_data->glXGetSwapIntervalMESA();
} else {
return swapinterval;
}
}
void
X11_GL_SwapWindow(_THIS, SDL_Window * window)
{
SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
Display *display = data->videodata->display;
_this->gl_data->glXSwapBuffers(display, data->xwindow);
}
void
X11_GL_DeleteContext(_THIS, SDL_GLContext context)
{
Display *display = ((SDL_VideoData *) _this->driverdata)->display;
GLXContext glx_context = (GLXContext) context;
if (!_this->gl_data) {
return;
}
_this->gl_data->glXDestroyContext(display, glx_context);
X11_XSync(display, False);
}
#endif /* SDL_VIDEO_OPENGL_GLX */
#endif /* SDL_VIDEO_DRIVER_X11 */
/* vi: set ts=4 sw=4 expandtab: */
|
dermoumi/m2n
|
extlibs/src/SDL2/src/video/x11/SDL_x11opengl.c
|
C
|
unlicense
| 27,126 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>DiscriminatedUnionMappingInfo - Legivel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="description" content=""/>
<meta name="author" content="Frank Joppe"/>
<script src="https://code.jquery.com/jquery-1.8.0.js"></script>
<script src="https://code.jquery.com/ui/1.8.23/jquery-ui.js"></script>
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet"/>
<link type="text/css" rel="stylesheet" href="Legivel/content/style.css" />
<script type="text/javascript" src="Legivel/content/tips.js"></script>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="masthead">
<ul class="nav nav-pills pull-right">
<li><a href="http://fsharp.org">fsharp.org</a></li>
<li><a href="https://github.com/fjoppe/Legivel">github page</a></li>
</ul>
<h3 class="muted"><a href="Legivel/index.html">Legivel</a></h3>
</div>
<hr />
<div class="row">
<div class="span9" id="main">
<h1>DiscriminatedUnionMappingInfo</h1>
<p>
<span>Namespace: Legivel.Customization</span><br />
<span>Parent Module: <a href="legivel-customization-mapping.html">Mapping</a></span><br />
</p>
<div class="xmldoc">
<p>Mapper structure for a Discriminated Union - non-enum</p>
</div>
<h3>Record Fields</h3>
<table class="table table-bordered member-list">
<thead>
<tr><td>Record Field</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '298', 298)" onmouseover="showTip(event, '298', 298)">
DUField
</code>
<div class="tip" id="298">
<strong>Signature:</strong> string option<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fjoppe/Legivel/tree/master/src/Legivel.Mapper/Customization.fs#L553-553" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '299', 299)" onmouseover="showTip(event, '299', 299)">
DUType
</code>
<div class="tip" id="299">
<strong>Signature:</strong> Type<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fjoppe/Legivel/tree/master/src/Legivel.Mapper/Customization.fs#L552-552" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '300', 300)" onmouseover="showTip(event, '300', 300)">
ProcessingOptions
</code>
<div class="tip" id="300">
<strong>Signature:</strong> ProcessingOptions<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fjoppe/Legivel/tree/master/src/Legivel.Mapper/Customization.fs#L556-556" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '301', 301)" onmouseover="showTip(event, '301', 301)">
UnionCaseMapping
</code>
<div class="tip" id="301">
<strong>Signature:</strong> (string * YTMRef) list<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fjoppe/Legivel/tree/master/src/Legivel.Mapper/Customization.fs#L555-555" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '302', 302)" onmouseover="showTip(event, '302', 302)">
UnionCases
</code>
<div class="tip" id="302">
<strong>Signature:</strong> DUFieldMapping list<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fjoppe/Legivel/tree/master/src/Legivel.Mapper/Customization.fs#L554-554" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
</tbody>
</table>
<h3>Static members</h3>
<table class="table table-bordered member-list">
<thead>
<tr><td>Static member</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '303', 303)" onmouseover="showTip(event, '303', 303)">
DiscriminatedUnionMappingInfo.TryFindMapper(...)
</code>
<div class="tip" id="303">
<strong>Signature:</strong> po:ProcessingOptions -> fmp:FindMapperParams -> TryFindMapperReturnType<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fjoppe/Legivel/tree/master/src/Legivel.Mapper/Customization.fs#L560-560" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
<p>Return a DiscriminatedUnionMappingInfo when the given type is a Discriminated Union</p>
</td>
</tr>
</tbody>
</table>
</div>
<div class="span3">
<img src="Legivel/img/logo.png" alt="F# Project" style="width:150px;margin:10px" />
<ul class="nav nav-list" id="menu" style="margin-top: 20px;">
<li class="nav-header">Legivel</li>
<li><a href="Legivel/index.html">Home page</a></li>
<li class="divider"></li>
<li><a href="http://nuget.org/packages/Legivel">Get Library via NuGet</a></li>
<li><a href="https://github.com/fjoppe/Legivel">Source Code on GitHub</a></li>
<li><a href="Legivel/license.html">License</a></li>
<li><a href="Legivel/release-notes.html">Release Notes</a></li>
<li class="nav-header">Getting started</li>
<li><a href="Legivel/tutorial.html">Sample tutorial</a></li>
<li class="nav-header">Documentation</li>
<li><a href="Legivel/reference/index.html">API Reference</a></li>
</ul>
</div>
</div>
</div>
<a href="https://github.com/fjoppe/Legivel"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"/></a>
</body>
</html>
|
fjoppe/Legivel
|
docs/reference/legivel-customization-mapping-discriminatedunionmappinginfo.html
|
HTML
|
unlicense
| 7,829 |
package org.samovich.cop2800.chapter8;
/**
* Filename BowlingTeam.java
* Created by Valery Samovich
* Written on 6/21/16
*/
public class BowlingTeam {
// declare fields
private String teamName;
private String[] members = new String[4];
/**
* Set(mutator) method for teamName.
* @param team
*/
public void setTeamName(String team) {
this.teamName = team;
}
/**
* Get(accessor) method for team name.
* @return
*/
public String getTeamName() {
return teamName;
}
/**
* Set(mutator) method for members.
* @param number
* @param name
*/
public void setMembers(int number, String name) {
members[number] = name;
}
/**
* Get(accessor) method for members.
* @param number
* @return
*/
public String getMember(int number) {
return members[number];
}
}
|
valerysamovich/java-technologies
|
src/main/java/org/samovich/cop2800/chapter8/BowlingTeam.java
|
Java
|
unlicense
| 913 |
<?php
class Analysis_type extends Doctrine_Record {
public function setTableDefinition() {
$this -> hasColumn('method_id', 'int', 11);
$this -> hasColumn('analysis_type', 'int', 11);
$this -> hasColumn('request_id', 'varchar', 30);
}
public function setUp() {
$this -> setTableName('analysis_type');
}//end setUp
public function getAll() {
$query = Doctrine_Query::create() -> select("*") -> from("columns");
$equipmentData = $query -> execute();
return $equipmentData;
}//end getAll
public function getType($reqid, $mid) {
$query = Doctrine_Query::create() -> select("*")
-> from("analysis_type")
-> where("request_id =?", $reqid)
-> andWhere("method_id=?", $mid);
$equipmentData = $query -> execute() -> toArray();
return $equipmentData;
}//end getAll
}
?>
|
alpho07/NQCL_LIMS
|
application/models/analysis_type.php
|
PHP
|
unlicense
| 829 |
*DECK CPSI
COMPLEX FUNCTION CPSI (ZIN)
C***BEGIN PROLOGUE CPSI
C***PURPOSE Compute the Psi (or Digamma) function.
C***LIBRARY SLATEC (FNLIB)
C***CATEGORY C7C
C***TYPE COMPLEX (PSI-S, DPSI-D, CPSI-C)
C***KEYWORDS DIGAMMA FUNCTION, FNLIB, PSI FUNCTION, SPECIAL FUNCTIONS
C***AUTHOR Fullerton, W., (LANL)
C***DESCRIPTION
C
C PSI(X) calculates the psi (or digamma) function of X. PSI(X)
C is the logarithmic derivative of the gamma function of X.
C
C***REFERENCES (NONE)
C***ROUTINES CALLED CCOT, R1MACH, XERMSG
C***REVISION HISTORY (YYMMDD)
C 780501 DATE WRITTEN
C 890531 Changed all specific intrinsics to generic. (WRB)
C 890531 REVISION DATE from Version 3.2
C 891214 Prologue converted to Version 4.0 format. (BAB)
C 900315 CALLs to XERROR changed to CALLs to XERMSG. (THJ)
C 900727 Added EXTERNAL statement. (WRB)
C***END PROLOGUE CPSI
COMPLEX ZIN, Z, Z2INV, CORR, CCOT
DIMENSION BERN(13)
LOGICAL FIRST
EXTERNAL CCOT
SAVE BERN, PI, NTERM, BOUND, DXREL, RMIN, RBIG, FIRST
DATA BERN( 1) / .8333333333 3333333 E-1 /
DATA BERN( 2) / -.8333333333 3333333 E-2 /
DATA BERN( 3) / .3968253968 2539683 E-2 /
DATA BERN( 4) / -.4166666666 6666667 E-2 /
DATA BERN( 5) / .7575757575 7575758 E-2 /
DATA BERN( 6) / -.2109279609 2796093 E-1 /
DATA BERN( 7) / .8333333333 3333333 E-1 /
DATA BERN( 8) / -.4432598039 2156863 E0 /
DATA BERN( 9) / .3053954330 2701197 E1 /
DATA BERN(10) / -.2645621212 1212121 E2 /
DATA BERN(11) / .2814601449 2753623 E3 /
DATA BERN(12) / -.3454885393 7728938 E4 /
DATA BERN(13) / .5482758333 3333333 E5 /
DATA PI / 3.141592653 589793 E0 /
DATA FIRST /.TRUE./
C***FIRST EXECUTABLE STATEMENT CPSI
IF (FIRST) THEN
NTERM = -0.30*LOG(R1MACH(3))
C MAYBE BOUND = N*(0.1*EPS)**(-1/(2*N-1)) / (PI*EXP(1))
BOUND = 0.1171*NTERM*(0.1*R1MACH(3))**(-1.0/(2*NTERM-1))
DXREL = SQRT(R1MACH(4))
RMIN = EXP (MAX (LOG(R1MACH(1)), -LOG(R1MACH(2))) + 0.011 )
RBIG = 1.0/R1MACH(3)
ENDIF
FIRST = .FALSE.
C
Z = ZIN
X = REAL(Z)
Y = AIMAG(Z)
IF (Y.LT.0.0) Z = CONJG(Z)
C
CORR = (0.0, 0.0)
CABSZ = ABS(Z)
IF (X.GE.0.0 .AND. CABSZ.GT.BOUND) GO TO 50
IF (X.LT.0.0 .AND. ABS(Y).GT.BOUND) GO TO 50
C
IF (CABSZ.LT.BOUND) GO TO 20
C
C USE THE REFLECTION FORMULA FOR REAL(Z) NEGATIVE, ABS(Z) LARGE, AND
C ABS(AIMAG(Y)) SMALL.
C
CORR = -PI*CCOT(PI*Z)
Z = 1.0 - Z
GO TO 50
C
C USE THE RECURSION RELATION FOR ABS(Z) SMALL.
C
20 IF (CABSZ .LT. RMIN) CALL XERMSG ('SLATEC', 'CPSI',
+ 'CPSI CALLED WITH Z SO NEAR 0 THAT CPSI OVERFLOWS', 2, 2)
C
IF (X.GE.(-0.5) .OR. ABS(Y).GT.DXREL) GO TO 30
IF (ABS((Z-AINT(X-0.5))/X) .LT. DXREL) CALL XERMSG ('SLATEC',
+ 'CPSI',
+ 'ANSWER LT HALF PRECISION BECAUSE Z TOO NEAR NEGATIVE INTEGER',
+ 1, 1)
IF (Y .EQ. 0.0 .AND. X .EQ. AINT(X)) CALL XERMSG ('SLATEC',
+ 'CPSI', 'Z IS A NEGATIVE INTEGER', 3, 2)
C
30 N = SQRT(BOUND**2-Y**2) - X + 1.0
DO 40 I=1,N
CORR = CORR - 1.0/Z
Z = Z + 1.0
40 CONTINUE
C
C NOW EVALUATE THE ASYMPTOTIC SERIES FOR SUITABLY LARGE Z.
C
50 IF (CABSZ.GT.RBIG) CPSI = LOG(Z) + CORR
IF (CABSZ.GT.RBIG) GO TO 70
C
CPSI = (0.0, 0.0)
Z2INV = 1.0/Z**2
DO 60 I=1,NTERM
NDX = NTERM + 1 - I
CPSI = BERN(NDX) + Z2INV*CPSI
60 CONTINUE
CPSI = LOG(Z) - 0.5/Z - CPSI*Z2INV + CORR
C
70 IF (Y.LT.0.0) CPSI = CONJG(CPSI)
C
RETURN
END
|
andremirt/v_cond
|
slatec/src/cpsi.f
|
FORTRAN
|
unlicense
| 3,623 |
from subprocess import CalledProcessError
from pyscripts.utilities import run
from pyscripts.utilities import sed_inplace
basics = ['base', 'base-devel', 'sudo', 'wget', 'git']
def install_basic_arch():
### Nicer formatting for pacstrap
sed_inplace("/etc/pacman.conf", "#Color", "Color")
sed_inplace("/etc/pacman.conf", "#TotalDownload", "TotalDownload")
### Enable Multilib
with open("/etc/pacman.conf", "a") as file:
file.write("[multilib]\nInclude = /etc/pacman.d/mirrorlist")
### Update mirrorlist
print(" >> Updating mirror list")
try:
run('reflector --latest 100 --sort rate --protocol https --save /etc/pacman.d/mirrorlist')
except CalledProcessError as error:
print('Updating package mirrorlist failed with message: ', error.output)
### Update system and keyring
print(" >> Updating system and keyring")
try:
run('pacman -Sy --noconfirm')
run('pacman -S archlinux-keyring --noconfirm')
except CalledProcessError as error:
print('Updating system and keyring failed with message: ', error.output)
### Install base packages
print(" >> Going to install arch base packages")
try:
run('pacstrap /mnt '+ ' '.join(basics))
except CalledProcessError as error:
print('Error installing base packages. Message: ', error.output)
print(" >> Installed arch base packages")
### Nicer formatting for pacstrap on installed system
sed_inplace("/mnt/etc/pacman.conf", "#Color", "Color")
sed_inplace("/mnt/etc/pacman.conf", "#TotalDownload", "TotalDownload")
### Enable Multilib on installed system
with open("/mnt/etc/pacman.conf", "a") as file:
file.write("[multilib]\nInclude = /etc/pacman.d/mirrorlist")
|
GPMueller/arch-installer
|
pyscripts/s02_basic_arch.py
|
Python
|
unlicense
| 1,765 |
/*
* 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.accumulo.shell.commands;
import java.util.TreeSet;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.shell.Shell;
import org.apache.accumulo.shell.Shell.Command;
import org.apache.accumulo.shell.ShellUtil;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.MissingArgumentException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.hadoop.io.Text;
public class AddSplitsCommand extends Command {
private Option optSplitsFile, base64Opt;
@Override
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws Exception {
final String tableName = OptUtil.getTableOpt(cl, shellState);
final boolean decode = cl.hasOption(base64Opt.getOpt());
final TreeSet<Text> splits = new TreeSet<>();
if (cl.hasOption(optSplitsFile.getOpt())) {
splits.addAll(ShellUtil.scanFile(cl.getOptionValue(optSplitsFile.getOpt()), decode));
} else {
if (cl.getArgList().isEmpty()) {
throw new MissingArgumentException("No split points specified");
}
for (String s : cl.getArgs()) {
splits.add(new Text(s.getBytes(Shell.CHARSET)));
}
}
if (!shellState.getConnector().tableOperations().exists(tableName)) {
throw new TableNotFoundException(null, tableName, null);
}
shellState.getConnector().tableOperations().addSplits(tableName, splits);
return 0;
}
@Override
public String description() {
return "adds split points to an existing table";
}
@Override
public Options getOptions() {
final Options o = new Options();
optSplitsFile = new Option("sf", "splits-file", true, "file with a newline-separated list of rows to split the table with");
optSplitsFile.setArgName("filename");
base64Opt = new Option("b64", "base64encoded", false, "decode encoded split points (splits file only)");
o.addOption(OptUtil.tableOpt("name of the table to add split points to"));
o.addOption(optSplitsFile);
o.addOption(base64Opt);
return o;
}
@Override
public String usage() {
return getName() + " [<split>{ <split>} ]";
}
@Override
public int numArgs() {
return Shell.NO_FIXED_ARG_LENGTH_CHECK;
}
}
|
mikewalch/accumulo
|
shell/src/main/java/org/apache/accumulo/shell/commands/AddSplitsCommand.java
|
Java
|
apache-2.0
| 3,101 |
<html>
<head>
<title>About 2D barcodes</title>
<link rel="stylesheet" href="style.css" type="text/css"/>
</head>
<body>
<p><b>Barcode Scanner</b> also understands how to read two dimensional barcodes, called <em>QR
Codes</em>. For example, the QR Code below contains a hyperlink to the ZXing Project home page:</p>
<p style="text-align:center"><img src="../images/big-qr.png" alt="QR code"></p>
<p>You can also represent contact information in a QR Code, and put it on a business card or web
site. When you scan it, the results screen provides a choice of actions:</p>
<p style="text-align:center"><img src="../images/contact-results-screen.jpg" alt="Contact results screen"></p>
<p>Besides URLs and contact info, QR Codes can also contain:</p>
<ul>
<li>Calendar events, which you can add to your Calendar</li>
<li>Phone numbers, which you can dial</li>
<li>SMS numbers, which you can text message</li>
<li>Email addresses, which you can email</li>
<li>Geographic coordinates, which you can open in Maps</li>
<li>Plain text, which you can read, then share with a friend</li>
</ul>
</body>
</html>
|
zilaiyedaren/zxing-iphone
|
android/assets/html/about2d.html
|
HTML
|
apache-2.0
| 1,112 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>GAVcoin</title>
</head>
<body>
<div id="container"></div>
<script src="/parity-utils/parity.js"></script>
<script src="dist/gavcoin.js"></script>
</body>
</html>
|
gavofyork/gavcoin
|
src/index.html
|
HTML
|
apache-2.0
| 364 |
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-card-content',
template: `
<div class="card-content">
<div class="content">
<div class="name">{{ name }}</div>
<div class="description">{{ description }}</div>
</div>
</div>
`
})
export class CardContentComponent implements OnInit {
@Input() name;
@Input() description;
ngOnInit() {}
}
|
wesleyegberto/courses-projects
|
frontend/angular/angular-architecture/labs/http-interceptors/end/src/app/shared/card-content.component.ts
|
TypeScript
|
apache-2.0
| 422 |
/* $Id: layout-custom.c,v 1.1.1.2 2011/08/17 18:40:04 jmmv Exp $ */
/*
* Copyright (c) 2010 Nicholas Marriott <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <ctype.h>
#include <string.h>
#include "tmux.h"
struct layout_cell *layout_find_bottomright(struct layout_cell *);
u_short layout_checksum(const char *);
int layout_append(struct layout_cell *, char *, size_t);
struct layout_cell *layout_construct(struct layout_cell *, const char **);
void layout_assign(struct window_pane **, struct layout_cell *);
/* Find the bottom-right cell. */
struct layout_cell *
layout_find_bottomright(struct layout_cell *lc)
{
if (lc->type == LAYOUT_WINDOWPANE)
return (lc);
lc = TAILQ_LAST(&lc->cells, layout_cells);
return (layout_find_bottomright(lc));
}
/* Calculate layout checksum. */
u_short
layout_checksum(const char *layout)
{
u_short csum;
csum = 0;
for (; *layout != '\0'; layout++) {
csum = (csum >> 1) + ((csum & 1) << 15);
csum += *layout;
}
return (csum);
}
/* Dump layout as a string. */
char *
layout_dump(struct window *w)
{
char layout[BUFSIZ], *out;
*layout = '\0';
if (layout_append(w->layout_root, layout, sizeof layout) != 0)
return (NULL);
xasprintf(&out, "%4x,%s", layout_checksum(layout), layout);
return (out);
}
/* Append information for a single cell. */
int
layout_append(struct layout_cell *lc, char *buf, size_t len)
{
struct layout_cell *lcchild;
char tmp[64];
size_t tmplen;
const char *brackets = "][";
if (len == 0)
return (-1);
tmplen = xsnprintf(tmp, sizeof tmp,
"%ux%u,%u,%u", lc->sx, lc->sy, lc->xoff, lc->yoff);
if (tmplen > (sizeof tmp) - 1)
return (-1);
if (strlcat(buf, tmp, len) >= len)
return (-1);
switch (lc->type) {
case LAYOUT_LEFTRIGHT:
brackets = "}{";
/* FALLTHROUGH */
case LAYOUT_TOPBOTTOM:
if (strlcat(buf, &brackets[1], len) >= len)
return (-1);
TAILQ_FOREACH(lcchild, &lc->cells, entry) {
if (layout_append(lcchild, buf, len) != 0)
return (-1);
if (strlcat(buf, ",", len) >= len)
return (-1);
}
buf[strlen(buf) - 1] = brackets[0];
break;
case LAYOUT_WINDOWPANE:
break;
}
return (0);
}
/* Parse a layout string and arrange window as layout. */
int
layout_parse(struct window *w, const char *layout)
{
struct layout_cell *lc, *lcchild;
struct window_pane *wp;
u_int npanes, ncells, sx, sy;
u_short csum;
/* Check validity. */
if (sscanf(layout, "%hx,", &csum) != 1)
return (-1);
layout += 5;
if (csum != layout_checksum(layout))
return (-1);
/* Build the layout. */
lc = layout_construct(NULL, &layout);
if (lc == NULL)
return (-1);
if (*layout != '\0')
goto fail;
/* Check this window will fit into the layout. */
for (;;) {
npanes = window_count_panes(w);
ncells = layout_count_cells(lc);
if (npanes > ncells)
goto fail;
if (npanes == ncells)
break;
/* Fewer panes than cells - close the bottom right. */
lcchild = layout_find_bottomright(lc);
layout_destroy_cell(lcchild, &lc);
}
/* Save the old window size and resize to the layout size. */
sx = w->sx; sy = w->sy;
window_resize(w, lc->sx, lc->sy);
/* Destroy the old layout and swap to the new. */
layout_free_cell(w->layout_root);
w->layout_root = lc;
/* Assign the panes into the cells. */
wp = TAILQ_FIRST(&w->panes);
layout_assign(&wp, lc);
/* Update pane offsets and sizes. */
layout_fix_offsets(lc);
layout_fix_panes(w, lc->sx, lc->sy);
/* Then resize the layout back to the original window size. */
layout_resize(w, sx, sy);
window_resize(w, sx, sy);
layout_print_cell(lc, __func__, 0);
return (0);
fail:
layout_free_cell(lc);
return (-1);
}
/* Assign panes into cells. */
void
layout_assign(struct window_pane **wp, struct layout_cell *lc)
{
struct layout_cell *lcchild;
switch (lc->type) {
case LAYOUT_WINDOWPANE:
layout_make_leaf(lc, *wp);
*wp = TAILQ_NEXT(*wp, entry);
return;
case LAYOUT_LEFTRIGHT:
case LAYOUT_TOPBOTTOM:
TAILQ_FOREACH(lcchild, &lc->cells, entry)
layout_assign(wp, lcchild);
return;
}
}
/* Construct a cell from all or part of a layout tree. */
struct layout_cell *
layout_construct(struct layout_cell *lcparent, const char **layout)
{
struct layout_cell *lc, *lcchild;
u_int sx, sy, xoff, yoff;
if (!isdigit((u_char) **layout))
return (NULL);
if (sscanf(*layout, "%ux%u,%u,%u", &sx, &sy, &xoff, &yoff) != 4)
return (NULL);
while (isdigit((u_char) **layout))
(*layout)++;
if (**layout != 'x')
return (NULL);
(*layout)++;
while (isdigit((u_char) **layout))
(*layout)++;
if (**layout != ',')
return (NULL);
(*layout)++;
while (isdigit((u_char) **layout))
(*layout)++;
if (**layout != ',')
return (NULL);
(*layout)++;
while (isdigit((u_char) **layout))
(*layout)++;
lc = layout_create_cell(lcparent);
lc->sx = sx;
lc->sy = sy;
lc->xoff = xoff;
lc->yoff = yoff;
switch (**layout) {
case ',':
case '}':
case ']':
case '\0':
return (lc);
case '{':
lc->type = LAYOUT_LEFTRIGHT;
break;
case '[':
lc->type = LAYOUT_TOPBOTTOM;
break;
default:
goto fail;
}
do {
(*layout)++;
lcchild = layout_construct(lc, layout);
if (lcchild == NULL)
goto fail;
TAILQ_INSERT_TAIL(&lc->cells, lcchild, entry);
} while (**layout == ',');
switch (lc->type) {
case LAYOUT_LEFTRIGHT:
if (**layout != '}')
goto fail;
break;
case LAYOUT_TOPBOTTOM:
if (**layout != ']')
goto fail;
break;
default:
goto fail;
}
(*layout)++;
return (lc);
fail:
layout_free_cell(lc);
return (NULL);
}
|
ayyucedemirbas/Minix-Source-Code
|
minix-master/external/bsd/tmux/dist/layout-custom.c
|
C
|
apache-2.0
| 6,265 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_181) on Sun Sep 30 15:32:15 WEST 2018 -->
<title>Constant Field Values</title>
<meta name="date" content="2018-09-30">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Constant Field Values";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li><a href="overview-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-all.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?constant-values.html" target="_top">Frames</a></li>
<li><a href="constant-values.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Constant Field Values" class="title">Constant Field Values</h1>
<h2 title="Contents">Contents</h2>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li><a href="overview-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-all.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?constant-values.html" target="_top">Frames</a></li>
<li><a href="constant-values.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
bergerch/library
|
doc/constant-values.html
|
HTML
|
apache-2.0
| 3,546 |
import testUtils from '../../util/testUtils';
var TestResults = require('@cdo/apps/constants.js').TestResults;
import blockUtils from '@cdo/apps/block_utils';
testUtils.setupLocale('craft');
import craftMsg from '@cdo/apps/craft/locale';
let _ = require('@cdo/apps/lodash');
let blankPlane = _.range(100).map(function () {
return "";
});
let actionPlane = _.clone(blankPlane);
actionPlane[(4 * 10) + 6] = "sheep";
module.exports = {
app: "craft",
skinId: 'craft',
levelDefinition: {
isTestLevel: true,
playerStartPosition: [3, 4],
playerStartDirection: 1,
groundPlane: _.range(100).map(() => { return "grass"; }),
groundDecorationPlane: blankPlane,
actionPlane: actionPlane,
fluffPlane: blankPlane,
verificationFunction: (verificationAPI => {
return verificationAPI.isPlayerNextTo("sheep");
}).toString(),
requiredBlocks: '',
ideal: 3,
freePlay: false
},
tests: [
{
description: "walk forward next to sheep",
expected: {
result: true,
testResult: TestResults.ALL_PASS
},
xml: '<xml>' + blockUtils.blocksFromList([
'craft_moveForward',
'craft_moveForward'
]) + "</xml>"
},
{
description: "walk forward turn right",
expected: {
result: false,
testResult: TestResults.APP_SPECIFIC_FAIL
},
xml: '<xml><block type="craft_moveForward"><next><block type="craft_turn"><title name="DIR">right</title></block></next></block></xml>'
},
{
description: "walk forward with too few blocks to reach sheep",
expected: {
result: false,
testResult: TestResults.TOO_FEW_BLOCKS_FAIL
},
xml: '<xml>' + blockUtils.blocksFromList([
'craft_moveForward'
]) + '</xml>'
},
{
description: "walk forward completing level with too many blocks (bumping into sheep)",
expected: {
result: true,
testResult: TestResults.TOO_MANY_BLOCKS_FAIL
},
xml: '<xml>' + blockUtils.blocksFromList([
'craft_moveForward',
'craft_moveForward',
'craft_moveForward'
]) + "</xml>"
},
]
};
|
pickettd/code-dot-org
|
apps/test/solutions/craft/movement.js
|
JavaScript
|
apache-2.0
| 2,165 |
/*
* Copyright (c) 2018 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef ZEPHYR_INCLUDE_LOGGING_LOG_H_
#define ZEPHYR_INCLUDE_LOGGING_LOG_H_
#include <logging/log_instance.h>
#include <logging/log_core.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Logging
* @defgroup logging Logging
* @{
* @}
*/
/**
* @brief Logger API
* @defgroup log_api Logging API
* @ingroup logger
* @{
*/
/**
* @brief Writes an ERROR level message to the log.
*
* @details It's meant to report severe errors, such as those from which it's
* not possible to recover.
*
* @param ... A string optionally containing printk valid conversion specifier,
* followed by as many values as specifiers.
*/
#define LOG_ERR(...) Z_LOG(LOG_LEVEL_ERR, __VA_ARGS__)
/**
* @brief Writes a WARNING level message to the log.
*
* @details It's meant to register messages related to unusual situations that
* are not necessarily errors.
*
* @param ... A string optionally containing printk valid conversion specifier,
* followed by as many values as specifiers.
*/
#define LOG_WRN(...) Z_LOG(LOG_LEVEL_WRN, __VA_ARGS__)
/**
* @brief Writes an INFO level message to the log.
*
* @details It's meant to write generic user oriented messages.
*
* @param ... A string optionally containing printk valid conversion specifier,
* followed by as many values as specifiers.
*/
#define LOG_INF(...) Z_LOG(LOG_LEVEL_INF, __VA_ARGS__)
/**
* @brief Writes a DEBUG level message to the log.
*
* @details It's meant to write developer oriented information.
*
* @param ... A string optionally containing printk valid conversion specifier,
* followed by as many values as specifiers.
*/
#define LOG_DBG(...) Z_LOG(LOG_LEVEL_DBG, __VA_ARGS__)
/**
* @brief Unconditionally print raw log message.
*
* The result is same as if printk was used but it goes through logging
* infrastructure thus utilizes logging mode, e.g. deferred mode.
*
* @param ... A string optionally containing printk valid conversion specifier,
* followed by as many values as specifiers.
*/
#define LOG_PRINTK(...) Z_LOG_PRINTK(__VA_ARGS__)
/**
* @brief Writes an ERROR level message associated with the instance to the log.
*
* Message is associated with specific instance of the module which has
* independent filtering settings (if runtime filtering is enabled) and
* message prefix (\<module_name\>.\<instance_name\>). It's meant to report
* severe errors, such as those from which it's not possible to recover.
*
* @param _log_inst Pointer to the log structure associated with the instance.
* @param ... A string optionally containing printk valid conversion specifier,
* followed by as many values as specifiers.
*/
#define LOG_INST_ERR(_log_inst, ...) \
Z_LOG_INSTANCE(LOG_LEVEL_ERR, _log_inst, __VA_ARGS__)
/**
* @brief Writes a WARNING level message associated with the instance to the
* log.
*
* Message is associated with specific instance of the module which has
* independent filtering settings (if runtime filtering is enabled) and
* message prefix (\<module_name\>.\<instance_name\>). It's meant to register
* messages related to unusual situations that are not necessarily errors.
*
* @param _log_inst Pointer to the log structure associated with the instance.
* @param ... A string optionally containing printk valid conversion
* specifier, followed by as many values as specifiers.
*/
#define LOG_INST_WRN(_log_inst, ...) \
Z_LOG_INSTANCE(LOG_LEVEL_WRN, _log_inst, __VA_ARGS__)
/**
* @brief Writes an INFO level message associated with the instance to the log.
*
* Message is associated with specific instance of the module which has
* independent filtering settings (if runtime filtering is enabled) and
* message prefix (\<module_name\>.\<instance_name\>). It's meant to write
* generic user oriented messages.
*
* @param _log_inst Pointer to the log structure associated with the instance.
* @param ... A string optionally containing printk valid conversion specifier,
* followed by as many values as specifiers.
*/
#define LOG_INST_INF(_log_inst, ...) \
Z_LOG_INSTANCE(LOG_LEVEL_INF, _log_inst, __VA_ARGS__)
/**
* @brief Writes a DEBUG level message associated with the instance to the log.
*
* Message is associated with specific instance of the module which has
* independent filtering settings (if runtime filtering is enabled) and
* message prefix (\<module_name\>.\<instance_name\>). It's meant to write
* developer oriented information.
*
* @param _log_inst Pointer to the log structure associated with the instance.
* @param ... A string optionally containing printk valid conversion specifier,
* followed by as many values as specifiers.
*/
#define LOG_INST_DBG(_log_inst, ...) \
Z_LOG_INSTANCE(LOG_LEVEL_DBG, _log_inst, __VA_ARGS__)
/**
* @brief Writes an ERROR level hexdump message to the log.
*
* @details It's meant to report severe errors, such as those from which it's
* not possible to recover.
*
* @param _data Pointer to the data to be logged.
* @param _length Length of data (in bytes).
* @param _str Persistent, raw string.
*/
#define LOG_HEXDUMP_ERR(_data, _length, _str) \
Z_LOG_HEXDUMP(LOG_LEVEL_ERR, _data, _length, _str)
/**
* @brief Writes a WARNING level message to the log.
*
* @details It's meant to register messages related to unusual situations that
* are not necessarily errors.
*
* @param _data Pointer to the data to be logged.
* @param _length Length of data (in bytes).
* @param _str Persistent, raw string.
*/
#define LOG_HEXDUMP_WRN(_data, _length, _str) \
Z_LOG_HEXDUMP(LOG_LEVEL_WRN, _data, _length, _str)
/**
* @brief Writes an INFO level message to the log.
*
* @details It's meant to write generic user oriented messages.
*
* @param _data Pointer to the data to be logged.
* @param _length Length of data (in bytes).
* @param _str Persistent, raw string.
*/
#define LOG_HEXDUMP_INF(_data, _length, _str) \
Z_LOG_HEXDUMP(LOG_LEVEL_INF, _data, _length, _str)
/**
* @brief Writes a DEBUG level message to the log.
*
* @details It's meant to write developer oriented information.
*
* @param _data Pointer to the data to be logged.
* @param _length Length of data (in bytes).
* @param _str Persistent, raw string.
*/
#define LOG_HEXDUMP_DBG(_data, _length, _str) \
Z_LOG_HEXDUMP(LOG_LEVEL_DBG, _data, _length, _str)
/**
* @brief Writes an ERROR hexdump message associated with the instance to the
* log.
*
* Message is associated with specific instance of the module which has
* independent filtering settings (if runtime filtering is enabled) and
* message prefix (\<module_name\>.\<instance_name\>). It's meant to report
* severe errors, such as those from which it's not possible to recover.
*
* @param _log_inst Pointer to the log structure associated with the instance.
* @param _data Pointer to the data to be logged.
* @param _length Length of data (in bytes).
* @param _str Persistent, raw string.
*/
#define LOG_INST_HEXDUMP_ERR(_log_inst, _data, _length, _str) \
Z_LOG_HEXDUMP_INSTANCE(LOG_LEVEL_ERR, _log_inst, _data, _length, _str)
/**
* @brief Writes a WARNING level hexdump message associated with the instance to
* the log.
*
* @details It's meant to register messages related to unusual situations that
* are not necessarily errors.
*
* @param _log_inst Pointer to the log structure associated with the instance.
* @param _data Pointer to the data to be logged.
* @param _length Length of data (in bytes).
* @param _str Persistent, raw string.
*/
#define LOG_INST_HEXDUMP_WRN(_log_inst, _data, _length, _str) \
Z_LOG_HEXDUMP_INSTANCE(LOG_LEVEL_WRN, _log_inst, _data, _length, _str)
/**
* @brief Writes an INFO level hexdump message associated with the instance to
* the log.
*
* @details It's meant to write generic user oriented messages.
*
* @param _log_inst Pointer to the log structure associated with the instance.
* @param _data Pointer to the data to be logged.
* @param _length Length of data (in bytes).
* @param _str Persistent, raw string.
*/
#define LOG_INST_HEXDUMP_INF(_log_inst, _data, _length, _str) \
Z_LOG_HEXDUMP_INSTANCE(LOG_LEVEL_INF, _log_inst, _data, _length, _str)
/**
* @brief Writes a DEBUG level hexdump message associated with the instance to
* the log.
*
* @details It's meant to write developer oriented information.
*
* @param _log_inst Pointer to the log structure associated with the instance.
* @param _data Pointer to the data to be logged.
* @param _length Length of data (in bytes).
* @param _str Persistent, raw string.
*/
#define LOG_INST_HEXDUMP_DBG(_log_inst, _data, _length, _str) \
Z_LOG_HEXDUMP_INSTANCE(LOG_LEVEL_DBG, _log_inst, _data, _length, _str)
/**
* @brief Writes an formatted string to the log.
*
* @details Conditionally compiled (see CONFIG_LOG_PRINTK). Function provides
* printk functionality. It is inefficient compared to standard logging
* because string formatting is performed in the call context and not deferred
* to the log processing context (@ref log_process).
*
* @param fmt Formatted string to output.
* @param ap Variable parameters.
*/
void z_log_printk(const char *fmt, va_list ap);
static inline void log_printk(const char *fmt, va_list ap)
{
z_log_printk(fmt, ap);
}
/** @brief Copy transient string to a buffer from internal, logger pool.
*
* Function should be used when transient string is intended to be logged.
* Logger allocates a buffer and copies input string returning a pointer to the
* copy. Logger ensures that buffer is freed when logger message is freed.
*
* Depending on configuration, this function may do nothing and just pass
* along the supplied string pointer. Do not rely on this function to always
* make a copy!
*
* @param str Transient string.
*
* @return Copy of the string or default string if buffer could not be
* allocated. String may be truncated if input string does not fit in
* a buffer from the pool (see CONFIG_LOG_STRDUP_MAX_STRING). In
* some configurations, the original string pointer is returned.
*/
char *z_log_strdup(const char *str);
static inline char *log_strdup(const char *str)
{
if (IS_ENABLED(CONFIG_LOG_MINIMAL) || IS_ENABLED(CONFIG_LOG2)) {
return (char *)str;
}
return z_log_strdup(str);
}
#ifdef __cplusplus
}
#define LOG_IN_CPLUSPLUS 1
#endif
/* Macro expects that optionally on second argument local log level is provided.
* If provided it is returned, otherwise default log level is returned or
* LOG_LEVEL, if it was locally defined.
*/
#if !defined(CONFIG_LOG)
#define _LOG_LEVEL_RESOLVE(...) LOG_LEVEL_NONE
#else
#define _LOG_LEVEL_RESOLVE(...) \
Z_LOG_EVAL(LOG_LEVEL, \
(GET_ARG_N(2, __VA_ARGS__, LOG_LEVEL)), \
(GET_ARG_N(2, __VA_ARGS__, CONFIG_LOG_DEFAULT_LEVEL)))
#endif
/* Return first argument */
#define _LOG_ARG1(arg1, ...) arg1
#define _LOG_MODULE_CONST_DATA_CREATE(_name, _level) \
IF_ENABLED(LOG_IN_CPLUSPLUS, (extern)) \
const struct log_source_const_data LOG_ITEM_CONST_DATA(_name) \
__attribute__ ((section("." STRINGIFY(LOG_ITEM_CONST_DATA(_name))))) \
__attribute__((used)) = { \
.name = STRINGIFY(_name), \
.level = _level \
}
#define _LOG_MODULE_DYNAMIC_DATA_CREATE(_name) \
struct log_source_dynamic_data LOG_ITEM_DYNAMIC_DATA(_name) \
__attribute__ ((section("." STRINGIFY( \
LOG_ITEM_DYNAMIC_DATA(_name)))) \
) \
__attribute__((used))
#define _LOG_MODULE_DYNAMIC_DATA_COND_CREATE(_name) \
IF_ENABLED(CONFIG_LOG_RUNTIME_FILTERING, \
(_LOG_MODULE_DYNAMIC_DATA_CREATE(_name);))
#define _LOG_MODULE_DATA_CREATE(_name, _level) \
_LOG_MODULE_CONST_DATA_CREATE(_name, _level); \
_LOG_MODULE_DYNAMIC_DATA_COND_CREATE(_name)
/**
* @brief Create module-specific state and register the module with Logger.
*
* This macro normally must be used after including <logging/log.h> to
* complete the initialization of the module.
*
* Module registration can be skipped in two cases:
*
* - The module consists of more than one file, and another file
* invokes this macro. (LOG_MODULE_DECLARE() should be used instead
* in all of the module's other files.)
* - Instance logging is used and there is no need to create module entry. In
* that case LOG_LEVEL_SET() should be used to set log level used within the
* file.
*
* Macro accepts one or two parameters:
* - module name
* - optional log level. If not provided then default log level is used in
* the file.
*
* Example usage:
* - LOG_MODULE_REGISTER(foo, CONFIG_FOO_LOG_LEVEL)
* - LOG_MODULE_REGISTER(foo)
*
*
* @note The module's state is defined, and the module is registered,
* only if LOG_LEVEL for the current source file is non-zero or
* it is not defined and CONFIG_LOG_DEFAULT_LEVEL is non-zero.
* In other cases, this macro has no effect.
* @see LOG_MODULE_DECLARE
*/
#define LOG_MODULE_REGISTER(...) \
Z_LOG_EVAL( \
_LOG_LEVEL_RESOLVE(__VA_ARGS__), \
(_LOG_MODULE_DATA_CREATE(GET_ARG_N(1, __VA_ARGS__), \
_LOG_LEVEL_RESOLVE(__VA_ARGS__))),\
()/*Empty*/ \
) \
LOG_MODULE_DECLARE(__VA_ARGS__)
/**
* @brief Macro for declaring a log module (not registering it).
*
* Modules which are split up over multiple files must have exactly
* one file use LOG_MODULE_REGISTER() to create module-specific state
* and register the module with the logger core.
*
* The other files in the module should use this macro instead to
* declare that same state. (Otherwise, LOG_INF() etc. will not be
* able to refer to module-specific state variables.)
*
* Macro accepts one or two parameters:
* - module name
* - optional log level. If not provided then default log level is used in
* the file.
*
* Example usage:
* - LOG_MODULE_DECLARE(foo, CONFIG_FOO_LOG_LEVEL)
* - LOG_MODULE_DECLARE(foo)
*
* @note The module's state is declared only if LOG_LEVEL for the
* current source file is non-zero or it is not defined and
* CONFIG_LOG_DEFAULT_LEVEL is non-zero. In other cases,
* this macro has no effect.
* @see LOG_MODULE_REGISTER
*/
#define LOG_MODULE_DECLARE(...) \
extern const struct log_source_const_data \
LOG_ITEM_CONST_DATA(GET_ARG_N(1, __VA_ARGS__)); \
extern struct log_source_dynamic_data \
LOG_ITEM_DYNAMIC_DATA(GET_ARG_N(1, __VA_ARGS__)); \
\
static const struct log_source_const_data * \
__log_current_const_data __unused = \
_LOG_LEVEL_RESOLVE(__VA_ARGS__) ? \
&LOG_ITEM_CONST_DATA(GET_ARG_N(1, __VA_ARGS__)) : \
NULL; \
\
static struct log_source_dynamic_data * \
__log_current_dynamic_data __unused = \
(_LOG_LEVEL_RESOLVE(__VA_ARGS__) && \
IS_ENABLED(CONFIG_LOG_RUNTIME_FILTERING)) ? \
&LOG_ITEM_DYNAMIC_DATA(GET_ARG_N(1, __VA_ARGS__)) : \
NULL; \
\
static const uint32_t __log_level __unused = \
_LOG_LEVEL_RESOLVE(__VA_ARGS__)
/**
* @brief Macro for setting log level in the file or function where instance
* logging API is used.
*
* @param level Level used in file or in function.
*
*/
#define LOG_LEVEL_SET(level) static const uint32_t __log_level __unused = \
Z_LOG_RESOLVED_LEVEL(level, 0)
/*
* Eclipse CDT parser is sometimes confused by logging API code and freezes the
* whole IDE. Following lines hides LOG_x macros from CDT.
*/
#if defined(__CDT_PARSER__)
#undef LOG_ERR
#undef LOG_WRN
#undef LOG_INF
#undef LOG_DBG
#undef LOG_HEXDUMP_ERR
#undef LOG_HEXDUMP_WRN
#undef LOG_HEXDUMP_INF
#undef LOG_HEXDUMP_DBG
#define LOG_ERR(...) (void) 0
#define LOG_WRN(...) (void) 0
#define LOG_DBG(...) (void) 0
#define LOG_INF(...) (void) 0
#define LOG_HEXDUMP_ERR(...) (void) 0
#define LOG_HEXDUMP_WRN(...) (void) 0
#define LOG_HEXDUMP_DBG(...) (void) 0
#define LOG_HEXDUMP_INF(...) (void) 0
#endif
/**
* @}
*/
#endif /* ZEPHYR_INCLUDE_LOGGING_LOG_H_ */
|
finikorg/zephyr
|
include/logging/log.h
|
C
|
apache-2.0
| 16,180 |
// Copyright 2012 Cloudera 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.
#include "runtime/descriptors.h"
#include <boost/algorithm/string/join.hpp>
#include <gutil/strings/substitute.h>
#include <ios>
#include <sstream>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/IR/DataLayout.h>
#include "codegen/llvm-codegen.h"
#include "common/object-pool.h"
#include "gen-cpp/Descriptors_types.h"
#include "gen-cpp/PlanNodes_types.h"
#include "exprs/expr.h"
#include "runtime/runtime-state.h"
#include "common/names.h"
using boost::algorithm::join;
using namespace llvm;
using namespace strings;
namespace impala {
string NullIndicatorOffset::DebugString() const {
stringstream out;
out << "(offset=" << byte_offset
<< " mask=" << hex << static_cast<int>(bit_mask) << dec << ")";
return out.str();
}
ostream& operator<<(ostream& os, const NullIndicatorOffset& null_indicator) {
os << null_indicator.DebugString();
return os;
}
SlotDescriptor::SlotDescriptor(
const TSlotDescriptor& tdesc, const TupleDescriptor* parent,
const TupleDescriptor* collection_item_descriptor)
: id_(tdesc.id),
type_(ColumnType::FromThrift(tdesc.slotType)),
parent_(parent),
collection_item_descriptor_(collection_item_descriptor),
col_path_(tdesc.materializedPath),
tuple_offset_(tdesc.byteOffset),
null_indicator_offset_(tdesc.nullIndicatorByte, tdesc.nullIndicatorBit),
slot_idx_(tdesc.slotIdx),
slot_size_(type_.GetByteSize()),
field_idx_(-1),
is_materialized_(tdesc.isMaterialized),
is_null_fn_(NULL),
set_not_null_fn_(NULL),
set_null_fn_(NULL) {
DCHECK_NE(type_.type, TYPE_STRUCT);
DCHECK(parent_ != NULL) << tdesc.parent;
if (type_.IsCollectionType()) {
DCHECK(tdesc.__isset.itemTupleId);
DCHECK(collection_item_descriptor_ != NULL) << tdesc.itemTupleId;
} else {
DCHECK(!tdesc.__isset.itemTupleId);
DCHECK(collection_item_descriptor == NULL);
}
}
bool SlotDescriptor::ColPathLessThan(const SlotDescriptor* a, const SlotDescriptor* b) {
int common_levels = min(a->col_path().size(), b->col_path().size());
for (int i = 0; i < common_levels; ++i) {
if (a->col_path()[i] == b->col_path()[i]) continue;
return a->col_path()[i] < b->col_path()[i];
}
return a->col_path().size() < b->col_path().size();
}
string SlotDescriptor::DebugString() const {
stringstream out;
out << "Slot(id=" << id_ << " type=" << type_.DebugString()
<< " col_path=[";
if (col_path_.size() > 0) out << col_path_[0];
for (int i = 1; i < col_path_.size(); ++i) {
out << ",";
out << col_path_[i];
}
out << "]";
if (collection_item_descriptor_ != NULL) {
out << " collection_item_tuple_id=" << collection_item_descriptor_->id();
}
out << " offset=" << tuple_offset_ << " null=" << null_indicator_offset_.DebugString()
<< " slot_idx=" << slot_idx_ << " field_idx=" << field_idx_
<< ")";
return out.str();
}
ColumnDescriptor::ColumnDescriptor(const TColumnDescriptor& tdesc)
: name_(tdesc.name),
type_(ColumnType::FromThrift(tdesc.type)) {
}
string ColumnDescriptor::DebugString() const {
return Substitute("$0: $1", name_, type_.DebugString());
}
TableDescriptor::TableDescriptor(const TTableDescriptor& tdesc)
: name_(tdesc.tableName),
database_(tdesc.dbName),
id_(tdesc.id),
num_clustering_cols_(tdesc.numClusteringCols) {
for (int i = 0; i < tdesc.columnDescriptors.size(); ++i) {
col_descs_.push_back(ColumnDescriptor(tdesc.columnDescriptors[i]));
}
}
string TableDescriptor::DebugString() const {
vector<string> cols;
BOOST_FOREACH(const ColumnDescriptor& col_desc, col_descs_) {
cols.push_back(col_desc.DebugString());
}
stringstream out;
out << "#cols=" << num_cols() << " #clustering_cols=" << num_clustering_cols_;
out << " cols=[";
out << join(cols, ", ");
out << "]";
return out.str();
}
HdfsPartitionDescriptor::HdfsPartitionDescriptor(const THdfsPartition& thrift_partition,
ObjectPool* pool)
: line_delim_(thrift_partition.lineDelim),
field_delim_(thrift_partition.fieldDelim),
collection_delim_(thrift_partition.collectionDelim),
escape_char_(thrift_partition.escapeChar),
block_size_(thrift_partition.blockSize),
location_(thrift_partition.location),
id_(thrift_partition.id),
exprs_prepared_(false),
exprs_opened_(false),
exprs_closed_(false),
file_format_(thrift_partition.fileFormat),
object_pool_(pool) {
for (int i = 0; i < thrift_partition.partitionKeyExprs.size(); ++i) {
ExprContext* ctx;
// TODO: Move to dedicated Init method and treat Status return correctly
Status status = Expr::CreateExprTree(object_pool_,
thrift_partition.partitionKeyExprs[i], &ctx);
DCHECK(status.ok());
partition_key_value_ctxs_.push_back(ctx);
}
}
Status HdfsPartitionDescriptor::PrepareExprs(RuntimeState* state) {
if (!exprs_prepared_) {
// TODO: RowDescriptor should arguably be optional in Prepare for known literals
exprs_prepared_ = true;
// Partition exprs are not used in the codegen case. Don't codegen them.
RETURN_IF_ERROR(Expr::Prepare(partition_key_value_ctxs_, state, RowDescriptor(),
state->instance_mem_tracker()));
}
return Status::OK();
}
Status HdfsPartitionDescriptor::OpenExprs(RuntimeState* state) {
if (exprs_opened_) return Status::OK();
exprs_opened_ = true;
return Expr::Open(partition_key_value_ctxs_, state);
}
void HdfsPartitionDescriptor::CloseExprs(RuntimeState* state) {
if (exprs_closed_ || !exprs_prepared_) return;
exprs_closed_ = true;
Expr::Close(partition_key_value_ctxs_, state);
}
string HdfsPartitionDescriptor::DebugString() const {
stringstream out;
out << " file_format=" << file_format_ << "'"
<< " line_delim='" << line_delim_ << "'"
<< " field_delim='" << field_delim_ << "'"
<< " coll_delim='" << collection_delim_ << "'"
<< " escape_char='" << escape_char_ << "')";
return out.str();
}
string DataSourceTableDescriptor::DebugString() const {
stringstream out;
out << "DataSourceTable(" << TableDescriptor::DebugString() << ")";
return out.str();
}
HdfsTableDescriptor::HdfsTableDescriptor(const TTableDescriptor& tdesc,
ObjectPool* pool)
: TableDescriptor(tdesc),
hdfs_base_dir_(tdesc.hdfsTable.hdfsBaseDir),
null_partition_key_value_(tdesc.hdfsTable.nullPartitionKeyValue),
null_column_value_(tdesc.hdfsTable.nullColumnValue),
object_pool_(pool) {
map<int64_t, THdfsPartition>::const_iterator it;
for (it = tdesc.hdfsTable.partitions.begin(); it != tdesc.hdfsTable.partitions.end();
++it) {
HdfsPartitionDescriptor* partition = new HdfsPartitionDescriptor(it->second, pool);
object_pool_->Add(partition);
partition_descriptors_[it->first] = partition;
}
avro_schema_ = tdesc.hdfsTable.__isset.avroSchema ? tdesc.hdfsTable.avroSchema : "";
}
string HdfsTableDescriptor::DebugString() const {
stringstream out;
out << "HdfsTable(" << TableDescriptor::DebugString()
<< " hdfs_base_dir='" << hdfs_base_dir_ << "'";
out << " partitions=[";
vector<string> partition_strings;
map<int64_t, HdfsPartitionDescriptor*>::const_iterator it;
for (it = partition_descriptors_.begin(); it != partition_descriptors_.end(); ++it) {
stringstream s;
s << " (id: " << it->first << ", partition: " << it->second->DebugString() << ")";
partition_strings.push_back(s.str());
}
out << join(partition_strings, ",") << "]";
out << " null_partition_key_value='" << null_partition_key_value_ << "'";
out << " null_column_value='" << null_column_value_ << "'";
return out.str();
}
HBaseTableDescriptor::HBaseTableDescriptor(const TTableDescriptor& tdesc)
: TableDescriptor(tdesc),
table_name_(tdesc.hbaseTable.tableName) {
for (int i = 0; i < tdesc.hbaseTable.families.size(); ++i) {
bool is_binary_encoded = tdesc.hbaseTable.__isset.binary_encoded &&
tdesc.hbaseTable.binary_encoded[i];
cols_.push_back(HBaseTableDescriptor::HBaseColumnDescriptor(
tdesc.hbaseTable.families[i], tdesc.hbaseTable.qualifiers[i], is_binary_encoded));
}
}
string HBaseTableDescriptor::DebugString() const {
stringstream out;
out << "HBaseTable(" << TableDescriptor::DebugString() << " table=" << table_name_;
out << " cols=[";
for (int i = 0; i < cols_.size(); ++i) {
out << (i > 0 ? " " : "") << cols_[i].family << ":" << cols_[i].qualifier << ":"
<< cols_[i].binary_encoded;
}
out << "])";
return out.str();
}
TupleDescriptor::TupleDescriptor(const TTupleDescriptor& tdesc)
: id_(tdesc.id),
table_desc_(NULL),
byte_size_(tdesc.byteSize),
num_null_bytes_(tdesc.numNullBytes),
num_materialized_slots_(0),
slots_(),
has_varlen_slots_(false),
tuple_path_(tdesc.tuplePath),
llvm_struct_(NULL) {
}
void TupleDescriptor::AddSlot(SlotDescriptor* slot) {
slots_.push_back(slot);
if (slot->is_materialized()) {
++num_materialized_slots_;
if (slot->type().IsVarLenStringType()) {
string_slots_.push_back(slot);
has_varlen_slots_ = true;
}
if (slot->type().IsCollectionType()) {
collection_slots_.push_back(slot);
has_varlen_slots_ = true;
}
}
}
bool TupleDescriptor::ContainsStringData() const {
if (!string_slots_.empty()) return true;
for (int i = 0; i < collection_slots_.size(); ++i) {
if (collection_slots_[i]->collection_item_descriptor_->ContainsStringData()) {
return true;
}
}
return false;
}
string TupleDescriptor::DebugString() const {
stringstream out;
out << "Tuple(id=" << id_ << " size=" << byte_size_;
if (table_desc_ != NULL) {
//out << " " << table_desc_->DebugString();
}
out << " slots=[";
for (size_t i = 0; i < slots_.size(); ++i) {
if (i > 0) out << ", ";
out << slots_[i]->DebugString();
}
out << "]";
out << " tuple_path=[";
for (size_t i = 0; i < tuple_path_.size(); ++i) {
if (i > 0) out << ", ";
out << tuple_path_[i];
}
out << "]";
out << ")";
return out.str();
}
RowDescriptor::RowDescriptor(const DescriptorTbl& desc_tbl,
const vector<TTupleId>& row_tuples,
const vector<bool>& nullable_tuples)
: tuple_idx_nullable_map_(nullable_tuples) {
DCHECK_EQ(nullable_tuples.size(), row_tuples.size());
DCHECK_GT(row_tuples.size(), 0);
for (int i = 0; i < row_tuples.size(); ++i) {
tuple_desc_map_.push_back(desc_tbl.GetTupleDescriptor(row_tuples[i]));
DCHECK(tuple_desc_map_.back() != NULL);
}
InitTupleIdxMap();
InitHasVarlenSlots();
}
RowDescriptor::RowDescriptor(const RowDescriptor& lhs_row_desc,
const RowDescriptor& rhs_row_desc) {
tuple_desc_map_.insert(tuple_desc_map_.end(), lhs_row_desc.tuple_desc_map_.begin(),
lhs_row_desc.tuple_desc_map_.end());
tuple_desc_map_.insert(tuple_desc_map_.end(), rhs_row_desc.tuple_desc_map_.begin(),
rhs_row_desc.tuple_desc_map_.end());
tuple_idx_nullable_map_.insert(tuple_idx_nullable_map_.end(),
lhs_row_desc.tuple_idx_nullable_map_.begin(),
lhs_row_desc.tuple_idx_nullable_map_.end());
tuple_idx_nullable_map_.insert(tuple_idx_nullable_map_.end(),
rhs_row_desc.tuple_idx_nullable_map_.begin(),
rhs_row_desc.tuple_idx_nullable_map_.end());
InitTupleIdxMap();
InitHasVarlenSlots();
}
RowDescriptor::RowDescriptor(const vector<TupleDescriptor*>& tuple_descs,
const vector<bool>& nullable_tuples)
: tuple_desc_map_(tuple_descs),
tuple_idx_nullable_map_(nullable_tuples) {
DCHECK_EQ(nullable_tuples.size(), tuple_descs.size());
DCHECK_GT(tuple_descs.size(), 0);
InitTupleIdxMap();
InitHasVarlenSlots();
}
RowDescriptor::RowDescriptor(TupleDescriptor* tuple_desc, bool is_nullable)
: tuple_desc_map_(1, tuple_desc),
tuple_idx_nullable_map_(1, is_nullable) {
InitTupleIdxMap();
InitHasVarlenSlots();
}
void RowDescriptor::InitTupleIdxMap() {
// find max id
TupleId max_id = 0;
for (int i = 0; i < tuple_desc_map_.size(); ++i) {
max_id = max(tuple_desc_map_[i]->id(), max_id);
}
tuple_idx_map_.resize(max_id + 1, INVALID_IDX);
for (int i = 0; i < tuple_desc_map_.size(); ++i) {
tuple_idx_map_[tuple_desc_map_[i]->id()] = i;
}
}
void RowDescriptor::InitHasVarlenSlots() {
has_varlen_slots_ = false;
for (int i = 0; i < tuple_desc_map_.size(); ++i) {
if (tuple_desc_map_[i]->HasVarlenSlots()) {
has_varlen_slots_ = true;
break;
}
}
}
int RowDescriptor::GetRowSize() const {
int size = 0;
for (int i = 0; i < tuple_desc_map_.size(); ++i) {
size += tuple_desc_map_[i]->byte_size();
}
return size;
}
int RowDescriptor::GetTupleIdx(TupleId id) const {
DCHECK_LT(id, tuple_idx_map_.size()) << "RowDescriptor: " << DebugString();
return tuple_idx_map_[id];
}
bool RowDescriptor::TupleIsNullable(int tuple_idx) const {
DCHECK_LT(tuple_idx, tuple_idx_nullable_map_.size());
return tuple_idx_nullable_map_[tuple_idx];
}
bool RowDescriptor::IsAnyTupleNullable() const {
for (int i = 0; i < tuple_idx_nullable_map_.size(); ++i) {
if (tuple_idx_nullable_map_[i]) return true;
}
return false;
}
void RowDescriptor::ToThrift(vector<TTupleId>* row_tuple_ids) {
row_tuple_ids->clear();
for (int i = 0; i < tuple_desc_map_.size(); ++i) {
row_tuple_ids->push_back(tuple_desc_map_[i]->id());
}
}
bool RowDescriptor::IsPrefixOf(const RowDescriptor& other_desc) const {
if (tuple_desc_map_.size() > other_desc.tuple_desc_map_.size()) return false;
for (int i = 0; i < tuple_desc_map_.size(); ++i) {
// pointer comparison okay, descriptors are unique
if (tuple_desc_map_[i] != other_desc.tuple_desc_map_[i]) return false;
}
return true;
}
bool RowDescriptor::Equals(const RowDescriptor& other_desc) const {
if (tuple_desc_map_.size() != other_desc.tuple_desc_map_.size()) return false;
for (int i = 0; i < tuple_desc_map_.size(); ++i) {
// pointer comparison okay, descriptors are unique
if (tuple_desc_map_[i] != other_desc.tuple_desc_map_[i]) return false;
}
return true;
}
string RowDescriptor::DebugString() const {
stringstream ss;
for (int i = 0; i < tuple_desc_map_.size(); ++i) {
ss << tuple_desc_map_[i]->DebugString() << endl;
}
return ss.str();
}
Status DescriptorTbl::Create(ObjectPool* pool, const TDescriptorTable& thrift_tbl,
DescriptorTbl** tbl) {
*tbl = pool->Add(new DescriptorTbl());
// deserialize table descriptors first, they are being referenced by tuple descriptors
for (size_t i = 0; i < thrift_tbl.tableDescriptors.size(); ++i) {
const TTableDescriptor& tdesc = thrift_tbl.tableDescriptors[i];
TableDescriptor* desc = NULL;
switch (tdesc.tableType) {
case TTableType::HDFS_TABLE:
desc = pool->Add(new HdfsTableDescriptor(tdesc, pool));
break;
case TTableType::HBASE_TABLE:
desc = pool->Add(new HBaseTableDescriptor(tdesc));
break;
case TTableType::DATA_SOURCE_TABLE:
desc = pool->Add(new DataSourceTableDescriptor(tdesc));
break;
default:
DCHECK(false) << "invalid table type: " << tdesc.tableType;
}
(*tbl)->tbl_desc_map_[tdesc.id] = desc;
}
for (size_t i = 0; i < thrift_tbl.tupleDescriptors.size(); ++i) {
const TTupleDescriptor& tdesc = thrift_tbl.tupleDescriptors[i];
TupleDescriptor* desc = pool->Add(new TupleDescriptor(tdesc));
// fix up table pointer
if (tdesc.__isset.tableId) {
desc->table_desc_ = (*tbl)->GetTableDescriptor(tdesc.tableId);
DCHECK(desc->table_desc_ != NULL);
}
(*tbl)->tuple_desc_map_[tdesc.id] = desc;
}
for (size_t i = 0; i < thrift_tbl.slotDescriptors.size(); ++i) {
const TSlotDescriptor& tdesc = thrift_tbl.slotDescriptors[i];
// Tuple descriptors are already populated in tbl
TupleDescriptor* parent = (*tbl)->GetTupleDescriptor(tdesc.parent);
TupleDescriptor* collection_item_descriptor = tdesc.__isset.itemTupleId ?
(*tbl)->GetTupleDescriptor(tdesc.itemTupleId) : NULL;
SlotDescriptor* slot_d = pool->Add(
new SlotDescriptor(tdesc, parent, collection_item_descriptor));
(*tbl)->slot_desc_map_[tdesc.id] = slot_d;
// link to parent
TupleDescriptorMap::iterator entry = (*tbl)->tuple_desc_map_.find(tdesc.parent);
if (entry == (*tbl)->tuple_desc_map_.end()) {
return Status("unknown tid in slot descriptor msg");
}
entry->second->AddSlot(slot_d);
}
return Status::OK();
}
TableDescriptor* DescriptorTbl::GetTableDescriptor(TableId id) const {
// TODO: is there some boost function to do exactly this?
TableDescriptorMap::const_iterator i = tbl_desc_map_.find(id);
if (i == tbl_desc_map_.end()) {
return NULL;
} else {
return i->second;
}
}
TupleDescriptor* DescriptorTbl::GetTupleDescriptor(TupleId id) const {
// TODO: is there some boost function to do exactly this?
TupleDescriptorMap::const_iterator i = tuple_desc_map_.find(id);
if (i == tuple_desc_map_.end()) {
return NULL;
} else {
return i->second;
}
}
SlotDescriptor* DescriptorTbl::GetSlotDescriptor(SlotId id) const {
// TODO: is there some boost function to do exactly this?
SlotDescriptorMap::const_iterator i = slot_desc_map_.find(id);
if (i == slot_desc_map_.end()) {
return NULL;
} else {
return i->second;
}
}
// return all registered tuple descriptors
void DescriptorTbl::GetTupleDescs(vector<TupleDescriptor*>* descs) const {
descs->clear();
for (TupleDescriptorMap::const_iterator i = tuple_desc_map_.begin();
i != tuple_desc_map_.end(); ++i) {
descs->push_back(i->second);
}
}
// Generate function to check if a slot is null. The resulting IR looks like:
// (in this case the tuple contains only a nullable double)
// define i1 @IsNull({ i8, double }* %tuple) {
// entry:
// %null_byte_ptr = getelementptr inbounds { i8, double }* %tuple, i32 0, i32 0
// %null_byte = load i8* %null_byte_ptr
// %null_mask = and i8 %null_byte, 1
// %is_null = icmp ne i8 %null_mask, 0
// ret i1 %is_null
// }
Function* SlotDescriptor::CodegenIsNull(LlvmCodeGen* codegen, StructType* tuple) {
if (is_null_fn_ != NULL) return is_null_fn_;
PointerType* tuple_ptr_type = PointerType::get(tuple, 0);
LlvmCodeGen::FnPrototype prototype(codegen, "IsNull", codegen->GetType(TYPE_BOOLEAN));
prototype.AddArgument(LlvmCodeGen::NamedVariable("tuple", tuple_ptr_type));
Value* mask = codegen->GetIntConstant(TYPE_TINYINT, null_indicator_offset_.bit_mask);
Value* zero = codegen->GetIntConstant(TYPE_TINYINT, 0);
int byte_offset = null_indicator_offset_.byte_offset;
LlvmCodeGen::LlvmBuilder builder(codegen->context());
Value* tuple_ptr;
Function* fn = prototype.GeneratePrototype(&builder, &tuple_ptr);
Value* null_byte_ptr = builder.CreateStructGEP(tuple_ptr, byte_offset, "null_byte_ptr");
Value* null_byte = builder.CreateLoad(null_byte_ptr, "null_byte");
Value* null_mask = builder.CreateAnd(null_byte, mask, "null_mask");
Value* is_null = builder.CreateICmpNE(null_mask, zero, "is_null");
builder.CreateRet(is_null);
return is_null_fn_ = codegen->FinalizeFunction(fn);
}
// Generate function to set a slot to be null or not-null. The resulting IR
// for SetNotNull looks like:
// (in this case the tuple contains only a nullable double)
// define void @SetNotNull({ i8, double }* %tuple) {
// entry:
// %null_byte_ptr = getelementptr inbounds { i8, double }* %tuple, i32 0, i32 0
// %null_byte = load i8* %null_byte_ptr
// %0 = and i8 %null_byte, -2
// store i8 %0, i8* %null_byte_ptr
// ret void
// }
Function* SlotDescriptor::CodegenUpdateNull(LlvmCodeGen* codegen,
StructType* tuple, bool set_null) {
if (set_null && set_null_fn_ != NULL) return set_null_fn_;
if (!set_null && set_not_null_fn_ != NULL) return set_not_null_fn_;
PointerType* tuple_ptr_type = PointerType::get(tuple, 0);
LlvmCodeGen::FnPrototype prototype(codegen, (set_null) ? "SetNull" :"SetNotNull",
codegen->void_type());
prototype.AddArgument(LlvmCodeGen::NamedVariable("tuple", tuple_ptr_type));
LlvmCodeGen::LlvmBuilder builder(codegen->context());
Value* tuple_ptr;
Function* fn = prototype.GeneratePrototype(&builder, &tuple_ptr);
Value* null_byte_ptr =
builder.CreateStructGEP(
tuple_ptr, null_indicator_offset_.byte_offset, "null_byte_ptr");
Value* null_byte = builder.CreateLoad(null_byte_ptr, "null_byte");
Value* result = NULL;
if (set_null) {
Value* null_set = codegen->GetIntConstant(
TYPE_TINYINT, null_indicator_offset_.bit_mask);
result = builder.CreateOr(null_byte, null_set);
} else {
Value* null_clear_val =
codegen->GetIntConstant(TYPE_TINYINT, ~null_indicator_offset_.bit_mask);
result = builder.CreateAnd(null_byte, null_clear_val);
}
builder.CreateStore(result, null_byte_ptr);
builder.CreateRetVoid();
fn = codegen->FinalizeFunction(fn);
if (set_null) {
set_null_fn_ = fn;
} else {
set_not_null_fn_ = fn;
}
return fn;
}
// The default llvm packing is identical to what we do in the FE. Each field is aligned
// to begin on the size for that type.
// TODO: Understand llvm::SetTargetData which allows you to explicitly define the packing
// rules.
StructType* TupleDescriptor::GenerateLlvmStruct(LlvmCodeGen* codegen) {
// If we already generated the llvm type, just return it.
if (llvm_struct_ != NULL) return llvm_struct_;
// For each null byte, add a byte to the struct
vector<Type*> struct_fields;
struct_fields.resize(num_null_bytes_ + num_materialized_slots_);
for (int i = 0; i < num_null_bytes_; ++i) {
struct_fields[i] = codegen->GetType(TYPE_TINYINT);
}
// Add the slot types to the struct description.
for (int i = 0; i < slots().size(); ++i) {
SlotDescriptor* slot_desc = slots()[i];
if (slot_desc->type().type == TYPE_CHAR) return NULL;
if (slot_desc->is_materialized()) {
slot_desc->field_idx_ = slot_desc->slot_idx_ + num_null_bytes_;
DCHECK_LT(slot_desc->field_idx(), struct_fields.size());
struct_fields[slot_desc->field_idx()] = codegen->GetType(slot_desc->type());
}
}
// Construct the struct type.
StructType* tuple_struct = StructType::get(codegen->context(),
ArrayRef<Type*>(struct_fields));
// Verify the alignment is correct. It is essential that the layout matches
// identically. If the layout does not match, return NULL indicating the
// struct could not be codegen'd. This will trigger codegen for anything using
// the tuple to be disabled.
const DataLayout* data_layout = codegen->execution_engine()->getDataLayout();
const StructLayout* layout = data_layout->getStructLayout(tuple_struct);
if (layout->getSizeInBytes() != byte_size()) {
DCHECK_EQ(layout->getSizeInBytes(), byte_size());
return NULL;
}
for (int i = 0; i < slots().size(); ++i) {
SlotDescriptor* slot_desc = slots()[i];
if (slot_desc->is_materialized()) {
int field_idx = slot_desc->field_idx();
// Verify that the byte offset in the llvm struct matches the tuple offset
// computed in the FE
if (layout->getElementOffset(field_idx) != slot_desc->tuple_offset()) {
DCHECK_EQ(layout->getElementOffset(field_idx), slot_desc->tuple_offset());
return NULL;
}
}
}
llvm_struct_ = tuple_struct;
return tuple_struct;
}
string DescriptorTbl::DebugString() const {
stringstream out;
out << "tuples:\n";
for (TupleDescriptorMap::const_iterator i = tuple_desc_map_.begin();
i != tuple_desc_map_.end(); ++i) {
out << i->second->DebugString() << '\n';
}
return out.str();
}
}
|
XiaominZhang/Impala
|
be/src/runtime/descriptors.cc
|
C++
|
apache-2.0
| 24,237 |
/*
* Copyright 2015 HM Revenue & Customs
*
* 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 uk.gov.hmrc.ct.ct600.v2
import uk.gov.hmrc.ct.box.{CtBoolean, CtBoxIdentifier, Input}
case class RSQ1(value: Boolean) extends CtBoxIdentifier with CtBoolean with Input
|
keithhall/ct-calculations
|
src/main/scala/uk/gov/hmrc/ct/ct600/v2/RSQ1.scala
|
Scala
|
apache-2.0
| 783 |
from nose.tools import * # noqa
from tests.base import (
OsfTestCase,
fake
)
from tests.factories import (
UserFactory,
ProjectFactory
)
from tests import utils
from website.files import models
from tests.test_addons import TestFile
from website.models import MetaSchema
from website.prereg.utils import get_prereg_schema
from scripts.migration.migrate_registration_extra import migrate
class TestMigrateRegistrationExtra(OsfTestCase):
def setUp(self):
super(TestMigrateRegistrationExtra, self).setUp()
self.user = UserFactory()
self.node = ProjectFactory(creator=self.user)
self.prereg_schema = get_prereg_schema()
self.file = self._get_test_file()
self.data = {
'uploader': {
'extra': {
'hasSelectedFile': True,
'nodeId': self.node._id,
'selectedFileName': 'file.txt',
'sha256': fake.sha256(),
'viewUrl': '/project/{}/files/osfstorage/5723787136b74e1a953d9612/'.format(
self.node._id
)
},
'value': 'file.txt'
},
'other': {
'value': 'foo'
},
'bad': {
'value': 'foobarbaz',
'extra': [
{
'viewUrl': '/project/{}/files/osfstorage/5723787136b74e1a953d9612/'.format(
self.node._id
),
'hasSelectedFile': True,
'selectedFileName': 'file.txt'
}
]
},
'nested': {
'value': {
'uploader': {
'extra': {
'hasSelectedFile': True,
'nodeId': self.node._id,
'selectedFileName': 'file.txt',
'sha256': fake.sha256(),
'viewUrl': '/project/{}/files/osfstorage/5723787136b74e1a953d9612/'.format(
self.node._id
)
},
'value': 'file.txt'
},
'question': {
'value': 'bar',
'extra': {}
},
'other': {
'value': 'foo',
'extra': []
}
}
}
}
def _get_test_file(self):
version = models.FileVersion(identifier='1', provider='osfstorage', metadata={'sha256': '2413fb3709b05939f04cf2e92f7d0897fc2596f9ad0b8a9ea855c7bfebaae892'})
version.save()
ret = models.FileNode(
_id='5723787136b74e1a953d9612',
name='file.txt',
node=self.node,
provider='osfstorage',
path='/test/file.txt',
materialized_path='/test/file.txt',
versions=[version]
)
ret.save()
return ret
def test_migrate_registration_extra(self):
with utils.mock_archive(
self.node,
schema=self.prereg_schema,
data=self.data,
autocomplete=True,
autoapprove=True
) as reg:
migrate()
reg.reload()
data = reg.registered_meta[self.prereg_schema._id]
assert_true(
isinstance(data['uploader']['extra'], list)
)
assert_true(
isinstance(
data['nested']['value']['uploader']['extra'],
list
)
)
assert_true(
isinstance(
data['nested']['value']['question']['extra'],
list
)
)
assert_equal(
self.data['uploader']['extra'],
data['uploader']['extra'][0]
)
assert_equal(
self.data['nested']['value']['uploader']['extra'],
data['nested']['value']['uploader']['extra'][0]
)
assert_equal(
self.data['nested']['value']['question']['value'],
data['nested']['value']['question']['value']
)
assert_equal(
self.data['nested']['value']['other'],
data['nested']['value']['other']
)
assert_equal(
self.data['other'],
data['other']
)
assert_true(
data['bad']['extra'][0].get('data', False)
)
assert_true(
isinstance(data['bad']['extra'][0]['data'], dict)
)
assert_equal(
data['bad']['extra'][0]['data']['name'], 'file.txt'
)
assert_equal(
data['bad']['extra'][0]['data']['sha256'], '2413fb3709b05939f04cf2e92f7d0897fc2596f9ad0b8a9ea855c7bfebaae892'
)
|
chrisseto/osf.io
|
scripts/tests/test_migrate_registration_extra.py
|
Python
|
apache-2.0
| 5,204 |
// +build linux
package node
import (
"errors"
"fmt"
"net"
"time"
"github.com/golang/glog"
"github.com/openshift/origin/pkg/util/netutils"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
utilwait "k8s.io/apimachinery/pkg/util/wait"
kapi "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/util/sysctl"
"github.com/vishvananda/netlink"
)
func (plugin *OsdnNode) alreadySetUp(localSubnetGatewayCIDR string, clusterNetworkCIDR []string) error {
var found bool
l, err := netlink.LinkByName(Tun0)
if err != nil {
return err
}
addrs, err := netlink.AddrList(l, netlink.FAMILY_V4)
if err != nil {
return err
}
found = false
for _, addr := range addrs {
if addr.IPNet.String() == localSubnetGatewayCIDR {
found = true
break
}
}
if !found {
return errors.New("local subnet gateway CIDR not found")
}
routes, err := netlink.RouteList(l, netlink.FAMILY_V4)
if err != nil {
return err
}
for _, clusterCIDR := range clusterNetworkCIDR {
found = false
for _, route := range routes {
if route.Dst != nil && route.Dst.String() == clusterCIDR {
found = true
break
}
}
if !found {
return errors.New("cluster CIDR not found")
}
}
if !plugin.oc.AlreadySetUp(plugin.networkInfo.VXLANPort) {
return errors.New("plugin is not setup")
}
return nil
}
func deleteLocalSubnetRoute(device, localSubnetCIDR string) {
// ~1 sec total
backoff := utilwait.Backoff{
Duration: 100 * time.Millisecond,
Factor: 1.25,
Steps: 7,
}
err := utilwait.ExponentialBackoff(backoff, func() (bool, error) {
l, err := netlink.LinkByName(device)
if err != nil {
return false, fmt.Errorf("could not get interface %s: %v", device, err)
}
routes, err := netlink.RouteList(l, netlink.FAMILY_V4)
if err != nil {
return false, fmt.Errorf("could not get routes: %v", err)
}
for _, route := range routes {
if route.Dst != nil && route.Dst.String() == localSubnetCIDR {
err = netlink.RouteDel(&route)
if err != nil {
return false, fmt.Errorf("could not delete route: %v", err)
}
return true, nil
}
}
return false, nil
})
if err != nil {
utilruntime.HandleError(fmt.Errorf("Error removing %s route from dev %s: %v; if the route appears later it will not be deleted.", localSubnetCIDR, device, err))
}
}
func (plugin *OsdnNode) SetupSDN() (bool, map[string]podNetworkInfo, error) {
// Make sure IPv4 forwarding state is 1
sysctl := sysctl.New()
val, err := sysctl.GetSysctl("net/ipv4/ip_forward")
if err != nil {
return false, nil, fmt.Errorf("could not get IPv4 forwarding state: %s", err)
}
if val != 1 {
return false, nil, fmt.Errorf("net/ipv4/ip_forward=0, it must be set to 1")
}
var clusterNetworkCIDRs []string
for _, cn := range plugin.networkInfo.ClusterNetworks {
clusterNetworkCIDRs = append(clusterNetworkCIDRs, cn.ClusterCIDR.String())
}
localSubnetCIDR := plugin.localSubnetCIDR
_, ipnet, err := net.ParseCIDR(localSubnetCIDR)
if err != nil {
return false, nil, fmt.Errorf("invalid local subnet CIDR: %v", err)
}
localSubnetMaskLength, _ := ipnet.Mask.Size()
localSubnetGateway := netutils.GenerateDefaultGateway(ipnet).String()
glog.V(5).Infof("[SDN setup] node pod subnet %s gateway %s", ipnet.String(), localSubnetGateway)
gwCIDR := fmt.Sprintf("%s/%d", localSubnetGateway, localSubnetMaskLength)
if err := waitForOVS(ovsDialDefaultNetwork, ovsDialDefaultAddress); err != nil {
return false, nil, err
}
var changed bool
var existingPods map[string]podNetworkInfo
if err := plugin.alreadySetUp(gwCIDR, clusterNetworkCIDRs); err == nil {
glog.V(5).Infof("[SDN setup] no SDN setup required")
} else {
glog.Infof("[SDN setup] full SDN setup required (%v)", err)
existingPods, err = plugin.oc.GetPodNetworkInfo()
if err != nil {
glog.Warningf("[SDN setup] Could not get details of existing pods: %v", err)
}
if err := plugin.setup(clusterNetworkCIDRs, localSubnetCIDR, localSubnetGateway, gwCIDR); err != nil {
return false, nil, err
}
changed = true
}
// TODO: make it possible to safely reestablish node configuration after restart
// If OVS goes down and fails the health check, restart the entire process
healthFn := func() error { return plugin.alreadySetUp(gwCIDR, clusterNetworkCIDRs) }
runOVSHealthCheck(ovsDialDefaultNetwork, ovsDialDefaultAddress, healthFn)
return changed, existingPods, nil
}
func (plugin *OsdnNode) setup(clusterNetworkCIDRs []string, localSubnetCIDR, localSubnetGateway, gwCIDR string) error {
serviceNetworkCIDR := plugin.networkInfo.ServiceNetwork.String()
if err := plugin.oc.SetupOVS(clusterNetworkCIDRs, serviceNetworkCIDR, localSubnetCIDR, localSubnetGateway, plugin.mtu, plugin.networkInfo.VXLANPort); err != nil {
return err
}
l, err := netlink.LinkByName(Tun0)
if err == nil {
gwIP, _ := netlink.ParseIPNet(gwCIDR)
err = netlink.AddrAdd(l, &netlink.Addr{IPNet: gwIP})
if err == nil {
defer deleteLocalSubnetRoute(Tun0, localSubnetCIDR)
}
}
if err == nil {
err = netlink.LinkSetUp(l)
}
if err == nil {
for _, clusterNetwork := range plugin.networkInfo.ClusterNetworks {
route := &netlink.Route{
LinkIndex: l.Attrs().Index,
Scope: netlink.SCOPE_LINK,
Dst: clusterNetwork.ClusterCIDR,
}
if err = netlink.RouteAdd(route); err != nil {
return err
}
}
}
if err == nil {
route := &netlink.Route{
LinkIndex: l.Attrs().Index,
Dst: plugin.networkInfo.ServiceNetwork,
}
err = netlink.RouteAdd(route)
}
if err != nil {
return err
}
return nil
}
func (plugin *OsdnNode) updateEgressNetworkPolicyRules(vnid uint32) {
policies := plugin.egressPolicies[vnid]
namespaces := plugin.policy.GetNamespaces(vnid)
if err := plugin.oc.UpdateEgressNetworkPolicyRules(policies, vnid, namespaces, plugin.egressDNS); err != nil {
utilruntime.HandleError(fmt.Errorf("Error updating OVS flows for EgressNetworkPolicy: %v", err))
}
}
func (plugin *OsdnNode) AddServiceRules(service *kapi.Service, netID uint32) {
glog.V(5).Infof("AddServiceRules for %v", service)
if err := plugin.oc.AddServiceRules(service, netID); err != nil {
utilruntime.HandleError(fmt.Errorf("Error adding OVS flows for service %v, netid %d: %v", service, netID, err))
}
}
func (plugin *OsdnNode) DeleteServiceRules(service *kapi.Service) {
glog.V(5).Infof("DeleteServiceRules for %v", service)
if err := plugin.oc.DeleteServiceRules(service); err != nil {
utilruntime.HandleError(fmt.Errorf("Error deleting OVS flows for service %v: %v", service, err))
}
}
|
linzhaoming/origin
|
pkg/network/node/sdn_controller.go
|
GO
|
apache-2.0
| 6,548 |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mathstats
import "testing"
func TestTTest(t *testing.T) {
s1 := Sample{Xs: []float64{2, 1, 3, 4}}
s2 := Sample{Xs: []float64{6, 5, 7, 9}}
check := func(want, got *TTestResult) {
if want.N1 != got.N1 || want.N2 != got.N2 ||
!aeq(want.T, got.T) || !aeq(want.DoF, got.DoF) ||
want.AltHypothesis != got.AltHypothesis ||
!aeq(want.P, got.P) {
t.Errorf("want %+v, got %+v", want, got)
}
}
check3 := func(test func(alt LocationHypothesis) (*TTestResult, error), n1, n2 int, t, dof float64, pless, pdiff, pgreater float64) {
want := &TTestResult{N1: n1, N2: n2, T: t, DoF: dof}
want.AltHypothesis = LocationLess
want.P = pless
got, _ := test(want.AltHypothesis)
check(want, got)
want.AltHypothesis = LocationDiffers
want.P = pdiff
got, _ = test(want.AltHypothesis)
check(want, got)
want.AltHypothesis = LocationGreater
want.P = pgreater
got, _ = test(want.AltHypothesis)
check(want, got)
}
check3(func(alt LocationHypothesis) (*TTestResult, error) {
return TwoSampleTTest(s1, s1, alt)
}, 4, 4, 0, 6,
0.5, 1, 0.5)
check3(func(alt LocationHypothesis) (*TTestResult, error) {
return TwoSampleWelchTTest(s1, s1, alt)
}, 4, 4, 0, 6,
0.5, 1, 0.5)
check3(func(alt LocationHypothesis) (*TTestResult, error) {
return TwoSampleTTest(s1, s2, alt)
}, 4, 4, -3.9703446152237674, 6,
0.0036820296121056195, 0.0073640592242113214, 0.9963179703878944)
check3(func(alt LocationHypothesis) (*TTestResult, error) {
return TwoSampleWelchTTest(s1, s2, alt)
}, 4, 4, -3.9703446152237674, 5.584615384615385,
0.004256431565689112, 0.0085128631313781695, 0.9957435684343109)
check3(func(alt LocationHypothesis) (*TTestResult, error) {
return PairedTTest(s1.Xs, s2.Xs, 0, alt)
}, 4, 4, -17, 3,
0.0002216717691559955, 0.00044334353831207749, 0.999778328230844)
check3(func(alt LocationHypothesis) (*TTestResult, error) {
return OneSampleTTest(s1, 0, alt)
}, 4, 0, 3.872983346207417, 3,
0.9847668541689145, 0.030466291662170977, 0.015233145831085482)
check3(func(alt LocationHypothesis) (*TTestResult, error) {
return OneSampleTTest(s1, 2.5, alt)
}, 4, 0, 0, 3,
0.5, 1, 0.5)
}
|
mahak/vitess
|
go/mathstats/ttest_test.go
|
GO
|
apache-2.0
| 2,308 |
/*
* 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.solr.client.solrj.io.eval;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.apache.solr.client.solrj.io.stream.expr.StreamExpression;
import org.apache.solr.client.solrj.io.stream.expr.StreamFactory;
public class FeatureSelectEvaluator extends RecursiveObjectEvaluator implements TwoValueWorker {
protected static final long serialVersionUID = 1L;
public FeatureSelectEvaluator(StreamExpression expression, StreamFactory factory)
throws IOException {
super(expression, factory);
if (2 != containedEvaluators.size()) {
throw new IOException(
String.format(
Locale.ROOT,
"Invalid expression %s - expecting exactly 2 values but found %d",
expression,
containedEvaluators.size()));
}
}
@Override
public Object doWork(Object value1, Object value2) throws IOException {
if (value1 instanceof Matrix) {
Matrix matrix = (Matrix) value1;
double[][] data = matrix.getData();
List<String> labels = matrix.getColumnLabels();
Set<String> features = new HashSet<>();
loadFeatures(value2, features);
List<String> newColumnLabels = new ArrayList<>();
for (String label : labels) {
if (features.contains(label)) {
newColumnLabels.add(label);
}
}
double[][] selectFeatures = new double[data.length][newColumnLabels.size()];
for (int i = 0; i < data.length; i++) {
double[] currentRow = data[i];
double[] newRow = new double[newColumnLabels.size()];
int index = -1;
for (int l = 0; l < currentRow.length; l++) {
String label = labels.get(l);
if (features.contains(label)) {
newRow[++index] = currentRow[l];
}
}
selectFeatures[i] = newRow;
}
Matrix newMatrix = new Matrix(selectFeatures);
newMatrix.setRowLabels(matrix.getRowLabels());
newMatrix.setColumnLabels(newColumnLabels);
return newMatrix;
} else {
throw new IOException("The featureSelect function expects a matrix as a parameter");
}
}
private void loadFeatures(Object o, Set<String> features) {
List<?> list = (List<?>) o;
for (Object v : list) {
if (v instanceof List) {
loadFeatures(v, features);
} else {
features.add((String) v);
}
}
}
}
|
apache/solr
|
solr/solrj/src/java/org/apache/solr/client/solrj/io/eval/FeatureSelectEvaluator.java
|
Java
|
apache-2.0
| 3,308 |
<?php
/*
* Copyright 2014 Google 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.
*/
namespace Google\Service\ShoppingContent;
class AccountsUpdateLabelsRequest extends \Google\Collection
{
protected $collection_key = 'labelIds';
/**
* @var string[]
*/
public $labelIds;
/**
* @param string[]
*/
public function setLabelIds($labelIds)
{
$this->labelIds = $labelIds;
}
/**
* @return string[]
*/
public function getLabelIds()
{
return $this->labelIds;
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(AccountsUpdateLabelsRequest::class, 'Google_Service_ShoppingContent_AccountsUpdateLabelsRequest');
|
googleapis/google-api-php-client-services
|
src/ShoppingContent/AccountsUpdateLabelsRequest.php
|
PHP
|
apache-2.0
| 1,211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.