repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
TelluIoT/ThingML
|
compilers/official-network-plugins/src/main/resources/templates/PosixWebsocketPlugin.h
|
507
|
#ifndef /*PORT_NAME*/_PosixWebsocketForward_h
#define /*PORT_NAME*/_PosixWebsocketForward_h
#include "lws_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <libwebsockets.h>
#include "/*PATH_TO_C*/" /*PORT_NAME*/_instance;
struct /*PORT_NAME*/_instance_type /*PORT_NAME*/_instance;
void /*PORT_NAME*/_set_listener_id(uint16_t id);
void /*PORT_NAME*/_setup();
void /*PORT_NAME*/_start_receiver_process() ;
void /*PORT_NAME*/_forwardMessage(char * msg, int length/*PARAM_CLIENT_ID*/);
#endif
|
apache-2.0
|
skunkiferous/Util
|
jactor2-coreSt/src/test/java/org/agilewiki/jactor2/core/impl/JActorStTestPlantScheduler.java
|
5403
|
package org.agilewiki.jactor2.core.impl;
import java.util.Timer;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.blockwithme.util.base.SystemUtils;
/**
* A scheduler for Plant, created by PlantConfiguration.
*/
public class JActorStTestPlantScheduler implements
org.agilewiki.jactor2.core.plant.PlantScheduler {
@SuppressWarnings("rawtypes")
private class MyTimerTask extends MyAbstractTimerTask {
private volatile Runnable runnable;
private volatile boolean cancelled;
private volatile boolean done;
private final boolean once;
public MyTimerTask(final Runnable runnable, final boolean once) {
this.runnable = runnable;
this.once = once;
}
/* (non-Javadoc)
* @see java.util.TimerTask#run()
*/
@Override
public void run() {
if (die) {
cancel();
runnable = null;
timer.purge();
} else {
if (once) {
done = true;
}
runnable.run();
}
}
/* (non-Javadoc)
* @see java.util.concurrent.Delayed#getDelay(java.util.concurrent.TimeUnit)
*/
@Override
public long getDelay(final TimeUnit unit) {
return unit.convert(
scheduledExecutionTime() - System.currentTimeMillis(),
TimeUnit.MILLISECONDS);
}
@Override
public boolean cancel() {
cancelled = true;
return super.cancel();
}
/* (non-Javadoc)
* @see java.util.concurrent.Future#isCancelled()
*/
@Override
public boolean isCancelled() {
return cancelled;
}
/* (non-Javadoc)
* @see java.util.concurrent.Future#cancel(boolean)
*/
@Override
public boolean cancel(final boolean mayInterruptIfRunning) {
return cancel();
}
/* (non-Javadoc)
* @see java.util.concurrent.Future#isDone()
*/
@Override
public boolean isDone() {
return done;
}
/* (non-Javadoc)
* @see java.util.concurrent.Future#get()
*/
@Override
public Object get() throws InterruptedException, ExecutionException {
if (done) {
return null;
}
throw new InterruptedException();
}
/* (non-Javadoc)
* @see java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit)
*/
@Override
public Object get(final long timeout, final TimeUnit unit)
throws InterruptedException, ExecutionException,
TimeoutException {
if (done) {
return null;
}
throw new InterruptedException();
}
}
private volatile long currentTimeMillis;
private volatile boolean die;
private final Timer timer;
/**
* Creates the default plantScheduler.
*/
public JActorStTestPlantScheduler() {
timer = SystemUtils.getTimer();
currentTimeMillis = System.currentTimeMillis();
timer.scheduleAtFixedRate(new MyTimerTask(new Runnable() {
@Override
public void run() {
currentTimeMillis = System.currentTimeMillis();
}
}, false), getHeartbeatMillis(), getHeartbeatMillis());
}
/**
* Controls how often currentTimeMillis is updated: every 500 milliseconds.
*
* @return The number of milliseconds between updates to currentTimeMillis.
*/
protected long getHeartbeatMillis() {
return 500;
}
/**
* Determines the size of the scheduledThreadPool: 2.
*
* @return Returns the number of threads in the scheduledThreadPool.
*/
protected int getSchedulerPoolSize() {
return 1;
}
@Override
public double currentTimeMillis() {
return currentTimeMillis;
}
@Override
public ScheduledFuture<?> schedule(final Runnable runnable,
final int _millisecondDelay) {
final MyTimerTask result = new MyTimerTask(runnable, true);
timer.schedule(result, _millisecondDelay);
return result;
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(final Runnable runnable,
final int _millisecondDelay) {
final MyTimerTask result = new MyTimerTask(runnable, false);
timer.scheduleAtFixedRate(result, _millisecondDelay, _millisecondDelay);
return result;
}
@Override
public void close() {
// No way to get the tasks from the Timer. :(
die = true;
}
/* (non-Javadoc)
* @see org.agilewiki.jactor2.core.plant.PlantScheduler#cancel(java.lang.Object)
*/
@Override
public void cancel(final Object task) {
if (task == null) {
throw new NullPointerException("task");
}
if (!(task instanceof ScheduledFuture)) {
throw new IllegalArgumentException("task: " + task.getClass());
}
((ScheduledFuture<?>) task).cancel(false);
}
}
|
apache-2.0
|
cpuguy83/cli
|
internal/licenseutils/client_test.go
|
4580
|
package licenseutils
import (
"context"
"github.com/docker/licensing"
"github.com/docker/licensing/model"
)
type (
fakeLicensingClient struct {
loginViaAuthFunc func(ctx context.Context, username, password string) (authToken string, err error)
getHubUserOrgsFunc func(ctx context.Context, authToken string) (orgs []model.Org, err error)
getHubUserByNameFunc func(ctx context.Context, username string) (user *model.User, err error)
verifyLicenseFunc func(ctx context.Context, license model.IssuedLicense) (res *model.CheckResponse, err error)
generateNewTrialSubscriptionFunc func(ctx context.Context, authToken, dockerID string) (subscriptionID string, err error)
listSubscriptionsFunc func(ctx context.Context, authToken, dockerID string) (response []*model.Subscription, err error)
listSubscriptionsDetailsFunc func(ctx context.Context, authToken, dockerID string) (response []*model.SubscriptionDetail, err error)
downloadLicenseFromHubFunc func(ctx context.Context, authToken, subscriptionID string) (license *model.IssuedLicense, err error)
parseLicenseFunc func(license []byte) (parsedLicense *model.IssuedLicense, err error)
storeLicenseFunc func(ctx context.Context, dclnt licensing.WrappedDockerClient, licenses *model.IssuedLicense, localRootDir string) error
loadLocalLicenseFunc func(ctx context.Context, dclnt licensing.WrappedDockerClient) (*model.Subscription, error)
summarizeLicenseFunc func(*model.CheckResponse, string) *model.Subscription
}
)
func (c *fakeLicensingClient) LoginViaAuth(ctx context.Context, username, password string) (authToken string, err error) {
if c.loginViaAuthFunc != nil {
return c.loginViaAuthFunc(ctx, username, password)
}
return "", nil
}
func (c *fakeLicensingClient) GetHubUserOrgs(ctx context.Context, authToken string) (orgs []model.Org, err error) {
if c.getHubUserOrgsFunc != nil {
return c.getHubUserOrgsFunc(ctx, authToken)
}
return nil, nil
}
func (c *fakeLicensingClient) GetHubUserByName(ctx context.Context, username string) (user *model.User, err error) {
if c.getHubUserByNameFunc != nil {
return c.getHubUserByNameFunc(ctx, username)
}
return nil, nil
}
func (c *fakeLicensingClient) VerifyLicense(ctx context.Context, license model.IssuedLicense) (res *model.CheckResponse, err error) {
if c.verifyLicenseFunc != nil {
return c.verifyLicenseFunc(ctx, license)
}
return nil, nil
}
func (c *fakeLicensingClient) GenerateNewTrialSubscription(ctx context.Context, authToken, dockerID string) (subscriptionID string, err error) {
if c.generateNewTrialSubscriptionFunc != nil {
return c.generateNewTrialSubscriptionFunc(ctx, authToken, dockerID)
}
return "", nil
}
func (c *fakeLicensingClient) ListSubscriptions(ctx context.Context, authToken, dockerID string) (response []*model.Subscription, err error) {
if c.listSubscriptionsFunc != nil {
return c.listSubscriptionsFunc(ctx, authToken, dockerID)
}
return nil, nil
}
func (c *fakeLicensingClient) ListSubscriptionsDetails(ctx context.Context, authToken, dockerID string) (response []*model.SubscriptionDetail, err error) {
if c.listSubscriptionsDetailsFunc != nil {
return c.listSubscriptionsDetailsFunc(ctx, authToken, dockerID)
}
return nil, nil
}
func (c *fakeLicensingClient) DownloadLicenseFromHub(ctx context.Context, authToken, subscriptionID string) (license *model.IssuedLicense, err error) {
if c.downloadLicenseFromHubFunc != nil {
return c.downloadLicenseFromHubFunc(ctx, authToken, subscriptionID)
}
return nil, nil
}
func (c *fakeLicensingClient) ParseLicense(license []byte) (parsedLicense *model.IssuedLicense, err error) {
if c.parseLicenseFunc != nil {
return c.parseLicenseFunc(license)
}
return nil, nil
}
func (c *fakeLicensingClient) StoreLicense(ctx context.Context, dclnt licensing.WrappedDockerClient, licenses *model.IssuedLicense, localRootDir string) error {
if c.storeLicenseFunc != nil {
return c.storeLicenseFunc(ctx, dclnt, licenses, localRootDir)
}
return nil
}
func (c *fakeLicensingClient) LoadLocalLicense(ctx context.Context, dclnt licensing.WrappedDockerClient) (*model.Subscription, error) {
if c.loadLocalLicenseFunc != nil {
return c.loadLocalLicenseFunc(ctx, dclnt)
}
return nil, nil
}
func (c *fakeLicensingClient) SummarizeLicense(cr *model.CheckResponse, keyid string) *model.Subscription {
if c.summarizeLicenseFunc != nil {
return c.summarizeLicenseFunc(cr, keyid)
}
return nil
}
|
apache-2.0
|
SAP/openui5
|
src/sap.ui.rta/test/sap/ui/rta/qunit/command/compVariant/CompVariantUpdate.qunit.js
|
8251
|
/* global QUnit */
sap.ui.define([
"sap/ui/core/Control",
"sap/ui/fl/write/api/SmartVariantManagementWriteAPI",
"sap/ui/fl/Layer",
"sap/ui/rta/command/CommandFactory",
"sap/ui/thirdparty/sinon-4"
], function(
Control,
SmartVariantManagementWriteAPI,
Layer,
CommandFactory,
sinon
) {
"use strict";
var sandbox = sinon.createSandbox();
QUnit.module("Given a control", {
beforeEach: function() {
this.oControl = new Control();
},
afterEach: function() {
this.oControl.destroy();
sandbox.restore();
}
}, function() {
QUnit.test("Update in the Save scenario", function(assert) {
var oUpdateCommand;
var sVariantId = "variantId";
var oContent = {foo: "bar"};
var oUpdateControlStub = sandbox.stub();
this.oControl.updateVariant = oUpdateControlStub;
var oSetModifiedStub = sandbox.stub();
this.oControl.setModified = oSetModifiedStub;
var oUpdateFlAPIStub = sandbox.stub(SmartVariantManagementWriteAPI, "updateVariant");
var oUndoVariantFlAPIStub = sandbox.stub(SmartVariantManagementWriteAPI, "revert");
return CommandFactory.getCommandFor(this.oControl, "compVariantUpdate", {
newVariantProperties: {
variantId: {
content: oContent
}
},
onlySave: true
}, {})
.then(function(oCreatedCommand) {
oUpdateCommand = oCreatedCommand;
return oUpdateCommand.execute();
}).then(function() {
assert.equal(oUpdateFlAPIStub.callCount, 1, "the FL update function was called");
var mExpectedProperties = {
id: sVariantId,
control: this.oControl,
content: oContent,
generator: "sap.ui.rta.command",
command: "compVariantUpdate",
layer: Layer.CUSTOMER
};
assert.deepEqual(oUpdateFlAPIStub.lastCall.args[0], mExpectedProperties, "the FL API was called with the correct properties");
assert.equal(oSetModifiedStub.callCount, 1, "the setModified was called..");
assert.equal(oSetModifiedStub.lastCall.args[0], false, "and set to false");
return oUpdateCommand.undo();
}.bind(this)).then(function() {
assert.equal(oUndoVariantFlAPIStub.callCount, 1, "the undo function was called");
assert.equal(oSetModifiedStub.callCount, 2, "the setModified was called again..");
assert.equal(oSetModifiedStub.lastCall.args[0], true, "and set to true");
return oUpdateCommand.execute();
}).then(function() {
assert.equal(oUpdateFlAPIStub.callCount, 2, "the FL update function was called again");
var mExpectedProperties = {
id: sVariantId,
control: this.oControl,
content: oContent,
generator: "sap.ui.rta.command",
command: "compVariantUpdate",
layer: Layer.CUSTOMER
};
assert.deepEqual(oUpdateFlAPIStub.lastCall.args[0], mExpectedProperties, "the FL API was called with the correct properties");
assert.equal(oSetModifiedStub.callCount, 3, "the setModified was called again..");
assert.equal(oSetModifiedStub.lastCall.args[0], false, "and set to false");
}.bind(this));
});
QUnit.test("Update in the Manage Views scenario", function(assert) {
var oUpdateCommand;
var oUpdateControlStub = sandbox.stub();
this.oControl.updateVariant = oUpdateControlStub;
var oRemoveControlStub = sandbox.stub();
this.oControl.removeVariant = oRemoveControlStub;
var oAddControlStub = sandbox.stub();
this.oControl.addVariant = oAddControlStub;
var oSetDefaultControlStub = sandbox.stub();
this.oControl.setDefaultVariantId = oSetDefaultControlStub;
var oSetModifiedStub = sandbox.stub();
this.oControl.setModified = oSetModifiedStub;
var oUpdateFlAPIStub = sandbox.stub(SmartVariantManagementWriteAPI, "updateVariant").callsFake(function(mPropertyBag) {
return mPropertyBag.id;
});
var oSetDefaultFlAPIStub = sandbox.stub(SmartVariantManagementWriteAPI, "setDefaultVariantId");
var oRevertDefaultFlAPIStub = sandbox.stub(SmartVariantManagementWriteAPI, "revertSetDefaultVariantId");
var oRemoveVariantFlAPIStub = sandbox.stub(SmartVariantManagementWriteAPI, "removeVariant");
var oRevertFlAPIStub = sandbox.stub(SmartVariantManagementWriteAPI, "revert").callsFake(function(mPropertyBag) {
return mPropertyBag.id;
});
function assertExecute(oControl) {
assert.equal(oUpdateFlAPIStub.callCount, 2, "the FL update function was called twice");
var mExpectedProperties1 = {
id: "variant2",
control: oControl,
generator: "sap.ui.rta.command",
command: "compVariantUpdate",
layer: Layer.CUSTOMER,
favorite: false
};
assert.deepEqual(oUpdateFlAPIStub.getCall(0).args[0], mExpectedProperties1, "the FL API was called with the correct properties 2");
var mExpectedProperties2 = {
id: "variant3",
control: oControl,
generator: "sap.ui.rta.command",
command: "compVariantUpdate",
layer: Layer.CUSTOMER,
executeOnSelection: true,
name: "newName",
oldName: "oldName",
favorite: true
};
assert.deepEqual(oUpdateFlAPIStub.getCall(1).args[0], mExpectedProperties2, "the FL API was called with the correct properties 3");
assert.equal(oSetDefaultFlAPIStub.callCount, 1, "the FL API setDefault was called");
assert.equal(oSetDefaultFlAPIStub.lastCall.args[0].defaultVariantId, "variant3", "the correct variant id was passed");
assert.equal(oRemoveVariantFlAPIStub.callCount, 1, "the FL API removeVariant was called");
assert.equal(oRemoveVariantFlAPIStub.lastCall.args[0].id, "variant1", "the correct variant id was passed");
assert.equal(oUpdateControlStub.callCount, 2, "the control API updateVariant was called twice");
assert.equal(oUpdateControlStub.getCall(0).args[0], "variant2", "with the return value of FL updateVariant");
assert.equal(oUpdateControlStub.getCall(1).args[0], "variant3", "with the return value of FL updateVariant");
assert.equal(oSetDefaultControlStub.callCount, 1, "the control API setDefault was called");
assert.equal(oSetDefaultControlStub.lastCall.args[0], "variant3", "the correct variant id was passed");
assert.equal(oRemoveControlStub.callCount, 1, "the control API removeVariant was called");
assert.equal(oRemoveControlStub.lastCall.args[0].variantId, "variant1", "the correct variant id was passed");
}
return CommandFactory.getCommandFor(this.oControl, "compVariantUpdate", {
newVariantProperties: {
variant1: {
executeOnSelection: false,
deleted: true
},
variant2: {
favorite: false
},
variant3: {
executeOnSelection: true,
name: "newName",
oldName: "oldName",
favorite: true
}
},
newDefaultVariantId: "variant3",
oldDefaultVariantId: "variant1"
}, {})
.then(function(oCreatedCommand) {
oUpdateCommand = oCreatedCommand;
return oUpdateCommand.execute();
}).then(function() {
assertExecute(this.oControl);
return oUpdateCommand.undo();
}.bind(this)).then(function() {
assert.equal(oRevertFlAPIStub.callCount, 3, "the revert function was called thrice");
assert.equal(oRevertFlAPIStub.getCall(0).args[0].id, "variant1", "the correct variant id was passed 1");
assert.equal(oRevertFlAPIStub.getCall(1).args[0].id, "variant2", "the correct variant id was passed 2");
assert.equal(oRevertFlAPIStub.getCall(2).args[0].id, "variant3", "the correct variant id was passed 3");
assert.equal(oRevertDefaultFlAPIStub.callCount, 1, "the revertSetDefaultVariantId function was called once");
assert.equal(oAddControlStub.lastCall.args[0], "variant1", "the correct variant was added");
assert.equal(oAddControlStub.callCount, 1, "the addVariant function on the control was called once");
assert.equal(oAddControlStub.lastCall.args[0], "variant1", "the correct variant was added");
assert.equal(oUpdateControlStub.callCount, 4, "the updateVariant function on the control was called twice");
assert.equal(oUpdateControlStub.getCall(2).args[0], "variant2", "the correct variant was updated 1");
assert.equal(oUpdateControlStub.getCall(3).args[0], "variant3", "the correct variant was updated 2");
sandbox.resetHistory();
return oUpdateCommand.execute();
}).then(function() {
assertExecute(this.oControl);
}.bind(this));
});
});
});
|
apache-2.0
|
cloudmesh/book
|
section/cluster/pi/pi_network_setup.md
|
21
|
# Network Setup
TBD
|
apache-2.0
|
excelly/xpy-ml
|
sdss/jake_lib/make_condensed_fits.py
|
4199
|
#!/astro/apps/pkg/python/bin/python
import pyfits
import SDSSfits
import numpy
from tools import create_fits
import os
def main(OUT_DIR = "/astro/net/scratch1/vanderplas/SDSS_GAL_RESTFRAME/",
DIR_ROOT = "/astro/net/scratch1/sdssspec/spectro/1d_26/*/1d",
LINES_FILE = "LINES_SHORT.TXT",
z_min = 0.0, #zmax is set such that SII lines will
z_max = 0.36, # fall in range of 3830 to 9200 angstroms
rebin_coeff0 = 3.583, # rebin parameters give a wavelength
rebin_coeff1 = 0.0002464, # range from 3830A to 9200A
rebin_length = 1000,
remove_sky_absorption = True,
normalize = True):
LINES = []
KEYS = ['TARGET','Z','Z_ERR','SPEC_CLN','MAG_G','MAG_R','MAG_I','N_BAD_PIX']
if LINES_FILE is not None:
for line in open(LINES_FILE):
line = line.split()
if len(line)==0:continue
W = float(line[0])
if W<3000 or W>7000:continue
LINES.append('%.2f'%W)
for info in ('flux','dflux','width','dwidth','nsigma'):
KEYS.append('%.2f_%s' % (W,info) )
for SET in os.listdir(DIR_ROOT.split('*')[0]):
if not SET.isdigit():
continue
DIR = DIR_ROOT.replace('*',SET)
if not os.path.exists(DIR):
continue
OUT_FILE = os.path.join(OUT_DIR,SET+'.dat')
print 'writing %s' % os.path.join(OUT_DIR,SET+'.dat')
col_dict = dict([(KEY,[]) for KEY in KEYS])
spec_list = []
NUMS = []
for F in os.listdir(DIR):
if not F.endswith('.fit'): continue
num = int( F.strip('.fit').split('-')[-1] )
if num in NUMS:
#print " - already measured: skipping %s" % F
continue
#open hdu file and glean necessary info
SPEC = SDSSfits.SDSSfits(os.path.join(DIR,F),LINES)
if SPEC.D['SPEC_CLN'] not in (1,2,3,4):
continue
if SPEC.z<z_min:
#print " - negative z: skipping %s" % F
continue
if SPEC.z>z_max:
#print " - z>z_max: skipping %s" % F
continue
if SPEC.numlines == 0:
#print " - no line measurements: skipping %s" % F
continue
if remove_sky_absorption:
#cover up strong oxygen absorption
SPEC.remove_O_lines()
#move to restframe, rebin, and normalize
SPEC.move_to_restframe()
try:
SPEC = SPEC.rebin(rebin_coeff0,rebin_coeff1,rebin_length)
except:
print " rebin failed. Skipping %s" % F
continue
if normalize:
try:
SPEC.normalize()
except:
print " normalize failed. Skipping %s" % F
continue
if min(SPEC.spectrum) < -4*max(SPEC.spectrum):
print " goes too far negative. Skipping %s" % F
NUMS.append(num)
spec_list.append(SPEC.spectrum.tolist())
for KEY in KEYS:
col_dict[KEY].append(SPEC.D[KEY])
del SPEC
if os.path.exists(OUT_FILE):
os.system('rm %s' % OUT_FILE)
col_dict['coeff0'] = rebin_coeff0
col_dict['coeff1'] = rebin_coeff1
create_fits(OUT_FILE,numpy.asarray( spec_list ),**col_dict)
print " - wrote %i spectra" % len(NUMS)
if __name__ == '__main__':
main(OUT_DIR = "/astro/net/scratch1/vanderplas/SDSS_GAL_RESTFRAME/",
DIR_ROOT = "/astro/net/scratch1/sdssspec/spectro/1d_26/*/1d",
#LINES_FILE = "LINES_SHORT.TXT",
LINES_FILE = None,
z_min = 0.0, #zmax is set such that SII lines will
z_max = 0.36, # fall in range of 3830 to 9200 angstroms
rebin_coeff0 = 3.583, # rebin parameters give a wavelength
rebin_coeff1 = 0.0002464, # range from 3830A to 9200A
rebin_length = 1000,
remove_sky_absorption = False,
normalize = False)
|
apache-2.0
|
krakky/market
|
coopr_standalone/bin/centos/3_set_java_home.sh
|
585
|
#set JAVA_HOME
echo "Exporting JAVA_HOME path after JAVA's JRE 1.7 was installed !"
export JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk.x86_64
sudo echo "export JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk.x86_64" >> /etc/environment
sudo echo "Saving JAVA_HOME variable so it doesn't get affected from system REBOOT !"
sudo echo ''\#\!/bin/sh'' > /etc/profile.d/jdk_home.sh
sudo echo "export JAVA_HOME=/usr/lib/jvm/jre-1.7.0-openjdk.x86_64" >> /etc/profile.d/jdk_home.sh
sudo echo ''export PATH=\$PATH:\$JAVA_HOME/bin'' >> /etc/profile.d/jdk_home.sh
sudo chmod 775 /etc/profile.d/jdk_home.sh
|
apache-2.0
|
onlysheep5200/NetnsEx
|
lib/__init__.py
|
2175
|
# -*- coding: utf-8 -*-
'''
部分通用的数据结构
container.py :
NetInterface : 描述容器的一个虚拟网卡
-name : 虚拟网卡名称
-hostVeth : 虚拟网卡对应的主机veth名称
-ip : IP地址
-mac : mac地址
-vethMac : 主机veth的mac地址
+ NetInterface::create : 创建一个虚拟网卡,返回NetInterface对象
container : 目标容器
vName : 容器端peer名字
h_vName : 主机端peer的名字
Container : 描述一个容器的数据结构,可持久化存储
-host : 容器所属的主机
-pid : 主机中容器的pid
-id : docker daemon 赋予容器的ID
-ifaces [list] : 容器的虚拟网卡列表 ,为Interface对象集合
-netns : 容器的网络命名空间,为NetworkNamespace对象实例
-image : 创建容器所用的镜像名称
-dataDirectory : 容器数据存储路径
-createTime : 创建时间
-state : 当前运行状态
-belongsTo : 所属用户
+attachToNetworkNamespace : 加入一个命名空间
netns : 要加入的命名空间对象
+detachNetworkNamespace : 离开命名空间
netns : 要离开的命名空间对象
net.py :
NetworkNamespace : 描述网络命名空间的数据结构
-uid : 唯一ID,初始化时通过uuid函数生成
-addrs [list] : 网络命名空间所属IP,可谓多个,为cidr地址
-containers : 加入网络的容器
-initHost : 初始化该命名空间时,该命名空间所属的主机
-createTime : 创建时间
-belongsTo : 所属用户
utils.py:
Host : 描述主机的数据结构
-mac : mac地址
-transportIp : 数据传输所用IP
-containers : 主机所包行的容器,为Container对象列表
-proxys : 主机上的容器创建代理代理列表
+getConcreteProxy :获取特定的容器创建代理类型
ProxyClass : 代理类型
Switch : 描述主机上安装着的虚拟交换机
-host : 所属主机
-portsToContainers : 交换机端口和容器的对应关系
-portsInfo : 每个端口的相关信息
-bridgeName : 网桥名称
exceptions.py :
ContainerCreatorTypeInvalidError : 容器创建器与容器创建代理类型不匹配
tools.py :
'''
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Setaria/Setaria parviflora/ Syn. Setaria affinis/README.md
|
180
|
# Setaria affinis Schult. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
chayoungrock/weather
|
app/src/main/java/com/example/android/sunshine/app/widget/DetailWidgetProvider.java
|
4337
|
package com.example.android.sunshine.app.widget;
import android.annotation.TargetApi;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.RemoteViews;
import com.example.android.sunshine.app.DetailActivity;
import com.example.android.sunshine.app.MainActivity;
import com.example.android.sunshine.app.R;
import com.example.android.sunshine.app.Utility;
import com.example.android.sunshine.app.sync.SunshineSyncAdapter;
/**
* Provider for a scrollable weather detail widget
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class DetailWidgetProvider extends AppWidgetProvider {
public final String LOG_TAG = DetailWidgetProvider.class.getSimpleName();
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// Perform this loop procedure for each App Widget that belongs to this provider
for (int appWidgetId : appWidgetIds) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_detail);
// Create an Intent to launch MainActivity
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.widget, pendingIntent);
String location = Utility.getCurrentAddress(context);
Log.d(LOG_TAG, "위젯에서 현재 위치는:" + location);
views.setTextViewText(R.id.widget_item_address_textview, location);
// Set up the collection
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
setRemoteAdapter(context, views);
} else {
setRemoteAdapterV11(context, views);
}
boolean useDetailActivity = context.getResources()
.getBoolean(R.bool.use_detail_activity);
Intent clickIntentTemplate = useDetailActivity
? new Intent(context, DetailActivity.class)
: new Intent(context, MainActivity.class);
PendingIntent clickPendingIntentTemplate = TaskStackBuilder.create(context)
.addNextIntentWithParentStack(clickIntentTemplate)
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
views.setPendingIntentTemplate(R.id.widget_list, clickPendingIntentTemplate);
views.setEmptyView(R.id.widget_list, R.id.widget_empty);
// Tell the AppWidgetManager to perform an update on the current app widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
@Override
public void onReceive(@NonNull Context context, @NonNull Intent intent) {
super.onReceive(context, intent);
if (SunshineSyncAdapter.ACTION_DATA_UPDATED.equals(intent.getAction())) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(
new ComponentName(context, getClass()));
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.widget_list);
}
}
/**
* Sets the remote adapter used to fill in the list items
*
* @param views RemoteViews to set the RemoteAdapter
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setRemoteAdapter(Context context, @NonNull final RemoteViews views) {
views.setRemoteAdapter(R.id.widget_list,
new Intent(context, DetailWidgetRemoteViewsService.class));
}
/**
* Sets the remote adapter used to fill in the list items
*
* @param views RemoteViews to set the RemoteAdapter
*/
@SuppressWarnings("deprecation")
private void setRemoteAdapterV11(Context context, @NonNull final RemoteViews views) {
views.setRemoteAdapter(0, R.id.widget_list,
new Intent(context, DetailWidgetRemoteViewsService.class));
}
}
|
apache-2.0
|
nilbody/sparkling-water
|
CHANGELOG.md
|
4219
|
ChangeLog
=========
## In current master
- Attach metadata derived from H2OFrame to Spark DataFrame
- Improved logging subsystem
- Expose new REST end-points
- to interpret Scala code
- to perform transformation between Spark DataFrame and H2O Frame
- Fix all scripts and create automatic tests for them
- [SW-39] pySparkling: use Sparkling Water from Python
- Model serialization support
- Upgrade of H2O dependency to 3.6.0.8
- Fixes
- [PUBDEV-282](https://0xdata.atlassian.net/browse/PUBDEV-282) Create windows batch scripts for starting sparkling-shell and running examples
- [SW-5, SW-17, SW-25](https://0xdata.atlassian.net/browse/SW-25) Remove categorical handling during asH2OFrame() transformation
- [SW-20](https://0xdata.atlassian.net/browse/SW-20) H2OFrame provides nicer API accepting parser setup
- [SW-32](https://0xdata.atlassian.net/browse/SW-32) Update documentation and remove top-level images folder
- [SW-33](https://0xdata.atlassian.net/browse/SW-33) Remove usage of deprecated VecUtils class
- [SW-38](https://0xdata.atlassian.net/browse/SW-38) Introduces Sparkling Water parameter to setup location of H2O logs
- [SW-39](https://0xdata.atlassian.net/browse/SW-39) PySparkling: Support of Sparkling Water from PySpark
- [SW-40](https://0xdata.atlassian.net/browse/SW-40) PySparkling: as\_h2o\_frame method accepts name of target H2O Frame
- [SW-41](https://0xdata.atlassian.net/browse/SW-41) H2OContext#asH2OFrame now
accepts name for resulting H2OFrame.
- fix idea setup
- fixes in coding typos
- cloud name was ignored
- wrong property name
- fix a bug in launch scripts overriding default value of `spark.driver.extraJavaOptions`
##v1.4.0 (2015-07-06)
- Support of primitives type in transformation from RDD to H2OFrame
- Support of Spark 1.4
- New applications
- Craigslist job predictions
- Streaming craigslist demo
- use H2O version 3.0.0.26 (algorithms weights, offsets, fixes)
- API improvements
- follow Spark way to provide implicit conversions
##v1.3.0 (2015-05-25)
- Major release of Sparkling Water
- Depends on:
- Spark 1.3.1
- H2O 3.0 Shannon release
- It contains major renaming of API:
- H2O's DataFrame was renamed to H2OFrame
- Spark's SchemaRDD was renamed to DataFrame
##v1.2.0 (2015-05-18)
- Major release of Sparkling Water
- Depends on:
- Spark 1.2.0
- H2O 3.0 Shannon release
##v0.2.14 (2015-05-14)
- Upgrade h2o dependency to build 1205 including fixes in algos, infrastructure,
and improvements in UI
- Examples changed to support modified h2o API
- Updated documentation
- list of demos and applications
- list of scripts for Sparkling Shell
- list of meetups with links to code and instructions
- Fix a limit on number of columns in SchemaRDD (thanks @nfergu)
##v0.2.13 (2015-05-01)
- Upgrade h2o dependency to build 1165
- Introduce type alias DataFrame pointing to `water.fvec.H2OFrame`
- Change naming of implicit operations `toDataFrame` to `toH2OFrame`
- Chicago crime shell script
##v0.2.12 (2015-04-21)
- Upgraded H2O dev to 1109 build.
- Applications
- Chicago crime application
- Ham or Spam application
- MLConf 2015 demo
- More unit testing for transformation between RDD and DataFrame
- Fix in handling string columns.
- Removed used of ExistingRdd which was deprecated in Spark 1.2.0
- Added joda-convert library into resulting assembly
- Parquet import test.
- Prototype of Sparkling Water ML pipelines
- Added quiet mode for h2o client.
- Devel Documentation
- Fixes
- [PUBDEV-771] Fix handling of UUIDs.
- [PUBDEV-767] Missing LongType handling.
- [PUBDEV-766] Fix wrong test.
- [PUBDEV-625] MLConf demo is now integration test.
- [PUBDEV-457] Array of strings is represented as set of String columns in H2O.
- [PUBDEV-457] Test scenario mentioned in the test.
- [PUBDEV-457] Support for hierarchical schemas including vectors and arrays
- [PUBDEV-483] Introduce option to setup client web port.
- [PUBDEV-357] Change of clouding strategy - now cloud members report themselves to a driver
|
apache-2.0
|
gravitee-io/graviteeio-access-management
|
gravitee-am-ui/protractor.conf.js
|
1386
|
/*
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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.
*/
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const { SpecReporter } = require('jasmine-spec-reporter');
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./e2e/**/*.e2e-spec.ts'
],
capabilities: {
'browserName': 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
beforeLaunch: function() {
require('ts-node').register({
project: 'e2e/tsconfig.e2e.json'
});
},
onPrepare() {
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Cineraria/Cineraria lacinata/README.md
|
172
|
# Cineraria lacinata Sw. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
taohaox/MyWeather
|
src/com/myweather/app/activity/BottomLayout.java
|
370
|
package com.myweather.app.activity;
import com.myweather.app.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
public class BottomLayout extends LinearLayout{
public BottomLayout(Context context) {
super(context);
LayoutInflater.from(context).inflate(R.layout.bottom_menu, this);
}
}
|
apache-2.0
|
moghaddam/cas
|
cas-server-support-jpa-ticket-registry/src/test/java/org/jasig/cas/ticket/registry/support/JpaLockingStrategyTests.java
|
10675
|
package org.jasig.cas.ticket.registry.support;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.jpa.SharedEntityManagerCreator;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.junit.Assert.*;
/**
* Unit test for {@link JpaLockingStrategy}.
*
* @author Marvin S. Addison
* @since 3.0.0
*/
public class JpaLockingStrategyTests {
/** Number of clients contending for lock in concurrent test. */
private static final int CONCURRENT_SIZE = 13;
/** Logger instance. */
private final Logger logger = LoggerFactory.getLogger(getClass());
private PlatformTransactionManager txManager;
private EntityManagerFactory factory;
private DataSource dataSource;
@Before
public void setup() {
final ClassPathXmlApplicationContext ctx = new
ClassPathXmlApplicationContext("classpath:/jpaSpringContext.xml");
this.factory = ctx.getBean("ticketEntityManagerFactory", EntityManagerFactory.class);
this.txManager = ctx.getBean("ticketTransactionManager", PlatformTransactionManager.class);
this.dataSource = ctx.getBean("dataSourceTicket", DataSource.class);
}
/**
* Test basic acquire/release semantics.
*
* @throws Exception On errors.
*/
@Test
public void verifyAcquireAndRelease() throws Exception {
final String appId = "basic";
final String uniqueId = appId + "-1";
final LockingStrategy lock = newLockTxProxy(appId, uniqueId, JpaLockingStrategy.DEFAULT_LOCK_TIMEOUT);
try {
assertTrue(lock.acquire());
assertEquals(uniqueId, getOwner(appId));
lock.release();
assertNull(getOwner(appId));
} catch (final Exception e) {
logger.debug("testAcquireAndRelease produced an error", e);
fail("testAcquireAndRelease failed");
}
}
/**
* Test lock expiration.
*
* @throws Exception On errors.
*/
@Test
public void verifyLockExpiration() throws Exception {
final String appId = "expquick";
final String uniqueId = appId + "-1";
final LockingStrategy lock = newLockTxProxy(appId, uniqueId, 1);
try {
assertTrue(lock.acquire());
assertEquals(uniqueId, getOwner(appId));
assertFalse(lock.acquire());
Thread.sleep(1500);
assertTrue(lock.acquire());
assertEquals(uniqueId, getOwner(appId));
lock.release();
assertNull(getOwner(appId));
} catch (final Exception e) {
logger.debug("testLockExpiration produced an error", e);
fail("testLockExpiration failed");
}
}
/**
* Verify non-reentrant behavior.
*/
@Test
public void verifyNonReentrantBehavior() {
final String appId = "reentrant";
final String uniqueId = appId + "-1";
final LockingStrategy lock = newLockTxProxy(appId, uniqueId, JpaLockingStrategy.DEFAULT_LOCK_TIMEOUT);
try {
assertTrue(lock.acquire());
assertEquals(uniqueId, getOwner(appId));
assertFalse(lock.acquire());
lock.release();
assertNull(getOwner(appId));
} catch (final Exception e) {
logger.debug("testNonReentrantBehavior produced an error", e);
fail("testNonReentrantBehavior failed.");
}
}
/**
* Test concurrent acquire/release semantics.
*/
@Test
public void verifyConcurrentAcquireAndRelease() throws Exception {
final ExecutorService executor = Executors.newFixedThreadPool(CONCURRENT_SIZE);
try {
testConcurrency(executor, getConcurrentLocks("concurrent-new"));
} catch (final Exception e) {
logger.debug("testConcurrentAcquireAndRelease produced an error", e);
fail("testConcurrentAcquireAndRelease failed.");
} finally {
executor.shutdownNow();
}
}
/**
* Test concurrent acquire/release semantics for existing lock.
*/
@Test
public void verifyConcurrentAcquireAndReleaseOnExistingLock() throws Exception {
final LockingStrategy[] locks = getConcurrentLocks("concurrent-exists");
locks[0].acquire();
locks[0].release();
final ExecutorService executor = Executors.newFixedThreadPool(CONCURRENT_SIZE);
try {
testConcurrency(executor, locks);
} catch (final Exception e) {
logger.debug("testConcurrentAcquireAndReleaseOnExistingLock produced an error", e);
fail("testConcurrentAcquireAndReleaseOnExistingLock failed.");
} finally {
executor.shutdownNow();
}
}
private LockingStrategy[] getConcurrentLocks(final String appId) {
final LockingStrategy[] locks = new LockingStrategy[CONCURRENT_SIZE];
for (int i = 1; i <= locks.length; i++) {
locks[i - 1] = newLockTxProxy(appId, appId + '-' + i, JpaLockingStrategy.DEFAULT_LOCK_TIMEOUT);
}
return locks;
}
private LockingStrategy newLockTxProxy(final String appId, final String uniqueId, final int ttl) {
final JpaLockingStrategy lock = new JpaLockingStrategy();
lock.entityManager = SharedEntityManagerCreator.createSharedEntityManager(factory);
lock.setApplicationId(appId);
lock.setUniqueId(uniqueId);
lock.setLockTimeout(ttl);
return (LockingStrategy) Proxy.newProxyInstance(
JpaLockingStrategy.class.getClassLoader(),
new Class[] {LockingStrategy.class},
new TransactionalLockInvocationHandler(lock, this.txManager));
}
private String getOwner(final String appId) {
final JdbcTemplate simpleJdbcTemplate = new JdbcTemplate(dataSource);
final List<Map<String, Object>> results = simpleJdbcTemplate.queryForList(
"SELECT unique_id FROM locks WHERE application_id=?", appId);
if (results.isEmpty()) {
return null;
}
return (String) results.get(0).get("unique_id");
}
private void testConcurrency(final ExecutorService executor, final LockingStrategy[] locks) throws Exception {
final List<Locker> lockers = new ArrayList<>(locks.length);
for (int i = 0; i < locks.length; i++) {
lockers.add(new Locker(locks[i]));
}
int lockCount = 0;
for (final Future<Boolean> result : executor.invokeAll(lockers)) {
if (result.get()) {
lockCount++;
}
}
assertTrue("Lock count should be <= 1 but was " + lockCount, lockCount <= 1);
final List<Releaser> releasers = new ArrayList<>(locks.length);
for (int i = 0; i < locks.length; i++) {
releasers.add(new Releaser(locks[i]));
}
int releaseCount = 0;
for (final Future<Boolean> result : executor.invokeAll(lockers)) {
if (result.get()) {
releaseCount++;
}
}
assertTrue("Release count should be <= 1 but was " + releaseCount, releaseCount <= 1);
}
private static class TransactionalLockInvocationHandler implements InvocationHandler {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final JpaLockingStrategy jpaLock;
private final PlatformTransactionManager txManager;
TransactionalLockInvocationHandler(final JpaLockingStrategy lock,
final PlatformTransactionManager txManager) {
jpaLock = lock;
this.txManager = txManager;
}
public JpaLockingStrategy getLock() {
return this.jpaLock;
}
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
return new TransactionTemplate(txManager).execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(final TransactionStatus status) {
try {
final Object result = method.invoke(jpaLock, args);
jpaLock.entityManager.flush();
logger.debug("Performed {} on {}", method.getName(), jpaLock);
return result;
// Force result of transaction to database
} catch (final Exception e) {
throw new RuntimeException("Transactional method invocation failed.", e);
}
}
});
}
}
private static class Locker implements Callable<Boolean> {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final LockingStrategy lock;
Locker(final LockingStrategy l) {
lock = l;
}
@Override
public Boolean call() throws Exception {
try {
return lock.acquire();
} catch (final Exception e) {
logger.debug("{} failed to acquire lock", lock, e);
return false;
}
}
}
private static class Releaser implements Callable<Boolean> {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final LockingStrategy lock;
Releaser(final LockingStrategy l) {
lock = l;
}
@Override
public Boolean call() throws Exception {
try {
lock.release();
return true;
} catch (final Exception e) {
logger.debug("{} failed to release lock", lock, e);
return false;
}
}
}
}
|
apache-2.0
|
weathersource/grib_api
|
src/grib_accessor_class_codetable.c
|
22574
|
/*
* Copyright 2005-2017 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*
* In applying this licence, ECMWF does not waive the privileges and immunities granted to it by
* virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
*/
/*****************************************
* Enrico Fucile
****************************************/
#include "grib_api_internal.h"
#include <ctype.h>
/*
* strcasecmp is not in the C standard. However, it's defined by
* 4.4BSD, POSIX.1-2001. So we use our own
*/
int grib_strcasecmp(const char *s1, const char *s2)
{
const unsigned char *us1 = (const unsigned char *)s1,
*us2 = (const unsigned char *)s2;
while (tolower(*us1) == tolower(*us2++))
if (*us1++ == '\0')
return (0);
return (tolower(*us1) - tolower(*--us2));
}
/*
This is used by make_class.pl
START_CLASS_DEF
CLASS = accessor
SUPER = grib_accessor_class_unsigned
IMPLEMENTS = init;dump;unpack_string;pack_expression;unpack_long
IMPLEMENTS = value_count;pack_string; destroy; get_native_type;
MEMBERS = const char* tablename
MEMBERS = const char* masterDir
MEMBERS = const char* localDir
MEMBERS = grib_codetable* table
END_CLASS_DEF
*/
/* START_CLASS_IMP */
/*
Don't edit anything between START_CLASS_IMP and END_CLASS_IMP
Instead edit values between START_CLASS_DEF and END_CLASS_DEF
or edit "accessor.class" and rerun ./make_class.pl
*/
static int get_native_type(grib_accessor*);
static int pack_string(grib_accessor*, const char*, size_t *len);
static int pack_expression(grib_accessor*, grib_expression*);
static int unpack_long(grib_accessor*, long* val,size_t *len);
static int unpack_string (grib_accessor*, char*, size_t *len);
static int value_count(grib_accessor*,long*);
static void destroy(grib_context*,grib_accessor*);
static void dump(grib_accessor*, grib_dumper*);
static void init(grib_accessor*,const long, grib_arguments* );
static void init_class(grib_accessor_class*);
typedef struct grib_accessor_codetable {
grib_accessor att;
/* Members defined in gen */
/* Members defined in long */
/* Members defined in unsigned */
long nbytes;
grib_arguments* arg;
/* Members defined in codetable */
const char* tablename;
const char* masterDir;
const char* localDir;
grib_codetable* table;
} grib_accessor_codetable;
extern grib_accessor_class* grib_accessor_class_unsigned;
static grib_accessor_class _grib_accessor_class_codetable = {
&grib_accessor_class_unsigned, /* super */
"codetable", /* name */
sizeof(grib_accessor_codetable), /* size */
0, /* inited */
&init_class, /* init_class */
&init, /* init */
0, /* post_init */
&destroy, /* free mem */
&dump, /* describes himself */
0, /* get length of section */
0, /* get length of string */
&value_count, /* get number of values */
0, /* get number of bytes */
0, /* get offset to bytes */
&get_native_type, /* get native type */
0, /* get sub_section */
0, /* grib_pack procedures long */
0, /* grib_pack procedures long */
0, /* grib_pack procedures long */
&unpack_long, /* grib_unpack procedures long */
0, /* grib_pack procedures double */
0, /* grib_unpack procedures double */
&pack_string, /* grib_pack procedures string */
&unpack_string, /* grib_unpack procedures string */
0, /* grib_pack procedures bytes */
0, /* grib_unpack procedures bytes */
&pack_expression, /* pack_expression */
0, /* notify_change */
0, /* update_size */
0, /* preferred_size */
0, /* resize */
0, /* nearest_smaller_value */
0, /* next accessor */
0, /* compare vs. another accessor */
0, /* unpack only ith value */
0, /* unpack a subarray */
0, /* clear */
};
grib_accessor_class* grib_accessor_class_codetable = &_grib_accessor_class_codetable;
static void init_class(grib_accessor_class* c)
{
c->next_offset = (*(c->super))->next_offset;
c->string_length = (*(c->super))->string_length;
c->byte_count = (*(c->super))->byte_count;
c->byte_offset = (*(c->super))->byte_offset;
c->sub_section = (*(c->super))->sub_section;
c->pack_missing = (*(c->super))->pack_missing;
c->is_missing = (*(c->super))->is_missing;
c->pack_long = (*(c->super))->pack_long;
c->pack_double = (*(c->super))->pack_double;
c->unpack_double = (*(c->super))->unpack_double;
c->pack_bytes = (*(c->super))->pack_bytes;
c->unpack_bytes = (*(c->super))->unpack_bytes;
c->notify_change = (*(c->super))->notify_change;
c->update_size = (*(c->super))->update_size;
c->preferred_size = (*(c->super))->preferred_size;
c->resize = (*(c->super))->resize;
c->nearest_smaller_value = (*(c->super))->nearest_smaller_value;
c->next = (*(c->super))->next;
c->compare = (*(c->super))->compare;
c->unpack_double_element = (*(c->super))->unpack_double_element;
c->unpack_double_subarray = (*(c->super))->unpack_double_subarray;
c->clear = (*(c->super))->clear;
}
/* END_CLASS_IMP */
static int grib_load_codetable(grib_context* c,const char* filename,
const char* recomposed_name,size_t size,grib_codetable* t);
static void init(grib_accessor* a, const long len, grib_arguments* params) {
int n=0;
grib_accessor_codetable* self = (grib_accessor_codetable*)a;
grib_action* act=(grib_action*)(a->creator);
self->tablename = grib_arguments_get_string(a->parent->h,params,n++);
self->masterDir = grib_arguments_get_name(a->parent->h,params,n++);
self->localDir = grib_arguments_get_name(a->parent->h,params,n++);
/*if (a->flags & GRIB_ACCESSOR_FLAG_STRING_TYPE)
printf("-------- %s type string (%ld)\n",a->name,a->flags);*/
if (a->flags & GRIB_ACCESSOR_FLAG_TRANSIENT) {
a->length = 0;
if (!a->vvalue)
a->vvalue = (grib_virtual_value*)grib_context_malloc_clear(a->parent->h->context,sizeof(grib_virtual_value));
a->vvalue->type=grib_accessor_get_native_type(a);
a->vvalue->length=len;
if (act->default_value!=NULL) {
const char* p = 0;
size_t len = 1;
long l;
int ret=0;
double d;
char tmp[1024];
grib_expression* expression=grib_arguments_get_expression(a->parent->h,act->default_value,0);
int type = grib_expression_native_type(a->parent->h,expression);
switch(type) {
case GRIB_TYPE_DOUBLE:
grib_expression_evaluate_double(a->parent->h,expression,&d);
grib_pack_double(a,&d,&len);
break;
case GRIB_TYPE_LONG:
grib_expression_evaluate_long(a->parent->h,expression,&l);
grib_pack_long(a,&l,&len);
break;
default:
len = sizeof(tmp);
p = grib_expression_evaluate_string(a->parent->h,expression,tmp,&len,&ret);
if (ret != GRIB_SUCCESS) {
grib_context_log(a->parent->h->context,GRIB_LOG_FATAL,
"unable to evaluate %s as string",a->name);
}
len = strlen(p)+1;
pack_string(a,p,&len);
break;
}
}
} else
a->length = len;
}
static int str_eq(const char* a, const char* b)
{
if ( a && b && (strcmp(a,b)==0) )
return 1;
return 0;
}
#ifdef DEBUG
static void dump_codetable(grib_codetable* atable)
{
grib_codetable* next = NULL;
int count = 0;
next=atable;
while(next) {
printf("[%.2d] CodeTable Dump: f0=%s f1=%s\n", count, next->filename[0], next->filename[1]);
count++;
next = next->next;
}
}
#endif
static grib_codetable* load_table(grib_accessor_codetable* self)
{
size_t size = 0;
grib_handle* h = ((grib_accessor*)self)->parent->h;
grib_context* c = h->context;
grib_codetable* t = NULL;
grib_codetable* next=NULL ;
grib_accessor* a=(grib_accessor*)self;
char *filename=0;
char name[1024]={0,};
char recomposed[1024]={0,};
char localRecomposed[1024]={0,};
char *localFilename=0;
char localName[1024]={0,};
char masterDir[1024]={0,};
char localDir[1024]={0,};
size_t len=1024;
if (self->masterDir != NULL)
grib_get_string(h,self->masterDir,masterDir,&len);
len=1024;
if (self->localDir != NULL)
grib_get_string(h,self->localDir,localDir,&len);
if (*masterDir!=0) {
sprintf(name,"%s/%s",masterDir,self->tablename);
grib_recompose_name(h, NULL,name, recomposed,0);
filename=grib_context_full_defs_path(c,recomposed);
} else {
grib_recompose_name(h, NULL,self->tablename, recomposed,0);
filename=grib_context_full_defs_path(c,recomposed);
}
if (*localDir!=0) {
sprintf(localName,"%s/%s",localDir,self->tablename);
grib_recompose_name(h, NULL,localName, localRecomposed,0);
localFilename=grib_context_full_defs_path(c,localRecomposed);
}
/*printf("%s: Looking in cache: f=%s lf=%s\n", self->att.name, filename, localFilename);*/
next=c->codetable;
while(next) {
if ((filename && next->filename[0] && strcmp(filename,next->filename[0]) == 0) &&
((localFilename==0 && next->filename[1]==NULL) ||
((localFilename!=0 && next->filename[1]!=NULL)
&& strcmp(localFilename,next->filename[1]) ==0)) )
{
return next;
}
/* Special case: see GRIB-735 */
if (filename==NULL && localFilename!=NULL)
{
if ( str_eq(localFilename, next->filename[0]) ||
str_eq(localFilename, next->filename[1]) )
{
return next;
}
}
next = next->next;
}
if (a->flags & GRIB_ACCESSOR_FLAG_TRANSIENT) {
Assert(a->vvalue!=NULL);
size=a->vvalue->length*8;
} else {
size = grib_byte_count((grib_accessor*)self) * 8;
}
size = grib_power(size,2);
t = (grib_codetable*)grib_context_malloc_clear_persistent(c,sizeof(grib_codetable) +
(size-1)*sizeof(code_table_entry));
if (filename!=0)
grib_load_codetable(c,filename,recomposed,size,t);
if (localFilename!=0)
grib_load_codetable(c,localFilename,localRecomposed,size,t);
/*dump_codetable(c->codetable);*/
if (t->filename[0]==NULL && t->filename[1]==NULL) {
grib_context_free_persistent(c,t);
return NULL;
}
return t;
}
static int grib_load_codetable(grib_context* c,const char* filename,
const char* recomposed_name,size_t size,grib_codetable* t)
{
char line[1024];
FILE *f = NULL;
int lineNumber = 0;
grib_context_log(c,GRIB_LOG_DEBUG,"Loading code table from %s",filename);
f=fopen(filename, "r");
if (!f) return GRIB_IO_PROBLEM;
Assert(t!=NULL);
if (t->filename[0] == NULL ){
t->filename[0] = grib_context_strdup_persistent(c,filename);
t->recomposed_name[0] = grib_context_strdup_persistent(c,recomposed_name);
t->next = c->codetable;
t->size = size;
c->codetable = t;
} else {
t->filename[1] = grib_context_strdup_persistent(c,filename);
t->recomposed_name[1] = grib_context_strdup_persistent(c,recomposed_name);
}
while(fgets(line,sizeof(line)-1,f))
{
char* p = line;
int code = 0;
char abbreviation[1024] = {0,};
char title[1024]={0,};
char* q = abbreviation;
char* r = title;
char* units=0;
char unknown[]="unknown";
++lineNumber;
line[strlen(line)-1] = 0;
while(*p != '\0' && isspace(*p)) p++;
if(*p == '#')
continue;
while(*p != '\0' && isspace(*p)) p++;
if( *p =='\0' ) continue;
if (!isdigit(*p))
{
grib_context_log(c,GRIB_LOG_ERROR, "Invalid entry in file %s: line %d", filename, lineNumber);
continue; /* skip this line */
}
Assert(isdigit(*p));
while(*p != '\0')
{
if(isspace(*p)) break;
code *= 10;
code += *p - '0';
p++;
}
if(code <0 || code >= size)
{
grib_context_log(c,GRIB_LOG_WARNING,"code_table_entry: invalid code in %s: %d (table size=%d)",filename,code,size);
continue;
}
while(*p != '\0' && isspace(*p)) p++;
while(*p != '\0')
{
if(isspace(*p)) break;
*q++ = *p++;
}
*q = 0;
while(*p != '\0' && isspace(*p)) p++;
while(*p != '\0')
{
if(*p == '(' ) break;
*r++ = *p++;
}
*r = 0;
while(*p != '\0' && isspace(*p)) p++;
if (*p != '\0') {
units=++p;
while(*p != '\0' && *p != ')' ) p++;
*p='\0';
} else {
units=unknown;
}
Assert(*abbreviation);
Assert(*title);
if(t->entries[code].abbreviation != NULL)
{
grib_context_log(c,GRIB_LOG_WARNING,"code_table_entry: duplicate code in %s: %d (table size=%d)",filename,code,size);
continue;
}
Assert(t->entries[code].abbreviation == NULL);
Assert(t->entries[code].title == NULL);
t->entries[code].abbreviation = grib_context_strdup_persistent(c,abbreviation);
t->entries[code].title = grib_context_strdup_persistent(c,title);
t->entries[code].units = grib_context_strdup_persistent(c,units);
}
fclose(f);
return 0;
}
void grib_codetable_delete(grib_context* c) {
grib_codetable* t = c->codetable;
while(t)
{
grib_codetable* s = t->next;
int i;
for(i = 0; i < t->size; i++)
{
grib_context_free_persistent(c,t->entries[i].abbreviation);
grib_context_free_persistent(c,t->entries[i].title);
}
grib_context_free_persistent(c,t->filename[0]);
if(t->filename[1])
grib_context_free_persistent(c,t->filename[1]);
grib_context_free_persistent(c,t->recomposed_name[0]);
if (t->recomposed_name[1])
grib_context_free_persistent(c,t->recomposed_name[1]);
grib_context_free_persistent(c,t);
t = s;
}
}
static void dump(grib_accessor* a, grib_dumper* dumper) {
grib_accessor_codetable* self = (grib_accessor_codetable*)a;
char comment[2048];
grib_codetable* table;
size_t llen = 1;
long value;
if(!self->table) self->table = load_table(self);
table=self->table;
grib_unpack_long(a, &value,&llen);
if(value == GRIB_MISSING_LONG)
{
if(a->length < 4)
{
value = (1L << a->length) - 1;
}
}
if(table && value >= 0 && value < table->size)
{
if(table->entries[value].abbreviation)
{
int b = atol(table->entries[value].abbreviation);
if(b == value)
strcpy(comment,table->entries[value].title);
else
sprintf(comment,"%s", table->entries[value].title);
if (table->entries[value].units!=NULL && strcmp(table->entries[value].units,"unknown")) {
strcat(comment," (");
strcat(comment,table->entries[value].units);
strcat(comment,") ");
}
}
else
{
strcpy(comment,"Unknown code table entry");
}
}
else
{
strcpy(comment,"Unknown code table entry");
}
strcat(comment," (");
if (table) {
strcat(comment,table->recomposed_name[0]);
if (table->recomposed_name[1]!=NULL) {
strcat(comment," , ");
strcat(comment,table->recomposed_name[1]);
}
}
strcat(comment,") ");
grib_dump_long(dumper,a,comment);
}
static int unpack_string (grib_accessor* a, char* buffer, size_t *len)
{
grib_accessor_codetable* self = (grib_accessor_codetable*)a;
grib_codetable* table = NULL;
size_t size = 1;
long value;
int err = GRIB_SUCCESS;
char tmp[1024];
size_t l = 0;
if( (err = grib_unpack_long(a,&value,&size)) != GRIB_SUCCESS)
return err;
if(!self->table) self->table = load_table(self);
table=self->table;
if(table && (value >= 0) && (value < table->size) && table->entries[value].abbreviation)
{
strcpy(tmp,table->entries[value].abbreviation);
}
else
{
#if 1
sprintf(tmp,"%d",(int)value);
#else
return GRIB_DECODING_ERROR;
#endif
}
l = strlen(tmp) + 1;
if(*len < l)
{
*len = l;
return GRIB_BUFFER_TOO_SMALL;
}
strcpy(buffer,tmp);
*len = l;
return GRIB_SUCCESS;
}
static int value_count(grib_accessor* a,long* count)
{
*count=1;
return 0;
}
static int pack_string(grib_accessor* a, const char* buffer, size_t *len)
{
grib_accessor_codetable* self = (grib_accessor_codetable*)a;
grib_codetable* table ;
long i;
size_t size = 1;
typedef int (*cmpproc)(const char*, const char*);
#ifndef GRIB_ON_WINDOWS
cmpproc cmp = (a->flags & GRIB_ACCESSOR_FLAG_LOWERCASE) ? grib_strcasecmp : strcmp;
#else
/* Microsoft Windows Visual Studio support */
cmpproc cmp = (a->flags & GRIB_ACCESSOR_FLAG_LOWERCASE) ? stricmp : strcmp;
#endif
if(!self->table) self->table = load_table(self);
table=self->table;
if(!table)
return GRIB_ENCODING_ERROR;
if (a->set) {
int err=grib_set_string(a->parent->h,a->set,buffer,len);
if (err!=0) return err;
}
for(i = 0 ; i < table->size; i++)
if(table->entries[i].abbreviation)
if(cmp(table->entries[i].abbreviation,buffer) == 0)
return grib_pack_long(a,&i,&size);
if (a->flags & GRIB_ACCESSOR_FLAG_NO_FAIL) {
grib_action* act=(grib_action*)(a->creator);
if (act->default_value!=NULL) {
const char* p = 0;
size_t len = 1;
long l;
int ret=0;
double d;
char tmp[1024];
grib_expression* expression=grib_arguments_get_expression(a->parent->h,act->default_value,0);
int type = grib_expression_native_type(a->parent->h,expression);
switch(type) {
case GRIB_TYPE_DOUBLE:
grib_expression_evaluate_double(a->parent->h,expression,&d);
grib_pack_double(a,&d,&len);
break;
case GRIB_TYPE_LONG:
grib_expression_evaluate_long(a->parent->h,expression,&l);
grib_pack_long(a,&l,&len);
break;
default:
len = sizeof(tmp);
p = grib_expression_evaluate_string(a->parent->h,expression,tmp,&len,&ret);
if (ret != GRIB_SUCCESS) {
grib_context_log(a->parent->h->context,GRIB_LOG_FATAL,
"unable to evaluate %s as string",a->name);
return ret;
}
len = strlen(p)+1;
pack_string(a,p,&len);
break;
}
return GRIB_SUCCESS;
}
}
return GRIB_ENCODING_ERROR;
}
static int pack_expression(grib_accessor* a, grib_expression *e){
const char* cval;
int ret=0;
long lval=0;
size_t len = 1;
char tmp[1024];
if (strcmp(e->cclass->name,"long")==0) {
ret=grib_expression_evaluate_long(a->parent->h,e,&lval);
ret = grib_pack_long(a,&lval,&len);
} else {
len = sizeof(tmp);
cval = grib_expression_evaluate_string(a->parent->h,e,tmp,&len,&ret);
if (ret!=GRIB_SUCCESS) {
grib_context_log(a->parent->h->context,GRIB_LOG_ERROR,"grib_accessor_codetable.pack_expression: unable to evaluate string %s to be set in %s\n",grib_expression_get_name(e),a->name);
return ret;
}
len = strlen(cval) + 1;
ret = grib_pack_string(a,cval,&len);
}
return ret;
}
static void destroy(grib_context* context,grib_accessor* a)
{
if (a->vvalue != NULL) {
grib_context_free(context, a->vvalue);
a->vvalue=NULL;
}
}
static int get_native_type(grib_accessor* a){
int type=GRIB_TYPE_LONG;
/*printf("---------- %s flags=%ld GRIB_ACCESSOR_FLAG_STRING_TYPE=%d\n",
a->name,a->flags,GRIB_ACCESSOR_FLAG_STRING_TYPE);*/
if (a->flags & GRIB_ACCESSOR_FLAG_STRING_TYPE)
type=GRIB_TYPE_STRING;
return type;
}
static int unpack_long (grib_accessor* a, long* val, size_t *len)
{
grib_accessor_codetable* self = (grib_accessor_codetable*)a;
long rlen = 0;
int err=0;
unsigned long i = 0;
long pos = a->offset*8;
err=grib_value_count(a,&rlen);
if (err) return err;
if(!self->table) self->table = load_table(self);
if(*len < rlen)
{
grib_context_log(a->parent->h->context, GRIB_LOG_ERROR, " wrong size (%ld) for %s it contains %d values ",*len, a->name , rlen);
*len = 0;
return GRIB_ARRAY_TOO_SMALL;
}
if (a->flags & GRIB_ACCESSOR_FLAG_TRANSIENT) {
*val=a->vvalue->lval;
*len=1;
return GRIB_SUCCESS;
}
for(i=0; i< rlen;i++){
val[i] = (long)grib_decode_unsigned_long(a->parent->h->buffer->data , &pos, self->nbytes*8);
}
*len = rlen;
return GRIB_SUCCESS;
}
|
apache-2.0
|
beamly/beamly.core.lang
|
src/test/scala/beamly/core/lang/MapWTest.scala
|
1051
|
/**
Copyright (C) 2011-2014 beamly Ltd. http://beamly.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
package beamly.core.lang
import org.specs2.mutable.Specification
class MapWTest extends Specification {
"MapW" should {
"merge the values of 2 maps together" in {
val left = Map(1 -> 100, 2 -> 222)
val right = Map(3 -> 33, 1 -> 99)
left.mergeValues(right) { case (leftValues,rightValues) =>
leftValues.getOrElse(0) + rightValues.getOrElse(0)
} === Map(1 -> 199, 2 -> 222, 3 -> 33)
}
}
}
|
apache-2.0
|
bozimmerman/CoffeeMud
|
com/planet_ink/coffee_mud/MOBS/DrowElf.java
|
4315
|
package com.planet_ink.coffee_mud.MOBS;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2022 Lee H. Fox
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.
*/
public class DrowElf extends StdMOB
{
@Override
public String ID()
{
return "DrowElf";
}
public static final int MALE = 0;
public static final int FEMALE = 1;
public int darkDown=4;
public DrowElf()
{
super();
final Random randomizer = new Random(System.currentTimeMillis());
basePhyStats().setLevel(4 + Math.abs(randomizer.nextInt() % 7));
final int gender = Math.abs(randomizer.nextInt() % 2);
String sex = null;
if (gender == MALE)
sex = "male";
else
sex = "female";
// ===== set the basics
_name="a Drow Elf";
setDescription("a " + sex + " Drow Fighter");
setDisplayText("The drow is armored in black chain mail and carrying a nice arsenal of weapons");
baseState.setHitPoints(CMLib.dice().roll(basePhyStats().level(),20,basePhyStats().level()));
setMoney((int)Math.round(CMath.div((50 * basePhyStats().level()),(randomizer.nextInt() % 10 + 1))));
basePhyStats.setWeight(70 + Math.abs(randomizer.nextInt() % 20));
setWimpHitPoint(5);
basePhyStats().setSpeed(2.0);
basePhyStats().setSensesMask(PhyStats.CAN_SEE_DARK | PhyStats.CAN_SEE_INFRARED);
if(gender == MALE)
baseCharStats().setStat(CharStats.STAT_GENDER,'M');
else
baseCharStats().setStat(CharStats.STAT_GENDER,'F');
baseCharStats().setStat(CharStats.STAT_STRENGTH,12 + Math.abs(randomizer.nextInt() % 6));
baseCharStats().setStat(CharStats.STAT_INTELLIGENCE,14 + Math.abs(randomizer.nextInt() % 6));
baseCharStats().setStat(CharStats.STAT_WISDOM,13 + Math.abs(randomizer.nextInt() % 6));
baseCharStats().setStat(CharStats.STAT_DEXTERITY,15 + Math.abs(randomizer.nextInt() % 6));
baseCharStats().setStat(CharStats.STAT_CONSTITUTION,12 + Math.abs(randomizer.nextInt() % 6));
baseCharStats().setStat(CharStats.STAT_CHARISMA,13 + Math.abs(randomizer.nextInt() % 6));
baseCharStats().setMyRace(CMClass.getRace("Elf"));
baseCharStats().getMyRace().startRacing(this,false);
recoverMaxState();
resetToMaxState();
recoverPhyStats();
recoverCharStats();
}
@Override
public boolean tick(final Tickable ticking, final int tickID)
{
if((!amDead())&&(tickID==Tickable.TICKID_MOB))
{
if (isInCombat())
{
if((--darkDown)<=0)
{
darkDown=4;
castDarkness();
}
}
}
return super.tick(ticking,tickID);
}
protected boolean castDarkness()
{
if(this.location()==null)
return true;
if(CMLib.flags().isInDark(this.location()))
return true;
Ability dark=CMClass.getAbility("Spell_Darkness");
dark.setProficiency(100);
dark.setSavable(false);
if(this.fetchAbility(dark.ID())==null)
this.addAbility(dark);
else
dark=this.fetchAbility(dark.ID());
if(dark!=null)
dark.invoke(this,null,true,0);
return true;
}
}
|
apache-2.0
|
gravitee-io/graviteeio-access-management
|
gravitee-am-common/src/main/java/io/gravitee/am/common/event/AlertEventKeys.java
|
1476
|
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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.gravitee.am.common.event;
/**
* @author Jeoffrey HAEYAERT (jeoffrey.haeyaert at graviteesource.com)
* @author GraviteeSource Team
*/
public interface AlertEventKeys {
String PROCESSOR_GEOIP = "geoip";
String PROCESSOR_USERAGENT = "useragent";
String CONTEXT_NODE_ID = "node.id";
String CONTEXT_NODE_HOSTNAME = "node.hostname";
String CONTEXT_NODE_APPLICATION = "node.application";
String CONTEXT_GATEWAY_PORT = "gateway.port";
String PROPERTY_DOMAIN = "domain";
String PROPERTY_APPLICATION = "application";
String PROPERTY_USER = "user";
String PROPERTY_IP = "ip";
String PROPERTY_USER_AGENT = "user_agent";
String PROPERTY_TRANSACTION_ID = "transaction_id";
String PROPERTY_AUTHENTICATION_STATUS = "authentication.status";
String TYPE_AUTHENTICATION = "AUTHENTICATION";
}
|
apache-2.0
|
accraze/Audiolet
|
examples/synth/js/synth.js
|
2107
|
window.onload = function() {
var Synth = function(audiolet) {
AudioletGroup.apply(this, [audiolet, 0, 1]);
// Basic wave
this.saw = new Saw(audiolet, 100);
// Frequency LFO
this.frequencyLFO = new Sine(audiolet, 2);
this.frequencyMA = new MulAdd(audiolet, 10, 100);
// Filter
this.filter = new LowPassFilter(audiolet, 1000);
// Filter LFO
this.filterLFO = new Sine(audiolet, 8);
this.filterMA = new MulAdd(audiolet, 900, 1000);
// Gain envelope
this.gain = new Gain(audiolet);
this.env = new ADSREnvelope(audiolet,
1, // Gate
1.5, // Attack
0.2, // Decay
0.9, // Sustain
2); // Release
// Main signal path
this.saw.connect(this.filter);
this.filter.connect(this.gain);
this.gain.connect(this.outputs[0]);
// Frequency LFO
this.frequencyLFO.connect(this.frequencyMA);
this.frequencyMA.connect(this.saw);
// Filter LFO
this.filterLFO.connect(this.filterMA);
this.filterMA.connect(this.filter, 0, 1);
// Envelope
this.env.connect(this.gain, 0, 1);
};
extend(Synth, AudioletGroup);
var audiolet = new Audiolet();
var synth = new Synth(audiolet);
var frequencyPattern = new PSequence([55, 55, 98, 98, 73, 73, 98, 98],
Infinity);
var filterLFOPattern = new PChoose([2, 4, 6, 8], Infinity);
var gatePattern = new PSequence([1, 0], Infinity);
var patterns = [frequencyPattern, filterLFOPattern, gatePattern];
audiolet.scheduler.play(patterns, 2,
function(frequency, filterLFOFrequency, gate) {
this.frequencyMA.add.setValue(frequency);
this.filterLFO.frequency.setValue(filterLFOFrequency);
this.env.gate.setValue(gate);
}.bind(synth)
);
synth.connect(audiolet.output);
};
|
apache-2.0
|
ripdajacker/commons-betwixt
|
src/java/org/apache/commons/betwixt/digester/package.html
|
989
|
<html>
<!--
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.
-->
<head>
</head>
<body>
<p> This package contains the Digester and associated rules and helper classes
for parsing the XMLBeanInfo metadata from an XML file format.</p>
</body>
</html>
|
apache-2.0
|
Sebastian-henn/twu-biblioteca-sebastian-henn
|
test/com/twu/biblioteca/MovieTest.java
|
815
|
package com.twu.biblioteca;
import org.junit.Test;
import static org.junit.Assert.*;
public class MovieTest {
String title = "random title";
int year = 2042;
String director = "random author";
int rating = 6;
Movie testMovie = new Movie(title,year,director,rating);
@Test
public void testMovieConstructor() {
assertEquals(title,testMovie.getTitle());
assertEquals(year,testMovie.getYear());
assertEquals(director, testMovie.getDirector());
assertEquals(rating,testMovie.getRating());
}
@Test
public void testSetAvailable() {
testMovie.setAvailable(false);
assertFalse(testMovie.getAvailability());
testMovie.setAvailable(true);
assertTrue(testMovie.getAvailability());
}
}
|
apache-2.0
|
quentinlesceller/OBC4J
|
doc/protos/Openchain.Response.Builder.html
|
30767
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_66) on Tue Mar 08 13:38:45 EST 2016 -->
<title>Openchain.Response.Builder</title>
<meta name="date" content="2016-03-08">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Openchain.Response.Builder";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":9,"i7":10,"i8":10,"i9":10,"i10":10,"i11":10,"i12":10,"i13":10,"i14":10,"i15":10,"i16":10,"i17":10,"i18":10,"i19":10};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Openchain.Response.Builder.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../protos/Openchain.Response.html" title="class in protos"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../protos/Openchain.Response.StatusCode.html" title="enum in protos"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?protos/Openchain.Response.Builder.html" target="_top">Frames</a></li>
<li><a href="Openchain.Response.Builder.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">protos</div>
<h2 title="Class Openchain.Response.Builder" class="title">Class Openchain.Response.Builder</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.google.protobuf.AbstractMessageLite.Builder<BuilderType></li>
<li>
<ul class="inheritance">
<li>com.google.protobuf.AbstractMessage.Builder<BuilderType></li>
<li>
<ul class="inheritance">
<li>com.google.protobuf.GeneratedMessage.Builder<<a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a>></li>
<li>
<ul class="inheritance">
<li>protos.Openchain.Response.Builder</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>com.google.protobuf.Message.Builder, com.google.protobuf.MessageLite.Builder, com.google.protobuf.MessageLiteOrBuilder, com.google.protobuf.MessageOrBuilder, java.lang.Cloneable, <a href="../protos/Openchain.ResponseOrBuilder.html" title="interface in protos">Openchain.ResponseOrBuilder</a></dd>
</dl>
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../protos/Openchain.Response.html" title="class in protos">Openchain.Response</a></dd>
</dl>
<hr>
<br>
<pre>public static final class <span class="typeNameLabel">Openchain.Response.Builder</span>
extends com.google.protobuf.GeneratedMessage.Builder<<a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a>>
implements <a href="../protos/Openchain.ResponseOrBuilder.html" title="interface in protos">Openchain.ResponseOrBuilder</a></pre>
<div class="block">Protobuf type <code>protos.Response</code></div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code><a href="../protos/Openchain.Response.html" title="class in protos">Openchain.Response</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#build--">build</a></span>()</code> </td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code><a href="../protos/Openchain.Response.html" title="class in protos">Openchain.Response</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#buildPartial--">buildPartial</a></span>()</code> </td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code><a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#clear--">clear</a></span>()</code> </td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code><a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#clearMsg--">clearMsg</a></span>()</code>
<div class="block"><code>optional bytes msg = 2;</code></div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code><a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#clearStatus--">clearStatus</a></span>()</code>
<div class="block"><code>optional .protos.Response.StatusCode status = 1;</code></div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code><a href="../protos/Openchain.Response.html" title="class in protos">Openchain.Response</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#getDefaultInstanceForType--">getDefaultInstanceForType</a></span>()</code> </td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>static com.google.protobuf.Descriptors.Descriptor</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#getDescriptor--">getDescriptor</a></span>()</code> </td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code>com.google.protobuf.Descriptors.Descriptor</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#getDescriptorForType--">getDescriptorForType</a></span>()</code> </td>
</tr>
<tr id="i8" class="altColor">
<td class="colFirst"><code>com.google.protobuf.ByteString</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#getMsg--">getMsg</a></span>()</code>
<div class="block"><code>optional bytes msg = 2;</code></div>
</td>
</tr>
<tr id="i9" class="rowColor">
<td class="colFirst"><code><a href="../protos/Openchain.Response.StatusCode.html" title="enum in protos">Openchain.Response.StatusCode</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#getStatus--">getStatus</a></span>()</code>
<div class="block"><code>optional .protos.Response.StatusCode status = 1;</code></div>
</td>
</tr>
<tr id="i10" class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#getStatusValue--">getStatusValue</a></span>()</code>
<div class="block"><code>optional .protos.Response.StatusCode status = 1;</code></div>
</td>
</tr>
<tr id="i11" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#isInitialized--">isInitialized</a></span>()</code> </td>
</tr>
<tr id="i12" class="altColor">
<td class="colFirst"><code><a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#mergeFrom-com.google.protobuf.CodedInputStream-com.google.protobuf.ExtensionRegistryLite-">mergeFrom</a></span>(com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)</code> </td>
</tr>
<tr id="i13" class="rowColor">
<td class="colFirst"><code><a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#mergeFrom-com.google.protobuf.Message-">mergeFrom</a></span>(com.google.protobuf.Message other)</code> </td>
</tr>
<tr id="i14" class="altColor">
<td class="colFirst"><code><a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#mergeFrom-protos.Openchain.Response-">mergeFrom</a></span>(<a href="../protos/Openchain.Response.html" title="class in protos">Openchain.Response</a> other)</code> </td>
</tr>
<tr id="i15" class="rowColor">
<td class="colFirst"><code><a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#mergeUnknownFields-com.google.protobuf.UnknownFieldSet-">mergeUnknownFields</a></span>(com.google.protobuf.UnknownFieldSet unknownFields)</code> </td>
</tr>
<tr id="i16" class="altColor">
<td class="colFirst"><code><a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#setMsg-com.google.protobuf.ByteString-">setMsg</a></span>(com.google.protobuf.ByteString value)</code>
<div class="block"><code>optional bytes msg = 2;</code></div>
</td>
</tr>
<tr id="i17" class="rowColor">
<td class="colFirst"><code><a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#setStatus-protos.Openchain.Response.StatusCode-">setStatus</a></span>(<a href="../protos/Openchain.Response.StatusCode.html" title="enum in protos">Openchain.Response.StatusCode</a> value)</code>
<div class="block"><code>optional .protos.Response.StatusCode status = 1;</code></div>
</td>
</tr>
<tr id="i18" class="altColor">
<td class="colFirst"><code><a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#setStatusValue-int-">setStatusValue</a></span>(int value)</code>
<div class="block"><code>optional .protos.Response.StatusCode status = 1;</code></div>
</td>
</tr>
<tr id="i19" class="rowColor">
<td class="colFirst"><code><a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../protos/Openchain.Response.Builder.html#setUnknownFields-com.google.protobuf.UnknownFieldSet-">setUnknownFields</a></span>(com.google.protobuf.UnknownFieldSet unknownFields)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.com.google.protobuf.GeneratedMessage.Builder">
<!-- -->
</a>
<h3>Methods inherited from class com.google.protobuf.GeneratedMessage.Builder</h3>
<code>addRepeatedField, clearField, clearOneof, clone, getAllFields, getField, getFieldBuilder, getOneofFieldDescriptor, getRepeatedField, getRepeatedFieldBuilder, getRepeatedFieldCount, getUnknownFields, hasField, hasOneof, newBuilderForField, setField, setRepeatedField</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.com.google.protobuf.AbstractMessage.Builder">
<!-- -->
</a>
<h3>Methods inherited from class com.google.protobuf.AbstractMessage.Builder</h3>
<code>findInitializationErrors, getInitializationErrorString, mergeDelimitedFrom, mergeDelimitedFrom, mergeFrom, mergeFrom, mergeFrom, mergeFrom, mergeFrom, mergeFrom, mergeFrom, mergeFrom, mergeFrom, toString</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.com.google.protobuf.MessageOrBuilder">
<!-- -->
</a>
<h3>Methods inherited from interface com.google.protobuf.MessageOrBuilder</h3>
<code>findInitializationErrors, getAllFields, getField, getInitializationErrorString, getOneofFieldDescriptor, getRepeatedField, getRepeatedFieldCount, getUnknownFields, hasField, hasOneof</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getDescriptor--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDescriptor</h4>
<pre>public static final com.google.protobuf.Descriptors.Descriptor getDescriptor()</pre>
</li>
</ul>
<a name="clear--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>clear</h4>
<pre>public <a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a> clear()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>clear</code> in interface <code>com.google.protobuf.Message.Builder</code></dd>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>clear</code> in interface <code>com.google.protobuf.MessageLite.Builder</code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>clear</code> in class <code>com.google.protobuf.GeneratedMessage.Builder<<a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a>></code></dd>
</dl>
</li>
</ul>
<a name="getDescriptorForType--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDescriptorForType</h4>
<pre>public com.google.protobuf.Descriptors.Descriptor getDescriptorForType()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>getDescriptorForType</code> in interface <code>com.google.protobuf.Message.Builder</code></dd>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>getDescriptorForType</code> in interface <code>com.google.protobuf.MessageOrBuilder</code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>getDescriptorForType</code> in class <code>com.google.protobuf.GeneratedMessage.Builder<<a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a>></code></dd>
</dl>
</li>
</ul>
<a name="getDefaultInstanceForType--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDefaultInstanceForType</h4>
<pre>public <a href="../protos/Openchain.Response.html" title="class in protos">Openchain.Response</a> getDefaultInstanceForType()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>getDefaultInstanceForType</code> in interface <code>com.google.protobuf.MessageLiteOrBuilder</code></dd>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>getDefaultInstanceForType</code> in interface <code>com.google.protobuf.MessageOrBuilder</code></dd>
</dl>
</li>
</ul>
<a name="build--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>build</h4>
<pre>public <a href="../protos/Openchain.Response.html" title="class in protos">Openchain.Response</a> build()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>build</code> in interface <code>com.google.protobuf.Message.Builder</code></dd>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>build</code> in interface <code>com.google.protobuf.MessageLite.Builder</code></dd>
</dl>
</li>
</ul>
<a name="buildPartial--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>buildPartial</h4>
<pre>public <a href="../protos/Openchain.Response.html" title="class in protos">Openchain.Response</a> buildPartial()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>buildPartial</code> in interface <code>com.google.protobuf.Message.Builder</code></dd>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>buildPartial</code> in interface <code>com.google.protobuf.MessageLite.Builder</code></dd>
</dl>
</li>
</ul>
<a name="mergeFrom-com.google.protobuf.Message-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>mergeFrom</h4>
<pre>public <a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a> mergeFrom(com.google.protobuf.Message other)</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>mergeFrom</code> in interface <code>com.google.protobuf.Message.Builder</code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>mergeFrom</code> in class <code>com.google.protobuf.AbstractMessage.Builder<<a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a>></code></dd>
</dl>
</li>
</ul>
<a name="mergeFrom-protos.Openchain.Response-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>mergeFrom</h4>
<pre>public <a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a> mergeFrom(<a href="../protos/Openchain.Response.html" title="class in protos">Openchain.Response</a> other)</pre>
</li>
</ul>
<a name="isInitialized--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isInitialized</h4>
<pre>public final boolean isInitialized()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>isInitialized</code> in interface <code>com.google.protobuf.MessageLiteOrBuilder</code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>isInitialized</code> in class <code>com.google.protobuf.GeneratedMessage.Builder<<a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a>></code></dd>
</dl>
</li>
</ul>
<a name="mergeFrom-com.google.protobuf.CodedInputStream-com.google.protobuf.ExtensionRegistryLite-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>mergeFrom</h4>
<pre>public <a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a> mergeFrom(com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>mergeFrom</code> in interface <code>com.google.protobuf.Message.Builder</code></dd>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>mergeFrom</code> in interface <code>com.google.protobuf.MessageLite.Builder</code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>mergeFrom</code> in class <code>com.google.protobuf.AbstractMessage.Builder<<a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a>></code></dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.io.IOException</code></dd>
</dl>
</li>
</ul>
<a name="getStatusValue--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getStatusValue</h4>
<pre>public int getStatusValue()</pre>
<div class="block"><code>optional .protos.Response.StatusCode status = 1;</code></div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../protos/Openchain.ResponseOrBuilder.html#getStatusValue--">getStatusValue</a></code> in interface <code><a href="../protos/Openchain.ResponseOrBuilder.html" title="interface in protos">Openchain.ResponseOrBuilder</a></code></dd>
</dl>
</li>
</ul>
<a name="setStatusValue-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setStatusValue</h4>
<pre>public <a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a> setStatusValue(int value)</pre>
<div class="block"><code>optional .protos.Response.StatusCode status = 1;</code></div>
</li>
</ul>
<a name="getStatus--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getStatus</h4>
<pre>public <a href="../protos/Openchain.Response.StatusCode.html" title="enum in protos">Openchain.Response.StatusCode</a> getStatus()</pre>
<div class="block"><code>optional .protos.Response.StatusCode status = 1;</code></div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../protos/Openchain.ResponseOrBuilder.html#getStatus--">getStatus</a></code> in interface <code><a href="../protos/Openchain.ResponseOrBuilder.html" title="interface in protos">Openchain.ResponseOrBuilder</a></code></dd>
</dl>
</li>
</ul>
<a name="setStatus-protos.Openchain.Response.StatusCode-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setStatus</h4>
<pre>public <a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a> setStatus(<a href="../protos/Openchain.Response.StatusCode.html" title="enum in protos">Openchain.Response.StatusCode</a> value)</pre>
<div class="block"><code>optional .protos.Response.StatusCode status = 1;</code></div>
</li>
</ul>
<a name="clearStatus--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>clearStatus</h4>
<pre>public <a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a> clearStatus()</pre>
<div class="block"><code>optional .protos.Response.StatusCode status = 1;</code></div>
</li>
</ul>
<a name="getMsg--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getMsg</h4>
<pre>public com.google.protobuf.ByteString getMsg()</pre>
<div class="block"><code>optional bytes msg = 2;</code></div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../protos/Openchain.ResponseOrBuilder.html#getMsg--">getMsg</a></code> in interface <code><a href="../protos/Openchain.ResponseOrBuilder.html" title="interface in protos">Openchain.ResponseOrBuilder</a></code></dd>
</dl>
</li>
</ul>
<a name="setMsg-com.google.protobuf.ByteString-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setMsg</h4>
<pre>public <a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a> setMsg(com.google.protobuf.ByteString value)</pre>
<div class="block"><code>optional bytes msg = 2;</code></div>
</li>
</ul>
<a name="clearMsg--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>clearMsg</h4>
<pre>public <a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a> clearMsg()</pre>
<div class="block"><code>optional bytes msg = 2;</code></div>
</li>
</ul>
<a name="setUnknownFields-com.google.protobuf.UnknownFieldSet-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setUnknownFields</h4>
<pre>public final <a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a> setUnknownFields(com.google.protobuf.UnknownFieldSet unknownFields)</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>setUnknownFields</code> in interface <code>com.google.protobuf.Message.Builder</code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>setUnknownFields</code> in class <code>com.google.protobuf.GeneratedMessage.Builder<<a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a>></code></dd>
</dl>
</li>
</ul>
<a name="mergeUnknownFields-com.google.protobuf.UnknownFieldSet-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>mergeUnknownFields</h4>
<pre>public final <a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a> mergeUnknownFields(com.google.protobuf.UnknownFieldSet unknownFields)</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>mergeUnknownFields</code> in interface <code>com.google.protobuf.Message.Builder</code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>mergeUnknownFields</code> in class <code>com.google.protobuf.GeneratedMessage.Builder<<a href="../protos/Openchain.Response.Builder.html" title="class in protos">Openchain.Response.Builder</a>></code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Openchain.Response.Builder.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../protos/Openchain.Response.html" title="class in protos"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../protos/Openchain.Response.StatusCode.html" title="enum in protos"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?protos/Openchain.Response.Builder.html" target="_top">Frames</a></li>
<li><a href="Openchain.Response.Builder.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
apache-2.0
|
aloysiusang/twu-biblioteca-aloysiusang
|
src/com/twu/biblioteca/menus/UserMainMenu.java
|
624
|
package com.twu.biblioteca.menus;
import com.twu.biblioteca.options.*;
import java.util.ArrayList;
/**
* Created by aloysiusang on 17/6/15.
*/
public class UserMainMenu extends MainMenu {
public UserMainMenu() {
super(new ArrayList<MainMenuOption>() {{
add(new ListBooksOption());
add(new CheckOutBookOption());
add(new ReturnBookOption());
add(new ListMoviesOption());
add(new CheckOutMovieOption());
add(new ReturnMovieOption());
add(new UserInformationOption());
add(new QuitOption());
}});
}
}
|
apache-2.0
|
lisuperhong/MDZhihuDaily
|
app/src/main/java/com/lzh/mdzhihudaily_mvp/presenter/ThemeDailyPresenter.java
|
2219
|
package com.lzh.mdzhihudaily_mvp.presenter;
import android.support.annotation.NonNull;
import com.lzh.mdzhihudaily_mvp.contract.ThemeDailyContract;
import com.lzh.mdzhihudaily_mvp.model.DataRepository;
import com.lzh.mdzhihudaily_mvp.model.Entity.ThemeNews;
import rx.Subscriber;
import rx.Subscription;
/**
* @author lzh
* @desc:
* @date Created on 2017/3/5 23:59
* @github: https://github.com/lisuperhong
*/
public class ThemeDailyPresenter implements ThemeDailyContract.Presenter {
private ThemeDailyContract.View themeDailyView;
private int themeId;
private Subscription subscription;
public ThemeDailyPresenter(@NonNull ThemeDailyContract.View view, int themeId) {
themeDailyView = view;
this.themeId = themeId;
}
@Override
public void start() {
themeDailyView.showLoading();
getThemeNews(false);
}
@Override
public void refreshData() {
getThemeNews(true);
}
private void getThemeNews(final boolean isRefresh) {
unsubscript();
subscription = DataRepository.getInstance()
.getThemeNews(themeId)
.subscribe(new Subscriber<ThemeNews>() {
@Override
public void onCompleted() {
if (isRefresh) {
themeDailyView.stopRefreshLayout();
} else {
themeDailyView.hideLoading();
}
}
@Override
public void onError(Throwable e) {
if (isRefresh) {
themeDailyView.stopRefreshLayout();
} else {
themeDailyView.hideLoading();
}
}
@Override
public void onNext(ThemeNews themeNews) {
themeDailyView.setData(themeNews);
}
});
}
@Override
public void unsubscript() {
if (subscription != null && !subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
}
}
|
apache-2.0
|
rpmoore/ds3_net_sdk
|
Ds3/Runtime/Ds3RequestException.cs
|
1105
|
/*
* ******************************************************************************
* Copyright 2014-2016 Spectra Logic Corporation. 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://www.apache.org/licenses/LICENSE-2.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.
* ****************************************************************************
*/
using System;
namespace Ds3.Runtime
{
public class Ds3RequestException : Exception
{
public Ds3RequestException(string message)
: base(message)
{
}
public Ds3RequestException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
|
apache-2.0
|
pczarn/rust
|
src/libsemver/lib.rs
|
14044
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Semantic version parsing and comparison.
//!
//! Semantic versioning (see http://semver.org/) is a set of rules for
//! assigning version numbers intended to convey meaning about what has
//! changed, and how much. A version number has five parts:
//!
//! * Major number, updated for incompatible API changes
//! * Minor number, updated for backwards-compatible API additions
//! * Patch number, updated for backwards-compatible bugfixes
//! * Pre-release information (optional), preceded by a hyphen (`-`)
//! * Build metadata (optional), preceded by a plus sign (`+`)
//!
//! The three mandatory components are required to be decimal numbers. The
//! pre-release information and build metadata are required to be a
//! period-separated list of identifiers containing only alphanumeric
//! characters and hyphens.
//!
//! An example version number with all five components is
//! `0.8.1-rc.3.0+20130922.linux`.
#![crate_name = "semver"]
#![experimental]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/master/")]
#![feature(default_type_params)]
use std::char;
use std::cmp;
use std::fmt::Show;
use std::fmt;
use std::hash;
/// An identifier in the pre-release or build metadata. If the identifier can
/// be parsed as a decimal value, it will be represented with `Numeric`.
#[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[allow(missing_doc)]
pub enum Identifier {
Numeric(uint),
AlphaNumeric(String)
}
impl fmt::Show for Identifier {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Numeric(ref n) => n.fmt(f),
AlphaNumeric(ref s) => s.fmt(f)
}
}
}
/// Represents a version number conforming to the semantic versioning scheme.
#[deriving(Clone, Eq)]
pub struct Version {
/// The major version, to be incremented on incompatible changes.
pub major: uint,
/// The minor version, to be incremented when functionality is added in a
/// backwards-compatible manner.
pub minor: uint,
/// The patch version, to be incremented when backwards-compatible bug
/// fixes are made.
pub patch: uint,
/// The pre-release version identifier, if one exists.
pub pre: Vec<Identifier>,
/// The build metadata, ignored when determining version precedence.
pub build: Vec<Identifier>,
}
impl fmt::Show for Version {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{}.{}.{}", self.major, self.minor, self.patch))
if !self.pre.is_empty() {
try!(write!(f, "-"));
for (i, x) in self.pre.iter().enumerate() {
if i != 0 { try!(write!(f, ".")) };
try!(x.fmt(f));
}
}
if !self.build.is_empty() {
try!(write!(f, "+"));
for (i, x) in self.build.iter().enumerate() {
if i != 0 { try!(write!(f, ".")) };
try!(x.fmt(f));
}
}
Ok(())
}
}
impl cmp::PartialEq for Version {
#[inline]
fn eq(&self, other: &Version) -> bool {
// We should ignore build metadata here, otherwise versions v1 and v2
// can exist such that !(v1 < v2) && !(v1 > v2) && v1 != v2, which
// violate strict total ordering rules.
self.major == other.major &&
self.minor == other.minor &&
self.patch == other.patch &&
self.pre == other.pre
}
}
impl cmp::PartialOrd for Version {
fn partial_cmp(&self, other: &Version) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl cmp::Ord for Version {
fn cmp(&self, other: &Version) -> Ordering {
match self.major.cmp(&other.major) {
Equal => {}
r => return r,
}
match self.minor.cmp(&other.minor) {
Equal => {}
r => return r,
}
match self.patch.cmp(&other.patch) {
Equal => {}
r => return r,
}
// NB: semver spec says 0.0.0-pre < 0.0.0
// but the version of ord defined for vec
// says that [] < [pre] so we alter it here
match (self.pre.len(), other.pre.len()) {
(0, 0) => Equal,
(0, _) => Greater,
(_, 0) => Less,
(_, _) => self.pre.cmp(&other.pre)
}
}
}
impl<S: hash::Writer> hash::Hash<S> for Version {
fn hash(&self, into: &mut S) {
self.major.hash(into);
self.minor.hash(into);
self.patch.hash(into);
self.pre.hash(into);
}
}
fn take_nonempty_prefix<T:Iterator<char>>(rdr: &mut T, pred: |char| -> bool)
-> (String, Option<char>) {
let mut buf = String::new();
let mut ch = rdr.next();
loop {
match ch {
None => break,
Some(c) if !pred(c) => break,
Some(c) => {
buf.push_char(c);
ch = rdr.next();
}
}
}
(buf, ch)
}
fn take_num<T: Iterator<char>>(rdr: &mut T) -> Option<(uint, Option<char>)> {
let (s, ch) = take_nonempty_prefix(rdr, char::is_digit);
match from_str::<uint>(s.as_slice()) {
None => None,
Some(i) => Some((i, ch))
}
}
fn take_ident<T: Iterator<char>>(rdr: &mut T) -> Option<(Identifier, Option<char>)> {
let (s,ch) = take_nonempty_prefix(rdr, char::is_alphanumeric);
if s.as_slice().chars().all(char::is_digit) {
match from_str::<uint>(s.as_slice()) {
None => None,
Some(i) => Some((Numeric(i), ch))
}
} else {
Some((AlphaNumeric(s), ch))
}
}
fn expect(ch: Option<char>, c: char) -> Option<()> {
if ch != Some(c) {
None
} else {
Some(())
}
}
fn parse_iter<T: Iterator<char>>(rdr: &mut T) -> Option<Version> {
let maybe_vers = take_num(rdr).and_then(|(major, ch)| {
expect(ch, '.').and_then(|_| Some(major))
}).and_then(|major| {
take_num(rdr).and_then(|(minor, ch)| {
expect(ch, '.').and_then(|_| Some((major, minor)))
})
}).and_then(|(major, minor)| {
take_num(rdr).and_then(|(patch, ch)| {
Some((major, minor, patch, ch))
})
});
let (major, minor, patch, ch) = match maybe_vers {
Some((a, b, c, d)) => (a, b, c, d),
None => return None
};
let mut pre = vec!();
let mut build = vec!();
let mut ch = ch;
if ch == Some('-') {
loop {
let (id, c) = match take_ident(rdr) {
Some((id, c)) => (id, c),
None => return None
};
pre.push(id);
ch = c;
if ch != Some('.') { break; }
}
}
if ch == Some('+') {
loop {
let (id, c) = match take_ident(rdr) {
Some((id, c)) => (id, c),
None => return None
};
build.push(id);
ch = c;
if ch != Some('.') { break; }
}
}
Some(Version {
major: major,
minor: minor,
patch: patch,
pre: pre,
build: build,
})
}
/// Parse a string into a semver object.
pub fn parse(s: &str) -> Option<Version> {
if !s.is_ascii() {
return None;
}
let s = s.trim();
let v = parse_iter(&mut s.chars());
match v {
Some(v) => {
if v.to_string().equiv(&s) {
Some(v)
} else {
None
}
}
None => None
}
}
#[test]
fn test_parse() {
assert_eq!(parse(""), None);
assert_eq!(parse(" "), None);
assert_eq!(parse("1"), None);
assert_eq!(parse("1.2"), None);
assert_eq!(parse("1.2"), None);
assert_eq!(parse("1"), None);
assert_eq!(parse("1.2"), None);
assert_eq!(parse("1.2.3-"), None);
assert_eq!(parse("a.b.c"), None);
assert_eq!(parse("1.2.3 abc"), None);
assert!(parse("1.2.3") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(),
build: vec!(),
}));
assert!(parse(" 1.2.3 ") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(),
build: vec!(),
}));
assert!(parse("1.2.3-alpha1") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(AlphaNumeric("alpha1".to_string())),
build: vec!(),
}));
assert!(parse(" 1.2.3-alpha1 ") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(AlphaNumeric("alpha1".to_string())),
build: vec!()
}));
assert!(parse("1.2.3+build5") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(),
build: vec!(AlphaNumeric("build5".to_string()))
}));
assert!(parse(" 1.2.3+build5 ") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(),
build: vec!(AlphaNumeric("build5".to_string()))
}));
assert!(parse("1.2.3-alpha1+build5") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(AlphaNumeric("alpha1".to_string())),
build: vec!(AlphaNumeric("build5".to_string()))
}));
assert!(parse(" 1.2.3-alpha1+build5 ") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(AlphaNumeric("alpha1".to_string())),
build: vec!(AlphaNumeric("build5".to_string()))
}));
assert!(parse("1.2.3-1.alpha1.9+build5.7.3aedf ") == Some(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(Numeric(1),AlphaNumeric("alpha1".to_string()),Numeric(9)),
build: vec!(AlphaNumeric("build5".to_string()),
Numeric(7),
AlphaNumeric("3aedf".to_string()))
}));
}
#[test]
fn test_eq() {
assert_eq!(parse("1.2.3"), parse("1.2.3"));
assert_eq!(parse("1.2.3-alpha1"), parse("1.2.3-alpha1"));
assert_eq!(parse("1.2.3+build.42"), parse("1.2.3+build.42"));
assert_eq!(parse("1.2.3-alpha1+42"), parse("1.2.3-alpha1+42"));
assert_eq!(parse("1.2.3+23"), parse("1.2.3+42"));
}
#[test]
fn test_ne() {
assert!(parse("0.0.0") != parse("0.0.1"));
assert!(parse("0.0.0") != parse("0.1.0"));
assert!(parse("0.0.0") != parse("1.0.0"));
assert!(parse("1.2.3-alpha") != parse("1.2.3-beta"));
}
#[test]
fn test_show() {
assert_eq!(format!("{}", parse("1.2.3").unwrap()),
"1.2.3".to_string());
assert_eq!(format!("{}", parse("1.2.3-alpha1").unwrap()),
"1.2.3-alpha1".to_string());
assert_eq!(format!("{}", parse("1.2.3+build.42").unwrap()),
"1.2.3+build.42".to_string());
assert_eq!(format!("{}", parse("1.2.3-alpha1+42").unwrap()),
"1.2.3-alpha1+42".to_string());
}
#[test]
fn test_to_string() {
assert_eq!(parse("1.2.3").unwrap().to_string(), "1.2.3".to_string());
assert_eq!(parse("1.2.3-alpha1").unwrap().to_string(), "1.2.3-alpha1".to_string());
assert_eq!(parse("1.2.3+build.42").unwrap().to_string(), "1.2.3+build.42".to_string());
assert_eq!(parse("1.2.3-alpha1+42").unwrap().to_string(), "1.2.3-alpha1+42".to_string());
}
#[test]
fn test_lt() {
assert!(parse("0.0.0") < parse("1.2.3-alpha2"));
assert!(parse("1.0.0") < parse("1.2.3-alpha2"));
assert!(parse("1.2.0") < parse("1.2.3-alpha2"));
assert!(parse("1.2.3-alpha1") < parse("1.2.3"));
assert!(parse("1.2.3-alpha1") < parse("1.2.3-alpha2"));
assert!(!(parse("1.2.3-alpha2") < parse("1.2.3-alpha2")));
assert!(!(parse("1.2.3+23") < parse("1.2.3+42")));
}
#[test]
fn test_le() {
assert!(parse("0.0.0") <= parse("1.2.3-alpha2"));
assert!(parse("1.0.0") <= parse("1.2.3-alpha2"));
assert!(parse("1.2.0") <= parse("1.2.3-alpha2"));
assert!(parse("1.2.3-alpha1") <= parse("1.2.3-alpha2"));
assert!(parse("1.2.3-alpha2") <= parse("1.2.3-alpha2"));
assert!(parse("1.2.3+23") <= parse("1.2.3+42"));
}
#[test]
fn test_gt() {
assert!(parse("1.2.3-alpha2") > parse("0.0.0"));
assert!(parse("1.2.3-alpha2") > parse("1.0.0"));
assert!(parse("1.2.3-alpha2") > parse("1.2.0"));
assert!(parse("1.2.3-alpha2") > parse("1.2.3-alpha1"));
assert!(parse("1.2.3") > parse("1.2.3-alpha2"));
assert!(!(parse("1.2.3-alpha2") > parse("1.2.3-alpha2")));
assert!(!(parse("1.2.3+23") > parse("1.2.3+42")));
}
#[test]
fn test_ge() {
assert!(parse("1.2.3-alpha2") >= parse("0.0.0"));
assert!(parse("1.2.3-alpha2") >= parse("1.0.0"));
assert!(parse("1.2.3-alpha2") >= parse("1.2.0"));
assert!(parse("1.2.3-alpha2") >= parse("1.2.3-alpha1"));
assert!(parse("1.2.3-alpha2") >= parse("1.2.3-alpha2"));
assert!(parse("1.2.3+23") >= parse("1.2.3+42"));
}
#[test]
fn test_spec_order() {
let vs = ["1.0.0-alpha",
"1.0.0-alpha.1",
"1.0.0-alpha.beta",
"1.0.0-beta",
"1.0.0-beta.2",
"1.0.0-beta.11",
"1.0.0-rc.1",
"1.0.0"];
let mut i = 1;
while i < vs.len() {
let a = parse(vs[i-1]).unwrap();
let b = parse(vs[i]).unwrap();
assert!(a < b);
i += 1;
}
}
|
apache-2.0
|
eljefe6a/incubator-beam
|
sdks/python/apache_beam/runners/portability/fn_api_runner_test.py
|
2196
|
#
# 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.
#
import logging
import unittest
import apache_beam as beam
from apache_beam.runners.portability import fn_api_runner
from apache_beam.runners.portability import maptask_executor_runner_test
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import equal_to
class FnApiRunnerTest(
maptask_executor_runner_test.MapTaskExecutorRunnerTest):
def create_pipeline(self):
return beam.Pipeline(
runner=fn_api_runner.FnApiRunner())
def test_combine_per_key(self):
# TODO(BEAM-1348): Enable once Partial GBK is supported in fn API.
pass
def test_combine_per_key(self):
# TODO(BEAM-1348): Enable once Partial GBK is supported in fn API.
pass
def test_pardo_side_inputs(self):
# TODO(BEAM-1348): Enable once side inputs are supported in fn API.
pass
def test_pardo_unfusable_side_inputs(self):
# TODO(BEAM-1348): Enable once side inputs are supported in fn API.
pass
def test_assert_that(self):
# TODO: figure out a way for fn_api_runner to parse and raise the
# underlying exception.
with self.assertRaisesRegexp(Exception, 'Failed assert'):
with self.create_pipeline() as p:
assert_that(p | beam.Create(['a', 'b']), equal_to(['a']))
# Inherits all tests from maptask_executor_runner.MapTaskExecutorRunner
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
unittest.main()
|
apache-2.0
|
JetBrains/resharper-unity
|
resharper/resharper-unity/src/Unity/Yaml/Psi/Search/UnityAnimationEventFindResults.cs
|
1533
|
using JetBrains.Annotations;
using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AnimationEventsUsages;
using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy.References;
using JetBrains.ReSharper.Psi;
namespace JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Search
{
public class UnityAnimationEventFindResults : UnityAssetFindResult
{
public UnityAnimationEventFindResults([NotNull] IPsiSourceFile sourceFile,
[NotNull] IDeclaredElement declaredElement,
[NotNull] AnimationUsage usage,
LocalReference owningElementLocation)
: base(sourceFile, declaredElement, owningElementLocation)
{
Usage = usage;
}
[NotNull]
public AnimationUsage Usage { get; }
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((UnityAnimationEventFindResults) obj);
}
private bool Equals([NotNull] UnityAnimationEventFindResults other)
{
return base.Equals(other) && Usage.Equals(other.Usage);
}
public override int GetHashCode()
{
unchecked
{
return (base.GetHashCode() * 397) ^ Usage.GetHashCode();
}
}
}
}
|
apache-2.0
|
stdlib-js/www
|
public/docs/api/latest/@stdlib/assert/is-collection/index.html
|
6258
|
<h1 id="iscollection">isCollection</h1><blockquote><p>Test if a value is a collection.</p></blockquote><section class="intro"><p>A collection is defined as either an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array"><code>Array</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>Typed Array</code></a>, or an array-like <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object"><code>Object</code></a> (excluding <code>strings</code> and <code>functions</code>).</p></section><section class="usage"><h2 id="usage">Usage</h2><pre><code class="hljs language-javascript"><span class="hljs-keyword">var</span> isCollection = <span class="hljs-built_in">require</span>( <span class="hljs-string">'@stdlib/assert/is-collection'</span> );
</code></pre><h4 id="iscollection-value-">isCollection( value )</h4><p>Tests if a value is a collection.</p><pre><code class="hljs language-javascript"><span class="hljs-keyword">var</span> bool = isCollection( [] );
<span class="hljs-comment">// returns true</span>
</code></pre></section><section class="examples"><h2 id="examples">Examples</h2><pre><code class="hljs language-javascript"><span class="hljs-keyword">var</span> <span class="hljs-built_in">Int8Array</span> = <span class="hljs-built_in">require</span>( <span class="hljs-string">'@stdlib/array/int8'</span> );
<span class="hljs-keyword">var</span> <span class="hljs-built_in">Uint8Array</span> = <span class="hljs-built_in">require</span>( <span class="hljs-string">'@stdlib/array/uint8'</span> );
<span class="hljs-keyword">var</span> <span class="hljs-built_in">Uint8ClampedArray</span> = <span class="hljs-built_in">require</span>( <span class="hljs-string">'@stdlib/array/uint8c'</span> );
<span class="hljs-keyword">var</span> <span class="hljs-built_in">Int16Array</span> = <span class="hljs-built_in">require</span>( <span class="hljs-string">'@stdlib/array/int16'</span> );
<span class="hljs-keyword">var</span> <span class="hljs-built_in">Uint16Array</span> = <span class="hljs-built_in">require</span>( <span class="hljs-string">'@stdlib/array/uint16'</span> );
<span class="hljs-keyword">var</span> <span class="hljs-built_in">Int32Array</span> = <span class="hljs-built_in">require</span>( <span class="hljs-string">'@stdlib/array/int32'</span> );
<span class="hljs-keyword">var</span> <span class="hljs-built_in">Uint32Array</span> = <span class="hljs-built_in">require</span>( <span class="hljs-string">'@stdlib/array/uint32'</span> );
<span class="hljs-keyword">var</span> <span class="hljs-built_in">Float32Array</span> = <span class="hljs-built_in">require</span>( <span class="hljs-string">'@stdlib/array/float32'</span> );
<span class="hljs-keyword">var</span> <span class="hljs-built_in">Float64Array</span> = <span class="hljs-built_in">require</span>( <span class="hljs-string">'@stdlib/array/float64'</span> );
<span class="hljs-keyword">var</span> isCollection = <span class="hljs-built_in">require</span>( <span class="hljs-string">'@stdlib/assert/is-collection'</span> );
<span class="hljs-keyword">var</span> bool = isCollection( [] );
<span class="hljs-comment">// returns true</span>
bool = isCollection( <span class="hljs-keyword">new</span> <span class="hljs-built_in">Float64Array</span>( <span class="hljs-number">10</span> ) );
<span class="hljs-comment">// returns true</span>
bool = isCollection( <span class="hljs-keyword">new</span> <span class="hljs-built_in">Float32Array</span>( <span class="hljs-number">10</span> ) );
<span class="hljs-comment">// returns true</span>
bool = isCollection( <span class="hljs-keyword">new</span> <span class="hljs-built_in">Int32Array</span>( <span class="hljs-number">10</span> ) );
<span class="hljs-comment">// returns true</span>
bool = isCollection( <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint32Array</span>( <span class="hljs-number">10</span> ) );
<span class="hljs-comment">// returns true</span>
bool = isCollection( <span class="hljs-keyword">new</span> <span class="hljs-built_in">Int16Array</span>( <span class="hljs-number">10</span> ) );
<span class="hljs-comment">// returns true</span>
bool = isCollection( <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint16Array</span>( <span class="hljs-number">10</span> ) );
<span class="hljs-comment">// returns true</span>
bool = isCollection( <span class="hljs-keyword">new</span> <span class="hljs-built_in">Int8Array</span>( <span class="hljs-number">10</span> ) );
<span class="hljs-comment">// returns true</span>
bool = isCollection( <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint8Array</span>( <span class="hljs-number">10</span> ) );
<span class="hljs-comment">// returns true</span>
bool = isCollection( <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint8ClampedArray</span>( <span class="hljs-number">10</span> ) );
<span class="hljs-comment">// returns true</span>
bool = isCollection( { <span class="hljs-string">'length'</span>: <span class="hljs-number">0</span> } );
<span class="hljs-comment">// returns true</span>
bool = isCollection( {} );
<span class="hljs-comment">// returns false</span>
bool = isCollection( <span class="hljs-string">'beep'</span> );
<span class="hljs-comment">// returns false</span>
bool = isCollection( isCollection );
<span class="hljs-comment">// returns false</span>
bool = isCollection( <span class="hljs-literal">null</span> );
<span class="hljs-comment">// returns false</span>
bool = isCollection( <span class="hljs-keyword">void</span> <span class="hljs-number">0</span> );
<span class="hljs-comment">// returns false</span>
bool = isCollection( <span class="hljs-number">3.14</span> );
<span class="hljs-comment">// returns false</span>
</code></pre></section><section class="related"><hr><h2 id="see-also">See Also</h2><ul><li><span class="package-name"><a href="/docs/api/latest/@stdlib/assert/is-array-like"><code>@stdlib/assert/is-array-like</code></a></span><span class="delimiter">: </span><span class="description">test if a value is array-like.</span></li></ul></section><section class="links"></section>
|
apache-2.0
|
TZClub/OMIPlatform
|
shopping-platfrom/src/main/webapp/resources/js/main.js
|
10332
|
(function ($) {
"use strict";
/*----------------------------
price-slider active
------------------------------ */
var range = $('#slider-range');
var amount = $('#amount');
range.slider({
range: true,
min: 2,
max: 300,
values: [ 2, 300 ],
slide: function( event, ui ) {
amount.val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
}
});
amount.val( "$" + range.slider( "values", 0 ) +
" - $" + range.slider( "values", 1 ) );
/*----------------------------
jQuery MeanMenu
------------------------------ */
jQuery('#mobile-menu-active').meanmenu();
/*----------------------
Carousel Activation
----------------------*/
$(".let_new_carasel").owlCarousel({
autoPlay: true,
slideSpeed:2000,
pagination:true,
navigation:true,
items : 1,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-caret-left'></i>","<i class='fa fa-caret-right'></i>"],
itemsDesktop : [1199,1],
itemsDesktopSmall : [980,1],
itemsTablet: [768,1],
itemsMobile : [767,1],
});
/*----------------------------
Tooltip
------------------------------ */
$('[data-toggle="tooltip"]').tooltip({
animated: 'fade',
placement: 'top',
container: 'body'
});
/*----------------------------
single portfolio activation
------------------------------ */
$(".sub_pix").owlCarousel({
autoPlay: true,
slideSpeed:2000,
pagination:true,
navigation:false,
items : 5,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1199,4],
itemsDesktopSmall : [980,3],
itemsTablet: [768,5],
itemsMobile : [767,3],
});
/*----------------------------
toggole active
------------------------------ */
$( ".all_catagories" ).on("click", function() {
$( ".cat_mega_start" ).slideToggle( "slow" );
});
$( ".showmore-items" ).on("click", function() {
$( ".cost-menu" ).slideToggle( "slow" );
});
/*----------------------
New Products Carousel Activation
----------------------*/
$(".whole_product").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 3,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1199,3],
itemsDesktopSmall : [980,3],
itemsTablet: [768,1],
itemsMobile : [767,1],
});
/*----------------------
Hot Deals Carousel Activation
----------------------*/
$(".new_cosmatic").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 1,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1199,1],
itemsDesktopSmall : [980,3],
itemsTablet: [768,2],
itemsMobile : [767,1],
});
/*---------------------
countdown
--------------------- */
$('[data-countdown]').each(function() {
var $this = $(this), finalDate = $(this).data('countdown');
$this.countdown(finalDate, function(event) {
$this.html(event.strftime('<span class="cdown days"><span class="time-count">%-D</span> <p>Days</p></span> <span class="cdown hour"><span class="time-count">%-H</span> <p>Hour</p></span> <span class="cdown minutes"><span class="time-count">%M</span> <p>Min</p></span> <span class="cdown second"> <span><span class="time-count">%S</span> <p>Sec</p></span>'));
});
});
/*----------------------
Products Catagory Carousel Activation
----------------------*/
$(".feature-carousel").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 4,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1199,3],
itemsDesktopSmall : [980,3],
itemsTablet: [768,2],
itemsMobile : [767,1],
});
/*----------------------------
Top Rate Carousel Activation
------------------------------ */
$(".all_ayntex").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 1,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1199,1],
itemsDesktopSmall : [980,3],
itemsTablet: [768,2],
itemsMobile : [767,1],
});
/*----------------------------
Featured Catagories Carousel Activation
------------------------------ */
$(".achard_all").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 5,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1199,4],
itemsDesktopSmall : [980,3],
itemsTablet: [768,4],
itemsMobile : [767,2
],
});
/*----------------------------
Blog Post Carousel Activation
------------------------------ */
$(".blog_carasel").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 3,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1199,2],
itemsDesktopSmall : [980,3],
itemsTablet: [768,2],
itemsMobile : [767,1],
});
/*----------------------------
Brand Logo Carousel Activation
------------------------------ */
$(".all_brand").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 6,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1199,4],
itemsDesktopSmall : [980,3],
itemsTablet: [768,2],
itemsMobile : [480,2],
});
/*----------------------
scrollUp
----------------------*/
$.scrollUp({
scrollText: '<i class="fa fa-angle-double-up"></i>',
easingType: 'linear',
scrollSpeed: 900,
animation: 'fade'
});
/*----------------------
New Products home-page-2 Carousel Activation
----------------------*/
$(".product_2").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 4,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1199,3],
itemsDesktopSmall : [980,4],
itemsTablet: [768,2],
itemsMobile : [767,1],
});
/*----------------------------
Blog Post home-page-2 Carousel Activation
------------------------------ */
$(".blog_new_carasel_2").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 2,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1199,2],
itemsDesktopSmall : [980,2],
itemsTablet: [768,1],
itemsMobile : [767,1],
});
/*----------------------------
Products Catagory-2 Carousel Activation
------------------------------ */
$(".feature-carousel-2").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 2,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1199,2],
itemsDesktopSmall : [980,3],
itemsTablet: [768,2],
itemsMobile : [767,1],
});
/*----------------------------
Blog Post home-page-3 Carousel Activation
------------------------------ */
$(".blog_carasel_5").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 4,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1199,4],
itemsDesktopSmall : [980,3],
itemsTablet: [768,2],
itemsMobile : [767,1],
});
/*-----------------------------
Category Menu toggle
-------------------------------*/
$('.expandable a').on('click', function() {
$(this).parent().find('.category-sub').toggleClass('submenu-active');
$(this).toggleClass('submenu-active');
return false;
});
/*----------------------------
MixItUp:
------------------------------ */
$('#Container') .mixItUp();
/*----------------------------
magnificPopup:
------------------------------ */
$('.magnify').magnificPopup({type:'image'});
/*-------------------------
Create an account toggle function
--------------------------*/
$( "#cbox" ).on("click", function() {
$( "#cbox_info" ).slideToggle(900);
});
$( '#showlogin, #showcoupon' ).on('click', function() {
$(this).parent().next().slideToggle(600);
});
/*-------------------------
accordion toggle function
--------------------------*/
$('.payment-accordion').find('.payment-accordion-toggle').on('click', function(){
//Expand or collapse this panel
$(this).next().slideToggle(500);
//Hide the other panels
$(".payment-content").not($(this).next()).slideUp(500);
});
/* -------------------------------------------------------
accordion active class for style
----------------------------------------------------------*/
$('.payment-accordion-toggle').on('click', function(event) {
$(this).siblings('.active').removeClass('active');
$(this).addClass('active');
event.preventDefault();
});
})(jQuery);
|
apache-2.0
|
eskatos/asadmin
|
asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/CreateJdbcConnectionPoolMojo.java
|
2248
|
/*
* Copyright (c) 2010, Christophe Souvignier.
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
import java.util.Iterator;
import java.util.Map;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.CreateJdbcConnectionPool;
/**
* @goal create-jdbc-connection-pool
*/
public class CreateJdbcConnectionPoolMojo
extends AbstractAsadminMojo
{
/**
* @parameter default-value="org.apache.derby.jdbc.ClientXADataSource"
* @required
*/
private String poolDataSource;
/**
* @parameter
* @required
*/
private String poolName;
/**
* @parameter default-value="javax.sql.XADataSource"
* @required
*/
private String restype;
/**
* @parameter
*/
private Map poolProperties;
@Override
protected AsAdminCmdList getAsCommandList()
throws MojoExecutionException, MojoFailureException
{
getLog().info( "Creating auth realm: " + poolName );
final AsAdminCmdList list = new AsAdminCmdList();
final CreateJdbcConnectionPool cmd = new CreateJdbcConnectionPool( poolName ).withDataSource( poolDataSource ).withRestype( restype );
if( poolProperties != null && !poolProperties.isEmpty() )
{
final Iterator it = poolProperties.keySet().iterator();
while( it.hasNext() )
{
final String key = (String) it.next();
cmd.addProperty( key, (String) poolProperties.get( key ) );
}
}
list.add( cmd );
return list;
}
}
|
apache-2.0
|
istio/istio.io
|
archive/v0.8/docs/tasks/traffic-management/version-migration.html
|
594
|
<!DOCTYPE html>
<html>
<head>
<title>Redirecting…</title>
<link rel="canonical" href="/v0.8/docs/tasks/traffic-management/traffic-shifting/">
<meta name="robots" content="noindex">
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="0; url=/v0.8/docs/tasks/traffic-management/traffic-shifting/">
</head>
<body>
<h1>Redirecting…</h1>
<a href="/v0.8/docs/tasks/traffic-management/traffic-shifting/">Click here if you are not redirected.</a>
</body>
</html>
|
apache-2.0
|
aws/aws-sdk-cpp
|
aws-cpp-sdk-imagebuilder/source/model/ComponentState.cpp
|
1432
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/imagebuilder/model/ComponentState.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace imagebuilder
{
namespace Model
{
ComponentState::ComponentState() :
m_status(ComponentStatus::NOT_SET),
m_statusHasBeenSet(false),
m_reasonHasBeenSet(false)
{
}
ComponentState::ComponentState(JsonView jsonValue) :
m_status(ComponentStatus::NOT_SET),
m_statusHasBeenSet(false),
m_reasonHasBeenSet(false)
{
*this = jsonValue;
}
ComponentState& ComponentState::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("status"))
{
m_status = ComponentStatusMapper::GetComponentStatusForName(jsonValue.GetString("status"));
m_statusHasBeenSet = true;
}
if(jsonValue.ValueExists("reason"))
{
m_reason = jsonValue.GetString("reason");
m_reasonHasBeenSet = true;
}
return *this;
}
JsonValue ComponentState::Jsonize() const
{
JsonValue payload;
if(m_statusHasBeenSet)
{
payload.WithString("status", ComponentStatusMapper::GetNameForComponentStatus(m_status));
}
if(m_reasonHasBeenSet)
{
payload.WithString("reason", m_reason);
}
return payload;
}
} // namespace Model
} // namespace imagebuilder
} // namespace Aws
|
apache-2.0
|
webanno/webanno
|
webanno-api-dao/src/main/java/de/tudarmstadt/ukp/clarin/webanno/api/dao/export/exporters/GuildelinesExporter.java
|
4420
|
/*
* Licensed to the Technische Universität Darmstadt under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The Technische Universität Darmstadt
* 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.
*
* 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 de.tudarmstadt.ukp.clarin.webanno.api.dao.export.exporters;
import static org.apache.commons.io.FileUtils.copyInputStreamToFile;
import static org.apache.commons.io.FileUtils.forceMkdir;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import de.tudarmstadt.ukp.clarin.webanno.api.ProjectService;
import de.tudarmstadt.ukp.clarin.webanno.api.export.ProjectExportRequest;
import de.tudarmstadt.ukp.clarin.webanno.api.export.ProjectExportTaskMonitor;
import de.tudarmstadt.ukp.clarin.webanno.api.export.ProjectExporter;
import de.tudarmstadt.ukp.clarin.webanno.api.export.ProjectImportRequest;
import de.tudarmstadt.ukp.clarin.webanno.export.model.ExportedProject;
import de.tudarmstadt.ukp.clarin.webanno.model.Project;
import de.tudarmstadt.ukp.clarin.webanno.support.ZipUtils;
@Component
public class GuildelinesExporter
implements ProjectExporter
{
public static final String GUIDELINE = "guideline";
private static final String GUIDELINES_FOLDER = "/" + GUIDELINE;
private final Logger log = LoggerFactory.getLogger(getClass());
private @Autowired ProjectService projectService;
/**
* Copy Project guidelines from the file system of this project to the export folder
*/
@Override
public void exportData(ProjectExportRequest aRequest, ProjectExportTaskMonitor aMonitor,
ExportedProject aExProject, File aStage)
throws Exception
{
File guidelineDir = new File(aStage + GUIDELINES_FOLDER);
FileUtils.forceMkdir(guidelineDir);
File annotationGuidlines = projectService.getGuidelinesFolder(aRequest.getProject());
if (annotationGuidlines.exists()) {
for (File annotationGuideline : annotationGuidlines.listFiles()) {
FileUtils.copyFileToDirectory(annotationGuideline, guidelineDir);
}
}
}
/**
* Copy guidelines from the exported project
*
* @param aZip
* the ZIP file.
* @param aProject
* the project.
* @throws IOException
* if an I/O error occurs.
*/
@Override
public void importData(ProjectImportRequest aRequest, Project aProject,
ExportedProject aExProject, ZipFile aZip)
throws Exception
{
for (Enumeration<? extends ZipEntry> zipEnumerate = aZip.entries(); zipEnumerate
.hasMoreElements();) {
ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();
// Strip leading "/" that we had in ZIP files prior to 2.0.8 (bug #985)
String entryName = ZipUtils.normalizeEntryName(entry);
if (entryName.startsWith(GUIDELINE + "/")) {
String fileName = FilenameUtils.getName(entry.getName());
if (fileName.trim().isEmpty()) {
continue;
}
File guidelineDir = projectService.getGuidelinesFolder(aProject);
forceMkdir(guidelineDir);
copyInputStreamToFile(aZip.getInputStream(entry), new File(guidelineDir, fileName));
log.info("Imported guideline [" + fileName + "] for project [" + aProject.getName()
+ "] with id [" + aProject.getId() + "]");
}
}
}
}
|
apache-2.0
|
nickgaski/docs
|
services/ObjectStorage/nl/zh/TW/os_remove_access.md
|
1726
|
---
copyright:
years: 2014, 2017
lastupdated: "2017-02-10"
---
{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:codeblock: .codeblock}
{:screen: .screen}
{:pre: .pre}
# 移除存取權
您可以利用存取控制清單,移除容器或物件的存取權。
{: shortdesc}
若要從容器中移除讀取 ACL,請執行下列其中一個指令。
* Swift 指令:
```
swift post <container_name> --read-acl ""
```
{: pre}
* cURL 指令:
```
curl -i <OS_STORAGE_URL> -X POST -H "Content-Length: 0" -H "X-Container-Read: " -H "X-Auth-Token: <OS_AUTH_TOKEN>"
```
{: pre}
若要從容器中移除寫入 ACL,請執行下列其中一個指令。
* Swift 指令:
```
swift post <container_name> --write-acl ""
```
{: pre}
* cURL 指令:
```
curl -i <OS_STORAGE_URL> -X POST -H "Content-Length: 0" -H "X-Container-Write: " -H "X-Auth-Token: <OS_AUTH_TOKEN>"
```
{: pre}
若要驗證您已移除 ACL,請執行下列其中一個指令。
* Swift 指令:
```
swift stat <container_name>
```
{: pre}
* 下列範例輸出將「讀取 ACL」及「寫入 ACL」顯示為空白,這表示已移除存取權。
```
Account: AUTH_c727d7e248b448f6b268f31a1bd8691e
Container: Test
Objects: 1
Bytes: 31512
Read ACL:
Write ACL:
Sync To:
Sync Key:
Accept-Ranges: bytes
X-Storage-Policy: standard
X-Timestamp: 1462818314.11220
X-Trans-Id: txf04968bc9ef8431982b77-005772e34b
Content-Type: text/plain; charset=utf-8
```
{: screen}
* cURL 指令:
```
curl -i <OS_STORAGE_URL> -I -H "X-Auth-Token: <OS_AUTH_TOKEN>"
```
{: pre}
|
apache-2.0
|
hammerlab/varcode
|
varcode/effects/__init__.py
|
2401
|
# Copyright (c) 2016. Mount Sinai School of Medicine
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function, division, absolute_import
from .effect_collection import EffectCollection
from .effect_ordering import (
effect_priority,
top_priority_effect,
)
from .effect_prediction import (
predict_variant_effects,
predict_variant_effect_on_transcript,
predict_variant_effect_on_transcript_or_failure,
)
from .effect_classes import (
MutationEffect,
TranscriptMutationEffect,
NonsilentCodingMutation,
Failure,
IncompleteTranscript,
Intergenic,
Intragenic,
NoncodingTranscript,
Intronic,
ThreePrimeUTR,
FivePrimeUTR,
Silent,
Substitution,
Insertion,
Deletion,
ComplexSubstitution,
AlternateStartCodon,
IntronicSpliceSite,
ExonicSpliceSite,
StopLoss,
SpliceDonor,
SpliceAcceptor,
PrematureStop,
FrameShiftTruncation,
StartLoss,
FrameShift,
ExonLoss,
)
__all__ = [
"EffectCollection",
# effect ordering
"effect_priority",
"top_priority_effect",
# prediction functions
"predict_variant_effects",
"predict_variant_effect_on_transcript",
"predict_variant_effect_on_transcript_or_failure",
# effect classes
"MutationEffect",
"TranscriptMutationEffect",
"Failure",
"IncompleteTranscript",
"Intergenic",
"Intragenic",
"IncompleteTranscript",
"NoncodingTranscript",
"ThreePrimeUTR",
"FivePrimeUTR",
"Intronic",
"Silent",
"NonsilentCodingMutation",
"Substitution",
"Insertion",
"Deletion",
"ComplexSubstitution",
"AlternateStartCodon",
"IntronicSpliceSite",
"ExonicSpliceSite",
"StopLoss",
"SpliceDonor",
"SpliceAcceptor",
"PrematureStop",
"FrameShiftTruncation",
"StartLoss",
"FrameShift",
"ExonLoss",
]
|
apache-2.0
|
Moonbloom/Boast
|
README.md
|
1645
|
# Boast
Library to easily create and modify Toast messages.
## Overview
**Boast** is a class that can be used by Android developers that feel the need for an **alternative to [Toast](http://developer.android.com/reference/android/widget/Toast.html)**.
A Boast will be displayed at the position of standard Toasts.
You can line up multiple Boasts for display, that will be shown one after another, modify colors, text, and even add an image.
You can check some features in the Boast Demo application that is also posted here in this repository.
### Current version: 0.2.5
## Usage
The API is made even more simple than the Toast API (No need to call .show() on Boasts):
Create a Boast for any CharSequence:
Boast.makeText(Context, CharSequence);
Create a Boast for any CharSequence with a specific BStyle:
Boast.makeText(Context, CharSequence, BStyle);
Create a Boast with a String from your application's resources:
Boast.makeText(Context, int);
Create a Boast with a String from your application's resources and a specific BStyle:
Boast.makeText(Context, int, BStyle);
## Basic Examples
Currently there are 4 different BStyles you can use out of the box (Or you can create your own, be creative!):
- **BStyle.OK** (Green)
- **BStyle.MESSAGE** (Blue)
- **BStyle.CAUTION** (Amber)
- **BStyle.ALERT** (Red)
In general you can modify:
- Display duration
- Padding settings
- Text size
- Custom Views
- Displayed image
- Image size
## Developer
- [Kasper H�bner Liholm] (https://www.linkedin.com/profile/view?id=330373856)
## License
- [Apache Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html)
|
apache-2.0
|
imangit/Advertise
|
Advertise/Advertise.Utility/Persians/PersianYeKeInterceptor.cs
|
2025
|
using System.Data.Common;
using System.Data.Entity.Infrastructure.Interception;
namespace Advertise.Utility.Persians
{
/// <summary>
/// </summary>
public class PersianYeKeInterceptor : IDbCommandInterceptor
{
/// <summary>
/// </summary>
/// <param name="command"></param>
/// <param name="interceptionContext"></param>
public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
command.ApplyCorrectYeKe();
}
/// <summary>
/// </summary>
/// <param name="command"></param>
/// <param name="interceptionContext"></param>
public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
}
/// <summary>
/// </summary>
/// <param name="command"></param>
/// <param name="interceptionContext"></param>
public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
command.ApplyCorrectYeKe();
}
/// <summary>
/// </summary>
/// <param name="command"></param>
/// <param name="interceptionContext"></param>
public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
}
/// <summary>
/// </summary>
/// <param name="command"></param>
/// <param name="interceptionContext"></param>
public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
}
/// <summary>
/// </summary>
/// <param name="command"></param>
/// <param name="interceptionContext"></param>
public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
command.ApplyCorrectYeKe();
}
}
}
|
apache-2.0
|
anirudh24seven/apps-android-wikipedia
|
app/src/main/java/org/wikipedia/edit/Edit.java
|
1491
|
package org.wikipedia.edit;
import android.support.annotation.Nullable;
import org.wikipedia.dataclient.mwapi.MwPostResponse;
class Edit extends MwPostResponse {
@SuppressWarnings("unused,") @Nullable private Result edit;
@Nullable Result edit() {
return edit;
}
boolean hasEditResult() {
return edit != null;
}
class Result {
@SuppressWarnings("unused") @Nullable private String result;
@SuppressWarnings("unused") private int newrevid;
@SuppressWarnings("unused") @Nullable private Captcha captcha;
@SuppressWarnings("unused") @Nullable private String code;
@SuppressWarnings("unused") @Nullable private String spamblacklist;
@Nullable String status() {
return result;
}
int newRevId() {
return newrevid;
}
@Nullable String captchaId() {
return captcha == null ? null : captcha.id();
}
boolean hasErrorCode() {
return code != null;
}
boolean hasCaptchaResponse() {
return captcha != null;
}
@Nullable String spamblacklist() {
return spamblacklist;
}
boolean hasSpamBlacklistResponse() {
return spamblacklist != null;
}
}
private static class Captcha {
@SuppressWarnings("unused") @Nullable private String id;
@Nullable String id() {
return id;
}
}
}
|
apache-2.0
|
gbl08ma/underlx
|
app/src/main/assets/help/pt/faq-underlx-5.html
|
251
|
<p><b>Como é calculado o tempo de espera?</b><p>
<p>Resposta...</p>
<p><a href="help:faq-underlx-2">Dá para pôr links para outras questões e páginas da ajuda</a></p>
<p><a href="http://sapo.pt">Dá para pôr links para sites externos</a></p>
|
apache-2.0
|
scalatest/scalatest-website
|
public/scaladoc/2.1.5/org/scalatest/Matchers$AWord.html
|
28012
|
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>AWord - ScalaTest 2.1.5 - org.scalatest.Matchers.AWord</title>
<meta name="description" content="AWord - ScalaTest 2.1.5 - org.scalatest.Matchers.AWord" />
<meta name="keywords" content="AWord ScalaTest 2.1.5 org.scalatest.Matchers.AWord" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />
<script type="text/javascript" src="../../lib/jquery.js" id="jquery-js"></script>
<script type="text/javascript" src="../../lib/jquery-ui.js"></script>
<script type="text/javascript" src="../../lib/template.js"></script>
<script type="text/javascript" src="../../lib/tools.tooltip.js"></script>
<script type="text/javascript">
if(top === self) {
var url = '../../index.html';
var hash = 'org.scalatest.Matchers$AWord';
var anchor = window.location.hash;
var anchor_opt = '';
if (anchor.length >= 1)
anchor_opt = '@' + anchor.substring(1);
window.location.href = url + '#' + hash + anchor_opt;
}
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-71294502-3', 'auto');
ga('send', 'pageview');
</script>
</head>
<body class="type">
<!-- Top of doc.scalatest.org [javascript] -->
<script type="text/javascript">
var rnd = window.rnd || Math.floor(Math.random()*10e6);
var pid204546 = window.pid204546 || rnd;
var plc204546 = window.plc204546 || 0;
var abkw = window.abkw || '';
var absrc = 'http://ab167933.adbutler-ikon.com/adserve/;ID=167933;size=468x60;setID=204546;type=js;sw='+screen.width+';sh='+screen.height+';spr='+window.devicePixelRatio+';kw='+abkw+';pid='+pid204546+';place='+(plc204546++)+';rnd='+rnd+';click=CLICK_MACRO_PLACEHOLDER';
document.write('<scr'+'ipt src="'+absrc+'" type="text/javascript"></scr'+'ipt>');
</script>
<div id="definition">
<img src="../../lib/class_big.png" />
<p id="owner"><a href="../package.html" class="extype" name="org">org</a>.<a href="package.html" class="extype" name="org.scalatest">scalatest</a>.<a href="Matchers.html" class="extype" name="org.scalatest.Matchers">Matchers</a></p>
<h1>AWord</h1>
</div>
<h4 id="signature" class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">class</span>
</span>
<span class="symbol">
<span class="name">AWord</span><span class="result"> extends <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
</h4>
<div id="comment" class="fullcommenttop"><div class="comment cmt"><p>This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
the matchers DSL.
</p></div><dl class="attributes block"> <dt>Source</dt><dd><a href="https://github.com/scalatest/scalatest/tree/release-2.1.5-for-scala-2.10/src/main/scala/org/scalatest/Matchers.scala" target="_blank">Matchers.scala</a></dd></dl><div class="toggleContainer block">
<span class="toggle">Linear Supertypes</span>
<div class="superTypes hiddenContent"><span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div>
</div></div>
<div id="mbrsel">
<div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div>
<div id="order">
<span class="filtertype">Ordering</span>
<ol>
<li class="alpha in"><span>Alphabetic</span></li>
<li class="inherit out"><span>By inheritance</span></li>
</ol>
</div>
<div id="ancestors">
<span class="filtertype">Inherited<br />
</span>
<ol id="linearization">
<li class="in" name="org.scalatest.Matchers.AWord"><span>AWord</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li>
</ol>
</div><div id="ancestors">
<span class="filtertype"></span>
<ol>
<li class="hideall out"><span>Hide All</span></li>
<li class="showall in"><span>Show all</span></li>
</ol>
<a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a>
</div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
<div id="template">
<div id="allMembers">
<div id="constructors" class="members">
<h3>Instance Constructors</h3>
<ol><li name="org.scalatest.Matchers.AWord#<init>" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="<init>():Matchers.this.AWord"></a>
<a id="<init>:AWord"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">new</span>
</span>
<span class="symbol">
<span class="name">AWord</span><span class="params">()</span>
</span>
</h4>
</li></ol>
</div>
<div id="values" class="values members">
<h3>Value Members</h3>
<ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:AnyRef):Boolean"></a>
<a id="!=(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.Any#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:Any):Boolean"></a>
<a id="!=(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="##():Int"></a>
<a id="##():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:AnyRef):Boolean"></a>
<a id="==(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.Any#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:Any):Boolean"></a>
<a id="==(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="org.scalatest.Matchers.AWord#apply" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="apply[T](aMatcher:org.scalatest.matchers.AMatcher[T]):org.scalatest.words.ResultOfAWordToAMatcherApplication[T]"></a>
<a id="apply[T](AMatcher[T]):ResultOfAWordToAMatcherApplication[T]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">apply</span><span class="tparams">[<span name="T">T</span>]</span><span class="params">(<span name="aMatcher">aMatcher: <span class="extype" name="org.scalatest.matchers.AMatcher">AMatcher</span>[<span class="extype" name="org.scalatest.Matchers.AWord.apply.T">T</span>]</span>)</span><span class="result">: <a href="words/ResultOfAWordToAMatcherApplication.html" class="extype" name="org.scalatest.words.ResultOfAWordToAMatcherApplication">ResultOfAWordToAMatcherApplication</a>[<span class="extype" name="org.scalatest.Matchers.AWord.apply.T">T</span>]</span>
</span>
</h4>
<p class="shortcomment cmt">This method enables the following syntax, where, <code>positiveNumber</code> is an <code>AMatcher[Book]</code>:</p><div class="fullcomment"><div class="comment cmt"><p>This method enables the following syntax, where, <code>positiveNumber</code> is an <code>AMatcher[Book]</code>:</p><p><pre class="stHighlighted">
result should not be a (positiveNumber)
^
</pre>
</p></div></div>
</li><li name="org.scalatest.Matchers.AWord#apply" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="apply[T](beTrueMatcher:org.scalatest.matchers.BePropertyMatcher[T]):org.scalatest.words.ResultOfAWordToBePropertyMatcherApplication[T]"></a>
<a id="apply[T](BePropertyMatcher[T]):ResultOfAWordToBePropertyMatcherApplication[T]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">apply</span><span class="tparams">[<span name="T">T</span>]</span><span class="params">(<span name="beTrueMatcher">beTrueMatcher: <a href="matchers/BePropertyMatcher.html" class="extype" name="org.scalatest.matchers.BePropertyMatcher">BePropertyMatcher</a>[<span class="extype" name="org.scalatest.Matchers.AWord.apply.T">T</span>]</span>)</span><span class="result">: <a href="words/ResultOfAWordToBePropertyMatcherApplication.html" class="extype" name="org.scalatest.words.ResultOfAWordToBePropertyMatcherApplication">ResultOfAWordToBePropertyMatcherApplication</a>[<span class="extype" name="org.scalatest.Matchers.AWord.apply.T">T</span>]</span>
</span>
</h4>
<p class="shortcomment cmt">This method enables the following syntax, where, for example, <code>badBook</code> is of type <code>Book</code> and <code>goodRead</code>
is a <code>BePropertyMatcher[Book]</code>:</p><div class="fullcomment"><div class="comment cmt"><p>This method enables the following syntax, where, for example, <code>badBook</code> is of type <code>Book</code> and <code>goodRead</code>
is a <code>BePropertyMatcher[Book]</code>:</p><p><pre class="stHighlighted">
badBook should not be a (goodRead)
^
</pre>
</p></div></div>
</li><li name="org.scalatest.Matchers.AWord#apply" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="apply(symbol:Symbol):org.scalatest.words.ResultOfAWordToSymbolApplication"></a>
<a id="apply(Symbol):ResultOfAWordToSymbolApplication"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">apply</span><span class="params">(<span name="symbol">symbol: <span class="extype" name="scala.Symbol">Symbol</span></span>)</span><span class="result">: <a href="words/ResultOfAWordToSymbolApplication.html" class="extype" name="org.scalatest.words.ResultOfAWordToSymbolApplication">ResultOfAWordToSymbolApplication</a></span>
</span>
</h4>
<p class="shortcomment cmt">This method enables the following syntax:</p><div class="fullcomment"><div class="comment cmt"><p>This method enables the following syntax:</p><p><pre class="stHighlighted">
badBook should not be a (<span class="stQuotedString">'goodRead</span>)
^
</pre>
</p></div></div>
</li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="asInstanceOf[T0]:T0"></a>
<a id="asInstanceOf[T0]:T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="clone():Object"></a>
<a id="clone():AnyRef"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="eq(x$1:AnyRef):Boolean"></a>
<a id="eq(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="equals(x$1:Any):Boolean"></a>
<a id="equals(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="finalize():Unit"></a>
<a id="finalize():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getClass():Class[_]"></a>
<a id="getClass():Class[_]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="hashCode():Int"></a>
<a id="hashCode():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isInstanceOf[T0]:Boolean"></a>
<a id="isInstanceOf[T0]:Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ne(x$1:AnyRef):Boolean"></a>
<a id="ne(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notify():Unit"></a>
<a id="notify():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notifyAll():Unit"></a>
<a id="notifyAll():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="synchronized[T0](x$1:=>T0):T0"></a>
<a id="synchronized[T0](⇒T0):T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="org.scalatest.Matchers.AWord#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="toString():String"></a>
<a id="toString():String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Predef.String">String</span></span>
</span>
</h4>
<p class="shortcomment cmt">Overrides to return pretty toString.</p><div class="fullcomment"><div class="comment cmt"><p>Overrides to return pretty toString.
</p></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>"a"
</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="org.scalatest.Matchers.AWord">AWord</a> → AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait():Unit"></a>
<a id="wait():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long,x$2:Int):Unit"></a>
<a id="wait(Long,Int):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long):Unit"></a>
<a id="wait(Long):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">()</span>
</dd></dl></div>
</li></ol>
</div>
</div>
<div id="inheritedMembers">
<div class="parent" name="scala.AnyRef">
<h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3>
</div><div class="parent" name="scala.Any">
<h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3>
</div>
</div>
<div id="groupedMembers">
<div class="group" name="Ungrouped">
<h3>Ungrouped</h3>
</div>
</div>
</div>
<div id="tooltip"></div>
<div id="footer"> </div>
</body>
</html>
|
apache-2.0
|
jitendraag/webpack-2-examples
|
example2/input.js
|
99
|
require('./second.js');
var i = 0;
console.log('Hello Webpack!');
console.log('Webpack is cool.');
|
apache-2.0
|
dotph/registry
|
features/services/contact_service.rb
|
6724
|
CONTACT_HANDLE = 'contact'
NEW_CONTACT_HANDLE = 'new_contact'
OTHER_CONTACT_HANDLE = 'other_contact'
BLANK_CONTACT_HANDLE = ''
NON_EXISTING_CONTACT_HANDLE = 'non_existing'
def contact_does_not_exist handle = CONTACT_HANDLE
contact = Contact.find_by(handle: handle)
contact.delete if contact
end
def contact_exists handle = CONTACT_HANDLE, under: nil
contact_does_not_exist handle
other_partner = under
partner = other_partner ? Partner.find_by(name: under) : @current_partner
create :contact, partner: partner, handle: handle
end
def other_contact_exists
contact_exists OTHER_CONTACT_HANDLE
end
def create_contact with: { partner: nil, json_request: nil }
params = with
json_request ||= { handle: CONTACT_HANDLE }
json_request[:partner] = NON_ADMIN_PARTNER if @current_user.admin?
json_request[:partner] = params[:partner] if params[:partner]
json_request = params[:json_request] if params[:json_request]
post contacts_url, json_request
end
def update_contact with: { handle: nil, partner: nil }
params = with
json_request = {
name: 'new_name',
organization: 'new_organization',
street: 'new_street',
street2: 'new_street2',
street3: 'new_street3',
city: 'new_city',
state: 'new_state',
postal_code: 'new_postal_code',
country_code: 'new_country',
local_name: 'New local name',
local_organization: 'New local organization',
local_street: 'New local street',
local_street2: 'New local street 2',
local_street3: 'New local street 3',
local_city: 'New local city',
local_state: 'New local state',
local_postal_code: 'New local postal code',
local_country_code: 'New local country code',
voice: 'new_phone',
voice_ext: '1234',
fax: 'new_fax',
fax_ext: '1234',
email: '[email protected]',
}
json_request[:handle] = params[:handle] if params[:handle]
json_request[:partner] = params[:partner] if params[:partner]
patch contact_path(CONTACT_HANDLE), json_request
end
def assert_contact_created
assert_response_status_must_be_created
expected_response = {
handle: CONTACT_HANDLE,
name: nil,
organization: nil,
street: nil,
street2: nil,
street3: nil,
city: nil,
state: nil,
postal_code: nil,
country_code: nil,
local_name: nil,
local_organization: nil,
local_street: nil,
local_street2: nil,
local_street3: nil,
local_city: nil,
local_state: nil,
local_postal_code: nil,
local_country_code: nil,
voice: nil,
voice_ext: nil,
fax: nil,
fax_ext: nil,
email: nil,
}
json_response.must_equal expected_response
Contact.find_by(handle: CONTACT_HANDLE).wont_be_nil
end
def assert_create_contact_history_created
assert_contact_history_created
end
def assert_update_contact_history_created
assert_contact_history_created count: 2
end
def assert_contact_history_created count: 1
contact = Contact.find_by(handle: CONTACT_HANDLE)
contact.contact_histories.count.must_equal count
assert_contact_history contact.contact_histories.last, contact
end
def assert_contact_history contact_history, contact
contact_history.handle.must_equal contact.handle
contact_history.partner.must_equal contact.partner
contact_history.name.must_equal contact.name
contact_history.organization.must_equal contact.organization
contact_history.street.must_equal contact.street
contact_history.street2.must_equal contact.street2
contact_history.street3.must_equal contact.street3
contact_history.city.must_equal contact.city
contact_history.state.must_equal contact.state
contact_history.postal_code.must_equal contact.postal_code
contact_history.country_code.must_equal contact.country_code
contact_history.local_name.must_equal contact.local_name
contact_history.local_organization.must_equal contact.local_organization
contact_history.local_street.must_equal contact.local_street
contact_history.local_street2.must_equal contact.local_street2
contact_history.local_street3.must_equal contact.local_street3
contact_history.local_city.must_equal contact.local_city
contact_history.local_state.must_equal contact.local_state
contact_history.local_postal_code.must_equal contact.local_postal_code
contact_history.local_country_code.must_equal contact.local_country_code
contact_history.voice.must_equal contact.voice
contact_history.voice_ext.must_equal contact.voice_ext
contact_history.fax.must_equal contact.fax
contact_history.fax_ext.must_equal contact.fax_ext
contact_history.email.must_equal contact.email
end
def assert_contact_updated
assert_response_status_must_be_ok
expected_response = {
handle: CONTACT_HANDLE,
name: 'new_name',
organization: 'new_organization',
street: 'new_street',
street2: 'new_street2',
street3: 'new_street3',
city: 'new_city',
state: 'new_state',
postal_code: 'new_postal_code',
country_code: 'new_country',
local_name: 'New local name',
local_organization: 'New local organization',
local_street: 'New local street',
local_street2: 'New local street 2',
local_street3: 'New local street 3',
local_city: 'New local city',
local_state: 'New local state',
local_postal_code: 'New local postal code',
local_country_code: 'New local country code',
voice: 'new_phone',
voice_ext: '1234',
fax: 'new_fax',
fax_ext: '1234',
email: '[email protected]'
}
json_response.must_equal expected_response
end
def assert_contacts_displayed
assert_response_status_must_be_ok
json_response.length.must_equal 2
json_response.must_equal contacts_response
end
def assert_no_contacts_displayed
assert_response_status_must_be_ok
json_response.length.must_equal 0
end
def view_contacts
get contacts_path
end
def contacts_response
[
{:handle=>"contact", :name=>nil, :organization=>nil, :street=>nil, :street2=>nil, :street3=>nil, :city=>nil, :state=>nil, :postal_code=>nil, :country_code=>nil, :local_name=>nil, :local_organization=>nil, :local_street=>nil, :local_street2=>nil, :local_street3=>nil, :local_city=>nil, :local_state=>nil, :local_postal_code=>nil, :local_country_code=>nil, :voice=>nil, :voice_ext=>nil, :fax=>nil, :fax_ext=>nil, :email=>nil},
{:handle=>"other_contact", :name=>nil, :organization=>nil, :street=>nil, :street2=>nil, :street3=>nil, :city=>nil, :state=>nil, :postal_code=>nil, :country_code=>nil, :local_name=>nil, :local_organization=>nil, :local_street=>nil, :local_street2=>nil, :local_street3=>nil, :local_city=>nil, :local_state=>nil, :local_postal_code=>nil, :local_country_code=>nil, :voice=>nil, :voice_ext=>nil, :fax=>nil, :fax_ext=>nil, :email=>nil}
]
end
|
apache-2.0
|
dbflute-test/dbflute-test-active-dockside
|
src/main/java/org/docksidestage/dockside/dbflute/bsbhv/pmbean/BsPurchaseMaxPriceMemberPmb.java
|
9658
|
/*
* Copyright 2014-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.docksidestage.dockside.dbflute.bsbhv.pmbean;
import java.util.*;
import org.dbflute.outsidesql.paging.SimplePagingBean;
import org.dbflute.outsidesql.typed.*;
import org.dbflute.jdbc.*;
import org.dbflute.cbean.coption.LikeSearchOption;
import org.dbflute.outsidesql.PmbCustodial;
import org.dbflute.util.DfTypeUtil;
import org.docksidestage.dockside.dbflute.allcommon.*;
import org.docksidestage.dockside.dbflute.exbhv.*;
import org.docksidestage.dockside.dbflute.exentity.customize.*;
/**
* The base class for typed parameter-bean of PurchaseMaxPriceMember. <br>
* This is related to "<span style="color: #AD4747">selectPurchaseMaxPriceMember</span>" on MemberBhv.
* @author DBFlute(AutoGenerator)
*/
public class BsPurchaseMaxPriceMemberPmb extends SimplePagingBean implements EntityHandlingPmb<MemberBhv, PurchaseMaxPriceMember>, ManualPagingHandlingPmb<MemberBhv, PurchaseMaxPriceMember>, FetchBean {
// ===================================================================================
// Attribute
// =========
/** The parameter of memberId. */
protected Integer _memberId;
/** The parameter of memberNameList:likePrefix. */
protected List<String> _memberNameList;
/** The option of like-search for memberNameList. */
protected LikeSearchOption _memberNameListInternalLikeSearchOption;
/** The parameter of memberStatusCodeList:cls(MemberStatus). */
protected List<org.docksidestage.dockside.dbflute.allcommon.CDef.MemberStatus> _memberStatusCodeList;
/** The time-zone for filtering e.g. from-to. (NullAllowed: if null, default zone) */
protected TimeZone _timeZone;
// ===================================================================================
// Constructor
// ===========
/**
* Constructor for the typed parameter-bean of PurchaseMaxPriceMember. <br>
* This is related to "<span style="color: #AD4747">selectPurchaseMaxPriceMember</span>" on MemberBhv.
*/
public BsPurchaseMaxPriceMemberPmb() {
if (DBFluteConfig.getInstance().isPagingCountLater()) {
enablePagingCountLater();
}
}
// ===================================================================================
// Typed Implementation
// ====================
/**
* {@inheritDoc}
*/
public String getOutsideSqlPath() { return "selectPurchaseMaxPriceMember"; }
/**
* Get the type of an entity for result. (implementation)
* @return The type instance of an entity, customize entity. (NotNull)
*/
public Class<PurchaseMaxPriceMember> getEntityType() { return PurchaseMaxPriceMember.class; }
// ===================================================================================
// Assist Helper
// =============
// -----------------------------------------------------
// String
// ------
protected String filterStringParameter(String value) { return isEmptyStringParameterAllowed() ? value : convertEmptyToNull(value); }
protected boolean isEmptyStringParameterAllowed() { return DBFluteConfig.getInstance().isEmptyStringParameterAllowed(); }
protected String convertEmptyToNull(String value) { return PmbCustodial.convertEmptyToNull(value); }
protected void assertLikeSearchOptionValid(String name, LikeSearchOption option) { PmbCustodial.assertLikeSearchOptionValid(name, option); }
// -----------------------------------------------------
// Date
// ----
protected Date toUtilDate(Object date) { return PmbCustodial.toUtilDate(date, _timeZone); }
protected <DATE> DATE toLocalDate(Date date, Class<DATE> localType) { return PmbCustodial.toLocalDate(date, localType, chooseRealTimeZone()); }
protected TimeZone chooseRealTimeZone() { return PmbCustodial.chooseRealTimeZone(_timeZone); }
/**
* Set time-zone, basically for LocalDate conversion. <br>
* Normally you don't need to set this, you can adjust other ways. <br>
* (DBFlute system's time-zone is used as default)
* @param timeZone The time-zone for filtering. (NullAllowed: if null, default zone)
*/
public void zone(TimeZone timeZone) { _timeZone = timeZone; }
// -----------------------------------------------------
// by Option Handling
// ------------------
// might be called by option handling
protected <NUMBER extends Number> NUMBER toNumber(Object obj, Class<NUMBER> type) { return PmbCustodial.toNumber(obj, type); }
protected Boolean toBoolean(Object obj) { return PmbCustodial.toBoolean(obj); }
@SuppressWarnings("unchecked")
protected <ELEMENT> ArrayList<ELEMENT> newArrayList(ELEMENT... elements) { return PmbCustodial.newArrayList(elements); }
// ===================================================================================
// Basic Override
// ==============
/**
* @return The display string of all parameters. (NotNull)
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(DfTypeUtil.toClassTitle(this)).append(":");
sb.append(xbuildColumnString());
return sb.toString();
}
protected String xbuildColumnString() {
final String dm = ", ";
final StringBuilder sb = new StringBuilder();
sb.append(dm).append(_memberId);
sb.append(dm).append(_memberNameList);
sb.append(dm).append(_memberStatusCodeList);
if (sb.length() > 0) { sb.delete(0, dm.length()); }
sb.insert(0, "{").append("}");
return sb.toString();
}
// ===================================================================================
// Accessor
// ========
/**
* [get] memberId <br>
* // not required / used as equal
* @return The value of memberId. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public Integer getMemberId() {
return _memberId;
}
/**
* [set] memberId <br>
* // not required / used as equal
* @param memberId The value of memberId. (NullAllowed)
*/
public void setMemberId(Integer memberId) {
_memberId = memberId;
}
/**
* [get] memberNameList:likePrefix <br>
* // list of prefix keyword
* @return The value of memberNameList. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public List<String> getMemberNameList() {
return _memberNameList;
}
/**
* [set as prefixSearch] memberNameList:likePrefix <br>
* // list of prefix keyword
* @param memberNameList The value of memberNameList. (NullAllowed)
*/
public void setMemberNameList_PrefixSearch(List<String> memberNameList) {
_memberNameList = memberNameList;
_memberNameListInternalLikeSearchOption = new LikeSearchOption().likePrefix();
}
/**
* Get the internal option of likeSearch for memberNameList. {Internal Method: Don't invoke this}
* @return The internal option of likeSearch for memberNameList. (NullAllowed)
*/
public LikeSearchOption getMemberNameListInternalLikeSearchOption() {
return _memberNameListInternalLikeSearchOption;
}
/**
* [get] memberStatusCodeList:cls(MemberStatus) <br>
* @return The value of memberStatusCodeList. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public List<org.docksidestage.dockside.dbflute.allcommon.CDef.MemberStatus> getMemberStatusCodeList() {
return _memberStatusCodeList;
}
/**
* [set] memberStatusCodeList:cls(MemberStatus) <br>
* @param memberStatusCodeList The value of memberStatusCodeList. (NullAllowed)
*/
public void setMemberStatusCodeList(List<org.docksidestage.dockside.dbflute.allcommon.CDef.MemberStatus> memberStatusCodeList) {
_memberStatusCodeList = memberStatusCodeList;
}
}
|
apache-2.0
|
aNNiMON/Lightweight-Stream-API
|
stream/src/test/java/com/annimon/stream/longstreamtests/SumTest.java
|
393
|
package com.annimon.stream.longstreamtests;
import com.annimon.stream.LongStream;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public final class SumTest {
@Test
public void testSum() {
assertThat(LongStream.of(100, 20, 3).sum(), is(123L));
assertThat(LongStream.empty().sum(), is(0L));
}
}
|
apache-2.0
|
Deutsche-Digitale-Bibliothek/ddb-backend
|
CoreServices/src/main/java/de/fhg/iais/cortex/services/institution/Institution.java
|
7623
|
package de.fhg.iais.cortex.services.institution;
import java.util.LinkedList;
import java.util.List;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
import org.codehaus.jackson.map.annotate.JsonSerialize;
@JsonPropertyOrder({
"id", "name", "sector", "latitude", "longitude", "locationDisplayName", "hasItems", "numberOfItems", "children", "level", "detailViewUri"
})
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Institution {
@JsonProperty("id")
private final String id;
@JsonProperty("name")
private final String name;
@JsonProperty("sector")
private final String sector;
@JsonProperty("latitude")
private final String latitude;
@JsonProperty("longitude")
private final String longitude;
@JsonProperty("locationDisplayName")
private final String locationDisplayName;
@JsonProperty("hasItems")
private final boolean hasItems;
@JsonProperty("numberOfItems")
private final long numberOfItems;
@JsonProperty("children")
private final List<Institution> children;
@JsonProperty("level")
private int level;
@JsonProperty("detailViewUri")
private String detailViewUri;
/*
* Only needed for automatic serialization and deserialization.
*/
@SuppressWarnings("unused")
private Institution() {
this(null, null, null, null, null, null, false, 0);
}
public Institution(
String id,
String name,
String sector,
String latitude,
String longitude,
String locationDisplayName,
boolean hasItems,
long numberOfItems) {
super();
this.id = id;
this.name = name;
this.sector = sector;
this.latitude = latitude;
this.longitude = longitude;
this.locationDisplayName = locationDisplayName;
this.hasItems = hasItems;
this.numberOfItems = numberOfItems;
this.children = new LinkedList<Institution>();
this.level = -1;
this.detailViewUri = null;
}
public String getId() {
return this.id;
}
public String getName() {
return this.name;
}
public String getSector() {
return this.sector;
}
public String getLatitude() {
return this.latitude;
}
public String getLongitude() {
return this.longitude;
}
public List<Institution> getChildren() {
return this.children;
}
public void addChild(Institution institution) {
this.children.add(institution);
}
public void setChildren(List<Institution> objects) {
this.children.clear();
this.children.addAll(objects);
}
public int getLevel() {
return this.level;
}
public void setLevel(int level) {
this.level = level;
}
public void setDetailViewUri(String detailViewUri) {
this.detailViewUri = detailViewUri;
}
public String getLocationDisplayName() {
return this.locationDisplayName;
}
public String getDetailViewUri() {
return this.detailViewUri;
}
public boolean hasItems() {
return this.hasItems;
}
public long getNumberOfItems() {
return this.numberOfItems;
}
public Institution copy() {
Institution newInstitution =
new Institution(this.id, this.name, this.sector, this.latitude, this.longitude, this.locationDisplayName, this.hasItems, this.numberOfItems);
for ( Institution inst : this.children ) {
newInstitution.getChildren().add(inst.copy());
}
return newInstitution;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((this.detailViewUri == null) ? 0 : this.detailViewUri.hashCode());
result = (prime * result) + (this.hasItems ? 1231 : 1237);
result = (prime * result) + ((this.id == null) ? 0 : this.id.hashCode());
result = (prime * result) + ((this.latitude == null) ? 0 : this.latitude.hashCode());
result = (prime * result) + this.level;
result = (prime * result) + ((this.locationDisplayName == null) ? 0 : this.locationDisplayName.hashCode());
result = (prime * result) + ((this.longitude == null) ? 0 : this.longitude.hashCode());
result = (prime * result) + ((this.name == null) ? 0 : this.name.hashCode());
result = (prime * result) + (int) (this.numberOfItems ^ (this.numberOfItems >>> 32));
result = (prime * result) + ((this.sector == null) ? 0 : this.sector.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
Institution other = (Institution) obj;
if ( this.detailViewUri == null ) {
if ( other.detailViewUri != null ) {
return false;
}
} else if ( !this.detailViewUri.equals(other.detailViewUri) ) {
return false;
}
if ( this.hasItems != other.hasItems ) {
return false;
}
if ( this.id == null ) {
if ( other.id != null ) {
return false;
}
} else if ( !this.id.equals(other.id) ) {
return false;
}
if ( this.latitude == null ) {
if ( other.latitude != null ) {
return false;
}
} else if ( !this.latitude.equals(other.latitude) ) {
return false;
}
if ( this.level != other.level ) {
return false;
}
if ( this.locationDisplayName == null ) {
if ( other.locationDisplayName != null ) {
return false;
}
} else if ( !this.locationDisplayName.equals(other.locationDisplayName) ) {
return false;
}
if ( this.longitude == null ) {
if ( other.longitude != null ) {
return false;
}
} else if ( !this.longitude.equals(other.longitude) ) {
return false;
}
if ( this.name == null ) {
if ( other.name != null ) {
return false;
}
} else if ( !this.name.equals(other.name) ) {
return false;
}
if ( this.numberOfItems != other.numberOfItems ) {
return false;
}
if ( this.sector == null ) {
if ( other.sector != null ) {
return false;
}
} else if ( !this.sector.equals(other.sector) ) {
return false;
}
return true;
}
@Override
public String toString() {
return "Institution [id="
+ this.id
+ ", name="
+ this.name
+ ", sector="
+ this.sector
+ ", latitude="
+ this.latitude
+ ", longitude="
+ this.longitude
+ ", locationDisplayName="
+ this.locationDisplayName
+ ", hasItems="
+ this.hasItems
+ ", numberOfItems="
+ this.numberOfItems
+ ", children="
+ this.children
+ ", level="
+ this.level
+ ", detailViewUri="
+ this.detailViewUri
+ "]";
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Chlorophyta/Charophyceae/Charales/Characeae/Nitella/Nitella elegans/ Syn. Nitella pseudoflabellata elegans/README.md
|
207
|
# Nitella pseudoflabellata f. elegans (B.P.Pal) R.D.Wood, 1962 FORM
#### Status
SYNONYM
#### According to
World Register of Marine Species
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Sordariomycetes/Xylariales/Xylariaceae/Sphaeria/Sphaeria concrescens/README.md
|
187
|
# Sphaeria concrescens Schwein. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Sphaeria concrescens Schwein.
### Remarks
null
|
apache-2.0
|
aaronxsu/raster-foundry
|
app-backend/backsplash-core/src/main/scala/com/rasterfoundry/backsplash/MosaicImplicits.scala
|
22604
|
package com.rasterfoundry.backsplash
import com.rasterfoundry.backsplash.color._
import com.rasterfoundry.backsplash.error._
import com.rasterfoundry.backsplash.HistogramStore.ToHistogramStoreOps
import geotrellis.proj4.WebMercator
import geotrellis.vector._
import geotrellis.raster._
import geotrellis.raster.histogram._
import geotrellis.raster.reproject._
import geotrellis.server._
import cats.implicits._
import cats.data.{NonEmptyList => NEL}
import cats.effect._
import cats.Semigroup
import scalacache._
import scalacache.memoization._
import scalacache.CatsEffect.modes._
import RenderableStore._
import ToolStore._
import ExtentReification._
import HasRasterExtents._
import TmsReification._
import com.colisweb.tracing.TracingContext
import com.typesafe.scalalogging.LazyLogging
import com.rasterfoundry.datamodel.SingleBandOptions
class MosaicImplicits[HistStore: HistogramStore, RendStore: RenderableStore](
histStore: HistStore,
rendStore: RendStore
) extends ToTmsReificationOps
with ToExtentReificationOps
with ToHasRasterExtentsOps
with ToHistogramStoreOps
with ToRenderableStoreOps
with ToToolStoreOps
with LazyLogging {
implicit val histCache = Cache.histCache
implicit val flags = Cache.histCacheFlags
val streamConcurrency = Config.parallelism.streamConcurrency
// To be used when folding over/merging tiles
val invisiCellType = IntUserDefinedNoDataCellType(0)
val invisiTile = IntUserDefinedNoDataArrayTile(
Array.fill(65536)(0),
256,
256,
invisiCellType
)
def getNoDataValue(cellType: CellType): Option[Double] = {
cellType match {
case ByteUserDefinedNoDataCellType(value) => Some(value.toDouble)
case UByteUserDefinedNoDataCellType(value) => Some(value.toDouble)
case UByteConstantNoDataCellType => Some(0)
case ShortUserDefinedNoDataCellType(value) => Some(value.toDouble)
case UShortUserDefinedNoDataCellType(value) => Some(value.toDouble)
case UShortConstantNoDataCellType => Some(0)
case IntUserDefinedNoDataCellType(value) => Some(value.toDouble)
case FloatUserDefinedNoDataCellType(value) => Some(value.toDouble)
case DoubleUserDefinedNoDataCellType(value) => Some(value.toDouble)
case _: NoNoData => None
case _: ConstantNoData[_] => Some(Double.NaN)
}
}
def mergeTiles(tiles: IO[List[MultibandTile]]): IO[Option[MultibandTile]] = {
tiles.map(_.reduceOption((t1: MultibandTile, t2: MultibandTile) => {
logger.trace(s"Tile 1 size: ${t1.band(0).cols}, ${t1.band(0).rows}")
logger.trace(s"Tile 2 size: ${t2.band(0).cols}, ${t2.band(0).rows}")
t1 merge t2
}))
}
def chooseMosaic(
z: Int,
baseImage: BacksplashImage[IO],
config: OverviewConfig,
fallbackIms: NEL[BacksplashImage[IO]]): NEL[BacksplashImage[IO]] =
config match {
case OverviewConfig(Some(overviewLocation), Some(minZoom))
if z <= minZoom =>
NEL.of(
BacksplashGeotiff(
baseImage.imageId,
baseImage.projectId,
baseImage.projectLayerId,
overviewLocation,
baseImage.subsetBands,
baseImage.corrections,
baseImage.singleBandOptions,
baseImage.mask,
baseImage.footprint,
baseImage.metadata
),
Nil: _*
)
case _ =>
fallbackIms
}
@SuppressWarnings(Array("TraversableHead"))
def renderMosaicSingleBand(
mosaic: NEL[BacksplashImage[IO]],
z: Int,
x: Int,
y: Int,
tracingContext: TracingContext[IO]
)(implicit contextShift: ContextShift[IO]): IO[Raster[MultibandTile]] = {
type MBTTriple = (MultibandTile, SingleBandOptions.Params, Option[Double])
val extent = BacksplashImage.tmsLevels(z).mapTransform.keyToExtent(x, y)
val ioMBTwithSBO: IO[List[MBTTriple]] = tracingContext.childSpan(
"renderMosaicSingleBand") use { context =>
mosaic
.traverse((relevant: BacksplashImage[IO]) => {
logger.debug(s"Band Subset Required: ${relevant.subsetBands}")
relevant.read(z, x, y, context) map {
(_, relevant.singleBandOptions, relevant.metadata.noDataValue)
}
})
.map(nel =>
nel.collect({
case (Some(mbtile), Some(sbo), nd) => (mbtile, sbo, nd)
}))
}
for {
imagesNel <- ioMBTwithSBO map { _.toNel } flatMap {
case Some(ims) => IO.pure(ims)
case None => IO.raiseError(NoScenesException)
}
firstIm = mosaic.head
histograms <- tracingContext.childSpan("renderMosaicSingleBand.histogram") use {
context =>
firstIm.singleBandOptions map { _.band } map { bd =>
histStore.projectLayerHistogram(firstIm.projectLayerId,
List(bd),
context)
} getOrElse {
IO.raiseError(
SingleBandOptionsException(
"Must provide band for single band visualization"
)
)
}
}
} yield {
val combinedHistogram = histograms.reduce(_ merge _)
val (_, firstSbos, firstNd) = imagesNel.head
imagesNel.toList match {
case (tile, sbo, nd) :: Nil =>
Raster(ColorRampMosaic.colorTile(interpretAsFallback(tile, nd),
List(combinedHistogram),
sbo),
extent)
case someTiles =>
val outTile = someTiles.foldLeft(MultibandTile(invisiTile))(
(baseTile: MultibandTile, triple2: MBTTriple) =>
interpretAsFallback(baseTile, firstNd) merge interpretAsFallback(
triple2._1,
firstNd))
Raster(
ColorRampMosaic.colorTile(
outTile,
List(combinedHistogram),
firstSbos
),
extent
)
}
}
}
def interpretAsFallback[T1, T2](tile: MultibandTile,
noData: Option[Double]): MultibandTile =
tile.interpretAs(
DoubleUserDefinedNoDataCellType(
noData
.orElse(getNoDataValue(tile.cellType))
.getOrElse(0.0)
)
)
@SuppressWarnings(Array("TraversableHead"))
def renderMosaicMultiband(
mosaic: NEL[BacksplashImage[IO]],
z: Int,
x: Int,
y: Int,
tracingContext: TracingContext[IO]
)(implicit contextShift: ContextShift[IO]): IO[Raster[MultibandTile]] = {
val extent = BacksplashImage.tmsLevels(z).mapTransform.keyToExtent(x, y)
val ioMBT = tracingContext.childSpan("renderMosaic") use { context =>
mosaic
.traverse((relevant: BacksplashImage[IO]) => {
val tags = Map("sceneId" -> relevant.imageId.toString,
"projectId" -> relevant.projectId.toString,
"projectLayerId" -> relevant.projectLayerId.toString,
"zoom" -> z.toString)
context
.childSpan("renderMosaicMultiband.renderBacksplashImage", tags) use {
childContext =>
for {
imFiber <- relevant.read(z, x, y, childContext).start
histsFiber <- {
childContext.childSpan("renderMosaicMultiband.readHistogram",
tags) use { _ =>
getHistogramWithCache(relevant, childContext)
}
}.start
hists <- histsFiber.join
im <- imFiber.join
renderedTile <- {
childContext.childSpan("renderMosaicMultiband.colorCorrect",
tags) use {
_ =>
IO.pure {
im map { mbTile =>
val noDataValue = getNoDataValue(mbTile.cellType)
logger.debug(
s"NODATA Value: $noDataValue with CellType: ${mbTile.cellType}"
)
relevant.corrections.colorCorrect(
mbTile,
hists,
relevant.metadata.noDataValue orElse noDataValue orElse Some(
0))
}
}
}
}
} yield {
renderedTile
}
}
})
.map(nel => nel.collect({ case Some(tile) => tile }))
}
mergeTiles(ioMBT).map {
case Some(t) => Raster(t, extent)
case _ =>
Raster(MultibandTile(invisiTile, invisiTile, invisiTile), extent)
}
}
val rawMosaicTmsReification: TmsReification[BacksplashMosaic] =
new TmsReification[BacksplashMosaic] {
def tmsReification(self: BacksplashMosaic, buffer: Int)(
implicit contextShift: ContextShift[IO]
): (Int, Int, Int) => IO[ProjectedRaster[MultibandTile]] =
(z: Int, x: Int, y: Int) => {
val extent =
BacksplashImage.tmsLevels(z).mapTransform.keyToExtent(x, y)
val mosaic = {
val mbtIO = self.flatMap {
case (tracingContext, listBsi) =>
tracingContext.childSpan("getMergedRawMosaic") use {
childContext =>
val listIO = listBsi.traverse { bsi =>
bsi.read(z, x, y, childContext)
}
childContext.childSpan("mergeRawTiles") use { _ =>
listIO.map(_.flatten.reduceOption(_ merge _))
}
}
}
mbtIO.map {
case Some(t) => Raster(t, extent)
case _ =>
Raster(MultibandTile(invisiTile, invisiTile, invisiTile),
extent)
}
}
mosaic.map(ProjectedRaster(_, WebMercator))
}
}
val paintedMosaicTmsReification: TmsReification[BacksplashMosaic] =
new TmsReification[BacksplashMosaic] {
def tmsReification(self: BacksplashMosaic, buffer: Int)(
implicit contextShift: ContextShift[IO]
): (Int, Int, Int) => IO[ProjectedRaster[MultibandTile]] =
(z: Int, x: Int, y: Int) => {
val imagesIO: IO[(TracingContext[IO], List[BacksplashImage[IO]])] =
self
(for {
(context, imagesNel) <- imagesIO map {
case (tracingContext, images) => (tracingContext, images.toNel)
} flatMap {
case (tracingContext, Some(ims)) => IO.pure((tracingContext, ims))
case (_, None) => IO.raiseError(NoDataInRegionException)
}
bandCount = imagesNel.head.subsetBands.length
overviewConfig <- context.childSpan("getOverviewConfig") use {
childContext =>
rendStore.getOverviewConfig(imagesNel.head.projectLayerId,
childContext)
}
mosaic = chooseMosaic(z, imagesNel.head, overviewConfig, imagesNel)
// for single band imagery, after color correction we have RGBA, so
// the empty tile needs to be four band as well
rendered <- context.childSpan("paintedRender") use {
renderContext =>
if (bandCount == 3) {
renderMosaicMultiband(mosaic, z, x, y, renderContext)
} else {
renderMosaicSingleBand(mosaic, z, x, y, renderContext)
}
}
} yield {
ProjectedRaster(rendered, WebMercator)
}).attempt.flatMap {
case Left(NoDataInRegionException) =>
IO.pure(
ProjectedRaster(
Raster(
MultibandTile(invisiTile, invisiTile, invisiTile),
Extent(0, 0, 256, 256)
),
WebMercator
)
)
case Left(e) => IO.raiseError(e)
case Right(rasterLit) => IO.pure(rasterLit)
}
}
}
/** Private histogram retrieval method to allow for caching on/off via settings
*
* @param relevant
* @return
*/
private def getHistogramWithCache(
relevant: BacksplashImage[IO],
tracingContext: TracingContext[IO]
)(implicit @cacheKeyExclude flags: Flags): IO[Array[Histogram[Double]]] =
memoizeF(None) {
relevant match {
case im: BacksplashGeotiff =>
logger.debug(
s"Retrieving Histograms for ${im.imageId} from histogram store")
histStore.layerHistogram(im.imageId, im.subsetBands, tracingContext)
case im: Landsat8MultiTiffImage =>
logger.debug(s"Retrieving histograms for ${im.imageId} from source")
im.getHistogram(tracingContext)
// Is this hilariously repetitive? Yes! But type erasure :(
case im: Sentinel2MultiTiffImage =>
logger.debug(s"Retrieving histograms for ${im.imageId} from source")
im.getHistogram(tracingContext)
case im: LandsatHistoricalMultiTiffImage =>
logger.debug(s"Retrieving histograms for ${im.imageId} from source")
im.getHistogram(tracingContext)
}
}
// We need to be able to pass information about whether scenes should paint themselves while
// we're working through the stream from the route into the extent reification. The solution
// we (Nathan Zimmerman and I) came up with that is the least painful is two implicits, choosing
// which one to use based on the information we have in the route. That solution can go away if:
//
// 1. color correction becomes a local op in MAML and we don't have to care about it in RF anymore
// 2. all color correction options (single and multiband) move onto backsplash images and
// BacksplashImage gets a paint attribute telling it whether to apply color correction
//
// Neither of those changes really fits in the scope of backsplash performance work, so we're doing
// this for now instead.
val paintedMosaicExtentReification: ExtentReification[BacksplashMosaic] =
new ExtentReification[BacksplashMosaic] {
def extentReification(
self: BacksplashMosaic
)(implicit contextShift: ContextShift[IO])
: (Extent, CellSize) => IO[ProjectedRaster[MultibandTile]] =
(extent: Extent, cs: CellSize) => {
for {
bands <- {
self.map {
case (_, bsiList) =>
bsiList.headOption match {
case Some(image) => image.subsetBands
case _ => throw NoScenesException
}
}
}
mosaic <- if (bands.length == 3) {
val bsm = self.map {
case (tracingContext, bsiList) => {
tracingContext.childSpan("paintedMosaicExtentReification") use {
childContext =>
bsiList traverse { relevant =>
val tags =
Map("imageId" -> relevant.imageId.toString,
"projectId" -> relevant.projectId.toString)
for {
imFiber <- relevant
.read(extent, cs, childContext)
.start
histsFiber <- childContext.childSpan("layerHistogram",
tags) use {
context =>
histStore
.layerHistogram(
relevant.imageId,
relevant.subsetBands,
context
)
.start
}
im <- imFiber.join
hists <- histsFiber.join
renderedTile <- childContext.childSpan("colorCorrect",
tags) use {
_ =>
IO.pure {
im map { mbTile =>
logger.debug(
s"N bands in resulting tile: ${mbTile.bands.length}"
)
relevant.corrections.colorCorrect(mbTile,
hists,
None)
}
}
}
} yield {
renderedTile match {
case Some(mbTile) =>
Some(
Raster(mbTile.interpretAs(invisiCellType),
extent))
case _ => None
}
}
}
}
}.map(_.flatten.reduceOption(_ merge _))
.map({
case Some(r) => r
case _ =>
Raster(
MultibandTile(invisiTile, invisiTile, invisiTile),
extent
)
})
}
bsm.flatten
} else {
logger.debug("Creating single band extent")
for {
histograms <- BacksplashMosaic.getStoreHistogram(self,
histStore)
(tracingContext, imageList) <- self
corrected <- tracingContext.childSpan(
"singleBandPaintedExtentReification") use { childContext =>
imageList.traverse { bsi =>
bsi.singleBandOptions match {
case Some(opts) =>
bsi.read(extent, cs, childContext) map {
case Some(mbt) =>
ColorRampMosaic.colorTile(mbt, histograms, opts)
case _ =>
MultibandTile(invisiTile, invisiTile, invisiTile)
}
case _ =>
IO.raiseError(
SingleBandOptionsException(
"Must specify single band options when requesting single band visualization.")
)
}
}
}
} yield {
corrected.reduceOption(_ merge _) match {
case Some(r) => Raster(r, extent)
case _ =>
Raster(
MultibandTile(invisiTile, invisiTile, invisiTile),
extent
)
}
}
}
} yield ProjectedRaster(mosaic, WebMercator)
}
}
implicit val rawMosaicExtentReification: ExtentReification[BacksplashMosaic] =
new ExtentReification[BacksplashMosaic] {
def extentReification(
self: BacksplashMosaic
)(implicit contextShift: ContextShift[IO])
: (Extent, CellSize) => IO[ProjectedRaster[MultibandTile]] =
(extent: Extent, cs: CellSize) => {
val mosaic = self.map {
case (tracingContext, listBsi) =>
tracingContext.childSpan("rawMosaicExtentReification") use {
childContext =>
for {
mbts <- {
childContext.childSpan("rawMosaicExtentReification.reads") use {
grandContext =>
listBsi.traverse({ relevant =>
relevant.read(extent, cs, grandContext)
})
}
}
} yield {
val tiles = mbts.collect({ case Some(mbTile) => mbTile })
val rasters = tiles.map(Raster(_, extent))
rasters.reduceOption(_ merge _) match {
case Some(r) => r
case _ =>
Raster(
MultibandTile(invisiTile, invisiTile, invisiTile),
extent
)
}
}
}
}
mosaic.flatten map {
ProjectedRaster(_, WebMercator)
}
}
}
implicit val extentSemigroup: Semigroup[Extent] = new Semigroup[Extent] {
def combine(x: Extent, y: Extent): Extent = x.combine(y)
}
implicit val mosaicHasRasterExtents: HasRasterExtents[BacksplashMosaic] =
new HasRasterExtents[BacksplashMosaic] {
def rasterExtents(
self: BacksplashMosaic
)(implicit contextShift: ContextShift[IO]): IO[NEL[RasterExtent]] = {
val mosaic = self.flatMap {
case (tracingContext, bsiList) =>
tracingContext.childSpan("mosaicRasterExtents") use {
childContext =>
bsiList.traverse({ img =>
img.getRasterSource(childContext) map { rs =>
val rasterExtents = rs.resolutions map { res =>
ReprojectRasterExtent(RasterExtent(res.extent,
res.cellwidth,
res.cellheight,
res.cols.toInt,
res.rows.toInt),
rs.crs,
WebMercator)
}
rasterExtents
}
})
}
}
mosaic.map(_.flatten.toNel.getOrElse(
throw new MetadataException("Cannot get raster extent from mosaic.")))
}
}
}
|
apache-2.0
|
mailgun/talon
|
tests/signature/learning/featurespace_test.py
|
1402
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from ... import *
from talon.signature.learning import featurespace as fs
def test_apply_features():
s = '''This is John Doe
Tuesday @3pm suits. I'll chat to you then.
VP Research and Development, Xxxx Xxxx Xxxxx
555-226-2345
[email protected]'''
sender = 'John <[email protected]>'
features = fs.features(sender)
result = fs.apply_features(s, features)
# note that we don't consider the first line because signatures don't
# usually take all the text, empty lines are not considered
eq_(result, [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
with patch.object(fs, 'SIGNATURE_MAX_LINES', 5):
features = fs.features(sender)
new_result = fs.apply_features(s, features)
# result remains the same because we don't consider empty lines
eq_(result, new_result)
def test_build_pattern():
s = '''John Doe
VP Research and Development, Xxxx Xxxx Xxxxx
555-226-2345
[email protected]'''
sender = 'John <[email protected]>'
features = fs.features(sender)
result = fs.build_pattern(s, features)
eq_(result, [2, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1])
|
apache-2.0
|
fbradyirl/home-assistant
|
script/gen_requirements_all.py
|
11383
|
#!/usr/bin/env python3
"""Generate an updated requirements_all.txt."""
import importlib
import os
import pathlib
import pkgutil
import re
import sys
from script.hassfest.model import Integration
COMMENT_REQUIREMENTS = (
"Adafruit-DHT",
"Adafruit_BBIO",
"avion",
"beacontools",
"blinkt",
"bluepy",
"bme680",
"credstash",
"decora",
"envirophat",
"evdev",
"face_recognition",
"fritzconnection",
"i2csense",
"opencv-python-headless",
"py_noaa",
"VL53L1X2",
"pybluez",
"pycups",
"PySwitchbot",
"pySwitchmate",
"python-eq3bt",
"python-lirc",
"pyuserinput",
"raspihats",
"rpi-rf",
"RPi.GPIO",
"smbus-cffi",
)
TEST_REQUIREMENTS = (
"adguardhome",
"ambiclimate",
"aioambient",
"aioautomatic",
"aiobotocore",
"aioesphomeapi",
"aiohttp_cors",
"aiohue",
"aionotion",
"aiounifi",
"aioswitcher",
"aiowwlln",
"apns2",
"aprslib",
"av",
"axis",
"caldav",
"coinmarketcap",
"defusedxml",
"dsmr_parser",
"eebrightbox",
"emulated_roku",
"enocean",
"ephem",
"evohomeclient",
"feedparser-homeassistant",
"foobot_async",
"geojson_client",
"geopy",
"georss_generic_client",
"georss_ign_sismologia_client",
"georss_qld_bushfire_alert_client",
"getmac",
"google-api-python-client",
"gTTS-token",
"ha-ffmpeg",
"hangups",
"HAP-python",
"hass-nabucasa",
"haversine",
"hbmqtt",
"hdate",
"holidays",
"home-assistant-frontend",
"homekit[IP]",
"homematicip",
"httplib2",
"huawei-lte-api",
"influxdb",
"jsonpath",
"libpurecool",
"libsoundtouch",
"luftdaten",
"pyMetno",
"mbddns",
"mficlient",
"netdisco",
"numpy",
"oauth2client",
"paho-mqtt",
"pexpect",
"pilight",
"pmsensor",
"prometheus_client",
"ptvsd",
"pushbullet.py",
"py-canary",
"pyblackbird",
"pydeconz",
"pydispatcher",
"pyheos",
"pyhomematic",
"pyiqvia",
"pylitejet",
"pymfy",
"pymonoprice",
"pynx584",
"pyopenuv",
"pyotp",
"pyps4-homeassistant",
"pysmartapp",
"pysmartthings",
"pysonos",
"pyqwikswitch",
"PyRMVtransport",
"PyTransportNSW",
"pyspcwebgw",
"python-forecastio",
"python-nest",
"python_awair",
"python-velbus",
"pytradfri[async]",
"pyunifi",
"pyupnp-async",
"pyvesync",
"pywebpush",
"pyHS100",
"PyNaCl",
"regenmaschine",
"restrictedpython",
"rflink",
"ring_doorbell",
"rxv",
"simplisafe-python",
"sleepyq",
"smhi-pkg",
"somecomfort",
"sqlalchemy",
"srpenergy",
"statsd",
"toonapilib",
"twentemilieu",
"uvcclient",
"vsure",
"warrant",
"pythonwhois",
"wakeonlan",
"vultr",
"YesssSMS",
"ruamel.yaml",
"zeroconf",
"zigpy-homeassistant",
"bellows-homeassistant",
"py17track",
)
IGNORE_PIN = ("colorlog>2.1,<3", "keyring>=9.3,<10.0", "urllib3")
IGNORE_REQ = ("colorama<=1",) # Windows only requirement in check_config
URL_PIN = (
"https://developers.home-assistant.io/docs/"
"creating_platform_code_review.html#1-requirements"
)
CONSTRAINT_PATH = os.path.join(
os.path.dirname(__file__), "../homeassistant/package_constraints.txt"
)
CONSTRAINT_BASE = """
pycryptodome>=3.6.6
# Breaks Python 3.6 and is not needed for our supported Python versions
enum34==1000000000.0.0
# This is a old unmaintained library and is replaced with pycryptodome
pycrypto==1000000000.0.0
# Contains code to modify Home Assistant to work around our rules
python-systemair-savecair==1000000000.0.0
"""
def explore_module(package, explore_children):
"""Explore the modules."""
module = importlib.import_module(package)
found = []
if not hasattr(module, "__path__"):
return found
for _, name, _ in pkgutil.iter_modules(module.__path__, package + "."):
found.append(name)
if explore_children:
found.extend(explore_module(name, False))
return found
def core_requirements():
"""Gather core requirements out of setup.py."""
with open("setup.py") as inp:
reqs_raw = re.search(r"REQUIRES = \[(.*?)\]", inp.read(), re.S).group(1)
return [x[1] for x in re.findall(r"(['\"])(.*?)\1", reqs_raw)]
def gather_recursive_requirements(domain, seen=None):
"""Recursively gather requirements from a module."""
if seen is None:
seen = set()
seen.add(domain)
integration = Integration(
pathlib.Path("homeassistant/components/{}".format(domain))
)
integration.load_manifest()
reqs = set(integration.manifest["requirements"])
for dep_domain in integration.manifest["dependencies"]:
reqs.update(gather_recursive_requirements(dep_domain, seen))
return reqs
def comment_requirement(req):
"""Comment out requirement. Some don't install on all systems."""
return any(ign in req for ign in COMMENT_REQUIREMENTS)
def gather_modules():
"""Collect the information."""
reqs = {}
errors = []
gather_requirements_from_manifests(errors, reqs)
gather_requirements_from_modules(errors, reqs)
for key in reqs:
reqs[key] = sorted(reqs[key], key=lambda name: (len(name.split(".")), name))
if errors:
print("******* ERROR")
print("Errors while importing: ", ", ".join(errors))
return None
return reqs
def gather_requirements_from_manifests(errors, reqs):
"""Gather all of the requirements from manifests."""
integrations = Integration.load_dir(pathlib.Path("homeassistant/components"))
for domain in sorted(integrations):
integration = integrations[domain]
if not integration.manifest:
errors.append("The manifest for integration {} is invalid.".format(domain))
continue
process_requirements(
errors,
integration.manifest["requirements"],
"homeassistant.components.{}".format(domain),
reqs,
)
def gather_requirements_from_modules(errors, reqs):
"""Collect the requirements from the modules directly."""
for package in sorted(
explore_module("homeassistant.scripts", True)
+ explore_module("homeassistant.auth", True)
):
try:
module = importlib.import_module(package)
except ImportError as err:
print("{}: {}".format(package.replace(".", "/") + ".py", err))
errors.append(package)
continue
if getattr(module, "REQUIREMENTS", None):
process_requirements(errors, module.REQUIREMENTS, package, reqs)
def process_requirements(errors, module_requirements, package, reqs):
"""Process all of the requirements."""
for req in module_requirements:
if req in IGNORE_REQ:
continue
if "://" in req:
errors.append(
"{}[Only pypi dependencies are allowed: {}]".format(package, req)
)
if req.partition("==")[1] == "" and req not in IGNORE_PIN:
errors.append(
"{}[Please pin requirement {}, see {}]".format(package, req, URL_PIN)
)
reqs.setdefault(req, []).append(package)
def generate_requirements_list(reqs):
"""Generate a pip file based on requirements."""
output = []
for pkg, requirements in sorted(reqs.items(), key=lambda item: item[0]):
for req in sorted(requirements):
output.append("\n# {}".format(req))
if comment_requirement(pkg):
output.append("\n# {}\n".format(pkg))
else:
output.append("\n{}\n".format(pkg))
return "".join(output)
def requirements_all_output(reqs):
"""Generate output for requirements_all."""
output = []
output.append("# Home Assistant core")
output.append("\n")
output.append("\n".join(core_requirements()))
output.append("\n")
output.append(generate_requirements_list(reqs))
return "".join(output)
def requirements_test_output(reqs):
"""Generate output for test_requirements."""
output = []
output.append("# Home Assistant test")
output.append("\n")
with open("requirements_test.txt") as test_file:
output.append(test_file.read())
output.append("\n")
filtered = {
key: value
for key, value in reqs.items()
if any(
re.search(r"(^|#){}($|[=><])".format(re.escape(ign)), key) is not None
for ign in TEST_REQUIREMENTS
)
}
output.append(generate_requirements_list(filtered))
return "".join(output)
def gather_constraints():
"""Construct output for constraint file."""
return "\n".join(
sorted(
core_requirements() + list(gather_recursive_requirements("default_config"))
)
+ [""]
)
def write_requirements_file(data):
"""Write the modules to the requirements_all.txt."""
with open("requirements_all.txt", "w+", newline="\n") as req_file:
req_file.write(data)
def write_test_requirements_file(data):
"""Write the modules to the requirements_test_all.txt."""
with open("requirements_test_all.txt", "w+", newline="\n") as req_file:
req_file.write(data)
def write_constraints_file(data):
"""Write constraints to a file."""
with open(CONSTRAINT_PATH, "w+", newline="\n") as req_file:
req_file.write(data + CONSTRAINT_BASE)
def validate_requirements_file(data):
"""Validate if requirements_all.txt is up to date."""
with open("requirements_all.txt", "r") as req_file:
return data == req_file.read()
def validate_requirements_test_file(data):
"""Validate if requirements_test_all.txt is up to date."""
with open("requirements_test_all.txt", "r") as req_file:
return data == req_file.read()
def validate_constraints_file(data):
"""Validate if constraints is up to date."""
with open(CONSTRAINT_PATH, "r") as req_file:
return data + CONSTRAINT_BASE == req_file.read()
def main(validate):
"""Run the script."""
if not os.path.isfile("requirements_all.txt"):
print("Run this from HA root dir")
return 1
data = gather_modules()
if data is None:
return 1
constraints = gather_constraints()
reqs_file = requirements_all_output(data)
reqs_test_file = requirements_test_output(data)
if validate:
errors = []
if not validate_requirements_file(reqs_file):
errors.append("requirements_all.txt is not up to date")
if not validate_requirements_test_file(reqs_test_file):
errors.append("requirements_test_all.txt is not up to date")
if not validate_constraints_file(constraints):
errors.append("home-assistant/package_constraints.txt is not up to date")
if errors:
print("******* ERROR")
print("\n".join(errors))
print("Please run script/gen_requirements_all.py")
return 1
return 0
write_requirements_file(reqs_file)
write_test_requirements_file(reqs_test_file)
write_constraints_file(constraints)
return 0
if __name__ == "__main__":
_VAL = sys.argv[-1] == "validate"
sys.exit(main(_VAL))
|
apache-2.0
|
balajiboggaram/algorithms
|
src/me/learn/personal/month2/CellsWithOddValuesInMatrix.java
|
1601
|
/**
*
*/
package me.learn.personal.month2;
/**
* Title 1252 :
*
* Given n and m which are the dimensions of a matrix initialized by zeros and
* given an array indices where indices[i] = [ri, ci]. For each pair of [ri, ci]
* you have to increment all cells in row ri and column ci by 1.
*
* Return the number of cells with odd values in the matrix after applying the
* increment to all indices.
*
* @author bramanarayan
* @date Jun 13, 2020
*/
public class CellsWithOddValuesInMatrix {
/**
* @param args
*/
public static void main(String[] args) {
CellsWithOddValuesInMatrix solution = new CellsWithOddValuesInMatrix();
System.out.println(solution.oddCells(2, 3, new int[][] { { 0, 1 }, { 1, 1 } }));
}
public int oddCells(int n, int m, int[][] indices) {
int row[] = new int[n];
int col[] = new int[m];
int[][] res = new int[n][m];
// Increment the row and col array based on indicies
for (int i = 0; i < indices.length; i++) {
int x = indices[i][0];
int y = indices[i][1];
row[x] += 1;
col[y] += 1;
}
// Increment the row
for (int i = 0; i < n; i++) {
if (row[i] > 0) {
int j = 0;
while (j < m) {
res[i][j] += row[i];
j++;
}
}
}
// Increment the column
for (int i = 0; i < m; i++) {
if (col[i] > 0) {
int j = 0;
while (j < n) {
res[j][i] += col[i];
j++;
}
}
}
// Check the odd values
int oddCount = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
oddCount = (res[i][j] % 2 != 0) ? oddCount + 1 : oddCount;
}
}
return oddCount;
}
}
|
apache-2.0
|
ryandcarter/hybris-connector
|
src/main/java/org/mule/modules/hybris/model/VariantTypeDTO.java
|
1073
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.11.29 at 12:35:53 PM GMT
//
package org.mule.modules.hybris.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for variantTypeDTO complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="variantTypeDTO">
* <complexContent>
* <extension base="{}composedTypeDTO">
* <sequence>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "variantTypeDTO")
public class VariantTypeDTO
extends ComposedTypeDTO
{
}
|
apache-2.0
|
wbonnet/pg-compile
|
postgresql/8.0.6/Makefile
|
1333
|
# vim: ft=make ts=4 sw=4 noet
#
# The contents of this file are subject to the Apache 2.0 license you may not
# use this file except in compliance with the License.
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
#
#
# Copyright 2015 William BONNET (https://github.com/wbonnet/pg-compile).
# All rights reserved. Use is subject to license terms.
#
# Even if this work is a complete rewrite, it is originally derivated work based
# upon mGAR build system from OpenCSW project (http://www.opencsw.org).
#
# Copyright 2001 Nick Moffitt: GAR ports system
# Copyright 2006 Cory Omand: Scripts and add-on make modules, except where otherwise noted.
# Copyright 2008 Dagobert Michelsen (OpenCSW): Enhancements to the CSW GAR system
# Copyright 2008-2013 Open Community Software Association: Packaging content
#
#
#
# Contributors list :
#
# William Bonnet [email protected]
#
#
# Defines the postgresql version
SOFTWARE_VERSION=8.0.6
# Include software common definitions
include ../postgresql.mk
# Defines the patches to apply on the software
# PATCHFILES += 0000_some_patch.diff
# Include build system
include buildsystem/pg-compile.mk
|
apache-2.0
|
zouzias/apache-nutch-2.3
|
nutch/docs/api/org/apache/nutch/protocol/http/api/package-summary.html
|
7010
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_55) on Fri Jan 09 00:43:08 PST 2015 -->
<title>org.apache.nutch.protocol.http.api (apache-nutch 2.3 API)</title>
<meta name="date" content="2015-01-09">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.apache.nutch.protocol.http.api (apache-nutch 2.3 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/apache/nutch/protocol/http/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../../org/apache/nutch/protocol/httpclient/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/nutch/protocol/http/api/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package org.apache.nutch.protocol.http.api</h1>
<div class="docSummary">
<div class="block">Common API used by HTTP plugins (<a href="../../../../../../org/apache/nutch/protocol/http/package-summary.html"><code>http</code></a>,
<a href="../../../../../../org/apache/nutch/protocol/httpclient/package-summary.html"><code>httpclient</code></a>)</div>
</div>
<p>See: <a href="#package_description">Description</a></p>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../org/apache/nutch/protocol/http/api/HttpBase.html" title="class in org.apache.nutch.protocol.http.api">HttpBase</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../org/apache/nutch/protocol/http/api/HttpRobotRulesParser.html" title="class in org.apache.nutch.protocol.http.api">HttpRobotRulesParser</a></td>
<td class="colLast">
<div class="block">This class is used for parsing robots for urls belonging to HTTP protocol.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Exception Summary table, listing exceptions, and an explanation">
<caption><span>Exception Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Exception</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../org/apache/nutch/protocol/http/api/BlockedException.html" title="class in org.apache.nutch.protocol.http.api">BlockedException</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../org/apache/nutch/protocol/http/api/HttpException.html" title="class in org.apache.nutch.protocol.http.api">HttpException</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="package_description">
<!-- -->
</a>
<h2 title="Package org.apache.nutch.protocol.http.api Description">Package org.apache.nutch.protocol.http.api Description</h2>
<div class="block"><p>Common API used by HTTP plugins (<a href="../../../../../../org/apache/nutch/protocol/http/package-summary.html"><code>http</code></a>,
<a href="../../../../../../org/apache/nutch/protocol/httpclient/package-summary.html"><code>httpclient</code></a>)</p></div>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/apache/nutch/protocol/http/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../../org/apache/nutch/protocol/httpclient/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/nutch/protocol/http/api/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2015 The Apache Software Foundation</small></p>
</body>
</html>
|
apache-2.0
|
nickgaski/docs
|
cloudnative/nl/ja/index.md
|
18733
|
---
copyright:
years: 2016, 2017
lastupdated: "2016-04-10"
---
{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:screen: .screen}
{:codeblock: .codeblock}
{:pre: .pre}
{:note:.deprecated}
# クラウド・ネイティブ・プロジェクトの構築
{: #web-mobile}
{{site.data.keyword.Bluemix}} {{site.data.keyword.dev_console}} [プロジェクト](projects.html)の概念を通じて、クラウド・ネイティブ・アプリを管理できます。プロジェクトを作成するには、[{{site.data.keyword.dev_console}}](devex.html) を使用するか、{{site.data.keyword.IBM_notm}} {{site.data.keyword.Bluemix_notm}} CLI のために [{{site.data.keyword.dev_cli_notm}}](dev_cli.html) を使用することができます。{{site.data.keyword.Bluemix_notm}} {{site.data.keyword.dev_console}} は、クラウド・ネイティブ・アプリケーション開発者に必要な最も一般的なサービス機能を、その開発者用に最適化された単一のエクスペリエンスに結合します。
{{site.data.keyword.Bluemix_notm}} {{site.data.keyword.dev_console}} を使用して、クラウド・ネイティブ・アプリケーション開発者は、さまざまな[パターン・タイプ](patterns.html)および[スターター](starters.html)からプロジェクトを作成し、{{site.data.keyword.Bluemix_notm}} 向けに最適化された主要サービスを作成してプロジェクトに接続し、機能するコードを SDK と共に迅速にダウンロードすることができます。それらの SDK には機能の資格情報や依存関係が完全に組み込まれているため、数分のうちに実行することが可能です。アプリケーションが実行中で、機能のセットアップおよび構成を完了したら、プロジェクトに戻って、アプリケーション・ユーザーとの関わりをモニターおよび管理することができます。また、{{site.data.keyword.dev_console}} でサービスを構成および管理することも可能です。
<!--
While the {{site.data.keyword.Bluemix_notm}} {{site.data.keyword.dev_console}} provides an integrated development experience, some developers might still want to have finer-grained control and wire services together manually. If this is your preferred approach, you might want to consider using the [{{site.data.keyword.mobilefirstbp}} Starter boilerplate](try_mobile.html).
-->
<!--With {{site.data.keyword.Bluemix}} Mobile services, you can incorporate pre-built, managed, and scalable cloud services into your mobile applications. You can focus on building your mobile apps, instead of the complexities of managing the back-end infrastructure.
The Mobile dashboard provides an integrated experience on {{site.data.keyword.Bluemix_notm}} where you can create mobile projects easily from within the dashboard.
-->
## プロジェクト
{: #projects}
{{site.data.keyword.Bluemix}} {{site.data.keyword.dev_console}} は、アプリのユーザー・インターフェース、データ、およびサービスを結合して 1 つの完全な*プロジェクト* にします。プロジェクトを作成することによって、アプリのすべての必要なパーツおよび追加された機能が {{site.data.keyword.Bluemix_notm}} サーバー上で保守されます。サービスがプロジェクトに構成されている場合に、アプリ・コードや、必要な資格情報および初期化指定子をダウンロードできます。**「プロジェクト」**を選択すると、すべてのプロジェクトを表示できます。
**「プロジェクト」**ページで単一プロジェクトを選択すると、それに関する追加情報を表示できます。これにより、プロジェクトの構成済みの使用可能なサービスを示した**「プロジェクト概要」**ページが表示されます。サービスは分離した機能であり、アプリの機能を拡充します。サービスは個別に追加されるため、必要なサービス (プッシュ・サービス、認証サービス、データおよびストレージ、またはその他のサービス) を追加できます。**「プロジェクト概要」**ページでサービスをプロジェクトに追加し、手順に従ってサービスを構成すると、サービスは自動的にアプリに関連付けられます。「プロジェクト概要」ページについて詳しくは、[「プロジェクト概要」ページ](project_overview_page.html)を参照してください。
プロジェクトを作成するには、[パターン](patterns.html)を選択し、その後に[スターター](starters.html)を選択する必要があります。
### プロジェクト概要ページ
{: #project_overview}
**「プロジェクト」**ページでプロジェクトを選択して「プロジェクト概要」ページを開くことにより、単一の {{site.data.keyword.Bluemix}} {{site.data.keyword.dev_console}} プロジェクトを表示および処理することができます。
{: shortdesc}
**「プロジェクト概要」**ページには、選択したプロジェクトで構成されている、または構成が可能な各機能のタイルが表示されています。このタイルには、機能のタイプと、垂直に並んだ 3 つのドットが付いた*「アクション」* ボタンが表示されています。使用可能または構成済みの可能性のある機能の例としては、{{site.data.keyword.mobilepushshort}}、Analytics (分析)、または Data and Storage (データおよびストレージ) があります。互換性のある機能は、プロジェクトのタイプおよびその地域で利用可能な機能によって異なるため、すべての機能がすべてのプロジェクトに関連付けできるわけではありません。
機能のタイプがまだプロジェクトに関連付けられていない場合は、タイルに**「作成」**ボタンが表示されます。アクション・ボタンのオプションは、サービスのインスタンスを作成すること、または機能がまだ関連付けられていない場合に既存のサービス・インスタンスを追加することです。**「既存の追加 (Add Existing)」**を選択すると、スペース内にあるそのタイプのサービス・インスタンスのリストが表示されます。
機能が既にこのプロジェクトに関連付けられている場合、関連付けられているサービス・インスタンスの名前が、タイル上の機能タイプの後に表示されます。これにより、{{site.data.keyword.dev_console}} 上でどのサービス・インスタンスがこのプロジェクトに関連しているかを見つけるのが容易になります。機能が既にプロジェクトに関連付けられている場合、アクション・ボタンで使用可能なアクションは** 「表示」**と **「削除」**です。サービス・インスタンスを削除しても、このプロジェクトへの関連付けが削除されるだけで、{{site.data.keyword.dev_console}} からサービス・インスタンスが削除されるわけではありません。サービス・インスタンスを削除するには、**「Web およびモバイル (Web and Mobile)」>「サービス」**ページをクリックし、サービス・インスタンスを表示して削除します。
プロジェクトのコードをダウンロードするには、**「コード」**タイルで**「コードの取得 (Get the Code)」**を選択します。コードのダウンロードについて詳しくは、[コードの取得](get_code.html)を参照してください。
### 新しいスターターを使用するためのプロジェクトの更新
{: #update-starter}
1. **「プロジェクト」**または**「プロジェクト概要」**ページから、**「オーバーフロー・メニュー (Overflow Menu)」**アイコンをクリックして**「スターターの更新 (Update Starter)」**を選択します。
2. 新しいスターターを選択して、**「更新」**をクリックします。
3. **「プロジェクト概要 (Project Overview)」**ページで**「コードの取得 (Get the Code)」**をクリックして、言語を選択します。
代替方法として、**「コード」**ページで以下をクリックすることもできます。
### 新しい言語を生成するためのプロジェクトの更新
{: #update-language}
1. **「プロジェクト」**または**「プロジェクト概要」**ページから、**「オーバーフロー・メニュー (Overflow Menu)」**アイコンをクリックして**「スターターの更新 (Update Starter)」**を選択します。
2. 新しい言語を選択して**「更新」**をクリックします。
3. **「プロジェクト概要 (Project Overview)」**ページで**「コードの取得 (Get the Code)」**をクリックして、言語を選択します。
## パターン・タイプ
{: #patterns}
クラウド・ネイティブ・パターンは、整合性、拡張性、信頼性のあるアプリケーション・トポロジーにするための実証された設計になっています。プロジェクトの作成時に、各種パターン・タイプが提示され、その中から選択することができます。プロジェクトに取り込みたいパターン・タイプと機能を選択するだけです。プロジェクト設定を定義すると、スターター・プロジェクトが生成されます。それを編集、実行、またはデバッグし、ローカルまたは {{site.data.keyword.Bluemix}} にデプロイできます。
### Web アプリ
{: #web}
Web プロジェクトでは、HTML、JavaScript、スタイルシートなどの Web コンテンツを処理する機能を Web サーバーに追加します。
以下の Web スターターが使用可能です。
* ベーシック Web: 静的 `index.html` ファイル、デフォルトおよび空のスタイルシート、JavaScript ファイルを処理します。
* Webpack: ECMAScript 6 (ES6) ソース・ファイルが `src/client` 内にあって、ブラウザーで使用するために縮小と変換が行われるように WebPack でコンパイルされるプロジェクトを作成します。
* Webpack + React: ユーザー・インターフェースをビルドするためのリッチ・フレームワーク。ソース・ファイルは `src/client/app` 内にあり、WebPack でコンパイルされて、パブリック・ディレクトリーで処理されます。
### モバイル・アプリ
{: #mobile}
モバイル・アプリ・パターンを利用して、{{site.data.keyword.mobilepushshort}}、{{site.data.keyword.mobileanalytics_short}}、
{{site.data.keyword.appid_short}}、その他のバックエンド・サービスに直接接続するモバイル・アプリを構築できます。プロジェクトは、sdkGen (BFF など) やマイクロサービスでも追加可能です。
{{site.data.keyword.watson}} Conversation、{{site.data.keyword.visualrecognitionshort}}、{{site.data.keyword.openwhisk_short}}、その他のスターターのリストから選択できます。
モバイル・アプリは、Swift、Android、または Cordova で生成できます。
### Backend for Frontend (BFF)
{: #bff}
Backend for Frontend パターン (通常 BFF と呼ばれる) は、ユーザー・インタラクションの要件に一致する形式でビジネス・データおよびサービスを公開することに重点を置く上で役立ちます。クラウド・ソリューションへのユーザー・ジャーニーを最適化するには、モバイル・アプリケーション用の別のユーザー・ジャーニーと、Web アプリケーション用のよりリッチで詳細なジャーニーが必要な可能性があります。[{{site.data.keyword.conversationfull}} ](https://www.ibm.com/watson/developercloud/conversation.html) サービスのような音声制御デバイスの導入により、ユーザーとのインタラクションは音声で制御される可能性があります。このデジタル・チャネルには、これらの音声インテント・ベースのインタラクションを管理するための、非常に異なる BFF が必要になります。
{{site.data.keyword.Bluemix_notm}} では、BFF を定義するための Polyglot プログラミング・アプローチを使用して BFF を作成することができます。Node.js、Swift、または Java を使用すること、および Cloud Foundry、Container サービス、またはサーバーレスのいずれかを使用してクラウド・ネイティブ・パターンでそれらを実行することを IBM は推奨しています。
BFF は、データ・パーシスタンスおよびキャッシング用のサービスとの統合、および {{site.data.keyword.ibmwatson}}、{{site.data.keyword.iot_short_notm}}、{{site.data.keyword.weather_short}} のような高価値サービス、および {{site.data.keyword.sparks}} のようなデータ分析との統合を管理します。
BFF は、最も一般的には REST パターンを使用して API を公開しますが、{{site.data.keyword.messagehub}} を使用してメッセージング・アーキテクチャーから BFF が機能するように設計することができます。
BFF ベーシック・スターターは、Node.js または Swift で使用可能です。
### マイクロサービス
{: #microservice}
マイクロサービス・プロジェクトは、基本ヘルス・エンドポイント、REST API などのバックエンド・マイクロサービスを構築するための基盤を提供します。生成されるプロジェクトには、マイクロサービス自体と、接続されたクラウド・サービスの両方に必要なすべての依存関係が含まれます。
マイクロサービス・ベーシック・スターターは、Java で使用可能です。
<!--
## Other
{: #other}
The Other pattern represents a project that consists of only the language-specific server-side web framework. It has all the other file assets to work with the project, such as needed libraries and config files.
Content to be provided by Karl Bishop.
-->
### 言語
{: #languages notoc}
サポートされる言語は、以下のとおりです。
* [Java ](../runtimes/liberty/getting-started.html){: new_window}
* [Node.js ](../runtimes/nodejs/getting-started.html){: new_window}
* [Swift ](../runtimes/swift/getting-started.html){: new_window}
#### Java
{: #java notoc}
Java には、エンタープライズ規模のアプリケーションを構築するための実証された機能があります。しかし、Java 8 の新機能では、Liberty のような軽量のランタイムと Spring Boot のようなフレームワークと組み合わせて、Java をマイクロサービスの構築にも最適なものにしています。
#### Node.js
{: #node notoc}
Node.js は、イベント・ドリブンの非ブロッキング入出力モデルを使用し、軽量化と効率化を図った JavaScript ランタイムで、Web アプリケーション、Backend for Frontends (BFF) パターン、およびマイクロサービスのスループットと拡張性に優れています。Node.js のパッケージ・エコシステムである npm により、非常に数多くのオープン・ソース・モジュールにアクセス可能になり、アプリケーション開発を加速する幅広い機能が提供されます。
#### Swift
{: #swift notoc}
Swift は、2014 年に Apple によって作成された最新のプログラミング言語です。Objective C の使用に置き換わるものとして設計され、2015 年 12 月にオープン・ソース化されました。今日では、x86、ARM、または Z アーキテクチャーを使用した Linux および macOS のオペレーティング・システムで、iOS、macOS、Web サービス、およびシステム・ソフトウェアを構築するために使用されます。スクリプト言語のように記述しますが、コンパイルされるとオーバーヘッドが少なく C のようなハイパフォーマンスを実現し、クラウド・ランタイムに理想的です。Java で見られる強力で静的なタイプのシステムを使用しながら、JavaScript で見られる機能スタイルおよび非同期ルーチンを使用しています。非常に高性能で、ソースは LLVM コンパイラー・ツールチェーンを使用してネイティブ・コードにコンパイルされ、C で記述された外部システム・ライブラリーを簡単に利用できます。
## スターター
{: #starters}
{{site.data.keyword.Bluemix}} {{site.data.keyword.dev_console}} で、各パターン・タイプに対応したさまざまなスターターから選択することができます。
スターターは、主要な {{site.data.keyword.Bluemix_notm}} と高価値サービスとの統合を示すことに焦点を当てた、実動準備の完了したスターター・コードになるように最適化されています。各スターターが 1 つのサービスに焦点を合わせていて、コードへのサービス SDK の統合を示します。場合によっては、スターターは、シンプルなユーザー・エクスペリエンスを提供してサービス・データの統合やユーザーとの対話を特長とします。プロジェクト用に Authentication (認証)、Data (データ)、およびその他の機能を構成すると決めた場合、各スターターはそれらの機能を有効にするように構成されます。
|
apache-2.0
|
ev1stensberg/lighthouse
|
lighthouse-core/audits/third-party-facades.js
|
11065
|
/**
* @license Copyright 2020 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
/**
* @fileoverview Audit which identifies third-party code on the page which can be lazy loaded.
* The audit will recommend a facade alternative which is used to imitate the third-party resource until it is needed.
*
* Entity: Set of domains which are used by a company or product area to deliver third-party resources
* Product: Specific piece of software belonging to an entity. Entities can have multiple products.
* Facade: Placeholder for a product which looks likes the actual product and replaces itself with that product when the user needs it.
*/
/** @typedef {import("third-party-web").IEntity} ThirdPartyEntity */
/** @typedef {import("third-party-web").IProduct} ThirdPartyProduct*/
/** @typedef {import("third-party-web").IFacade} ThirdPartyFacade*/
/** @typedef {{product: ThirdPartyProduct, entity: ThirdPartyEntity}} FacadableProduct */
const Audit = require('./audit.js');
const i18n = require('../lib/i18n/i18n.js');
const thirdPartyWeb = require('../lib/third-party-web.js');
const NetworkRecords = require('../computed/network-records.js');
const MainResource = require('../computed/main-resource.js');
const MainThreadTasks = require('../computed/main-thread-tasks.js');
const ThirdPartySummary = require('./third-party-summary.js');
const UIStrings = {
/** Title of a diagnostic audit that provides details about the third-party code on a web page that can be lazy loaded with a facade alternative. This descriptive title is shown to users when no resources have facade alternatives available. A facade is a lightweight component which looks like the desired resource. Lazy loading means resources are deferred until they are needed. Third-party code refers to resources that are not within the control of the site owner. */
title: 'Lazy load third-party resources with facades',
/** Title of a diagnostic audit that provides details about the third-party code on a web page that can be lazy loaded with a facade alternative. This descriptive title is shown to users when one or more third-party resources have available facade alternatives. A facade is a lightweight component which looks like the desired resource. Lazy loading means resources are deferred until they are needed. Third-party code refers to resources that are not within the control of the site owner. */
failureTitle: 'Some third-party resources can be lazy loaded with a facade',
/** Description of a Lighthouse audit that identifies the third-party code on the page that can be lazy loaded with a facade alternative. This is displayed after a user expands the section to see more. No character length limits. 'Learn More' becomes link text to additional documentation. A facade is a lightweight component which looks like the desired resource. Lazy loading means resources are deferred until they are needed. Third-party code refers to resources that are not within the control of the site owner. */
description: 'Some third-party embeds can be lazy loaded. ' +
'Consider replacing them with a facade until they are required. [Learn more](https://web.dev/third-party-facades/).',
/** Summary text for the result of a Lighthouse audit that identifies the third-party code on a web page that can be lazy loaded with a facade alternative. This text summarizes the number of lazy loading facades that can be used on the page. A facade is a lightweight component which looks like the desired resource. */
displayValue: `{itemCount, plural,
=1 {# facade alternative available}
other {# facade alternatives available}
}`,
/** Label for a table column that displays the name of the product that a URL is used for. The products in the column will be pieces of software used on the page, like the "YouTube Embedded Player" or the "Drift Live Chat" box. */
columnProduct: 'Product',
/**
* @description Template for a table entry that gives the name of a product which we categorize as video related.
* @example {YouTube Embedded Player} productName
*/
categoryVideo: '{productName} (Video)',
/**
* @description Template for a table entry that gives the name of a product which we categorize as customer success related. Customer success means the product supports customers by offering chat and contact solutions.
* @example {Intercom Widget} productName
*/
categoryCustomerSuccess: '{productName} (Customer Success)',
/**
* @description Template for a table entry that gives the name of a product which we categorize as marketing related.
* @example {Drift Live Chat} productName
*/
categoryMarketing: '{productName} (Marketing)',
/**
* @description Template for a table entry that gives the name of a product which we categorize as social related.
* @example {Facebook Messenger Customer Chat} productName
*/
categorySocial: '{productName} (Social)',
};
const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings);
/** @type {Record<string, string>} */
const CATEGORY_UI_MAP = {
'video': UIStrings.categoryVideo,
'customer-success': UIStrings.categoryCustomerSuccess,
'marketing': UIStrings.categoryMarketing,
'social': UIStrings.categorySocial,
};
class ThirdPartyFacades extends Audit {
/**
* @return {LH.Audit.Meta}
*/
static get meta() {
return {
id: 'third-party-facades',
title: str_(UIStrings.title),
failureTitle: str_(UIStrings.failureTitle),
description: str_(UIStrings.description),
requiredArtifacts: ['traces', 'devtoolsLogs', 'URL'],
};
}
/**
* Sort items by transfer size and combine small items into a single row.
* Items will be mutated in place to a maximum of 6 rows.
* @param {ThirdPartySummary.URLSummary[]} items
*/
static condenseItems(items) {
items.sort((a, b) => b.transferSize - a.transferSize);
// Items <1KB are condensed. If all items are <1KB, condense all but the largest.
let splitIndex = items.findIndex((item) => item.transferSize < 1000) || 1;
// Show details for top 5 items.
if (splitIndex === -1 || splitIndex > 5) splitIndex = 5;
// If there is only 1 item to condense, leave it as is.
if (splitIndex >= items.length - 1) return;
const remainder = items.splice(splitIndex);
const finalItem = remainder.reduce((result, item) => {
result.transferSize += item.transferSize;
result.blockingTime += item.blockingTime;
return result;
});
// If condensed row is still <1KB, don't show it.
if (finalItem.transferSize < 1000) return;
finalItem.url = str_(i18n.UIStrings.otherResourcesLabel);
items.push(finalItem);
}
/**
* @param {Map<string, ThirdPartySummary.Summary>} byURL
* @param {ThirdPartyEntity | undefined} mainEntity
* @return {FacadableProduct[]}
*/
static getProductsWithFacade(byURL, mainEntity) {
/** @type {Map<string, FacadableProduct>} */
const facadableProductMap = new Map();
for (const url of byURL.keys()) {
const entity = thirdPartyWeb.getEntity(url);
if (!entity || thirdPartyWeb.isFirstParty(url, mainEntity)) continue;
const product = thirdPartyWeb.getProduct(url);
if (!product || !product.facades || !product.facades.length) continue;
if (facadableProductMap.has(product.name)) continue;
facadableProductMap.set(product.name, {product, entity});
}
return Array.from(facadableProductMap.values());
}
/**
* @param {LH.Artifacts} artifacts
* @param {LH.Audit.Context} context
* @return {Promise<LH.Audit.Product>}
*/
static async audit(artifacts, context) {
const settings = context.settings;
const trace = artifacts.traces[Audit.DEFAULT_PASS];
const devtoolsLog = artifacts.devtoolsLogs[Audit.DEFAULT_PASS];
const networkRecords = await NetworkRecords.request(devtoolsLog, context);
const mainResource = await MainResource.request({devtoolsLog, URL: artifacts.URL}, context);
const mainEntity = thirdPartyWeb.getEntity(mainResource.url);
const tasks = await MainThreadTasks.request(trace, context);
const multiplier = settings.throttlingMethod === 'simulate' ?
settings.throttling.cpuSlowdownMultiplier : 1;
const summaries = ThirdPartySummary.getSummaries(networkRecords, tasks, multiplier);
const facadableProducts =
ThirdPartyFacades.getProductsWithFacade(summaries.byURL, mainEntity);
/** @type {LH.Audit.Details.TableItem[]} */
const results = [];
for (const {product, entity} of facadableProducts) {
const categoryTemplate = CATEGORY_UI_MAP[product.categories[0]];
let productWithCategory;
if (categoryTemplate) {
// Display product name with category next to it in the same column.
productWithCategory = str_(categoryTemplate, {productName: product.name});
} else {
// Just display product name if no category is found.
productWithCategory = product.name;
}
const urls = summaries.urls.get(entity);
const entitySummary = summaries.byEntity.get(entity);
if (!urls || !entitySummary) continue;
const items = Array.from(urls).map((url) => {
const urlStats = summaries.byURL.get(url);
return /** @type {ThirdPartySummary.URLSummary} */ ({url, ...urlStats});
});
this.condenseItems(items);
results.push({
product: productWithCategory,
transferSize: entitySummary.transferSize,
blockingTime: entitySummary.blockingTime,
subItems: {type: 'subitems', items},
});
}
if (!results.length) {
return {
score: 1,
notApplicable: true,
};
}
/** @type {LH.Audit.Details.Table['headings']} */
const headings = [
/* eslint-disable max-len */
{key: 'product', itemType: 'text', subItemsHeading: {key: 'url', itemType: 'url'}, text: str_(UIStrings.columnProduct)},
{key: 'transferSize', itemType: 'bytes', subItemsHeading: {key: 'transferSize'}, granularity: 1, text: str_(i18n.UIStrings.columnTransferSize)},
{key: 'blockingTime', itemType: 'ms', subItemsHeading: {key: 'blockingTime'}, granularity: 1, text: str_(i18n.UIStrings.columnBlockingTime)},
/* eslint-enable max-len */
];
return {
score: 0,
displayValue: str_(UIStrings.displayValue, {
itemCount: results.length,
}),
details: Audit.makeTableDetails(headings, results),
};
}
}
module.exports = ThirdPartyFacades;
module.exports.UIStrings = UIStrings;
|
apache-2.0
|
LBiNetherlands/LBi.Cli.Arguments
|
LBi.Cli.Arguments/Parsing/Ast/LiteralValueType.cs
|
759
|
/*
* Copyright 2012 LBi Netherlands B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace LBi.Cli.Arguments.Parsing.Ast
{
public enum LiteralValueType
{
Numeric,
String,
Null,
Boolean,
}
}
|
apache-2.0
|
groupon/promise
|
src/main/java/com/groupon/promise/function/PromiseFunctionResult.java
|
1887
|
/**
* Copyright 2015 Groupon.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.groupon.promise.function;
import com.groupon.promise.AsyncPromiseFunction;
import com.groupon.promise.ComparablePromiseFunction;
import com.groupon.promise.DefaultPromiseFuture;
import com.groupon.promise.PromiseFuture;
import com.groupon.promise.SyncPromiseFunction;
/**
* Wrapper for getting the future result from a synchronous promise function.
*
* @author Stuart Siegrist (fsiegrist at groupon dot com)
* @since 0.1
*/
public class PromiseFunctionResult<T, O> implements AsyncPromiseFunction<T, O>, ComparablePromiseFunction {
protected SyncPromiseFunction<T, ? extends O> promiseFunction;
public PromiseFunctionResult(SyncPromiseFunction<T, ? extends O> promiseFunction) {
this.promiseFunction = promiseFunction;
}
@Override
public PromiseFuture<O> handle(T data) {
PromiseFuture<O> future = new DefaultPromiseFuture<>();
try {
future.setResult(promiseFunction.handle(data));
} catch (Throwable t) {
future.setFailure(t);
}
return future;
}
@Override
public boolean equivalent(Object o) {
return this == o || (o != null && o instanceof ComparablePromiseFunction &&
((ComparablePromiseFunction) o).equivalent(promiseFunction));
}
}
|
apache-2.0
|
NeilRen/NEILREN4J
|
src/main/java/com/neilren/neilren4j/dao/TLogSendEmailMapper.java
|
366
|
package com.neilren.neilren4j.dao;
import com.neilren.neilren4j.dbentity.TLogSendEmail;
import java.util.List;
public interface TLogSendEmailMapper {
int deleteByPrimaryKey(Long id);
int insert(TLogSendEmail record);
TLogSendEmail selectByPrimaryKey(Long id);
List<TLogSendEmail> selectAll();
int updateByPrimaryKey(TLogSendEmail record);
}
|
apache-2.0
|
zhouronglv/myapp
|
myapp-demo/src/main/java/com/myapp/demo/spring/proxy/PerformanceHandler.java
|
696
|
package com.myapp.demo.spring.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* Created by Zhourl on 2017/8/11.
*/
public class PerformanceHandler implements InvocationHandler {//①实现InvocationHandler
private Object target;
public PerformanceHandler(Object target) {//②target为目标的业务类
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
PerformanceMonitor.begin(target.getClass().getName() + "." + method.getName());
Object obj = method.invoke(target, args);
PerformanceMonitor.end();
return obj;
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Sordariomycetes/Hypocreales/Nectriaceae/Calonectria/Calonectria parasitica/README.md
|
285
|
# Calonectria parasitica Saccas SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Étude de la Flore Cryptogamique des Caféirs en Afrique Centrale, (Bulletin IFCC <b>16</b>) 44 (1981)
#### Original name
Calonectria parasitica Saccas
### Remarks
null
|
apache-2.0
|
openshift/sti-nodejs
|
examples/from-dockerfile/Dockerfile
|
209
|
FROM registry.access.redhat.com/ubi8/nodejs-12
# Add application sources
ADD app-src .
# Install the dependencies
RUN npm install
# Run script uses standard ways to run the application
CMD npm run -d start
|
apache-2.0
|
suxi-lu/learn
|
learn-service/src/main/java/io/github/suxil/service/LearnServiceApplication.java
|
1309
|
package io.github.suxil.service;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestTemplate;
/**
* @Author: luxq
* @Description:
* @Date: Created in 2018/5/27 0027 12:08
*/
@SpringBootApplication
@ComponentScan("io.github.suxil")
@EnableDiscoveryClient
@EnableFeignClients("io.github.suxil")
@RibbonClients
@EnableTransactionManagement
@MapperScan("io.github.suxil.service.**.mapper")
public class LearnServiceApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
new SpringApplicationBuilder(LearnServiceApplication.class).run(args);
}
}
|
apache-2.0
|
graymeta/stow
|
b2/stow_test.go
|
3088
|
package b2
import (
"math/rand"
"os"
"strings"
"testing"
"time"
isi "github.com/cheekybits/is"
"github.com/graymeta/stow"
"github.com/graymeta/stow/test"
)
func TestStow(t *testing.T) {
is := isi.New(t)
accountID := os.Getenv("B2_ACCOUNT_ID")
applicationKey := os.Getenv("B2_APPLICATION_KEY")
if accountID == "" || applicationKey == "" {
t.Skip("Backblaze credentials missing from environment. Skipping tests")
}
cfg := stow.ConfigMap{
"account_id": accountID,
"application_key": applicationKey,
}
location, err := stow.Dial("b2", cfg)
is.NoErr(err)
is.OK(location)
t.Run("basic stow interface tests", func(t *testing.T) {
test.All(t, "b2", cfg)
})
// This test is designed to test the container.Items() function. B2 doesn't
// support listing items in a bucket by prefix, so our implementation fakes this
// functionality by requesting additional pages of files
t.Run("Items with prefix", func(t *testing.T) {
is := isi.New(t)
container, err := location.CreateContainer("stowtest" + randName(10))
is.NoErr(err)
is.OK(container)
defer func() {
is.NoErr(location.RemoveContainer(container.ID()))
}()
// add some items to the container
content := "foo"
item1, err := container.Put("b/a", strings.NewReader(content), int64(len(content)), nil)
is.NoErr(err)
item2, err := container.Put("b/bb", strings.NewReader(content), int64(len(content)), nil)
is.NoErr(err)
item3, err := container.Put("b/bc", strings.NewReader(content), int64(len(content)), nil)
is.NoErr(err)
item4, err := container.Put("b/bd", strings.NewReader(content), int64(len(content)), nil)
is.NoErr(err)
defer func() {
is.NoErr(container.RemoveItem(item1.ID()))
is.NoErr(container.RemoveItem(item2.ID()))
is.NoErr(container.RemoveItem(item3.ID()))
is.NoErr(container.RemoveItem(item4.ID()))
}()
items, cursor, err := container.Items("b/b", stow.CursorStart, 2)
is.NoErr(err)
is.Equal(len(items), 2)
is.Equal(cursor, "b/bc ")
items, cursor, err = container.Items("", stow.CursorStart, 2)
is.NoErr(err)
is.Equal(len(items), 2)
is.Equal(cursor, "b/bb ")
})
t.Run("Item Delete", func(t *testing.T) {
is := isi.New(t)
container, err := location.CreateContainer("stowtest" + randName(10))
is.NoErr(err)
is.OK(container)
defer func() {
is.NoErr(location.RemoveContainer(container.ID()))
}()
// Put an item twice, creating two versions of the file
content := "foo"
i, err := container.Put("foo", strings.NewReader(content), int64(len(content)), nil)
is.NoErr(err)
content = "foo_v2"
_, err = container.Put("foo", strings.NewReader(content), int64(len(content)), nil)
is.NoErr(err)
is.NoErr(container.RemoveItem(i.ID()))
// verify item is gone
_, err = container.Item(i.ID())
is.Equal(err, stow.ErrNotFound)
})
}
func randName(length int) string {
b := make([]rune, length)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
var letters = []rune("abcdefghijklmnopqrstuvwxyz")
func init() {
rand.Seed(int64(time.Now().Nanosecond()))
}
|
apache-2.0
|
markini/ServiceMonitoringTestSystem
|
Client/src/main/java/marki/at/Client/events/newMessageEvent.java
|
266
|
package marki.at.Client.events;
import marki.at.Client.utils.Message;
/**
* Created by marki on 29.10.13.
*/
public class newMessageEvent {
public final Message message;
public newMessageEvent(Message message) {
this.message = message;
}
}
|
apache-2.0
|
maloteiro/hermes
|
base/html/processo/processo_formCadastro.html
|
6273
|
{literal}
<!--script type="text/javascript" src="./libs/js/multiple-file-upload/jquery.MultiFile.pack.js"></script-->
<script type="text/javascript" src="./libs/php/tags/src/jquery.tagsinput.js"></script>
<link rel="stylesheet" type="text/css" href="./libs/php/tags/src/jquery.tagsinput.css" />
<script type="text/javascript" src="./libs/js/ajax/processo/processo.js" charset="iso-8859-1"></script>
<style>
.MultiFile-label {
background-color: #F5F5F5;
border: 2px solid #E5E5E5;
font: 11px Verdana, Geneva, sans-serif;
margin-top: 5px;
padding: 10px;
}
.ui-datepicker-trigger {
background: none repeat scroll 0 0 transparent;
border-style: none;
border-width: 5px 0 0;
}
.cke_skin_kama {
float: left;
}
.MultiFile-wrap {
clear: none !important;
}
.MultiFile-list {
width: 450px;
margin-left: 0px !important;
}
.tagsinput {
clear: none !important;
}
</style>
<script>
$(function(){
$('#nom_cliente_nome_razao').tagsInput({
width: '500px',
autocomplete_url:'index.php?a=processo&d=processo&f=ajaxCliente'
});
});
</script>
{/literal}
<table id="table_message" width="100%" class="login_box" style="display:none;">
<tr>
<td id="messageBoxAtribuicao">
</td>
</tr>
</table>
<br />
<div id="message-red" {if !$smarty.request.msg}style="display:none;"{/if}>
<table border="0" width="100%" cellpadding="0" cellspacing="0">
<tr>
<td class="red-left">
<a href="#">{$smarty.request.msg}</a>
</td>
<td class="red-right">
<a class="close-red">
<img src="./imgs/table/icon_close_red.gif" alt="" />
</a>
</td>
</tr>
</table>
</div>
<div class="box_cabecalho">
Cadastro de processos
</div>
<div class="box">
<form id="formulario" name="formulario" action="?" method="POST" enctype="multipart/form-data">
{dynamic}
<input type="hidden" name="d" id="d" value="{$smarty.post.d}" />
<input type="hidden" name="a" id="a" value="{$smarty.post.a}" />
<input type="hidden" name="f" id="f" value="salvarCadastro" />
<input type="hidden" name="token" id="token" value="{$smarty.session.token}" />
<input type="hidden" name="seq_processo" id="seq_processo" value="{$dados.seq_processo}" />
<center>
<table border='0'>
<tr>
<td colspan="2" align="left">
<label for="num_processo_numero">Número Processo</label>
</td>
</tr>
<tr>
<td colspan="2" align="left">
<input type="text" name="num_processo_numero" id="num_processo_numero" size="30" value="{$dados.num_processo_numero}" class="required" maxlength='25' alt="numeroProcesso" required/> (Obrigatório)
</td>
</tr>
<tr >
<td colspan="2" align="left">
<label for="dat_processo_distribuicao">Data da Distribuição</label>
</td>
</tr>
<tr>
<td colspan="2" align="left">
<input type="text" name="dat_processo_distribuicao" id="dat_processo_distribuicao" size="20" value="{if $dados.dat_processo_distribuicao!="0000-00-00"}{$dados.dat_processo_distribuicao|date_format:"%d/%m/%Y"}{/if}" maxlength='20' alt="dateBR" required/> (Obrigatório)
</td>
</tr>
<tr>
<td colspan="2" align="left">
<label for="dsc_processo_orgao_julgador">Órgão Julgador</label>
</td>
</tr>
<tr>
<td colspan="2" align="left">
<input type="text" name="dsc_processo_orgao_julgador" id="dsc_processo_orgao_julgador" size="45" value="{$dados.dsc_processo_orgao_julgador}" maxlength='150' class="required" required/> (Obrigatório)
</td>
</tr>
<tr>
<td colspan="2" align="left">
<label for="dsc_processo_classe">Classe Judicial</label>
</td>
</tr>
<tr>
<td colspan="2" align="left">
<input type="text" name="dsc_processo_classe" id="dsc_processo_classe" size="45" value="{$dados.dsc_processo_classe}" maxlength='255' class="required" required/> (Obrigatório)
</td>
</tr>
<tr>
<td colspan="2" align="left">
<label for="dsc_processo_assunto">Assunto</label>
</td>
</tr>
<tr>
<td colspan="2" align="left">
<input type="text" name="dsc_processo_assunto" id="dsc_processo_assunto" size="45" value="{$dados.dsc_processo_assunto}" maxlength='500' class="required" required/> (Obrigatório)
</td>
</tr>
<tr>
<td colspan="2" align="left">
<label for="flg_processo_encerrado">Encerrado</label>
</td>
</tr>
<tr>
<td align="left">
<input type="checkbox" name="flg_processo_encerrado" id="flg_processo_encerrado" value="S" {if $dados.flg_processo_encerrado=="S"}checked{/if}/> Sim
</td>
</tr>
<tr>
<td colspan="2" align="left">
<label for="nom_cliente_nome_razao">Autor</label>
</td>
</tr>
<tr>
<td align="left">
<input name="nom_cliente_nome_razao" id='nom_cliente_nome_razao' type='text' class='tags' value="{$dados.nom_cliente_nome_razao}" class="required" required>
</td>
</tr>
</table>
<br>
</center>
<br/>
<table align="center">
<tr>
<td align="center" >
<button type="submit" name="btn_gravar" id="btn_gravar" role="button" class="botoes ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" title="Clique no botão para salvar" alt="Clique no botão para salvar">
<span class="ui-button-text">Salvar</span>
</button>
<button type="button" name="btn_add_novo" id="btn_add_novo" role="button" class="botoes ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" title="Clique no botão para novo cadastro" alt="Clique no botão para novo cadastro">
<span class="ui-button-text">Novo</span>
</button>
<button type="button" name="btn_pesquisar" id="btn_pesquisar" role="button" class="botoes ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" title="Clique no botão para pesquisar" alt="Clique no botão para pesquisar">
<span class="ui-button-text">Pesquisar</span>
</button>
</td>
</tr>
</table>
<br>
{/dynamic}
</form>
</div>
|
apache-2.0
|
JoyIfBam5/aws-sdk-cpp
|
aws-cpp-sdk-waf/include/aws/waf/model/ListLoggingConfigurationsRequest.h
|
8038
|
/*
* 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/waf/WAF_EXPORTS.h>
#include <aws/waf/WAFRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace WAF
{
namespace Model
{
/**
*/
class AWS_WAF_API ListLoggingConfigurationsRequest : public WAFRequest
{
public:
ListLoggingConfigurationsRequest();
// 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 "ListLoggingConfigurations"; }
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>If you specify a value for <code>Limit</code> and you have more
* <code>LoggingConfigurations</code> than the value of <code>Limit</code>, AWS WAF
* returns a <code>NextMarker</code> value in the response that allows you to list
* another group of <code>LoggingConfigurations</code>. For the second and
* subsequent <code>ListLoggingConfigurations</code> requests, specify the value of
* <code>NextMarker</code> from the previous response to get information about
* another batch of <code>ListLoggingConfigurations</code>.</p>
*/
inline const Aws::String& GetNextMarker() const{ return m_nextMarker; }
/**
* <p>If you specify a value for <code>Limit</code> and you have more
* <code>LoggingConfigurations</code> than the value of <code>Limit</code>, AWS WAF
* returns a <code>NextMarker</code> value in the response that allows you to list
* another group of <code>LoggingConfigurations</code>. For the second and
* subsequent <code>ListLoggingConfigurations</code> requests, specify the value of
* <code>NextMarker</code> from the previous response to get information about
* another batch of <code>ListLoggingConfigurations</code>.</p>
*/
inline void SetNextMarker(const Aws::String& value) { m_nextMarkerHasBeenSet = true; m_nextMarker = value; }
/**
* <p>If you specify a value for <code>Limit</code> and you have more
* <code>LoggingConfigurations</code> than the value of <code>Limit</code>, AWS WAF
* returns a <code>NextMarker</code> value in the response that allows you to list
* another group of <code>LoggingConfigurations</code>. For the second and
* subsequent <code>ListLoggingConfigurations</code> requests, specify the value of
* <code>NextMarker</code> from the previous response to get information about
* another batch of <code>ListLoggingConfigurations</code>.</p>
*/
inline void SetNextMarker(Aws::String&& value) { m_nextMarkerHasBeenSet = true; m_nextMarker = std::move(value); }
/**
* <p>If you specify a value for <code>Limit</code> and you have more
* <code>LoggingConfigurations</code> than the value of <code>Limit</code>, AWS WAF
* returns a <code>NextMarker</code> value in the response that allows you to list
* another group of <code>LoggingConfigurations</code>. For the second and
* subsequent <code>ListLoggingConfigurations</code> requests, specify the value of
* <code>NextMarker</code> from the previous response to get information about
* another batch of <code>ListLoggingConfigurations</code>.</p>
*/
inline void SetNextMarker(const char* value) { m_nextMarkerHasBeenSet = true; m_nextMarker.assign(value); }
/**
* <p>If you specify a value for <code>Limit</code> and you have more
* <code>LoggingConfigurations</code> than the value of <code>Limit</code>, AWS WAF
* returns a <code>NextMarker</code> value in the response that allows you to list
* another group of <code>LoggingConfigurations</code>. For the second and
* subsequent <code>ListLoggingConfigurations</code> requests, specify the value of
* <code>NextMarker</code> from the previous response to get information about
* another batch of <code>ListLoggingConfigurations</code>.</p>
*/
inline ListLoggingConfigurationsRequest& WithNextMarker(const Aws::String& value) { SetNextMarker(value); return *this;}
/**
* <p>If you specify a value for <code>Limit</code> and you have more
* <code>LoggingConfigurations</code> than the value of <code>Limit</code>, AWS WAF
* returns a <code>NextMarker</code> value in the response that allows you to list
* another group of <code>LoggingConfigurations</code>. For the second and
* subsequent <code>ListLoggingConfigurations</code> requests, specify the value of
* <code>NextMarker</code> from the previous response to get information about
* another batch of <code>ListLoggingConfigurations</code>.</p>
*/
inline ListLoggingConfigurationsRequest& WithNextMarker(Aws::String&& value) { SetNextMarker(std::move(value)); return *this;}
/**
* <p>If you specify a value for <code>Limit</code> and you have more
* <code>LoggingConfigurations</code> than the value of <code>Limit</code>, AWS WAF
* returns a <code>NextMarker</code> value in the response that allows you to list
* another group of <code>LoggingConfigurations</code>. For the second and
* subsequent <code>ListLoggingConfigurations</code> requests, specify the value of
* <code>NextMarker</code> from the previous response to get information about
* another batch of <code>ListLoggingConfigurations</code>.</p>
*/
inline ListLoggingConfigurationsRequest& WithNextMarker(const char* value) { SetNextMarker(value); return *this;}
/**
* <p>Specifies the number of <code>LoggingConfigurations</code> that you want AWS
* WAF to return for this request. If you have more
* <code>LoggingConfigurations</code> than the number that you specify for
* <code>Limit</code>, the response includes a <code>NextMarker</code> value that
* you can use to get another batch of <code>LoggingConfigurations</code>.</p>
*/
inline int GetLimit() const{ return m_limit; }
/**
* <p>Specifies the number of <code>LoggingConfigurations</code> that you want AWS
* WAF to return for this request. If you have more
* <code>LoggingConfigurations</code> than the number that you specify for
* <code>Limit</code>, the response includes a <code>NextMarker</code> value that
* you can use to get another batch of <code>LoggingConfigurations</code>.</p>
*/
inline void SetLimit(int value) { m_limitHasBeenSet = true; m_limit = value; }
/**
* <p>Specifies the number of <code>LoggingConfigurations</code> that you want AWS
* WAF to return for this request. If you have more
* <code>LoggingConfigurations</code> than the number that you specify for
* <code>Limit</code>, the response includes a <code>NextMarker</code> value that
* you can use to get another batch of <code>LoggingConfigurations</code>.</p>
*/
inline ListLoggingConfigurationsRequest& WithLimit(int value) { SetLimit(value); return *this;}
private:
Aws::String m_nextMarker;
bool m_nextMarkerHasBeenSet;
int m_limit;
bool m_limitHasBeenSet;
};
} // namespace Model
} // namespace WAF
} // namespace Aws
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Dendrobium/Dendrobium hamiferum/README.md
|
188
|
# Dendrobium hamiferum P.J.Cribb SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
CXuesong/WikiClientLibrary
|
WikiClientLibrary/Sites/WikiSiteToken.cs
|
850
|
using System;
using System.Collections.Generic;
using System.Text;
using WikiClientLibrary.Client;
namespace WikiClientLibrary.Sites
{
/// <summary>
/// Represents a token placeholder in the <see cref="MediaWikiFormRequestMessage"/>.
/// This enables <see cref="WikiSite"/> to detect bad tokens.
/// </summary>
public sealed class WikiSiteToken
{
public static WikiSiteToken Edit = new WikiSiteToken("edit");
public static WikiSiteToken Move = new WikiSiteToken("move");
public static WikiSiteToken Delete = new WikiSiteToken("delete");
public static WikiSiteToken Patrol = new WikiSiteToken("patrol");
public WikiSiteToken(string type)
{
Type = type ?? throw new ArgumentNullException(nameof(type));
}
public string Type { get; }
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Strophariaceae/Psilocybe/Psilocybe peladae/README.md
|
208
|
# Psilocybe peladae Singer SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Nova Hedwigia, Beih. 29: 254 (1969)
#### Original name
Psilocybe peladae Singer
### Remarks
null
|
apache-2.0
|
learning-layers/SocialSemanticServer
|
servs/livingdocument/livingdocument.datatype/src/main/java/at/tugraz/sss/servs/livingdocument/datatype/SSLivingDocSQLTableE.java
|
1146
|
/**
* Code contributed to the Learning Layers project
* http://www.learning-layers.eu
* Development is partly funded by the FP7 Programme of the European Commission under
* Grant Agreement FP7-ICT-318209.
* Copyright (c) 2016, Graz University of Technology - KTI (Knowledge Technologies Institute).
* For a list of contributors see the AUTHORS file at the top-level directory of this distribution.
*
* 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 at.tugraz.sss.servs.livingdocument.datatype;
import at.tugraz.sss.serv.db.api.*;
public enum SSLivingDocSQLTableE implements SSSQLTableI{
livingdoc,
livingdocusers;
}
|
apache-2.0
|
amriteshkumar1/sales-service
|
node_modules/pubnub/src/core/components/subscription_manager.js
|
10768
|
/* @flow */
import Crypto from '../components/cryptography';
import Config from '../components/config';
import ListenerManager from '../components/listener_manager';
import ReconnectionManager from '../components/reconnection_manager';
import utils from '../utils';
import { MessageAnnouncement, SubscribeEnvelope, StatusAnnouncement, PresenceAnnouncement } from '../flow_interfaces';
import categoryConstants from '../constants/categories';
type SubscribeArgs = {
channels: Array<string>,
channelGroups: Array<string>,
withPresence: ?boolean,
timetoken: ?number
}
type UnsubscribeArgs = {
channels: Array<string>,
channelGroups: Array<string>
}
type StateArgs = {
channels: Array<string>,
channelGroups: Array<string>,
state: Object
}
type SubscriptionManagerConsturct = {
leaveEndpoint: Function,
subscribeEndpoint: Function,
timeEndpoint: Function,
heartbeatEndpoint: Function,
setStateEndpoint: Function,
config: Config,
crypto: Crypto,
listenerManager: ListenerManager
}
export default class {
_crypto: Crypto;
_config: Config;
_listenerManager: ListenerManager;
_reconnectionManager: ReconnectionManager;
_leaveEndpoint: Function;
_heartbeatEndpoint: Function;
_setStateEndpoint: Function;
_subscribeEndpoint: Function;
_channels: Object;
_presenceChannels: Object;
_channelGroups: Object;
_presenceChannelGroups: Object;
_timetoken: number;
_region: number;
_subscribeCall: ?Object;
_heartbeatTimer: ?number;
_subscriptionStatusAnnounced: boolean;
constructor({ subscribeEndpoint, leaveEndpoint, heartbeatEndpoint, setStateEndpoint, timeEndpoint, config, crypto, listenerManager }: SubscriptionManagerConsturct) {
this._listenerManager = listenerManager;
this._config = config;
this._leaveEndpoint = leaveEndpoint;
this._heartbeatEndpoint = heartbeatEndpoint;
this._setStateEndpoint = setStateEndpoint;
this._subscribeEndpoint = subscribeEndpoint;
this._crypto = crypto;
this._channels = {};
this._presenceChannels = {};
this._channelGroups = {};
this._presenceChannelGroups = {};
this._timetoken = 0;
this._subscriptionStatusAnnounced = false;
this._reconnectionManager = new ReconnectionManager({ timeEndpoint });
}
adaptStateChange(args: StateArgs, callback: Function) {
const { state, channels = [], channelGroups = [] } = args;
channels.forEach((channel) => {
if (channel in this._channels) this._channels[channel].state = state;
});
channelGroups.forEach((channelGroup) => {
if (channelGroup in this._channelGroups) this._channelGroups[channelGroup].state = state;
});
this._setStateEndpoint({ state, channels, channelGroups }, callback);
}
adaptSubscribeChange(args: SubscribeArgs) {
const { timetoken, channels = [], channelGroups = [], withPresence = false } = args;
if (timetoken) this._timetoken = timetoken;
channels.forEach((channel) => {
this._channels[channel] = { state: {} };
if (withPresence) this._presenceChannels[channel] = {};
});
channelGroups.forEach((channelGroup) => {
this._channelGroups[channelGroup] = { state: {} };
if (withPresence) this._presenceChannelGroups[channelGroup] = {};
});
this._subscriptionStatusAnnounced = false;
this.reconnect();
}
adaptUnsubscribeChange(args: UnsubscribeArgs) {
const { channels = [], channelGroups = [] } = args;
channels.forEach((channel) => {
if (channel in this._channels) delete this._channels[channel];
if (channel in this._presenceChannels) delete this._presenceChannels[channel];
});
channelGroups.forEach((channelGroup) => {
if (channelGroup in this._channelGroups) delete this._channelGroups[channelGroup];
if (channelGroup in this._presenceChannelGroups) delete this._channelGroups[channelGroup];
});
if (this._config.suppressLeaveEvents === false) {
this._leaveEndpoint({ channels, channelGroups }, (status) => {
this._listenerManager.announceStatus(status);
});
}
this.reconnect();
}
unsubscribeAll() {
this.adaptUnsubscribeChange({ channels: this.getSubscribedChannels(), channelGroups: this.getSubscribedChannelGroups() });
}
getSubscribedChannels() {
return Object.keys(this._channels);
}
getSubscribedChannelGroups() {
return Object.keys(this._channelGroups);
}
reconnect() {
this._startSubscribeLoop();
this._registerHeartbeatTimer();
}
disconnect() {
this._stopSubscribeLoop();
this._stopHeartbeatTimer();
}
_registerHeartbeatTimer() {
this._stopHeartbeatTimer();
this._performHeartbeatLoop();
this._heartbeatTimer = setInterval(this._performHeartbeatLoop.bind(this), this._config.getHeartbeatInterval() * 1000);
}
_stopHeartbeatTimer() {
if (this._heartbeatTimer) {
clearInterval(this._heartbeatTimer);
this._heartbeatTimer = null;
}
}
_performHeartbeatLoop() {
let presenceChannels = Object.keys(this._channels);
let presenceChannelGroups = Object.keys(this._channelGroups);
let presenceState = {};
if (presenceChannels.length === 0 && presenceChannelGroups.length === 0) {
return;
}
presenceChannels.forEach((channel) => {
let channelState = this._channels[channel].state;
if (Object.keys(channelState).length) presenceState[channel] = channelState;
});
presenceChannelGroups.forEach((channelGroup) => {
let channelGroupState = this._channelGroups[channelGroup].state;
if (Object.keys(channelGroupState).length) presenceState[channelGroup] = channelGroupState;
});
let onHeartbeat = (status: StatusAnnouncement) => {
if (status.error && this._config.announceFailedHeartbeats) {
this._listenerManager.announceStatus(status);
}
if (!status.error && this._config.announceSuccessfulHeartbeats) {
this._listenerManager.announceStatus(status);
}
};
this._heartbeatEndpoint({
channels: presenceChannels,
channelGroups: presenceChannelGroups,
state: presenceState }, onHeartbeat.bind(this));
}
_startSubscribeLoop() {
this._stopSubscribeLoop();
let channels = [];
let channelGroups = [];
Object.keys(this._channels).forEach(channel => channels.push(channel));
Object.keys(this._presenceChannels).forEach(channel => channels.push(channel + '-pnpres'));
Object.keys(this._channelGroups).forEach(channelGroup => channelGroups.push(channelGroup));
Object.keys(this._presenceChannelGroups).forEach(channelGroup => channelGroups.push(channelGroup + '-pnpres'));
if (channels.length === 0 && channelGroups.length === 0) {
return;
}
const subscribeArgs = {
channels,
channelGroups,
timetoken: this._timetoken,
filterExpression: this._config.filterExpression,
region: this._region
};
this._subscribeCall = this._subscribeEndpoint(subscribeArgs, this._processSubscribeResponse.bind(this));
}
_processSubscribeResponse(status: StatusAnnouncement, payload: SubscribeEnvelope) {
if (status.error) {
// if we timeout from server, restart the loop.
if (status.category === categoryConstants.PNTimeoutCategory) {
this._startSubscribeLoop();
}
// we lost internet connection, alert the reconnection manager and terminate all loops
if (status.category === categoryConstants.PNNetworkIssuesCategory) {
this.disconnect();
this._reconnectionManager.onReconnection(() => {
this.reconnect();
this._subscriptionStatusAnnounced = true;
let reconnectedAnnounce: StatusAnnouncement = {
category: categoryConstants.PNReconnectedCategory,
operation: status.operation
};
this._listenerManager.announceStatus(reconnectedAnnounce);
});
this._reconnectionManager.startPolling();
this._listenerManager.announceStatus(status);
}
return;
}
if (!this._subscriptionStatusAnnounced) {
let connectedAnnounce: StatusAnnouncement = {};
connectedAnnounce.category = categoryConstants.PNConnectedCategory;
connectedAnnounce.operation = status.operation;
this._subscriptionStatusAnnounced = true;
this._listenerManager.announceStatus(connectedAnnounce);
}
payload.messages.forEach((message) => {
let channel = message.channel;
let subscriptionMatch = message.subscriptionMatch;
let publishMetaData = message.publishMetaData;
if (channel === subscriptionMatch) {
subscriptionMatch = null;
}
if (utils.endsWith(message.channel, '-pnpres')) {
let announce: PresenceAnnouncement = {};
announce.channel = null;
announce.subscription = null;
// deprecated -->
announce.actualChannel = (subscriptionMatch != null) ? channel : null;
announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel;
// <-- deprecated
if (channel) {
announce.channel = channel.substring(0, channel.lastIndexOf('-pnpres'));
}
if (subscriptionMatch) {
announce.subscription = subscriptionMatch.substring(0, subscriptionMatch.lastIndexOf('-pnpres'));
}
announce.action = message.payload.action;
announce.state = message.payload.data;
announce.timetoken = publishMetaData.publishTimetoken;
announce.occupancy = message.payload.occupancy;
announce.uuid = message.payload.uuid;
announce.timestamp = message.payload.timestamp;
this._listenerManager.announcePresence(announce);
} else {
let announce: MessageAnnouncement = {};
announce.channel = null;
announce.subscription = null;
// deprecated -->
announce.actualChannel = (subscriptionMatch != null) ? channel : null;
announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel;
// <-- deprecated
announce.channel = channel;
announce.subscription = subscriptionMatch;
announce.timetoken = publishMetaData.publishTimetoken;
if (this._config.cipherKey) {
announce.message = this._crypto.decrypt(message.payload);
} else {
announce.message = message.payload;
}
this._listenerManager.announceMessage(announce);
}
});
this._region = payload.metadata.region;
this._timetoken = payload.metadata.timetoken;
this._startSubscribeLoop();
}
_stopSubscribeLoop() {
if (this._subscribeCall) {
this._subscribeCall.abort();
this._subscribeCall = null;
}
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Dermateaceae/Mollisia/Mollisia sphaeroides/README.md
|
240
|
# Mollisia sphaeroides (Desm.) W. Phillips, 1887 SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Man. Brit. Discomyc. (London) 187 (1887)
#### Original name
null
### Remarks
null
|
apache-2.0
|
Kloudy/Slots
|
src/com/antarescraft/kloudy/slots/events/CommandEvent.java
|
1946
|
package com.antarescraft.kloudy.slots.events;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.antarescraft.kloudy.hologuiapi.plugincore.command.CommandHandler;
import com.antarescraft.kloudy.hologuiapi.plugincore.command.CommandParser;
import com.antarescraft.kloudy.hologuiapi.plugincore.messaging.MessageManager;
import com.antarescraft.kloudy.slots.Slots;
import com.antarescraft.kloudy.slots.SlotsConfiguration;
import com.antarescraft.kloudy.slots.pagemodels.SlotsPageModel;
public class CommandEvent implements CommandExecutor
{
protected Slots slots;
protected SlotsConfiguration config;
public CommandEvent(Slots plugin)
{
this.slots = plugin;
config = SlotsConfiguration.getSlotsConfiguration(slots);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
return CommandParser.parseCommand(slots, this, "slots", cmd.getName(), sender, args);
}
@CommandHandler(description = "Reloads the config files",
mustBePlayer = false, permission = "slots.admin", subcommands = "reload")
public void reload(CommandSender sender, String[] args)
{
slots.getHoloGUIApi().destroyGUIPages(slots);
slots.removeAllPlayers();
SlotsConfiguration.loadConfig(slots);
MessageManager.info(sender, "Reloaded the config");
}
@CommandHandler(description = "Opens the Slots GUI",
mustBePlayer = true, permission = "slots.play", subcommands = "play")
public void play(CommandSender sender, String[] args)
{
Player player = (Player)sender;
if(!slots.isPlaying(player))
{
SlotsPageModel model = new SlotsPageModel(slots, slots.getGUIPage("slot-machine"), player);
slots.getHoloGUIApi().openGUIPage(slots, model);
slots.isPlaying(player, true);
}
else
{
player.sendMessage(config.getAlreadyPlayingMessage());
}
}
}
|
apache-2.0
|
jdgwartney/vsphere-ws
|
java/JAXWS/samples/com/vmware/vim25/AnswerFileSerializedCreateSpec.java
|
1691
|
package com.vmware.vim25;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for AnswerFileSerializedCreateSpec complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="AnswerFileSerializedCreateSpec">
* <complexContent>
* <extension base="{urn:vim25}AnswerFileCreateSpec">
* <sequence>
* <element name="answerFileConfigString" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AnswerFileSerializedCreateSpec", propOrder = {
"answerFileConfigString"
})
public class AnswerFileSerializedCreateSpec
extends AnswerFileCreateSpec
{
@XmlElement(required = true)
protected String answerFileConfigString;
/**
* Gets the value of the answerFileConfigString property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAnswerFileConfigString() {
return answerFileConfigString;
}
/**
* Sets the value of the answerFileConfigString property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAnswerFileConfigString(String value) {
this.answerFileConfigString = value;
}
}
|
apache-2.0
|
deeplearning4j/deeplearning4j
|
deeplearning4j/deeplearning4j-core/src/main/java/org/deeplearning4j/core/loader/impl/SerializedDataSetLoader.java
|
1380
|
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.deeplearning4j.core.loader.impl;
import org.deeplearning4j.core.loader.DataSetLoader;
import org.nd4j.common.loader.Source;
import org.nd4j.linalg.dataset.DataSet;
import java.io.IOException;
import java.io.InputStream;
/**
* Loads DataSets using {@link DataSet#load(InputStream)}
*
* @author Alex Black
*/
public class SerializedDataSetLoader implements DataSetLoader {
@Override
public DataSet load(Source source) throws IOException {
DataSet ds = new DataSet();
try(InputStream is = source.getInputStream()){
ds.load(is);
}
return ds;
}
}
|
apache-2.0
|
sarl/sarl
|
main/coreplugins/io.sarl.lang/src/io/sarl/lang/sarl/actionprototype/FormalParameterProvider.java
|
3887
|
/*
* $Id$
*
* SARL is an general-purpose agent programming language.
* More details on http://www.sarl.io
*
* Copyright (C) 2014-2021 the original authors or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sarl.lang.sarl.actionprototype;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.common.types.JvmTypeReference;
import org.eclipse.xtext.xbase.XExpression;
/** An object able to provide the name and the type of a formal parameter.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
public interface FormalParameterProvider {
/** Replies the number of formal parameters.
*
* @return the number of formal parameters.
*/
int getFormalParameterCount();
/** Replies the name of the formal parameter at the given position.
*
* @param position the position of the formal parameter.
* @return the name of the formal parameter.
*/
String getFormalParameterName(int position);
/** Replies the type of the formal parameter at the given position.
*
* @param position the position of the formal parameter.
* @param isVarargs indicates if the parameter should be considered as a vararg parameter.
* @return the type of the formal parameter.
*/
String getFormalParameterType(int position, boolean isVarargs);
/** Replies the type of the formal parameter at the given position.
*
* @param position the position of the formal parameter.
* @param isVarargs indicates if the parameter should be considered as a vararg parameter.
* @return the type of the formal parameter.
*/
JvmTypeReference getFormalParameterTypeReference(int position, boolean isVarargs);
/** Replies if the formal parameter at the given position has a default value.
*
* @param position the position of the formal parameter.
* @return <code>true</code> if the parameter has a default value, <code>false</code> if not.
*/
boolean hasFormalParameterDefaultValue(int position);
/** Replies the default value of the formal parameter at the given position.
*
* <p>This function replies the Xbase expression for the default value.
*
* <p>If this function replies {@code null}, the string representation of the
* default value may be still available. See {@link #getFormalParameterDefaultValueString(int)}.
*
* @param position the position of the formal parameter.
* @return the default value, or {@code null} if none.
* @see #getFormalParameterDefaultValueString(int)
*/
XExpression getFormalParameterDefaultValue(int position);
/** Replies the default value of the formal parameter at the given position.
*
* <p>This function replies the string representation of the default value.
*
* <p>If this function replies {@code null} or an empty string of characters, the Xbase representation of the
* default value may be still available. See {@link #getFormalParameterDefaultValue(int)}.
*
* @param position the position of the formal parameter.
* @return the default value, or {@code null} if none.
* @see #getFormalParameterDefaultValue(int)
*/
String getFormalParameterDefaultValueString(int position);
/** Replies the formal parameter at the given position.
*
* @param position the position of the formal parameter.
* @return the formal parameter
*/
EObject getFormalParameter(int position);
}
|
apache-2.0
|
sonu283304/onos
|
drivers/lumentum/src/main/java/org/onosproject/drivers/lumentum/LumentumFlowRuleDriver.java
|
16751
|
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.drivers.lumentum;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.tuple.Pair;
import org.onosproject.net.ChannelSpacing;
import org.onosproject.net.GridType;
import org.onosproject.net.OchSignal;
import org.onosproject.net.OchSignalType;
import org.onosproject.net.Port;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.driver.AbstractHandlerBehaviour;
import org.onosproject.net.flow.DefaultFlowEntry;
import org.onosproject.net.flow.DefaultFlowRule;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.FlowEntry;
import org.onosproject.net.flow.FlowId;
import org.onosproject.net.flow.FlowRule;
import org.onosproject.net.flow.FlowRuleProgrammable;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flow.criteria.Criteria;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snmp4j.PDU;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.UnsignedInteger32;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.util.TreeEvent;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkArgument;
// TODO: need to convert between OChSignal and XC channel number
public class LumentumFlowRuleDriver extends AbstractHandlerBehaviour implements FlowRuleProgrammable {
private static final Logger log =
LoggerFactory.getLogger(LumentumFlowRuleDriver.class);
// Default values
private static final int DEFAULT_TARGET_GAIN_PREAMP = 150;
private static final int DEFAULT_TARGET_GAIN_BOOSTER = 200;
private static final int DISABLE_CHANNEL_TARGET_POWER = -650;
private static final int DEFAULT_CHANNEL_TARGET_POWER = -30;
private static final int DISABLE_CHANNEL_ABSOLUTE_ATTENUATION = 160;
private static final int DEFAULT_CHANNEL_ABSOLUTE_ATTENUATION = 50;
private static final int OUT_OF_SERVICE = 1;
private static final int IN_SERVICE = 2;
private static final int OPEN_LOOP = 1;
private static final int CLOSED_LOOP = 2;
// OIDs
private static final String CTRL_AMP_MODULE_SERVICE_STATE_PREAMP = ".1.3.6.1.4.1.46184.1.4.4.1.2.1";
private static final String CTRL_AMP_MODULE_SERVICE_STATE_BOOSTER = ".1.3.6.1.4.1.46184.1.4.4.1.2.2";
private static final String CTRL_AMP_MODULE_TARGET_GAIN_PREAMP = ".1.3.6.1.4.1.46184.1.4.4.1.8.1";
private static final String CTRL_AMP_MODULE_TARGET_GAIN_BOOSTER = ".1.3.6.1.4.1.46184.1.4.4.1.8.2";
private static final String CTRL_CHANNEL_STATE = ".1.3.6.1.4.1.46184.1.4.2.1.3.";
private static final String CTRL_CHANNEL_MODE = ".1.3.6.1.4.1.46184.1.4.2.1.4.";
private static final String CTRL_CHANNEL_TARGET_POWER = ".1.3.6.1.4.1.46184.1.4.2.1.6.";
private static final String CTRL_CHANNEL_ADD_DROP_PORT_INDEX = ".1.3.6.1.4.1.46184.1.4.2.1.13.";
private static final String CTRL_CHANNEL_ABSOLUTE_ATTENUATION = ".1.3.6.1.4.1.46184.1.4.2.1.5.";
private LumentumSnmpDevice snmp;
@Override
public Collection<FlowEntry> getFlowEntries() {
try {
snmp = new LumentumSnmpDevice(handler().data().deviceId());
} catch (IOException e) {
log.error("Failed to connect to device: ", e);
return Collections.emptyList();
}
// Line in is last but one port, line out is last
DeviceService deviceService = this.handler().get(DeviceService.class);
List<Port> ports = deviceService.getPorts(data().deviceId());
if (ports.size() < 2) {
return Collections.emptyList();
}
PortNumber lineIn = ports.get(ports.size() - 2).number();
PortNumber lineOut = ports.get(ports.size() - 1).number();
Collection<FlowEntry> entries = Lists.newLinkedList();
// Add rules
OID addOid = new OID(CTRL_CHANNEL_STATE + "1");
entries.addAll(
fetchRules(addOid, true, lineOut).stream()
.map(fr -> new DefaultFlowEntry(fr, FlowEntry.FlowEntryState.ADDED, 0, 0, 0))
.collect(Collectors.toList())
);
// Drop rules
OID dropOid = new OID(CTRL_CHANNEL_STATE + "2");
entries.addAll(
fetchRules(dropOid, false, lineIn).stream()
.map(fr -> new DefaultFlowEntry(fr, FlowEntry.FlowEntryState.ADDED, 0, 0, 0))
.collect(Collectors.toList())
);
return entries;
}
@Override
public Collection<FlowRule> applyFlowRules(Collection<FlowRule> rules) {
try {
snmp = new LumentumSnmpDevice(data().deviceId());
} catch (IOException e) {
log.error("Failed to connect to device: ", e);
}
// Line ports
DeviceService deviceService = this.handler().get(DeviceService.class);
List<Port> ports = deviceService.getPorts(data().deviceId());
List<PortNumber> linePorts = ports.subList(ports.size() - 2, ports.size()).stream()
.map(p -> p.number())
.collect(Collectors.toList());
// Apply the valid rules on the device
Collection<FlowRule> added = rules.stream()
.map(r -> new CrossConnectFlowRule(r, linePorts))
.filter(xc -> installCrossConnect(xc))
.collect(Collectors.toList());
// Cache the cookie/priority
CrossConnectCache cache = this.handler().get(CrossConnectCache.class);
added.stream()
.forEach(xc -> cache.set(
Objects.hash(data().deviceId(), xc.selector(), xc.treatment()),
xc.id(),
xc.priority()));
return added;
}
@Override
public Collection<FlowRule> removeFlowRules(Collection<FlowRule> rules) {
try {
snmp = new LumentumSnmpDevice(data().deviceId());
} catch (IOException e) {
log.error("Failed to connect to device: ", e);
}
// Line ports
DeviceService deviceService = this.handler().get(DeviceService.class);
List<Port> ports = deviceService.getPorts(data().deviceId());
List<PortNumber> linePorts = ports.subList(ports.size() - 2, ports.size()).stream()
.map(p -> p.number())
.collect(Collectors.toList());
// Apply the valid rules on the device
Collection<FlowRule> removed = rules.stream()
.map(r -> new CrossConnectFlowRule(r, linePorts))
.filter(xc -> removeCrossConnect(xc))
.collect(Collectors.toList());
// Remove flow rule from cache
CrossConnectCache cache = this.handler().get(CrossConnectCache.class);
removed.stream()
.forEach(xc -> cache.remove(
Objects.hash(data().deviceId(), xc.selector(), xc.treatment())));
return removed;
}
// Installs cross connect on device
private boolean installCrossConnect(CrossConnectFlowRule xc) {
int channel = toChannel(xc.ochSignal());
long addDrop = xc.addDrop().toLong();
// Create the PDU object
PDU pdu = new PDU();
pdu.setType(PDU.SET);
// Enable preamp & booster
List<OID> oids = Arrays.asList(new OID(CTRL_AMP_MODULE_SERVICE_STATE_PREAMP),
new OID(CTRL_AMP_MODULE_SERVICE_STATE_BOOSTER));
oids.forEach(
oid -> pdu.add(new VariableBinding(oid, new Integer32(IN_SERVICE)))
);
// Set target gain on preamp & booster
OID ctrlAmpModuleTargetGainPreamp = new OID(CTRL_AMP_MODULE_TARGET_GAIN_PREAMP);
pdu.add(new VariableBinding(ctrlAmpModuleTargetGainPreamp, new Integer32(DEFAULT_TARGET_GAIN_PREAMP)));
OID ctrlAmpModuleTargetGainBooster = new OID(CTRL_AMP_MODULE_TARGET_GAIN_BOOSTER);
pdu.add(new VariableBinding(ctrlAmpModuleTargetGainBooster, new Integer32(DEFAULT_TARGET_GAIN_BOOSTER)));
// Make cross connect
OID ctrlChannelAddDropPortIndex = new OID(CTRL_CHANNEL_ADD_DROP_PORT_INDEX +
(xc.isAddRule() ? "1." : "2.") + channel);
pdu.add(new VariableBinding(ctrlChannelAddDropPortIndex, new UnsignedInteger32(addDrop)));
// Add rules use closed loop, drop rules open loop
// Add rules are set to target power, drop rules are attenuated
if (xc.isAddRule()) {
OID ctrlChannelMode = new OID(CTRL_CHANNEL_MODE + "1." + channel);
pdu.add(new VariableBinding(ctrlChannelMode, new Integer32(CLOSED_LOOP)));
OID ctrlChannelTargetPower = new OID(CTRL_CHANNEL_TARGET_POWER + "1." + channel);
pdu.add(new VariableBinding(ctrlChannelTargetPower, new Integer32(DEFAULT_CHANNEL_TARGET_POWER)));
} else {
OID ctrlChannelMode = new OID(CTRL_CHANNEL_MODE + "2." + channel);
pdu.add(new VariableBinding(ctrlChannelMode, new Integer32(OPEN_LOOP)));
OID ctrlChannelAbsoluteAttenuation = new OID(CTRL_CHANNEL_ABSOLUTE_ATTENUATION + "2." + channel);
pdu.add(new VariableBinding(
ctrlChannelAbsoluteAttenuation, new UnsignedInteger32(DEFAULT_CHANNEL_ABSOLUTE_ATTENUATION)));
}
// Final step is to enable the channel
OID ctrlChannelState = new OID(CTRL_CHANNEL_STATE + (xc.isAddRule() ? "1." : "2.") + channel);
pdu.add(new VariableBinding(ctrlChannelState, new Integer32(IN_SERVICE)));
try {
ResponseEvent response = snmp.set(pdu);
// TODO: parse response
} catch (IOException e) {
log.error("Failed to create cross connect, unable to connect to device: ", e);
}
return true;
}
// Removes cross connect on device
private boolean removeCrossConnect(CrossConnectFlowRule xc) {
int channel = toChannel(xc.ochSignal());
// Create the PDU object
PDU pdu = new PDU();
pdu.setType(PDU.SET);
// Disable the channel
OID ctrlChannelState = new OID(CTRL_CHANNEL_STATE + (xc.isAddRule() ? "1." : "2.") + channel);
pdu.add(new VariableBinding(ctrlChannelState, new Integer32(OUT_OF_SERVICE)));
// Put cross connect back into default port 1
OID ctrlChannelAddDropPortIndex = new OID(CTRL_CHANNEL_ADD_DROP_PORT_INDEX +
(xc.isAddRule() ? "1." : "2.") + channel);
pdu.add(new VariableBinding(ctrlChannelAddDropPortIndex, new UnsignedInteger32(OUT_OF_SERVICE)));
// Put port/channel back to open loop
OID ctrlChannelMode = new OID(CTRL_CHANNEL_MODE + (xc.isAddRule() ? "1." : "2.") + channel);
pdu.add(new VariableBinding(ctrlChannelMode, new Integer32(OPEN_LOOP)));
// Add rules are set to target power, drop rules are attenuated
if (xc.isAddRule()) {
OID ctrlChannelTargetPower = new OID(CTRL_CHANNEL_TARGET_POWER + "1." + channel);
pdu.add(new VariableBinding(ctrlChannelTargetPower, new Integer32(DISABLE_CHANNEL_TARGET_POWER)));
} else {
OID ctrlChannelAbsoluteAttenuation = new OID(CTRL_CHANNEL_ABSOLUTE_ATTENUATION + "2." + channel);
pdu.add(new VariableBinding(
ctrlChannelAbsoluteAttenuation, new UnsignedInteger32(DISABLE_CHANNEL_ABSOLUTE_ATTENUATION)));
}
try {
ResponseEvent response = snmp.set(pdu);
// TODO: parse response
} catch (IOException e) {
log.error("Failed to remove cross connect, unable to connect to device: ", e);
return false;
}
return true;
}
/**
* Convert OCh signal to Lumentum channel ID.
*
* @param ochSignal OCh signal
* @return Lumentum channel ID
*/
public static int toChannel(OchSignal ochSignal) {
// FIXME: move to cross connect validation
checkArgument(ochSignal.channelSpacing() == ChannelSpacing.CHL_50GHZ);
checkArgument(LumentumSnmpDevice.START_CENTER_FREQ.compareTo(ochSignal.centralFrequency()) <= 0);
checkArgument(LumentumSnmpDevice.END_CENTER_FREQ.compareTo(ochSignal.centralFrequency()) >= 0);
return ochSignal.spacingMultiplier() + LumentumSnmpDevice.MULTIPLIER_SHIFT;
}
/**
* Convert Lumentum channel ID to OCh signal.
*
* @param channel Lumentum channel ID
* @return OCh signal
*/
public static OchSignal toOchSignal(int channel) {
checkArgument(1 <= channel);
checkArgument(channel <= 96);
return new OchSignal(GridType.DWDM, ChannelSpacing.CHL_50GHZ,
channel - LumentumSnmpDevice.MULTIPLIER_SHIFT, 4);
}
// Returns the currently configured add/drop port for the given channel.
private PortNumber getAddDropPort(int channel, boolean isAddPort) {
OID oid = new OID(CTRL_CHANNEL_ADD_DROP_PORT_INDEX + (isAddPort ? "1" : "2"));
for (TreeEvent event : snmp.get(oid)) {
if (event == null) {
return null;
}
VariableBinding[] varBindings = event.getVariableBindings();
for (VariableBinding varBinding : varBindings) {
if (varBinding.getOid().last() == channel) {
int port = varBinding.getVariable().toInt();
return PortNumber.portNumber(port);
}
}
}
return null;
}
// Returns the currently installed flow entries on the device.
private List<FlowRule> fetchRules(OID oid, boolean isAdd, PortNumber linePort) {
List<FlowRule> rules = new LinkedList<>();
for (TreeEvent event : snmp.get(oid)) {
if (event == null) {
continue;
}
VariableBinding[] varBindings = event.getVariableBindings();
for (VariableBinding varBinding : varBindings) {
CrossConnectCache cache = this.handler().get(CrossConnectCache.class);
if (varBinding.getVariable().toInt() == IN_SERVICE) {
int channel = varBinding.getOid().removeLast();
PortNumber addDropPort = getAddDropPort(channel, isAdd);
if (addDropPort == null) {
continue;
}
TrafficSelector selector = DefaultTrafficSelector.builder()
.matchInPort(isAdd ? addDropPort : linePort)
.add(Criteria.matchOchSignalType(OchSignalType.FIXED_GRID))
.add(Criteria.matchLambda(toOchSignal(channel)))
.build();
TrafficTreatment treatment = DefaultTrafficTreatment.builder()
.setOutput(isAdd ? linePort : addDropPort)
.build();
// Lookup flow ID and priority
int hash = Objects.hash(data().deviceId(), selector, treatment);
Pair<FlowId, Integer> lookup = cache.get(hash);
if (lookup == null) {
continue;
}
FlowRule fr = DefaultFlowRule.builder()
.forDevice(data().deviceId())
.makePermanent()
.withSelector(selector)
.withTreatment(treatment)
.withPriority(lookup.getRight())
.withCookie(lookup.getLeft().value())
.build();
rules.add(fr);
}
}
}
return rules;
}
}
|
apache-2.0
|
jorgevillaverde/co
|
src/main/java/ar/com/circuloodontochaco/co/model/contraints/RemesaValidator.java
|
2000
|
/*
* Copyright (C) 2017 Circulo Odontologico del Chaco
*
* 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 ar.com.circuloodontochaco.co.model.contraints;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import ar.com.circuloodontochaco.co.model.Remesa;
/**
* @author Jorge E. Villaverde
*
*/
public class RemesaValidator implements ConstraintValidator<ValidRemesa, Remesa> {
@SuppressWarnings("unused")
private ValidRemesa valid;
@Override
public void initialize(ValidRemesa valid) {
this.valid = valid;
}
@Override
public boolean isValid(Remesa remesa, ConstraintValidatorContext context) {
if (remesa == null) {
return false;
}
boolean isValid = true;
if(remesa.getImporte() == null || remesa.getImporte().compareTo(remesa.getOrigen().getSaldo()) > 0){
isValid = false;
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(
"{ar.com.circuloodontochaco.co.model.contraints.RemesaImporte.message}")
.addConstraintViolation();
}
if(remesa.getOrigen().getCuenta().equals(remesa.getDestino().getCuenta())) {
isValid = false;
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(
"{ar.com.circuloodontochaco.co.model.contraints.RemesaSameAccount.message}")
.addConstraintViolation();
}
return isValid;
}
}
|
apache-2.0
|
sugarcrmlabs/AdminSudo
|
SudoAudit2016_11_08_114528/SugarModules/modules/sa_SudoAudit/clients/base/views/search-list/search-list.php
|
1127
|
<?php
/*
* Your installation or use of this SugarCRM file is subject to the applicable
* terms available at
* http://support.sugarcrm.com/06_Customer_Center/10_Master_Subscription_Agreements/.
* If you do not agree to all of the applicable terms or do not have the
* authority to bind the entity as an authorized representative, then do not
* install or use this SugarCRM file.
*
* Copyright (C) SugarCRM Inc. All rights reserved.
*/
$module_name = 'sa_SudoAudit';
$viewdefs[$module_name]['base']['view']['search-list'] = array(
'panels' => array(
array(
'name' => 'primary',
'fields' => array(
array(
'name' => 'picture',
'type' => 'avatar',
'size' => 'medium',
'readonly' => true,
'css_class' => 'pull-left',
),
array(
'name' => 'name',
'type' => 'name',
'link' => true,
'label' => 'LBL_SUBJECT',
),
),
),
),
);
|
apache-2.0
|
LotteryOne/tools
|
src/com/wonders/alpha/bo/Alpha.java
|
409
|
package com.wonders.alpha.bo;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="alpha")
public class Alpha implements Serializable{
private String id;
@Id
@Column(name="ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
|
apache-2.0
|
michel-kraemer/citeproc-java
|
citeproc-java/src/main/java/de/undercouch/citeproc/DefaultLocaleProvider.java
|
1590
|
package de.undercouch.citeproc;
import de.undercouch.citeproc.helper.CSLUtils;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* Default implementation of {@link LocaleProvider}. Loads locales from
* the classpath.
* @author Michel Kraemer
*/
public class DefaultLocaleProvider implements LocaleProvider {
/**
* A cache for the serialized XML of locales
*/
private Map<String, String> locales = new HashMap<>();
/**
* Retrieves the serialized XML for the given locale from the classpath.
* For example, if the locale is <code>en-US</code> this method loads
* the file <code>/locales-en-US.xml</code> from the classpath.
*/
@Override
public String retrieveLocale(String lang) {
String r = locales.get(lang);
if (r == null) {
try {
URL u = getClass().getResource("/locales-" + lang + ".xml");
if (u == null) {
throw new IllegalArgumentException("Unable to load locale " +
lang + ". Make sure you have a file called " +
"'/locales-" + lang + ".xml' at the root of your " +
"classpath. Did you add the CSL locale files to "
+ "your classpath?");
}
r = CSLUtils.readURLToString(u, "UTF-8");
} catch (IOException e) {
throw new RuntimeException(e);
}
locales.put(lang, r);
}
return r;
}
}
|
apache-2.0
|
entoj/entoj-core
|
source/model/entity/EntityAspect.js
|
4718
|
'use strict';
/**
* Requirements
* @ignore
*/
const BaseValueObject = require('../BaseValueObject.js').BaseValueObject;
const Entity = require('./Entity.js').Entity;
const Site = require('../site/Site.js').Site;
const ContentKind = require('../ContentKind.js');
const BaseMap = require('../../base/BaseMap.js').BaseMap;
const EntityIdTemplate = require('./EntityIdTemplate.js').EntityIdTemplate;
const assertParameter = require('../../utils/assert.js').assertParameter;
/**
* @namespace model.entity
*/
class EntityAspect extends BaseValueObject
{
/**
* @param {model.entity.Entity} entity
* @param {model.site.Site} site
*/
constructor(entity, site, entityIdTemplate)
{
super();
//Check params
assertParameter(this, 'entity', entity, true, Entity);
assertParameter(this, 'site', site, true, Site);
//assertParameter(this, 'entityIdTemplate', entityIdTemplate, true, EntityIdTemplate);
// Add initial values
this._entity = entity;
this._site = site;
this._entityIdTemplate = entityIdTemplate;
// Extend id
this._entityId = this._entity.id.clone();
this._entityId.site = this._site;
// Get extended sites
this._extendedSites = [];
let currentSite = this._site;
while(currentSite)
{
this._extendedSites.unshift(currentSite);
currentSite = currentSite.extends;
}
// Extend files, properties, documentation & tests
const properties = new BaseMap();
const examples = {};
const macros = {};
const texts = [];
const datamodels = [];
const tests = [];
for (const s of this._extendedSites)
{
// Files
this.files.load(this._entity.files.filter(file => file.site === s));
// Examples
const siteExamples = this._entity.documentation.filter(doc => doc.contentKind === ContentKind.EXAMPLE);
for (const siteExample of siteExamples)
{
examples[siteExample.file.basename] = siteExample;
}
// Models
const siteDatamodels = this._entity.documentation.filter(doc => doc.contentKind === ContentKind.DATAMODEL);
for (const siteDatamodel of siteDatamodels)
{
datamodels.push(siteDatamodel);
}
// Macros
const siteMacros = this._entity.documentation.filter(doc => doc.contentKind === ContentKind.MACRO);
for (const siteMacro of siteMacros)
{
macros[siteMacro.name] = siteMacro;
}
// Text
const siteTexts = this._entity.documentation.filter(doc => doc.contentKind === ContentKind.TEXT);
for (const siteText of siteTexts)
{
texts.push(siteText);
}
// Properties
const siteProperties = this._entity.properties.getByPath(s.name.toLowerCase(), {});
properties.merge(siteProperties);
// Tests
this.tests.load(this._entity.tests.filter(test => test.site === s));
}
this.properties.load(properties);
this.documentation.load(examples);
this.documentation.load(datamodels);
this.documentation.load(macros);
this.documentation.load(texts);
}
/**
* @inheritDoc
*/
static get injections()
{
return { 'parameters': [Entity, Site, EntityIdTemplate] };
}
/**
* @inheritDoc
*/
static get className()
{
return 'model.entity/EntityAspect';
}
/**
* @property {*}
*/
get uniqueId()
{
return this.pathString;
}
/**
* @property {entity.EntityId}
*/
get id()
{
return this._entityId;
}
/**
* @property {String}
*/
get idString()
{
return this._entityId.idString;
}
/**
* @property {String}
*/
get pathString()
{
return this._entityId.pathString;
}
/**
* @property {model.entity.Entity}
*/
get entity()
{
return this._entity;
}
/**
* @property {model.site.Site}
*/
get site()
{
return this._site;
}
/**
* @property {Bool}
*/
get isGlobal()
{
return this._entity.isGlobal;
}
/**
* @inheritDoc
*/
toString()
{
return `[${this.className} ${this.site.name}/${this.id.category.longName}-${this.id.name}]`;
}
}
/**
* Exports
* @ignore
*/
module.exports.EntityAspect = EntityAspect;
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Mycenaceae/Mycena/Mycena alphitophora/Mycena alphitophora distincta/README.md
|
256
|
# Mycena alphitophora var. distincta Manim. & Leelav. VARIETY
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Mycol. Res. 93(1): 118 (1989)
#### Original name
Mycena alphitophora var. distincta Manim. & Leelav.
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Grindelia scorzonerifolia/ Syn. Grindelia scorzonerifolia pectinata/README.md
|
212
|
# Grindelia scorzonerifolia var. pectinata (Baker) Hassl. VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
siqinbateer/myTestPro
|
my project/oc/@class/@class/Student.h
|
381
|
//
// Student.h
// @class
//
// Created by pcbeta on 15-4-12.
// Copyright (c) 2015年 pcbeta. All rights reserved.
//
#import <Foundation/Foundation.h>
@class Book;
@interface Student : NSObject
@property (nonatomic,assign) int age;
@property (nonatomic,retain) Book *book;
//-(void)setBook:(Book *)book;
//-(Book *)book;
+(id)student;
+(id)studentWithAge:(int) age;
@end
|
apache-2.0
|
rafati/unitime
|
JavaSource/org/unitime/timetable/onlinesectioning/custom/purdue/XEInterface.java
|
8329
|
/*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* The Apereo Foundation 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.unitime.timetable.onlinesectioning.custom.purdue;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
import com.google.gson.reflect.TypeToken;
public class XEInterface {
public static class Registration {
public String subject;
public String subjectDescription;
public String courseNumber;
public String courseReferenceNumber;
public String courseTitle;
/**
* 40 CEC 40% refund
* 60 CEC 60% refund
* 80 CEC 80% refund
* AA Auditor Access
* AU Audit
* CA Cancel Administratively
* DB Boiler Gold Rush Drop Course
* DC Drop Course
* DD Drop/Delete
* DT Drop Course-TSW
* DW Drop (Web)
* RC **ReAdd Course**
* RE **Registered**
* RT **Web Registered**
* RW **Web Registered**
* W Withdrawn-W
* W1 Withdrawn
* W2 Withdrawn
* W3 Withdrawn
* W4 Withdrawn
* W5 Withdrawn
* WF Withdrawn-WF
* WG Withdrawn-pending grade
* WN Withdrawn-WN
* WT Withdrawn-W
* WU Withdrawn-WU
* WL Waitlist
*/
public String courseRegistrationStatus;
public String courseRegistrationStatusDescription;
public Double creditHour;
public String gradingMode;
public String gradingModeDescription;
public String level;
public String levelDescription;
public DateTime registrationStatusDate;
public String scheduleDescription;
public String scheduleType;
public String sequenceNumber;
public String statusDescription;
/**
* P = pending
* R = registered
* D = dropped
* L = waitlisted
* F = fatal error prevented registration
* W = withdrawn
*/
public String statusIndicator;
public List<CrnError> crnErrors;
public String term;
public String campus;
public List<RegistrationAction> registrationActions;
public boolean can(String status) {
if (registrationActions != null)
for (RegistrationAction action: registrationActions) {
if (status.equals(action.courseRegistrationStatus))
return true;
}
return false;
}
public boolean canDrop() {
return can("DW");
}
public boolean canAdd(boolean admin) {
return can(admin ? "RE" : "RW");
}
public boolean isRegistered() {
return "R".equals(statusIndicator);
}
}
public static class CrnError {
public String errorFlag;
public String message;
public String messageType;
}
public static class RegistrationAction {
public String courseRegistrationStatus;
public String description;
public Boolean remove;
public String voiceType;
}
public static class TimeTicket {
public DateTime beginDate;
public DateTime endDate;
public String startTime;
public String endTime;
}
public static class FailedRegistration {
public String failedCRN;
public String failure;
public Registration registration;
}
public static class RegisterResponse {
public static final Type TYPE_LIST = new TypeToken<ArrayList<RegisterResponse>>() {}.getType();
public List<FailedRegistration> failedRegistrations;
public List<String> failureReasons;
public List<Registration> registrations;
public List<TimeTicket> timeTickets;
public Boolean validStudent;
public String registrationException;
}
public static class CourseReferenceNumber {
public String courseReferenceNumber;
public String courseRegistrationStatus;
public CourseReferenceNumber() {}
public CourseReferenceNumber(String crn) {
this.courseReferenceNumber = crn;
}
public CourseReferenceNumber(String crn, String status) {
this.courseReferenceNumber = crn;
this.courseRegistrationStatus = status;
}
}
public static class RegisterAction {
public String courseReferenceNumber;
public String selectedAction;
public String selectedLevel;
public String selectedGradingMode;
public String selectedStudyPath;
public String selectedCreditHour;
public RegisterAction(String action, String crn) {
selectedAction = action;
courseReferenceNumber = crn;
}
}
public static class RegisterRequest {
public String bannerId;
public String term;
public String altPin;
public String systemIn;
public List<CourseReferenceNumber> courseReferenceNumbers;
public List<RegisterAction> actionsAndOptions;
public RegisterRequest(String term, String bannerId, String pin, boolean admin) {
this.term = term; this.bannerId = bannerId; this.altPin = pin; this.systemIn = (admin ? "SB" : "WA");
}
public RegisterRequest drop(String crn) {
if (actionsAndOptions == null) actionsAndOptions = new ArrayList<RegisterAction>();
actionsAndOptions.add(new RegisterAction("DW", crn));
return this;
}
public RegisterRequest keep(String crn) {
if (courseReferenceNumbers == null)
courseReferenceNumbers = new ArrayList<XEInterface.CourseReferenceNumber>();
courseReferenceNumbers.add(new CourseReferenceNumber(crn));
return this;
}
public RegisterRequest add(String crn, boolean changeStatus) {
if (changeStatus) {
if (actionsAndOptions == null) actionsAndOptions = new ArrayList<RegisterAction>();
actionsAndOptions.add(new RegisterAction("SB".equals(systemIn) ? "RE" : "RW", crn));
} else {
if (courseReferenceNumbers == null)
courseReferenceNumbers = new ArrayList<XEInterface.CourseReferenceNumber>();
// if ("SB".equals(systemIn)) courseReferenceNumbers.add(new CourseReferenceNumber(crn, "RW")); else
courseReferenceNumbers.add(new CourseReferenceNumber(crn));
}
return this;
}
public RegisterRequest empty() {
if (courseReferenceNumbers == null)
courseReferenceNumbers = new ArrayList<XEInterface.CourseReferenceNumber>();
courseReferenceNumbers.add(new CourseReferenceNumber());
return this;
}
public boolean isEmpty() {
return (actionsAndOptions == null || actionsAndOptions.isEmpty()) && (courseReferenceNumbers == null || courseReferenceNumbers.isEmpty());
}
}
public static class DegreePlan {
public static final Type TYPE_LIST = new TypeToken<ArrayList<DegreePlan>>() {}.getType();
public String id;
public String description;
public Student student;
public CodeDescription degree;
public CodeDescription school;
public List<Year> years;
}
public static class Student {
public String id;
public String name;
}
public static class CodeDescription {
public String code;
public String description;
}
public static class Year extends CodeDescription {
public List<Term> terms;
}
public static class Term {
public String id;
public CodeDescription term;
public Group group;
}
public static class Group {
public CodeDescription groupType;
public List<Course> plannedClasses;
public List<Group> groups;
public List<PlaceHolder> plannedPlaceholders;
public String summaryDescription;
public boolean isGroupSelection;
}
public static class Course {
public String id;
public String title;
public String courseNumber;
public String courseDiscipline;
public boolean isGroupSelection;
}
public static class PlaceHolder {
public String id;
public CodeDescription placeholderType;
public String placeholderValue;
}
public static class ErrorResponse {
public List<Error> errors;
public Error getError() {
return (errors == null || errors.isEmpty() ? null : errors.get(0));
}
}
public static class Error {
public String code;
public String message;
public String description;
public String type;
public String errorMessage;
}
}
|
apache-2.0
|
vangj/py-bbn
|
docs/Makefile
|
606
|
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SPHINXPROJ = PyBBN
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
apache-2.0
|
rsk-mind/rsk-mind.github.com
|
stylesheets/stylesheet.css
|
5784
|
* {
box-sizing: border-box; }
body {
padding: 0;
margin: 0;
font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 1.5;
color: #354759; }
a {
color: #1e6bb8;
text-decoration: none; }
a:hover {
text-decoration: underline; }
.btn {
display: inline-block;
margin-bottom: 1rem;
color: rgba(255, 255, 255, 0.7);
background-color: rgba(255, 255, 255, 0.08);
border-color: rgba(255, 255, 255, 0.2);
border-style: solid;
border-width: 1px;
border-radius: 0.3rem;
transition: color 0.2s, background-color 0.2s, border-color 0.2s; }
.btn + .btn {
margin-left: 1rem; }
.btn:hover {
color: rgba(255, 255, 255, 0.8);
text-decoration: none;
background-color: rgba(255, 255, 255, 0.2);
border-color: rgba(255, 255, 255, 0.3); }
@media screen and (min-width: 64em) {
.btn {
padding: 0.75rem 1rem; } }
@media screen and (min-width: 42em) and (max-width: 64em) {
.btn {
padding: 0.6rem 0.9rem;
font-size: 0.9rem; } }
@media screen and (max-width: 42em) {
.btn {
display: block;
width: 100%;
padding: 0.75rem;
font-size: 0.9rem; }
.btn + .btn {
margin-top: 1rem;
margin-left: 0; } }
.page-header {
color: #fff;
text-align: center;
background-color: #354759;
/*background-image: linear-gradient(120deg, #1590f2, #354759); }*/
}
@media screen and (min-width: 64em) {
.page-header {
padding: 5rem 6rem; } }
@media screen and (min-width: 42em) and (max-width: 64em) {
.page-header {
padding: 3rem 4rem; } }
@media screen and (max-width: 42em) {
.page-header {
padding: 2rem 1rem; } }
.project-name {
margin-top: 0;
margin-bottom: 0.1rem; }
@media screen and (min-width: 64em) {
.project-name {
font-size: 3.25rem; } }
@media screen and (min-width: 42em) and (max-width: 64em) {
.project-name {
font-size: 2.25rem; } }
@media screen and (max-width: 42em) {
.project-name {
font-size: 1.75rem; } }
.project-tagline {
margin-bottom: 2rem;
font-weight: normal;
opacity: 0.7; }
@media screen and (min-width: 64em) {
.project-tagline {
font-size: 1.25rem; } }
@media screen and (min-width: 42em) and (max-width: 64em) {
.project-tagline {
font-size: 1.15rem; } }
@media screen and (max-width: 42em) {
.project-tagline {
font-size: 1rem; } }
.main-content :first-child {
margin-top: 0; }
.main-content img {
max-width: 100%; }
.main-content h1, .main-content h2, .main-content h3, .main-content h4, .main-content h5, .main-content h6 {
margin-top: 2rem;
margin-bottom: 1rem;
font-weight: normal;
color: #159957; }
.main-content p {
margin-bottom: 1em; }
.main-content code {
padding: 2px 4px;
font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
font-size: 0.9rem;
color: #383e41;
background-color: #f3f6fa;
border-radius: 0.3rem; }
.main-content pre {
padding: 0.8rem;
margin-top: 0;
margin-bottom: 1rem;
font: 1rem Consolas, "Liberation Mono", Menlo, Courier, monospace;
color: #567482;
word-wrap: normal;
background-color: #f3f6fa;
border: solid 1px #dce6f0;
border-radius: 0.3rem; }
.main-content pre > code {
padding: 0;
margin: 0;
font-size: 0.9rem;
color: #567482;
word-break: normal;
white-space: pre;
background: transparent;
border: 0; }
.main-content .highlight {
margin-bottom: 1rem; }
.main-content .highlight pre {
margin-bottom: 0;
word-break: normal; }
.main-content .highlight pre, .main-content pre {
padding: 0.8rem;
overflow: auto;
font-size: 0.9rem;
line-height: 1.45;
border-radius: 0.3rem; }
.main-content pre code, .main-content pre tt {
display: inline;
max-width: initial;
padding: 0;
margin: 0;
overflow: initial;
line-height: inherit;
word-wrap: normal;
background-color: transparent;
border: 0; }
.main-content pre code:before, .main-content pre code:after, .main-content pre tt:before, .main-content pre tt:after {
content: normal; }
.main-content ul, .main-content ol {
margin-top: 0; }
.main-content blockquote {
padding: 0 1rem;
margin-left: 0;
color: #819198;
border-left: 0.3rem solid #dce6f0; }
.main-content blockquote > :first-child {
margin-top: 0; }
.main-content blockquote > :last-child {
margin-bottom: 0; }
.main-content table {
display: block;
width: 100%;
overflow: auto;
word-break: normal;
word-break: keep-all; }
.main-content table th {
font-weight: bold; }
.main-content table th, .main-content table td {
padding: 0.5rem 1rem;
border: 1px solid #e9ebec; }
.main-content dl {
padding: 0; }
.main-content dl dt {
padding: 0;
margin-top: 1rem;
font-size: 1rem;
font-weight: bold; }
.main-content dl dd {
padding: 0;
margin-bottom: 1rem; }
.main-content hr {
height: 2px;
padding: 0;
margin: 1rem 0;
background-color: #eff0f1;
border: 0; }
@media screen and (min-width: 64em) {
.main-content {
max-width: 64rem;
padding: 2rem 6rem;
margin: 0 auto;
font-size: 1.1rem; } }
@media screen and (min-width: 42em) and (max-width: 64em) {
.main-content {
padding: 2rem 4rem;
font-size: 1.1rem; } }
@media screen and (max-width: 42em) {
.main-content {
padding: 2rem 1rem;
font-size: 1rem; } }
.site-footer {
padding-top: 2rem;
margin-top: 2rem;
border-top: solid 1px #eff0f1;}
.site-footer-owner {
display: block;
font-weight: bold; }
.site-footer-credits {
color: #819198; }
@media screen and (min-width: 64em) {
.site-footer {
font-size: 1rem; } }
@media screen and (min-width: 42em) and (max-width: 64em) {
.site-footer {
font-size: 1rem; } }
@media screen and (max-width: 42em) {
.site-footer {
font-size: 0.9rem; } }
|
apache-2.0
|
blox/blox
|
end-to-end-tests/src/main/java/com/amazonaws/blox/integ/ECSClusterWrapper.java
|
2607
|
/*
* Copyright 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.
*/
package com.amazonaws.blox.integ;
import com.amazonaws.blox.integ.CloudFormationStacks.CfnStack;
import java.util.Collections;
import java.util.List;
import lombok.RequiredArgsConstructor;
import software.amazon.awssdk.services.ecs.ECSClient;
import software.amazon.awssdk.services.ecs.model.DescribeTasksRequest;
import software.amazon.awssdk.services.ecs.model.DesiredStatus;
import software.amazon.awssdk.services.ecs.model.ListTasksRequest;
import software.amazon.awssdk.services.ecs.model.StopTaskRequest;
import software.amazon.awssdk.services.ecs.model.Task;
/** Wrapper for interacting with a test ECS cluster */
@RequiredArgsConstructor
public class ECSClusterWrapper {
private final ECSClient ecs;
// TODO: For now, act on all tasks that match startedBy, we should change this to filter by prefix
private final String startedBy = "blox";
private final CfnStack stack;
public ECSClusterWrapper(ECSClient ecs, CloudFormationStacks stacks) {
this(ecs, stacks.get("blox-test-cluster"));
}
public String getTransientTaskDefinition() {
return stack.output("transienttask");
}
public String getPersistentTaskDefinition() {
return stack.output("persistenttask");
}
public String getCluster() {
return stack.output("cluster");
}
public List<Task> describeTasks() {
List<String> taskArns = listTasks();
if (taskArns.isEmpty()) {
return Collections.emptyList();
}
return ecs.describeTasks(
DescribeTasksRequest.builder().cluster(getCluster()).tasks(taskArns).build())
.tasks();
}
private List<String> listTasks() {
return ecs.listTasks(
ListTasksRequest.builder()
.cluster(getCluster())
.startedBy(startedBy)
.desiredStatus(DesiredStatus.RUNNING)
.build())
.taskArns();
}
public void reset() {
for (String task : listTasks()) {
ecs.stopTask(StopTaskRequest.builder().cluster(getCluster()).task(task).build());
}
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Sordariomycetes/Diaporthales/Gnomoniaceae/Apioplagiostoma/Apioplagiostoma populi/README.md
|
281
|
# Apioplagiostoma populi (E.K. Cash & Waterman) M.E. Barr, 1978 SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Mycol. Mem. 7: 102 (1978)
#### Original name
Plagiostoma populi E.K. Cash & Waterman, 1957
### Remarks
null
|
apache-2.0
|
EZWebvietnam/vieclam24h
|
template/home/js/jquery.scrollstore.js
|
1126
|
function swl_scrollStopExtend() {
var a = SWL.$.event.special, b = "D" + +new Date, c = "D" + (+new Date + 1);
a.scrollstart = {
setup : function() {
var c, d = function(b) {
var d = this, e = arguments;
c ? clearTimeout(c) : (b.type = "scrollstart", SWL.$.event.handle.apply(d, e)), c = setTimeout(function() {
c = null
}, a.scrollstop.latency)
};
SWL.$(this).bind("scroll", d).data(b, d)
},
teardown : function() {
SWL.$(this).unbind("scroll", SWL.$(this).data(b))
}
}, a.scrollstop = {
latency : 300,
setup : function() {
var b, d = function(c) {
var d = this, e = arguments;
b && clearTimeout(b), b = setTimeout(function() {
b = null, c.type = "scrollstop", SWL.$.event.handle.apply(d, e)
}, a.scrollstop.latency)
};
SWL.$(this).bind("scroll", d).data(c, d)
},
teardown : function() {
SWL.$(this).unbind("scroll", SWL.$(this).data(c))
}
}
}
function swl_scrollStopInit() {
return "undefined" == typeof SWL ? (window.setTimeout(function() {
swl_scrollStopInit()
}, 50),
void 0) : (swl_scrollStopExtend(),
void 0)
}swl_scrollStopInit();
|
apache-2.0
|
teecube/t3
|
t3-site-enhancer/src/main/java/t3/site/gitlab/tags/Release.java
|
2129
|
/**
* (C) Copyright 2016-2019 teecube
* (https://teecu.be) 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.
*/
package t3.site.gitlab.tags;
import com.fasterxml.jackson.annotation.*;
import java.util.HashMap;
import java.util.Map;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"tag_name",
"description"
})
public class Release {
/**
*
* (Required)
*
*/
@JsonProperty("tag_name")
private String tagName;
/**
*
* (Required)
*
*/
@JsonProperty("description")
private String description;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* (Required)
*
*/
@JsonProperty("tag_name")
public String getTagName() {
return tagName;
}
/**
*
* (Required)
*
*/
@JsonProperty("tag_name")
public void setTagName(String tagName) {
this.tagName = tagName;
}
/**
*
* (Required)
*
*/
@JsonProperty("description")
public String getDescription() {
return description;
}
/**
*
* (Required)
*
*/
@JsonProperty("description")
public void setDescription(String description) {
this.description = description;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
|
apache-2.0
|
fbotelho-university-code/poseidon
|
target/docs/net/floodlightcontroller/topology/class-use/OrderedNodePair.html
|
5984
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Fri May 31 12:12:37 WEST 2013 -->
<TITLE>
Uses of Class net.floodlightcontroller.topology.OrderedNodePair
</TITLE>
<META NAME="date" CONTENT="2013-05-31">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class net.floodlightcontroller.topology.OrderedNodePair";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../net/floodlightcontroller/topology/OrderedNodePair.html" title="class in net.floodlightcontroller.topology"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?net/floodlightcontroller/topology//class-useOrderedNodePair.html" target="_top"><B>FRAMES</B></A>
<A HREF="OrderedNodePair.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>net.floodlightcontroller.topology.OrderedNodePair</B></H2>
</CENTER>
No usage of net.floodlightcontroller.topology.OrderedNodePair
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../net/floodlightcontroller/topology/OrderedNodePair.html" title="class in net.floodlightcontroller.topology"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?net/floodlightcontroller/topology//class-useOrderedNodePair.html" target="_top"><B>FRAMES</B></A>
<A HREF="OrderedNodePair.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
|
apache-2.0
|
dconz13/MySunshine-Watch-Face
|
app/src/main/java/com/example/android/sunshine/app/sync/SunshineSyncAdapter.java
|
29790
|
package com.example.android.sunshine.app.sync;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SyncRequest;
import android.content.SyncResult;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.IntDef;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.text.format.Time;
import android.util.Log;
import com.bumptech.glide.Glide;
import com.example.android.sunshine.app.BuildConfig;
import com.example.android.sunshine.app.MainActivity;
import com.example.android.sunshine.app.R;
import com.example.android.sunshine.app.Utility;
import com.example.android.sunshine.app.data.WeatherContract;
import com.example.android.sunshine.app.muzei.WeatherMuzeiSource;
import com.example.android.sunshine.app.wear.WearIntentService;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Vector;
import java.util.concurrent.ExecutionException;
public class SunshineSyncAdapter extends AbstractThreadedSyncAdapter {
public final String LOG_TAG = SunshineSyncAdapter.class.getSimpleName();
public static final String ACTION_DATA_UPDATED =
"com.example.android.sunshine.app.ACTION_DATA_UPDATED";
public static final String ACTION_WEAR_UPDATED =
"com.example.android.sunshine.app.ACTION_WEAR_UPDATED";
// Interval at which to sync with the weather, in seconds.
// 60 seconds (1 minute) * 180 = 3 hours
public static final int SYNC_INTERVAL = 60 * 180;
public static final int SYNC_FLEXTIME = SYNC_INTERVAL/3;
private static final long DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
private static final int WEATHER_NOTIFICATION_ID = 3004;
private static final String[] NOTIFY_WEATHER_PROJECTION = new String[] {
WeatherContract.WeatherEntry.COLUMN_WEATHER_ID,
WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
WeatherContract.WeatherEntry.COLUMN_MIN_TEMP,
WeatherContract.WeatherEntry.COLUMN_SHORT_DESC
};
// these indices must match the projection
private static final int INDEX_WEATHER_ID = 0;
private static final int INDEX_MAX_TEMP = 1;
private static final int INDEX_MIN_TEMP = 2;
private static final int INDEX_SHORT_DESC = 3;
@Retention(RetentionPolicy.SOURCE)
@IntDef({LOCATION_STATUS_OK, LOCATION_STATUS_SERVER_DOWN, LOCATION_STATUS_SERVER_INVALID, LOCATION_STATUS_UNKNOWN, LOCATION_STATUS_INVALID})
public @interface LocationStatus {}
public static final int LOCATION_STATUS_OK = 0;
public static final int LOCATION_STATUS_SERVER_DOWN = 1;
public static final int LOCATION_STATUS_SERVER_INVALID = 2;
public static final int LOCATION_STATUS_UNKNOWN = 3;
public static final int LOCATION_STATUS_INVALID = 4;
public SunshineSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
Log.d(LOG_TAG, "Starting sync");
String locationQuery = Utility.getPreferredLocation(getContext());
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 14;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String FORECAST_BASE_URL =
"http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
final String APPID_PARAM = "APPID";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, locationQuery)
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY)
.build();
URL url = new URL(builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
setLocationStatus(getContext(), LOCATION_STATUS_SERVER_DOWN);
return;
}
forecastJsonStr = buffer.toString();
getWeatherDataFromJson(forecastJsonStr, locationQuery);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
setLocationStatus(getContext(), LOCATION_STATUS_SERVER_DOWN);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
setLocationStatus(getContext(), LOCATION_STATUS_SERVER_INVALID);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private void getWeatherDataFromJson(String forecastJsonStr,
String locationSetting)
throws JSONException {
// Now we have a String representing the complete forecast in JSON Format.
// Fortunately parsing is easy: constructor takes the JSON string and converts it
// into an Object hierarchy for us.
// These are the names of the JSON objects that need to be extracted.
// Location information
final String OWM_CITY = "city";
final String OWM_CITY_NAME = "name";
final String OWM_COORD = "coord";
// Location coordinate
final String OWM_LATITUDE = "lat";
final String OWM_LONGITUDE = "lon";
// Weather information. Each day's forecast info is an element of the "list" array.
final String OWM_LIST = "list";
final String OWM_PRESSURE = "pressure";
final String OWM_HUMIDITY = "humidity";
final String OWM_WINDSPEED = "speed";
final String OWM_WIND_DIRECTION = "deg";
// All temperatures are children of the "temp" object.
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_WEATHER = "weather";
final String OWM_DESCRIPTION = "main";
final String OWM_WEATHER_ID = "id";
final String OWM_MESSAGE_CODE = "cod";
try {
JSONObject forecastJson = new JSONObject(forecastJsonStr);
// do we have an error?
if ( forecastJson.has(OWM_MESSAGE_CODE) ) {
int errorCode = forecastJson.getInt(OWM_MESSAGE_CODE);
switch (errorCode) {
case HttpURLConnection.HTTP_OK:
break;
case HttpURLConnection.HTTP_NOT_FOUND:
setLocationStatus(getContext(), LOCATION_STATUS_INVALID);
return;
default:
setLocationStatus(getContext(), LOCATION_STATUS_SERVER_DOWN);
return;
}
}
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
String cityName = cityJson.getString(OWM_CITY_NAME);
JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);
long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);
// Insert the new weather information into the database
Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());
// OWM returns daily forecasts based upon the local time of the city that is being
// asked for, which means that we need to know the GMT offset to translate this data
// properly.
// Since this data is also sent in-order and the first day is always the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a mess.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
// now we work exclusively in UTC
dayTime = new Time();
for(int i = 0; i < weatherArray.length(); i++) {
// These are the values that will be collected.
long dateTime;
double pressure;
int humidity;
double windSpeed;
double windDirection;
double high;
double low;
String description;
int weatherId;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// Cheating to convert this to UTC time, which is what we want anyhow
dateTime = dayTime.setJulianDay(julianStartDay+i);
pressure = dayForecast.getDouble(OWM_PRESSURE);
humidity = dayForecast.getInt(OWM_HUMIDITY);
windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);
// Description is in a child array called "weather", which is 1 element long.
// That element also contains a weather code.
JSONObject weatherObject =
dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
weatherId = weatherObject.getInt(OWM_WEATHER_ID);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
high = temperatureObject.getDouble(OWM_MAX);
low = temperatureObject.getDouble(OWM_MIN);
ContentValues weatherValues = new ContentValues();
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationId);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, dateTime);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDirection);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, high);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, low);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, description);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, weatherId);
cVVector.add(weatherValues);
}
int inserted = 0;
// add to database
if ( cVVector.size() > 0 ) {
ContentValues[] cvArray = new ContentValues[cVVector.size()];
cVVector.toArray(cvArray);
getContext().getContentResolver().bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI, cvArray);
// delete old data so we don't build up an endless history
getContext().getContentResolver().delete(WeatherContract.WeatherEntry.CONTENT_URI,
WeatherContract.WeatherEntry.COLUMN_DATE + " <= ?",
new String[] {Long.toString(dayTime.setJulianDay(julianStartDay-1))});
updateWidgets();
updateWearables();
updateMuzei();
notifyWeather();
}
Log.d(LOG_TAG, "Sync Complete. " + cVVector.size() + " Inserted");
setLocationStatus(getContext(), LOCATION_STATUS_OK);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
setLocationStatus(getContext(), LOCATION_STATUS_SERVER_INVALID);
}
}
private void updateWidgets() {
Context context = getContext();
// Setting the package ensures that only components in our app will receive the broadcast
Intent dataUpdatedIntent = new Intent(ACTION_DATA_UPDATED)
.setPackage(context.getPackageName());
context.sendBroadcast(dataUpdatedIntent);
}
private void updateWearables() {
Context context = getContext();
context.startService(new Intent(ACTION_WEAR_UPDATED)
.setClass(context,WearIntentService.class));
}
private void updateMuzei() {
// Muzei is only compatible with Jelly Bean MR1+ devices, so there's no need to update the
// Muzei background on lower API level devices
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Context context = getContext();
context.startService(new Intent(ACTION_DATA_UPDATED)
.setClass(context, WeatherMuzeiSource.class));
}
}
private void notifyWeather() {
Context context = getContext();
//checking the last update and notify if it' the first of the day
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String displayNotificationsKey = context.getString(R.string.pref_enable_notifications_key);
boolean displayNotifications = prefs.getBoolean(displayNotificationsKey,
Boolean.parseBoolean(context.getString(R.string.pref_enable_notifications_default)));
if ( displayNotifications ) {
String lastNotificationKey = context.getString(R.string.pref_last_notification);
long lastSync = prefs.getLong(lastNotificationKey, 0);
if (System.currentTimeMillis() - lastSync >= DAY_IN_MILLIS) {
// Last sync was more than 1 day ago, let's send a notification with the weather.
String locationQuery = Utility.getPreferredLocation(context);
Uri weatherUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(locationQuery, System.currentTimeMillis());
// we'll query our contentProvider, as always
Cursor cursor = context.getContentResolver().query(weatherUri, NOTIFY_WEATHER_PROJECTION, null, null, null);
if (cursor.moveToFirst()) {
int weatherId = cursor.getInt(INDEX_WEATHER_ID);
double high = cursor.getDouble(INDEX_MAX_TEMP);
double low = cursor.getDouble(INDEX_MIN_TEMP);
String desc = cursor.getString(INDEX_SHORT_DESC);
int iconId = Utility.getIconResourceForWeatherCondition(weatherId);
Resources resources = context.getResources();
int artResourceId = Utility.getArtResourceForWeatherCondition(weatherId);
String artUrl = Utility.getArtUrlForWeatherCondition(context, weatherId);
// On Honeycomb and higher devices, we can retrieve the size of the large icon
// Prior to that, we use a fixed size
@SuppressLint("InlinedApi")
int largeIconWidth = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB
? resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_width)
: resources.getDimensionPixelSize(R.dimen.notification_large_icon_default);
@SuppressLint("InlinedApi")
int largeIconHeight = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB
? resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_height)
: resources.getDimensionPixelSize(R.dimen.notification_large_icon_default);
// Retrieve the large icon
Bitmap largeIcon;
try {
largeIcon = Glide.with(context)
.load(artUrl)
.asBitmap()
.error(artResourceId)
.fitCenter()
.into(largeIconWidth, largeIconHeight).get();
} catch (InterruptedException | ExecutionException e) {
Log.e(LOG_TAG, "Error retrieving large icon from " + artUrl, e);
largeIcon = BitmapFactory.decodeResource(resources, artResourceId);
}
String title = context.getString(R.string.app_name);
// Define the text of the forecast.
String contentText = String.format(context.getString(R.string.format_notification),
desc,
Utility.formatTemperature(context, high),
Utility.formatTemperature(context, low));
// NotificationCompatBuilder is a very convenient way to build backward-compatible
// notifications. Just throw in some data.
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getContext())
.setColor(resources.getColor(R.color.primary_light))
.setSmallIcon(iconId)
.setLargeIcon(largeIcon)
.setContentTitle(title)
.setContentText(contentText);
// Make something interesting happen when the user clicks on the notification.
// In this case, opening the app is sufficient.
Intent resultIntent = new Intent(context, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
// WEATHER_NOTIFICATION_ID allows you to update the notification later on.
mNotificationManager.notify(WEATHER_NOTIFICATION_ID, mBuilder.build());
//refreshing last sync
SharedPreferences.Editor editor = prefs.edit();
editor.putLong(lastNotificationKey, System.currentTimeMillis());
editor.commit();
}
cursor.close();
}
}
}
/**
* Helper method to handle insertion of a new location in the weather database.
*
* @param locationSetting The location string used to request updates from the server.
* @param cityName A human-readable city name, e.g "Mountain View"
* @param lat the latitude of the city
* @param lon the longitude of the city
* @return the row ID of the added location.
*/
long addLocation(String locationSetting, String cityName, double lat, double lon) {
long locationId;
// First, check if the location with this city name exists in the db
Cursor locationCursor = getContext().getContentResolver().query(
WeatherContract.LocationEntry.CONTENT_URI,
new String[]{WeatherContract.LocationEntry._ID},
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
new String[]{locationSetting},
null);
if (locationCursor.moveToFirst()) {
int locationIdIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID);
locationId = locationCursor.getLong(locationIdIndex);
} else {
// Now that the content provider is set up, inserting rows of data is pretty simple.
// First create a ContentValues object to hold the data you want to insert.
ContentValues locationValues = new ContentValues();
// Then add the data, along with the corresponding name of the data type,
// so the content provider knows what kind of value is being inserted.
locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
// Finally, insert location data into the database.
Uri insertedUri = getContext().getContentResolver().insert(
WeatherContract.LocationEntry.CONTENT_URI,
locationValues
);
// The resulting URI contains the ID for the row. Extract the locationId from the Uri.
locationId = ContentUris.parseId(insertedUri);
}
locationCursor.close();
// Wait, that worked? Yes!
return locationId;
}
/**
* Helper method to schedule the sync adapter periodic execution
*/
public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) {
Account account = getSyncAccount(context);
String authority = context.getString(R.string.content_authority);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// we can enable inexact timers in our periodic sync
SyncRequest request = new SyncRequest.Builder().
syncPeriodic(syncInterval, flexTime).
setSyncAdapter(account, authority).
setExtras(new Bundle()).build();
ContentResolver.requestSync(request);
} else {
ContentResolver.addPeriodicSync(account,
authority, new Bundle(), syncInterval);
}
}
/**
* Helper method to have the sync adapter sync immediately
* @param context The context used to access the account service
*/
public static void syncImmediately(Context context) {
Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
ContentResolver.requestSync(getSyncAccount(context),
context.getString(R.string.content_authority), bundle);
}
/**
* Helper method to get the fake account to be used with SyncAdapter, or make a new one
* if the fake account doesn't exist yet. If we make a new account, we call the
* onAccountCreated method so we can initialize things.
*
* @param context The context used to access the account service
* @return a fake account.
*/
public static Account getSyncAccount(Context context) {
// Get an instance of the Android account manager
AccountManager accountManager =
(AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
// Create the account type and default account
Account newAccount = new Account(
context.getString(R.string.app_name), context.getString(R.string.sync_account_type));
// If the password doesn't exist, the account doesn't exist
if ( null == accountManager.getPassword(newAccount) ) {
/*
* Add the account and account type, no password or user data
* If successful, return the Account object, otherwise report an error.
*/
if (!accountManager.addAccountExplicitly(newAccount, "", null)) {
return null;
}
/*
* If you don't set android:syncable="true" in
* in your <provider> element in the manifest,
* then call ContentResolver.setIsSyncable(account, AUTHORITY, 1)
* here.
*/
onAccountCreated(newAccount, context);
}
return newAccount;
}
private static void onAccountCreated(Account newAccount, Context context) {
/*
* Since we've created an account
*/
SunshineSyncAdapter.configurePeriodicSync(context, SYNC_INTERVAL, SYNC_FLEXTIME);
/*
* Without calling setSyncAutomatically, our periodic sync will not be enabled.
*/
ContentResolver.setSyncAutomatically(newAccount, context.getString(R.string.content_authority), true);
/*
* Finally, let's do a sync to get things started
*/
syncImmediately(context);
}
public static void initializeSyncAdapter(Context context) {
getSyncAccount(context);
}
/**
* Sets the location status into shared preference. This function should not be called from
* the UI thread because it uses commit to write to the shared preferences.
* @param c Context to get the PreferenceManager from.
* @param locationStatus The IntDef value to set
*/
static private void setLocationStatus(Context c, @LocationStatus int locationStatus){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c);
SharedPreferences.Editor spe = sp.edit();
spe.putInt(c.getString(R.string.pref_location_status_key), locationStatus);
spe.commit();
}
}
|
apache-2.0
|
wildfly-swarm/wildfly-swarm-javadocs
|
2016.12.1/apidocs/org/wildfly/swarm/config/WebservicesConsumer.html
|
10886
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_60-ea) on Thu Dec 15 09:48:31 EST 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>WebservicesConsumer (Public javadocs 2016.12.1 API)</title>
<meta name="date" content="2016-12-15">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="WebservicesConsumer (Public javadocs 2016.12.1 API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6,"i1":18};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"],16:["t5","Default Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/WebservicesConsumer.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2016.12.1</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/wildfly/swarm/config/Webservices.WsdlUriScheme.html" title="enum in org.wildfly.swarm.config"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../org/wildfly/swarm/config/WebservicesSupplier.html" title="interface in org.wildfly.swarm.config"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/wildfly/swarm/config/WebservicesConsumer.html" target="_top">Frames</a></li>
<li><a href="WebservicesConsumer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.wildfly.swarm.config</div>
<h2 title="Interface WebservicesConsumer" class="title">Interface WebservicesConsumer<T extends <a href="../../../../org/wildfly/swarm/config/Webservices.html" title="class in org.wildfly.swarm.config">Webservices</a><T>></h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Functional Interface:</dt>
<dd>This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.</dd>
</dl>
<hr>
<br>
<pre><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html?is-external=true" title="class or interface in java.lang">@FunctionalInterface</a>
public interface <span class="typeNameLabel">WebservicesConsumer<T extends <a href="../../../../org/wildfly/swarm/config/Webservices.html" title="class in org.wildfly.swarm.config">Webservices</a><T>></span></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span><span id="t5" class="tableTab"><span><a href="javascript:show(16);">Default Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/wildfly/swarm/config/WebservicesConsumer.html#accept-T-">accept</a></span>(<a href="../../../../org/wildfly/swarm/config/WebservicesConsumer.html" title="type parameter in WebservicesConsumer">T</a> value)</code>
<div class="block">Configure a pre-constructed instance of Webservices resource</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>default <a href="../../../../org/wildfly/swarm/config/WebservicesConsumer.html" title="interface in org.wildfly.swarm.config">WebservicesConsumer</a><<a href="../../../../org/wildfly/swarm/config/WebservicesConsumer.html" title="type parameter in WebservicesConsumer">T</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/wildfly/swarm/config/WebservicesConsumer.html#andThen-org.wildfly.swarm.config.WebservicesConsumer-">andThen</a></span>(<a href="../../../../org/wildfly/swarm/config/WebservicesConsumer.html" title="interface in org.wildfly.swarm.config">WebservicesConsumer</a><<a href="../../../../org/wildfly/swarm/config/WebservicesConsumer.html" title="type parameter in WebservicesConsumer">T</a>> after)</code> </td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="accept-org.wildfly.swarm.config.Webservices-">
<!-- -->
</a><a name="accept-T-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>accept</h4>
<pre>void accept(<a href="../../../../org/wildfly/swarm/config/WebservicesConsumer.html" title="type parameter in WebservicesConsumer">T</a> value)</pre>
<div class="block">Configure a pre-constructed instance of Webservices resource</div>
</li>
</ul>
<a name="andThen-org.wildfly.swarm.config.WebservicesConsumer-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>andThen</h4>
<pre>default <a href="../../../../org/wildfly/swarm/config/WebservicesConsumer.html" title="interface in org.wildfly.swarm.config">WebservicesConsumer</a><<a href="../../../../org/wildfly/swarm/config/WebservicesConsumer.html" title="type parameter in WebservicesConsumer">T</a>> andThen(<a href="../../../../org/wildfly/swarm/config/WebservicesConsumer.html" title="interface in org.wildfly.swarm.config">WebservicesConsumer</a><<a href="../../../../org/wildfly/swarm/config/WebservicesConsumer.html" title="type parameter in WebservicesConsumer">T</a>> after)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/WebservicesConsumer.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2016.12.1</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/wildfly/swarm/config/Webservices.WsdlUriScheme.html" title="enum in org.wildfly.swarm.config"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../org/wildfly/swarm/config/WebservicesSupplier.html" title="interface in org.wildfly.swarm.config"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/wildfly/swarm/config/WebservicesConsumer.html" target="_top">Frames</a></li>
<li><a href="WebservicesConsumer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2016 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
apache-2.0
|
eatplayhate/versionr
|
VersionrCore/Objects/VaultLock.cs
|
566
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Versionr.Objects
{
[ProtoBuf.ProtoContract]
public class VaultLock
{
[ProtoBuf.ProtoMember(1)]
[SQLite.PrimaryKey]
public Guid ID { get; set; }
[ProtoBuf.ProtoMember(2)]
public Guid? Branch { get; set; }
[ProtoBuf.ProtoMember(3)]
public string Path { get; set; }
[ProtoBuf.ProtoMember(4)]
public string User { get; set; }
}
}
|
apache-2.0
|
Zarkonnen/whichfish
|
templates/entry.html
|
87
|
<a href="{{link}}"><li class='{{sustainable}}'>{{name}}{{inSeason}}{{mercury}}</li></a>
|
apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.