code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
# Pyrus mamorensis var. brevipes Emb. & Maire VARIETY #### Status DOUBTFUL #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Pyrus/Pyrus mamorensis/Pyrus mamorensis brevipes/README.md
Markdown
apache-2.0
201
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="Rect.js"></script> </head> <body> <canvas width="550" height="400" id="canvas"></canvas> <script src="main.js"></script> </body> </html>
plter/HTML5Course20160612
20160628/HandleEvent/index.html
HTML
apache-2.0
246
/* * * LegendShop 多用户商城系统 * * 版权所有,并保留所有权利。 * */ package com.legendshop.business.dao; import com.legendshop.core.dao.BaseDao; import com.legendshop.model.entity.VisitLog; /** * The Interface VisitLogDao. */ public interface VisitLogDao extends BaseDao { /** * Update visit log. * * @param visitLog * the visit log */ void updateVisitLog(VisitLog visitLog); /** * Delete visit log by id. * * @param id * the id */ void deleteVisitLogById(Long id); /** * Gets the visited index log. * * @param visitLog * the visit log * @return the visited index log */ VisitLog getVisitedIndexLog(VisitLog visitLog); /** * Gets the visited prod log. * * @param visitLog * the visit log * @return the visited prod log */ VisitLog getVisitedProdLog(VisitLog visitLog); }
8090boy/gomall.la
legendshop/src/java/com/legendshop/business/dao/VisitLogDao.java
Java
apache-2.0
909
using System; using Independentsoft.Office; using Independentsoft.Office.Word; using Independentsoft.Office.Word.Tables; namespace Sample { class Program { static void Main(string[] args) { WordDocument doc = new WordDocument(); Run run1 = new Run("Quantity"); run1.Bold = ExtendedBoolean.True; Paragraph paragraph1 = new Paragraph(); paragraph1.Add(run1); Run run2 = new Run("Item #"); run2.Bold = ExtendedBoolean.True; Paragraph paragraph2 = new Paragraph(); paragraph2.Add(run2); Run run3 = new Run("Description"); run3.Bold = ExtendedBoolean.True; Paragraph paragraph3 = new Paragraph(); paragraph3.Add(run3); Run run4 = new Run("Unit Price"); run4.Bold = ExtendedBoolean.True; Paragraph paragraph4 = new Paragraph(); paragraph4.Add(run4); Run run5 = new Run("Line Total"); run5.Bold = ExtendedBoolean.True; Paragraph paragraph5 = new Paragraph(); paragraph5.Add(run5); Shading cell1Shading = new Shading(ShadingPattern.Percent10); cell1Shading.BackgroundColor = "#FF0000"; //red color Cell cell1 = new Cell(); cell1.Width = new Width(TableWidthUnit.Point, 1260); cell1.Shading = cell1Shading; cell1.Add(paragraph1); Cell cell2 = new Cell(); cell2.Width = new Width(TableWidthUnit.Point, 1440); cell2.Shading = new Shading(ShadingPattern.Percent10); cell2.Add(paragraph2); Cell cell3 = new Cell(); cell3.Width = new Width(TableWidthUnit.Point, 4140); cell3.Shading = new Shading(ShadingPattern.Percent10); cell3.Add(paragraph3); Cell cell4 = new Cell(); cell4.Width = new Width(TableWidthUnit.Point, 1620); cell4.Shading = new Shading(ShadingPattern.Percent10); cell4.Add(paragraph4); Cell cell5 = new Cell(); cell5.Width = new Width(TableWidthUnit.Point, 1620); cell5.Shading = new Shading(ShadingPattern.Percent10); cell5.Add(paragraph5); Row firstRow = new Row(); firstRow.Add(cell1); firstRow.Add(cell2); firstRow.Add(cell3); firstRow.Add(cell4); firstRow.Add(cell5); Row row1 = new Row(); row1.Add(new Cell()); row1.Add(new Cell()); row1.Add(new Cell()); row1.Add(new Cell()); row1.Add(new Cell()); Table table1 = new Table(StandardBorderStyle.SingleLine); table1.Add(firstRow); table1.Add(row1); table1.Add(row1); table1.Add(row1); table1.Add(row1); table1.Add(row1); table1.Add(row1); table1.Add(row1); table1.Add(row1); table1.Add(row1); table1.Add(row1); doc.Body.Add(table1); doc.Save("c:\\test\\output.docx", true); } } }
AndreKuzubov/Easy_Report
packages/Independentsoft.Office.Word.2.0.400/Tutorial/SetCellColor/Program.cs
C#
apache-2.0
3,227
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>Netty Source Xref (3.10.1.Final) Package org.jboss.netty.example.http.websocketx.server</title> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="style" /> </head> <body> <div class="overview"> <ul> <li> <a href="../../../../../../../overview-summary.html">Overview</a> </li> <li class="selected">Package</li> </ul> </div> <div class="framenoframe"> <ul> <li> <a href="../../../../../../../index.html" target="_top">FRAMES</a> </li> <li> <a href="package-summary.html" target="_top">NO FRAMES</a> </li> </ul> </div> <h2>Package org.jboss.netty.example.http.websocketx.server</h2> <table class="summary"> <thead> <tr> <th>Class Summary</th> </tr> </thead> <tbody> <tr> <td> <a href="WebSocketServer.html" target="classFrame">WebSocketServer</a> </td> </tr> <tr> <td> <a href="WebSocketServerHandler.html" target="classFrame">WebSocketServerHandler</a> </td> </tr> <tr> <td> <a href="WebSocketServerIndexPage.html" target="classFrame">WebSocketServerIndexPage</a> </td> </tr> <tr> <td> <a href="WebSocketServerPipelineFactory.html" target="classFrame">WebSocketServerPipelineFactory</a> </td> </tr> </tbody> </table> <div class="overview"> <ul> <li> <a href="../../../../../../../overview-summary.html">Overview</a> </li> <li class="selected">Package</li> </ul> </div> <div class="framenoframe"> <ul> <li> <a href="../../../../../../../index.html" target="_top">FRAMES</a> </li> <li> <a href="package-summary.html" target="_top">NO FRAMES</a> </li> </ul> </div> <hr /> Copyright &#169; 2008-2015 The Netty Project. All Rights Reserved. </body> </html>
anmei/netty-3.10.1.Final
doc/xref/org/jboss/netty/example/http/websocketx/server/package-summary.html
HTML
apache-2.0
2,627
package com.whenling.extension.mall.order.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; import com.whenling.module.domain.model.BaseEntity; /** * 发货项 * @作者 孔祥溪 * @博客 http://ken.whenling.com * @创建时间 2016年3月2日 下午4:37:26 */ @Entity @Table(name = "mall_shipping_item") public class ShippingItem extends BaseEntity<Long> { private static final long serialVersionUID = 4883958012370518864L; /** 商品编号 */ @NotEmpty @Column(nullable = false, updatable = false) private String sn; /** 商品名称 */ @NotEmpty @Column(nullable = false, updatable = false) private String name; /** 数量 */ @NotNull @Min(1) @Column(nullable = false, updatable = false) private Integer quantity; /** 发货单 */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(nullable = false, updatable = false) private Shipping shipping; public String getSn() { return sn; } public void setSn(String sn) { this.sn = sn; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Shipping getShipping() { return shipping; } public void setShipping(Shipping shipping) { this.shipping = shipping; } }
xiangxik/java-platform
extension/extension-mall/src/main/java/com/whenling/extension/mall/order/model/ShippingItem.java
Java
apache-2.0
1,732
/* * Copyright 2018 75py * * 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. */ // generated by work/generate_extentions_res.py // template: work/template.HookTest.java package com.nagopy.android.downloadconfirm.extension; import android.support.test.runner.AndroidJUnit4; import com.nagopy.android.downloadconfirm.R; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class ZipHookTest extends HookTest { @Test public void testZipHookEnabled() throws Throwable { testCheckboxOn("zip", R.string.label_zip); } @Test public void testZipHookDisabled() throws Throwable { testCheckboxOff("zip"); } }
75py/Download-Confirm
app/src/androidTest/java/com/nagopy/android/downloadconfirm/extension/ZipHookTest.java
Java
apache-2.0
1,193
<link href="css/stickyfooter.css" rel="stylesheet"> <footer class="footer"> <div class="container"> <div class="row"> <div class="col-md-4"> <span class="copyright">Copyright &copy; CS KickStart 2015</span> </div> <div class="col-md-4"> <ul class="list-inline social-buttons"> <li><a href="https://www.facebook.com/CS.KickStart/?fref=ts" target="blank"><i class="fa fa-facebook"></i></a> </li> <li><a href="https://www.linkedin.com/groups/6952434/" target="blank"><i class="fa fa-linkedin"></i></a> </li> </ul> </div> <div class="col-md-4"> <ul class="list-inline quicklinks"> <li><a href="http://www.berkeley.edu/" target="blank">University of California, Berkeley</a> </li> <li>·</li> <li><a href="http://www.eecs.berkeley.edu/" target="blank">EECS</a> </li> </ul> </div> </div> </div> </footer>
cskickstart/cskickstart.github.io
footer.html
HTML
apache-2.0
976
// Copyright 2018 The OpenSDS 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 util import ( "errors" "log" "net" "os" "path" "reflect" "regexp" "strings" ) // getProtoandAdd return protocal and address func getProtoAndAdd(target string) (string, string) { reg := `(?i)^((?:(?:tcp|udp|ip)[46]?)|` + `(?:unix(?:gram|packet)?))://(.+)$` t := regexp.MustCompile(reg).FindStringSubmatch(target) return t[1], t[2] } func PathExists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err } // getCSIEndPoint from environment variable func getCSIEndPoint(csiEndpoint string) (string, error) { // example: CSI_ENDPOINT=unix://path/to/unix/domain/socket.sock csiEndpoint = strings.TrimSpace(csiEndpoint) if csiEndpoint == "" { err := errors.New("csi endpoint is empty") log.Fatalf("%v", err) return csiEndpoint, err } return csiEndpoint, nil } // GetCSIEndPointListener from endpoint func GetCSIEndPointListener(csiEndpoint string) (net.Listener, error) { target, err := getCSIEndPoint(csiEndpoint) if err != nil { return nil, err } proto, addr := getProtoAndAdd(target) log.Printf("proto: %s addr: %s", proto, addr) if strings.HasPrefix(proto, "unix") { // clean up previous sock file. os.RemoveAll(addr) log.Printf("remove sock file: %s", addr) // Need to make directory at the first time the csi service runs. dir := path.Dir(addr) if exist, _ := PathExists(dir); !exist { os.MkdirAll(dir, 0755) } } return net.Listen(proto, addr) } // Contained ... func Contained(obj, target interface{}) bool { targetValue := reflect.ValueOf(target) switch reflect.TypeOf(target).Kind() { case reflect.Slice, reflect.Array: for i := 0; i < targetValue.Len(); i++ { if targetValue.Index(i).Interface() == obj { return true } } case reflect.Map: if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() { return true } default: return false } return false }
opensds/nbp
csi/util/util.go
GO
apache-2.0
2,556
# Diversiphyllum C. Buzek, 1971 GENUS #### Status ACCEPTED #### According to IRMNG Homonym List #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Convolvulaceae/Diversiphyllum/README.md
Markdown
apache-2.0
164
// Copyright 2015 CoreOS, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package proccmdline import ( "errors" "fmt" "io/ioutil" "strings" "github.com/rancher/os/log" "github.com/rancher/os/config/cloudinit/datasource" "github.com/rancher/os/config/cloudinit/pkg" ) const ( ProcCmdlineLocation = "/proc/cmdline" ProcCmdlineCloudConfigFlag = "cloud-config-url" ) type ProcCmdline struct { Location string lastError error } func NewDatasource() *ProcCmdline { return &ProcCmdline{Location: ProcCmdlineLocation} } func (c *ProcCmdline) IsAvailable() bool { var contents []byte contents, c.lastError = ioutil.ReadFile(c.Location) if c.lastError != nil { return false } cmdline := strings.TrimSpace(string(contents)) _, c.lastError = findCloudConfigURL(cmdline) return (c.lastError == nil) } func (c *ProcCmdline) Finish() error { return nil } func (c *ProcCmdline) String() string { return fmt.Sprintf("%s: %s (lastError: %v)", c.Type(), c.Location, c.lastError) } func (c *ProcCmdline) AvailabilityChanges() bool { return false } func (c *ProcCmdline) ConfigRoot() string { return "" } func (c *ProcCmdline) FetchMetadata() (datasource.Metadata, error) { return datasource.Metadata{}, nil } func (c *ProcCmdline) FetchUserdata() ([]byte, error) { contents, err := ioutil.ReadFile(c.Location) if err != nil { return nil, err } cmdline := strings.TrimSpace(string(contents)) url, err := findCloudConfigURL(cmdline) if err != nil { return nil, err } client := pkg.NewHTTPClient() cfg, err := client.GetRetry(url) if err != nil { return nil, err } return cfg, nil } func (c *ProcCmdline) Type() string { return "proc-cmdline" } func findCloudConfigURL(input string) (url string, err error) { err = errors.New("cloud-config-url not found") for _, token := range strings.Split(input, " ") { parts := strings.SplitN(token, "=", 2) key := parts[0] key = strings.Replace(key, "_", "-", -1) if key != "cloud-config-url" { continue } if len(parts) != 2 { log.Printf("Found cloud-config-url in /proc/cmdline with no value, ignoring.") continue } url = parts[1] err = nil } return }
gizmotronic/os
config/cloudinit/datasource/proccmdline/proc_cmdline.go
GO
apache-2.0
2,692
package com.suscipio_solutions.consecro_mud.Abilities.Druid; import java.util.Vector; import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability; import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg; import com.suscipio_solutions.consecro_mud.Items.interfaces.Food; import com.suscipio_solutions.consecro_mud.Items.interfaces.RawMaterial; import com.suscipio_solutions.consecro_mud.Locales.interfaces.Room; import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB; import com.suscipio_solutions.consecro_mud.core.CMClass; import com.suscipio_solutions.consecro_mud.core.CMLib; import com.suscipio_solutions.consecro_mud.core.CMStrings; import com.suscipio_solutions.consecro_mud.core.interfaces.ItemPossessor; import com.suscipio_solutions.consecro_mud.core.interfaces.Physical; @SuppressWarnings("rawtypes") public class Chant_SummonFood extends Chant { @Override public String ID() { return "Chant_SummonFood"; } private final static String localizedName = CMLib.lang().L("Summon Food"); @Override public String name() { return localizedName; } @Override public int abstractQuality(){return Ability.QUALITY_INDIFFERENT;} @Override protected int canAffectCode(){return 0;} @Override protected int canTargetCode(){return 0;} @Override public int classificationCode(){return Ability.ACODE_CHANT|Ability.DOMAIN_PLANTGROWTH;} @Override public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel) { if(((mob.location().domainType()&Room.INDOORS)>0)&&(!auto)) { mob.tell(L("You must be outdoors to try this.")); return false; } if((mob.location().domainType()==Room.DOMAIN_OUTDOORS_CITY) ||(mob.location().domainType()==Room.DOMAIN_OUTDOORS_SPACEPORT) ||(mob.location().domainType()==Room.DOMAIN_OUTDOORS_UNDERWATER) ||(mob.location().domainType()==Room.DOMAIN_OUTDOORS_AIR) ||(mob.location().domainType()==Room.DOMAIN_OUTDOORS_WATERSURFACE)) { mob.tell(L("This magic will not work here.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; // now see if it worked final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,null,this,verbalCastCode(mob,null,auto),auto?"":L("^S<S-NAME> chant(s) to the ground.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); Food newItem=null; final int berryType=RawMaterial.CODES.BERRIES()[CMLib.dice().roll(1,RawMaterial.CODES.BERRIES().length,-1)]; for(int i=0;i<((adjustedLevel(mob,asLevel)/4)+1);i++) { newItem=(Food)CMClass.getBasicItem("GenFoodResource"); newItem.setName(L("some @x1",RawMaterial.CODES.NAME(berryType).toLowerCase())); newItem.setDisplayText(L("@x1 are growing here.",CMStrings.capitalizeAndLower(newItem.name()))); newItem.setDescription(L("These little berries look juicy and good.")); newItem.setMaterial(berryType); newItem.setNourishment(150+(10*super.getX1Level(mob))); newItem.setBaseValue(1); CMLib.materials().addEffectsToResource(newItem); newItem.setMiscText(newItem.text()); mob.location().addItem(newItem,ItemPossessor.Expire.Resource); } if(newItem!=null) mob.location().showHappens(CMMsg.MSG_OK_ACTION,L("@x1 quickly begin to grow here.",CMStrings.capitalizeAndLower(newItem.name()))); mob.location().recoverPhyStats(); } } else return beneficialWordsFizzle(mob,null,L("<S-NAME> chant(s) to the ground, but nothing happens.")); // return whether it worked return success; } }
ConsecroMUD/ConsecroMUD
com/suscipio_solutions/consecro_mud/Abilities/Druid/Chant_SummonFood.java
Java
apache-2.0
3,609
/* Copyright 2005-2015 Red Hat, Inc. Red Hat licenses this file to you under the Apache License, version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. MODIFICATION: This file is from jboss-fuse/fabric8 project. It has been modified for fuse-autoscale project by GitHub user yuruki. */ package com.github.yuruki.fuse.autoscale; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.fabric8.api.DataStore; import io.fabric8.api.FabricService; import io.fabric8.api.ProfileRequirements; import io.fabric8.api.jcip.GuardedBy; import io.fabric8.api.jcip.ThreadSafe; import io.fabric8.api.scr.AbstractComponent; import io.fabric8.common.util.Closeables; import io.fabric8.groups.Group; import io.fabric8.groups.GroupListener; import io.fabric8.groups.internal.ZooKeeperGroup; import io.fabric8.zookeeper.ZkPath; import io.fabric8.zookeeper.utils.ZooKeeperMasterCache; import org.apache.curator.framework.CuratorFramework; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.ConfigurationPolicy; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A Fabric auto-scaler which when it becomes the master auto-scales * profiles according to their requirements defined via * {@link FabricService#setRequirements(io.fabric8.api.FabricRequirements)} */ @SuppressWarnings("WeakerAccess") @ThreadSafe @Component(name = "io.fabric8.autoscale", label = "Fuse Autoscaler", immediate = true, policy = ConfigurationPolicy.REQUIRE, metatype = true) public final class AutoScaleController extends AbstractComponent implements GroupListener<AutoScalerNode> { private static final Logger LOGGER = LoggerFactory.getLogger(AutoScaleController.class); @Reference(referenceInterface = CuratorFramework.class) private CuratorFramework curator; @Reference(referenceInterface = FabricService.class) private FabricService fabricService; @Property(value = "true", label = "Enable autoscaling", description = "Enable autoscaling.") private static final String ENABLE_AUTOSCALE = "enableAutoscale"; private Boolean enableAutoscale; @Property(value = "15000", label = "Poll period", description = "The number of milliseconds between polls to check if the system still has its requirements satisfied.") private static final String POLL_TIME = "pollTime"; private Long pollTime; @Property(value = "default", label = "Autoscaler group ID", description = "ID for the autoscaler group.") private static final String AUTOSCALER_GROUP_ID = "autoscalerGroupId"; private String autoscalerGroupId; @Property(value = AutoScaledGroupOptions.PROFILE_PATTERN_DEFAULT, label = "Profile name pattern", description = "Profiles matching this pattern will be auto-scaled.") private static final String PROFILE_PATTERN = "profilePattern"; private Matcher profilePattern; @Property(value = AutoScaledGroupOptions.CONTAINER_PATTERN_DEFAULT, label = "Container name pattern", description = "Containers matching this pattern will be auto-scaled.") private static final String CONTAINER_PATTERN = "containerPattern"; private Matcher containerPattern; @Property(value = AutoScaledGroupOptions.CONTAINER_PREFIX_DEFAULT, label = "Container name prefix for new containers", description = "New containers will be named with this prefix. The prefix must match containerPattern.") private static final String CONTAINER_PREFIX = "containerPrefix"; private String containerPrefix; @Property(value = AutoScaledGroupOptions.SCALE_CONTAINERS_DEFAULT, label = "Scale containers", description = "Allow autoscaler to create, start and remove containers.") private static final String SCALE_CONTAINERS = "scaleContainers"; private Boolean scaleContainers; @Property(value = AutoScaledGroupOptions.DEFAULT_MAX_INSTANCES_PER_HOST_DEFAULT, label = "Default value for maximum profile instances per host", description = "Default value for maximum profile instances per host when profile requirements don't define it.") private static final String DEFAULT_MAX_INSTANCES_PER_HOST = "defaultMaxInstancesPerHost"; private Integer defaultMaximumInstancesPerHost; @Property(value = AutoScaledGroupOptions.MIN_CONTAINER_COUNT_DEFAULT, label = "Minimum number of containers", description = "Minimum number of applicable containers to perform auto-scaling. Used when scaleContainers is false") private static final String MIN_CONTAINER_COUNT = "minContainerCount"; private Integer minContainerCount; @Property(value = AutoScaledGroupOptions.MAX_DEVIATION_DEFAULT, label = "Maximum deviation = n * average, where n >= 0", description = "If a container has more than average + (n * average) matching profile instances assigned, the excess will be reassigned on other containers.") private static final String MAX_DEVIATION = "maxDeviation"; private Double maxDeviation; @Property(value = AutoScaledGroupOptions.INHERIT_REQUIREMENTS_DEFAULT, label = "Inherit requirements", description = "Profile dependencies will inherit their requirements from parent when their requirements are not set.") private static final String INHERIT_REQUIREMENTS = "inheritRequirements"; private Boolean inheritRequirements; @Property(value = AutoScaledGroupOptions.AVERAGE_INSTANCES_PER_CONTAINER_DEFAULT, label = "Desired average profile instance count per container", description = "Desired average profile instance count per container. Negative value equals no value.") private static final String AVERAGE_INSTANCES_PER_CONTAINER = "averageInstancesPerContainer"; private Integer averageInstancesPerContainer; @Property(value = AutoScaledGroupOptions.IGNORE_ERRORS_DEFAULT, label = "Don't cancel auto-scaling on error", description = "When enabled, errors will be logged but the auto-scaling will be performed regardless.") private static final String IGNORE_ERRORS = "ignoreErrors"; private Boolean ignoreErrors; @Property(value = AutoScaledGroupOptions.MAX_CONTAINERS_PER_HOST_DEFAULT, label = "Maximum allowed auto-scaled containers per host", description = "Maximum number of auto-scaled containers per host for this group.") private static final String MAX_CONTAINERS_PER_HOST = "maxContainersPerHost"; private Integer maxContainersPerHost; @Property(value = AutoScaledGroupOptions.DRY_RUN_DEFAULT, label = "Do not apply changes", description = "Do not apply any changes.") private static final String DRY_RUN = "dryRun"; private Boolean dryRun; @Property(value = AutoScaledGroupOptions.ROOT_CONTAINER_PATTERN_DEFAULT, label = "Root container name pattern", description = "Only root containers matching this pattern will be included in autoscaling.") private static final String ROOT_CONTAINER_PATTERN = "rootContainerPattern"; private Matcher rootContainerPattern; @Property(value = AutoScaledGroupOptions.CHANGES_PER_POLL_DEFAULT, label = "Max changes per poll", description = "Determines how many containers can be affected per fuse-autoscale invocation/poll. 0 = no limit.") private static final String CHANGES_PER_POLL = "changesPerPoll"; private Integer changesPerPoll; private AtomicReference<Timer> timer = new AtomicReference<>(); @GuardedBy("volatile") private volatile Group<AutoScalerNode> group; private Runnable runnable = new Runnable() { @Override public void run() { onConfigurationChanged(); } }; private ZooKeeperMasterCache zkMasterCache; @Activate void activate(final Map<String, String> properties) { this.enableAutoscale = Boolean.parseBoolean(properties.get(ENABLE_AUTOSCALE)); this.pollTime = Long.parseLong(properties.get(POLL_TIME)); this.profilePattern = Pattern.compile(properties.get(PROFILE_PATTERN)).matcher(""); this.containerPattern = Pattern.compile(properties.get(CONTAINER_PATTERN)).matcher(""); this.containerPrefix = properties.get(CONTAINER_PREFIX); this.scaleContainers = Boolean.parseBoolean(properties.get(SCALE_CONTAINERS)); this.defaultMaximumInstancesPerHost = Integer.parseInt(properties.get(DEFAULT_MAX_INSTANCES_PER_HOST)); this.autoscalerGroupId = properties.get(AUTOSCALER_GROUP_ID); this.minContainerCount = Integer.parseInt(properties.get(MIN_CONTAINER_COUNT)); this.maxDeviation = Double.parseDouble(properties.get(MAX_DEVIATION)) >= 0 ? Double.parseDouble(properties.get(MAX_DEVIATION)) : 1; this.inheritRequirements = Boolean.parseBoolean(properties.get(INHERIT_REQUIREMENTS)); this.averageInstancesPerContainer = Integer.parseInt(properties.get(AVERAGE_INSTANCES_PER_CONTAINER)); this.ignoreErrors = Boolean.parseBoolean(properties.get(IGNORE_ERRORS)); this.maxContainersPerHost = Integer.parseInt(properties.get(MAX_CONTAINERS_PER_HOST)); this.dryRun = Boolean.parseBoolean(properties.get(DRY_RUN)); this.rootContainerPattern = Pattern.compile(properties.get(ROOT_CONTAINER_PATTERN)).matcher(""); this.changesPerPoll = Integer.parseInt(properties.get(CHANGES_PER_POLL)); enableMasterZkCache(curator); if (enableAutoscale) { group = new ZooKeeperGroup<>(curator, ZkPath.AUTO_SCALE_CLUSTER.getPath() + "/" + autoscalerGroupId, AutoScalerNode.class); group.add(this); group.update(createState()); group.start(); } else { LOGGER.warn("{}: autoscaling is disabled (enableAutoscale = false)", autoscalerGroupId); } activateComponent(); } @Deactivate void deactivate() { disableMasterZkCache(); disableTimer(); deactivateComponent(); if (null != group) { group.remove(this); Closeables.closeQuietly(group); group = null; } } @Override public void groupEvent(Group<AutoScalerNode> group, GroupEvent event) { DataStore dataStore = fabricService.adapt(DataStore.class); switch (event) { case CONNECTED: case CHANGED: if (isValid()) { AutoScalerNode state = createState(); try { if (group.isMaster()) { enableMasterZkCache(curator); LOGGER.info("{}: AutoScaleController is the master", autoscalerGroupId); group.update(state); dataStore.trackConfiguration(runnable); enableTimer(); onConfigurationChanged(); } else { LOGGER.info("{}: AutoScaleController is not the master", autoscalerGroupId); group.update(state); disableTimer(); dataStore.untrackConfiguration(runnable); disableMasterZkCache(); } } catch (IllegalStateException e) { // Ignore } } else { LOGGER.info("{}: Not valid with master: " + group.isMaster() + " fabric: " + fabricService + " curator: " + curator, autoscalerGroupId); } break; case DISCONNECTED: dataStore.untrackConfiguration(runnable); } } private void enableMasterZkCache(CuratorFramework curator) { zkMasterCache = new ZooKeeperMasterCache(curator); } private void disableMasterZkCache() { if (zkMasterCache != null) { zkMasterCache = null; } } private void enableTimer() { Timer newTimer = new Timer("fabric8-autoscaler"); if (timer.compareAndSet(null, newTimer)) { TimerTask timerTask = new TimerTask() { @Override public void run() { LOGGER.debug("{}: autoscale timer", autoscalerGroupId); autoScale(); } }; newTimer.schedule(timerTask, pollTime, pollTime); } } private void disableTimer() { Timer oldValue = timer.getAndSet(null); if (oldValue != null) { oldValue.cancel(); } } private void onConfigurationChanged() { LOGGER.debug("{}: configuration has changed, checking the auto-scaling requirements", autoscalerGroupId); autoScale(); } private void autoScale() { try { if (fabricService == null) { throw new Exception(autoscalerGroupId + ": FabricService not available"); } AutoScaledGroupOptions options = new AutoScaledGroupOptions( containerPattern, profilePattern, scaleContainers, inheritRequirements, maxDeviation, averageInstancesPerContainer, containerPrefix, minContainerCount, defaultMaximumInstancesPerHost, ignoreErrors, maxContainersPerHost, dryRun, rootContainerPattern, changesPerPoll); List<ProfileRequirements> profileRequirements = fabricService.getRequirements().getProfileRequirements(); AutoScaledGroup autoScaledGroup = new AutoScaledGroup( autoscalerGroupId, options, fabricService.getContainers(), profileRequirements.toArray(new ProfileRequirements[profileRequirements.size()]), new ContainerFactory(fabricService)); autoScaledGroup.apply(); } catch (Exception e) { LOGGER.error("{}: AutoScaledGroup canceled", autoscalerGroupId, e); } } private AutoScalerNode createState() { return new AutoScalerNode(); } }
yuruki/fuse-autoscale
src/main/java/com/github/yuruki/fuse/autoscale/AutoScaleController.java
Java
apache-2.0
14,893
/* * Copyright 2022 The Hekate Project * * The Hekate Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.hekate.cluster; import io.hekate.HekateNodeTestBase; import io.hekate.core.internal.HekateTestNode; import io.hekate.core.jmx.JmxService; import javax.management.ObjectName; import javax.management.openmbean.CompositeData; import org.junit.Test; import static io.hekate.core.jmx.JmxTestUtils.jmxAttribute; import static io.hekate.core.jmx.JmxTestUtils.verifyJmxNode; import static io.hekate.core.jmx.JmxTestUtils.verifyJmxTopology; import static org.junit.Assert.assertEquals; public class ClusterServiceJmxTest extends HekateNodeTestBase { @Test public void test() throws Exception { HekateTestNode node1 = createNode(boot -> { boot.withRole("role1"); boot.withProperty("prop1", "value1"); boot.withJmx(jmx -> jmx.withDomain("test-node-1") ); }).join(); HekateTestNode node2 = createNode(boot -> { boot.withRole("role2"); boot.withProperty("prop2", "value2"); boot.withJmx(jmx -> jmx.withDomain("test-node-2") ); }).join(); awaitForTopology(node1, node2); ObjectName name1 = node1.get(JmxService.class).nameFor(ClusterServiceJmx.class); ObjectName name2 = node2.get(JmxService.class).nameFor(ClusterServiceJmx.class); assertEquals(node1.cluster().namespace(), jmxAttribute(name1, "Namespace", String.class, node1)); assertEquals(node2.cluster().namespace(), jmxAttribute(name2, "Namespace", String.class, node2)); assertEquals(node1.cluster().topology().size(), (int)jmxAttribute(name1, "TopologySize", Integer.class, node1)); assertEquals(node2.cluster().topology().size(), (int)jmxAttribute(name2, "TopologySize", Integer.class, node2)); assertEquals(node1.cluster().topology().version(), (long)jmxAttribute(name1, "TopologyVersion", Long.class, node1)); assertEquals(node2.cluster().topology().version(), (long)jmxAttribute(name2, "TopologyVersion", Long.class, node2)); verifyJmxNode(node1.cluster().localNode(), jmxAttribute(name1, "LocalNode", CompositeData.class, node1)); verifyJmxNode(node2.cluster().localNode(), jmxAttribute(name2, "LocalNode", CompositeData.class, node2)); CompositeData[] jmxTop1 = jmxAttribute(name1, "Topology", CompositeData[].class, node1); CompositeData[] jmxTop2 = jmxAttribute(name1, "Topology", CompositeData[].class, node2); verifyJmxTopology(node1.cluster().topology(), jmxTop1); verifyJmxTopology(node2.cluster().topology(), jmxTop2); } }
hekate-io/hekate
hekate-core/src/test/java/io/hekate/cluster/ClusterServiceJmxTest.java
Java
apache-2.0
3,232
//---------------------------------------------------------- -*- Mode: C++ -*- // $Id: KfsWriter_main.cc 71 2008-07-07 15:49:14Z sriramsrao $ // // Created 2006/06/23 // // Copyright 2008 Quantcast Corp. // Copyright 2006-2008 Kosmix Corp. // // This file is part of Kosmos File System (KFS). // // 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. // // \brief Program that writes sequentially to a file in KFS. // //---------------------------------------------------------------------------- #include <iostream> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <fstream> #include <fcntl.h> #include "libkfsClient/KfsClient.h" #define MIN_FILE_SIZE 2048 #define MAX_FILE_SIZE (4096 * 8) #define MAX_FILE_NAME_LEN 256 using std::cout; using std::endl; using std::ifstream; using namespace KFS; KfsClientPtr gKfsClient; bool doMkdir(char *dirname); bool doFileOps(char *testDataFile, char *dirname, int seqNum, int numIter); bool compareData(char *dst, char *src, int numBytes); void generateData(char *testDataFile, char *buf, int numBytes); int main(int argc, char **argv) { char dirname[256]; if (argc < 3) { cout << "Usage: " << argv[0] << " <test-data-file> <kfs-client-properties file> " << endl; exit(0); } gKfsClient = getKfsClientFactory()->GetClient(argv[2]); if (!gKfsClient) { cout << "kfs client failed to initialize...exiting" << endl; exit(0); } srand(100); strcpy(dirname, "/dir1"); doMkdir(dirname); if (doFileOps(argv[1], dirname, 0, 1) < 0) { cout << "File ops failed" << endl; } #if 0 // the second call rename once should fail if (doFileOps(argv[1], dirname, 0, 1) < 0) { cout << "File ops failed" << endl; } for (int i = 0; i < numFiles; i++) { if (doFileOps(dirname, 0, 10) < 0) { cout << "File ops failed..." << endl; exit(0); } } #endif cout << "Test passed" << endl; } bool doMkdir(char *dirname) { int fd; cout << "Making dir: " << dirname << endl; fd = gKfsClient->Mkdir(dirname); if (fd < 0) { cout << "Mkdir failed: " << fd << endl; return false; } cout << "Mkdir returned: " << fd << endl; return fd > 0; } bool doFileOps(char *testDataFile, char *parentDir, int seqNum, int numIter) { char *dataBuf, *kfsBuf; size_t numBytes = 0; int fd; char fileName[MAX_FILE_NAME_LEN]; while (numBytes < MIN_FILE_SIZE) { numBytes = rand() % MAX_FILE_SIZE; } numBytes = 70000; cout << "Writing " << numBytes << endl; dataBuf = new char[numBytes]; generateData(testDataFile, dataBuf, numBytes); memset(fileName, 0, MAX_FILE_NAME_LEN); snprintf(fileName, MAX_FILE_NAME_LEN, "%s/foo.%d", parentDir, seqNum); fd = gKfsClient->Open(fileName, O_CREAT|O_RDWR); if (fd < 0) { cout << "Create failed: " << endl; exit(0); } kfsBuf = new char[numBytes]; memcpy(kfsBuf, dataBuf, numBytes); if (gKfsClient->Write(fd, kfsBuf, numBytes) < 0) { cout << "Write failed: " << endl; exit(-1); } // flush out the write gKfsClient->Sync(fd); cout << "sync is done...writing some more" << endl; // write some more; since we are writing in sizes that are // different from the checksum block size, this will force reading // in the "block" to recompute the checksum. // if (gKfsClient->Write(fd, kfsBuf, numBytes) < 0) { cout << "Write failed: " << endl; exit(-1); } cout << "write is done...." << endl; gKfsClient->Close(fd); char newpath[256]; snprintf(newpath, 256, "/dir1/foo.%d", seqNum + 5); // test out the O_EXCL flag and verify failure... fd = gKfsClient->Open(fileName, O_CREAT|O_RDWR|O_EXCL); if (fd > 0) { cout << "Failure: Create with O_EXCL on an existing file worked... " << endl; exit(0); } else { cout << "Crate with O_EXCL failed: " << ErrorCodeToStr(fd) << endl; cout << "Expected failure..." << endl; } delete [] kfsBuf; delete [] dataBuf; return 0; } void generateData(char *testDataFile, char *buf, int numBytes) { int i; ifstream ifs(testDataFile); if (!ifs) { cout << "Unable to open test data file" << endl; exit(0); } for (i = 0; i < numBytes; ++i) { ifs >> buf[i]; if (ifs.eof()) { cout << "Test-data file is too small (" << i << " vs. data= " << numBytes << endl; exit(0); } } } bool compareData(char *dst, char *src, int numBytes) { int i; for (i = 0; i < numBytes; i++) { if (dst[i] == src[i]) continue; cout << "Mismatch at index: " << i << endl; return false; } return true; }
nzinfo/my-kfs-022
src/cc/tests/KfsWriter_main.cc
C++
apache-2.0
5,421
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "kudu/tablet/rowset.h" #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "kudu/common/generic_iterators.h" #include "kudu/common/iterator.h" #include "kudu/common/schema.h" #include "kudu/common/timestamp.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/tablet/rowset_metadata.h" using std::shared_ptr; using std::string; using std::vector; using strings::Substitute; namespace kudu { namespace tablet { DuplicatingRowSet::DuplicatingRowSet(RowSetVector old_rowsets, RowSetVector new_rowsets) : old_rowsets_(std::move(old_rowsets)), new_rowsets_(std::move(new_rowsets)) { CHECK_GT(old_rowsets_.size(), 0); CHECK_GT(new_rowsets_.size(), 0); } DuplicatingRowSet::~DuplicatingRowSet() { } // Stringify the given list of rowsets into 'dst'. static void AppendRowSetStrings(const RowSetVector &rowsets, string *dst) { bool first = true; dst->append("["); for (const shared_ptr<RowSet> &rs : rowsets) { if (!first) { dst->append(", "); } first = false; dst->append(rs->ToString()); } dst->append("]"); } string DuplicatingRowSet::ToString() const { string ret; ret.append("DuplicatingRowSet("); AppendRowSetStrings(old_rowsets_, &ret); ret.append(" -> "); AppendRowSetStrings(new_rowsets_, &ret); ret.append(")"); return ret; } Status DuplicatingRowSet::NewRowIterator(const Schema *projection, const MvccSnapshot &snap, OrderMode order, gscoped_ptr<RowwiseIterator>* out) const { // Use the original rowset. if (old_rowsets_.size() == 1) { return old_rowsets_[0]->NewRowIterator(projection, snap, order, out); } // Union or merge between them vector<shared_ptr<RowwiseIterator> > iters; for (const shared_ptr<RowSet> &rowset : old_rowsets_) { gscoped_ptr<RowwiseIterator> iter; RETURN_NOT_OK_PREPEND(rowset->NewRowIterator(projection, snap, order, &iter), Substitute("Could not create iterator for rowset $0", rowset->ToString())); iters.push_back(shared_ptr<RowwiseIterator>(iter.release())); } switch (order) { case ORDERED: out->reset(new MergeIterator(*projection, std::move(iters))); break; case UNORDERED: out->reset(new UnionIterator(std::move(iters))); break; default: LOG(FATAL) << "unknown order: " << order; } return Status::OK(); } Status DuplicatingRowSet::NewCompactionInput(const Schema* projection, const MvccSnapshot &snap, gscoped_ptr<CompactionInput>* out) const { LOG(FATAL) << "duplicating rowsets do not act as compaction input"; return Status::OK(); } Status DuplicatingRowSet::MutateRow(Timestamp timestamp, const RowSetKeyProbe &probe, const RowChangeList &update, const consensus::OpId& op_id, ProbeStats* stats, OperationResultPB* result) { // Duplicate the update to both the relevant input rowset and the output rowset. // // It's crucial to do the mutation against the input side first, due to the potential // for a race during flush: the output rowset may not yet hold a DELETE which // is present in the input rowset. In that case, the UPDATE against the output rowset would // succeed whereas it can't be applied to the input rowset. So, we update the input rowset first, // and if it succeeds, propagate to the output. // First mutate the relevant input rowset. bool updated = false; for (const shared_ptr<RowSet> &rowset : old_rowsets_) { Status s = rowset->MutateRow(timestamp, probe, update, op_id, stats, result); if (s.ok()) { updated = true; break; } else if (!s.IsNotFound()) { LOG(ERROR) << "Unable to update key " << probe.schema()->CreateKeyProjection().DebugRow(probe.row_key()) << " (failed on rowset " << rowset->ToString() << "): " << s.ToString(); return s; } } if (!updated) { return Status::NotFound("not found in any compaction input"); } // If it succeeded there, we also need to mirror into the new rowset. int mirrored_count = 0; for (const shared_ptr<RowSet> &new_rowset : new_rowsets_) { Status s = new_rowset->MutateRow(timestamp, probe, update, op_id, stats, result); if (s.ok()) { mirrored_count++; #ifdef NDEBUG // In non-DEBUG builds, we can break as soon as we find the correct // rowset to mirror to. In a DEBUG build, though, we keep looking // through all, and make sure that we only update in one of them. break; #endif } else if (!s.IsNotFound()) { RETURN_NOT_OK_PREPEND(s, Substitute("Unable to mirror update to rowset $0 for key: $1", new_rowset->ToString(), probe.schema()->CreateKeyProjection().DebugRow(probe.row_key()))); } // IsNotFound is OK - it might be in a different one. } CHECK_EQ(mirrored_count, 1) << "Updated row in compaction input, but didn't mirror in exactly 1 new rowset: " << probe.schema()->CreateKeyProjection().DebugRow(probe.row_key()); return Status::OK(); } Status DuplicatingRowSet::CheckRowPresent(const RowSetKeyProbe &probe, bool *present, ProbeStats* stats) const { *present = false; for (const shared_ptr<RowSet> &rowset : old_rowsets_) { RETURN_NOT_OK(rowset->CheckRowPresent(probe, present, stats)); if (*present) { return Status::OK(); } } return Status::OK(); } Status DuplicatingRowSet::CountRows(rowid_t *count) const { int64_t accumulated_count = 0; for (const shared_ptr<RowSet> &rs : new_rowsets_) { rowid_t this_count; RETURN_NOT_OK(rs->CountRows(&this_count)); accumulated_count += this_count; } CHECK_LT(accumulated_count, std::numeric_limits<rowid_t>::max()) << "TODO: should make sure this is 64-bit safe - probably not right now" << " because rowid_t is only 32-bit."; *count = accumulated_count; return Status::OK(); } Status DuplicatingRowSet::GetBounds(string* min_encoded_key, string* max_encoded_key) const { // The range out of the output rowset always spans the full range // of the input rowsets, since no new rows can be inserted. // The output rowsets are in ascending order, so their total range // spans the range [front().min, back().max]. string junk; RETURN_NOT_OK(new_rowsets_.front()->GetBounds(min_encoded_key, &junk)); RETURN_NOT_OK(new_rowsets_.back()->GetBounds(&junk, max_encoded_key)); return Status::OK(); } uint64_t DuplicatingRowSet::OnDiskSize() const { uint64_t size = 0; for (const shared_ptr<RowSet> &rs : new_rowsets_) { size += rs->OnDiskSize(); } return size; } uint64_t DuplicatingRowSet::OnDiskBaseDataSize() const { uint64_t size = 0; for (const shared_ptr<RowSet> &rs : new_rowsets_) { size += rs->OnDiskBaseDataSize(); } return size; } uint64_t DuplicatingRowSet::OnDiskBaseDataSizeWithRedos() const { // The actual value of this doesn't matter, since it won't be selected // for compaction. uint64_t size = 0; for (const shared_ptr<RowSet> &rs : new_rowsets_) { size += rs->OnDiskBaseDataSizeWithRedos(); } return size; } shared_ptr<RowSetMetadata> DuplicatingRowSet::metadata() { return shared_ptr<RowSetMetadata>(reinterpret_cast<RowSetMetadata *>(NULL)); } Status DuplicatingRowSet::DebugDump(vector<string> *lines) { // NOLINT(*) int i = 1; for (const shared_ptr<RowSet> &rs : old_rowsets_) { LOG_STRING(INFO, lines) << "Duplicating rowset input " << ToString() << " " << i << "/" << old_rowsets_.size() << ":"; RETURN_NOT_OK(rs->DebugDump(lines)); i++; } i = 1; for (const shared_ptr<RowSet> &rs : new_rowsets_) { LOG_STRING(INFO, lines) << "Duplicating rowset output " << ToString() << " " << i << "/" << new_rowsets_.size() << ":"; RETURN_NOT_OK(rs->DebugDump(lines)); i++; } return Status::OK(); } } // namespace tablet } // namespace kudu
andrwng/kudu
src/kudu/tablet/rowset.cc
C++
apache-2.0
9,246
/** * @version: 1.0.1 * @author: Dan Grossman http://www.dangrossman.info/ * @date: 2012-08-20 * @copyright: Copyright (c) 2012 Dan Grossman. All rights reserved. * @license: Licensed under Apache License v2.0. See http://www.apache.org/licenses/LICENSE-2.0 * @website: http://www.improvely.com/ */ !function ($) { var DateRangePicker = function (element, options, cb) { var hasOptions = typeof options == 'object' var localeObject; //state this.startDate = Date.today(); this.endDate = Date.today(); this.minDate = false; this.maxDate = false; this.changed = false; this.ranges = {}; this.opens = 'right'; this.cb = function () { }; this.format = 'MM/dd/yyyy'; this.separator = ' - '; this.showWeekNumbers = false; this.buttonClasses = ['btn-success']; this.locale = { applyLabel: 'Apply', fromLabel: 'From', toLabel: 'To', weekLabel: 'W', customRangeLabel: 'Custom Range', daysOfWeek: Date.CultureInfo.shortestDayNames, monthNames: Date.CultureInfo.monthNames, firstDay: 0 }; localeObject = this.locale; this.leftCalendar = { month: Date.today().set({ day: 1, month: this.startDate.getMonth(), year: this.startDate.getFullYear() }), calendar: Array() }; this.rightCalendar = { month: Date.today().set({ day: 1, month: this.endDate.getMonth(), year: this.endDate.getFullYear() }), calendar: Array() }; // by default, the daterangepicker element is placed at the bottom of HTML body this.parentEl = 'body'; //element that triggered the date range picker this.element = $(element); if (this.element.hasClass('pull-right')) this.opens = 'left'; if (this.element.is('input')) { this.element.on({ click: $.proxy(this.show, this), focus: $.proxy(this.show, this) }); } else { this.element.on('click', $.proxy(this.show, this)); } if (hasOptions) { if(typeof options.locale == 'object') { $.each(localeObject, function (property, value) { localeObject[property] = options.locale[property] || value; }); } } var DRPTemplate = '<div class="daterangepicker dropdown-menu">' + '<div class="calendar left"></div>' + '<div class="calendar right"></div>' + '<div class="ranges">' + '<div class="range_inputs">' + '<div>' + '<input class="m-wrap input-mini" type="text" name="daterangepicker_start" value="" disabled="disabled" />' + '</div>' + '<div>' + '<input class="m-wrap input-mini" type="text" name="daterangepicker_end" value="" disabled="disabled" />' + '</div>' + '<button class="btn " disabled="disabled">' + this.locale.applyLabel + '</button>' + '</div>' + '</div>' + '</div>'; var DRPTemplate2 = '<div class="daterangepicker dropdown-menu">' + '<div class="calendar left"></div>' + '<div class="ranges">' + '<div class="range_inputs">' + '<button class="btn " disabled="disabled">' + this.locale.applyLabel + '</button>' + '</div>' + '</div>' + '</div>'; this.parentEl = (hasOptions && options.parentEl && $(options.parentEl)) || $(this.parentEl); //the date range picker this.container = $(DRPTemplate).appendTo(this.parentEl); if (hasOptions) { if (typeof options.format == 'string') this.format = options.format; if (typeof options.separator == 'string') this.separator = options.separator; if (typeof options.startDate == 'string') this.startDate = Date.parse(options.startDate, this.format); if (typeof options.endDate == 'string') this.endDate = Date.parse(options.endDate, this.format); if (typeof options.minDate == 'string') this.minDate = Date.parse(options.minDate, this.format); if (typeof options.maxDate == 'string') this.maxDate = Date.parse(options.maxDate, this.format); if (typeof options.startDate == 'object') this.startDate = options.startDate; if (typeof options.endDate == 'object') this.endDate = options.endDate; if (typeof options.minDate == 'object') this.minDate = options.minDate; if (typeof options.maxDate == 'object') this.maxDate = options.maxDate; if (typeof options.ranges == 'object') { for (var range in options.ranges) { var start = options.ranges[range][0]; var end = options.ranges[range][1]; if (typeof start == 'string') start = Date.parse(start); if (typeof end == 'string') end = Date.parse(end); // If we have a min/max date set, bound this range // to it, but only if it would otherwise fall // outside of the min/max. if (this.minDate && start < this.minDate) start = this.minDate; if (this.maxDate && end > this.maxDate) end = this.maxDate; // If the end of the range is before the minimum (if min is set) OR // the start of the range is after the max (also if set) don't display this // range option. if ((this.minDate && end < this.minDate) || (this.maxDate && start > this.maxDate)) { continue; } this.ranges[range] = [start, end]; } var list = '<ul>'; for (var range in this.ranges) { list += '<li>' + range + '</li>'; } list += '<li>' + this.locale.customRangeLabel + '</li>'; list += '</ul>'; this.container.find('.ranges').prepend(list); } // update day names order to firstDay if (typeof options.locale == 'object') { if (typeof options.locale.firstDay == 'number') { this.locale.firstDay = options.locale.firstDay; var iterator = options.locale.firstDay; while (iterator > 0) { this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift()); iterator--; } } } if (typeof options.opens == 'string') this.opens = options.opens; if (typeof options.showWeekNumbers == 'boolean') { this.showWeekNumbers = options.showWeekNumbers; } if (typeof options.buttonClasses == 'string') { this.buttonClasses = [options.buttonClasses]; } if (typeof options.buttonClasses == 'object') { this.buttonClasses = options.buttonClasses; } } //apply CSS classes to buttons var c = this.container; $.each(this.buttonClasses, function (idx, val) { c.find('button').addClass(val); }); if (this.opens == 'right') { //swap calendar positions var left = this.container.find('.calendar.left'); var right = this.container.find('.calendar.right'); left.removeClass('left').addClass('right'); right.removeClass('right').addClass('left'); } if (typeof options == 'undefined' || typeof options.ranges == 'undefined') this.container.find('.calendar').show(); if (typeof cb == 'function') this.cb = cb; this.container.addClass('opens' + this.opens); //event listeners this.container.on('mousedown', $.proxy(this.mousedown, this)); this.container.find('.calendar').on('click', '.prev', $.proxy(this.clickPrev, this)); this.container.find('.calendar').on('click', '.next', $.proxy(this.clickNext, this)); this.container.find('.ranges').on('click', 'button', $.proxy(this.clickApply, this)); this.container.find('.calendar').on('click', 'td.available', $.proxy(this.clickDate, this)); this.container.find('.calendar').on('mouseenter', 'td.available', $.proxy(this.enterDate, this)); this.container.find('.calendar').on('mouseleave', 'td.available', $.proxy(this.updateView, this)); this.container.find('.ranges').on('click', 'li', $.proxy(this.clickRange, this)); this.container.find('.ranges').on('mouseenter', 'li', $.proxy(this.enterRange, this)); this.container.find('.ranges').on('mouseleave', 'li', $.proxy(this.updateView, this)); this.element.on('keyup', $.proxy(this.updateFromControl, this)); this.updateView(); this.updateCalendars(); }; DateRangePicker.prototype = { constructor: DateRangePicker, mousedown: function (e) { e.stopPropagation(); e.preventDefault(); }, updateView: function () { this.leftCalendar.month.set({ month: this.startDate.getMonth(), year: this.startDate.getFullYear() }); this.rightCalendar.month.set({ month: this.endDate.getMonth(), year: this.endDate.getFullYear() }); this.container.find('input[name=daterangepicker_start]').val(this.startDate.toString(this.format)); this.container.find('input[name=daterangepicker_end]').val(this.endDate.toString(this.format)); if (this.startDate.equals(this.endDate) || this.startDate.isBefore(this.endDate)) { this.container.find('button').removeAttr('disabled'); } else { this.container.find('button').attr('disabled', 'disabled'); } }, updateFromControl: function () { if (!this.element.is('input')) return; var dateString = this.element.val().split(this.separator); var start = Date.parseExact(dateString[0], this.format); var end = Date.parseExact(dateString[1], this.format); if (start == null || end == null) return; if (end.isBefore(start)) return; this.startDate = start; this.endDate = end; this.updateView(); this.cb(this.startDate, this.endDate); this.updateCalendars(); }, notify: function () { this.updateView(); if (this.element.is('input')) { this.element.val(this.startDate.toString(this.format) + this.separator + this.endDate.toString(this.format)); } this.cb(this.startDate, this.endDate); }, move: function () { var parentOffset = { top: this.parentEl.offset().top - this.parentEl.scrollTop(), left: this.parentEl.offset().left - this.parentEl.scrollLeft() }; if (this.opens == 'left') { this.container.css({ top: this.element.offset().top + this.element.outerHeight(), right: $(window).width() - this.element.offset().left - this.element.outerWidth() - parentOffset.left, left: 'auto' }); } else { this.container.css({ top: this.element.offset().top + this.element.outerHeight(), left: this.element.offset().left - parentOffset.left, right: 'auto' }); } }, show: function (e) { this.container.show(); this.move(); if (e) { e.stopPropagation(); e.preventDefault(); } this.changed = false; $(document).on('mousedown', $.proxy(this.hide, this)); }, hide: function (e) { this.container.hide(); $(document).off('mousedown', this.hide); if (this.changed) { this.changed = false; this.notify(); } }, enterRange: function (e) { var label = e.target.innerHTML; if (label == this.locale.customRangeLabel) { this.updateView(); } else { var dates = this.ranges[label]; this.container.find('input[name=daterangepicker_start]').val(dates[0].toString(this.format)); this.container.find('input[name=daterangepicker_end]').val(dates[1].toString(this.format)); } }, clickRange: function (e) { var label = e.target.innerHTML; if (label == this.locale.customRangeLabel) { this.container.find('.calendar').show(); } else { var dates = this.ranges[label]; this.startDate = dates[0]; this.endDate = dates[1]; this.leftCalendar.month.set({ month: this.startDate.getMonth(), year: this.startDate.getFullYear() }); this.rightCalendar.month.set({ month: this.endDate.getMonth(), year: this.endDate.getFullYear() }); this.updateCalendars(); this.changed = true; this.container.find('.calendar').hide(); this.hide(); } }, clickPrev: function (e) { var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { this.leftCalendar.month.add({ months: -1 }); } else { this.rightCalendar.month.add({ months: -1 }); } this.updateCalendars(); }, clickNext: function (e) { var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { this.leftCalendar.month.add({ months: 1 }); } else { this.rightCalendar.month.add({ months: 1 }); } this.updateCalendars(); }, enterDate: function (e) { var title = $(e.target).attr('title'); var row = title.substr(1, 1); var col = title.substr(3, 1); var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { this.container.find('input[name=daterangepicker_start]').val(this.leftCalendar.calendar[row][col].toString(this.format)); } else { this.container.find('input[name=daterangepicker_end]').val(this.rightCalendar.calendar[row][col].toString(this.format)); } }, clickDate: function (e) { var title = $(e.target).attr('title'); var row = title.substr(1, 1); var col = title.substr(3, 1); var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { startDate = this.leftCalendar.calendar[row][col]; endDate = this.endDate; } else { startDate = this.startDate; endDate = this.rightCalendar.calendar[row][col]; } cal.find('td').removeClass('active'); if (startDate.equals(endDate) || startDate.isBefore(endDate)) { $(e.target).addClass('active'); if (!startDate.equals(this.startDate) || !endDate.equals(this.endDate)) this.changed = true; this.startDate = startDate; this.endDate = endDate; } this.leftCalendar.month.set({ month: this.startDate.getMonth(), year: this.startDate.getFullYear() }); this.rightCalendar.month.set({ month: this.endDate.getMonth(), year: this.endDate.getFullYear() }); this.updateCalendars(); }, clickApply: function (e) { this.hide(); }, updateCalendars: function () { this.leftCalendar.calendar = this.buildCalendar(this.leftCalendar.month.getMonth(), this.leftCalendar.month.getFullYear()); this.rightCalendar.calendar = this.buildCalendar(this.rightCalendar.month.getMonth(), this.rightCalendar.month.getFullYear()); this.container.find('.calendar.left').html(this.renderCalendar(this.leftCalendar.calendar, this.startDate, this.minDate, this.endDate)); this.container.find('.calendar.right').html(this.renderCalendar(this.rightCalendar.calendar, this.endDate, this.startDate, this.maxDate)); }, buildCalendar: function (month, year) { var firstDay = Date.today().set({ day: 1, month: month, year: year }); var lastMonth = firstDay.clone().add(-1).day().getMonth(); var lastYear = firstDay.clone().add(-1).day().getFullYear(); var daysInMonth = Date.getDaysInMonth(year, month); var daysInLastMonth = Date.getDaysInMonth(lastYear, lastMonth); var dayOfWeek = firstDay.getDay(); //initialize a 6 rows x 7 columns array for the calendar var calendar = Array(); for (var i = 0; i < 6; i++) { calendar[i] = Array(); } //populate the calendar with date objects var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1; if (startDay > daysInLastMonth) startDay -= 7; if (dayOfWeek == this.locale.firstDay) startDay = daysInLastMonth - 6; var curDate = Date.today().set({ day: startDay, month: lastMonth, year: lastYear }); for (var i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = curDate.clone().add(1).day()) { if (i > 0 && col % 7 == 0) { col = 0; row++; } calendar[row][col] = curDate; } return calendar; }, renderCalendar: function (calendar, selected, minDate, maxDate) { var html = '<table class="table-condensed">'; html += '<thead>'; html += '<tr>'; // add empty cell for week number if (this.showWeekNumbers) html += '<th></th>'; if (!minDate || minDate < calendar[1][1]) { html += '<th class="prev available"><i class="icon-angle-left"></i></th>'; } else { html += '<th></th>'; } html += '<th colspan="5" style="width: auto">' + this.locale.monthNames[calendar[1][1].getMonth()] + calendar[1][1].toString(" yyyy") + '</th>'; if (!maxDate || maxDate > calendar[1][1]) { html += '<th class="next available"><i class="icon-angle-right"></i></th>'; } else { html += '<th></th>'; } html += '</tr>'; html += '<tr>'; // add week number label if (this.showWeekNumbers) html += '<th class="week">' + this.locale.weekLabel + '</th>'; $.each(this.locale.daysOfWeek, function (index, dayOfWeek) { html += '<th>' + dayOfWeek + '</th>'; }); html += '</tr>'; html += '</thead>'; html += '<tbody>'; for (var row = 0; row < 6; row++) { html += '<tr>'; // add week number if (this.showWeekNumbers) html += '<td class="week">' + calendar[row][0].getWeek() + '</td>'; for (var col = 0; col < 7; col++) { var cname = 'available '; cname += (calendar[row][col].getMonth() == calendar[1][1].getMonth()) ? '' : 'off'; // Normalise the time so the comparison won't fail selected.setHours(0,0,0,0); if ( (minDate && calendar[row][col] < minDate) || (maxDate && calendar[row][col] > maxDate)) { cname = 'off disabled'; } else if (calendar[row][col].equals(selected)) { cname += 'active'; } var title = 'r' + row + 'c' + col; html += '<td class="' + cname + '" title="' + title + '">' + calendar[row][col].getDate() + '</td>'; } html += '</tr>'; } html += '</tbody>'; html += '</table>'; return html; } }; $.fn.daterangepicker = function (options, cb) { this.each(function() { var el = $(this); if (!el.data('daterangepicker')) el.data('daterangepicker', new DateRangePicker(el, options, cb)); }); return this; }; } (window.jQuery);
healerkx/AdminBuildr
www/view/media/js/daterangepicker.js
JavaScript
apache-2.0
21,817
package org.easyarch.netpet.web.http.session.impl; import org.easyarch.netpet.web.http.session.HttpSession; import org.easyarch.netpet.kits.TimeKits; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by xingtianyu on 17-3-14 * 下午8:35 * description:session,在HandlerContext处实现了主动淘汰,内部getAttr实现被动淘汰 */ public class DefaultHttpSession implements HttpSession { private Map<String,Object> sessionMap = new HashMap<>(); private int maxAge; public String sessionId; private Date createAt; public DefaultHttpSession(){ createAt = new Date(); } public Object getAttr(String name){ if (isExpire()){ remove(name); return null; } return sessionMap.get(name); } public void setAttr(String name,Object value){ sessionMap.put(name,value); } public Object remove(String name){ return sessionMap.remove(name); } @Override public void clear() { sessionMap.clear(); } public int getMaxAge() { return maxAge; } public void setMaxAge(int maxAge) { this.maxAge = maxAge; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public Map<String,Object> getAll(){ return sessionMap; } @Override public boolean isExpire() { Date current = new Date(); return current.before(TimeKits.plusSeconds(maxAge,createAt)); } @Override public String toString() { return "DefaultHttpSession{" + "sessionMap=" + sessionMap + '}'; } }
rpgmakervx/netpet
src/main/java/org/easyarch/netpet/web/http/session/impl/DefaultHttpSession.java
Java
apache-2.0
1,766
<!--- 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. --> # Trainer Training a neural network model consists of iteratively performing three simple steps. The first step is the forward step which computes the loss. In MXNet Gluon, this first step is achieved by doing a forward pass by calling `net.forward(X)` or simply `net(X)` and then calling the loss function with the result of the forward pass and the labels. For example `l = loss_fn(net(X), y)`. The second step is the backward step which computes the gradient of the loss with respect to the parameters. In Gluon, this step is achieved by doing the first step in an [autograd.record()](/api/python/docs/api/autograd/index.html) scope to record the computations needed to calculate the loss, and then calling `l.backward()` to compute the gradient of the loss with respect to the parameters. The final step is to update the neural network model parameters using an optimization algorithm. In Gluon, this step is performed by the [gluon.Trainer](/api/python/docs/api/gluon/trainer.html) and is the subject of this guide. When creating a Gluon `Trainer` you must provide a collection of parameters that need to be learnt. You also provide an `Optimizer` that will be used to update the parameters every training iteration when `trainer.step` is called. ## Basic Usage ### Network and Trainer To illustrate how to use the Gluon `Trainer` we will create a simple perceptron model and create a `Trainer ` instance using the perceptron model parameters and a simple optimizer - `sgd` with learning rate as 1. ```{.python .input} from mxnet import nd, autograd, optimizer, gluon net = gluon.nn.Dense(1) net.initialize() trainer = gluon.Trainer(net.collect_params(), optimizer='sgd', optimizer_params={'learning_rate':1}) ``` ### Forward and Backward Pass Before we can use the `trainer` to update model parameters, we must first run the forward and backward passes. Here we implement a function to compute the first two steps (forward step and backward step) of training the perceptron on a random dataset. ```{.python .input} batch_size = 8 X = nd.random.uniform(shape=(batch_size, 4)) y = nd.random.uniform(shape=(batch_size,)) loss = gluon.loss.L2Loss() def forward_backward(): with autograd.record(): l = loss(net(X), y) l.backward() forward_backward() ``` **Warning**: It is extremely important that the gradients of the loss function with respect to your model parameters are computed before running `trainer step`. A common way to introduce bugs to your model training code is to omit the `loss.backward()`before the update step. Before updating, let's check the current network parameters. ```{.python .input} curr_weight = net.weight.data().copy() print(curr_weight) ``` ### `Trainer` step Now we will call the `step` method to perform one update. We provide the `batch_size` as an argument to normalize the size of the gradients and make it independent of the batch size. Otherwise we'd get larger gradients with larger batch sizes. We can see the network parameters have now changed. ```{.python .input} trainer.step(batch_size) print(net.weight.data()) ``` Since we used plain SGD, the update rule is $w = w - \eta/b \nabla \ell$, where $b$ is the batch size and $\nabla\ell$ is the gradient of the loss function with respect to the weights and $\eta$ is the learning rate. We can verify it by running the following code snippet which is explicitly performing the SGD update. ```{.python .input} print(curr_weight - net.weight.grad() * 1 / batch_size) ``` ## Advanced Usage ### Using Optimizer Instance In the previous example, we use the string argument `sgd` to select the optimization method, and `optimizer_params` to specify the optimization method arguments. All pre-defined optimization methods can be passed in this way and the complete list of implemented optimizers is provided in the [`mxnet.optimizer`](/api/python/docs/api/optimizer/index.html) module. However we can also pass an optimizer instance directly to the `Trainer` constructor. For example: ```{.python .input} optim = optimizer.Adam(learning_rate = 1) trainer = gluon.Trainer(net.collect_params(), optim) ``` ```{.python .input} forward_backward() trainer.step(batch_size) net.weight.data() ``` For reference and implementation details about each optimizer, please refer to the [guide](/api/python/docs/api/optimizer/index.html) for the `optimizer` module. ### KVStore Options The `Trainer` constructor also accepts the following keyword arguments for : - `kvstore` – how key value store should be created for multi-gpu and distributed training. Check out [`mxnet.kvstore.KVStore`](/api/python/docs/api/kvstore/index.html) for more information. String options are any of the following ['local', 'device', 'dist_device_sync', 'dist_device_async']. - `compression_params` – Specifies type of gradient compression and additional arguments depending on the type of compression being used. See [`mxnet.KVStore.set_gradient_compression_method`](/api/python/docs/api/kvstore/index.html#mxnet.kvstore.KVStore.set_gradient_compression) for more details on gradient compression. - `update_on_kvstore` – Whether to perform parameter updates on KVStore. If None, then the `Trainer` instance will choose the more suitable option depending on the type of KVStore. ### Changing the Learning Rate We set the initial learning rate when creating a trainer by passing the learning rate as an `optimizer_param`. However, sometimes we may need to change the learning rate during training, for example when doing an explicit learning rate warmup schedule. The trainer instance provides an easy way to achieve this. The current training rate can be accessed through the `learning_rate` attribute. ```{.python .input} trainer.learning_rate ``` We can change it through the `set_learning_rate` method. ```{.python .input} trainer.set_learning_rate(0.1) trainer.learning_rate ``` In addition, there are multiple pre-defined learning rate scheduling methods that are already implemented in the [mxnet.lr_scheduler](/api/python/docs/api/lr_scheduler/index.html) module. The learning rate schedulers can be incorporated into your trainer by passing them in as an `optimizer_param` entry. Please refer to the [LR scheduler guide](/api/python/docs/tutorials/packages/gluon/training/learning_rates/learning_rate_schedules.html) to learn more. ## Summary * The MXNet Gluon `Trainer` API is used to update the parameters of a network with a particular optimization algorithm. * After the forward and backward pass, the model update step is done in Gluon using `trainer.step()`. * A Gluon `Trainer` can be instantiated by passing in the name of the optimizer to use and the `optimizer_params` for that optimizer or alternatively by passing in an instance of `mxnet.optimizer.Optimizer`. * You can change the learning rate for a Gluon `Trainer` by setting the member variable but Gluon also provides a module for learning rate scheduling. ## Next Steps While optimization and optimizers play a significant role in deep learning model training, there are still other important components to model training. Here are a few suggestions about where to look next. * The [Optimizer API](/api/python/docs/api/optimizer/index.html) and [optimizer guide](/api/python/docs/tutorials/packages/optimizer/index.html) have information about all the different optimizers implemented in MXNet and their update steps. The [Dive into Deep Learning](https://en.diveintodeeplearning.org/chapter_optimization/index.html) book also has a chapter dedicated to optimization methods and explains various key optimizers in great detail. - Take a look at the [guide to parameter initialization](/api/python/docs/tutorials/packages/gluon/blocks/init.html) in MXNet to learn about what initialization schemes are already implemented, and how to implement your custom initialization schemes. - Also check out this [guide on parameter management](/api/python/docs/tutorials/packages/gluon/blocks/parameters.html) to learn about how to manage model parameters in gluon. - Make sure to take a look at the [guide to scheduling learning rates](/api/python/docs/tutorials/packages/gluon/training/learning_rates/learning_rate_schedules.html) to learn how to create learning rate schedules to make your training converge faster. - Finally take a look at the [KVStore API](/api/python/docs/api/kvstore/index.html) to learn how parameter values are synchronized over multiple devices.
mlperf/training_results_v0.7
Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/docs/python_docs/python/tutorials/packages/gluon/training/trainer.md
Markdown
apache-2.0
9,401
#!/bin/bash # # modify by hiyang @ 2016-12-19 # Install-JDK18() { pushd ${oneinstack_dir}/src JDK_FILE="jdk-`echo $jdk18_version | awk -F. '{print $2}'`u`echo $jdk18_version | awk -F_ '{print $NF}'`-linux-$SYS_BIG_FLAG.tar.gz" JAVA_dir=/usr/java JDK_NAME="jdk$jdk18_version" JDK_PATH=$JAVA_dir/$JDK_NAME [ "$OS" == 'CentOS' ] && [ -n "`rpm -qa | grep jdk`" ] && rpm -e `rpm -qa | grep jdk` tar xzf $JDK_FILE if [ -d "$JDK_NAME" ]; then rm -rf $JAVA_dir; mkdir -p $JAVA_dir mv $JDK_NAME $JAVA_dir [ -z "`grep ^'export JAVA_HOME=' /etc/profile`" ] && { [ -z "`grep ^'export PATH=' /etc/profile`" ] && echo "export JAVA_HOME=$JDK_PATH" >> /etc/profile || sed -i "s@^export PATH=@export JAVA_HOME=$JDK_PATH\nexport PATH=@" /etc/profile; } || sed -i "s@^export JAVA_HOME=.*@export JAVA_HOME=$JDK_PATH@" /etc/profile [ -z "`grep ^'export CLASSPATH=' /etc/profile`" ] && sed -i "s@export JAVA_HOME=\(.*\)@export JAVA_HOME=\1\nexport CLASSPATH=\$JAVA_HOME/lib/tools.jar:\$JAVA_HOME/lib/dt.jar:\$JAVA_HOME/lib@" /etc/profile [ -n "`grep ^'export PATH=' /etc/profile`" -a -z "`grep '$JAVA_HOME/bin' /etc/profile`" ] && sed -i "s@^export PATH=\(.*\)@export PATH=\$JAVA_HOME/bin:\1@" /etc/profile [ -z "`grep ^'export PATH=' /etc/profile | grep '$JAVA_HOME/bin'`" ] && echo 'export PATH=$JAVA_HOME/bin:$PATH' >> /etc/profile . /etc/profile echo "${CSUCCESS}$JDK_NAME installed successfully! ${CEND}" else rm -rf $JAVA_dir echo "${CFAILURE}JDK install failed, Please contact the author! ${CEND}" kill -9 $$ fi popd }
PoplarYang/oneinstack-odm
include/jdk-1.8.sh
Shell
apache-2.0
1,584
// -*- coding: us-ascii-unix -*- // Copyright 2012 Lukas Kemmer // // Licensed under the Apache License, Version 2.0 (the "License"); you // may not use this file except in compliance with the License. You // may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. #include <cassert> #include "bitmap/bitmap.hh" #include "bitmap/draw.hh" #include "commands/command.hh" #include "commands/resize-cmd.hh" #include "geo/geo-func.hh" #include "geo/int-rect.hh" #include "geo/point.hh" #include "text/utf8-string.hh" #include "util/optional.hh" namespace faint{ class ResizeCommand : public Command { public: ResizeCommand(const IntRect& rect, const Paint& bg, const utf8_string& name) : Command(CommandType::HYBRID), m_bg(bg), m_name(name), m_rect(rect) {} ResizeCommand(const IntRect& rect, const AltIntRect& altRect, const Paint& bg, const utf8_string& name) : Command(CommandType::HYBRID), m_altRect(altRect.Get()), m_bg(bg), m_name(name), m_rect(rect) {} ResizeCommand(const IntRect& rect, const Paint& bg, const AltPaint& altBg, const utf8_string& name) : Command(CommandType::HYBRID), m_altBg(altBg.Get()), m_bg(bg), m_name(name), m_rect(rect) {} void Do(CommandContext& context) override{ DoRaster(context); context.OffsetOrigin(-m_rect.TopLeft()); } void DoRaster(CommandContext& context) override{ Bitmap bmp(m_rect.GetSize(), m_bg); blit(offsat(context.GetBitmap(), -m_rect.TopLeft()), onto(bmp)); context.SetBitmap(std::move(bmp)); } Command* GetDWIM() override{ if (m_altBg.IsSet()){ return new ResizeCommand(m_rect, m_altBg.Get(), alternate(m_bg), "Resize Image (DWIM)"); } else if (m_altRect.IsSet()){ return new ResizeCommand(m_altRect.Get(), alternate(m_rect), m_bg, "Resize Image (DWIM)"); } assert(false); return nullptr; } bool HasDWIM() const override{ return m_altBg.IsSet() || m_altRect.IsSet(); } utf8_string Name() const override{ return m_name; } Point Translate(const Point& p) const override{ return p - floated(m_rect.TopLeft()); } void Undo(CommandContext& context) override{ context.OffsetOrigin(m_rect.TopLeft()); } Point UndoTranslate(const Point& p) const override{ return p + floated(m_rect.TopLeft()); } private: Optional<Paint> m_altBg; Optional<IntRect> m_altRect; Paint m_bg; utf8_string m_name; IntRect m_rect; }; Command* resize_command(const IntRect& rect, const Paint& bg, const utf8_string& name) { return new ResizeCommand(rect, bg, name); } Command* resize_command(const IntRect& rect, const AltIntRect& altRect, const Paint& bg, const utf8_string& name) { return new ResizeCommand(rect, altRect, bg, name); } Command* resize_command(const IntRect& rect, const Paint& bg, const AltPaint& altBg, const utf8_string& name) { return new ResizeCommand(rect, bg, altBg, name); } } // namespace
tectronics/faint-graphics-editor
commands/resize-cmd.cpp
C++
apache-2.0
3,344
Database.Dispose Method (Boolean) ================================= Releases the resources used by this [Database][1] instance. **Namespace:**  [DbExtensions][2] **Assembly:**  DbExtensions (in DbExtensions.dll) Syntax ------ ```csharp protected virtual void Dispose( bool disposing ) ``` #### Parameters ##### *disposing* Type: [System.Boolean][3] true if this method is being called due to a call to [Dispose()][4]; otherwise, false. See Also -------- #### Reference [Database Class][1] [DbExtensions Namespace][2] [1]: README.md [2]: ../README.md [3]: http://msdn.microsoft.com/en-us/library/a28wyd50 [4]: Dispose.md
maxtoroq/DbExtensions
docs/api/DbExtensions/Database/Dispose_1.md
Markdown
apache-2.0
645
package com.planet_ink.coffee_mud.Abilities.Skills; 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 2017-2022 Bo Zimmerman 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 Skill_BoulderThrowing extends StdSkill { @Override public String ID() { return "Skill_BoulderThrowing"; } private final static String localizedName = CMLib.lang().L("Boulder Throwing"); @Override public String name() { return localizedName; } @Override public String displayText() { return ""; } @Override protected int canAffectCode() { return CAN_MOBS; } @Override protected int canTargetCode() { return 0; } @Override public int abstractQuality() { return Ability.QUALITY_BENEFICIAL_SELF; } @Override public int classificationCode() { return Ability.ACODE_SKILL | Ability.DOMAIN_MARTIALLORE; } @Override public boolean isAutoInvoked() { return true; } @Override public boolean canBeUninvoked() { return false; } protected volatile int tickDownThisShipCombatRound = CombatLibrary.TICKS_PER_SHIP_COMBAT; @Override public boolean tick(final Tickable ticking, final int tickID) { if(tickID==Tickable.TICKID_MOB) { if(tickDownThisShipCombatRound>0) tickDownThisShipCombatRound--; if(affected instanceof MOB) { final MOB mob=(MOB)affected; final Room R=(mob!=null)?mob.location():null; final Area A=(R != null) ? R.getArea() : null; final Item shipItem=(A instanceof Boardable) ? ((Boardable)A).getBoardableItem() : null; if((mob!=null) &&(mob.isMonster()) &&(shipItem instanceof SiegableItem) &&(!mob.isInCombat())) { final Item ammoI=mob.fetchHeldItem(); if(ammoI instanceof Ammunition) { if(tickDownThisShipCombatRound==0) { if(((SiegableItem)shipItem).isInCombat()) CMLib.commands().forceStandardCommand(mob, "Throw", new XVector<String>("THROW",ammoI.Name())); } } else { if(ammoI!=null) CMLib.commands().postRemove(mob, ammoI, false); Item holdI=null; for(final Enumeration<Item> i=mob.items();i.hasMoreElements();) { final Item I=i.nextElement(); if((I instanceof Ammunition) &&(I.container()==null) &&(I.amWearingAt(Item.IN_INVENTORY))) { holdI=I; break; } } if(holdI!=null) CMLib.commands().forceStandardCommand(mob, "Hold", new XVector<String>("HOLD",holdI.Name())); else if(R!=null) { for(final Enumeration<Item> i=R.items();i.hasMoreElements();) { final Item I=i.nextElement(); if((I instanceof Ammunition) &&(I.container()==null) &&(CMLib.flags().isGettable(I))) { holdI=I; break; } } if(holdI!=null) CMLib.commands().postGet(mob, null, holdI, false); } } } } } return super.tick(ticking,tickID); } private AmmunitionWeapon boulderThrower=null; @Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(!(affected instanceof MOB)) return true; final MOB mob=(MOB)affected; if((msg.source()==mob) &&(msg.sourceMinor()==CMMsg.TYP_COMMANDFAIL) &&(msg.targetMessage()!=null)) { final List<String> cmd =CMParms.parse(msg.targetMessage()); final Room R=mob.location(); if(cmd.get(0).toUpperCase().startsWith("TH") && (R!=null)) { final CMObject O = CMLib.english().findCommand(mob, cmd); if((O instanceof Command) && (((Command)O).ID().equals("Throw"))) { final Area A=R.getArea(); final Item possShipItem = (A instanceof Boardable) ? ((Boardable)A).getBoardableItem() : null; final SiegableItem siegeBase = (possShipItem instanceof SiegableItem) ? (SiegableItem)possShipItem : null; final Room shipR=(siegeBase != null)?CMLib.map().roomLocation(siegeBase):null; final String str; if(cmd.size()>2) { str=cmd.get(cmd.size()-1); cmd.remove(str); } else if((siegeBase instanceof SiegableItem) &&(shipR!=null) &&(siegeBase.getCombatant()!=null)) str=shipR.getContextName(siegeBase.getCombatant()); else return true; final String what=CMParms.combine(cmd,1); Item item=mob.fetchItem(null,Wearable.FILTER_WORNONLY,what); if(item==null) item=mob.findItem(null,what); if((item==null)||(!CMLib.flags().canBeSeenBy(item,mob))) return true; if((!item.amWearingAt(Wearable.WORN_HELD))&&(!item.amWearingAt(Wearable.WORN_WIELD))) return true; final Item target; if((siegeBase != null)&&(shipR!=null)) target=shipR.findItem(null,str); else target=R.findItem(null,str); if((target instanceof SiegableItem) &&(CMLib.flags().canBeSeenBy(target, mob))) { final SiegableItem targetSiegeItem = (SiegableItem)target; if(tickDownThisShipCombatRound>0) msg.setSourceMessage(L("You've already thrown this round.")); else if(mob.charStats().getStat(CharStats.STAT_STRENGTH)<10) msg.setSourceMessage(L("You aren't strong enough.")); else if((!(item instanceof Ammunition))||(((Ammunition)item).ammunitionRemaining()<1)) msg.setSourceMessage(L("You can't throw that.")); else if((siegeBase instanceof SiegableItem) &&((R.domainType()&Room.INDOORS)==0)) { if(siegeBase.isInCombat() && (siegeBase.getCombatant()==target)) { if(this.boulderThrower==null) { boulderThrower=(AmmunitionWeapon)CMClass.getWeapon("GenSiegeWeapon"); boulderThrower.setAmmoCapacity(1); boulderThrower.setWeaponClassification(Weapon.CLASS_THROWN); boulderThrower.setWeaponDamageType(Weapon.TYPE_BASHING); } final AmmunitionWeapon weapon=boulderThrower; final Ammunition ammo=(Ammunition)item; boulderThrower.setOwner(null); weapon.setAmmunitionType(ammo.ammunitionType()); weapon.setName(ammo.Name()); weapon.setRanges(0, 1+(mob.charStats().getStat(CharStats.STAT_STRENGTH)-10)/2); final int distance=siegeBase.rangeToTarget(); boolean wasHit=true; if((weapon.maxRange() < distance)||(weapon.minRange() > distance)) { msg.setSourceMessage(L("Your target is presently at distance of @x1, but your range is @x2 to @x3.", ""+distance,""+weapon.minRange(),""+weapon.maxRange())); } else { if(ammo.ammunitionType().equals("catapult-boulders")) weapon.basePhyStats().setDamage(10 + super.getXLEVELLevel(mob)); else if(ammo.ammunitionType().equals("ballista-bolts")) weapon.basePhyStats().setDamage(5 + super.getXLEVELLevel(mob)); else if(ammo.ammunitionType().equals("trebuchet-shots")) weapon.basePhyStats().setDamage(15 + super.getXLEVELLevel(mob)); else weapon.basePhyStats().setDamage(1 + (super.getXLEVELLevel(mob)/2)); weapon.phyStats().setDamage(weapon.basePhyStats().damage()); weapon.setAmmoRemaining(1); weapon.setAmmoRemaining(ammo.ammunitionRemaining()-1); final LinkedList<Ability> removeThese=new LinkedList<Ability>(); for(final Enumeration<Ability> a=weapon.effects();a.hasMoreElements();) { final Ability A1=a.nextElement(); if((A1!=null)&&(!A1.isSavable())&&(A1.invoker()==null)) removeThese.add(A1); } for(final Ability A1 : removeThese) weapon.delEffect(A1); for(final Enumeration<Ability> a=ammo.effects();a.hasMoreElements();) { Ability A1=a.nextElement(); if((A!=null)&&(A.isSavable())&&(weapon.fetchEffect(A1.ID())==null)) { A1=(Ability)A1.copyOf(); A1.setInvoker(null); A1.setSavable(false); weapon.addEffect(A1); } } tickDownThisShipCombatRound=CombatLibrary.TICKS_PER_SHIP_COMBAT; for(int i=0;i<distance;i++) wasHit = wasHit && super.proficiencyCheck(mob, -50+mob.charStats().getStat(CharStats.STAT_DEXTERITY)+(super.getXLEVELLevel(mob)*2), false); CMLib.combat().postSiegeAttack(mob, siegeBase, targetSiegeItem, weapon, wasHit); if(ammo.ammunitionRemaining()<=0) ammo.destroy(); } } else msg.setSourceMessage(L("Your ship must first be in combat with @x1.",target.name(mob))); } else msg.setSourceMessage(L("You must be on the deck of a ship to throw at another ship.")); } } } } return true; } @Override public void executeMsg(final Environmental myHost, final CMMsg msg) { if((this.boulderThrower!=null) &&(msg.tool()==this.boulderThrower)) this.boulderThrower.executeMsg(myHost, msg); super.executeMsg(myHost, msg); } }
bozimmerman/CoffeeMud
com/planet_ink/coffee_mud/Abilities/Skills/Skill_BoulderThrowing.java
Java
apache-2.0
10,515
/******************************************************************************* * Copyright 2012 Manning Publications Co. * * 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.manning.cmis.theblend.android.tracks; import java.math.BigInteger; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.chemistry.opencmis.client.api.Document; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.manning.cmis.theblend.android.constant.CmisBookIds; /** * Responsible to display track item into the listview. * * @author Jean Marie Pascal * */ public class TracksAdapter extends ArrayAdapter<Document> { /** The track list from the server. */ private List<Document> trackList; /** Android Service inflater. */ private LayoutInflater inflater; /** The context associated to the listview. */ private Context context; /** * Instantiates a new tracks adapter. * * @param context * the context associated to the listview * @param tracks * list of tracks */ public TracksAdapter(Context context, List<Document> tracks) { super(context, android.R.layout.simple_list_item_2, tracks); this.context = context; this.trackList = tracks; } /* * (non-Javadoc) * * @see android.widget.ArrayAdapter#getView(int, android.view.View, * android.view.ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; // Try to reuse previous view from the listview. // If the view doesn't exist, create a new one. if (convertView == null) { holder = new ViewHolder(); inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(android.R.layout.simple_list_item_2, null); holder.topText = (TextView) convertView.findViewById(android.R.id.text1); holder.bottomText = (TextView) convertView.findViewById(android.R.id.text2); convertView.setTag(holder); } // Displays information Name + Artist name holder = (ViewHolder) convertView.getTag(); holder.topText.setText((String) trackList.get(position).getName()); holder.bottomText.setText(getArtistValue(trackList.get(position)) + getFormattedLength((BigInteger) trackList.get(position).getProperty(CmisBookIds.LENGTH).getValue())); return convertView; } /** * Utility method to display or not the artist property value. * * @param track * Document object representing the track * @return String representation of artist value. */ private String getArtistValue(Document track) { String value = ""; if (track.getProperty(CmisBookIds.ARTIST) != null && track.getProperty(CmisBookIds.ARTIST).getValue() != null) { value = track.getProperty(CmisBookIds.ARTIST).getValueAsString(); } return value; } /** * Utility method to transform time in seconds into formatted text * * @param length * : time in seconds * @return formatted string representing the value of length. */ private String getFormattedLength(BigInteger length) { if (length != null) { return String.format(" - %d min, %d sec", TimeUnit.SECONDS.toMinutes(length.longValue()), length.longValue() - TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(length.longValue()))); } else { return ""; } } /** * Utility Class ViewHolder. */ private class ViewHolder { /** The top text. */ TextView topText; /** The bottom text. */ TextView bottomText; } }
fmui/ApacheChemistryInAction
chapter10/android/src/com/manning/cmis/theblend/android/tracks/TracksAdapter.java
Java
apache-2.0
4,768
package com.tle.webtests.pageobject.viewitem; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.tle.webtests.framework.PageContext; import com.tle.webtests.pageobject.AbstractPage; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; public class TermsOfUsePage extends AbstractPage<TermsOfUsePage> { public TermsOfUsePage(PageContext context) { super(context, By.xpath("//h2[text()='Terms of use']")); } public boolean hasTerms(String terms) { try { WebElement termsDiv = driver.findElement(By.className("terms")); return termsDiv.getText().equals(terms); } catch (NoSuchElementException e) { return false; } } public int getNumberOfAcceptances() { return Integer.parseInt(driver.findElement(By.id("acceptancecount")).getText().split(" ")[0]); } public List<String> getUsersAccepted() { List<WebElement> cells = driver.findElements(By.xpath("//div/table/tbody/tr/td[1]")); return Lists.transform( cells, new Function<WebElement, String>() { @Override public String apply(WebElement we) { return we.getText(); } }); } }
equella/Equella
autotest/Tests/src/main/java/com/tle/webtests/pageobject/viewitem/TermsOfUsePage.java
Java
apache-2.0
1,286
export interface IFeatureResponse { result: IFeature[]; lastUpdated: number; } export interface IFeature { id: string; openEstimate: number; inProgressEstimate: number; completeEstimate: number; }
capitalone/Hygieia
src/app/widget_modules/feature/interfaces.ts
TypeScript
apache-2.0
211
package spot.scripts; import org.openqa.selenium.WebElement; import org.testng.Assert; import org.testng.annotations.*; import spot.BaseSelenium; import spot.components.NewActionComponent; public class LimitedAccessForNruTest extends BaseSelenium { @BeforeClass public void beforeClass() { navigateToStartPage(); // TODO make sure that no login took place } @Test public void newActionNonExistentTest() { WebElement newButton = new NewActionComponent(driver).getNewButton(); boolean isNewButtonDisplayed = isElementDisplayed(newButton); Assert.assertEquals( isNewButtonDisplayed, false, "New Button for creating new collections/albums is displayed despite being not logged in"); } }
imeji-community/imeji-gui-testing
src/spot/scripts/LimitedAccessForNruTest.java
Java
apache-2.0
749
# Chamaedorea sullivaniorum Hodel & N.W.Uhl SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Arecales/Arecaceae/Chamaedorea/Chamaedorea pumila/ Syn. Chamaedorea sullivaniorum/README.md
Markdown
apache-2.0
198
//Server settings for android push notifications with node-gcm // Load modules var express = require('express'); var gcm = require('node-gcm'); // The apiKey of your project on FCM var app = express(); //var apiKey = "AAAAjo8JDg0:APA91bEkbzZbEgR7eXY1jKgmJZhoW3GaNmRYf5yICNQQEOcaHxZuYtOKLNSK98T9aFAiUpkLUukldgsYDPBvVcEWEabVnQeKyBGWWM-O7yrrufGe2N-40x4I07WLvveL8O3dzDAKKKM7"; // var apiKey = "AAAA7qUjTrg:APA91bFW2oVQ1mE9u2ANPjFy8IfkMWVGrHs0f1b1Umd_K1DDfng9h0e0hRQih8mLaXCPvu35xHBq9recmJ1EGJiCk7o2qwdN2n3FYPwHr21_p4iP2z1mgZGDdZo-uFLGrRxpqXM5L_tRvudTQJTxxH2IpQC0VquYPQ"; //iadapt var apiKey = "AAAAjo8JDg0:APA91bEkbzZbEgR7eXY1jKgmJZhoW3GaNmRYf5yICNQQEOcaHxZuYtOKLNSK98T9aFAiUpkLUukldgsYDPBvVcEWEabVnQeKyBGWWM-O7yrrufGe2N-40x4I07WLvveL8O3dzDAKKKM7"; //Set up the server var server = app.listen(3000, function() { console.log('server is just fine!'); }); var bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); //Define the basic route app.get('/', function(req, res) { res.send("This is basic route"); }); app.post('/register', function(req, res) { var device_token; device_token = req.body.device_token; console.log('device token received'); console.log(device_token); res.send('ok'); }); app.get('/push', function(req, res) { //Initialize the service var service = new gcm.Sender(apiKey); //the number of times to retry sending the message if it fails var retry_times = 4; /***** Define the message for Android Devices *****/ var message_Android = new gcm.Message(); //The title will be shown in the notification center message_Android.addData('title', 'Hello, World'); message_Android.addData('message', 'This is a notification that will be displayed ASAP.'); //Add action buttons, set the foreground property to true the app will be brought to the front //if foreground is false then the callback is run without the app being brought to the foreground. message_Android.addData('actions', [ { "icon": "accept", "title": "Accept", "callback": "window.accept", "foreground": true }, { "icon": "reject", "title": "Reject", "callback": "window.reject", "foreground": false }, ]); //Set content-available = 1, the on('notification') event handler will be called //even app running in background or closed message_Android.addData('content-available', '1'); //Give every message a unique id message_Android.addData('notId', Math.ceil(Math.random() * 100)); //priority can be: -2: minimum, -1: low, 0: default , 1: high, 2: maximum priority. //Set priority will inform the user on the screen even though in the background or close the app. //This priority value determines where the push notification will be put in the notification shade. message_Android.addData('priority', 1); /* message_Android.addData('style', 'inbox'); message_Android.addData('summaryText', 'There are %n% notifications');*/ message_Android.addData('data', { 'type': 'New Medicine', 'id': 1112 }); /***** Define the message for IOS Devices *****/ // var message_IOS = new gcm.Message({ // contentAvailable: true, // // priority: 'high', // notification: { // "sound": "default", // "icon": "default", // title: "Hello, World", // body: 'This is a notification that will be displayed ASAP.', // 'click-action': 'invite' // }, // //Add additional data to the payload // data: { // 'type': 'New Medicine', // 'data': 1112, // notId: Math.random() * 100, // } // }); // var payload = { // // 'content_available': true, // // 'prioriry': 'high', // // notification: { // // 'title': 'Hellow world notif', // // 'body': 'Notification Body for both IOS and Android' // // }, // data: { // 'content-available': '1', // 'priority': 1, // 'title': 'Hellow world data', // 'message': 'Notification Message for both IOS and Android', // // 'icon': 'default', // // 'sound': 'default', // 'notId': Math.random() * 100, // // 'actions': [ // // { "icon": "accept", "title": "Accept", "callback": "window.accept", "foreground": true }, // // { "icon": "reject", "title": "Reject", "callback": "window.reject", "foreground": false }, // // ], // 'data': { // 'type': 'TEST' // } // } // } // //for android payload = { "data": { 'priority': 1, "content-available": "1", "notId": Math.random() * 100, "data": "{\n \"timestamp\" : \"2017-04-14T23:37:12Z\",\n \"content\" : \"{\\n \\\"id\\\" : 8\\n}\",\n \"type\" : \"update_goal\"\n}", "title": "Update goal", "message": "Goal was updated" } } var message = new gcm.Message(payload); //console.log(message, message.toJson(), message_Android.toJson()); //Here get the devices from your database into an array var deviceID_Android = "es9CSkHH6GM:APA91bH2o9_kSiV0Lv4cu5lTS30nYlHc6XzwiFqm8uFr8U8OVT7jn1Y2nGbDODDUE9P4LPwlVZxUuUhAYlRC5sUQDy2A6GJQz7emiF_1NY82QTiDczWzqJ2VaKhfiqZf8ha6M7BcCik0"; //var deviceID_Android = "m3kHS4BnrF0:APA91bGDRjNibKqDkMooSmaQlO2xVTE3D1FvmNzqttO6l_yeLCQwztRv3FY-R92T3En-3TdwH403c_4Dr7qMPL-l6PAG10-_E7pOkUhGgZXOImuYbvl29mDcwZI-WIwzUGpQUUTIzaf3"; // var deviceID_IOS = "nO19ipNbiYU:APA91bGkIiKA57BXw_IpI2rT9_gnFag3-1cbiNHDavS9N1MKqo4rk7E-oKhkp5ej--9WVtqugVolC4C6YrCOC1-3y99Q6LbbBTlrQMv36vnNKR1yUiLXi_7zvJPrhGILxbS-4DF831gN"; var deviceID_IOS = "mFtMmQH2nJs:APA91bEL6oNDbMYtJZfGInMBnBLzZ_rACEb_07BAugaDx8t68Hl8AnKIYsHw_mC23gxtcStHIvavlEEXz-HqcgGwJ_NIrMLY7HdtY6Fs0SZaw8ThWHO_n9i_UGnSo4BnrdN98BX4sVor"; /**** Send Notifications to Android devices *****/ console.log(message.toJson()); service.send(message, { registrationTokens: [deviceID_Android] }, retry_times, function(err, response) { if (err) console.error(err); else console.log(response); }); /**** Send Notifications to IOS devices *****/ // // for ios payload = { "notification": { "sound": "default", "icon": "default", "body": "Notify in Body", "title": "Title Notification" }, "contentAvailable": true, "priority": "high", "data": { // "content-available": '1', // "priority": 1, "notId": Math.random() * 100, "data": "{\"type\" : \"update_goal\"\n}", "title": "Title Data", "message": "Message in Data" } } message = new gcm.Message(payload); console.log(message.toJson()); service.send(message, { registrationTokens: [deviceID_IOS] }, retry_times, function(err, response) { if (err) console.error(err); else console.log(response); }); });
parmantolab/ionic-push-notification-wrapper
server/gcmservice.js
JavaScript
apache-2.0
7,393
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Drnek piana - CRM</title> <!-- Bootstrap Core CSS --> <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- MetisMenu CSS --> <link href="../bower_components/metisMenu/dist/metisMenu.min.css" rel="stylesheet"> <!-- DataTables CSS --> <link href="../bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet"> <!-- DataTables Responsive CSS --> <link href="../bower_components/datatables-responsive/css/dataTables.responsive.css" rel="stylesheet"> <!-- Custom CSS --> <link href="../dist/css/sb-admin-2.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div id="wrapper"> <!-- Navigation --> <nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.html">Drnek piana - CRM</a> </div> <!-- /.navbar-header --> <ul class="nav navbar-top-links navbar-right"> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <i class="fa fa-envelope fa-fw"></i> <i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu dropdown-messages"> <li> <a href="#"> <div> <strong>John Smith</strong> <span class="pull-right text-muted"> <em>Yesterday</em> </span> </div> <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <strong>John Smith</strong> <span class="pull-right text-muted"> <em>Yesterday</em> </span> </div> <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <strong>John Smith</strong> <span class="pull-right text-muted"> <em>Yesterday</em> </span> </div> <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div> </a> </li> <li class="divider"></li> <li> <a class="text-center" href="#"> <strong>Read All Messages</strong> <i class="fa fa-angle-right"></i> </a> </li> </ul> <!-- /.dropdown-messages --> </li> <!-- /.dropdown --> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <i class="fa fa-tasks fa-fw"></i> <i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu dropdown-tasks"> <li> <a href="#"> <div> <p> <strong>Task 1</strong> <span class="pull-right text-muted">40% Complete</span> </p> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%"> <span class="sr-only">40% Complete (success)</span> </div> </div> </div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <p> <strong>Task 2</strong> <span class="pull-right text-muted">20% Complete</span> </p> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"> <span class="sr-only">20% Complete</span> </div> </div> </div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <p> <strong>Task 3</strong> <span class="pull-right text-muted">60% Complete</span> </p> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"> <span class="sr-only">60% Complete (warning)</span> </div> </div> </div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <p> <strong>Task 4</strong> <span class="pull-right text-muted">80% Complete</span> </p> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"> <span class="sr-only">80% Complete (danger)</span> </div> </div> </div> </a> </li> <li class="divider"></li> <li> <a class="text-center" href="#"> <strong>See All Tasks</strong> <i class="fa fa-angle-right"></i> </a> </li> </ul> <!-- /.dropdown-tasks --> </li> <!-- /.dropdown --> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <i class="fa fa-bell fa-fw"></i> <i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu dropdown-alerts"> <li> <a href="#"> <div> <i class="fa fa-comment fa-fw"></i> New Comment <span class="pull-right text-muted small">4 minutes ago</span> </div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <i class="fa fa-twitter fa-fw"></i> 3 New Followers <span class="pull-right text-muted small">12 minutes ago</span> </div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <i class="fa fa-envelope fa-fw"></i> Message Sent <span class="pull-right text-muted small">4 minutes ago</span> </div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <i class="fa fa-tasks fa-fw"></i> New Task <span class="pull-right text-muted small">4 minutes ago</span> </div> </a> </li> <li class="divider"></li> <li> <a href="#"> <div> <i class="fa fa-upload fa-fw"></i> Server Rebooted <span class="pull-right text-muted small">4 minutes ago</span> </div> </a> </li> <li class="divider"></li> <li> <a class="text-center" href="#"> <strong>See All Alerts</strong> <i class="fa fa-angle-right"></i> </a> </li> </ul> <!-- /.dropdown-alerts --> </li> <!-- /.dropdown --> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <i class="fa fa-user fa-fw"></i> <i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu dropdown-user"> <li><a href="#"><i class="fa fa-user fa-fw"></i> User Profile</a> </li> <li><a href="#"><i class="fa fa-gear fa-fw"></i> Settings</a> </li> <li class="divider"></li> <li><a href="login.html"><i class="fa fa-sign-out fa-fw"></i> Logout</a> </li> </ul> <!-- /.dropdown-user --> </li> <!-- /.dropdown --> </ul> <!-- /.navbar-top-links --> <div class="navbar-default sidebar" role="navigation"> <div class="sidebar-nav navbar-collapse"> <ul class="nav" id="side-menu"> <li class="sidebar-search"> <div class="input-group custom-search-form"> <input type="text" class="form-control" placeholder="Search..."> <span class="input-group-btn"> <button class="btn btn-default" type="button"> <i class="fa fa-search"></i> </button> </span> </div> <!-- /input-group --> </li> <li> <a href="index.html"><i class="fa fa-dashboard fa-fw"></i> Dashboard</a> </li> <li> <a href="#"><i class="fa fa-bar-chart-o fa-fw"></i> Charts<span class="fa arrow"></span></a> <ul class="nav nav-second-level"> <li> <a href="flot.html">Flot Charts</a> </li> <li> <a href="morris.html">Morris.js Charts</a> </li> </ul> <!-- /.nav-second-level --> </li> <li> <a href="tables.html"><i class="fa fa-table fa-fw"></i> Tables</a> </li> <li> <a href="forms.html"><i class="fa fa-edit fa-fw"></i> Forms</a> </li> <li> <a href="#"><i class="fa fa-wrench fa-fw"></i> UI Elements<span class="fa arrow"></span></a> <ul class="nav nav-second-level"> <li> <a href="panels-wells.html">Panels and Wells</a> </li> <li> <a href="buttons.html">Buttons</a> </li> <li> <a href="notifications.html">Notifications</a> </li> <li> <a href="typography.html">Typography</a> </li> <li> <a href="icons.html"> Icons</a> </li> <li> <a href="grid.html">Grid</a> </li> </ul> <!-- /.nav-second-level --> </li> <li> <a href="#"><i class="fa fa-sitemap fa-fw"></i> Multi-Level Dropdown<span class="fa arrow"></span></a> <ul class="nav nav-second-level"> <li> <a href="#">Second Level Item</a> </li> <li> <a href="#">Second Level Item</a> </li> <li> <a href="#">Third Level <span class="fa arrow"></span></a> <ul class="nav nav-third-level"> <li> <a href="#">Third Level Item</a> </li> <li> <a href="#">Third Level Item</a> </li> <li> <a href="#">Third Level Item</a> </li> <li> <a href="#">Third Level Item</a> </li> </ul> <!-- /.nav-third-level --> </li> </ul> <!-- /.nav-second-level --> </li> <li> <a href="#"><i class="fa fa-files-o fa-fw"></i> Sample Pages<span class="fa arrow"></span></a> <ul class="nav nav-second-level"> <li> <a href="blank.html">Blank Page</a> </li> <li> <a href="login.html">Login Page</a> </li> </ul> <!-- /.nav-second-level --> </li> </ul> </div> <!-- /.sidebar-collapse --> </div> <!-- /.navbar-static-side --> </nav> <div id="page-wrapper"> <div class="row"> <div class="col-lg-12"> <h1 class="page-header">Tables</h1> </div> <!-- /.col-lg-12 --> </div> <!-- /.row --> <div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading"> DataTables Advanced Tables </div> <!-- /.panel-heading --> <div class="panel-body"> <div class="dataTable_wrapper"> <table class="table table-striped table-bordered table-hover" id="dataTables-example"> <thead> <tr> <th>Rendering engine</th> <th>Browser</th> <th>Platform(s)</th> <th>Engine version</th> <th>CSS grade</th> </tr> </thead> <tbody> <tr class="odd gradeX"> <td>Trident</td> <td>Internet Explorer 4.0</td> <td>Win 95+</td> <td class="center">4</td> <td class="center">X</td> </tr> <tr class="even gradeC"> <td>Trident</td> <td>Internet Explorer 5.0</td> <td>Win 95+</td> <td class="center">5</td> <td class="center">C</td> </tr> <tr class="odd gradeA"> <td>Trident</td> <td>Internet Explorer 5.5</td> <td>Win 95+</td> <td class="center">5.5</td> <td class="center">A</td> </tr> <tr class="even gradeA"> <td>Trident</td> <td>Internet Explorer 6</td> <td>Win 98+</td> <td class="center">6</td> <td class="center">A</td> </tr> <tr class="odd gradeA"> <td>Trident</td> <td>Internet Explorer 7</td> <td>Win XP SP2+</td> <td class="center">7</td> <td class="center">A</td> </tr> <tr class="even gradeA"> <td>Trident</td> <td>AOL browser (AOL desktop)</td> <td>Win XP</td> <td class="center">6</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Firefox 1.0</td> <td>Win 98+ / OSX.2+</td> <td class="center">1.7</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Firefox 1.5</td> <td>Win 98+ / OSX.2+</td> <td class="center">1.8</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Firefox 2.0</td> <td>Win 98+ / OSX.2+</td> <td class="center">1.8</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Firefox 3.0</td> <td>Win 2k+ / OSX.3+</td> <td class="center">1.9</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Camino 1.0</td> <td>OSX.2+</td> <td class="center">1.8</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Camino 1.5</td> <td>OSX.3+</td> <td class="center">1.8</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Netscape 7.2</td> <td>Win 95+ / Mac OS 8.6-9.2</td> <td class="center">1.7</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Netscape Browser 8</td> <td>Win 98SE+</td> <td class="center">1.7</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Netscape Navigator 9</td> <td>Win 98+ / OSX.2+</td> <td class="center">1.8</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Mozilla 1.0</td> <td>Win 95+ / OSX.1+</td> <td class="center">1</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Mozilla 1.1</td> <td>Win 95+ / OSX.1+</td> <td class="center">1.1</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Mozilla 1.2</td> <td>Win 95+ / OSX.1+</td> <td class="center">1.2</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Mozilla 1.3</td> <td>Win 95+ / OSX.1+</td> <td class="center">1.3</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Mozilla 1.4</td> <td>Win 95+ / OSX.1+</td> <td class="center">1.4</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Mozilla 1.5</td> <td>Win 95+ / OSX.1+</td> <td class="center">1.5</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Mozilla 1.6</td> <td>Win 95+ / OSX.1+</td> <td class="center">1.6</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Mozilla 1.7</td> <td>Win 98+ / OSX.1+</td> <td class="center">1.7</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Mozilla 1.8</td> <td>Win 98+ / OSX.1+</td> <td class="center">1.8</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Seamonkey 1.1</td> <td>Win 98+ / OSX.2+</td> <td class="center">1.8</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Gecko</td> <td>Epiphany 2.20</td> <td>Gnome</td> <td class="center">1.8</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Webkit</td> <td>Safari 1.2</td> <td>OSX.3</td> <td class="center">125.5</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Webkit</td> <td>Safari 1.3</td> <td>OSX.3</td> <td class="center">312.8</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Webkit</td> <td>Safari 2.0</td> <td>OSX.4+</td> <td class="center">419.3</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Webkit</td> <td>Safari 3.0</td> <td>OSX.4+</td> <td class="center">522.1</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Webkit</td> <td>OmniWeb 5.5</td> <td>OSX.4+</td> <td class="center">420</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Webkit</td> <td>iPod Touch / iPhone</td> <td>iPod</td> <td class="center">420.1</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Webkit</td> <td>S60</td> <td>S60</td> <td class="center">413</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Presto</td> <td>Opera 7.0</td> <td>Win 95+ / OSX.1+</td> <td class="center">-</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Presto</td> <td>Opera 7.5</td> <td>Win 95+ / OSX.2+</td> <td class="center">-</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Presto</td> <td>Opera 8.0</td> <td>Win 95+ / OSX.2+</td> <td class="center">-</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Presto</td> <td>Opera 8.5</td> <td>Win 95+ / OSX.2+</td> <td class="center">-</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Presto</td> <td>Opera 9.0</td> <td>Win 95+ / OSX.3+</td> <td class="center">-</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Presto</td> <td>Opera 9.2</td> <td>Win 88+ / OSX.3+</td> <td class="center">-</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Presto</td> <td>Opera 9.5</td> <td>Win 88+ / OSX.3+</td> <td class="center">-</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Presto</td> <td>Opera for Wii</td> <td>Wii</td> <td class="center">-</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Presto</td> <td>Nokia N800</td> <td>N800</td> <td class="center">-</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>Presto</td> <td>Nintendo DS browser</td> <td>Nintendo DS</td> <td class="center">8.5</td> <td class="center">C/A<sup>1</sup> </td> </tr> <tr class="gradeC"> <td>KHTML</td> <td>Konqureror 3.1</td> <td>KDE 3.1</td> <td class="center">3.1</td> <td class="center">C</td> </tr> <tr class="gradeA"> <td>KHTML</td> <td>Konqureror 3.3</td> <td>KDE 3.3</td> <td class="center">3.3</td> <td class="center">A</td> </tr> <tr class="gradeA"> <td>KHTML</td> <td>Konqureror 3.5</td> <td>KDE 3.5</td> <td class="center">3.5</td> <td class="center">A</td> </tr> <tr class="gradeX"> <td>Tasman</td> <td>Internet Explorer 4.5</td> <td>Mac OS 8-9</td> <td class="center">-</td> <td class="center">X</td> </tr> <tr class="gradeC"> <td>Tasman</td> <td>Internet Explorer 5.1</td> <td>Mac OS 7.6-9</td> <td class="center">1</td> <td class="center">C</td> </tr> <tr class="gradeC"> <td>Tasman</td> <td>Internet Explorer 5.2</td> <td>Mac OS 8-X</td> <td class="center">1</td> <td class="center">C</td> </tr> <tr class="gradeA"> <td>Misc</td> <td>NetFront 3.1</td> <td>Embedded devices</td> <td class="center">-</td> <td class="center">C</td> </tr> <tr class="gradeA"> <td>Misc</td> <td>NetFront 3.4</td> <td>Embedded devices</td> <td class="center">-</td> <td class="center">A</td> </tr> <tr class="gradeX"> <td>Misc</td> <td>Dillo 0.8</td> <td>Embedded devices</td> <td class="center">-</td> <td class="center">X</td> </tr> <tr class="gradeX"> <td>Misc</td> <td>Links</td> <td>Text only</td> <td class="center">-</td> <td class="center">X</td> </tr> <tr class="gradeX"> <td>Misc</td> <td>Lynx</td> <td>Text only</td> <td class="center">-</td> <td class="center">X</td> </tr> <tr class="gradeC"> <td>Misc</td> <td>IE Mobile</td> <td>Windows Mobile 6</td> <td class="center">-</td> <td class="center">C</td> </tr> <tr class="gradeC"> <td>Misc</td> <td>PSP browser</td> <td>PSP</td> <td class="center">-</td> <td class="center">C</td> </tr> <tr class="gradeU"> <td>Other browsers</td> <td>All others</td> <td>-</td> <td class="center">-</td> <td class="center">U</td> </tr> </tbody> </table> </div> <!-- /.table-responsive --> <div class="well"> <h4>DataTables Usage Information</h4> <p>DataTables is a very flexible, advanced tables plugin for jQuery. In SB Admin, we are using a specialized version of DataTables built for Bootstrap 3. We have also customized the table headings to use Font Awesome icons in place of images. For complete documentation on DataTables, visit their website at <a target="_blank" href="https://datatables.net/">https://datatables.net/</a>.</p> <a class="btn btn-default btn-lg btn-block" target="_blank" href="https://datatables.net/">View DataTables Documentation</a> </div> </div> <!-- /.panel-body --> </div> <!-- /.panel --> </div> <!-- /.col-lg-12 --> </div> <!-- /.row --> <div class="row"> <div class="col-lg-6"> <div class="panel panel-default"> <div class="panel-heading"> Kitchen Sink </div> <!-- /.panel-heading --> <div class="panel-body"> <div class="table-responsive"> <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <td>2</td> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <td>3</td> <td>Larry</td> <td>the Bird</td> <td>@twitter</td> </tr> </tbody> </table> </div> <!-- /.table-responsive --> </div> <!-- /.panel-body --> </div> <!-- /.panel --> </div> <!-- /.col-lg-6 --> <div class="col-lg-6"> <div class="panel panel-default"> <div class="panel-heading"> Basic Table </div> <!-- /.panel-heading --> <div class="panel-body"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <td>2</td> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <td>3</td> <td>Larry</td> <td>the Bird</td> <td>@twitter</td> </tr> </tbody> </table> </div> <!-- /.table-responsive --> </div> <!-- /.panel-body --> </div> <!-- /.panel --> </div> <!-- /.col-lg-6 --> </div> <!-- /.row --> <div class="row"> <div class="col-lg-6"> <div class="panel panel-default"> <div class="panel-heading"> Striped Rows </div> <!-- /.panel-heading --> <div class="panel-body"> <div class="table-responsive"> <table class="table table-striped"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <td>2</td> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <td>3</td> <td>Larry</td> <td>the Bird</td> <td>@twitter</td> </tr> </tbody> </table> </div> <!-- /.table-responsive --> </div> <!-- /.panel-body --> </div> <!-- /.panel --> </div> <!-- /.col-lg-6 --> <div class="col-lg-6"> <div class="panel panel-default"> <div class="panel-heading"> Bordered Table </div> <!-- /.panel-heading --> <div class="panel-body"> <div class="table-responsive table-bordered"> <table class="table"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <td>2</td> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <td>3</td> <td>Larry</td> <td>the Bird</td> <td>@twitter</td> </tr> </tbody> </table> </div> <!-- /.table-responsive --> </div> <!-- /.panel-body --> </div> <!-- /.panel --> </div> <!-- /.col-lg-6 --> </div> <!-- /.row --> <div class="row"> <div class="col-lg-6"> <div class="panel panel-default"> <div class="panel-heading"> Hover Rows </div> <!-- /.panel-heading --> <div class="panel-body"> <div class="table-responsive"> <table class="table table-hover"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <td>2</td> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <td>3</td> <td>Larry</td> <td>the Bird</td> <td>@twitter</td> </tr> </tbody> </table> </div> <!-- /.table-responsive --> </div> <!-- /.panel-body --> </div> <!-- /.panel --> </div> <!-- /.col-lg-6 --> <div class="col-lg-6"> <div class="panel panel-default"> <div class="panel-heading"> Context Classes </div> <!-- /.panel-heading --> <div class="panel-body"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> </tr> </thead> <tbody> <tr class="success"> <td>1</td> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr class="info"> <td>2</td> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr class="warning"> <td>3</td> <td>Larry</td> <td>the Bird</td> <td>@twitter</td> </tr> <tr class="danger"> <td>4</td> <td>John</td> <td>Smith</td> <td>@jsmith</td> </tr> </tbody> </table> </div> <!-- /.table-responsive --> </div> <!-- /.panel-body --> </div> <!-- /.panel --> </div> <!-- /.col-lg-6 --> </div> <!-- /.row --> </div> <!-- /#page-wrapper --> </div> <!-- /#wrapper --> <!-- jQuery --> <script src="../bower_components/jquery/dist/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script> <!-- Metis Menu Plugin JavaScript --> <script src="../bower_components/metisMenu/dist/metisMenu.min.js"></script> <!-- DataTables JavaScript --> <script src="../bower_components/datatables/media/js/jquery.dataTables.min.js"></script> <script src="../bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js"></script> <!-- Custom Theme JavaScript --> <script src="../dist/js/sb-admin-2.js"></script> <!-- Page-Level Demo Scripts - Tables - Use for reference --> <script> $(document).ready(function() { $('#dataTables-example').DataTable({ responsive: true }); }); </script> </body> </html>
hlavi01/pianos
pages/tables.html
HTML
apache-2.0
61,528
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // 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: 2016.04.17 at 06:03:51 PM CEST // package org.jboss.bus.config.model; import javax.xml.bind.annotation.XmlRegistry; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the org.jboss.bus.config.model package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.jboss.bus.config.model * */ public ObjectFactory() { } /** * Create an instance of {@link Federated } * */ public Federated createFederated() { return new Federated(); } /** * Create an instance of {@link Federated.Bus } * */ public Federated.Bus createFederatedBus() { return new Federated.Bus(); } /** * Create an instance of {@link Federated.Bus.Translators } * */ public Federated.Bus.Translators createFederatedBusTranslators() { return new Federated.Bus.Translators(); } /** * Create an instance of {@link PropertyType } * */ public PropertyType createPropertyType() { return new PropertyType(); } /** * Create an instance of {@link PropertiesType } * */ public PropertiesType createPropertiesType() { return new PropertiesType(); } /** * Create an instance of {@link Federated.Bus.Translators.Translator } * */ public Federated.Bus.Translators.Translator createFederatedBusTranslatorsTranslator() { return new Federated.Bus.Translators.Translator(); } }
lvecera/FederatedBus
src/main/java/org/jboss/bus/config/model/ObjectFactory.java
Java
apache-2.0
2,376
const { dest, series, src, symlink } = require('gulp'); const del = require('del'); const inject = require('gulp-inject'); const map = require('map-stream') const path = require('path'); const rename = require('gulp-rename'); const sort = require('gulp-sort'); function deleteSymlinks() { return del(['components/modules/ROOT/pages/*', '!components/modules/ROOT/pages/index.adoc']); } function createSymlinks() { return src('../components/*/src/main/docs/*.adoc') .pipe(map((file, done) => { // this flattens the output to just .../pages/....adoc // instead of .../pages/camel-.../src/main/docs/....adoc file.base = path.dirname(file.path); done(null, file); })) // Antora disabled symlinks, there is an issue open // https://gitlab.com/antora/antora/issues/188 // to reinstate symlink support, until that's resolved // we'll simply copy over instead of creating symlinks // .pipe(symlink('components/modules/ROOT/pages/', { // relativeSymlinks: true // })); // uncomment above .pipe() and remove the .pipe() below // when antora#188 is resolved .pipe(dest('components/modules/ROOT/pages/')); } function nav() { return src('nav.adoc.template') .pipe(inject(src('../components/*/src/main/docs/*.adoc').pipe(sort()), { removeTags: true, transform: (filename, file) => { const filepath = path.basename(filename); const maybeName = /(?:==|##) (.*)/.exec(file.contents.toString()) if (maybeName == null) { throw new Error(`${file.path} doesn't contain Asciidoc heading ('== <Title>') or ('## <Title')`); } return `* xref:${filepath}[${maybeName[1]}]`; } })) .pipe(rename('nav.adoc')) .pipe(dest('components/modules/ROOT/')) } const symlinks = series(deleteSymlinks, createSymlinks); exports.symlinks = symlinks; exports.nav = nav; exports.default = series(symlinks, nav);
kevinearls/camel
docs/gulpfile.js
JavaScript
apache-2.0
2,100
<!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_65) on Mon Apr 04 02:08:28 MDT 2016 --> <title>ActivityControllerFactory.FactoryCatalog</title> <meta name="date" content="2016-04-04"> <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="ActivityControllerFactory.FactoryCatalog"; } } catch(err) { } //--> var methods = {"i0":9,"i1":9}; var tabs = {65535:["t0","All Methods"],1:["t1","Static 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="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="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.html" title="class in cmput301.textbookhub.Controllers"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../cmput301/textbookhub/Controllers/AppUserController.html" title="class in cmput301.textbookhub.Controllers"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" target="_top">Frames</a></li> <li><a href="ActivityControllerFactory.FactoryCatalog.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;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:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#enum.constant.summary">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#enum.constant.detail">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</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">cmput301.textbookhub.Controllers</div> <h2 title="Enum ActivityControllerFactory.FactoryCatalog" class="title">Enum ActivityControllerFactory.FactoryCatalog</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>java.lang.Enum&lt;<a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" title="enum in cmput301.textbookhub.Controllers">ActivityControllerFactory.FactoryCatalog</a>&gt;</li> <li> <ul class="inheritance"> <li>cmput301.textbookhub.Controllers.ActivityControllerFactory.FactoryCatalog</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Serializable, java.lang.Comparable&lt;<a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" title="enum in cmput301.textbookhub.Controllers">ActivityControllerFactory.FactoryCatalog</a>&gt;</dd> </dl> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.html" title="class in cmput301.textbookhub.Controllers">ActivityControllerFactory</a></dd> </dl> <hr> <br> <pre>public static enum <span class="typeNameLabel">ActivityControllerFactory.FactoryCatalog</span> extends java.lang.Enum&lt;<a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" title="enum in cmput301.textbookhub.Controllers">ActivityControllerFactory.FactoryCatalog</a>&gt;</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== ENUM CONSTANT SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="enum.constant.summary"> <!-- --> </a> <h3>Enum Constant Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Constant Summary table, listing enum constants, and an explanation"> <caption><span>Enum Constants</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Enum Constant and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html#ACTIVITY_EDIT_BOOK">ACTIVITY_EDIT_BOOK</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html#ACTIVITY_LOGIN">ACTIVITY_LOGIN</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html#ACTIVITY_MAIN">ACTIVITY_MAIN</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html#ACTIVITY_MY_BIDS">ACTIVITY_MY_BIDS</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html#ACTIVITY_MY_BORROWS">ACTIVITY_MY_BORROWS</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html#ACTIVITY_MY_INVENTORY">ACTIVITY_MY_INVENTORY</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html#ACTIVITY_USER_PROFILE">ACTIVITY_USER_PROFILE</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html#ACTIVITY_VIEW_BOOK">ACTIVITY_VIEW_BOOK</a></span></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== 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">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</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>static <a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" title="enum in cmput301.textbookhub.Controllers">ActivityControllerFactory.FactoryCatalog</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html#valueOf-java.lang.String-">valueOf</a></span>(java.lang.String&nbsp;name)</code> <div class="block">Returns the enum constant of this type with the specified name.</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>static <a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" title="enum in cmput301.textbookhub.Controllers">ActivityControllerFactory.FactoryCatalog</a>[]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html#values--">values</a></span>()</code> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Enum"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Enum</h3> <code>clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>getClass, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ ENUM CONSTANT DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="enum.constant.detail"> <!-- --> </a> <h3>Enum Constant Detail</h3> <a name="ACTIVITY_EDIT_BOOK"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ACTIVITY_EDIT_BOOK</h4> <pre>public static final&nbsp;<a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" title="enum in cmput301.textbookhub.Controllers">ActivityControllerFactory.FactoryCatalog</a> ACTIVITY_EDIT_BOOK</pre> </li> </ul> <a name="ACTIVITY_LOGIN"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ACTIVITY_LOGIN</h4> <pre>public static final&nbsp;<a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" title="enum in cmput301.textbookhub.Controllers">ActivityControllerFactory.FactoryCatalog</a> ACTIVITY_LOGIN</pre> </li> </ul> <a name="ACTIVITY_MAIN"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ACTIVITY_MAIN</h4> <pre>public static final&nbsp;<a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" title="enum in cmput301.textbookhub.Controllers">ActivityControllerFactory.FactoryCatalog</a> ACTIVITY_MAIN</pre> </li> </ul> <a name="ACTIVITY_MY_BIDS"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ACTIVITY_MY_BIDS</h4> <pre>public static final&nbsp;<a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" title="enum in cmput301.textbookhub.Controllers">ActivityControllerFactory.FactoryCatalog</a> ACTIVITY_MY_BIDS</pre> </li> </ul> <a name="ACTIVITY_MY_BORROWS"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ACTIVITY_MY_BORROWS</h4> <pre>public static final&nbsp;<a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" title="enum in cmput301.textbookhub.Controllers">ActivityControllerFactory.FactoryCatalog</a> ACTIVITY_MY_BORROWS</pre> </li> </ul> <a name="ACTIVITY_MY_INVENTORY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ACTIVITY_MY_INVENTORY</h4> <pre>public static final&nbsp;<a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" title="enum in cmput301.textbookhub.Controllers">ActivityControllerFactory.FactoryCatalog</a> ACTIVITY_MY_INVENTORY</pre> </li> </ul> <a name="ACTIVITY_USER_PROFILE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ACTIVITY_USER_PROFILE</h4> <pre>public static final&nbsp;<a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" title="enum in cmput301.textbookhub.Controllers">ActivityControllerFactory.FactoryCatalog</a> ACTIVITY_USER_PROFILE</pre> </li> </ul> <a name="ACTIVITY_VIEW_BOOK"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>ACTIVITY_VIEW_BOOK</h4> <pre>public static final&nbsp;<a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" title="enum in cmput301.textbookhub.Controllers">ActivityControllerFactory.FactoryCatalog</a> ACTIVITY_VIEW_BOOK</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="values--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>values</h4> <pre>public static&nbsp;<a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" title="enum in cmput301.textbookhub.Controllers">ActivityControllerFactory.FactoryCatalog</a>[]&nbsp;values()</pre> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows: <pre> for (ActivityControllerFactory.FactoryCatalog c : ActivityControllerFactory.FactoryCatalog.values()) &nbsp; System.out.println(c); </pre></div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>an array containing the constants of this enum type, in the order they are declared</dd> </dl> </li> </ul> <a name="valueOf-java.lang.String-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>valueOf</h4> <pre>public static&nbsp;<a href="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" title="enum in cmput301.textbookhub.Controllers">ActivityControllerFactory.FactoryCatalog</a>&nbsp;valueOf(java.lang.String&nbsp;name)</pre> <div class="block">Returns the enum constant of this type with the specified name. The string must match <i>exactly</i> an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>name</code> - the name of the enum constant to be returned.</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the enum constant with the specified name</dd> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code>java.lang.IllegalArgumentException</code> - if this enum type has no constant with the specified name</dd> <dd><code>java.lang.NullPointerException</code> - if the argument is null</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="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="../../../cmput301/textbookhub/Controllers/ActivityControllerFactory.html" title="class in cmput301.textbookhub.Controllers"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../cmput301/textbookhub/Controllers/AppUserController.html" title="class in cmput301.textbookhub.Controllers"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html" target="_top">Frames</a></li> <li><a href="ActivityControllerFactory.FactoryCatalog.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;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:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#enum.constant.summary">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#enum.constant.detail">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Thirteam/CMPUT301W16T13
Javadocs/cmput301/textbookhub/Controllers/ActivityControllerFactory.FactoryCatalog.html
HTML
apache-2.0
18,011
// // HomeSearchDetialViewController.h // ChangChunTax // // Created by XIU-Developer on 16/5/5. // Copyright © 2016年 XIU. All rights reserved. // #import <UIKit/UIKit.h> @interface HomeSearchListDetialNewsVC : UIViewController @property (nonatomic, strong) NSString *ids; @end
axiubest/ChangChunTax
ChangChunTax/ChangChunTax/Class/Home/Home/View/HomeSearchListDetialNewsVC.h
C
apache-2.0
288
<?php namespace Google\AdsApi\AdManager\v202108; /** * This file was generated from WSDL. DO NOT EDIT. */ class ImageRedirectOverlayCreative extends \Google\AdsApi\AdManager\v202108\BaseImageRedirectCreative { /** * @var \Google\AdsApi\AdManager\v202108\Size $assetSize */ protected $assetSize = null; /** * @var int $duration */ protected $duration = null; /** * @var int[] $companionCreativeIds */ protected $companionCreativeIds = null; /** * @var \Google\AdsApi\AdManager\v202108\ConversionEvent_TrackingUrlsMapEntry[] $trackingUrls */ protected $trackingUrls = null; /** * @var string $customParameters */ protected $customParameters = null; /** * @var string $vastPreviewUrl */ protected $vastPreviewUrl = null; /** * @param int $advertiserId * @param int $id * @param string $name * @param \Google\AdsApi\AdManager\v202108\Size $size * @param string $previewUrl * @param string[] $policyLabels * @param \Google\AdsApi\AdManager\v202108\AppliedLabel[] $appliedLabels * @param \Google\AdsApi\AdManager\v202108\DateTime $lastModifiedDateTime * @param \Google\AdsApi\AdManager\v202108\BaseCustomFieldValue[] $customFieldValues * @param \Google\AdsApi\AdManager\v202108\ThirdPartyDataDeclaration $thirdPartyDataDeclaration * @param string $destinationUrl * @param string $destinationUrlType * @param string $imageUrl * @param \Google\AdsApi\AdManager\v202108\Size $assetSize * @param int $duration * @param int[] $companionCreativeIds * @param \Google\AdsApi\AdManager\v202108\ConversionEvent_TrackingUrlsMapEntry[] $trackingUrls * @param string $customParameters * @param string $vastPreviewUrl */ public function __construct($advertiserId = null, $id = null, $name = null, $size = null, $previewUrl = null, array $policyLabels = null, array $appliedLabels = null, $lastModifiedDateTime = null, array $customFieldValues = null, $thirdPartyDataDeclaration = null, $destinationUrl = null, $destinationUrlType = null, $imageUrl = null, $assetSize = null, $duration = null, array $companionCreativeIds = null, array $trackingUrls = null, $customParameters = null, $vastPreviewUrl = null) { parent::__construct($advertiserId, $id, $name, $size, $previewUrl, $policyLabels, $appliedLabels, $lastModifiedDateTime, $customFieldValues, $thirdPartyDataDeclaration, $destinationUrl, $destinationUrlType, $imageUrl); $this->assetSize = $assetSize; $this->duration = $duration; $this->companionCreativeIds = $companionCreativeIds; $this->trackingUrls = $trackingUrls; $this->customParameters = $customParameters; $this->vastPreviewUrl = $vastPreviewUrl; } /** * @return \Google\AdsApi\AdManager\v202108\Size */ public function getAssetSize() { return $this->assetSize; } /** * @param \Google\AdsApi\AdManager\v202108\Size $assetSize * @return \Google\AdsApi\AdManager\v202108\ImageRedirectOverlayCreative */ public function setAssetSize($assetSize) { $this->assetSize = $assetSize; return $this; } /** * @return int */ public function getDuration() { return $this->duration; } /** * @param int $duration * @return \Google\AdsApi\AdManager\v202108\ImageRedirectOverlayCreative */ public function setDuration($duration) { $this->duration = $duration; return $this; } /** * @return int[] */ public function getCompanionCreativeIds() { return $this->companionCreativeIds; } /** * @param int[]|null $companionCreativeIds * @return \Google\AdsApi\AdManager\v202108\ImageRedirectOverlayCreative */ public function setCompanionCreativeIds(array $companionCreativeIds = null) { $this->companionCreativeIds = $companionCreativeIds; return $this; } /** * @return \Google\AdsApi\AdManager\v202108\ConversionEvent_TrackingUrlsMapEntry[] */ public function getTrackingUrls() { return $this->trackingUrls; } /** * @param \Google\AdsApi\AdManager\v202108\ConversionEvent_TrackingUrlsMapEntry[]|null $trackingUrls * @return \Google\AdsApi\AdManager\v202108\ImageRedirectOverlayCreative */ public function setTrackingUrls(array $trackingUrls = null) { $this->trackingUrls = $trackingUrls; return $this; } /** * @return string */ public function getCustomParameters() { return $this->customParameters; } /** * @param string $customParameters * @return \Google\AdsApi\AdManager\v202108\ImageRedirectOverlayCreative */ public function setCustomParameters($customParameters) { $this->customParameters = $customParameters; return $this; } /** * @return string */ public function getVastPreviewUrl() { return $this->vastPreviewUrl; } /** * @param string $vastPreviewUrl * @return \Google\AdsApi\AdManager\v202108\ImageRedirectOverlayCreative */ public function setVastPreviewUrl($vastPreviewUrl) { $this->vastPreviewUrl = $vastPreviewUrl; return $this; } }
googleads/googleads-php-lib
src/Google/AdsApi/AdManager/v202108/ImageRedirectOverlayCreative.php
PHP
apache-2.0
5,364
//>>built define("dojox/drawing/util/typeset",["../library/greek"],function(c){return{convertHTML:function(b){return b?b.replace(/&([^;]+);/g,function(b,a){if("#"==a.charAt(0)){var d=+a.substr(1);if(!isNaN(d))return String.fromCharCode(d)}else if(c[a])return String.fromCharCode(c[a]);console.warn("no HTML conversion for ",b);return b}):b},convertLaTeX:function(b){return b?b.replace(/\\([a-zA-Z]+)/g,function(b,a){if(c[a])return String.fromCharCode(c[a]);if("mu"==a.substr(0,2))return String.fromCharCode(c.mu)+ a.substr(2);if("theta"==a.substr(0,5))return String.fromCharCode(c.theta)+a.substr(5);if("phi"==a.substr(0,3))return String.fromCharCode(c.phi)+a.substr(3)}).replace(/\\\\/g,"\\"):b}}}); //# sourceMappingURL=typeset.js.map
Caspar12/zh.sw
zh.web.site.admin/src/main/resources/static/js/dojo/dojox/drawing/util/typeset.js
JavaScript
apache-2.0
736
import * as ui from '../../ui'; import { WorkItemQuickPreview } from './workitem-quickpreview'; export class WorkItemDetailPage extends WorkItemQuickPreview { detailPageDiv = new ui.BaseElement(this.$('#wi-detail-form'), 'wi detail page'); }
pranavgore09/fabric8-planner
src/tests/ui/planner/workitem-detailpage.ts
TypeScript
apache-2.0
245
/* * Github Authorized Keys - Use GitHub teams to manage system user accounts and authorized_keys * * Copyright 2016 Cloud Posse, LLC <hello@cloudposse.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 api import ( "errors" "os/user" ) const ( // Group file contains one row per group // Format of the row consists at least of 3 columns // https://en.wikipedia.org/wiki/Group_identifier countOfColumnsInGroup = 3 // Group name stored in 0 column nameColumnNumberInGroup = 0 // Group password flag stored in 1 column passwordFlagColumnNumberInGroup = 1 // Group GID stored in 2 column gidColumnNumberInGroup = 2 // Group GID stored in 3 column usersColumnNumberInGroup = 3 ) func (linux *Linux) groupLookup(groupName string) (*user.Group, error) { groupInfo, err := linux.getEntity("group", groupName) if err != nil { return nil, user.UnknownGroupError(groupName) } if len(groupInfo) < countOfColumnsInGroup { return nil, errors.New("Wrong format of /etc/group") } group := user.Group{ Gid: groupInfo[gidColumnNumberInGroup], Name: groupInfo[nameColumnNumberInGroup], } return &group, err } func (linux *Linux) groupLookupByID(groupID string) (*user.Group, error) { groupInfo, err := linux.getEntity("group", groupID) if err != nil { return nil, user.UnknownGroupIdError(groupID) } if len(groupInfo) < countOfColumnsInGroup { return nil, errors.New("Wrong format of /etc/group") } group := user.Group{ Gid: groupInfo[gidColumnNumberInGroup], Name: groupInfo[nameColumnNumberInGroup], } return &group, err } // GroupExists - check if group {groupName} exists func (linux *Linux) GroupExists(groupName string) bool { group, _ := linux.groupLookup(groupName) return group != nil } func (linux *Linux) groupExistsByID(groupID string) bool { group, _ := linux.groupLookupByID(groupID) return group != nil }
cloudposse/github-authorized-keys
api/linux_groups.go
GO
apache-2.0
2,399
package io.quarkus.it.jpa.h2; import javax.persistence.Entity; @Entity public class IndividualCustomer extends Customer { String firstname; String surname; }
quarkusio/quarkus
integration-tests/jpa-h2/src/main/java/io/quarkus/it/jpa/h2/IndividualCustomer.java
Java
apache-2.0
168
package com.packtpub.storm.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Board implements Serializable { private static final long serialVersionUID = 1L; public static final String EMPTY = " "; public String[][] board = {{EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY}}; public Board() { } public Board(String key) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { this.board[i][j] = "" + key.charAt(i * 3 + j); } } } public List<Board> nextBoards(String player) { List<Board> boards = new ArrayList<Board>(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j].equals(EMPTY)) { Board newBoard = this.clone(); newBoard.board[i][j] = player; boards.add(newBoard); } } } return boards; } public boolean isEndState() { return (nextBoards("X").size() == 0 || Math.abs(score("X")) > 1000); } public int score(String player) { return scoreLines(player) - scoreLines(Player.next(player)); } public int scoreLines(String player) { int score = 0; // Columns score += scoreLine(board[0][0], board[1][0], board[2][0], player); score += scoreLine(board[0][1], board[1][1], board[2][1], player); score += scoreLine(board[0][2], board[1][2], board[2][2], player); // Rows score += scoreLine(board[0][0], board[0][1], board[0][2], player); score += scoreLine(board[1][0], board[1][1], board[1][2], player); score += scoreLine(board[2][0], board[2][1], board[2][2], player); // Diagonals score += scoreLine(board[0][0], board[1][1], board[2][2], player); score += scoreLine(board[2][0], board[1][1], board[0][2], player); return score; } public int scoreLine(String pos1, String pos2, String pos3, String player) { int score = 0; if (pos1.equals(player) && pos2.equals(player) && pos3.equals(player)) { score = 10000; } else if (pos1.equals(player) && pos2.equals(player) && pos3.equals(EMPTY) || pos1.equals(EMPTY) && pos2.equals(player) && pos3.equals(player)) { score = 100; } else { if (pos1.equals(player) && pos2.equals(EMPTY) && pos3.equals(EMPTY) || pos1.equals(EMPTY) && pos2.equals(player) && pos3.equals(EMPTY) || pos1.equals(EMPTY) && pos2.equals(EMPTY) && pos3.equals(player)) { score = 10; } } return score; } public Board clone() { Board clone = new Board(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { clone.board[i][j] = this.board[i][j]; } } return clone; } public String toString() { StringBuilder sb = new StringBuilder("\n---------\n"); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { sb.append("|").append(board[i][j]).append("|"); } sb.append("\n---------\n"); } return sb.toString(); } public String toKey() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { sb.append(board[i][j]); } } return sb.toString(); } }
jfmwz/storm-example
Chapter06/src/main/java/com/packtpub/storm/model/Board.java
Java
apache-2.0
3,636
package org.lightadmin.page.fieldDisplay.listView; import org.junit.Test; import org.lightadmin.SeleniumIntegrationTest; import org.lightadmin.config.ChildEntityConfiguration; import org.lightadmin.reporting.ConfigurationProblemException; public class ReferenceFieldTest extends SeleniumIntegrationTest { //Covers LA-5: https://github.com/max-dev/light-admin/issues/5#issuecomment-10261092 @Test(expected = ConfigurationProblemException.class) public void referenceFieldNotAddedToEntityIsNotDisplayed() { registerDomainTypeAdministrationConfiguration(ChildEntityConfiguration.class); } }
pramoth/light-admin
lightadmin-tests/src/test/java/org/lightadmin/page/fieldDisplay/listView/ReferenceFieldTest.java
Java
apache-2.0
615
import React from "react" import List from "@material-ui/core/List" import ListItem from "@material-ui/core/ListItem" import { Article, Header } from "muy" import Typography from "@material-ui/core/Typography" import { ListItemText } from "@material-ui/core" import Link from "@material-ui/core/Link" export default () => ( <Article> <Header> <Typography component={"h1"} variant={"h1"}> Uhu! Agora é só esperar! </Typography> <Typography component={"p"} variant={"h2"}> Daqui a pouco a gente vai fazer contato com você. </Typography> </Header> <Typography paragraph={true}> Enquanto isso, olha só esses <em lang="en">links</em> interessantes pra você aprender mais sobre programação: </Typography> <List> <ListItem> <ListItemText> <Link href="https://educodar.herokuapp.com/" rel={"noopener noreferrer"} target={"_blank"} tabIndex={0} > Jogo do Aviãozinho </Link> <br /> Passeie pelas nuvens em busca de balões. </ListItemText> </ListItem> </List> </Article> )
educodar/educodar.github.io
src/pages/quero-aprender/sucesso.js
JavaScript
apache-2.0
1,190
<!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_20) on Thu Jan 26 13:33:45 PST 2012 --> <TITLE> Uses of Class org.apache.hadoop.mapreduce.lib.db.DBInputFormat (Hadoop 0.20.2-cdh3u3 API) </TITLE> <META NAME="date" CONTENT="2012-01-26"> <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 org.apache.hadoop.mapreduce.lib.db.DBInputFormat (Hadoop 0.20.2-cdh3u3 API)"; } } </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>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DBInputFormat.html" title="class in org.apache.hadoop.mapreduce.lib.db"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/hadoop/mapreduce/lib/db//class-useDBInputFormat.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="DBInputFormat.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<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>org.apache.hadoop.mapreduce.lib.db.DBInputFormat</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DBInputFormat.html" title="class in org.apache.hadoop.mapreduce.lib.db">DBInputFormat</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.hadoop.mapred.lib.db"><B>org.apache.hadoop.mapred.lib.db</B></A></TD> <TD>org.apache.hadoop.mapred.lib.db Package&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.hadoop.mapreduce.lib.db"><B>org.apache.hadoop.mapreduce.lib.db</B></A></TD> <TD>org.apache.hadoop.mapred.lib.db Package&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.hadoop.mapred.lib.db"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DBInputFormat.html" title="class in org.apache.hadoop.mapreduce.lib.db">DBInputFormat</A> in <A HREF="../../../../../../../org/apache/hadoop/mapred/lib/db/package-summary.html">org.apache.hadoop.mapred.lib.db</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DBInputFormat.html" title="class in org.apache.hadoop.mapreduce.lib.db">DBInputFormat</A> in <A HREF="../../../../../../../org/apache/hadoop/mapred/lib/db/package-summary.html">org.apache.hadoop.mapred.lib.db</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../../org/apache/hadoop/mapred/lib/db/DBInputFormat.html" title="class in org.apache.hadoop.mapred.lib.db">DBInputFormat&lt;T extends DBWritable&gt;</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.hadoop.mapreduce.lib.db"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DBInputFormat.html" title="class in org.apache.hadoop.mapreduce.lib.db">DBInputFormat</A> in <A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/package-summary.html">org.apache.hadoop.mapreduce.lib.db</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DBInputFormat.html" title="class in org.apache.hadoop.mapreduce.lib.db">DBInputFormat</A> in <A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/package-summary.html">org.apache.hadoop.mapreduce.lib.db</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DataDrivenDBInputFormat.html" title="class in org.apache.hadoop.mapreduce.lib.db">DataDrivenDBInputFormat&lt;T extends DBWritable&gt;</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;A InputFormat that reads input data from an SQL table.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/OracleDataDrivenDBInputFormat.html" title="class in org.apache.hadoop.mapreduce.lib.db">OracleDataDrivenDBInputFormat&lt;T extends DBWritable&gt;</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;A InputFormat that reads input data from an SQL table in an Oracle db.</TD> </TR> </TABLE> &nbsp; <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>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/mapreduce/lib/db/DBInputFormat.html" title="class in org.apache.hadoop.mapreduce.lib.db"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/hadoop/mapreduce/lib/db//class-useDBInputFormat.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="DBInputFormat.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<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> Copyright &copy; 2009 The Apache Software Foundation </BODY> </HTML>
koven2049/hdfs-cloudera-cdh3u3-production
docs/api/org/apache/hadoop/mapreduce/lib/db/class-use/DBInputFormat.html
HTML
apache-2.0
10,468
int a[2] = {2, 2}, b[3] = {3, 3, 3}, c = 4, d = 5; int i = 0, j = 1; void main() { ++b[i]; assert(b[0] == 4, "b[0] must be 4"); ++c; assert(c == 5, "c must be 5"); d = ++b[j]; assert(d == 4, "d must be 4"); d = ++c; assert(d == 6, "d must be 6"); --b[1]; assert(b[1] == 3, "b[1] must be 3"); --i; assert(i == -1, "i must be -1"); c = --b[j]; assert(c == 2, "c must be 2"); i = 1; j = 2; c = --d; assert(c == 5, "c must be 5"); b[i]++; assert(b[1] == 3, "b[1] must be 3"); d++; assert(d == 6, "d must be 6"); d = b[j]++; assert(d == 3, "d must be 3"); c = d++; assert(c == 3, "c must be 3"); b[1] += i; assert(b[1] == 4, "b[1] must be 4"); --d; assert(d == 3, "d must be 3"); d = b[j]--; assert(d == 4, "d must be 4"); d = c--; assert(d == 3, "d must be 3"); assert(c == 2, "c must be 2"); }
andrey-terekhov/RuC
tests/codegen/executable/types/int/test_4.c
C
apache-2.0
959
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.appmgt.impl.token; //To be fixed with - https://wso2.org/jira/browse/APPM-1060 /** * This class represents the JWT signature algorithms. */ public enum JWTSignatureAlgorithm { SHA256_WITH_RSA("RS256"), NONE("none"); private String jwsCompliantCode; private JWTSignatureAlgorithm(String s){ jwsCompliantCode = s; } public String getJwsCompliantCode() { return jwsCompliantCode; } }
lakshani/carbon-mobile-appmgt
components/org.wso2.carbon.appmgt.impl/src/main/java/org/wso2/carbon/appmgt/impl/token/JWTSignatureAlgorithm.java
Java
apache-2.0
1,126
package com.example.ppawel.model; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.validation.constraints.NotNull; /** * Holds information of a single exchange rate query. * * @author ppawel * */ @Entity public class UserQuery implements Serializable { private static final long serialVersionUID = 9193245354648768670L; @Id @GeneratedValue private Long id; /** * Date of execution of this query. By default it's the current date at the * time of creation of this object. */ private Date executionDate = new Date(); /** * E-mail of the user. */ @NotNull private String email; /** * Base currency. */ private String baseCurrency; /** * Target currency. */ private String targetCurrency; /** * Date of exchange rate as queried by the user (<code>null</code> means * "latest rate" was queried). */ private Date date; @Column(precision = 12, scale = 9) private BigDecimal rate; public UserQuery() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getExecutionDate() { return executionDate; } public void setExecutionDate(Date executionDate) { this.executionDate = executionDate; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBaseCurrency() { return baseCurrency; } public void setBaseCurrency(String baseCurrency) { this.baseCurrency = baseCurrency; } public String getTargetCurrency() { return targetCurrency; } public void setTargetCurrency(String targetCurrency) { this.targetCurrency = targetCurrency; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public BigDecimal getRate() { return rate; } public void setRate(BigDecimal rate) { this.rate = rate; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.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; UserQuery other = (UserQuery) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
ppawel/currency-converter
src/main/java/com/example/ppawel/model/UserQuery.java
Java
apache-2.0
2,541
# chjdkver 2.0 ## What is this? It is difficult to switch jdk version on OS X environment which contains several jdk versions. Because, the relation among symbolic links is quite complex. This program simply switches jdk versions. ## Usage ### Print Available JDKs This program shows available jdks with no command line arguments, and prints currently used jdk. The printed jdks are the available jdks. $ cd /Library/Java/JavaVirtualMachines $ ls -F 1.7@ 1.7.0_45@ 1.8.0@ jdk1.7.0_45.jdk/ 1.7.0@ 1.8@ 1.8.0_20@ jdk1.8.0_20.jdk/ $ chjdkver 1.7 (*) 1.7.0 1.7.0_45 1.8 1.8.0 1.8.0_20 ### Switch JDK This program changes jdk version to command line argument. If unavailable version is specified, this program shows error message and quit. $ java -version java version "1.7.0_45" Java(TM) SE Runtime Environment (build 1.7.0_45-b18) Java HotSpot(TM) 64-Bit Server VM (build 24.45-b08, mixed mode) $ chjdkver 1.7 (*) 1.7.0 1.7.0_10 1.7.0_45 1.8 1.8.0 1.8.0_20 $ sudo chjdkver 1.8 $ java -version java version "1.8.0_20-ea" Java(TM) SE Runtime Environment (build 1.8.0_20-ea-b05) Java HotSpot(TM) 64-Bit Server VM (build 25.20-b05, mixed mode) $ chjdkver 1.7 1.7.0 1.7.0_10 1.7.0_45 1.8 (*) 1.8.0 1.8.0_20 ### Preparation This program supports initialization of environment and available jdks. Initialization sequence runs with certain options, as follows. $ sudo chjdkver --init Above command performs initialization sequence for environment and installed jdks. When this initialization sequence is done, following two initialization sequence is performed. #### Preparation for environment Note that, `/System/Library/Frameworks/JavaVM.framework/Versions/A/Commands` must be linked to `../CurrentJDK/Contents/Home/bin`. Because `/usr/bin/java` and etc. are symblic linked to `/System/Library/Frameworks/JavaVM.framework/Versions/A/Commands/java`, and the `A` directory is not symbolic link. $ sudo chjdkver --init_env Above command shows the following commands. $ cd /System/Library/Frameworks/JavaVM.framework/Versions/A $ sudo mv Commands Commands.back $ sudo ln -s ../CurrentJDK/Contents/Home/bin ./Commands #### Preparation for installed JDKs Oracle JDKs are installed into `/Library/Java/JavaVirtualMachines`. This program shows only files whose name is contained numbers, dot(.), hyphen, and underbar. Therefore, this initialization sequence symbolik link to certain name. $ ls -F jdk1.7.0_10.jdk/ jdk1.7.0_45.jdk/ jdk1.8.0_20.jdk/ $ chjdkver $ sudo chjdkver --init_jdks 1.7@ 1.7.0_10@ 1.8@ 1.8.0_20@ jdk1.7.0_45.jdk/ 1.7.0@ 1.7.0_45@ 1.8.0@ jdk1.7.0_10.jdk/ jdk1.8.0_20.jdk/ $ chjdkver 1.7 (*) 1.7.0 1.7.0_10 1.7.0_45 1.8 1.8.0 1.8.0_20 ## Future work * ???? ## Authors * Author: Haruaki Tamada * Web page: http://github.com/tamada/chjdkver ## License Apache License Version 2.0 Copyright 2013- Haruaki Tamada 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.
tamada/chjdkver
README.md
Markdown
apache-2.0
3,813
# cruddy [![Circle CI](https://circleci.com/gh/cloudnative/cruddy.svg?style=svg)](https://circleci.com/gh/cloudnative/cruddy) A simple CRUD wrapper around Amazon DynamoDB. ## Installation ``` $ pip install cruddy ``` ## Getting Started The first thing to do is to create a CRUD handler for your DynamoDB table. The constructor for the CRUD class takes a number of parameters to help configure the handler for your application. The full list of parameters are: * **table_name** - name of the backing DynamoDB table (required) * **profile_name** - name of the AWS credential profile to use when creating the boto3 Session * **region_name** - name of the AWS region to use when creating the boto3 Session * **prototype** - a dictionary that describes the prototypical object stored in your table (see below) * **supported_ops** - a list of operations supported by the CRUD handler (choices are list, get, create, update, delete, search, increment_counter) * **encrypted_attributes** - a list of lists or tuples where the first item is the name of the attribute that should be encrypted and the second item is the KMS master key ID to use for encrypting/decrypting the value. * **debug** - if not False this will cause the raw_response to be left in the response dictionary ### Prototypes A prototype is a description of the prototypical item in your table. It's kind of like a template for the item. A prototype can be used to describe what attributes are in the item, which are required or optional, and the type of value that is associated with the attribute. In addition, there are special values you can use that allow a small range of calculated values in your item. If you don't specify a prototype, cruddy will store whatever values are in the item with no validation or insertion of calculated values. Let's look at a few examples using prototypes. ``` { 'id': '', 'created_at': 1, 'foo': 1 } ``` This prototype says that your item must have an ``id`` attribute whose value is of type ``str``, a ``created_at`` attribute whose value is of type ``int``, and a ``foo`` attribute whose value is also an ``int``. Your item may contain other items as well (this is not a schema) but it must contain these attribute name/value pairs. If the item you pass into the ``create`` method does not contain these attributes cruddy will create the necessary attributes and will initialize the value to what ever value you have specified. #### Calculated Values The above example assumes that you are going to generate the ``id`` and ``created_at`` values in your application code. You may, however, prefer to have cruddy handle that for you. In that case, you can make use of cruddy's calcuated value tokens. ``` { 'id': 'on-create:<uuid>', 'created_at': 'on-create:<timestamp>' } ``` Now, when you create a new item you could supply one without an ``id`` or ``created_at`` value and cruddy will calculate these values for you. If those attributes already exist in the item, cruddy will not overwrite them. Note that the calulated values are specified as ``on-create``. This is called a ``trigger`` and indicates when the calculation will be performed. If you wanted to also have a timestamp to indicate when an item has been modified (i.e. created or updated) you could do this. ``` { 'id': 'on-create:<uuid>', 'created_at': 'on-create:<timestamp>', 'modified_at': 'on-update:<timestamp>' } ``` The currently supported calculated value types are: * **``<uuid>``** to generate a string representation of a Type4 UUID * **``<timestamp>``** to generate an integer timestamp generated by ``int(time.time()*1000)`` The currently supported triggers for calculated values are: * **on-create** will be applied when the item is created * **on-update** will be applied when the item is created or updated ### Configuring your CRUD handler An easy way to configure your CRUD handler is to gather all of the parameters together in a dictionary and then pass that dictionary to the class constructor. ``` import cruddy params = { 'profile_name': 'foobar', 'region_name': 'us-west-2', 'table_name': 'fiebaz', 'prototype': {'id': '<on-create:uuid>', 'created_at': '<on-create:timestamp>', 'modified_at': '<on-update:timestamp>'} } crud = cruddy.CRUD(**params) ``` Once you have your handler, you can start to use it. ``` item = {'name': 'the dude', 'email': 'the@dude.com', 'twitter': 'thedude'} response = crud.create(item) ``` The response returned from all CRUD operations is a Python object with the following attributes. * **data** is the actual data returned from the CRUD operation (if successful) * **status** is the status of the response and is either ``success`` or ``error`` * **metadata** is metadata from the underlying DynamoDB API call * **error_type** will be the type of error, if ``status != 'success'`` * **error_code** will be the code of error, if ``status != 'success'`` * **error_type** will be the full error message, if ``status != 'success'`` * **raw_response** will contain the full response from DynamoDB if the CRUD handler is in ``debug`` mode. * **is_successful** a simple short-cut, equivalent to ``status == 'success'`` You can convert the CRUDResponse object into a standard Python dictionary using the ``flatten`` method ``` >>> response = crud.create(...) >>> response.flatten() {'data': {'created_at': 1452109758363, 'name': 'the dude', 'email': 'the@dude.com', 'twitter': 'thedude', 'id': 'a6ac0fd7-cdde-4170-a1a9-30e139c44897', 'modified_at': 1452109758363}, 'error_code': None, 'error_message': None, 'error_type': None, 'metadata': {'HTTPStatusCode': 200, 'RequestId': 'LBBFLMIAVOKR8LOTK7SRGFO4Q3VV4KQNSO5AEMVJF66Q9ASUAAJG'}, 'raw_response': None, 'status': 'success'} >>> ``` ## CRUD operations The CRUD object supports the following operations. Note that depending on the value of the ``supported_operations`` parameter passed to the constructor, some of these methods may return an ``UnsupportedOperation`` error type. ### list() Returns a list of items in the database. Encrypted attributes are not decrypted when listing items. ### get(*id*, *decrypt=False*) Returns the item corresponding to ``id``. If the ``decrypt`` param is not False (the default) any encrypted attributes in the item will be decrypted before the item is returned. If not, the encrypted attributes will contain the encrypted value. ### create(*item*) Creates a new item. You pass in an item containing initial values. Any attribute names defined in ``prototype`` that are missing from the item will be added using the default value defined in ``prototype``. ### update(*item*, *encrypt=True*) Updates the item based on the current values of the dictionary passed in. If the ``encrypt`` param is True (the default), encrypted attributes in ``item`` are encrypted. To prevent double-encrypting when using ``list`` or ``get`` without ``decrypt=True``, you can specify ``encrypt=False`` and the item will be stored verbatim. ### delete(*id*) Deletes the item corresponding to ``id``. ## Beyond CRUD The following operations extend beyond the basic CRUD functions but are included because of they are quite useful. ### search(*query*) Cruddy provides a limited but useful interface to search GSI indexes in DynamoDB with the following limitations (hopefully some of these will be expanded or eliminated in the future. * The GSI must be configured with a only HASH and not a RANGE. * The only operation supported in the query is equality To use the ``search`` operation you must pass in a query string of this form: <attribute_name>=<value> As stated above, the only operation currently supported is equality (=) but other operations will be added over time. Also, the ``attribute_name`` must be an attribute which is configured as the ``HASH`` of a GSI in the DynamoDB table. If all of the above conditions are met, the ``query`` operation will return a list (possibly empty) of all items matching the query and the ``status`` of the response will be ``success``. Otherwise, the ``status`` will be ``error`` and the ``error_type`` and ``error_message`` will provide further information about the error. ### increment_counter(*id*, *counter_name*, [*increment*]) Atomically increments a counter attribute in the item identified by ``id``. You must specify the name of the attribute as ``counter_name`` and, optionally, the ``increment`` which defaults to ``1``. ## Using the handler interface In addition to the methods described above, cruddy also provides a generic handler interface. This is mainly useful when you want to wrap a cruddy handler in a Lambda function and then call that Lambda function to access the CRUD capabilities. To call the handler, you simply put all necessary parameters into a Python dictionary and then call the handler with that dict. ``` params = { 'operation': 'create', 'item': {'foo': 'bar', 'fie': 'baz'} } response = crud.handler(**params) ``` So, you could define a Lambda function like this: ``` import logging import json import cruddy LOG = logging.getLogger() LOG.setLevel(logging.INFO) config = json.load(open('config.json')) crud = cruddy.CRUD(**config) def handler(event, context): LOG.info(event) response = crud.handler(**event) return response.flatten() ``` Where ``config.json`` looks like this: ``` { "region_name": "us-west-2", "table_name": "foobar", "prototype": {"id": "<on-create:uuid>", "created_at": "<on-create:timestamp>", "modified_at": "<on-update:timestamp>", "foo": 1, "bar": ""}, } ``` If you uploaded this function (and config file) to AWS Lambda you could then invoke the handler like this. ``` import json import boto3 session = boto3.Session() lambda_client = session.client('lambda') params = {'operation': 'create', 'item': {'fie': 'baz'}} response = lambda_client.invoke( FunctionName='myfunction', InvocationType='RequestResponse', Payload=json.dumps(params)) cruddy_response = json.load(response['Payload']) ``` The variable ``cruddy_response`` would now contain the response structure returned by cruddy, flattened into a Python dictionary. ## The cruddy CLI cruddy also offers a CLI that allows you to access your DynamoDB table or Lambda-based handler via a simple command line interface. It supports all operations supported by cruddy. ### Using the cruddy CLI with a DynamoDB table To use cruddy to directly interact with a DynamoDB table, you need to place the configuration information for your cruddy handler in a JSON file. So, from our previous example if we created a file called ``fiebaz.json`` like this: ``` { "profile_name": "foobar", "region_name": "us-west-2", "table_name": "fiebaz", "prototype": {"id": "<on-create:uuid>", "created_at": "<on-create:timestamp>", "modified_at": "<on-update:timestamp>"} } ``` We could then reference this when using the cruddy CLI: ``` $ cruddy --config fiebaz.json list [ {<a listing of all items in fiebaz>} ... ] ``` Use the ``--help`` for more information on how to use the cruddy CLI. ### Using the cruddy CLI with a Lambda handler All of the operations of the CLI work exactly the same whether you are using it with a DynamoDB table directly or through a Lambda controller. The only difference is that rather than referencing a config file containing info about the table and other parameters needed to create the cruddy CRUD handler, you simply tell the CLI about the Lambda function. ``` $ cruddy --lambda-fn fiebaz list [ {<a listing of all items in fiebaz>} ... ] ``` where ``fiebaz`` is the name of your Lambda handler.
cloudnative/cruddy
README.md
Markdown
apache-2.0
11,839
/* * Windows.cpp * * Created on: Mar 14, 2014 * Author: Frank Ebner */ #ifdef WITH_TESTS #include "../../Test.h" #include "../../../math/dsp/dft/DFT.h" namespace K { /** fill array with simple sine function */ void dftFillSine(double arr[], unsigned int len) { for (unsigned int i = 0; i < len; ++i) { double t = (double) i / (double) len; arr[i] = sin(2 * K::PI * t) + sin(2 * K::PI * t * 8); } } TEST(DFT, DFTandIDFT) { // create test-data double sine[128]; dftFillSine(sine, 128); // output array DFTRectangular<double> out[128/2+1]; DFT<double, 128> dft; dft.getDFT(sine, out); double back[128]; dft.getIDFT(out, back); for (unsigned int i = 0; i < 128; ++i) { //std::cout << back[i] << std::endl; } for (unsigned int i = 0; i < 128; ++i) { ASSERT_NEAR( sine[i], back[i], 0.0000001 ); } } TEST(DFT, removeFreq) { // create test-data double sine[128]; dftFillSine(sine, 128); // output array DFTRectangular<double> dfted[128/2+1]; DFT<double, 128> dft; dft.getDFT(sine, dfted); dfted[1].sin = 0; // back to time domain double idfted[128]; dft.getIDFT(dfted, idfted); for (unsigned int i = 0; i < 128; ++i) { std::cout << idfted[i] << std::endl; } } } #endif
k-a-z-u/KLib
test/math/dsp/TestDSP.cpp
C++
apache-2.0
1,275
<!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_12-ea) on Wed Feb 05 23:03:20 CET 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Interface at.ac.tuwien.infosys.jcloudscale.datastore.mapping.Visitor (JCloudScale 0.4.1-SNAPSHOT API)</title> <meta name="date" content="2014-02-05"> <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="Uses of Interface at.ac.tuwien.infosys.jcloudscale.datastore.mapping.Visitor (JCloudScale 0.4.1-SNAPSHOT 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><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/Visitor.html" title="interface in at.ac.tuwien.infosys.jcloudscale.datastore.mapping">Class</a></li> <li class="navBarCell1Rev">Use</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>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?at/ac/tuwien/infosys/jcloudscale/datastore/mapping/class-use/Visitor.html" target="_top">Frames</a></li> <li><a href="Visitor.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"> <h2 title="Uses of Interface at.ac.tuwien.infosys.jcloudscale.datastore.mapping.Visitor" class="title">Uses of Interface<br>at.ac.tuwien.infosys.jcloudscale.datastore.mapping.Visitor</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/Visitor.html" title="interface in at.ac.tuwien.infosys.jcloudscale.datastore.mapping">Visitor</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#at.ac.tuwien.infosys.jcloudscale.datastore.mapping">at.ac.tuwien.infosys.jcloudscale.datastore.mapping</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#at.ac.tuwien.infosys.jcloudscale.datastore.mapping.hbase">at.ac.tuwien.infosys.jcloudscale.datastore.mapping.hbase</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#at.ac.tuwien.infosys.jcloudscale.datastore.mapping.json">at.ac.tuwien.infosys.jcloudscale.datastore.mapping.json</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="at.ac.tuwien.infosys.jcloudscale.datastore.mapping"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/Visitor.html" title="interface in at.ac.tuwien.infosys.jcloudscale.datastore.mapping">Visitor</a> in <a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/package-summary.html">at.ac.tuwien.infosys.jcloudscale.datastore.mapping</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/package-summary.html">at.ac.tuwien.infosys.jcloudscale.datastore.mapping</a> with parameters of type <a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/Visitor.html" title="interface in at.ac.tuwien.infosys.jcloudscale.datastore.mapping">Visitor</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">ObjectNavigatorImpl.</span><code><strong><a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/ObjectNavigatorImpl.html#navigate(java.lang.Object, at.ac.tuwien.infosys.jcloudscale.datastore.mapping.Visitor)">navigate</a></strong>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;object, <a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/Visitor.html" title="interface in at.ac.tuwien.infosys.jcloudscale.datastore.mapping">Visitor</a>&nbsp;visitor)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">ObjectNavigator.</span><code><strong><a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/ObjectNavigator.html#navigate(java.lang.Object, at.ac.tuwien.infosys.jcloudscale.datastore.mapping.Visitor)">navigate</a></strong>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;object, <a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/Visitor.html" title="interface in at.ac.tuwien.infosys.jcloudscale.datastore.mapping">Visitor</a>&nbsp;visitor)</code> <div class="block">Navigates through the given object using the given visitor</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="at.ac.tuwien.infosys.jcloudscale.datastore.mapping.hbase"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/Visitor.html" title="interface in at.ac.tuwien.infosys.jcloudscale.datastore.mapping">Visitor</a> in <a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/hbase/package-summary.html">at.ac.tuwien.infosys.jcloudscale.datastore.mapping.hbase</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/hbase/package-summary.html">at.ac.tuwien.infosys.jcloudscale.datastore.mapping.hbase</a> that implement <a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/Visitor.html" title="interface in at.ac.tuwien.infosys.jcloudscale.datastore.mapping">Visitor</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/hbase/HbaseDeserializationVisitor.html" title="class in at.ac.tuwien.infosys.jcloudscale.datastore.mapping.hbase">HbaseDeserializationVisitor</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/hbase/HbaseSerializationVisitor.html" title="class in at.ac.tuwien.infosys.jcloudscale.datastore.mapping.hbase">HbaseSerializationVisitor</a></strong></code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="at.ac.tuwien.infosys.jcloudscale.datastore.mapping.json"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/Visitor.html" title="interface in at.ac.tuwien.infosys.jcloudscale.datastore.mapping">Visitor</a> in <a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/json/package-summary.html">at.ac.tuwien.infosys.jcloudscale.datastore.mapping.json</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/json/package-summary.html">at.ac.tuwien.infosys.jcloudscale.datastore.mapping.json</a> that implement <a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/Visitor.html" title="interface in at.ac.tuwien.infosys.jcloudscale.datastore.mapping">Visitor</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/json/JsonDeserializationVisitor.html" title="class in at.ac.tuwien.infosys.jcloudscale.datastore.mapping.json">JsonDeserializationVisitor</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/json/JsonSerializationVisitor.html" title="class in at.ac.tuwien.infosys.jcloudscale.datastore.mapping.json">JsonSerializationVisitor</a></strong></code> <div class="block">Visitor for mapping objects to JSON</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </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><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../at/ac/tuwien/infosys/jcloudscale/datastore/mapping/Visitor.html" title="interface in at.ac.tuwien.infosys.jcloudscale.datastore.mapping">Class</a></li> <li class="navBarCell1Rev">Use</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>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?at/ac/tuwien/infosys/jcloudscale/datastore/mapping/class-use/Visitor.html" target="_top">Frames</a></li> <li><a href="Visitor.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 &#169; 2014. All Rights Reserved.</small></p> </body> </html>
xLeitix/jcloudscale
docs/javadoc/apidocs/at/ac/tuwien/infosys/jcloudscale/datastore/mapping/class-use/Visitor.html
HTML
apache-2.0
12,575
#pragma once #include "il2cpp-codegen-common.h" #include "il2cpp-pinvoke-support.h" #include "icalls/mscorlib/System.Threading/Interlocked.h" #include "icalls/mscorlib/System.Runtime.InteropServices/Marshal.h" #include "utils/Il2CppHStringReference.h" #include "utils/RegisterRuntimeInitializeAndCleanup.h" #include "vm/Atomic.h" #include "vm/ClassInlines.h" #include "vm/ScopedThreadAttacher.h" #include "vm/String.h" #if IL2CPP_ENABLE_PROFILER void il2cpp_codegen_profiler_method_enter(const RuntimeMethod* method); void il2cpp_codegen_profiler_method_exit(const RuntimeMethod* method); #endif struct ProfilerMethodSentry { ProfilerMethodSentry(const RuntimeMethod* method) #if IL2CPP_ENABLE_PROFILER : m_method(method) #endif { #if IL2CPP_ENABLE_PROFILER il2cpp_codegen_profiler_method_enter(m_method); #endif } ~ProfilerMethodSentry() { #if IL2CPP_ENABLE_PROFILER il2cpp_codegen_profiler_method_exit(m_method); #endif } private: const RuntimeMethod* m_method; }; void il2cpp_codegen_stacktrace_push_frame(Il2CppStackFrameInfo& frame); void il2cpp_codegen_stacktrace_pop_frame(); struct StackTraceSentry { StackTraceSentry(const RuntimeMethod* method) : m_method(method) { Il2CppStackFrameInfo frame_info; frame_info.method = method; il2cpp_codegen_stacktrace_push_frame(frame_info); } ~StackTraceSentry() { il2cpp_codegen_stacktrace_pop_frame(); } private: const RuntimeMethod* m_method; }; #define IL2CPP_FAKE_BOX_SENTRY (MonitorData*)UINTPTR_MAX template<typename T> struct Il2CppFakeBox : RuntimeObject { T m_Value; Il2CppFakeBox(RuntimeClass* boxedType, T* value) { klass = boxedType; monitor = IL2CPP_FAKE_BOX_SENTRY; m_Value = *value; } }; inline bool il2cpp_codegen_is_fake_boxed_object(RuntimeObject* object) { return object->monitor == IL2CPP_FAKE_BOX_SENTRY; } // TODO: This file should contain all the functions and type declarations needed for the generated code. // Hopefully, we stop including everything in the generated code and know exactly what dependencies we have. // Note that all parameter and return types should match the generated types not the runtime types. void il2cpp_codegen_register(const Il2CppCodeRegistration* const codeRegistration, const Il2CppMetadataRegistration* const metadataRegistration, const Il2CppCodeGenOptions* const codeGenOptions); // type registration void* il2cpp_codegen_get_thread_static_data(RuntimeClass* klass); String_t* il2cpp_codegen_string_new_wrapper(const char* str); String_t* il2cpp_codegen_string_new_utf16(const il2cpp::utils::StringView<Il2CppChar>& str); Type_t* il2cpp_codegen_type_get_object(const RuntimeType* type); NORETURN void il2cpp_codegen_raise_exception(Exception_t *ex, MethodInfo* lastManagedFrame = NULL); NORETURN void il2cpp_codegen_raise_exception(il2cpp_hresult_t hresult, bool defaultToCOMException); void il2cpp_codegen_raise_execution_engine_exception_if_method_is_not_found(const RuntimeMethod* method); void il2cpp_codegen_raise_execution_engine_exception(const RuntimeMethod* method); NORETURN void il2cpp_codegen_raise_out_of_memory_exception(); NORETURN void il2cpp_codegen_raise_null_reference_exception(); NORETURN void il2cpp_codegen_raise_divide_by_zero_exception(); Exception_t* il2cpp_codegen_get_argument_exception(const char* param, const char* msg); Exception_t* il2cpp_codegen_get_argument_null_exception(const char* param); Exception_t* il2cpp_codegen_get_overflow_exception(); Exception_t* il2cpp_codegen_get_not_supported_exception(const char* msg); Exception_t* il2cpp_codegen_get_array_type_mismatch_exception(); Exception_t* il2cpp_codegen_get_invalid_cast_exception(const char* msg); Exception_t* il2cpp_codegen_get_invalid_operation_exception(const char* msg); Exception_t* il2cpp_codegen_get_marshal_directive_exception(const char* msg); Exception_t* il2cpp_codegen_get_missing_method_exception(const char* msg); Exception_t* il2cpp_codegen_get_maximum_nested_generics_exception(); Exception_t* il2cpp_codegen_get_index_out_of_range_exception(); Exception_t* il2cpp_codegen_get_exception(il2cpp_hresult_t hresult, bool defaultToCOMException); inline RuntimeClass* il2cpp_codegen_object_class(RuntimeObject* obj) { return obj->klass; } // OpCode.IsInst RuntimeObject* IsInst(RuntimeObject *obj, RuntimeClass* targetType); inline RuntimeObject* IsInstSealed(RuntimeObject *obj, RuntimeClass* targetType) { #if IL2CPP_DEBUG IL2CPP_ASSERT((targetType->flags & TYPE_ATTRIBUTE_SEALED) != 0); IL2CPP_ASSERT((targetType->flags & TYPE_ATTRIBUTE_INTERFACE) == 0); #endif if (!obj) return NULL; // optimized version to compare sealed classes return (obj->klass == targetType ? obj : NULL); } inline RuntimeObject* IsInstClass(RuntimeObject *obj, RuntimeClass* targetType) { #if IL2CPP_DEBUG IL2CPP_ASSERT((targetType->flags & TYPE_ATTRIBUTE_INTERFACE) == 0); #endif if (!obj) return NULL; // optimized version to compare classes return il2cpp::vm::ClassInlines::HasParentUnsafe(obj->klass, targetType) ? obj : NULL; } // OpCode.Castclass NORETURN void RaiseInvalidCastException(RuntimeObject* obj, RuntimeClass* targetType); inline RuntimeObject* Castclass(RuntimeObject *obj, RuntimeClass* targetType) { if (!obj) return NULL; RuntimeObject* result = IsInst(obj, targetType); if (result) return result; RaiseInvalidCastException(obj, targetType); return NULL; } inline RuntimeObject* CastclassSealed(RuntimeObject *obj, RuntimeClass* targetType) { if (!obj) return NULL; RuntimeObject* result = IsInstSealed(obj, targetType); if (result) return result; RaiseInvalidCastException(obj, targetType); return NULL; } inline RuntimeObject* CastclassClass(RuntimeObject *obj, RuntimeClass* targetType) { if (!obj) return NULL; RuntimeObject* result = IsInstClass(obj, targetType); if (result) return result; RaiseInvalidCastException(obj, targetType); return NULL; } inline void NullCheck(void* this_ptr) { if (this_ptr != NULL) return; il2cpp_codegen_raise_null_reference_exception(); } // OpCode.Box RuntimeObject* Box(RuntimeClass* type, void* data); // OpCode.UnBox void* Unbox_internal(Il2CppObject* obj); inline void* UnBox(RuntimeObject* obj) { NullCheck(obj); return Unbox_internal(obj); } inline void* UnBox(RuntimeObject* obj, RuntimeClass* expectedBoxedClass) { NullCheck(obj); if (obj->klass->element_class == expectedBoxedClass->element_class) return Unbox_internal(obj); RaiseInvalidCastException(obj, expectedBoxedClass); return NULL; } void UnBoxNullable_internal(RuntimeObject* obj, RuntimeClass* expectedBoxedClass, void* storage); inline void UnBoxNullable(RuntimeObject* obj, RuntimeClass* expectedBoxedClass, void* storage) { // We only need to do type checks if obj is not null // Unboxing null nullable is perfectly valid and returns an instance that has no value if (obj != NULL) { if (obj->klass->element_class != expectedBoxedClass->element_class) RaiseInvalidCastException(obj, expectedBoxedClass); } UnBoxNullable_internal(obj, expectedBoxedClass, storage); } int32_t il2cpp_codgen_class_get_instance_size(RuntimeClass* klass); inline uint32_t il2cpp_codegen_sizeof(RuntimeClass* klass) { if (!klass->valuetype) { return sizeof(void*); } return il2cpp_codgen_class_get_instance_size(klass) - sizeof(RuntimeObject); } inline bool il2cpp_codegen_method_is_virtual(RuntimeMethod* method) { return method->slot != kInvalidIl2CppMethodSlot; } inline bool il2cpp_codegen_object_is_of_sealed_type(RuntimeObject* obj) { return obj != NULL && (obj->klass->flags & TYPE_ATTRIBUTE_SEALED) != 0; } bool il2cpp_codegen_method_is_generic_instance(RuntimeMethod* method); RuntimeClass* il2cpp_codegen_method_get_declaring_type(RuntimeMethod* method); bool il2cpp_codegen_method_is_interface_method(RuntimeMethod* method); inline uint16_t il2cpp_codegen_method_get_slot(RuntimeMethod* method) { return method->slot; } IL2CPP_FORCE_INLINE const VirtualInvokeData& il2cpp_codegen_get_virtual_invoke_data(Il2CppMethodSlot slot, const RuntimeObject* obj) { Assert(slot != kInvalidIl2CppMethodSlot && "il2cpp_codegen_get_virtual_invoke_data got called on a non-virtual method"); return obj->klass->vtable[slot]; } IL2CPP_FORCE_INLINE const VirtualInvokeData& il2cpp_codegen_get_interface_invoke_data(Il2CppMethodSlot slot, RuntimeObject* obj, const RuntimeClass* declaringInterface) { Assert(slot != kInvalidIl2CppMethodSlot && "il2cpp_codegen_get_interface_invoke_data got called on a non-virtual method"); return il2cpp::vm::ClassInlines::GetInterfaceInvokeDataFromVTable(obj, declaringInterface, slot); } const RuntimeMethod* il2cpp_codegen_get_generic_virtual_method_internal(const RuntimeMethod* methodDefinition, const RuntimeMethod* inflatedMethod); IL2CPP_FORCE_INLINE const RuntimeMethod* il2cpp_codegen_get_generic_virtual_method(const RuntimeMethod* method, const RuntimeObject* obj) { uint16_t slot = method->slot; const RuntimeMethod* methodDefinition = obj->klass->vtable[slot].method; return il2cpp_codegen_get_generic_virtual_method_internal(methodDefinition, method); } IL2CPP_FORCE_INLINE void il2cpp_codegen_get_generic_virtual_invoke_data(const RuntimeMethod* method, const RuntimeObject* obj, VirtualInvokeData* invokeData) { const RuntimeMethod* targetRuntimeMethod = il2cpp_codegen_get_generic_virtual_method(method, obj); #if IL2CPP_DEBUG IL2CPP_ASSERT(targetRuntimeMethod); #endif invokeData->methodPtr = targetRuntimeMethod->methodPointer; invokeData->method = targetRuntimeMethod; } IL2CPP_FORCE_INLINE const RuntimeMethod* il2cpp_codegen_get_generic_interface_method(const RuntimeMethod* method, RuntimeObject* obj) { const RuntimeMethod* methodDefinition = il2cpp::vm::ClassInlines::GetInterfaceInvokeDataFromVTable(obj, method->klass, method->slot).method; return il2cpp_codegen_get_generic_virtual_method_internal(methodDefinition, method); } IL2CPP_FORCE_INLINE void il2cpp_codegen_get_generic_interface_invoke_data(const RuntimeMethod* method, RuntimeObject* obj, VirtualInvokeData* invokeData) { const RuntimeMethod* targetRuntimeMethod = il2cpp_codegen_get_generic_interface_method(method, obj); #if IL2CPP_DEBUG IL2CPP_ASSERT(targetRuntimeMethod); #endif invokeData->methodPtr = targetRuntimeMethod->methodPointer; invokeData->method = targetRuntimeMethod; } inline RuntimeClass* InitializedTypeInfo(RuntimeClass* klass) { il2cpp::vm::ClassInlines::InitFromCodegen(klass); return klass; } RuntimeClass* il2cpp_codegen_class_from_type_internal(const RuntimeType* type); inline RuntimeClass* il2cpp_codegen_class_from_type(const RuntimeType *type) { return InitializedTypeInfo(il2cpp_codegen_class_from_type_internal(type)); } inline void* InterlockedExchangeImplRef(void** location, void* value) { return il2cpp::icalls::mscorlib::System::Threading::Interlocked::ExchangePointer(location, value); } template<typename T> inline T InterlockedCompareExchangeImpl(T* location, T value, T comparand) { return (T)il2cpp::icalls::mscorlib::System::Threading::Interlocked::CompareExchange_T((void**)location, value, comparand); } template<typename T> inline T InterlockedExchangeImpl(T* location, T value) { return (T)InterlockedExchangeImplRef((void**)location, value); } void il2cpp_codegen_memory_barrier(); inline void ArrayGetGenericValueImpl(RuntimeArray* thisPtr, int32_t pos, void* value) { memcpy(value, ((uint8_t*)thisPtr) + sizeof(RuntimeArray) + pos * thisPtr->klass->element_size, thisPtr->klass->element_size); } inline void ArraySetGenericValueImpl(RuntimeArray * thisPtr, int32_t pos, void* value) { memcpy(((uint8_t*)thisPtr) + sizeof(RuntimeArray) + pos * thisPtr->klass->element_size, value, thisPtr->klass->element_size); } RuntimeArray* SZArrayNew(RuntimeClass* arrayType, uint32_t length); RuntimeArray* GenArrayNew(RuntimeClass* arrayType, il2cpp_array_size_t* dimensions); // Performance optimization as detailed here: http://blogs.msdn.com/b/clrcodegeneration/archive/2009/08/13/array-bounds-check-elimination-in-the-clr.aspx // Since array size is a signed int32_t, a single unsigned check can be performed to determine if index is less than array size. // Negative indices will map to a unsigned number greater than or equal to 2^31 which is larger than allowed for a valid array. #define IL2CPP_ARRAY_BOUNDS_CHECK(index, length) \ do { \ if (((uint32_t)(index)) >= ((uint32_t)length)) il2cpp_codegen_raise_exception (il2cpp_codegen_get_index_out_of_range_exception()); \ } while (0) bool il2cpp_codegen_class_is_assignable_from(RuntimeClass *klass, RuntimeClass *oklass); RuntimeObject* il2cpp_codegen_object_new(RuntimeClass *klass); Il2CppMethodPointer il2cpp_codegen_resolve_icall(const char* name); Il2CppMethodPointer il2cpp_codegen_resolve(const PInvokeArguments& pinvokeArgs); template<typename FunctionPointerType, size_t dynamicLibraryLength, size_t entryPointLength> inline FunctionPointerType il2cpp_codegen_resolve_pinvoke(const Il2CppNativeChar(&nativeDynamicLibrary)[dynamicLibraryLength], const char(&entryPoint)[entryPointLength], Il2CppCallConvention callingConvention, Il2CppCharSet charSet, int parameterSize, bool isNoMangle) { const PInvokeArguments pinvokeArgs = { il2cpp::utils::StringView<Il2CppNativeChar>(nativeDynamicLibrary), il2cpp::utils::StringView<char>(entryPoint), callingConvention, charSet, parameterSize, isNoMangle }; return reinterpret_cast<FunctionPointerType>(il2cpp_codegen_resolve(pinvokeArgs)); } void* il2cpp_codegen_marshal_allocate(size_t size); template<typename T> inline T* il2cpp_codegen_marshal_allocate_array(size_t length) { return static_cast<T*>(il2cpp_codegen_marshal_allocate((il2cpp_array_size_t)(sizeof(T) * length))); } template<typename T> inline T* il2cpp_codegen_marshal_allocate() { return static_cast<T*>(il2cpp_codegen_marshal_allocate(sizeof(T))); } char* il2cpp_codegen_marshal_string(String_t* string); void il2cpp_codegen_marshal_string_fixed(String_t* string, char* buffer, int numberOfCharacters); Il2CppChar* il2cpp_codegen_marshal_wstring(String_t* string); void il2cpp_codegen_marshal_wstring_fixed(String_t* string, Il2CppChar* buffer, int numberOfCharacters); Il2CppChar* il2cpp_codegen_marshal_bstring(String_t* string); String_t* il2cpp_codegen_marshal_string_result(const char* value); String_t* il2cpp_codegen_marshal_wstring_result(const Il2CppChar* value); String_t* il2cpp_codegen_marshal_bstring_result(const Il2CppChar* value); void il2cpp_codegen_marshal_free_bstring(Il2CppChar* value); char* il2cpp_codegen_marshal_empty_string_builder(StringBuilder_t* stringBuilder); char* il2cpp_codegen_marshal_string_builder(StringBuilder_t* stringBuilder); Il2CppChar* il2cpp_codegen_marshal_empty_wstring_builder(StringBuilder_t* stringBuilder); Il2CppChar* il2cpp_codegen_marshal_wstring_builder(StringBuilder_t* stringBuilder); void il2cpp_codegen_marshal_string_builder_result(StringBuilder_t* stringBuilder, char* buffer); void il2cpp_codegen_marshal_wstring_builder_result(StringBuilder_t* stringBuilder, Il2CppChar* buffer); Il2CppHString il2cpp_codegen_create_hstring(String_t* str); String_t* il2cpp_codegen_marshal_hstring_result(Il2CppHString hstring); void il2cpp_codegen_marshal_free_hstring(Il2CppHString hstring); void il2cpp_codegen_marshal_type_to_native(Type_t* type, Il2CppWindowsRuntimeTypeName& nativeType); const Il2CppType* il2cpp_codegen_marshal_type_from_native_internal(Il2CppWindowsRuntimeTypeName& nativeType); inline Type_t* il2cpp_codegen_marshal_type_from_native(Il2CppWindowsRuntimeTypeName& nativeType) { const Il2CppType* type = il2cpp_codegen_marshal_type_from_native_internal(nativeType); if (type == NULL) return NULL; return il2cpp_codegen_type_get_object(type); } void il2cpp_codegen_delete_native_type(Il2CppWindowsRuntimeTypeName& nativeType); void il2cpp_codegen_marshal_free(void* ptr); Il2CppMethodPointer il2cpp_codegen_marshal_delegate(MulticastDelegate_t* d); Il2CppDelegate* il2cpp_codegen_marshal_function_ptr_to_delegate_internal(void* functionPtr, Il2CppClass* delegateType); template<typename T> inline T* il2cpp_codegen_marshal_function_ptr_to_delegate(Il2CppMethodPointer functionPtr, RuntimeClass* delegateType) { return (T*)il2cpp_codegen_marshal_function_ptr_to_delegate_internal(reinterpret_cast<void*>(functionPtr), delegateType); } void il2cpp_codegen_marshal_store_last_error(); #if _DEBUG void il2cpp_codegen_marshal_allocate_push_allocation_frame(); void il2cpp_codegen_marshal_allocate_pop_allocation_frame(); bool il2cpp_codegen_marshal_allocate_has_unfreed_allocations(); void il2cpp_codegen_marshal_allocate_clear_all_tracked_allocations(); struct ScopedMarshallingAllocationFrame { ScopedMarshallingAllocationFrame() { il2cpp_codegen_marshal_allocate_push_allocation_frame(); } ~ScopedMarshallingAllocationFrame() { il2cpp_codegen_marshal_allocate_pop_allocation_frame(); } }; struct ScopedMarshallingAllocationCheck { ~ScopedMarshallingAllocationCheck() { if (il2cpp_codegen_marshal_allocate_has_unfreed_allocations()) il2cpp_codegen_raise_exception(il2cpp_codegen_get_invalid_operation_exception("Error in marshaling allocation. Some memory has been leaked.")); } private: ScopedMarshallingAllocationFrame m_AllocationFrame; }; struct ScopedMarshalingAllocationClearer { ~ScopedMarshalingAllocationClearer() { il2cpp_codegen_marshal_allocate_clear_all_tracked_allocations(); } private: ScopedMarshallingAllocationFrame m_AllocationFrame; }; #endif inline void DivideByZeroCheck(int64_t denominator) { if (denominator != 0) return; il2cpp_codegen_raise_divide_by_zero_exception(); } inline void il2cpp_codegen_initobj(void* value, size_t size) { memset(value, 0, size); } bool MethodIsStatic(const RuntimeMethod* method); bool MethodHasParameters(const RuntimeMethod* method); void il2cpp_codegen_runtime_class_init(RuntimeClass* klass); #define IL2CPP_RUNTIME_CLASS_INIT(klass) do { if((klass)->has_cctor && !(klass)->cctor_finished) il2cpp_codegen_runtime_class_init ((klass)); } while (0) // generic sharing #define IL2CPP_RGCTX_DATA(rgctxVar, index) (InitializedTypeInfo(rgctxVar[index].klass)) #define IL2CPP_RGCTX_SIZEOF(rgctxVar, index) (il2cpp_codegen_sizeof(IL2CPP_RGCTX_DATA(rgctxVar, index))) #define IL2CPP_RGCTX_TYPE(rgctxVar, index) (rgctxVar[index].type) #define IL2CPP_RGCTX_METHOD_INFO(rgctxVar, index) (rgctxVar[index].method) #define IL2CPP_RGCTX_FIELD_INFO(klass, index) ((klass)->fields+index) inline void ArrayElementTypeCheck(RuntimeArray* array, void* value) { #if !IL2CPP_TINY if (value != NULL && IsInst((RuntimeObject*)value, array->klass->element_class) == NULL) il2cpp_codegen_raise_exception(il2cpp_codegen_get_array_type_mismatch_exception()); #endif } inline const RuntimeMethod* GetVirtualMethodInfo(RuntimeObject* pThis, Il2CppMethodSlot slot) { if (!pThis) il2cpp_codegen_raise_null_reference_exception(); return pThis->klass->vtable[slot].method; } inline const RuntimeMethod* GetInterfaceMethodInfo(RuntimeObject* pThis, Il2CppMethodSlot slot, RuntimeClass* declaringInterface) { if (!pThis) il2cpp_codegen_raise_null_reference_exception(); return il2cpp::vm::ClassInlines::GetInterfaceInvokeDataFromVTable(pThis, declaringInterface, slot).method; } void il2cpp_codegen_initialize_method(uint32_t index); bool il2cpp_codegen_class_is_value_type(RuntimeClass* type); inline bool il2cpp_codegen_type_implements_virtual_method(RuntimeClass* type, const RuntimeMethod* method) { IL2CPP_ASSERT(il2cpp_codegen_class_is_value_type(type)); return method->klass == type; } MethodBase_t* il2cpp_codegen_get_method_object_internal(const RuntimeMethod* method, RuntimeClass* refclass); const RuntimeMethod* il2cpp_codegen_get_generic_method_definition(const RuntimeMethod* method); inline MethodBase_t* il2cpp_codegen_get_method_object(const RuntimeMethod* method) { if (method->is_inflated) method = il2cpp_codegen_get_generic_method_definition(method); return il2cpp_codegen_get_method_object_internal(method, method->klass); } RuntimeString* il2cpp_codegen_type_append_assembly_name_if_necessary(RuntimeString* typeName, const char* assemblyName); inline Type_t* il2cpp_codegen_get_type(Il2CppMethodPointer getTypeFunction, String_t* typeName, const char* assemblyName) { typedef Type_t* (*getTypeFuncType)(String_t*); RuntimeString* assemblyQualifiedTypeName = il2cpp_codegen_type_append_assembly_name_if_necessary((RuntimeString*)typeName, assemblyName); // Try to find the type using a hint about about calling assembly. If it is not found, fall back to calling GetType without the hint. Type_t* type = ((getTypeFuncType)getTypeFunction)((String_t*)assemblyQualifiedTypeName); if (type == NULL) return ((getTypeFuncType)getTypeFunction)(typeName); return type; } inline Type_t* il2cpp_codegen_get_type(Il2CppMethodPointer getTypeFunction, String_t* typeName, bool throwOnError, const char* assemblyName) { typedef Type_t* (*getTypeFuncType)(String_t*, bool); RuntimeString* assemblyQualifiedTypeName = il2cpp_codegen_type_append_assembly_name_if_necessary((RuntimeString*)typeName, assemblyName); // Try to find the type using a hint about about calling assembly. If it is not found, fall back to calling GetType without the hint. Type_t* type = ((getTypeFuncType)getTypeFunction)((String_t*)assemblyQualifiedTypeName, throwOnError); if (type == NULL) return ((getTypeFuncType)getTypeFunction)(typeName, throwOnError); return type; } inline Type_t* il2cpp_codegen_get_type(Il2CppMethodPointer getTypeFunction, String_t* typeName, bool throwOnError, bool ignoreCase, const char* assemblyName) { typedef Type_t* (*getTypeFuncType)(String_t*, bool, bool); RuntimeString* assemblyQualifiedTypeName = il2cpp_codegen_type_append_assembly_name_if_necessary((RuntimeString*)typeName, assemblyName); // Try to find the type using a hint about about calling assembly. If it is not found, fall back to calling GetType without the hint. Type_t* type = ((getTypeFuncType)getTypeFunction)((String_t*)assemblyQualifiedTypeName, throwOnError, ignoreCase); if (type == NULL) return ((getTypeFuncType)getTypeFunction)(typeName, throwOnError, ignoreCase); return type; } Assembly_t* il2cpp_codegen_get_executing_assembly(const RuntimeMethod* method); // Atomic inline void* il2cpp_codegen_atomic_compare_exchange_pointer(void* volatile* dest, void* exchange, void* comparand) { return il2cpp::vm::Atomic::CompareExchangePointer(dest, exchange, comparand); } template<typename T> inline T* il2cpp_codegen_atomic_compare_exchange_pointer(T* volatile* dest, T* newValue, T* oldValue) { return il2cpp::vm::Atomic::CompareExchangePointer(dest, newValue, oldValue); } // COM void il2cpp_codegen_com_marshal_variant(RuntimeObject* obj, Il2CppVariant* variant); RuntimeObject* il2cpp_codegen_com_marshal_variant_result(const Il2CppVariant* variant); void il2cpp_codegen_com_destroy_variant(Il2CppVariant* variant); Il2CppSafeArray* il2cpp_codegen_com_marshal_safe_array(Il2CppChar type, RuntimeArray* managedArray); RuntimeArray* il2cpp_codegen_com_marshal_safe_array_result(Il2CppChar variantType, RuntimeClass* type, Il2CppSafeArray* safeArray); Il2CppSafeArray* il2cpp_codegen_com_marshal_safe_array_bstring(RuntimeArray* managedArray); RuntimeArray* il2cpp_codegen_com_marshal_safe_array_bstring_result(RuntimeClass* type, Il2CppSafeArray* safeArray); void il2cpp_codegen_com_destroy_safe_array(Il2CppSafeArray* safeArray); void il2cpp_codegen_com_create_instance(const Il2CppGuid& clsid, Il2CppIUnknown** identity); void il2cpp_codegen_com_register_rcw(Il2CppComObject* rcw); RuntimeObject* il2cpp_codegen_com_get_or_create_rcw_from_iunknown_internal(Il2CppIUnknown* unknown, RuntimeClass* fallbackClass); template<typename T> inline T* il2cpp_codegen_com_get_or_create_rcw_from_iunknown(Il2CppIUnknown* unknown, RuntimeClass* fallbackClass) { return static_cast<T*>(il2cpp_codegen_com_get_or_create_rcw_from_iunknown_internal(unknown, fallbackClass)); } RuntimeObject* il2cpp_codegen_com_get_or_create_rcw_from_iinspectable_internal(Il2CppIInspectable* unknown, RuntimeClass* fallbackClass); template<typename T> inline T* il2cpp_codegen_com_get_or_create_rcw_from_iinspectable(Il2CppIInspectable* unknown, RuntimeClass* fallbackClass) { return static_cast<T*>(il2cpp_codegen_com_get_or_create_rcw_from_iinspectable_internal(unknown, fallbackClass)); } RuntimeObject* il2cpp_codegen_com_get_or_create_rcw_for_sealed_class_internal(Il2CppIUnknown* unknown, RuntimeClass* objectClass); template<typename T> inline T* il2cpp_codegen_com_get_or_create_rcw_for_sealed_class(Il2CppIUnknown* unknown, RuntimeClass* objectClass) { return static_cast<T*>(il2cpp_codegen_com_get_or_create_rcw_for_sealed_class_internal(unknown, objectClass)); } Il2CppIUnknown* il2cpp_codegen_com_query_interface_internal(Il2CppComObject* rcw, const Il2CppGuid& guid); Il2CppIUnknown* il2cpp_codegen_com_query_interface_no_throw_internal(Il2CppComObject* rcw, const Il2CppGuid& guid); void il2cpp_codegen_com_cache_queried_interface(Il2CppComObject* rcw, const Il2CppGuid& guid, Il2CppIUnknown* queriedInterface); template<typename T> inline T* il2cpp_codegen_com_query_interface(Il2CppComObject* rcw) { return static_cast<T*>(il2cpp_codegen_com_query_interface_internal(rcw, T::IID)); } template<typename T> inline T* il2cpp_codegen_com_query_interface_no_throw(Il2CppComObject* rcw) { return static_cast<T*>(il2cpp_codegen_com_query_interface_no_throw_internal(rcw, T::IID)); } void il2cpp_codegen_il2cpp_com_object_cleanup(Il2CppComObject* rcw); Il2CppIUnknown* il2cpp_codegen_com_get_or_create_ccw_internal(RuntimeObject* obj, const Il2CppGuid& iid); template<typename InterfaceType> inline InterfaceType* il2cpp_codegen_com_get_or_create_ccw(RuntimeObject* obj) { return static_cast<InterfaceType*>(il2cpp_codegen_com_get_or_create_ccw_internal(obj, InterfaceType::IID)); } inline intptr_t il2cpp_codegen_com_get_iunknown_for_object(RuntimeObject* obj) { return reinterpret_cast<intptr_t>(il2cpp_codegen_com_get_or_create_ccw_internal(obj, Il2CppIUnknown::IID)); } Il2CppObject* il2cpp_codegen_com_unpack_ccw(Il2CppIUnknown* obj); inline void il2cpp_codegen_com_raise_exception_if_failed(il2cpp_hresult_t hr, bool defaultToCOMException) { // Copied from il2cpp::vm::Exception::RaiseIfFailed to keep inlined if (IL2CPP_HR_FAILED(hr)) il2cpp_codegen_raise_exception(hr, defaultToCOMException); } inline RuntimeException* il2cpp_codegen_com_get_exception(il2cpp_hresult_t hr, bool defaultToCOMException) { return (RuntimeException*)il2cpp_codegen_get_exception(hr, defaultToCOMException); } il2cpp_hresult_t il2cpp_codegen_com_handle_invalid_iproperty_conversion(const char* fromType, const char* toType); il2cpp_hresult_t il2cpp_codegen_com_handle_invalid_iproperty_conversion(RuntimeObject* value, const char* fromType, const char* toType); il2cpp_hresult_t il2cpp_codegen_com_handle_invalid_ipropertyarray_conversion(const char* fromArrayType, const char* fromElementType, const char* toElementType, il2cpp_array_size_t index); il2cpp_hresult_t il2cpp_codegen_com_handle_invalid_ipropertyarray_conversion(RuntimeObject* value, const char* fromArrayType, const char* fromElementType, const char* toElementType, il2cpp_array_size_t index); void il2cpp_codegen_store_exception_info(RuntimeException* ex, String_t* exceptionString); Il2CppIActivationFactory* il2cpp_codegen_windows_runtime_get_activation_factory(const il2cpp::utils::StringView<Il2CppNativeChar>& runtimeClassName); // delegate Il2CppAsyncResult* il2cpp_codegen_delegate_begin_invoke(RuntimeDelegate* delegate, void** params, RuntimeDelegate* asyncCallback, RuntimeObject* state); RuntimeObject* il2cpp_codegen_delegate_end_invoke(Il2CppAsyncResult* asyncResult, void **out_args); #if !IL2CPP_TINY inline bool il2cpp_codegen_delegate_has_invoker(Il2CppDelegate* delegate) { return delegate->invoke_impl != NULL; } #endif inline const Il2CppGenericInst* il2cpp_codegen_get_generic_class_inst(RuntimeClass* genericClass) { IL2CPP_ASSERT(genericClass->generic_class); return genericClass->generic_class->context.class_inst; } RuntimeClass* il2cpp_codegen_inflate_generic_class(RuntimeClass* genericClassDefinition, const Il2CppGenericInst* genericInst); inline void* il2cpp_codegen_static_fields_for(RuntimeClass* klass) { return klass->static_fields; } inline Il2CppMethodPointer il2cpp_codegen_get_method_pointer(const RuntimeMethod* method) { return method->methodPointer; } inline const RuntimeType* il2cpp_codegen_method_return_type(const RuntimeMethod* method) { return method->return_type; } inline int il2cpp_codegen_method_parameter_count(const RuntimeMethod* method) { return method->parameters_count; } inline bool il2cpp_codegen_is_import_or_windows_runtime(const RuntimeObject *object) { return object->klass->is_import_or_windows_runtime; } inline intptr_t il2cpp_codegen_get_com_interface_for_object(Il2CppObject* object, Type_t* type) { return il2cpp::icalls::mscorlib::System::Runtime::InteropServices::Marshal::GetCCW(object, reinterpret_cast<Il2CppReflectionType*>(type)); } NORETURN void il2cpp_codegen_raise_profile_exception(const RuntimeMethod* method); const char* il2cpp_codegen_get_field_data(RuntimeField* field); #if IL2CPP_TINY // Add intrinsics used by Tiny. #include "utils/MemoryUtils.h" Type_t* il2cpp_codegen_get_type(Il2CppObject* obj); inline int32_t il2cpp_codegen_get_array_length(Il2CppArray* szArray) { return static_cast<int32_t>(szArray->max_length); } inline int32_t il2cpp_codegen_get_array_length(Il2CppArray* genArray, int32_t dimension) { return static_cast<int32_t>(genArray->bounds[dimension].length); } MulticastDelegate_t* il2cpp_codegen_create_combined_delegate(Type_t* type, Il2CppArray* delegates, int delegateCount); inline int il2cpp_codegen_get_offset_to_string_data() { return offsetof(Il2CppString, chars); } inline String_t* il2cpp_codegen_marshal_ptr_to_string_ansi(intptr_t ptr) { return il2cpp_codegen_marshal_string_result(reinterpret_cast<const char*>(ptr)); } inline intptr_t il2cpp_codegen_marshal_string_to_co_task_mem_ansi(String_t* ptr) { return reinterpret_cast<intptr_t>(il2cpp_codegen_marshal_string(ptr)); } inline void il2cpp_codegen_marshal_string_free_co_task_mem(intptr_t ptr) { il2cpp_codegen_marshal_free(reinterpret_cast<void*>(ptr)); } struct Delegate_t; inline intptr_t il2cpp_codegen_marshal_get_function_pointer_for_delegate(const Delegate_t* d) { return reinterpret_cast<intptr_t>(reinterpret_cast<const Il2CppDelegate*>(d)->m_ReversePInvokeWrapperPtr); } inline String_t* il2cpp_codegen_string_new_from_char_array(Il2CppArray* characterArray, size_t startIndex, size_t length) { il2cpp_array_size_t arraySize = characterArray->max_length; if (startIndex + length > arraySize || startIndex < 0) il2cpp_codegen_raise_exception(NULL); return il2cpp_codegen_string_new_utf16(il2cpp::utils::StringView<Il2CppChar>(reinterpret_cast<Il2CppChar*>(characterArray + 1), startIndex, length)); } inline String_t* il2cpp_codegen_string_new_length(int length) { return reinterpret_cast<String_t*>(il2cpp::vm::String::NewSize(length)); } Type_t* il2cpp_codegen_get_base_type(const Type_t* t); Type_t* il2cpp_codegen_get_type_from_handle(intptr_t handle); bool il2cpp_codegen_is_assignable_from(Type_t* left, Type_t* right); template<typename T> struct Il2CppReversePInvokeMethodHolder { Il2CppReversePInvokeMethodHolder(T** storageAddress) : m_LastValue(*storageAddress), m_StorageAddress(storageAddress) { } ~Il2CppReversePInvokeMethodHolder() { *m_StorageAddress = m_LastValue; } private: T* const m_LastValue; T** const m_StorageAddress; }; void il2cpp_codegen_no_reverse_pinvoke_wrapper(const char* methodName, const char* reason); #endif
googlecreativelab/lines-of-play
Builds/iOS/linesofplay/Libraries/libil2cpp/include/codegen/il2cpp-codegen-il2cpp.h
C
apache-2.0
32,681
"use strict"; var chai = require('chai'); var expect = chai.expect; describe('templates with boolean, 0, or "" default values', function () { var bbj2j = require('../index'); var j2j = bbj2j.instance(); it('default: false', function () { var template = { content: { id: { dataKey: 'id', default: 'unknown' }, boolVal: { dataKey: 'boolVal', default: false } } }; var r = j2j.run(template, { id: 'test' }); expect(r).to.deep.equal({ id: 'test', boolVal: false }); }); it('default: true', function () { var template = { content: { id: { dataKey: 'id', default: 'unknown' }, boolVal: { dataKey: 'boolVal', default: true } } }; var r = j2j.run(template, { id: 'test' }); expect(r).to.deep.equal({ id: 'test', boolVal: true }); }); it('default: 0', function () { var template = { content: { id: { dataKey: 'id', default: 'unknown' }, boolVal: { dataKey: 'boolVal', default: 0 } } }; var r = j2j.run(template, { id: 'test' }); expect(r).to.deep.equal({ id: 'test', boolVal: 0 }); }); it('default: ""', function () { var template = { content: { id: { dataKey: 'id', default: 'unknown' }, boolVal: { dataKey: 'boolVal', default: "" } } }; var r = j2j.run(template, { id: 'test' }); expect(r).to.deep.equal({ id: 'test', boolVal: "" }); }); });
amida-tech/jsonapter
test/test-boolean-default.js
JavaScript
apache-2.0
2,298
/* * Copyright 2012-2013 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.slc.sli.ingestion.transformation; import java.util.List; import com.mongodb.BasicDBObject; import org.mockito.ArgumentMatcher; import org.springframework.data.mongodb.core.query.Query; /** * Util class for Query match * * @author slee * */ public class IsCorrectQuery extends ArgumentMatcher<Query> { private Query query; public IsCorrectQuery(Query query) { this.query = query; } @Override public boolean matches(Object argument) { if (query != null) { return matches((Query) argument); } return false; } private boolean matches(Query arg) { String queryKey; String argKey; for (String key : query.getQueryObject().keySet()) { queryKey = query.getQueryObject().get(key).getClass().getSimpleName(); argKey = arg.getQueryObject().get(key).getClass().getSimpleName(); if (!queryKey.equals(argKey)) { return false; } else if (queryKey.equals("BasicDBObject")) { BasicDBObject queryObj = (BasicDBObject) query.getQueryObject().get(key); BasicDBObject argObj = (BasicDBObject) arg.getQueryObject().get(key); // System.out.println(key); // System.out.print("\t"+queryObj); // System.out.println(" "+argObj); for (String key2 : queryObj.keySet()) { if (queryObj.get(key2).getClass() != argObj.get(key2).getClass()) { return false; } else if (key2.equals("$in")) { List<?> queryVal = (List<?>) queryObj.get(key2); List<?> argVal = (List<?>) argObj.get(key2); if (queryVal.size() != argVal.size()) { return false; } for (int i = 0; i < queryVal.size(); ++i) { if (!(queryVal.get(i).equals(argVal.get(i)))) { return false; } } return true; } } } else if (!query.getQueryObject().get(key).equals(arg.getQueryObject().get(key))) { return false; } } return true; } }
inbloom/secure-data-service
sli/ingestion/ingestion-core/src/test/java/org/slc/sli/ingestion/transformation/IsCorrectQuery.java
Java
apache-2.0
3,019
package com.planet_ink.coffee_mud.Races.interfaces; 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 2001-2016 Bo Zimmerman 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. */ /** * A, well, Race * @author Bo Zimmerman */ public interface Race extends Tickable, StatsAffecting, MsgListener, CMObject, Modifiable { /** * Return a nice, displayable name for this race * @return the races name */ @Override public String name(); /** * Which racial category this race falls in. * @return racial category */ public String racialCategory(); /** * Returns one or a combination of the Area.THEME_* * constants from the Area interface. This bitmap * then describes the types of areas, skills, and * classes which can interact. * This bitmap is also used to to tell whether * the race is available for selection by users * at char creation time, whether they can * change to this race via spells, or whether * the race is utterly unavailable to them. * @see com.planet_ink.coffee_mud.Areas.interfaces.Area * @return the availability/theme of this race */ public int availabilityCode(); /** * After a mob is set or changed to a new race, this method * should be called to finalize or initialize any settings * from this race. * The verify flag is almost always true, unless the mob * is a new player being created, in which case false is sent. * @param mob the mob or player being set to this race * @param verifyOnly true flag unless this is a new player character */ public void startRacing(MOB mob, boolean verifyOnly); /** * Will initialize a player or mobs height and weight based * on this races parameters. * @see com.planet_ink.coffee_mud.Common.interfaces.PhyStats * @param stats the PhyStats object to change * @param gender the mobs gender 'M' or 'F' */ public void setHeightWeight(PhyStats stats, char gender); /** * The minimum height of males of this race. * @return minimum height of males in inches */ public int shortestMale(); /** * The minimum height of females of this race. * @return minimum height of females in inches */ public int shortestFemale(); /** * The amount from 0-this to add to the minimum height * to achieve a random height. * @return a range of inches to add to the mimiumum height */ public int heightVariance(); /** * The lightest weight for a member of this race * @return the lightest weight for something of this race */ public int lightestWeight(); /** * The amount from 0-this to add to the minumum weight * to achieve a random weight. * @return a range of pounds to add to the minimum weight */ public int weightVariance(); /** * Returns an integer array equal in size and index to the * Race.AGE_* constants in the Race interface. Each value * in the index represents the first mudyear age of that * age category. * @see Race * @return an integer array mapping ages to age categories */ public int[] getAgingChart(); /** * A bitmap showing which on locations a member of this * race can not wear clothing, even if the members have one * or more of the required limbs. The bitmap is made from * Wearable.WORN_* constant values. * @see com.planet_ink.coffee_mud.Items.interfaces.Item * @return the illegal wear location bitmap */ public long forbiddenWornBits(); /** * Returns an array indexed by body part codes as defined by * the BODY_* constants in the Race interface. Each value is * either -1 to show that the body part does not apply, 0 to * show that the body part is not found on this race, and 1 or * more to show how many of that part this race normally has. * @return an array of body parts */ public int[] bodyMask(); /** * Converts this race to a generic race (if it isn't already) * and returns it. Returns itself if its already generic. * @return the generic race. */ public Race makeGenRace(); /** * Converts this race to a generic race (if it isn't already) * and mixes its attributes with the race passed it. A new * race ID and a new race name must also be provided. * @param race the race to use as a baseline * @param newRaceID the id of the new race * @param newRaceName the name of the new race * @return the generic race. */ public Race mixRace(Race race, String newRaceID, String newRaceName); /** * Returns a vector of Item objects representing the standard * clothing, weapons, or other objects commonly given to players * of this race just starting out. * @param myChar one who will receive the objects * @return a vector of Item objects */ public List<Item> outfit(MOB myChar); /** * Returns a description of the given mobs description, by * consulting the mobs curState().getHitPoints method. * @see com.planet_ink.coffee_mud.MOBS.interfaces.MOB#curState() * @see com.planet_ink.coffee_mud.Common.interfaces.CharState#getHitPoints() * @param viewer the mob observing the health of this one * @param mob the mob whose health to check * @return a string describing his health */ public String healthText(MOB viewer, MOB mob); /** * Returns the list of ability IDs of skills that this * race is flatly and quietly immune to, whether * malicious or not -- it just won't happen. * @return the list of Ability IDs. */ public String[] abilityImmunities(); /** * Sends back a generic mob name appropriate to a mob of this * race, at the given gender and age-group. * * @param gender the gender of the mob * @param age the age category * @return a good name */ public String makeMobName(char gender, int age); /** * Returns a Weapon object representing what a member of this * race fights with when unarmed. This method may change what it * returns on every call to mix things up a bit. * @see com.planet_ink.coffee_mud.Items.interfaces.Weapon * @return a Weapon object representing claws or teeth, etc.. */ public Weapon myNaturalWeapon(); /** * Returns resource codes of what this race can breathe as * an atmosphere. The list is guarenteed sorted. If the list * is empty, the race can breathe anything at all. * @see com.planet_ink.coffee_mud.Items.interfaces.RawMaterial * @return a list of resource codes that this race can breathe */ public int[] getBreathables(); /** * Returns a list of RawMaterial objects (usually GenFoodResource, GenLiquidResource, * or GenResource items) representing what is left over of a member of this race * after they've been butchered and cut up. * @see com.planet_ink.coffee_mud.Items.interfaces.RawMaterial * @return a list of rawmaterial objects */ public List<RawMaterial> myResources(); /** * Returns the corpse of a member of this race, populates it with the equipment of * the given mob, and places it in the given room. If the destroyBodyAfterUse returns * true, it will also populate the body with the contents of the myResources method. * @see #myResources() * @param mob the mob to use as a template for the body * @param room the room to place the corpse in * @return the corpse generated and placed in the room */ public DeadBody getCorpseContainer(MOB mob, Room room); /** * Whether this race object represents a Generic Race, or one which is modifiable by * builders at run-time. * @return whether this race is modifiable at run-time. */ public boolean isGeneric(); /** * Whether this race is usually rideable; helps determine the appropriate java class to use. * @return whether this race is generally rideable */ public boolean useRideClass(); /** * If this race is modifiable at run time, this method will return an xml document * describing the several attributes of this race. * @see #isGeneric() * @see #setRacialParms(String) * @return an xml document describing this race */ public String racialParms(); /** * If this race is modifiable at run time, this method will use the given xml document * describing the several attributes of this race to populate this races fields and attributes. * @see #isGeneric() * @see #racialParms() * @param parms an xml document describing this race */ public void setRacialParms(String parms); /** * Returns the string describing what folks see when a member of this race enters a room. * Should give an idea of the gate or walking style of this race. * @return what people see what this race enters a room */ public String arriveStr(); /** * Returns the string describing what folks see when a member of this race leaves a room. * Should give an idea of the gate or walking style of this race. * @return what people see what this race leaves a room */ public String leaveStr(); /** * This method is called whenever a player gains a level while a member of this race. If * there are any special things which need to be done to a player who gains a level, they * can be done in this method. By default, it doesn't do anything. * @param mob the mob to level up * @param gainedAbilityIDs the set of abilities/skill IDs gained during this leveling process */ public void level(MOB mob, List<String> gainedAbilityIDs); /** * Whenever a player or mob of this race gains experience, this method gets a chance * to modify the amount before the gain actually occurs. * @param host the player or mob whose race object this is * @param mob the player or mob gaining experience * @param victim if applicable, the mob or player who died to give the exp * @param amount the amount of exp on track for gaining * @return the adjusted amount of experience to gain */ public int adjustExperienceGain(MOB host, MOB mob, MOB victim, int amount); /** * Returns true if the given race is actually the same as the * current race. Usually just ID().equals(ID()), or if either * is human. Passing the race to itself in this method is a good * way to check for general fertility. * @param R the race to check * @return true if its the same as this one, false otherwise */ public boolean canBreedWith(Race R); /** * Whether this race can be associated with a character class. * @see com.planet_ink.coffee_mud.CharClasses.interfaces.CharClass * @return whether this race can have a class */ public boolean classless(); /** * Whether players of this race can be associated with an experience level. * @return whether players of this race can have a level */ public boolean leveless(); /** * Whether players of this race can gain or lose experience points. * @return whether players of this race can gain or lose experience points */ public boolean expless(); /** * Return a vector of skills, spells, and other ability ids granted to the given * mob when they are created as this race. * @see com.planet_ink.coffee_mud.Abilities.interfaces.Ability * @return a pairvector of the Ability names, and profficiencies */ public PairVector<String,Integer> culturalAbilities(); /** * Return a vector of skills, spells, and other abilities granted to the given * mob of the given mobs level. * @see com.planet_ink.coffee_mud.Abilities.interfaces.Ability * @param mob the mob to grant the abilities to * @return a vector of the Ability objects */ public SearchIDList<Ability> racialAbilities(MOB mob); /** * Return a vector of skills, spells, and other abilities granted to the given * mob of the given mobs level. This method is not functionally used because * it doesn't quite work correctly yet. * @see com.planet_ink.coffee_mud.Abilities.interfaces.Ability * @see com.planet_ink.coffee_mud.Races.interfaces.Race#numRacialEffects(MOB) * @param mob the mob to grant the abilities to * @return a vector of the Ability objects */ public ChameleonList<Ability> racialEffects(MOB mob); /** * Returns the number of racial effects elligible to the given lob. Must * faster and more efficient than getting the whole list and checking its * size. * @param mob the mob to grant the abilities to * @return number of entries in the ability object vector */ public int numRacialEffects(MOB mob); /** * Apply any affects of the given mob at the given age to the given base and/or * current char stats. * @see com.planet_ink.coffee_mud.Common.interfaces.CharState * @param mob the mob to apply changes to * @param baseStats permanent charstats changes * @param charStats temporary charstats changes */ public void agingAffects(MOB mob, CharStats baseStats, CharStats charStats); /** * Returns a list of the stat adjustments made by this race * @return a list of the stat adjustments made by this race */ public String getStatAdjDesc(); /** * Returns the adjustment to practices made by this race (or nothing) * @return the adjustment to practices made by this race (or nothing) */ public String getPracAdjDesc(); /** * Returns the adjustment to trains made by this race (or nothing) * @return the adjustment to trains made by this race (or nothing) */ public String getTrainAdjDesc(); /** * Returns the list of modifications to senses done by this race * or nothing. * @return the list of modifications to senses done by this race */ public String getSensesChgDesc(); /** * Returns the list of modifications to disposition done by this race * or nothing. * @return the list of modifications to disposition done by this race */ public String getDispositionChgDesc(); /** * Returns the list of racial abilities granted to those of this race * or nothing. * @return the list of racial abilities granted to those of this race */ public String getAbilitiesDesc(); /** * Returns the list of racial languages granted to those of this race * or nothing. * @return the list of racial languages granted to those of this race */ public String getLanguagesDesc(); /** Age constant for an infant */ public final static int AGE_INFANT=0; /** Age constant for a toddler */ public final static int AGE_TODDLER=1; /** Age constant for a child */ public final static int AGE_CHILD=2; /** Age constant for a yound adultt */ public final static int AGE_YOUNGADULT=3; /** Age constant for the mature adult */ public final static int AGE_MATURE=4; /** Age constant for the middle aged adult*/ public final static int AGE_MIDDLEAGED=5; /** Age constant for the old*/ public final static int AGE_OLD=6; /** Age constant for the very old*/ public final static int AGE_VENERABLE=7; /** Age constant for the very very old*/ public final static int AGE_ANCIENT=8; /** Constant string list for the names of the age constants, in their order of value */ public final static String[] AGE_DESCS=CMLib.lang().sessionTranslation(new String[] { "Infant","Toddler","Child","Young adult","Adult", "Mature", "Old", "Venerable", "Ancient" }); /** Age in Years constant for an immortal thing */ public final static int YEARS_AGE_LIVES_FOREVER=Integer.MAX_VALUE; /** body part constant representing antenea*/ public final static int BODY_ANTENEA=0; /** body part constant representing eyes */ public final static int BODY_EYE=1; /** body part constant representing ears*/ public final static int BODY_EAR=2; /** body part constant representing head*/ public final static int BODY_HEAD=3; /** body part constant representing neck*/ public final static int BODY_NECK=4; /** body part constant representing arm*/ public final static int BODY_ARM=5; /** body part constant representing hand*/ public final static int BODY_HAND=6; /** body part constant representing torso*/ public final static int BODY_TORSO=7; /** body part constant representing legs*/ public final static int BODY_LEG=8; /** body part constant representing feet*/ public final static int BODY_FOOT=9; /** body part constant representing noses*/ public final static int BODY_NOSE=10; /** body part constant representing gills*/ public final static int BODY_GILL=11; /** body part constant representing mouth*/ public final static int BODY_MOUTH=12; /** body part constant representing waists*/ public final static int BODY_WAIST=13; /** body part constant representing tails*/ public final static int BODY_TAIL=14; /** body part constant representing wings*/ public final static int BODY_WING=15; /** the number of body part constants*/ public final static int BODY_PARTS=16; /** constant string list naming each of the BODY_* constants in the order of their value*/ public final static String[] BODYPARTSTR= { "ANTENEA","EYE","EAR","HEAD","NECK","ARM","HAND","TORSO","LEG","FOOT", "NOSE","GILL","MOUTH","WAIST","TAIL","WING" }; /** constant hash of BODYPARTSTR */ public final static Map<Object,Integer> BODYPARTHASH=CMStrings.makeNumericHash(BODYPARTSTR); /** constant used to set and check the classless flag on generic races */ public final static int GENFLAG_NOCLASS=1; /** constant used to set and check the levelless flag on generic races */ public final static int GENFLAG_NOLEVELS=2; /** constant used to set and check the expless flag on generic races */ public final static int GENFLAG_NOEXP=4; /** constant used to set and check the charming flag on generic races */ public final static int GENFLAG_NOCHARM=8; /** constant used to set and check the fertility flag on generic races */ public final static int GENFLAG_NOFERTILE=16; /** constant string list naming each of the GENFLAG_* constants in the order of their value */ public final static String[] GENFLAG_DESCS={"CLASSLESS","LEVELLESS","EXPLESS","CHARMLESS","CHILDLESS"}; public final static Map<String,Integer> BODYPARTHASH_RL_LOWER=new SHashtable<String,Integer>(new Enumeration<Pair<String,Integer>>() { private int index = 0; private final Stack<Pair<String, Integer>> others = new Stack<Pair<String, Integer>>(); @Override public boolean hasMoreElements() { return (others.size() > 0) || (index < BODYPARTSTR.length); } @Override public Pair<String, Integer> nextElement() { if (!hasMoreElements()) throw new NoSuchElementException(); if (others.size() > 0) return others.pop(); others.push(new Pair<String, Integer>(BODYPARTSTR[index].toLowerCase(), Integer.valueOf(index))); others.push(new Pair<String, Integer>("left " + BODYPARTSTR[index].toLowerCase(), Integer.valueOf(index))); others.push(new Pair<String, Integer>("right " + BODYPARTSTR[index].toLowerCase(), Integer.valueOf(index))); index++; return others.pop(); } }); /** array mapping worn locations to body parts, indexed by body parts. */ public final static long[] BODY_WEARVECTOR= { Wearable.WORN_HEAD, // ANTENEA, having any of these removes that pos Wearable.WORN_EYES, // EYES, having any of these adds this position Wearable.WORN_EARS, // EARS, gains a wear position here for every 2 Wearable.WORN_HEAD, // HEAD, gains a wear position here for every 1 Wearable.WORN_NECK, // NECK, gains a wear position here for every 1 Wearable.WORN_ARMS, // ARMS, gains a wear position here for every 2 Wearable.WORN_HANDS, // HANDS, gains a wear position here for every 1 Wearable.WORN_TORSO, // TORSO, gains a wear position here for every 1 Wearable.WORN_LEGS, // LEGS, gains a wear position here for every 2 Wearable.WORN_FEET, // FEET, gains a wear position here for every 2 Wearable.WORN_HEAD, // NOSE, No applicable wear position for this body part Wearable.WORN_HEAD, // GILLS, No applicable wear position for this body part Wearable.WORN_MOUTH, // MOUTH, gains a wear position here for every 1 Wearable.WORN_WAIST, // WAIST, gains a wear position here for every 1 Wearable.WORN_BACK, // TAIL, having any of these removes that pos Wearable.WORN_BACK, // WINGS, having any of these removes that pos }; /** 2 dimentional array, indexed first by body_ part constant, with each row * having two values: the first being the Wearable.WORN_ location which is affected * by having or losing this body part, and then the number of such body parts * necessary to gain or lose one such wear location. A value of -1 means N/A */ public final static long[][] BODY_WEARGRID= { {Wearable.WORN_HEAD,-1}, // ANTENEA, having any of these removes that pos {Wearable.WORN_EYES,2}, // EYES, having any of these adds this position {Wearable.WORN_EARS,2}, // EARS, gains a wear position here for every 2 {Wearable.WORN_HEAD,1}, // HEAD, gains a wear position here for every 1 {Wearable.WORN_NECK,1}, // NECK, gains a wear position here for every 1 {Wearable.WORN_ARMS,2}, // ARMS, gains a wear position here for every 2 {Wearable.WORN_WIELD|Wearable.WORN_HELD|Wearable.WORN_HANDS |Wearable.WORN_LEFT_FINGER|Wearable.WORN_LEFT_WRIST |Wearable.WORN_RIGHT_FINGER|Wearable.WORN_RIGHT_WRIST,1}, // HANDS, gains a wear position here for every 1 // lots of exceptions apply to the above {Wearable.WORN_TORSO|Wearable.WORN_BACK,1}, // TORSO, gains a wear position here for every 1 {Wearable.WORN_LEGS,2}, // LEGS, gains a wear position here for every 2 {Wearable.WORN_FEET,2}, // FEET, gains a wear position here for every 2 {-1,-1}, // NOSE, No applicable wear position for this body part {-1,-1}, // GILLS, No applicable wear position for this body part {Wearable.WORN_MOUTH,1}, // MOUTH, gains a wear position here for every 1 {Wearable.WORN_WAIST,1}, // WAIST, gains a wear position here for every 1 {-1,-1}, // TAIL, having any of these removes that pos {Wearable.WORN_BACK,-1}, // WINGS, having any of these removes that pos }; }
oriontribunal/CoffeeMud
com/planet_ink/coffee_mud/Races/interfaces/Race.java
Java
apache-2.0
23,377
/*! * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ body { width: 100%; height: 100%; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; color: #000; background-color: #FFFFFF; } html { width: 100%; height: 100%; } h1, h2, h3, h4, h5, h6 { margin: 0 0 35px; text-transform: uppercase; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; font-weight: 700; letter-spacing: 1px; } p { margin: 0 0 25px; font-size: 18px; line-height: 1.5; } @media(min-width:768px) { p { margin: 0 0 35px; font-size: 20px; line-height: 1.6; } } a { color: #42dca3; -webkit-transition: all .2s ease-in-out; -moz-transition: all .2s ease-in-out; transition: all .2s ease-in-out; } a:hover, a:focus { text-decoration: none; color: #1d9b6c; } .light { font-weight: 400; } .navbar-custom { margin-bottom: 0; border-bottom: 1px solid rgba(255,255,255,.3); text-transform: uppercase; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; background-color: #000000; color: #FFFFFF; } .navbar-custom .navbar-brand { font-weight: 700; } .navbar-custom .navbar-brand:focus { outline: 0; } .navbar-custom .navbar-brand .navbar-toggle { padding: 4px 6px; font-size: 16px; color: #fff; } .navbar-custom .navbar-brand .navbar-toggle:focus, .navbar-custom .navbar-brand .navbar-toggle:active { outline: 0; } .navbar-custom a { color: #FFFFFF; } .navbar-custom .nav li a { -webkit-transition: background .3s ease-in-out; -moz-transition: background .3s ease-in-out; transition: background .3s ease-in-out; } .navbar-custom .nav li a:hover { outline: 0; color: rgba(255,255,255,.8); background-color: transparent; } .navbar-custom .nav li a:focus, .navbar-custom .nav li a:active { outline: 0; background-color: transparent; } .navbar-custom .nav li.active { outline: 0; } .navbar-custom .nav li.active a { background-color: rgba(255,255,255,.3); } .navbar-custom .nav li.active a:hover { color: #fff; } @media(min-width:768px) { .navbar-custom { padding: 20px 0; border-bottom: 0; letter-spacing: 1px; background: 0 0; -webkit-transition: background .5s ease-in-out,padding .5s ease-in-out; -moz-transition: background .5s ease-in-out,padding .5s ease-in-out; transition: background .5s ease-in-out,padding .5s ease-in-out; } .navbar-custom.top-nav-collapse { padding: 0; border-bottom: 1px solid rgba(255,255,255,.3); background: #000; } } .intro { display: table; width: 100%; height: auto; padding: 100px 0; text-align: center; color: #fff; background: url(../img/test-bg-bw.jpg) no-repeat bottom center scroll; background-color: #FFFFFF; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; } .intro .intro-body { display: table-cell; vertical-align: middle; } .intro .intro-body .brand-heading { font-size: 30px; } .intro .intro-body .intro-text { font-size: 18px; } @media(min-width:768px) { .intro { height: 100%; padding: 0; } .intro .intro-body .brand-heading { font-size: 80px; } .intro .intro-body .intro-text { font-size: 26px; } } .btn-circle { width: 70px; height: 70px; margin-top: 15px; padding: 7px 16px; border: 2px solid #fff; border-radius: 100%!important; font-size: 40px; color: #fff; background: 0 0; -webkit-transition: background .3s ease-in-out; -moz-transition: background .3s ease-in-out; transition: background .3s ease-in-out; } .btn-circle:hover, .btn-circle:focus { outline: 0; color: #fff; background: rgba(255,255,255,.1); } .btn-circle i.animated { -webkit-transition-property: -webkit-transform; -webkit-transition-duration: 1s; -moz-transition-property: -moz-transform; -moz-transition-duration: 1s; } .btn-circle:hover i.animated { -webkit-animation-name: pulse; -moz-animation-name: pulse; -webkit-animation-duration: 1.5s; -moz-animation-duration: 1.5s; -webkit-animation-iteration-count: infinite; -moz-animation-iteration-count: infinite; -webkit-animation-timing-function: linear; -moz-animation-timing-function: linear; } @-webkit-keyframes pulse { 0% { -webkit-transform: scale(1); transform: scale(1); } 50% { -webkit-transform: scale(1.2); transform: scale(1.2); } 100% { -webkit-transform: scale(1); transform: scale(1); } } @-moz-keyframes pulse { 0% { -moz-transform: scale(1); transform: scale(1); } 50% { -moz-transform: scale(1.2); transform: scale(1.2); } 100% { -moz-transform: scale(1); transform: scale(1); } } .content-section { padding-top: 50px; } .get-involved-section { width: 100%; padding: 90px 0; color: #FFFFFF; background: url(../img/wasmun-mission.jpg) no-repeat center center scroll; background-color: #FFFFFF; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; } #map { width: 100%; height: 200px; margin-top: 100px; } @media(min-width:767px) { .content-section { padding-top: 100px; } .get-involved-section { padding: 100px 0; } .mission-section { padding: 100px 0; } #map { height: 400px; margin-top: 250px; } } .btn { border-radius: 0; text-transform: uppercase; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; font-weight: 400; -webkit-transition: all .3s ease-in-out; -moz-transition: all .3s ease-in-out; transition: all .3s ease-in-out; } .btn-default { border: 1px solid #42dca3; color: #42dca3; background-color: transparent; } .btn-default:hover, .btn-default:focus { border: 1px solid #42dca3; outline: 0; color: #000; background-color: #42dca3; } ul.banner-social-buttons { margin-top: 0; } @media(max-width:1199px) { ul.banner-social-buttons { margin-top: 15px; } } @media(max-width:767px) { ul.banner-social-buttons li { display: block; margin-bottom: 20px; padding: 0; } ul.banner-social-buttons li:last-child { margin-bottom: 0; } } footer { padding: 50px 0; } footer p { margin: 0; } ::-moz-selection { text-shadow: none; background: #fcfcfc; background: rgba(255,255,255,.2); } ::selection { text-shadow: none; background: #fcfcfc; background: rgba(255,255,255,.2); } img::selection { background: 0 0; } img::-moz-selection { background: 0 0; } body { webkit-tap-highlight-color: rgba(255,255,255,.2); }
Taurvi/wasmun-site
Old Code/css/grayscale.css
CSS
apache-2.0
7,232
package com.github.davidmoten.jns; public class Matrix { private final Vector row1; private final Vector row2; private final Vector row3; public Matrix(Vector row1, Vector row2, Vector row3) { this.row1 = row1; this.row2 = row2; this.row3 = row3; } public Vector times(Vector v) { return Vector.create(row1.dotProduct(v), row2.dotProduct(v), row3.dotProduct(v)); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Matrix ["); builder.append("\n"); builder.append(row1); builder.append("\n"); builder.append(row2); builder.append("\n"); builder.append(row3); builder.append("]"); return builder.toString(); } }
davidmoten/jns
src/main/java/com/github/davidmoten/jns/Matrix.java
Java
apache-2.0
817
// [[[[INFO> // Copyright 2015 Epicycle (http://epicycle.org, https://github.com/open-epicycle) // // 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. // // For more information check https://github.com/open-epicycle/Epicycle.Math-cs // ]]]] using System.Linq; namespace Epicycle.Math.Geometry { using System; public static class Box2Utils { public static Vector2 Corner(this Box2 @this, Interval.EndType end) { switch (end) { case Interval.EndType.Min: return @this.MinCorner; case Interval.EndType.Max: return @this.MaxCorner; default: throw new ArgumentOutOfRangeException("end", end, "Illegal EndType " + end.ToString()); } } public static Interval Range(this Box2 @this, Vector2.Axis axis) { switch (axis) { case Vector2.Axis.X: return @this.XRange; case Vector2.Axis.Y: return @this.YRange; default: throw new ArgumentOutOfRangeException("Invalid 2D axis " + axis.ToString()); } } public static bool Contains(this Box2 @this, Box2 that) { return @this.MinX <= that.MinX && @this.MinY <= that.MinY && @this.MaxX >= that.MaxX && @this.MaxY >= that.MaxY; } public static Vector2 ToBoxCoords(this Vector2 v, Box2 box) { return new Vector2((v.X - box.MinX) / box.Width, (v.Y - box.MinY) / box.Height); } public static Vector2 FromBoxCoords(this Vector2 v, Box2 box) { return new Vector2(box.MinX + box.Width * v.X, box.MinY + box.Height * v.Y); } public static bool IsOnPositiveSide(this Box2 @this, Line2 line) { return @this.Vertices.All(v => v.IsOnPositiveSide(line)); } public static bool IsOnNegativeSide(this Box2 @this, Line2 line) { return @this.Vertices.All(v => !v.IsOnPositiveSide(line)); } public static double DistanceTo(this Vector2 @this, Box2 box) { return Math.Sqrt(box.Distance2(@this)); } public sealed class YamlSerialization { public Vector2Utils.YamlSerialization MinCorner { get; set; } public Vector2Utils.YamlSerialization Dimensions { get; set; } public YamlSerialization() { } public YamlSerialization(Box2 box2) { MinCorner = new Vector2Utils.YamlSerialization(box2.MinCorner); Dimensions = new Vector2Utils.YamlSerialization(box2.Dimensions); } public Box2 Deserialize() { return new Box2(MinCorner.Deserialize(), Dimensions.Deserialize()); } } } }
open-epicycle/Epicycle.Math-cs
projects/Epicycle.Math_cs/Geometry/Box2Utils.cs
C#
apache-2.0
3,527
// Copyright ©2017 Black Sphere Studios #ifndef __ZLIBSTREAM_H__UPATCH__ #define __ZLIBSTREAM_H__UPATCH__ #include "bss-util/stream.h" #include "zlib.h" #include <istream> #include <ostream> namespace upatch { struct InstallPayload; class ZLibStream : public bss::StreamBufFunction { inline ZLibStream(const ZLibStream& copy) BSS_DELETEFUNC inline ZLibStream& operator =(const ZLibStream& right) BSS_DELETEFUNCOP public: inline ZLibStream(ZLibStream&& mov) : StreamBufFunction(std::move(mov)) {} ZLibStream(std::istream& in, size_t bufsize = DEFAULTBUFSIZE); ZLibStream(std::ostream& out, int level = -1, size_t bufsize = DEFAULTBUFSIZE); ~ZLibStream(); protected: virtual void _onwrite() override; virtual void _onread() override; char* _icur; char* _iend; z_stream strm; }; } #endif
Black-Sphere-Studios/upatch
uPatch/ZLibStream.h
C
apache-2.0
850
########################################################################### # # Library: MSVTK # # Copyright (c) Kitware Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0.txt # # 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. # ########################################################################### ################################################################################ # # Program: 3D Slicer # # Copyright (c) Kitware Inc. # # See COPYRIGHT.txt # or http://www.slicer.org/copyright/copyright.txt for details. # # 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. # # This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc. # and was partially funded by NIH grant 3P41RR013218-12S1 # ################################################################################ # # The module defines the following variables: # GIT_EXECUTABLE - path to git command line client # GIT_FOUND - true if the command line client was found # # If the command line client executable is found the macro # GIT_WC_INFO(<dir> <var-prefix>) # is defined to extract information of a git working copy at # a given location. # # The macro defines the following variables: # <var-prefix>_WC_REVISION_HASH - Current SHA1 hash # <var-prefix>_WC_REVISION - Current SHA1 hash # <var-prefix>_WC_REVISION_NAME - Name associated with <var-prefix>_WC_REVISION_HASH # <var-prefix>_WC_URL - output of command `git config --get remote.origin.url' # <var-prefix>_WC_ROOT - Same value as working copy URL # <var-prefix>_WC_GITSVN - Set to false # # ... and also the following ones if it's a git-svn repository: # <var-prefix>_WC_GITSVN - Set to True if it is a # <var-prefix>_WC_INFO - output of command `git svn info' # <var-prefix>_WC_URL - url of the associated SVN repository # <var-prefix>_WC_ROOT - root url of the associated SVN repository # <var-prefix>_WC_REVISION - current SVN revision number # <var-prefix>_WC_LAST_CHANGED_AUTHOR - author of last commit # <var-prefix>_WC_LAST_CHANGED_DATE - date of last commit # <var-prefix>_WC_LAST_CHANGED_REV - revision of last commit # <var-prefix>_WC_LAST_CHANGED_LOG - last log of base revision # # Example usage: # find_package(Git) # if(GIT_FOUND) # GIT_WC_INFO(${PROJECT_SOURCE_DIR} Project) # message("Current revision is ${Project_WC_REVISION_HASH}") # message("git found: ${GIT_EXECUTABLE}") # endif() # # Look for 'git' or 'eg' (easy git) # set(git_names git eg) # Prefer .cmd variants on Windows unless running in a Makefile # in the MSYS shell. # if(WIN32) if(NOT CMAKE_GENERATOR MATCHES "MSYS") # Note: Due to a bug in 'git.cmd' preventing it from returning the exit code of 'git', # we excluded it from the list of executables to search. # See http://code.google.com/p/msysgit/issues/detail?id=428 # TODO Check if 'git' exists, get the associated version, if the corresponding version # is known to have a working version of 'git.cmd', use it. set(git_names git eg.cmd eg) endif() endif() find_program(GIT_EXECUTABLE ${git_names} PATHS "C:/Program Files/Git/bin" "C:/Program Files (x86)/Git/bin" DOC "git command line client") mark_as_advanced(GIT_EXECUTABLE) if(GIT_EXECUTABLE) #! \brief Extract information of a git working copy at a given location macro(GIT_WC_INFO dir prefix) execute_process(COMMAND ${GIT_EXECUTABLE} rev-parse --verify -q --short=7 HEAD WORKING_DIRECTORY ${dir} ERROR_VARIABLE GIT_error OUTPUT_VARIABLE ${prefix}_WC_REVISION_HASH OUTPUT_STRIP_TRAILING_WHITESPACE) set(${prefix}_WC_REVISION ${${prefix}_WC_REVISION_HASH}) if(NOT ${GIT_error} EQUAL 0) message(SEND_ERROR "Command \"${GIT_EXECUTBALE} rev-parse --verify -q --short=7 HEAD\" in directory ${dir} failed with output:\n${GIT_error}") else(NOT ${GIT_error} EQUAL 0) execute_process(COMMAND ${GIT_EXECUTABLE} name-rev ${${prefix}_WC_REVISION_HASH} WORKING_DIRECTORY ${dir} OUTPUT_VARIABLE ${prefix}_WC_REVISION_NAME OUTPUT_STRIP_TRAILING_WHITESPACE) endif(NOT ${GIT_error} EQUAL 0) execute_process(COMMAND ${GIT_EXECUTABLE} config --get remote.origin.url WORKING_DIRECTORY ${dir} OUTPUT_VARIABLE ${prefix}_WC_URL OUTPUT_STRIP_TRAILING_WHITESPACE) set(${prefix}_WC_GITSVN False) # Check if this git is likely to be a git-svn repository execute_process(COMMAND ${GIT_EXECUTABLE} config --get-regexp "^svn-remote" WORKING_DIRECTORY ${dir} OUTPUT_VARIABLE git_config_output OUTPUT_STRIP_TRAILING_WHITESPACE ) if(NOT "${git_config_output}" STREQUAL "") # In case git-svn is used, attempt to extract svn info execute_process(COMMAND ${GIT_EXECUTABLE} svn info WORKING_DIRECTORY ${dir} TIMEOUT 3 ERROR_VARIABLE git_svn_info_error OUTPUT_VARIABLE ${prefix}_WC_INFO RESULT_VARIABLE git_svn_info_result OUTPUT_STRIP_TRAILING_WHITESPACE) if(${git_svn_info_result} EQUAL 0) set(${prefix}_WC_GITSVN True) string(REGEX REPLACE "^(.*\n)?URL: ([^\n]+).*" "\\2" ${prefix}_WC_URL "${${prefix}_WC_INFO}") string(REGEX REPLACE "^(.*\n)?Revision: ([^\n]+).*" "\\2" ${prefix}_WC_REVISION "${${prefix}_WC_INFO}") string(REGEX REPLACE "^(.*\n)?Repository Root: ([^\n]+).*" "\\2" ${prefix}_WC_ROOT "${${prefix}_WC_INFO}") string(REGEX REPLACE "^(.*\n)?Last Changed Author: ([^\n]+).*" "\\2" ${prefix}_WC_LAST_CHANGED_AUTHOR "${${prefix}_WC_INFO}") string(REGEX REPLACE "^(.*\n)?Last Changed Rev: ([^\n]+).*" "\\2" ${prefix}_WC_LAST_CHANGED_REV "${${prefix}_WC_INFO}") string(REGEX REPLACE "^(.*\n)?Last Changed Date: ([^\n]+).*" "\\2" ${prefix}_WC_LAST_CHANGED_DATE "${${prefix}_WC_INFO}") endif(${git_svn_info_result} EQUAL 0) endif(NOT "${git_config_output}" STREQUAL "") # If there is no 'remote.origin', default to "NA" value and print a warning message. if(NOT ${prefix}_WC_URL) message(WARNING "No remote origin set for git repository: ${dir}" ) set( ${prefix}_WC_URL "NA" ) else() set(${prefix}_WC_ROOT ${${prefix}_WC_URL}) endif() endmacro(GIT_WC_INFO) endif(GIT_EXECUTABLE) # Handle the QUIETLY and REQUIRED arguments and set GIT_FOUND to TRUE if # all listed variables are TRUE include(FindPackageHandleStandardArgs) find_package_handle_standard_args(Git DEFAULT_MSG GIT_EXECUTABLE)
MSV-Project/MSVTK
CMake/FindGit.cmake
CMake
apache-2.0
7,231
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Reflection; using System.Xml; namespace AutoSniper.Framework.Converter { public static class DataUtility { #region 转DateTime /// <summary> /// Convert to date time /// </summary> /// <param name="timeStamp">millseconds</param> /// <returns>DateTime</returns> public static DateTime ToDateTime(this long timeStamp) { return new DateTime(1970, 1, 1).ToLocalTime().AddMilliseconds(timeStamp); } /// <summary> /// Convert to date time stamp (millseconds) /// </summary> /// <param name="dateTime"></param> /// <returns>millseconds</returns> public static long ToTimeStamp(this DateTime dateTime) { return (dateTime.ToLocalTime() - new DateTime(1970, 1, 1).ToLocalTime()).Ticks / 10000; } #endregion #region 转QueryString public static string ToQueryString(this object obj) { var list = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(s => s.GetGetMethod() != null && s.GetGetMethod().IsPublic) .Select(p => p.Name + "=" + p.GetGetMethod().Invoke(obj, null) ?? ""); return string.Join("&", list); } public static String ToQueryString(this Dictionary<String, String> dic) { return dic.Aggregate("", (current, i) => current + (i.Key + "=" + i.Value + "&")).TrimEnd('&'); } public static String ToQueryString(this NameValueCollection nv) { return String.Join("&", nv.AllKeys.Select(i => String.Format("{0}={1}", i, nv[i])).ToList()); } #endregion #region 转Dictionary /// <summary> /// Xml转Dictionary /// </summary> /// <param name="doc"></param> /// <returns></returns> public static Dictionary<String, Object> XmlToDictionary(this XmlDocument doc) { var json = JsonConvert.SerializeXmlNode(doc); return JsonConvert.DeserializeObject<Dictionary<String, Object>>(json); } /// <param name="nvc"></param> /// <param name="handleMultipleValuesPerKey">处理重复Key的方式</param> /// <returns></returns> public static Dictionary<String, String> ToDictionary(this NameValueCollection nvc, bool handleMultipleValuesPerKey) { var result = new Dictionary<String, String>(); foreach (String key in nvc.Keys) { if (handleMultipleValuesPerKey) { String[] values = nvc.GetValues(key); if (values != null && values.Length == 1) { result.Add(key, values[0]); } else { result.Add(key, values.ToString()); } } else { result.Add(key, nvc[key]); } } return result; } #endregion /// <summary> /// 枚举转List /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static List<string> ToList<T>() { return Enum.GetValues(typeof(T)).Cast<T>().Select(m => Enum.GetName(typeof(T), m)).ToList(); } /// <summary> /// 将小数值按指定的小数位数截断 /// </summary> /// <param name="d">要截断的小数</param> /// <param name="s">小数位数,s大于等于0,小于等于28</param> /// <returns></returns> public static decimal ToFixed(this decimal d, int s) { decimal sp = Convert.ToDecimal(Math.Pow(10, s)); if (d < 0) return Math.Truncate(d) + Math.Ceiling((d - Math.Truncate(d)) * sp) / sp; else return Math.Truncate(d) + Math.Floor((d - Math.Truncate(d)) * sp) / sp; } } }
pengpercy/AutoSniper
AutoSniper.Framework/Converter/DataUtility.cs
C#
apache-2.0
4,286
.close-item{ margin-top:-15px; } .pad { padding-bottom: 70px; } .absolute { position: absolute; top: 120px; right: 0; } .icon1-color:hover{ color:#17B12A; } .icon2-color:hover{ color:#FF123D; } .icon3-color:hover{ color:#1C5DF3; } .icon-color{ color:#FF123D; } .icon-text{ display:none; } .icon-display:hover .icon-text{ display: block; } .icon-right{ text-align:right; } .ok-item-width{ padding: 5px 8px; } .mymouse{ cursor: pointer; } .text-area-style{ margin: 1px; height: 100px; resize: none; } .text-area-width{ width: 100%; } .btn-position{ margin-left: 1250px; margin-top: 1px; } .btn2-position{ margin-top: 30px; } .btn3-position{ margin-top: 15px } .item-border-n{ border: none; } .item-padding-top-50{ padding-top: 50px; } .item-position{ position: absolute; top: 15px; right: 365px; width: 300px; height: 200px; border-style:solid; border-width: 1px; border-color: #DDD; border-radius:10px; background-color: white; z-index: 100; } .warn-item-position{ width:100%; height: 250px; border-style:solid; border-width: 1px; border-color: #DDD; border-radius:10px; background-color: white; } .warn-font-size{ font-size: 48px; text-align:center; padding-top: 40px; } .icon-padding-top{ padding-top: 6px; } .uploader-area{ border-style:solid; border-width: 1px; border-color: #DDD; border-radius:3px; background-color: white; } .item-color{ color: black; } .upload-btn-position{ top: 4px; } .upload-fixed { position: fixed; bottom: 0; right: 0px; width: 600px; z-index: 100; } .hr-width{ width: 100%; } .trash-btn-position{ top: 3px; } .icon-display-inline{ display: inline; } .items-padding{ padding: 10px; } .items-border{ border-bottom: 1px#DDD solid; } .items-font{ font-size: 16px; } .items2-padding{ padding: 6px; } .content-display-none { display:none !important; } .uploadList-display-none { display:none; } .tab-border-top{ border-radius: 4px; border-right: 1px; border-left: 1px; border-top: 1px; border-bottom: 1px; border-color: #DDD; border-style: solid; } .uploadList-position{ position: relative; } .uploadList-position-absolute{ position: absolute; width: 120px; z-index: 100; top: 50px; left: 41.0002px; } .uploadList-color:hover{ color:#ed786a; background-color:#ddd; } .tag-border{ border-radius: 4px; border-style: solid; border-width: 1px; border-color: red; color: red; } .tag-color-red{ border-color: red; color: red; } .tag-color-orange{ border-color: #ed786a; color: #ed786a; } .tag-color-purple{ border-color:purple; color:purple; } .tag-color-green{ border-color: green; color: green; } .tag-color-blue{ border-color: blue; color: blue; } .title-font-size-18px{ font-size: 18px; } .title-font-size-24px{ font-size: 24px; } .text-area-style-h25px{ margin: 1px; height: 25px; resize: none; } .padding-5px{ padding-top: 5px; padding-bottom:5px; } .border-margin-top{ margin-top: 30px; } .border-margin-top-15px{ margin-top: 15px; } .padding-top-10px{ padding-top: 10px; } .border-margin-top-25px{ margin-top: 25px; } .line-height-0{ line-height: 0; }
DelphiRace/Customers-Mana
public/include/css/file-mana.css
CSS
apache-2.0
3,203
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.apache.uima.json Class Hierarchy (Apache UIMA Java SDK 2.8.1 User-Level API Documentation)</title> <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.uima.json Class Hierarchy (Apache UIMA Java SDK 2.8.1 User-Level API Documentation)"; } //--> </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><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</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/uima/jcas/tcas/package-tree.html">Prev</a></li> <li><a href="../../../../org/apache/uima/pear/tools/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/uima/json/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.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 class="title">Hierarchy For Package org.apache.uima.json</h1> <span class="strong">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="strong">Object</span></a> <ul> <li type="circle">org.apache.uima.json.<a href="../../../../org/apache/uima/json/JsonCasSerializer.html" title="class in org.apache.uima.json"><span class="strong">JsonCasSerializer</span></a></li> <li type="circle">org.apache.uima.json.<a href="../../../../org/apache/uima/json/JsonMetaDataSerializer.html" title="class in org.apache.uima.json"><span class="strong">JsonMetaDataSerializer</span></a></li> </ul> </li> </ul> <h2 title="Enum Hierarchy">Enum Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="strong">Object</span></a> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html?is-external=true" title="class or interface in java.lang"><span class="strong">Enum</span></a>&lt;E&gt; (implements java.lang.<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html?is-external=true" title="class or interface in java.lang">Comparable</a>&lt;T&gt;, java.io.<a href="http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>) <ul> <li type="circle">org.apache.uima.json.<a href="../../../../org/apache/uima/json/JsonCasSerializer.JsonContextFormat.html" title="enum in org.apache.uima.json"><span class="strong">JsonCasSerializer.JsonContextFormat</span></a></li> </ul> </li> </ul> </li> </ul> </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><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</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/uima/jcas/tcas/package-tree.html">Prev</a></li> <li><a href="../../../../org/apache/uima/pear/tools/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/uima/json/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.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 &#169; 2006&#x2013;2015 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
TitasNandi/Summer_Project
apache-uima/docs/d/api/org/apache/uima/json/package-tree.html
HTML
apache-2.0
6,149
# AUTOGENERATED FILE FROM balenalib/apalis-imx6q-ubuntu:eoan-run ENV GO_VERSION 1.15.11 # gcc for cgo RUN apt-get update && apt-get install -y --no-install-recommends \ g++ \ gcc \ libc6-dev \ make \ pkg-config \ git \ && rm -rf /var/lib/apt/lists/* RUN set -x \ && fetchDeps=' \ curl \ ' \ && apt-get update && apt-get install -y $fetchDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \ && mkdir -p /usr/local/go \ && curl -SLO "http://resin-packages.s3.amazonaws.com/golang/v$GO_VERSION/go$GO_VERSION.linux-armv7hf.tar.gz" \ && echo "f5253eb04ed6b92e49cb0cbc57a80b4777ce27c6590e05a5c91095870e8632a0 go$GO_VERSION.linux-armv7hf.tar.gz" | sha256sum -c - \ && tar -xzf "go$GO_VERSION.linux-armv7hf.tar.gz" -C /usr/local/go --strip-components=1 \ && rm -f go$GO_VERSION.linux-armv7hf.tar.gz ENV GOROOT /usr/local/go ENV GOPATH /go ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH" WORKDIR $GOPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@golang.sh" \ && echo "Running test-stack@golang" \ && chmod +x test-stack@golang.sh \ && bash test-stack@golang.sh \ && rm -rf test-stack@golang.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu eoan \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.15.11 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
nghiant2710/base-images
balena-base-images/golang/apalis-imx6q/ubuntu/eoan/1.15.11/run/Dockerfile
Dockerfile
apache-2.0
2,354
# AUTOGENERATED FILE FROM balenalib/colibri-imx6dl-ubuntu:xenial-run ENV NODE_VERSION 15.6.0 ENV YARN_VERSION 1.22.4 RUN buildDeps='curl libatomic1' \ && set -x \ && for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends \ && rm -rf /var/lib/apt/lists/* \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && echo "234871415c54174f91764f332a72631519a6af7b1a87797ad7c729855182f9cd node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \ && echo "Running test-stack@node" \ && chmod +x test-stack@node.sh \ && bash test-stack@node.sh \ && rm -rf test-stack@node.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu xenial \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.6.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
nghiant2710/base-images
balena-base-images/node/colibri-imx6dl/ubuntu/xenial/15.6.0/run/Dockerfile
Dockerfile
apache-2.0
2,920
/* Copyright 2019 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package utils import ( "encoding/json" "fmt" "io/ioutil" "path/filepath" "strings" "github.com/containerd/cri/pkg/annotations" specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) const volumeKeyPrefix = "dev.gvisor.spec.mount." var kubeletPodsDir = "/var/lib/kubelet/pods" // volumeName gets volume name from volume annotation key, example: // dev.gvisor.spec.mount.NAME.share func volumeName(k string) string { return strings.SplitN(strings.TrimPrefix(k, volumeKeyPrefix), ".", 2)[0] } // volumeFieldName gets volume field name from volume annotation key, example: // `type` is the field of dev.gvisor.spec.mount.NAME.type func volumeFieldName(k string) string { parts := strings.Split(strings.TrimPrefix(k, volumeKeyPrefix), ".") return parts[len(parts)-1] } // podUID gets pod UID from the pod log path. func podUID(s *specs.Spec) (string, error) { sandboxLogDir := s.Annotations[annotations.SandboxLogDir] if sandboxLogDir == "" { return "", errors.New("no sandbox log path annotation") } fields := strings.Split(filepath.Base(sandboxLogDir), "_") switch len(fields) { case 1: // This is the old CRI logging path return fields[0], nil case 3: // This is the new CRI logging path return fields[2], nil } return "", errors.Errorf("unexpected sandbox log path %q", sandboxLogDir) } // isVolumeKey checks whether an annotation key is for volume. func isVolumeKey(k string) bool { return strings.HasPrefix(k, volumeKeyPrefix) } // volumeSourceKey constructs the annotation key for volume source. func volumeSourceKey(volume string) string { return volumeKeyPrefix + volume + ".source" } // volumePath searches the volume path in the kubelet pod directory. func volumePath(volume, uid string) (string, error) { // TODO: Support subpath when gvisor supports pod volume bind mount. volumeSearchPath := fmt.Sprintf("%s/%s/volumes/*/%s", kubeletPodsDir, uid, volume) dirs, err := filepath.Glob(volumeSearchPath) if err != nil { return "", err } if len(dirs) != 1 { return "", errors.Errorf("unexpected matched volume list %v", dirs) } return dirs[0], nil } // isVolumePath checks whether a string is the volume path. func isVolumePath(volume, path string) (bool, error) { // TODO: Support subpath when gvisor supports pod volume bind mount. volumeSearchPath := fmt.Sprintf("%s/*/volumes/*/%s", kubeletPodsDir, volume) return filepath.Match(volumeSearchPath, path) } // UpdateVolumeAnnotations add necessary OCI annotations for gvisor // volume optimization. func UpdateVolumeAnnotations(bundle string, s *specs.Spec) error { var ( uid string err error ) if IsSandbox(s) { uid, err = podUID(s) if err != nil { // Skip if we can't get pod UID, because this doesn't work // for containerd 1.1. logrus.WithError(err).Error("Can't get pod uid") return nil } } var updated bool for k, v := range s.Annotations { if !isVolumeKey(k) { continue } if volumeFieldName(k) != "type" { continue } volume := volumeName(k) if uid != "" { // This is a sandbox path, err := volumePath(volume, uid) if err != nil { return errors.Wrapf(err, "get volume path for %q", volume) } s.Annotations[volumeSourceKey(volume)] = path updated = true } else { // This is a container for i := range s.Mounts { // An error is returned for sandbox if source annotation // is not successfully applied, so it is guaranteed that // the source annotation for sandbox has already been // successfully applied at this point. // The volume name is unique inside a pod, so matching without // podUID is fine here. // TODO: Pass podUID down to shim for containers to do // more accurate matching. if yes, _ := isVolumePath(volume, s.Mounts[i].Source); yes { // gVisor requires the container mount type to match // sandbox mount type. s.Mounts[i].Type = v updated = true } } } } if !updated { return nil } // Update bundle b, err := json.Marshal(s) if err != nil { return err } return ioutil.WriteFile(filepath.Join(bundle, "config.json"), b, 0666) }
google/gvisor-containerd-shim
pkg/v1/utils/volumes.go
GO
apache-2.0
4,727
package com.selflearning.webdriver; import junit.framework.Assert; import org.junit.*; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriverService; import java.io.File; import java.io.IOException; /** * Created with IntelliJ IDEA. * User: billxin * Date: 11/28/12 * Time: 8:01 PM * To change this template use File | Settings | File Templates. */ public class ChromeDriverTest { private static ChromeDriverService service; private WebDriver driver; //private String path = "C:\\Tools\\Selenium\\ChromeDriver\\chromedriver_win_23.0.1240.0\\chromedriver.exe"; private static String path = "C:\\Tools\\Selenium\\ChromeDriver\\chromedriver_win_23.0.1240.0\\chromedriver.exe"; @BeforeClass public static void createAndStartService() throws IOException { service = new ChromeDriverService.Builder().usingDriverExecutable(new File(path)).usingAnyFreePort().build(); service.start(); } /** * add comment template */ @AfterClass public static void createAndStopService() { service.stop(); } @Before public void setup() { System.setProperty("webdriver.chrome.driver", "C:\\Tools\\Selenium\\ChromeDriver\\chromedriver.exe"); //System.setProperty("webdriver.ie.driver","C:\\Tools\\Selenium\\IEDriver\\IEDriverServer.exe"); } @Test public void googleTest() { driver = new ChromeDriver(); //driver = new InternetExplorerDriver(); //driver = new FirefoxDriver(); driver.navigate().to("http://www.news.com.au"); Assert.assertTrue(driver.getTitle().contains("News.com.au | News Online from Australia and the World | NewsComAu")); driver.close(); } @After public void clear(){ driver.quit(); } //File file = new File("C:/Selenium/iexploredriver.exe"); //System.setProperty() //System.setProperty("webdriver.ie.driver", file.getAbsolutePath()); //WebDriver driver = new InternetExplorerDriver(); }
XinCai/webdriverProject
src/test/java/com/selflearning/webdriver/ChromeDriverTest.java
Java
apache-2.0
2,078
package io.quarkus.arc.test.observers.notification; import static org.junit.jupiter.api.Assertions.assertEquals; import io.quarkus.arc.Arc; import io.quarkus.arc.test.ArcTestContainer; import java.util.concurrent.atomic.AtomicInteger; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Observes; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class ObserverNotificationTest { @RegisterExtension public ArcTestContainer container = new ArcTestContainer(StringObserver.class); @Test public void testContextualInstanceIsUsed() { assertEquals(0, StringObserver.CONSTRUCTED.get()); assertEquals(0, StringObserver.NOTIFIED.get()); Arc.container().beanManager().fireEvent("hello"); assertEquals(1, StringObserver.CONSTRUCTED.get()); assertEquals(1, StringObserver.NOTIFIED.get()); } @ApplicationScoped static class StringObserver { private static final AtomicInteger CONSTRUCTED = new AtomicInteger(); private static final AtomicInteger NOTIFIED = new AtomicInteger(); StringObserver() { CONSTRUCTED.incrementAndGet(); } void observeString(@Observes String value) { NOTIFIED.incrementAndGet(); } } }
quarkusio/quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/observers/notification/ObserverNotificationTest.java
Java
apache-2.0
1,331
# Understanding and Using the App In the following we briefly describe the structure of this sample app, then provide instructions on how to use it together with some insights into the code. ### Overview The actual application is located in the [`webclient`](webclient) directory of this GitHub repositoriy. It has the following structure: * [readapp.py](webclient/readapp.py): Python script with the application code * [Procfile](webclient/Procfile): Process file which tells Bluemix / Cloud Foundry how to start the application. This is especially needed when there are several Python files. * [requirements.txt](webclient/requirements.txt): Holds the dependencies, i.e., packages that need to be installed for the application to be able to run. * [readapp.cfg](webclient/readapp.cfg): Only needed when testing locally, it holds configuration parameters for the app that else are specified through the user-provided service. * [templates](webclient/templates): Directory with HTML templates. The files are used by the app and the Flask framework to produce (render) the Web pages. * [layout.html](webclient/templates/layout.html): Common template with the general page layout. It is extended by the other templates. * [index.html](webclient/templates/index.html): Template file for the index page that displays a table with the list entries. * [new.html](webclient/templates/new.html): Template file for the page with a form to enter new list items. * [requirements.txt.db2](webclient/requirements.txt.db2): Not used, but shows a requirements.txt if DB2 or dashDB are used. * [requirements.txt.mysql](webclient/requirements.txt.mysql): Not used, but shows a requirements.txt for MySQL usage. As you noticed, most files are just for the page layout or to tell Bluemix how to set up the application. Almost all logic is in a single file. ### Using the App After we have learned about the structure of the application, we are going to take a look now at how to use it once it has been deployed. 1. First Test - Hello As a simple test that the app has been successfully deployed and is started go to its "hello" page. The URL is `http://yourAppName.eu-gb.mybluemix.net/hello` if you deployed to the London/EU-GB data center or `http://yourAppName.mybluemix.net/hello` for the US-SOUTH/NG data center. You should see the following as response. ``` Hello folks, this is Python with Flask on Bluemix! ``` The output corresponds with what we have in the [app](webclient/readapp.py) itself. When the path `/hello` is visited, the Flask framework directs the request to the code path for the "hello" route and executes the given code: ``` # Simple route to test the app. It does not use a template, just returns a string. @app.route('/hello') def hello(): return "Hello folks, this is Python with Flask on Bluemix!" ``` 2. Initialize Based on the configuration the app knows where the database is located and which database system is going to be used. As you remember, we didn't create any tables or inserted any data yet. We are going to do this as part of the initialization. Instead of `/hello` we are now going to use the `/init` path. In the app first all tables related to the model are dropped (if existing), then created. When done, a short message with a link to the index page is returned. Dropping existing tables is useful when the schema is changed as part of testing or code extensions. ``` # This is a "secret" init page that can be called to initialize an empty database # with our "readlist" table. The table structure is defined above through the model. @app.route('/init') def init(): db.drop_all() db.create_all() return 'ok, go to <a href="/">home</a>' ``` 3. Index Page The index page shows the items that have been added so far. Initially this is an empty list. If an internal server is shown it could mean that either the database has not been initialized yet (see above) or that the URL for the database server has not been configured correctly (see the [overview document](README.md)). The list is generated by SQLAlchemy by composing a query on the readlist model. All attributes should be returned, sorted by the date they were added. That list is passed as parameter to the function which renders the HTML template [`index.html`](webclient/templates/index.html). Take a look at that [template](webclient/templates/index.html) to see how the attributes are included into the output. ``` # Our title/index page shows the items on the reading list, so # we have to grab them sorted by the date they were added. @app.route('/') def index(): return render_template('index.html', items=Readlist.query.order_by(Readlist.add_date.desc()).all() ) ``` ![](https://raw.githubusercontent.com/data-henrik/Bluemix-onprem-data/master/screenshots/BMReadingListIndex.png) 4. Adding an Entry After clicking on `New Item` on the index page you get to the form shown below. Provide a short description and a link/URL to a web resource, then click `Create Item`. It will now be added to the list. Within the code the new values are taken from the input form to create a new Readlist item. It is then added and the change committed to the database. ![](https://raw.githubusercontent.com/data-henrik/Bluemix-onprem-data/master/screenshots/BMReadListNewItem.png) ### Closing Remarks Go back to the [overview document](README.md).
data-henrik/Bluemix-onprem-data
ReadingListApp.md
Markdown
apache-2.0
5,476
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #ifndef vnsw_evpn_route_hpp #define vnsw_evpn_route_hpp ////////////////////////////////////////////////////////////////// // EVPN ///////////////////////////////////////////////////////////////// class EvpnAgentRouteTable : public AgentRouteTable { public: EvpnAgentRouteTable(DB *db, const std::string &name) : AgentRouteTable(db, name) { } virtual ~EvpnAgentRouteTable() { } virtual std::string GetTableName() const {return "EvpnAgentRouteTable";} virtual Agent::RouteTableType GetTableType() const { return Agent::EVPN; } virtual void UpdateDependants(AgentRoute *entry); virtual void PreRouteDelete(AgentRoute *entry); static DBTableBase *CreateTable(DB *db, const std::string &name); //Add routines void AddReceiveRouteReq(const Peer *peer, const std::string &vrf_name, uint32_t label, const MacAddress &mac, const IpAddress &ip_addr, uint32_t ethernet_tag, const std::string &vn_name); void AddReceiveRoute(const Peer *peer, const std::string &vrf_name, uint32_t label, const MacAddress &mac, const IpAddress &ip_addr, uint32_t ethernet_tag, const std::string &vn_name); void AddLocalVmRouteReq(const Peer *peer, const std::string &vrf_name, const MacAddress &mac, const IpAddress &ip_addr, uint32_t ethernet_tag, LocalVmRoute *data); void AddLocalVmRoute(const Peer *peer, const std::string &vrf_name, const MacAddress &mac, const VmInterface *intf, const IpAddress &ip, uint32_t label, const std::string &vn_name, const SecurityGroupList &sg_id_list, const PathPreference &path_pref, uint32_t ethernet_tag); static void ResyncVmRouteReq(const Peer *peer, const string &vrf_name, const MacAddress &mac, const IpAddress &ip_addr, uint32_t ethernet_tag, AgentRouteData *data); static void AddRemoteVmRouteReq(const Peer *peer, const std::string &vrf_name, const MacAddress &mac, const IpAddress &ip_addr, uint32_t ethernet_tag, AgentRouteData *data); //Delete routines void DelLocalVmRoute(const Peer *peer, const std::string &vrf_name, const MacAddress &mac, const VmInterface *intf, const IpAddress &ip, uint32_t ethernet_tag); static void DeleteReq(const Peer *peer, const std::string &vrf_name, const MacAddress &mac, const IpAddress &ip_addr, uint32_t ethernet_tag); static void Delete(const Peer *peer, const std::string &vrf_name, const MacAddress &mac, const IpAddress &ip_addr, uint32_t ethernet_tag); EvpnRouteEntry *FindRoute(const MacAddress &mac, const IpAddress &ip_addr, uint32_t ethernet_tag); static EvpnRouteEntry *FindRoute(const Agent *agent, const std::string &vrf_name, const MacAddress &mac, const IpAddress &ip_addr, uint32_t ethernet_tag); private: DBTableWalker::WalkId walkid_; DISALLOW_COPY_AND_ASSIGN(EvpnAgentRouteTable); }; class EvpnRouteEntry : public AgentRoute { public: EvpnRouteEntry(VrfEntry *vrf, const MacAddress &mac, const IpAddress &ip_addr, uint32_t ethernet_tag); virtual ~EvpnRouteEntry() { } virtual int CompareTo(const Route &rhs) const; virtual std::string ToString() const; virtual void UpdateDependantRoutes() { } virtual void UpdateNH() { } virtual KeyPtr GetDBRequestKey() const; virtual void SetKey(const DBRequestKey *key); virtual const std::string GetAddressString() const { return mac_.ToString(); } virtual Agent::RouteTableType GetTableType() const { return Agent::EVPN; } virtual bool DBEntrySandesh(Sandesh *sresp, bool stale) const; virtual uint32_t GetActiveLabel() const; virtual bool RecomputeRoutePath(Agent *agent, DBTablePartition *part, AgentPath *path, AgentRouteData *data); const MacAddress &mac() const {return mac_;} const IpAddress &ip_addr() const {return ip_addr_;} const uint32_t GetVmIpPlen() const; uint32_t ethernet_tag() const {return ethernet_tag_;} private: bool FloodDhcpRequired() const; MacAddress mac_; IpAddress ip_addr_; uint32_t ethernet_tag_; DISALLOW_COPY_AND_ASSIGN(EvpnRouteEntry); }; class EvpnRouteKey : public AgentRouteKey { public: EvpnRouteKey(const Peer *peer, const std::string &vrf_name, const MacAddress &mac, const IpAddress &ip_addr, uint32_t ethernet_tag) : AgentRouteKey(peer, vrf_name), dmac_(mac), ip_addr_(ip_addr), ethernet_tag_(ethernet_tag) { } virtual ~EvpnRouteKey() { } virtual AgentRoute *AllocRouteEntry(VrfEntry *vrf, bool is_multicast) const; virtual Agent::RouteTableType GetRouteTableType() { return Agent::EVPN; } virtual std::string ToString() const; virtual EvpnRouteKey *Clone() const; const MacAddress &GetMac() const { return dmac_;} const IpAddress &ip_addr() const { return ip_addr_;} uint32_t ethernet_tag() const {return ethernet_tag_;} private: MacAddress dmac_; IpAddress ip_addr_; //ethernet_tag is the segment identifier for VXLAN. In control node its used //as a key however for forwarding only MAC is used as a key. //To handle this ethernet_tag is sent as part of key for all remote routes //which in turn is used to create a seperate path for same peer and //mac. uint32_t ethernet_tag_; DISALLOW_COPY_AND_ASSIGN(EvpnRouteKey); }; #endif // vnsw_evpn_route_hpp
srajag/contrail-controller
src/vnsw/agent/oper/evpn_route.h
C
apache-2.0
6,648
package kata.checkout; // Classical TDD Loop // // INSTRUCTIONS // // 1) Uncomment out a test and save/compile // 2) run tests; see red // 3) change the code; see green // 4) Refactor. // 5) run tests; see green // 6) goto step 1 /* (Background information for the tests.) Scan prices of As, Bs, Cs, and Ds. Item Unit Special Price Price -------------------------- A 50 3 for 130 B 30 2 for 45 C 20 D 15 */ public class CheckOutTest { // // Section 1 begins here // // @Test public void priceIsZeroWhenNoGoods() // throws Exception // { // assertEquals(0, price("")); // } // // @Test public void priceIsFiftyWhenGoodIsA() // throws Exception // { // assertEquals(50, price("A")); // } // // @Test public void priceIsEightyWhenGoodsAreAB() // throws Exception // { // assertEquals(80, price("AB")); // } // // @Test public void priceIsOneHundredFifteenWhenGoodsAreCDBA() // throws Exception // { // assertEquals(115, price("CDBA")); // } // // // Section 1 ends here // // // Section 2 begins here // // @Test public void priceIsOneHundredWhenGoodsAreAA() // throws Exception // { // assertEquals(100, price("AA")); // } // // @Test public void priceIsOneHundredThirtyWhenGoodsAreAAA() // throws Exception // { // assertEquals(130, price("AAA")); // } // // @Test public void priceIsOneHundredEightyWhenGoodsAreAAAA() // throws Exception // { // assertEquals(180, price("AAAA")); // } // // @Test public void priceIsTwoHundredThirtyWhenGoodsAreAAAAA() // throws Exception // { // assertEquals(230, price("AAAAA")); // } // // @Test public void priceIsTwoHundredSixtyWhenGoodsAreAAAAAA() // throws Exception // { // assertEquals(260, price("AAAAAA")); // } // // // Section 2 ends here // // // Section 3 begins here // // @Test public void priceIsOneHundredSixtyWhenGoodsAreAAAB() // throws Exception // { // assertEquals(160, price("AAAB")); // } // // @Test public void priceIsOneHundredSeventyFiveWhenGoodsAreAAABB() // throws Exception // { // assertEquals(175, price("AAABB")); // } // // @Test public void priceIsOneHundredNinetyWhenGoodsAreAAABBD() // throws Exception // { // assertEquals(190, price("AAABBD")); // } // // @Test public void priceIsOneHundredNinetyWhenGoodsAreDABABA() // throws Exception // { // assertEquals(190, price("DABABA")); // } // // // Section 3 ends here // // // Section 4 starts here // // @Test public void totalIncrementsAccordingToPricePlanPerScan() // throws Exception // { // // CheckOut checkout = new CheckOut(); // // assertEquals(0, checkout.total()); // // checkout.scan('A'); // assertEquals(50, checkout.total()); // // checkout.scan('B'); // assertEquals(80, checkout.total()); // // checkout.scan('A'); // assertEquals(130, checkout.total()); // // checkout.scan('A'); // assertEquals(160, checkout.total()); // // checkout.scan('B'); // assertEquals(175, checkout.total()); // } // Section 4 ends here private int price(CharSequence goods) { CheckOut checkOut = new CheckOut(); for (int i = 0; i < goods.length(); ++i) { char good = goods.charAt(i); checkOut.scan(good); } return checkOut.total(); } }
goeckeler/katas
katas/Checkout/src/test/java/kata/checkout/CheckOutTest.java
Java
apache-2.0
3,352
#!/usr/bin/env ruby require 'spec_helper' describe Puppet::Type.type(:dsc_xroute) do let :dsc_xroute do Puppet::Type.type(:dsc_xroute).new( :name => 'foo', :dsc_interfacealias => 'foo', :dsc_addressfamily => 'IPv4', :dsc_destinationprefix => 'foo', :dsc_nexthop => 'foo', ) end it 'should allow all properties to be specified' do expect { Puppet::Type.type(:dsc_xroute).new( :name => 'foo', :dsc_interfacealias => 'foo', :dsc_addressfamily => 'IPv4', :dsc_destinationprefix => 'foo', :dsc_nexthop => 'foo', :dsc_ensure => 'Present', :dsc_routemetric => 16, :dsc_publish => 'No', :dsc_preferredlifetime => '64.000', )}.to_not raise_error end it "should stringify normally" do expect(dsc_xroute.to_s).to eq("Dsc_xroute[foo]") end it 'should default to ensure => present' do expect(dsc_xroute[:ensure]).to eq :present end it 'should require that dsc_interfacealias is specified' do #dsc_xroute[:dsc_interfacealias] expect { Puppet::Type.type(:dsc_xroute).new( :name => 'foo', :dsc_addressfamily => 'IPv4', :dsc_destinationprefix => 'foo', :dsc_nexthop => 'foo', )}.to raise_error(Puppet::Error, /dsc_interfacealias is a required attribute/) end it 'should not accept array for dsc_interfacealias' do expect{dsc_xroute[:dsc_interfacealias] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_interfacealias' do expect{dsc_xroute[:dsc_interfacealias] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_interfacealias' do expect{dsc_xroute[:dsc_interfacealias] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_interfacealias' do expect{dsc_xroute[:dsc_interfacealias] = 16}.to raise_error(Puppet::ResourceError) end it 'should require that dsc_addressfamily is specified' do #dsc_xroute[:dsc_addressfamily] expect { Puppet::Type.type(:dsc_xroute).new( :name => 'foo', :dsc_interfacealias => 'foo', :dsc_destinationprefix => 'foo', :dsc_nexthop => 'foo', )}.to raise_error(Puppet::Error, /dsc_addressfamily is a required attribute/) end it 'should accept dsc_addressfamily predefined value IPv4' do dsc_xroute[:dsc_addressfamily] = 'IPv4' expect(dsc_xroute[:dsc_addressfamily]).to eq('IPv4') end it 'should accept dsc_addressfamily predefined value ipv4' do dsc_xroute[:dsc_addressfamily] = 'ipv4' expect(dsc_xroute[:dsc_addressfamily]).to eq('ipv4') end it 'should accept dsc_addressfamily predefined value IPv6' do dsc_xroute[:dsc_addressfamily] = 'IPv6' expect(dsc_xroute[:dsc_addressfamily]).to eq('IPv6') end it 'should accept dsc_addressfamily predefined value ipv6' do dsc_xroute[:dsc_addressfamily] = 'ipv6' expect(dsc_xroute[:dsc_addressfamily]).to eq('ipv6') end it 'should not accept values not equal to predefined values' do expect{dsc_xroute[:dsc_addressfamily] = 'invalid value'}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_addressfamily' do expect{dsc_xroute[:dsc_addressfamily] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_addressfamily' do expect{dsc_xroute[:dsc_addressfamily] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_addressfamily' do expect{dsc_xroute[:dsc_addressfamily] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_addressfamily' do expect{dsc_xroute[:dsc_addressfamily] = 16}.to raise_error(Puppet::ResourceError) end it 'should require that dsc_destinationprefix is specified' do #dsc_xroute[:dsc_destinationprefix] expect { Puppet::Type.type(:dsc_xroute).new( :name => 'foo', :dsc_interfacealias => 'foo', :dsc_addressfamily => 'IPv4', :dsc_nexthop => 'foo', )}.to raise_error(Puppet::Error, /dsc_destinationprefix is a required attribute/) end it 'should not accept array for dsc_destinationprefix' do expect{dsc_xroute[:dsc_destinationprefix] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_destinationprefix' do expect{dsc_xroute[:dsc_destinationprefix] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_destinationprefix' do expect{dsc_xroute[:dsc_destinationprefix] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_destinationprefix' do expect{dsc_xroute[:dsc_destinationprefix] = 16}.to raise_error(Puppet::ResourceError) end it 'should require that dsc_nexthop is specified' do #dsc_xroute[:dsc_nexthop] expect { Puppet::Type.type(:dsc_xroute).new( :name => 'foo', :dsc_interfacealias => 'foo', :dsc_addressfamily => 'IPv4', :dsc_destinationprefix => 'foo', )}.to raise_error(Puppet::Error, /dsc_nexthop is a required attribute/) end it 'should not accept array for dsc_nexthop' do expect{dsc_xroute[:dsc_nexthop] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_nexthop' do expect{dsc_xroute[:dsc_nexthop] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_nexthop' do expect{dsc_xroute[:dsc_nexthop] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_nexthop' do expect{dsc_xroute[:dsc_nexthop] = 16}.to raise_error(Puppet::ResourceError) end it 'should accept dsc_ensure predefined value Present' do dsc_xroute[:dsc_ensure] = 'Present' expect(dsc_xroute[:dsc_ensure]).to eq('Present') end it 'should accept dsc_ensure predefined value present' do dsc_xroute[:dsc_ensure] = 'present' expect(dsc_xroute[:dsc_ensure]).to eq('present') end it 'should accept dsc_ensure predefined value present and update ensure with this value (ensure end value should be a symbol)' do dsc_xroute[:dsc_ensure] = 'present' expect(dsc_xroute[:ensure]).to eq(dsc_xroute[:dsc_ensure].downcase.to_sym) end it 'should accept dsc_ensure predefined value Absent' do dsc_xroute[:dsc_ensure] = 'Absent' expect(dsc_xroute[:dsc_ensure]).to eq('Absent') end it 'should accept dsc_ensure predefined value absent' do dsc_xroute[:dsc_ensure] = 'absent' expect(dsc_xroute[:dsc_ensure]).to eq('absent') end it 'should accept dsc_ensure predefined value absent and update ensure with this value (ensure end value should be a symbol)' do dsc_xroute[:dsc_ensure] = 'absent' expect(dsc_xroute[:ensure]).to eq(dsc_xroute[:dsc_ensure].downcase.to_sym) end it 'should not accept values not equal to predefined values' do expect{dsc_xroute[:dsc_ensure] = 'invalid value'}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_ensure' do expect{dsc_xroute[:dsc_ensure] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_ensure' do expect{dsc_xroute[:dsc_ensure] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_ensure' do expect{dsc_xroute[:dsc_ensure] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_ensure' do expect{dsc_xroute[:dsc_ensure] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_routemetric' do expect{dsc_xroute[:dsc_routemetric] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_routemetric' do expect{dsc_xroute[:dsc_routemetric] = true}.to raise_error(Puppet::ResourceError) end it 'should accept uint for dsc_routemetric' do dsc_xroute[:dsc_routemetric] = 16 expect(dsc_xroute[:dsc_routemetric]).to eq(16) end it 'should not accept signed (negative) value for dsc_routemetric' do value = -16 expect(value).to be < 0 expect{dsc_xroute[:dsc_routemetric] = value}.to raise_error(Puppet::ResourceError) end it 'should accept string-like uint for dsc_routemetric' do dsc_xroute[:dsc_routemetric] = '16' expect(dsc_xroute[:dsc_routemetric]).to eq(16) end it 'should accept string-like uint for dsc_routemetric' do dsc_xroute[:dsc_routemetric] = '32' expect(dsc_xroute[:dsc_routemetric]).to eq(32) end it 'should accept string-like uint for dsc_routemetric' do dsc_xroute[:dsc_routemetric] = '64' expect(dsc_xroute[:dsc_routemetric]).to eq(64) end it 'should accept dsc_publish predefined value No' do dsc_xroute[:dsc_publish] = 'No' expect(dsc_xroute[:dsc_publish]).to eq('No') end it 'should accept dsc_publish predefined value no' do dsc_xroute[:dsc_publish] = 'no' expect(dsc_xroute[:dsc_publish]).to eq('no') end it 'should accept dsc_publish predefined value Yes' do dsc_xroute[:dsc_publish] = 'Yes' expect(dsc_xroute[:dsc_publish]).to eq('Yes') end it 'should accept dsc_publish predefined value yes' do dsc_xroute[:dsc_publish] = 'yes' expect(dsc_xroute[:dsc_publish]).to eq('yes') end it 'should accept dsc_publish predefined value Age' do dsc_xroute[:dsc_publish] = 'Age' expect(dsc_xroute[:dsc_publish]).to eq('Age') end it 'should accept dsc_publish predefined value age' do dsc_xroute[:dsc_publish] = 'age' expect(dsc_xroute[:dsc_publish]).to eq('age') end it 'should not accept values not equal to predefined values' do expect{dsc_xroute[:dsc_publish] = 'invalid value'}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_publish' do expect{dsc_xroute[:dsc_publish] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_publish' do expect{dsc_xroute[:dsc_publish] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_publish' do expect{dsc_xroute[:dsc_publish] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_publish' do expect{dsc_xroute[:dsc_publish] = 16}.to raise_error(Puppet::ResourceError) end it 'should not accept array for dsc_preferredlifetime' do expect{dsc_xroute[:dsc_preferredlifetime] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError) end it 'should not accept boolean for dsc_preferredlifetime' do expect{dsc_xroute[:dsc_preferredlifetime] = true}.to raise_error(Puppet::ResourceError) end it 'should not accept int for dsc_preferredlifetime' do expect{dsc_xroute[:dsc_preferredlifetime] = -16}.to raise_error(Puppet::ResourceError) end it 'should not accept uint for dsc_preferredlifetime' do expect{dsc_xroute[:dsc_preferredlifetime] = 16}.to raise_error(Puppet::ResourceError) end # Configuration PROVIDER TESTS describe "powershell provider tests" do it "should successfully instanciate the provider" do described_class.provider(:powershell).new(dsc_xroute) end before(:each) do @provider = described_class.provider(:powershell).new(dsc_xroute) end describe "when dscmeta_module_name existing/is defined " do it "should compute powershell dsc test script with Invoke-DscResource" do expect(@provider.ps_script_content('test')).to match(/Invoke-DscResource/) end it "should compute powershell dsc test script with method Test" do expect(@provider.ps_script_content('test')).to match(/Method\s+=\s*'test'/) end it "should compute powershell dsc set script with Invoke-DscResource" do expect(@provider.ps_script_content('set')).to match(/Invoke-DscResource/) end it "should compute powershell dsc test script with method Set" do expect(@provider.ps_script_content('set')).to match(/Method\s+=\s*'set'/) end end describe "when dsc_ensure is 'present'" do before(:each) do dsc_xroute.original_parameters[:dsc_ensure] = 'present' dsc_xroute[:dsc_ensure] = 'present' @provider = described_class.provider(:powershell).new(dsc_xroute) end it "should update :ensure to :present" do expect(dsc_xroute[:ensure]).to eq(:present) end it "should compute powershell dsc test script in which ensure value is 'present'" do expect(@provider.ps_script_content('test')).to match(/ensure = 'present'/) end it "should compute powershell dsc set script in which ensure value is 'present'" do expect(@provider.ps_script_content('set')).to match(/ensure = 'present'/) end end describe "when dsc_ensure is 'absent'" do before(:each) do dsc_xroute.original_parameters[:dsc_ensure] = 'absent' dsc_xroute[:dsc_ensure] = 'absent' @provider = described_class.provider(:powershell).new(dsc_xroute) end it "should update :ensure to :absent" do expect(dsc_xroute[:ensure]).to eq(:absent) end it "should compute powershell dsc test script in which ensure value is 'present'" do expect(@provider.ps_script_content('test')).to match(/ensure = 'present'/) end it "should compute powershell dsc set script in which ensure value is 'absent'" do expect(@provider.ps_script_content('set')).to match(/ensure = 'absent'/) end end end end
cowofevil/puppetlabs-dsc
spec/unit/puppet/type/dsc_xroute_spec.rb
Ruby
apache-2.0
13,614
/******************************************************************************* * * Copyright (C) 2015-2022 the BBoxDB project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ package org.bboxdb.tools.converter.osm.filter.multipoint; import java.util.Collection; import org.bboxdb.tools.converter.osm.filter.OSMTagEntityFilter; import org.openstreetmap.osmosis.core.domain.v0_6.Tag; public class WoodEntityFilter implements OSMTagEntityFilter { @Override public boolean match(final Collection<Tag> tags) { for(final Tag tag : tags) { if(tag.getKey().equals("natural") && tag.getValue().equals("wood")) { return true; } } return false; } @Override public boolean isMultiPointFilter() { return true; } }
jnidzwetzki/bboxdb
bboxdb-tools/src/main/java/org/bboxdb/tools/converter/osm/filter/multipoint/WoodEntityFilter.java
Java
apache-2.0
1,370
package com.xiaoleilu.hutool.db.ds.druid; import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSource; import com.xiaoleilu.hutool.db.DbUtil; import com.xiaoleilu.hutool.db.dialect.DialectFactory; import com.xiaoleilu.hutool.log.Log; import com.xiaoleilu.hutool.log.LogFactory; import com.xiaoleilu.hutool.setting.Setting; import com.xiaoleilu.hutool.util.IoUtil; import com.xiaoleilu.hutool.util.StrUtil; /** * 基于配置文件的Druid数据源 * @author Looly * */ public class SettingDruidDataSource extends DruidDataSource { private static final long serialVersionUID = 5151196020608949563L; private final static Log log = LogFactory.get(); /** 默认的Druid配置文件路径 */ public final static String DEFAULT_DRUID_CONFIG_PATH = "config/druid.setting"; /** 默认的数据库连接配置文件路径 */ public final static String DEFAULT_DB_CONFIG_PATH = "config/db.setting"; /** 默认的数据库连接驱动(MySQL) */ public final static String DEFAULT_DRIVER = DialectFactory.DRIVER_MYSQL; /*--------------------------私有变量 start-------------------------------*/ /** JDBC配置对象 */ private Setting dbSetting; private Setting druidSetting; /*--------------------------私有变量 end-------------------------------*/ /** * 构造 */ public SettingDruidDataSource() { this(null, null, null); } /** * 构造 * @param group 分组 */ public SettingDruidDataSource(String group) { this(null, null, group); } /** * 初始化数据库连接配置文件 * * @param druid_setting Druid配置文件 * @param db_setting 数据库配置文件 * @param group 分组 */ public SettingDruidDataSource(Setting druid_setting, Setting db_setting, String group) { init(druid_setting, db_setting, group); } /** * 初始化数据库连接配置文件 * * @param druidSetting Druid配置文件 * @param dbSetting 数据库配置文件 */ public void init(Setting druidSetting, Setting dbSetting, String group) { // 初始化数据库连接配置文件 this.dbSetting = dbSetting; if (this.dbSetting == null) { try { this.dbSetting = new Setting(DEFAULT_DB_CONFIG_PATH, Setting.DEFAULT_CHARSET, true); } catch (Exception e) { log.info("No default DB config file [{}] found, custom to init it.", DEFAULT_DB_CONFIG_PATH); } } // 初始化Druid配置文件 this.druidSetting = druidSetting; if (this.druidSetting == null) { try { this.druidSetting = new Setting(DEFAULT_DRUID_CONFIG_PATH, Setting.DEFAULT_CHARSET, true); } catch (Exception e) { log.info("Druid setting file [{}], custom to init it.", DEFAULT_DRUID_CONFIG_PATH); } } initDatasource(group); } /** * 初始化数据源 * * @param group 数据源分组 * @throws ConnException */ public DataSource initDatasource(String group) { if (group == null) { group = StrUtil.EMPTY; } this.setName(group); // 数据源名称为连接名称 final String jdbcUrl = this.dbSetting.getString("url", group); log.debug("JDBC url: {}", jdbcUrl); this.setDriverClassName(this.dbSetting.getStringWithDefault("driver", group, DbUtil.identifyDriver(jdbcUrl))); this.setUrl(jdbcUrl); this.setUsername(this.dbSetting.getString("user", group)); this.setPassword(this.dbSetting.getString("pass", group)); //注入连接池配置 final String dsSettingPath = this.dbSetting.getString("ds.setting.path"); if (StrUtil.isNotBlank(dsSettingPath)) { injectSetting(new Setting(dsSettingPath)); }else{ injectSetting(druidSetting); } return this; } // ------------------------------------------------------------------- Private method start private void injectSetting(Setting setting) { if(null != setting) { setting.toBean(this); } } // ------------------------------------------------------------------- Private method end @Override protected void finalize() throws Throwable { IoUtil.close(this); } }
Z-starts/hutool
src/main/java/com/xiaoleilu/hutool/db/ds/druid/SettingDruidDataSource.java
Java
apache-2.0
4,105
package com.appleframework.jms.core.consumer; /** * @author cruise.xu * */ public interface IMessageConusmer<Message> { public void onMessage(Message message); }
xushaomin/apple-jms
apple-jms-core/src/main/java/com/appleframework/jms/core/consumer/IMessageConusmer.java
Java
apache-2.0
182
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="aui-page-header-main" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="test-Test_AbaRouteValidator_14.html">Class Test_AbaRouteValidator_14</a></li> </ol></div> <h1 class="aui-h2-clover"> Test testAbaNumberCheck_30431_good </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_14.html?line=10408#src-10408" >testAbaNumberCheck_30431_good</a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:43:40 </td> <td> 0.0 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_30431_good</th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=28787#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.7352941</span>73.5% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
dcarda/aba.route.validator
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_14_testAbaNumberCheck_30431_good_m7n.html
HTML
apache-2.0
9,181
<html> <head> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <span class='rank23 23.207682162752263'>?Velva</span> <span class='rank8 8.149646173268101'>E.</span> <span class='rank27 26.846770952363187'>Rudd.</span> <span class='rank10 10.021448350169694'>U.</span> <span class='rank7 7.347299700743164'>S.</span> <span class='rank-4 -3.660633618838432'>National</span> <span class='rank16 15.862423049989623'>Museum</span> </br> <span class='rank6 6.033766030327724'>THE</span> <span class='rank5 5.23758013687111'>NEW</span> <span class='rank5 5.092407184714711'>YORK</span> <span class='rank4 4.3452095742978045'>BOTANICAL</span> <span class='rank5 4.836230413135688'>GARDEN</span> </br> <span class='rank4 3.9555862618421074'>PLANTS</span> <span class='rank6 6.171300748459634'>OF</span> <span class='rank29 28.740270262875306'>MONTSERRAT,</span> <span class='rank8 7.9420068084898565'>W.</span> <span class='rank0 0.0'>I</span> </br> <span class='rank-8 -7.6747233763154625'>January</span> </br> <span class='rank3 3.340677699866724'>1907</span> </br> <span class='rank29 29.31503654973747'>1615764</span> </br> </br></br> <strong>Legend - </strong> Level of confidence that token is an accurately-transcribed word</br> <span class='rank-13'>&nbsp;&nbsp;&nbsp;</span> extremely low <span class='rank-7'>&nbsp;&nbsp;&nbsp;</span> very low <span class='rank-1'>&nbsp;&nbsp;&nbsp;</span> low <span class='rank0'>&nbsp;&nbsp;&nbsp;</span> undetermined <span class='rank1'>&nbsp;&nbsp;&nbsp;</span> medium <span class='rank6'>&nbsp;&nbsp;&nbsp;</span> high <span class='rank16'>&nbsp;&nbsp;&nbsp;</span> very high</br> </body> </html>
idigbio-citsci-hackathon/carrotFacetNgram
carrot2-webapp-3.8.1/herballsilvertrigram/1615764.txt.html
HTML
apache-2.0
1,662
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.util.text.base; import javax.inject.Inject; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import net.sf.mmm.util.text.api.JustificationBuilder; import net.sf.mmm.util.text.impl.spring.UtilTextSpringConfig; /** * This is the test-case for {@link JustificationBuilder} configured using spring. * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.1.1 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { UtilTextSpringConfig.class }) public class JustificationBuilderSpringTest extends JustificationBuilderTest { @Inject private JustificationBuilder justificationBuilder; @Override protected JustificationBuilder getJustificationBuilder() { return this.justificationBuilder; } }
m-m-m/util
text/src/test/java/net/sf/mmm/util/text/base/JustificationBuilderSpringTest.java
Java
apache-2.0
1,052
/* * Copyright 2012-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.services.elasticbeanstalk.model.transform; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.elasticbeanstalk.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * ApplicationResourceLifecycleConfig StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ApplicationResourceLifecycleConfigStaxUnmarshaller implements Unmarshaller<ApplicationResourceLifecycleConfig, StaxUnmarshallerContext> { public ApplicationResourceLifecycleConfig unmarshall(StaxUnmarshallerContext context) throws Exception { ApplicationResourceLifecycleConfig applicationResourceLifecycleConfig = new ApplicationResourceLifecycleConfig(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return applicationResourceLifecycleConfig; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("ServiceRole", targetDepth)) { applicationResourceLifecycleConfig.setServiceRole(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("VersionLifecycleConfig", targetDepth)) { applicationResourceLifecycleConfig.setVersionLifecycleConfig(ApplicationVersionLifecycleConfigStaxUnmarshaller.getInstance().unmarshall( context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return applicationResourceLifecycleConfig; } } } } private static ApplicationResourceLifecycleConfigStaxUnmarshaller instance; public static ApplicationResourceLifecycleConfigStaxUnmarshaller getInstance() { if (instance == null) instance = new ApplicationResourceLifecycleConfigStaxUnmarshaller(); return instance; } }
dagnir/aws-sdk-java
aws-java-sdk-elasticbeanstalk/src/main/java/com/amazonaws/services/elasticbeanstalk/model/transform/ApplicationResourceLifecycleConfigStaxUnmarshaller.java
Java
apache-2.0
2,990
/* * Copyright 2014-2019 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.services.databasemigrationservice.model; import javax.annotation.Generated; /** * <p> * The storage quota has been exceeded. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class StorageQuotaExceededException extends com.amazonaws.services.databasemigrationservice.model.AWSDatabaseMigrationServiceException { private static final long serialVersionUID = 1L; /** * Constructs a new StorageQuotaExceededException with the specified error message. * * @param message * Describes the error encountered. */ public StorageQuotaExceededException(String message) { super(message); } }
jentfoo/aws-sdk-java
aws-java-sdk-dms/src/main/java/com/amazonaws/services/databasemigrationservice/model/StorageQuotaExceededException.java
Java
apache-2.0
1,270
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.sdk.trace.testbed.errorreporting; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.hamcrest.core.IsEqual.equalTo; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.StatusCode; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Scope; import io.opentelemetry.sdk.testing.junit5.OpenTelemetryExtension; import io.opentelemetry.sdk.trace.data.EventData; import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.testbed.TestUtils; import java.time.Duration; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @SuppressWarnings("FutureReturnValueIgnored") public final class ErrorReportingTest { @RegisterExtension static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); private final Tracer tracer = otelTesting.getOpenTelemetry().getTracer(ErrorReportingTest.class.getName()); private final ExecutorService executor = Executors.newCachedThreadPool(); /* Very simple error handling **/ @Test void testSimpleError() { Span span = tracer.spanBuilder("one").startSpan(); try (Scope ignored = span.makeCurrent()) { throw new RuntimeException("Invalid state"); } catch (RuntimeException e) { span.setStatus(StatusCode.ERROR); } finally { span.end(); } assertThat(Span.current()).isSameAs(Span.getInvalid()); List<SpanData> spans = otelTesting.getSpans(); assertThat(spans).hasSize(1); assertThat(spans.get(0).getStatus().getStatusCode()).isEqualTo(StatusCode.ERROR); } /* Error handling in a callback capturing/activating the Span */ @Test void testCallbackError() { Span span = tracer.spanBuilder("one").startSpan(); executor.submit( () -> { try (Scope ignored = span.makeCurrent()) { throw new RuntimeException("Invalid state"); } catch (RuntimeException exc) { span.setStatus(StatusCode.ERROR); } finally { span.end(); } }); await() .atMost(Duration.ofSeconds(5)) .until(TestUtils.finishedSpansSize(otelTesting), equalTo(1)); List<SpanData> spans = otelTesting.getSpans(); assertThat(spans).hasSize(1); assertThat(spans.get(0).getStatus().getStatusCode()).isEqualTo(StatusCode.ERROR); } /* Error handling for a max-retries task (such as url fetching). * We log the error at each retry. */ @Test void testErrorRecovery() { int maxRetries = 1; int retries = 0; Span span = tracer.spanBuilder("one").startSpan(); try (Scope ignored = span.makeCurrent()) { while (retries++ < maxRetries) { try { throw new RuntimeException("No url could be fetched"); } catch (RuntimeException exc) { span.addEvent("error"); } } } span.setStatus(StatusCode.ERROR); // Could not fetch anything. span.end(); assertThat(Span.current()).isSameAs(Span.getInvalid()); List<SpanData> spans = otelTesting.getSpans(); assertThat(spans).hasSize(1); assertThat(spans.get(0).getStatus().getStatusCode()).isEqualTo(StatusCode.ERROR); List<EventData> events = spans.get(0).getEvents(); assertThat(events).hasSize(maxRetries); assertThat("error").isEqualTo(events.get(0).getName()); } /* Error handling for a mocked layer automatically capturing/activating * the Span for a submitted Runnable. */ @Test void testInstrumentationLayer() { Span span = tracer.spanBuilder("one").startSpan(); try (Scope ignored = span.makeCurrent()) { // ScopedRunnable captures the active Span at this time. executor.submit( new ScopedRunnable( () -> { try { throw new RuntimeException("Invalid state"); } catch (RuntimeException exc) { Span.current().setStatus(StatusCode.ERROR); } finally { Span.current().end(); } }, tracer)); } await() .atMost(Duration.ofSeconds(5)) .until(TestUtils.finishedSpansSize(otelTesting), equalTo(1)); List<SpanData> spans = otelTesting.getSpans(); assertThat(spans).hasSize(1); assertThat(StatusCode.ERROR).isEqualTo(spans.get(0).getStatus().getStatusCode()); } private static class ScopedRunnable implements Runnable { Runnable runnable; Tracer tracer; Span span; private ScopedRunnable(Runnable runnable, Tracer tracer) { this.runnable = runnable; this.tracer = tracer; this.span = Span.current(); } @Override public void run() { // No error reporting is done, as we are a simple wrapper. try (Scope ignored = span.makeCurrent()) { runnable.run(); } } } }
open-telemetry/opentelemetry-java
sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/errorreporting/ErrorReportingTest.java
Java
apache-2.0
5,140
using Newtonsoft.Json; namespace CSharpTradeOffers.Community { public class Profile { public const string Type = "profileSave"; // ToDo: Better Property Names for the weblinks need to be checked with the input ids from the profile edit page [JsonProperty("weblink_1_title")] public string Weblink1Title { get; set; } [JsonProperty("weblink_1_url")] public string Weblink1Url { get; set; } [JsonProperty("weblink_2_title")] public string Weblink2Title { get; set; } [JsonProperty("weblink_2_url")] public string Weblink2Url { get; set; } [JsonProperty("weblink_3_title")] public string Weblink3Title { get; set; } [JsonProperty("weblink_3_url")] public string Weblink3Url { get; set; } [JsonProperty("personaName")] public string PersonaName { get; set; } [JsonProperty("real_name")] public string RealName { get; set; } [JsonProperty("country")] public string Country { get; set; } [JsonProperty("state")] public string State { get; set; } [JsonProperty("city")] public string City { get; set; } [JsonProperty("customURL")] public string CustomUrl { get; set; } [JsonProperty("summary")] public string Summary { get; set; } [JsonProperty("favorite_badge_badgeid")] public ulong? FavoriteBadgeBadgeId { get; set; } [JsonProperty("favorite_badge_communityitemid")] public ulong? FavoriteBadgeCommunityItemId { get; set; } [JsonProperty("primary_group_steamid")] public ulong? PrimaryGroupSteamId { get; set; } } }
FatherFoxxy/CSharpTradeOffers
CSharpTradeOffers/Community/Data Classes/Profile.cs
C#
apache-2.0
1,709
//! Tests for --unit-graph option. use cargo_test_support::project; use cargo_test_support::registry::Package; #[cargo_test] fn gated() { let p = project().file("src/lib.rs", "").build(); p.cargo("build --unit-graph") .with_status(101) .with_stderr( "\ [ERROR] the `--unit-graph` flag is unstable[..] See [..] See [..] ", ) .run(); } #[cargo_test] fn simple() { Package::new("a", "1.0.0") .dep("b", "1.0") .feature("feata", &["b/featb"]) .publish(); Package::new("b", "1.0.0") .dep("c", "1.0") .feature("featb", &["c/featc"]) .publish(); Package::new("c", "1.0.0").feature("featc", &[]).publish(); let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.1.0" [dependencies] a = "1.0" "#, ) .file("src/lib.rs", "") .build(); p.cargo("build --features a/feata --unit-graph -Zunstable-options") .masquerade_as_nightly_cargo() .with_json( r#"{ "version": 1, "units": [ { "pkg_id": "a 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "target": { "kind": [ "lib" ], "crate_types": [ "lib" ], "name": "a", "src_path": "[..]/a-1.0.0/src/lib.rs", "edition": "2015", "doctest": true }, "profile": { "name": "dev", "opt_level": "0", "lto": "false", "codegen_units": null, "debuginfo": 2, "debug_assertions": true, "overflow_checks": true, "rpath": false, "incremental": false, "panic": "unwind" }, "platform": null, "mode": "build", "features": [ "feata" ], "dependencies": [ { "index": 1, "extern_crate_name": "b", "public": false, "noprelude": false } ] }, { "pkg_id": "b 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "target": { "kind": [ "lib" ], "crate_types": [ "lib" ], "name": "b", "src_path": "[..]/b-1.0.0/src/lib.rs", "edition": "2015", "doctest": true }, "profile": { "name": "dev", "opt_level": "0", "lto": "false", "codegen_units": null, "debuginfo": 2, "debug_assertions": true, "overflow_checks": true, "rpath": false, "incremental": false, "panic": "unwind" }, "platform": null, "mode": "build", "features": [ "featb" ], "dependencies": [ { "index": 2, "extern_crate_name": "c", "public": false, "noprelude": false } ] }, { "pkg_id": "c 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "target": { "kind": [ "lib" ], "crate_types": [ "lib" ], "name": "c", "src_path": "[..]/c-1.0.0/src/lib.rs", "edition": "2015", "doctest": true }, "profile": { "name": "dev", "opt_level": "0", "lto": "false", "codegen_units": null, "debuginfo": 2, "debug_assertions": true, "overflow_checks": true, "rpath": false, "incremental": false, "panic": "unwind" }, "platform": null, "mode": "build", "features": [ "featc" ], "dependencies": [] }, { "pkg_id": "foo 0.1.0 (path+file://[..]/foo)", "target": { "kind": [ "lib" ], "crate_types": [ "lib" ], "name": "foo", "src_path": "[..]/foo/src/lib.rs", "edition": "2015", "doctest": true }, "profile": { "name": "dev", "opt_level": "0", "lto": "false", "codegen_units": null, "debuginfo": 2, "debug_assertions": true, "overflow_checks": true, "rpath": false, "incremental": false, "panic": "unwind" }, "platform": null, "mode": "build", "features": [], "dependencies": [ { "index": 0, "extern_crate_name": "a", "public": false, "noprelude": false } ] } ], "roots": [3] } "#, ) .run(); }
vojtechkral/cargo
tests/testsuite/unit_graph.rs
Rust
apache-2.0
4,630
/** * This file is part of the Nodium core package * * (c) Niko van Meurs & Sid Mijnders * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * @author Niko van Meurs <nikovanmeurs@gmail.com> */ (function (context, undefined) { /** * Returns an object based on a fully qualified classname * @param string fullyQualifiedClassName * @return mixed */ context.use = function (fullyQualifiedClassName) { var components = fullyQualifiedClassName.split('.'), parent = context, child; while (child = components.shift()) { parent = parent[child] || {}; } return parent; }; }(this));
nodium/core
js/namespace/use.js
JavaScript
apache-2.0
772
package net.webservicex; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.xml.bind.annotation.XmlSeeAlso; /** * This class was generated by Apache CXF 3.1.11 * 2017-05-09T14:33:43.429+06:00 * Generated source version: 3.1.11 * */ @WebService(targetNamespace = "http://www.webservicex.net/", name = "GeoIPServiceHttpPost") @XmlSeeAlso({ObjectFactory.class}) @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE) public interface GeoIPServiceHttpPost { /** * GeoIPService - GetGeoIP enables you to easily look up countries by IP addresses */ @WebMethod(operationName = "GetGeoIP") @WebResult(name = "GeoIP", targetNamespace = "http://www.webservicex.net/", partName = "Body") public GeoIP getGeoIP( @WebParam(partName = "IPAddress", name = "IPAddress", targetNamespace = "") java.lang.String ipAddress ); /** * GeoIPService - GetGeoIPContext enables you to easily look up countries by Context */ @WebMethod(operationName = "GetGeoIPContext") @WebResult(name = "GeoIP", targetNamespace = "http://www.webservicex.net/", partName = "Body") public GeoIP getGeoIPContext(); }
Dmitrii29/java_courses
soap-sample/src/main/java/net/webservicex/GeoIPServiceHttpPost.java
Java
apache-2.0
1,271
--[[ Author: PicoleDeLimao Date: 10.24.2016 Add modifier_tree to trees ]] LinkLuaModifier("modifier_tree", "modifiers/modifier_tree", LUA_MODIFIER_MOTION_NONE) function OnCreated(event) local caster = event.caster local ability = event.ability ability:ApplyDataDrivenModifier(caster, caster, "modifier_tree", {}) end
PicoleDeLimao/Ninpou2
game/dota_addons/ninpou2/scripts/vscripts/buildings/trees.lua
Lua
apache-2.0
325
# frozen_string_literal: true require 'rails_helper' describe BannerHelper do describe "#show_eula?" do subject { show_eula?(subdomain) } context 'press wants EULA' do let(:subdomain) { 'barpublishing' } context 'not press or monograph catalog' do before do allow(controller).to receive(:is_a?).with(PressCatalogController).and_return(false) allow(controller).to receive(:is_a?).with(MonographCatalogController).and_return(false) end it { is_expected.to be false } end context 'press catalog' do before do allow(controller).to receive(:is_a?).with(PressCatalogController).and_return(true) allow(controller).to receive(:is_a?).with(MonographCatalogController).and_return(false) end it { is_expected.to be true } end context 'monograph catalog' do before do allow(controller).to receive(:is_a?).with(PressCatalogController).and_return(false) allow(controller).to receive(:is_a?).with(MonographCatalogController).and_return(true) end it { is_expected.to be true } end end context 'press does not want EULA' do let(:subdomain) { 'blahpress' } context 'not press or monograph catalog' do before do allow(controller).to receive(:is_a?).with(PressCatalogController).and_return(false) allow(controller).to receive(:is_a?).with(MonographCatalogController).and_return(false) end it { is_expected.to be false } end context 'press catalog' do before do allow(controller).to receive(:is_a?).with(PressCatalogController).and_return(true) allow(controller).to receive(:is_a?).with(MonographCatalogController).and_return(false) end it { is_expected.to be false } end context 'monograph catalog' do before do allow(controller).to receive(:is_a?).with(PressCatalogController).and_return(false) allow(controller).to receive(:is_a?).with(MonographCatalogController).and_return(true) end it { is_expected.to be false } end end end describe "#show_acceptable_use_policy?" do subject { show_acceptable_use_policy?(subdomain) } context "a press with a custom eula does not show the default acceptable use policy" do let(:subdomain) { 'barpublishing' } context 'not press or monograph catalog' do before do allow(controller).to receive(:is_a?).with(PressCatalogController).and_return(false) allow(controller).to receive(:is_a?).with(MonographCatalogController).and_return(false) end it { is_expected.to be false } end context 'press catalog' do before do allow(controller).to receive(:is_a?).with(PressCatalogController).and_return(true) allow(controller).to receive(:is_a?).with(MonographCatalogController).and_return(false) end it { is_expected.to be false } end context 'monograph catalog' do before do allow(controller).to receive(:is_a?).with(PressCatalogController).and_return(false) allow(controller).to receive(:is_a?).with(MonographCatalogController).and_return(true) end it { is_expected.to be false } end end context 'a press without a custom eula gets the default acceptable use policy' do let(:subdomain) { 'blahpress' } context 'not press or monograph catalog' do before do allow(controller).to receive(:is_a?).with(PressCatalogController).and_return(false) allow(controller).to receive(:is_a?).with(MonographCatalogController).and_return(false) end it { is_expected.to be false } end context 'press catalog' do before do allow(controller).to receive(:is_a?).with(PressCatalogController).and_return(true) allow(controller).to receive(:is_a?).with(MonographCatalogController).and_return(false) end it { is_expected.to be true } end context 'monograph catalog' do before do allow(controller).to receive(:is_a?).with(PressCatalogController).and_return(false) allow(controller).to receive(:is_a?).with(MonographCatalogController).and_return(true) end it { is_expected.to be true } end end end end
mlibrary/heliotrope
spec/helpers/banner_helper_spec.rb
Ruby
apache-2.0
4,457
#include "recursive.hpp" #include <iostream> template <typename T> bool RecSLL<T>::del(const T& comparable) { bool found = false; if (this->head && comparable == this->head->value) { found = true; this->head = this->head->next; // Special case of the last element if (!this->head) { this->tail = this->head; // Terminal... return found; } // In case the new head is bad also... this->del(comparable); return true; } return del_int(comparable, this->head, this->tail); } template <typename T> bool RecSLL<T>::del_int(const T& comparable, std::shared_ptr<typename SinglyLinkedList<T>::element>& last, std::shared_ptr<typename SinglyLinkedList<T>::element>& curr) { if (curr) { if (comparable == curr->value) { last->next = curr->next; this->del_int(comparable, last, last->next); return true; } else { return this->del_int(comparable, curr, curr->next); } } else { // Set the tail to be sure! this->tail = last; return false; } } template <typename T> bool RecSLL<T>::contains(const T& comparable) { return this->contains_int(comparable, this->head); } template <typename T> bool RecSLL<T>::contains_int(const T& comparable, const std::shared_ptr<typename SinglyLinkedList<T>::element>& curr) { if (curr) { if (comparable == curr->value) { return true; } else { return this->contains_int(comparable, curr->next); } } else { return false; } } // So that we get the templates generated template class RecSLL<int>;
ddeflyer/CodeExamples
SLL/recursive.cpp
C++
apache-2.0
1,584
# Call vendor to add the dependencies to the classpath import vendor vendor.add('lib') # Import the Flask Framework from flask import Flask, render_template, url_for, request, jsonify app = Flask(__name__) import translate # Root directory @app.route('/') def index_route(): phrase = request.args.get("q") if not phrase: return render_template("index.html", phrase="") return render_template("index.html", phrase=phrase) @app.route("/translate") def translate_route(): phrase = request.args.get("text") fro = request.args.get("from") to = request.args.get("to") translated_text = translate.get_translation(phrase, lang=fro + "-" + to) if translated_text == None: return "Failed to translate", 404 return translated_text if __name__ == '__main__': #app.run(host="0.0.0.0") # For development app.run() # For production
PiJoules/translation
__init__.py
Python
apache-2.0
847
import contextlib from time import time from .meter import Meter from .stats import Stat from .histogram import Histogram class Timer(Stat): def __init__(self): self.count = 0 self.meter = Meter() self.histogram = Histogram() super(Timer, self).__init__() @contextlib.contextmanager def time(self): start_time = time() try: yield finally: self.update(time() - start_time) def update(self, value): self.meter.mark() self.histogram.update(value) def get_values(self): values = self.meter.get_values() values.update(self.histogram.get_values()) return values
emilssolmanis/tapes
tapes/local/timer.py
Python
apache-2.0
702
/* * (C) Copyright 2014 mjahnen <jahnen@in.tum.de> * * 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.github.mjdev.libaums.usbfileman; import com.github.mjdev.libaums.fs.UsbFile; /** * Small helper class to move files or directories to another directory. It * saves the instance to the {@link UsbFile} which shall be moved to another * place. * * @author mjahnen * */ public class MoveClipboard { private static MoveClipboard instance; private UsbFile file; private MoveClipboard() { } /** * * @return The global used instance. */ public static synchronized MoveClipboard getInstance() { if (instance == null) instance = new MoveClipboard(); return instance; } /** * * @return The file saved in the clipboard. */ public synchronized UsbFile getFile() { return file; } /** * Sets the file in the clipboard. * * @param file * The file which shall be moved. */ public synchronized void setFile(UsbFile file) { this.file = file; } }
jmue/libaums
app/src/main/java/com/github/mjdev/libaums/usbfileman/MoveClipboard.java
Java
apache-2.0
1,537
package com.google.api.ads.dfp.jaxws.v201602; import java.util.List; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; /** * * Provides methods for creating, updating and retrieving {@link ActivityGroup} objects. * <p> * An activity group contains {@link Activity} objects. Activities have a one-to-one relationship * with activity groups. Each activity can belong to only one activity group. Activity groups, * however, have a one-to-many relationship with activities, meaning each activity group can have * multiple activities. A activity group can be used to manage the activities it contains. * </p> * * * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.1 * */ @WebService(name = "ActivityGroupServiceInterface", targetNamespace = "https://www.google.com/apis/ads/publisher/v201602") @XmlSeeAlso({ ObjectFactory.class }) public interface ActivityGroupServiceInterface { /** * * Creates a new {@link ActivityGroup} objects. * * @param activityGroups the activity groups to be created. * @return the created activity groups with their IDs filled in. * * * @param activityGroups * @return * returns java.util.List<com.google.api.ads.dfp.jaxws.v201602.ActivityGroup> * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://www.google.com/apis/ads/publisher/v201602") @RequestWrapper(localName = "createActivityGroups", targetNamespace = "https://www.google.com/apis/ads/publisher/v201602", className = "com.google.api.ads.dfp.jaxws.v201602.ActivityGroupServiceInterfacecreateActivityGroups") @ResponseWrapper(localName = "createActivityGroupsResponse", targetNamespace = "https://www.google.com/apis/ads/publisher/v201602", className = "com.google.api.ads.dfp.jaxws.v201602.ActivityGroupServiceInterfacecreateActivityGroupsResponse") public List<ActivityGroup> createActivityGroups( @WebParam(name = "activityGroups", targetNamespace = "https://www.google.com/apis/ads/publisher/v201602") List<ActivityGroup> activityGroups) throws ApiException_Exception ; /** * * Gets an {@link ActivityGroupPage} of {@link ActivityGroup} objects that satisfy the given * {@link Statement#query}. The following fields are supported for filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link ActivityGroup#id}</td> * </tr> * <tr> * <td>{@code name}</td> * <td>{@link ActivityGroup#name}</td> * </tr> * <tr> * <td>{@code impressionsLookback}</td> * <td>{@link ActivityGroup#impressionsLookback}</td> * </tr> * <tr> * <td>{@code clicksLookback}</td> * <td>{@link ActivityGroup#clicksLookback}</td> * </tr> * <tr> * <td>{@code status}</td> * <td>{@link ActivityGroup#status}</td> * </tr> * </table> * * @param filterStatement a statement used to filter a set of activity groups * @return the activity groups that match the given filter * * * @param filterStatement * @return * returns com.google.api.ads.dfp.jaxws.v201602.ActivityGroupPage * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://www.google.com/apis/ads/publisher/v201602") @RequestWrapper(localName = "getActivityGroupsByStatement", targetNamespace = "https://www.google.com/apis/ads/publisher/v201602", className = "com.google.api.ads.dfp.jaxws.v201602.ActivityGroupServiceInterfacegetActivityGroupsByStatement") @ResponseWrapper(localName = "getActivityGroupsByStatementResponse", targetNamespace = "https://www.google.com/apis/ads/publisher/v201602", className = "com.google.api.ads.dfp.jaxws.v201602.ActivityGroupServiceInterfacegetActivityGroupsByStatementResponse") public ActivityGroupPage getActivityGroupsByStatement( @WebParam(name = "filterStatement", targetNamespace = "https://www.google.com/apis/ads/publisher/v201602") Statement filterStatement) throws ApiException_Exception ; /** * * Updates the specified {@link ActivityGroup} objects. * * @param activityGroups the activity groups to update. * @return the updated activity groups. * * * @param activityGroups * @return * returns java.util.List<com.google.api.ads.dfp.jaxws.v201602.ActivityGroup> * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://www.google.com/apis/ads/publisher/v201602") @RequestWrapper(localName = "updateActivityGroups", targetNamespace = "https://www.google.com/apis/ads/publisher/v201602", className = "com.google.api.ads.dfp.jaxws.v201602.ActivityGroupServiceInterfaceupdateActivityGroups") @ResponseWrapper(localName = "updateActivityGroupsResponse", targetNamespace = "https://www.google.com/apis/ads/publisher/v201602", className = "com.google.api.ads.dfp.jaxws.v201602.ActivityGroupServiceInterfaceupdateActivityGroupsResponse") public List<ActivityGroup> updateActivityGroups( @WebParam(name = "activityGroups", targetNamespace = "https://www.google.com/apis/ads/publisher/v201602") List<ActivityGroup> activityGroups) throws ApiException_Exception ; }
gawkermedia/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201602/ActivityGroupServiceInterface.java
Java
apache-2.0
6,075
/********************************************************************************** * $URL: https://source.sakaiproject.org/svn/message/tags/sakai-10.6/message-api/api/src/java/org/sakaiproject/message/api/MessageChannel.java $ * $Id: MessageChannel.java 105079 2012-02-24 23:08:11Z ottenhoff@longsight.com $ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.message.api; // import import java.util.Collection; import java.util.List; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.IdUsedException; import org.sakaiproject.exception.InUseException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.javax.Filter; import org.sakaiproject.javax.PagingPosition; import org.sakaiproject.site.api.Group; import org.w3c.dom.Element; /** * <p> * MessageChannel is the base interface for Sakai communications service message channels. Extensions to this interface configure types of communications channels (Chat, Announcements, etc.) * </p> * <p> * Channels contains collections of messages, each Message (or extension) object. Each chat channel has a unique channel id (read only), and is a Sakai Resource. * </p> * <p> * The chat channel can be asked: * <ul> * <li>for an iterator on the messages, with a filter</li> * <li>to find a specific message</li> * <li>to add a new message</li> * <li>to update an existing message</li> * <li>to remove an existing message</li> * </ul> * </p> * <p> * The chat channel can be subscribed to providing notification when: * <ul> * <li>a new message has been posted</li> * <li>a message has been changed</li> * <li>a message has been removed</li> * <li>the channel has been removed</li> * </ul> * </p> * <p> * Security on the channel include: * <ul> * <li>message.channel.read</li> * <li>message.channel.remove.any</li> * <li>message.channel.remove.own</li> * <li>message.channel.post</li> * </ul> * Security Roles for the channel include: * <ul> * <li>message.member: read, remove.own, post</li> * <li>message.administrator: chat.member, remove.any</li> * </ul> * </p> * <p> * Event handling is defined in the specific extension classes. * </p> * * @author Sakai Software Development Team */ public interface MessageChannel extends Entity { /** * Access the context of the resource. * * @return The context. */ String getContext(); /** * check permissions for getMessages() or getMessage(). * * @return true if the user is allowed to get messages from this channel, false if not. */ boolean allowGetMessages(); /** * Get the number of messages in this particular channel. * * @return The count. */ int getCount() throws PermissionException; /** * Get the number of messages in this particular channel if the filter * were applied. * * @param filter * A filtering object to accept messages, or null if no filtering is desired. * * @return The count. */ int getCount(Filter filter) throws PermissionException; /** * Return a list of all or filtered messages in the channel. The order in which the messages will be found in the iteration is by date, oldest first if ascending is true, newest first if ascending is false. * * @param filter * A filtering object to accept messages, or null if no filtering is desired. * @param ascending * Order of messages, ascending if true, descending if false * @return a list of channel Message objects or specializations of Message objects (may be empty). * @exception PermissionException * if the user does not have read permission to the channel. */ List<Message> getMessages(Filter filter, boolean ascending) throws PermissionException; /** * Return a list of all or filtered messages in the channel. The order in which the * messages will be found in the iteration is by date, oldest first if * ascending is true, newest first if ascending is false. See getMessagesSearch() * for detail on the possible differences between search and filter retrievals. * * @param filter * A filtering object to accept messages, or null if no filtering is desired. * @param ascending * Order of messages, ascending if true, descending if false * @param pages * An indication of the range of messages we are looking for * @return a list of channel Message objects or specializations of Message objects (may be empty). * @exception PermissionException * if the user does not have read permission to the channel. */ List<Message> getMessages(Filter filter, boolean ascending, PagingPosition pages) throws PermissionException; /** * Return a list of all public messages in the channel. * The order in which the messages will be found in the iteration is by date, * oldest first if ascending is true, newest first if ascending is false. * * @param filter * Optional additional filtering object to accept messages, or null * @param ascending * Order of messages, ascending if true, descending if false * @return a list of channel Message objects or specializations of Message objects (may be empty). */ List<Message> getMessagesPublic(Filter filter, boolean ascending); /** * Return a specific channel message, as specified by message name. * * @param messageId * The id of the message to get. * @return the Message that has the specified id. * @exception IdUnusedException * If this name is not a defined message in this channel. * @exception PermissionException * If the user does not have any permissions to read the message. */ Message getMessage(String messageId) throws IdUnusedException, PermissionException; /** * check permissions for editMessage() * * @param id * The message id. * @return true if the user is allowed to update the message, false if not. */ boolean allowEditMessage(String messageId); /** * Return a specific channel message, as specified by message name, locked for update. Must commitEdit() to make official, or cancelEdit() when done! * * @param messageId * The id of the message to get. * @return the Message that has the specified id. * @exception IdUnusedException * If this name is not a defined message in this channel. * @exception PermissionException * If the user does not have any permissions to edit the message. * @exception InUseException * if the message is locked for edit by someone else. */ MessageEdit editMessage(String messageId) throws IdUnusedException, PermissionException, InUseException; /** * Commit the changes made to a MessageEdit object for announcement reorder, and release the lock. The MessageEdit is disabled, and not to be used after this call. If the message is in a form that the user has no permission to store, a PermissionException is thrown, and the * edit is canceled. * * @param user * The UserEdit object to commit. */ void commitMessage_order(MessageEdit edit); /** * Commit the changes made to a MessageEdit object, and release the lock. The MessageEdit is disabled, and not to be used after this call. If the message is in a form that the user has no permission to store, a PermissionException is thrown, and the * edit is canceled. * * @param user * The UserEdit object to commit. */ void commitMessage(MessageEdit edit); /** * Commit the changes made to a MessageEdit object, and release the lock. The MessageEdit is disabled, and not to be used after this call. If the message is in a form that the user has no permission to store, a PermissionException is thrown, and the * edit is canceled. * * @param user * The UserEdit object to commit. * @param priority * The notification priority for this commit. */ void commitMessage(MessageEdit edit, int priority); /** * Commit the changes made to a MessageEdit object, and release the lock. The MessageEdit is disabled, and not to be used after this call. If the message is in a form that the user has no permission to store, a PermissionException is thrown, and the * edit is canceled. Used when a scheduled notification is made for this message. * * @param user * The UserEdit object to commit. * @param priority * The notification priority for this commit. * @param invokee * The id for the object to be called when the scheduled notification fires. */ void commitMessage(MessageEdit edit, int priority, String invokee); /** * Cancel the changes made to a MessageEdit object, and release the lock. The MessageEdit is disabled, and not to be used after this call. * * @param user * The UserEdit object to commit. */ void cancelMessage(MessageEdit edit); /** * check permissions for addMessage(). * * @return true if the user is allowed to addMessage(...), false if not. */ boolean allowAddMessage(); /** * check permission for adding draft message and modifying it afterwards. */ boolean allowAddDraftMessage(); /** * Check if the user has permission to add a channel-wide (not grouped) message. * * @return true if the user has permission to add a channel-wide (not grouped) message. */ boolean allowAddChannelMessage(); /** * Add a new message to this channel. Must commitEdit() to make official, or cancelEdit() when done! * * @return The newly added message, locked for update. * @exception PermissionException * If the user does not have write permission to the channel. */ MessageEdit addMessage() throws PermissionException; /** * check permissions for removeMessage(). * * @param message * The message from this channel to remove. * @return true if the user is allowed to removeMessage(...), false if not. */ boolean allowRemoveMessage(Message message); /** * Remove a message from the channel based on message id * * @param messageId * The messageId for the message of the channel to remove. * @exception PermissionException * if the user does not have permission to remove the message. */ void removeMessage(String messageId) throws PermissionException; /** * Remove a message from the channel - it must be locked from editMessage(). * * @param message * The message from this channel to remove. * @exception PermissionException * if the user does not have permission to remove the message. */ void removeMessage(MessageEdit message) throws PermissionException; /** * Merge in a new message as defined in the xml. Must commitEdit() to make official, or cancelEdit() when done! * * @param el * The message information in XML in a DOM element. * @return The newly added message, locked for update. * @exception PermissionException * If the user does not have write permission to the channel. * @exception IdUsedException * if the user id is already used. */ MessageEdit mergeMessage(Element el) throws PermissionException, IdUsedException; /** * Get the collection of Groups defined for the context of this channel that the end user has add message permissions in. * * @return The Collection (Group) of groups defined for the context of this channel that the end user has add message permissions in, empty if none. */ Collection<Group> getGroupsAllowAddMessage(); /** * Get the collection of Group defined for the context of this channel that the end user has get message permissions in. * * @return The Collection (Group) of groups defined for the context of this channel that the end user has get message permissions in, empty if none. */ Collection<Group> getGroupsAllowGetMessage(); /** * Get the collection of Group defined for the context of this channel that the end user has remove message permissions in. * * @param own * true if the message is the user's own, false if it is someone else's. * @return The Collection (Group) of groups defined for the context of this channel that the end user has get message permissions in, empty if none. */ Collection<Group> getGroupsAllowRemoveMessage(boolean own); }
eemirtekin/Sakai-10.6-TR
message/message-api/api/src/java/org/sakaiproject/message/api/MessageChannel.java
Java
apache-2.0
13,131
<?php /** * * @copyright Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com) */ namespace Magento\Eav\Api; interface AttributeGroupRepositoryInterface { /** * Save attribute group * * @param \Magento\Eav\Api\Data\AttributeGroupInterface $group * @return \Magento\Eav\Api\Data\AttributeGroupInterface * @throws \Magento\Framework\Exception\NoSuchEntityException * @throws \Magento\Framework\Exception\StateException */ public function save(\Magento\Eav\Api\Data\AttributeGroupInterface $group); /** * Retrieve attribute group * * @param int $groupId * @return \Magento\Eav\Api\Data\AttributeGroupInterface * @throws \Magento\Framework\Exception\NoSuchEntityException */ public function get($groupId); /** * Retrieve list of attribute groups * * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria * @return \Magento\Eav\Api\Data\AttributeGroupSearchResultsInterface * @throws \Magento\Framework\Exception\NoSuchEntityException */ public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria); /** * Remove attribute group by id * * @param int $groupId * @return bool * @throws \Magento\Framework\Exception\NoSuchEntityException * @throws \Magento\Framework\Exception\StateException */ public function deleteById($groupId); /** * Remove attribute group * * @param \Magento\Eav\Api\Data\AttributeGroupInterface $group * @return bool * @throws \Magento\Framework\Exception\NoSuchEntityException * @throws \Magento\Framework\Exception\StateException */ public function delete(\Magento\Eav\Api\Data\AttributeGroupInterface $group); }
webadvancedservicescom/magento
app/code/Magento/Eav/Api/AttributeGroupRepositoryInterface.php
PHP
apache-2.0
1,802
from hazelcast.serialization.bits import * from hazelcast.protocol.builtin import FixSizedTypesCodec from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer from hazelcast.protocol.builtin import StringCodec from hazelcast.protocol.builtin import DataCodec # hex: 0x011300 _REQUEST_MESSAGE_TYPE = 70400 # hex: 0x011301 _RESPONSE_MESSAGE_TYPE = 70401 _REQUEST_THREAD_ID_OFFSET = REQUEST_HEADER_SIZE _REQUEST_REFERENCE_ID_OFFSET = _REQUEST_THREAD_ID_OFFSET + LONG_SIZE_IN_BYTES _REQUEST_INITIAL_FRAME_SIZE = _REQUEST_REFERENCE_ID_OFFSET + LONG_SIZE_IN_BYTES def encode_request(name, key, thread_id, reference_id): buf = create_initial_buffer(_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAGE_TYPE) FixSizedTypesCodec.encode_long(buf, _REQUEST_THREAD_ID_OFFSET, thread_id) FixSizedTypesCodec.encode_long(buf, _REQUEST_REFERENCE_ID_OFFSET, reference_id) StringCodec.encode(buf, name) DataCodec.encode(buf, key, True) return OutboundMessage(buf, True)
hazelcast/hazelcast-python-client
hazelcast/protocol/codec/map_unlock_codec.py
Python
apache-2.0
1,021
/** * Copyright (C) 2010-2013 Alibaba Group Holding Limited * * 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.alibaba.rocketmq.namesrv; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import com.alibaba.rocketmq.common.MQVersion; import com.alibaba.rocketmq.common.MixAll; import com.alibaba.rocketmq.common.conflict.PackageConflictDetect; import com.alibaba.rocketmq.common.constant.LoggerName; import com.alibaba.rocketmq.common.namesrv.NamesrvConfig; import com.alibaba.rocketmq.remoting.netty.NettyServerConfig; import com.alibaba.rocketmq.remoting.netty.NettySystemConfig; import com.alibaba.rocketmq.remoting.protocol.RemotingCommand; import com.alibaba.rocketmq.srvutil.ServerUtil; /** * Name server 启动入口 * * @author shijia.wxr<vintage.wang@gmail.com> * @since 2013-7-5 */ public class NamesrvStartup { public static Properties properties = null; public static CommandLine commandLine = null; /** * Apache Commons CLI 是 Apache 下面的一个解析命令行输入的工具包 * * @param options * @return */ public static Options buildCommandlineOptions(final Options options) { Option opt = new Option("c", "configFile", true, "Name server config properties file"); opt.setRequired(false); options.addOption(opt); opt = new Option("p", "printConfigItem", false, "Print all config item"); opt.setRequired(false); options.addOption(opt); return options; } public static void main(String[] args) { main0(args); } public static NamesrvController main0(String[] args) { System.setProperty(RemotingCommand.RemotingVersionKey, Integer.toString(MQVersion.CurrentVersion)); // Socket发送缓冲区大小 if (null == System.getProperty(NettySystemConfig.SystemPropertySocketSndbufSize)) { NettySystemConfig.SocketSndbufSize = 2048; } // Socket接收缓冲区大小 if (null == System.getProperty(NettySystemConfig.SystemPropertySocketRcvbufSize)) { NettySystemConfig.SocketRcvbufSize = 1024; } try { // 检测fastjson包冲突 PackageConflictDetect.detectFastjson(); // 解析命令行 Options options = ServerUtil.buildCommandlineOptions(new Options()); commandLine = ServerUtil.parseCmdLine("mqnamesrv", args, buildCommandlineOptions(options), new PosixParser()); if (null == commandLine) { System.exit(-1); return null; } // 初始化配置文件 final NamesrvConfig namesrvConfig = new NamesrvConfig(); final NettyServerConfig nettyServerConfig = new NettyServerConfig(); nettyServerConfig.setListenPort(9876); if (commandLine.hasOption('c')) { String file = commandLine.getOptionValue('c'); if (file != null) { InputStream in = new BufferedInputStream(new FileInputStream(file)); properties = new Properties(); properties.load(in); MixAll.properties2Object(properties, namesrvConfig); MixAll.properties2Object(properties, nettyServerConfig); System.out.println("load config properties file OK, " + file); in.close(); } } // 打印默认配置 if (commandLine.hasOption('p')) { MixAll.printObjectProperties(null, namesrvConfig); MixAll.printObjectProperties(null, nettyServerConfig); System.exit(0); } MixAll.properties2Object(ServerUtil.commandLine2Properties(commandLine), namesrvConfig); if (null == namesrvConfig.getRocketmqHome()) { System.out.println("Please set the " + MixAll.ROCKETMQ_HOME_ENV + " variable in your environment to match the location of the RocketMQ installation"); System.exit(-2); } // 初始化Logback LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(namesrvConfig.getRocketmqHome() + "/conf/logback_namesrv.xml"); final Logger log = LoggerFactory.getLogger(LoggerName.NamesrvLoggerName); // 打印服务器配置参数 MixAll.printObjectProperties(log, namesrvConfig); MixAll.printObjectProperties(log, nettyServerConfig); // 初始化服务控制对象 final NamesrvController controller = new NamesrvController(namesrvConfig, nettyServerConfig); boolean initResult = controller.initialize(); if (!initResult) { controller.shutdown(); System.exit(-3); } /** * nameserver停止hook */ Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { private volatile boolean hasShutdown = false; private AtomicInteger shutdownTimes = new AtomicInteger(0); @Override public void run() { synchronized (this) { log.info("shutdown hook was invoked, " + this.shutdownTimes.incrementAndGet()); if (!this.hasShutdown) { this.hasShutdown = true; long begineTime = System.currentTimeMillis(); controller.shutdown(); long consumingTimeTotal = System.currentTimeMillis() - begineTime; log.info("shutdown hook over, consuming time total(ms): " + consumingTimeTotal); } } } }, "ShutdownHook")); // 启动服务 controller.start(); String tip = "The Name Server boot success."; log.info(tip); System.out.println(tip); return controller; } catch (Throwable e) { e.printStackTrace(); System.exit(-1); } return null; } }
liujia128/RocketMQ-Master-analyze
rocketmq-namesrv/src/main/java/com/alibaba/rocketmq/namesrv/NamesrvStartup.java
Java
apache-2.0
7,412
/**************************************************************************** * * Copyright 2016 Samsung Electronics 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. * ****************************************************************************/ /**************************************************************************** * tools/cfgdefine.h * * Copyright (C) 2007-2011 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __TOOLS_CFGDEFINE_H #define __TOOLS_CFGDEFINE_H /**************************************************************************** * Included Files ****************************************************************************/ #include <stdio.h> #include <limits.h> /**************************************************************************** * Definitions ****************************************************************************/ #define LINESIZE (PATH_MAX > 256 ? PATH_MAX : 256) /**************************************************************************** * Public Data ****************************************************************************/ extern char line[LINESIZE + 1]; /**************************************************************************** * Public Functions ****************************************************************************/ void generate_definitions(FILE *stream); #endif /* __TOOLS_CFGDEFINE_H */
tizenrt/tizen_rt
os/tools/cfgdefine.h
C
apache-2.0
3,537
/** * Copyright (C) 2015 Orange * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.francetelecom.clara.cloud.db.liquibase; import static org.junit.Assert.*; import java.sql.SQLException; import javax.sql.DataSource; import liquibase.exception.LiquibaseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.support.rowset.SqlRowSet; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * This test class verifies that some 'complex' liquibase refactoring commands work as expected * This test class shall be enhanced when more complex refactorings need to be tested */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration() public class CheckVariousRefactoringCommandsIT { @Autowired public DataSource datasource; // liquibase wrapper used to call liquibase functions private LiquibaseTestWrapper liquibaseWrapper = new LiquibaseTestWrapper(); // test db credentials used by liquibaseTestWrapper private String paasTestDbUrl; private String paasTestDbUser; private String paasTestDbPassword; // jdbcTemplate used to execute some sql requests private JdbcTemplate jdbcTemplate; // Default changelog used to set-up test data public String basicInitialChangeLofFile = "classpath:./test-changesets/initial-changeset.xml"; /** * Setup of test data: set attributes, purge and initialize test datbase */ @Before public void setup() throws SQLException, LiquibaseException { // Init jdbcTemplate this.jdbcTemplate = new JdbcTemplate(datasource); // Set test db properties DriverManagerDataSource ds = (DriverManagerDataSource)datasource; this.paasTestDbUrl = ds.getUrl(); this.paasTestDbUser = ds.getUsername(); this.paasTestDbPassword = ds.getPassword(); // purge test database liquibaseWrapper.purgeDatabase(paasTestDbUrl, paasTestDbUser, paasTestDbPassword); // init database state liquibaseWrapper.applyChangeLog(paasTestDbUrl, paasTestDbUser, paasTestDbPassword, basicInitialChangeLofFile); } /** * Test clean-up: purge test database */ @After public void teardown() throws SQLException, LiquibaseException { // purge test database liquibaseWrapper.purgeDatabase(paasTestDbUrl, paasTestDbUser, paasTestDbPassword); } /** * Given a database with a table TABLE_TEST_1 with some lines * When liquibase executes following changeset: * <renameTable oldTableName="TABLE_TEST_1" newTableName="table_test_2"/> * Then table 'TABLE_TEST_2' can be requested * And table 'TABLE_TEST_1' does not exist anymore */ @Test public void testRenameTable() throws SQLException, LiquibaseException { // Prepare test data jdbcTemplate.execute("insert into table_test_1 values (1717,'test-1717')"); // Run test applyChangeLog("classpath:./test-changesets/rename-table-changeset.xml"); // Assert table has been renamed int n = jdbcTemplate.queryForObject("select count(*) from table_test_2 where id=1717 and text='test-1717'", Integer.class); assertEquals(1,n); // And old name does not exist try { jdbcTemplate.queryForObject("select count(*) from table_test_1", Integer.class); fail("table_test_1 still exists"); } catch(DataAccessException e) { // ignore as we expect an exception } } /** * Given a database with a table TABLE_TEST_1 with some lines * When liquibase executes following changeset: * <addColumn tableName="table_test_1"> * <column name="new_data" type="varchar(255)" defaultValue="default_value_for_new_column"/> * </addColumn> * Then 'new_data' column on existing lines is 'default_value_for_new_column' */ @Test public void testNewColumnWithDefaultValue() throws SQLException, LiquibaseException { // Prepare test data jdbcTemplate.execute("insert into table_test_1 values (1717,'test-1717')"); // Run test applyChangeLog("classpath:./test-changesets/new-column-changeset.xml"); // Assert new column can be requested and has a default value int n = jdbcTemplate.queryForObject("select count(*) from table_test_1 where id=1717 and NEW_DATA='default_value_for_new_column'", Integer.class); assertEquals(1,n); } /** * Given a database with no sequence * When liquibase executes following changeset: <createSequence sequenceName="my_sequence" incrementBy="2" startValue="1"/> * Then the first value of "my_sequence" is 1 * And the next value of "my_sequence" is 3 */ @Test public void testCreateSequence() throws SQLException, LiquibaseException { // Run test applyChangeLog("classpath:./test-changesets/create-sequence-changeset.xml"); // Assert new sequence is created by requesting it twice int v1 = jdbcTemplate.queryForObject("select nextval('my_sequence')", Integer.class); assertEquals(1,v1); int v2 = jdbcTemplate.queryForObject("select nextval('my_sequence')", Integer.class); assertEquals(3,v2); } /** * This test verifies a pattern to fix art #95049 * Given a database in which a changeset adding a not nullable column has been commited without defining a default value * And they are some data in the updated table * When liquibase applies a similar changeset that defines a default value * Then the fixed changeset should be executed without error * @throws LiquibaseException * @throws SQLException */ @Test public void testFixInvalidChangeSetAddNotNullColumnWithNoDefaultValue() throws SQLException, LiquibaseException { // Prepare test data: purge test table, apply incorrect change set and insert data in table jdbcTemplate.execute("delete from table_test_1"); applyChangeLog("classpath:./test-changesets/new-column-no-default-value-invalid-changeset.xml"); jdbcTemplate.execute("insert into table_test_1 values (1717,'test-1717','new-data-1717')"); // Run test applyChangeLog("classpath:./test-changesets/new-column-no-default-value-fixed-changeset.xml"); // Assertion: nothing; changeset should simply be applied without error } /** * This test verifies a pattern to implement database denormalization * Given a database with 3 tables table_1, table_1 and table_3 modeling an inheritance entity_1 > entity_2 > entity_3 * When schema is denormalized * Then table_1 and table_2 data are moved into table_3 */ @Test public void testDenormalization() throws SQLException, LiquibaseException { // Prepare test data: complete initialization with additional change set applyChangeLog("classpath:./test-changesets/denormalization-init-changeset.xml"); // Run test applyChangeLog("classpath:./test-changesets/denormalization-migration-changeset.xml"); // Assertions SqlRowSet results = jdbcTemplate.queryForRowSet("select id, c1, c2, c3 from table_3"); assertTrue("no data in SqlRowSet results", results.first()); do { int id = results.getInt("id"); String c1 = results.getString("c1"); String c2 = results.getString("c2"); String c3 = results.getString("c3"); assertEquals("t1v"+id, c1); assertEquals("t2v"+id, c2); assertEquals("t3v"+id, c3); } while(results.next()); } // === Utility methods /** * apply change log by calling liquibase test wrapper * @param changeLog * @throws SQLException * @throws LiquibaseException */ private void applyChangeLog(String changeLog) throws SQLException, LiquibaseException { liquibaseWrapper.applyChangeLog(paasTestDbUrl, paasTestDbUser, paasTestDbPassword,changeLog); } }
Orange-OpenSource/elpaaso-core
cloud-paas-db/src/test/java/com/francetelecom/clara/cloud/db/liquibase/CheckVariousRefactoringCommandsIT.java
Java
apache-2.0
8,301
// Copyright 2014 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. #![feature(unboxed_closures, overloaded_calls)] #[inline] pub fn has_closures() -> uint { let x = 1u; let mut f = move |&mut:| x; let y = 1u; let g = |:| y; f() + g() } pub fn has_generic_closures<T: Add<T,T> + Copy>(x: T, y: T) -> T { let mut f = move |&mut:| x; let g = |:| y; f() + g() }
barosl/rust
src/test/auxiliary/unboxed-closures-cross-crate.rs
Rust
apache-2.0
792
package se.lth.cs.docforia.graph.outline; /* * Copyright 2016 Marcus Klang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import se.lth.cs.docforia.DocumentProxy; import se.lth.cs.docforia.Node; import se.lth.cs.docforia.query.NodeTVar; /** * Section annotation, e.g. annotation of a collection of paragraphs */ public class Section extends Node<Section> { /** Title property key */ public static final String TITLE_PROPERTY = "title"; public Section() { super(); } public Section(DocumentProxy doc) { super(doc); } public Section setTitle(String title) { putProperty(TITLE_PROPERTY, title); return this; } public String getTitle() { return getProperty(TITLE_PROPERTY); } public static NodeTVar<Section> var() { return new NodeTVar<Section>(Section.class); } public static NodeTVar<Section> var(String variant) { return new NodeTVar<Section>(Section.class, variant); } }
marcusklang/docforia
src/main/java/se/lth/cs/docforia/graph/outline/Section.java
Java
apache-2.0
1,432
/* * ReportSettingsXMLConverter.java * * Created 23 October 2009 * * * Copyright 2006-2015 James F. Bowring and www.Earth-Time.org * * 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.earthtime.UPb_Redux.reports; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * A <code>ReportSettingsXMLConverter</code> is used to marshal and unmarshal * data between <code>reportSettings</code> and XML files. * * @imports * <a href=http://xstream.codehaus.org/javadoc/com/thoughtworks/xstream/converters/Converter.html> * com.thoughtworks.xstream.converters.Converter</a> * @imports * <a href=http://xstream.codehaus.org/javadoc/com/thoughtworks/xstream/converters/MarshallingContext.html> * com.thoughtworks.xstream.converters.MarhsallingContext</a> * @imports * <a href=http://xstream.codehaus.org/javadoc/com/thoughtworks/xstream/converters/UnmarshallingContext.html> * com.thoughtworks.xstream.converters.UnmarshallingContext</a> * @imports * <a href=http://xstream.codehaus.org/javadoc/com/thoughtworks/xstream/io/HierarchicalStreamReader.html> * com.thoughtworks.xstream.io.HierachicalSreamReader</a> * @imports * <a href=http://xstream.codehaus.org/javadoc/com/thoughtworks/xstream/io/HierarchicalStreamWriter.html> * com.thoughtworks.xstream.io.HierarchicalStreamWriter</a> * @author James F. Bowring, javaDocs by Stan Gasque */ public class ReportSettingsXMLConverter implements Converter { /** * checks the argument <code>clazz</code> against * <code>reportSettings</code>'s <code>Class</code>. Used to ensure that the * object about to be marshalled/unmarshalled is of the correct type. * * @pre argument <code>clazz</code> is a valid <code>Class</code> * @post <code>boolean</code> is returned comparing <code>clazz</code> * against <code>reportSettings.class</code> * @param clazz <code>Class</code> of the <code>Object</code> you wish to * convert to/from XML * @return <code>boolean</code> - <code>true</code> if <code>clazz</code> * matches <code>reportSettings</code>'s <code>Class</code>; else * <code>false</code>. */ @Override public boolean canConvert(Class clazz) { return clazz.equals(ReportSettings.class); } /** * writes the argument <code>value</code> to the XML file specified through * <code>writer</code> * * @pre <code>value</code> is a valid <code>reportSettings</code>, <code> * writer</code> is a valid <code>HierarchicalStreamWriter</code>, and * <code>context</code> is a valid <code>MarshallingContext</code> * @post <code>value</code> is written to the XML file specified via * <code>writer</code> * @param value <code>reportSettings</code> that you wish to write to a file * @param writer stream to write through * @param context <code>MarshallingContext</code> used to store generic data */ @Override public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) { ReportSettings reportSettings = (ReportSettings) value; writer.startNode("name"); writer.setValue(reportSettings.getName()); writer.endNode(); writer.startNode("version"); writer.setValue(Integer.toString(reportSettings.getVersion())); writer.endNode(); writer.startNode("isotopeStyle"); writer.setValue(reportSettings.getIsotopeStyle()); writer.endNode(); writer.startNode("fractionCategory"); context.convertAnother(reportSettings.getFractionCategory()); writer.endNode(); writer.startNode("compositionCategory"); context.convertAnother(reportSettings.getCompositionCategory()); writer.endNode(); writer.startNode("isotopicRatiosCategory"); context.convertAnother(reportSettings.getIsotopicRatiosCategory()); writer.endNode(); writer.startNode("isotopicRatiosPbcCorrCategory"); context.convertAnother(reportSettings.getIsotopicRatiosPbcCorrCategory()); writer.endNode(); writer.startNode("datesCategory"); context.convertAnother(reportSettings.getDatesCategory()); writer.endNode(); writer.startNode("datesPbcCorrCategory"); context.convertAnother(reportSettings.getDatesPbcCorrCategory()); writer.endNode(); writer.startNode("rhosCategory"); context.convertAnother(reportSettings.getRhosCategory()); writer.endNode(); writer.startNode("traceElementsCategory"); context.convertAnother(reportSettings.getTraceElementsCategory()); writer.endNode(); writer.startNode("fractionCategory2"); context.convertAnother(reportSettings.getFractionCategory2()); writer.endNode(); writer.startNode("reportSettingsComment"); writer.setValue(reportSettings.getReportSettingsComment()); writer.endNode(); writer.startNode("legacyData"); writer.setValue(Boolean.toString(reportSettings.isLegacyData())); writer.endNode(); } /** * reads a <code>reportSettings</code> from the XML file specified through * <code>reader</code> * * @pre <code>reader</code> leads to a valid <code>reportSettings</code> * @post the <code>reportSettings</code> is read from the XML file and * returned * @param reader stream to read through * @param context <code>UnmarshallingContext</code> used to store generic * data * @return <code>Object</code> - <code>reportSettings</code> read from file * specified by <code>reader</code> */ @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { ReportSettings reportSettings = new ReportSettings(); reader.moveDown(); reportSettings.setName(reader.getValue()); reader.moveUp(); reader.moveDown(); reportSettings.setVersion(Integer.parseInt(reader.getValue())); reader.moveUp(); reader.moveDown(); if ("isotopeStyle".equals(reader.getNodeName())) { reportSettings.setIsotopeStyle(reader.getValue()); reader.moveUp(); reader.moveDown(); } ReportCategory reportCategory = new ReportCategory(); reportCategory = (ReportCategory) context.convertAnother(reportCategory, ReportCategory.class); reportSettings.setFractionCategory(reportCategory); reader.moveUp(); reader.moveDown(); reportCategory = new ReportCategory(); reportCategory = (ReportCategory) context.convertAnother(reportCategory, ReportCategory.class); reportSettings.setCompositionCategory(reportCategory); reader.moveUp(); reader.moveDown(); reportCategory = new ReportCategory(); reportCategory = (ReportCategory) context.convertAnother(reportCategory, ReportCategory.class); reportSettings.setIsotopicRatiosCategory(reportCategory); reader.moveUp(); reader.moveDown(); reportCategory = new ReportCategory(); reportCategory = (ReportCategory) context.convertAnother(reportCategory, ReportCategory.class); reportSettings.setIsotopicRatiosPbcCorrCategory(reportCategory); reader.moveUp(); reader.moveDown(); reportCategory = new ReportCategory(); reportCategory = (ReportCategory) context.convertAnother(reportCategory, ReportCategory.class); reportSettings.setDatesCategory(reportCategory); reader.moveUp(); reader.moveDown(); reportCategory = new ReportCategory(); reportCategory = (ReportCategory) context.convertAnother(reportCategory, ReportCategory.class); reportSettings.setDatesPbcCorrCategory(reportCategory); reader.moveUp(); reader.moveDown(); reportCategory = new ReportCategory(); reportCategory = (ReportCategory) context.convertAnother(reportCategory, ReportCategory.class); reportSettings.setRhosCategory(reportCategory); reader.moveUp(); reader.moveDown(); reportCategory = new ReportCategory(); reportCategory = (ReportCategory) context.convertAnother(reportCategory, ReportCategory.class); reportSettings.setTraceElementsCategory(reportCategory); reader.moveUp(); reader.moveDown(); reportCategory = new ReportCategory(); reportCategory = (ReportCategory) context.convertAnother(reportCategory, ReportCategory.class); reportSettings.setFractionCategory2(reportCategory); reader.moveUp(); reader.moveDown(); reportSettings.setReportSettingsComment(reader.getValue()); reader.moveUp(); reader.moveDown(); reportSettings.setLegacyData((reader.getValue().equalsIgnoreCase("true"))); reader.moveUp(); reportSettings.assembleReportCategories(); return reportSettings; } }
johnzeringue/ET_Redux
src/main/java/org/earthtime/UPb_Redux/reports/ReportSettingsXMLConverter.java
Java
apache-2.0
9,839