repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
YegorKozlov/acs-aem-commons
|
bundle/src/main/java/com/adobe/acs/commons/httpcache/config/impl/ResourcePropertiesHttpCacheConfigExtension.java
|
<filename>bundle/src/main/java/com/adobe/acs/commons/httpcache/config/impl/ResourcePropertiesHttpCacheConfigExtension.java
/*
* #%L
* ACS AEM Commons Bundle
* %%
* Copyright (C) 2015 Adobe
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.adobe.acs.commons.httpcache.config.impl;
import com.adobe.acs.commons.httpcache.config.HttpCacheConfig;
import com.adobe.acs.commons.httpcache.config.HttpCacheConfigExtension;
import com.adobe.acs.commons.httpcache.keys.CacheKeyFactory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.ValueMap;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* ResourcePropertiesHttpCacheConfigExtension
* <p>
* This extension on the HTTP cache allows for specific Resource Property combinations to create separate cache entries.
* </p>
*/
@Component(
configurationPolicy = ConfigurationPolicy.REQUIRE,
service = {HttpCacheConfigExtension.class, CacheKeyFactory.class},
property = {Constants.SERVICE_RANKING + ":Integer=50" }
)
@Designate(
ocd = ResourcePropertiesHttpCacheConfigExtension.Config.class,
factory = true
)
public class ResourcePropertiesHttpCacheConfigExtension extends AbstractKeyValueExtension implements CacheKeyFactory, HttpCacheConfigExtension {
@ObjectClassDefinition(
name = "ACS AEM Commons - HTTP Cache - Extension - Resource Properties",
description = "Defines Resource Property names / Resource Property values that will be allowed for this extension (HttpCacheConfig and CacheKeyFactory)."
)
public @interface Config {
@AttributeDefinition(
name = "Allowed Property names",
description = "The Resource Property name to check."
)
String httpcache_config_extension_property() default "";
@AttributeDefinition(
name = "Allowed Property values",
description = "This request is only accepted for caching when its named resource property (above) contains one of these values. Leave blank for any value."
)
String[] httpcache_config_extension_property_values() default {};
@AttributeDefinition(
name = "Config Name"
)
String config_name() default StringUtils.EMPTY;
@AttributeDefinition
String webconsole_configurationFactory_nameHint() default "Properties: [ {httpcache.config.extension.property} ] Property values: [ {httpcache.config.extension.property.values} ] Config name: [ {config.name} ]";
}
private static final Logger log = LoggerFactory.getLogger(ResourcePropertiesHttpCacheConfigExtension.class);
private String configName;
private Map<String, String[]> allowedProperties;
private String cacheKeyId;
@Override
public Map<String, String[]> getAllowedKeyValues() {
return allowedProperties;
}
@Override
public boolean accepts(SlingHttpServletRequest request, HttpCacheConfig cacheConfig, Map<String, String[]> allowedKeyValues) {
for (final Map.Entry<String, String[]> entry : allowedKeyValues.entrySet()) {
final ValueMap properties = request.getResource().getValueMap();
final String key = entry.getKey();
if (properties.containsKey(key)) {
log.debug("{} - passed contains key with key {} for resource {}", configName, key, request.getResource().getPath());
final String[] propertyValues = properties.get(key, String[].class);
if (ArrayUtils.isEmpty(propertyValues) || CollectionUtils.containsAny(Arrays.asList(entry.getValue()), Arrays.asList(propertyValues))) {
log.debug("{} - passed value check with value {} for resource {}", configName, entry.getValue(), request.getResource().getPath());
// If no values were specified, then assume ANY and ALL values are acceptable, and were are merely looking for the existence of the property
return true;
}
// No matches found for this row; continue looking through the allowed list
}
}
// No valid resource property could be found.
return false;
}
@Override
protected String getActualValue(String key, SlingHttpServletRequest request) {
return request.getResource().getValueMap().get(key, String.class);
}
@Override
public String getCacheKeyId() {
return "[Resource Property: " + cacheKeyId + "]";
}
@Activate
public void activate(ResourcePropertiesHttpCacheConfigExtension.Config config) {
allowedProperties = new HashMap<>();
allowedProperties.put(config.httpcache_config_extension_property(), config.httpcache_config_extension_property_values());
cacheKeyId = UUID.randomUUID().toString();
configName = config.config_name();
}
}
|
circusliving/amp
|
apollo/articleByIdentifier.js
|
<reponame>circusliving/amp
import gql from 'graphql-tag'
export default gql`query article($identifier: String!) {
article(filter: { identifier: { eq: $identifier } }) {
name
alternateName
text,
image,
coverImage
}
}`
|
LoliGothick/mitama-dimensional
|
tests/format-io-tests/molar_conductivity-tests/molar_conductivity-tests.cpp
|
<gh_stars>10-100
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include <mitama/dimensional/systems/si/derived_units/molar_conductivity.hpp>
#include <mitama/dimensional/systems/si/quantity.hpp>
#include "../format_io_common.hpp"
TEST_CASE("molar_conductivity format test", "[quantity][abbreviation]") {
REQUIRE(fmt(1 | systems::si::molar_conductivity_t{}) == "1 [S m^2/mol]");
}
TEST_CASE("molar_conductivity quantifier format test", "[quantity][abbreviation]") {
REQUIRE(fmt(1 | systems::si::molar_conductivity) == "1 [S m^2/mol]");
}
TEST_CASE("molar_conductivity type test", "[quantity][abbreviation]") {
REQUIRE(mitama::is_same_dimensional_v<std::decay_t<decltype(1|systems::si::molar_conductivity)>, mitama::systems::si::quantity_t<std::decay_t<decltype(kilogram<-1>*second<3>*ampere<2>*mol<-1>)>>>);
}
|
zhangkn/iOS14Header
|
System/Library/PrivateFrameworks/DocumentManagerExecutables.framework/FPItemCollectionIndexPathBasedDelegate.h
|
/*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:54:25 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/DocumentManagerExecutables.framework/DocumentManagerExecutables
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
@protocol FPItemCollectionIndexPathBasedDelegate <FPItemCollectionMinimalDelegate>
@required
-(void)collection:(id)arg1 didInsertItemsAtIndexPaths:(id)arg2;
-(void)collection:(id)arg1 didMoveItemsFromIndexPaths:(id)arg2 toIndexPaths:(id)arg3;
-(void)collection:(id)arg1 didDeleteItemsAtIndexPaths:(id)arg2;
-(void)collection:(id)arg1 didUpdateItemsAtIndexPaths:(id)arg2 changes:(id)arg3;
-(void)collection:(id)arg1 didPerformBatchUpdateWithReplayBlock:(/*^block*/id)arg2;
@end
|
keeponZhang/android_design_pattern_book_source
|
app/src/main/java/zhushen/com/shejimoshi/leetcode/partition.java
|
package zhushen.com.shejimoshi.leetcode;
import java.util.List;
/**
* Created by Zhushen on 2018/10/8.
*/
public class partition {
public List<List<String>> partition(String s) {
return null;
}
public ListNode partition(ListNode head, int x) {
ListNode dummyHead1 = new ListNode(0);
ListNode dummyHead2 = new ListNode(0);
ListNode node1 = dummyHead1;
ListNode node2 = dummyHead2;
while (head != null) {
if (head.val < x) {
node1.next = head;
head = head.next;
node1 = node1.next;
node1.next = null;
} else {
node2.next = head;
head = head.next;
node2 = node2.next;
node2.next = null;
}
}
node1.next = dummyHead2.next;
return dummyHead1.next;
}
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
}
|
GQMai/mbed-cloud-sdk-python
|
src/mbed_cloud/account_management/__init__.py
|
<gh_stars>10-100
from .account_management import AccountManagementAPI
from .account_management import Account
from .account_management import ApiKey
from .account_management import Group
from .account_management import LoginHistory
from .account_management import User
|
xlf19/PurchasingCenter
|
jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/contract/elements/mapper/ContractElementsMapper.java
|
<gh_stars>0
package org.jeecg.modules.contract.elements.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.jeecg.modules.contract.elements.entity.ContractElements;
/**
* @Description: 合同元素表
* @Author: jeecg-boot
* @Date: 2020-08-31
* @Version: V1.0
*/
public interface ContractElementsMapper extends BaseMapper<ContractElements> {
//获取合同元素信息
public List<ContractElements> findList(@Param("cid") String cid);
//删除合同元素信息
public void updateElelist(@Param("cid")String cid);
//根据合同号获取合同元素信息
public List<String> findListhth(@Param("htbh") String htbh);
}
|
jakllsch/openafs
|
src/fsprobe/fsprobe_callback.c
|
/*
* Copyright 2000, International Business Machines Corporation and others.
* All Rights Reserved.
*
* This software has been released under the terms of the IBM Public
* License. For details, see the LICENSE file in the top-level source
* directory or online at http://www.openafs.org/dl/license10.html
*/
/*
* Description:
* Implementation of the fsprobe callback routines. These are the
* server-side functions that the FileServer expects to invoke on
* the client machine via the afsint interface. In this case, the
* client workstation is acting as a callback listener.
*
* Environment:
* The afsint server stubs expect the functions defined here to
* be provided. There is no .h file for this code, since the
* linker really does all the work for us, and these don't really
* need to be ``visible'' to anyone else.
*------------------------------------------------------------------------*/
#include <afsconfig.h>
#include <afs/param.h>
#include <roken.h>
#include <afs/afscbint.h> /*Callback interface defs */
#include <afs/afsutil.h>
#define FSPROBE_CALLBACK_VERBOSE 0
int afs_cb_inited = 0;
struct interfaceAddr afs_cb_interface;
/*
* Initialize the callback interface structure
*/
static int
init_afs_cb(void)
{
int count;
afs_uuid_create(&afs_cb_interface.uuid);
count = rx_getAllAddr((afs_uint32 *) &afs_cb_interface.addr_in, AFS_MAX_INTERFACE_ADDR);
if (count <= 0)
afs_cb_interface.numberOfInterfaces = 0;
else
afs_cb_interface.numberOfInterfaces = count;
afs_cb_inited = 1;
return 0;
}
/*------------------------------------------------------------------------
* SRXAFSCB_CallBack
*
* Description:
* Handle a set of callbacks from the FileServer.
*
* Arguments:
* struct rx_call *rxcall : Ptr to the associated Rx call structure.
* AFSCBFids *Fids_Array : Ptr to the set of Fids.
* AFSCBs *CallBacks_Array : Ptr to the set of callbacks.
*
* Returns:
* 0 on success,
* Error value otherwise.
*
* Environment:
* Nothing interesting.
*
* Side Effects:
* As advertised.
*------------------------------------------------------------------------*/
afs_int32
SRXAFSCB_CallBack(struct rx_call * rxcall, AFSCBFids * Fids_Array,
AFSCBs * CallBack_Array)
{ /*SRXAFSCB_CallBack */
#if FSPROBE_CALLBACK_VERBOSE
static char rn[] = "SRXAFSCB_CallBack"; /*Routine name */
char hostName[256]; /*Host name buffer */
char *hostNameResult; /*Ptr to static */
if (rxcall != (struct rx_call *)0) {
hostNameResult =
hostutil_GetNameByINet((afs_int32) (rxcall->conn->peer->host));
strcpy(hostName, hostNameResult);
fprintf(stderr, "[%s:%s] Called from host %s, port %d\n", mn, rn,
hostName, rxcall->conn->peer->port);
} /*Valid rxcall param */
#endif /* FSPROBE_CALLBACK_VERBOSE */
/*
* Return successfully.
*/
return (0);
} /*SRXAFSCB_CallBack */
/*------------------------------------------------------------------------
* SRXAFSCB_InitCallBackState
*
* Description:
* Initialize callback state on this ``Cache Manager''.
*
* Arguments:
* struct rx_call *rxcall : Ptr to the associated Rx call structure.
*
* Returns:
* 0 on success,
* Error value otherwise.
*
* Environment:
* This will definitely be called by the FileServer (exactly once),
* since it will think we are another new ``Cache Manager''.
*
* Side Effects:
* As advertised.
*------------------------------------------------------------------------*/
afs_int32
SRXAFSCB_InitCallBackState(struct rx_call * rxcall)
{ /*SRXAFSCB_InitCallBackState */
#if FSPROBE_CALLBACK_VERBOSE
static char rn[] = "SRXAFSCB_InitCallBackState"; /*Routine name */
char hostName[256]; /*Host name buffer */
char *hostNameResult; /*Ptr to static */
if (rxcall != (struct rx_call *)0) {
hostNameResult =
hostutil_GetNameByINet((afs_int32) (rxcall->conn->peer->host));
strcpy(hostName, hostNameResult);
fprintf(stderr, "[%s:%s] Called from host %s, port %d\n", mn, rn,
hostName, rxcall->conn->peer->port);
} /*Valid rxcall param */
#endif /* FSPROBE_CALLBACK_VERBOSE */
/*
* Return successfully.
*/
return (0);
} /*SRXAFSCB_InitCallBackState */
/*------------------------------------------------------------------------
* SRXAFSCB_Probe
*
* Description:
* Respond to a probe from the FileServer. If a FileServer doesn't
* hear from you every so often, it will send you a probe to make
* sure you're there, just like any other ``Cache Manager'' it's
* keeping track of.
*
* Arguments:
* struct rx_call *rxcall : Ptr to the associated Rx call structure.
*
* Returns:
* 0 on success,
* Error value otherwise.
*
* Environment:
* This may be called by the FileServer if we don't call it often
* enough.
*
* Side Effects:
* As advertised.
*------------------------------------------------------------------------*/
afs_int32
SRXAFSCB_Probe(struct rx_call * rxcall)
{ /*SRXAFSCB_Probe */
#if FSPROBE_CALLBACK_VERBOSE
static char rn[] = "SRXAFSCB_Probe"; /*Routine name */
char hostName[256]; /*Host name buffer */
char *hostNameResult; /*Ptr to static */
if (rxcall != (struct rx_call *)0) {
hostNameResult =
hostutil_GetNameByINet((afs_int32) (rxcall->conn->peer->host));
strcpy(hostName, hostNameResult);
fprintf(stderr, "[%s:%s] Called from host %s, port %d\n", mn, rn,
hostName, rxcall->conn->peer->port);
} /*Valid rxcall param */
#endif /* FSPROBE_CALLBACK_VERBOSE */
/*
* Return successfully.
*/
return (0);
} /*SRXAFSCB_Probe */
/*------------------------------------------------------------------------
* SRXAFSCB_GetCE64
*
* Description:
* Respond minimally to a request for returning the contents of
* a cache entry, since someone out there thinks you're a Cache
* Manager.
*
* Arguments:
* struct rx_call *rxcall: Ptr to the associated Rx call structure.
*
* Returns:
* 0 (always)
*
* Environment:
* Nothing interesting.
*
* Side Effects:
* As advertised.
*------------------------------------------------------------------------*/
afs_int32
SRXAFSCB_GetCE64(struct rx_call * rxcall, afs_int32 index,
AFSDBCacheEntry64 * ce)
{ /*SRXAFSCB_GetCE64 */
#if XSTAT_FS_CALLBACK_VERBOSE
static char rn[] = "SRXAFSCB_GetCE64"; /*Routine name */
char hostName[256]; /*Host name buffer */
char *hostNameResult; /*Ptr to static */
if (rxcall != (struct rx_call *)0) {
hostNameResult =
hostutil_GetNameByINet((afs_int32) (rxcall->conn->peer->host));
strcpy(hostName, hostNameResult);
fprintf(stderr, "[%s:%s] Called from host %s, port %d\n", mn, rn,
hostName, rxcall->conn->peer->port);
} /*Valid rxcall param */
#endif /* XSTAT_FS_CALLBACK_VERBOSE */
return (0);
} /*SRXAFSCB_GetCE64 */
afs_int32
SRXAFSCB_GetCE(struct rx_call * rxcall, afs_int32 index, AFSDBCacheEntry * ce)
{ /*SRXAFSCB_GetCE */
#if XSTAT_FS_CALLBACK_VERBOSE
static char rn[] = "SRXAFSCB_GetCE"; /*Routine name */
char hostName[256]; /*Host name buffer */
char *hostNameResult; /*Ptr to static */
if (rxcall != (struct rx_call *)0) {
hostNameResult =
hostutil_GetNameByINet((afs_int32) (rxcall->conn->peer->host));
strcpy(hostName, hostNameResult);
fprintf(stderr, "[%s:%s] Called from host %s, port %d\n", mn, rn,
hostName, rxcall->conn->peer->port);
} /*Valid rxcall param */
#endif /* XSTAT_FS_CALLBACK_VERBOSE */
return (0);
} /*SRXAFSCB_GetCE */
/*------------------------------------------------------------------------
* SRXAFSCB_GetLock
*
* Description:
* Respond minimally to a request for returning the contents of
* a cache lock, since someone out there thinks you're a Cache
* Manager.
*
* Arguments:
* struct rx_call *rxcall: Ptr to the associated Rx call structure.
*
* Returns:
* 0 (always)
*
* Environment:
* Nothing interesting.
*
* Side Effects:
* As advertised.
*------------------------------------------------------------------------*/
afs_int32
SRXAFSCB_GetLock(struct rx_call * rxcall, afs_int32 index, AFSDBLock * lock)
{ /*SRXAFSCB_GetLock */
#if XSTAT_FS_CALLBACK_VERBOSE
static char rn[] = "SRXAFSCB_GetLock"; /*Routine name */
char hostName[256]; /*Host name buffer */
char *hostNameResult; /*Ptr to static */
if (rxcall != (struct rx_call *)0) {
hostNameResult =
hostutil_GetNameByINet((afs_int32) (rxcall->conn->peer->host));
strcpy(hostName, hostNameResult);
fprintf(stderr, "[%s:%s] Called from host %s, port %d\n", mn, rn,
hostName, rxcall->conn->peer->port);
} /*Valid rxcall param */
#endif /* XSTAT_FS_CALLBACK_VERBOSE */
return (0);
} /*SRXAFSCB_GetLock */
/*------------------------------------------------------------------------
* SRXAFSCB_XStatsVersion
*
* Description:
* Respond minimally to a request for fetching the version of
* extended Cache Manager statistics offered, since someone out
* there thinks you're a Cache Manager.
*
* Arguments:
* struct rx_call *rxcall: Ptr to the associated Rx call structure.
*
* Returns:
* 0 (always)
*
* Environment:
* Nothing interesting.
*
* Side Effects:
* As advertised.
*------------------------------------------------------------------------*/
afs_int32
SRXAFSCB_XStatsVersion(struct rx_call * rxcall, afs_int32 * versionNumberP)
{ /*SRXAFSCB_XStatsVersion */
#if XSTAT_FS_CALLBACK_VERBOSE
static char rn[] = "SRXAFSCB_XStatsVersion"; /*Routine name */
char hostName[256]; /*Host name buffer */
char *hostNameResult; /*Ptr to static */
if (rxcall != (struct rx_call *)0) {
hostNameResult =
hostutil_GetNameByINet((afs_int32) (rxcall->conn->peer->host));
strcpy(hostName, hostNameResult);
fprintf(stderr, "[%s:%s] Called from host %s, port %d\n", mn, rn,
hostName, rxcall->conn->peer->port);
} /*Valid rxcall param */
#endif /* XSTAT_FS_CALLBACK_VERBOSE */
return (0);
} /*SRXAFSCB_XStatsVersion */
/*------------------------------------------------------------------------
* SRXAFSCB_GetXStats
*
* Description:
* Respond minimally to a request for returning extended
* statistics for a Cache Manager, since someone out there thinks
* you're a Cache Manager.
*
* Arguments:
* struct rx_call *rxcall: Ptr to the associated Rx call structure.
*
* Returns:
* 0 (always)
*
* Environment:
* Nothing interesting.
*
* Side Effects:
* As advertised.
*------------------------------------------------------------------------*/
afs_int32
SRXAFSCB_GetXStats(struct rx_call * rxcall, afs_int32 clientVN,
afs_int32 collN, afs_int32 * srvVNP, afs_int32 * timeP,
AFSCB_CollData * dataP)
{ /*SRXAFSCB_GetXStats */
#if XSTAT_FS_CALLBACK_VERBOSE
static char rn[] = "SRXAFSCB_GetXStats"; /*Routine name */
char hostName[256]; /*Host name buffer */
char *hostNameResult; /*Ptr to static */
if (rxcall != (struct rx_call *)0) {
hostNameResult =
hostutil_GetNameByINet((afs_int32) (rxcall->conn->peer->host));
strcpy(hostName, hostNameResult);
fprintf(stderr, "[%s:%s] Called from host %s, port %d\n", mn, rn,
hostName, rxcall->conn->peer->port);
} /*Valid rxcall param */
#endif /* XSTAT_FS_CALLBACK_VERBOSE */
return (0);
} /*SRXAFSCB_GetXStats */
/*------------------------------------------------------------------------
* EXPORTED SRXAFSCB_InitCallBackState2
*
* Description:
* This routine was used in the AFS 3.5 beta release, but not anymore.
* It has since been replaced by SRXAFSCB_InitCallBackState3.
*
* Arguments:
* rxcall : Ptr to Rx call on which this request came in.
*
* Returns:
* RXGEN_OPCODE (always).
*
* Environment:
* Nothing interesting.
*
* Side Effects:
* None
*------------------------------------------------------------------------*/
afs_int32
SRXAFSCB_InitCallBackState2(struct rx_call * rxcall,
struct interfaceAddr * addr)
{
#if FSPROBE_CALLBACK_VERBOSE
static char rn[] = "SRXAFSCB_InitCallBackState2"; /*Routine name */
char hostName[256]; /*Host name buffer */
char *hostNameResult; /*Ptr to static */
if (rxcall != (struct rx_call *)0) {
hostNameResult =
hostutil_GetNameByINet((afs_int32) (rxcall->conn->peer->host));
strcpy(hostName, hostNameResult);
fprintf(stderr, "[%s:%s] Called from host %s, port %d\n", mn, rn,
hostName, rxcall->conn->peer->port);
} /*Valid rxcall param */
#endif /* FSPROBE_CALLBACK_VERBOSE */
return RXGEN_OPCODE;
}
/*------------------------------------------------------------------------
* EXPORTED SRXAFSCB_WhoAreYou
*
* Description:
* Routine called by the server-side callback RPC interface to
* obtain a unique identifier for the client. The server uses
* this identifier to figure out whether or not two RX connections
* are from the same client, and to find out which addresses go
* with which clients.
*
* Arguments:
* rxcall : Ptr to Rx call on which this request came in.
* addr: Ptr to return the list of interfaces for this client.
*
* Returns:
* 0 (Always)
*
* Environment:
* Nothing interesting.
*
* Side Effects:
* As advertised.
*------------------------------------------------------------------------*/
afs_int32
SRXAFSCB_WhoAreYou(struct rx_call * rxcall, struct interfaceAddr * addr)
{
#if FSPROBE_CALLBACK_VERBOSE
static char rn[] = "SRXAFSCB_WhoAreYou"; /*Routine name */
char hostName[256]; /*Host name buffer */
char *hostNameResult; /*Ptr to static */
if (rxcall != (struct rx_call *)0) {
hostNameResult =
hostutil_GetNameByINet((afs_int32) (rxcall->conn->peer->host));
strcpy(hostName, hostNameResult);
fprintf(stderr, "[%s:%s] Called from host %s, port %d\n", mn, rn,
hostName, rxcall->conn->peer->port);
} /*Valid rxcall param */
#endif /* FSPROBE_CALLBACK_VERBOSE */
if (rxcall && addr) {
if (!afs_cb_inited)
init_afs_cb();
*addr = afs_cb_interface;
}
/*
* Return successfully.
*/
return (0);
}
/*------------------------------------------------------------------------
* EXPORTED SRXAFSCB_InitCallBackState3
*
* Description:
* Routine called by the server-side callback RPC interface to
* implement clearing all callbacks from this host.
*
* Arguments:
* rxcall : Ptr to Rx call on which this request came in.
*
* Returns:
* 0 (always).
*
* Environment:
* Nothing interesting.
*
* Side Effects:
* As advertised.
*------------------------------------------------------------------------*/
afs_int32
SRXAFSCB_InitCallBackState3(struct rx_call * rxcall, afsUUID * uuidp)
{
#if FSPROBE_CALLBACK_VERBOSE
static char rn[] = "SRXAFSCB_InitCallBackState2"; /*Routine name */
char hostName[256]; /*Host name buffer */
char *hostNameResult; /*Ptr to static */
if (rxcall != (struct rx_call *)0) {
hostNameResult =
hostutil_GetNameByINet((afs_int32) (rxcall->conn->peer->host));
strcpy(hostName, hostNameResult);
fprintf(stderr, "[%s:%s] Called from host %s, port %d\n", mn, rn,
hostName, rxcall->conn->peer->port);
} /*Valid rxcall param */
#endif /* FSPROBE_CALLBACK_VERBOSE */
/*
* Return successfully.
*/
return (0);
}
/*------------------------------------------------------------------------
* EXPORTED SRXAFSCB_ProbeUuid
*
* Description:
* Routine called by the server-side callback RPC interface to
* implement ``probing'' the Cache Manager, just making sure it's
* still there is still the same client it used to be.
*
* Arguments:
* rxcall : Ptr to Rx call on which this request came in.
* uuidp : Ptr to UUID that must match the client's UUID.
*
* Returns:
* 0 if uuidp matches the UUID for this client
* Non-zero otherwize
*
* Environment:
* Nothing interesting.
*
* Side Effects:
* As advertised.
*------------------------------------------------------------------------*/
afs_int32
SRXAFSCB_ProbeUuid(struct rx_call * rxcall, afsUUID * uuidp)
{
int code = 0;
#if FSPROBE_CALLBACK_VERBOSE
static char rn[] = "SRXAFSCB_ProbeUuid"; /*Routine name */
char hostName[256]; /*Host name buffer */
char *hostNameResult; /*Ptr to static */
if (rxcall != (struct rx_call *)0) {
hostNameResult =
hostutil_GetNameByINet((afs_int32) (rxcall->conn->peer->host));
strcpy(hostName, hostNameResult);
fprintf(stderr, "[%s:%s] Called from host %s, port %d\n", mn, rn,
hostName, rxcall->conn->peer->port);
} /*Valid rxcall param */
#endif /* FSPROBE_CALLBACK_VERBOSE */
if (!afs_cb_inited)
init_afs_cb();
if (!afs_uuid_equal(uuidp, &afs_cb_interface.uuid))
code = 1; /* failure */
return code;
}
/*------------------------------------------------------------------------
* EXPORTED SRXAFSCB_GetServerPrefs
*
* Description:
* Routine to list server preferences used by this client.
*
* Arguments:
* a_call : Ptr to Rx call on which this request came in.
* a_index : Input server index
* a_srvr_addr : Output server address (0xffffffff on last server)
* a_srvr_rank : Output server rank
*
* Returns:
* 0 on success
*
* Environment:
* Nothing interesting.
*
* Side Effects:
* As advertised.
*------------------------------------------------------------------------*/
afs_int32
SRXAFSCB_GetServerPrefs(struct rx_call * a_call, afs_int32 a_index,
afs_int32 * a_srvr_addr, afs_int32 * a_srvr_rank)
{
*a_srvr_addr = 0xffffffff;
*a_srvr_rank = 0xffffffff;
return 0;
}
/*------------------------------------------------------------------------
* EXPORTED SRXAFSCB_GetCellServDB
*
* Description:
* Routine to list cells configured for this client
*
* Arguments:
* a_call : Ptr to Rx call on which this request came in.
* a_index : Input cell index
* a_name : Output cell name ("" on last cell)
* a_hosts : Output cell database servers
*
* Returns:
* RXGEN_OPCODE (always)
*
* Environment:
* Nothing interesting.
*
* Side Effects:
* As advertised.
*------------------------------------------------------------------------*/
afs_int32
SRXAFSCB_GetCellServDB(struct rx_call * a_call, afs_int32 a_index,
char **a_name, serverList * a_hosts)
{
return RXGEN_OPCODE;
}
afs_int32
SRXAFSCB_GetCellByNum(struct rx_call * a_call, afs_int32 a_cellnum,
char **a_name, serverList * a_hosts)
{
return RXGEN_OPCODE;
}
/*------------------------------------------------------------------------
* EXPORTED SRXAFSCB_GetLocalCell
*
* Description:
* Routine to return name of client's local cell
*
* Arguments:
* a_call : Ptr to Rx call on which this request came in.
* a_name : Output cell name
*
* Returns:
* RXGEN_OPCODE (always)
*
* Environment:
* Nothing interesting.
*
* Side Effects:
* As advertised.
*------------------------------------------------------------------------*/
afs_int32
SRXAFSCB_GetLocalCell(struct rx_call * a_call, char **a_name)
{
return RXGEN_OPCODE;
}
/*------------------------------------------------------------------------
* EXPORTED SRXAFSCB_GetCacheConfig
*
* Description:
* Routine to return parameters used to initialize client cache.
* Client may request any format version. Server may not return
* format version greater than version requested by client.
*
* Arguments:
* a_call: Ptr to Rx call on which this request came in.
* callerVersion: Data format version desired by the client.
* serverVersion: Data format version of output data.
* configCount: Number bytes allocated for output data.
* config: Client cache configuration.
*
* Returns:
* RXGEN_OPCODE (always)
*
* Environment:
* Nothing interesting.
*
* Side Effects:
* As advertised.
*------------------------------------------------------------------------*/
afs_int32
SRXAFSCB_GetCacheConfig(struct rx_call * a_call, afs_uint32 callerVersion,
afs_uint32 * serverVersion, afs_uint32 * configCount,
cacheConfig * config)
{
return RXGEN_OPCODE;
}
afs_int32
SRXAFSCB_TellMeAboutYourself(struct rx_call * rxcall,
struct interfaceAddr * addr,
Capabilities * capabilities)
{
#if FSPROBE_CALLBACK_VERBOSE
static char rn[] = "SRXAFSCB_TellMeAboutYourself"; /*Routine name */
char hostName[256]; /*Host name buffer */
char *hostNameResult; /*Ptr to static */
if (rxcall != (struct rx_call *)0) {
hostNameResult =
hostutil_GetNameByINet((afs_int32) (rxcall->conn->peer->host));
strcpy(hostName, hostNameResult);
fprintf(stderr, "[%s:%s] Called from host %s, port %d\n", mn, rn,
hostName, rxcall->conn->peer->port);
} /*Valid rxcall param */
#endif /* FSPROBE_CALLBACK_VERBOSE */
if (rxcall && addr) {
if (!afs_cb_inited)
init_afs_cb();
*addr = afs_cb_interface;
}
/*
* Return successfully.
*/
return (0);
}
int SRXAFSCB_GetDE(struct rx_call *a_call, afs_int32 a_index,
afs_int32 addr, afs_int32 inode, afs_int32 flags,
afs_int32 time, char ** fileName)
{
return RXGEN_OPCODE;
}
|
djh329/Jarvis_Mark_7
|
RPi/src/text/app.js
|
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://test.mosquitto.org')
var {SPEECH_INPUT} = require('../constants');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
client.on('connect', function () {
console.log('Connected!')
readTerm()
})
function readTerm() {
rl.question('Give an input? ', (answer) => {
client.publish(SPEECH_INPUT, `${answer}`)
readTerm()
});
}
|
getcircle/circle-android
|
app/src/main/java/com/rhlabs/circle/adapters/ProfileListAdapter.java
|
package com.rhlabs.circle.adapters;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.rhlabs.circle.R;
import com.rhlabs.circle.models.Card;
import com.rhlabs.circle.utils.DateUtils;
import com.rhlabs.circle.views.CircleImageView;
import com.rhlabs.protobufs.services.organization.containers.LocationV1;
import com.rhlabs.protobufs.services.organization.containers.TeamV1;
import com.rhlabs.protobufs.services.profile.containers.ProfileV1;
import java.util.ArrayList;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by anju on 5/8/15.
*/
public class ProfileListAdapter extends ArrayAdapter {
private Context mContext;
private Card.CardType mCardType;
public ProfileListAdapter(Context context, ArrayList objects) {
super(context, R.layout.view_profile_item, objects);
mContext = context;
}
static class ViewHolder {
@InjectView(R.id.tvProfileName)
TextView profileNameTextView;
@InjectView(R.id.tvProfileSecondaryInfo)
TextView profileSecondaryInfoTextView;
@InjectView(R.id.civProfileImageView)
CircleImageView profileImageView;
public ViewHolder(View view) {
ButterKnife.inject(this, view);
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
// Set and cache the view holder
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.view_profile_item, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Object object = getItem(position);
if (object instanceof ProfileV1) {
setProfile(viewHolder, (ProfileV1) object);
} else if (object instanceof TeamV1) {
setTeam(viewHolder, (TeamV1) object);
} else if (object instanceof LocationV1) {
setLocation(viewHolder, (LocationV1) object);
}
return convertView;
}
public void setCardType(Card.CardType cardType) {
mCardType = cardType;
}
private void setLocation(ViewHolder viewHolder, LocationV1 locationV1) {
String numberOfPeopleString = mContext.getString(R.string.number_of_people_singular);
if (locationV1.profile_count != null && locationV1.profile_count > 1) {
numberOfPeopleString = String.format(
mContext.getString(R.string.number_of_people_plural),
locationV1.profile_count
);
}
viewHolder.profileImageView.setLocation(locationV1);
viewHolder.profileNameTextView.setText(locationV1.name);
viewHolder.profileSecondaryInfoTextView.setText(numberOfPeopleString);
}
private void setTeam(ViewHolder viewHolder, TeamV1 teamV1) {
String secondaryInfoString = "";
if (teamV1.child_team_count != null && teamV1.child_team_count > 0) {
if (teamV1.child_team_count == 1) {
secondaryInfoString += mContext.getString(R.string.number_of_teams_singular);
}
else {
secondaryInfoString += String.format(
mContext.getString(R.string.number_of_teams_plural),
teamV1.child_team_count
);
}
secondaryInfoString += ", ";
}
if (teamV1.profile_count != null && teamV1.profile_count > 0) {
if (teamV1.profile_count == 1) {
secondaryInfoString += mContext.getString(R.string.number_of_people_singular);
}
else {
secondaryInfoString += String.format(
mContext.getString(R.string.number_of_people_plural),
teamV1.profile_count
);
}
}
viewHolder.profileImageView.lettersView.setVisibility(View.INVISIBLE);
viewHolder.profileImageView.imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
viewHolder.profileImageView.imageView.setImageDrawable(
ContextCompat.getDrawable(mContext, R.drawable.ic_feedreports)
);
viewHolder.profileNameTextView.setText(teamV1.name);
viewHolder.profileSecondaryInfoTextView.setText(secondaryInfoString);
}
private void setProfile(final ViewHolder viewHolder, ProfileV1 profileV1) {
viewHolder.profileImageView.setProfile(profileV1);
String secondaryInfo = profileV1.title;
if (mCardType != null) {
switch (mCardType) {
case Birthdays:
secondaryInfo = DateUtils.getFormattedBirthDate(profileV1.birth_date);
break;
case NewHires:
secondaryInfo = DateUtils.getFormattedNewHireDate(profileV1.hire_date);
break;
case Anniversaries:
secondaryInfo = DateUtils.getFormattedWorkAnniversaryDate(profileV1.hire_date);
break;
default:
break;
}
}
viewHolder.profileNameTextView.setText(profileV1.full_name);
viewHolder.profileSecondaryInfoTextView.setText(secondaryInfo);
}
}
|
pjworkspace/wscs
|
wscs-model/src/main/java/com/xxx/market/model/base/BaseCompTicket.java
|
<filename>wscs-model/src/main/java/com/xxx/market/model/base/BaseCompTicket.java<gh_stars>0
package com.xxx.market.model.base;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.IBean;
/**
* Generated by JFinal, do not modify this file.
*/
@SuppressWarnings("serial")
public abstract class BaseCompTicket<M extends BaseCompTicket<M>> extends Model<M> implements IBean {
public void setId(java.lang.Long id) {
set("id", id);
}
public java.lang.Long getId() {
return get("id");
}
public void setCompVerifyTicket(java.lang.String compVerifyTicket) {
set("comp_verify_ticket", compVerifyTicket);
}
public java.lang.String getCompVerifyTicket() {
return get("comp_verify_ticket");
}
public void setCreated(java.util.Date created) {
set("created", created);
}
public java.util.Date getCreated() {
return get("created");
}
public void setUpdated(java.util.Date updated) {
set("updated", updated);
}
public java.util.Date getUpdated() {
return get("updated");
}
}
|
henrikingo/dsi
|
bin/tests/test_config_test_control.py
|
''' Test config_test_control.py '''
import logging
import os
import unittest
from mock import Mock, patch
from testfixtures import LogCapture
import test_control
from common.config import ConfigDict
from common.remote_host import RemoteHost
from test_lib.fixture_files import FixtureFiles
FIXTURE_FILES = FixtureFiles(dir_name=os.path.dirname(__file__), subdir_name='config_test_control')
class TestConfigTestControl(unittest.TestCase):
''' Test config_test_control.py'''
def setUp(self):
"""
Setup basic environment
"""
# Mocking `ConfigDict.assert_valid_ids` because it enforces structural constraints on yaml
# files that aren't necessary here.
with patch('common.config.ConfigDict.assert_valid_ids') as mock_assert_valid_ids:
prev_dir = os.getcwd()
os.chdir(FIXTURE_FILES.fixture_dir_path)
self.config = ConfigDict('test_control')
self.config.load()
mock_assert_valid_ids.assert_called_once()
os.chdir(prev_dir)
def test_benchrun_workload_config(self):
"""
Test that generate_config_files works with a benchrun workload
"""
test = self.config['test_control']['run'][0]
mock_host = Mock(spec=RemoteHost)
test_control.generate_config_file(test, FIXTURE_FILES.fixture_dir_path, mock_host)
self.assertEqual(FIXTURE_FILES.load_yaml_file('workloads.yml'),
FIXTURE_FILES.load_yaml_file('workloads.benchrun.yml.ok'),
'workloads.yml doesn\'t match expected for test_control.yml')
mock_host.upload_file.assert_called_once_with(
FIXTURE_FILES.fixture_file_path(test['config_filename']), test['config_filename'])
def test_ycsb_workload_config(self):
"""
Test that generate_config_files works with a ycsb run
"""
test = self.config['test_control']['run'][1]
mock_host = Mock(spec=RemoteHost)
test_control.generate_config_file(test, FIXTURE_FILES.fixture_dir_path, mock_host)
self.assertEqual(FIXTURE_FILES.load_yaml_file('workloadEvergreen'),
FIXTURE_FILES.load_yaml_file('workloadEvergreen.ok'),
'workloadEvergreen doesn\'t match expected for test_control.yml')
mock_host.upload_file.assert_called_once_with(
FIXTURE_FILES.fixture_file_path(test['config_filename']), test['config_filename'])
@patch('test_control.open')
def test_generate_config_no_config(self, mock_open):
"""
Test that generate_config_file doesn't create a workload file and logs the correct message
if there is no config file
"""
test = self.config['test_control']['run'][2]
mock_host = Mock(spec=RemoteHost)
with LogCapture(level=logging.WARNING) as warning:
test_control.generate_config_file(test, FIXTURE_FILES.fixture_dir_path, mock_host)
warning.check(('test_control', 'WARNING', 'No workload config in test control'))
mock_open.assert_not_called()
mock_host.upload_file.assert_not_called()
if __name__ == '__main__':
unittest.main()
|
scottyrogers10/6502-js
|
src/library/utils/styles/index.js
|
import jssToClassName from "./jss-to-class-name";
export { jssToClassName };
|
ouonline/lua-cpp
|
lua_function.h
|
#ifndef __LUA_CPP_LUA_FUNCTION_H__
#define __LUA_CPP_LUA_FUNCTION_H__
#include "lua_object.h"
#include "lua_user_data.h"
#include "func_utils.h"
#include <string>
namespace luacpp {
class LuaFunction final : public LuaObject {
public:
LuaFunction(lua_State* l, int index) : LuaObject(l, index) {}
LuaFunction(LuaObject&& lobj) : LuaObject(std::move(lobj)) {}
LuaFunction(const LuaObject& lobj) : LuaObject(lobj) {}
LuaFunction(LuaFunction&&) = default;
LuaFunction(const LuaFunction&) = default;
LuaFunction& operator=(LuaFunction&&) = default;
LuaFunction& operator=(const LuaFunction&) = default;
/** i starts from 0 */
template <typename... Argv>
bool Execute(const std::function<bool (uint32_t i, const LuaObject&)>& callback = nullptr,
std::string* errstr = nullptr, Argv&&... argv) {
PushSelf();
PushValues(m_l, std::forward<Argv>(argv)...);
return Invoke(callback, sizeof...(Argv), errstr);
}
private:
// i starts from 0
bool Invoke(const std::function<bool (uint32_t i, const LuaObject)>& callback, int argc,
std::string* errstr) {
const int top = lua_gettop(m_l) - argc - 1 /* the function itself */;
bool ok = (lua_pcall(m_l, argc, LUA_MULTRET, 0) == LUA_OK);
if (!ok) {
if (errstr) {
*errstr = lua_tostring(m_l, -1);
}
lua_pop(m_l, 1);
return false;
}
if (!callback) {
return true;
}
const int nresults = lua_gettop(m_l) - top;
for (int i = nresults; i > 0; --i) {
if (!callback(nresults - i, LuaObject(m_l, -i))) {
break;
}
}
if (nresults > 0) {
lua_pop(m_l, nresults);
}
return true;
}
};
}
#endif
|
hasaranga/RFC-Framework
|
rfc/security/KSHA1.cpp
|
<reponame>hasaranga/RFC-Framework
/*
RFC - KSHA1.cpp
Copyright (C) 2013-2019 CrownSoft
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 "KSHA1.h"
#include "../io/KFile.h"
#include "../external/sha1.h"
KSHA1::KSHA1()
{
}
KString KSHA1::GenerateFromString(const KString& text)
{
if (text.GetLength() == 0)
return KString();
ExtLibs::CSHA1 sha1;
sha1.Update((const UINT_8*)(const char*)text, text.GetLength());
sha1.Final();
char szReport[256];
szReport[0] = 0;
sha1.ReportHash(szReport, ExtLibs::CSHA1::REPORT_HEX);
return KString(szReport);
}
KString KSHA1::GenerateFromFile(const KString& fileName)
{
if (fileName.GetLength() == 0) // empty path
return KString();
if (!KFile::IsFileExists(fileName)) // file does not exists
return KString();
KFile file;
file.OpenFile(fileName, KFile::KREAD, false);
const DWORD fileSize = file.GetFileSize();
file.CloseFile();
if (fileSize == 0) // empty file
return KString();
ExtLibs::CSHA1 sha1;
sha1.HashFile((const char*)fileName);
sha1.Final();
char szReport[256];
szReport[0] = 0;
sha1.ReportHash(szReport, ExtLibs::CSHA1::REPORT_HEX);
return KString(szReport);
}
KSHA1::~KSHA1()
{
}
|
emmamcbryde/AuTuMN-1
|
autumn/models/sm_sir/detection.py
|
from typing import Tuple, Callable, Any, Optional, List
import numpy as np
from .parameters import TestingToDetection, Population
from autumn.core.inputs import get_population_by_agegroup
from autumn.settings import COVID_BASE_AGEGROUPS
from autumn.core.utils.utils import apply_moving_average
from autumn.model_features.curve import scale_up_function
from autumn.core.inputs.testing.eur_testing_data import (
get_uk_testing_numbers,
get_eu_testing_numbers,
)
from autumn.core.inputs.covid_au.queries import get_vic_testing_numbers
from autumn.core.inputs.covid_phl.queries import get_phl_subregion_testing_numbers
from autumn.core.inputs.covid_lka.queries import get_lka_testing_numbers
from autumn.core.inputs.covid_mmr.queries import get_mmr_testing_numbers
from autumn.core.inputs.covid_bgd.queries import get_coxs_bazar_testing_numbers
from autumn.core.inputs.owid.queries import get_international_testing_numbers
from autumn.core.inputs.covid_btn.queries import get_btn_testing_numbers
def get_testing_numbers_for_region(
country_iso3: str, subregion: Optional[str]
) -> Tuple[list, list]:
"""
Use the appropriate function to retrieve the testing numbers applicable to the region being modelled.
Functions are taken from the autumn input tools module, as above.
"""
subregion = subregion or False
if country_iso3 == "AUS":
test_dates, test_values = get_vic_testing_numbers()
elif country_iso3 == "PHL":
phl_region = subregion.lower() if subregion else "philippines"
test_dates, test_values = get_phl_subregion_testing_numbers(phl_region)
elif subregion == "Sabah":
test_dates, test_values = get_international_testing_numbers(country_iso3)
elif country_iso3 == "GBR":
test_dates, test_values = get_uk_testing_numbers()
elif country_iso3 in {"BEL", "ITA", "SWE", "FRA", "ESP"}:
test_dates, test_values = get_eu_testing_numbers(country_iso3)
elif country_iso3 == "LKA":
test_dates, test_values = get_lka_testing_numbers()
elif country_iso3 == "MMR":
test_dates, test_values = get_mmr_testing_numbers()
elif country_iso3 == "BGD" and subregion == "FDMN":
test_dates, test_values = get_coxs_bazar_testing_numbers()
elif country_iso3 == "BTN":
test_dates, test_values = get_btn_testing_numbers(subregion)
else:
test_dates, test_values = get_international_testing_numbers(country_iso3)
assert len(test_dates) == len(
test_values
), "Length of test dates and test values are not equal"
return test_dates, test_values
def create_cdr_function(assumed_tests: int, assumed_cdr: float, floor_value: float=0.) -> Callable:
"""
Factory function for finding CDRs from number of tests done in setting modelled
To work out the function, only one parameter is needed, so this can be estimated from one known point on the curve,
being a value of the CDR that is associated with a certain testing rate
Args:
assumed_tests: Value of CDR associated with the testing coverage
assumed_cdr: Number of tests needed to result in this CDR
floor_cdr: Floor value for the case detection rate
Returns:
Callable: Function to provide CDR for a certain number of tests
"""
# Find the single unknown parameter to the function - i.e. for minus b, where CDR = 1 - (1 - f) * exp(-b * t)
exponent_multiplier = np.log((1.0 - assumed_cdr) / (1.0 - floor_value)) / assumed_tests
# Construct the function based on this parameter
def cdr_function(tests_per_capita):
return 1.0 - np.exp(exponent_multiplier * tests_per_capita) * (1.0 - floor_value)
return cdr_function
def find_cdr_function_from_test_data(
test_detect_params, iso3: str, region: str, year: int
) -> Callable:
"""
Sort out case detection rate from testing numbers, sequentially calling the functions above as required.
"""
# Get the testing population denominator
testing_pops = get_population_by_agegroup(COVID_BASE_AGEGROUPS, iso3, region, year=year)
# Get the numbers of tests performed
test_dates, test_values = get_testing_numbers_for_region(iso3, region)
# Convert test numbers to per capita testing rates
per_capita_tests = [i_tests / sum(testing_pops) for i_tests in test_values]
# Smooth the testing data if requested
if test_detect_params.smoothing_period:
smoothed_per_capita_tests = apply_moving_average(
per_capita_tests, test_detect_params.smoothing_period
)
else:
smoothed_per_capita_tests = per_capita_tests
# Check data
msg = "Negative test values present"
assert all((val >= 0.0 for val in smoothed_per_capita_tests)), msg
# Calculate CDRs and the resulting CDR function
cdr_from_tests_func: Callable[[Any], float] = create_cdr_function(
test_detect_params.assumed_tests_parameter,
test_detect_params.assumed_cdr_parameter,
test_detect_params.floor_value,
)
# Get the final CDR function
cdr_function = scale_up_function(
test_dates,
[
cdr_from_tests_func(i_test_rate)
for i_test_rate in smoothed_per_capita_tests
],
smoothness=0.2,
method=4,
bound_low=0.0,
)
return cdr_function
def get_cdr_func(
detect_prop: float,
testing_params: TestingToDetection,
pop_params: Population,
iso3: str,
) -> Tuple[callable, callable]:
"""
The master function that can call various approaches to calculating the proportion of cases detected over time.
Currently just supporting two approaches, but would be the entry point if more approaches were added:
- Testing-based case detection
- Constant case detection fraction
Args:
detect_prop: Back-up single value to set a constant case detection rate over time
testing_params: Parameters to specify the relationship between CDR and testing, if requested
pop_params: Population-related parameters
iso3: Country code
Returns:
The case detection rate function of time
"""
if testing_params:
cdr_func = find_cdr_function_from_test_data(testing_params, iso3, pop_params.region, pop_params.year)
else:
def cdr_func(time, computed_values):
return detect_prop
def non_detect_func(time, computed_values):
return 1.0 - computed_values["cdr"]
return cdr_func, non_detect_func
|
scala-steward/reactive-aws-clients
|
reactive-aws-eks/core/src/main/scala/com/github/j5ik2o/reactive/aws/eks/model/ops/VpcConfigRequestOps.scala
|
<filename>reactive-aws-eks/core/src/main/scala/com/github/j5ik2o/reactive/aws/eks/model/ops/VpcConfigRequestOps.scala
// Auto-Generated
package com.github.j5ik2o.reactive.aws.eks.model.ops
import software.amazon.awssdk.services.eks.model._
final class VpcConfigRequestBuilderOps(val self: VpcConfigRequest.Builder) extends AnyVal {
@SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf"))
final def subnetIdsAsScala(value: Option[Seq[String]]): VpcConfigRequest.Builder = {
value.filter(_.nonEmpty).fold(self) { v =>
import com.github.j5ik2o.reactive.aws.utils.JavaCollectionHelper._; self.subnetIds(v.asJava)
}
}
@SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf"))
final def securityGroupIdsAsScala(value: Option[Seq[String]]): VpcConfigRequest.Builder = {
value.filter(_.nonEmpty).fold(self) { v =>
import com.github.j5ik2o.reactive.aws.utils.JavaCollectionHelper._; self.securityGroupIds(v.asJava)
}
}
@SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf"))
final def endpointPublicAccessAsScala(value: Option[Boolean]): VpcConfigRequest.Builder = {
value.fold(self) { v => self.endpointPublicAccess(v) }
}
@SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf"))
final def endpointPrivateAccessAsScala(value: Option[Boolean]): VpcConfigRequest.Builder = {
value.fold(self) { v => self.endpointPrivateAccess(v) }
}
@SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf"))
final def publicAccessCidrsAsScala(value: Option[Seq[String]]): VpcConfigRequest.Builder = {
value.filter(_.nonEmpty).fold(self) { v =>
import com.github.j5ik2o.reactive.aws.utils.JavaCollectionHelper._; self.publicAccessCidrs(v.asJava)
}
}
}
final class VpcConfigRequestOps(val self: VpcConfigRequest) extends AnyVal {
@SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf"))
final def subnetIdsAsScala: Option[Seq[String]] =
Option(self.subnetIds).map { v => import com.github.j5ik2o.reactive.aws.utils.JavaCollectionHelper._; v.asScala }
@SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf"))
final def securityGroupIdsAsScala: Option[Seq[String]] =
Option(self.securityGroupIds).map { v =>
import com.github.j5ik2o.reactive.aws.utils.JavaCollectionHelper._; v.asScala
}
@SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf"))
final def endpointPublicAccessAsScala: Option[Boolean] = Option(self.endpointPublicAccess)
@SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf"))
final def endpointPrivateAccessAsScala: Option[Boolean] = Option(self.endpointPrivateAccess)
@SuppressWarnings(Array("org.wartremover.warts.AsInstanceOf"))
final def publicAccessCidrsAsScala: Option[Seq[String]] =
Option(self.publicAccessCidrs).map { v =>
import com.github.j5ik2o.reactive.aws.utils.JavaCollectionHelper._; v.asScala
}
}
@SuppressWarnings(Array("org.wartremover.warts.ImplicitConversion"))
trait ToVpcConfigRequestOps {
implicit def toVpcConfigRequestBuilderOps(v: VpcConfigRequest.Builder): VpcConfigRequestBuilderOps =
new VpcConfigRequestBuilderOps(v)
implicit def toVpcConfigRequestOps(v: VpcConfigRequest): VpcConfigRequestOps = new VpcConfigRequestOps(v)
}
|
Specla/Validator
|
test/types/mixed.js
|
/* eslint-env mocha */
const { expect } = require('chai')
const { mixed } = require('../../lib/types')
const types = require('../utils/types')
describe('Type: mixed', () => {
it('Should accept all types', () => {
const validator = mixed({ optional: true })
for (const type in types) {
expect(validator(types[type])).to.be.equal(true)
}
})
it('Should be able to set one allowed type', () => {
const validator = mixed({ optional: true, allows: String })
const accepts = ['string', 'email', 'url', 'undefined', 'null']
for (const type in types) {
if (accepts.includes(type)) {
expect(validator(types[type])).to.be.equal(true)
} else {
expect(validator(types[type])).to.be.equal(false)
}
}
})
it('Should be able to set multiple allowed types', () => {
const validator = mixed({ optional: true, allows: [String, Number] })
const accepts = [
'string', 'email', 'url', 'number', 'integer', 'undefined', 'null'
]
for (const type in types) {
if (accepts.includes(type)) {
expect(validator(types[type])).to.be.equal(true)
} else {
expect(validator(types[type])).to.be.equal(false)
}
}
})
})
|
philschmid/gatsby-blog
|
src/components/reusecore/Alert/index.js
|
import React from 'react';
import PropTypes from 'prop-types';
import AlertStyle from './alert.style';
const Alert = ({ className, isMaterial, children, ...props }) => {
// Add all classs to an array
const addAllClasses = ['reusecore__alert'];
// className prop checking
if (className) {
addAllClasses.push(className);
}
// isMaterial prop checking
if (isMaterial) {
addAllClasses.push('is-material');
}
return (
<AlertStyle className={addAllClasses.join(' ')} {...props}>
{children}
</AlertStyle>
);
};
Alert.propTypes = {
/** ClassName of the Alert */
className: PropTypes.string,
/** Add Material effect */
isMaterial: PropTypes.bool,
/** Used to render icon, button, text or any elements inside the Alert.
* This can be a string or any component. */
children: PropTypes.element
};
Alert.defaultProps = {};
export default Alert;
|
SyedThaseemuddin/MPLAB-Harmony-Reference-Apps
|
apps/sam_e70_xult/ftp_bootloader/firmware/src/config/default/driver/miim/src/dynamic/drv_miim_mapping.h
|
<filename>apps/sam_e70_xult/ftp_bootloader/firmware/src/config/default/driver/miim/src/dynamic/drv_miim_mapping.h
/*******************************************************************************
MIIM Driver Local Data Structures
Company:
Microchip Technology Inc.
File Name:
drv_miim_local.h
Summary:
MIIM driver local declarations and definitions.
Description:
This file contains the MIIM driver's local declarations and definitions.
*******************************************************************************/
//DOM-IGNORE-BEGIN
/*****************************************************************************
Copyright (C) 2013-2018 Microchip Technology Inc. and its subsidiaries.
Microchip Technology Inc. and its subsidiaries.
Subject to your compliance with these terms, you may use Microchip software
and any derivatives exclusively with Microchip products. It is your
responsibility to comply with third party license terms applicable to your
use of third party software (including open source software) that may
accompany Microchip software.
THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A PARTICULAR
PURPOSE.
IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*****************************************************************************/
//DOM-IGNORE-END
#ifndef _DRV_MIIM_MAPPING_H
#define _DRV_MIIM_MAPPING_H
// *****************************************************************************
// *****************************************************************************
// Section: File includes
// *****************************************************************************
// *****************************************************************************
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include "device.h"
// *****************************************************************************
// *****************************************************************************
// Section: Data Type Definitions
// *****************************************************************************
// *****************************************************************************
//*****************************************************************************
/* MII Clock Selection
Summary:
Lists the possible speed selection for the Reduced Media Independent
Interface (RMII).
Description:
This enumeration lists the possible speed selection for RMII.
The body contains only two states: RMII_10Mbps or RMII_100Mbps.
Remarks:
This enumeration is processor specific and is defined in the processor-
specific header files (see processor.h).
*/
typedef enum {
GMAC_MIIM_SYSCLK_DIV_BY_8 /*DOM-IGNORE-BEGIN*/ = 0x00 /*DOM-IGNORE-END*/ ,
GMAC_MIIM_SYSCLK_DIV_BY_16 /*DOM-IGNORE-BEGIN*/ = 0x01 /*DOM-IGNORE-END*/ ,
GMAC_MIIM_SYSCLK_DIV_BY_32 /*DOM-IGNORE-BEGIN*/ = 0x02 /*DOM-IGNORE-END*/ ,
GMAC_MIIM_SYSCLK_DIV_BY_48 /*DOM-IGNORE-BEGIN*/ = 0x03 /*DOM-IGNORE-END*/ ,
GMAC_MIIM_SYSCLK_DIV_BY_64 /*DOM-IGNORE-BEGIN*/ = 0x04 /*DOM-IGNORE-END*/ ,
GMAC_MIIM_SYSCLK_DIV_BY_96 /*DOM-IGNORE-BEGIN*/ = 0x05 /*DOM-IGNORE-END*/ ,
} GMAC_MIIM_CLK;
static __inline__ DRV_MIIM_RESULT __attribute__((always_inline))_DRV_MIIM_ETH_ENABLE(uintptr_t ethPhyId)
{
return DRV_MIIM_RES_OK;
}
static __inline__ void __attribute__((always_inline))_DRV_MIIM_MII_RELEASE_RESET(uintptr_t ethPhyId)
{
}
static __inline__ void __attribute__((always_inline))_DRV_MIIM_SETUP_PREAMBLE(uintptr_t ethPhyId,const DRV_MIIM_SETUP* pSetUp)
{
}
static __inline__ void __attribute__((always_inline))_DRV_MIIM_SCAN_INCREMENT(uintptr_t ethPhyId,const DRV_MIIM_SETUP* pSetUp)
{
}
static __inline__ void __attribute__((always_inline))_DRV_MIIM_MNGMNT_PORT_ENABLE(uintptr_t ethPhyId)
{
GMAC_REGS->GMAC_NCR |= GMAC_NCR_MPE_Msk;
}
static __inline__ void __attribute__((always_inline))_DRV_MIIM_MNGMNT_PORT_DISABLE(uintptr_t ethPhyId)
{
GMAC_REGS->GMAC_NCR &= ~GMAC_NCR_MPE_Msk;
}
static __inline__ bool __attribute__((always_inline))_DRV_MIIM_IS_BUSY(uintptr_t ethPhyId)
{
if ((GMAC_REGS->GMAC_NSR & GMAC_NSR_IDLE_Msk) != GMAC_NSR_IDLE_Msk)
return true;
else
return false;
}
static __inline__ void __attribute__((always_inline))_DRV_MIIM_PHYADDR_SET(uintptr_t ethPhyId,DRV_MIIM_OP_DCPT* pOpDcpt)
{
}
static __inline__ DRV_MIIM_TXFER_STAT __attribute__((always_inline))_DRV_MIIM_OP_SCAN_ENABLE(uintptr_t ethPhyId)
{
return DRV_MIIM_TXFER_SCAN_STALE;
}
static __inline__ void __attribute__((always_inline))_DRV_MIIM_OP_WRITE_DATA(uintptr_t ethPhyId,DRV_MIIM_OP_DCPT* pOpDcpt)
{
GMAC_REGS->GMAC_MAN =
(~GMAC_MAN_WZO_Msk & GMAC_MAN_CLTTO_Msk)
| (GMAC_MAN_OP(0x1))
| GMAC_MAN_WTN(0x02)
| GMAC_MAN_PHYA(pOpDcpt->phyAdd)
| GMAC_MAN_REGA(pOpDcpt->regIx)
| GMAC_MAN_DATA(pOpDcpt->opData);
}
static __inline__ void __attribute__((always_inline))_DRV_MIIM_WRITE_START(uintptr_t ethPhyId)
{
}
static __inline__ void __attribute__((always_inline))_DRV_MIIM_OP_READ_START(uintptr_t ethPhyId, DRV_MIIM_OP_DCPT* pOpDcpt)
{
GMAC_REGS->GMAC_MAN = (~GMAC_MAN_WZO_Msk & GMAC_MAN_CLTTO_Msk)
| (GMAC_MAN_OP(0x2))
| GMAC_MAN_WTN(0x02)
| GMAC_MAN_PHYA(pOpDcpt->phyAdd)
| GMAC_MAN_REGA(pOpDcpt->regIx)
| GMAC_MAN_DATA(0);
}
static __inline__ uint16_t __attribute__((always_inline))_DRV_MIIM_OP_READ_DATA_GET(uintptr_t ethPhyId)
{
return (uint16_t)(GMAC_REGS->GMAC_MAN & GMAC_MAN_DATA_Msk) ;
}
static __inline__ void __attribute__((always_inline))_DRV_MIIM_CLEAR_DATA_VALID(uintptr_t ethPhyId)
{
}
static __inline__ bool __attribute__((always_inline))_DRV_MIIM_IS_DATA_VALID(uintptr_t ethPhyId)
{
return false;
}
static __inline__ void __attribute__((always_inline))_DRV_MIIM_SCAN_DISABLE(uintptr_t ethPhyId)
{
}
static __inline__ void __attribute__((always_inline)) _DRV_MIIM_SMI_CLOCK_SET(uintptr_t ethPhyId, uint32_t hostClock, uint32_t maxMIIMClock )
{
uint32_t mdc_div;
GMAC_MIIM_CLK clock_dividor ;
mdc_div = hostClock/maxMIIMClock;
if (mdc_div <= 8 )
{
clock_dividor = GMAC_MIIM_SYSCLK_DIV_BY_8;
}
else if (mdc_div <= 16 )
{
clock_dividor = GMAC_MIIM_SYSCLK_DIV_BY_16;
}
else if (mdc_div <= 32 )
{
clock_dividor = GMAC_MIIM_SYSCLK_DIV_BY_32;
}
else if (mdc_div <= 48 )
{
clock_dividor = GMAC_MIIM_SYSCLK_DIV_BY_48;
}
else if (mdc_div <= 64 )
{
clock_dividor = GMAC_MIIM_SYSCLK_DIV_BY_64;
}
else if (mdc_div <= 96 )
{
clock_dividor = GMAC_MIIM_SYSCLK_DIV_BY_96;
}
else
{
clock_dividor = 0;
}
GMAC_REGS->GMAC_NCR &= ~GMAC_NCR_TXEN_Msk;
GMAC_REGS->GMAC_NCR &= ~GMAC_NCR_RXEN_Msk;
GMAC_REGS->GMAC_NCFGR =
(GMAC_REGS->GMAC_NCFGR &
(~GMAC_NCFGR_CLK_Msk)) | (clock_dividor << GMAC_NCFGR_CLK_Pos);
GMAC_REGS->GMAC_NCR |= GMAC_NCR_TXEN_Msk;
GMAC_REGS->GMAC_NCR |= GMAC_NCR_RXEN_Msk;
}
#endif //#ifndef _DRV_MIIM_MAPPING_H
/*******************************************************************************
End of File
*/
|
R4stl1n/condex
|
models/IndexInfoModel.py
|
from peewee import *
from models.BaseModel import BaseModel
class IndexInfoModel(BaseModel):
Active = BooleanField()
TotalBTCVal = DoubleField()
TotalUSDVal = DoubleField()
BalanceThreshold = DoubleField()
OrderTimeout = IntegerField()
OrderRetryAmount = IntegerField()
RebalanceTickSetting = IntegerField()
|
scrutinizer-ci-testing/netguru-people
|
app/repositories/user_repository.rb
|
<reponame>scrutinizer-ci-testing/netguru-people
class UserRepository
def from_api(params)
search(id_or_email: params)
end
def where(params)
search(params).items
end
def active
User
.includes(
:location,
:contract_type,
:abilities,
:projects,
:roles,
:teams,
:previous_memberships,
current_memberships: [:project],
potential_memberships: [:project],
next_memberships: [:project],
booked_memberships: [:project],
last_membership: [:project],
primary_role: [:users])
.active.by_last_name.decorate
end
def items
search = UserSearch.new(search_params)
clear_search
search.results
end
def get(id)
User.find id
end
def all_by_name
User.includes(:projects, :teams).by_name
end
def find_by(attrs)
User.find_by attrs
end
def find_by_full_name(name)
User.find_by first_name: name.split[0], last_name: name.split[1]
end
private
def api_request_params(params)
params['id'].present? ? { id: params['id'] } : { email: params['email'] }
end
def search(params)
@search_params = search_params.merge(params)
self
end
def search_params
@search_params ||= {}
end
def clear_search
@search_params = nil
end
end
|
Keneral/apackages
|
services/Telecomm/src/com/android/server/telecom/CallIdMapper.java
|
<filename>services/Telecomm/src/com/android/server/telecom/CallIdMapper.java
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.telecom;
import android.util.ArrayMap;
import com.android.internal.annotations.VisibleForTesting;
import java.util.Map;
/** Utility to map {@link Call} objects to unique IDs. IDs are generated when a call is added. */
@VisibleForTesting
public class CallIdMapper {
/**
* A very basic bidirectional map.
*/
static class BiMap<K, V> {
private Map<K, V> mPrimaryMap = new ArrayMap<>();
private Map<V, K> mSecondaryMap = new ArrayMap<>();
public boolean put(K key, V value) {
if (key == null || value == null || mPrimaryMap.containsKey(key) ||
mSecondaryMap.containsKey(value)) {
return false;
}
mPrimaryMap.put(key, value);
mSecondaryMap.put(value, key);
return true;
}
public boolean remove(K key) {
if (key == null) {
return false;
}
if (mPrimaryMap.containsKey(key)) {
V value = getValue(key);
mPrimaryMap.remove(key);
mSecondaryMap.remove(value);
return true;
}
return false;
}
public boolean removeValue(V value) {
if (value == null) {
return false;
}
return remove(getKey(value));
}
public V getValue(K key) {
return mPrimaryMap.get(key);
}
public K getKey(V value) {
return mSecondaryMap.get(value);
}
public void clear() {
mPrimaryMap.clear();
mSecondaryMap.clear();
}
}
private final BiMap<String, Call> mCalls = new BiMap<>();
void replaceCall(Call newCall, Call callToReplace) {
// Use the old call's ID for the new call.
String callId = getCallId(callToReplace);
mCalls.put(callId, newCall);
}
void addCall(Call call, String id) {
if (call == null) {
return;
}
mCalls.put(id, call);
}
void addCall(Call call) {
addCall(call, call.getId());
}
void removeCall(Call call) {
if (call == null) {
return;
}
mCalls.removeValue(call);
}
void removeCall(String callId) {
mCalls.remove(callId);
}
String getCallId(Call call) {
if (call == null || mCalls.getKey(call) == null) {
return null;
}
return call.getId();
}
Call getCall(Object objId) {
String callId = null;
if (objId instanceof String) {
callId = (String) objId;
}
return mCalls.getValue(callId);
}
void clear() {
mCalls.clear();
}
}
|
AlgorithmLX/IndustrialLevel
|
build/tmp/expandedArchives/forge-1.18.1-39.0.0_mapped_official_1.18.1-sources.jar_f6a4a89164f1bd9335800eaab8a74a09/net/minecraft/world/level/levelgen/feature/configurations/NetherForestVegetationConfig.java
|
<filename>build/tmp/expandedArchives/forge-1.18.1-39.0.0_mapped_official_1.18.1-sources.jar_f6a4a89164f1bd9335800eaab8a74a09/net/minecraft/world/level/levelgen/feature/configurations/NetherForestVegetationConfig.java
package net.minecraft.world.level.levelgen.feature.configurations;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.util.ExtraCodecs;
import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider;
public class NetherForestVegetationConfig extends BlockPileConfiguration {
public static final Codec<NetherForestVegetationConfig> CODEC = RecordCodecBuilder.create((p_191267_) -> {
return p_191267_.group(BlockStateProvider.CODEC.fieldOf("state_provider").forGetter((p_191273_) -> {
return p_191273_.stateProvider;
}), ExtraCodecs.POSITIVE_INT.fieldOf("spread_width").forGetter((p_191271_) -> {
return p_191271_.spreadWidth;
}), ExtraCodecs.POSITIVE_INT.fieldOf("spread_height").forGetter((p_191269_) -> {
return p_191269_.spreadHeight;
})).apply(p_191267_, NetherForestVegetationConfig::new);
});
public final int spreadWidth;
public final int spreadHeight;
public NetherForestVegetationConfig(BlockStateProvider p_191263_, int p_191264_, int p_191265_) {
super(p_191263_);
this.spreadWidth = p_191264_;
this.spreadHeight = p_191265_;
}
}
|
Learnosity/lib-psychometrics
|
psychometrics-irt/src/main/java/com/itemanalysis/psychometrics/irt/estimation/ItemResponseFileSummary.java
|
<filename>psychometrics-irt/src/main/java/com/itemanalysis/psychometrics/irt/estimation/ItemResponseFileSummary.java
/**
* Copyright 2014 <NAME>
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itemanalysis.psychometrics.irt.estimation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.math3.stat.Frequency;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class ItemResponseFileSummary {
public ItemResponseFileSummary(){
}
public ItemResponseVector[] getResponseVectors(String fileName, boolean headerIncluded){
return getResponseVectors(new File(fileName), headerIncluded);
}
public ItemResponseVector[] getResponseVectors(File f, boolean headerIncluded){
String responseString = "";
String[] line = null;
ArrayList<ItemResponseVector> responseData = new ArrayList<ItemResponseVector>();
byte[] rv = null;
ItemResponseVector irv = null;
ItemResponseVector[] itemResponseVector = null;
try(BufferedReader br = new BufferedReader(new FileReader(f))){
if(headerIncluded) br.readLine();//skip header
while((responseString=br.readLine())!=null){
line = responseString.split(",");
rv = new byte[line.length];
for(int j=0;j<line.length;j++){
rv[j] = Byte.parseByte(line[j]);
}
irv = new ItemResponseVector(rv, 1.0);
responseData.add(irv);
}
itemResponseVector = new ItemResponseVector[responseData.size()];
for(int i=0;i<responseData.size();i++){
itemResponseVector[i] = responseData.get(i);
}
}catch(IOException ex){
ex.printStackTrace();
}
return itemResponseVector;
}
/**
* Reads a comma delimited file.
*
* @param f file to be summarized
* @param headerIncluded true if header included. False otherwise. The header will be omitted (ignored).
* @return
*/
public ItemResponseVector[] getResponseVectors(File f, int start, int nItems, boolean headerIncluded){
String responseString = "";
String[] line = null;
ArrayList<ItemResponseVector> responseData = new ArrayList<ItemResponseVector>();
int lineCount = 0;
byte[] rv = null;
ItemResponseVector irv = null;
ItemResponseVector[] itemResponseVector = null;
try(BufferedReader br = new BufferedReader(new FileReader(f))){
if(headerIncluded) br.readLine();//skip header
while((responseString=br.readLine())!=null){
line = responseString.split(",");
rv = new byte[nItems];
for(int j=0;j<nItems;j++){
rv[j] = Byte.parseByte(line[j+start]);
}
irv = new ItemResponseVector(rv, 1.0);
responseData.add(irv);
lineCount++;
}
itemResponseVector = new ItemResponseVector[lineCount];
for(int i=0;i<lineCount;i++){
itemResponseVector[i] = responseData.get(i);
}
}catch(IOException ex){
ex.printStackTrace();
}
return itemResponseVector;
}
/**
* Summarize comma delimited file. It will extract the data beginning in the column indicated by start
* and it will continue for nItems columns.
*
* @param f file to summarize
* @param start the column index of the first item. It is zero based. If teh data start in the first column, then start=0.
* @param nItems number of items to read from the file. It will begin at the column indicated by start.
* @param headerIncluded true if header is included. False otherwise. The header will be omitted.
* @return an array of item resposne vectors
*/
public ItemResponseVector[] getCondensedResponseVectors(File f, int start, int nItems, boolean headerIncluded){
Frequency freq = new Frequency();
String responseString = "";
try{
BufferedReader br = new BufferedReader(new FileReader(f));
String line = "";
String[] s = null;
if(headerIncluded) br.readLine();//skip header
while((line=br.readLine())!=null){
s = line.split(",");
line = "";
for(int j=0;j<nItems;j++){
line += s[j+start];
}
freq.addValue(line);
}
br.close();
}catch(IOException ex){
ex.printStackTrace();
}
ItemResponseVector[] responseData = new ItemResponseVector[freq.getUniqueCount()];
ItemResponseVector irv = null;
Iterator<Comparable<?>> iter = freq.valuesIterator();
int index = 0;
byte[] rv = null;
//create array of ItemResponseVector objects
while(iter.hasNext()){
Comparable<?> value = iter.next();
responseString = value.toString();
int n=responseString.length();
rv = new byte[n];
String response = "";
for (int i = 0;i < n; i++){
response = String.valueOf(responseString.charAt(i)).toString();
rv[i] = Byte.parseByte(response);
}
//create response vector objects
irv = new ItemResponseVector(rv, Long.valueOf(freq.getCount(value)).doubleValue());
responseData[index] = irv;
index++;
}
return responseData;
}
private ItemResponseVector[] readTapData(){
byte[][] tap = new byte[35][18];
try{
File f = FileUtils.toFile(this.getClass().getResource("/testdata/tap-data.txt"));
BufferedReader br = new BufferedReader(new FileReader(f));
String line = "";
String[] s = null;
int row = 0;
while((line=br.readLine())!=null){
s = line.split(",");
for(int j=0;j<s.length;j++){
tap[row][j] = Byte.parseByte(s[j]);
}
row++;
}
br.close();
}catch(IOException ex){
ex.printStackTrace();
}
Frequency freq = new Frequency();
for(int i=0;i<tap.length;i++){
freq.addValue(Arrays.toString(tap[i]));
}
ItemResponseVector[] responseData = new ItemResponseVector[freq.getUniqueCount()];
ItemResponseVector irv = null;
Iterator<Comparable<?>> iter = freq.valuesIterator();
int index = 0;
//create array of ItemResponseVector objects
while(iter.hasNext()){
//get response string from frequency summary and convert to byte array
Comparable<?> value = iter.next();
String s = value.toString();
s = s.substring(1,s.lastIndexOf("]"));
String[] sa = s.split(",");
byte[] rv = new byte[sa.length];
for(int i=0;i<sa.length;i++){
rv[i] = Byte.parseByte(sa[i].trim());
}
//create response vector objects
irv = new ItemResponseVector(rv, Long.valueOf(freq.getCount(value)).doubleValue());
responseData[index] = irv;
index++;
}
// //display results of summary
// for(int i=0;i<responseData.length;i++){
// System.out.println(responseData[i].toString() + ": " + responseData[i].getFrequency());
// }
return responseData;
}
}
|
GwtMaterialDesign/gmd-am4charts-demo
|
src/main/java/gmd/amcharts4/demo/client/application/charts/gauges/AnimatedGaugeDemo.java
|
/*
* #%L
* GwtMaterial
* %%
* Copyright (C) 2015 - 2018 GwtMaterialDesign
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package gmd.amcharts4.demo.client.application.charts.gauges;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.user.client.ui.Widget;
import gmd.amcharts4.demo.client.application.charts.ChartDemo;
import gwt.material.design.amcharts.client.Am4Charts;
import gwt.material.design.amcharts.client.Chart;
import gwt.material.design.amcharts.client.GaugeChart;
import gwt.material.design.amcharts.client.axis.ValueAxis;
import gwt.material.design.amcharts.client.dataitem.ValueAxisDataItem;
import gwt.material.design.amcharts.client.renderer.AxisRendererCircular;
import gwt.material.design.amcharts.client.tick.ClockHand;
import gwt.material.design.amcore.client.Am4Core;
import gwt.material.design.amcore.client.animation.Animation;
import gwt.material.design.amcore.client.animation.AnimationOptions;
import gwt.material.design.amcore.client.base.Percent;
import gwt.material.design.amcore.client.color.ColorSet;
import gwt.material.design.amcore.client.ui.Label;
public class AnimatedGaugeDemo implements ChartDemo {
private GaugeChart chart;
@Override
public void generate(Widget widget) {
chart = (GaugeChart) Am4Core.create(widget, Am4Charts.GaugeChart);
// create chart
chart.innerRadius = new Percent(82);
// Normal axis
ValueAxis axis = (ValueAxis) chart.xAxes.push(new ValueAxis());
axis.min = 0;
axis.max = 100;
axis.strictMinMax = true;
AxisRendererCircular rendererCircular1 = (AxisRendererCircular) axis.renderer;
rendererCircular1.radius = new Percent(80);
rendererCircular1.inside = true;
rendererCircular1.line.strokeOpacity = 1;
rendererCircular1.ticks.template.strokeOpacity = 1;
rendererCircular1.ticks.template.length = 10;
rendererCircular1.grid.template.disabled = true;
rendererCircular1.labels.template.radius = 40;
rendererCircular1.labels.template.adapter.add("text", (source, target) -> source + "%");
// Axis for ranges
ColorSet colorSet = new ColorSet();
ValueAxis axis2 = (ValueAxis) chart.xAxes.push(new ValueAxis());
axis2.min = 0;
axis2.max = 100;
axis2.strictMinMax = true;
AxisRendererCircular rendererCircular = (AxisRendererCircular) axis2.renderer;
rendererCircular.innerRadius = 10;
rendererCircular.labels.template.disabled = true;
rendererCircular.ticks.template.disabled = true;
rendererCircular.grid.template.disabled = true;
ValueAxisDataItem range0 = axis2.axisRanges.create();
range0.value = 0;
range0.endValue = 50;
range0.axisFill.fillOpacity = 1;
range0.axisFill.fill = colorSet.getIndex(0);
ValueAxisDataItem range1 = axis2.axisRanges.create();
range1.value = 50;
range1.endValue = 100;
range1.axisFill.fillOpacity = 1;
range1.axisFill.fill = colorSet.getIndex(2);
Label label = (Label) chart.radarContainer.createChild(Am4Core.Label);
label.isMeasured = false;
label.fontSize = 45;
label.x = new Percent(50);
label.y = new Percent(100);
label.horizontalCenter = "middle";
label.verticalCenter = "bottom";
label.text = "50%";
// Hand
ClockHand hand = chart.hands.push(new ClockHand());
hand.axis = axis2;
hand.innerRadius = new Percent(20);
hand.startWidth = 10;
hand.pin.disabled = true;
hand.value = 50;
hand.events.on("propertychanged", ev -> {
range0.endValue = ev.target.value;
range1.value = ev.target.value;
axis2.invalidate();
});
Scheduler.get().scheduleFixedDelay(() -> {
double value = Math.round(Math.random() * 100);
label.text = value + "%";
AnimationOptions<Double> op1 = new AnimationOptions();
op1.property = "value";
op1.to = value;
Animation animation = new Animation(hand, new AnimationOptions[]{op1}, 1000, Am4Core.ease.cubicOut);
animation.start();
return true;
}, 1000);
}
@Override
public String getImage() {
return "https://www.amcharts.com/wp-content/uploads/2016/08/demo_8418_none.png";
}
private void randomValue(ClockHand hand) {
hand.showValue(Math.random() * 100, 1000, Am4Core.ease.cubicOut);
}
@Override
public Chart getChart() {
return chart;
}
}
|
androidmalin/EffectiveJava
|
patterns_creational/abstract_factory_patterns/src/main/java/com/example/factory/absfactory/common/ConcreteFactoryA.java
|
<gh_stars>1-10
package com.example.factory.absfactory.common;
public class ConcreteFactoryA implements IAbstractFactory {
@Override
public IAbstractProductA makeProductA() {
return new ConcreteProductAWithFamilyA();
}
@Override
public IAbstractProductB makeProductB() {
return new ConcreteProductBWithFamilyA();
}
}
|
elguero/warewulf
|
internal/app/wwctl/profile/delete/main.go
|
<gh_stars>10-100
package delete
import (
"fmt"
"os"
"github.com/hpcng/warewulf/internal/pkg/node"
"github.com/hpcng/warewulf/internal/pkg/util"
"github.com/hpcng/warewulf/internal/pkg/wwlog"
"github.com/manifoldco/promptui"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
func CobraRunE(cmd *cobra.Command, args []string) error {
var count int
nodeDB, err := node.New()
if err != nil {
wwlog.Printf(wwlog.ERROR, "Failed to open node database: %s\n", err)
os.Exit(1)
}
profiles, err := nodeDB.FindAllProfiles()
if err != nil {
wwlog.Printf(wwlog.ERROR, "Could not load all profiles: %s\n", err)
os.Exit(1)
}
for _, r := range args {
for _, p := range profiles {
if p.Id.Get() == r {
nodes, err := nodeDB.FindAllNodes()
if err != nil {
wwlog.Printf(wwlog.ERROR, "Could not load all nodes: %s\n", err)
os.Exit(1)
}
for _, n := range nodes {
for _, np := range n.Profiles {
if np == r {
wwlog.Printf(wwlog.VERBOSE, "Removing profile from node %s: %s\n", n.Id.Get(), r)
n.Profiles = util.SliceRemoveElement(n.Profiles, r)
err := nodeDB.NodeUpdate(n)
if err != nil {
return errors.Wrap(err, "failed to update node")
}
}
}
}
}
}
}
for _, r := range args {
var found bool
for _, p := range profiles {
if p.Id.Get() == r {
count++
found = true
err := nodeDB.DelProfile(r)
if err != nil {
wwlog.Printf(wwlog.ERROR, "%s\n", err)
}
}
}
if !found {
fmt.Fprintf(os.Stderr, "Profile not found: %s\n", r)
}
}
if count == 0 {
fmt.Fprintf(os.Stderr, "No profiles found\n")
os.Exit(1)
}
if SetYes {
err := nodeDB.Persist()
if err != nil {
return errors.Wrap(err, "failed to persist nodedb")
}
} else {
q := fmt.Sprintf("Are you sure you want to delete %d profile(s)", count)
prompt := promptui.Prompt{
Label: q,
IsConfirm: true,
}
result, _ := prompt.Run()
if result == "y" || result == "yes" {
err := nodeDB.Persist()
if err != nil {
return errors.Wrap(err, "failed to persist nodedb")
}
}
}
return nil
}
|
JHetzel/Vagar
|
app/src/main/java/de/juliushetzel/sample/adapter/TaskListPropertyChangeCallback.java
|
<reponame>JHetzel/Vagar
package de.juliushetzel.sample.adapter;
import android.databinding.ObservableList;
import de.juliushetzel.sample.model.Task;
class TaskListPropertyChangeCallback extends ObservableList.OnListChangedCallback<ObservableList<Task>> {
private final TaskListAdapter mListAdapter;
TaskListPropertyChangeCallback(TaskListAdapter listAdapter) {
mListAdapter = listAdapter;
}
@Override
public void onChanged(ObservableList<Task> sender) {
mListAdapter.notifyDataSetChanged();
}
@Override
public void onItemRangeChanged(ObservableList<Task> sender, int positionStart, int itemCount) {
mListAdapter.notifyDataSetChanged();
}
@Override
public void onItemRangeInserted(ObservableList<Task> sender, int positionStart, int itemCount) {
mListAdapter.notifyDataSetChanged();
}
@Override
public void onItemRangeMoved(ObservableList<Task> sender, int fromPosition, int toPosition, int itemCount) {
mListAdapter.notifyDataSetChanged();
}
@Override
public void onItemRangeRemoved(ObservableList<Task> sender, int positionStart, int itemCount) {
mListAdapter.notifyDataSetChanged();
}
}
|
HappyTobi/fog-azure-rm
|
test/requests/network/test_check_network_interface_exists.rb
|
<gh_stars>10-100
require File.expand_path '../../test_helper', __dir__
# Test class for Check Network Interface Exists Request
class TestCheckNetworkInterfaceExists < Minitest::Test
def setup
@service = Fog::Network::AzureRM.new(credentials)
@network_client = @service.instance_variable_get(:@network_client)
@network_interfaces = @network_client.network_interfaces
end
def test_check_network_interface_exists_success
mocked_response = ApiStub::Requests::Network::NetworkInterface.create_network_interface_response(@network_client)
@network_interfaces.stub :get, mocked_response do
assert @service.check_network_interface_exists('fog-test-rg', 'fog-test-network-interface')
end
end
def test_check_network_interface_exists_failure
response = proc { raise MsRestAzure::AzureOperationError.new(nil, create_mock_response, 'error' => { 'message' => 'mocked exception', 'code' => 'ResourceNotFound' }) }
@network_interfaces.stub :get, response do
assert !@service.check_network_interface_exists('fog-test-rg', 'fog-test-network-interface')
end
end
def test_check_network_interface_resource_group_exists_failure
response = proc { raise MsRestAzure::AzureOperationError.new(nil, create_mock_response, 'error' => { 'message' => 'mocked exception', 'code' => 'ResourceGroupNotFound' }) }
@network_interfaces.stub :get, response do
assert !@service.check_network_interface_exists('fog-test-rg', 'fog-test-network-interface')
end
end
def test_check_network_interface_exists_exception
response = proc { raise MsRestAzure::AzureOperationError.new(nil, create_mock_response, 'error' => { 'message' => 'mocked exception', 'code' => 'Exception' }) }
@network_interfaces.stub :get, response do
assert_raises(MsRestAzure::AzureOperationError) { @service.check_network_interface_exists('fog-test-rg', 'fog-test-network-interface') }
end
end
end
|
iFindTA/YiBaoAssistantPro
|
YBAssistantPro/Vendors/Yuntx_FullLib_SDK/Manager/ECManagerBase.h
|
<filename>YBAssistantPro/Vendors/Yuntx_FullLib_SDK/Manager/ECManagerBase.h
//
// ECManagerBase.h
// CCPiPhoneSDK
//
// Created by jiazy on 14/11/5.
// Copyright (c) 2014年 ronglian. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "ECEnumDefs.h"
/**
* 管理基类
*/
@protocol ECManagerBase <NSObject>
@end
|
Phygon/aaf
|
test/com/XMLStoredFormat/XMLStoredFormatTest.cpp
|
<reponame>Phygon/aaf
//=---------------------------------------------------------------------=
//
// $Id$ $Name$
//
// The contents of this file are subject to the AAF SDK Public Source
// License Agreement Version 2.0 (the "License"); You may not use this
// file except in compliance with the License. The License is available
// in AAFSDKPSL.TXT, or you may obtain a copy of the License from the
// Advanced Media Workflow Association, Inc., or its successor.
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
// the License for the specific language governing rights and limitations
// under the License. Refer to Section 3.3 of the License for proper use
// of this Exhibit.
//
// WARNING: Please contact the Advanced Media Workflow Association,
// Inc., for more information about any additional licenses to
// intellectual property covering the AAF Standard that may be required
// to create and distribute AAF compliant products.
// (http://www.amwa.tv/policies).
//
// Copyright Notices:
// The Original Code of this file is Copyright 1998-2009, licensor of the
// Advanced Media Workflow Association. All rights reserved.
//
// The Initial Developer of the Original Code of this file and the
// licensor of the Advanced Media Workflow Association is
// British Broadcasting Corporation.
// All rights reserved.
//
//=---------------------------------------------------------------------=
#include "XMLStoredFormatTest.h"
struct CAAFInitialize
{
CAAFInitialize(const char *dllname = NULL)
{
HRESULT hr = AAFLoad(dllname);
if (!AAFRESULT_SUCCEEDED(hr))
{
fprintf(stderr, "Error : Failed to load the AAF library, ");
fprintf(stderr, "check environment variables -\n");
fprintf(stderr, " Windows - $PATH\n");
fprintf(stderr, " Unix/Linux - $LD_LIBRARY_PATH\n");
exit(hr);
}
}
~CAAFInitialize()
{
AAFUnload();
}
};
void report(bool passed)
{
if (passed)
{
printf("--> passed\n");
}
else
{
printf("--> FAILED\n");
}
}
IAAFFile* openFileForReading(const aafCharacter* fileName)
{
IAAFFile* file = 0;
checkResult(AAFFileOpenExistingRead(fileName, 0, &file));
return file;
}
void replaceCharacter(wchar_t* str, wchar_t c, wchar_t r)
{
wchar_t* tmp = wcschr(str, c);
*tmp = r;
}
static aafCharacter companyName[] = L"AMW Association";
static aafCharacter productName[] = L"XMLStoredFormatTest";
void saveCopy(const aafCharacter* inFileName, const aafCharacter* outFileName)
{
char tmp[256];
wcstombs(tmp, outFileName, 256);
remove(tmp);
IAAFFile* inFile = 0;
IAAFFile* outFile = 0;
checkResult(AAFFileOpenExistingRead(inFileName, 0, &inFile));
aafProductVersion_t v;
v.major = 0;
v.minor = 1;
v.tertiary = 0;
v.patchLevel = 0;
v.type = kAAFVersionUnknown;
const aafUID_t productUID =
{0xd3ec8680, 0x1e79, 0x48f9, {0x99, 0x41, 0x0a, 0x10, 0xa1, 0x68, 0x86, 0xaf}};
aafProductIdentification_t productInfo;
productInfo.companyName = companyName;
productInfo.productName = productName;
productInfo.productVersion = &v;
productInfo.productVersionString = 0;
productInfo.productID = productUID;
productInfo.platform = 0;
checkResult(AAFFileOpenNewModifyEx(outFileName, &kAAFFileKind_AafXmlText, 0, &productInfo, &outFile));
checkResult(inFile->SaveCopyAs(outFile));
checkResult(outFile->Close());
release(outFile);
checkResult(inFile->Close());
release(inFile);
}
void copyAndTouch(const aafCharacter* inFileName, const aafCharacter* outFileName)
{
char tmp[256];
wcstombs(tmp, outFileName, 256);
remove(tmp);
char copyCmd[512];
#if defined (_WIN32)
strcpy(copyCmd, "copy ");
#else
strcpy(copyCmd, "cp ");
#endif
wcstombs(tmp, inFileName, 256);
strcat(copyCmd, tmp);
wcstombs(tmp, outFileName, 256);
strcat(copyCmd, " ");
strcat(copyCmd, tmp);
#if defined (_WIN32)
// replace '/' separator with '\' for benefit of copy command
char* sep = copyCmd;
while ((sep = strchr(sep, '/')) != NULL)
{
*sep = '\\';
sep++;
}
#endif
int result = system(copyCmd);
if (result != 0)
{
fprintf(stderr, "\nSystem copy command returned '%0x', at line %d in %s\n", result,
__LINE__, __FILE__);
throw "System copy command failed";
}
IAAFFile* outFile = 0;
aafProductVersion_t v;
v.major = 0;
v.minor = 1;
v.tertiary = 0;
v.patchLevel = 0;
v.type = kAAFVersionUnknown;
const aafUID_t productUID =
{0xd3ec8680, 0x1e79, 0x48f9, {0x99, 0x41, 0x0a, 0x10, 0xa1, 0x68, 0x86, 0xaf}};
aafProductIdentification_t productInfo;
productInfo.companyName = companyName;
productInfo.productName = productName;
productInfo.productVersion = &v;
productInfo.productVersionString = 0;
productInfo.productID = productUID;
productInfo.platform = 0;
checkResult(AAFFileOpenExistingModify(outFileName, 0, &productInfo, &outFile));
checkResult(outFile->Save());
checkResult(outFile->Close());
release(outFile);
}
//
// NOTE: this diff breaks very easily !!
//
bool diff(const aafCharacter* fileNameA, const aafCharacter* fileNameB)
{
char tmp[256];
wcstombs(tmp, fileNameA, 256);
FILE* fileA = fopen(tmp, "r");
if (fileA == 0)
{
return true;
}
wcstombs(tmp, fileNameB, 256);
FILE* fileB = fopen(tmp, "r");
if (fileB == 0)
{
fclose(fileA);
return true;
}
char* bufferA = 0;
char* bufferB = 0;
bool diff = false;
size_t checkSize;
bufferA = new char[1048576];
bufferB = new char[1048576];
// read into memory
size_t numReadA = fread(bufferA, 1, 1048575, fileA);
bufferA[numReadA] = '\0';
size_t numReadB = fread(bufferB, 1, 1048575, fileB);
bufferB[numReadB] = '\0';
if (numReadA == 1048575 || numReadB == 1048575)
{
delete [] bufferA;
delete [] bufferB;
throw "Diff buffer too small - test update required";
}
checkSize = numReadA;
// blank out the LastModified
char* lastModA = strstr(bufferA, "<LastModified>");
char* lastModEndA = strstr(bufferA, "</LastModified>");
char* lastModB = strstr(bufferB, "<LastModified>");
char* lastModEndB = strstr(bufferB, "</LastModified>");
if ((lastModA == 0) != (lastModB == 0) ||
(lastModEndA == 0) != (lastModEndB == 0))
{
diff = true;
}
// replace last modified timestamp with spaces
if (lastModA != 0)
{
char* timestamp = lastModA + strlen("<LastModified>");
while (timestamp != lastModEndA)
{
*timestamp = ' ';
timestamp++;
}
timestamp = lastModB + strlen("<LastModified>");
while (timestamp != lastModEndB)
{
*timestamp = ' ';
timestamp++;
}
}
// check after <AAF
char* rootA = strstr(bufferA, "<AAF");
char* rootB = strstr(bufferB, "<AAF");
if (rootA == 0 || rootB == 0)
{
delete [] bufferA;
delete [] bufferB;
throw "No root element found";
}
// don't check after the identification list
char* idListA = strstr(bufferA, "<IdentificationList>");
char* idListB = strstr(bufferB, "<IdentificationList>");
if (idListA == 0 || idListB == 0)
{
diff = true;
}
checkSize = idListA - rootA;
if ((size_t)(idListB - rootB) < checkSize)
{
checkSize = idListB - rootB;
}
diff = diff || memcmp(rootA, rootB, checkSize) != 0;
delete [] bufferA;
delete [] bufferB;
fclose(fileA);
fclose(fileB);
return diff;
}
#define XML_NUM_TESTS 15
typedef struct {
const char *name;
int (*function)(void);
} XMLTests_t;
int main(int argc, char *argv[])
{
CAAFInitialize aafInit;
XMLTests_t tests[XML_NUM_TESTS] =
{
{"Character", testCharacter},
{"Enum", testEnum},
{"ExtEnum", testExtEnum},
{"FixedArray", testFixedArray},
{"Indirect", testIndirect},
{"Integer", testInteger},
{"Opaque", testOpaque},
{"Record", testRecord},
{"Rename", testRename},
{"Set", testSet},
{"Stream", testStream},
{"String", testString},
{"VarArray", testVarArray},
{"WeakRef", testWeakRef},
{"Examples", testExampleFiles}
};
printf("\n");
printf("**************************\n");
printf("* XML Stored Format Test *\n");
printf("**************************\n");
printf("\n");
printf("\nResults summary:\n");
bool passed = false;
for (unsigned int i = 0; i < XML_NUM_TESTS; i++)
{
if (argc > 1)
{
// If arguments supplied, only execute tests matching arguments
bool name_matched = false;
for (int n = 1; n < argc; n++)
{
if (strcmp(argv[n], tests[i].name) == 0)
name_matched = true;
}
if (! name_matched)
continue;
}
int result = tests[i].function();
printf(" %10s", tests[i].name);
if (result == 0)
{
printf("\t\tpassed\n");
passed = true;
}
else if (result == 1)
{
printf("\t\tpassed (with known FAILURES)\n");
passed = true;
}
else
{
printf("\t\tFAILED\n");
passed = false;
}
}
return passed ? 0 : 1;
}
|
gitter-badger/Starting-Out-With-C-Plus-Plus-Programming-Challenges
|
Chapter 04/009.cpp
|
<gh_stars>1-10
#include <iostream>
using namespace std;
int main()
{
// Constant variables
const float ONE_DOLLAR = 1.00,
PENNY = 0.01,
NICKEL = 0.05,
DIME = 0.10,
QUARTER = 0.25;
// Variables
float pennies,
nickels,
dimes,
quarters,
total_coins;
// explain
cout << "\nLet's see if your coins equal 1 dollar.\n";
cout << endl;
// Ask for pennies, nickels, dimes, and quarters.
cout << "How many pennies do you have? ";
cin >> pennies;
cout << "Nickels? ";
cin >> nickels;
cout << "Dimes? ";
cin >> dimes;
cout << "Quarters? ";
cin >> quarters;
// Format line break
cout << endl;
// Calculate total coins
total_coins += ((pennies *= PENNY) +
(nickels *= NICKEL) +
(dimes *= DIME) +
(quarters *= QUARTER));
// Decision statement
if (total_coins == ONE_DOLLAR)
{
cout << '$' << total_coins;
cout << " equal to $1." << endl;
}
else if (total_coins < ONE_DOLLAR)
{
cout << '$' << total_coins;
cout << " is less than $1. Re-run program and ";
cout << " Try again.\n";
}
else if (total_coins > ONE_DOLLAR)
{
cout << '$' << total_coins;
cout << " greater than $1. Re-run program and ";
cout << " Try again.\n";
}
// Format line break
cout << endl;
// Terminate program
return 0;
}
|
OutpostUniverse/op2-landlord
|
OP2-Landlord/Control.h
|
#pragma once
#include "NAS2D/NAS2D.h"
using namespace NAS2D;
/**
* \class Control
* \brief Implements a base for all GUI Controls to derive from.
*
* I know that this has already been effectively implemented in NAS2D_Gui. I rebuilt
* it here with some cleaner design paradigms in addition to the newer event system
* and with a stricter adherence to encapsulation principles.
*
* Basically, I want this new version of the Control class to replace the version
* that's currently part of NAS2D_Gui. The TextField and Button classes have both
* been moved to this system. Skinning is irrelevant for the moment.
*/
class Control
{
public:
typedef NAS2D::Signal<Control*> ResizeCallback;
typedef NAS2D::Signal<Control*> TextChangedCallback;
typedef NAS2D::Signal<float, float> PositionChangedCallback;
public:
Control();
virtual ~Control();
void font(const Font& font);
void position(const Point<float>& pos);
void position(float x, float y);
float positionX();
float positionY();
PositionChangedCallback& moved();
void highlight(bool highlight);
bool highlight() const;
void enabled(bool enabled);
bool enabled() const;
void visible(bool visible);
bool visible() const;
virtual void hide() { visible(false); }
virtual void show() { visible(true); }
const Rectangle<float>& rect() const;
virtual void hasFocus(bool focus);
bool hasFocus() const;
void text(const std::string& text);
const std::string& text() const;
TextChangedCallback& textChanged();
virtual void onMouseDown(NAS2D::EventHandler::MouseButton button, int x, int y) {};
virtual void onMouseUp(NAS2D::EventHandler::MouseButton button, int x, int y) {};
virtual void onMouseMotion(int x, int y, int dX, int dY) {};
virtual void onKeyDown(NAS2D::EventHandler::KeyCode key, NAS2D::EventHandler::KeyModifier mod, bool repeat) {};
virtual void onKeyUp(NAS2D::EventHandler::KeyCode key, NAS2D::EventHandler::KeyModifier mod) {};
void size(float _s);
void size(float w, float h);
void width(float w);
void height(float h);
float width() const;
float height() const;
ResizeCallback& resized();
virtual void update() {};
protected:
/**
* Called whenever the Control's position is changed.
*
* \param dX Difference in X Position.
* \param dY Difference in Y Position.
*/
virtual void positionChanged(float dX, float dY) { mPositionChanged(dX, dY); }
virtual void visibilityChanged(bool visible) {}
virtual void onFocusChanged() {};
virtual void onSizeChanged() { mResized(this); }
virtual void onTextChanged() { mTextChanged(this); };
virtual void onFontChanged() {};
const Font& font();
bool fontSet() const;
Rectangle<float>& _rect();
std::string& _text();
protected:
PositionChangedCallback mPositionChanged; /**< Callback fired whenever the position of the Control changes. */
ResizeCallback mResized;
TextChangedCallback mTextChanged;
private:
virtual void draw() {};
const Font* mFont; /**< Pointer to a Font object. Control DOES NOT own the pointer. */
std::string mText; /**< Internal text string. */
Rectangle<float> mRect; /**< Area of the Control. */
bool mEnabled; /**< Flag indicating whether or not the Control is enabled. */
bool mHasFocus; /**< Flag indicating that the Control has input focus. */
bool mVisible; /**< Flag indicating visibility of the Control. */
bool mHighlight; /**< Flag indicating that this Control is highlighted. */
};
|
TopDogger1/corrosion
|
net/java/games/input/Component$Identifier.java
|
package net.java.games.input;
public class Identifier {
private final String name;
protected Identifier(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public String toString() {
return this.name;
}
public static class Key extends Identifier {
public static final Identifier.Key VOID = new Identifier.Key("Void");
public static final Identifier.Key ESCAPE = new Identifier.Key("Escape");
public static final Identifier.Key _1 = new Identifier.Key("1");
public static final Identifier.Key _2 = new Identifier.Key("2");
public static final Identifier.Key _3 = new Identifier.Key("3");
public static final Identifier.Key _4 = new Identifier.Key("4");
public static final Identifier.Key _5 = new Identifier.Key("5");
public static final Identifier.Key _6 = new Identifier.Key("6");
public static final Identifier.Key _7 = new Identifier.Key("7");
public static final Identifier.Key _8 = new Identifier.Key("8");
public static final Identifier.Key _9 = new Identifier.Key("9");
public static final Identifier.Key _0 = new Identifier.Key("0");
public static final Identifier.Key MINUS = new Identifier.Key("-");
public static final Identifier.Key EQUALS = new Identifier.Key("=");
public static final Identifier.Key BACK = new Identifier.Key("Back");
public static final Identifier.Key TAB = new Identifier.Key("Tab");
public static final Identifier.Key Q = new Identifier.Key("Q");
public static final Identifier.Key W = new Identifier.Key("W");
public static final Identifier.Key E = new Identifier.Key("E");
public static final Identifier.Key R = new Identifier.Key("R");
public static final Identifier.Key T = new Identifier.Key("T");
public static final Identifier.Key Y = new Identifier.Key("Y");
public static final Identifier.Key U = new Identifier.Key("U");
public static final Identifier.Key I = new Identifier.Key("I");
public static final Identifier.Key O = new Identifier.Key("O");
public static final Identifier.Key P = new Identifier.Key("P");
public static final Identifier.Key LBRACKET = new Identifier.Key("[");
public static final Identifier.Key RBRACKET = new Identifier.Key("]");
public static final Identifier.Key RETURN = new Identifier.Key("Return");
public static final Identifier.Key LCONTROL = new Identifier.Key("Left Control");
public static final Identifier.Key A = new Identifier.Key("A");
public static final Identifier.Key S = new Identifier.Key("S");
public static final Identifier.Key D = new Identifier.Key("D");
public static final Identifier.Key F = new Identifier.Key("F");
public static final Identifier.Key G = new Identifier.Key("G");
public static final Identifier.Key H = new Identifier.Key("H");
public static final Identifier.Key J = new Identifier.Key("J");
public static final Identifier.Key K = new Identifier.Key("K");
public static final Identifier.Key L = new Identifier.Key("L");
public static final Identifier.Key SEMICOLON = new Identifier.Key(";");
public static final Identifier.Key APOSTROPHE = new Identifier.Key("'");
public static final Identifier.Key GRAVE = new Identifier.Key("~");
public static final Identifier.Key LSHIFT = new Identifier.Key("Left Shift");
public static final Identifier.Key BACKSLASH = new Identifier.Key("\\");
public static final Identifier.Key Z = new Identifier.Key("Z");
public static final Identifier.Key X = new Identifier.Key("X");
public static final Identifier.Key C = new Identifier.Key("C");
public static final Identifier.Key V = new Identifier.Key("V");
public static final Identifier.Key B = new Identifier.Key("B");
public static final Identifier.Key N = new Identifier.Key("N");
public static final Identifier.Key M = new Identifier.Key("M");
public static final Identifier.Key COMMA = new Identifier.Key(",");
public static final Identifier.Key PERIOD = new Identifier.Key(".");
public static final Identifier.Key SLASH = new Identifier.Key("/");
public static final Identifier.Key RSHIFT = new Identifier.Key("Right Shift");
public static final Identifier.Key MULTIPLY = new Identifier.Key("Multiply");
public static final Identifier.Key LALT = new Identifier.Key("Left Alt");
public static final Identifier.Key SPACE = new Identifier.Key(" ");
public static final Identifier.Key CAPITAL = new Identifier.Key("Caps Lock");
public static final Identifier.Key F1 = new Identifier.Key("F1");
public static final Identifier.Key F2 = new Identifier.Key("F2");
public static final Identifier.Key F3 = new Identifier.Key("F3");
public static final Identifier.Key F4 = new Identifier.Key("F4");
public static final Identifier.Key F5 = new Identifier.Key("F5");
public static final Identifier.Key F6 = new Identifier.Key("F6");
public static final Identifier.Key F7 = new Identifier.Key("F7");
public static final Identifier.Key F8 = new Identifier.Key("F8");
public static final Identifier.Key F9 = new Identifier.Key("F9");
public static final Identifier.Key F10 = new Identifier.Key("F10");
public static final Identifier.Key NUMLOCK = new Identifier.Key("Num Lock");
public static final Identifier.Key SCROLL = new Identifier.Key("Scroll Lock");
public static final Identifier.Key NUMPAD7 = new Identifier.Key("Num 7");
public static final Identifier.Key NUMPAD8 = new Identifier.Key("Num 8");
public static final Identifier.Key NUMPAD9 = new Identifier.Key("Num 9");
public static final Identifier.Key SUBTRACT = new Identifier.Key("Num -");
public static final Identifier.Key NUMPAD4 = new Identifier.Key("Num 4");
public static final Identifier.Key NUMPAD5 = new Identifier.Key("Num 5");
public static final Identifier.Key NUMPAD6 = new Identifier.Key("Num 6");
public static final Identifier.Key ADD = new Identifier.Key("Num +");
public static final Identifier.Key NUMPAD1 = new Identifier.Key("Num 1");
public static final Identifier.Key NUMPAD2 = new Identifier.Key("Num 2");
public static final Identifier.Key NUMPAD3 = new Identifier.Key("Num 3");
public static final Identifier.Key NUMPAD0 = new Identifier.Key("Num 0");
public static final Identifier.Key DECIMAL = new Identifier.Key("Num .");
public static final Identifier.Key F11 = new Identifier.Key("F11");
public static final Identifier.Key F12 = new Identifier.Key("F12");
public static final Identifier.Key F13 = new Identifier.Key("F13");
public static final Identifier.Key F14 = new Identifier.Key("F14");
public static final Identifier.Key F15 = new Identifier.Key("F15");
public static final Identifier.Key KANA = new Identifier.Key("Kana");
public static final Identifier.Key CONVERT = new Identifier.Key("Convert");
public static final Identifier.Key NOCONVERT = new Identifier.Key("Noconvert");
public static final Identifier.Key YEN = new Identifier.Key("Yen");
public static final Identifier.Key NUMPADEQUAL = new Identifier.Key("Num =");
public static final Identifier.Key CIRCUMFLEX = new Identifier.Key("Circumflex");
public static final Identifier.Key AT = new Identifier.Key("At");
public static final Identifier.Key COLON = new Identifier.Key("Colon");
public static final Identifier.Key UNDERLINE = new Identifier.Key("Underline");
public static final Identifier.Key KANJI = new Identifier.Key("Kanji");
public static final Identifier.Key STOP = new Identifier.Key("Stop");
public static final Identifier.Key AX = new Identifier.Key("Ax");
public static final Identifier.Key UNLABELED = new Identifier.Key("Unlabeled");
public static final Identifier.Key NUMPADENTER = new Identifier.Key("Num Enter");
public static final Identifier.Key RCONTROL = new Identifier.Key("Right Control");
public static final Identifier.Key NUMPADCOMMA = new Identifier.Key("Num ,");
public static final Identifier.Key DIVIDE = new Identifier.Key("Num /");
public static final Identifier.Key SYSRQ = new Identifier.Key("SysRq");
public static final Identifier.Key RALT = new Identifier.Key("Right Alt");
public static final Identifier.Key PAUSE = new Identifier.Key("Pause");
public static final Identifier.Key HOME = new Identifier.Key("Home");
public static final Identifier.Key UP = new Identifier.Key("Up");
public static final Identifier.Key PAGEUP = new Identifier.Key("Pg Up");
public static final Identifier.Key LEFT = new Identifier.Key("Left");
public static final Identifier.Key RIGHT = new Identifier.Key("Right");
public static final Identifier.Key END = new Identifier.Key("End");
public static final Identifier.Key DOWN = new Identifier.Key("Down");
public static final Identifier.Key PAGEDOWN = new Identifier.Key("Pg Down");
public static final Identifier.Key INSERT = new Identifier.Key("Insert");
public static final Identifier.Key DELETE = new Identifier.Key("Delete");
public static final Identifier.Key LWIN = new Identifier.Key("Left Windows");
public static final Identifier.Key RWIN = new Identifier.Key("Right Windows");
public static final Identifier.Key APPS = new Identifier.Key("Apps");
public static final Identifier.Key POWER = new Identifier.Key("Power");
public static final Identifier.Key SLEEP = new Identifier.Key("Sleep");
public static final Identifier.Key UNKNOWN = new Identifier.Key("Unknown");
protected Key(String name) {
super(name);
}
}
public static class Button extends Identifier {
public static final Identifier.Button _0 = new Identifier.Button("0");
public static final Identifier.Button _1 = new Identifier.Button("1");
public static final Identifier.Button _2 = new Identifier.Button("2");
public static final Identifier.Button _3 = new Identifier.Button("3");
public static final Identifier.Button _4 = new Identifier.Button("4");
public static final Identifier.Button _5 = new Identifier.Button("5");
public static final Identifier.Button _6 = new Identifier.Button("6");
public static final Identifier.Button _7 = new Identifier.Button("7");
public static final Identifier.Button _8 = new Identifier.Button("8");
public static final Identifier.Button _9 = new Identifier.Button("9");
public static final Identifier.Button _10 = new Identifier.Button("10");
public static final Identifier.Button _11 = new Identifier.Button("11");
public static final Identifier.Button _12 = new Identifier.Button("12");
public static final Identifier.Button _13 = new Identifier.Button("13");
public static final Identifier.Button _14 = new Identifier.Button("14");
public static final Identifier.Button _15 = new Identifier.Button("15");
public static final Identifier.Button _16 = new Identifier.Button("16");
public static final Identifier.Button _17 = new Identifier.Button("17");
public static final Identifier.Button _18 = new Identifier.Button("18");
public static final Identifier.Button _19 = new Identifier.Button("19");
public static final Identifier.Button _20 = new Identifier.Button("20");
public static final Identifier.Button _21 = new Identifier.Button("21");
public static final Identifier.Button _22 = new Identifier.Button("22");
public static final Identifier.Button _23 = new Identifier.Button("23");
public static final Identifier.Button _24 = new Identifier.Button("24");
public static final Identifier.Button _25 = new Identifier.Button("25");
public static final Identifier.Button _26 = new Identifier.Button("26");
public static final Identifier.Button _27 = new Identifier.Button("27");
public static final Identifier.Button _28 = new Identifier.Button("28");
public static final Identifier.Button _29 = new Identifier.Button("29");
public static final Identifier.Button _30 = new Identifier.Button("30");
public static final Identifier.Button _31 = new Identifier.Button("31");
public static final Identifier.Button TRIGGER = new Identifier.Button("Trigger");
public static final Identifier.Button THUMB = new Identifier.Button("Thumb");
public static final Identifier.Button THUMB2 = new Identifier.Button("Thumb 2");
public static final Identifier.Button TOP = new Identifier.Button("Top");
public static final Identifier.Button TOP2 = new Identifier.Button("Top 2");
public static final Identifier.Button PINKIE = new Identifier.Button("Pinkie");
public static final Identifier.Button BASE = new Identifier.Button("Base");
public static final Identifier.Button BASE2 = new Identifier.Button("Base 2");
public static final Identifier.Button BASE3 = new Identifier.Button("Base 3");
public static final Identifier.Button BASE4 = new Identifier.Button("Base 4");
public static final Identifier.Button BASE5 = new Identifier.Button("Base 5");
public static final Identifier.Button BASE6 = new Identifier.Button("Base 6");
public static final Identifier.Button DEAD = new Identifier.Button("Dead");
public static final Identifier.Button A = new Identifier.Button("A");
public static final Identifier.Button B = new Identifier.Button("B");
public static final Identifier.Button C = new Identifier.Button("C");
public static final Identifier.Button X = new Identifier.Button("X");
public static final Identifier.Button Y = new Identifier.Button("Y");
public static final Identifier.Button Z = new Identifier.Button("Z");
public static final Identifier.Button LEFT_THUMB = new Identifier.Button("Left Thumb");
public static final Identifier.Button RIGHT_THUMB = new Identifier.Button("Right Thumb");
public static final Identifier.Button LEFT_THUMB2 = new Identifier.Button("Left Thumb 2");
public static final Identifier.Button RIGHT_THUMB2 = new Identifier.Button("Right Thumb 2");
public static final Identifier.Button SELECT = new Identifier.Button("Select");
public static final Identifier.Button MODE = new Identifier.Button("Mode");
public static final Identifier.Button LEFT_THUMB3 = new Identifier.Button("Left Thumb 3");
public static final Identifier.Button RIGHT_THUMB3 = new Identifier.Button("Right Thumb 3");
public static final Identifier.Button TOOL_PEN = new Identifier.Button("Pen");
public static final Identifier.Button TOOL_RUBBER = new Identifier.Button("Rubber");
public static final Identifier.Button TOOL_BRUSH = new Identifier.Button("Brush");
public static final Identifier.Button TOOL_PENCIL = new Identifier.Button("Pencil");
public static final Identifier.Button TOOL_AIRBRUSH = new Identifier.Button("Airbrush");
public static final Identifier.Button TOOL_FINGER = new Identifier.Button("Finger");
public static final Identifier.Button TOOL_MOUSE = new Identifier.Button("Mouse");
public static final Identifier.Button TOOL_LENS = new Identifier.Button("Lens");
public static final Identifier.Button TOUCH = new Identifier.Button("Touch");
public static final Identifier.Button STYLUS = new Identifier.Button("Stylus");
public static final Identifier.Button STYLUS2 = new Identifier.Button("Stylus 2");
public static final Identifier.Button UNKNOWN = new Identifier.Button("Unknown");
public static final Identifier.Button BACK = new Identifier.Button("Back");
public static final Identifier.Button EXTRA = new Identifier.Button("Extra");
public static final Identifier.Button FORWARD = new Identifier.Button("Forward");
public static final Identifier.Button LEFT = new Identifier.Button("Left");
public static final Identifier.Button MIDDLE = new Identifier.Button("Middle");
public static final Identifier.Button RIGHT = new Identifier.Button("Right");
public static final Identifier.Button SIDE = new Identifier.Button("Side");
public Button(String name) {
super(name);
}
}
public static class Axis extends Identifier {
public static final Identifier.Axis X = new Identifier.Axis("x");
public static final Identifier.Axis Y = new Identifier.Axis("y");
public static final Identifier.Axis Z = new Identifier.Axis("z");
public static final Identifier.Axis RX = new Identifier.Axis("rx");
public static final Identifier.Axis RY = new Identifier.Axis("ry");
public static final Identifier.Axis RZ = new Identifier.Axis("rz");
public static final Identifier.Axis SLIDER = new Identifier.Axis("slider");
public static final Identifier.Axis SLIDER_ACCELERATION = new Identifier.Axis("slider-acceleration");
public static final Identifier.Axis SLIDER_FORCE = new Identifier.Axis("slider-force");
public static final Identifier.Axis SLIDER_VELOCITY = new Identifier.Axis("slider-velocity");
public static final Identifier.Axis X_ACCELERATION = new Identifier.Axis("x-acceleration");
public static final Identifier.Axis X_FORCE = new Identifier.Axis("x-force");
public static final Identifier.Axis X_VELOCITY = new Identifier.Axis("x-velocity");
public static final Identifier.Axis Y_ACCELERATION = new Identifier.Axis("y-acceleration");
public static final Identifier.Axis Y_FORCE = new Identifier.Axis("y-force");
public static final Identifier.Axis Y_VELOCITY = new Identifier.Axis("y-velocity");
public static final Identifier.Axis Z_ACCELERATION = new Identifier.Axis("z-acceleration");
public static final Identifier.Axis Z_FORCE = new Identifier.Axis("z-force");
public static final Identifier.Axis Z_VELOCITY = new Identifier.Axis("z-velocity");
public static final Identifier.Axis RX_ACCELERATION = new Identifier.Axis("rx-acceleration");
public static final Identifier.Axis RX_FORCE = new Identifier.Axis("rx-force");
public static final Identifier.Axis RX_VELOCITY = new Identifier.Axis("rx-velocity");
public static final Identifier.Axis RY_ACCELERATION = new Identifier.Axis("ry-acceleration");
public static final Identifier.Axis RY_FORCE = new Identifier.Axis("ry-force");
public static final Identifier.Axis RY_VELOCITY = new Identifier.Axis("ry-velocity");
public static final Identifier.Axis RZ_ACCELERATION = new Identifier.Axis("rz-acceleration");
public static final Identifier.Axis RZ_FORCE = new Identifier.Axis("rz-force");
public static final Identifier.Axis RZ_VELOCITY = new Identifier.Axis("rz-velocity");
public static final Identifier.Axis POV = new Identifier.Axis("pov");
public static final Identifier.Axis UNKNOWN = new Identifier.Axis("unknown");
protected Axis(String name) {
super(name);
}
}
}
|
gzacharski/AGH-Praca-inzynierska-front-end
|
src/main/components/timetable/appointmentTooltip/HeaderTooltip.js
|
<gh_stars>0
/* eslint-disable react/jsx-props-no-spreading */
import React, { useState } from 'react';
import { AppointmentTooltip } from '@devexpress/dx-react-scheduler-material-ui';
import { IconButton, Menu, MenuItem, Fade } from '@material-ui/core';
import { MoreVert } from '@material-ui/icons';
export const HeaderTooltip = ({ appointmentData, ...restProps }) => {
const [anchorEl, setAnchorEl] = useState(null);
const handleClick = (event) => setAnchorEl(event.currentTarget);
const handleClose = () => setAnchorEl(null);
return (
<AppointmentTooltip.Header
{...restProps}
appointmentData={appointmentData}
>
<IconButton
aria-haspopup="true"
onClick={(event) => handleClick(event)}
>
<MoreVert />
</IconButton>
<Menu
id="menu"
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={handleClose}
TransitionComponent={Fade}
>
<MenuItem>Dołącz</MenuItem>
<MenuItem>Oceń</MenuItem>
</Menu>
</AppointmentTooltip.Header>
);
};
|
timmy61109/C-How-to-Program
|
src/fig09_04.c
|
// Fig. 9.2: fig09_04.c
// Using filationg-point conversion specifiers
#include <stdio.h>
int main(int argc, char const *argv[]) {
printf("%e\n", 1234567.89);
printf("%e\n", +1234567.89);
printf("%e\n", -1234567.89);
printf("%E\n", 1234567.89);
printf("%f\n", 1234567.89);
printf("%g\n", 1234567.89);
printf("%G\n", 1234567.89);
}
|
jtama/quarkus-github-app
|
testing/src/main/java/io/quarkiverse/githubapp/testing/dsl/EventContextSpecification.java
|
package io.quarkiverse.githubapp.testing.dsl;
public interface EventContextSpecification {
<T extends Throwable> EventContextSpecification github(GitHubMockSetup<T> gitHubMockSetup) throws T;
EventSenderOptions when();
}
|
rehohoho/coiltraine
|
coilutils/experiment_schedule.py
|
from logger import monitorer
import heapq
def get_remainig_exps(executing_processes, experiment_list):
executing_list = []
for process in executing_processes:
executing_list.append(process['experiment'])
return list(set(experiment_list)- set(executing_list))
def get_gpu_resources(gpu_resources, executing_processes, allocation_params):
"""
Args:
allocated_gpus:
executing_processes:
allocation_params:
Returns:
"""
still_executing_processes = []
for process_specs in executing_processes:
# Make process name:
if process_specs['type'] == 'drive':
name = 'drive_' + process_specs['environment']
elif process_specs['type'] == 'validation':
name = 'validation_' + process_specs['dataset']
else:
name = process_specs['type']
status = monitorer.get_status(process_specs['folder'], process_specs['experiment'],
name)[0]
if status == "Finished" or status == 'Error':
gpu_resources[process_specs['gpu']] += allocation_params[process_specs['type']+'_cost']
else:
still_executing_processes.append(process_specs)
return gpu_resources, max(gpu_resources.values()), still_executing_processes
def allocate_gpu_resources(gpu_resources, amount_to_allocate):
"""
On GPU management allocate gpu resources considering a dictionary with resources
for each gpu
Args:
gpu_resources:
amount_to_allocate:
Returns:
"""
for gpu, resource in gpu_resources.items():
if resource >= amount_to_allocate:
gpu_resources[gpu] -= amount_to_allocate
return gpu_resources, max(gpu_resources.values()), gpu
raise ValueError("Not enough gpu resources to allocate")
def dict_to_namevec(process_dict):
"""
Converts a process dict to a name vec
"""
name_vec = ''
name_vec += process_dict['type']
if 'environment' in process_dict:
name_vec += process_dict['environment']
if 'dataset' in process_dict:
name_vec += process_dict['dataset']
name_vec += process_dict['experiment']
return name_vec
def execvec_to_names(executing_processes):
"""
Creates a name_vec for each the dictonary on the list of executing processss
Args:
List of executing process
returns
List of name vecs
"""
process_name_vec = []
for process_dict in executing_processes:
process_name_vec.append(dict_to_namevec(process_dict))
return process_name_vec
#TODO refactor.
def mount_experiment_heap(folder, experiments_list, is_training, executing_processes, old_tasks_queue,
validation_datasets, drive_environments, restart_error=True):
"""
Function that will add all the experiments to a heap. These experiments will
be consumed when there is enough resources
Args:
folder: The folder with the experiments
experiments_list: The list of all experiments to be executed
is_training: If Training is being add also ( NOT IMPLEMENTED)
executing_processes: The current processes being executed
old_tasks_queue: Current process on the task queue
validation_datasets: The validation datasets to be evaluated
drive_environments: All the driving environments where the models are going to be tested.
restart_error: If you are going to restart experiments that are not working (NOT implemented)
Returns:
"""
tasks_queue = []
exec_name_vec = execvec_to_names(executing_processes)
for experiment in experiments_list:
# Train is always priority.
task_to_add = None
if is_training:
if monitorer.get_status(folder, experiment, 'train')[0] == "Not Started":
task_to_add = (0, experiment + '_train',
{'type': 'train', 'folder': folder,
'experiment': experiment})
elif restart_error and monitorer.get_status(folder, experiment, 'train')[0] \
== "Error":
task_to_add = (0, experiment + '_train',
{'type': 'train', 'folder': folder,
'experiment': experiment})
if task_to_add is not None:
task_name_vec = dict_to_namevec(task_to_add[2])
if task_name_vec in exec_name_vec:
continue
if task_to_add is not None and task_to_add not in old_tasks_queue:
heapq.heappush(tasks_queue, task_to_add)
for val_data in validation_datasets:
task_to_add = None
if monitorer.get_status(folder, experiment, 'validation_' + val_data)[0] == "Not Started":
task_to_add = (1, experiment + '_validation_' + val_data,
{'type': 'validation', 'folder': folder,
'experiment': experiment, 'dataset': val_data})
elif restart_error and monitorer.get_status(folder, experiment, 'validation_'
+ val_data)[0] == "Error":
task_to_add = (1, experiment + '_validation_' + val_data,
{'type': 'validation', 'folder': folder,
'experiment': experiment, 'dataset': val_data})
if task_to_add is not None:
task_name_vec = dict_to_namevec(task_to_add[2])
if task_name_vec in exec_name_vec:
continue
if task_to_add is not None and task_to_add not in old_tasks_queue:
heapq.heappush(tasks_queue, task_to_add)
for drive_env in drive_environments:
task_to_add = None
if monitorer.get_status(folder, experiment, 'drive_' + drive_env)[0] == "Not Started":
task_to_add = (2, experiment + '_drive_' + drive_env,
{'type': 'drive', 'folder': folder,
'experiment': experiment, 'environment': drive_env})
elif restart_error and monitorer.get_status(folder, experiment, 'drive_' + drive_env)\
[0] == "Error":
task_to_add = (2, experiment + '_drive_' + drive_env,
{'type': 'drive', 'folder': folder,
'experiment': experiment, 'environment': drive_env})
if task_to_add is not None:
task_name_vec = dict_to_namevec(task_to_add[2])
if task_name_vec in exec_name_vec:
continue
if task_to_add is not None and task_to_add not in old_tasks_queue:
heapq.heappush(tasks_queue, task_to_add)
return tasks_queue
|
b8raoult/magics
|
src/attributes/EpsPlumeAttributes.h
|
/******************************* LICENSE *******************************
* (C) Copyright 1996-2016 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
******************************* LICENSE *******************************/
/*! \fileEpsPlumeAttributes.h
\brief Definition of EpsPlume Attributes class.
This file is automatically generated.
Do Not Edit!
Generated:
*/
#ifndef EpsPlumeAttributes_H
#define EpsPlumeAttributes_H
#include "magics.h"
#include "Colour.h"
namespace magics {
class XmlNode;
class EpsPlumeAttributes
{
public:
// -- constructor
EpsPlumeAttributes();
// -- destructor
virtual ~EpsPlumeAttributes();
virtual void set(const std::map<std::string, std::string>&);
virtual void set(const XmlNode&);
virtual void copy(const EpsPlumeAttributes&);
virtual bool accept(const std::string&);
void setTag(const std::string& tag) { tag_ = tag; }
public:
// -- method
virtual void print(std::ostream&) const;
virtual void toxml(std::ostream& out) const;
// -- members:
string tag_;
string method_;
bool legend_;
bool line_;
int line_thickness_;
bool forecast_;
int forecast_line_thickness_;
bool control_;
int control_line_thickness_;
bool median_;
int median_line_thickness_;
bool shading_;
doublearray shading_levels_;
stringarray shading_colours_;
unique_ptr<Colour> line_colour_;
LineStyle line_style_;
unique_ptr<Colour> forecast_line_colour_;
LineStyle forecast_line_style_;
unique_ptr<Colour> control_line_colour_;
LineStyle control_line_style_;
unique_ptr<Colour> median_line_colour_;
LineStyle median_line_style_;
private:
friend ostream& operator<<(ostream& s,const EpsPlumeAttributes& p)
{ p.print(s); return s; }
};
} // namespace magics
#endif
|
quqiangsheng/abhot
|
src/main/java/com/max256/abhot/core/datastore/TagSetImpl.java
|
<reponame>quqiangsheng/abhot<gh_stars>1-10
package com.max256.abhot.core.datastore;
import com.google.common.collect.TreeMultimap;
import java.util.Set;
/**
* TagSetImpl
* @author fbf
*
*/
public class TagSetImpl implements TagSet
{
private TreeMultimap<String, String> m_tags = TreeMultimap.create();
public void addTag(String name, String value)
{
m_tags.put(name, value);
}
@Override
public Set<String> getTagNames()
{
return (m_tags.keySet());
}
@Override
public Set<String> getTagValues(String tag)
{
return (m_tags.get(tag));
}
}
|
mbryles/devcon_reactor
|
src/main/java/com/blastingconcept/devcon/domain/post/PostRepository.java
|
<reponame>mbryles/devcon_reactor
package com.blastingconcept.devcon.domain.post;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public interface PostRepository {
Mono<Post> save(Post post);
Flux<Post> findAll();
Mono<Post> findById(String id);
Mono<Void> deleteById(String id);
Mono<Void> deleteAllUserPosts(String userId);
}
|
keiichi-hikita/eclsdk
|
ecl/dns/v2/_proxy.py
|
<reponame>keiichi-hikita/eclsdk
# 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.
from ecl import proxy2
from ecl.dns.v2 import zone as _zone
from ecl.dns.v2 import name_server
from ecl.dns.v2 import recordset as _recordset
class Proxy(proxy2.BaseProxy):
def zones(self):
"""
List the zones.
:return: A list of zone object
"""
return list(self._list(_zone.Zone))
def get_zone(self, zone):
"""
Show a Zone.
:param: zone: The value can be the ID of a zone or a
:class:`~ecl.dns.v2.zone.Zone` instance.
:return: One :class:`~ecl.dns.v2.zone.Zone` or
:class:`~ecl.exceptions.ResourceNotFound`when no
resource can be found.
"""
return self._get(_zone.Zone, zone)
def find_zone(self, name_or_id, ignore_missing=False):
"""
Find a zone by its name or ID
:param name_or_id: The name or ID of a zone
:param bool ignore_missing: When set to ``False``
:class:`~ecl.exceptions.ResourceNotFound` will be
raised when the resource does not exist.
When set to ``True``, None will be returned when
attempting to find a nonexistent resource.
:return: One :class:`~ecl.dns.v2.zone.Zone` or
:class:`~ecl.exceptions.ResourceNotFound`when no
resource can be found.
"""
return self._find(_zone.Zone, name_or_id, ignore_missing=ignore_missing)
def create_zone(self, name=None, ttl=None, type=None,
description=None, email=None, masters=None):
"""
Create a zone.
:param name: DNS Name for the zone. Required.
:param ttl: TTL (Time to Live) for the zone. This parameter is not currently supported.
:param type: Type of zone. PRIMARY is controlled by ECL2.0 DNS, SECONDARY zones are slaved from another DNS Server. Defaults to PRIMARY. This parameter is not currently supported.
:param description: Description for this zone
:param email: e-mail for the zone. Used in SOA records for the zone. This parameter is not currently supported.
:param masters: For secondary zones. The servers to slave from to get DNS information. This parameter is not currently supported.
:return: :class:`~ecl.dns.v2.zone.Zone`
"""
attr = {"name": name}
if ttl is not None:
attr["ttl"] = ttl
if type is not None:
attr["type"] = type
if description is not None:
attr["description"] = description
if email is not None:
attr["email"] = email
if masters is not None:
attr["masters"] = masters
return self._create(_zone.Zone, **attr)
def update_zone(self, zone, ttl=None,
description=None, email=None, masters=None):
"""
Update the attribute(s) for an existing zone.
:param zone: ID for the zone or zone instance to update.
:param ttl: TTL (Time to Live) for the zone. This parameter is not currently supported.
:param description: Description for this zone
:param email: e-mail for the zone. Used in SOA records for the zone. This parameter is not currently supported.
:param masters: For secondary zones. The servers to slave from to get DNS information. This parameter is not currently supported.
:return: :class:`~ecl.dns.v2.zone.Zone`
"""
attr = {}
if ttl is not None:
attr["ttl"] = ttl
if description is not None:
attr["description"] = description
if email is not None:
attr["email"] = email
if masters is not None:
attr["masters"] = masters
if not isinstance(zone, _zone.Zone):
zone = self._get_resource(_zone.Zone, zone)
zone._body.clean()
return self._update(_zone.Zone, zone, **attr)
def delete_zone(self, zone_id, ignore_missing=False):
"""
Delete a zone.
:param zone_id: ID for the zone
:param bool ignore_missing: When set to ``False``
:class:`~ecl.exceptions.ResourceNotFound` will be
raised when the server does not exist.
When set to ``True``, no exception will be set when
attempting to delete a nonexistent zone
:return: None
"""
return self._delete(_zone.Zone, zone_id, ignore_missing=False)
def get_name_server(self, zone_id):
"""
Show the nameservers for a zone.
:param zone_id: ID for the zone
:return: :class:`~ecl.dns.v2.name_server.NameServer`
"""
return list(self._list(name_server.NameServer, zone_id=zone_id))
def recordsets(self, zone_id):
"""
This lists all recordsets in a zone.
:param zone_id: ID for the zone
:return: One list of :class:`~ecl.dns.v2.recordsets.Recordsets`
"""
return list(self._list(_recordset.RecordSet, zone_id=zone_id))
def get_recordset(self, zone_id, recordset_id):
"""
Show a single recordset.
:param zone_id: ID for the zone the recordset belonging to
:param recordset_id: ID for the recordset
:return: One :class:`~ecl.dns.v2.recordsets.Recordsets` or
:class:`~ecl.exceptions.ResourceNotFound`when no
resource can be found.
"""
# TODO: If zone instance is used...
return self._get(_recordset.RecordSet, recordset_id, zone_id=zone_id)
def find_recordset(self, zone_id, name_or_id, ignore_missing=False):
"""
Find a recordset by its name or ID.
:param name_or_id: Name or ID for this recordset
:return: One :class:`~ecl.dns.v2.recordsets.Recordsets` or
:class:`~ecl.exceptions.ResourceNotFound`when no
resource can be found.
"""
return self._find(_recordset.RecordSet, name_or_id, zone_id=zone_id, ignore_missing=ignore_missing)
def create_recordset(self, zone_id, name=None, description=None,
type=None, ttl=None, records=None):
"""
Create a recordset in a zone.
:param zone_id: ID for the zone.
:param name: DNS Name for the recordset.
:param description: Description for this recordset.
:param type: RRTYPE of the recordset. Valid Values: A | AAAA | MX | CNAME | SRV | SPF | TXT | PTR | NS
:param ttl: TTL (Time to Live) for the recordset.
:param recodrs: A list of data for this recordset.
Each item will be a separate record in ECL2.0 DNS.
These items should conform to the DNS spec for the record type
- e.g. A records must be IPv4 addresses, CNAME records must be a hostname.
:return: :class:`~ecl.dns.v2.recordsets.Recordsets`
"""
attr = {"name": name}
if ttl is not None:
attr["ttl"] = ttl
if type is not None:
attr["type"] = type
if description is not None:
attr["description"] = description
if records is not None:
attr["records"] = records
return self._create(_recordset.RecordSet, zone_id=zone_id, **attr)
def update_recordset(self, zone_id, recordset, ttl=None, description=None,
name=None, records=None):
"""
Update a recordset.
:param recordset: ID for the recordset.
:param zone_id: ID for the zone.
:param ttl: TTL (Time to Live) for the recordset.
:param description: Description for this recordset.
:param name: DNS Name for the recordset.
:param record: A list of data for this recordset.
Each item will be a separate record in ECL2.0 DNS.
These items should conform to the DNS spec for the record type
- e.g. A records must be IPv4 addresses, CNAME records must be a hostname.
:return: :class:`~ecl.dns.v2.recordsets.Recordsets`
"""
attr = {}
if ttl is not None:
attr["ttl"] = ttl
if description is not None:
attr["description"] = description
if records is not None:
attr["records"] = records
if name is not None:
attr["name"] = name
if not isinstance(recordset, _recordset.RecordSet):
recordset = self._get_resource(_recordset.RecordSet, recordset)
recordset._body.clean()
return self._update(_recordset.RecordSet,
recordset, zone_id=zone_id, **attr)
def delete_recordset(self, zone_id, recordset):
"""
Delete a recordset.
:param zone_id: ID for the recordset.
:param recordset: ID for the zone.
:return: None
"""
return self._delete(_recordset.RecordSet, recordset, zone_id=zone_id)
def delete_multiple_recordsets(self, zone_id, recordset_ids):
"""
Delete multiple Recordsets.
:param recordset_ids: A list of IDs for the recordsets.
:param zone_id: ID for the zone
:return: None
"""
return _recordset.RecordSet.multi_delete(
self.session, zone_id=zone_id,
recordset_ids=recordset_ids
)
|
SkyLined/mWindowsAPI
|
fStopDebuggingForProcessId.py
|
from .fThrowLastError import fThrowLastError;
def fStopDebuggingForProcessId(uProcessId):
oKernel32 = foLoadKernel32DLL();
if not oKernel32.DebugActiveProcessStop(uProcessId):
fThrowLastError("DebugActiveProcessStop(%d/0x%X)" % (uProcessId, uProcessId,));
|
Next-Gen-UI/Code-Dynamics
|
Leetcode/1000-2000/1825. Finding MK Average/1825.cpp
|
<filename>Leetcode/1000-2000/1825. Finding MK Average/1825.cpp
class MKAverage {
public:
MKAverage(int m, int k) : m(m), k(k) {}
void addElement(int num) {
q.push(num);
add(mid, num);
midSum += num;
if (q.size() > m) {
const int removed = q.front();
q.pop();
if (top.count(removed)) {
remove(top, removed);
--topSize;
} else if (mid.count(removed)) {
remove(mid, removed);
midSum -= removed;
} else {
remove(bot, removed);
--botSize;
}
}
// move item(s) from mid to top to fill k slots
while (!mid.empty() && topSize < k) {
midSum -= rbegin(mid)->first;
add(top, remove(mid, rbegin(mid)->first));
++topSize;
}
// rebalance mid and top
while (!mid.empty() && rbegin(mid)->first > begin(top)->first) {
midSum -= rbegin(mid)->first;
midSum += begin(top)->first;
add(top, remove(mid, rbegin(mid)->first));
add(mid, remove(top, begin(top)->first));
}
// move item(s) from mid to bot to fill k slots
while (!mid.empty() && botSize < k) {
midSum -= begin(mid)->first;
add(bot, remove(mid, begin(mid)->first));
++botSize;
}
// move item(s) from mid to bot to fill k slots
while (!mid.empty() && begin(mid)->first < rbegin(bot)->first) {
midSum -= begin(mid)->first;
midSum += rbegin(bot)->first;
add(bot, remove(mid, begin(mid)->first));
add(mid, remove(bot, rbegin(bot)->first));
}
}
int calculateMKAverage() {
return q.size() == m ? midSum / (m - 2 * k) : -1;
}
private:
const int m;
const int k;
queue<int> q;
map<int, int> top;
map<int, int> mid;
map<int, int> bot;
int topSize = 0;
int botSize = 0;
long midSum = 0;
void add(map<int, int>& map, int num) {
++map[num];
}
int remove(map<int, int>& map, int num) {
if (--map[num] == 0)
map.erase(num);
return num;
}
};
|
httpsgithu/mindspore
|
mindspore/lite/src/delegate/tensorrt/op/allgather_tensorrt.cc
|
<filename>mindspore/lite/src/delegate/tensorrt/op/allgather_tensorrt.cc<gh_stars>1-10
/**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* 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 "src/delegate/tensorrt/op/allgather_tensorrt.h"
#include <numeric>
#include "NvInferRuntimeCommon.h"
namespace mindspore::lite {
REGISTER_TENSORRT_PLUGIN(AllGatherPluginCreater);
template class TensorRTPluginCreater<AllGatherPlugin>;
template <class T>
nvinfer1::PluginFieldCollection TensorRTPluginCreater<T>::field_collection_{};
template <class T>
std::vector<nvinfer1::PluginField> TensorRTPluginCreater<T>::fields_;
int AllGatherTensorRT::IsSupport(const schema::Primitive *primitive, const std::vector<mindspore::MSTensor> &in_tensors,
const std::vector<mindspore::MSTensor> &out_tensors) {
#ifndef LITE_CUDA_DISTRIBUTION
MS_LOG(ERROR)
<< "Unsupported package for gpu distribution feature, please recompile with MS_ENABLE_CUDA_DISTRIBUTION set to on.";
return RET_ERROR;
#else
if (!IsShapeKnown()) {
MS_LOG(ERROR) << "Unsupported input tensor unknown shape: " << op_name_;
return RET_ERROR;
}
if (in_tensors.size() != 1) {
MS_LOG(ERROR) << "invalid input tensor size: " << in_tensors.size();
return RET_ERROR;
}
if (out_tensors.size() != 1) {
MS_LOG(ERROR) << "invalid output tensor size: " << out_tensors.size();
return RET_ERROR;
}
dynamic_shape_params_.support_hw_dynamic_ = false;
return RET_OK;
#endif
}
int AllGatherTensorRT::AddInnerOp(nvinfer1::INetworkDefinition *network) {
nvinfer1::ITensor *inputTensors[] = {tensorrt_in_tensors_[0].trt_tensor_};
auto allgather_op = op_primitive_->value_as_AllGather();
if (allgather_op == nullptr) {
MS_LOG(ERROR) << "convert failed for " << op_name_;
return RET_ERROR;
}
int rank = GetGPUGroupSize();
auto plugin = std::make_shared<AllGatherPlugin>(op_name_, rank);
MS_LOG(INFO) << op_name_ << " group size: " << rank << ", rank id: " << GetRankID();
nvinfer1::IPluginV2Layer *allgather_layer = network->addPluginV2(inputTensors, 1, *plugin);
if (allgather_layer == nullptr) {
MS_LOG(ERROR) << "create AllGather layer failed for: " << op_name_;
return RET_ERROR;
}
nvinfer1::ITensor *allgather_out = allgather_layer->getOutput(0);
allgather_layer->setName(op_name_.c_str());
allgather_out->setName((op_name_ + "_output").c_str());
this->AddInnerOutTensors(
ITensorHelper{allgather_out, tensorrt_in_tensors_[0].format_, tensorrt_in_tensors_[0].same_format_});
this->layer_ = allgather_layer;
return RET_OK;
}
// AllGatherPlugin
int AllGatherPlugin::enqueue(const nvinfer1::PluginTensorDesc *inputDesc, const nvinfer1::PluginTensorDesc *outputDesc,
const void *const *inputs, void *const *outputs, void *workspace,
cudaStream_t stream) noexcept {
MS_LOG(INFO) << "all gather run at rank id: " << GetRankID() << " stream: " << stream;
nvinfer1::Dims input_dims = inputDesc[0].dims;
int send_element_cnt = std::accumulate(input_dims.d, input_dims.d + input_dims.nbDims, 1, std::multiplies<int64_t>());
const void *input = inputs[0];
void *output = outputs[0];
auto ret = DistributionCollective::instance().AllGatherWrapper(input, output, send_element_cnt, inputDesc->type,
stream, NCCL_WORLD_GROUP);
if (ret != RET_OK) {
MS_LOG(ERROR) << "AllGather nccl run failed for " << layer_name_;
return ret;
}
return RET_OK;
}
nvinfer1::IPluginV2DynamicExt *AllGatherPlugin::clone() const noexcept {
auto *plugin = new AllGatherPlugin(*this);
plugin->setPluginNamespace(name_space_.c_str());
return plugin;
}
nvinfer1::DimsExprs AllGatherPlugin::getOutputDimensions(int outputIndex, const nvinfer1::DimsExprs *inputs,
int nbInputs, nvinfer1::IExprBuilder &exprBuilder) noexcept {
nvinfer1::DimsExprs out_dims{};
out_dims.nbDims = inputs->nbDims;
auto rank_dim = exprBuilder.constant(rank_);
out_dims.d[0] = exprBuilder.operation(nvinfer1::DimensionOperation::kPROD, *inputs->d[0], *rank_dim);
for (int i = 1; i < inputs->nbDims; i++) {
out_dims.d[i] = inputs->d[i];
}
return out_dims;
}
REGISTER_TENSORRT_CREATOR(schema::PrimitiveType_AllGather, AllGatherTensorRT)
} // namespace mindspore::lite
|
SLAsticSPE/slastic
|
src-gen/kieker/tools/slastic/metamodel/usage/AssemblyComponentConnectorCallFrequency.java
|
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package kieker.tools.slastic.metamodel.usage;
import kieker.tools.slastic.metamodel.componentAssembly.AssemblyComponentConnector;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Assembly Component Connector Call Frequency</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link kieker.tools.slastic.metamodel.usage.AssemblyComponentConnectorCallFrequency#getConnector <em>Connector</em>}</li>
* </ul>
* </p>
*
* @see kieker.tools.slastic.metamodel.usage.UsagePackage#getAssemblyComponentConnectorCallFrequency()
* @model
* @generated
*/
public interface AssemblyComponentConnectorCallFrequency extends AssemblyConnectorCallFrequency {
/**
* Returns the value of the '<em><b>Connector</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Connector</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Connector</em>' reference.
* @see #setConnector(AssemblyComponentConnector)
* @see kieker.tools.slastic.metamodel.usage.UsagePackage#getAssemblyComponentConnectorCallFrequency_Connector()
* @model required="true" ordered="false"
* @generated
*/
AssemblyComponentConnector getConnector();
/**
* Sets the value of the '{@link kieker.tools.slastic.metamodel.usage.AssemblyComponentConnectorCallFrequency#getConnector <em>Connector</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Connector</em>' reference.
* @see #getConnector()
* @generated
*/
void setConnector(AssemblyComponentConnector value);
} // AssemblyComponentConnectorCallFrequency
|
ericcf/icalendar2
|
lib/icalendar2/property/dtend.rb
|
module Icalendar2
module Property
# See http://tools.ietf.org/html/rfc5545#section-3.8.2.2
class Dtend < Base
name "DTEND"
value :types => [:date_time, :date]
end
end
end
|
MrLiuFang/emap
|
emap-service/src/main/java/com/pepper/service/emap/event/EventRuleService.java
|
<gh_stars>1-10
package com.pepper.service.emap.event;
import com.pepper.core.base.BaseService;
import com.pepper.model.emap.event.EventRule;
public interface EventRuleService extends BaseService<EventRule> {
/**
*
* @param nodeId
* @return
*/
public EventRule findByNodeId(String nodeId);
/**
*
* @param nodeId
* @return
*/
public EventRule findByNodeTypeId(String nodeTypeId);
}
|
1iyiwei/deform2d
|
Wml/Source/Meshes/WmlBasicMesh.cpp
|
<reponame>1iyiwei/deform2d
// Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2004. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlBasicMesh.h"
#include "WmlEdgeKey.h"
using namespace Wml;
#include <cassert>
#include <map>
using namespace std;
//----------------------------------------------------------------------------
BasicMesh::BasicMesh (int iVQuantity, void* akPoint, int iTQuantity,
const int* aiConnect)
{
m_iVQuantity = iVQuantity;
m_iEQuantity = 0;
m_iTQuantity = iTQuantity;
m_akPoint = akPoint;
m_aiConnect = aiConnect;
// dynamically construct triangle mesh from input
m_akVertex = new Vertex[m_iVQuantity];
m_akEdge = new Edge[3*m_iTQuantity];
m_akTriangle = new Triangle[m_iTQuantity];
map<EdgeKey,int> kEMap;
for (int iT = 0; iT < m_iTQuantity; iT++)
{
// update triangle
Triangle& rkT = m_akTriangle[iT];
rkT.V[0] = *aiConnect++;
rkT.V[1] = *aiConnect++;
rkT.V[2] = *aiConnect++;
// add edges to mesh
for (int i0 = 2, i1 = 0; i1 < 3; i0 = i1++)
{
// update vertices
m_akVertex[rkT.V[i1]].InsertTriangle(iT);
EdgeKey kKey(rkT.V[i0],rkT.V[i1]);
map<EdgeKey,int>::iterator kEIter = kEMap.find(kKey);
if ( kEIter == kEMap.end() )
{
// first time edge encountered
kEMap[kKey] = m_iEQuantity;
// update edge
Edge& rkE = m_akEdge[m_iEQuantity];
rkE.V[0] = rkT.V[i0];
rkE.V[1] = rkT.V[i1];
rkE.T[0] = iT;
// update vertices
m_akVertex[rkE.V[0]].InsertEdge(rkE.V[1],m_iEQuantity);
m_akVertex[rkE.V[1]].InsertEdge(rkE.V[0],m_iEQuantity);
// update triangle
rkT.E[i0] = m_iEQuantity;
m_iEQuantity++;
}
else
{
// second time edge encountered
int iE = kEIter->second;
Edge& rkE = m_akEdge[iE];
// update edge
assert( rkE.T[1] == -1 ); // mesh must be manifold
rkE.T[1] = iT;
// update triangles
int iAdj = rkE.T[0];
Triangle& rkAdj = m_akTriangle[iAdj];
for (int j = 0; j < 3; j++)
{
if ( rkAdj.E[j] == iE )
{
rkAdj.T[j] = iT;
break;
}
}
rkT.E[i0] = iE;
rkT.T[i0] = iAdj;
}
}
}
}
//----------------------------------------------------------------------------
BasicMesh::~BasicMesh ()
{
delete[] m_akVertex;
delete[] m_akEdge;
delete[] m_akTriangle;
}
//----------------------------------------------------------------------------
int BasicMesh::GetVQuantity () const
{
return m_iVQuantity;
}
//----------------------------------------------------------------------------
int BasicMesh::GetEQuantity () const
{
return m_iEQuantity;
}
//----------------------------------------------------------------------------
int BasicMesh::GetTQuantity () const
{
return m_iTQuantity;
}
//----------------------------------------------------------------------------
void* BasicMesh::GetPoints () const
{
return m_akPoint;
}
//----------------------------------------------------------------------------
const int* BasicMesh::GetConnectivity () const
{
return m_aiConnect;
}
//----------------------------------------------------------------------------
const BasicMesh::Vertex* BasicMesh::GetVertices () const
{
return m_akVertex;
}
//----------------------------------------------------------------------------
const BasicMesh::Edge* BasicMesh::GetEdges () const
{
return m_akEdge;
}
//----------------------------------------------------------------------------
const BasicMesh::Triangle* BasicMesh::GetTriangles () const
{
return m_akTriangle;
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// BasicMesh::Vertex
//----------------------------------------------------------------------------
BasicMesh::Vertex::Vertex ()
{
VQuantity = 0;
V = NULL;
E = NULL;
TQuantity = 0;
T = 0;
}
//----------------------------------------------------------------------------
BasicMesh::Vertex::~Vertex ()
{
delete[] V;
delete[] E;
delete[] T;
}
//----------------------------------------------------------------------------
void BasicMesh::Vertex::InsertEdge (int iV, int iE)
{
// check if vertex/edge in adjacency array (nothing to do if in array)
for (int i = 0; i < VQuantity; i++)
{
if ( iV == V[i] )
return;
}
if ( (VQuantity % MV_CHUNK) == 0 )
{
int* aiSave = V;
V = new int[VQuantity+MV_CHUNK];
memcpy(V,aiSave,VQuantity*sizeof(int));
aiSave = E;
E = new int[VQuantity+MV_CHUNK];
memcpy(E,aiSave,VQuantity*sizeof(int));
}
V[VQuantity] = iV;
E[VQuantity] = iE;
VQuantity++;
}
//----------------------------------------------------------------------------
void BasicMesh::Vertex::InsertTriangle (int iT)
{
// check if triangle in adjacency array (nothing to do if in array)
for (int i = 0; i < TQuantity; i++)
{
if ( iT == T[i] )
return;
}
if ( (TQuantity % MV_CHUNK) == 0 )
{
int* aiSave = T;
T = new int[TQuantity+MV_CHUNK];
memcpy(T,aiSave,TQuantity*sizeof(int));
}
T[TQuantity] = iT;
TQuantity++;
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// BasicMesh::Edge
//----------------------------------------------------------------------------
BasicMesh::Edge::Edge ()
{
for (int i = 0; i < 2; i++)
{
V[i] = -1;
T[i] = -1;
}
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// BasicMesh::Triangle
//----------------------------------------------------------------------------
BasicMesh::Triangle::Triangle ()
{
for (int i = 0; i < 3; i++)
{
V[i] = -1;
E[i] = -1;
T[i] = -1;
}
}
//----------------------------------------------------------------------------
|
johnthecat/babel-plugin-jsdoc-runtime-type-check
|
test/smoke/fixtures/runtime/src/exception/wrong-validate-in-scope.js
|
// @typecheck
function Test() {}
/**
* @param {Test} data
* @returns {null}
*/
function testFunction(data) {
return null;
}
testFunction('wrong data');
|
jjzhang166/avocadodb
|
3rdParty/velocypack/include/velocypack/Helpers.h
|
////////////////////////////////////////////////////////////////////////////////
/// @brief Library to build up VPack documents.
///
/// DISCLAIMER
///
/// Copyright 2015 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author <NAME>
/// @author <NAME>
/// @author Copyright 2015, ArangoDB GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#ifndef VELOCYPACK_HELPERS_H
#define VELOCYPACK_HELPERS_H 1
#include <string>
#include <cstdint>
#include <unordered_set>
#include "velocypack/velocypack-common.h"
#include "velocypack/Exception.h"
#include "velocypack/Options.h"
#include "velocypack/Slice.h"
namespace avocadodb {
namespace velocypack {
struct TopLevelAttributeExcludeHandler final : AttributeExcludeHandler {
TopLevelAttributeExcludeHandler (std::unordered_set<std::string> const& attributes)
: attributes(attributes) {
}
bool shouldExclude(Slice const& key, int nesting) override final {
return (nesting == 1 && attributes.find(key.copyString()) != attributes.end());
}
std::unordered_set<std::string> attributes;
};
static inline Slice buildNullValue(char* dst, size_t length) {
if (length < 1) {
throw Exception(Exception::InternalError, "supplied buffer is too small");
}
*dst = 0x18;
return Slice(dst);
}
} // namespace avocadodb::velocypack
} // namespace avocadodb
#endif
|
hjheath/ProjectEuler
|
projecteuler/problems/problem_42.py
|
<filename>projecteuler/problems/problem_42.py
"""Problem 42 of https://projecteuler.net"""
from itertools import takewhile
from pkg_resources import resource_string
from projecteuler.generators import triangle_numbers
# Assume no word is longer than 20 letters
TRIANGLES = [x for x in takewhile(lambda x: x < 520, triangle_numbers())]
def problem_42():
"""Solution to problem 42."""
file_contents = resource_string('projecteuler.data', 'problem_42.dat')
file_as_string = file_contents.decode('utf-8')
words = file_as_string.replace('"', '').split(',')
count = 0
for word in words:
if triangle_word(word):
count += 1
return count
def triangle_word(word):
"""Check if a word is a triangle word"""
return sum([ord(character) - 64 for character in word]) in TRIANGLES
|
it-novum/openitcockpit-agent-go
|
checks/agent_posix.go
|
// +build linux darwin
package checks
import (
"context"
"runtime"
"time"
"github.com/it-novum/openitcockpit-agent-go/config"
"github.com/shirou/gopsutil/v3/host"
)
// Run the actual check
// if error != nil the check result will be nil
// ctx can be canceled and runs the timeout
// CheckResult will be serialized after the return and should not change until the next call to Run
func (c *CheckAgent) Run(ctx context.Context) (interface{}, error) {
uptime, err := host.UptimeWithContext(ctx)
if err != nil {
uptime = 0
}
now := time.Now()
return &resultAgent{
LastUpdated: now.String(),
LastUpdatedTimestamp: now.Unix(),
System: c.System,
SystemUptime: uptime,
KernelVersion: c.KernelVersion,
MacVersion: c.MacVersion,
Family: c.Family,
AgentVersion: config.AgentVersion,
TemperatureUnit: "C",
GOOS: runtime.GOOS,
GOARCH: runtime.GOARCH,
}, nil
}
// Configure the command or return false if the command was disabled
func (c *CheckAgent) Configure(config *config.Configuration) (bool, error) {
c.Init()
return true, nil
}
func (c *CheckAgent) Init() {
kernel, _ := host.KernelVersionWithContext(context.Background())
platfrom, family, pver, _ := host.PlatformInformationWithContext(context.Background())
c.System = platfrom
c.KernelVersion = kernel
c.MacVersion = pver
c.Family = family
}
|
supertick/jmonkeyengine
|
jme3-core/src/main/java/com/jme3/shader/ShaderGenerator.java
|
/*
* Copyright (c) 2009-2021 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.shader;
import com.jme3.asset.AssetManager;
import com.jme3.material.ShaderGenerationInfo;
import com.jme3.material.TechniqueDef;
import com.jme3.shader.Shader.ShaderType;
import com.jme3.shader.plugins.ShaderAssetKey;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This class is the base for a shader generator using the ShaderNodes system,
* it contains basis mechanism of generation, but no actual generation code.
* This class is abstract, any Shader generator must extend it.
*
* @author Nehon
*/
public abstract class ShaderGenerator {
public static final String NAME_SPACE_GLOBAL = "Global";
public static final String NAME_SPACE_VERTEX_ATTRIBUTE = "Attr";
public static final String NAME_SPACE_MAT_PARAM = "MatParam";
public static final String NAME_SPACE_WORLD_PARAM = "WorldParam";
/**
* the asset manager
*/
protected AssetManager assetManager;
/**
* indentation value for generation
*/
protected int indent;
/**
* the technique def to use for the shader generation
*/
protected TechniqueDef techniqueDef = null;
/**
* Extension pattern
*/
Pattern extensions = Pattern.compile("(#extension.*\\s+)");
final private Map<String, String> imports = new LinkedHashMap<>();
/**
* Build a shaderGenerator
*
* @param assetManager for loading assets (alias created)
*/
protected ShaderGenerator(AssetManager assetManager) {
this.assetManager = assetManager;
}
public void initialize(TechniqueDef techniqueDef){
this.techniqueDef = techniqueDef;
}
/**
* Generate vertex and fragment shaders for the given technique
*
* @param definesSourceCode (may be null)
* @return a Shader program
*/
public Shader generateShader(String definesSourceCode) {
if (techniqueDef == null) {
throw new UnsupportedOperationException("The shaderGenerator was not "
+ "properly initialized, call "
+ "initialize(TechniqueDef) before any generation");
}
String techniqueName = techniqueDef.getName();
ShaderGenerationInfo info = techniqueDef.getShaderGenerationInfo();
Shader shader = new Shader();
for (ShaderType type : ShaderType.values()) {
String extension = type.getExtension();
String language = getLanguageAndVersion(type);
String shaderSourceCode = buildShader(techniqueDef.getShaderNodes(), info, type);
if (shaderSourceCode != null) {
String shaderSourceAssetName = techniqueName + "." + extension;
shader.addSource(type, shaderSourceAssetName, shaderSourceCode, definesSourceCode, language);
}
}
techniqueDef = null;
return shader;
}
/**
* This method is responsible for the shader generation.
*
* @param shaderNodes the list of shader nodes
* @param info the ShaderGenerationInfo filled during the Technique loading
* @param type the type of shader to generate
* @return the code of the generated vertex shader
*/
protected String buildShader(List<ShaderNode> shaderNodes, ShaderGenerationInfo info, ShaderType type) {
if (type == ShaderType.TessellationControl ||
type == ShaderType.TessellationEvaluation ||
type == ShaderType.Geometry) {
// TODO: Those are not supported.
// Too much code assumes that type is either Vertex or Fragment
return null;
}
imports.clear();
indent = 0;
StringBuilder sourceDeclaration = new StringBuilder();
StringBuilder source = new StringBuilder();
generateUniforms(sourceDeclaration, info, type);
if (type == ShaderType.Vertex) {
generateAttributes(sourceDeclaration, info);
}
generateVaryings(sourceDeclaration, info, type);
generateStartOfMainSection(source, info, type);
generateDeclarationAndMainBody(shaderNodes, sourceDeclaration, source, info, type);
generateEndOfMainSection(source, info, type);
//insert imports backward
int insertIndex = sourceDeclaration.length();
for (String importSource : imports.values()) {
sourceDeclaration.insert(insertIndex, importSource);
}
sourceDeclaration.append(source);
return moveExtensionsUp(sourceDeclaration);
}
/**
* parses the source and moves all the extensions at the top of the shader source as having extension declarations
* in the middle of a shader is against the specs and not supported by all drivers.
* @param sourceDeclaration
* @return
*/
private String moveExtensionsUp(StringBuilder sourceDeclaration) {
Matcher m = extensions.matcher( sourceDeclaration.toString());
StringBuilder finalSource = new StringBuilder();
while(m.find()){
finalSource.append(m.group());
}
finalSource.append(m.replaceAll(""));
return finalSource.toString();
}
/**
* iterates through shader nodes to load them and generate the shader
* declaration part and main body extracted from the shader nodes, for the
* given shader type
*
* @param shaderNodes the list of shader nodes
* @param sourceDeclaration the declaration part StringBuilder of the shader
* to generate
* @param source the main part StringBuilder of the shader to generate
* @param info the ShaderGenerationInfo
* @param type the Shader type
*/
@SuppressWarnings("unchecked")
protected void generateDeclarationAndMainBody(List<ShaderNode> shaderNodes, StringBuilder sourceDeclaration, StringBuilder source, ShaderGenerationInfo info, Shader.ShaderType type) {
for (ShaderNode shaderNode : shaderNodes) {
if (info.getUnusedNodes().contains(shaderNode.getName())) {
continue;
}
if (shaderNode.getDefinition().getType() == type) {
int index = findShaderIndexFromVersion(shaderNode, type);
String shaderPath = shaderNode.getDefinition().getShadersPath().get(index);
Map<String, String> sources = (Map<String, String>) assetManager.loadAsset(new ShaderAssetKey(shaderPath, false));
String loadedSource = sources.get("[main]");
for (String name : sources.keySet()) {
if (!name.equals("[main]")) {
imports.put(name, sources.get(name));
}
}
appendNodeDeclarationAndMain(loadedSource, sourceDeclaration, source, shaderNode, info, shaderPath);
}
}
}
/**
* Appends declaration and main part of a node to the shader declaration and
* main part. the loadedSource is split by "void main(){" to split
* declaration from main part of the node source code.The trailing "}" is
* removed from the main part. Each part is then respectively passed to
* generateDeclarativeSection and generateNodeMainSection.
*
* @see ShaderGenerator#generateDeclarativeSection
* @see ShaderGenerator#generateNodeMainSection
*
* @param loadedSource the actual source code loaded for this node.
* @param shaderPath path to the shader file
* @param sourceDeclaration the Shader declaration part string builder.
* @param source the Shader main part StringBuilder.
* @param shaderNode the shader node.
* @param info the ShaderGenerationInfo.
*/
protected void appendNodeDeclarationAndMain(String loadedSource, StringBuilder sourceDeclaration, StringBuilder source, ShaderNode shaderNode, ShaderGenerationInfo info, String shaderPath) {
if (loadedSource.length() > 1) {
loadedSource = loadedSource.substring(0, loadedSource.lastIndexOf("}"));
String[] sourceParts = loadedSource.split("\\s*void\\s*main\\s*\\(\\s*\\)\\s*\\{");
if(sourceParts.length<2){
throw new IllegalArgumentException("Syntax error in "+ shaderPath +". Cannot find 'void main(){' in \n"+ loadedSource);
}
generateDeclarativeSection(sourceDeclaration, shaderNode, sourceParts[0], info);
generateNodeMainSection(source, shaderNode, sourceParts[1], info);
} else {
//if source is empty, we still call generateNodeMainSection so that mappings can be done.
generateNodeMainSection(source, shaderNode, loadedSource, info);
}
}
/**
* returns the language + version of the shader should be something like
* "GLSL100" for glsl 1.0 "GLSL150" for glsl 1.5.
*
* @param type the shader type for which the version should be returned.
*
* @return the shaderLanguage and version.
*/
protected abstract String getLanguageAndVersion(Shader.ShaderType type);
/**
* generates the uniforms declaration for a shader of the given type.
*
* @param source the source StringBuilder to append generated code.
* @param info the ShaderGenerationInfo.
* @param type the shader type the uniforms have to be generated for.
*/
protected abstract void generateUniforms(StringBuilder source, ShaderGenerationInfo info, ShaderType type);
/**
* generates the attributes declaration for the vertex shader. There is no
* Shader type passed here as attributes are only used in vertex shaders
*
* @param source the source StringBuilder to append generated code.
* @param info the ShaderGenerationInfo.
*/
protected abstract void generateAttributes(StringBuilder source, ShaderGenerationInfo info);
/**
* generates the varyings for the given shader type shader. Note that
* varyings are deprecated in glsl 1.3, but this method will still be called
* to generate all non global inputs and output of the shaders.
*
* @param source the source StringBuilder to append generated code.
* @param info the ShaderGenerationInfo.
* @param type the shader type the varyings have to be generated for.
*/
protected abstract void generateVaryings(StringBuilder source, ShaderGenerationInfo info, ShaderType type);
/**
* Appends the given shaderNode declarative part to the shader declarative
* part. If needed the shader type can be determined by fetching the
* shaderNode's definition type.
*
* @see ShaderNode#getDefinition()
* @see ShaderNodeDefinition#getType()
*
* @param nodeDecalarationSource the declaration part of the node
* @param source the StringBuilder to append generated code.
* @param shaderNode the shaderNode.
* @param info the ShaderGenerationInfo.
*/
protected abstract void generateDeclarativeSection(StringBuilder source, ShaderNode shaderNode, String nodeDecalarationSource, ShaderGenerationInfo info);
/**
* generates the start of the shader main section. this method is
* responsible of appending the "void main(){" in the shader and declaring
* all global outputs of the shader
*
* @param source the StringBuilder to append generated code.
* @param info the ShaderGenerationInfo.
* @param type the shader type the section has to be generated for.
*/
protected abstract void generateStartOfMainSection(StringBuilder source, ShaderGenerationInfo info, ShaderType type);
/**
* generates the end of the shader main section. this method is responsible
* of appending the last "}" in the shader and mapping all global outputs of
* the shader
*
* @param source the StringBuilder to append generated code.
* @param info the ShaderGenerationInfo.
* @param type the shader type the section has to be generated for.
*/
protected abstract void generateEndOfMainSection(StringBuilder source, ShaderGenerationInfo info, ShaderType type);
/**
* Appends the given shaderNode main part to the shader declarative part. If
* needed the shader type can be determined by fetching the shaderNode's
* definition type.
*
* @see ShaderNode#getDefinition()
* @see ShaderNodeDefinition#getType()
*
* @param source the StringBuilder to append generated code.
* @param shaderNode the shaderNode.
* @param nodeSource the declaration part of the loaded shaderNode source.
* @param info the ShaderGenerationInfo.
*/
protected abstract void generateNodeMainSection(StringBuilder source, ShaderNode shaderNode, String nodeSource, ShaderGenerationInfo info);
/**
* returns the shaderpath index according to the version of the generator.
* This allow to select the higher version of the shader that the generator
* can handle
*
* @param shaderNode the shaderNode being processed
* @param type the shaderType
* @return the index of the shader path in ShaderNodeDefinition shadersPath
* list
* @throws NumberFormatException for an invalid version
*/
protected int findShaderIndexFromVersion(ShaderNode shaderNode, ShaderType type) throws NumberFormatException {
int index = 0;
List<String> lang = shaderNode.getDefinition().getShadersLanguage();
int genVersion = Integer.parseInt(getLanguageAndVersion(type).substring(4));
int curVersion = 0;
for (int i = 0; i < lang.size(); i++) {
int version = Integer.parseInt(lang.get(i).substring(4));
if (version > curVersion && version <= genVersion) {
curVersion = version;
index = i;
}
}
return index;
}
}
|
SINTEF/simapy
|
src/sima/metocean/blueprints/directiondependentweibulldistribution.py
|
#
# Generated with DirectionDependentWeibullDistributionBlueprint
from dmt.blueprint import Blueprint
from dmt.dimension import Dimension
from dmt.attribute import Attribute
from dmt.enum_attribute import EnumAttribute
from dmt.blueprint_attribute import BlueprintAttribute
from .weibulldistribution import WeibullDistributionBlueprint
class DirectionDependentWeibullDistributionBlueprint(WeibullDistributionBlueprint):
""""""
def __init__(self, name="DirectionDependentWeibullDistribution", package_path="sima/metocean", description=""):
super().__init__(name,package_path,description)
self.attributes.append(Attribute("name","string","",default=""))
self.attributes.append(Attribute("description","string","",default=""))
self.attributes.append(Attribute("_id","string","",default=""))
self.attributes.append(BlueprintAttribute("scriptableValues","sima/sima/ScriptableValue","",True,Dimension("*")))
self.attributes.append(Attribute("returnPeriod","number","",default=0.0))
self.attributes.append(Attribute("level","number","",default=0.0))
self.attributes.append(Attribute("duration","number","",default=0.0))
self.attributes.append(BlueprintAttribute("items","sima/metocean/WeibullDistributionItem","",True,Dimension("*")))
|
alefbispo/Exercicios-do-curso-de-Python
|
Pyon exercicios/Exercicios/061.py
|
<reponame>alefbispo/Exercicios-do-curso-de-Python
'''Refaça o DESAFIO 51,
lendo o primeiro termo e a razão de uma PA,
mostrando os 10 primeiros termos da progressão usando a estrutura while.'''
primeiro = int(input('Qual o termo? '))
progressao = int(input('Pular de quanto em quanto? '))
contador = 1
termo = primeiro
while contador <= 10:
print('{}'.format(termo), end=' > ')
termo += progressao
contador += 1
print('fim')
|
ManpraXSoftware/discourse-lite
|
discourse/src/main/java/com/manprax/discourseplugin/discourse_views/DiscoursePostFragment.java
|
<gh_stars>0
package com.manprax.discourseplugin.discourse_views;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.manprax.discourseplugin.R;
import com.manprax.discourseplugin.discourse_views.adapter.PostRecyclerAdapter;
import com.manprax.discourseplugin.model.PostActionType;
import com.manprax.discourseplugin.model.ResponseError;
import com.manprax.discourseplugin.model.post.Post;
import com.manprax.discourseplugin.model.topic.Topic;
import com.manprax.discourseplugin.net.DiscourseCallback;
import com.manprax.discourseplugin.net.DiscourseRepository;
import com.manprax.discourseplugin.net.post.PostAPI;
import com.manprax.discourseplugin.net.topic.TopicAPI;
import java.util.Arrays;
/**
* Created by Mukesh on 04-12-2017.
*/
public class DiscoursePostFragment extends Fragment {
public static final String TAG = "DiscoursePostFragment";
public static String ARG_TOPIC_ID = "ARG_TOPIC_ID";
RecyclerView mRecyclerView;
SwipeRefreshLayout mSwipeRefreshLayout;
FloatingActionButton mWritePostFab;
private ProgressBar mProgressIndicator;
TopicAPI topicApi;
PostAPI postApi;
PostRecyclerAdapter mPostRecyclerAdapter;
private OnNewPostFabClickListener newPostFabListener;
private int topicId;
private int mSelectedPosition;
private RecyclerItemClickListener<Post> mRecyclerItemClickListener = new RecyclerItemClickListener<Post>() {
@Override
public void onItemClick(View view, Post post) {
mSelectedPosition = (int) view.getTag();
int i = view.getId();
if (i == R.id.like_button) {
if (post.isPostLiked() && post.canUndoLike()) doPostUnlike(post.getId());
else if (!post.isPostLiked())
doPostActions(post.getId(), PostActionType.LIKE, false);
} else if (i == R.id.share_link_button) {
sharePost(post.prepareShareLink(DiscourseRepository.getConfig().getBasUrl(), DiscourseRepository.getConfig().getUserName()));
} else if (i == R.id.bookmark_button) {
if (!post.isBookmarked())
doPostActions(post.getId(), PostActionType.BOOKMARK, false);
} else if (i == R.id.reply_button) {
}
else if (i == R.id.reply_layout) {
mRecyclerView.smoothScrollToPosition(mPostRecyclerAdapter.getPostPositionByPostNumber(post.getReply_to_post_number()));
}
}
};
public static DiscoursePostFragment newInstance(int id) {
DiscoursePostFragment dPostFrag = new DiscoursePostFragment();
Bundle b = new Bundle();
b.putInt(ARG_TOPIC_ID, id);
dPostFrag.setArguments(b);
return dPostFrag;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
topicId = getArguments().getInt(ARG_TOPIC_ID);
}
topicApi=DiscourseRepository.get().getTopicApi();
postApi= DiscourseRepository.get().getPostApi();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.common_fragment_layout, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView= (RecyclerView) view.findViewById(R.id.discourse_recycler_view);
mSwipeRefreshLayout= (SwipeRefreshLayout) view.findViewById(R.id.discourse_swipe_layout);
mProgressIndicator= (ProgressBar) view.findViewById(R.id.progress_indicator);
// mEmptyTextView= (TextView) view.findViewById(R.id.empty_state_text);
mProgressIndicator.setVisibility(View.GONE);
mWritePostFab= (FloatingActionButton) view.findViewById(R.id.new_topic_fab);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.setHasFixedSize(true);
mPostRecyclerAdapter = new PostRecyclerAdapter(getActivity(), mRecyclerItemClickListener);
mRecyclerView.setAdapter(mPostRecyclerAdapter);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
getSingleTopic(topicId);
}
});
getSingleTopic(topicId);
mWritePostFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (newPostFabListener != null) {
newPostFabListener.onNewPostFabClick();
}
}
});
}
private void sharePost(String url){
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, url);
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "Share with"));
}
private void doPostActions(int postId,PostActionType actionType,boolean isFlaged) {
postApi.postActions(postId, actionType.getValue(), isFlaged)
.enqueue(new DiscourseCallback<Post>() {
@Override
protected void onResponse(@NonNull Post responseBody) {
if (mPostRecyclerAdapter!=null){
mPostRecyclerAdapter.updateAt(mSelectedPosition,responseBody);
}
}
});
}
private void doPostUnlike(int postId) {
postApi.unlikePost(postId)
.enqueue(new DiscourseCallback<Post>() {
@Override
protected void onResponse(@NonNull Post responseBody) {
if (mPostRecyclerAdapter!=null){
mPostRecyclerAdapter.updateAt(mSelectedPosition,responseBody);
}
}
});
}
private void getSingleTopic(int id) {
mSwipeRefreshLayout.setRefreshing(true);
topicApi.getTopicById(id)
.enqueue(new DiscourseCallback<Topic>() {
@Override
protected void onResponse(@NonNull Topic responseBody) {
mSwipeRefreshLayout.setRefreshing(false);
mPostRecyclerAdapter.refreshPostList(Arrays.asList(responseBody.getPost_stream().getPosts()));
}
@Override
protected void onFailure(ResponseError responseError, @NonNull Throwable error) {
super.onFailure(responseError, error);
mSwipeRefreshLayout.setRefreshing(false);
error.printStackTrace();
}
});
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
newPostFabListener = (OnNewPostFabClickListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnNewPostFabClickListener");
}
}
@Override
public void onDetach() {
super.onDetach();
if (newPostFabListener != null)
newPostFabListener = null;
}
public interface OnNewPostFabClickListener {
void onNewPostFabClick();
}
}
|
xSuperr/gophertunnel
|
minecraft/nbt/dump.go
|
package nbt
import (
"fmt"
"reflect"
"strconv"
"strings"
)
// Dump returns a human readable decoded version of a serialised slice of NBT encoded using the encoding that
// is passed.
// Types are printed using the names present in the doc.go file and nested tags are indented using a single
// tab.
// Due to the nature of NBT, TAG_Compounds will not be printed in the same order. A different result is to be
// expected every time Dump is called, due to the random ordering.
//
// If the serialised NBT data passed is not parsable using the encoding that was passed, an error is returned
// and the resulting string will always be empty.
func Dump(data []byte, encoding Encoding) (string, error) {
var m map[string]interface{}
if err := UnmarshalEncoding(data, &m, encoding); err != nil {
return "", fmt.Errorf("error decoding NBT: %v", err)
}
s := &dumpState{}
return s.encodeTagType(m) + "(" + s.encodeTagValue(m) + ")", nil
}
// dumpState is used to keep track of values used during a single dump operations. A new one is created upon
// every call to Dump().
type dumpState struct {
// currentIndent specifies the amount of tabs that should be present in front of tags in the dump upon
// writing. The value is increased every time a compound or list tag is opened, and reduced every time
// a compound or list tag is closed.
currentIndent int
}
// indent returns the indentation required for the current nesting level. It is increased every time a list
// or compound tag is opened, and reduced when it is closed.
func (s *dumpState) indent() string {
return strings.Repeat(" ", s.currentIndent)
}
// encodeTagType encodes the type of the value passed to an NBT tag name. The way these are translated can be
// found in the doc.go file.
func (s *dumpState) encodeTagType(val interface{}) string {
if val == nil {
return "nil"
}
switch val.(type) {
case byte:
return "TAG_Byte"
case int16:
return "TAG_Short"
case int32:
return "TAG_Int"
case int64:
return "TAG_Long"
case float32:
return "TAG_Float"
case float64:
return "TAG_Double"
case string:
return "TAG_String"
}
t := reflect.TypeOf(val)
switch t.Kind() {
case reflect.Map:
return "TAG_Compound"
case reflect.Slice:
elemType := reflect.New(t.Elem()).Elem().Interface()
v := reflect.ValueOf(val)
if v.Len() != 0 && elemType == nil {
elemType = v.Index(0).Elem().Interface()
}
return "TAG_List<" + s.encodeTagType(elemType) + ">"
case reflect.Array:
switch t.Elem().Kind() {
case reflect.Uint8, reflect.Bool:
return "TAG_ByteArray"
case reflect.Int32:
return "TAG_IntArray"
case reflect.Int64:
return "TAG_LongArray"
}
}
panic("should not happen")
}
// encodeTagValue encodes a value passed to a format in which they are displayed in the dump string.
// encodeTagValue operates recursively: If lists or compounds are nested, encodeTagValue will include all
// nested tags.
func (s *dumpState) encodeTagValue(val interface{}) string {
//noinspection SpellCheckingInspection
const hexTable = "0123456789abcdef"
switch v := val.(type) {
case byte:
return "0x" + string([]byte{hexTable[v>>4], hexTable[v&0x0f]})
case int16:
return strconv.Itoa(int(v))
case int32:
return strconv.Itoa(int(v))
case int64:
return strconv.FormatInt(v, 10)
case float32:
return strconv.FormatFloat(float64(v), 'g', -1, 32)
case float64:
return strconv.FormatFloat(v, 'g', -1, 64)
case string:
return v
}
t := reflect.TypeOf(val)
reflectVal := reflect.ValueOf(val)
switch t.Kind() {
case reflect.Map:
b := strings.Builder{}
b.WriteString("{\n")
for _, k := range reflectVal.MapKeys() {
v := reflectVal.MapIndex(k)
actualVal := v.Interface()
s.currentIndent++
b.WriteString(fmt.Sprintf("%v'%v': %v(%v),\n", s.indent(), k.String(), s.encodeTagType(actualVal), s.encodeTagValue(actualVal)))
s.currentIndent--
}
b.WriteString(s.indent() + "}")
return b.String()
case reflect.Slice:
b := strings.Builder{}
b.WriteString("{\n")
for i := 0; i < reflectVal.Len(); i++ {
v := reflectVal.Index(i)
actualVal := v.Interface()
s.currentIndent++
b.WriteString(fmt.Sprintf("%v%v,\n", s.indent(), s.encodeTagValue(actualVal)))
s.currentIndent--
}
b.WriteString(s.indent() + "}")
return b.String()
case reflect.Array:
switch t.Elem().Kind() {
case reflect.Uint8:
b := strings.Builder{}
for i := 0; i < reflectVal.Len(); i++ {
v := reflectVal.Index(i).Uint()
b.WriteString("0x")
b.WriteString(string([]byte{hexTable[v>>4], hexTable[v&0x0f]}))
if i != reflectVal.Len()-1 {
b.WriteByte(' ')
}
}
return b.String()
case reflect.Int32, reflect.Int64:
b := strings.Builder{}
for i := 0; i < reflectVal.Len(); i++ {
v := reflectVal.Index(i).Int()
b.WriteString(strconv.FormatInt(v, 10))
if i != reflectVal.Len()-1 {
b.WriteByte(' ')
}
}
return b.String()
}
}
panic("should not happen")
}
|
aggarwal2000/ginkgo
|
examples/ginkgo-overhead/ginkgo-overhead.cpp
|
/*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2021, the Ginkgo authors
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. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************<GINKGO LICENSE>*******************************/
#include <ginkgo/ginkgo.hpp>
#include <chrono>
#include <cmath>
#include <iostream>
[[noreturn]] void print_usage_and_exit(const char *name)
{
std::cerr << "Usage: " << name << " [NUM_ITERS]" << std::endl;
std::exit(-1);
}
int main(int argc, char *argv[])
{
using ValueType = double;
using IndexType = int;
using vec = gko::matrix::Dense<ValueType>;
using mtx = gko::matrix::Csr<ValueType, IndexType>;
using cg = gko::solver::Cg<ValueType>;
long unsigned num_iters = 1000000;
if (argc > 2) {
print_usage_and_exit(argv[0]);
}
if (argc == 2) {
num_iters = std::atol(argv[1]);
if (num_iters == 0) {
print_usage_and_exit(argv[0]);
}
}
std::cout << gko::version_info::get() << std::endl;
auto exec = gko::ReferenceExecutor::create();
auto cg_factory =
cg::build()
.with_criteria(
gko::stop::Iteration::build().with_max_iters(num_iters).on(
exec))
.on(exec);
auto A = gko::initialize<mtx>({1.0}, exec);
auto b = gko::initialize<vec>({std::nan("")}, exec);
auto x = gko::initialize<vec>({0.0}, exec);
auto tic = std::chrono::steady_clock::now();
auto solver = cg_factory->generate(gko::give(A));
solver->apply(lend(x), lend(b));
exec->synchronize();
auto tac = std::chrono::steady_clock::now();
auto time = std::chrono::duration_cast<std::chrono::nanoseconds>(tac - tic);
std::cout << "Running " << num_iters
<< " iterations of the CG solver took a total of "
<< static_cast<double>(time.count()) /
static_cast<double>(std::nano::den)
<< " seconds." << std::endl
<< "\tAverage library overhead: "
<< static_cast<double>(time.count()) /
static_cast<double>(num_iters)
<< " [nanoseconds / iteration]" << std::endl;
}
|
sungho-joo/leetcode2github
|
src/leetcode_91_decode_ways.py
|
<gh_stars>0
# @l2g 91 python3
# [91] Decode Ways
# Difficulty: Medium
# https://leetcode.com/problems/decode-ways
#
# A message containing letters from A-Z can be encoded into numbers using the following mapping:
#
# 'A' -> "1"
# 'B' -> "2"
# ...
# 'Z' -> "26"
#
# To decode an encoded message,
# all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways).
# For example,"11106" can be mapped into:
#
# "AAJF" with the grouping (1 1 10 6)
# "KJF" with the grouping (11 10 6)
#
# Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
# Given a string s containing only digits, return the number of ways to decode it.
# The answer is guaranteed to fit in a 32-bit integer.
#
# Example 1:
#
# Input: s = "12"
# Output: 2
# Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).
#
# Example 2:
#
# Input: s = "226"
# Output: 3
# Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
#
# Example 3:
#
# Input: s = "0"
# Output: 0
# Explanation: There is no character that is mapped to a number starting with 0.
# The only valid mappings with 0 are 'J' -> "10" and 'T' -> "20", neither of which start with 0.
# Hence, there are no valid ways to decode this since all digits need to be mapped.
#
# Example 4:
#
# Input: s = "06"
# Output: 0
# Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06").
#
#
# Constraints:
#
# 1 <= s.length <= 100
# s contains only digits and may contain leading zero(s).
#
#
class Solution:
def numDecodings(self, s: str) -> int:
valid_nums = set([str(i) for i in range(1, 27)])
@lru_cache(None)
def dp(pos):
if pos == len(s) - 1:
return int(s[pos] in valid_nums)
if pos == len(s):
return 1
ans = 0
ans = ans + dp(pos + 1) if s[pos] in valid_nums else ans
ans = ans + dp(pos + 2) if s[pos : pos + 2] in valid_nums else ans
return ans
return dp(0)
if __name__ == "__main__":
import os
import pytest
pytest.main([os.path.join("tests", "test_91.py")])
|
athenagroup/brxm
|
services-htmlprocessor/src/test/java/org/onehippo/cms7/services/htmlprocessor/service/VisibleHtmlCheckerServiceTest.java
|
/*
* Copyright 2019 <NAME>. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onehippo.cms7.services.htmlprocessor.service;
import org.junit.Test;
import org.onehippo.repository.mock.MockNode;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class VisibleHtmlCheckerServiceTest {
private static final String NORMAL_SPACE = Character.toString((char) 32);
private static final String NON_BREAKING_SPACE = Character.toString((char) 160);
private final VisibleHtmlCheckerService service = new VisibleHtmlCheckerService(MockNode.root());
@Test
public void nullIsInvisible() {
assertFalse(service.isVisible(null));
}
@Test
public void blankStringIsEmpty() {
assertInvisible("");
assertInvisible(" ");
}
@Test
public void invisibleCharactersIsEmpty() {
assertInvisible("\f\n\t\r");
}
@Test
public void simpleHtmlIsNotEmpty() {
assertVisible("aap noot mies");
}
@Test
public void complexHtmlIsNotEmpty() {
assertVisible("\n\raap<br /><p/>");
}
@Test
public void brIsEmpty() {
assertInvisible("<br />");
}
@Test
public void paragraphWithNormalSpaceIsEmpty() {
assertInvisible("<p>" + NORMAL_SPACE + "</p>");
}
@Test
public void paragraphWithNonBreakingSpaceIsEmpty() {
assertInvisible("<p>" + NON_BREAKING_SPACE + "</p>");
}
@Test
public void imageIsNotEmpty() {
assertVisible("<img src=\"xxx\" />");
}
@Test
public void objectIsNotEmpty() {
assertVisible("<object data=\"http://www.youtube.com/v/3Rj9oiNZiog&hl=en\" height=\"355\" type=\"application/x-shockwave-flash\" width=\"425\"><param name=\"movie\" value=\"http://www.youtube.com/v/3Rj9oiNZiog&hl=en\"/><param name=\"wmode\" value=\"transparent\"/></object>");
}
@Test
public void embedIsNotEmpty() {
assertVisible("<EMBED TYPE=\"application/x-mplayer2\" SRC=\"videofilename.wmv\" NAME=\"MediaPlayer\" WIDTH=\"192\" HEIGHT=\"290\" ShowControls=\"1\" ShowStatusBar=\"1\" ShowDisplay=\"1\" autostart=\"0\"> </EMBED>");
}
@Test
public void appletIsNotEmpty() {
assertVisible("<APPLET CODE=\"MyApplet.class\" WIDTH=200 HEIGHT=50><PARAM NAME=TEXT VALUE=\"Hi There\"></APPLET>");
}
@Test
public void formIsNotEmpty() {
assertVisible("<form name=\"myForm\"><input type=\"button\" value=\"button\" /></form>");
}
@Test
public void iframeIsNotEmpty() {
assertVisible("<iframe src=\"http://example.com\"></iframe>");
}
private static String wrapWithHtmlBody(final String text) {
return "<html><body>" + text + "</body></html>";
}
private void assertVisible(final String text) {
assertTrue(service.isVisible(text));
assertTrue(service.isVisible(wrapWithHtmlBody(text)));
}
private void assertInvisible(final String text) {
assertFalse(service.isVisible(text));
assertFalse(service.isVisible(wrapWithHtmlBody(text)));
}
}
|
phillip-keldenich/squares-in-disk
|
ivarp/include/ivarp/math_fn/eval.hpp
|
// The code is open source under the MIT license.
// Copyright 2019-2020, <NAME>, TU Braunschweig, Algorithms Group
// https://ibr.cs.tu-bs.de/alg
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by <NAME> on 08.10.19.
//
#pragma once
#include "ivarp/array.hpp"
#include "eval/number_type.hpp"
#include "eval/basic.hpp"
#include "eval/unary.hpp"
#include "eval/binary.hpp"
#include "eval/ternary.hpp"
#include "eval/n_ary.hpp"
namespace ivarp {
namespace impl {
template<typename Context, typename CalledType, typename... Args>
EvaluationCallResultType<Context, BareType<CalledType>, Args...>
evaluate(const CalledType& c, Args&&... args)
{
const Array<typename Context::NumberType, sizeof...(args)> a{
convert_number<typename Context::NumberType>(std::forward<Args>(args))...
};
return EvaluateImpl<Context, BareType<CalledType>, BareType<decltype(a)>>::eval(c, a);
}
}
}
template<typename Derived> template<typename Context, typename... Args>
auto ivarp::MathExpressionBase<Derived>::evaluate(Args&&... args) const ->
impl::EvaluationCallResultType<Context, Derived, Args...>
{
return impl::evaluate<Context>(static_cast<const Derived&>(*this), std::forward<Args>(args)...);
}
template<typename Derived> template<typename Context, typename ArrayType>
auto ivarp::MathExpressionBase<Derived>::array_evaluate(const ArrayType &args) const noexcept ->
EnableForCUDANT<typename Context::NumberType, impl::ArrayEvaluationCallResultType<Context, ArrayType>>
{
return impl::EvaluateImpl<Context, Derived, BareType<ArrayType>>::
eval(static_cast<const Derived&>(*this), args);
}
template<typename Derived> template<typename Context, typename ArrayType>
auto ivarp::MathExpressionBase<Derived>::array_evaluate(const ArrayType &args) const ->
DisableForCUDANT<typename Context::NumberType, impl::ArrayEvaluationCallResultType<Context, ArrayType>>
{
return impl::EvaluateImpl<Context, Derived, BareType<ArrayType>>::
eval(static_cast<const Derived&>(*this), args);
}
template<typename Derived> template<typename... Args, typename V>
auto ivarp::MathExpressionBase<Derived>::operator()(Args&&... args) const ->
impl::EvaluationCallResultType<DefaultEvaluationContext<Derived, BareType<Args>...>, Derived, Args...>
{
using Context = DefaultEvaluationContext<Derived, BareType<Args>...>;
return impl::evaluate<Context>(static_cast<const Derived&>(*this), std::forward<Args>(args)...);
}
|
cflowe/ACE
|
TAO/TAO_IDL/be/be_param_holder.cpp
|
<filename>TAO/TAO_IDL/be/be_param_holder.cpp
//=============================================================================
/**
* @file be_param_holder.cpp
*
* $Id: be_param_holder.cpp 91816 2010-09-17 08:35:56Z johnnyw $
*
* Place holder referenced by AST_Field (or subclass)
* representing a corresponding template parameter in IDL.
*
*
* @author <NAME>
*/
//=============================================================================
#include "be_param_holder.h"
#include "be_visitor.h"
be_param_holder::be_param_holder (UTL_ScopedName *parameter_name,
FE_Utils::T_Param_Info *info)
: COMMON_Base (false,
false),
AST_Decl (AST_Decl::NT_param_holder,
parameter_name),
AST_Type (AST_Decl::NT_param_holder,
parameter_name),
AST_Param_Holder (parameter_name,
info),
be_decl (AST_Decl::NT_param_holder,
parameter_name),
be_type (AST_Decl::NT_param_holder,
parameter_name)
{
}
be_param_holder::~be_param_holder (void)
{
}
int
be_param_holder::accept (be_visitor *visitor)
{
return visitor->visit_param_holder (this);
}
void
be_param_holder::destroy (void)
{
this->AST_Param_Holder::destroy ();
this->be_type::destroy ();
}
IMPL_NARROW_FROM_DECL (be_param_holder)
|
Jasonandy/Skeleton-X
|
skeleton-webapp/src/main/java/cn/ucaner/skeleton/webapp/entity/Message.java
|
/*******************************************************************************
* ~ Copyright (c) 2018 [<EMAIL> | https://github.com/Jasonandy] *
* ~ *
* ~ 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 cn.ucaner.skeleton.webapp.entity;
import java.io.Serializable;
/**
* @projectName:Skeleton-X
* @Package:cn.ucaner.skeleton.webapp.entity
* @Description: <p> Message </p>
* @Author: - Jason
* @CreatTime:2019/7/2 - 15:40
* @Modify By:
* @ModifyTime: 2019/7/2
* @Modify marker:
*/
public class Message implements Serializable {
/**
* 消息推送者
*/
private User from;
/**
* 消息内容
*/
private String message;
/**
* 消息接收者:
* 如果是私有(向指定窗口推送),to即为接受者User对象
* 如果是公共消息(群组聊天),to设为null
*/
private User to;
/**
* 创建时间
*/
private String time;
public void setMessage(String message) {
this.message = message == null ? "" : message.replaceAll("\r\n|\r|\n", "");
}
public User getFrom() {
return from;
}
public void setFrom(User from) {
this.from = from;
}
public String getMessage() {
return message;
}
public User getTo() {
return to;
}
public void setTo(User to) {
this.to = to;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
|
manavm1990/stream-adventure-1
|
test/solutions/duplexer.js
|
const { spawn } = require('child_process')
const duplexer = require('duplexer2')
module.exports = function (cmd, args) {
const ps = spawn(cmd, args)
return duplexer(ps.stdin, ps.stdout)
}
|
pageseeder/psml
|
src/main/java/org/pageseeder/psml/template/XML.java
|
<filename>src/main/java/org/pageseeder/psml/template/XML.java<gh_stars>0
/*
* Copyright 2016 Allette Systems (Australia)
* http://www.allette.com.au
*
* 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.pageseeder.psml.template;
import java.io.PrintWriter;
import java.nio.charset.Charset;
/**
* A collection of utility classes for XML.
*
* @author <NAME>
*/
public final class XML {
/**
* Last ASCII character.
*/
private final static int ASCII_LAST_CHAR = 0x80;
/**
* @param cs the charset to use for the target XML output.
* @return The corresponding XML encoder or <code>null</code> is none exists.
*/
public static Encoder getEncoder(Charset cs) {
if (cs.equals(Constants.ASCII)) return ASCII_ENCODER;
if (cs.equals(Constants.UTF8)) return UNICODE_ENCODER;
return null;
}
/**
* Indicates whether the has a non ASCII character.
*
* @param xml The XML to test.
* @return <code>true</code> if this XML contains a non-ASCII character;
* <code>false</code> if if all characters are ASCII (less than 0x80)
*/
public static boolean hasNonASCIIChar(String xml) {
final int upto = xml.length();
for (int i = 0; i < upto; i++) {
if (xml.charAt(i) >= ASCII_LAST_CHAR) return true;
}
return false;
}
/**
* Make the specified XML ASCII safe.
*
* @param unicode The XML as a unicode string.
* @param ascii The same XML with all non-ASCII characters converted to ASCII.
*/
public static void toASCII(String unicode, PrintWriter ascii) {
final int upto = unicode.length();
for (int i = 0; i < upto; i++) {
char c = unicode.charAt(i);
if (c >= ASCII_LAST_CHAR) {
ascii.append("&#x");
ascii.append(Integer.toHexString(c));
ascii.append(';');
} else {
ascii.append(c);
}
}
}
/**
* Encodes the XML text and attribute values using the appropriate numeric character entity when required
*/
public static interface Encoder {
/**
* Note: XML encoders can assume that attributes values are wrapped in double quotes.
*
* @param value Attribute value to XML encode.
* @param xml The XML output
*/
public void attribute(String value, StringBuilder xml);
/**
* XML encode for text value (reported by SAX <code>characters</code> method).
*
* @param ch Character array (reported by)
* @param start The start index in array to encode
* @param length The number of characters to encode.
* @param xml The XML output
*/
public void text(char[] ch, int start, int length, StringBuilder xml);
}
/**
* XML encode a character in an attribute node.
*
* @param c The character to check
* @param xml The XML output
*/
private final static void attributeChar(char c, StringBuilder xml) {
switch (c) {
case '&' :
xml.append("&");
break;
case '<' :
xml.append("<");
break;
case '"' :
xml.append(""");
break;
// output by default
default:
xml.append(c);
}
}
/**
* XML encode a character in a text node.
*
* @param c The character to check
* @param xml The XML output
*/
private final static void textChar(char c, StringBuilder xml) {
switch (c) {
case '&' :
xml.append("&");
break;
case '<' :
xml.append("<");
break;
// output by default
default:
xml.append(c);
}
}
/**
* The encoder to use for writing XML as unicode encoding only the characters which are illegal
* in some parts of the markup.
*/
private static final Encoder UNICODE_ENCODER = new Encoder() {
@Override
public void attribute(String value, StringBuilder xml) {
final int upto = value.length();
for (int i = 0; i < upto; i++) {
attributeChar(value.charAt(i), xml);
}
}
@Override
public void text(char[] ch, int start, int length, StringBuilder xml) {
final int upto = start+length;
for (int i = start; i < upto; i++) {
textChar(ch[i], xml);
}
}
};
/**
* The encoder to use for writing XML as ASCII encoding any characters which is illegal or
* outside the ASCII range.
*/
private static final Encoder ASCII_ENCODER = new Encoder() {
@Override
public void attribute(String value, StringBuilder xml) {
final int upto = value.length();
for (int i = 0; i < upto; i++) {
char c = value.charAt(i);
if (c < ASCII_LAST_CHAR) {
attributeChar(value.charAt(i), xml);
} else {
xml.append("&#x");
xml.append(Integer.toHexString(c));
xml.append(';');
}
}
}
@Override
public void text(char[] ch, int start, int length, StringBuilder xml) {
final int upto = start+length;
for (int i = start; i < upto; i++) {
if (ch[i] < ASCII_LAST_CHAR) {
textChar(ch[i], xml);
} else {
xml.append("&#x");
xml.append(Integer.toHexString(ch[i]));
xml.append(';');
}
}
}
};
}
|
dmgerman/hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/resourceplugin/deviceframework/DeviceResourceDockerRuntimePluginImpl.java
|
<gh_stars>0
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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 *<p> * http://www.apache.org/licenses/LICENSE-2.0 *<p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
DECL|package|org.apache.hadoop.yarn.server.nodemanager.containermanager.resourceplugin.deviceframework
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|containermanager
operator|.
name|resourceplugin
operator|.
name|deviceframework
package|;
end_package
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|LoggerFactory
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ContainerId
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|api
operator|.
name|deviceplugin
operator|.
name|Device
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|api
operator|.
name|deviceplugin
operator|.
name|DevicePlugin
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|api
operator|.
name|deviceplugin
operator|.
name|DeviceRuntimeSpec
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|api
operator|.
name|deviceplugin
operator|.
name|MountDeviceSpec
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|api
operator|.
name|deviceplugin
operator|.
name|MountVolumeSpec
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|api
operator|.
name|deviceplugin
operator|.
name|VolumeSpec
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|api
operator|.
name|deviceplugin
operator|.
name|YarnRuntimeType
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|containermanager
operator|.
name|container
operator|.
name|Container
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|containermanager
operator|.
name|linux
operator|.
name|runtime
operator|.
name|docker
operator|.
name|DockerRunCommand
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|containermanager
operator|.
name|linux
operator|.
name|runtime
operator|.
name|docker
operator|.
name|DockerVolumeCommand
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|containermanager
operator|.
name|resourceplugin
operator|.
name|DockerCommandPlugin
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|containermanager
operator|.
name|runtime
operator|.
name|ContainerExecutionException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|util
operator|.
name|LRUCacheHashMap
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Collections
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Set
import|;
end_import
begin_comment
comment|/** * Bridge DevicePlugin and the hooks related to lunch Docker container. * When launching Docker container, DockerLinuxContainerRuntime will invoke * this class's methods which get needed info back from DevicePlugin. * */
end_comment
begin_class
DECL|class|DeviceResourceDockerRuntimePluginImpl
specifier|public
class|class
name|DeviceResourceDockerRuntimePluginImpl
implements|implements
name|DockerCommandPlugin
block|{
DECL|field|LOG
specifier|final
specifier|static
name|Logger
name|LOG
init|=
name|LoggerFactory
operator|.
name|getLogger
argument_list|(
name|DeviceResourceDockerRuntimePluginImpl
operator|.
name|class
argument_list|)
decl_stmt|;
DECL|field|resourceName
specifier|private
name|String
name|resourceName
decl_stmt|;
DECL|field|devicePlugin
specifier|private
name|DevicePlugin
name|devicePlugin
decl_stmt|;
DECL|field|devicePluginAdapter
specifier|private
name|DevicePluginAdapter
name|devicePluginAdapter
decl_stmt|;
DECL|field|maxCacheSize
specifier|private
name|int
name|maxCacheSize
init|=
literal|100
decl_stmt|;
comment|// LRU to avoid memory leak if getCleanupDockerVolumesCommand not invoked.
DECL|field|cachedAllocation
specifier|private
name|Map
argument_list|<
name|ContainerId
argument_list|,
name|Set
argument_list|<
name|Device
argument_list|>
argument_list|>
name|cachedAllocation
init|=
name|Collections
operator|.
name|synchronizedMap
argument_list|(
operator|new
name|LRUCacheHashMap
argument_list|(
name|maxCacheSize
argument_list|,
literal|true
argument_list|)
argument_list|)
decl_stmt|;
DECL|field|cachedSpec
specifier|private
name|Map
argument_list|<
name|ContainerId
argument_list|,
name|DeviceRuntimeSpec
argument_list|>
name|cachedSpec
init|=
name|Collections
operator|.
name|synchronizedMap
argument_list|(
operator|new
name|LRUCacheHashMap
argument_list|<>
argument_list|(
name|maxCacheSize
argument_list|,
literal|true
argument_list|)
argument_list|)
decl_stmt|;
DECL|method|DeviceResourceDockerRuntimePluginImpl (String resourceName, DevicePlugin devicePlugin, DevicePluginAdapter devicePluginAdapter)
specifier|public
name|DeviceResourceDockerRuntimePluginImpl
parameter_list|(
name|String
name|resourceName
parameter_list|,
name|DevicePlugin
name|devicePlugin
parameter_list|,
name|DevicePluginAdapter
name|devicePluginAdapter
parameter_list|)
block|{
name|this
operator|.
name|resourceName
operator|=
name|resourceName
expr_stmt|;
name|this
operator|.
name|devicePlugin
operator|=
name|devicePlugin
expr_stmt|;
name|this
operator|.
name|devicePluginAdapter
operator|=
name|devicePluginAdapter
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|updateDockerRunCommand (DockerRunCommand dockerRunCommand, Container container)
specifier|public
name|void
name|updateDockerRunCommand
parameter_list|(
name|DockerRunCommand
name|dockerRunCommand
parameter_list|,
name|Container
name|container
parameter_list|)
throws|throws
name|ContainerExecutionException
block|{
name|String
name|containerId
init|=
name|container
operator|.
name|getContainerId
argument_list|()
operator|.
name|toString
argument_list|()
decl_stmt|;
name|LOG
operator|.
name|debug
argument_list|(
literal|"Try to update docker run command for: {}"
argument_list|,
name|containerId
argument_list|)
expr_stmt|;
if|if
condition|(
operator|!
name|requestedDevice
argument_list|(
name|resourceName
argument_list|,
name|container
argument_list|)
condition|)
block|{
return|return;
block|}
name|DeviceRuntimeSpec
name|deviceRuntimeSpec
init|=
name|getRuntimeSpec
argument_list|(
name|container
argument_list|)
decl_stmt|;
if|if
condition|(
name|deviceRuntimeSpec
operator|==
literal|null
condition|)
block|{
name|LOG
operator|.
name|warn
argument_list|(
literal|"The device plugin: "
operator|+
name|devicePlugin
operator|.
name|getClass
argument_list|()
operator|.
name|getCanonicalName
argument_list|()
operator|+
literal|" returns null device runtime spec value for container: "
operator|+
name|containerId
argument_list|)
expr_stmt|;
return|return;
block|}
comment|// handle runtime
name|dockerRunCommand
operator|.
name|addRuntime
argument_list|(
name|deviceRuntimeSpec
operator|.
name|getContainerRuntime
argument_list|()
argument_list|)
expr_stmt|;
name|LOG
operator|.
name|debug
argument_list|(
literal|"Handle docker container runtime type: {} for container: {}"
argument_list|,
name|deviceRuntimeSpec
operator|.
name|getContainerRuntime
argument_list|()
argument_list|,
name|containerId
argument_list|)
expr_stmt|;
comment|// handle device mounts
name|Set
argument_list|<
name|MountDeviceSpec
argument_list|>
name|deviceMounts
init|=
name|deviceRuntimeSpec
operator|.
name|getDeviceMounts
argument_list|()
decl_stmt|;
name|LOG
operator|.
name|debug
argument_list|(
literal|"Handle device mounts: {} for container: {}"
argument_list|,
name|deviceMounts
argument_list|,
name|containerId
argument_list|)
expr_stmt|;
for|for
control|(
name|MountDeviceSpec
name|mountDeviceSpec
range|:
name|deviceMounts
control|)
block|{
name|dockerRunCommand
operator|.
name|addDevice
argument_list|(
name|mountDeviceSpec
operator|.
name|getDevicePathInHost
argument_list|()
argument_list|,
name|mountDeviceSpec
operator|.
name|getDevicePathInContainer
argument_list|()
argument_list|)
expr_stmt|;
block|}
comment|// handle volume mounts
name|Set
argument_list|<
name|MountVolumeSpec
argument_list|>
name|mountVolumeSpecs
init|=
name|deviceRuntimeSpec
operator|.
name|getVolumeMounts
argument_list|()
decl_stmt|;
name|LOG
operator|.
name|debug
argument_list|(
literal|"Handle volume mounts: {} for container: {}"
argument_list|,
name|mountVolumeSpecs
argument_list|,
name|containerId
argument_list|)
expr_stmt|;
for|for
control|(
name|MountVolumeSpec
name|mountVolumeSpec
range|:
name|mountVolumeSpecs
control|)
block|{
if|if
condition|(
name|mountVolumeSpec
operator|.
name|getReadOnly
argument_list|()
condition|)
block|{
name|dockerRunCommand
operator|.
name|addReadOnlyMountLocation
argument_list|(
name|mountVolumeSpec
operator|.
name|getHostPath
argument_list|()
argument_list|,
name|mountVolumeSpec
operator|.
name|getMountPath
argument_list|()
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|dockerRunCommand
operator|.
name|addReadWriteMountLocation
argument_list|(
name|mountVolumeSpec
operator|.
name|getHostPath
argument_list|()
argument_list|,
name|mountVolumeSpec
operator|.
name|getMountPath
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
comment|// handle envs
name|dockerRunCommand
operator|.
name|addEnv
argument_list|(
name|deviceRuntimeSpec
operator|.
name|getEnvs
argument_list|()
argument_list|)
expr_stmt|;
name|LOG
operator|.
name|debug
argument_list|(
literal|"Handle envs: {} for container: {}"
argument_list|,
name|deviceRuntimeSpec
operator|.
name|getEnvs
argument_list|()
argument_list|,
name|containerId
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|getCreateDockerVolumeCommand (Container container)
specifier|public
name|DockerVolumeCommand
name|getCreateDockerVolumeCommand
parameter_list|(
name|Container
name|container
parameter_list|)
throws|throws
name|ContainerExecutionException
block|{
if|if
condition|(
operator|!
name|requestedDevice
argument_list|(
name|resourceName
argument_list|,
name|container
argument_list|)
condition|)
block|{
return|return
literal|null
return|;
block|}
name|DeviceRuntimeSpec
name|deviceRuntimeSpec
init|=
name|getRuntimeSpec
argument_list|(
name|container
argument_list|)
decl_stmt|;
if|if
condition|(
name|deviceRuntimeSpec
operator|==
literal|null
condition|)
block|{
return|return
literal|null
return|;
block|}
name|Set
argument_list|<
name|VolumeSpec
argument_list|>
name|volumeClaims
init|=
name|deviceRuntimeSpec
operator|.
name|getVolumeSpecs
argument_list|()
decl_stmt|;
for|for
control|(
name|VolumeSpec
name|volumeSec
range|:
name|volumeClaims
control|)
block|{
if|if
condition|(
name|volumeSec
operator|.
name|getVolumeOperation
argument_list|()
operator|.
name|equals
argument_list|(
name|VolumeSpec
operator|.
name|CREATE
argument_list|)
condition|)
block|{
name|DockerVolumeCommand
name|command
init|=
operator|new
name|DockerVolumeCommand
argument_list|(
name|DockerVolumeCommand
operator|.
name|VOLUME_CREATE_SUB_COMMAND
argument_list|)
decl_stmt|;
name|command
operator|.
name|setDriverName
argument_list|(
name|volumeSec
operator|.
name|getVolumeDriver
argument_list|()
argument_list|)
expr_stmt|;
name|command
operator|.
name|setVolumeName
argument_list|(
name|volumeSec
operator|.
name|getVolumeName
argument_list|()
argument_list|)
expr_stmt|;
name|LOG
operator|.
name|debug
argument_list|(
literal|"Get volume create request from plugin:{} for container: {}"
argument_list|,
name|volumeClaims
argument_list|,
name|container
operator|.
name|getContainerId
argument_list|()
argument_list|)
expr_stmt|;
return|return
name|command
return|;
block|}
block|}
return|return
literal|null
return|;
block|}
annotation|@
name|Override
DECL|method|getCleanupDockerVolumesCommand (Container container)
specifier|public
name|DockerVolumeCommand
name|getCleanupDockerVolumesCommand
parameter_list|(
name|Container
name|container
parameter_list|)
throws|throws
name|ContainerExecutionException
block|{
if|if
condition|(
operator|!
name|requestedDevice
argument_list|(
name|resourceName
argument_list|,
name|container
argument_list|)
condition|)
block|{
return|return
literal|null
return|;
block|}
name|Set
argument_list|<
name|Device
argument_list|>
name|allocated
init|=
name|getAllocatedDevices
argument_list|(
name|container
argument_list|)
decl_stmt|;
try|try
block|{
name|devicePlugin
operator|.
name|onDevicesReleased
argument_list|(
name|allocated
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|warn
argument_list|(
literal|"Exception thrown in onDeviceReleased of "
operator|+
name|devicePlugin
operator|.
name|getClass
argument_list|()
operator|+
literal|"for container: "
operator|+
name|container
operator|.
name|getContainerId
argument_list|()
operator|.
name|toString
argument_list|()
argument_list|,
name|e
argument_list|)
expr_stmt|;
block|}
comment|// remove cache
name|ContainerId
name|containerId
init|=
name|container
operator|.
name|getContainerId
argument_list|()
decl_stmt|;
name|cachedAllocation
operator|.
name|remove
argument_list|(
name|containerId
argument_list|)
expr_stmt|;
name|cachedSpec
operator|.
name|remove
argument_list|(
name|containerId
argument_list|)
expr_stmt|;
return|return
literal|null
return|;
block|}
DECL|method|requestedDevice (String resName, Container container)
specifier|protected
name|boolean
name|requestedDevice
parameter_list|(
name|String
name|resName
parameter_list|,
name|Container
name|container
parameter_list|)
block|{
return|return
name|DeviceMappingManager
operator|.
name|getRequestedDeviceCount
argument_list|(
name|resName
argument_list|,
name|container
operator|.
name|getResource
argument_list|()
argument_list|)
operator|>
literal|0
return|;
block|}
DECL|method|getAllocatedDevices (Container container)
specifier|private
name|Set
argument_list|<
name|Device
argument_list|>
name|getAllocatedDevices
parameter_list|(
name|Container
name|container
parameter_list|)
block|{
comment|// get allocated devices
name|Set
argument_list|<
name|Device
argument_list|>
name|allocated
decl_stmt|;
name|ContainerId
name|containerId
init|=
name|container
operator|.
name|getContainerId
argument_list|()
decl_stmt|;
name|allocated
operator|=
name|cachedAllocation
operator|.
name|get
argument_list|(
name|containerId
argument_list|)
expr_stmt|;
if|if
condition|(
name|allocated
operator|!=
literal|null
condition|)
block|{
return|return
name|allocated
return|;
block|}
name|allocated
operator|=
name|devicePluginAdapter
operator|.
name|getDeviceMappingManager
argument_list|()
operator|.
name|getAllocatedDevices
argument_list|(
name|resourceName
argument_list|,
name|containerId
argument_list|)
expr_stmt|;
name|LOG
operator|.
name|debug
argument_list|(
literal|"Get allocation from deviceMappingManager: {}, {} for"
operator|+
literal|" container: {}"
argument_list|,
name|allocated
argument_list|,
name|resourceName
argument_list|,
name|containerId
argument_list|)
expr_stmt|;
name|cachedAllocation
operator|.
name|put
argument_list|(
name|containerId
argument_list|,
name|allocated
argument_list|)
expr_stmt|;
return|return
name|allocated
return|;
block|}
DECL|method|getRuntimeSpec (Container container)
specifier|public
specifier|synchronized
name|DeviceRuntimeSpec
name|getRuntimeSpec
parameter_list|(
name|Container
name|container
parameter_list|)
block|{
name|ContainerId
name|containerId
init|=
name|container
operator|.
name|getContainerId
argument_list|()
decl_stmt|;
name|DeviceRuntimeSpec
name|deviceRuntimeSpec
init|=
name|cachedSpec
operator|.
name|get
argument_list|(
name|containerId
argument_list|)
decl_stmt|;
if|if
condition|(
name|deviceRuntimeSpec
operator|==
literal|null
condition|)
block|{
name|Set
argument_list|<
name|Device
argument_list|>
name|allocated
init|=
name|getAllocatedDevices
argument_list|(
name|container
argument_list|)
decl_stmt|;
if|if
condition|(
name|allocated
operator|==
literal|null
operator|||
name|allocated
operator|.
name|size
argument_list|()
operator|==
literal|0
condition|)
block|{
name|LOG
operator|.
name|error
argument_list|(
literal|"Cannot get allocation for container:"
operator|+
name|containerId
argument_list|)
expr_stmt|;
return|return
literal|null
return|;
block|}
try|try
block|{
name|deviceRuntimeSpec
operator|=
name|devicePlugin
operator|.
name|onDevicesAllocated
argument_list|(
name|allocated
argument_list|,
name|YarnRuntimeType
operator|.
name|RUNTIME_DOCKER
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|error
argument_list|(
literal|"Exception thrown in onDeviceAllocated of "
operator|+
name|devicePlugin
operator|.
name|getClass
argument_list|()
operator|+
literal|" for container: "
operator|+
name|containerId
argument_list|,
name|e
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|deviceRuntimeSpec
operator|==
literal|null
condition|)
block|{
name|LOG
operator|.
name|error
argument_list|(
literal|"Null DeviceRuntimeSpec value got from "
operator|+
name|devicePlugin
operator|.
name|getClass
argument_list|()
operator|+
literal|" for container: "
operator|+
name|containerId
operator|+
literal|", please check plugin logic"
argument_list|)
expr_stmt|;
return|return
literal|null
return|;
block|}
name|cachedSpec
operator|.
name|put
argument_list|(
name|containerId
argument_list|,
name|deviceRuntimeSpec
argument_list|)
expr_stmt|;
block|}
return|return
name|deviceRuntimeSpec
return|;
block|}
block|}
end_class
end_unit
|
DEFRA/ffc-pay-processing
|
app/processing/route-debt-to-request-editor.js
|
<reponame>DEFRA/ffc-pay-processing
const db = require('../data')
const { getHoldCategoryId } = require('../holds')
const sendDebtMessage = require('../messaging/send-debt-message')
const holdAndReschedule = require('../reschedule')
const util = require('util')
const routeToRequestEditor = async (paymentRequest) => {
const transaction = await db.sequelize.transaction()
try {
await sendDebtMessage(paymentRequest)
console.log('Payment request routed to request editor:', util.inspect(paymentRequest, false, null, true))
const holdCategoryId = await getHoldCategoryId(paymentRequest.schemeId, 'Awaiting debt enrichment', transaction)
await holdAndReschedule(paymentRequest.schemeId, paymentRequest.paymentRequestId, holdCategoryId, paymentRequest.frn, transaction)
await transaction.commit()
} catch (error) {
await transaction.rollback()
throw (error)
}
}
module.exports = routeToRequestEditor
|
TomasEkeli/AspNetCore
|
Legacy/doLittle.JavaScript.Specs/validation/for_Validator/when_creating_without_options_and_setting_options_later.js
|
<gh_stars>0
describe("when creating without options and setting options later", function () {
var options = { something: "hello world" };
var rules = { knownRule: options };
var validator = null;
var knownRule = null;
beforeEach(function () {
knownRule = {
_name: "knownRule",
create: sinon.mock().withArgs({ options: options }).once()
};
Dolittle.validation.Rule = {
getExtenders: function () {
return [knownRule];
}
}
validator = Dolittle.validation.Validator.create();
validator.setOptions(rules);
});
it("should create a rule with correct name and options", function () {
expect(knownRule.create.called).toBe(true);
});
});
|
MMMMQQQQ/shacl-plugin
|
lib/shacl-master/src/test/java/org/topbraid/shacl/MF.java
|
package org.topbraid.shacl;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
public class MF {
public final static String BASE_URI = "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest";
public final static String NS = BASE_URI + "#";
public final static String PREFIX = "mf";
public final static Resource Manifest = ResourceFactory.createResource(NS + "Manifest");
public final static Property action = ResourceFactory.createProperty(NS + "action");
public final static Property entries = ResourceFactory.createProperty(NS + "entries");
public final static Property include = ResourceFactory.createProperty(NS + "include");
public final static Property name = ResourceFactory.createProperty(NS + "name");
public final static Property result = ResourceFactory.createProperty(NS + "result");
public final static Property status = ResourceFactory.createProperty(NS + "status");
}
|
CognizantOpenSource/Cognizant-Intelligent-Test-Scripter
|
StoryWriter/src/main/java/com/cognizant/storywriter/bdd/ui/UIControl.java
|
<reponame>CognizantOpenSource/Cognizant-Intelligent-Test-Scripter
/*
* Copyright 2014 - 2017 Cognizant Technology Solutions
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cognizant.storywriter.bdd.ui;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import com.cognizant.storywriter.bdd.data.Story;
import com.cognizant.storywriter.bdd.data.BDDProject;
import com.cognizant.storywriter.bdd.data.StoryParser;
import com.cognizant.storywriter.bdd.ui.handlers.FeatureListTransferHandler;
import com.cognizant.storywriter.util.Notification.Msg;
import com.cognizant.storywriter.util.SLogger;
import com.cognizant.storywriter.util.Tools;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
*
*/
public final class UIControl {
BDDProject project;
String path = "projects/test.json";
public UI2 ui;
public static JFileChooser openProj, newProj, importFeature, exportFeature;
Story cStory;
boolean editStory;
public MouseListener sClick;
public static UIControl ctrl;
boolean editScn;
private static final Logger LOGGER = Logger.getLogger(UIControl.class.getName());
RecentItems rItems;
TransferHandler featureTransferHandler;
public UIControl() throws IOException {
openProj = new JFileChooser(System.getProperty("user.dir"), null);
openProj.setFileSelectionMode(JFileChooser.OPEN_DIALOG);
openProj.setFileFilter(com.cognizant.storywriter.util.Tools.json);
newProj = new JFileChooser(System.getProperty("user.dir"), null);
newProj.setFileSelectionMode(JFileChooser.SAVE_DIALOG);
newProj.setFileFilter(com.cognizant.storywriter.util.Tools.json);
exportFeature = new JFileChooser(System.getProperty("user.dir"), null);
importFeature = new JFileChooser(System.getProperty("user.dir"), null);
importFeature.setFileSelectionMode(JFileChooser.OPEN_DIALOG);
importFeature.setFileFilter(com.cognizant.storywriter.util.Tools.feature);
featureTransferHandler = new FeatureListTransferHandler(this::importFeature);
ui = new UI2(this);
rItems = new RecentItems();
File latest = rItems.lastProject();
if (latest != null) {
loadProj(latest.getAbsolutePath());
}
rItems.updateMenu(ui.recentsMenu);
initListeners();
ui.setVisible(true);
}
/**
* loads a projects
*
* @param path
*/
public void loadProj(String path) {
try {
clearAll();
project = BDDProject.load(new File(path));
ui.eTools(true);
if (project.hasStories()) {
ui.initStoryData(project.getStories());
}
ui.setTitle(new File(path).getName().replace(".json", ""));
} catch (Exception ex) {
SLogger.LOGE(ex.getMessage());
}
}
public static void main(String[] args) throws IOException {
try {
LogManager logManager = LogManager.getLogManager();
try (InputStream is = UIManager.class.getResourceAsStream("/log.config")) {
logManager.readConfiguration(is);
}
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if (info.getName().equals("Metal")) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
ctrl = new UIControl();
}
/**
* initialize listeners
*/
private void initListeners() {
ui.featureList.addListSelectionListener((ListSelectionEvent e) -> {
storyChanged();
});
sClick = (new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
startEdit((Story) ui.featureList.getSelectedValue());
}
}
});
}
/**
* initiate actions on story change
*/
public void storyChanged() {
Story s = (Story) ui.featureList.getSelectedValue();
if (s != null && cStory != s) {
cStory = s;
ui.setStoryText(s.getData());
}
}
/**
* set story edit flag true
*
* @param s
*/
void startEdit(Story s) {
editStory = true;
ui.addStory.setVisible(true);
ui.storyName.setText(s.desc);
}
/**
* removes the story selected
*/
void removeStory() {
int[] list = ui.featureList.getSelectedIndices();
if (list.length > 0) {
int index = list[0] - 1;
for (int i : list) {
Story s = (Story) ui.featureList.getSelectedValue();
project.getStories().remove(s);
ui.storydata.removeElement(s);
}
ui.refreshStoryList();
if (index >= 0) {
ui.featureList.setSelectedIndex(index);
}
}
}
/**
* save the project
*/
void saveAll() {
try {
saveFeature(ui.getStoryText());
project.write();
SLogger.LOGA(Msg.C_SAVE);
LOGGER.info(Msg.C_SAVE);
} catch (Exception ex) {
SLogger.LOGA(Msg.SOS + ex.getMessage());
LOGGER.log(Level.SEVERE, Msg.SOS, ex);
}
}
/**
* export a selected story/feature
*/
void export() {
Story s = (Story) ui.featureList.getSelectedValue();
if (s != null) {
exportFeature.setSelectedFile(new File(String.format("%s.feature", s.name)));
int stat = exportFeature.showSaveDialog(ui);
if (stat == JFileChooser.APPROVE_OPTION) {
Tools.writeFile(exportFeature.getSelectedFile(), s.getData());
SLogger.LOGA(Msg.C_EXPORT);
LOGGER.info(Msg.C_EXPORT);
}
} else {
SLogger.LOGA(Msg.NO_EXPORT);
LOGGER.warning(Msg.NO_EXPORT);
}
}
/**
* open a project (json)
*/
void openProj() {
int res = openProj.showOpenDialog(ui);
if (res == JFileChooser.APPROVE_OPTION) {
loadProj(openProj.getSelectedFile().getAbsolutePath());
rItems.addentry(openProj.getSelectedFile().getAbsolutePath());
rItems.updateMenu(ui.recentsMenu);
SLogger.LOGA(openProj.getSelectedFile().getAbsolutePath());
LOGGER.info(openProj.getSelectedFile().getAbsolutePath());
}
}
/**
* add or edit a story
*/
void addStory() {
String name = ui.storyName.getText();
if (editStory) {
LOGGER.info(String.format("Updating Feature %s", ((Story) ui.featureList.getSelectedValue()).name));
((Story) ui.featureList.getSelectedValue()).name = ui.storyName.getText();
} else if (name != null && !"".equals(name)) {
Story s = new Story(name, ui.storyDesc.getText());
LOGGER.info(String.format("Adding Feature %s", s.name));
addStory(s);
ui.refreshStoryList();
}
}
/**
* add story to stories
*
* @param s
*/
void addStory(Story s) {
ui.storydata.addElement(s);
project.getStories().add(s);
}
/**
* creates new project
*/
private static String sanitizePathTraversal(String filename) {
Path p = Paths.get(filename);
return p.getFileName().toString();
}
void createNewProject() {
String name = sanitizePathTraversal(ui.npName.getText());
if (!name.isEmpty()) {
File f = new File("projects" + File.separator + name + ".json");
if (!f.exists()) {
f.getParentFile().mkdirs();
BDDProject.create(f, name, ui.npDesc.getText());
loadProj(f.getAbsolutePath());
rItems.addentry(f.getAbsolutePath());
rItems.updateMenu(ui.recentsMenu);
SLogger.LOGA("New Project created!\n" + f.getAbsolutePath());
LOGGER.log(Level.INFO, "New Project created! {0}", f.getAbsolutePath());
} else {
SLogger.LOGA("Project Exist!\n" + f.getAbsolutePath());
LOGGER.log(Level.WARNING, "Project Exist! {0}", f.getAbsolutePath());
}
}
}
/**
* clear all existing
*/
private void clearAll() {
ui.storydata.clear();
}
/**
* Get - Open - Parse and Import a feature file
*/
void importFeature() {
int stat = importFeature.showOpenDialog(ui);
if (stat == JFileChooser.APPROVE_OPTION) {
importFeature(importFeature.getSelectedFile());
}
}
/**
* Get - Open - Parse and Import a feature file
*
* @param feature
*/
public void importFeature(File feature) {
try {
LOGGER.log(Level.INFO, "Importing {0}", feature.getName());
StoryParser sp = new StoryParser(feature);
project.getStories().addAll(sp.stories());
sp.stories().stream().forEach(ui.storydata::addElement);
ui.refreshStoryList();
SLogger.LOGA(String.format("%s Imported!", feature.getName()));
LOGGER.log(Level.INFO, String.format("%s Imported!", feature.getName()));
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, Msg.SOS, ex);
}
}
void saveFeature(String text) {
cStory.setData(text);
ui.updateAutoComplete();
}
}
|
chenleii/chen-ddd
|
ddd-core/ddd-core-order/src/main/java/com/chen/ddd/core/order/domain/model/event/PrepaidOrderEvent.java
|
package com.chen.ddd.core.order.domain.model.event;
import com.chen.ddd.core.order.domain.model.Order;
import lombok.Getter;
import lombok.ToString;
import lombok.experimental.SuperBuilder;
/**
* @author cl
* @version 1.0
* @since 2021/9/6 21:23
*/
@SuperBuilder
@Getter
@ToString(callSuper = true)
public class PrepaidOrderEvent extends OrderEvent{
public static PrepaidOrderEvent create(Order order) {
return PrepaidOrderEvent.builder().build();
}
}
|
HeatherHeath5/swirve
|
SwrveSDK/src/main/java/com/swrve/sdk/rest/SwrveFilterInputStream.java
|
<filename>SwrveSDK/src/main/java/com/swrve/sdk/rest/SwrveFilterInputStream.java
package com.swrve.sdk.rest;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public final class SwrveFilterInputStream extends FilterInputStream {
private boolean hasMoreToRead = true;
public SwrveFilterInputStream(InputStream stream) {
super(stream);
}
@Override
public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
if (hasMoreToRead) {
int result = super.read(buffer, byteOffset, byteCount);
if (result != -1) {
return result;
}
}
hasMoreToRead = false;
return -1;
}
}
|
zhukevgeniy/owi
|
bin/www.js
|
<reponame>zhukevgeniy/owi
if(process.env.NODE_ENV === 'production'){
require('../dist/server.bundle.js');
} else {
require('../server');
}
|
yossugi/vico
|
app/ViMarkManager.h
|
/*
* Copyright (c) 2008-2012 <NAME> <<EMAIL>>
* 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.
*
* 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.
*/
#import "ViMark.h"
@interface ViMarkGroup : NSObject
{
SEL _groupSelector;
NSMutableDictionary *_groups;
}
@property (nonatomic, readonly) NSArray *groups;
+ (ViMarkGroup *)markGroupWithSelector:(SEL)aSelector;
- (ViMarkGroup *)initWithSelector:(SEL)aSelector;
- (NSString *)attribute;
- (void)rebuildFromMarks:(NSArray *)marks;
- (void)addMark:(ViMark *)mark;
- (void)addMarksFromArray:(NSArray *)marksToAdd;
- (void)removeMark:(ViMark *)mark;
- (void)clear;
@end
@interface ViMarkList : NSObject
{
NSMutableArray *_marks;
NSMutableDictionary *_marksByName;
NSInteger _currentIndex;
NSMutableDictionary *_groups;
id _identifier;
NSImage *_icon;
id _userParameter;
}
@property (nonatomic, readonly) NSArray *marks;
@property (nonatomic, readwrite, retain) id userParameter;
+ (ViMarkList *)markListWithIdentifier:(id)anIdentifier;
+ (ViMarkList *)markList;
- (ViMarkList *)initWithIdentifier:(id)anIdentifier;
- (void)clear;
- (ViMark *)lookup:(NSString *)name;
- (NSUInteger)count;
- (void)addMark:(ViMark *)mark;
- (void)addMarksFromArray:(NSArray *)marksToAdd;
- (void)removeMarkAtIndex:(NSUInteger)index;
- (void)removeMark:(ViMark *)mark;
- (ViMark *)first;
- (ViMark *)last;
- (ViMark *)next;
- (ViMark *)previous;
- (ViMark *)current;
- (BOOL)atBeginning;
- (BOOL)atEnd;
- (void)push:(ViMark *)mark;
- (ViMark *)pop;
@end
@interface ViMarkStack : NSObject
{
NSString *_name;
NSMutableArray *_lists;
NSInteger _currentIndex;
NSInteger _maxLists;
}
@property (nonatomic, readwrite, copy) NSString *name;
@property (nonatomic, readonly) ViMarkList *list;
@property (nonatomic, readwrite) NSInteger maxLists;
+ (ViMarkStack *)markStackWithName:(NSString *)name;
- (ViMarkStack *)initWithName:(NSString *)name;
- (ViMarkList *)makeList;
- (void)clear;
- (void)setMaxLists:(NSInteger)num;
- (void)removeListAtIndex:(NSUInteger)index;
- (ViMarkList *)push:(ViMarkList *)list;
- (ViMarkList *)listAtIndex:(NSInteger)anIndex;
- (ViMarkList *)next;
- (ViMarkList *)previous;
- (ViMarkList *)last;
- (ViMarkList *)current;
- (BOOL)atBeginning;
- (BOOL)atEnd;
@end
@interface ViMarkManager : NSObject
{
NSMutableArray *_stacks;
NSMutableDictionary *_namedStacks; // keyed by name
}
@property (nonatomic, readonly) NSArray *stacks;
+ (ViMarkManager *)sharedManager;
- (void)removeStack:(ViMarkStack *)stack;
- (void)removeStackWithName:(NSString *)name;
- (ViMarkStack *)makeStack;
- (ViMarkStack *)stackWithName:(NSString *)name;
@end
|
heatd/edk2-platforms
|
Platform/Intel/WhitleyOpenBoardPkg/Include/Library/MultiPlatSupportLib.h
|
<filename>Platform/Intel/WhitleyOpenBoardPkg/Include/Library/MultiPlatSupportLib.h
/** @file
@copyright
Copyright 2012 - 2021 Intel Corporation. <BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#ifndef _MULTI_PLATFORM_SUPPORT_LIB_H_
#define _MULTI_PLATFORM_SUPPORT_LIB_H_
#define MAX_TEMP_BUFFER 0x5000
//#define MULTI_PLATFORM_DEBUG TRUE
/*++
Description:
This function finds the matched default data and create GUID hob for it.
Arguments:
DefaultId - Specifies the type of defaults to retrieve.
BoardId - Specifies the platform board of defaults to retrieve.
Returns:
EFI_SUCCESS - The matched default data is found.
EFI_NOT_FOUND - The matched default data is not found.
EFI_OUT_OF_RESOURCES - No enough resource to create HOB.
--*/
EFI_STATUS
CreateDefaultVariableHob (
IN UINT16 DefaultId,
IN UINT16 BoardId
);
/**
Gets a vairable store header from FFS inserted by FCE
Arguments:
DefaultId - Specifies the type of defaults to retrieve.
BoardId - Specifies the platform board of defaults to retrieve.
@return The start address of VARIABLE_STORE_HEADER *. Null if cannot find it
**/
VOID * FindDefaultHobinFfs (
IN UINT16 DefaultId,
IN UINT16 BoardId
);
#endif
|
michael105/minicore
|
core/rm.c
|
<reponame>michael105/minicore<gh_stars>10-100
#if 0
mini_start
mini_writes
mini_perror
mini_errno
LDSCRIPT text_and_bss
shrinkelf
INCLUDESRC
return
#endif
void usage(){
writes("Usage: rm file1 [file2] ...\n");
exit(1);
}
int main(int argc, char *argv[])
{
int i;
if (argc == 1) {
usage();
}
for (i = 1; i < argc; i++) {
if (unlink(argv[i]) < 0) {
perror("rm: ");
return 1;
}
}
return 0;
}
|
PaulYuQ/Movie_Seven
|
src/main/java/dao/CommentDao.java
|
<reponame>PaulYuQ/Movie_Seven<filename>src/main/java/dao/CommentDao.java<gh_stars>0
package dao;
import pojo.Comment;
import java.util.List;
/**
* @Author <NAME>
* @Date 2020/9/13 18:53
* @Version 1.0
* Comment(评论)的dao 层
*/
public interface CommentDao{
/**
* 根据电影id的查询指定的comments
* @param movie_id 传入当前页面的movie_id
* @param flag 用于时间排序
* @return 返回类型为Comment的List集合
*/
List<Comment> findCommentsByMovieId(Integer movie_id,Integer flag);
/**
*根据movie_id的查询并处理好的commits评论
* @param movie_id 传入当前页面的movie_id
* @param flag 用于时间排序
* @return 返回类型为Comment的List集合
*/
List<Comment> getComments(Integer movie_id,Integer flag);
/**
* 返回指定的movie_id的评论数量
* @param movie_id
* @return
*/
Integer getCount(Integer movie_id);
/**
* 返回处理好的Comment的size大小
* @param movie_id
* @param flag
* @return
*/
Integer getCountComments(Integer movie_id,Integer flag);
/**
* 添加评论
* @param comments 传入一个comment评论
* @return 成功 返回1,否则返回0
*/
Integer addComments(Comment comments);
/**
* 删除评论
* @param comment_id
* @return
*/
Integer deleteComments(Integer comment_id);
/**
* 通过parent_id获取子comment_id集合
* @param parentId 父id
* @return 返回list集合
*/
List<Comment> getCommentIdByParentsId(Integer parentId);
}
|
ut-osa/syncchar
|
linux-2.6.16-unmod/drivers/usb/storage/jumpshot.c
|
/* Driver for Lexar "Jumpshot" Compact Flash reader
*
* $Id: jumpshot.c,v 1.7 2002/02/25 00:40:13 mdharm Exp $
*
* jumpshot driver v0.1:
*
* First release
*
* Current development and maintenance by:
* (c) 2000 <NAME> (<EMAIL>)
*
* Many thanks to <NAME> for the SanDisk SmartMedia reader driver
* which I used as a template for this driver.
*
* Some bugfixes and scatter-gather code by <NAME>
* (<EMAIL>)
*
* Fix for media change by <NAME> (<EMAIL>)
*
* Developed with the assistance of:
*
* (C) 2002 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* This driver attempts to support the Lexar Jumpshot USB CompactFlash
* reader. Like many other USB CompactFlash readers, the Jumpshot contains
* a USB-to-ATA chip.
*
* This driver supports reading and writing. If you're truly paranoid,
* however, you can force the driver into a write-protected state by setting
* the WP enable bits in jumpshot_handle_mode_sense. See the comments
* in that routine.
*/
#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include "usb.h"
#include "transport.h"
#include "protocol.h"
#include "debug.h"
#include "jumpshot.h"
static inline int jumpshot_bulk_read(struct us_data *us,
unsigned char *data,
unsigned int len)
{
if (len == 0)
return USB_STOR_XFER_GOOD;
US_DEBUGP("jumpshot_bulk_read: len = %d\n", len);
return usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
data, len, NULL);
}
static inline int jumpshot_bulk_write(struct us_data *us,
unsigned char *data,
unsigned int len)
{
if (len == 0)
return USB_STOR_XFER_GOOD;
US_DEBUGP("jumpshot_bulk_write: len = %d\n", len);
return usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
data, len, NULL);
}
static int jumpshot_get_status(struct us_data *us)
{
int rc;
if (!us)
return USB_STOR_TRANSPORT_ERROR;
// send the setup
rc = usb_stor_ctrl_transfer(us, us->recv_ctrl_pipe,
0, 0xA0, 0, 7, us->iobuf, 1);
if (rc != USB_STOR_XFER_GOOD)
return USB_STOR_TRANSPORT_ERROR;
if (us->iobuf[0] != 0x50) {
US_DEBUGP("jumpshot_get_status: 0x%2x\n",
us->iobuf[0]);
return USB_STOR_TRANSPORT_ERROR;
}
return USB_STOR_TRANSPORT_GOOD;
}
static int jumpshot_read_data(struct us_data *us,
struct jumpshot_info *info,
u32 sector,
u32 sectors)
{
unsigned char *command = us->iobuf;
unsigned char *buffer;
unsigned char thistime;
unsigned int totallen, alloclen;
int len, result;
unsigned int sg_idx = 0, sg_offset = 0;
// we're working in LBA mode. according to the ATA spec,
// we can support up to 28-bit addressing. I don't know if Jumpshot
// supports beyond 24-bit addressing. It's kind of hard to test
// since it requires > 8GB CF card.
if (sector > 0x0FFFFFFF)
return USB_STOR_TRANSPORT_ERROR;
totallen = sectors * info->ssize;
// Since we don't read more than 64 KB at a time, we have to create
// a bounce buffer and move the data a piece at a time between the
// bounce buffer and the actual transfer buffer.
alloclen = min(totallen, 65536u);
buffer = kmalloc(alloclen, GFP_NOIO);
if (buffer == NULL)
return USB_STOR_TRANSPORT_ERROR;
do {
// loop, never allocate or transfer more than 64k at once
// (min(128k, 255*info->ssize) is the real limit)
len = min(totallen, alloclen);
thistime = (len / info->ssize) & 0xff;
command[0] = 0;
command[1] = thistime;
command[2] = sector & 0xFF;
command[3] = (sector >> 8) & 0xFF;
command[4] = (sector >> 16) & 0xFF;
command[5] = 0xE0 | ((sector >> 24) & 0x0F);
command[6] = 0x20;
// send the setup + command
result = usb_stor_ctrl_transfer(us, us->send_ctrl_pipe,
0, 0x20, 0, 1, command, 7);
if (result != USB_STOR_XFER_GOOD)
goto leave;
// read the result
result = jumpshot_bulk_read(us, buffer, len);
if (result != USB_STOR_XFER_GOOD)
goto leave;
US_DEBUGP("jumpshot_read_data: %d bytes\n", len);
// Store the data in the transfer buffer
usb_stor_access_xfer_buf(buffer, len, us->srb,
&sg_idx, &sg_offset, TO_XFER_BUF);
sector += thistime;
totallen -= len;
} while (totallen > 0);
kfree(buffer);
return USB_STOR_TRANSPORT_GOOD;
leave:
kfree(buffer);
return USB_STOR_TRANSPORT_ERROR;
}
static int jumpshot_write_data(struct us_data *us,
struct jumpshot_info *info,
u32 sector,
u32 sectors)
{
unsigned char *command = us->iobuf;
unsigned char *buffer;
unsigned char thistime;
unsigned int totallen, alloclen;
int len, result, waitcount;
unsigned int sg_idx = 0, sg_offset = 0;
// we're working in LBA mode. according to the ATA spec,
// we can support up to 28-bit addressing. I don't know if Jumpshot
// supports beyond 24-bit addressing. It's kind of hard to test
// since it requires > 8GB CF card.
//
if (sector > 0x0FFFFFFF)
return USB_STOR_TRANSPORT_ERROR;
totallen = sectors * info->ssize;
// Since we don't write more than 64 KB at a time, we have to create
// a bounce buffer and move the data a piece at a time between the
// bounce buffer and the actual transfer buffer.
alloclen = min(totallen, 65536u);
buffer = kmalloc(alloclen, GFP_NOIO);
if (buffer == NULL)
return USB_STOR_TRANSPORT_ERROR;
do {
// loop, never allocate or transfer more than 64k at once
// (min(128k, 255*info->ssize) is the real limit)
len = min(totallen, alloclen);
thistime = (len / info->ssize) & 0xff;
// Get the data from the transfer buffer
usb_stor_access_xfer_buf(buffer, len, us->srb,
&sg_idx, &sg_offset, FROM_XFER_BUF);
command[0] = 0;
command[1] = thistime;
command[2] = sector & 0xFF;
command[3] = (sector >> 8) & 0xFF;
command[4] = (sector >> 16) & 0xFF;
command[5] = 0xE0 | ((sector >> 24) & 0x0F);
command[6] = 0x30;
// send the setup + command
result = usb_stor_ctrl_transfer(us, us->send_ctrl_pipe,
0, 0x20, 0, 1, command, 7);
if (result != USB_STOR_XFER_GOOD)
goto leave;
// send the data
result = jumpshot_bulk_write(us, buffer, len);
if (result != USB_STOR_XFER_GOOD)
goto leave;
// read the result. apparently the bulk write can complete
// before the jumpshot drive is finished writing. so we loop
// here until we get a good return code
waitcount = 0;
do {
result = jumpshot_get_status(us);
if (result != USB_STOR_TRANSPORT_GOOD) {
// I have not experimented to find the smallest value.
//
msleep(50);
}
} while ((result != USB_STOR_TRANSPORT_GOOD) && (waitcount < 10));
if (result != USB_STOR_TRANSPORT_GOOD)
US_DEBUGP("jumpshot_write_data: Gah! Waitcount = 10. Bad write!?\n");
sector += thistime;
totallen -= len;
} while (totallen > 0);
kfree(buffer);
return result;
leave:
kfree(buffer);
return USB_STOR_TRANSPORT_ERROR;
}
static int jumpshot_id_device(struct us_data *us,
struct jumpshot_info *info)
{
unsigned char *command = us->iobuf;
unsigned char *reply;
int rc;
if (!us || !info)
return USB_STOR_TRANSPORT_ERROR;
command[0] = 0xE0;
command[1] = 0xEC;
reply = kmalloc(512, GFP_NOIO);
if (!reply)
return USB_STOR_TRANSPORT_ERROR;
// send the setup
rc = usb_stor_ctrl_transfer(us, us->send_ctrl_pipe,
0, 0x20, 0, 6, command, 2);
if (rc != USB_STOR_XFER_GOOD) {
US_DEBUGP("jumpshot_id_device: Gah! "
"send_control for read_capacity failed\n");
rc = USB_STOR_TRANSPORT_ERROR;
goto leave;
}
// read the reply
rc = jumpshot_bulk_read(us, reply, 512);
if (rc != USB_STOR_XFER_GOOD) {
rc = USB_STOR_TRANSPORT_ERROR;
goto leave;
}
info->sectors = ((u32)(reply[117]) << 24) |
((u32)(reply[116]) << 16) |
((u32)(reply[115]) << 8) |
((u32)(reply[114]) );
rc = USB_STOR_TRANSPORT_GOOD;
leave:
kfree(reply);
return rc;
}
static int jumpshot_handle_mode_sense(struct us_data *us,
struct scsi_cmnd * srb,
int sense_6)
{
static unsigned char rw_err_page[12] = {
0x1, 0xA, 0x21, 1, 0, 0, 0, 0, 1, 0, 0, 0
};
static unsigned char cache_page[12] = {
0x8, 0xA, 0x1, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
static unsigned char rbac_page[12] = {
0x1B, 0xA, 0, 0x81, 0, 0, 0, 0, 0, 0, 0, 0
};
static unsigned char timer_page[8] = {
0x1C, 0x6, 0, 0, 0, 0
};
unsigned char pc, page_code;
unsigned int i = 0;
struct jumpshot_info *info = (struct jumpshot_info *) (us->extra);
unsigned char *ptr = us->iobuf;
pc = srb->cmnd[2] >> 6;
page_code = srb->cmnd[2] & 0x3F;
switch (pc) {
case 0x0:
US_DEBUGP("jumpshot_handle_mode_sense: Current values\n");
break;
case 0x1:
US_DEBUGP("jumpshot_handle_mode_sense: Changeable values\n");
break;
case 0x2:
US_DEBUGP("jumpshot_handle_mode_sense: Default values\n");
break;
case 0x3:
US_DEBUGP("jumpshot_handle_mode_sense: Saves values\n");
break;
}
memset(ptr, 0, 8);
if (sense_6) {
ptr[2] = 0x00; // WP enable: 0x80
i = 4;
} else {
ptr[3] = 0x00; // WP enable: 0x80
i = 8;
}
switch (page_code) {
case 0x0:
// vendor-specific mode
info->sense_key = 0x05;
info->sense_asc = 0x24;
info->sense_ascq = 0x00;
return USB_STOR_TRANSPORT_FAILED;
case 0x1:
memcpy(ptr + i, rw_err_page, sizeof(rw_err_page));
i += sizeof(rw_err_page);
break;
case 0x8:
memcpy(ptr + i, cache_page, sizeof(cache_page));
i += sizeof(cache_page);
break;
case 0x1B:
memcpy(ptr + i, rbac_page, sizeof(rbac_page));
i += sizeof(rbac_page);
break;
case 0x1C:
memcpy(ptr + i, timer_page, sizeof(timer_page));
i += sizeof(timer_page);
break;
case 0x3F:
memcpy(ptr + i, timer_page, sizeof(timer_page));
i += sizeof(timer_page);
memcpy(ptr + i, rbac_page, sizeof(rbac_page));
i += sizeof(rbac_page);
memcpy(ptr + i, cache_page, sizeof(cache_page));
i += sizeof(cache_page);
memcpy(ptr + i, rw_err_page, sizeof(rw_err_page));
i += sizeof(rw_err_page);
break;
}
if (sense_6)
ptr[0] = i - 1;
else
((__be16 *) ptr)[0] = cpu_to_be16(i - 2);
usb_stor_set_xfer_buf(ptr, i, srb);
return USB_STOR_TRANSPORT_GOOD;
}
static void jumpshot_info_destructor(void *extra)
{
// this routine is a placeholder...
// currently, we don't allocate any extra blocks so we're okay
}
// Transport for the Lexar 'Jumpshot'
//
int jumpshot_transport(struct scsi_cmnd * srb, struct us_data *us)
{
struct jumpshot_info *info;
int rc;
unsigned long block, blocks;
unsigned char *ptr = us->iobuf;
static unsigned char inquiry_response[8] = {
0x00, 0x80, 0x00, 0x01, 0x1F, 0x00, 0x00, 0x00
};
if (!us->extra) {
us->extra = kmalloc(sizeof(struct jumpshot_info), GFP_NOIO);
if (!us->extra) {
US_DEBUGP("jumpshot_transport: Gah! Can't allocate storage for jumpshot info struct!\n");
return USB_STOR_TRANSPORT_ERROR;
}
memset(us->extra, 0, sizeof(struct jumpshot_info));
us->extra_destructor = jumpshot_info_destructor;
}
info = (struct jumpshot_info *) (us->extra);
if (srb->cmnd[0] == INQUIRY) {
US_DEBUGP("jumpshot_transport: INQUIRY. Returning bogus response.\n");
memcpy(ptr, inquiry_response, sizeof(inquiry_response));
fill_inquiry_response(us, ptr, 36);
return USB_STOR_TRANSPORT_GOOD;
}
if (srb->cmnd[0] == READ_CAPACITY) {
info->ssize = 0x200; // hard coded 512 byte sectors as per ATA spec
rc = jumpshot_get_status(us);
if (rc != USB_STOR_TRANSPORT_GOOD)
return rc;
rc = jumpshot_id_device(us, info);
if (rc != USB_STOR_TRANSPORT_GOOD)
return rc;
US_DEBUGP("jumpshot_transport: READ_CAPACITY: %ld sectors, %ld bytes per sector\n",
info->sectors, info->ssize);
// build the reply
//
((__be32 *) ptr)[0] = cpu_to_be32(info->sectors - 1);
((__be32 *) ptr)[1] = cpu_to_be32(info->ssize);
usb_stor_set_xfer_buf(ptr, 8, srb);
return USB_STOR_TRANSPORT_GOOD;
}
if (srb->cmnd[0] == MODE_SELECT_10) {
US_DEBUGP("jumpshot_transport: Gah! MODE_SELECT_10.\n");
return USB_STOR_TRANSPORT_ERROR;
}
if (srb->cmnd[0] == READ_10) {
block = ((u32)(srb->cmnd[2]) << 24) | ((u32)(srb->cmnd[3]) << 16) |
((u32)(srb->cmnd[4]) << 8) | ((u32)(srb->cmnd[5]));
blocks = ((u32)(srb->cmnd[7]) << 8) | ((u32)(srb->cmnd[8]));
US_DEBUGP("jumpshot_transport: READ_10: read block 0x%04lx count %ld\n", block, blocks);
return jumpshot_read_data(us, info, block, blocks);
}
if (srb->cmnd[0] == READ_12) {
// I don't think we'll ever see a READ_12 but support it anyway...
//
block = ((u32)(srb->cmnd[2]) << 24) | ((u32)(srb->cmnd[3]) << 16) |
((u32)(srb->cmnd[4]) << 8) | ((u32)(srb->cmnd[5]));
blocks = ((u32)(srb->cmnd[6]) << 24) | ((u32)(srb->cmnd[7]) << 16) |
((u32)(srb->cmnd[8]) << 8) | ((u32)(srb->cmnd[9]));
US_DEBUGP("jumpshot_transport: READ_12: read block 0x%04lx count %ld\n", block, blocks);
return jumpshot_read_data(us, info, block, blocks);
}
if (srb->cmnd[0] == WRITE_10) {
block = ((u32)(srb->cmnd[2]) << 24) | ((u32)(srb->cmnd[3]) << 16) |
((u32)(srb->cmnd[4]) << 8) | ((u32)(srb->cmnd[5]));
blocks = ((u32)(srb->cmnd[7]) << 8) | ((u32)(srb->cmnd[8]));
US_DEBUGP("jumpshot_transport: WRITE_10: write block 0x%04lx count %ld\n", block, blocks);
return jumpshot_write_data(us, info, block, blocks);
}
if (srb->cmnd[0] == WRITE_12) {
// I don't think we'll ever see a WRITE_12 but support it anyway...
//
block = ((u32)(srb->cmnd[2]) << 24) | ((u32)(srb->cmnd[3]) << 16) |
((u32)(srb->cmnd[4]) << 8) | ((u32)(srb->cmnd[5]));
blocks = ((u32)(srb->cmnd[6]) << 24) | ((u32)(srb->cmnd[7]) << 16) |
((u32)(srb->cmnd[8]) << 8) | ((u32)(srb->cmnd[9]));
US_DEBUGP("jumpshot_transport: WRITE_12: write block 0x%04lx count %ld\n", block, blocks);
return jumpshot_write_data(us, info, block, blocks);
}
if (srb->cmnd[0] == TEST_UNIT_READY) {
US_DEBUGP("jumpshot_transport: TEST_UNIT_READY.\n");
return jumpshot_get_status(us);
}
if (srb->cmnd[0] == REQUEST_SENSE) {
US_DEBUGP("jumpshot_transport: REQUEST_SENSE.\n");
memset(ptr, 0, 18);
ptr[0] = 0xF0;
ptr[2] = info->sense_key;
ptr[7] = 11;
ptr[12] = info->sense_asc;
ptr[13] = info->sense_ascq;
usb_stor_set_xfer_buf(ptr, 18, srb);
return USB_STOR_TRANSPORT_GOOD;
}
if (srb->cmnd[0] == MODE_SENSE) {
US_DEBUGP("jumpshot_transport: MODE_SENSE_6 detected\n");
return jumpshot_handle_mode_sense(us, srb, 1);
}
if (srb->cmnd[0] == MODE_SENSE_10) {
US_DEBUGP("jumpshot_transport: MODE_SENSE_10 detected\n");
return jumpshot_handle_mode_sense(us, srb, 0);
}
if (srb->cmnd[0] == ALLOW_MEDIUM_REMOVAL) {
// sure. whatever. not like we can stop the user from popping
// the media out of the device (no locking doors, etc)
//
return USB_STOR_TRANSPORT_GOOD;
}
if (srb->cmnd[0] == START_STOP) {
/* this is used by sd.c'check_scsidisk_media_change to detect
media change */
US_DEBUGP("jumpshot_transport: START_STOP.\n");
/* the first jumpshot_id_device after a media change returns
an error (determined experimentally) */
rc = jumpshot_id_device(us, info);
if (rc == USB_STOR_TRANSPORT_GOOD) {
info->sense_key = NO_SENSE;
srb->result = SUCCESS;
} else {
info->sense_key = UNIT_ATTENTION;
srb->result = SAM_STAT_CHECK_CONDITION;
}
return rc;
}
US_DEBUGP("jumpshot_transport: Gah! Unknown command: %d (0x%x)\n",
srb->cmnd[0], srb->cmnd[0]);
info->sense_key = 0x05;
info->sense_asc = 0x20;
info->sense_ascq = 0x00;
return USB_STOR_TRANSPORT_FAILED;
}
|
chenhaigang888/CHGAdapter
|
CHGAdapter/Sample/TableView/CHGSimpleTableViewAdapter用法/view/UITableViewCell/AddressNoSelectTableViewCell.h
|
<filename>CHGAdapter/Sample/TableView/CHGSimpleTableViewAdapter用法/view/UITableViewCell/AddressNoSelectTableViewCell.h
//
// AddressNoSelectTableViewCell.h
// CHGAdapter
//
// Created by <NAME> on 2018/7/28.
// Copyright © 2018年 <NAME>. All rights reserved.
//
#import "CHGTableViewCell.h"
@interface AddressNoSelectTableViewCell : CHGTableViewCell
@end
|
tobice/payola-viz
|
src/app/model/rdf/sparql/visualization/extractor/ConceptCountExtractor.scala
|
package model.rdf.sparql.visualization.extractor
import model.rdf.extractor.QueryExecutionResultExtractor
import model.rdf.sparql.visualization.query.ConceptCountQuery
import org.apache.jena.query.QueryExecution
class ConceptCountExtractor extends QueryExecutionResultExtractor[ConceptCountQuery, Int] {
def extract(input: QueryExecution): Option[Int] = {
try {
val resultSet = input.execSelect()
Some(resultSet.nextSolution().getLiteral("count").getInt)
} catch {
case e: org.apache.jena.sparql.engine.http.QueryExceptionHTTP => {
None
}
}
}
}
|
DanylZhang/IdeaWorkspace
|
spiders/src/main/java/com/danyl/spiders/jooq/gen/proxy/tables/Proxy.java
|
/*
* This file is generated by jOOQ.
*/
package com.danyl.spiders.jooq.gen.proxy.tables;
import com.danyl.spiders.jooq.gen.proxy.Indexes;
import com.danyl.spiders.jooq.gen.proxy.Keys;
import com.danyl.spiders.jooq.gen.proxy.Public;
import com.danyl.spiders.jooq.gen.proxy.tables.records.ProxyRecord;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Index;
import org.jooq.Name;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.10.7"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Proxy extends TableImpl<ProxyRecord> {
private static final long serialVersionUID = -1389319410;
/**
* The reference instance of <code>PUBLIC.PROXY</code>
*/
public static final Proxy PROXY = new Proxy();
/**
* The class holding records for this type
*/
@Override
public Class<ProxyRecord> getRecordType() {
return ProxyRecord.class;
}
/**
* The column <code>PUBLIC.PROXY.IP</code>. 代理IP
*/
public final TableField<ProxyRecord, String> IP = createField("IP", org.jooq.impl.SQLDataType.VARCHAR(20).nullable(false).defaultValue(org.jooq.impl.DSL.field("''", org.jooq.impl.SQLDataType.VARCHAR)), this, "代理IP");
/**
* The column <code>PUBLIC.PROXY.PORT</code>. 端口
*/
public final TableField<ProxyRecord, Integer> PORT = createField("PORT", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaultValue(org.jooq.impl.DSL.field("0", org.jooq.impl.SQLDataType.INTEGER)), this, "端口");
/**
* The column <code>PUBLIC.PROXY.IS_VALID</code>. 是否可用
*/
public final TableField<ProxyRecord, Boolean> IS_VALID = createField("IS_VALID", org.jooq.impl.SQLDataType.BOOLEAN.nullable(false).defaultValue(org.jooq.impl.DSL.field("FALSE", org.jooq.impl.SQLDataType.BOOLEAN)), this, "是否可用");
/**
* The column <code>PUBLIC.PROXY.ANONYMITY</code>. 匿名性
*/
public final TableField<ProxyRecord, String> ANONYMITY = createField("ANONYMITY", org.jooq.impl.SQLDataType.VARCHAR(32).defaultValue(org.jooq.impl.DSL.field("''", org.jooq.impl.SQLDataType.VARCHAR)), this, "匿名性");
/**
* The column <code>PUBLIC.PROXY.SPEED</code>. 响应耗时
*/
public final TableField<ProxyRecord, Integer> SPEED = createField("SPEED", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaultValue(org.jooq.impl.DSL.field("15000", org.jooq.impl.SQLDataType.INTEGER)), this, "响应耗时");
/**
* The column <code>PUBLIC.PROXY.PROTOCOL</code>. 支持协议
*/
public final TableField<ProxyRecord, String> PROTOCOL = createField("PROTOCOL", org.jooq.impl.SQLDataType.VARCHAR(10).defaultValue(org.jooq.impl.DSL.field("'http'", org.jooq.impl.SQLDataType.VARCHAR)), this, "支持协议");
/**
* The column <code>PUBLIC.PROXY.CHECKED_TIME</code>. 上次校验
*/
public final TableField<ProxyRecord, LocalDateTime> CHECKED_TIME = createField("CHECKED_TIME", org.jooq.impl.SQLDataType.LOCALDATETIME.nullable(false).defaultValue(org.jooq.impl.DSL.field("CURRENT_TIMESTAMP()", org.jooq.impl.SQLDataType.LOCALDATETIME)), this, "上次校验");
/**
* The column <code>PUBLIC.PROXY.CREATED_TIME</code>. 入库时间
*/
public final TableField<ProxyRecord, LocalDateTime> CREATED_TIME = createField("CREATED_TIME", org.jooq.impl.SQLDataType.LOCALDATETIME.nullable(false).defaultValue(org.jooq.impl.DSL.field("CURRENT_TIMESTAMP()", org.jooq.impl.SQLDataType.LOCALDATETIME)), this, "入库时间");
/**
* The column <code>PUBLIC.PROXY.SOURCE</code>. 来源
*/
public final TableField<ProxyRecord, String> SOURCE = createField("SOURCE", org.jooq.impl.SQLDataType.VARCHAR(64).defaultValue(org.jooq.impl.DSL.field("''", org.jooq.impl.SQLDataType.VARCHAR)), this, "来源");
/**
* The column <code>PUBLIC.PROXY.COUNTRY</code>. 国家
*/
public final TableField<ProxyRecord, String> COUNTRY = createField("COUNTRY", org.jooq.impl.SQLDataType.VARCHAR(128).defaultValue(org.jooq.impl.DSL.field("''", org.jooq.impl.SQLDataType.VARCHAR)), this, "国家");
/**
* The column <code>PUBLIC.PROXY.CITY</code>. 省市
*/
public final TableField<ProxyRecord, String> CITY = createField("CITY", org.jooq.impl.SQLDataType.VARCHAR(32).defaultValue(org.jooq.impl.DSL.field("''", org.jooq.impl.SQLDataType.VARCHAR)), this, "省市");
/**
* The column <code>PUBLIC.PROXY.REGION</code>. 县区
*/
public final TableField<ProxyRecord, String> REGION = createField("REGION", org.jooq.impl.SQLDataType.VARCHAR(32).defaultValue(org.jooq.impl.DSL.field("''", org.jooq.impl.SQLDataType.VARCHAR)), this, "县区");
/**
* The column <code>PUBLIC.PROXY.ISP</code>. 运营商
*/
public final TableField<ProxyRecord, String> ISP = createField("ISP", org.jooq.impl.SQLDataType.VARCHAR(256).defaultValue(org.jooq.impl.DSL.field("''", org.jooq.impl.SQLDataType.VARCHAR)), this, "运营商");
/**
* Create a <code>PUBLIC.PROXY</code> table reference
*/
public Proxy() {
this(DSL.name("PROXY"), null);
}
/**
* Create an aliased <code>PUBLIC.PROXY</code> table reference
*/
public Proxy(String alias) {
this(DSL.name(alias), PROXY);
}
/**
* Create an aliased <code>PUBLIC.PROXY</code> table reference
*/
public Proxy(Name alias) {
this(alias, PROXY);
}
private Proxy(Name alias, Table<ProxyRecord> aliased) {
this(alias, aliased, null);
}
private Proxy(Name alias, Table<ProxyRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public Schema getSchema() {
return Public.PUBLIC;
}
/**
* {@inheritDoc}
*/
@Override
public List<Index> getIndexes() {
return Arrays.<Index>asList(Indexes.PRIMARY_KEY_4);
}
/**
* {@inheritDoc}
*/
@Override
public UniqueKey<ProxyRecord> getPrimaryKey() {
return Keys.CONSTRAINT_48;
}
/**
* {@inheritDoc}
*/
@Override
public List<UniqueKey<ProxyRecord>> getKeys() {
return Arrays.<UniqueKey<ProxyRecord>>asList(Keys.CONSTRAINT_48);
}
/**
* {@inheritDoc}
*/
@Override
public Proxy as(String alias) {
return new Proxy(DSL.name(alias), this);
}
/**
* {@inheritDoc}
*/
@Override
public Proxy as(Name alias) {
return new Proxy(alias, this);
}
/**
* Rename this table
*/
@Override
public Proxy rename(String name) {
return new Proxy(DSL.name(name), null);
}
/**
* Rename this table
*/
@Override
public Proxy rename(Name name) {
return new Proxy(name, null);
}
}
|
yohcop/google-depan
|
DepanEdge/prod/src/com/google/devtools/depan/edges/matchers/GraphEdgeMatchers.java
|
<filename>DepanEdge/prod/src/com/google/devtools/depan/edges/matchers/GraphEdgeMatchers.java
/**
*
*/
package com.google.devtools.depan.edges.matchers;
import com.google.devtools.depan.graph.api.Relation;
import com.google.devtools.depan.graph.api.RelationSet;
import com.google.devtools.depan.model.GraphEdgeMatcher;
/**
* @author <NAME>
*
*/
public class GraphEdgeMatchers {
private GraphEdgeMatchers() {
// Prevent instantiation
}
// Only need one
public static final GraphEdgeMatcher EMPTY = new GraphEdgeMatcher();
// Only need one
public static final GraphEdgeMatcher FORWARD = new GraphEdgeMatcher() {
@Override
public boolean relationForward(Relation relation) {
return true;
}
};
public static GraphEdgeMatcher createForwardEdgeMatcher(
final RelationSet relationSet) {
return new ForwardEdgeMatcher(relationSet);
}
public static GraphEdgeMatcher createBinaryEdgeMatcher(
final RelationSet forward, final RelationSet reverse) {
return new BinaryEdgeMatcher(forward, reverse);
}
}
|
getmrinal/Algo-Dump
|
stack.cpp
|
<filename>stack.cpp<gh_stars>0
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node*next;
Node(int data){
this->data = data;
this->next = NULL;
}
};
Node * Push(Node*head=NULL){
cout<<"enter element in stack";
int data;
cin>>data;
if(data ==-1){
return head;
}else if(head == NULL){
head = new Node(data);
return Push(head);
}else{
Node *node = new Node(data);
node->next = head;
head = node;
return Push(head);
}
}
void printStack(Node*head){
Node*temp=head;
while(temp!=NULL){
cout<<temp->data<<"->";
temp = temp->next;
}
}
Node *pop(Node*head){
if(head==NULL){
return head;
}else{
head = head->next;
return head;
}
}
int main(){
Node *head= new Node(7);
//Node*temp = head;
head = Push(head);
printStack(head);
cout<<'\n';
head = pop(head);
printStack(head);
}
|
HossamBadawy/miniProject
|
node_modules/decree/tests/01.test.js
|
var should = require('should'),
assert = require('assert'),
decree = require('../');
describe('judge returns args', function() {
var decs = [{
type: 'string'
}, {
type: 'number'
}, {
type: 'hash'
}];
var judge = decree(decs);
describe('with legal arguments', function() {
var args = ['hello', 1, {
a: 'b'
}];
it('should be ok', function() {
args = judge(args);
args[0].should.be.a.String;
args[1].should.be.a.Number;
args[2].should.be.an.Object;
});
});
describe('with illegal arguments', function() {
var args = [1, 1, {
a: 'b'
}];
it('should throw an error', function() {
judge.bind(null, args).should.throwError();
});
});
});
describe('judge with a callback', function() {
var decs = [{
type: 'string'
}, {
type: 'number'
}, {
type: 'hash'
}];
var judge = decree(decs);
describe('with legal arguments', function() {
var args = ['hello', 1, {
a: 'b'
}];
it('should be ok', function() {
var called = false;
args = judge(args, function(a1, a2, a3) {
called = true;
a1.should.be.a.String;
a2.should.be.a.Number;
a3.should.be.an.Object;
});
called.should.be.true;
});
});
describe('with illegal arguments', function() {
var args = [1, 1, {
a: 'b'
}];
it('should throw an error', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
}).should.throwError();
called.should.be.false;
});
});
});
describe('judge with an error handling callback', function() {
var decs = [{
type: 'string'
}, {
type: 'number'
}, {
type: 'hash'
}];
var judge = decree(decs);
describe('with legal arguments', function() {
var args = ['hello', 1, {
a: 'b'
}];
it('should be ok', function() {
var cbCalled = false,
errCbCalled = false;
args = judge(args, function(a1, a2, a3) {
cbCalled = true;
a1.should.be.a.String;
a2.should.be.a.Number;
a3.should.be.an.Object;
}, function(err) {
errCbCalled = true;
});
cbCalled.should.be.true;
errCbCalled.should.be.false;
});
});
describe('with illegal arguments', function() {
var args = [1, 1, {
a: 'b'
}];
it('should call handler with an error', function() {
var cbCalled = false,
errCbCalled = false;
judge(args, function(a1, a2, a3) {
cbCalled = true;
}, function(err) {
errCbCalled = true;
err.should.be.an.Error;
});
cbCalled.should.be.false;
errCbCalled.should.be.true;
});
});
});
describe('arguments with default assignments modified by user', function() {
var decs = [{
type: 'hash',
optional: true,
default: {
a: 'b'
}
}];
var judge = decree(decs);
it('should should not affect default value', function() {
var called = false;
judge([], function(a) {
called = true;
a.should.be.an.Object;
assert(a.a === 'b');
// modify a (should not modify the default value):
a.a = 'c';
assert(a.a === 'c');
});
called.should.be.true;
called = false;
judge([], function(a) {
called = true;
a.should.be.an.Object;
assert(a.a === 'b'); // still 'b'
});
called.should.be.true;
assert(decs[0].default.a === 'b');
});
});
describe('one type per argument', function() {
describe('3 args, none is optional', function() {
var decs = [{
type: 'string'
}, {
type: 'number'
}, {
type: 'hash'
}];
var judge = decree(decs);
describe('function called with legal arguments', function() {
var args = ['hello', 1, {
a: 'b'
}];
it('should be ok', function() {
var called = false;
judge(args, function(a1, a2, a3) {
called = true;
a1.should.be.a.String;
a2.should.be.a.Number;
a3.should.be.an.Object;
});
called.should.be.true;
});
});
describe('function called with illegal arguments', function() {
describe('judge returns args', function() {
describe('illegal first argument', function() {
var args = [1, 1, {
a: 'b'
}];
it('should throw an error', function() {
judge.bind(null, args).should.throwError();
});
});
describe('illegal second argument', function() {
var args = ['hello', 'world', {
a: 'b'
}];
it('should throw an error', function() {
judge.bind(null, args).should.throwError();
});
});
describe('illegal third argument', function() {
var args = ['hello', 1, 1];
it('should throw an error', function() {
judge.bind(null, args).should.throwError();
});
});
describe('missing first argument', function() {
var args = [1, {
a: 'b'
}];
it('should throw an error', function() {
judge.bind(null, args).should.throwError();
});
});
describe('missing second argument', function() {
var args = ['hello', {
a: 'b'
}];
it('should throw an error', function() {
judge.bind(null, args).should.throwError();
});
});
describe('missing third argument', function() {
var args = ['hello', 1];
it('should throw an error', function() {
judge.bind(null, args).should.throwError();
});
});
describe('missing all arguments', function() {
var args = [];
it('should throw an error', function() {
judge.bind(null, args).should.throwError();
});
});
});
});
}); // none is optional
describe('3 args, first and third are optional (with defaults)', function() {
var decs = [{
type: 'string',
optional: true,
default: 'hello'
}, {
type: 'number'
}, {
type: 'hash',
optional: true,
default: {
a: 'b'
}
}];
var judge = decree(decs);
describe('function called with legal arguments', function() {
describe('all arguments provided', function() {
var args = ['hi', 10, {
a: 'c'
}];
it('should be ok', function() {
var called = false;
judge(args, function(a1, a2, a3) {
called = true;
assert(a1 === 'hi');
assert(a2 === 10);
a3.should.be.an.Object;
assert(a3.a === 'c');
});
called.should.be.true;
});
});
describe('first argument missing', function() {
var args = [10, {
a: 'c'
}];
it('should be ok', function() {
var called = false;
judge(args, function(a1, a2, a3) {
called = true;
assert(a1 === 'hello');
assert(a2 === 10);
a3.should.be.an.Object;
assert(a3.a === 'c');
});
called.should.be.true;
});
});
describe('third argument missing', function() {
var args = ['hi', 1];
it('should be ok', function() {
var called = false;
judge(args, function(a1, a2, a3) {
called = true;
assert(a1 === 'hi');
assert(a2 === 1);
a3.should.be.an.Object;
assert(a3.a === 'b');
});
called.should.be.true;
});
});
describe('first and third arguments missing', function() {
var args = [1];
it('should be ok', function() {
var called = false;
judge(args, function(a1, a2, a3) {
called = true;
assert(a1 === 'hello');
assert(a2 === 1);
a3.should.be.an.Object;
assert(a3.a === 'b');
});
called.should.be.true;
});
});
});
describe('function called with illegal arguments', function() {
describe('first argument illegal', function() {
var args = [1, 1, {
a: 'c'
}];
it('should throw an error', function() {
judge.bind(null, args).should.throwError();
});
});
describe('third argument illegal', function() {
var args = ['hi', 1, 6];
it('should throw an error', function() {
judge.bind(null, args).should.throwError();
});
});
describe('second argument missing', function() {
var args = ['hi', {
a: 'c'
}];
it('should throw an error', function() {
judge.bind(null, args).should.throwError();
});
});
});
}); // first and third are optional (with defaults)
describe('3 args, first and third are optional (without defaults)', function() {
var decs = [{
type: 'string',
optional: true
}, {
type: 'number'
}, {
type: 'hash',
optional: true
}];
var judge = decree(decs);
describe('function called with legal arguments', function() {
describe('all arguments provided', function() {
var args = ['hi', 10, {
a: 'c'
}];
it('should be ok', function() {
var called = false;
judge(args, function(a1, a2, a3) {
called = true;
assert(a1 === 'hi');
assert(a2 === 10);
a3.should.be.an.Object;
assert(a3.a === 'c');
});
called.should.be.true;
});
});
describe('first argument missing', function() {
var args = [10, {
a: 'c'
}];
it('should be ok', function() {
var called = false;
judge(args, function(a1, a2, a3) {
called = true;
assert(a1 === undefined);
assert(a2 === 10);
a3.should.be.an.Object;
assert(a3.a === 'c');
});
called.should.be.true;
});
});
describe('third argument missing', function() {
var args = ['hi', 1];
it('should be ok', function() {
var called = false;
judge(args, function(a1, a2, a3) {
called = true;
assert(a1 === 'hi');
assert(a2 === 1);
assert(a3 === undefined);
});
called.should.be.true;
});
});
describe('first and third arguments missing', function() {
var args = [1];
it('should be ok', function() {
var called = false;
judge(args, function(a1, a2, a3) {
called = true;
assert(a1 === undefined);
assert(a2 === 1);
assert(a3 === undefined);
});
called.should.be.true;
});
});
});
}); // first and third are optional (without defaults)
}); // one type per argument
describe('multiple types per argument', function() {
describe('3 args, none is optional', function() {
var decs = [{
types: ['string', 'hash']
}, {
types: ['array', 'hash']
}, {
types: ['string', 'function', 'number']
}];
var judge = decree(decs);
describe('function called with legal arguments (1)', function() {
var args = ['hello', [1, 2, 3], 'world'];
it('should be ok', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
a1.should.be.a.String;
a2.should.be.an.Array;
a3.should.be.a.String;
}).should.not.throwError();
called.should.be.true;
});
});
describe('function called with legal arguments (2)', function() {
var args = ['hello', [1, 2, 3],
function() {}
];
it('should be ok', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
a1.should.be.a.String;
a2.should.be.an.Array;
a3.should.be.a.Function;
}).should.not.throwError();
called.should.be.true;
});
});
describe('function called with legal arguments (3)', function() {
var args = ['hello', [1, 2, 3], 1];
it('should be ok', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
a1.should.be.a.String;
a2.should.be.an.Array;
a3.should.be.a.Number;
}).should.not.throwError();
called.should.be.true;
});
});
describe('function called with legal arguments (4)', function() {
var args = [{
a: 'b'
},
[1, 2, 3], 'world'
];
it('should be ok', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
a1.should.be.an.Object;
a2.should.be.an.Array;
a3.should.be.a.String;
}).should.not.throwError();
called.should.be.true;
});
});
describe('function called with legal arguments (5)', function() {
var args = [{
a: 'b'
},
[1, 2, 3],
function() {}
];
it('should be ok', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
a1.should.be.an.Object;
a2.should.be.an.Array;
a3.should.be.a.Function;
}).should.not.throwError();
called.should.be.true;
});
});
describe('function called with legal arguments (6)', function() {
var args = [{
a: 'b'
},
[1, 2, 3], 1
];
it('should be ok', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
a1.should.be.an.Object;
a2.should.be.an.Array;
a3.should.be.a.Number;
}).should.not.throwError();
called.should.be.true;
});
});
describe('function called with legal arguments (7)', function() {
var args = ['hello', {
foo: 'bar'
}, 'world'];
it('should be ok', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
a1.should.be.a.String;
a2.should.be.an.Object;
a3.should.be.a.String;
}).should.not.throwError();
called.should.be.true;
});
});
describe('function called with legal arguments (8)', function() {
var args = ['hello', {
foo: 'bar'
},
function() {}
];
it('should be ok', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
a1.should.be.a.String;
a2.should.be.an.Object;
a3.should.be.a.Function;
}).should.not.throwError();
called.should.be.true;
});
});
describe('function called with legal arguments (9)', function() {
var args = ['hello', {
foo: 'bar'
},
1
];
it('should be ok', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
a1.should.be.a.String;
a2.should.be.an.Object;
a3.should.be.a.Number;
}).should.not.throwError();
called.should.be.true;
});
});
describe('function called with legal arguments (10)', function() {
var args = [{
a: 'b'
}, {
foo: 'bar'
},
'world'
];
it('should be ok', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
a1.should.be.an.Object;
a2.should.be.an.Object;
a3.should.be.a.String;
}).should.not.throwError();
called.should.be.true;
});
});
describe('function called with legal arguments (11)', function() {
var args = [{
a: 'b'
}, {
foo: 'bar'
},
function() {}
];
it('should be ok', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
a1.should.be.an.Object;
a2.should.be.an.Object;
a3.should.be.a.Function;
}).should.not.throwError();
called.should.be.true;
});
});
describe('function called with legal arguments (12)', function() {
var args = [{
a: 'b'
}, {
foo: 'bar'
},
1
];
it('should be ok', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
a1.should.be.an.Object;
a2.should.be.an.Object;
a3.should.be.a.Number;
}).should.not.throwError();
called.should.be.true;
});
});
describe('function called with illegal arguments (1)', function() {
var args = [1, [1, 2, 3], 1];
it('should not be ok', function() {
judge.bind(null, args).should.throwError();
});
});
describe('function called with illegal arguments (2)', function() {
var args = ['hello', 'world',
function() {}
];
it('should not be ok', function() {
judge.bind(null, args).should.throwError();
});
});
describe('function called with illegal arguments (3)', function() {
var args = ['hello', [1, 2, 3],
[1, 2, 3]
];
it('should not be ok', function() {
judge.bind(null, args).should.throwError();
});
});
describe('function called with missing first argument', function() {
var args = [
[1, 2, 3], 'hello'
];
it('should not be ok', function() {
judge.bind(null, args).should.throwError();
});
});
describe('function called with missing second argument', function() {
var args = ['hello', -55];
it('should not be ok', function() {
judge.bind(null, args).should.throwError();
});
});
describe('function called with missing third argument', function() {
var args = ['hello', [1, 2, 3]];
it('should not be ok', function() {
judge.bind(null, args).should.throwError();
});
});
describe('function called with no arguments', function() {
var args = [];
it('should not be ok', function() {
judge.bind(null, args).should.throwError();
});
});
}); //none is optional
describe('3 args, first and second are optional (with defaults)', function() {
var decs = [{
types: ['string', 'hash'],
optional: true,
default: 'hello'
}, {
types: ['array', 'hash'],
optional: true,
default: [0, 9, 8]
}, {
types: ['string', 'function', 'number']
}];
var judge = decree(decs);
describe('function called with legal arguments (1)', function() {
var args = [{
a: 'b'
}, {
a: 'b'
},
0.99
];
it('should be ok', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
a1.should.be.an.Object;
a2.should.be.an.Object;
a3.should.be.a.Number;
}).should.not.throwError();
called.should.be.true;
});
});
describe('function called with legal arguments (2)', function() {
var args = [
[1, 2, 3],
function() {}
];
it('should be ok', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
a1.should.be.a.String;
a2.should.be.an.Array;
a3.should.be.a.Function;
}).should.not.throwError();
called.should.be.true;
});
});
describe('function called with legal arguments (3)', function() {
var args = ['hello', 1];
it('should be ok', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
a1.should.be.a.String;
a2.should.be.an.Array;
a3.should.be.a.Number;
}).should.not.throwError();
called.should.be.true;
});
});
describe('function called with legal arguments (4)', function() {
var args = [1];
it('should be ok', function() {
var called = false;
judge.bind(null, args, function(a1, a2, a3) {
called = true;
a1.should.be.a.String;
a2.should.be.an.Array;
a3.should.be.a.Number;
}).should.not.throwError();
called.should.be.true;
});
});
describe('function called with illegal arguments', function() {
describe('ambiguity between first and second arguments', function() {
var args = [{
a: 'b'
},
1
];
it('should not be ok', function() {
judge.bind(null, args).should.throwError();
});
});
});
}); //first and third are optional (with defaults)
}); // multiple types per argument
|
ItsMrTurtle/PythonChris
|
Unit 2 Strings and Tuples/Lesson9.1.py
|
<filename>Unit 2 Strings and Tuples/Lesson9.1.py
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 21 00:21:51 2020
@author: abcdk
"""
#Swaps
long = "hello"
short = "hi"
(short,long) = (long, short)
s = "strong"
w = "weak"
(s,w) = (w,s)
yes = "affirmative"
no = "negative"
(yes,no) = (no,yes)
|
jayanth-karri22/Onsurity-Demo
|
app/components/Header/NavBar.js
|
<reponame>jayanth-karri22/Onsurity-Demo<filename>app/components/Header/NavBar.js
import styled from 'styled-components';
export default styled.div`
flex: 2;
text-align: center;
display: flex;
justify-content: space-between;
align-items: center;
@media (max-width: 768px) {
margin: 5% 0 0 5%;
}
`;
|
Jiezhi/myleetcode
|
src/648-ReplaceWords.py
|
<reponame>Jiezhi/myleetcode
#!/usr/bin/env python
"""
CREATED AT: 2021/10/8
Des:
https://leetcode.com/problems/replace-words/
https://leetcode.com/explore/learn/card/trie/148/practical-application-i/1053/
GITHUB: https://github.com/Jiezhi/myleetcode
Difficulty: Medium
See: 208
Tag: Trie
"""
from typing import List
# See: 208
class Trie:
def __init__(self):
self.root = {}
def insert(self, word):
cur = self.root
for c in word:
if c not in cur:
cur[c] = {}
cur = cur[c]
cur['#'] = True
def get_word_root(self, word):
cur = self.root
ret = ''
for c in word:
if c not in cur:
return word
ret += c
cur = cur[c]
if '#' in cur:
return ret
return word
class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
"""
126 / 126 test cases passed.
Status: Accepted
Runtime: 68 ms
Memory Usage: 28.3 MB
:param dictionary:
:param sentence:
:return:
"""
trie = Trie()
[trie.insert(x) for x in dictionary]
ret = [trie.get_word_root(x) for x in sentence.split()]
return ' '.join(ret)
def test():
assert Solution().replaceWords(
dictionary=["a", "aa", "aaa", "aaaa"],
sentence="a aa a aaaa aaa aaa aaa aaaaaa bbb baba ababa"
) == "a a a a a a a a bbb baba a"
assert Solution().replaceWords(
dictionary=["cat", "bat", "rat"],
sentence="the cattle was rattled by the battery"
) == "the cat was rat by the bat"
if __name__ == '__main__':
test()
|
flipsters/connekt
|
commons/src/main/scala/com/flipkart/connekt/commons/entities/WNSCredential.scala
|
<reponame>flipsters/connekt<gh_stars>1-10
/*
* -╥⌐⌐⌐⌐ -⌐⌐⌐⌐-
* ≡╢░░░░⌐\░░░φ ╓╝░░░░⌐░░░░╪╕
* ╣╬░░` `░░░╢┘ φ▒╣╬╝╜ ░░╢╣Q
* ║╣╬░⌐ ` ╤▒▒▒Å` ║╢╬╣
* ╚╣╬░⌐ ╔▒▒▒▒`«╕ ╢╢╣▒
* ╫╬░░╖ .░ ╙╨╨ ╣╣╬░φ ╓φ░╢╢Å
* ╙╢░░░░⌐"░░░╜ ╙Å░░░░⌐░░░░╝`
* ``˚¬ ⌐ ˚˚⌐´
*
* Copyright © 2016 Flipkart.com
*/
package com.flipkart.connekt.commons.entities
import com.flipkart.connekt.commons.utils.StringUtils
case class WNSCredential(secureId: String, clientSecret: String) {
def isEmpty:Boolean = {
StringUtils.isNullOrEmpty(secureId) && StringUtils.isNullOrEmpty(clientSecret)
}
}
|
guanjilai/FastCAE
|
Code/ModelData/modelDataSingleton.cpp
|
#include "modelDataSingleton.h"
#include "modelDataBase.h"
#include <QString>
#include <assert.h>
#include <QDataStream>
#include <QCryptographicHash>
#include <QDomElement>
#include <QDomDocument>
#include <QDebug>
#include <QFile>
#include <QTextCodec>
namespace ModelData
{
ModelDataSingleton* ModelDataSingleton::_instance = nullptr;
ModelDataSingleton::ModelDataSingleton()
{
}
ModelDataSingleton::~ModelDataSingleton()
{
clear();
}
ModelDataSingleton* ModelDataSingleton::getinstance()
{
if (_instance == nullptr)
{
_instance = new ModelDataSingleton;
}
return _instance;
}
void ModelDataSingleton::appendModel(ModelDataBase* model)
{
_modelList.append(model);
}
int ModelDataSingleton::getModelCount()
{
return _modelList.size();
}
ModelDataBase* ModelDataSingleton::getModelAt(const int index)
{
assert(index >= 0 && index < _modelList.size());
return _modelList.at(index);
}
QString ModelDataSingleton::getMD5()
{
const int n = _modelList.size();
if (n < 1) return "";
// QFile file("test.dat");
// if (!file.open(QIODevice::WriteOnly))
// {
// printf("can't open file for write\n");
// exit(1);
// }
QDataStream stream/*(&file)*/;
for (int i = 0; i < _modelList.size(); ++i)
{
_modelList[i]->dataToStream(&stream);
}
char* s;
// QString a;
stream >> s;
// QByteArray string = s;
// QCryptographicHash *hash = new QCryptographicHash(QCryptographicHash::Md5);
// hash->addData(string);
// QByteArray string1 = hash->result();
// QTextCodec *codec = QTextCodec::codecForName("KOI8-R");
// QString string2 = codec->toUnicode(string1);
//
// qDebug() << "baisuishankuangquanshui" << sizeof(stream);
// file.close();
QString md5 = QCryptographicHash::hash(s, QCryptographicHash::Md5);
//return md5;
return md5;
}
ModelDataBase* ModelDataSingleton::getModelByID(const int id)
{
const int n = _modelList.size();
for (int i = 0; i < n; ++i)
{
ModelDataBase* m = _modelList.at(i);
if (m->getID() == id)
return m;
}
return nullptr;
}
ModelData::ModelDataBase* ModelDataSingleton::getModelByName(QString name)
{
for (auto m : _modelList)
{
if (m->getName() == name)
return m;
}
return nullptr;
}
QDomElement& ModelDataSingleton::writeToProjectFile(QDomDocument* doc, QDomElement* parent)
{
QDomElement modelElement = doc->createElement("ModelData");
const int nmodel = _modelList.size();
for (int i = 0; i < nmodel; ++i)
{
ModelDataBase* model = _modelList.at(i);
#ifdef Q_OS_WIN
model->writeToProjectFile(doc, &modelElement);
#else
QDomElement modelEle = doc->createElement("Model");
model->writeToProjectFile1(doc,&modelEle);
modelElement.appendChild(modelEle);
#endif
}
parent->appendChild(modelElement);
return modelElement;
}
void ModelDataSingleton::clear()
{
const int n = _modelList.size();
for (int i = 0; i < n; ++i)
{
ModelDataBase* d = _modelList.at(i);
delete d;
}
_modelList.clear();
ModelDataBase::resetMaxID();
}
void ModelDataSingleton::removeModelByID(const int id)
{
ModelDataBase* dataBase = getModelByID(id);
if (dataBase == nullptr) return;
const int index = _modelList.indexOf(dataBase);
_modelList.removeAt(index);
delete dataBase;
}
int ModelDataSingleton::getModelIDByIndex(const int index)
{
const int n = _modelList.size();
if (index >= n || index < 0) return -1;
ModelDataBase* data = _modelList.at(index);
const int id = data->getID();
return id;
}
}
|
Softsimulation/siturmagdalena
|
public/js/administrador/eventos/indexController.js
|
<filename>public/js/administrador/eventos/indexController.js
/* global angular */
/* global swal */
angular.module('eventos.index', [])
.controller('eventosIndexController', function($scope, eventosServi){
$("body").attr("class", "cbp-spmenu-push charging");
eventosServi.getDatos().then(function (data){
$("body").attr("class", "cbp-spmenu-push");
if (data.success){
$scope.eventos = data.eventos;
$scope.idiomas = data.idiomas;
}
}).catch(function (errs){
$("body").attr("class", "cbp-spmenu-push");
swal('Error', 'Error al cargar los datos. Por favor recargue la página.', 'error');
});
$scope.desactivarActivar = function (evento){
$("body").attr("class", "cbp-spmenu-push charging");
eventosServi.postDesactivarActivar(evento.id).then(function (data){
$("body").attr("class", "cbp-spmenu-push");
if (data.success){
evento.estado = !evento.estado;
swal('¡Éxito!', 'Operación realizada con éxito.', 'success');
}
}).catch(function (error){
$("body").attr("class", "cbp-spmenu-push");
swal('Error', 'Error al desactivar la atracción. Por favor, recargue la página.', 'error');
});
}
$scope.sugerir = function (evento){
$("body").attr("class", "cbp-spmenu-push charging");
eventosServi.postSugerir(evento.id).then(function (data){
$("body").attr("class", "cbp-spmenu-push");
if (data.success){
evento.sugerido = !evento.sugerido;
swal('¡Éxito!', 'Operación realizada con éxito.', 'success');
}
}).catch(function (error){
$("body").attr("class", "cbp-spmenu-push");
swal('Error', 'Error al desactivar la atracción. Por favor, recargue la página.', 'error');
});
}
$scope.modalIdioma = function (atraccion){
$scope.eventoEdit = atraccion;
$("#idiomaModal").modal('show');
}
$scope.nuevoIdioma = function (){
if ($scope.idiomaEditSelected == ""){
swal("Información", 'Elija un idioma.', 'info');
return;
}
window.location = "/administradoreventos/idioma/"+ $scope.eventoEdit.id +"/" + $scope.idiomaEditSelected;
}
$scope.busquedaEvento = function (query){
if (query === undefined || query === ''){
return;
}
return function (evento){
return (evento.eventos_con_idiomas[0].nombre + ' - ' + evento.eventos_con_idiomas[0].edicion).toLocaleLowerCase().includes(query.toLocaleLowerCase());
}
}
});
|
panjinqiang11/xqDoctor
|
XQDoctors/XQDoctors/rwdTableViewCell.h
|
<gh_stars>1-10
//
// rwdTableViewCell.h
// XQDoctor
//
// Created by 任文迪 on 16/6/27.
// Copyright © 2016年 li. All rights reserved.
//
#import <UIKit/UIKit.h>
@class settingModel;
@interface rwdTableViewCell : UITableViewCell
@property(strong,nonatomic)settingModel *model;
@end
|
NicolasdeLimaAlves/Curso-de-Python
|
Mundos/Mundo 2/Aulas/Aula 12/ex038.py
|
<gh_stars>0
np = int(input('Digite o primeiro número: '))
ns = int(input('Digite o segundo número: '))
if np > ns:
print('O primeiro número é o MAIOR'.format('\033[1:32m', '\033[m'))
elif ns > np:
print('O segundo número é o MAIOR'.format('\033[1:32m', '\033[m'))
else:
print('Os dois número são iguais')
|
chrischen/gluestick
|
packages/gluestick/src/config/webpack/prepareEntries.js
|
/* @flow */
import type { GSConfig } from '../../types';
const path = require('path');
const { convertToCamelCase } = require('../../utils');
module.exports = (
gluestickConfig: GSConfig,
appOrGroupToBuild?: string,
): Object => {
const entries = require(path.join(
process.cwd(),
gluestickConfig.entriesPath,
));
// `/main` is a alias for `/` so it must not be used, as this will create
// a bunch of errors down the road
if (entries['/main']) {
throw new Error(
'`/main` cannot be used as entry key, as `main` is a reserved word',
);
}
if (!appOrGroupToBuild) {
return entries;
}
const singleApp: boolean = appOrGroupToBuild[0] === '/';
const appOrGroupName: string = convertToCamelCase(
appOrGroupToBuild.replace(/^\//, ''),
);
const entriesToBuild: string[] = Object.keys(
entries,
).filter((entryKey: string): boolean => {
if (singleApp && entries[entryKey].name) {
// If `name` property is defined
return entries[entryKey].name === appOrGroupName;
} else if (singleApp && entryKey === '/') {
// If `name` is not defined, check if entry is a index entry
return appOrGroupName === 'main';
} else if (singleApp) {
// Fallback: convert entryKey to camelCase and compare with passed value
return convertToCamelCase(entryKey.replace(/^\//, '')) === appOrGroupName;
}
return (
Array.isArray(entries[entryKey].group) &&
entries[entryKey].group.findIndex((groupName: string) => {
return convertToCamelCase(groupName) === appOrGroupName;
}) > -1
);
});
if (!entriesToBuild.length) {
throw new Error('No matching entry found');
}
return entriesToBuild.reduce((prev: Object, curr: string): Object => {
return { ...prev, [curr]: entries[curr] };
}, {});
};
|
Incapture/OG-Platform
|
projects/OG-Engine/src/main/java/com/opengamma/engine/fudgemsg/ViewComputationResultModelFudgeBuilder.java
|
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.engine.fudgemsg;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import org.fudgemsg.FudgeField;
import org.fudgemsg.FudgeMsg;
import org.fudgemsg.MutableFudgeMsg;
import org.fudgemsg.mapping.FudgeBuilder;
import org.fudgemsg.mapping.FudgeDeserializer;
import org.fudgemsg.mapping.FudgeSerializer;
import org.fudgemsg.mapping.GenericFudgeBuilderFor;
import com.google.common.collect.Sets;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.engine.view.InMemoryViewComputationResultModel;
import com.opengamma.engine.view.InMemoryViewResultModel;
import com.opengamma.engine.view.ViewComputationResultModel;
/**
*/
@GenericFudgeBuilderFor(ViewComputationResultModel.class)
public class ViewComputationResultModelFudgeBuilder extends ViewResultModelFudgeBuilder implements FudgeBuilder<ViewComputationResultModel> {
private static final String FIELD_LIVEDATA = "liveData";
private static final String FIELD_SPECIFICATION_MAPPING = "specificationMapping";
@Override
public MutableFudgeMsg buildMessage(final FudgeSerializer serializer, final ViewComputationResultModel resultModel) {
final MutableFudgeMsg message = ViewResultModelFudgeBuilder.createResultModelMessage(serializer, resultModel);
// Prevent subclass headers from being added to the message later, ensuring that this builder will be used for deserialization
FudgeSerializer.addClassHeader(message, ViewComputationResultModel.class);
final MutableFudgeMsg liveDataMsg = message.addSubMessage(FIELD_LIVEDATA, null);
for (final ComputedValue value : resultModel.getAllMarketData()) {
serializer.addToMessage(liveDataMsg, null, 1, value);
}
final MutableFudgeMsg mappingMsg = message.addSubMessage(FIELD_SPECIFICATION_MAPPING, null);
for (final Map.Entry<ValueSpecification, Set<ValueRequirement>> specMappingEntry : resultModel.getRequirementToSpecificationMapping().entrySet()) {
serializer.addToMessage(mappingMsg, null, 1, specMappingEntry.getKey());
final MutableFudgeMsg requirements = mappingMsg.addSubMessage(null, 2);
for (final ValueRequirement requirement : specMappingEntry.getValue()) {
serializer.addToMessage(requirements, null, null, requirement);
}
}
return message;
}
private static ValueSpecification getSpecification(final FudgeDeserializer deserializer, final FudgeField specification) {
return deserializer.fieldValueToObject(ValueSpecification.class, specification);
}
private Set<ValueRequirement> getRequirements(final FudgeDeserializer deserializer, final FudgeField requirements) {
final FudgeMsg msg = (FudgeMsg) requirements.getValue();
final Set<ValueRequirement> result = Sets.newHashSetWithExpectedSize(msg.getNumFields());
for (final FudgeField requirement : msg) {
result.add(deserializer.fieldValueToObject(ValueRequirement.class, requirement));
}
return result;
}
@Override
public ViewComputationResultModel buildObject(final FudgeDeserializer deserializer, final FudgeMsg message) {
final InMemoryViewComputationResultModel resultModel = (InMemoryViewComputationResultModel) bootstrapCommonDataFromMessage(deserializer, message);
for (final FudgeField field : message.getFieldValue(FudgeMsg.class, message.getByName(FIELD_LIVEDATA))) {
final ComputedValue liveData = deserializer.fieldValueToObject(ComputedValue.class, field);
resultModel.addMarketData(liveData);
}
final FudgeMsg mappingMsg = message.getMessage(FIELD_SPECIFICATION_MAPPING);
if (mappingMsg != null) {
final LinkedList<FudgeField> buffer = new LinkedList<FudgeField>();
FudgeField specification = null;
FudgeField requirements = null;
for (final FudgeField field : mappingMsg) {
final Integer ord = field.getOrdinal();
if (ord != null) {
if (ord.intValue() == 1) {
if (specification == null) {
if (requirements != null) {
resultModel.addRequirements(getRequirements(deserializer, requirements), getSpecification(deserializer, field));
requirements = buffer.pollFirst();
} else {
specification = field;
}
} else {
buffer.add(field);
}
} else if (ord.intValue() == 2) {
if (requirements == null) {
if (specification != null) {
resultModel.addRequirements(getRequirements(deserializer, field), getSpecification(deserializer, specification));
specification = buffer.pollFirst();
} else {
requirements = field;
}
} else {
buffer.add(field);
}
}
}
}
assert specification == null;
assert requirements == null;
}
return resultModel;
}
@Override
protected InMemoryViewResultModel constructImpl() {
return new InMemoryViewComputationResultModel();
}
}
|
sgroschupf/katta
|
modules/katta-core/src/main/java/net/sf/katta/node/monitor/MetricsRecord.java
|
/**
* Copyright 2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.katta.node.monitor;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class MetricsRecord implements Serializable {
private static final long serialVersionUID = 1832158671826263268L;
private List<Record> _records = new ArrayList<Record>();
private final String _serverId;
public MetricsRecord(String serverId) {
_serverId = serverId;
}
public String getServerId() {
return _serverId;
}
public void addValue(String key, long value, long timeStamp) {
_records.add(new Record(key, value, timeStamp));
}
public List<Record> getRecords() {
return _records;
}
public class Record implements Serializable {
private static final long serialVersionUID = 8134090886018804896L;
private final String _key;
private final long _value;
private final long _timeStamp;
public Record(String key, long value, long timeStamp) {
_key = key;
_value = value;
_timeStamp = timeStamp;
}
public String getKey() {
return _key;
}
public long getValue() {
return _value;
}
public long getTimeStamp() {
return _timeStamp;
}
@Override
public String toString() {
return _key + " " + _value + " " + _timeStamp;
}
}
@Override
public String toString() {
return _serverId + ": " + _records;
}
}
|
mzsilak/arrowhead
|
core-common/src/main/java/eu/arrowhead/common/database/ArrowheadService.java
|
<filename>core-common/src/main/java/eu/arrowhead/common/database/ArrowheadService.java
/*
* This work is part of the Productive 4.0 innovation project, which receives grants from the
* European Commissions H2020 research and innovation programme, ECSEL Joint Undertaking
* (project no. 737459), the free state of Saxony, the German Federal Ministry of Education and
* national funding authorities from involved countries.
*/
package eu.arrowhead.common.database;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.google.common.base.MoreObjects;
import eu.arrowhead.common.Utility;
import eu.arrowhead.common.exception.BadPayloadException;
import eu.arrowhead.common.json.support.ArrowheadServiceSupport;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.Size;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.validator.constraints.NotBlank;
/**
* Representation of a service within Arrowhead.
*
* @author uzoltan
* @since 4.2
*/
@Entity
@Table(name = "arrowhead_service", uniqueConstraints = {@UniqueConstraint(columnNames = {"service_definition"})})
public class ArrowheadService {
@Id
@GenericGenerator(name = "table_generator", strategy = "org.hibernate.id.enhanced.TableGenerator")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "table_generator")
private Long id;
@NotBlank
@Size(max = 255, message = "Service serviceDefinition must be 255 character at max")
@Column(name = "service_definition")
private String serviceDefinition;
@Size(max = 100, message = "Service can only have 100 interfaces at max")
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "arrowhead_service_interfaces", joinColumns = @JoinColumn(name = "arrowhead_service_id"))
private Set<String> interfaces = new HashSet<>();
@Transient
@JsonInclude(Include.NON_EMPTY)
@Size(max = 100, message = "Service can only have 100 serviceMetadata key-value pairs at max")
private Map<String, String> serviceMetadata = new HashMap<>();
public ArrowheadService() {
}
/**
* Constructor with all the fields of the ArrowheadService class.
*
* @param serviceDefinition A descriptive name for the service
* @param interfaces The set of interfaces that can be used to consume this service (helps interoperability between
* ArrowheadSystems). Concrete meaning of what is an interface is service specific (e.g. JSON, I2C)
* @param serviceMetadata Arbitrary additional serviceMetadata belonging to the service, stored as key-value pairs.
*/
public ArrowheadService(String serviceDefinition, Set<String> interfaces, Map<String, String> serviceMetadata) {
this.serviceDefinition = serviceDefinition;
this.interfaces = interfaces;
this.serviceMetadata = serviceMetadata;
}
public ArrowheadService(ArrowheadServiceSupport service) {
this.serviceDefinition = service.getServiceGroup() + "_" + service.getServiceDefinition();
this.interfaces = new HashSet<>(service.getInterfaces());
this.serviceMetadata = service.getServiceMetadata();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getServiceDefinition() {
return serviceDefinition;
}
public void setServiceDefinition(String serviceDefinition) {
this.serviceDefinition = serviceDefinition;
}
public Set<String> getInterfaces() {
return interfaces;
}
@JsonSetter
public void setInterfaces(Set<String> interfaces) {
for (String serviceInterface : interfaces) {
if (serviceInterface == null || serviceInterface.trim().isEmpty()) {
throw new BadPayloadException("ArrowheadService interface can not be blank!");
}
}
this.interfaces = interfaces;
}
public Map<String, String> getServiceMetadata() {
return serviceMetadata;
}
@JsonSetter
public void setServiceMetadata(Map<String, String> serviceMetadata) {
for (Map.Entry<String, String> entry : serviceMetadata.entrySet()) {
String key = entry.getKey();
if (key == null || key.trim().isEmpty()) {
throw new BadPayloadException("ArrowheadService metadata key can not be blank!");
}
String value = entry.getValue();
if (value == null || value.trim().isEmpty()) {
throw new BadPayloadException("ArrowheadService metadata value can not be blank!");
}
}
this.serviceMetadata = serviceMetadata;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ArrowheadService)) {
return false;
}
ArrowheadService that = (ArrowheadService) o;
if (!Objects.equals(serviceDefinition, that.serviceDefinition)) {
return false;
}
//2 services can be equal if they have at least 1 common interface
if (interfaces == null || that.interfaces == null) {
return true;
} else {
Set<String> intersection = new HashSet<>(interfaces);
intersection.retainAll(that.interfaces);
return !intersection.isEmpty();
}
}
@Override
public int hashCode() {
return Objects.hash(serviceDefinition);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("serviceDefinition", serviceDefinition).toString();
}
@SuppressWarnings("unchecked")
public void partialUpdate(ArrowheadService other) {
this.serviceDefinition = other.getServiceDefinition() != null ? other.getServiceDefinition() : this.serviceDefinition;
//Making deep copies of the collections with the help of JSON (de)serialization
this.interfaces = other.getInterfaces().isEmpty() ? this.interfaces : Utility
.fromJson(Utility.toPrettyJson(null, other.getInterfaces()), Set.class);
this.serviceMetadata = other.getServiceMetadata().isEmpty() ? this.serviceMetadata : Utility.fromJson(Utility.toPrettyJson(null, other.getServiceMetadata()), Map.class);
}
}
|
jxblum/cp-elements
|
src/main/java/org/cp/elements/data/struct/tabular/AbstractColumn.java
|
/*
* Copyright 2011-Present Author or Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cp.elements.data.struct.tabular;
import java.util.Optional;
import org.cp.elements.lang.Assert;
import org.cp.elements.lang.StringUtils;
/**
* The {@link AbstractColumn} class is an abstract base class implementing the {@link Column} interface,
* encapsulating common state and functionality for implementing {@link Column} types.
*
* @author <NAME>
* @param <T> {@link Class type} of {@link Object values} stored in this {@link Column}.
* @see org.cp.elements.data.struct.tabular.Column
* @see org.cp.elements.data.struct.tabular.Row
* @see org.cp.elements.data.struct.tabular.Table
* @see org.cp.elements.data.struct.tabular.View
* @since 1.0.0
*/
@SuppressWarnings("unused")
public abstract class AbstractColumn<T> implements Column<T> {
protected static final String COLUMN_TO_STRING =
"{ @type = %1$s, name = %2$s, alias = %3$s, description = %4$s, type = %5$s, defaultValue = %6$s }";
private T defaultValue;
private final Class<T> type;
private String alias;
private String description;
private final String name;
private View view;
/**
* Constructs a new instance of {@link AbstractColumn} initialized with
* the given {@link String name} and {@link Class type}.
*
* @param name {@link String} containing the name for this {@link Column}; must not be {@literal null}.
* @param type {@link Class} specifying the type of {@link Object values} stored by this {@link Column};
* must not be {@literal null}.
* @throws IllegalArgumentException if either {@link String name} or {@link Class type} are {@literal null}.
*/
public AbstractColumn(String name, Class<T> type) {
Assert.hasText(name, "Column name is required");
Assert.notNull(type, "Column type is required");
this.name = name;
this.type = type;
}
/**
* Constructs a new instance of {@link AbstractColumn} initialized with the given {@link Column}.
*
* @param column {@link Column} to copy; must not be {@literal null}.
* @throws IllegalArgumentException if the given {@link Column} is {@literal null}.
* @see org.cp.elements.data.struct.tabular.Column
*/
public AbstractColumn(Column<T> column) {
Assert.notNull(column, "The Column to copy is required");
this.name = column.getName();
this.type = column.getType();
column.getAlias().ifPresent(this::setAlias);
column.getDefaultValue().ifPresent(this::setDefaultValue);
column.getDescription().ifPresent(this::setDescription);
}
/**
* Sets the {@link String alias}, or alternate name for referring to this {@link Column}.
*
* @param alias {@link String} containing the alias, or alternate name for this {@link Column}.
*/
public void setAlias(String alias) {
this.alias = alias;
}
/**
* Returns an {@link Optional} {@link String alias}, or alternate name for referring to this {@link Column}.
*
* @return an {@link Optional} {@link String alias}, or alternate name for referring to this {@link Column}.
* @see java.util.Optional
* @see #getName()
*/
public Optional<String> getAlias() {
return Optional.ofNullable(this.alias).filter(StringUtils::hasText);
}
/**
* Sets the {@link Object default value} used when a {@link Object value} is not specified for this {@link Column}.
*
* @param defaultValue {@link Object default value} used when a {@link Object value} is not specified
* for this {@link Column}.
*/
public void setDefaultValue(T defaultValue) {
this.defaultValue = defaultValue;
}
/**
* Returns an {@link Optional} {@link Object default value} used when a {@link Object value}
* is not specified for this {@link Column}.
*
* @return an {@link Optional} {@link Object default value} used when a {@link Object value}
* is not specified for this {@link Column}.
* @see java.util.Optional
*/
public Optional<T> getDefaultValue() {
return Optional.ofNullable(this.defaultValue);
}
/**
* Sets a {@link String} to describe the data stored by this {@link Column}.
*
* @param description {@link String} containing the description for this {@link Column}.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Returns an {@link Optional} {@link String} to describe the data stored by this {@link Column}.
*
* @return an {@link Optional} {@link String} to describe the data stored by this {@link Column}.
* @see java.util.Optional
* @see #getAlias()
* @see #getName()
*/
public Optional<String> getDescription() {
return Optional.ofNullable(this.description).filter(StringUtils::hasText);
}
/**
* Returns the {@link String name} of this {@link Column}.
*
* @return the {@link String name} of this {@link Column}.
* @see org.cp.elements.lang.Nameable#getName()
*/
public String getName() {
return this.name;
}
/**
* Returns the {@link Class type} of {@link Object values} stored in this {@link Column}.
*
* @return {@link Class type} of {@link Object values} stored in this {@link Column}.
* @see java.lang.Class
*/
public Class<T> getType() {
return this.type;
}
/**
* Set the {@link View} containing this {@link Column}.
*
* @param view {@link View} containing this {@link Column}.
* @see org.cp.elements.data.struct.tabular.View
*/
public void setView(View view) {
this.view = view;
}
/**
* Returns an {@link Optional} {@link View} containing this {@link Column}.
*
* @return an {@link Optional} {@link View} containing this {@link Column}.
* @see org.cp.elements.data.struct.tabular.View
* @see java.util.Optional
*/
public Optional<View> getView() {
return Optional.ofNullable(this.view);
}
/**
* Builder method used to set a {@link String description} of this {@link Column}.
*
* @param <S> {@link Class Sub-type} of this {@link Column}.
* @param description {@link String} describing this {@link Column}.
* @return this {@link Column}.
* @see #setDescription(String)
*/
@SuppressWarnings("unchecked")
public <S extends AbstractColumn<T>> S describedAs(String description) {
setDescription(description);
return (S) this;
}
/**
* Builder methods used to set the {@link Object default value} used when a {@link Object value}
* is not specified for this {@link Column}.
*
* @param <S> {@link Class Sub-type} of this {@link Column}.
* @param defaultValue {@link Object default value} used when a {@link Object value}
* is not specified for this {@link Column}.
* @return this {@link Column}.
* @see #setDefaultValue(Object)
*/
@SuppressWarnings("unchecked")
public <S extends AbstractColumn<T>> S usingDefaultValue(T defaultValue) {
setDefaultValue(defaultValue);
return (S) this;
}
/**
* Builder method used to set the {@link String alias}, or alternate name for this {@link Column}.
*
* @param <S> {@link Class Sub-type} of this {@link Column}.
* @param alias {@link String} containing the alias, or alternate name for this {@link Column}.
* @return this {@link Column}.
* @see #setAlias(String)
*/
@SuppressWarnings("unchecked")
public <S extends AbstractColumn<T>> S withAlias(String alias) {
setAlias(alias);
return (S) this;
}
/**
* Determines whether this {@link Column} is equal to the given {@link Object}.
*
* @param obj {@link Object} to compare for equality with this {@link Column}.
* @return a boolean value indicating whether this {@link Column} is equal to
* the given {@link Object}
* @see java.lang.Object#equals(Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Column)) {
return false;
}
Column that = (Column) obj;
return this.getName().equals(that.getName());
}
/**
* Computes the {@link Integer hash value} for this {@link Column}.
*
* @return the computed {@link Integer hash value} for this {@link Column}.
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
int hashValue = 17;
hashValue = 37 * hashValue + getName().hashCode();
return hashValue;
}
/**
* Returns a {@link String} representation of this {@link Column}.
*
* @return a {@link String} describing this {@link Column}.
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.format(COLUMN_TO_STRING,
getClass().getName(), getName(), getAlias().orElse(null), getDescription().orElse(null), getType(),
getDefaultValue().orElse(null));
}
}
|
MegEngine/cutlass-bak
|
include/cutlass/convolution/device/convolution.h
|
<reponame>MegEngine/cutlass-bak<filename>include/cutlass/convolution/device/convolution.h
/***************************************************************************************************
* Copyright (c) 2017-2020, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
*modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
*this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
*notice, this list of conditions and the following disclaimer in the
*documentation and/or other materials provided with the distribution.
* * Neither the name of the NVIDIA CORPORATION nor the names of its
*contributors may be used to endorse or promote products derived from this
*software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
*AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
*IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION 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 TOR (INCLUDING
*NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
*EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/**
* \file include/cutlass/convolution/device/convolution.h
*
* Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*/
#pragma once
#include "cutlass/arch/arch.h"
#include "cutlass/cutlass.h"
#include "cutlass/device_kernel.h"
#include "cutlass/numeric_types.h"
#include "cutlass/convolution/convolution.h"
#include "cutlass/convolution/kernel/convolution.h"
#include "cutlass/convolution/kernel/convolution_precompute_offset.h"
#include "cutlass/convolution/threadblock/threadblock_swizzle.h"
#include "cutlass/convolution/device/default_convolution_configuration.h"
#include "cutlass/convolution/kernel/default_convolution.h"
////////////////////////////////////////////////////////////////////////////////
namespace cutlass {
namespace convolution {
namespace device {
/////////////////////////////////////////////////////////////////////////////////////////////////
/*! Convolution device-level operator.
*/
template <
/// Element type for Src Tensor operand
typename ElementSrc_,
/// Layout type for Src Tensor operand
typename LayoutSrc_,
/// Element type for Filter Tensor operand
typename ElementFilter_,
/// Layout type for Filter Tensor operand
typename LayoutFilter_,
/// Element type for Dst and Z Tensor operands
typename ElementDst_,
/// Layout type for Dst and Z Tensor operands
typename LayoutDst_,
/// Element type for Bias Tensor operands
typename ElementBias_,
/// Layout type for Bias Tensor operands
typename LayoutBias_,
/// Element type for internal accumulation
typename ElementAccumulator_,
/// Convolution Type
ConvType ConvolutionType = ConvType::kConvolution,
/// Operator class tag
typename OperatorClass_ = arch::OpClassSimt,
/// Tag indicating architecture to tune for
typename ArchTag_ = arch::Sm61,
/// Threadblock-level tile size (concept: GemmShape)
typename ThreadblockShape_ = typename DefaultConvolutionConfiguration<
OperatorClass_, ArchTag_, ElementSrc_, ElementFilter_,
ElementDst_, ElementAccumulator_>::ThreadblockShape,
/// Warp-level tile size (concept: GemmShape)
typename WarpShape_ = typename DefaultConvolutionConfiguration<
OperatorClass_, ArchTag_, ElementSrc_, ElementFilter_,
ElementDst_, ElementAccumulator_>::WarpShape,
/// Instruction-level tile size (concept: GemmShape)
typename InstructionShape_ = typename DefaultConvolutionConfiguration<
OperatorClass_, ArchTag_, ElementSrc_, ElementFilter_,
ElementDst_, ElementAccumulator_>::InstructionShape,
/// Epilogue output operator
typename EpilogueOutputOp_ = typename DefaultConvolutionConfiguration<
OperatorClass_, ArchTag_, ElementSrc_, ElementFilter_,
ElementDst_, ElementAccumulator_>::EpilogueOutputOp,
/// Threadblock-level swizzling operator
typename ThreadblockSwizzle_ = typename threadblock::
ConvolutionCxRSKxThreadblockSwizzle<ConvolutionType>,
/// Number of stages used in the pipelined mainloop
int Stages = DefaultConvolutionConfiguration<
OperatorClass_, ArchTag_, ElementSrc_, ElementFilter_,
ElementDst_, ElementAccumulator_>::kStages,
/// Access granularity of Src Tensor in units of elements
int AlignmentSrc = DefaultConvolutionConfiguration<
OperatorClass_, ArchTag_, ElementSrc_, ElementFilter_,
ElementDst_, ElementAccumulator_>::kAlignmentSrc,
/// Access granularity of Filter Tensor in units of elements
int AlignmentFilter = DefaultConvolutionConfiguration<
OperatorClass_, ArchTag_, ElementSrc_, ElementFilter_,
ElementDst_, ElementAccumulator_>::kAlignmentFilter,
/// whether use special optimization for convolution 1x1
bool NeedLoadFromConstMem = true,
/// Operation performed by Convolution
typename Operator_ = typename DefaultConvolutionConfiguration<
OperatorClass_, ArchTag_, ElementSrc_, ElementFilter_,
ElementDst_, ElementAccumulator_>::Operator>
class Convolution {
public:
using ElementSrc = ElementSrc_;
using LayoutSrc = LayoutSrc_;
using TensorRefSrc = TensorRef<ElementSrc const, LayoutSrc>;
using ElementFilter = ElementFilter_;
using LayoutFilter = LayoutFilter_;
using TensorRefFilter = TensorRef<ElementFilter const, LayoutFilter>;
using ElementBias = ElementBias_;
using LayoutBias = LayoutBias_;
using TensorRefBias = TensorRef<ElementBias const, LayoutBias>;
using ElementDst = ElementDst_;
using LayoutDst = LayoutDst_;
using TensorRefDst = TensorRef<ElementDst const, LayoutDst>;
using TensorRefZ = TensorRef<ElementDst, LayoutDst>;
using ElementAccumulator = ElementAccumulator_;
using OperatorClass = OperatorClass_;
using ArchTag = ArchTag_;
using ThreadblockShape = ThreadblockShape_;
using WarpShape = WarpShape_;
using InstructionShape = InstructionShape_;
using EpilogueOutputOp = EpilogueOutputOp_;
using ThreadblockSwizzle = ThreadblockSwizzle_;
using Operator = Operator_;
static const ConvType kConvolutionType = ConvolutionType;
using ConvolutionParameter = ConvParam<kConvolutionType>;
static int const kStages = Stages;
static int const kAlignmentSrc = AlignmentSrc;
static int const kAlignmentFilter = AlignmentFilter;
static int const kAlignmentDst = EpilogueOutputOp::kCount;
static bool const kNeedLoadFromConstMem = NeedLoadFromConstMem;
/// Define the kernel
using ConvolutionKernel = typename kernel::DefaultConvolution<
ElementSrc, LayoutSrc, kAlignmentSrc, ElementFilter, LayoutFilter,
kAlignmentFilter, ElementDst, LayoutDst, ElementAccumulator,
kConvolutionType, OperatorClass, ArchTag, ThreadblockShape,
WarpShape, InstructionShape, EpilogueOutputOp, ThreadblockSwizzle,
kStages, Operator, kNeedLoadFromConstMem>::ConvolutionKernel;
using TransformSrc = typename ConvolutionKernel::Mma::TransformSrc;
using TransformFilter = typename ConvolutionKernel::Mma::TransformFilter;
/// Argument structure
struct Arguments {
ConvolutionParameter conv_param;
TensorRef<ElementSrc const, LayoutSrc> ref_src;
TensorRef<ElementFilter const, LayoutFilter> ref_filter;
TensorRef<ElementBias const, LayoutBias> ref_bias;
TensorRef<ElementDst const, LayoutDst> ref_z;
TensorRef<ElementDst, LayoutDst> ref_dst;
typename EpilogueOutputOp::Params epilogue;
typename TransformSrc::Params transform_src;
typename TransformFilter::Params transform_filter;
/// Default ctor
CUTLASS_HOST_DEVICE
Arguments() : conv_param(ConvolutionParameter()) {}
/// Constructs an Arguments structure
CUTLASS_HOST_DEVICE
Arguments(ConvolutionParameter conv_param_,
TensorRef<ElementSrc const, LayoutSrc> ref_src_,
TensorRef<ElementFilter const, LayoutFilter> ref_filter_,
TensorRef<ElementBias const, LayoutBias> ref_bias_,
TensorRef<ElementDst const, LayoutDst> ref_z_,
TensorRef<ElementDst, LayoutDst> ref_dst_,
typename EpilogueOutputOp::Params epilogue_ =
typename EpilogueOutputOp::Params(),
typename TransformSrc::Params transform_src_ =
typename TransformSrc::Params(),
typename TransformFilter::Params transform_filter_ =
typename TransformFilter::Params())
: conv_param(conv_param_),
ref_src(ref_src_),
ref_filter(ref_filter_),
ref_bias(ref_bias_),
ref_z(ref_z_),
ref_dst(ref_dst_),
epilogue(epilogue_),
transform_src(transform_src_),
transform_filter(transform_filter_) {}
};
private:
/// Kernel parameters object
typename ConvolutionKernel::Params params_;
public:
/// Constructs the GEMM.
Convolution() {}
/// Determines whether the GEMM can execute the given problem.
static Status can_implement(Arguments const& args) {
Status status = ConvolutionKernel::can_implement(
args.conv_param, args.ref_src.non_const_ref(),
args.ref_filter.non_const_ref(), args.ref_bias.non_const_ref(),
args.ref_z.non_const_ref(), args.ref_dst);
if (status != Status::kSuccess) {
return status;
}
return Status::kSuccess;
}
/// Gets the workspace size
static size_t get_workspace_size(Arguments const& args) {
return ConvolutionKernel::get_workspace_size(args.conv_param);
}
/// Initializes GEMM state from arguments.
Status initialize(Arguments const& args, void* workspace = nullptr,
cudaStream_t stream = nullptr) {
// Determine grid shape
ThreadblockSwizzle threadblock_swizzle;
cutlass::gemm::GemmCoord grid_shape =
threadblock_swizzle.get_tiled_shape(
args.conv_param,
{ThreadblockShape::kM, ThreadblockShape::kN,
ThreadblockShape::kK});
// Initialize the Params structure
params_ = typename ConvolutionKernel::Params{
args.conv_param,
grid_shape,
args.ref_src.non_const_ref(),
args.ref_filter.non_const_ref(),
args.ref_bias.non_const_ref(),
args.ref_z.non_const_ref(),
args.ref_dst,
args.epilogue,
args.transform_src,
args.transform_filter,
static_cast<int*>(workspace)};
return Status::kSuccess;
}
/// Lightweight update given a subset of arguments
Status update(Arguments const& args, void* workspace = nullptr) {
params_.ref_src.reset(args.ref_src.non_const_ref().data());
params_.ref_filter.reset(args.ref_filter.non_const_ref().data());
params_.ref_bias.reset(args.ref_bias.non_const_ref().data());
params_.ref_z.reset(args.ref_z.non_const_ref().data());
params_.ref_dst.reset(args.ref_dst.data());
params_.output_op = args.epilogue;
params_.transform_src = args.transform_src;
params_.transform_filter = args.transform_filter;
params_.workspace = static_cast<int*>(workspace);
return Status::kSuccess;
}
/// Runs the kernel using initialized state.
Status run(cudaStream_t stream = nullptr) {
ThreadblockSwizzle threadblock_swizzle;
dim3 grid =
threadblock_swizzle.get_grid_shape(params_.grid_tiled_shape);
dim3 block(ConvolutionKernel::kThreadCount, 1, 1);
cudaError_t result;
int smem_size = int(sizeof(typename ConvolutionKernel::SharedStorage));
if (smem_size >= (48 << 10)) {
result = cudaFuncSetAttribute(
Kernel<ConvolutionKernel>,
cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size);
if (result != cudaSuccess) {
return Status::kErrorInternal;
}
result = cudaFuncSetAttribute(
Kernel<ConvolutionKernel>,
cudaFuncAttributePreferredSharedMemoryCarveout, 100);
if (result != cudaSuccess) {
return Status::kErrorInternal;
}
}
cutlass::Kernel<ConvolutionKernel>
<<<grid, block, smem_size, stream>>>(params_);
result = cudaGetLastError();
return result == cudaSuccess ? Status::kSuccess
: Status::kErrorInternal;
}
/// Runs the kernel using initialized state.
Status operator()(cudaStream_t stream = nullptr) { return run(stream); }
/// Runs the kernel using initialized state.
Status operator()(Arguments const& args, void* workspace = nullptr,
cudaStream_t stream = nullptr) {
Status status = initialize(args, workspace);
if (status == Status::kSuccess) {
status = run(stream);
}
return status;
}
};
////////////////////////////////////////////////////////////////////////////////
} // namespace device
} // namespace convolution
} // namespace cutlass
// vim: ft=cpp syntax=cuda.doxygen foldmethod=marker foldmarker=f{{{,f}}}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.