repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
player1537-forks/spack
|
var/spack/repos/builtin/packages/r-bslib/package.py
|
<reponame>player1537-forks/spack
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RBslib(RPackage):
"""Custom 'Bootstrap' 'Sass' Themes for 'shiny' and 'rmarkdown'.
Simplifies custom 'CSS' styling of both 'shiny' and 'rmarkdown' via
'Bootstrap' 'Sass'. Supports both 'Bootstrap' 3 and 4 as well as their
various 'Bootswatch' themes. An interactive widget is also provided for
previewing themes in real time."""
cran = "bslib"
version('0.3.1', sha256='5f5cb56e5cab9039a24cd9d70d73b69c2cab5b2f5f37afc15f71dae0339d9849')
depends_on('r@2.10:', type=('build', 'run'))
depends_on('r-htmltools@0.5.2:', type=('build', 'run'))
depends_on('r-jsonlite', type=('build', 'run'))
depends_on('r-sass@0.4.0:', type=('build', 'run'))
depends_on('r-jquerylib@0.1.3:', type=('build', 'run'))
depends_on('r-rlang', type=('build', 'run'))
|
atosorigin/blueprint-fabric8
|
sandbox/fabric/fabric-api/src/main/java/io/fabric8/api/jmx/MetaTypeSummaryDTO.java
|
/**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.api.jmx;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.osgi.framework.Bundle;
import org.osgi.service.metatype.MetaTypeInformation;
import org.osgi.service.metatype.ObjectClassDefinition;
/**
*/
public class MetaTypeSummaryDTO {
private Map<String, MetaTypeObjectSummaryDTO> pids = new HashMap<String, MetaTypeObjectSummaryDTO>();
private Set<String> locales = new HashSet<String>();
public void addTypeInformation(Bundle bundle, MetaTypeInformation info) {
addBundleInfo(bundle, info, info.getFactoryPids(), true);
addBundleInfo(bundle, info, info.getPids(), false);
String[] localeArray = info.getLocales();
if (localeArray != null) {
for (String locale : localeArray) {
locales.add(locale);
}
}
}
public Map<String, MetaTypeObjectSummaryDTO> getPids() {
return pids;
}
public void setPids(Map<String, MetaTypeObjectSummaryDTO> pids) {
this.pids = pids;
}
public Set<String> getLocales() {
return locales;
}
private void addBundleInfo(Bundle bundle, MetaTypeInformation info, String[] pids, boolean factory) {
String locale = null;
if (pids != null) {
long bundleId = bundle.getBundleId();
for (String pid : pids) {
MetaTypeObjectSummaryDTO summary = getOrCreateMetaTypeSummaryDTO(pid);
if (factory) {
summary.getFactoryPidBundleIds().add(bundleId);
} else {
summary.getPidBundleIds().add(bundleId);
}
ObjectClassDefinition objectClassDefinition = MetaTypeSummaryDTO.tryGetObjectClassDefinition(info, pid, locale);
if (objectClassDefinition != null) {
summary.appendObjectDefinition(objectClassDefinition);
}
}
}
}
public MetaTypeObjectSummaryDTO getOrCreateMetaTypeSummaryDTO(String pid) {
MetaTypeObjectSummaryDTO summary = this.pids.get(pid);
if (summary == null) {
summary = new MetaTypeObjectSummaryDTO(pid);
this.pids.put(pid, summary);
}
return summary;
}
/**
* Attempts to get the object definition ignoring any failures of missing declarations
*/
public static ObjectClassDefinition tryGetObjectClassDefinition(MetaTypeInformation info, String pid, String locale) {
ObjectClassDefinition object = null;
try {
object = info.getObjectClassDefinition(pid, locale);
} catch (Exception e) {
// ignore missing definition
}
return object;
}
}
|
tli-group-4-grimm/backend
|
src/main/java/entities/LoanDataFactory.java
|
<gh_stars>1-10
// layer: usecases
package entities;
import attributes.ArrayAttribute;
import attributes.Attribute;
import attributes.AttributeMap;
import constants.EntityStringNames;
import constants.Exceptions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LoanDataFactory {
/**
* Constructs a new LoanData using the values in the given AttributeMap
*
* @param map an AttributeMap containing keys and values corresponding to the attributes of a
* LoanData
* @return a LoanData constructed from the values in map
* @throws Exceptions.FactoryException if the required key/value pairs for LoanData construction
* aren't present in map
*/
public static LoanData getEntity(AttributeMap map) throws Exceptions.FactoryException {
double interestRate;
double installment;
String sensoScore;
double loanAmount;
int termLength;
double interestSum;
double addOnBudget = 0;
List<Map<String, Double>> amortizationTable = new ArrayList<>();
try {
interestRate =
AttributeMap.getDoubleMaybeInteger(EntityStringNames.LOAN_INTEREST_RATE, map);
installment =
AttributeMap.getDoubleMaybeInteger(EntityStringNames.LOAN_INSTALLMENT, map);
sensoScore = (String) map.getItem(EntityStringNames.LOAN_SCORE).getAttribute();
loanAmount = AttributeMap.getDoubleMaybeInteger(EntityStringNames.LOAN_AMOUNT, map);
termLength = (int) map.getItem(EntityStringNames.LOAN_TERM_LENGTH).getAttribute();
try {
addOnBudget =
(double) map.getItem(EntityStringNames.LOAN_ADD_ON_BUDGET).getAttribute();
} catch (NullPointerException ignored) {
// if add-on budget isn't in the map we just default its value to 0
}
interestSum =
AttributeMap.getDoubleMaybeInteger(EntityStringNames.LOAN_INTEREST_SUM, map);
ArrayAttribute amortizationArray =
(ArrayAttribute) map.getItem(EntityStringNames.LOAN_AMORTIZATION);
addAmortizationEntries(amortizationTable, amortizationArray);
} catch (ClassCastException | NullPointerException e) {
String message = "Failed to generate LoanData";
throw new Exceptions.FactoryException(message, e);
}
return new LoanData(
interestRate,
installment,
sensoScore,
loanAmount,
termLength,
interestSum,
addOnBudget,
amortizationTable);
}
private static void addAmortizationEntries(
List<Map<String, Double>> amortizationTable, ArrayAttribute amortizationArray) {
Attribute[] amortization = amortizationArray.getAttribute();
for (Attribute a : amortization) {
AttributeMap installmentAttMap = (AttributeMap) a;
Map<String, Attribute> installmentMap = installmentAttMap.getAttribute();
Map<String, Double> installmentDoubleMap = new HashMap<>();
for (String s : installmentMap.keySet()) {
installmentDoubleMap.put(
s, AttributeMap.getDoubleMaybeInteger(s, installmentAttMap));
}
amortizationTable.add(installmentDoubleMap);
}
}
}
|
yunjaena/android_study
|
RxJavaJason/src/main/java/com/itvillage/chapter05/chapter0503/Searcher.java
|
package com.itvillage.chapter05.chapter0503;
import java.util.*;
public class Searcher {
public Map<String, List<String>> map = new HashMap<>();
{
map.put("M", Arrays.asList("Macau", "Malaysia", "Maldives", "Mexico", "Myanmar", "Macedonia"));
map.put("Ma", Arrays.asList("Macau", "Malaysia", "Maldives", "Macedonia"));
map.put("Mal", Arrays.asList("Malaysia", "Maldives"));
map.put("Malay", Arrays.asList("Malaysia"));
}
public List<String> search(String keyword){
List<String> results = map.get(keyword);
if(results == null){
results = new ArrayList<>();
}
return results;
}
}
|
aramk/react-cosmos
|
packages/react-cosmos-shared/index.js
|
// @flow
exports.importModule = require('./dist/import-module').importModule;
exports.splitUnserializableParts = require('./dist/unserializable-parts').splitUnserializableParts;
exports.getOldSchoolFixturesFromNewStyleComponents = require('./dist/fixtures-format').getOldSchoolFixturesFromNewStyleComponents;
exports.getNormalizedFixtureModules = require('./dist/fixtures-format').getNormalizedFixtureModules;
|
ScalablyTyped/SlinkyTyped
|
a/aws-sdk/src/main/scala/typingsSlinky/awsSdk/ssoadminMod/AttachedManagedPolicy.scala
|
package typingsSlinky.awsSdk.ssoadminMod
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait AttachedManagedPolicy extends StObject {
/**
* The ARN of the IAM managed policy. For more information about ARNs, see Amazon Resource Names (ARNs) and AWS Service Namespaces in the AWS General Reference.
*/
var Arn: js.UndefOr[ManagedPolicyArn] = js.native
/**
* The name of the IAM managed policy.
*/
var Name: js.UndefOr[typingsSlinky.awsSdk.ssoadminMod.Name] = js.native
}
object AttachedManagedPolicy {
@scala.inline
def apply(): AttachedManagedPolicy = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[AttachedManagedPolicy]
}
@scala.inline
implicit class AttachedManagedPolicyMutableBuilder[Self <: AttachedManagedPolicy] (val x: Self) extends AnyVal {
@scala.inline
def setArn(value: ManagedPolicyArn): Self = StObject.set(x, "Arn", value.asInstanceOf[js.Any])
@scala.inline
def setArnUndefined: Self = StObject.set(x, "Arn", js.undefined)
@scala.inline
def setName(value: Name): Self = StObject.set(x, "Name", value.asInstanceOf[js.Any])
@scala.inline
def setNameUndefined: Self = StObject.set(x, "Name", js.undefined)
}
}
|
openid-certification/-conformance-suite
|
src/main/java/net/openid/conformance/condition/client/CreateRandomEndSessionState.java
|
package net.openid.conformance.condition.client;
import net.openid.conformance.condition.AbstractCondition;
import net.openid.conformance.condition.PostEnvironment;
import net.openid.conformance.condition.util.RFC6749AppendixASyntaxUtils;
import net.openid.conformance.testmodule.Environment;
public class CreateRandomEndSessionState extends AbstractCondition {
@Override
@PostEnvironment(strings = "end_session_state")
public Environment evaluate(Environment env) {
// https://openid.net/specs/openid-connect-session-1_0.html#RPLogout does not appear to define a character
// set for state; assume it is in same as state defined in RFC6749
String state = RFC6749AppendixASyntaxUtils.generateVSChar(50, 10, 30);
// the way we encode urls escapes + incorrectly in the url query currently, so don't include '+'s
// @see net.openid.conformance.condition.client.BuildPlainRedirectToAuthorizationEndpoint_UnitTest.testEscape
state = state.replace('+', '~');
state = state.replace(' ', '~');
// avoid ; as spring seems to not process them correctly when they're returned to us unescaped; see
// https://gitlab.com/openid/conformance-suite/-/issues/871
state = state.replace(';', '~');
env.putString("end_session_state", state);
log("Created end_session_state value", args("end_session_state", state));
return env;
}
}
|
syfxlin/xkjava
|
xkjava-framework/src/main/java/me/ixk/framework/exception/WebSocketException.java
|
package me.ixk.framework.exception;
/**
* @author <NAME>
* @date 2021/2/22 下午 9:37
*/
public class WebSocketException extends Exception {
public WebSocketException() {
super();
}
public WebSocketException(String message) {
super(message);
}
public WebSocketException(String message, Throwable cause) {
super(message, cause);
}
public WebSocketException(Throwable cause) {
super(cause);
}
protected WebSocketException(
String message,
Throwable cause,
boolean enableSuppression,
boolean writableStackTrace
) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
wm28/main
|
src/main/java/seedu/address/ui/ResultDisplay.java
|
<filename>src/main/java/seedu/address/ui/ResultDisplay.java
package seedu.address.ui;
import java.util.logging.Logger;
import com.google.common.eventbus.Subscribe;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.scene.layout.Region;
import seedu.address.commons.core.LogsCenter;
import seedu.address.commons.events.ui.NewResultAvailableEvent;
/**
* A ui for the status bar that is displayed at the header of the application.
*/
public class ResultDisplay extends UiPart<Region> {
public static final String ERROR_IN_COMMAND = "error";
private static final Logger logger = LogsCenter.getLogger(ResultDisplay.class);
private static final String FXML = "ResultDisplay.fxml";
private final StringProperty displayed = new SimpleStringProperty("");
@FXML
private TextArea resultDisplay;
public ResultDisplay() {
super(FXML);
resultDisplay.textProperty().bind(displayed);
registerAsAnEventHandler(this);
}
@Subscribe
private void handleNewResultAvailableEvent(NewResultAvailableEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event));
Platform.runLater(() -> {
displayed.setValue(event.message);
if (event.isCorrectCommand) {
setStyleforSuccessfulCommand();
} else {
setStyleforIncorrectCommand();
}
});
}
/**
* Sets the {@code ResultDisplay} style to display the default style
* Note: This code was adapted from the example implementation provide by @yamgent from SE-EDU
*/
private void setStyleforSuccessfulCommand() {
resultDisplay.getStyleClass().remove(ERROR_IN_COMMAND);
}
/**
* Sets the {@code ResultDisplay} style to display an incorrect command
* Note: This code was adapted from the example implementation provide by @yamgent from SE-EDU
*/
private void setStyleforIncorrectCommand() {
ObservableList<String> styleClass = resultDisplay.getStyleClass();
if (styleClass.contains(ERROR_IN_COMMAND)) {
return;
}
styleClass.add(ERROR_IN_COMMAND);
}
}
|
zyj-nanjing/SmartCloud
|
SmartCloud-client/src/main/java/www/bwsensing/com/device/dto/command/AlertParamSaveCmd.java
|
<reponame>zyj-nanjing/SmartCloud<filename>SmartCloud-client/src/main/java/www/bwsensing/com/device/dto/command/AlertParamSaveCmd.java<gh_stars>0
package www.bwsensing.com.device.dto.command;
import lombok.Data;
import java.util.List;
import com.alibaba.cola.dto.Command;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* @author macos-zyj
*/
@Data
public class AlertParamSaveCmd extends Command {
/**告警名称**/
@NotBlank(message = "告警名称不能为空")
private String alertName;
/**监测参数编号 注数据库编号*/
@NotNull(message = "监测参数编号不能为空")
private Integer paramNo;
/**问题发生后的持续时间 默认为 0 */
private String lastTime;
/**监测周期 默认为1m*/
private String period;
/**
* 每组格式为 (max,>,10,&&) 第一位为 函数 可以为 max avg min 第二位为 运算符 可以为 < <= > >= != == 第三位为具体数据 第四位为 逻辑或按位 运算符 || | && & 注意数组末尾不要加加了校验不会让你过的
**/
@Valid
@NotNull(message = "监测公式不能为空")
@Size(min = 1, message = "监测公式至少要有一个自定义属性")
private List<String> formulas;
/**颜色*/
private String color;
}
|
wangcy6/weekly_read
|
code_reading/oceanbase-master/src/sql/engine/expr/ob_expr_oracle_decode.h
|
/**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#ifndef _OB_SQL_EXPR_ORACLE_DECODE_H_
#define _OB_SQL_EXPR_ORACLE_DECODE_H_
#include "sql/engine/expr/ob_expr_operator.h"
namespace oceanbase {
namespace sql {
class ObExprOracleDecode : public ObExprOperator {
OB_UNIS_VERSION_V(1);
public:
explicit ObExprOracleDecode(common::ObIAllocator& alloc);
virtual ~ObExprOracleDecode();
virtual int calc_result_typeN(
ObExprResType& type, ObExprResType* types_stack, int64_t param_num, common::ObExprTypeCtx& type_ctx) const;
virtual int calc_resultN(
common::ObObj& result, const common::ObObj* objs_stack, int64_t param_num, common::ObExprCtx& expr_ctx) const;
int no_cast_calc(common::ObObj& result, const common::ObObj* objs_stack, int64_t param_num) const;
int calc_result_type_for_literal(
ObExprResType& type, ObExprResType* types_stack, int64_t param_num, common::ObExprTypeCtx& type_ctx) const;
virtual int cg_expr(ObExprCGCtx& expr_cg_ctx, const ObRawExpr& raw_expr, ObExpr& rt_expr) const override;
static int eval_decode(const ObExpr& expr, ObEvalCtx& ctx, ObDatum& res);
public:
inline void set_cond_all_same_meta(bool all_same_meta);
inline void set_val_all_same_meta(bool all_same_meta);
static bool can_compare_directly(common::ObObjType type1, common::ObObjType type2);
private:
inline static int get_cmp_type(common::ObObjType& type, const common::ObObjType& type1,
const common::ObObjType& type2, const common::ObObjType& type3);
inline bool is_cond_all_same_meta() const;
inline bool is_val_all_same_meta() const;
inline bool need_no_cast() const;
private:
typedef uint32_t ObExprDecodeParamFlag;
static const uint32_t COND_ALL_SAME_META = 1U << 0;
static const uint32_t VAL_ALL_SAME_META = 1U << 1;
ObExprDecodeParamFlag param_flags_;
// disallow copy
DISALLOW_COPY_AND_ASSIGN(ObExprOracleDecode);
};
inline void ObExprOracleDecode::set_cond_all_same_meta(bool all_same_meta)
{
if (all_same_meta) {
param_flags_ |= COND_ALL_SAME_META;
} else {
param_flags_ &= ~COND_ALL_SAME_META;
}
}
inline void ObExprOracleDecode::set_val_all_same_meta(bool all_same_meta)
{
if (all_same_meta) {
param_flags_ |= VAL_ALL_SAME_META;
} else {
param_flags_ &= ~VAL_ALL_SAME_META;
}
}
inline bool ObExprOracleDecode::is_cond_all_same_meta() const
{
return param_flags_ & COND_ALL_SAME_META;
}
inline bool ObExprOracleDecode::is_val_all_same_meta() const
{
return param_flags_ & VAL_ALL_SAME_META;
}
inline bool ObExprOracleDecode::need_no_cast() const
{
return is_cond_all_same_meta() && is_val_all_same_meta();
}
} // namespace sql
} // namespace oceanbase
#endif /* _OB_SQL_EXPR_ORACLE_DECODE_H_ */
|
shans/arcs
|
runtime/strategies/map-slots.js
|
<filename>runtime/strategies/map-slots.js
// Copyright (c) 2017 Google Inc. All rights reserved.
// This code may only be used under the BSD style license found at
// http://polymer.github.io/LICENSE.txt
// Code distributed by Google as part of this project is also
// subject to an additional IP rights grant found at
// http://polymer.github.io/PATENTS.txt
import {Strategy} from '../../strategizer/strategizer.js';
import {Recipe} from '../ts-build/recipe/recipe.js';
import {Walker} from '../ts-build/recipe/walker.js';
import {assert} from '../../platform/assert-web.js';
export class MapSlots extends Strategy {
constructor(arc) {
super();
this._arc = arc;
}
async generate(inputParams) {
const arc = this._arc;
return Recipe.over(this.getResults(inputParams), new class extends Walker {
onSlotConnection(recipe, slotConnection) {
// don't try to connect verb constraints
// TODO: is this right? Should constraints be connectible, in order to precompute the
// recipe side once the verb is substituted?
if (slotConnection.slotSpec == undefined) {
return;
}
if (slotConnection.isConnected()) {
return;
}
const {local, remote} = MapSlots.findAllSlotCandidates(slotConnection, arc);
// ResolveRecipe handles one-slot case.
if (local.length + remote.length < 2) {
return;
}
// If there are any local slots, prefer them over remote slots.
const slotList = local.length > 0 ? local : remote;
return slotList.map(slot => ((recipe, slotConnection) => {
MapSlots.connectSlotConnection(slotConnection, slot);
return 1;
}));
}
}(Walker.Permuted), this);
}
// Helper methods.
// Connect the given slot connection to the selectedSlot, create the slot, if needed.
static connectSlotConnection(slotConnection, selectedSlot) {
const recipe = slotConnection.recipe;
if (!slotConnection.targetSlot) {
let clonedSlot = recipe.updateToClone({selectedSlot}).selectedSlot;
if (!clonedSlot) {
clonedSlot = recipe.slots.find(s => selectedSlot.id && selectedSlot.id == s.id);
if (clonedSlot == undefined) {
clonedSlot = recipe.newSlot(selectedSlot.name);
clonedSlot.id = selectedSlot.id;
}
}
slotConnection.connectToSlot(clonedSlot);
}
assert(!selectedSlot.id || !slotConnection.targetSlot.id || (selectedSlot.id == slotConnection.targetSlot.id),
`Cannot override slot id '${slotConnection.targetSlot.id}' with '${selectedSlot.id}'`);
slotConnection.targetSlot.id = selectedSlot.id || slotConnection.targetSlot.id;
// TODO: need to concat to existing tags and dedup?
slotConnection.targetSlot.tags = [...selectedSlot.tags];
}
// Returns all possible slot candidates, sorted by "quality"
static findAllSlotCandidates(slotConnection, arc) {
return {
// Note: during manfiest parsing, target slot is only set in slot connection, if the slot exists in the recipe.
// If this slot is internal to the recipe, it has the sourceConnection set to the providing connection
// (and hence the consuming connection is considered connected already). Otherwise, this may only be a remote slot.
local: !slotConnection.targetSlot ? MapSlots._findSlotCandidates(slotConnection, slotConnection.recipe.slots) : [],
remote: MapSlots._findSlotCandidates(slotConnection, arc.pec.slotComposer.getAvailableContexts())
};
}
// Returns the given slot candidates, sorted by "quality".
static _findSlotCandidates(slotConnection, slots) {
const possibleSlots = slots.filter(s => this.slotMatches(slotConnection, s));
possibleSlots.sort((slot1, slot2) => {
// TODO: implement.
return slot1.name < slot2.name;
});
return possibleSlots;
}
// Returns true, if the given slot is a viable candidate for the slotConnection.
static slotMatches(slotConnection, slot) {
if (!MapSlots.specMatch(slotConnection, slot)) {
return false;
}
if (!MapSlots.tagsOrNameMatch(slotConnection, slot)) {
return false;
}
// Match handles of the provided slot with the slot-connection particle's handles.
if (!MapSlots.handlesMatch(slotConnection, slot)) {
return false;
}
return true;
}
static specMatch(slotConnection, slot) {
return slotConnection.slotSpec && // if there's no slotSpec, this is just a slot constraint on a verb
slotConnection.slotSpec.isSet == slot.spec.isSet;
}
// Returns true, if the slot connection's tags intersection with slot's tags is nonempty.
// TODO: replace with generic tag matcher
static tagsOrNameMatch(slotConnection, slot) {
const consumeConnTags = [].concat(slotConnection.slotSpec.tags || [], slotConnection.tags, slotConnection.targetSlot ? slotConnection.targetSlot.tags : []);
const slotTags = new Set([].concat(slot.tags, slot.spec.tags || [], [slot.name]));
// Consume connection tags aren't empty and intersection with the slot isn't empty.
if (consumeConnTags.length > 0 && consumeConnTags.some(t => slotTags.has(t))) {
return true;
}
// For backward compatibility support explicit slot names matching.
return (slotConnection.name === slot.name);
}
// Returns true, if the providing slot handle restrictions are satisfied by the consuming slot connection.
// TODO: should we move some of this logic to the recipe? Or type matching?
static handlesMatch(slotConnection, slot) {
if (slot.handles.length == 0) {
return true; // slot is not limited to specific handles
}
return Object.values(slotConnection.particle.connections).find(handleConn => {
return slot.handles.includes(handleConn.handle) ||
(handleConn.handle && handleConn.handle.id && slot.handles.map(sh => sh.id).includes(handleConn.handle.id));
});
}
}
|
aligungr/ue-ran-sim
|
src/asn/ngap/ASN_NGAP_Criticality.h
|
<reponame>aligungr/ue-ran-sim
/*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "NGAP-CommonDataTypes"
* found in "asn/ngap-15.8.0.asn1"
* `asn1c -fcompound-names -pdu=all -findirect-choice -fno-include-deps -gen-PER -no-gen-OER -no-gen-example -D ngap`
*/
#ifndef _ASN_NGAP_Criticality_H_
#define _ASN_NGAP_Criticality_H_
#include <asn_application.h>
/* Including external dependencies */
#include <NativeEnumerated.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Dependencies */
typedef enum ASN_NGAP_Criticality {
ASN_NGAP_Criticality_reject = 0,
ASN_NGAP_Criticality_ignore = 1,
ASN_NGAP_Criticality_notify = 2
} e_ASN_NGAP_Criticality;
/* ASN_NGAP_Criticality */
typedef long ASN_NGAP_Criticality_t;
/* Implementation */
extern asn_per_constraints_t asn_PER_type_ASN_NGAP_Criticality_constr_1;
extern asn_TYPE_descriptor_t asn_DEF_ASN_NGAP_Criticality;
extern const asn_INTEGER_specifics_t asn_SPC_ASN_NGAP_Criticality_specs_1;
asn_struct_free_f ASN_NGAP_Criticality_free;
asn_struct_print_f ASN_NGAP_Criticality_print;
asn_constr_check_f ASN_NGAP_Criticality_constraint;
ber_type_decoder_f ASN_NGAP_Criticality_decode_ber;
der_type_encoder_f ASN_NGAP_Criticality_encode_der;
xer_type_decoder_f ASN_NGAP_Criticality_decode_xer;
xer_type_encoder_f ASN_NGAP_Criticality_encode_xer;
per_type_decoder_f ASN_NGAP_Criticality_decode_uper;
per_type_encoder_f ASN_NGAP_Criticality_encode_uper;
per_type_decoder_f ASN_NGAP_Criticality_decode_aper;
per_type_encoder_f ASN_NGAP_Criticality_encode_aper;
#ifdef __cplusplus
}
#endif
#endif /* _ASN_NGAP_Criticality_H_ */
#include <asn_internal.h>
|
mtasa-typescript/mtasa-wiki-parser
|
to_typescript/filters/oop_declarations.py
|
<reponame>mtasa-typescript/mtasa-wiki-parser
from collections import defaultdict
from typing import Set, DefaultDict, List
from crawler.core.types import PageUrl
from to_python.core.types import FunctionOOP
from to_typescript.core.filter import FilterAbstract
from to_typescript.core.transform.function import TypeScriptFunctionGenerator
from to_typescript.core.transform.oop import TypeScriptOOPGenerator
class FilterGenerateOOPDeclarations(FilterAbstract):
def __init__(self):
super().__init__()
# < function name, <side, prop list> >
self.fields_in_class: DefaultDict[
str, DefaultDict[str, Set[str]]] = defaultdict(
lambda: defaultdict(set))
def generate_declaration(self,
side: str,
oop_data: FunctionOOP,
url: PageUrl):
file_name = oop_data.class_name
field_name = oop_data.field.name if oop_data.field else None
generator = TypeScriptOOPGenerator(host_name=self.context.host_name,
data=oop_data,
url=url)
declaration_field = generator.generate_field()
declaration_method = generator.generate_method()
if declaration_field and field_name not in \
self.fields_in_class[file_name][side]:
self.fields_in_class[file_name][side].add(field_name)
self.context.declarations.oop_fields[file_name][side].append(
declaration_field)
if declaration_method:
self.context.declarations.oop_methods[file_name][side].append(
declaration_method)
# Adds class generic (template) string
if oop_data.method.name == 'constructor':
self.context.declarations.oop_class_templates[file_name][
side].append(
TypeScriptFunctionGenerator.generate_generics(
oop_data.method.signature.generic_types)
)
def apply(self):
"""
Generates OOP declarations
"""
for oop in self.context.oops:
for side, oop_list in oop:
oop_list: List[FunctionOOP]
for oop_data in oop_list:
url = self.context.urls[oop_data.method.url]
self.generate_declaration(side=side,
oop_data=oop_data,
url=url)
print('OOP Declarations generated\u001b[0m')
|
gautamprajapati090/sample-code
|
flashpik-user/source/pages/dispute/chatStyle.js
|
'use strict';
import { StyleSheet, Dimensions, Platform, StatusBar } from 'react-native';
import Color from '../../component/color';
import Font from '../../component/font';
var { width, height } = Dimensions.get('window');
module.exports = StyleSheet.create({
container: {
flex: 1,
backgroundColor: Color.white
},
mainContainer: {
paddingHorizontal: width * 0.05
},
title: {
fontFamily: Font.bold,
color: Color.dark_blue,
fontSize: width * 0.07,
//paddingTop: width * 0.025,
paddingBottom: width * 0.05
},
orderBox: {
borderBottomColor: Color.dark_blue,
borderBottomWidth: 1,
paddingHorizontal: width * 0.05,
//borderWidth: 1,
},
topNavigation: {
flexDirection:'row',
alignItems: 'center',
marginBottom: 10,
paddingVertical: 1,
//borderWidth: 1,
},
leftNavigation: {
flex: 1,
alignItems: 'flex-start',
},
rightNavigation: {
flex: 1,
alignItems: 'flex-end'
},
subTitle: {
fontFamily: Font.semi_bold,
fontSize: width * 0.037,
//borderWidth: 1,
lineHeight: height * 0.023
},
nav: {
flexDirection:'row',
borderBottomColor: Color.grey_3,
paddingBottom: width * 0.001,
//borderWidth: 1,
},
leftNav: {
flex: 0.25,
justifyContent: 'flex-start',
alignItems: 'flex-start'
},
rightNav: {
flex: 1,
alignItems: 'flex-start'
},
heading: {
fontFamily: Font.semi_bold,
fontSize: width * 0.036
},
reason: {
fontFamily: Font.semi_bold,
fontSize: width * 0.03,
},
chatContainer: {
flex: 1,
}
})
|
hapify/cli
|
dist/interface/schema/ValidatorResult.js
|
<filename>dist/interface/schema/ValidatorResult.js
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TransformValidationMessage = exports.ValidatorResultSchema = void 0;
const joi_1 = __importDefault(require("joi"));
exports.ValidatorResultSchema = joi_1.default.object({
errors: joi_1.default.array().items(joi_1.default.string()).required().min(0),
warnings: joi_1.default.array().items(joi_1.default.string()).required().min(0),
});
function TransformValidationMessage(error) {
if (error.details && error.details.length) {
error.message = error.details.map((d) => `${d.message} (${d.path.join('.')})`).join('. ');
}
return error;
}
exports.TransformValidationMessage = TransformValidationMessage;
//# sourceMappingURL=ValidatorResult.js.map
|
isabella232/mod_dup
|
src/filters_migrate.cc
|
/*
* mod_compare - compare apache requests
*
* Copyright (C) 2013 Orange
*
* 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 "RequestInfo.hh"
#include "mod_migrate.hh"
#include "Utils.hh"
#include <http_config.h>
#include <httpd.h>
// Work-around boost::chrono 1.53 conflict on CR typedef vs define in apache
#undef CR
#include <assert.h>
#include <stdexcept>
#include <boost/thread/detail/singleton.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/tokenizer.hpp>
#include <iomanip>
#include <boost/regex.hpp>
#include <boost/foreach.hpp>
namespace MigrateModule {
/// set apache env var
static bool setEnvVar(request_rec *pRequest, const MigrateConf::MigrateEnv &ctx, const std::string& toSet, int& count) {
if (!toSet.empty()) {
Log::debug("CE: URL match: Value to set: %s, varName: %s", toSet.c_str(), ctx.mVarName.c_str());
#ifndef UNIT_TESTING
apr_table_set(pRequest->subprocess_env, ctx.mVarName.c_str(), toSet.c_str());
#endif
return true;
}
return false;
}
/*
* Parse the MigrateEnv objects and for each of them
* If the regex matches (in the right scope), then it sets the environment variable
*/
int enrichContext(request_rec *pRequest, const RequestInfo &rInfo) {
MigrateConf *conf = reinterpret_cast<MigrateConf *>(ap_get_module_config(pRequest->per_dir_config, &migrate_module));
if (!conf || !conf->mDirName) {
// Not a location that we treat, we decline the request
return DECLINED;
}
// No filters for this path
if (conf->mEnvLists.empty())
return 0;
int count = 0;
// Iteration through context enrichment
BOOST_FOREACH(const MigrateConf::MigrateEnv &ctx, conf->mEnvLists) {
// PATH is not supported here => use mod_rewrite directly
// URL is handled by QUERY_STRING here
if (ctx.mApplicationScope & ApplicationScope::QUERY_STRING) {
std::string toSet = boost::regex_replace(rInfo.mArgs, ctx.mMatchRegex, ctx.mSetValue, boost::match_default | boost::format_no_copy);
count += (int)setEnvVar(pRequest, ctx, toSet, count);
}
if ((ctx.mApplicationScope & ApplicationScope::BODY) && !rInfo.mBody.empty()) {
std::string toSet = regex_replace(rInfo.mBody, ctx.mMatchRegex, ctx.mSetValue, boost::match_default | boost::format_no_copy);
count += (int)setEnvVar(pRequest, ctx, toSet, count);
}
if ((ctx.mApplicationScope & ApplicationScope::HEADERS) && !rInfo.mHeader.empty()) {
std::string toSet = regex_replace(rInfo.mHeader, ctx.mMatchRegex, ctx.mSetValue, boost::match_default | boost::format_no_copy);
count += (int)setEnvVar(pRequest, ctx, toSet, count);
}
}
return count;
}
/*
* Callback to iterate over the headers tables
* Pushes a copy of key => value in a list passed without typing as the first argument
*/
static int iterateOverHeadersCallBack(void *d, const char *key, const char *value) {
std::string *headers = reinterpret_cast<std::string *>(d);
headers->append(std::string(key)+std::string(": ")+std::string(value)+"\r\n");
return 1;
}
/*
* Translate_name level HOOK
* - Read the body of a request.
* - Analyse request (body and header) with a synchroneous call on RequestProcessor::enrichContext method
* - If enrichment criteria are satisfied, the request context is enriched
* - This context can be used by mod_rewrite to redirect/modify the request
* - A RequestInfo object (containing the body) is stored in the request_config array. This object
* will be used by the inputfilter named 'inputFilterBody2Brigade' that reinjects the body to the input filters that follow him
* - A shared pointer manages the requestcontext object lifespan.
*/
int translateHook(request_rec *pRequest) {
if (!pRequest->per_dir_config)
return DECLINED;
MigrateConf *conf = reinterpret_cast<MigrateConf *>(ap_get_module_config(pRequest->per_dir_config, &migrate_module));
if (!conf || !conf->mDirName) {
// Not a location that we treat, we decline the request
return DECLINED;
}
if (!pRequest->connection->pool) {
Log::error(42, "No connection pool associated to the request");
return DECLINED;
}
if (!pRequest->connection->bucket_alloc) {
pRequest->connection->bucket_alloc = apr_bucket_alloc_create(pRequest->connection->pool);
if (!pRequest->connection->bucket_alloc) {
Log::error(42, "Request bucket allocation failed");
return DECLINED;
}
}
boost::shared_ptr<RequestInfo>* wrappedInfo = CommonModule::makeRequestInfo<RequestInfo,&migrate_module>(pRequest);
RequestInfo *info = wrappedInfo->get();
apr_bucket_brigade *bb = apr_brigade_create(pRequest->connection->pool, pRequest->connection->bucket_alloc);
if (!bb) {
Log::error(42, "[MIGRATE] Bucket brigade allocation failed");
return DECLINED;
}
std::string body;
while (!CommonModule::extractBrigadeContent(bb, pRequest->input_filters, info->mBody)){
apr_brigade_cleanup(bb);
}
apr_brigade_cleanup(bb);
// Body read :)
// Copy headers in
apr_table_do(&iterateOverHeadersCallBack, &info->mHeader, pRequest->headers_in, NULL);
// Synchronous context enrichment
info->mConf = conf;
info->mArgs = pRequest->args ? pRequest->args : "";
enrichContext(pRequest, *info);
pRequest->read_length = 0;
return DECLINED;
}
/**
* InputFilter which target is to fill the brigade passed as an argument with
* the body read in the previous hook: 'translateName'
*/
apr_status_t inputFilterBody2Brigade(ap_filter_t *pF, apr_bucket_brigade *pB, ap_input_mode_t pMode, apr_read_type_e pBlock, apr_off_t pReadbytes)
{
Log::debug("[MIGRATE] inputFilterBody2Brigade");
request_rec *pRequest = pF->r;
if (!pRequest || !pRequest->per_dir_config) {
return ap_get_brigade(pF->next, pB, pMode, pBlock, pReadbytes);
}
// Retrieve request info from context
boost::shared_ptr<RequestInfo> *shPtr = reinterpret_cast<boost::shared_ptr<RequestInfo> *>(ap_get_module_config(pRequest->request_config, &migrate_module));
if (!shPtr) {
// Happens after a rewrite on a location that we do not treat
return ap_get_brigade(pF->next, pB, pMode, pBlock, pReadbytes);
}
RequestInfo *info = shPtr->get();
if (pF->ctx != (void *) -1) {
if (!pF->ctx) {
pRequest->remaining = info->mBody.size();
}
long int read = (long int) pF->ctx;
int bSize = info->mBody.size();
int toRead = std::min((bSize - read), pReadbytes);
if (toRead > 0) {
apr_status_t st;
if ((st = apr_brigade_write(pB, NULL, NULL, info->mBody.c_str() + read, toRead)) != APR_SUCCESS ) {
Log::warn(1, "Failed to write request body in a brigade: %s", info->mBody.c_str());
return st;
}
read += toRead;
pRequest->remaining -= toRead;
}
// Request context update
if (read >= bSize) {
pF->ctx = (void *) -1;
} else {
pF->ctx = (void*)(read);
return APR_SUCCESS;
}
} else {
return ap_get_brigade(pF->next, pB, pMode, pBlock, pReadbytes);
}
return ap_get_brigade(pF->next, pB, pMode, pBlock, pReadbytes);
}
};
|
helenren/utam-java-1
|
utam-compiler/src/main/java/utam/compiler/grammar/UtamArgumentDeserializer.java
|
<reponame>helenren/utam-java-1
/*
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: MIT
* For full license text, see the LICENSE file in the repo root
* or https://opensource.org/licenses/MIT
*/
package utam.compiler.grammar;
import static utam.compiler.grammar.UtamArgument.ELEMENT_REFERENCE_TYPE_PROPERTY;
import static utam.compiler.grammar.UtamArgument.FRAME_ELEMENT_TYPE_PROPERTY;
import static utam.compiler.grammar.UtamArgument.FUNCTION_TYPE_PROPERTY;
import static utam.compiler.grammar.UtamArgument.PAGE_OBJECT_TYPE_PROPERTY;
import static utam.compiler.grammar.UtamArgument.ROOT_PAGE_OBJECT_TYPE_PROPERTY;
import static utam.compiler.grammar.UtamArgument.SELECTOR_TYPE_PROPERTY;
import static utam.compiler.helpers.TypeUtilities.PARAMETER_REFERENCE;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import utam.compiler.UtamCompilationError;
import utam.compiler.grammar.UtamArgument.UtamArgumentElementReference;
import utam.compiler.grammar.UtamArgument.UtamArgumentLiteralPrimitive;
import utam.compiler.grammar.UtamArgument.UtamArgumentLiteralSelector;
import utam.compiler.grammar.UtamArgument.UtamArgumentLiteralPageObjectType;
import utam.compiler.grammar.UtamArgument.UtamArgumentNonLiteral;
import utam.compiler.grammar.UtamArgument.UtamArgumentPredicate;
import utam.compiler.helpers.PrimitiveType;
import utam.core.framework.consumer.UtamError;
/**
* Custom deserializer for UtamArgument with purpose of parse literal objects, currently selector
* and element. Parses JSON and provides validations that are possible without getting a Page Object
* context.
*
* @author elizaveta.ivanova
* @since 232
*/
class UtamArgumentDeserializer extends
com.fasterxml.jackson.databind.JsonDeserializer<UtamArgument> {
static final Set<String> SUPPORTED_NON_LITERAL_TYPES = getSupportedJsonTypes();
private static final String SUPPORTED_TYPES_STRING = String.join(", ", getSupportedJsonTypes());
private static final String ERR_ARGS_TYPE_NOT_SUPPORTED =
"args type '%s' is not supported, supported are { " + SUPPORTED_TYPES_STRING + " }";
private static Set<String> getSupportedJsonTypes() {
Set<String> supported = Stream.of(PrimitiveType.values())
.map(PrimitiveType::getJsonTypeName)
.collect(Collectors.toSet());
supported.add(SELECTOR_TYPE_PROPERTY);
supported.add(FUNCTION_TYPE_PROPERTY);
supported.add(PARAMETER_REFERENCE.getSimpleName());
supported.add(PAGE_OBJECT_TYPE_PROPERTY);
supported.add(FRAME_ELEMENT_TYPE_PROPERTY);
supported.add(ROOT_PAGE_OBJECT_TYPE_PROPERTY);
return supported;
}
static String getUnsupportedTypeErr(String type) {
return String.format(ERR_ARGS_TYPE_NOT_SUPPORTED, type);
}
static String getErrorMessage(JsonNode node, String text) {
return "\n" + node.toPrettyString() + ": " + text;
}
@Override
public UtamArgument deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException {
ObjectMapper mapper = (ObjectMapper) parser.getCodec();
ObjectNode rootArgNode = mapper.readTree(parser);
String typeStr = rootArgNode.has("type")? rootArgNode.get("type").asText() : null;
boolean isLiteral = rootArgNode.has("value");
try {
if (FUNCTION_TYPE_PROPERTY.equals(typeStr)) {
return mapper.treeToValue(rootArgNode, UtamArgumentPredicate.class);
}
if (ELEMENT_REFERENCE_TYPE_PROPERTY.equals(typeStr)) {
return mapper.treeToValue(rootArgNode, UtamArgumentElementReference.class);
}
if (isLiteral) {
if (PAGE_OBJECT_TYPE_PROPERTY.equals(typeStr) || ROOT_PAGE_OBJECT_TYPE_PROPERTY.equals(typeStr)) {
return mapper.treeToValue(rootArgNode, UtamArgumentLiteralPageObjectType.class);
}
if (SELECTOR_TYPE_PROPERTY.equals(typeStr)) {
return mapper.treeToValue(rootArgNode, UtamArgumentLiteralSelector.class);
}
return mapper.treeToValue(rootArgNode, UtamArgumentLiteralPrimitive.class);
}
return mapper.treeToValue(rootArgNode, UtamArgumentNonLiteral.class);
} catch (IOException | UtamError e) {
throw new UtamCompilationError(getErrorMessage(rootArgNode, e.getMessage()), e);
}
}
}
|
Data4Life-Initiative/dashboard
|
src/components/dashboard/dashboardSlice.js
|
<filename>src/components/dashboard/dashboardSlice.js
import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";
export const slice = createSlice({
name: "dashboard",
initialState: {
stats: {
immunized: 0,
naturally_immune: 0,
currently_infected: 0,
},
},
reducers: {
update: (state, action) => {
state.stats = action.payload;
},
},
});
export const selectDashboardStats = (state) => {
return state.data ? state.data.dashboard.stats : {};
};
const endpoint =
"https://mydata4life-api.igrant.io/v1/data-entry/dashboard/stats/";
export const fetchDashboardStats = () => (dispatch, getState) => {
const { access_token } = getState().login;
const config = {
headers: { Authorization: `Bearer ${access_token}` },
};
axios.get(endpoint, config).then((res) => {
const { data } = res ? res.data : [];
dispatch(slice.actions.update(data));
});
};
export default slice.reducer;
|
mbauman/DemoMonkey
|
src/commands/RecolorImage.js
|
<reponame>mbauman/DemoMonkey
/**
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Command from './Command'
import UndoElement from './UndoElement'
import { v4 as uuidV4 } from 'uuid'
class RecolorImage extends Command {
constructor(search, replace) {
super()
this.search = search
this.replace = typeof replace === 'string' ? Command._getColorFromValue(replace) : false
}
isApplicableForGroup(group) {
return group === 'image' || group === '*'
}
apply(target, key = 'value') {
if (!this.replace) {
return false
}
const search = this._lookupImage(this.search)
if (this._match(target[key], search) && !target.style.filter.includes('#demomonkey-color-')) {
const original = target.style.filter
const colorId = 'demomonkey-color-' + uuidV4()
// Note: For some reason it does not work to add the SVG first and apply the filter second.
target.style.filter += `url(#${colorId})`
target.dataset.demoMonkeyId = `dmid-${uuidV4()}`
const [red, green, blue] = this.replace.rgb().color.map(v => v / 255)
const alpha = this.replace.rgb().valpha
target.parentElement.innerHTML += `<svg height="0px" width="0px"><defs><filter id="${colorId}"><feColorMatrix type="matrix" values="0 0 0 0 ${red} 0 0 0 0 ${green} 0 0 0 0 ${blue} 0 0 0 ${alpha} 0"/></filter></defs></svg>`
return new UndoElement(target.dataset.demoMonkeyId, 'style.filter', original, target.style.filter)
}
return false
}
toString() {
return this.search.toString() + '/' + this.replace.toString()
}
}
export default RecolorImage
|
haseeAmarathunga/canner
|
docs/components/ondeploy-string-editor/index.js
|
import * as React from 'react';
import {Input} from 'antd';
export default class Editor extends React.Component {
constructor(props) {
super(props);
props.onDeploy(v => {
console.log(v);
return `${v}_appendByOnDeployMethod`;
});
}
onChange = e => {
const {onChange, refId} = this.props;
onChange(refId, 'update', e.target.value)
}
render() {
const {value} = this.props;
return (
<Input
value={value}
onChange={this.onChange}
/>
);
}
}
|
DaMSL/K3
|
runtime/cpp/src/HashCollections.hpp
|
#ifndef K3_HASH_COLLECTIONS
#define K3_HASH_COLLECTIONS
#include "Hash.hpp"
#include "Common.hpp"
namespace std {
// Collections
template <class K3Collection>
size_t hash_collection(K3Collection const& b) {
size_t seed = 0;
for (auto& elem : b) {
hash_combine(seed, elem);
}
return seed;
}
template <class Elem>
struct hash<K3::Collection<Elem>> {
size_t operator()(K3::Collection<Elem> const& b) const {
return hash_collection(b);
}
};
template <class Elem>
struct hash<K3::Map<Elem>> {
size_t operator()(K3::Map<Elem> const& b) const { return hash_collection(b); }
};
template <class Elem>
struct hash<K3::Set<Elem>> {
size_t operator()(K3::Set<Elem> const& b) const { return hash_collection(b); }
};
template <class Elem>
struct hash<K3::Seq<Elem>> {
size_t operator()(K3::Seq<Elem> const& b) const { return hash_collection(b); }
};
template <class Elem>
struct hash<K3::Sorted<Elem>> {
size_t operator()(K3::Sorted<Elem> const& b) const {
return hash_collection(b);
}
};
template <class Elem>
struct hash<K3::IntMap<Elem>> {
size_t operator()(K3::IntMap<Elem> const& b) const {
return hash_collection(b);
}
};
template <class Elem>
struct hash<K3::StrMap<Elem>> {
size_t operator()(K3::StrMap<Elem> const& b) const {
return hash_collection(b);
}
};
template <class Elem>
struct hash<K3::VMap<Elem>> {
size_t operator()(K3::VMap<Elem> const& b) const {
const auto& c = b.getConstContainer();
size_t seed = 0;
for (const auto& e : b) {
hash_combine(seed, e.first);
hash_combine(seed, e.second);
}
return seed;
}
};
template <class Elem>
struct hash<K3::SortedMap<Elem>> {
size_t operator()(K3::SortedMap<Elem> const& b) const {
return hash_collection(b);
}
};
template <typename... Args>
struct hash<K3::MultiIndexBag<Args...>> {
size_t operator()(K3::MultiIndexBag<Args...> const& b) {
return hash_collection(b);
}
};
template <typename... Args>
struct hash<K3::MultiIndexMap<Args...>> {
size_t operator()(K3::MultiIndexMap<Args...> const& b) {
return hash_collection(b);
}
};
template <typename... Args>
struct hash<K3::MultiIndexVMap<Args...>> {
size_t operator()(K3::MultiIndexVMap<Args...> const& b) {
return hash_collection(b);
}
};
} // namespace std
#endif
|
yudinggood/mtx
|
mtx-admin/src/main/java/com/mtx/system/rpc/service/impl/SystemDicServiceImpl.java
|
package com.mtx.system.rpc.service.impl;
import com.mtx.common.annotation.BaseService;
import com.mtx.common.base.BaseServiceImpl;
import com.mtx.common.util.base.JsonUtil;
import com.mtx.common.util.base.StringUtil;
import com.mtx.common.util.base.ToolUtil;
import com.mtx.system.common.bean.DictCacheKit;
import com.mtx.system.common.enums.DictEnum;
import com.mtx.system.common.exception.BusinessException;
import com.mtx.system.common.exception.ErrorCodeEnum;
import com.mtx.system.dao.dto.SystemDicDto;
import com.mtx.system.dao.mapper.SystemDicMapper;
import com.mtx.system.dao.model.SystemDic;
import com.mtx.system.dao.model.SystemDicExample;
import com.mtx.system.dao.vo.SystemDicVo;
import com.mtx.system.dao.vo.Ztree;
import com.mtx.system.rpc.api.SystemDicService;
import com.mtx.system.rpc.factory.SystemDicFactory;
import com.mtx.system.rpc.mapper.SystemDicExtMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* SystemDicService实现
* Created by yu on 2018/12/9.
*/
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
@BaseService
public class SystemDicServiceImpl extends BaseServiceImpl<SystemDicMapper, SystemDic, SystemDicExample> implements SystemDicService {
private SystemDicFactory systemDicFactory=new SystemDicFactory();
@Autowired
SystemDicMapper systemDicMapper;
@Autowired
SystemDicExtMapper systemDicExtMapper;
@Override
public String selectForTree(String keywords) {
List<SystemDic> list=systemDicExtMapper.selectForTree(keywords);
List<Ztree> voList= systemDicFactory.convertList(list,Ztree.class);
String json = null;
try {
json = JsonUtil.toJson(voList);
} catch (IOException e) {
log.error(e.getMessage(),e);
}
return json;
}
@Override
public String selectForTreeList(int dicId) {
if(dicId==0){
return null;
}
List<SystemDic> list= systemDicExtMapper.selectForTreeList(dicId);
String json = null;
try {
json = JsonUtil.toJson(list);
} catch (IOException e) {
log.error(e.getMessage(),e);
}
return json;
}
@Override
public SystemDicVo selectById(int dicId) {
if(dicId==0){
return new SystemDicVo();
}
SystemDic systemDic=systemDicMapper.selectByPrimaryKey(dicId);
return systemDicFactory.convertModel(systemDic,SystemDicVo.class);
}
@Override
public int insertDto(SystemDicDto systemDicDto) {
//判断名称是否重复
SystemDicExample systemDicExample=new SystemDicExample();
SystemDicExample.Criteria criteria = systemDicExample.createCriteria();
criteria.andDicNameEqualTo(systemDicDto.getDicName());
List<SystemDic> list =systemDicMapper.selectByExample(systemDicExample);
if(!ToolUtil.isEmpty(list)){
throw new BusinessException(ErrorCodeEnum.DIC10000001);
}
//加入父字典
List<Map<String, String>> items = StringUtil.parseKeyValue(systemDicDto.getDictValues());
SystemDic systemDic = systemDicFactory.convertParent(systemDicDto);
systemDicMapper.insert(systemDic);
//批量插入子字典
List<SystemDic> subList = new ArrayList<>();
for (Map<String, String> item : items) {
SystemDic itemDict = new SystemDic();
itemDict.setDicPid(systemDic.getDicId());
itemDict.setEditDate(new Date());
itemDict.setDicName(item.get(StringUtil.MUTI_STR_VALUE));
itemDict.setDicCode(item.get(StringUtil.MUTI_STR_KEY));
subList.add(itemDict);
}
if(ToolUtil.isEmpty(subList)){
return 1;
}else {
return systemDicExtMapper.batchInsert(subList);
}
}
@Override
public List<SystemDicVo> selectByPid(int dicId) {
SystemDicExample systemDicExample=new SystemDicExample();
SystemDicExample.Criteria criteria = systemDicExample.createCriteria();
criteria.andDicPidEqualTo(dicId);
List<SystemDic> list=systemDicMapper.selectByExample(systemDicExample);
return systemDicFactory.convertListDozer(list,SystemDicVo.class);
}
@Override
public int updateDto(SystemDicDto systemDicDto) {
int count=0;
//判断名称是否重复
SystemDicExample systemDicExample=new SystemDicExample();
SystemDicExample.Criteria criteria = systemDicExample.createCriteria();
criteria.andDicNameEqualTo(systemDicDto.getDicName());
criteria.andDicIdNotEqualTo(systemDicDto.getDicId());
List<SystemDic> list =systemDicMapper.selectByExample(systemDicExample);
if(!ToolUtil.isEmpty(list)){
throw new BusinessException(ErrorCodeEnum.DIC10000001);
}
//修改父字典
SystemDic systemDic = systemDicFactory.convertParent(systemDicDto);
systemDicMapper.updateByPrimaryKeySelective(systemDic);
//先批量删除子字典,再批量添加
List<SystemDicVo> plist = selectByPid(systemDic.getDicId());
if(!ToolUtil.isEmpty(plist)){
systemDicExtMapper.batchDelete(plist);
}
List<Map<String, String>> items = StringUtil.parseKeyValue(systemDicDto.getDictValues());
List<SystemDic> subList = new ArrayList<>();
for (Map<String, String> item : items) {
SystemDic itemDict = new SystemDic();
itemDict.setDicPid(systemDic.getDicId());
itemDict.setEditDate(new Date());
itemDict.setDicName(item.get(StringUtil.MUTI_STR_VALUE));
itemDict.setDicCode(item.get(StringUtil.MUTI_STR_KEY));
subList.add(itemDict);
}
if(ToolUtil.isEmpty(subList)){
count = 1;
}else {
count = systemDicExtMapper.batchInsert(subList);
}
//刷新缓存
DictCacheKit.me().refresh(DictEnum.codeOf(systemDicDto.getDicCode()));
return count;
}
@Override
public int deleteAll(int id) {
int count=systemDicMapper.deleteByPrimaryKey(id);
List<SystemDicVo> plist = selectByPid(id);
if(!ToolUtil.isEmpty(plist)){
systemDicExtMapper.batchDelete(plist);
}
return count;
}
}
|
hannahrogers-google/google-cloud-java
|
google-api-grpc/proto-google-cloud-datalabeling-v1beta1/src/main/java/com/google/cloud/datalabeling/v1beta1/LabelTextClassificationOperationMetadataOrBuilder.java
|
<reponame>hannahrogers-google/google-cloud-java
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/datalabeling/v1beta1/operations.proto
package com.google.cloud.datalabeling.v1beta1;
public interface LabelTextClassificationOperationMetadataOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.datalabeling.v1beta1.LabelTextClassificationOperationMetadata)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Basic human annotation config used in labeling request.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basic_config = 1;</code>
*/
boolean hasBasicConfig();
/**
*
*
* <pre>
* Basic human annotation config used in labeling request.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basic_config = 1;</code>
*/
com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig getBasicConfig();
/**
*
*
* <pre>
* Basic human annotation config used in labeling request.
* </pre>
*
* <code>.google.cloud.datalabeling.v1beta1.HumanAnnotationConfig basic_config = 1;</code>
*/
com.google.cloud.datalabeling.v1beta1.HumanAnnotationConfigOrBuilder getBasicConfigOrBuilder();
}
|
phatblat/macOSPrivateFrameworks
|
PrivateFrameworks/Safari/CreditCardDataController.h
|
<filename>PrivateFrameworks/Safari/CreditCardDataController.h
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "WBSCreditCardDataController.h"
__attribute__((visibility("hidden")))
@interface CreditCardDataController : WBSCreditCardDataController
{
}
+ (id)shared;
- (unsigned long long)virtualCardFieldsToRequest;
- (void)_offerToSaveCreditCardData:(id)arg1 submittedToFrameInBrowserViewController:(id)arg2 fromFrameInBrowserViewController:(id)arg3 finishedSavingFormDataBlock:(CDUnknownBlockType)arg4;
- (void)_userDidSelectNeverSaveForCardData:(id)arg1;
- (void)_userDidSelectSaveForCardData:(id)arg1;
- (void)willSubmitFormContainingCreditCardData:(id)arg1 toFrame:(const struct Frame *)arg2 fromFrame:(const struct Frame *)arg3 finishedSavingFormDataHandler:(struct ScopeExitHandler *)arg4;
- (void)creditCardDataDidChange;
@end
|
antoniogsjunior/react_boilerplate
|
src/views/home/pages/home.js
|
<gh_stars>0
import React from 'react'
import Body from 'components/dashboard/body'
import PropTypes from 'prop-types'
function Home ({ title, history }) {
return (
<Body history={history} title={title}>
<h3>Home</h3>
</Body>
)
}
Home.propTypes = {
title: PropTypes.string.isRequired,
history: PropTypes.object.isRequired
}
export default Home
|
ozayats/CarMissionReact
|
controllers/features.js
|
<gh_stars>0
const Feature = require("../models/Feature");
const queryCreator = require("../commonHelpers/queryCreator");
const _ = require("lodash");
const {
updateS3Credentials,
upload,
} = require("../commonHelpers/amazon-s3-upload");
const uploadS3 = upload("about-us");
exports.addFeature = (req, res, next) => {
const newFeature = new Feature(req.body);
newFeature
.save()
.then((data) => res.json(data))
.catch((err) =>
res.status(400).json({
message: `Error happened on server: "${err}" `,
})
);
};
exports.getFeatures = (req, res, next) => {
Feature.find()
.then((data) => res.send(data))
.catch((err) =>
res.status(400).json({
message: `Error happened on server: "${err}" `,
})
);
};
exports.updateFeature = (req, res, next) => {
Feature.findOne({ _id: req.params.id })
.then((feature) => {
if (!feature) {
return res.status(400).json({
message: `Feature with _id "${req.params.id}" is not found.`,
});
} else {
const featureData = _.cloneDeep(req.body);
const updatedFeature = queryCreator(featureData);
Feature.findOneAndUpdate(
{ _id: req.params.id },
{ $set: updatedFeature },
{ new: true }
)
.then((feature) => res.json(feature))
.catch((err) =>
res.status(400).json({
message: `Error happened on server: "${err}" `,
})
);
}
})
.catch((err) =>
res.status(400).json({
message: `Error happened on server: "${err}" `,
})
);
};
exports.deleteFeature = (req, res, next) => {
Feature.findOne({ _id: req.params.id }).then(async (feature) => {
if (!feature) {
return res.status(400).json({
message: `Feature with id "${req.params.id}" is not found.`,
});
} else {
const featureToDelete = await Feature.findOne({
_id: req.params.id,
});
Feature.deleteOne({ _id: req.params.id })
.then((deletedCount) =>
res.status(200).json({
message: `Feature with id "${featureToDelete._id}" is successfully deletes from DB.`,
deletedFeatureInfo: featureToDelete,
})
)
.catch((err) =>
res.status(400).json({
message: `Error happened on server: "${err}" `,
})
);
}
});
};
exports.uploadFeatureImg = async (req, res, next) => {
await updateS3Credentials();
const { id } = req.params;
uploadS3(req, res, (error) => {
if (error) {
res.status(400).json({
message: `Error happened on server: "${error}" `,
});
} else {
// If File not found
if (!req.file) {
res.status(400).json({ message: "No File Selected" });
} else {
// If Success
const imageName = req.file.key;
const imageLocation = req.file.location;
Feature.findOne({ _id: id }).then(async (stage) => {
if (!stage) {
return res.status(400).json({
message: `Feature with id "${id}" is not found.`,
});
} else {
Feature.findOneAndUpdate(
{ _id: id },
{ $set: { imgPath: imageLocation } },
{ new: true }
)
.then(() =>
res.json({
image: imageName,
location: imageLocation,
})
)
.catch((err) =>
res.status(400).json({
message: `Error happened on server: "${err}" `,
})
);
}
});
}
}
});
};
|
bartwe/Colore
|
docs/search/enums_6.js
|
<gh_stars>0
var searchData=
[
['implicitusekindflags',['ImplicitUseKindFlags',['../_annotations_8cs.html#acc26806cec0b003502b38c6c2ee67fd1',1,'Annotations.cs']]],
['implicitusetargetflags',['ImplicitUseTargetFlags',['../_annotations_8cs.html#a59f21202ead30f3d1e2093e42214bf7c',1,'Annotations.cs']]]
];
|
GheisMohammadi/CppCommon
|
include/threads/wait_batcher.inl
|
<gh_stars>100-1000
/*!
\file wait_batcher.inl
\brief Multiple producers / multiple consumers wait batcher inline implementation
\author <NAME>
\date 13.03.2019
\copyright MIT License
*/
namespace CppCommon {
template<typename T>
inline WaitBatcher<T>::WaitBatcher(size_t capacity, size_t initial) : _closed(false), _capacity(capacity)
{
_batch.reserve(initial);
}
template<typename T>
inline WaitBatcher<T>::~WaitBatcher()
{
Close();
}
template<typename T>
inline bool WaitBatcher<T>::closed() const
{
Locker<CriticalSection> locker(_cs);
return _closed;
}
template<typename T>
inline size_t WaitBatcher<T>::capacity() const
{
if (_capacity > 0)
return _capacity;
Locker<CriticalSection> locker(_cs);
return _batch.capacity();
}
template<typename T>
inline size_t WaitBatcher<T>::size() const
{
Locker<CriticalSection> locker(_cs);
return _batch.size();
}
template<typename T>
inline bool WaitBatcher<T>::Enqueue(const T& item)
{
Locker<CriticalSection> locker(_cs);
if (_closed)
return false;
do
{
if ((_capacity == 0) || (_batch.size() < _capacity))
{
_batch.push_back(item);
_cv1.NotifyOne();
return true;
}
_cv2.Wait(_cs, [this]() { return (_closed || (_capacity == 0) || (_batch.size() < _capacity)); });
} while (!_closed);
return false;
}
template<typename T>
inline bool WaitBatcher<T>::Enqueue(T&& item)
{
Locker<CriticalSection> locker(_cs);
if (_closed)
return false;
do
{
if ((_capacity == 0) || (_batch.size() < _capacity))
{
_batch.emplace_back(item);
_cv1.NotifyOne();
return true;
}
_cv2.Wait(_cs, [this]() { return (_closed || (_capacity == 0) || (_batch.size() < _capacity)); });
} while (!_closed);
return false;
}
template<typename T>
template <class InputIterator>
inline bool WaitBatcher<T>::Enqueue(InputIterator first, InputIterator last)
{
Locker<CriticalSection> locker(_cs);
if (_closed)
return false;
do
{
if ((_capacity == 0) || (_batch.size() < _capacity))
{
_batch.insert(_batch.end(), first, last);
_cv1.NotifyOne();
return true;
}
_cv2.Wait(_cs, [this]() { return (_closed || (_capacity == 0) || (_batch.size() < _capacity)); });
} while (!_closed);
return false;
}
template<typename T>
inline bool WaitBatcher<T>::Dequeue(std::vector<T>& items)
{
// Clear the result items vector
items.clear();
Locker<CriticalSection> locker(_cs);
if (_closed && _batch.empty())
return false;
do
{
if (!_batch.empty())
{
// Swap batch items
std::swap(_batch, items);
_cv2.NotifyOne();
return true;
}
_cv1.Wait(_cs, [this]() { return (_closed || !_batch.empty()); });
} while (!_closed || !_batch.empty());
return false;
}
template<typename T>
inline void WaitBatcher<T>::Close()
{
Locker<CriticalSection> locker(_cs);
_closed = true;
_cv1.NotifyAll();
_cv2.NotifyAll();
}
} // namespace CppCommon
|
eduardolm/orange-talents-01-template-proposta
|
src/main/java/br/com/zup/proposta/repository/BlockedRepository.java
|
<gh_stars>0
package br.com.zup.proposta.repository;
import br.com.zup.proposta.model.Blocked;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BlockedRepository extends JpaRepository<Blocked, Long> {
}
|
ploki/aws-sdk-cpp
|
aws-cpp-sdk-glue/include/aws/glue/model/UserDefinedFunctionInput.h
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#pragma once
#include <aws/glue/Glue_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/glue/model/PrincipalType.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/glue/model/ResourceUri.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace Glue
{
namespace Model
{
/**
* <p>A structure used to create or updata a user-defined function.</p><p><h3>See
* Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/UserDefinedFunctionInput">AWS
* API Reference</a></p>
*/
class AWS_GLUE_API UserDefinedFunctionInput
{
public:
UserDefinedFunctionInput();
UserDefinedFunctionInput(Aws::Utils::Json::JsonView jsonValue);
UserDefinedFunctionInput& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The name of the function.</p>
*/
inline const Aws::String& GetFunctionName() const{ return m_functionName; }
/**
* <p>The name of the function.</p>
*/
inline void SetFunctionName(const Aws::String& value) { m_functionNameHasBeenSet = true; m_functionName = value; }
/**
* <p>The name of the function.</p>
*/
inline void SetFunctionName(Aws::String&& value) { m_functionNameHasBeenSet = true; m_functionName = std::move(value); }
/**
* <p>The name of the function.</p>
*/
inline void SetFunctionName(const char* value) { m_functionNameHasBeenSet = true; m_functionName.assign(value); }
/**
* <p>The name of the function.</p>
*/
inline UserDefinedFunctionInput& WithFunctionName(const Aws::String& value) { SetFunctionName(value); return *this;}
/**
* <p>The name of the function.</p>
*/
inline UserDefinedFunctionInput& WithFunctionName(Aws::String&& value) { SetFunctionName(std::move(value)); return *this;}
/**
* <p>The name of the function.</p>
*/
inline UserDefinedFunctionInput& WithFunctionName(const char* value) { SetFunctionName(value); return *this;}
/**
* <p>The Java class that contains the function code.</p>
*/
inline const Aws::String& GetClassName() const{ return m_className; }
/**
* <p>The Java class that contains the function code.</p>
*/
inline void SetClassName(const Aws::String& value) { m_classNameHasBeenSet = true; m_className = value; }
/**
* <p>The Java class that contains the function code.</p>
*/
inline void SetClassName(Aws::String&& value) { m_classNameHasBeenSet = true; m_className = std::move(value); }
/**
* <p>The Java class that contains the function code.</p>
*/
inline void SetClassName(const char* value) { m_classNameHasBeenSet = true; m_className.assign(value); }
/**
* <p>The Java class that contains the function code.</p>
*/
inline UserDefinedFunctionInput& WithClassName(const Aws::String& value) { SetClassName(value); return *this;}
/**
* <p>The Java class that contains the function code.</p>
*/
inline UserDefinedFunctionInput& WithClassName(Aws::String&& value) { SetClassName(std::move(value)); return *this;}
/**
* <p>The Java class that contains the function code.</p>
*/
inline UserDefinedFunctionInput& WithClassName(const char* value) { SetClassName(value); return *this;}
/**
* <p>The owner of the function.</p>
*/
inline const Aws::String& GetOwnerName() const{ return m_ownerName; }
/**
* <p>The owner of the function.</p>
*/
inline void SetOwnerName(const Aws::String& value) { m_ownerNameHasBeenSet = true; m_ownerName = value; }
/**
* <p>The owner of the function.</p>
*/
inline void SetOwnerName(Aws::String&& value) { m_ownerNameHasBeenSet = true; m_ownerName = std::move(value); }
/**
* <p>The owner of the function.</p>
*/
inline void SetOwnerName(const char* value) { m_ownerNameHasBeenSet = true; m_ownerName.assign(value); }
/**
* <p>The owner of the function.</p>
*/
inline UserDefinedFunctionInput& WithOwnerName(const Aws::String& value) { SetOwnerName(value); return *this;}
/**
* <p>The owner of the function.</p>
*/
inline UserDefinedFunctionInput& WithOwnerName(Aws::String&& value) { SetOwnerName(std::move(value)); return *this;}
/**
* <p>The owner of the function.</p>
*/
inline UserDefinedFunctionInput& WithOwnerName(const char* value) { SetOwnerName(value); return *this;}
/**
* <p>The owner type.</p>
*/
inline const PrincipalType& GetOwnerType() const{ return m_ownerType; }
/**
* <p>The owner type.</p>
*/
inline void SetOwnerType(const PrincipalType& value) { m_ownerTypeHasBeenSet = true; m_ownerType = value; }
/**
* <p>The owner type.</p>
*/
inline void SetOwnerType(PrincipalType&& value) { m_ownerTypeHasBeenSet = true; m_ownerType = std::move(value); }
/**
* <p>The owner type.</p>
*/
inline UserDefinedFunctionInput& WithOwnerType(const PrincipalType& value) { SetOwnerType(value); return *this;}
/**
* <p>The owner type.</p>
*/
inline UserDefinedFunctionInput& WithOwnerType(PrincipalType&& value) { SetOwnerType(std::move(value)); return *this;}
/**
* <p>The resource URIs for the function.</p>
*/
inline const Aws::Vector<ResourceUri>& GetResourceUris() const{ return m_resourceUris; }
/**
* <p>The resource URIs for the function.</p>
*/
inline void SetResourceUris(const Aws::Vector<ResourceUri>& value) { m_resourceUrisHasBeenSet = true; m_resourceUris = value; }
/**
* <p>The resource URIs for the function.</p>
*/
inline void SetResourceUris(Aws::Vector<ResourceUri>&& value) { m_resourceUrisHasBeenSet = true; m_resourceUris = std::move(value); }
/**
* <p>The resource URIs for the function.</p>
*/
inline UserDefinedFunctionInput& WithResourceUris(const Aws::Vector<ResourceUri>& value) { SetResourceUris(value); return *this;}
/**
* <p>The resource URIs for the function.</p>
*/
inline UserDefinedFunctionInput& WithResourceUris(Aws::Vector<ResourceUri>&& value) { SetResourceUris(std::move(value)); return *this;}
/**
* <p>The resource URIs for the function.</p>
*/
inline UserDefinedFunctionInput& AddResourceUris(const ResourceUri& value) { m_resourceUrisHasBeenSet = true; m_resourceUris.push_back(value); return *this; }
/**
* <p>The resource URIs for the function.</p>
*/
inline UserDefinedFunctionInput& AddResourceUris(ResourceUri&& value) { m_resourceUrisHasBeenSet = true; m_resourceUris.push_back(std::move(value)); return *this; }
private:
Aws::String m_functionName;
bool m_functionNameHasBeenSet;
Aws::String m_className;
bool m_classNameHasBeenSet;
Aws::String m_ownerName;
bool m_ownerNameHasBeenSet;
PrincipalType m_ownerType;
bool m_ownerTypeHasBeenSet;
Aws::Vector<ResourceUri> m_resourceUris;
bool m_resourceUrisHasBeenSet;
};
} // namespace Model
} // namespace Glue
} // namespace Aws
|
jgchenu/react-and-redux-practice
|
src/todos/actions.js
|
import { ADD_TODO, REMOVE_TODO, TOGGLE_TODO } from './actionTypes';
let todoId = 0;
export const addTodo = (text) => ({
type: ADD_TODO,
payload: {
text,
id: todoId++,
completed: false
}
})
export const removeTodo = (id) => ({
type: REMOVE_TODO,
payload: {
id
}
})
export const toggleTodo = (id) => ({
type: TOGGLE_TODO,
payload: {
id,
}
})
|
jjmartinr01/gauss3
|
reuniones/urls.py
|
# -*- coding: utf-8 -*-
from django.urls import path
from . import views
urlpatterns = [
path('conv_template/', views.conv_template),
path('conv_template_ajax/', views.conv_template_ajax),
path('conv_reunion/', views.conv_reunion),
path('conv_reunion_ajax/', views.conv_reunion_ajax),
path('redactar_actas_reunion/', views.redactar_actas_reunion),
path('redactar_actas_reunion_ajax/', views.redactar_actas_reunion_ajax),
path('lectura_actas_reunion/', views.lectura_actas_reunion),
path('control_asistencia_reunion/', views.control_asistencia_reunion),
path('firmar_acta_reunion/', views.firmar_acta_reunion),
]
|
mmg-3/OpenOLAT
|
src/main/java/org/olat/modules/appointments/ui/FindingConfirmationController.java
|
/**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.modules.appointments.ui;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.olat.basesecurity.BaseSecurityManager;
import org.olat.basesecurity.BaseSecurityModule;
import org.olat.basesecurity.GroupRoles;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.form.flexible.FormItemContainer;
import org.olat.core.gui.components.form.flexible.elements.FlexiTableElement;
import org.olat.core.gui.components.form.flexible.impl.FormBasicController;
import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer;
import org.olat.core.gui.components.form.flexible.impl.elements.table.DefaultFlexiColumnModel;
import org.olat.core.gui.components.form.flexible.impl.elements.table.FlexiTableColumnModel;
import org.olat.core.gui.components.form.flexible.impl.elements.table.FlexiTableDataModelFactory;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.Event;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.id.Identity;
import org.olat.modules.appointments.Appointment;
import org.olat.modules.appointments.AppointmentSearchParams;
import org.olat.modules.appointments.AppointmentsService;
import org.olat.modules.appointments.Participation;
import org.olat.modules.appointments.ParticipationSearchParams;
import org.olat.modules.appointments.Topic;
import org.olat.repository.RepositoryEntry;
import org.olat.repository.RepositoryEntryRelationType;
import org.olat.repository.RepositoryService;
import org.olat.user.UserManager;
import org.olat.user.UserPropertiesRow;
import org.olat.user.propertyhandlers.UserPropertyHandler;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* Initial date: 25 Jun 2020<br>
* @author uhensler, <EMAIL>, http://www.frentix.com
*
*/
public class FindingConfirmationController extends FormBasicController {
private static final String usageIdentifyer = UserRestrictionTableModel.class.getCanonicalName();
private UserRestrictionTableModel usersTableModel;
private FlexiTableElement usersTableEl;
private final Appointment appointment;
private final Topic topic;
private final RepositoryEntry entry;
private final List<UserPropertyHandler> userPropertyHandlers;
private List<Participation> participations;
private List<Long> participationIdentityKeys;
@Autowired
private AppointmentsService appointmentsService;
@Autowired
private RepositoryService repositoryService;
@Autowired
private BaseSecurityManager securityManager;
@Autowired
private BaseSecurityModule securityModule;
@Autowired
private UserManager userManager;
public FindingConfirmationController(UserRequest ureq, WindowControl wControl, Appointment appointment) {
super(ureq, wControl, "finding_confirmation");
setTranslator(userManager.getPropertyHandlerTranslator(getTranslator()));
this.appointment = appointment;
this.topic = appointment.getTopic();
this.entry = topic.getEntry();
boolean isAdministrativeUser = securityModule.isUserAllowedAdminProps(ureq.getUserSession().getRoles());
userPropertyHandlers = userManager.getUserPropertyHandlersFor(usageIdentifyer, isAdministrativeUser);
initForm(ureq);
loadModel();
}
@Override
protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) {
setFormInfo("finding.confirmation.info");
if (appointment.getBBBMeeting() != null) {
flc.contextPut("meeting", Boolean.TRUE);
}
FlexiTableColumnModel columnsModel = FlexiTableDataModelFactory.createFlexiTableColumnModel();
int colIndex = UserRestrictionTableModel.USER_PROPS_OFFSET;
for (int i = 0; i < userPropertyHandlers.size(); i++) {
UserPropertyHandler userPropertyHandler = userPropertyHandlers.get(i);
boolean visible = userManager.isMandatoryUserProperty(usageIdentifyer , userPropertyHandler);
columnsModel.addFlexiColumnModel(new DefaultFlexiColumnModel(visible, userPropertyHandler.i18nColumnDescriptorLabelKey(), colIndex, null, true, "userProp-" + colIndex));
colIndex++;
}
usersTableModel = new UserRestrictionTableModel(columnsModel, getLocale());
usersTableEl = uifactory.addTableElement(getWindowControl(), "users", usersTableModel, 20, false, getTranslator(), formLayout);
usersTableEl.setAndLoadPersistedPreferences(ureq, "finding.confirmation.v2");
usersTableEl.setEmtpyTableMessageKey("finding.confirmation.empty.table");
usersTableEl.setSelectAllEnable(true);
usersTableEl.setMultiSelect(true);
FormLayoutContainer buttonCont = FormLayoutContainer.createButtonLayout("buttons", getTranslator());
buttonCont.setRootForm(mainForm);
formLayout.add(buttonCont);
uifactory.addFormSubmitButton("save", buttonCont);
uifactory.addFormCancelButton("cancel", buttonCont, ureq, getWindowControl());
}
private void loadModel() {
boolean groupRestrictions = appointmentsService.hasGroupRestrictions(topic);
List<Identity> restrictedIdentities = groupRestrictions
? appointmentsService.getRestrictionMembers(topic)
: repositoryService.getMembers(entry, RepositoryEntryRelationType.all, GroupRoles.participant.name());
ParticipationSearchParams params = new ParticipationSearchParams();
params.setAppointment(appointment);
params.setFetchIdentities(true);
params.setFetchUser(true);
participations = appointmentsService.getParticipations(params);
List<Identity> participationIdentities = new ArrayList<>(participations.size());
participationIdentityKeys = new ArrayList<>(participations.size());
for (Participation participation : participations) {
Identity identity = participation.getIdentity();
participationIdentities.add(identity);
participationIdentityKeys.add(identity.getKey());
}
Set<Identity> allIdentities = new HashSet<>();
allIdentities.addAll(participationIdentities);
allIdentities.addAll(restrictedIdentities);
List<UserPropertiesRow> rows = new ArrayList<>(allIdentities.size());
for (Identity identity : allIdentities) {
rows.add(new UserPropertiesRow(identity, userPropertyHandlers, getLocale()));
}
usersTableModel.setObjects(rows);
usersTableEl.reset(true, true, true);
Set<Integer> selectedRows = new HashSet<>();
for(int i=usersTableModel.getRowCount(); i--> 0; ) {
UserPropertiesRow row = usersTableModel.getObject(i);
if(participationIdentityKeys.contains(row.getIdentityKey())) {
selectedRows.add(Integer.valueOf(i));
}
}
usersTableEl.setMultiSelectedIndex(selectedRows);
}
@Override
protected boolean validateFormLogic(UserRequest ureq) {
boolean allOk = super.validateFormLogic(ureq);
usersTableEl.clearError();
if (appointment.getBBBMeeting() != null) {
AppointmentSearchParams params = new AppointmentSearchParams();
params.setAppointment(appointment);
params.setFetchMeetings(true);
List<Appointment> appointments = appointmentsService.getAppointments(params);
if (!appointments.isEmpty()) {
Integer maxMeetingParticipants = appointments.get(0).getBBBMeeting().getTemplate().getMaxParticipants();
if (maxMeetingParticipants.intValue() < usersTableEl.getMultiSelectedIndex().size()) {
usersTableEl.setErrorKey("error.selected.identities.greater.room", new String[] {maxMeetingParticipants.toString()});
allOk &= false;
}
}
}
return allOk;
}
@Override
protected void formCancelled(UserRequest ureq) {
fireEvent(ureq, Event.CANCELLED_EVENT);
}
@Override
protected void formOK(UserRequest ureq) {
Set<Integer> index = usersTableEl.getMultiSelectedIndex();
List<Long> selectedIdentityKeys = new ArrayList<>(index.size());
for (Integer i : index) {
UserPropertiesRow row = usersTableModel.getObject(i.intValue());
selectedIdentityKeys.add(row.getIdentityKey());
}
Collection<Long> addedIdentityKeys = new ArrayList<>();
for (Long selectedKey : selectedIdentityKeys) {
if (!participationIdentityKeys.contains(selectedKey)) {
addedIdentityKeys.add(selectedKey);
}
}
Collection<Identity> identities = securityManager.loadIdentityByKeys(addedIdentityKeys);
appointmentsService.createParticipations(appointment, identities, getIdentity(), topic.isMultiParticipation(),
topic.isAutoConfirmation(), false);
List<Participation> unselectedParticipations = new ArrayList<>();
for (Participation participation : participations) {
Long identityKey = participation.getIdentity().getKey();
if (!selectedIdentityKeys.contains(identityKey)) {
unselectedParticipations.add(participation);
}
}
appointmentsService.deleteParticipations(unselectedParticipations, false);
appointmentsService.confirmAppointment(appointment);
fireEvent(ureq, Event.DONE_EVENT);
}
@Override
protected void doDispose() {
//
}
}
|
wandns/axl
|
include/axl_lua_Pch.h
|
<reponame>wandns/axl
#include <axl_lua/axl_lua_Pch.h>
|
rajeshGavvala-reThink/radien-ce
|
rd-api/src/main/java/io/radien/api/service/ecm/model/Content.java
|
/*
* Copyright (c) 2006-present openappframe.org & its legal owners. All rights reserved.
* <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 io.radien.api.service.ecm.model;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
/**
* Simple implementation of an Enterprise Content Manager
*
* @author <NAME>
*/
@JsonDeserialize(as = Content.class)
public class Content extends AbstractECMModel implements EnterpriseContent {
private static final long serialVersionUID = -4081831237381066985L;
/**
* ECM Content constructor
* @param title of the content
* @param htmlContent path for the content description
*/
public Content(String title, String htmlContent) {
this.name = title;
this.htmlContent = htmlContent;
this.contentType = ContentType.HTML;
}
/**
* Compares this object with the specified object for order. Returns a negative integer,
* zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
* @param o the object to be compared.
* @return a negative integer, zero, or a positive integer as this object is less than,
* equal to, or greater than the specified object.
*/
@Override
public int compareTo(EnterpriseContent o) {
return this.getName().compareTo(o.getName());
}
/**
* This object (which is already a string!) is itself returned.
* @return the string itself.
*/
@Override
public String toString() {
return name;
}
}
|
michaelneu/gorillamail
|
src/main/java/com/ecorp/gorillamail/entities/Variable.java
|
package com.ecorp.gorillamail.entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@NoArgsConstructor
@AllArgsConstructor
@Embeddable
@Table( name = "Variables" )
public class Variable implements Serializable {
private static final long serialVersionUID = 0L;
@Column( nullable = false )
@Getter
@Setter
private String name;
@Column( nullable = false )
@Getter
@Setter
private String value;
}
|
trobol/redmine_git_hosting
|
app/controllers/gitolite_public_keys_controller.rb
|
# frozen_string_literal: true
class GitolitePublicKeysController < ApplicationController
include RedmineGitHosting::GitoliteAccessor::Methods
before_action :require_login
before_action :find_user
before_action :find_gitolite_public_key, only: [:destroy]
helper :gitolite_public_keys
helper :git_hosting
def index
@gitolite_user_keys = @user.gitolite_public_keys.user_key.sorted
@gitolite_deploy_keys = @user.gitolite_public_keys.deploy_key.sorted
end
def create
if params[:create_button]
@gitolite_public_key = @user.gitolite_public_keys.new
@gitolite_public_key.safe_attributes = params[:gitolite_public_key]
if @gitolite_public_key.save
create_ssh_key @gitolite_public_key
flash[:notice] = l :notice_public_key_created, title: view_context.keylabel(@gitolite_public_key)
else
flash[:error] = @gitolite_public_key.errors.full_messages.to_sentence
end
redirect_to @redirect_url
else
redirect_to @cancel_url
end
end
def destroy
return unless request.delete?
if @gitolite_public_key.user == @user || @user.admin?
if @gitolite_public_key.destroy
destroy_ssh_key @gitolite_public_key
flash[:notice] = l :notice_public_key_deleted, title: view_context.keylabel(@gitolite_public_key)
end
redirect_to @redirect_url
else
render_403
end
end
private
def find_user
if params[:user_id]
set_user_from_params
else
set_user_from_current_user
end
end
def set_user_from_params
@user = params[:user_id] == 'current' ? User.current : User.find_by(id: params[:user_id])
if @user
@cancel_url = @redirect_url = url_for controller: 'users', action: 'edit', id: params[:user_id], tab: 'keys'
else
render_404
end
end
def set_user_from_current_user
if User.current.allowed_to_create_ssh_keys?
@user = User.current
@redirect_url = url_for controller: 'gitolite_public_keys', action: 'index'
@cancel_url = url_for controller: 'my', action: 'account'
else
render_403
end
end
def find_gitolite_public_key
@gitolite_public_key = @user.gitolite_public_keys.find params[:id]
rescue ActiveRecord::RecordNotFound
render_404
end
def create_ssh_key(ssh_key)
gitolite_accessor.create_ssh_key ssh_key
end
def destroy_ssh_key(ssh_key)
gitolite_accessor.destroy_ssh_key ssh_key
end
end
|
koordinates/react-redux-grid
|
dist/util/getData.js
|
<filename>dist/util/getData.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.nameFromDataIndex = exports.getValueFromDataIndexArr = exports.setDataAtDataIndex = exports.getRowKey = exports.setKeysInData = exports.getData = undefined;
var _immutable = require('immutable');
var _camelize = require('./camelize');
var getData = exports.getData = function getData() {
var row = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new _immutable.Map();
var columns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var colIndex = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var editorValues = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
if (!row.get) {
row = (0, _immutable.fromJS)(row);
}
var column = columns[colIndex];
if (!column) {
return undefined;
}
var dataIndex = column.dataIndex || null;
if (!dataIndex) {
throw new Error('No dataIndex found on column', column);
}
if (editorValues && editorValues.get && editorValues.get(dataIndex) !== undefined) {
return editorValues.get(dataIndex);
}
if (typeof dataIndex === 'string') {
var val = row && row.get && row.get(dataIndex) !== undefined ? row.get(dataIndex) : null;
return val && val.toJS ? val.toJS() : val;
} else if (Array.isArray(dataIndex)) {
var _val = getValueFromDataIndexArr(row, dataIndex);
return _val && _val.toJS ? _val.toJS() : _val;
}
};
var setKeysInData = exports.setKeysInData = function setKeysInData(data) {
if (_immutable.List.isList(data)) {
if (data.getIn([0, '_key'])) {
return data;
}
return data.map(function (item, i) {
return item.set('_key', 'row-' + i);
});
}
if (!data || !Array.isArray(data)) {
return (0, _immutable.List)([]);
}
if (data[0] && data[0]._key === undefined) {
data.forEach(function (row, i) {
row._key = 'row-' + i;
});
}
return (0, _immutable.fromJS)(data);
};
var getRowKey = exports.getRowKey = function getRowKey(columns, rowValues, suffix) {
var uniqueCol = columns.filter(function (col) {
return col.createKeyFrom;
});
var val = rowValues.get('_key');
if (uniqueCol.length > 1) {
throw new Error('Only one column can declare createKeyFrom');
}
if (uniqueCol.length > 0) {
var dataIndex = nameFromDataIndex(uniqueCol[0]);
val = rowValues && rowValues.get(dataIndex) ? rowValues.get(dataIndex) : rowValues.get('_key');
}
if (suffix) {
val = val + '-' + suffix;
}
return val;
};
var setDataAtDataIndex = exports.setDataAtDataIndex = function setDataAtDataIndex(row, dataIndex, val) {
if (!row.toJS) {
row = (0, _immutable.fromJS)(row);
}
if (typeof dataIndex === 'string') {
return row.set(dataIndex, val);
}
if (row.getIn(dataIndex)) {
return row.setIn(dataIndex, val);
}
throw new Error('Invalid key path');
};
var getValueFromDataIndexArr = exports.getValueFromDataIndexArr = function getValueFromDataIndexArr(row, dataIndex) {
var val = row.getIn(dataIndex);
return val !== undefined ? val : '';
};
var nameFromDataIndex = exports.nameFromDataIndex = function nameFromDataIndex(column) {
if (!column) {
return '';
}
if (typeof column.dataIndex === 'string') {
return column.dataIndex;
}
if (Array.isArray(column.dataIndex)) {
return column.dataIndex[column.dataIndex.length - 1];
}
if (!column.dataIndex) {
return (0, _camelize.camelize)(column.name);
}
};
;
var _temp = function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}
__REACT_HOT_LOADER__.register(getData, 'getData', 'src/util/getData.js');
__REACT_HOT_LOADER__.register(setKeysInData, 'setKeysInData', 'src/util/getData.js');
__REACT_HOT_LOADER__.register(getRowKey, 'getRowKey', 'src/util/getData.js');
__REACT_HOT_LOADER__.register(setDataAtDataIndex, 'setDataAtDataIndex', 'src/util/getData.js');
__REACT_HOT_LOADER__.register(getValueFromDataIndexArr, 'getValueFromDataIndexArr', 'src/util/getData.js');
__REACT_HOT_LOADER__.register(nameFromDataIndex, 'nameFromDataIndex', 'src/util/getData.js');
}();
;
|
tadvi/uva
|
UVa 11219 how old are you/sample/11219 - How old are you.cpp
|
<filename>UVa 11219 how old are you/sample/11219 - How old are you.cpp
#include <stdio.h>
int main() {
int t, test = 0;
scanf("%d", &t);
while(t--) {
int age, a, b, c, e, f, g;
scanf("%d/%d/%d", &a, &b, &c);
scanf("%d/%d/%d", &e, &f, &g);
age = c-g;
if(f > b) age--;
if(f == b && e > a) age--;
printf("Case #%d: ", ++test);
if(age < 0)
puts("Invalid birth date");
else if(age > 130)
puts("Check birth date");
else
printf("%d\n", age);
}
return 0;
}
|
Roopesh2/C.js
|
src/c.js
|
<reponame>Roopesh2/C.js<gh_stars>1-10
export { defineProperties } from "./utils.js";
export * from "./settings.js";
export { C } from "./main.js";
export * from "./constants/math.js";
export * from "./constants/drawing.js";
export * from "./constants/color_palettes.js";
export * from "./color/gradients.js";
export * from "./color/random.js";
export * from "./color/color_reader.js";
export * from "./color/interpolation.js";
export * from "./color/color_converters.js";
export * from "./image/image.js";
export * from "./image/processing.js";
export * from "./objects/tex.js";
export * from "./objects/text.js";
export * from "./objects/braces.js";
export * from "./objects/arrows.js";
export * from "./objects/geometry.js";
export * from "./objects/functions.js";
export * from "./objects/coordinate_systems.js";
export * from "./objects/more_shapes.js";
export * from "./math/functions.js";
export * from "./math/points.js";
export * from "./math/random.js";
export * from "./math/aritmetics.js";
export * from "./math/rate_functions.js";
//! Experimental features
export * from "./WebGL/webgl.js";
export * from "./WebGL/settings.js";
|
zhy0313/temptation
|
web/actions/global.js
|
<gh_stars>1-10
export const SET_TITLE = 'SET_TITLE'
export function setTitle(title) {
return {
type: SET_TITLE,
title,
}
}
/*
侧滑菜单
*/
export const OPEN_SIDE_MENU = 'OPEN_SIDE_MENU'
export const CLOSE_SIDE_MENU = 'CLOSE_SIDE_MENU'
export function toggleSideMenu(flag) {
return { type: flag ? OPEN_SIDE_MENU : CLOSE_SIDE_MENU }
}
/*
全局的登录对话框
*/
export const OPEN_LOGIN_DIALOG = 'OPEN_LOGIN_DIALOG'
export const CLOSE_LOGIN_DIALOG = 'CLOSE_LOGIN_DIALOG'
export function toggleLoginDialog(flag) {
return { type: flag ? OPEN_LOGIN_DIALOG : CLOSE_LOGIN_DIALOG }
}
|
wapalxj/Java
|
javaworkplace/Thinking_in_Java/src/C13_String/P287_case.java
|
<reponame>wapalxj/Java<gh_stars>0
package C13_String;
import java.util.ArrayList;
import java.util.List;
public class P287_case {
/**
* @param args
*/
public static void main(String[] args) {
List<InfiniteRecursion> ins=new ArrayList<>();
for (int i = 0; i < 10; i++) {
ins.add(new InfiniteRecursion());
}
System.out.println(ins);
}
}
class InfiniteRecursion{
@Override
public String toString() {
return "InfiniteRecursion addr: "+this+"\n";
}
}
|
Johniel/contests
|
codeforces/350div2/A/main.cpp
|
#include <bits/stdc++.h>
#define each(i, c) for (auto& i : c)
#define unless(cond) if (!(cond))
using namespace std;
typedef long long int lli;
typedef unsigned long long ull;
typedef complex<double> point;
template<typename P, typename Q>
ostream& operator << (ostream& os, pair<P, Q> p)
{
os << "(" << p.first << "," << p.second << ")";
return os;
}
int main(int argc, char *argv[])
{
int n;
while (scanf("%d", &n) == 1) {
int mn = n * 2, mx = 0;
for (int base = 0; base < 7; ++base) {
int cnt = 0;
for (int d = 0; d < n; ++d) {
cnt += (5 <= (base + d) % 7);
}
mn = min(mn, cnt);
mx = max(mx, cnt);
}
printf("%d %d\n", mn, mx);
}
return 0;
}
|
rexcorp01/bet6
|
pick6-frontend/src/App.js
|
import React from 'react';
import { Route, Switch, withRouter } from 'react-router-dom'
import './App.css';
import { connect } from 'react-redux'
import { getCurrentUser } from './actions/currentUser.js'
import Login from './components/Login.js'
import Navbar from './components/Navbar.js'
import UserShow from './components/UserShow.js'
import Home from './components/Home.js'
import GroupShow from './components/GroupShow.js'
import Signup from './components/Signup.js'
import NewGroupForm from './components/NewGroupForm.js'
import EditGroupForm from './components/EditGroupForm.js'
import JoinGroup from './components/JoinGroup.js'
import WeekShow from './components/WeekShow.js'
import AdminPage from './components/AdminPage.js'
import AdminEditGameForm from './components/AdminEditGameForm.js'
class App extends React.Component {
componentDidMount() {
this.props.getCurrentUser()
}
render() {
const { loggedIn, groups, weeks, teams, games } = this.props
return (
<div className="App background" id="page-container">
<Navbar location={this.props.location}/>
<div id="content-wrap">
<Switch>
<Route exact path='/' render={(props)=> loggedIn ? <UserShow {...props}/> : <Home {...props}/>} />
<Route exact path='/login' component={Login}/>
<Route exact path='/signup' component={Signup}/>
<Route exact path='/admin' render={props => <AdminPage {...props} />}/>
<Route exact path='/groups/join' render={props => <JoinGroup {...props} />}/>
<Route exact path='/groups/new' component={NewGroupForm} />
<Route exact path='/groups/:id' render={props => {
const group = groups.find(group => group.id === props.match.params.id)
return <GroupShow group={group} {...props}/>
}
}/>
<Route path='/weeks/:id' render={props => {
const week = weeks.find(week => week.id === props.match.params.id)
return <WeekShow week={week} groups={groups} teams={teams} {...props}/>
}
}/>
<Route path='/games/:id/edit' render={props => {
const game = games.find(game => game.id === props.match.params.id)
return <AdminEditGameForm game={game} {...props}/>
}
}/>
<Route exact path='/groups/:id/edit' render={props => {
const group = groups.find(group => group.id === props.match.params.id)
return <EditGroupForm group={group} {...props}/>
}
}/>
</Switch>
</div>
<footer id="footer">
This app is not affiliated with, funded by, or in any way associated with the NFL.
</footer>
</div>
);
}
}
const mapStateToProps = state => {
return {
currentUser: state.current_user,
loggedIn: !!state.currentUser,
groups: state.myGroups,
weeks: state.myWeeks,
teams: state.teams,
games: state.games
}
}
export default withRouter(connect(mapStateToProps, { getCurrentUser })(App));
|
lucid-at-dream/citylife
|
src/base-libs/operations/server/server.c
|
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "logger.h"
#include "server.h"
#include "worker_pool.h"
socket_server *server_new(unsigned short port)
{
info("server.c: Creating a new server bound to port %d", port);
socket_server *new_server = (socket_server *)calloc(1, sizeof(socket_server));
new_server->server_port = port;
new_server->protoent = getprotobyname("tcp");
return new_server;
}
void server_stop(socket_server *server)
{
info("server.c: Stopping the server");
server->stop = 1;
}
void server_start(socket_server *server, char *(*handle_request)(char *))
{
server->server_address.sin_family = AF_INET;
server->server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server->server_address.sin_port = htons(server->server_port);
server->server_sock_file_descriptor = socket(AF_INET, SOCK_STREAM, server->protoent->p_proto);
if (server->server_sock_file_descriptor == -1)
{
perror("Could not create the server socket.");
exit(EXIT_FAILURE);
}
if (bind(server->server_sock_file_descriptor, (struct sockaddr *)&server->server_address, sizeof(server->server_address)) == -1)
{
perror("Could not bind the server socket to the given port.");
exit(EXIT_FAILURE);
}
if (listen(server->server_sock_file_descriptor, 1000) == -1)
{
perror("Unable to start listening for requests.");
exit(EXIT_FAILURE);
}
info("server.c: Listening on port %d", server->server_port);
struct sockaddr_in client_address;
while (!server->stop)
{
debug("server.c: server stop flag is set to %d", server->stop);
socklen_t client_len = sizeof(client_address);
// Accept a new connection
server->client_sock_file_descriptor = accept(server->server_sock_file_descriptor, (struct sockaddr *)&client_address, &client_len);
// Read the request
int read_bytes = read(server->client_sock_file_descriptor, server->buffer, BUFSIZE);
if (read_bytes <= 1)
{
debug("server.c: Server read unblocked but no data was read");
continue;
}
info("server.c: Request with %d Bytes received", read_bytes);
// Handle the request
char *response = handle_request(server->buffer);
// Write the response
write(server->client_sock_file_descriptor, response, strlen(response));
// Close the file descriptor and deallocate resources
close(server->client_sock_file_descriptor);
free(response);
}
info("server.c: Server exiting from server loop");
close(server->server_sock_file_descriptor);
}
|
TonyBrewer/OpenHT
|
tests/dsn11/src_pers/PersInc_src.cpp
|
#include "Ht.h"
#include "PersInc.h"
ht_uint4 CPersInc::fu4()
{
return 4;
}
bool CPersInc::fb()
{
ht_uint4 u4 = 4;
bool b;
switch (u4 + fu4()) {
case 1: b = true; break;
default: b = false; break;
}
return b;
}
ht_uint4 CPersInc::fp1(ht_uint4 const & a, ht_uint4 const & b)
{
return a + b;
}
CStruct CPersInc::fs()
{
CStruct s;
s = 0;
return s;
}
ht_uint4 CPersInc::fg(ht_uint4 const & a, ht_uint4 & b, ht_uint4 & c)
{
b = a + b;
c = a + S_pu4;
return a - S_pu4;
}
ht_uint4 CPersInc::fl(ht_uint4 const & a, ht_uint4 & b, ht_uint4 & c)
{
b = a + b;
c = a;
return a;
}
struct CStruct2 {
ht_uint4 m_u4[3];
bool m_b;
};
void CPersInc::PersInc()
{
if (PR_htValid) {
switch (PR_htInst) {
case INC_INIT:
{
P_loopCnt = 0;
// test signed expressions
sc_int<5> a = 5;
sc_int<5> b = -3;
sc_int<5> c = a + b;
S_pu4 = (ht_uint4)c;
c = c++;
// test function calls in expressions
CStruct2 st;
st.m_b = true;
st.m_u4[(ht_uint2)st.m_b] = st.m_b ? st.m_u4[2] : (ht_uint4)(fu4() + st.m_u4[(ht_uint2)(P_loopCnt & 1)]);
st.m_u4[(ht_uint2)st.m_b] = 5;
ht_uint4 u4;
S_pu4 = fg(fu4() + 5, S_pu4, u4);
S_pu4 = fl(fu4() + 5, S_pu4, u4);
++S_pu4;
S_pu4 = S_pu4++ + u4;
S_pu4 = fs().m_u3 << 1;
fp1(S_pu4, fu4() + 4);
S_pb = S_pb || fb();
S_pb = S_pb || fb() || S_pb;
S_pu4 = fu4() + 4;
S_pu4 = S_pu4 + fu4() + 4 - fu4();
ht_uint4 arr[2][4];
for (int i = 0; i < 4; i += 1) {
arr[0][i] = 0;
arr[1][i] = 0;
}
arr[fb() ? 0u : 1u][fb() << 1] = arr[fu4() & 1][fu4() & 3] + fu4() + 4 - fu4();
// test logicals
bool b1 = true;
bool b2 = true;
bool b3 = true;
S_pb = S_pb || fb() || b1 && b2 && b3 || fb();
// test conditional expression
S_pu4 = S_pb ? fu4() : (ht_uint4)8;
S_pu4 = fb() ? fu4() : (ht_uint4)8;
S_pu4 += 1;
S_pu4 = fu4() + (fb() && b1 ? S_pu4 : (ht_uint4)(fu4() + 4ul));
S_pb = b2 && (fb() ? b1 : b3);
S_pb = fb() || (fb() && b3 && S_pu4++ < 4 || --S_pu4 > 5 ? b2 : b1 && fb()) && fb() && b2;
HtContinue(INC_READ);
}
break;
case INC_READ:
{
if (ReadMemBusy() || SendReturnBusy_htmain()) {
HtRetry();
break;
}
// Check if end of loop
if (P_loopCnt == P_elemCnt) {
// Return to host interface
SendReturn_htmain(P_loopCnt);
} else {
// Calculate memory read address
MemAddr_t memRdAddr = SR_arrayAddr + (P_loopCnt << 3);
// Issue read request to memory
ReadMem_arrayMem(memRdAddr, PR_htId);
// Set address for reading memory response data
P_arrayMemRdPtr = PR_htId;
ReadMemPause(INC_WRITE);
}
}
break;
case INC_WRITE:
{
if (WriteMemBusy()) {
HtRetry();
break;
}
// Increment memory data
uint64_t memWrData = GR_arrayMem.data + 1;
// Calculate memory write address
MemAddr_t memWrAddr = SR_arrayAddr + (P_loopCnt << 3);
// Issue write memory request
WriteMem(memWrAddr, memWrData);
memWrData = GR_arrayMem2.data;
// Increment loop count
P_loopCnt = P_loopCnt + 1;
WriteMemPause(INC_READ);
}
break;
default:
assert(0);
}
}
}
|
Palem1988/beacon-chain-java
|
ssz/src/main/java/org/ethereum/beacon/ssz/access/list/ArrayAccessor.java
|
package org.ethereum.beacon.ssz.access.list;
import java.lang.reflect.Array;
import java.util.List;
import org.ethereum.beacon.ssz.access.SSZField;
import org.ethereum.beacon.ssz.type.SSZType;
public class ArrayAccessor extends AbstractListAccessor {
@Override
public boolean isSupported(SSZField field) {
return field.getRawClass().isArray();
}
@Override
public int getChildrenCount(Object complexObject) {
return Array.getLength(complexObject);
}
@Override
public Object getChildValue(Object complexObject, int index) {
return Array.get(complexObject, index);
}
@Override
public SSZField getListElementType(SSZField listTypeDescriptor) {
return new SSZField(listTypeDescriptor.getRawClass().getComponentType());
}
@Override
public ListInstanceBuilder createInstanceBuilder(SSZType sszType) {
SSZField compositeDescriptor = sszType.getTypeDescriptor();
return new SimpleInstanceBuilder() {
@Override
protected Object buildImpl(List<Object> children) {
if (!getListElementType(compositeDescriptor).getRawClass().isPrimitive()) {
return children.toArray((Object[]) Array.newInstance(
getListElementType(compositeDescriptor).getRawClass(),children.size()));
} else {
if (getListElementType(compositeDescriptor).getRawClass() == byte.class) {
Object ret = Array.newInstance(byte.class);
for (int i = 0; i < children.size(); i++) {
Array.setByte(ret, i, (Byte) children.get(i));
}
return ret;
} else {
throw new UnsupportedOperationException("Not implemented yet");
}
}
}
};
}
}
|
gabr1e11/cornerstone
|
Source/Framework/Core/ILifeCycle.hpp
|
<filename>Source/Framework/Core/ILifeCycle.hpp
//
// ILifeCycle.hpp
//
// @author <NAME>
//
#pragma once
namespace Framework
{
namespace Core
{
class ILifeCycle
{
public:
virtual void init() = 0;
virtual void start() = 0;
virtual void update(float dt) = 0;
protected:
virtual void internalInit() = 0;
virtual void internalStart() = 0;
virtual void internalUpdate(float dt) = 0;
};
}
}
|
eincioch/Mastering-Java-EE-Development-with-WildFly
|
Chapter04/src/main/java/it/vige/businesscomponents/businesslogic/context/old/Ejb21StateEngineLocalBean.java
|
package it.vige.businesscomponents.businesslogic.context.old;
import static java.util.logging.Logger.getLogger;
import java.security.Principal;
import java.util.Collection;
import java.util.Map;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJBException;
import javax.ejb.EJBLocalHome;
import javax.ejb.EJBLocalObject;
import javax.ejb.Init;
import javax.ejb.Local;
import javax.ejb.LocalHome;
import javax.ejb.RemoveException;
import javax.ejb.SessionContext;
import javax.ejb.Stateful;
import it.vige.businesscomponents.businesslogic.context.old.Ejb21StateLocal;
import it.vige.businesscomponents.businesslogic.context.old.Ejb21StateLocalHome;
@Stateful(name = "ejb21StateEngineLocal")
@LocalHome(value = Ejb21StateLocalHome.class)
@Local(value = Ejb21StateLocal.class)
public class Ejb21StateEngineLocalBean implements Ejb21StateLocal {
private static final Logger logger = getLogger(Ejb21StateEngineLocalBean.class.getName());
private int speed;
@Resource
private SessionContext context;
@Init
public void init() {
speed = 1;
}
@Init
public void init(String message) {
speed = 1;
}
@Init
public void init(Collection<?> messages) {
speed = 1;
}
@Override
public int go(int speed) {
return this.speed += speed;
}
@Override
public int retry(int speed) {
return this.speed -= speed;
}
@Override
public int getSpeed() {
return speed;
}
@Override
public void add(Object data) {
context.getContextData().put("state_engine_data", data);
}
public void log() {
Principal principal = context.getCallerPrincipal();
Map<String, Object> contextData = context.getContextData();
EJBLocalHome ejbLocalHome = context.getEJBLocalHome();
EJBLocalObject ejbLocalObject = context.getEJBLocalObject();
Ejb21StateLocal stateLocalEngine = context.getBusinessObject(Ejb21StateLocal.class);
boolean isCallerInRole = context.isCallerInRole("admin");
logger.info("stateLocalEngineBean principal: " + principal);
logger.info("stateLocalEngineBean contextData:" + contextData);
logger.info("stateLocalEngineBean ejbLocalHome:" + ejbLocalHome);
logger.info("stateLocalEngineBean ejbLocalObject:" + ejbLocalObject);
logger.info("stateLocalEngineBean stateLocalEngineBean:" + stateLocalEngine);
logger.info("stateLocalEngineBean isCallerInRole:" + isCallerInRole);
}
@Override
public EJBLocalHome getEJBLocalHome() throws EJBException {
logger.info("getEJBLocalHome");
return null;
}
@Override
public Object getPrimaryKey() throws EJBException {
logger.info("getPrimaryKey");
return null;
}
@Override
public void remove() throws RemoveException, EJBException {
logger.info("remove");
}
@Override
public boolean isIdentical(EJBLocalObject obj) throws EJBException {
logger.info("isIdentical");
return false;
}
}
|
TeacherManoj0131/HacktoberFest2020-Contributions
|
Games/Zeldiablo/src/moteurPerso/MainPerso.java
|
<filename>Games/Zeldiablo/src/moteurPerso/MainPerso.java<gh_stars>100-1000
package moteurPerso;
import java.util.Scanner;
import moteurJeu.MoteurGraphique;
public class MainPerso {
public static void main(String[] args) throws InterruptedException {
// creation du jeu particulier et de son afficheur
JeuPerso jeu = new JeuPerso();
DessinPerso aff = new DessinPerso(jeu);
// classe qui lance le moteur de jeu generique
MoteurGraphique moteur = new MoteurGraphique(jeu, aff);
// lance la boucle de jeu qui tourne jusque la fin du jeu
moteur.lancerJeu(400, 400);
// lorsque le jeu est fini
System.out.println("Fin du Jeu - Appuyer sur Entree");
Scanner sc=new Scanner(System.in);
sc.nextLine();
System.exit(1);
}
}
|
geometryzen/webgl-core
|
build/main/lib/core/TextureParameterName.js
|
<reponame>geometryzen/webgl-core
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TextureParameterName = void 0;
/**
*
*/
var TextureParameterName;
(function (TextureParameterName) {
TextureParameterName[TextureParameterName["TEXTURE_MAG_FILTER"] = 10240] = "TEXTURE_MAG_FILTER";
TextureParameterName[TextureParameterName["TEXTURE_MIN_FILTER"] = 10241] = "TEXTURE_MIN_FILTER";
TextureParameterName[TextureParameterName["TEXTURE_WRAP_S"] = 10242] = "TEXTURE_WRAP_S";
TextureParameterName[TextureParameterName["TEXTURE_WRAP_T"] = 10243] = "TEXTURE_WRAP_T";
})(TextureParameterName = exports.TextureParameterName || (exports.TextureParameterName = {}));
|
fx02/Open-Shell-Menu
|
Src/ClassicExplorer/ShareOverlay.h
|
// Classic Shell (c) 2009-2017, <NAME>
// Open-Shell (c) 2017-2018, The Open-Shell Team
// Confidential information of <NAME>. Not for disclosure or distribution without prior written consent from the author
// ShareOverlay.h : Declaration of the CShareOverlay
#pragma once
#include "resource.h" // main symbols
#include <lm.h>
#include "ClassicExplorer_i.h"
// CShareOverlay
class ATL_NO_VTABLE CShareOverlay :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CShareOverlay, &CLSID_ShareOverlay>,
public IShellIconOverlayIdentifier
{
public:
CShareOverlay( void );
DECLARE_REGISTRY_RESOURCEID(IDR_SHAREOVERLAY)
DECLARE_PROTECT_FINAL_CONSTRUCT()
HRESULT FinalConstruct( void )
{
return S_OK;
}
void FinalRelease( void );
public:
HRESULT _InternalQueryInterface( REFIID iid, void** ppvObject );
// IShellIconOverlayIdentifier
STDMETHOD (IsMemberOf)( LPCWSTR pwszPath, DWORD dwAttrib );
STDMETHOD (GetOverlayInfo)( LPWSTR pwszIconFile, int cchMax, int * pIndex, DWORD * pdwFlags );
STDMETHOD (GetPriority)( int * pIPriority );
static void InitOverlay( const wchar_t *icon, bool showHidden );
private:
CComPtr<IShellFolder> m_pDesktop;
CRITICAL_SECTION m_Section;
SHARE_INFO_502 *m_pShareInfo;
DWORD m_ShareCount;
int m_UpdateTime;
void UpdateShareInfo( void );
static bool s_bEnabled;
static bool s_bShowHidden;
static int s_Index;
static wchar_t s_IconPath[_MAX_PATH];
};
OBJECT_ENTRY_AUTO(__uuidof(ShareOverlay), CShareOverlay)
|
Hei-Joy/pig
|
pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/model/entity/Assets.java
|
<filename>pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/model/entity/Assets.java
package com.github.pig.admin.model.entity;
import lombok.Data;
@Data
public class Assets {
private String id;
private String name;
private Integer tbValue;
private String tbType;
private Boolean tbStatic;
private String rootid;
}
|
samcom12/anuga_core
|
validation_tests/analytical_exact/carrier_greenspan_transient/plot_results.py
|
<filename>validation_tests/analytical_exact/carrier_greenspan_transient/plot_results.py
"""
Quick plot of the Carrier-Greenspan outputs
"""
import anuga.utilities.plot_utils as util
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as pyplot
from analytical_cg_transient import *
p_st = util.get_output('carrier_greenspan.sww')
p2_st=util.get_centroids(p_st)
v = p2_st.y[10]
v2=(p2_st.y==v)
#Dimensional parameters
L = 5e4 # Length of channel (m)
h0 = 5e2 # Height at origin when the water is still
g = 9.81 # Gravity
#Dimensionless solution
W1, Z1, U1 = analytical_sol(p2_st.x[v2]/L, p2_st.time[0]*sqrt(g*h0)/L)
W2, Z2, U2 = analytical_sol(p2_st.x[v2]/L, p2_st.time[1]*sqrt(g*h0)/L)
W3, Z3, U3 = analytical_sol(p2_st.x[v2]/L, p2_st.time[30]*sqrt(g*h0)/L)
#Dimensional solution
W1 = W1*h0 # dimensional
U1 = U1*sqrt(g*h0) # dimensional
Z1 = Z1*h0 # dimensional
H1 = W1 - Z1 # dimensional
P1 = U1 * H1 # dimensional
W2 = W2*h0 # dimensional
U2 = U2*sqrt(g*h0) # dimensional
Z2 = Z2*h0 # dimensional
H2 = W2 - Z2 # dimensional
P2 = U2 * H2 # dimensional
W3 = W3*h0 # dimensional
U3 = U3*sqrt(g*h0) # dimensional
Z3 = Z3*h0 # dimensional
H3 = W3 - Z3 # dimensional
P3 = U3 * H3 # dimensional
#Plot the stages##############################################################
pyplot.clf()
pyplot.plot(p2_st.x[v2], p2_st.stage[0,v2], 'b.', label='numerical')
pyplot.plot(p2_st.x[v2], p2_st.stage[1,v2], 'b.')
pyplot.plot(p2_st.x[v2], p2_st.stage[30,v2], 'b.')
pyplot.plot(p2_st.x[v2], W1,'r-', label='analytical')
pyplot.plot(p2_st.x[v2], W2,'r-')
pyplot.plot(p2_st.x[v2], W3,'r-')
pyplot.title('Stage at several instants in time')
#pyplot.ylim(-5.0,5.0)
pyplot.legend(loc='best')
pyplot.xlabel('Xposition')
pyplot.ylabel('Stage')
pyplot.savefig('stage_plot.png')
#Plot the momentums##########################################################
pyplot.clf()
pyplot.plot(p2_st.x[v2], p2_st.xmom[0,v2], 'b.', label='numerical')
pyplot.plot(p2_st.x[v2], p2_st.xmom[1,v2], 'b.')
pyplot.plot(p2_st.x[v2], p2_st.xmom[30,v2], 'b.')
pyplot.plot(p2_st.x[v2], P1,'r-', label='analytical')
pyplot.plot(p2_st.x[v2], P2,'r-')
pyplot.plot(p2_st.x[v2], P3,'r-')
pyplot.title('Xmomentum at several instants in time')
pyplot.legend(loc='best')
pyplot.xlabel('Xposition')
pyplot.ylabel('Xmomentum')
pyplot.savefig('xmom_plot.png')
#Plot the velocities#########################################################
pyplot.clf()
pyplot.plot(p2_st.x[v2], p2_st.xvel[0,v2], 'b.', label='numerical')
pyplot.plot(p2_st.x[v2], p2_st.xvel[1,v2], 'b.')
pyplot.plot(p2_st.x[v2], p2_st.xvel[30,v2], 'b.')
pyplot.plot(p2_st.x[v2], U1,'r-', label='analytical')
pyplot.plot(p2_st.x[v2], U2,'r-')
pyplot.plot(p2_st.x[v2], U3,'r-')
pyplot.title('Xvelocity at several instants in time')
pyplot.legend(loc='best')
pyplot.xlabel('Xposition')
pyplot.ylabel('Xvelocity')
pyplot.savefig('xvel_plot.png')
|
o-dasher/libremelting
|
core/src/com/dasher/meltinglight/Graphics/ShapeRendering/FadeBlock.java
|
package com.dasher.meltinglight.Graphics.ShapeRendering;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.utils.Null;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.dasher.meltinglight.Graphics.Interfaces.ResizeListener;
public class FadeBlock implements ResizeListener {
private final Color color;
private boolean isFadingIn = false;
private boolean isFadingOut = false;
private float period = 1;
private final ShapeRenderer shapeRenderer;
private Runnable fadeInTask;
private Runnable fadeOutTask;
private float w;
private float h;
public FadeBlock(Color color, ShapeRenderer shapeRenderer) {
this.color = color.cpy();
this.color.a = 0;
this.shapeRenderer = shapeRenderer;
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight();
}
public void update(float delta) {
float w = Gdx.graphics.getWidth();;
float h = Gdx.graphics.getHeight();
if (isFading()) {
if (isFadingIn) {
color.a = Math.min(1, color.a + delta / period);
if (color.a >= 1) {
isFadingOut = true;
isFadingIn = false;
if (fadeInTask != null) {
fadeInTask.run();
fadeInTask = null;
}
}
} else {
color.a = Math.max(0, color.a - delta / period);
if (color.a <= 0) {
isFadingOut = false;
if (fadeOutTask != null) {
fadeOutTask.run();
fadeOutTask = null;
}
}
}
Gdx.gl.glEnable(GL30.GL_BLEND);
Gdx.gl.glBlendFunc(GL30.GL_SRC_ALPHA, GL30.GL_ONE_MINUS_SRC_ALPHA);
shapeRenderer.setColor(color);
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
shapeRenderer.rect(0, 0, w, h);
shapeRenderer.end();
Gdx.gl.glDisable(GL30.GL_BLEND);
}
}
public boolean isFading() {
return isFadingIn || isFadingOut;
}
public void setPeriod(float period) {
this.period = period;
}
public void setFade(boolean isFadingIn) {
this.isFadingIn = isFadingIn;
}
public void setFadeInTask(Runnable fadeInTask) {
this.fadeInTask = fadeInTask;
}
public void setFadeOutTask(Runnable fadeOutTask) {
this.fadeOutTask = fadeOutTask;
}
@Override
public void resize(float width, float height) {
w = width;
h = height;
}
}
|
nathants/aws-util
|
lib/aws.go
|
<gh_stars>0
package lib
import (
"context"
"os"
"sync"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
var sess *session.Session
var sessLock sync.RWMutex
var sessRegional = make(map[string]*session.Session)
func SessionExplicit(accessKeyID, accessKeySecret, region string) *session.Session {
sess, err := session.NewSession(&aws.Config{
Region: aws.String(region),
STSRegionalEndpoint: endpoints.RegionalSTSEndpoint,
MaxRetries: aws.Int(5),
Credentials: credentials.NewStaticCredentials(accessKeyID, accessKeySecret, ""),
})
if err != nil {
panic(err)
}
return sess
}
func Session() *session.Session {
sessLock.Lock()
defer sessLock.Unlock()
if sess == nil {
err := os.Setenv("AWS_SDK_LOAD_CONFIG", "true")
if err != nil {
panic(err)
}
sess = session.Must(session.NewSession(&aws.Config{
STSRegionalEndpoint: endpoints.RegionalSTSEndpoint,
MaxRetries: aws.Int(5),
}))
}
return sess
}
func SessionRegion(region string) (*session.Session, error) {
sessLock.Lock()
defer sessLock.Unlock()
sess, ok := sessRegional[region]
if !ok {
err := os.Setenv("AWS_SDK_LOAD_CONFIG", "true")
if err != nil {
return nil, err
}
sess, err = session.NewSession(&aws.Config{
Region: aws.String(region),
STSRegionalEndpoint: endpoints.RegionalSTSEndpoint,
MaxRetries: aws.Int(5),
})
if err != nil {
return nil, err
}
sessRegional[region] = sess
}
return sess, nil
}
func Region() string {
sess := Session()
return *sess.Config.Region
}
func Zones(ctx context.Context) ([]*ec2.AvailabilityZone, error) {
out, err := EC2Client().DescribeAvailabilityZonesWithContext(ctx, &ec2.DescribeAvailabilityZonesInput{})
if err != nil {
Logger.Println("error:", err)
return nil, err
}
return out.AvailabilityZones, nil
}
|
mreinsch/api-umbrella
|
test/support/models/api/rate_limit.rb
|
class Api::RateLimit
include Mongoid::Document
field :_id, :type => String, :overwrite => true, :default => lambda { SecureRandom.uuid }
field :duration, :type => Integer
field :accuracy, :type => Integer
field :limit_by, :type => String
field :limit, :type => Integer
field :distributed, :type => Boolean
field :response_headers, :type => Boolean
embedded_in :settings
end
|
miw-upm/apaw-practice
|
src/test/java/es/upm/miw/apaw_practice/adapters/mongodb/car_hire/daos/VehicleRepositoryIT.java
|
<gh_stars>1-10
package es.upm.miw.apaw_practice.adapters.mongodb.car_hire.daos;
import es.upm.miw.apaw_practice.TestConfig;
import es.upm.miw.apaw_practice.adapters.mongodb.car_hire.entities.VehicleEntity;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.math.BigDecimal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@TestConfig
class VehicleRepositoryIT {
@Autowired
private VehicleRepository vehicleRepository;
@Test
void testFindByVinNumber() {
assertTrue(this.vehicleRepository.findByVinNumber("VSSZZZ6KZ1R149943").isPresent());
VehicleEntity vehicle = this.vehicleRepository.findByVinNumber("VSSZZZ6KZ1R149943").get();
assertEquals(0, new BigDecimal("50").compareTo(vehicle.getDailyCost()));
assertEquals(25400, vehicle.getKilometersAmount());
assertEquals(true, vehicle.getGoodCondition());
}
}
|
raindigi/Merchello
|
src/Merchello.Web.UI.Client/src/views/gatewayproviders/notificationmessageeditor.controller.js
|
<gh_stars>100-1000
angular.module('merchello').controller('Merchello.Backoffice.NotificationMessageEditorController',
['$scope', '$q', '$routeParams', '$location', 'assetsService', 'dialogService', 'eventsService', 'notificationsService', 'merchelloTabsFactory', 'dialogDataFactory',
'notificationGatewayProviderResource', 'notificationMessageDisplayBuilder', 'notificationMonitorDisplayBuilder',
function($scope, $q, $routeParams, $location, assetsService, dialogService, eventsService, notificationsService, merchelloTabsFactory, dialogDataFactory,
notificationGatewayProviderResource, notificationMessageDisplayBuilder, notificationMonitorDisplayBuilder) {
$scope.loaded = false;
$scope.preValuesLoaded = false;
$scope.tabs = [];
$scope.notificationMessage = {};
$scope.notificationMonitors = [];
$scope.currentMonitor = {};
$scope.reload = init;
// exposed methods
$scope.save = save;
$scope.deleteMessage = deleteMessage;
var saveEventName = 'notification.message.saved';
function init() {
$scope.loaded = false;
var key = $routeParams.id;
$q.all([
notificationGatewayProviderResource.getNotificationMessagesByKey(key),
notificationGatewayProviderResource.getAllNotificationMonitors()
]).then(function(data) {
$scope.notificationMessage = notificationMessageDisplayBuilder.transform(data[0]);
$scope.notificationMonitors = notificationMonitorDisplayBuilder.transform(data[1]);
$scope.currentMonitor = _.find($scope.notificationMonitors, function(m) {
return m.monitorKey === $scope.notificationMessage.monitorKey;
});
$scope.tabs = merchelloTabsFactory.createGatewayProviderTabs();
$scope.tabs.insertTab('messageEditor', 'merchelloTabs_message', '#/merchello/merchello/notification.messageeditor/' + key, 2);
$scope.tabs.setActive('messageEditor');
$scope.loaded = true;
$scope.preValuesLoaded = true;
});
}
function deleteMessage() {
var dialogData = dialogDataFactory.createDeleteNotificationMessageDialogData();
dialogData.notificationMessage = $scope.notificationMessage;
dialogData.name = $scope.notificationMessage.name;
dialogService.open({
template: '/App_Plugins/Merchello/Backoffice/Merchello/Dialogs/delete.confirmation.html',
show: true,
callback: notificationsMessageDeleteDialogConfirm,
dialogData: dialogData
});
}
/**
* @ngdoc method
* @name notificationsMessageDeleteDialogConfirm
* @function
*
* @description
* Handles the delete after recieving the deleted command from the dialog view/controller
*/
function notificationsMessageDeleteDialogConfirm(dialogData) {
var promiseNotificationMethod = notificationGatewayProviderResource.deleteNotificationMessage(dialogData.notificationMessage.key);
promiseNotificationMethod.then(function () {
$location.url('merchello/merchello/notificationproviders/manage', true);
}, function (reason) {
notificationsService.error("Notification Method Deletion Failed", reason.message);
});
}
/**
* @ngdoc method
* @name save
* @function
*
* @description
* Saves the notification message
*/
function save() {
$scope.preValuesLoaded = false;
var promiseSave = notificationGatewayProviderResource.updateNotificationMessage($scope.notificationMessage);
promiseSave.then(function () {
notificationsService.success("Notification Message Saved");
eventsService.emit(saveEventName, $scope.notificationMessage);
init();
}, function (reason) {
notificationsService.error("Notification Message Save Failed", reason.message);
});
}
// Initialize the controller
init();
}]);
|
HaoyeTianCoder/coming
|
src/main/java/fr/inria/coming/core/filter/diff/syntcomparison/Fragmentable.java
|
package fr.inria.coming.core.filter.diff.syntcomparison;
import org.eclipse.compare.rangedifferencer.IRangeComparator;
public interface Fragmentable extends IRangeComparator {
String getFragment(int i);
}
|
Joshuahelmle/connect4-SWAR
|
src/main/scala/de/htwg/se/connect4/controller/controllerComponent/controllerBaseImpl/Controller.scala
|
package de.htwg.se.connect4.controller.controllerComponent.controllerBaseImpl
import com.google.inject.{Guice, Inject}
import de.htwg.se.connect4.Connect4Module
import de.htwg.se.connect4.controller.controllerComponent.ControllerInterface
import de.htwg.se.connect4.model.boardComponent.BoardInterface
import de.htwg.se.connect4.model.boardComponent.boardBaseImpl.{BoardSizeStrategy, Cell, Color}
import de.htwg.se.connect4.model.fileIoComponent.FileIoInterface
import de.htwg.se.connect4.model.playerComponent
import de.htwg.se.connect4.model.playerComponent.Player
import de.htwg.se.connect4.util.{Observable, UndoManager}
import net.codingwell.scalaguice.InjectorExtensions._
class Controller @Inject()(var board: BoardInterface, var players: List[Player]) extends Observable with ControllerInterface {
val injector = Guice.createInjector(new Connect4Module)
val fileIo = injector.instance[FileIoInterface]
var state: ControllerState = InitializationState(this)
var currentPlayerIndex: Int = 0
private val undoManager = new UndoManager
def stateString: String = state.stateString()
def handle(input: String, board: BoardInterface): String = {
state.handle(input, board)
}
def getWelcomeString: String = "Welcome to connect 4. Please Enter your names."
def setCol(col : Int) : String = {
var idx = board.sizeOfRows-1
var found = false;
while(!found && idx >= 0){
found = !board.cell(idx,col).isSet
idx -= 1
}
if(found) {
return set(idx+1,col)
}
else {
notifyObservers
"Cell is already set. Please chose different one."
}
}
def set(row: Int, col: Int): String = {
if (board.cell(row, col).isSet) {
notifyObservers
"Cell is already set. Please chose different one."
} else {
undoManager.doStep(new SetCommand(row, col, players(currentPlayerIndex), this, true))
players = players.updated(currentPlayerIndex, players(currentPlayerIndex).setPiece())
if (playerWin(row, col)) {
triggerNextStateAndEvaluateInput
return ""
}
if (playersHaveNoPiecesLeft) {
triggerNextStateAndEvaluateInput
return ""
}
currentPlayerIndex = getNextPlayerIndex
notifyObservers
""
}
}
def triggerNextStateAndEvaluateInput: Unit = {
state = state.nextState()
notifyObservers
}
def playerWin(row: Int, col: Int): Boolean = {
val matchInCols = board.checkCols(col, players(currentPlayerIndex).color)
val matchInRows = board.checkRow(row, players(currentPlayerIndex).color)
val matchDiagonal = board.checkDiagonal(row, col, players(currentPlayerIndex).color)
matchInCols || matchInRows || matchDiagonal
}
def playersHaveNoPiecesLeft: Boolean = if (players.head.piecesLeft == 0 && players(1).piecesLeft == 0) true else false
def getNextPlayerIndex: Int = if (currentPlayerIndex == 0) 1 else 0
def boardToString: String = board.getBoardAsString(board.getCells)
def addPlayer(input: String): String = {
if (players.isEmpty) {
players = players ::: playerComponent.Player(input, Color.RED) :: Nil
}
else if (players.size < 2) {
players = players ::: playerComponent.Player(input, Color.YELLOW) :: Nil
triggerNextStateAndEvaluateInput
}
else triggerNextStateAndEvaluateInput
""
}
def createNewBoard(rows: Int, cols: Int): String = {
board = BoardSizeStrategy.execute((rows, cols))
currentPlayerIndex = 0
var newPlayers: List[Player] = Nil
newPlayers = newPlayers ::: players.head.copy(piecesLeft = 21) :: Nil
newPlayers = newPlayers ::: players(1).copy(piecesLeft = 21) :: Nil
players = newPlayers
state = InGameState(this)
notifyObservers
"created new Board \n" + getPlayerDemandString
}
def getPlayerDemandString: String = "It's your turn Player " + players(currentPlayerIndex).playerName
def getIncorrectInputMessage: String = "Please Enter two numbers separated by a whitespace."
def undo(): String = {
undoManager.undoStep()
notifyObservers
"Undo Step."
}
def redo: String = {
undoManager.redoStep()
notifyObservers
"Redo Step."
}
def sizeOfRows: Int = board.sizeOfRows
def sizeOfCols: Int = board.sizeOfCols
def isSet(row: Int, col: Int): Boolean = board.cell(row, col).isSet
def cell(row: Int, col: Int): Cell = board.cell(row, col)
def getCell(row: Int, col: Int): Cell = board.cell(row, col)
def getBoard: BoardInterface = board
def getState: ControllerState = state
def getPlayers: List[Player] = players
def getCurrentPlayerIndex: Int = currentPlayerIndex
override def save: String = {
val stateToSave = State(currentPlayerIndex, players, state.toString())
fileIo.save(board, stateToSave)
"saved"
}
override def load: String = {
val (newBoard, loadedState) = fileIo.load
board = newBoard
players = loadedState.players
currentPlayerIndex = loadedState.currentPlayerIndex
setStateOfString(loadedState.state)
notifyObservers
"loaded"
}
def setStateOfString(stateString: String): Unit = {
stateString match {
case "GameOverState" => state = GameOverState(this)
case "InitializationState" => state = InitializationState(this)
case "PlayerWinState" => PlayerWinState
case "InGameState" => state = InGameState(this)
}
}
}
|
MilkyStorm3/SplashyEngine
|
Engine/src/Input/Event.hpp
|
#pragma once
#include <stdint.h>
#include <string>
#include <functional>
#include <vector>
#include <typeinfo>
#include <utility>
#include "Input/KeyCodes.hpp"
namespace ant
{
using KeycodeType = KeyCode;
using ButtoncodeType = MouseButtonCode;
using ScrollType = double;
using MouseOffsetType = double;
using WindowSizeType = int32_t;
enum class EventType
{
None = 0,
KeyPressed,
KeyReleased,
MouseButtonPressed,
MouseButtonReleased,
MouseScrolled,
MouseMoved,
WindowRezised,
WindowMinimalized, // missing implemenration
WindowClosed,
WindowFocused,
WindowUnfocused
};
enum class EventCategory
{
None = 0,
Keyboard,
Mouse,
Window
};
#define SET_EVENT_TYPE(event_type) \
virtual const char *GetLog() override { return "Event: " #event_type; } \
inline static EventType GetStaticType() { return EventType::event_type; }
#define LOG_FUNC_OVERRIDE() virtual std::string GetStringLog() override;
class Event
{
public:
virtual ~Event() {}
virtual std::string GetStringLog() { return GetLog(); } // override manually
inline const EventType &GetEventType() { return m_type; }
virtual const char *GetLog() = 0;
void MarkHandled(bool state = true) { m_handled = state; }
friend class EventDispatcher;
friend class LayerStack;
EventCategory GetEventCategory();
bool IsInCategory(EventCategory category) { return GetEventCategory() == category; }
protected:
Event(EventType type) : m_type(type) {}
EventType m_type;
bool m_handled = false;
};
class EventDispatcher
{
public:
EventDispatcher() {}
EventDispatcher(Event &e) : m_event(&e) {}
~EventDispatcher() {}
void SetEventPtr(Event *e) { m_event = e; }
template <class evType>
bool DispatchEvent(const std::function<void(evType &)> &handler) //?check these casts
{
if (evType::GetStaticType() == m_event->GetEventType())
{
handler(static_cast<evType &>(*m_event));
return true;
}
return false;
}
private:
Event *m_event;
};
// KeyEvents
class KeyEvent
: public Event
{
public:
virtual ~KeyEvent() {}
LOG_FUNC_OVERRIDE();
inline KeycodeType GetKeyCode() { return m_key; }
bool HasModifier(KeyModifier mod) const;
protected:
KeyEvent(KeycodeType key, KeyModifier modifier, EventType type) : Event(type), m_key(key), m_modifier(modifier) {}
KeycodeType m_key;
KeyModifier m_modifier;
};
class KeyPressedEvent
: public KeyEvent
{
public:
KeyPressedEvent(KeycodeType key, KeyModifier modifier, bool repeating = false) : KeyEvent(key, modifier, EventType::KeyPressed), m_repeating(repeating) {}
~KeyPressedEvent() {}
SET_EVENT_TYPE(KeyPressed);
LOG_FUNC_OVERRIDE();
inline bool IsRepeating() { return m_repeating; }
private:
bool m_repeating;
};
class KeyReleasedEvent
: public KeyEvent
{
public:
KeyReleasedEvent(KeycodeType key, KeyModifier modifier) : KeyEvent(key, modifier, EventType::KeyReleased) {}
~KeyReleasedEvent() {}
SET_EVENT_TYPE(KeyReleased);
};
//MouseEvents
class MouseButtonEvent
: public Event
{
public:
virtual ~MouseButtonEvent() {}
inline ButtoncodeType GetButtonCode() { return m_button; }
bool HasModifier(KeyModifier mod) const;
LOG_FUNC_OVERRIDE();
protected:
MouseButtonEvent(EventType type, ButtoncodeType key, KeyModifier modifier) : Event(type), m_button(key), m_modifier(modifier) {}
KeyModifier m_modifier;
ButtoncodeType m_button;
};
class MouseButtonPressedEvent
: public MouseButtonEvent
{
public:
MouseButtonPressedEvent(ButtoncodeType button, KeyModifier modifier)
: MouseButtonEvent(EventType::MouseButtonPressed, button, modifier) {}
~MouseButtonPressedEvent() {}
SET_EVENT_TYPE(MouseButtonPressed);
};
class MouseButtonReleasedEvent
: public MouseButtonEvent
{
public:
MouseButtonReleasedEvent(ButtoncodeType button, KeyModifier modifier) : MouseButtonEvent(EventType::MouseButtonReleased, button, modifier) {}
~MouseButtonReleasedEvent() {}
SET_EVENT_TYPE(MouseButtonReleased);
};
class MouseScrolledEvent
: public Event
{
public:
struct ScrollData
{
ScrollType x, y;
};
public:
MouseScrolledEvent(const ScrollData &scrollData) : Event(EventType::MouseScrolled), m_scrollData(scrollData) {}
const ScrollData &GetScrollOffset() { return m_scrollData; }
~MouseScrolledEvent() {}
SET_EVENT_TYPE(MouseScrolled);
LOG_FUNC_OVERRIDE();
private:
ScrollData m_scrollData;
};
class MouseMovedEvent
: public Event
{
public:
struct MousePosData
{
MouseOffsetType x, y;
};
public:
MouseMovedEvent(MousePosData pos) : Event(EventType::MouseMoved), m_position(pos) {}
~MouseMovedEvent() {}
SET_EVENT_TYPE(MouseMoved);
LOG_FUNC_OVERRIDE();
inline const MousePosData &GetMousePos() { return m_position; }
private:
MousePosData m_position;
};
//WindowEvents
class WindowRezisedEvent
: public Event
{
public:
struct WindowSize
{
WindowSizeType x, y;
};
public:
WindowRezisedEvent(WindowSize size) : Event(EventType::WindowRezised), m_size(size) {}
~WindowRezisedEvent() {}
SET_EVENT_TYPE(WindowRezised);
inline const WindowSize &GetWindowSize() { return m_size; }
LOG_FUNC_OVERRIDE();
private:
WindowSize m_size;
};
class WindowMinimalizedEvent
: public Event
{
public:
WindowMinimalizedEvent() : Event(EventType::WindowMinimalized) {}
~WindowMinimalizedEvent() {}
SET_EVENT_TYPE(WindowRezised);
};
class WindowClosedEvent
: public Event
{
public:
WindowClosedEvent() : Event(EventType::WindowClosed) {}
~WindowClosedEvent() {}
SET_EVENT_TYPE(WindowClosed);
};
class WindowFocusedEvent
: public Event
{
public:
WindowFocusedEvent() : Event(EventType::WindowFocused) {}
~WindowFocusedEvent() {}
SET_EVENT_TYPE(WindowFocused);
};
class WindowUnfocusedEvent
: public Event
{
public:
WindowUnfocusedEvent() : Event(EventType::WindowUnfocused) {}
~WindowUnfocusedEvent() {}
SET_EVENT_TYPE(WindowUnfocused);
};
} // namespace ant
|
zhengyd2014/java-knowledge
|
src/main/java/com/watercup/kafka/TaskScheduler.java
|
package com.watercup.kafka;
import java.util.PriorityQueue;
public class TaskScheduler implements Runnable {
/*
有一個 class TaskScheduler which implements runnable, 加上一個 api schedule(task, delay)
實現這個 API
*/
PriorityQueue<TaskWrapper> taskQueue =
new PriorityQueue<>((a, b) -> Long.compare(a.executeAtMilliSecond, b.executeAtMilliSecond));
public synchronized void schedule(Task task, long delayInSeconds) {
taskQueue.offer(new TaskWrapper(task, delayInSeconds));
notifyAll();
}
public void run() {
while (true) {
synchronized(this) {
try {
while (taskQueue.isEmpty()) {
wait();
}
long sleepFor = taskQueue.peek().executeAtMilliSecond - System.currentTimeMillis();
if (sleepFor <= 0) {
TaskWrapper taskWrapper = taskQueue.poll();
taskWrapper.task.call();
} else {
wait(sleepFor);
}
} catch (InterruptedException ex) {
// do nothing
}
}
}
}
}
interface Task {
public void call();
}
class TaskWrapper {
Task task;
long executeAtMilliSecond;
public TaskWrapper(Task task, long delayInSeconds) {
this.task = task;
this.executeAtMilliSecond = System.currentTimeMillis() + delayInSeconds * 1000;
}
}
|
dlabaj/enmasse
|
mqtt-gateway/src/main/java/enmasse/mqtt/MqttGatewayOptions.java
|
<reponame>dlabaj/enmasse<gh_stars>1-10
/*
* Copyright 2016-2018, EnMasse authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package enmasse.mqtt;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
public class MqttGatewayOptions {
// binding info for listening
private String bindAddress;
private int listenPort;
// mqtt server options
private int maxMessageSize;
// connection info to the messaging service
private String messagingServiceHost;
private int messagingServicePort;
// SSL/TLS support stuff
private boolean ssl;
private String certFile;
private String keyFile;
private Duration startupTimeout;
public String getBindAddress() {
return bindAddress;
}
public void setBindAddress(String bindAddress) {
this.bindAddress = bindAddress;
}
public int getListenPort() {
return listenPort;
}
public void setListenPort(int listenPort) {
this.listenPort = listenPort;
}
public int getMaxMessageSize() {
return maxMessageSize;
}
public void setMaxMessageSize(int maxMessageSize) {
this.maxMessageSize = maxMessageSize;
}
public String getMessagingServiceHost() {
return messagingServiceHost;
}
public void setMessagingServiceHost(String messagingServiceHost) {
this.messagingServiceHost = messagingServiceHost;
}
public int getMessagingServicePort() {
return messagingServicePort;
}
public void setMessagingServicePort(int messagingServicePort) {
this.messagingServicePort = messagingServicePort;
}
public boolean isSsl() {
return ssl;
}
public void setSsl(boolean ssl) {
this.ssl = ssl;
}
public String getCertFile() {
return certFile;
}
public void setCertFile(String certFile) {
this.certFile = certFile;
}
public String getKeyFile() {
return keyFile;
}
public void setKeyFile(String keyFile) {
this.keyFile = keyFile;
}
public Duration getStartupTimeout() {
return startupTimeout;
}
public void setStartupTimeout(Duration startupTimeout) {
this.startupTimeout = startupTimeout;
}
private static Optional<String> getEnv(Map<String, String> env, String envVar) {
return Optional.ofNullable(env.get(envVar));
}
public static MqttGatewayOptions fromEnv(Map<String, String> env) {
MqttGatewayOptions options = new MqttGatewayOptions();
options.setMessagingServiceHost(getEnv(env, "MESSAGING_SERVICE_HOST")
.orElse("0.0.0.0"));
options.setMessagingServicePort(getEnv(env, "MESSAGING_SERVICE_PORT")
.map(Integer::parseInt)
.orElse(5672));
options.setStartupTimeout(getEnv(env, "ENMASSE_MQTT_STARTUPTIMEOUT")
.map(i -> Duration.ofSeconds(Long.parseLong(i)))
.orElse(Duration.ofSeconds(20)));
options.setBindAddress(getEnv(env, "ENMASSE_MQTT_BINDADDRESS")
.orElse("0.0.0.0"));
options.setListenPort(getEnv(env, "ENMASSE_MQTT_LISTENPORT")
.map(Integer::parseInt)
.orElse(1883));
options.setSsl(getEnv(env, "ENMASSE_MQTT_SSL")
.map(Boolean::parseBoolean)
.orElse(false));
options.setMaxMessageSize(getEnv(env, "ENMASSE_MQTT_MAXMESSAGESIZE")
.map(Integer::parseInt)
.orElse(131072));
options.setCertFile(getEnv(env, "ENMASSE_MQTT_CERTFILE")
.orElse("./src/test/resources/tls/server-cert.pem"));
options.setKeyFile(getEnv(env, "ENMASSE_MQTT_KEYFILE")
.orElse("./src/test/resources/tls/server-key.pem"));
return options;
}
@Override
public String toString() {
return "MqttGatewayOptions{" +
"bindAddress='" + bindAddress + '\'' +
", listenPort=" + listenPort +
", maxMessageSize=" + maxMessageSize +
", messagingServiceHost='" + messagingServiceHost + '\'' +
", messagingServicePort=" + messagingServicePort +
", ssl=" + ssl +
", certFile='" + certFile + '\'' +
", keyFile='" + keyFile + '\'' +
", startupTimeout=" + startupTimeout +
'}';
}
}
|
haizhenhan/Kepler
|
kernel/2.6.32/drivers/staging/otus/hal/hpfwu_OTUS_RC.c
|
/*
* Copyright (c) 2007-2008 Atheros Communications Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "cprecomp.h"
const u32_t zcFwImage[] = {
0x0009000B, 0x4F222FE6, 0xDE287FFC, 0xE114D728,
0x1E13D428, 0x1E4C470B, 0x0009B018, 0xA0039543,
0x3652E600, 0x76018D04, 0xC84060E2, 0x2F028DF9,
0xDE22D421, 0x00094E0B, 0x4E0BD421, 0xD4210009,
0x00094E0B, 0x4F267F04, 0x6EF6A022, 0xD11E4F22,
0x0009410B, 0x440BD41D, 0xD51D0009, 0x0009450B,
0xE1FFD71C, 0xD21C611D, 0x50292712, 0xCB01E1FF,
0xD61BD41A, 0x22121209, 0xE5011211, 0x2452E200,
0xD5182622, 0x970FD618, 0x4F262572, 0x2620000B,
0xDD17DC16, 0x4C0BDE17, 0x4D0B0009, 0x4E0B0009,
0xAFF80009, 0x27100009, 0x00000640, 0x001C001C,
0x002008EA, 0x0000B38E, 0x002028DC, 0x00200DA6,
0x002028E8, 0x00202900, 0x00200C6C, 0x00200EA2,
0x00200940, 0x001C3510, 0x001C3624, 0x001E212C,
0x00202894, 0x0020288C, 0x002027F0, 0x00200B68,
0x00201F74, 0x00201734, 0x2FD62FC6, 0x4F222FE6,
0xDEA17FA4, 0x61E0E01C, 0x7D016DE3, 0x61D00F14,
0xD59FD49E, 0x450BE020, 0xE0200F14, 0xE78004FC,
0x604C66E2, 0x7D7F677C, 0x1F693070, 0x2D628F17,
0x01FCE01C, 0x641CE500, 0xD797DE96, 0x3243625D,
0xA21A8B01, 0x655D0009, 0x31EC6153, 0xE0286C10,
0x6D530FC4, 0x3D7C62CE, 0xAFEF2D20, 0x20087501,
0xE01C8B15, 0xE50001FC, 0xD78BDE8A, 0x641CA00A,
0x6C53655D, 0x66C23CEC, 0x66626253, 0x2262327C,
0x1F697504, 0x3243625D, 0xA1F68BF2, 0x88012D10,
0xE01C8B16, 0xE40001FC, 0x671C2D40, 0x624DDE7D,
0x8B013273, 0x0009A1E9, 0x62E3644D, 0x72046D43,
0x3DEC6143, 0x65D2312C, 0x74086C12, 0x25C2AFEF,
0x8B188804, 0x01FCE01C, 0x2D40E400, 0xDE71671C,
0x3273624D, 0xA1D08B01, 0x644D0009, 0x62E36D43,
0x65D23DEC, 0x61437204, 0x6612312C, 0x74086C52,
0xAFED2C69, 0x880525C2, 0xE01C8B18, 0xE40001FC,
0x671C2D40, 0x624DDE63, 0x8B013273, 0x0009A1B5,
0x6C43644D, 0x3CEC62E3, 0x720465C2, 0x3D2C6D43,
0x615266D2, 0x216B7408, 0x2512AFED, 0x8B138830,
0xE200DE58, 0x64E22D20, 0x8B042448, 0x420BD257,
0xA19A0009, 0x55E10009, 0x57E356E2, 0xDD545CE4,
0x2FC64D0B, 0x7F04A191, 0x89018828, 0x0009A0EA,
0xE143DE4C, 0x622D62E1, 0x8F033217, 0x56FB1FEB,
0x2621E240, 0x8B013217, 0x0009A0D5, 0xE1015EFB,
0x301685E1, 0xA0CE8B01, 0xE4010009, 0x2D4055FB,
0x6451B179, 0xE14357FB, 0xE0546271, 0x3517652D,
0x0F568D41, 0x3563E640, 0xE6008B05, 0x0F65E034,
0xA00FE11A, 0x615372C0, 0x41214121, 0x41214121,
0x45214121, 0x45214521, 0xC9036053, 0xE0346603,
0x71180F65, 0x2209E007, 0x641DE030, 0x0F2565F3,
0x1F4EB1F1, 0x04FDE034, 0x674DE030, 0x47080CFD,
0x607361CD, 0x4108D22B, 0xE00F0CFE, 0x1F1F420B,
0x2CD96D07, 0x5EFB6073, 0x85E20FC6, 0x420B51FF,
0x2C0B600D, 0x54FE6073, 0xB1BB0FC6, 0xE05465F3,
0x652D62E1, 0xE6400F56, 0x89623563, 0xE050E100,
0x60230F15, 0x4008C903, 0x6D034000, 0xE0406103,
0xE0440FD6, 0xD217EEFF, 0x6EEC0FF6, 0x0F26E058,
0x60E3420B, 0x42216253, 0x42214221, 0x66234221,
0x326C4200, 0x45214200, 0xE0486707, 0x0F764521,
0xC9036053, 0x40085CFB, 0x7C0630FC, 0x6E036D2D,
0x1FD51FC6, 0x1F04A02E, 0x00117D00, 0x00202904,
0x00200DA6, 0x00117D04, 0x00117D84, 0x00200700,
0x0020074C, 0x00201FD4, 0x0FD6E04C, 0x05FEE044,
0x64D3B189, 0x64E2E048, 0xE04006FE, 0x2E422469,
0x01FE67C4, 0x667CE058, 0x420B02FE, 0x240B6063,
0x05FEE044, 0xB15D2E42, 0xE05064D3, 0x7D0101FD,
0x0F157101, 0x02FDE050, 0x3262E606, 0x56FB8BDC,
0x55FB6261, 0x85514200, 0x302C750C, 0x6103701B,
0x64F3E600, 0xE704A004, 0x76016256, 0x74042422,
0x3273626D, 0x65F38BF8, 0x641DB13C, 0xB0D256FB,
0xA0AA6461, 0xD4880009, 0xE201D588, 0x2D20450B,
0x0009A0A3, 0x8B078829, 0xE200DE85, 0x66E22D20,
0x646DB0A1, 0x0009A099, 0x622CE281, 0x8B3D3020,
0xD680E738, 0xE0442D70, 0xE0480C6E, 0x6E621DC1,
0x51611DE2, 0x54621D13, 0x55651D44, 0x57631D55,
0x5C661D76, 0x0E6E1DC7, 0x1DE8E040, 0xE050016E,
0x54641D19, 0x056E1D4A, 0x1D5BE04C, 0xE054076E,
0x0C6E1D7C, 0x1DCDE058, 0xE044026E, 0xED001D2E,
0xE04806D6, 0x16D126D2, 0x16D516D2, 0x16D616D3,
0xE04006D6, 0xE05006D6, 0x06D616D4, 0x06D6E04C,
0x06D6E054, 0x06D6E058, 0x1F29A057, 0x622CE282,
0x89313020, 0x05FCE020, 0x625CE683, 0x3260666C,
0xD65D8B07, 0x2650E500, 0x52617680, 0xA044D65B,
0xE6902622, 0x3260666C, 0xD2578B16, 0xE500D658,
0x60622250, 0xCB20D257, 0xE6052602, 0xD6562262,
0x2252460B, 0x420BD255, 0xD2550009, 0x2262E601,
0x4618D254, 0x2262A029, 0xD254D453, 0xD4546542,
0x0009420B, 0x0009A021, 0xE524D647, 0xD5452650,
0x16215257, 0x16225258, 0x16235259, 0x1624525A,
0x1625525B, 0x1626525C, 0x1627525D, 0x1628525E,
0x1F29525F, 0xE2001629, 0x15281527, 0x152A1529,
0x152C152B, 0x152E152D, 0x7F5C152F, 0x6EF64F26,
0x000B6DF6, 0x4F226CF6, 0xE240614D, 0x89173123,
0x3127E21F, 0xD43B8908, 0xE001D53B, 0x6642450B,
0x26796707, 0x2462A00C, 0x3127E23F, 0xD7358908,
0x71E0D635, 0x460BE001, 0x62075571, 0x17512529,
0x000B4F26, 0x4F220009, 0xE240614D, 0x89153123,
0x3127E21F, 0xD42B8907, 0x6642D22B, 0xE001420B,
0xA00B260B, 0xE23F2462, 0x89073127, 0xD626D725,
0x71E05571, 0xE001460B, 0x1751250B, 0x000B4F26,
0xE6400009, 0x46284618, 0x6252D520, 0x89FC2268,
0x0009000B, 0x4618E680, 0xD51C4628, 0x22686252,
0x000B89FC, 0xA0010009, 0x7201E200, 0x8BFC3242,
0x0009000B, 0x4618E680, 0xD5154628, 0x22686252,
0x000B8BFC, 0x00000009, 0x00202908, 0x00200DA6,
0x00117D04, 0x002027F8, 0x00117D80, 0x0020288C,
0x001C3500, 0x001D4004, 0x00200EA2, 0x00200940,
0x001E212C, 0x001C3D28, 0x00117D00, 0x00200E06,
0x00202920, 0x001C3704, 0x00201FD4, 0x001C373C,
0x001C3700, 0x4F222FE6, 0x6E537FFC, 0x2F42BFCA,
0xD61561E2, 0x1615E280, 0x421854E1, 0x55E21646,
0x16574228, 0x6EF257E3, 0x2E2B1678, 0x7F0426E2,
0xAFA74F26, 0x2FC66EF6, 0x2FE62FD6, 0xDD0A4F22,
0xBFAF6C53, 0xBF946E43, 0xBFAB2DE2, 0x51D50009,
0x54D62C12, 0x55D71C41, 0x56D81C52, 0x4F261C63,
0x6DF66EF6, 0x6CF6000B, 0x001C370C, 0x0009A0C0,
0xD17B4F22, 0xD47B92B6, 0x2122B00D, 0x97B2E605,
0xB02295B2, 0xB0366463, 0xB0360009, 0xB0390009,
0xA0680009, 0x4F124F26, 0xD1734F02, 0x94A43145,
0x4609060A, 0x46094609, 0x00293646, 0xD76CD56F,
0x2500CA01, 0x4F062762, 0x4F16000B, 0xBFEA4F22,
0xB01F0009, 0xA04E0009, 0x2FE64F26, 0x6E63D168,
0x44186612, 0x4528928A, 0x26294408, 0x44084500,
0x4400265B, 0x4708264B, 0x47082162, 0x27EBD161,
0x000B2172, 0x000B6EF6, 0xD25F0009, 0xE40A9677,
0x2262AFB4, 0x2FC62FB6, 0x2FE62FD6, 0xDC5B4F22,
0x2C22E201, 0xBFA9E40A, 0x60C27C44, 0xCB01ED00,
0x60C22C02, 0xC901EB64, 0x6E03A008, 0x89073DB2,
0xE40160C2, 0xBF99C901, 0x7D016E03, 0x8BF52EE8,
0x8B033DB2, 0xD24FD44E, 0x0009420B, 0x4F26E40A,
0x6DF66EF6, 0xAF896CF6, 0x44116BF6, 0x604B8F01,
0x000B6043, 0x2FB60009, 0x2FD62FC6, 0x4F222FE6,
0xDC457FFC, 0x60C2ED00, 0xCB02EB64, 0x60C22C02,
0xC9022F02, 0x6E03A009, 0x89083DB3, 0xE46460C2,
0xC9022F02, 0x6E03BF6A, 0x2EE87D01, 0xD73B8BF4,
0x617251C1, 0xDE3BDC3A, 0xD23CD13B, 0x64C23DB3,
0x651264E2, 0x65228F09, 0xD232D439, 0x4F267F04,
0x6DF66EF6, 0x422B6CF6, 0x7F046BF6, 0x6EF64F26,
0x6CF66DF6, 0x6BF6000B, 0x5651D532, 0x46286052,
0x306C000B, 0x5288096C, 0x09B45BB4, 0x03C41FFF,
0x2FC62FB6, 0x2FE62FD6, 0x4F124F22, 0xBFEB4F02,
0x6B036E43, 0xDD18DC28, 0x0009BFE6, 0x3C0530B8,
0x4609060A, 0x46014609, 0x020A3D65, 0x42094209,
0x32E24209, 0x4F068BF0, 0x4F264F16, 0x6DF66EF6,
0x000B6CF6, 0x2FE66BF6, 0xDE1C4F22, 0xE500E102,
0x2E12E403, 0x2E52BFD4, 0x4618E606, 0xE403E700,
0x2E722E62, 0xAFCB4F26, 0x000B6EF6, 0x00000009,
0x00202890, 0x0024CDE0, 0x10624DD3, 0x00202A8C,
0x001C5814, 0x001C59D0, 0x001C5804, 0x001C581C,
0x00202934, 0x00200DA6, 0x001C5860, 0x001C6864,
0x001C7864, 0x001C59BC, 0x001C69BC, 0x001C79BC,
0x0020294C, 0x001C1040, 0xCCCCCCCD, 0x001D4004,
0x2F962F86, 0x2FB62FA6, 0x2FD62FC6, 0x4F222FE6,
0xE4007FE4, 0x4528E510, 0x67436C43, 0xE107A00F,
0x6043644D, 0x0F564008, 0xEE0060C3, 0x815125C1,
0x81538152, 0x157315E2, 0x751415E4, 0x624D7401,
0x8BED3213, 0xDA6F51F1, 0x1A1154F2, 0xD16E2A12,
0x57F455F3, 0x6DF258F5, 0x1141D96C, 0x11532142,
0x11751152, 0x11871174, 0x52F61186, 0x19D1D668,
0xD86829D2, 0xDA68E950, 0x1621EBB4, 0x6BBC2622,
0xA0214908, 0x6EEDEE00, 0x61E36DE3, 0x41084D08,
0x31EC3DEC, 0x41084D08, 0x60C33D8C, 0xE7904108,
0x81D12DC1, 0x41086093, 0x81D2677C, 0x31AC60C3,
0x3472E200, 0x1DD281D3, 0xD4551D13, 0x1D248D01,
0xB03AD450, 0x7E0165D3, 0x34B264ED, 0xD14D8BDB,
0x6512DB52, 0x4529D24D, 0x64121B51, 0x674DD14A,
0x67222B72, 0x4729D64E, 0x69221B73, 0x689D2FD2,
0x69121B82, 0x5A122692, 0x5B1416A2, 0x16B4DA44,
0x16C65C16, 0x16EA6EA2, 0x4F267F1C, 0x6DF66EF6,
0x6BF66CF6, 0x69F66AF6, 0x68F6000B, 0x60616642,
0x8D04C803, 0x6061E500, 0x8802C903, 0x52628B03,
0x51246563, 0x000B2412, 0x2FD66053, 0x4F222FE6,
0x6E537FEC, 0xE5506253, 0xE4006D43, 0xA0014508,
0x5224E101, 0x22116043, 0x81238121, 0x81226053,
0x362056E2, 0xD22F8BF5, 0x64F316E4, 0x420BE614,
0x65E165E3, 0x2549E4FC, 0x61F12E51, 0x214965F3,
0x54D12F11, 0x410BD127, 0x57D1E614, 0xCB016071,
0x1DE12701, 0x4F267F14, 0x000B6EF6, 0x2FD66DF6,
0x4F222FE6, 0x6E537FEC, 0xE5FC6653, 0x60616D43,
0xCB012059, 0x52E22601, 0x8B063260, 0x51E212E4,
0x8B0431E0, 0xA00252D1, 0xAFF01E22, 0xD2155664,
0xE61464F3, 0x65E3420B, 0xE1FC67E1, 0x2E712719,
0x54D167F1, 0xD10F2719, 0xE61465F3, 0x2F71410B,
0x602152D1, 0x2201CB01, 0x7F141DE1, 0x6EF64F26,
0x6DF6000B, 0x0020285C, 0x00202864, 0x00202854,
0x00202884, 0x0010008C, 0x00100EC0, 0x001E2108,
0x001C3D00, 0x00202134, 0x2FC62FB6, 0x2FE62FD6,
0xD6314F22, 0x60D36D62, 0x894DC803, 0xDB30DC2F,
0x0009A02C, 0xC9036061, 0x892B8801, 0xD22DD42B,
0x0009420B, 0x65035603, 0xC8208561, 0xE0508903,
0x720102BE, 0x85620B26, 0x4000600D, 0x4000366A,
0x40004624, 0x206D4624, 0xD423C903, 0x40086E03,
0xD1224000, 0x340C410B, 0x61E3D521, 0xD721E001,
0x450BD221, 0x64E37E30, 0x2702420B, 0x66C252C1,
0x8BCF3620, 0x4E18EE01, 0xA011DB1C, 0x6061EC75,
0x8801C903, 0xD4198910, 0x460BD612, 0xD4180009,
0x470BD718, 0xD2136503, 0x64C3D113, 0x22E2410B,
0x66B252B1, 0x8BEA3620, 0xC80460D3, 0xD2128906,
0x6EF64F26, 0x6CF66DF6, 0x6BF6422B, 0x6EF64F26,
0x6CF66DF6, 0x6BF6000B, 0x001E2100, 0x0020285C,
0x002027F8, 0x00200A5C, 0x00202864, 0x00200ADE,
0x00201FD4, 0x001C3D30, 0x00200D6C, 0x00202854,
0x00202884, 0x00200A7A, 0x002000F8, 0xE601D237,
0x1265D537, 0x000B2252, 0xD6361266, 0x88016062,
0xE1018B62, 0xD5342612, 0x5451D134, 0xE0406212,
0x2122324C, 0x54115752, 0x1141347C, 0x57125453,
0x1172374C, 0x52135755, 0x1123327C, 0x56146452,
0x1164364C, 0x54155754, 0x1145347C, 0x56165458,
0x1166364C, 0x6762D626, 0x327C5217, 0x57611127,
0x327C5218, 0x57621128, 0x327C5219, 0x57631129,
0x347C541A, 0x5764114A, 0x347C541B, 0x5765114B,
0x347C541C, 0x5266114C, 0x372C571D, 0x5267117D,
0x342C541E, 0x5268114E, 0x362C561F, 0xD615116F,
0x041E6262, 0x342C7694, 0xE0440146, 0x061E6262,
0x0166362C, 0x525CE048, 0xD60F051E, 0x0156352C,
0xE0546262, 0x4229051E, 0x0156352C, 0xE0585561,
0x4529061E, 0x0166365C, 0x0009000B, 0x001C1010,
0x0000C34F, 0x001C1028, 0x001C369C, 0x002027F8,
0x001C3CA0, 0x001C36F4, 0x001C3B88, 0xD62F7FFC,
0x2642644C, 0xC8205066, 0x2F028DFC, 0x7F04000B,
0x2FD62FC6, 0x4F222FE6, 0x6D436C53, 0xEE00A004,
0x7E0164D4, 0x644CBFEA, 0x8BF93EC2, 0x6EF64F26,
0x000B6DF6, 0xA0016CF6, 0x76016643, 0x22286260,
0x36488BFB, 0x6563AFE4, 0x2FB62F96, 0x2FD62FC6,
0x4F222FE6, 0xEC1CED08, 0xDB196E53, 0x61C3E90A,
0x60434B0B, 0x3092C90F, 0x66038D02, 0x7630A001,
0x4D107637, 0x7E012E60, 0x7CFC8FF1, 0x8058E000,
0x6EF64F26, 0x6CF66DF6, 0x000B6BF6, 0x000B69F6,
0x000BE000, 0x2FE6E000, 0x7FEC4F22, 0x6E436253,
0xBFD165F3, 0xBFC66423, 0xBFC464E3, 0xD40564F3,
0x0009BFC1, 0x4F267F14, 0x6EF6000B, 0x001C0004,
0x00202094, 0x00202968, 0xE110D59C, 0xE6406050,
0x2500C9FD, 0xE0FF75E9, 0x80516453, 0x80538052,
0x80568055, 0x251075EF, 0xE1EF6250, 0x2219E001,
0xE7202520, 0x24608052, 0x2570000B, 0xE4FDD590,
0xE7026152, 0x25122149, 0x74016052, 0x2502CB01,
0xD18C6652, 0x25622649, 0x92C26012, 0x2102CB08,
0xC9CF6012, 0x60122102, 0x2102CB03, 0x000B1172,
0x4F221123, 0xE100D484, 0xD285D784, 0xD5852410,
0x2711D485, 0x2211E700, 0xBFBD2511, 0xD5832471,
0x2560E600, 0x4F26AFD2, 0xD281664C, 0x362C4600,
0xCB106060, 0x2600000B, 0xD27D654C, 0x352C4500,
0xE1EF6650, 0x000B2619, 0x664C2560, 0x4600D279,
0x6060362C, 0x000BCB10, 0x654C2600, 0x4500D275,
0x6650352C, 0x2619E1EF, 0x2560000B, 0xD270664C,
0x362C4600, 0xCB086060, 0x2600000B, 0xD26C654C,
0x352C4500, 0xE1F76650, 0x000B2619, 0x664C2560,
0x4600D268, 0x6060362C, 0x000BCB08, 0x654C2600,
0x4500D264, 0x6650352C, 0x2619E1F7, 0x2560000B,
0xD65F624C, 0x326C4200, 0xC9086020, 0x40214021,
0x000B4021, 0x624C600C, 0x4200D65A, 0x6020326C,
0x4021C908, 0x40214021, 0x600C000B, 0xD156644C,
0x341C74FF, 0x000B6240, 0xD154602C, 0x341C644C,
0x000B6240, 0x2FE6602C, 0x655C4F22, 0x3567E60A,
0x6E438D15, 0x6453BFEA, 0x60EC640C, 0x8B028801,
0xA002E00F, 0x44092409, 0x624C4409, 0x3263E60A,
0xBFE28905, 0x620C644C, 0xC8806023, 0xE2008B00,
0x4F266023, 0x6EF6000B, 0xD6414F22, 0x88016062,
0xB2228B03, 0xA0030009, 0xD23E0009, 0x2260E640,
0xE200D63D, 0x000B4F26, 0x4F222622, 0x6062D638,
0x8B018802, 0x0009B26C, 0xE200D637, 0x000B4F26,
0x0FFF2622, 0xD433D532, 0xE701E100, 0x000B2512,
0xD2302470, 0x000BE604, 0xD5202260, 0x6150E4FD,
0x2149D62E, 0x2510E700, 0x2670000B, 0xE4FBD51B,
0x22496250, 0x2520000B, 0xE4F7D518, 0x22496250,
0x2520000B, 0xD2264F22, 0x600D8522, 0x89112008,
0x89138801, 0x89158803, 0x89178805, 0x89418806,
0x89478808, 0x894D8809, 0x8953880A, 0x8959880B,
0x0009A060, 0x0009B062, 0x600CA05D, 0x0009B070,
0x600CA059, 0x0009B07A, 0x600CA055, 0x6260D606,
0x8B4F2228, 0x0009B086, 0x600CA04D, 0x001E1028,
0x001E2148, 0x001E1108, 0x002028D9, 0x002028C8,
0x002028CA, 0x002028CC, 0x002028AC, 0x001E1008,
0x001E103F, 0x001E105F, 0x001E1030, 0x001E1090,
0x002028D4, 0x001E100B, 0x002028D0, 0x002028D8,
0x002028A0, 0x6260D687, 0x8B232228, 0x0009B06A,
0x600CA021, 0x6260D683, 0x8B1B2228, 0x0009B0B4,
0x600CA019, 0x6260D67F, 0x8B132228, 0x0009B0BA,
0x600CA011, 0x6260D67B, 0x8B0B2228, 0x0009B11E,
0x600CA009, 0x6260D677, 0x8B032228, 0x0009B136,
0x600CA001, 0x4F26E000, 0x0009000B, 0xD273D172,
0xD5738412, 0x4000C90F, 0xD772012D, 0x611CE403,
0xD671E20F, 0x27122540, 0xE0012520, 0x2602000B,
0xE601D269, 0x30668523, 0xE0008D06, 0xE000D267,
0x8122D669, 0x2602E001, 0x0009000B, 0x8523D262,
0x2008600D, 0x88018905, 0xD6648B0A, 0xCB016060,
0xD6612600, 0xE101D45D, 0x2612E001, 0x8142000B,
0xE000000B, 0xE501D158, 0x45188513, 0x3453640D,
0x8D056603, 0xD25AE000, 0xE001D557, 0x25022260,
0x0009000B, 0xD1504F22, 0x650D8513, 0x44196453,
0x672E6249, 0x602C227D, 0x89098801, 0x890C8802,
0x89108803, 0x89268806, 0x89298807, 0x0009A038,
0xD64DD54C, 0xA027E212, 0x625C2652, 0x8B2F2228,
0xA01ED64A, 0x605C6262, 0x89052008, 0x89088810,
0x890B8820, 0x0009A024, 0xD643D445, 0xA013E204,
0xD7442642, 0xE20CD640, 0x2672A00E, 0xD63ED542,
0xA009E218, 0xD4412652, 0xE20AD63B, 0x2642A004,
0xD639D23F, 0xE22E2622, 0xD43E8515, 0x3277670D,
0x8F012421, 0x24516503, 0x0009B0DF, 0xE001A001,
0x4F26E000, 0x0009000B, 0xE101D629, 0x2610D436,
0xD7286541, 0x655DD128, 0xE001E20F, 0x26202752,
0x2102000B, 0x4F222FE6, 0x8523D21F, 0x2448640C,
0xD62D8B08, 0xE200D521, 0x84512621, 0x20499430,
0x8051A026, 0x60E0DE1D, 0x8D0BC840, 0x3427E201,
0xD1258922, 0x420BD225, 0xD5252141, 0xCB046052,
0x2502A00B, 0x89173427, 0xD722D21F, 0x2241470B,
0xE5FBD61F, 0x21596162, 0x84E12612, 0xB12DCB80,
0x60E080E1, 0xCB04D61C, 0x60602E00, 0x2600C93F,
0xE001D609, 0x2602A001, 0x4F26E000, 0x6EF6000B,
0x0000FF7F, 0x002028D9, 0x002028A0, 0x002028AC,
0x001E1100, 0x001E100C, 0x002028D0, 0x001E1000,
0x001E1001, 0x00202A90, 0x002028B4, 0x002028BC,
0x00202AFE, 0x00202B02, 0x00202B0E, 0x00202B26,
0x00202B30, 0x002028B8, 0x002028C6, 0x00201A32,
0x001E1108, 0x00201B3E, 0x001E1015, 0x6060D696,
0x8919C880, 0x6021D295, 0x8B158801, 0xE501D294,
0x30568524, 0xD1938910, 0xD493E203, 0x65412120,
0x655DE00B, 0xD5910656, 0xE702E40F, 0x25712140,
0xE001D78F, 0x2702000B, 0xE000000B, 0x4F222FE6,
0x84E1DE8C, 0x8934C880, 0x8554D585, 0x8F302008,
0xD7896103, 0x66728553, 0x650C6403, 0x620C8566,
0x8B263520, 0xD780D685, 0x644C651C, 0x27412651,
0xC84060E0, 0xD2828907, 0x0009420B, 0x6062D681,
0xA008CB04, 0xD1802602, 0x0009410B, 0xE5FBD67D,
0x24596462, 0xB0A12642, 0xD5750009, 0x2522E201,
0xD77A60E0, 0x2E00CB04, 0xC93F6070, 0xA0012700,
0xE0006023, 0x000B4F26, 0x2FA66EF6, 0x2FC62FB6,
0x2FE62FD6, 0xE240DA69, 0xDC6666A1, 0x3123616D,
0x62638900, 0x6ED36D2C, 0x4E2136D8, 0x4E212A61,
0xDB6CD46B, 0xE700A00F, 0x770166B2, 0x71026163,
0x65612B12, 0x71026613, 0x62612B12, 0x622D655D,
0x325C4228, 0x627C2422, 0x8BED32E3, 0xC90360D3,
0x8B108803, 0xED076EB2, 0x710261E3, 0x67132B12,
0x62E17102, 0x65712B12, 0x655D622D, 0x352C4528,
0xA00C2CD0, 0x88022452, 0xA0038B01, 0x8801E203,
0xE2018B05, 0x66B22C20, 0x677D6761, 0xEB0F2472,
0x6DA12CB0, 0x8B052DD8, 0xD445D24F, 0xE101EE00,
0x241222E2, 0x6DF66EF6, 0x6BF66CF6, 0x6AF6000B,
0x2FE62FD6, 0xE240DD3D, 0x616D66D1, 0x89003123,
0x672C6263, 0xDE433678, 0x2D617703, 0xD6404721,
0x472164E2, 0xE100A00E, 0x71016562, 0x24506253,
0x42197401, 0x74012420, 0x24504529, 0x45197401,
0x74012450, 0x3273621C, 0x42008BEE, 0x64D166E2,
0x362C4200, 0x8F062448, 0xDD332E62, 0xE500DE28,
0x2D52E701, 0x6EF62E72, 0x6DF6000B, 0x2FE62FD6,
0xEE014F22, 0xED0AA005, 0x64E3BCB6, 0x64E3BCBC,
0x62EC7E01, 0x8BF732D7, 0xEE01A005, 0x64E3BCBD,
0x64E3BCC3, 0x62EC7E01, 0x8BF732D7, 0x6EF64F26,
0x6DF6000B, 0x2FE62FD6, 0x7FFC4F22, 0x6060D61F,
0x89758801, 0xE101D41E, 0xD7128548, 0x650D2610,
0x45196070, 0x6659DD1B, 0x61D3626E, 0xC840262D,
0x74027102, 0x8D47D718, 0xD218666C, 0xE501DE0A,
0xA0312E22, 0x0000EE04, 0x001E1001, 0x002028C6,
0x002028A0, 0x001E1100, 0x002028CA, 0x002028B8,
0x002028D0, 0x001E1000, 0x002028BC, 0x002028C8,
0x00201A32, 0x001E1108, 0x00201B3E, 0x001E1015,
0x001E100C, 0x002028B4, 0x002028D4, 0x002028D8,
0x00202A90, 0x00202B26, 0x00202B32, 0x00202AA2,
0x75016245, 0x71022121, 0x32E3625C, 0x60638BF8,
0xE60181D4, 0xE417D538, 0x3243626C, 0x6255891E,
0x27217601, 0x7702AFF8, 0xDE35D234, 0x2E22E501,
0xEE04A004, 0x75016245, 0x71022121, 0x32E3625C,
0x60638BF8, 0xE60181D4, 0xA004D52E, 0x6255E417,
0x27217601, 0x626C7702, 0x8BF83243, 0x2D21924B,
0xD72AD429, 0x2F126142, 0x6DF265F2, 0xC9806053,
0x60532700, 0x6103C960, 0x60538071, 0x65F26EF2,
0x4D19C903, 0x80724529, 0x451960DC, 0x4E298172,
0x62EC605C, 0x302C4018, 0x6D428173, 0x2FD22118,
0x62F26EF2, 0x421966F2, 0x656C4629, 0x602C66F2,
0x401864EC, 0x304C4629, 0x81744619, 0x4018606C,
0x8F07305C, 0xBCB58175, 0x620C0009, 0x89082228,
0x0009A00A, 0x88406013, 0xB00A8B03, 0xA0030009,
0xD60B0009, 0x2622E202, 0x4F267F04, 0x000B6EF6,
0x000B6DF6, 0x060A0009, 0x00202AD2, 0x00202AD0,
0x002028BC, 0x00202AA4, 0x001E100C, 0x002028A0,
0x002028D0, 0x7FFC4F22, 0x6620D27E, 0x8D082668,
0xD47D2F60, 0x420BD27D, 0x64F00009, 0xA0907F04,
0x7F044F26, 0x000B4F26, 0x000B0009, 0x2FE60009,
0xDE774F22, 0x60E0D677, 0xCBC0D477, 0x62602E00,
0xC803602C, 0x40218904, 0x70014021, 0x6603A002,
0x66034009, 0xD671616D, 0xE500A004, 0x75016262,
0x74042422, 0x3213625D, 0xD16D8BF8, 0x0009410B,
0xE401D66C, 0x84E22641, 0x80E2C9BF, 0x000B4F26,
0x2FE66EF6, 0xD5687FFC, 0x6250DE61, 0x642C84E2,
0xCB407404, 0x80E2614D, 0x44216413, 0xD7634421,
0xE600A004, 0x76016256, 0x27222F22, 0x3243626D,
0x60138BF8, 0x2008C903, 0x88038912, 0x88028905,
0x88018906, 0xA0088907, 0xE0070009, 0x8078A005,
0xA002E003, 0xE0018078, 0x62528078, 0x27222F22,
0xD650E00F, 0x60618078, 0x8B018801, 0x2621E200,
0x6060D64F, 0x2600CB08, 0xC93F60E0, 0x7F042E00,
0x6EF6000B, 0x6021D247, 0x8D188801, 0xD2466143,
0x22106053, 0x60638021, 0xD4468121, 0xE500A007,
0x027C605D, 0x364C6603, 0x26207001, 0x625D6503,
0x3213611C, 0xD6408BF4, 0xC9BF6060, 0x000B2600,
0x2FD60009, 0x4F222FE6, 0x60437FFC, 0x8D02C820,
0xBF6A6E43, 0x60E30009, 0x8901C810, 0x0009BF67,
0xC84060E3, 0xBF8C8901, 0x60E30009, 0x8929C801,
0x60D0DD32, 0x8D03C802, 0xD6312F00, 0x0009460B,
0xC80460F0, 0xD62F8902, 0x0009460B, 0x602362F0,
0x8902C880, 0xC97F60D0, 0x60232D00, 0x8902C801,
0x420BD229, 0xD5290009, 0x88026052, 0xD2288B03,
0xA005E604, 0x88012260, 0xD2258B02, 0x2260E601,
0x2522E200, 0xC88060E3, 0xD2228916, 0x60E36E20,
0x8902C802, 0x420BD220, 0x60E30009, 0x8902C804,
0x420BD21E, 0x60E30009, 0x8905C808, 0x7F04D21C,
0x6EF64F26, 0x6DF6422B, 0x4F267F04, 0x000B6EF6,
0x00006DF6, 0x001E1020, 0x0020296C, 0x00200DA6,
0x001E1015, 0x001E10BF, 0x00117D00, 0x001E10FC,
0x002000F8, 0x002028CC, 0x00117D80, 0x001E10F8,
0x001E10AE, 0x00117D84, 0x001E1017, 0x001E1021,
0x00200FD8, 0x00200FFA, 0x00201584, 0x002028D0,
0x001E100B, 0x001E1028, 0x0020102A, 0x0020103C,
0x00201048, 0xD6A8644C, 0x346C74FF, 0x2450000B,
0x644CD6A6, 0x000B346C, 0xD6A52450, 0x346C644C,
0x2450000B, 0x616D625C, 0x41194208, 0x60194208,
0x644C4200, 0x324C670E, 0x207DD19E, 0xC90F4200,
0x000B321C, 0x67632200, 0x4208625C, 0x42004208,
0x324C644C, 0x4200D198, 0x000B321C, 0x2FE62270,
0x614C4F12, 0x4100D493, 0x6710314C, 0x2729E29F,
0x65736E53, 0x4719676D, 0x672E6279, 0x4221227D,
0x42214221, 0x7601662C, 0xE4014608, 0x34E84608,
0x644C4600, 0x0E1A0467, 0x215025EB, 0x000B4F16,
0x4F226EF6, 0xD2857FE8, 0x88016021, 0xD2848B7B,
0x26686621, 0xD2838B77, 0x26686621, 0xE50F8B73,
0xE401BFA0, 0xBFA3E501, 0xE586E400, 0xE400655C,
0x2F50BFA3, 0xBFA0E401, 0xE602E506, 0x60634618,
0x81F2E401, 0x6543BF9E, 0xE40185F2, 0xBFAA6543,
0x85F26603, 0x6543E401, 0x6603BFB1, 0xE40265F0,
0x6053756C, 0x80F8BF7E, 0xBF81E402, 0x84F8E512,
0x7090E402, 0x6503BF81, 0x4618E602, 0x81F66063,
0xBF7FE402, 0x85F6E500, 0x6603E402, 0xE500BF8B,
0xE40285F6, 0xBF926603, 0xE5FEE500, 0xE010655C,
0xBF5FE403, 0xE5130F54, 0xE40EBF62, 0x05FCE010,
0xBF62E40E, 0xE5007585, 0xBF63E403, 0xE500E640,
0xBF70E403, 0xE500E640, 0xBF78E403, 0xE5FFE640,
0xE014655C, 0xBF45E404, 0xE40F0F54, 0xE504BF48,
0x05FCE014, 0xBF48E40F, 0xE5017584, 0xBF49E640,
0xE501E404, 0xBF56E640, 0xE501E404, 0xE404E640,
0xAF5C7F18, 0x7F184F26, 0x000B4F26, 0x4F220009,
0xD2427FF0, 0x88016021, 0xD2418B71, 0x26686621,
0xD2408B6D, 0x26686621, 0xE50F8B69, 0xE401BF1A,
0xBF1DE501, 0xE586E400, 0xE400655C, 0x2F50BF1D,
0xBF1AE401, 0xE401E506, 0xBF1B6543, 0xE401E640,
0xBF286543, 0xE401E640, 0xBF306543, 0x65F0E640,
0x756CE402, 0xBEFD6053, 0xE40280F4, 0xE512BF00,
0xE40284F4, 0xBF007090, 0xE6406503, 0xBF01E402,
0xE640E500, 0xBF0EE402, 0xE640E500, 0xBF16E402,
0xE5FEE500, 0x6053655C, 0xBEE3E403, 0xE51380F8,
0xE40EBEE6, 0xE40E84F8, 0xBEE67085, 0xE5006503,
0xBEE7E640, 0xE500E403, 0xBEF4E640, 0xE500E403,
0xBEFCE640, 0xE5FFE403, 0x6053655C, 0xBEC9E404,
0xE40F80FC, 0xE504BECC, 0xE40F84FC, 0xBECC7083,
0xE5016503, 0xBECDE640, 0xE501E404, 0xBEDAE640,
0xE501E404, 0xE404E640, 0xAEE07F10, 0x7F104F26,
0x000B4F26, 0x00000009, 0x001E1030, 0x001E1080,
0x001E1090, 0x001E103F, 0x001E103E, 0x002028C6,
0x002028C8, 0x002028CA, 0x0009000B, 0x666CE680,
0x6563D2A8, 0x7540E700, 0x6473422B, 0x2FB62FA6,
0x2FD62FC6, 0x4F222FE6, 0x4C18EC01, 0xDAA3DBA2,
0x65B252B1, 0x89223520, 0xC9036051, 0x891E8801,
0xD19FDE9D, 0x64E3410B, 0x85036503, 0x670D66A2,
0xDD9C3762, 0xD49C890A, 0x420BD29C, 0xD19C0009,
0xE701D49C, 0x21724D0B, 0x0009AFE2, 0x420BD29A,
0xD69A64E3, 0x4D0BD49A, 0xAFD926C2, 0x4F260009,
0x6DF66EF6, 0x6BF66CF6, 0x6AF6000B, 0x7FF44F22,
0xE6818546, 0x85472F01, 0x81F1666C, 0xD2858548,
0x854281F2, 0x81F367F3, 0xE40C8543, 0x605381F4,
0x81F56563, 0x7540420B, 0x4F267F0C, 0x0009000B,
0x2F962F86, 0x2FB62FA6, 0x2FD62FC6, 0x4F222FE6,
0xDC847FF0, 0xE800A0DD, 0xD2836B13, 0xE0014B08,
0x4B00420B, 0x1F03DE81, 0x3BEC85F2, 0x2F827E30,
0x1FE26803, 0x66C2DD7E, 0x362052C1, 0xA0C38B01,
0x60610009, 0x8801C903, 0xA0BD8B01, 0x85610009,
0x8965C801, 0xEE105163, 0xDA6A8512, 0xC9036603,
0x85136403, 0x4021600D, 0xC93F4021, 0x8D1C30E3,
0xD7706503, 0x62704408, 0x44004408, 0x22284500,
0x345C8F0A, 0x6043D26C, 0x697D072D, 0x68994919,
0x697C6E8E, 0x28EDA009, 0x6043D268, 0x697D072D,
0x68994919, 0x697C6E8E, 0xEEFF28ED, 0x6EEC629D,
0x8B0F32E0, 0x410BD152, 0x540364C3, 0xBF85E502,
0xD45F6E03, 0x460BD654, 0xD75E65E3, 0xD45EEE01,
0x27E2A01D, 0x26E9EEFC, 0x81126063, 0x97888513,
0x20794208, 0x85128113, 0x8112208B, 0x202B8513,
0x85148113, 0x4218E208, 0x8114202B, 0x854164C2,
0x814120E9, 0xD45165C2, 0xCB016051, 0x4A0B2501,
0x60C20009, 0x52F356F2, 0x2B02CB01, 0x2622AF8B,
0xD2378561, 0x8D2EC802, 0x420B64C3, 0xD6480009,
0x5E036503, 0x076EE04C, 0x7701D146, 0x60120676,
0x8B058801, 0xEA0C85E1, 0x20AB4A18, 0x81E1A007,
0x88026012, 0x85E18B03, 0x20A9EADF, 0x855181E1,
0x20A9EAFC, 0x60518151, 0xCB01DA28, 0x4A0B64C3,
0x56F22501, 0xD73851F3, 0x85EF2612, 0x470B64D3,
0xAF58650D, 0x420B0009, 0x54030009, 0x85446E03,
0x4A18EA08, 0x30A020A9, 0x8B03DA1A, 0xE501BF16,
0x0009A007, 0xD62D8541, 0x2268620D, 0xBF0D8901,
0xD423E500, 0x420BD218, 0xD72265E3, 0xEE01D428,
0x27E24A0B, 0x0009AF37, 0x68F26083, 0x780181F2,
0x618D7C08, 0x31E7EE03, 0xAF1D8901, 0x7F100009,
0x6EF64F26, 0x6CF66DF6, 0x6AF66BF6, 0x000B69F6,
0xFE0368F6, 0x00201834, 0x00202884, 0x0020288C,
0x00200A5C, 0x00200DA6, 0x00202854, 0x00200ADE,
0x001E2130, 0x00202A70, 0x00200A7A, 0x001C3D30,
0x00202A74, 0x00202864, 0x00201FD4, 0x001C3D00,
0x00202A80, 0x00202A8C, 0x00202970, 0x002029F0,
0x0020285C, 0x001E212C, 0x00202A78, 0x00202A7C,
0x002027F8, 0x002027F4, 0x00200E06, 0x00008000,
0x00202A88, 0x4F222FE6, 0x6E22D20D, 0xC84060E3,
0x22E28D02, 0x0009BE68, 0x4218E240, 0x89012E28,
0x0009BE64, 0xC80560E3, 0xBEB98901, 0x60E30009,
0x8902C802, 0xAE614F26, 0x4F266EF6, 0x6EF6000B,
0x001C3510, 0x080A0C0E, 0x00020406, 0x1A1C1E20,
0x12141618, 0x2E303234, 0x26282A2C, 0x3A3C3E40,
0x6C625648, 0x41112F26, 0xE2208F18, 0x890B3123,
0x321CD204, 0xD1026220, 0x412B312C, 0x00090009,
0x00201FFE, 0x00201FB4, 0x000BE000, 0x400062F6,
0x40004000, 0x40004000, 0x40004000, 0x62F6000B,
0x40004000, 0x40004000, 0x40004000, 0x40184000,
0x62F6000B, 0x40004000, 0x40004000, 0x40004000,
0x40284000, 0x62F6000B, 0x40004000, 0x40184000,
0x000B4028, 0xC90F62F6, 0x40054005, 0x40054005,
0x62F6000B, 0x4005C907, 0x40054005, 0x62F6000B,
0x4005C903, 0x000B4005, 0xC90162F6, 0x000B4005,
0x000062F6, 0x080A0C0E, 0x00020406, 0x1A1C1E20,
0x12141618, 0x2E303234, 0x26282A2C, 0x3A3C3E40,
0x6C625648, 0x41112F26, 0xE2208F18, 0x890B3123,
0x321CD204, 0xD1026220, 0x412B312C, 0x00090009,
0x002020BE, 0x00202074, 0x000BE000, 0x400162F6,
0x40014001, 0x40014001, 0x40014001, 0x62F6000B,
0x40014001, 0x40014001, 0x40014001, 0x40194001,
0x62F6000B, 0x40014001, 0x40014001, 0x40014001,
0x40294001, 0x62F6000B, 0x40014001, 0x40194001,
0x000B4029, 0x400462F6, 0x40044004, 0xC90F4004,
0x62F6000B, 0x40044004, 0xC9074004, 0x62F6000B,
0x40044004, 0x000BC903, 0x400462F6, 0x000BC901,
0x000062F6, 0x3622E218, 0x67438F12, 0x0009A004,
0x76FF6254, 0x74012420, 0xC8036053, 0x60438BF8,
0x8902C803, 0x422BD22B, 0xD22B0009, 0x0009422B,
0x2FE66473, 0x8D4A3450, 0x27786763, 0x62438947,
0x227B225B, 0xC9016023, 0x8D203452, 0x2EE86E03,
0x60238B15, 0x8B08C803, 0x47096643, 0x47106256,
0x8FFB2622, 0xA0327604, 0x47010009, 0x61436673,
0x46106255, 0x8FFB2121, 0xA0287102, 0x66430009,
0x47106254, 0x8FFB2620, 0xA0207601, 0x61430009,
0x2EE8357C, 0x8F15317C, 0x60236653, 0x8B07C803,
0x76FC4709, 0x47106262, 0x21268FFB, 0x0009A00F,
0x65634701, 0x75FE6673, 0x46106251, 0x21258FFB,
0x0009A005, 0x626076FF, 0x8FFB4710, 0x60432124,
0x6EF6000B, 0x002022A6, 0x00202752, 0xE21E2FE6,
0x67633626, 0x8D1B6153, 0x3E106E43, 0x3E128916,
0x65E38908, 0x3672E600, 0x62148910, 0x25207601,
0x7501AFF9, 0x317C64E3, 0x6513347C, 0xE600A004,
0x625075FF, 0x24247601, 0x8BF93672, 0x60E3A011,
0x890831E2, 0x327C6213, 0x8B0432E6, 0x651364E3,
0xA0086673, 0xD28F6EF6, 0x651364E3, 0x422B6673,
0x000B6EF6, 0xE2046EF6, 0x67433622, 0x8F10356C,
0xA004346C, 0x75FF0009, 0x76FF6250, 0x60532424,
0x8BF8C803, 0xC8036043, 0xA1058901, 0xA2770009,
0xA2990009, 0x2FB60009, 0x2FD62FC6, 0x7FE42FE6,
0x6C636043, 0x66521F62, 0xC9037504, 0x1F516E53,
0x45086503, 0xE1FC6D43, 0x2D194500, 0x1F732558,
0x1F651F44, 0x2FD28D0B, 0x88086053, 0x88108923,
0x8818895B, 0xA0898B01, 0xA0BD0009, 0x62630009,
0x2D22E600, 0x7CFC7D04, 0xEB10A00D, 0xE60064E6,
0x7CF065E6, 0x62E261E6, 0x1D512D42, 0x1D231D12,
0x7E047D10, 0x3CB21FE1, 0x1F6589F0, 0x2FD21FC2,
0xA0A11FE6, 0x64D21FD4, 0x44286263, 0x44294418,
0x42184419, 0x4629242B, 0x2D424619, 0x65637D04,
0xA0217CFD, 0x67E6EB10, 0x62E67CF0, 0x64E66673,
0x256B4618, 0x2D5261E2, 0x65234729, 0x45184719,
0x4229275B, 0x42191D71, 0x47186743, 0x4429227B,
0x44196713, 0x247B4718, 0x1D431D22, 0x41194129,
0x65137D10, 0x1FE17E04, 0x89DC3CB2, 0x1FE67EFF,
0x1FC21F55, 0xA0672FD2, 0x6CF21FD4, 0x66C257F5,
0x46286273, 0x42284629, 0x2C62262B, 0x7C045DF2,
0x7DFE4729, 0xA01CEB10, 0x65E65EF1, 0x66E66273,
0x47286753, 0x6763227B, 0x452961E6, 0x257B4728,
0x2C2264E6, 0x65131C51, 0x45284629, 0x1C62265B,
0x41296643, 0x216B4628, 0x44291C13, 0x67437C10,
0x3DB27DF0, 0x1FD289E1, 0x7EFEA034, 0x51F56CF2,
0x621366C2, 0x42284618, 0x42184619, 0x2C62262B,
0x7C045DF2, 0x7DFF4119, 0xA01FEB10, 0x65E65EF1,
0x64E67DF0, 0x42286253, 0x421867E6, 0x66E6212B,
0x61432C12, 0x45194128, 0x251B4118, 0x65731C51,
0x44194528, 0x245B4518, 0x64631C42, 0x47194428,
0x274B4418, 0x46191C73, 0x61637C10, 0x89DE3DB2,
0x7EFD1FD2, 0x1FC41FE6, 0x5DF2E704, 0xA00D5EF6,
0x62E451F4, 0x66E47DFC, 0x65E464E4, 0x71012120,
0x71012160, 0x71012140, 0x71012150, 0x89F03D72,
0x66D357F3, 0x641365E3, 0x6EF67F1C, 0x6CF66DF6,
0x6BF6A190, 0x00202134, 0x2FC62FB6, 0x2FE62FD6,
0x60437FE4, 0x6C63C903, 0x66031F62, 0x460875FC,
0x61526E43, 0x4600E2FC, 0x26682E29, 0x1F441F73,
0x1F516D53, 0x8D0B1F15, 0x60632FE2, 0x891F8808,
0x89538810, 0x8B018818, 0x0009A081, 0x0009A0B9,
0xEB10A00D, 0x52D37DF0, 0x54D156D2, 0x2E1665D2,
0x2E662E26, 0x2E427EFC, 0x1FD16153, 0x3CB27CF0,
0x7D0489F0, 0x1F151FD6, 0x2FE21FC2, 0x1FE4A0A1,
0x621366E2, 0x42294619, 0x42194618, 0x2E62262B,
0x7CFF4118, 0xEB10A021, 0x54D37DF0, 0x624357D2,
0x42194229, 0x55D1212B, 0x2E1666D2, 0x41296173,
0x41194418, 0x2E46241B, 0x44296453, 0x44194718,
0x2E76274B, 0x47296763, 0x47194518, 0x257B7EFC,
0x46182E52, 0x1FD16163, 0x3CB27CF0, 0x7D0389DC,
0x1F151FD6, 0x2FE21FC2, 0x1FE4A06B, 0x57F56EF2,
0x627366E2, 0x46284629, 0x262B4229, 0x2E625CF2,
0x7CFE4728, 0xA01BEB10, 0x7DF05DF1, 0x55D251D3,
0x46296613, 0x54D1276B, 0x2E7662D2, 0x41286753,
0x217B4729, 0x61432E16, 0x41294528, 0x2E56251B,
0x44286523, 0x245B4529, 0x42282E46, 0x7CF06723,
0x89E23CB2, 0x1FD67D02, 0xA03A1FC2, 0x67F21FE4,
0x657251F5, 0x45296213, 0x45284519, 0x42194518,
0x5CF2252B, 0x41282752, 0x7CFD4118, 0xA022EB10,
0x7DF05DF1, 0x54D256D3, 0x45196563, 0x52D14628,
0x4618215B, 0x6ED26543, 0x45192716, 0x265B4428,
0x65436163, 0x45186423, 0x42284419, 0x4218254B,
0x271664E3, 0x44196623, 0x264B2756, 0x4E282766,
0x61E34E18, 0x3CB27CF0, 0x7D0189DB, 0x1FC21FD6,
0xE7041F74, 0x51F45DF2, 0x5EF6A00D, 0x84E27EFC,
0x620364E0, 0x7DFC84E1, 0x84E36503, 0x21646603,
0x21542124, 0x3D722144, 0x57F389F0, 0x641366D3,
0x7F1C65E3, 0x6DF66EF6, 0xA09D6CF6, 0x2F866BF6,
0x2FA62F96, 0x2FC62FB6, 0x2FE62FD6, 0x614374E0,
0x6A636873, 0x6B56E920, 0x6C567AE0, 0x6D567120,
0x6E563A92, 0x64566756, 0x62566656, 0x11C121B2,
0x11E311D2, 0x11451174, 0x8DEC1166, 0x71201127,
0x6613A004, 0x7AFF6254, 0x76012620, 0x8BF92AA8,
0x6EF66083, 0x6CF66DF6, 0x6AF66BF6, 0x000B69F6,
0x2F8668F6, 0x2FA62F96, 0x2FC62FB6, 0x2FE62FD6,
0x6A636873, 0x75E0E920, 0x56565257, 0x57545155,
0x5D525E53, 0x6B525C51, 0x24662426, 0x24762416,
0x7AE024E6, 0x24C624D6, 0x8DEC3A92, 0x66A324B6,
0x6EF66783, 0x6CF66DF6, 0x6AF66BF6, 0xA04369F6,
0x2FE668F6, 0xC8046063, 0x8D046E63, 0x62166153,
0x24227EFC, 0x60E37404, 0x8908C818, 0x71046513,
0x62526616, 0x24227EF8, 0xAFF41461, 0xE2047408,
0x65133E22, 0x66E38D02, 0x6EF6A01C, 0x6EF6AF87,
0xC8046063, 0x61638D04, 0x625275FC, 0x242671FC,
0xC8186013, 0x75F88906, 0x66525251, 0x24662426,
0x71F8AFF6, 0x3122E204, 0x66138F02, 0x0009AFA1,
0x0009A00A, 0x0009A004, 0x76FF6254, 0x74012420,
0x8BF92668, 0x6073000B, 0x0009A004, 0x625075FF,
0x242476FF, 0x8BF92668, 0x6073000B, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x544F0D0A,
0x46205355, 0x00003A57, 0x2072614D, 0x32203232,
0x20373030, 0x353A3431, 0x33353A34, 0x00000000,
0x00000D0A, 0x00000043, 0x61766E49, 0x2064696C,
0x72657375, 0x20726F20, 0x2079656B, 0x00214449,
0x6E6B6E55, 0x206E776F, 0x6D6D6F63, 0x3D646E61,
0x00000000, 0x61437748, 0x7262696C, 0x6F697461,
0x6620206E, 0x0A6C6961, 0x0000000D, 0x73696F4E,
0x61432065, 0x7262696C, 0x6F697461, 0x6166206E,
0x21216C69, 0x00000D0A, 0x00000D0A, 0x00000042,
0x000000FF, 0x00020001, 0x00FF00FF, 0x00FF00FF,
0x00FF00FF, 0x00FF00FF, 0x00FF00FF, 0x00FF00FF,
0x00FF00FF, 0x00FF00FF, 0x00FF00FF, 0x00FF00FF,
0x010E010D, 0x00020003, 0x01090108, 0x0002010A,
0x00030002, 0x02020201, 0x02040203, 0x02060205,
0x02080207, 0x020A0209, 0x020C020B, 0x020E020D,
0x00FF00FF, 0x00FF00FF, 0x00FF00FF, 0x00FF00FF,
0x00FF00FF, 0x00FF00FF, 0x00FF00FF, 0x00FF00FF,
0x00FF00FF, 0x00FF00FF, 0x00FF00FF, 0x00FF00FF,
0x00FF00FF, 0x00FF00FF, 0x00FF00FF, 0x00FF00FF,
0x00FF00FF, 0x00FF00FF, 0x00FF00FF, 0x00FF00FF,
0x010E010D, 0x00FF010F, 0x01090108, 0x010B010A,
0x00030002, 0x02020201, 0x02040203, 0x02060205,
0x02080207, 0x020A0209, 0x020C020B, 0x020E020D,
0x00FF00FF, 0x00FF00FF, 0x00FF00FF, 0x00FF00FF,
0x00FF00FF, 0x00FF00FF, 0x00FF00FF, 0x00FF00FF,
0x00000072, 0x00205220, 0x00000046, 0x00000059,
0x73204142, 0x003D7165, 0x00000074, 0x00000000,
0x02000112, 0x40FFFFFF, 0x12210ACE, 0x20104890,
0x02090100, 0x0101002E, 0x09FA8000, 0x04000004,
0x000000FF, 0x02010507, 0x07000200, 0x00028205,
0x05070002, 0x00400383, 0x04050701, 0x01004003,
0x002E0209, 0x80000101, 0x000409FA, 0x00FF0400,
0x05070000, 0x00400201, 0x82050700, 0x00004002,
0x03830507, 0x07010040, 0x40030405, 0x03040100,
0x030C0409, 0x0079005A, 0x00410044, 0x03180053,
0x00530055, 0x00320042, 0x0030002E, 0x00570020,
0x0041004C, 0x0000004E, 0x00000000, 0x00000000,
0x00000709, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
};
const u32_t zcFwImageSize=11104;
|
laurence-bird/comms-orchestration
|
src/test/scala/com/ovoenergy/orchestration/profile/CustomerProfilerSpec.scala
|
package com.ovoenergy.orchestration.profile
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}
import cats.effect.IO
import cats.effect._
import cats.implicits._
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock
import com.ovoenergy.comms.model._
import org.scalatest._
import WireMock.{get, _}
import com.github.tomakehurst.wiremock.core.WireMockConfiguration._
import com.github.tomakehurst.wiremock.http.UniformDistribution
import com.ovoenergy.orchestration.domain.{CustomerProfile => CProfile}
import com.ovoenergy.orchestration.domain.{
CommunicationPreference,
ContactProfile,
CustomerProfileName,
EmailAddress,
MobilePhoneNumber
}
import com.ovoenergy.orchestration.processes.Orchestrator.ErrorDetails
import com.ovoenergy.orchestration.profile.CustomerProfiler.{ProfileCustomer, ServerErrorException}
import com.ovoenergy.orchestration.util.Retry
import org.http4s.{InvalidMessageBodyFailure, Uri}
import scala.concurrent.ExecutionContext
import scala.concurrent.duration._
import scala.util.Try
class CustomerProfilerSpec
extends FlatSpec
with Matchers
with EitherValues
with BeforeAndAfterEach
with BeforeAndAfterAll
with TryValues
with Assertions {
val profileApiKey = "apiKey"
val profileHost = "http://somehost.com"
val traceToken = "token"
val commId = "id"
lazy val uri = Uri.unsafeFromString(s"http://localhost:${wireMockServer.port()}/yolo")
val customerId = "whatever"
val path = s"/yolo/api/customers/$customerId"
val validResponseJson =
new String(Files.readAllBytes(Paths.get("src/test/resources/profile_valid_response.json")), StandardCharsets.UTF_8)
import cats.effect.IO._
implicit lazy val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global
implicit lazy val t: Timer[IO] = timer(ec)
implicit lazy val concurrenctEffect: ConcurrentEffect[IO] = cats.effect.IO.ioConcurrentEffect(contextShift(ec))
lazy val customerProfiler = CustomerProfiler.resource[IO](Retry.fixed[IO](4, 10.millisecond), profileApiKey, uri)
behavior of "Customer Profiler"
val wireMockServer: WireMockServer = new WireMockServer(wireMockConfig().dynamicPort())
it should "Return an appropriate error code for 4xx (non-recoverable errors), without retry" in {
stubFor(
get(urlPathEqualTo(path))
.withQueryParam("apikey", equalTo(profileApiKey))
.willReturn(
aResponse()
.withRandomDelay(new UniformDistribution(300, 5000))
.withBody("You're not allowed here")
.withStatus(401)))
customerProfiler
.use(_.apply(ProfileCustomer("whatever", canary = false, traceToken, commId)))
.unsafeRunSync()
.left
.value shouldBe ErrorDetails("Error response (401) retrieving customer profile: You're not allowed here",
OrchestrationError)
verify(1,
getRequestedFor(urlPathEqualTo(path))
.withQueryParam("apikey", equalTo(profileApiKey)))
}
it should "Fail when response is not a success code, with retries" in {
stubFor(
get(urlPathEqualTo(path))
.withQueryParam("apikey", equalTo(profileApiKey))
.willReturn(
aResponse()
.withRandomDelay(new UniformDistribution(300, 5000))
.withBody(s"Profile service is dead")
.withStatus(500)))
val resultIo = customerProfiler
.use(_.apply(ProfileCustomer("whatever", canary = false, traceToken, commId)))
val result = Try(resultIo.unsafeRunSync())
verify(5,
getRequestedFor(urlPathEqualTo(path))
.withQueryParam("apikey", equalTo(profileApiKey)))
result.failure.exception.isInstanceOf[ServerErrorException]
}
it should "Fail when response body is invalid" in {
stubFor(
get(urlPathEqualTo(path))
.withQueryParam("apikey", equalTo(profileApiKey))
.willReturn(
aResponse()
.withRandomDelay(new UniformDistribution(300, 5000))
.withBody(s"""{\"some\":\"value\"}""")
.withStatus(200)))
val resultIo = customerProfiler
.use(_.apply(ProfileCustomer("whatever", canary = false, traceToken, commId)))
assertThrows[InvalidMessageBodyFailure](resultIo.unsafeRunSync())
}
it should "Succeed when response is valid" in {
stubFor(
get(urlPathEqualTo(path))
.withQueryParam("apikey", equalTo(profileApiKey))
.willReturn(
aResponse()
.withRandomDelay(new UniformDistribution(300, 5000))
.withBody(validResponseJson)
.withStatus(200)))
val resultIo = customerProfiler
.use(_.apply(ProfileCustomer("whatever", canary = false, traceToken, commId)))
resultIo.unsafeRunSync() shouldBe Right(
CProfile(
name = CustomerProfileName(
title = Some("Mr"),
firstName = "John",
lastName = "Wayne",
suffix = None
),
communicationPreferences = Seq(
CommunicationPreference(
Service,
Seq(SMS, Email)
)
),
ContactProfile(
emailAddress = Some(EmailAddress("<EMAIL>")),
mobileNumber = Some(MobilePhoneNumber("+447985631544")),
postalAddress = None
)
)
)
}
it should "Ask the profiles service for the canary when requested" in {
stubFor(
get(urlPathEqualTo(path))
.withQueryParam("canary", equalTo("true"))
.withQueryParam("apikey", equalTo(profileApiKey))
.willReturn(
aResponse()
.withRandomDelay(new UniformDistribution(300, 5000))
.withBody(validResponseJson)
.withStatus(200)))
val result: Either[ErrorDetails, CProfile] = customerProfiler
.use(_.apply(ProfileCustomer("whatever", canary = true, traceToken, commId)))
.unsafeRunSync()
result match {
case Right(customerProfile) => succeed
// ok
case Left(err) =>
fail(s"Unexpected failure: ${err.reason}")
}
}
override protected def beforeEach(): Unit = {
super.beforeEach()
wireMockServer.resetAll()
WireMock.configureFor(wireMockServer.port())
}
override protected def afterEach(): Unit = {
wireMockServer.resetAll()
super.afterEach()
}
override protected def beforeAll(): Unit = {
super.beforeAll()
wireMockServer.start()
}
override protected def afterAll(): Unit = {
wireMockServer.shutdown()
super.afterAll()
}
}
|
jorexe/haikunet
|
debug/atomics/ATLAS-TDAQ/Vector_PacketNetworkServer.cpp
|
#include "Vector_PacketNetworkServer.h"
|
Hope6537/hope-battlepack
|
hope-note-module/hope-java-native-note/src/main/java/org/hope6537/note/design/servant/example/ServicedImpl1.java
|
package org.hope6537.note.design.servant.example;
/**
*
*/
public class ServicedImpl1 implements Serviced {
@Override
public void serviced() {
System.out.println("serivce1");
}
}
|
hvonck/lambda-lilac
|
src/engine/renderers/d3d11/d3d11_texture.h
|
<filename>src/engine/renderers/d3d11/d3d11_texture.h
#pragma once
#include "assets/texture.h"
#include <d3d11.h>
namespace lambda
{
namespace windows
{
///////////////////////////////////////////////////////////////////////////
class D3D11Texture
{
friend class D3D11RenderTargetView;
friend class D3D11DepthStencilView;
friend class D3D11RenderTexture;
friend class D3D11Context;
public:
D3D11Texture(
asset::VioletTextureHandle texture,
ID3D11Device* device,
ID3D11DeviceContext* context
);
~D3D11Texture();
void update(
asset::VioletTextureHandle texture,
ID3D11Device* device,
ID3D11DeviceContext* context);
void bind(ID3D11DeviceContext* context, uint8_t slot);
DXGI_FORMAT getFormat() const;
ID3D11ShaderResourceView* getSRV() const;
void generateMips(ID3D11DeviceContext* context) const;
ID3D11DepthStencilView* getDSV(
unsigned char layer,
unsigned char mip_map
) const;
ID3D11RenderTargetView* getRTV(
unsigned char layer,
unsigned char mip_map
) const;
protected:
const ID3D11Texture2D* getTexture() const;
ID3D11Texture2D* getTexture();
private:
void createSRVs(
ID3D11Device* device,
unsigned char layer_count,
unsigned char mip_count
);
void createRTVs(
ID3D11Device* device,
unsigned char layer_count,
unsigned char mip_count
);
void createDSVs(
ID3D11Device* device,
unsigned char layer_count,
unsigned char mip_count
);
private:
struct Layer
{
Vector<ID3D11DepthStencilView*> dsvs;
Vector<ID3D11RenderTargetView*> rtvs;
};
DXGI_FORMAT format_;
ID3D11ShaderResourceView* srv_;
ID3D11Texture2D* texture_;
Vector<Layer> layers_;
bool is_render_target_;
bool is_dynamic_;
};
}
}
|
dwt/capybara.py
|
capybara/tests/session/test_assert_selector.py
|
import pytest
import re
import capybara
from capybara.exceptions import ElementNotFound
class TestAssertSelector:
@pytest.fixture(autouse=True)
def setup_session(self, session):
session.visit("/with_html")
def test_does_not_raise_if_the_given_selector_is_on_the_page(self, session):
session.assert_selector("xpath", "//p")
session.assert_selector("css", "p a#foo")
session.assert_selector("//p[contains(.,'est')]")
def test_raises_if_the_given_selector_is_not_on_the_page(self, session):
with pytest.raises(ElementNotFound):
session.assert_selector("xpath", "//abbr")
with pytest.raises(ElementNotFound):
session.assert_selector("css", "p a#doesnotexist")
with pytest.raises(ElementNotFound):
session.assert_selector("//p[contains(.,'thisstringisnotonpage')]")
def test_uses_default_selector(self, session):
capybara.default_selector = "css"
with pytest.raises(ElementNotFound):
session.assert_selector("p a#doesnotexist")
session.assert_selector("p a#foo")
def test_respects_scopes(self, session):
with session.scope("//p[@id='first']"):
session.assert_selector(".//a[@id='foo']")
with pytest.raises(ElementNotFound):
session.assert_selector(".//a[@id='red']")
def test_is_true_if_the_content_is_on_the_page_the_given_number_of_times(self, session):
session.assert_selector("//p", count=3)
session.assert_selector("//p//a[@id='foo']", count=1)
session.assert_selector("//p[contains(.,'est')]", count=1)
def test_raises_if_the_content_is_on_the_page_the_given_number_of_times(self, session):
with pytest.raises(ElementNotFound):
session.assert_selector("//p", count=6)
with pytest.raises(ElementNotFound):
session.assert_selector("//p//a[@id='foo']", count=2)
with pytest.raises(ElementNotFound):
session.assert_selector("//p[contains(.,'est')]", count=5)
def test_raises_if_the_content_is_not_on_the_page_at_all(self, session):
with pytest.raises(ElementNotFound):
session.assert_selector("//abbr", count=2)
with pytest.raises(ElementNotFound):
session.assert_selector("//p//a[@id='doesnotexist']", count=1)
def test_discards_all_matches_where_the_given_string_is_not_contained(self, session):
session.assert_selector("//p//a", text="Redirect", count=1)
with pytest.raises(ElementNotFound):
session.assert_selector("//p", text="Doesnotexist")
def test_discards_all_matches_where_the_given_regex_is_not_matched(self, session):
session.assert_selector("//p//a", text=re.compile("re[dab]i", re.IGNORECASE), count=1)
with pytest.raises(ElementNotFound):
session.assert_selector("//p//a", text=re.compile("Red$"))
@pytest.mark.requires("js")
def test_finds_element_if_it_appears_before_given_wait_duration(self, session):
with capybara.using_wait_time(0.1):
session.visit("/with_js")
session.click_link("Click me")
session.assert_selector("css", "a#has-been-clicked", text="Has been clicked", wait=0.9)
class TestAssertNoSelector:
@pytest.fixture(autouse=True)
def setup_session(self, session):
session.visit("/with_html")
def test_raises_an_error_if_the_given_selector_is_on_the_page(self, session):
with pytest.raises(ElementNotFound):
session.assert_no_selector("xpath", "//p")
with pytest.raises(ElementNotFound):
session.assert_no_selector("css", "p a#foo")
with pytest.raises(ElementNotFound):
session.assert_no_selector("//p[contains(.,'est')]")
def test_is_true_if_the_given_selector_is_not_on_the_page(self, session):
session.assert_no_selector("xpath", "//abbr")
session.assert_no_selector("css", "p a#doesnotexist")
session.assert_no_selector("//p[contains(.,'thisstringisnotonpage')]")
def test_uses_the_default_selector(self, session):
capybara.default_selector = "css"
session.assert_no_selector("p a#doesnotexist")
with pytest.raises(ElementNotFound):
session.assert_no_selector("p a#foo")
def test_respects_scopes(self, session):
with session.scope("//p[@id='first']"):
with pytest.raises(ElementNotFound):
session.assert_no_selector(".//a[@id='foo']")
session.assert_no_selector(".//a[@id='red']")
def test_raises_an_error_if_the_content_is_on_the_page_the_given_number_of_times(self, session):
with pytest.raises(ElementNotFound):
session.assert_no_selector("//p", count=3)
with pytest.raises(ElementNotFound):
session.assert_no_selector("//p//a[@id='foo']", count=1)
with pytest.raises(ElementNotFound):
session.assert_no_selector("//p[contains(.,'est')]", count=1)
def test_is_true_if_the_content_is_on_the_page_the_wrong_number_of_times(self, session):
session.assert_no_selector("//p", count=6)
session.assert_no_selector("//p//a[@id='foo']", count=2)
session.assert_no_selector("//p[contains(.,'est')]", count=5)
def test_is_true_if_the_content_is_not_on_the_page_at_all(self, session):
session.assert_no_selector("//abbr", count=2)
session.assert_no_selector("//p//a[@id='doesnotexist']", count=1)
def test_discards_all_matches_where_the_given_string_is_contained(self, session):
with pytest.raises(ElementNotFound):
session.assert_no_selector("//p//a", text="Redirect", count=1)
session.assert_no_selector("//p", text="Doesnotexist")
def test_discards_all_matches_where_the_given_regex_is_matched(self, session):
with pytest.raises(ElementNotFound):
session.assert_no_selector("//p//a", text=re.compile(r"re[dab]i", re.IGNORECASE), count=1)
session.assert_no_selector("//p//a", text=re.compile(r"Red$"))
@pytest.mark.requires("js")
def test_does_not_find_element_if_it_appears_after_given_wait_duration(self, session):
session.visit("/with_js")
session.click_link("Click me")
session.assert_no_selector("css", "a#has-been-clicked", text="Has been clicked", wait=0.1)
|
itteco/service_merchant
|
subscription_management/tasks/schema.rb
|
namespace :subscription do
desc 'Create Subscription management database tables'
task :create_tables => :connection do
ActiveRecord::Base.connection.create_table :subscriptions, :force => true do |t|
t.column :account_id, :string, :null => false
t.column :tariff_plan_id, :string, :null => false
t.column :taxes_id, :string, :null => false
t.column :quantity, :integer, :null => false
t.column :currency, :string, :null => false
t.column :net_amount, :integer, :null => false
t.column :taxes_amount, :integer, :null => false
t.column :periodicity, :string, :null => false
t.column :starts_on, :date, :null => false
t.column :ends_on, :date
t.column :status, :string, :null => false
t.column :created_at, :datetime, :null => false
t.column :updated_at, :datetime
t.column :deleted_at, :datetime
end
ActiveRecord::Base.connection.add_index :subscriptions, [ :account_id ], :name => 'ix_subscription_account'
ActiveRecord::Base.connection.create_table :subscription_profiles, :force => true do |t|
t.column :subscription_id, :integer, :null => false
t.column :recurring_payment_profile_id, :integer, :null => false
t.column :created_at, :datetime, :null => false
end
ActiveRecord::Base.connection.add_index :subscription_profiles, [ :subscription_id ], :name => 'ix_subscription_profiles_subscription'
end
desc 'Drop Subscription management database tables'
task :drop_tables => :connection do
ActiveRecord::Base.connection.drop_table :subscription_profiles
ActiveRecord::Base.connection.drop_table :subscriptions
end
# Use Rails connection when appropriate or fallback to local test db
task :connection do
connected = false
begin
begin
Rake::Task[:environment].invoke
connected = true if ActiveRecord::Base.connection
rescue ActiveRecord::ConnectionNotEstablished
# ignore
rescue RuntimeError
puts "no database configuration found"
end
rescue NameError # ActiveRecord not loaded, use test mode
end
require File.dirname(__FILE__) + "/../test/connection" unless connected
end
end
|
jorjoh/Simplediagram
|
src/gui/domain/Domainview.java
|
<filename>src/gui/domain/Domainview.java
package gui.domain;
import figure.graphics.Figure;
import figure.model.IFigure;
import svg.Svg;
import uml.graphics.Thing;
import uml.model.*;
import uml.model.Package;
import javax.swing.*;
import java.awt.*;
import java.awt.Component;
import java.awt.event.ActionEvent;
public class Domainview extends JPanel implements IFigure {
private Diagram diagram = new Diagram("Brukstilfeller og akt�rer");
private Shadow sh = new Shadow();
public Domainview() {
setLayout(new BorderLayout());
add(diagram);
add(sh, BorderLayout.SOUTH);
diagram.addFigure(new Actormodel(10, 10));
diagram.addFigure(new Usecasemodel(10, 65));
diagram.addFigure(new Business(10, 115));
diagram.addFigure(new ClassSymbol(10,160));
diagram.addFigure(new Node(10,245));
diagram.addFigure(new Package(10,350));
diagram.addFigure(new uml.model.Component(10,430));
setShadow(Shadows.LOW.f());
setBackground(Color.WHITE);
}
private Figure figureSource(ActionEvent e) {
Component c = (Component) e.getSource();
JComponent jc = (JComponent) c.getParent();
return (Figure) ((JPopupMenu) jc).getInvoker();
}
public void insertFigure(ActionEvent e) {
diagram.addFigure(figureSource(e).newInstance());
repaint();
}
public void connect(ActionEvent object) {
diagram.connect((Thing) figureSource(object));
repaint();
}
public void setShadow(float d) {
diagram.setShadow(d);
}
public void deleteFigure(ActionEvent e) {
diagram.deleteFigure(figureSource(e));
}
public void shadow(ActionEvent e) {
sh.setVisible(((AbstractButton)e.getSource()).isSelected());
}
public void storesvg() {
new Svg().store(diagram);
}
public void edtext(ActionEvent e) {
diagram.edtext((Thing) figureSource(e));
}
public void finishConnection(Object e) {
diagram.finishConnection((Thing) e);
}
}
|
Imterrorblade/admin_cms
|
src/utils/validate.js
|
/**
* Created by jiachenpan on 16/11/18.
*/
export function isvalidUsername(str) {
const reg = /^[A-Za-z0-9]+$/
return reg.test(str)
}
/* 合法uri*/
export function validateURL(textval) {
const urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
return urlregex.test(textval)
}
/* 小写字母*/
export function validateLowerCase(str) {
const reg = /^[a-z]+$/
return reg.test(str)
}
/* 大写字母*/
export function validateUpperCase(str) {
const reg = /^[A-Z]+$/
return reg.test(str)
}
/* 大小写字母*/
export function validateAlphabets(str) {
const reg = /^[A-Za-z]+$/
return reg.test(str)
}
/**
* validate email
* @param email
* @returns {boolean}
*/
export function validateEmail(email) {
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return re.test(email)
}
/**
* validate tel
* @param tel
* @returns {boolean}
*/
export function isvalidateTel(tel, type) {
const re = [/^0\d{2,3}-?\d{7,8}$/, /^1\d{10}$/, /^0\d{2,3}-?\d{7,8}$|1\d{10}$/]
type = type || 0
return re[type].test(tel)
}
/**
* from checkRequired
* @param message _selef(vue)
* @returns message
*/
export function checkRequired(message, _self) {
message += _self.$t('table.common.error.__message')
return message
}
// 获取单个字段表单验证规则
export function formRule(mapfield, _self) {
return [{ required: true, message: checkRequired(_self.$t(mapfield), _self), trigger: 'change' }]
}
// 手机号验证
export function isTelvalidate(tel, type) {
const re = [/^[1][3,4,5,7,8][0-9]{9}$/]
type = type || 0
return re[type].test(tel)
}
// 身份证验证
export function IdCodeValid(code, type) {
// 身份证号合法性验证
// 支持15位和18位身份证号
// 支持地址编码、出生日期、校验位验证
// var city = { 11: '北京', 12: '天津', 13: '河北', 14: '山西', 15: '内蒙古', 21: '辽宁', 22: '吉林', 23: '黑龙江 ', 31: '上海', 32: '江苏', 33: '浙江', 34: '安徽', 35: '福建', 36: '江西', 37: '山东', 41: '河南', 42: '湖北 ', 43: '湖南', 44: '广东', 45: '广西', 46: '海南', 50: '重庆', 51: '四川', 52: '贵州', 53: '云南', 54: '西藏 ', 61: '陕西', 62: '甘肃', 63: '青海', 64: '宁夏', 65: '新疆', 71: '台湾', 81: '香港', 82: '澳门', 91: '国外 ' }
const re = [/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/]
type = type || 0
return re[type].test(code)
}
// 获取整个表单验证规则
export function getRules(fields, _self) {
const rules = {}
for (const i of fields) {
if (typeof i === 'string') {
rules[i] = formRule('table.common.' + i, _self)
} else if (typeof i === 'object') {
const key = Object.keys(i)[0]
rules[key] = formRule(i[key], _self)
}
}
return rules
}
|
climategames/climategames-website
|
lib/tasks/game_state.rake
|
namespace :game_state do
desc 'Store a snapshot of the current game state'
task snapshot: :environment do
GameState.current.save!
end
end
|
aTiKhan/nuxeo
|
modules/core/nuxeo-core-test/src/test/java/org/nuxeo/ecm/core/bulk/TestSetPropertiesAction.java
|
<filename>modules/core/nuxeo-core-test/src/test/java/org/nuxeo/ecm/core/bulk/TestSetPropertiesAction.java<gh_stars>0
/*
* (C) Copyright 2018 Nuxeo (http://nuxeo.com/) and others.
*
* 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.
*
* Contributors:
* pierre
*/
package org.nuxeo.ecm.core.bulk;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.nuxeo.ecm.core.bulk.action.SetPropertiesAction.ACTION_FULL_NAME;
import static org.nuxeo.ecm.core.bulk.action.SetPropertiesAction.ACTION_NAME;
import static org.nuxeo.ecm.core.bulk.message.BulkStatus.State.ABORTED;
import static org.nuxeo.ecm.core.bulk.message.BulkStatus.State.COMPLETED;
import static org.nuxeo.ecm.core.test.DocumentSetRepositoryInit.DOC_BY_LEVEL;
import static org.nuxeo.ecm.core.test.DocumentSetRepositoryInit.USERNAME;
import java.io.Serializable;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import javax.inject.Inject;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentRef;
import org.nuxeo.ecm.core.api.PathRef;
import org.nuxeo.ecm.core.bulk.computation.BulkScrollerComputation;
import org.nuxeo.ecm.core.bulk.message.BulkCommand;
import org.nuxeo.ecm.core.bulk.message.BulkStatus;
import org.nuxeo.ecm.core.test.CoreFeature;
import org.nuxeo.ecm.core.test.DocumentSetRepositoryInit;
import org.nuxeo.ecm.core.test.annotations.RepositoryConfig;
import org.nuxeo.lib.stream.computation.Record;
import org.nuxeo.lib.stream.log.LogManager;
import org.nuxeo.lib.stream.log.LogTailer;
import org.nuxeo.lib.stream.log.Name;
import org.nuxeo.runtime.api.Framework;
import org.nuxeo.runtime.stream.StreamService;
import org.nuxeo.runtime.test.runner.Deploy;
import org.nuxeo.runtime.test.runner.Features;
import org.nuxeo.runtime.test.runner.FeaturesRunner;
import org.nuxeo.runtime.test.runner.TransactionalFeature;
@RunWith(FeaturesRunner.class)
@Features(CoreFeature.class)
@Deploy("org.nuxeo.ecm.core.test.tests:OSGI-INF/test-repo-core-types-contrib.xml")
@RepositoryConfig(init = DocumentSetRepositoryInit.class)
public class TestSetPropertiesAction {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(BulkScrollerComputation.class);
@Inject
public BulkService service;
@Inject
public CoreSession session;
@Inject
public TransactionalFeature txFeature;
@Test
public void testSetPropertiesAsAdmin() throws Exception {
testSetProperties("Administrator");
}
@Test
public void testSetPropertiesAsNonAdmin() throws Exception {
testSetProperties(USERNAME);
}
protected void testSetProperties(String username) throws Exception {
DocumentModel model = session.getDocument(new PathRef("/default-domain/workspaces/test"));
String nxql = String.format("SELECT * from Document where ecm:parentId='%s'", model.getId());
String title = "test title";
String description = "test description";
String foo = "test foo";
String bar = "test bar";
HashMap<String, Serializable> complex = new HashMap<>();
complex.put("foo", foo);
complex.put("bar", bar);
int oldSize = service.getStatuses(username).size();
String commandId = service.submit(
new BulkCommand.Builder(ACTION_NAME, nxql, username).repository(session.getRepositoryName())
.param("dc:title", title)
.param("dc:description", description)
.param("cpx:complex", complex)
.build());
assertTrue("Bulk action didn't finish", service.await(Duration.ofSeconds(60)));
BulkStatus status = service.getStatus(commandId);
assertNotNull(status);
assertEquals(COMPLETED, status.getState());
assertEquals(DOC_BY_LEVEL, status.getProcessed());
List<BulkStatus> statuses = service.getStatuses(username);
assertEquals(1, statuses.size() - oldSize);
assertEquals(status.getId(), statuses.get(statuses.size() - 1).getId());
List<BulkStatus> emptyStatuses = service.getStatuses("toto");
assertEquals(0, emptyStatuses.size());
txFeature.nextTransaction();
for (DocumentModel child : session.query(nxql)) {
assertEquals(title, child.getTitle());
assertEquals(description, child.getPropertyValue("dc:description"));
if (child.getType().equals("ComplexDoc")) {
assertEquals(foo, child.getPropertyValue("cpx:complex/foo"));
assertEquals(bar, child.getPropertyValue("cpx:complex/bar"));
}
}
}
/**
* The action must not completely fail even when setting a property fails (property not found or version not
* writable).
*/
@Test
public void testSetPropertiesFailures() throws Exception {
DocumentModel workspace = session.getDocument(new PathRef("/default-domain/workspaces/test"));
DocumentModel doc = session.getDocument(new PathRef("/default-domain/workspaces/test/testdoc0"));
DocumentRef verRef = session.checkIn(doc.getRef(), null, null);
DocumentModel ver = session.getDocument(verRef);
session.save();
txFeature.nextTransaction();
String nxql = String.format("SELECT * FROM Document WHERE ecm:uuid in ('%s', '%s', '%s')", //
workspace.getId(), // no such property
ver.getId(), // not writable
doc.getId() // ok
);
int oldSize = service.getStatuses(session.getPrincipal().getName()).size();
String commandId = service.submit(
new BulkCommand.Builder(ACTION_NAME, nxql, session.getPrincipal().getName()).repository(
session.getRepositoryName()).param("cpx:complex/foo", "test foo").build());
assertTrue("Bulk action didn't finish", service.await(Duration.ofSeconds(60)));
BulkStatus status = service.getStatus(commandId);
assertNotNull(status);
assertEquals(COMPLETED, status.getState());
assertEquals(3, status.getProcessed());
List<BulkStatus> statuses = service.getStatuses(session.getPrincipal().getName());
assertEquals(1, statuses.size() - oldSize);
assertEquals(status.getId(), statuses.get(statuses.size() - 1).getId());
// docs not in error are still written though
txFeature.nextTransaction();
doc.refresh();
assertEquals("test foo", doc.getPropertyValue("cpx:complex/foo"));
}
@Test
@Deploy("org.nuxeo.ecm.core.test.tests:OSGI-INF/bulk-low-scroll-size-contrib.xml")
public void testAbort() throws Exception {
StreamService streamService = Framework.getService(StreamService.class);
@SuppressWarnings("resource")
LogManager logManager = streamService.getLogManager();
try (LogTailer<Record> tailer = logManager.createTailer(Name.ofUrn("test"), Name.ofUrn(ACTION_FULL_NAME))) {
tailer.toLastCommitted();
DocumentModel model = session.getDocument(new PathRef("/default-domain/workspaces/test"));
String nxql = String.format("SELECT * from Document where ecm:parentId='%s'", model.getId());
String commandId = service.submit(
new BulkCommand.Builder(ACTION_NAME, nxql, session.getPrincipal().getName()).repository(
session.getRepositoryName()).param("dc:description", "foo").bucket(1).batch(1).build());
BulkStatus abortStatus = service.abort(commandId);
if (abortStatus.getState().equals(COMPLETED)) {
log.warn("Bulk command cannot be aborted because already completed");
return;
}
assertEquals(ABORTED, abortStatus.getState());
BulkStatus status = service.getStatus(commandId);
assertEquals(ABORTED, status.getState());
assertTrue("Bulk action didn't finish", service.await(Duration.ofSeconds(10)));
status = service.getStatus(commandId);
assertEquals(ABORTED, status.getState());
int scrolledDocument = 0;
while (tailer.read(Duration.ofSeconds(1)) != null) {
scrolledDocument++;
}
// scroller should have aborted and so we shouldn't have scrolled everything as scrollSize = bucketSize = 1
assertNotEquals(DOC_BY_LEVEL, scrolledDocument);
}
}
}
|
timkpaine/arrow
|
r/src/schema.cpp
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "./arrow_types.h"
#if defined(ARROW_R_WITH_ARROW)
#include <arrow/ipc/writer.h>
#include <arrow/type.h>
#include <arrow/util/key_value_metadata.h>
// [[arrow::export]]
std::shared_ptr<arrow::Schema> schema_(
const std::vector<std::shared_ptr<arrow::Field>>& fields) {
return arrow::schema(fields);
}
// [[arrow::export]]
std::string Schema__ToString(const std::shared_ptr<arrow::Schema>& s) {
return s->ToString();
}
// [[arrow::export]]
int Schema__num_fields(const std::shared_ptr<arrow::Schema>& s) {
return s->num_fields();
}
// [[arrow::export]]
std::shared_ptr<arrow::Field> Schema__field(const std::shared_ptr<arrow::Schema>& s,
int i) {
if (i >= s->num_fields() || i < 0) {
cpp11::stop("Invalid field index for schema.");
}
return s->field(i);
}
// [[arrow::export]]
std::shared_ptr<arrow::Schema> Schema__AddField(
const std::shared_ptr<arrow::Schema>& s, int i,
const std::shared_ptr<arrow::Field>& field) {
return ValueOrStop(s->AddField(i, field));
}
// [[arrow::export]]
std::shared_ptr<arrow::Schema> Schema__SetField(
const std::shared_ptr<arrow::Schema>& s, int i,
const std::shared_ptr<arrow::Field>& field) {
return ValueOrStop(s->SetField(i, field));
}
// [[arrow::export]]
std::shared_ptr<arrow::Schema> Schema__RemoveField(
const std::shared_ptr<arrow::Schema>& s, int i) {
return ValueOrStop(s->RemoveField(i));
}
// [[arrow::export]]
std::shared_ptr<arrow::Field> Schema__GetFieldByName(
const std::shared_ptr<arrow::Schema>& s, std::string x) {
return s->GetFieldByName(x);
}
// [[arrow::export]]
cpp11::list Schema__fields(const std::shared_ptr<arrow::Schema>& schema) {
return arrow::r::to_r_list(schema->fields());
}
// [[arrow::export]]
std::vector<std::string> Schema__field_names(
const std::shared_ptr<arrow::Schema>& schema) {
return schema->field_names();
}
// [[arrow::export]]
bool Schema__HasMetadata(const std::shared_ptr<arrow::Schema>& schema) {
return schema->HasMetadata();
}
// [[arrow::export]]
cpp11::writable::list Schema__metadata(const std::shared_ptr<arrow::Schema>& schema) {
auto meta = schema->metadata();
int64_t n = 0;
if (schema->HasMetadata()) {
n = meta->size();
}
cpp11::writable::list out(n);
std::vector<std::string> names_out(n);
for (int i = 0; i < n; i++) {
auto key = meta->key(i);
out[i] = cpp11::as_sexp(meta->value(i));
if (key == "r") {
Rf_classgets(out[i], arrow::r::data::classes_metadata_r);
}
names_out[i] = key;
}
out.names() = names_out;
return out;
}
// [[arrow::export]]
std::shared_ptr<arrow::Schema> Schema__WithMetadata(
const std::shared_ptr<arrow::Schema>& schema, cpp11::strings metadata) {
auto values = cpp11::as_cpp<std::vector<std::string>>(metadata);
auto names = cpp11::as_cpp<std::vector<std::string>>(metadata.attr("names"));
auto kv =
std::make_shared<arrow::KeyValueMetadata>(std::move(names), std::move(values));
return schema->WithMetadata(std::move(kv));
}
// [[arrow::export]]
cpp11::writable::raws Schema__serialize(const std::shared_ptr<arrow::Schema>& schema) {
auto out = ValueOrStop(arrow::ipc::SerializeSchema(*schema));
auto n = out->size();
return cpp11::writable::raws(out->data(), out->data() + n);
}
// [[arrow::export]]
bool Schema__Equals(const std::shared_ptr<arrow::Schema>& schema,
const std::shared_ptr<arrow::Schema>& other, bool check_metadata) {
return schema->Equals(*other, check_metadata);
}
// [[arrow::export]]
std::shared_ptr<arrow::Schema> arrow__UnifySchemas(
const std::vector<std::shared_ptr<arrow::Schema>>& schemas) {
return ValueOrStop(arrow::UnifySchemas(schemas));
}
#endif
|
viniciusalmada/Drawer-Qt
|
manager/grid.cpp
|
#include "grid.h"
Grid::Grid() = default;
void Grid::setSnapData(bool isSnapOn, double dx, double dy) {
mGridX = dx;
mGridY = dy;
mIsSnapOn = isSnapOn;
}
bool Grid::getSnapInfo() const {
return mIsSnapOn;
}
pair<double, double> Grid::getGridSpace() {
return {mGridX, mGridY};
}
void Grid::snapTo(QPointF& pt) const {
QPointF pivotF{};
pivotF.rx() = pt.x() / mGridX;
pivotF.ry() = pt.y() / mGridY;
QPoint pivot = pivotF.toPoint();
pivot.rx() = (int) (pivot.rx() * mGridX);
pivot.ry() = (int) (pivot.ry() * mGridY);
QPoint p1 = pivot + QPoint{static_cast<int>(pivot.x() + mGridX), pivot.y()};
QPoint p2 = pivot + QPoint{static_cast<int>(pivot.x() + mGridX), static_cast<int>(pivot.y() + mGridY)};
QPoint p3 = pivot + QPoint{pivot.x(), static_cast<int>(pivot.y() + mGridY)};
pt = PointUtils::closestPoint(pt, {pivot, p1, p2, p3});
}
|
suhanime/installer
|
vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/pool.go
|
<reponame>suhanime/installer
package s3manager
import (
"fmt"
"sync"
"github.com/aws/aws-sdk-go/aws"
)
type byteSlicePool interface {
Get(aws.Context) (*[]byte, error)
Put(*[]byte)
ModifyCapacity(int)
SliceSize() int64
Close()
}
type maxSlicePool struct {
// allocator is defined as a function pointer to allow
// for test cases to instrument custom tracers when allocations
// occur.
allocator sliceAllocator
slices chan *[]byte
allocations chan struct{}
capacityChange chan struct{}
max int
sliceSize int64
mtx sync.RWMutex
}
func newMaxSlicePool(sliceSize int64) *maxSlicePool {
p := &maxSlicePool{sliceSize: sliceSize}
p.allocator = p.newSlice
return p
}
var errZeroCapacity = fmt.Errorf("get called on zero capacity pool")
func (p *maxSlicePool) Get(ctx aws.Context) (*[]byte, error) {
// check if context is canceled before attempting to get a slice
// this ensures priority is given to the cancel case first
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
p.mtx.RLock()
for {
select {
case bs, ok := <-p.slices:
p.mtx.RUnlock()
if !ok {
// attempt to get on a zero capacity pool
return nil, errZeroCapacity
}
return bs, nil
case _, ok := <-p.allocations:
p.mtx.RUnlock()
if !ok {
// attempt to get on a zero capacity pool
return nil, errZeroCapacity
}
return p.allocator(), nil
case <-ctx.Done():
p.mtx.RUnlock()
return nil, ctx.Err()
default:
// In the event that there are no slices or allocations available
// This prevents some deadlock situations that can occur around sync.RWMutex
// When a lock request occurs on ModifyCapacity, no new readers are allowed to acquire a read lock.
// By releasing the read lock here and waiting for a notification, we prevent a deadlock situation where
// Get could hold the read lock indefinitely waiting for capacity, ModifyCapacity is waiting for a write lock,
// and a Put is blocked trying to get a read-lock which is blocked by ModifyCapacity.
// Short-circuit if the pool capacity is zero.
if p.max == 0 {
p.mtx.RUnlock()
return nil, errZeroCapacity
}
// Since we will be releasing the read-lock we need to take the reference to the channel.
// Since channels are references we will still get notified if slices are added, or if
// the channel is closed due to a capacity modification. This specifically avoids a data race condition
// where ModifyCapacity both closes a channel and initializes a new one while we don't have a read-lock.
c := p.capacityChange
p.mtx.RUnlock()
select {
case _ = <-c:
p.mtx.RLock()
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
}
func (p *maxSlicePool) Put(bs *[]byte) {
p.mtx.RLock()
defer p.mtx.RUnlock()
if p.max == 0 {
return
}
select {
case p.slices <- bs:
p.notifyCapacity()
default:
// If the new channel when attempting to add the slice then we drop the slice.
// The logic here is to prevent a deadlock situation if channel is already at max capacity.
// Allows us to reap allocations that are returned and are no longer needed.
}
}
func (p *maxSlicePool) ModifyCapacity(delta int) {
if delta == 0 {
return
}
p.mtx.Lock()
defer p.mtx.Unlock()
p.max += delta
if p.max == 0 {
p.empty()
return
}
if p.capacityChange != nil {
close(p.capacityChange)
}
p.capacityChange = make(chan struct{}, p.max)
origAllocations := p.allocations
p.allocations = make(chan struct{}, p.max)
newAllocs := len(origAllocations) + delta
for i := 0; i < newAllocs; i++ {
p.allocations <- struct{}{}
}
if origAllocations != nil {
close(origAllocations)
}
origSlices := p.slices
p.slices = make(chan *[]byte, p.max)
if origSlices == nil {
return
}
close(origSlices)
for bs := range origSlices {
select {
case p.slices <- bs:
default:
// If the new channel blocks while adding slices from the old channel
// then we drop the slice. The logic here is to prevent a deadlock situation
// if the new channel has a smaller capacity then the old.
}
}
}
func (p *maxSlicePool) notifyCapacity() {
select {
case p.capacityChange <- struct{}{}:
default:
// This *shouldn't* happen as the channel is both buffered to the max pool capacity size and is resized
// on capacity modifications. This is just a safety to ensure that a blocking situation can't occur.
}
}
func (p *maxSlicePool) SliceSize() int64 {
return p.sliceSize
}
func (p *maxSlicePool) Close() {
p.mtx.Lock()
defer p.mtx.Unlock()
p.empty()
}
func (p *maxSlicePool) empty() {
p.max = 0
if p.capacityChange != nil {
close(p.capacityChange)
p.capacityChange = nil
}
if p.allocations != nil {
close(p.allocations)
for range p.allocations {
// drain channel
}
p.allocations = nil
}
if p.slices != nil {
close(p.slices)
for range p.slices {
// drain channel
}
p.slices = nil
}
}
func (p *maxSlicePool) newSlice() *[]byte {
bs := make([]byte, p.sliceSize)
return &bs
}
type returnCapacityPoolCloser struct {
byteSlicePool
returnCapacity int
}
func (n *returnCapacityPoolCloser) ModifyCapacity(delta int) {
if delta > 0 {
n.returnCapacity = -1 * delta
}
n.byteSlicePool.ModifyCapacity(delta)
}
func (n *returnCapacityPoolCloser) Close() {
if n.returnCapacity < 0 {
n.byteSlicePool.ModifyCapacity(n.returnCapacity)
}
}
type sliceAllocator func() *[]byte
var newByteSlicePool = func(sliceSize int64) byteSlicePool {
return newMaxSlicePool(sliceSize)
}
|
assens/activemq-artemis
|
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCreateConsumerTest.java
|
<filename>tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/SessionCreateConsumerTest.java
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.tests.integration.client;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.ActiveMQInvalidFilterExpressionException;
import org.apache.activemq.artemis.api.core.ActiveMQNonExistentQueueException;
import org.apache.activemq.artemis.api.core.client.ClientConsumer;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.core.client.impl.ClientSessionInternal;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class SessionCreateConsumerTest extends ActiveMQTestBase {
private final String queueName = "ClientSessionCreateConsumerTestQ";
private ServerLocator locator;
private ActiveMQServer service;
private ClientSessionInternal clientSession;
private ClientSessionFactory cf;
@Override
@Before
public void setUp() throws Exception {
locator = createInVMNonHALocator();
super.setUp();
service = createServer(false);
service.start();
locator.setProducerMaxRate(99).setBlockOnNonDurableSend(true).setBlockOnNonDurableSend(true);
cf = createSessionFactory(locator);
clientSession = (ClientSessionInternal) addClientSession(cf.createSession(false, true, true));
}
@Test
public void testCreateConsumer() throws Exception {
clientSession.createQueue(queueName, queueName, false);
ClientConsumer consumer = clientSession.createConsumer(queueName);
Assert.assertNotNull(consumer);
}
@Test
public void testCreateConsumerNoQ() throws Exception {
try {
clientSession.createConsumer(queueName);
Assert.fail("should throw exception");
} catch (ActiveMQNonExistentQueueException neqe) {
//ok
} catch (ActiveMQException e) {
fail("Invalid Exception type:" + e.getType());
}
}
@Test
public void testCreateConsumerWithFilter() throws Exception {
clientSession.createQueue(queueName, queueName, false);
ClientConsumer consumer = clientSession.createConsumer(queueName, "foo=bar");
Assert.assertNotNull(consumer);
}
@Test
public void testCreateConsumerWithInvalidFilter() throws Exception {
clientSession.createQueue(queueName, queueName, false);
try {
clientSession.createConsumer(queueName, "this is not valid filter");
Assert.fail("should throw exception");
} catch (ActiveMQInvalidFilterExpressionException ifee) {
//ok
} catch (ActiveMQException e) {
fail("Invalid Exception type:" + e.getType());
}
}
@Test
public void testCreateConsumerWithBrowseOnly() throws Exception {
clientSession.createQueue(queueName, queueName, false);
ClientConsumer consumer = clientSession.createConsumer(queueName, null, true);
Assert.assertNotNull(consumer);
}
@Test
public void testCreateConsumerWithOverrides() throws Exception {
clientSession.createQueue(queueName, queueName, false);
ClientConsumer consumer = clientSession.createConsumer(queueName, null, 100, 100, false);
Assert.assertNotNull(consumer);
}
}
|
phileinSophos/programming
|
LeetCode/1389_Target_Array_Given_Order.py
|
<filename>LeetCode/1389_Target_Array_Given_Order.py
'''
Problem Statement : 1389. Create Target Array in the Given Order
Link : https://leetcode.com/contest/weekly-contest-181/problems/create-target-array-in-the-given-order/
score : accepted
'''
class Solution:
def createTargetArray(self,nums, index):
'''
runtime : 32ms
'''
final = []
for number,ind in zip(nums,index):
final.insert(ind,number)
return final
def createTargetArray2(self,nums, index):
'''
runtime : 20ms
'''
final = []
for i in range(len(nums)):
final.insert(index[i],nums[i])
return final
nums = [1,2,3,4,0]
index = [0,1,2,3,0]
s = Solution()
#s.createTargetArray(nums,index)
s.createTargetArray2(nums,index)
|
sinefuse/shiromino
|
src/Input/KeyBindings.h
|
#pragma once
#include "PDINI.h"
#include "SDL.h"
#include <string>
namespace Shiro {
class KeyBindings {
public:
KeyBindings();
KeyBindings(const int playerNumber);
void read(PDINI::INI& ini);
void write(PDINI::INI& ini) const;
SDL_Keycode left;
SDL_Keycode right;
SDL_Keycode up;
SDL_Keycode down;
SDL_Keycode start;
SDL_Keycode a;
SDL_Keycode b;
SDL_Keycode c;
SDL_Keycode d;
SDL_Keycode escape;
};
}
|
bigbugbb/iTracker
|
app/src/main/java/com/itracker/android/xmpp/carbon/ForwardedProvider.java
|
<gh_stars>10-100
package com.itracker.android.xmpp.carbon;
import com.itracker.android.xmpp.AbstractExtensionProvider;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.util.PacketParserUtils;
import org.jivesoftware.smackx.delay.packet.DelayInformation;
import org.jivesoftware.smackx.delay.provider.DelayInformationProvider;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
/**
* Packet extension for XEP-0297: Stanza Forwarding. This class implements
* a {@link AbstractExtensionProvider} to parse forwarded messages from a packet.
* The extension <a href="http://xmpp.org/extensions/xep-0297.html">XEP-0297</a>
* is a prerequisite for XEP-0280 (Message Carbons).
*
* <p>The {@link ForwardedProvider} must be registered in the
* <b>smack.providers</b> file for the element <b>forwarded</b> with
* namespace <b>urn:xmpp:forwarded:0</b></p> to be used.
*
* @author <NAME>
*/
public class ForwardedProvider extends AbstractExtensionProvider<Forwarded> {
DelayInformationProvider dip = new DelayInformationProvider();
@Override
protected Forwarded createInstance(XmlPullParser parser) {
return new Forwarded(null, null);
}
@Override
public Forwarded parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException, SmackException {
DelayInformationProvider delayInformationProvider = new DelayInformationProvider();
DelayInformation delayInformation = null;
Stanza packet = null;
boolean done = false;
while (!done) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("delay"))
delayInformation = delayInformationProvider.parse(parser);
else if (parser.getName().equals("message"))
packet = PacketParserUtils.parseMessage(parser);
else throw new SmackException("Unsupported forwarded packet type: " + parser.getName());
}
else if (eventType == XmlPullParser.END_TAG && parser.getName().equals(Forwarded.ELEMENT_NAME))
done = true;
}
if (packet == null)
throw new SmackException("forwarded extension must contain a packet");
return new Forwarded(delayInformation, packet);
}
}
|
khcitizen/tomcat-deployed
|
webapps/jasperserver-pro/scripts/bower_components/jrs-ui/src/dataSource/DataSourceController.js
|
<reponame>khcitizen/tomcat-deployed<filename>webapps/jasperserver-pro/scripts/bower_components/jrs-ui/src/dataSource/DataSourceController.js
/*
* Copyright (C) 2005 - 2018 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author: <NAME>
* @version: $Id$
*/
/* global dialogs, redirectToUrl */
define(function (require) {
"use strict";
var Backbone = require("backbone"),
_ = require("underscore"),
$ = require("jquery"),
i18n = require("bundle!all"),
BaseDataSourceModel = require("dataSource/model/BaseDataSourceModel"),
TouchController = require("touchcontroller"),
featureDetection = require("common/util/featureDetection"),
history = require("util/historyHelper"),
dataSourceViewFactory = require("dataSource/factory/dataSourceViewFactory"),
dataSourceResourceTypes = require("dataSource/enum/dataSourceResourceTypes"),
saveDialogViewFactory = require("dataSource/factory/saveDialogViewFactory"),
dataSourceMainTemplate = require("text!dataSource/template/dataSourceMainTemplate.htm"),
jrsConfigs = require('jrs.configs'),
CustomDataSourcesCollection = require("dataSource/collection/CustomDataSourceCollection"),
awsSettings = require("settings!awsSettings"),
settingsUtility = require("dataSource/util/settingsUtility");
return Backbone.View.extend({
dataSourceType: false,
dataSourceView: false,
saveDialog: false,
events: {
"change select[name='dataSourceType']" : "onDataSourceTypeChange",
"click #saveBtn" : "onSaveClick",
"click #cancelBtn" : "onCancelClick"
},
historyBackToken: "DataSourceControllerHistory",
constructor: function(options) {
// since the options object will be changed, we need to make the copy of it
options = $.extend(true, {}, options);
arguments[0] = options;
this.isEditMode = options.isEditMode;
Backbone.View.apply(this, arguments);
},
initialize: function(options) {
this.options = options;
this.dataSourceType = undefined;
featureDetection.supportsTouch && this.initSwipeScroll();
history.saveReferrer(this.historyBackToken);
// Starting the game !
// from the early beginning we need to have answers to 2 questions:
// a) what custom data sources are defined in XML files on the server ?
// b) are we in the editing mode ? if yes, then we need to get that model from the server
//
// As you will see below, these questions need async requests to server, and because of
// this we are creating two deferred objects
// allows us to wait till we get 'custom data sources' from xml files
this.fetchingCustomDataSourcesDeferred = $.Deferred();
// allows us to wait till we fetch the model
this.fetchingTheModelDeferred = $.Deferred();
// So, fetching 'custom data sources' from the server
// (these 'custom data sources' defined in XML files)
this.customDataSourceCollection = new CustomDataSourcesCollection();
this.customDataSourceCollection.fetch().done(_.bind(function(){this.renderDataSourceContainer();}, this));
var deepDefaults = settingsUtility.deepDefaults(options, {
awsSettings: awsSettings
});
// Also, deciding if we are in the editing mode, and if we are, then we need to fetch the model
// If we aren't, then we can just resolve the deferred object
if (this.options.resourceUri) {
// we are in the editing an existing DS mode, so we need to fetch it from the server
var self = this, modelToEdit = new BaseDataSourceModel({uri: this.options.resourceUri});
modelToEdit.fetch().then(function(data, textStatus, jqXHR) {
self.dataSource = modelToEdit.attributes;
self.dataSourceType = dataSourceViewFactory.getViewType(jqXHR.getResponseHeader("Content-Type"), self.dataSource);
self.fetchingTheModelDeferred.resolve();
});
} else if (this.options.dataSource && this.options.dataSourceClientType) {
// data source and it's client type are available. So, it's edit mode and no fetching is required.
this.dataSource = this.options.dataSource;
this.dataSourceType = dataSourceViewFactory.getViewType(this.options.dataSourceClientType, this.options.dataSource);
this.fetchingTheModelDeferred.resolve();
} else {
// if this product working on AWS - by default we create AWS Data Source
if (deepDefaults.awsSettings.productTypeIsEc2) {
this.dataSourceType = dataSourceViewFactory.getViewType(dataSourceResourceTypes.AWS, null);
}
this.fetchingTheModelDeferred.resolve();
}
},
renderDataSourceContainer: function() {
// key in dataSourceLabelSuffixes should be equal to corresponding key in dataSourceResourceTypes
var dataSourceLabelSuffixes = {
AZURE_SQL: "AzureSql",
AWS: "Aws",
BEAN: "Bean",
JDBC: "JDBC",
JNDI: "JNDI",
VIRTUAL: "Virtual"
};
// fill in the pre-existent data sources
var dataSourceTypeOptions = _.chain(dataSourceLabelSuffixes)
.map(function(value, key){
return {
value: dataSourceResourceTypes[key].toLowerCase(),
label: i18n['resource.dataSource.dstype' + value]
};
})
.value();
// now, add custom data sources which are defined in XML files on the server
this.customDataSourceCollection.forEach(function(element) {
var currentCustomDataSourceType = element.get("id");
// disable file data sources for now
// if (currentCustomDataSourceType in {"xlsDataSource": 1, "xlsxDataSource": 1, "textDataSource":1}) {
// return;
// }
dataSourceTypeOptions.push({
value: currentCustomDataSourceType,
label: i18n[currentCustomDataSourceType + '.name'] ? i18n[currentCustomDataSourceType + '.name'] : currentCustomDataSourceType
});
});
// sort them
dataSourceTypeOptions = _.sortBy(dataSourceTypeOptions, function(option) {
return option.label.toLowerCase();
});
// and display the interface header and select of data source type
this.$el.append(_.template(dataSourceMainTemplate, {
dataSourceTypeOptions: dataSourceTypeOptions,
i18n: i18n,
supportsTouch: featureDetection.supportsTouch,
isEditMode: this.isEditMode
}));
// resolve deferred object
this.fetchingCustomDataSourcesDeferred.resolve();
},
initSwipeScroll: function() {
var display = this.$("#stepDisplay");
display.length && new TouchController(display.parent()[0], display.parent().parent()[0], {});
},
render: function(){
$.when(this.fetchingCustomDataSourcesDeferred, this.fetchingTheModelDeferred)
.done(_.bind(function(){this._render();}, this));
},
_render: function() {
var saveParams = {};
if (this.dataSourceView) {
saveParams = {
label: this.dataSourceView.model.get("label"),
name: this.dataSourceView.model.get("name"),
description: this.dataSourceView.model.get("description")
};
}
this.dataSourceView && this.dataSourceView.remove();
delete this.dataSourceView;
// if we already removed view, "body" element was also removed, so we need to recreate it for new view manually
if (this.$(".row.inputs .body:eq(0)").length === 0) {
this.$(".row.inputs > .column > .content").append("<div class='body dataSourceBody'></div>");
}
if (!this.dataSourceType) {
this.dataSourceType = dataSourceResourceTypes.JDBC.toLowerCase();
// Use it for development reasons: you can pre-select any DS type
//this.dataSourceType = "MongoDbDataSource";
}
this.dataSourceView = dataSourceViewFactory.getView(_.extend(this.options, {
dataSourceType: this.dataSourceType,
dataSource: _.extend({}, this.dataSource, saveParams),
el: this.$(".row.inputs .body:eq(0)")
}));
// set specific class to help customize specific page with css styles
this.$(".dataSourceBody").attr("dstype", this.dataSourceType.toLowerCase());
this.$("select[name='dataSourceType']").val(this.dataSourceType);
return this;
},
onDataSourceTypeChange: function(e) {
var selectedType = $(e.target).val();
if (this.dataSourceType != selectedType) {
this.dataSourceType = selectedType;
this.render();
}
},
_prepareSaveDialog: function() {
this.saveDialog && this.saveDialog.remove();
var SaveDialog = saveDialogViewFactory.getView(this.dataSourceType);
this.saveDialog = new SaveDialog(_.extend({}, this.options, {
model: this.dataSourceView.model,
saveFn: this.options.saveFn,
success: _.bind(this._onSaveDone, this),
error: _.bind(this._onSaveFail, this)
}));
},
onSaveClick: function() {
if (!this.dataSourceView.model.isValid(true)) {
return;
}
var self = this, funcOnceValidationPassed = function() {
self._prepareSaveDialog();
self.saveDialog.startSaveDialog();
};
// validationMethodOnSaveClick is moved to view in text-data-source branch,
// but let's have them both (in model and in a view) here till merged
if (!_.isUndefined(this.dataSourceView.model.validationMethodOnSaveClick)) {
this.dataSourceView.model.validationMethodOnSaveClick(funcOnceValidationPassed);
return;
} else if (!_.isUndefined(this.dataSourceView.validationMethodOnSaveClick)) {
this.dataSourceView.validationMethodOnSaveClick(funcOnceValidationPassed);
return;
}
funcOnceValidationPassed();
},
_onSaveDone: function() {
redirectToUrl(jrsConfigs.contextPath + "/flow.html?_flowId=repositoryConfirmFlow&resourceType=dataSource");
},
_onSaveFail: function(model, xhr) {
if (this.saveDialog) {
this.saveDialog.close();
this.saveDialog.remove();
}
var self = this, errors = false, msg;
var handled = false;
try { errors = JSON.parse(xhr.responseText); } catch(e) {}
if (!_.isArray(errors)) {
errors = [errors];
}
_.each(errors, function(error){
var field = false, msg = false;
if (!error) {
return;
}
if (error.errorCode === "mandatory.parameter.error") {
if (error.parameters && error.parameters[0]) {
msg = i18n["resource.datasource.saveDialog.parameterIsMissing"];
field = error.parameters[0].substr(error.parameters[0].indexOf(".") + 1);
}
}
else if (error.errorCode === "illegal.parameter.value.error") {
if (error.parameters && error.parameters[0]) {
field = error.parameters[0].substr(error.parameters[0].indexOf(".") + 1);
msg = i18n["resource.datasource.saveDialog.parameterIsWrong"];
}
}
// converting field names
if (field === "ConnectionUrl") {
field = "connectionUrl";
}
if (msg && field) {
self.dataSourceView.invalidField(
"[name=" + field + "]",
msg
);
handled = true;
}
});
if (handled === false) {
// otherwise, proceed with common error handling
msg = "Failed to save data source.";
if (errors[0] && errors[0].errorCode) msg += "<br/>The reason is: " + errors[0].errorCode;
else if (errors.message) msg += "<br/>The reason is: " + errors.message;
msg += "<br/><br/>The full response from the server is: " + xhr.responseText;
dialogs.errorPopup.show(msg);
}
},
onCancelClick: function() {
if (this.options.cancelFn) {
this.options.cancelFn();
} else {
history.restore(this.historyBackToken);
}
}
});
});
|
AntsCodeCommunity/spring-boot
|
spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/configuration/ResolvedDockerHostTests.java
|
/*
* Copyright 2012-2022 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
*
* https://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.springframework.boot.buildpack.platform.docker.configuration;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.api.io.TempDir;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ResolvedDockerHost}.
*
* @author <NAME>
*/
class ResolvedDockerHostTests {
private final Map<String, String> environment = new LinkedHashMap<>();
@Test
@DisabledOnOs(OS.WINDOWS)
void resolveWhenDockerHostIsNullReturnsLinuxDefault() {
ResolvedDockerHost dockerHost = ResolvedDockerHost.from(this.environment::get, null);
assertThat(dockerHost.getAddress()).isEqualTo("/var/run/docker.sock");
assertThat(dockerHost.isSecure()).isFalse();
assertThat(dockerHost.getCertificatePath()).isNull();
}
@Test
@EnabledOnOs(OS.WINDOWS)
void resolveWhenDockerHostIsNullReturnsWindowsDefault() {
ResolvedDockerHost dockerHost = ResolvedDockerHost.from(this.environment::get, null);
assertThat(dockerHost.getAddress()).isEqualTo("//./pipe/docker_engine");
assertThat(dockerHost.isSecure()).isFalse();
assertThat(dockerHost.getCertificatePath()).isNull();
}
@Test
@DisabledOnOs(OS.WINDOWS)
void resolveWhenDockerHostAddressIsNullReturnsLinuxDefault() {
ResolvedDockerHost dockerHost = ResolvedDockerHost.from(this.environment::get, new DockerHost(null));
assertThat(dockerHost.getAddress()).isEqualTo("/var/run/docker.sock");
assertThat(dockerHost.isSecure()).isFalse();
assertThat(dockerHost.getCertificatePath()).isNull();
}
@Test
void resolveWhenDockerHostAddressIsLocalReturnsAddress(@TempDir Path tempDir) throws IOException {
String socketFilePath = Files.createTempFile(tempDir, "remote-transport", null).toAbsolutePath().toString();
ResolvedDockerHost dockerHost = ResolvedDockerHost.from(this.environment::get,
new DockerHost(socketFilePath, false, null));
assertThat(dockerHost.isLocalFileReference()).isTrue();
assertThat(dockerHost.isRemote()).isFalse();
assertThat(dockerHost.getAddress()).isEqualTo(socketFilePath);
assertThat(dockerHost.isSecure()).isFalse();
assertThat(dockerHost.getCertificatePath()).isNull();
}
@Test
void resolveWhenDockerHostAddressIsLocalWithSchemeReturnsAddress(@TempDir Path tempDir) throws IOException {
String socketFilePath = Files.createTempFile(tempDir, "remote-transport", null).toAbsolutePath().toString();
ResolvedDockerHost dockerHost = ResolvedDockerHost.from(this.environment::get,
new DockerHost("unix://" + socketFilePath, false, null));
assertThat(dockerHost.isLocalFileReference()).isTrue();
assertThat(dockerHost.isRemote()).isFalse();
assertThat(dockerHost.getAddress()).isEqualTo(socketFilePath);
assertThat(dockerHost.isSecure()).isFalse();
assertThat(dockerHost.getCertificatePath()).isNull();
}
@Test
void resolveWhenDockerHostAddressIsHttpReturnsAddress() {
ResolvedDockerHost dockerHost = ResolvedDockerHost.from(this.environment::get,
new DockerHost("http://docker.example.com", false, null));
assertThat(dockerHost.isLocalFileReference()).isFalse();
assertThat(dockerHost.isRemote()).isTrue();
assertThat(dockerHost.getAddress()).isEqualTo("http://docker.example.com");
assertThat(dockerHost.isSecure()).isFalse();
assertThat(dockerHost.getCertificatePath()).isNull();
}
@Test
void resolveWhenDockerHostAddressIsHttpsReturnsAddress() {
ResolvedDockerHost dockerHost = ResolvedDockerHost.from(this.environment::get,
new DockerHost("https://docker.example.com", true, "/cert-path"));
assertThat(dockerHost.isLocalFileReference()).isFalse();
assertThat(dockerHost.isRemote()).isTrue();
assertThat(dockerHost.getAddress()).isEqualTo("https://docker.example.com");
assertThat(dockerHost.isSecure()).isTrue();
assertThat(dockerHost.getCertificatePath()).isEqualTo("/cert-path");
}
@Test
void resolveWhenDockerHostAddressIsTcpReturnsAddress() {
ResolvedDockerHost dockerHost = ResolvedDockerHost.from(this.environment::get,
new DockerHost("tcp://192.168.99.100:2376", true, "/cert-path"));
assertThat(dockerHost.isLocalFileReference()).isFalse();
assertThat(dockerHost.isRemote()).isTrue();
assertThat(dockerHost.getAddress()).isEqualTo("tcp://192.168.99.100:2376");
assertThat(dockerHost.isSecure()).isTrue();
assertThat(dockerHost.getCertificatePath()).isEqualTo("/cert-path");
}
@Test
void resolveWhenEnvironmentAddressIsLocalReturnsAddress(@TempDir Path tempDir) throws IOException {
String socketFilePath = Files.createTempFile(tempDir, "remote-transport", null).toAbsolutePath().toString();
this.environment.put("DOCKER_HOST", socketFilePath);
ResolvedDockerHost dockerHost = ResolvedDockerHost.from(this.environment::get,
new DockerHost("/unused", true, "/unused"));
assertThat(dockerHost.isLocalFileReference()).isTrue();
assertThat(dockerHost.isRemote()).isFalse();
assertThat(dockerHost.getAddress()).isEqualTo(socketFilePath);
assertThat(dockerHost.isSecure()).isFalse();
assertThat(dockerHost.getCertificatePath()).isNull();
}
@Test
void resolveWhenEnvironmentAddressIsLocalWithSchemeReturnsAddress(@TempDir Path tempDir) throws IOException {
String socketFilePath = Files.createTempFile(tempDir, "remote-transport", null).toAbsolutePath().toString();
this.environment.put("DOCKER_HOST", "unix://" + socketFilePath);
ResolvedDockerHost dockerHost = ResolvedDockerHost.from(this.environment::get,
new DockerHost("/unused", true, "/unused"));
assertThat(dockerHost.isLocalFileReference()).isTrue();
assertThat(dockerHost.isRemote()).isFalse();
assertThat(dockerHost.getAddress()).isEqualTo(socketFilePath);
assertThat(dockerHost.isSecure()).isFalse();
assertThat(dockerHost.getCertificatePath()).isNull();
}
@Test
void resolveWhenEnvironmentAddressIsTcpReturnsAddress() {
this.environment.put("DOCKER_HOST", "tcp://192.168.99.100:2376");
this.environment.put("DOCKER_TLS_VERIFY", "1");
this.environment.put("DOCKER_CERT_PATH", "/cert-path");
ResolvedDockerHost dockerHost = ResolvedDockerHost.from(this.environment::get,
new DockerHost("tcp://1.1.1.1", false, "/unused"));
assertThat(dockerHost.isLocalFileReference()).isFalse();
assertThat(dockerHost.isRemote()).isTrue();
assertThat(dockerHost.getAddress()).isEqualTo("tcp://192.168.99.100:2376");
assertThat(dockerHost.isSecure()).isTrue();
assertThat(dockerHost.getCertificatePath()).isEqualTo("/cert-path");
}
}
|
hatchways/team-fruit-loops
|
server/routes/stripe.js
|
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser')
const authenticate = require("../controllers/authenticate");
const stripe = require('../controllers/stripe');
router.post('/webhook', bodyParser.raw({type: 'application/json'}), stripe.webhook);
// requests to stripe user should target valid user
router.use('/:player', authenticate.player);
router.get('/:player/intent', stripe.intent);
router.get('/:player/private-enabled', stripe.privateGamesEnabled);
module.exports = router;
|
mishadynin/ideal
|
bootstrapped/ideal/runtime/elements/empty.java
|
<reponame>mishadynin/ideal<gh_stars>0
// Autogenerated from runtime/elements/empty.i
package ideal.runtime.elements;
import ideal.library.elements.*;
public class empty<element_type> implements immutable_list<element_type>, immutable_set<element_type> {
public empty() { }
public @Override int size() {
return 0;
}
public @Override boolean is_empty() {
return true;
}
public @Override element_type first() {
utilities.panic(new base_string("Can't access the first element of the empty list"));
return null;
}
public @Override element_type last() {
utilities.panic(new base_string("Can't access the last element of the empty list"));
return null;
}
public @Override boolean contains(final element_type key) {
return false;
}
public @Override element_type get(final int index) {
utilities.panic(new base_string("Empty list"));
return null;
}
public @Override immutable_list<element_type> elements() {
return this;
}
public @Override empty<element_type> frozen_copy() {
return this;
}
public @Override immutable_list<element_type> skip(final int count) {
assert count == 0;
return this;
}
public @Override immutable_list<element_type> slice(final int begin, final int end) {
assert begin == 0 && end == 0;
return this;
}
public @Override immutable_list<element_type> reverse() {
return this;
}
}
|
perfectrecall/aws-sdk-cpp
|
aws-cpp-sdk-iotwireless/include/aws/iotwireless/model/GetWirelessDeviceRequest.h
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/iotwireless/IoTWireless_EXPORTS.h>
#include <aws/iotwireless/IoTWirelessRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/iotwireless/model/WirelessDeviceIdType.h>
#include <utility>
namespace Aws
{
namespace Http
{
class URI;
} //namespace Http
namespace IoTWireless
{
namespace Model
{
/**
*/
class AWS_IOTWIRELESS_API GetWirelessDeviceRequest : public IoTWirelessRequest
{
public:
GetWirelessDeviceRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "GetWirelessDevice"; }
Aws::String SerializePayload() const override;
void AddQueryStringParameters(Aws::Http::URI& uri) const override;
/**
* <p>The identifier of the wireless device to get.</p>
*/
inline const Aws::String& GetIdentifier() const{ return m_identifier; }
/**
* <p>The identifier of the wireless device to get.</p>
*/
inline bool IdentifierHasBeenSet() const { return m_identifierHasBeenSet; }
/**
* <p>The identifier of the wireless device to get.</p>
*/
inline void SetIdentifier(const Aws::String& value) { m_identifierHasBeenSet = true; m_identifier = value; }
/**
* <p>The identifier of the wireless device to get.</p>
*/
inline void SetIdentifier(Aws::String&& value) { m_identifierHasBeenSet = true; m_identifier = std::move(value); }
/**
* <p>The identifier of the wireless device to get.</p>
*/
inline void SetIdentifier(const char* value) { m_identifierHasBeenSet = true; m_identifier.assign(value); }
/**
* <p>The identifier of the wireless device to get.</p>
*/
inline GetWirelessDeviceRequest& WithIdentifier(const Aws::String& value) { SetIdentifier(value); return *this;}
/**
* <p>The identifier of the wireless device to get.</p>
*/
inline GetWirelessDeviceRequest& WithIdentifier(Aws::String&& value) { SetIdentifier(std::move(value)); return *this;}
/**
* <p>The identifier of the wireless device to get.</p>
*/
inline GetWirelessDeviceRequest& WithIdentifier(const char* value) { SetIdentifier(value); return *this;}
/**
* <p>The type of identifier used in <code>identifier</code>.</p>
*/
inline const WirelessDeviceIdType& GetIdentifierType() const{ return m_identifierType; }
/**
* <p>The type of identifier used in <code>identifier</code>.</p>
*/
inline bool IdentifierTypeHasBeenSet() const { return m_identifierTypeHasBeenSet; }
/**
* <p>The type of identifier used in <code>identifier</code>.</p>
*/
inline void SetIdentifierType(const WirelessDeviceIdType& value) { m_identifierTypeHasBeenSet = true; m_identifierType = value; }
/**
* <p>The type of identifier used in <code>identifier</code>.</p>
*/
inline void SetIdentifierType(WirelessDeviceIdType&& value) { m_identifierTypeHasBeenSet = true; m_identifierType = std::move(value); }
/**
* <p>The type of identifier used in <code>identifier</code>.</p>
*/
inline GetWirelessDeviceRequest& WithIdentifierType(const WirelessDeviceIdType& value) { SetIdentifierType(value); return *this;}
/**
* <p>The type of identifier used in <code>identifier</code>.</p>
*/
inline GetWirelessDeviceRequest& WithIdentifierType(WirelessDeviceIdType&& value) { SetIdentifierType(std::move(value)); return *this;}
private:
Aws::String m_identifier;
bool m_identifierHasBeenSet;
WirelessDeviceIdType m_identifierType;
bool m_identifierTypeHasBeenSet;
};
} // namespace Model
} // namespace IoTWireless
} // namespace Aws
|
wangcy6/weekly.github.io
|
KM/03code/book/Thinking-In-C-resource-master/C04/c0416.cpp
|
#include "c0416.h"
#include <cassert>
void VStash::initialize(int sz)
{
size = sz;
next = 0;
}
void VStash::cleanup()
{}
int VStash:: add(const void* element)
{
for(int i = 0; i < size; i++)
{
storage.push_back(((char*)element)[i]);
}
next++;
return (next - 1);
}
void* VStash::fetch(int index)
{
assert(index >= 0);
if(index >= next)
return 0;
return &(storage[index * size]);
}
int VStash::count()
{
return next;
}
|
Boundarybreaker/LibBlockAttributes
|
src/main/java/alexiil/mc/lib/attributes/fluid/impl/SimpleFixedFluidInvExtractable.java
|
package alexiil.mc.lib.attributes.fluid.impl;
import alexiil.mc.lib.attributes.Simulation;
import alexiil.mc.lib.attributes.fluid.FixedFluidInv;
import alexiil.mc.lib.attributes.fluid.FluidExtractable;
import alexiil.mc.lib.attributes.fluid.filter.FluidFilter;
import alexiil.mc.lib.attributes.fluid.volume.FluidKeys;
import alexiil.mc.lib.attributes.fluid.volume.FluidVolume;
/** @deprecated Use {@link GroupedFluidInvFixedWrapper} instead of this! */
@Deprecated
public final class SimpleFixedFluidInvExtractable implements FluidExtractable {
private final FixedFluidInv inv;
/** Null means that this can extract from any of the tanks. */
private final int[] tanks;
public SimpleFixedFluidInvExtractable(FixedFluidInv inv, int[] tanks) {
this.inv = inv;
this.tanks = tanks;
}
@Override
public FluidVolume attemptExtraction(FluidFilter filter, int maxAmount, Simulation simulation) {
if (maxAmount < 0) {
throw new IllegalArgumentException("maxAmount cannot be negative! (was " + maxAmount + ")");
}
FluidVolume fluid = FluidKeys.EMPTY.withAmount(0);
if (maxAmount == 0) {
return fluid;
}
if (tanks == null) {
for (int t = 0; t < inv.getTankCount(); t++) {
FluidVolume invFluid = inv.getInvFluid(t);
if (invFluid.isEmpty() || !filter.matches(invFluid.fluidKey)) {
continue;
}
invFluid = invFluid.copy();
FluidVolume addable = invFluid.split(maxAmount);
FluidVolume merged = FluidVolume.merge(fluid, addable);
if (merged != null && inv.setInvFluid(t, invFluid, simulation)) {
maxAmount -= addable.getAmount();
fluid = merged;
assert maxAmount >= 0;
if (maxAmount <= 0) {
return fluid;
}
}
}
} else {
for (int t : tanks) {
// Copy of above
FluidVolume invFluid = inv.getInvFluid(t);
if (invFluid.isEmpty() || !filter.matches(invFluid.fluidKey)) {
continue;
}
invFluid = invFluid.copy();
FluidVolume addable = invFluid.split(maxAmount);
FluidVolume merged = FluidVolume.merge(fluid, addable);
if (merged != null && inv.setInvFluid(t, invFluid, simulation)) {
maxAmount -= addable.getAmount();
fluid = merged;
assert maxAmount >= 0;
if (maxAmount <= 0) {
return fluid;
}
}
}
}
return fluid;
}
}
|
rebaze/neo4j
|
enterprise/ha/src/main/java/org/neo4j/kernel/ha/HaCaches.java
|
<gh_stars>1-10
/**
* Copyright (c) 2002-2013 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.ha;
import static org.neo4j.graphdb.factory.GraphDatabaseSettings.node_cache_array_fraction;
import static org.neo4j.graphdb.factory.GraphDatabaseSettings.node_cache_size;
import static org.neo4j.graphdb.factory.GraphDatabaseSettings.relationship_cache_array_fraction;
import static org.neo4j.graphdb.factory.GraphDatabaseSettings.relationship_cache_size;
import org.neo4j.graphdb.factory.GraphDatabaseSetting;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.kernel.impl.cache.Cache;
import org.neo4j.kernel.impl.cache.CacheProvider;
import org.neo4j.kernel.impl.cache.GCResistantCacheProvider;
import org.neo4j.kernel.impl.core.Caches;
import org.neo4j.kernel.impl.core.NodeImpl;
import org.neo4j.kernel.impl.core.RelationshipImpl;
import org.neo4j.kernel.impl.util.StringLogger;
public class HaCaches implements Caches
{
private CacheProvider type;
private Config config;
private Cache<NodeImpl> node;
private Cache<RelationshipImpl> relationship;
private final StringLogger logger;
public HaCaches( StringLogger logger )
{
this.logger = logger;
}
@Override
public void configure( CacheProvider newType, Config config )
{
if ( !cacheConfigSame( newType, config ) )
{
node = newType.newNodeCache( logger, config );
relationship = newType.newRelationshipCache( logger, config );
}
else
{
node.clear();
relationship.clear();
}
this.type = newType;
this.config = config;
}
private boolean cacheConfigSame( CacheProvider type, Config config )
{
return
this.type != null && this.type.getName().equals( type.getName() ) &&
// Only reuse array caches, since the other ones are cheap to recreate
GCResistantCacheProvider.NAME.equals( this.type.getName() ) &&
mySettingIsSameAs(config, node_cache_array_fraction ) &&
mySettingIsSameAs(config, relationship_cache_array_fraction ) &&
mySettingIsSameAs(config, node_cache_size) &&
mySettingIsSameAs(config, relationship_cache_size);
}
private boolean mySettingIsSameAs(Config otherConfig, GraphDatabaseSetting<?> setting) {
Object myValue = config.get(setting);
Object otherValue = otherConfig.get(setting);
return myValue.equals(otherValue);
}
@Override
public Cache<NodeImpl> node()
{
return node;
}
@Override
public Cache<RelationshipImpl> relationship()
{
return relationship;
}
@Override
public void invalidate()
{
type = null;
config = null;
}
}
|
Lavish883/Loki-Stream
|
node_modules/@react-navigation/material-top-tabs/lib/commonjs/views/MaterialTopTabView.js
|
version https://git-lfs.github.com/spec/v1
oid sha256:0befbd6472f77861ce0a67d2ee4039004cf5eaf462f32c7396165c7427adf01a
size 3032
|
jarekankowski/pegasus_spyware
|
sample3/recompiled_java/sources/android/support/v4/content/res/ResourcesCompatIcsMr1.java
|
<reponame>jarekankowski/pegasus_spyware
package android.support.v4.content.res;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
class ResourcesCompatIcsMr1 {
ResourcesCompatIcsMr1() {
}
public static Drawable getDrawableForDensity(Resources res, int id, int density) throws Resources.NotFoundException {
return res.getDrawableForDensity(id, density);
}
}
|
psrc/psrc
|
vendor/extensions/event_registrations/vendor/plugins/active_merchant/test/unit/integrations/action_view_helper_test.rb
|
require 'test_helper'
class ActionViewHelperTest < Test::Unit::TestCase
include ActiveMerchant::Billing::Integrations::ActionViewHelper
include ActionView::Helpers::FormHelper
include ActionView::Helpers::FormTagHelper
include ActionView::Helpers::UrlHelper
include ActionView::Helpers::TagHelper
include ActionView::Helpers::TextHelper
attr_accessor :output_buffer
def setup
@controller = Class.new do
attr_reader :url_for_options
def url_for(options, *parameters_for_method_reference)
@url_for_options = options
end
end
@controller = @controller.new
@output_buffer = ''
end
def test_basic_payment_service
_erbout = ''
payment_service_for('order-1','test', :service => :bogus){}
expected = [
'<form action="http://www.bogus.com" method="post">',
'<input id="order" name="order" type="hidden" value="order-1" />',
'<input id="account" name="account" type="hidden" value="test" />',
"</form>"
]
_erbout.each_line do |line|
assert expected.include?(line.chomp), "Failed to match #{line}"
end
end
def test_payment_service_no_block_given
assert_raise(ArgumentError){ payment_service_for }
end
protected
def protect_against_forgery?
false
end
end
|
l3ch4tno1r/LCN_Math
|
Source/_Geometry/VectorBase.h
|
#pragma once
#include <cmath>
#include "_Matrix/StaticMatrixBase.h"
template<class Derived, typename T, size_t N>
class VectorBase : public StaticMatrixBase<Derived, T, N, 1>
{
public:
T operator[](size_t i) const { return this->Derived()[i]; }
T SquareNorm() const
{
T norm = 0;
for (size_t i = 0; i < N; ++i)
norm += (*this)[i] * (*this)[i];
return norm;
}
T Norm() const
{
return std::sqrt(this->SquareNorm());
}
};
template<class E, typename T, size_t N>
T operator|(const VectorBase<E, T, N>& a, const VectorBase<E, T, N>& b)
{
T dotproduct = 0;
for (size_t i = 0; i < N; ++i)
dotproduct += a[i] * b[i];
return dotproduct;
}
|
antelets/synopsys-detect
|
src/main/java/com/synopsys/integration/detect/tool/impactanalysis/ImpactAnalysisNamingOperation.java
|
<filename>src/main/java/com/synopsys/integration/detect/tool/impactanalysis/ImpactAnalysisNamingOperation.java
/*
* synopsys-detect
*
* Copyright (c) 2021 Synopsys, Inc.
*
* Use subject to the terms and conditions of the Synopsys End User Software License and Maintenance Agreement. All rights reserved worldwide.
*/
package com.synopsys.integration.detect.tool.impactanalysis;
import java.io.File;
import java.io.IOException;
import com.synopsys.integration.detect.workflow.codelocation.CodeLocationNameManager;
import com.synopsys.integration.util.NameVersion;
public class ImpactAnalysisNamingOperation {
private final CodeLocationNameManager codeLocationNameManager;
public ImpactAnalysisNamingOperation(final CodeLocationNameManager codeLocationNameManager) {
this.codeLocationNameManager = codeLocationNameManager;
}
public String createCodeLocationName(File toScan, NameVersion projectNameAndVersion, ImpactAnalysisOptions impactAnalysisOptions) throws IOException {
String projectName = projectNameAndVersion.getName();
String projectVersionName = projectNameAndVersion.getVersion();
String codeLocationPrefix = impactAnalysisOptions.getCodeLocationPrefix();
String codeLocationSuffix = impactAnalysisOptions.getCodeLocationSuffix();
return codeLocationNameManager.createImpactAnalysisCodeLocationName(toScan, projectName, projectVersionName, codeLocationPrefix, codeLocationSuffix);
}
}
|
Zaid-maker/DiscordBot
|
src/commands/admin/Purge.js
|
<filename>src/commands/admin/Purge.js<gh_stars>10-100
const { Command } = require('discord.js-commando');
module.exports = class PurgeCommand extends Command {
constructor(client) {
super(client, {
name: 'purge',
group: 'admin',
memberName: 'purge',
description:
'Filters through set number of messages (default: 10) removing the messages from a single user',
examples: ['purge @odyn 10 spam', 'purge @Bryan 100'],
args: [
{
key: 'member',
prompt: 'Who do you want to purge?',
type: 'member',
},
{
key: 'num_messages',
prompt: 'How many messages do you want to filter through?',
type: 'integer',
default: 10,
},
{
key: 'reason',
prompt: 'Why do you want to purge them?',
type: 'string',
default: "'None provided'",
},
],
clientPermissions: ['MANAGE_MESSAGES'],
userPermissions: ['MANAGE_MESSAGES'],
});
}
async run(msg, { member, num_messages, reason }) {
let messages = await msg.channel.messages.fetch({ limit: num_messages });
messages = messages.filter((msg) => msg.author.id === member.id);
msg.channel.bulkDelete(messages);
}
};
|
data-integrations/firestore-plugins
|
src/test/java/io/cdap/plugin/gcp/firestore/source/FirestoreSourceConfigHelper.java
|
/*
* Copyright © 2020 <NAME>, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.gcp.firestore.source;
/**
* Utility class that provides handy methods to construct Firestore Source Config for testing
*/
public class FirestoreSourceConfigHelper {
public static final String TEST_REF_NAME = "TestRefName";
public static final String TEST_PROJECT = "test-project";
public static final String TEST_DATABASE = "TestDatabase";
public static final String TEST_COLLECTION = "TestCollection";
public static ConfigBuilder newConfigBuilder() {
return new ConfigBuilder();
}
public static class ConfigBuilder {
private String referenceName = TEST_REF_NAME;
private String project = TEST_PROJECT;
private String serviceFilePath = "/path/to/file";
private String database = TEST_DATABASE;
private String collection = TEST_COLLECTION;
private String includeDocumentId = "true";
private String idAlias = "__id__";
private String schema;
public ConfigBuilder setReferenceName(String referenceName) {
this.referenceName = referenceName;
return this;
}
public ConfigBuilder setProject(String project) {
this.project = project;
return this;
}
public ConfigBuilder setServiceFilePath(String serviceFilePath) {
this.serviceFilePath = serviceFilePath;
return this;
}
public ConfigBuilder setDatabase(String database) {
this.database = database;
return this;
}
public ConfigBuilder setCollection(String collection) {
this.collection = collection;
return this;
}
public ConfigBuilder setIncludeDocumentId(String includeDocumentId) {
this.includeDocumentId = includeDocumentId;
return this;
}
public ConfigBuilder setIdAlias(String idAlias) {
this.idAlias = idAlias;
return this;
}
public ConfigBuilder setSchema(String schema) {
this.schema = schema;
return this;
}
public FirestoreSourceConfig build() {
return new FirestoreSourceConfig(referenceName, project, serviceFilePath, collection,
"Basic", "", "", "", includeDocumentId, idAlias, schema);
}
}
}
|
shaojiankui/iOS10-Runtime-Headers
|
Frameworks/UIKit.framework/UICollectionViewTableLayoutInvalidationContext.h
|
<reponame>shaojiankui/iOS10-Runtime-Headers
/* Generated by RuntimeBrowser
Image: /System/Library/Frameworks/UIKit.framework/UIKit
*/
@interface UICollectionViewTableLayoutInvalidationContext : UICollectionViewLayoutInvalidationContext {
bool _invalidateTableWidth;
}
@property (nonatomic) bool invalidateTableWidth;
- (bool)invalidateTableWidth;
- (void)setInvalidateTableWidth:(bool)arg1;
@end
|
reposense/testrepo-Beta
|
src/main/java/seedu/address/ui/TagColorMap.java
|
package seedu.address.ui;
import java.util.HashMap;
//@@author nbriannl
/**
* The mapping of the tag colors to be shared across any UI components containing tags
*/
public class TagColorMap {
private static TagColorMap instance;
private static final String[] COLORS = {"Crimson", "orange", "DarkSalmon", "LightSeaGreen",
"RoyalBlue", "MediumPurple", "Teal", "Sienna", "HotPink", "MediumSeaGreen",
"DarkSlateBlue", "CadetBlue", "MidnightBlue", "LightPink", "LightSalmon", "LightSkyBlue", "PaleVioletRed "};
private static final int NUM_COLORS = COLORS.length;
private static int colorIndex = 0;
private HashMap<String, String> tagColors = new HashMap<String, String>();
private TagColorMap() {
}
public static TagColorMap getInstance() {
if (instance == null) {
instance = new TagColorMap();
}
return instance;
}
/**
* Gets a random unused color for the new tagName, or returns the corresponding color of the old tagName
* @param tagName
* @return the color of the tag
*/
public String getTagColor(String tagName) {
if (!tagColors.containsKey(tagName)) {
tagColors.put(tagName, COLORS[colorIndex]);
updateColorIndex();
}
return tagColors.get(tagName);
}
//@@author April0616
/**
* Updates the color index to pick a new color for the new tag.
*/
private static void updateColorIndex() {
if (colorIndex == NUM_COLORS - 1) {
colorIndex = 0;
} else {
colorIndex++;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.