repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
ithinkicancode/zio-flow
zio-flow/shared/src/test/scala/zio/flow/remote/RemoteTupleSpec.scala
package zio.flow.remote import zio.ZIO import zio.flow.utils.RemoteAssertionSyntax.RemoteAssertionOps import zio.flow.{Remote, RemoteContext} import zio.test.{TestResult, Spec, TestEnvironment} object RemoteTupleSpec extends RemoteSpecBase { override def spec: Spec[TestEnvironment, Nothing] = suite("RemoteTupleSpec")( test("Tuple2") { val tuple2 = Remote((1, "A")) ZIO .collectAll( List( tuple2._1 <-> 1, tuple2._2 <-> "A" ) ) .map(TestResult.all(_: _*)) }, test("Tuple3") { val tuple3 = Remote((1, "A", true)) ZIO .collectAll( List( tuple3._1 <-> 1, tuple3._2 <-> "A", tuple3._3 <-> true ) ) .map(TestResult.all(_: _*)) }, test("Tuple4") { val tuple4 = Remote((1, "A", true, 10.5)) ZIO .collectAll( List( tuple4._1 <-> 1, tuple4._2 <-> "A", tuple4._3 <-> true, tuple4._4 <-> 10.5 ) ) .map(TestResult.all(_: _*)) } // test("Tuple5") { // val tuple5 = Remote((1, "A", true, 10.5, "X")) // ZIO // .collectAll( // List( // tuple5._1 <-> 1, // tuple5._2 <-> "A", // tuple5._3 <-> true, // tuple5._4 <-> 10.5, // tuple5._5 <-> "X" // ) // ) // .map(TestResult.all(_ : _*))// // } ).provide(RemoteContext.inMemory) }
fiolino/searcher
src/main/java/org/fiolino/searcher/statement/Filter.java
<gh_stars>0 package org.fiolino.searcher.statement; /** * Created by kuli on 29.02.16. */ public abstract class Filter extends Statement { protected Filter() { } public Filter and(Filter other) { return new BooleanFilter(this, other, Operator.AND); } public Filter or(Filter other) { return new BooleanFilter(this, other, Operator.OR); } public Filter negated() { return new NegatedFilter(this); } public Filter allowsNullValues() { return new AllowsNullFilter(this); } public Filter uncached() { return new ParameterizedFilter(this, "cache=false"); } public Filter withCost(int cost) { return new ParameterizedFilter(this, "cache=false cost=" + cost); } @Override protected final void applyTo(StringBuilder sb) { applyTo(sb, false, false); } protected abstract void applyTo(StringBuilder sb, boolean negated, boolean allowsNull); }
moibenko/enstore
src/mounts_per_robot_plotter_module.py
<reponame>moibenko/enstore #!/usr/bin/env python ############################################################################### # # purpose: create mount/day plots per tape library and # install them in MOUNTS_PER_ROBOT_PLOTS_SUBDIR # $Id$ # ############################################################################### import pg import string import sys import os import time import enstore_plots import configuration_client import enstore_functions2 import enstore_plotter_module import enstore_constants import histogram import enstore_plots import e_errors WEB_SUB_DIRECTORY = enstore_constants.MOUNTS_PER_ROBOT_PLOTS_SUBDIR TIME_CONDITION=" current_timestamp - '1 mons'::interval " SELECT_STATEMENT="select start, finish "+\ "from tape_mounts where start > "+TIME_CONDITION+\ " and state='%s' and logname in ('%s') " class MountsPerRobotPlotterModule(enstore_plotter_module.EnstorePlotterModule): def __init__(self,name,isActive=True): enstore_plotter_module.EnstorePlotterModule.__init__(self,name,isActive) self.db=None self.ntuples={} self.now_time = time.time() self.nbins=30 Y, M, D, h, m, s, wd, jd, dst = time.localtime(self.now_time) self.now_time = time.mktime((Y, M, D, 23, 59, 59, wd, jd, dst)) self.start_time = self.now_time-self.nbins*3600*24 self.histograms={} def __decorate(self,h,color,ylabel,marker): h.set_time_axis(True) h.set_ylabel(ylabel) h.set_xlabel("Date (year-month-day)") h.set_line_color(color) h.set_line_width(20) h.set_marker_text(marker) h.set_marker_type("impulses") def book(self, frame): # # this handles destination directory creation if needed # cron_dict = frame.get_configuration_client().get("crons", {}) self.html_dir = cron_dict.get("html_dir", "") self.plot_dir = os.path.join(self.html_dir, enstore_constants.PLOTS_SUBDIR) if not os.path.exists(self.plot_dir): os.makedirs(self.plot_dir) self.web_dir = os.path.join(self.html_dir, WEB_SUB_DIRECTORY) if not os.path.exists(self.web_dir): os.makedirs(self.web_dir) def __fill(self,server_tuple): csc = configuration_client.ConfigurationClient(server_tuple) acc = csc.get(enstore_constants.ACCOUNTING_SERVER) db = pg.DB(host = acc.get('dbhost', 'localhost'), dbname= acc.get('dbname', 'accounting'), port = acc.get('dbport', 5432), user = acc.get('dbuser_reader', 'enstore_reader')) # # get list of media changers # mcs = csc.get_media_changers() # # filter out null and disk # for m in mcs.keys(): if m.find('null') != -1 or m.find('disk') != -1: del mcs[m] # # get all movers # mover_list=csc.get_movers(None) # # fill { "media changer" : ["mover1","mover2",....] } map of movers # belonging to this media changer # mc_mover_map={} for mc in mcs: movers=[] mc_name="%s.media_changer"%(mc,) for mover_name in mover_list: mover=csc.get(mover_name['mover']) if mc_name==mover.get('media_changer'): movers.append(mover.get('logname')) # # MC labelled "SL8500" are actually "SL8500G1" # if mc=="SL8500" : mc = "SL8500G1" mc_mover_map[mc]=movers for mc in mc_mover_map.keys(): if not self.histograms.has_key(mc): self.histograms[mc] = histogram.Histogram1D(mc,mc,self.nbins,self.start_time,self.now_time) h=self.histograms.get(mc) movers=mc_mover_map.get(mc) # # plot Mounts / day per robot library # q=SELECT_STATEMENT%("M",string.join(movers,"','"),) results=db.query(q).dictresult() for r in results: h.fill(time.mktime(time.strptime(r.get('start'),"%Y-%m-%d %H:%M:%S"))) db.close() def fill(self, frame): csc = frame.get_configuration_client() known_config_servers=csc.get('known_config_servers') if known_config_servers.get('status')[0] != e_errors.OK: return del known_config_servers['status'] for name,server in known_config_servers.iteritems(): self.__fill(server) return def plot(self): for h in self.histograms.values(): self.__decorate(h,1,"Mounts / day","Total %d"%(h.get_entries(),)) h.plot(directory=self.web_dir) h.plot()
lifeomic/phc-sdk-py
tests/easy/util/frame.py
<gh_stars>1-10 import pandas as pd from nose.tools import assert_equals from phc.easy.util.frame import combine_first def test_combine_first(): frame = pd.DataFrame( [ {"count": pd.NA, "count1": 10, "count2": 100}, {"count": pd.NA, "count1": pd.NA, "count2": 200}, {"count": 3, "count1": pd.NA, "count2": pd.NA}, ] ) assert_equals( combine_first(frame, ["count", "count1", "count2"], "count")["count"], pd.Series(), )
rate-engineering/rate3-monorepo
packages/ethereum-contracts/test/lib/Ownable.test.js
import { BN, constants, expectEvent, time, shouldFail } from 'openzeppelin-test-helpers'; const Ownable = artifacts.require('./lib/ownership/Ownable'); contract('Ownable', function (accounts) { beforeEach(async function () { this.ownable = await Ownable.new(); }); shouldBehaveLikeOwnable(accounts); }); require('chai') .should(); function shouldBehaveLikeOwnable (accounts) { describe('as an ownable', function () { it('should have an owner', async function () { const owner = await this.ownable.owner(); owner.should.not.eq(constants.ZERO_ADDRESS); }); it('changes owner after transfer', async function () { const other = accounts[1]; await this.ownable.transferOwnership(other); const owner = await this.ownable.owner(); owner.should.eq(other); }); it('should prevent non-owners from transfering', async function () { const other = accounts[2]; const owner = await this.ownable.owner.call(); owner.should.not.eq(other); await shouldFail.reverting(this.ownable.transferOwnership(other, { from: other })); }); it('should guard ownership against stuck state', async function () { const originalOwner = await this.ownable.owner(); await shouldFail.reverting(this.ownable.transferOwnership(constants.ZERO_ADDRESS, { from: originalOwner })); }); }); } module.exports = { shouldBehaveLikeOwnable, };
knightjdr/prohits-viz-analysis
pkg/specificity/calculatespecificity.go
// Package specificity calculates specificity scores. package specificity import ( "math" "strconv" "strings" customMath "github.com/knightjdr/prohits-viz-analysis/pkg/math" "github.com/knightjdr/prohits-viz-analysis/pkg/types" "gonum.org/v1/gonum/stat" ) // Calculate scores for readouts between conditions. func Calculate(analysis *types.Analysis) map[string]map[string]map[string]float64 { abundanceByReadout, noConditions := getAbundanceByReadout(analysis.Data) specificity := calculateSpecificityByMetric(abundanceByReadout, noConditions, analysis.Settings.SpecificityMetric) return reshapeSpecifictyByCondition(specificity) } func getAbundanceByReadout(data []map[string]string) (map[string]map[string]map[string]float64, int) { abundanceByReadout := make(map[string]map[string]map[string]float64) conditions := make(map[string]bool) for _, datum := range data { abundance := datum["abundance"] condition := datum["condition"] readout := datum["readout"] score, _ := strconv.ParseFloat(datum["score"], 64) conditions[condition] = true if _, ok := abundanceByReadout[readout]; !ok { abundanceByReadout[readout] = make(map[string]map[string]float64) } abundances := make([]float64, 0) reproducibility := 0.0 for _, strValue := range strings.Split(abundance, "|") { value, _ := strconv.ParseFloat(strValue, 64) abundances = append(abundances, value) if value != 0 { reproducibility++ } } abundanceByReadout[readout][condition] = map[string]float64{ "abundance": stat.Mean(abundances, nil), "reproducibility": reproducibility, "score": score, } } return abundanceByReadout, len(conditions) } func calculateSpecificityByMetric(abundanceByReadout map[string]map[string]map[string]float64, noConditions int, metric string) map[string]map[string]map[string]float64 { defineSpecificity := getSpecificityMetric(metric, noConditions) specificity := make(map[string]map[string]map[string]float64, len(abundanceByReadout)) for readout, conditionData := range abundanceByReadout { specificity[readout] = make(map[string]map[string]float64, len(conditionData)) for condition := range conditionData { specificity[readout][condition] = defineSpecificity(condition, conditionData) } } return specificity } func getSpecificityMetric(metric string, noConditions int) func(condition string, abundanceByCondition map[string]map[string]float64) map[string]float64 { if metric == "zscore" { return func(condition string, abundanceByCondition map[string]map[string]float64) map[string]float64 { values := make([]float64, noConditions) i := 0 for _, datum := range abundanceByCondition { values[i] = datum["abundance"] i++ } mean, sd := stat.MeanStdDev(values, nil) specificity := 0.0 if sd != 0 { specificity = customMath.Round((abundanceByCondition[condition]["abundance"]-mean)/sd, 0.01) } return map[string]float64{ "abundance": abundanceByCondition[condition]["abundance"], "score": abundanceByCondition[condition]["score"], "specificity": specificity, } } } if metric == "sscore" { return func(condition string, abundanceByCondition map[string]map[string]float64) map[string]float64 { freq := float64(noConditions) / float64(len(abundanceByCondition)) adjustedAbundance := freq * math.Abs(abundanceByCondition[condition]["abundance"]) return map[string]float64{ "abundance": abundanceByCondition[condition]["abundance"], "score": abundanceByCondition[condition]["score"], "specificity": customMath.Round(math.Sqrt(adjustedAbundance), 0.01), } } } if metric == "dscore" { return func(condition string, abundanceByCondition map[string]map[string]float64) map[string]float64 { freq := float64(noConditions) / float64(len(abundanceByCondition)) multiplier := math.Pow(freq, abundanceByCondition[condition]["reproducibility"]) adjustedAbundance := multiplier * math.Abs(abundanceByCondition[condition]["abundance"]) return map[string]float64{ "abundance": abundanceByCondition[condition]["abundance"], "score": abundanceByCondition[condition]["score"], "specificity": customMath.Round(math.Sqrt(adjustedAbundance), 0.01), } } } if metric == "wdscore" { return func(condition string, abundanceByCondition map[string]map[string]float64) map[string]float64 { values := make([]float64, noConditions) i := 0 for _, datum := range abundanceByCondition { values[i] = math.Abs(datum["abundance"]) i++ } mean, sd := stat.MeanStdDev(values, nil) omega := sd / mean if omega < 1 { omega = 1 } freq := float64(noConditions) / float64(len(abundanceByCondition)) weightedFrequency := freq * omega multiplier := math.Pow(weightedFrequency, abundanceByCondition[condition]["reproducibility"]) adjustedAbundance := multiplier * math.Abs(abundanceByCondition[condition]["abundance"]) return map[string]float64{ "abundance": abundanceByCondition[condition]["abundance"], "score": abundanceByCondition[condition]["score"], "specificity": customMath.Round(math.Sqrt(adjustedAbundance), 0.01), } } } return func(condition string, abundanceByCondition map[string]map[string]float64) map[string]float64 { values := make([]float64, noConditions-1) i := 0 for key, datum := range abundanceByCondition { if key != condition { values[i] = math.Abs(datum["abundance"]) i++ } } mean := stat.Mean(values, nil) specificity := float64(0) if math.Abs(abundanceByCondition[condition]["abundance"]) > 0 { specificity = math.Abs(abundanceByCondition[condition]["abundance"] / mean) } return map[string]float64{ "abundance": abundanceByCondition[condition]["abundance"], "score": abundanceByCondition[condition]["score"], "specificity": customMath.Round(specificity, 0.01), } } } func reshapeSpecifictyByCondition(specificity map[string]map[string]map[string]float64) map[string]map[string]map[string]float64 { specificityByCondition := make(map[string]map[string]map[string]float64) for readout, readoutData := range specificity { for condition, conditionData := range readoutData { if _, ok := specificityByCondition[condition]; !ok { specificityByCondition[condition] = make(map[string]map[string]float64) } specificityByCondition[condition][readout] = conditionData } } return specificityByCondition }
Tanc009/jdcloud-sdk-java
pod/src/main/java/com/jdcloud/sdk/service/pod/model/ContainerSpec.java
/* * Copyright 2018 JDCLOUD.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. * * * * * * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ package com.jdcloud.sdk.service.pod.model; import java.util.List; import java.util.ArrayList; import com.jdcloud.sdk.annotation.Required; /** * 容器规格 */ public class ContainerSpec implements java.io.Serializable { private static final long serialVersionUID = 1L; /** * 容器名称,符合DNS-1123 label规范,在一个Pod内不可重复、不支持修改 * Required:true */ @Required private String name; /** * 容器执行命令,如果不指定默认是docker镜像的ENTRYPOINT。总长度256个字符。 */ private List<String> command; /** * 容器执行命令的参数,如果不指定默认是docker镜像的CMD。总长度2048个字符。 */ private List<String> args; /** * 容器执行的环境变量;如果和镜像中的环境变量Key相同,会覆盖镜像中的值。数组范围:[0-100] */ private List<EnvSpec> env; /** * 镜像名称 &lt;/br&gt; 容器镜像名字。 nginx:latest。长度范围:[1-639] 1. Docker Hub官方镜像通过类似nginx, mysql/mysql-server的名字指定 &lt;/br&gt; 2. repository长度最大256个字符,tag最大128个字符,registry最大255个字符 &lt;/br&gt; * Required:true */ @Required private String image; /** * 镜像仓库认证信息。如果目前不传,默认选择dockerHub镜像 */ private String secret; /** * 容器是否分配tty。默认不分配 */ private Boolean tty; /** * 容器的工作目录。如果不指定,默认是根目录(/);必须是绝对路径;长度范围:[0-1024] */ private String workingDir; /** * 容器存活探针配置 */ private ProbeSpec livenessProbe; /** * 容器服务就绪探针配置 */ private ProbeSpec readinessProbe; /** * 容器计算资源配置 */ private ResourceRequestsSpec resources; /** * 容器计算资源配置 * Required:true */ @Required private CloudDiskSpec systemDisk; /** * 云盘挂载信息 */ private List<VolumeMountSpec> volumeMounts; /** * get 容器名称,符合DNS-1123 label规范,在一个Pod内不可重复、不支持修改 * * @return */ public String getName() { return name; } /** * set 容器名称,符合DNS-1123 label规范,在一个Pod内不可重复、不支持修改 * * @param name */ public void setName(String name) { this.name = name; } /** * get 容器执行命令,如果不指定默认是docker镜像的ENTRYPOINT。总长度256个字符。 * * @return */ public List<String> getCommand() { return command; } /** * set 容器执行命令,如果不指定默认是docker镜像的ENTRYPOINT。总长度256个字符。 * * @param command */ public void setCommand(List<String> command) { this.command = command; } /** * get 容器执行命令的参数,如果不指定默认是docker镜像的CMD。总长度2048个字符。 * * @return */ public List<String> getArgs() { return args; } /** * set 容器执行命令的参数,如果不指定默认是docker镜像的CMD。总长度2048个字符。 * * @param args */ public void setArgs(List<String> args) { this.args = args; } /** * get 容器执行的环境变量;如果和镜像中的环境变量Key相同,会覆盖镜像中的值。数组范围:[0-100] * * @return */ public List<EnvSpec> getEnv() { return env; } /** * set 容器执行的环境变量;如果和镜像中的环境变量Key相同,会覆盖镜像中的值。数组范围:[0-100] * * @param env */ public void setEnv(List<EnvSpec> env) { this.env = env; } /** * get 镜像名称 &lt;/br&gt; 容器镜像名字。 nginx:latest。长度范围:[1-639] 1. Docker Hub官方镜像通过类似nginx, mysql/mysql-server的名字指定 &lt;/br&gt; 2. repository长度最大256个字符,tag最大128个字符,registry最大255个字符 &lt;/br&gt; * * @return */ public String getImage() { return image; } /** * set 镜像名称 &lt;/br&gt; 容器镜像名字。 nginx:latest。长度范围:[1-639] 1. Docker Hub官方镜像通过类似nginx, mysql/mysql-server的名字指定 &lt;/br&gt; 2. repository长度最大256个字符,tag最大128个字符,registry最大255个字符 &lt;/br&gt; * * @param image */ public void setImage(String image) { this.image = image; } /** * get 镜像仓库认证信息。如果目前不传,默认选择dockerHub镜像 * * @return */ public String getSecret() { return secret; } /** * set 镜像仓库认证信息。如果目前不传,默认选择dockerHub镜像 * * @param secret */ public void setSecret(String secret) { this.secret = secret; } /** * get 容器是否分配tty。默认不分配 * * @return */ public Boolean getTty() { return tty; } /** * set 容器是否分配tty。默认不分配 * * @param tty */ public void setTty(Boolean tty) { this.tty = tty; } /** * get 容器的工作目录。如果不指定,默认是根目录(/);必须是绝对路径;长度范围:[0-1024] * * @return */ public String getWorkingDir() { return workingDir; } /** * set 容器的工作目录。如果不指定,默认是根目录(/);必须是绝对路径;长度范围:[0-1024] * * @param workingDir */ public void setWorkingDir(String workingDir) { this.workingDir = workingDir; } /** * get 容器存活探针配置 * * @return */ public ProbeSpec getLivenessProbe() { return livenessProbe; } /** * set 容器存活探针配置 * * @param livenessProbe */ public void setLivenessProbe(ProbeSpec livenessProbe) { this.livenessProbe = livenessProbe; } /** * get 容器服务就绪探针配置 * * @return */ public ProbeSpec getReadinessProbe() { return readinessProbe; } /** * set 容器服务就绪探针配置 * * @param readinessProbe */ public void setReadinessProbe(ProbeSpec readinessProbe) { this.readinessProbe = readinessProbe; } /** * get 容器计算资源配置 * * @return */ public ResourceRequestsSpec getResources() { return resources; } /** * set 容器计算资源配置 * * @param resources */ public void setResources(ResourceRequestsSpec resources) { this.resources = resources; } /** * get 容器计算资源配置 * * @return */ public CloudDiskSpec getSystemDisk() { return systemDisk; } /** * set 容器计算资源配置 * * @param systemDisk */ public void setSystemDisk(CloudDiskSpec systemDisk) { this.systemDisk = systemDisk; } /** * get 云盘挂载信息 * * @return */ public List<VolumeMountSpec> getVolumeMounts() { return volumeMounts; } /** * set 云盘挂载信息 * * @param volumeMounts */ public void setVolumeMounts(List<VolumeMountSpec> volumeMounts) { this.volumeMounts = volumeMounts; } /** * set 容器名称,符合DNS-1123 label规范,在一个Pod内不可重复、不支持修改 * * @param name */ public ContainerSpec name(String name) { this.name = name; return this; } /** * set 容器执行命令,如果不指定默认是docker镜像的ENTRYPOINT。总长度256个字符。 * * @param command */ public ContainerSpec command(List<String> command) { this.command = command; return this; } /** * set 容器执行命令的参数,如果不指定默认是docker镜像的CMD。总长度2048个字符。 * * @param args */ public ContainerSpec args(List<String> args) { this.args = args; return this; } /** * set 容器执行的环境变量;如果和镜像中的环境变量Key相同,会覆盖镜像中的值。数组范围:[0-100] * * @param env */ public ContainerSpec env(List<EnvSpec> env) { this.env = env; return this; } /** * set 镜像名称 &lt;/br&gt; 容器镜像名字。 nginx:latest。长度范围:[1-639] 1. Docker Hub官方镜像通过类似nginx, mysql/mysql-server的名字指定 &lt;/br&gt; 2. repository长度最大256个字符,tag最大128个字符,registry最大255个字符 &lt;/br&gt; * * @param image */ public ContainerSpec image(String image) { this.image = image; return this; } /** * set 镜像仓库认证信息。如果目前不传,默认选择dockerHub镜像 * * @param secret */ public ContainerSpec secret(String secret) { this.secret = secret; return this; } /** * set 容器是否分配tty。默认不分配 * * @param tty */ public ContainerSpec tty(Boolean tty) { this.tty = tty; return this; } /** * set 容器的工作目录。如果不指定,默认是根目录(/);必须是绝对路径;长度范围:[0-1024] * * @param workingDir */ public ContainerSpec workingDir(String workingDir) { this.workingDir = workingDir; return this; } /** * set 容器存活探针配置 * * @param livenessProbe */ public ContainerSpec livenessProbe(ProbeSpec livenessProbe) { this.livenessProbe = livenessProbe; return this; } /** * set 容器服务就绪探针配置 * * @param readinessProbe */ public ContainerSpec readinessProbe(ProbeSpec readinessProbe) { this.readinessProbe = readinessProbe; return this; } /** * set 容器计算资源配置 * * @param resources */ public ContainerSpec resources(ResourceRequestsSpec resources) { this.resources = resources; return this; } /** * set 容器计算资源配置 * * @param systemDisk */ public ContainerSpec systemDisk(CloudDiskSpec systemDisk) { this.systemDisk = systemDisk; return this; } /** * set 云盘挂载信息 * * @param volumeMounts */ public ContainerSpec volumeMounts(List<VolumeMountSpec> volumeMounts) { this.volumeMounts = volumeMounts; return this; } /** * add item to 容器执行命令,如果不指定默认是docker镜像的ENTRYPOINT。总长度256个字符。 * * @param command */ public void addCommand(String command) { if (this.command == null) { this.command = new ArrayList<>(); } this.command.add(command); } /** * add item to 容器执行命令的参数,如果不指定默认是docker镜像的CMD。总长度2048个字符。 * * @param arg */ public void addArg(String arg) { if (this.args == null) { this.args = new ArrayList<>(); } this.args.add(arg); } /** * add item to 容器执行的环境变量;如果和镜像中的环境变量Key相同,会覆盖镜像中的值。数组范围:[0-100] * * @param env */ public void addEnv(EnvSpec env) { if (this.env == null) { this.env = new ArrayList<>(); } this.env.add(env); } /** * add item to 云盘挂载信息 * * @param volumeMount */ public void addVolumeMount(VolumeMountSpec volumeMount) { if (this.volumeMounts == null) { this.volumeMounts = new ArrayList<>(); } this.volumeMounts.add(volumeMount); } }
brezillon/opensplice
src/kernel/code/v_cfAttribute.c
/* * Vortex OpenSplice * * This software and documentation are Copyright 2006 to TO_YEAR ADLINK * Technology Limited, its affiliated companies and licensors. 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. * */ #include "v_cfAttribute.h" #include "v_cfNode.h" #include "v_kernel.h" #include "os_report.h" v_cfAttribute v_cfAttributeNew ( v_configuration config, const c_char *name, c_value value) { v_cfAttribute attr; assert(C_TYPECHECK(config, v_configuration)); assert(name != NULL); if (value.kind != V_UNDEFINED) { attr = v_cfAttribute(v_cfNodeNew(config, V_CFATTRIBUTE)); v_cfAttributeInit(attr, config, name, value); } else { attr = NULL; } return attr; } void v_cfAttributeInit ( v_cfAttribute attribute, v_configuration config, const c_char *name, c_value value) { assert(C_TYPECHECK(attribute, v_cfAttribute)); assert(name != NULL); v_cfNodeInit(v_cfNode(attribute), config, V_CFATTRIBUTE, name); attribute->value = value; switch (value.kind) { case V_STRING: attribute->value.is.String = c_stringNew(c_getBase(c_object(config)), value.is.String); break; case V_UNDEFINED: case V_BOOLEAN: case V_OCTET: case V_SHORT: case V_LONG: case V_LONGLONG: case V_USHORT: case V_ULONG: case V_ULONGLONG: case V_FLOAT: case V_DOUBLE: case V_CHAR: case V_WCHAR: case V_WSTRING: case V_FIXED: case V_OBJECT: default: /* nothing to copy */ OS_REPORT(OS_ERROR, "kernel", V_RESULT_ILL_PARAM, "Unknown value (%d) type given at creation of " "configuration attribute.", value.kind); break; } } c_value v_cfAttributeValue( v_cfAttribute attribute) { assert(C_TYPECHECK(attribute, v_cfAttribute)); return attribute->value; }
jdm7dv/visual-studio
VSSDK/VisualStudioIntegration/Common/Source/CPP/VSL/MockInterfaces/VSLMockIVsWindowView.h
<reponame>jdm7dv/visual-studio /*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. This code is a part of the Visual Studio Library. ***************************************************************************/ #ifndef IVSWINDOWVIEW_H_10C49CA1_2F46_11D3_A504_00C04F5E0BA5 #define IVSWINDOWVIEW_H_10C49CA1_2F46_11D3_A504_00C04F5E0BA5 #if _MSC_VER > 1000 #pragma once #endif #include "vsshell.h" #pragma warning(push) #pragma warning(disable : 4510) // default constructor could not be generated #pragma warning(disable : 4610) // can never be instantiated - user defined constructor required #pragma warning(disable : 4512) // assignment operator could not be generated #pragma warning(disable : 6011) // Dereferencing NULL pointer (a NULL derference is just another kind of failure for a unit test namespace VSL { class IVsWindowViewNotImpl : public IVsWindowView { VSL_DECLARE_NONINSTANTIABLE_BASE_CLASS(IVsWindowViewNotImpl) public: typedef IVsWindowView Interface; STDMETHOD(GetProperty)( /*[in]*/ VSVPROPID /*propid*/, /*[out]*/ VARIANT* /*pvar*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(SetProperty)( /*[in]*/ VSVPROPID /*propid*/, /*[in]*/ VARIANT /*var*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(GetGuidProperty)( /*[in]*/ VSVPROPID /*propid*/, /*[out]*/ GUID* /*pguid*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(SetGuidProperty)( /*[in]*/ VSVPROPID /*propid*/, /*[in]*/ REFGUID /*rguid*/)VSL_STDMETHOD_NOTIMPL }; class IVsWindowViewMockImpl : public IVsWindowView, public MockBase { VSL_DECLARE_NONINSTANTIABLE_BASE_CLASS(IVsWindowViewMockImpl) public: VSL_DEFINE_MOCK_CLASS_TYPDEFS(IVsWindowViewMockImpl) typedef IVsWindowView Interface; struct GetPropertyValidValues { /*[in]*/ VSVPROPID propid; /*[out]*/ VARIANT* pvar; HRESULT retValue; }; STDMETHOD(GetProperty)( /*[in]*/ VSVPROPID propid, /*[out]*/ VARIANT* pvar) { VSL_DEFINE_MOCK_METHOD(GetProperty) VSL_CHECK_VALIDVALUE(propid); VSL_SET_VALIDVALUE_VARIANT(pvar); VSL_RETURN_VALIDVALUES(); } struct SetPropertyValidValues { /*[in]*/ VSVPROPID propid; /*[in]*/ VARIANT var; HRESULT retValue; }; STDMETHOD(SetProperty)( /*[in]*/ VSVPROPID propid, /*[in]*/ VARIANT var) { VSL_DEFINE_MOCK_METHOD(SetProperty) VSL_CHECK_VALIDVALUE(propid); VSL_CHECK_VALIDVALUE(var); VSL_RETURN_VALIDVALUES(); } struct GetGuidPropertyValidValues { /*[in]*/ VSVPROPID propid; /*[out]*/ GUID* pguid; HRESULT retValue; }; STDMETHOD(GetGuidProperty)( /*[in]*/ VSVPROPID propid, /*[out]*/ GUID* pguid) { VSL_DEFINE_MOCK_METHOD(GetGuidProperty) VSL_CHECK_VALIDVALUE(propid); VSL_SET_VALIDVALUE(pguid); VSL_RETURN_VALIDVALUES(); } struct SetGuidPropertyValidValues { /*[in]*/ VSVPROPID propid; /*[in]*/ REFGUID rguid; HRESULT retValue; }; STDMETHOD(SetGuidProperty)( /*[in]*/ VSVPROPID propid, /*[in]*/ REFGUID rguid) { VSL_DEFINE_MOCK_METHOD(SetGuidProperty) VSL_CHECK_VALIDVALUE(propid); VSL_CHECK_VALIDVALUE(rguid); VSL_RETURN_VALIDVALUES(); } }; } // namespace VSL #pragma warning(pop) #endif // IVSWINDOWVIEW_H_10C49CA1_2F46_11D3_A504_00C04F5E0BA5
dennyac/dropwizard-redis
src/test/java/io/dropwizard/redis/metrics/event/LettuceMetricsSubscriberTest.java
package io.dropwizard.redis.metrics.event; import com.google.common.collect.ImmutableList; import io.dropwizard.redis.metrics.event.visitor.*; import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent; import io.lettuce.core.event.connection.ConnectedEvent; import io.lettuce.core.event.connection.ConnectionActivatedEvent; import io.lettuce.core.event.connection.ConnectionDeactivatedEvent; import io.lettuce.core.event.connection.DisconnectedEvent; import io.lettuce.core.event.metrics.CommandLatencyEvent; import org.junit.Test; import java.util.List; import static org.mockito.Mockito.*; public class LettuceMetricsSubscriberTest { @Test public void shouldDispatchEventsToListeners() { List<EventVisitor> visitors = ImmutableList.of( mock(ClusterTopologyChangedEventVisitor.class), mock(CommandLatencyEventVisitor.class), mock(ConnectedEventVisitor.class), mock(ConnectionActivatedEventVisitor.class), mock(ConnectionDeactivatedEventVisitor.class), mock(DisconnectedEventVisitor.class) ); LettuceMetricsSubscriber subscriber = new LettuceMetricsSubscriber(visitors); verifyClusterTopologyChangedEvent(subscriber, visitors); verifyCommandLatencyEvent(subscriber, visitors); verifyConnectedEvent(subscriber, visitors); verifyConnectionActivatedEvent(subscriber, visitors); verifyConnectionDeactivatedEvent(subscriber, visitors); verifyDisconnectedEvent(subscriber, visitors); for (EventVisitor visitor : visitors) { verifyNoMoreInteractions(visitor); } } private void verifyClusterTopologyChangedEvent(LettuceMetricsSubscriber subscriber, List<EventVisitor> visitors) { ClusterTopologyChangedEvent event = mock(ClusterTopologyChangedEvent.class); subscriber.accept(event); for (EventVisitor visitor : visitors) { verify(visitor, times(1)).visit(event); } } private void verifyCommandLatencyEvent(LettuceMetricsSubscriber subscriber, List<EventVisitor> visitors) { CommandLatencyEvent event = mock(CommandLatencyEvent.class); subscriber.accept(event); for (EventVisitor visitor : visitors) { verify(visitor, times(1)).visit(event); } } private void verifyConnectedEvent(LettuceMetricsSubscriber subscriber, List<EventVisitor> visitors) { ConnectedEvent event = mock(ConnectedEvent.class); subscriber.accept(event); for (EventVisitor visitor : visitors) { verify(visitor, times(1)).visit(event); } } private void verifyConnectionActivatedEvent(LettuceMetricsSubscriber subscriber, List<EventVisitor> visitors) { ConnectionActivatedEvent event = mock(ConnectionActivatedEvent.class); subscriber.accept(event); for (EventVisitor visitor : visitors) { verify(visitor, times(1)).visit(event); } } private void verifyConnectionDeactivatedEvent(LettuceMetricsSubscriber subscriber, List<EventVisitor> visitors) { ConnectionDeactivatedEvent event = mock(ConnectionDeactivatedEvent.class); subscriber.accept(event); for (EventVisitor visitor : visitors) { verify(visitor, times(1)).visit(event); } } private void verifyDisconnectedEvent(LettuceMetricsSubscriber subscriber, List<EventVisitor> visitors) { DisconnectedEvent event = mock(DisconnectedEvent.class); subscriber.accept(event); for (EventVisitor visitor : visitors) { verify(visitor, times(1)).visit(event); } } }
imranzaidi/cbt-planner
config/libraries/sequelize.js
<reponame>imranzaidi/cbt-planner<gh_stars>1-10 /*********************** * Module Dependencies * ***********************/ const Sequelize = require('sequelize'), config = require('../config'); /****************** * Module Members * ******************/ const db = {}; /** * Helper function; parses model name from path string. * * @param {String} path - file path * @returns {String} * - model file name with the first letter capitalized */ function getModelName(path) { return path.replace('app/models/', '').replace('.js', ''); } /** * Loads all models and forms associations. * * @param {Object} sequelize - Sequelize instance * @param {Array} paths - a list of model paths * @returns {Object} db - a database object */ function loadModels(sequelize, paths) { // Load models const models = paths.reduce((acc, path) => { acc[getModelName(path)] = sequelize.import(`../../${path}`); return acc; }, {}); // Form associations Object.keys(models).forEach((modelName) => { if ('associate' in models[modelName]) { models[modelName].associate(models); } }); return models; } /** * Connects to Postgres database. * * @returns {Object} new sequelize instance */ function connect() { const { dbName, username, password, dialect, host } = config.db, sequelizeConfig = { host, dialect, pool: { max: 5, min: 0, acquire: 30000, idle: 10000 }, operatorsAliases: false }; if (process.env.NODE_ENV === 'test') sequelizeConfig.logging = false; return new Sequelize(dbName, username, password, sequelizeConfig); } const sequelize = connect(); db.models = loadModels(sequelize, config.paths.models); db.sequelize = sequelize; module.exports = db;
suncoast-devs/gateway
db/migrate/20201029145828_create_communications.rb
<reponame>suncoast-devs/gateway # frozen_string_literal: true class CreateCommunications < ActiveRecord::Migration[6.0] def change create_table :communications do |t| t.references :person, null: false, foreign_key: true t.references :user, null: true, foreign_key: true t.integer :media, null: false, default: 0 t.boolean :is_unread, null: false, default: true t.text :subject t.text :body t.jsonb :data, default: '{}', null: false t.timestamp :messaged_at t.timestamps end end end
anyulled/React-Skeleton
client/app/containers/Modals/EditUserModal.js
<reponame>anyulled/React-Skeleton<gh_stars>0 import React from "react"; import {Modal, Button} from "react-bootstrap"; import FieldGroup from "../../components/FieldGroup"; import Select from "../../components/Select"; import {reduxForm} from "redux-form"; import * as userActions from "../../actions/users/users"; import * as modalActions from "../../actions/modal/modal"; const clearForm = (dispatch) => { dispatch(modalActions.modalHide()); }; const submitUpdate = (id, dispatch, values) => { dispatch(userActions.userUpdate(id, values)); clearForm(dispatch); }; const submitRemove = (id, dispatch) => { dispatch(userActions.userRemove(id)); clearForm(dispatch); }; const submitCancelEdit = (dispatch) => { clearForm(dispatch); }; let countries = [ "FRANCE", "GERMANY", "IRELAND", "ITALY", "JAPAN", "SPAIN", "UK", "USA", "VENEZUELA" ]; const validate = values => { const errors = {}; if (!values.name) { errors.name = "Required"; } if (!values.yearOfBirth) { errors.yearOfBirth = "Required"; } if (!values.username) { errors.username = "Required"; } if (!values.country) { errors.country = "Required"; } return errors; }; const EditUserModal = ({ fields: { name, yearOfBirth, country, username }, handleSubmit, dispatch, id, show }) => { const usubmit = submitUpdate.bind(undefined, id, dispatch); const cESubmit = submitCancelEdit.bind(undefined, dispatch); const dsubmit = submitRemove.bind(undefined, id, dispatch); return (<Modal onHide={cESubmit} show={show}> <Modal.Header closeButton> <Modal.Title>Edit User</Modal.Title> </Modal.Header> <Modal.Body> <form onSubmit={handleSubmit(usubmit)}> <FieldGroup label="Name" field={name}/> <FieldGroup label="Year of Birth" field={yearOfBirth}/> <FieldGroup label="Username" field={username}/> <Select label="Country" field={country} options={ [ {name: "Select one", id: ""}, ...countries.map(a => ({"id": a, "name": a})) ] }/> </form> </Modal.Body> <Modal.Footer> <Button type="button" bsStyle="info" onClick={handleSubmit(usubmit)}> Save </Button> <Button type="button" bsStyle="danger" onClick={handleSubmit(dsubmit)}> Delete </Button> <Button type="button" bsStyle="warning" onClick={cESubmit}> Cancel </Button> </Modal.Footer> </Modal>); }; const mapStateToProps = (state, props) => { let initial = {}; const {user} = props; if (user) { initial = user; } return { initialValues: initial, id: initial.id }; }; export default reduxForm({ form: "editUserForm", fields: ["name", "yearOfBirth", "username", "country"], validate }, mapStateToProps)(EditUserModal);
aasensio/pyiacsun
pyiacsun/machinelearn/kmeans.py
<gh_stars>1-10 import numpy as np __all__ = ['kmeans'] def distancia(media, matriz): """Calcula la distancia euclideana desde la media hasta cada vector en la matriz """ res = [] for i in matriz: res.append(np.sum((media - i)**2.)) return res def kmeans(datos_fila, nGrupos, umbral=None): """Calcula los vectores clase de la muestra para nGrupos Args: datos_fila (array [vectores x lambdas]): matriz de datos nGrupos (int): Numero de grupos para la clasificacion umbral (None, optional): Error relativo Returns: dict: Los diccionarios con los grupos y las medias """ if umbral is None: umbral = 1e-6 media = np.zeros((nGrupos, datos_fila.shape[1])) media[0:nGrupos, :] = datos_fila[0:nGrupos, :] difrel = 1. contador = 0 # Creamos nGrupos grupos: grupos = {} for i in range(nGrupos): grupos['grupo' + str(i)] = [] # Creamos nGrupos medias: medias = {} for i in range(nGrupos): medias['media' + str(i)] = [] # Creo la matriz de distancias para todos los vectores distancias = np.zeros((nGrupos, datos_fila.shape[0])) # Comienza las iteraciones hasta que no lleguen a la convergencia while difrel > umbral: # Reseteamos los grupos: for i in range(nGrupos): grupos['grupo' + str(i)] = [] # Calculamos sus distancias for grupo in range(nGrupos): distancias[grupo, :] = distancia(media[grupo, :], datos_fila) # Inserto cada vector con distancia minima al vector medio for i in range(len(datos_fila)): grupos['grupo' + str(np.argmin(distancias[:, i]))].append(datos_fila[i, :]) # Calculo el nuevo vector medio for grupo in range(nGrupos): medias['media' + str(grupo)] = np.mean(np.array(grupos['grupo' + str(grupo)]), axis=0) # Calculo las diferencias relativas con la iteracion anterior difrel = 0. for grupo in range(nGrupos): difrel += np.max(np.abs(medias['media'+str(grupo)]-media[grupo, :])/media[grupo, :]) # Inserto la nueva media: for grupo in range(nGrupos): media[grupo, :] = medias['media' + str(grupo)] contador += 1 return [medias, grupos]
danlangford/LegendsBrowser
src/main/java/legends/model/events/HfPrayedInsideStructure.java
<gh_stars>10-100 package legends.model.events; import legends.model.World; import legends.model.events.basic.HfEvent; import legends.model.events.basic.SiteRelatedEvent; import legends.model.events.basic.StructureRelatedEvent; import legends.xml.annotation.Xml; import legends.xml.annotation.XmlSubtype; @XmlSubtype("hf prayed inside structure") public class HfPrayedInsideStructure extends HfEvent implements SiteRelatedEvent, StructureRelatedEvent { @Xml("site,site_id") private int siteId = -1; @Xml("structure,structure_id") private int structureId = -1; @Override public boolean isRelatedToSite(int siteId) { return this.siteId == siteId; } @Override public boolean isRelatedToStructure(int structureId, int siteId) { return this.structureId == structureId && this.siteId == siteId; } @Override public String getShortDescription() { String hf = World.getHistoricalFigure(getHfId()).getLink(); String site = World.getSite(siteId).getLink(); return hf + " prayed inside " + World.getStructure(structureId, siteId).getLink() + " in " + site; } }
jromero/kpack-cli
pkg/builder/helpers.go
<reponame>jromero/kpack-cli<filename>pkg/builder/helpers.go // Copyright 2020-Present VMware, Inc. // SPDX-License-Identifier: Apache-2.0 package builder import ( "fmt" "io" "io/ioutil" "os" "regexp" "github.com/ghodss/yaml" corev1alpha1 "github.com/pivotal/kpack/pkg/apis/core/v1alpha1" ) func ReadOrder(path string) ([]corev1alpha1.OrderEntry, error) { var ( file io.ReadCloser err error ) if path == "-" { file = os.Stdin } else { file, err = os.Open(path) if err != nil { return nil, err } } defer file.Close() buf, err := ioutil.ReadAll(file) if err != nil { return nil, err } var order []corev1alpha1.OrderEntry return order, yaml.Unmarshal(buf, &order) } func CreateOrder(buildpacks []string) []corev1alpha1.OrderEntry { group := make([]corev1alpha1.BuildpackRef, 0) // this regular expression splits out buildpack id and version var re = regexp.MustCompile(`(?m)^([^@]+)[@]?(.*)`) for _, buildpack := range buildpacks { submatch := re.FindStringSubmatch(buildpack) id := submatch[1] version := submatch[2] group = append(group, corev1alpha1.BuildpackRef{ BuildpackInfo: corev1alpha1.BuildpackInfo{ Id: id, Version: version, }, }) } return []corev1alpha1.OrderEntry{{Group: group}} } func CreateDetectionOrderRow(ref corev1alpha1.BuildpackRef) (string, string) { data := fmt.Sprintf(" %s", ref.Id) optional := "" if ref.Version != "" { data = fmt.Sprintf("%s@%s", data, ref.Version) } if ref.Optional { optional = "(Optional)" } return data, optional }
GuillaumeSimo/autoforecast
autoforecast/models/tests/ml_test.py
<reponame>GuillaumeSimo/autoforecast<filename>autoforecast/models/tests/ml_test.py import unittest from ..ml import * # noqa: F401 class MLTest(unittest.TestCase): def test_ml(self): pass
marstau/shinsango
src/mugen/parser/def.cpp
<reponame>marstau/shinsango #include "mugen/ast/all.h" #include <map> #include "gc.h" typedef std::list<Ast::Section*> SectionList; #include <list> #include <string> #include <vector> #include <map> #include <fstream> #include <sstream> #include <iostream> #include <string.h> namespace Mugen{ namespace Def{ struct Value{ typedef std::list<Value>::const_iterator iterator; Value(): which(1), value(0){ } Value(const Value & him): which(him.which), value(0){ if (him.isData()){ value = him.value; } if (him.isList()){ values = him.values; } } explicit Value(const void * value): which(0), value(value){ } Value & operator=(const Value & him){ which = him.which; if (him.isData()){ value = him.value; } if (him.isList()){ values = him.values; } return *this; } Value & operator=(const void * what){ this->value = what; return *this; } void reset(){ this->value = 0; this->values.clear(); this->which = 1; } int which; // 0 is value, 1 is values inline bool isList() const { return which == 1; } inline bool isData() const { return which == 0; } inline const void * getValue() const { return value; } inline void setValue(const void * value){ which = 0; this->value = value; } inline const std::list<Value> & getValues() const { return values; } /* inline void setValues(std::list<Value> values){ which = 1; values = values; } */ const void * value; std::list<Value> values; }; class Result{ public: Result(): position(-2){ } Result(const int position): position(position){ } Result(const Result & r): position(r.position), value(r.value){ } Result & operator=(const Result & r){ position = r.position; value = r.value; return *this; } void reset(){ value.reset(); } void setPosition(int position){ this->position = position; } inline int getPosition() const { return position; } inline bool error(){ return position == -1; } inline bool calculated(){ return position != -2; } inline void nextPosition(){ position += 1; } void setError(){ position = -1; } inline void setValue(const Value & value){ this->value = value; } /* Value getLastValue() const { if (value.isList()){ if (value.values.size() == 0){ std::cout << "[peg] No last value to get!" << std::endl; } return value.values[value.values.size()-1]; } else { return value; } } */ inline int matches() const { if (value.isList()){ return this->value.values.size(); } else { return 1; } } inline const Value & getValues() const { return this->value; } void addResult(const Result & result){ std::list<Value> & mine = this->value.values; mine.push_back(result.getValues()); this->position = result.getPosition(); this->value.which = 1; } private: int position; Value value; }; struct Chunk0{ Result chunk_start; Result chunk_line; Result chunk_line_end; Result chunk_section; Result chunk_section_line; }; struct Chunk1{ Result chunk_section_start; Result chunk_name; Result chunk_line_end_or_comment; Result chunk_filename; Result chunk_attribute; }; struct Chunk2{ Result chunk_attribute_simple; Result chunk_identifier; Result chunk_identifier_list; Result chunk_valuelist; Result chunk_value; }; struct Chunk3{ Result chunk_date; Result chunk_number; Result chunk_float_or_integer; }; struct Column{ Column(): chunk0(0) ,chunk1(0) ,chunk2(0) ,chunk3(0){ } Chunk0 * chunk0; Chunk1 * chunk1; Chunk2 * chunk2; Chunk3 * chunk3; int hitCount(){ return 0; } int maxHits(){ return 18; } ~Column(){ delete chunk0; delete chunk1; delete chunk2; delete chunk3; } }; class ParseException: std::exception { public: ParseException(const std::string & reason): std::exception(), line(-1), column(-1), message(reason){ } ParseException(const std::string & reason, int line, int column): std::exception(), line(line), column(column), message(reason){ } std::string getReason() const; int getLine() const; int getColumn() const; virtual ~ParseException() throw(){ } protected: int line, column; std::string message; }; class Stream{ public: struct LineInfo{ LineInfo(int line, int column): line(line), column(column){ } LineInfo(const LineInfo & copy): line(copy.line), column(copy.column){ } LineInfo(): line(-1), column(-1){ } int line; int column; }; public: /* read from a file */ Stream(const std::string & filename): temp(0), buffer(0), farthest(0), last_line_info(-1){ std::ifstream stream; /* ios::binary is needed on windows */ stream.open(filename.c_str(), std::ios::in | std::ios::binary); if (stream.fail()){ std::ostringstream out; out << __FILE__ << " cannot open '" << filename << "'"; throw ParseException(out.str()); } stream.seekg(0, std::ios_base::end); max = stream.tellg(); stream.seekg(0, std::ios_base::beg); temp = new char[max]; stream.read(temp, max); buffer = temp; stream.close(); line_info[-1] = LineInfo(1, 1); setup(); } /* for null-terminated strings */ Stream(const char * in): temp(0), buffer(in), farthest(0), last_line_info(-1){ max = strlen(buffer); line_info[-1] = LineInfo(1, 1); setup(); } /* user-defined length */ Stream(const char * in, int length): temp(0), buffer(in), farthest(0), last_line_info(-1){ max = length; line_info[-1] = LineInfo(1, 1); setup(); } void setup(){ createMemo(); } void createMemo(){ memo_size = 1024 * 2; memo = new Column*[memo_size]; /* dont create column objects before they are needed because transient * productions will never call for them so we can save some space by * not allocating columns at all. */ memset(memo, 0, sizeof(Column*) * memo_size); } int length(){ return max; } /* prints statistics about how often rules were fired and how * likely rules are to succeed */ void printStats(){ double min = 1; double max = 0; double average = 0; int count = 0; for (int i = 0; i < length(); i++){ Column & c = getColumn(i); double rate = (double) c.hitCount() / (double) c.maxHits(); if (rate != 0 && rate < min){ min = rate; } if (rate > max){ max = rate; } if (rate != 0){ average += rate; count += 1; } } std::cout << "Min " << (100 * min) << " Max " << (100 * max) << " Average " << (100 * average / count) << " Count " << count << " Length " << length() << " Rule rate " << (100.0 * (double)count / (double) length()) << std::endl; } char get(const int position){ if (position >= max || position < 0){ return '\0'; } // std::cout << "Read char '" << buffer[position] << "'" << std::endl; return buffer[position]; } bool find(const char * str, const int position){ if (position >= max || position < 0){ return false; } return strncmp(&buffer[position], str, max - position) == 0; } void growMemo(){ int newSize = memo_size * 2; Column ** newMemo = new Column*[newSize]; /* Copy old memo table */ memcpy(newMemo, memo, sizeof(Column*) * memo_size); /* Zero out new entries */ memset(&newMemo[memo_size], 0, sizeof(Column*) * (newSize - memo_size)); /* Delete old memo table */ delete[] memo; /* Set up new memo table */ memo = newMemo; memo_size = newSize; } /* I'm sure this can be optimized. It only takes into account * the last position used to get line information rather than * finding a position closest to the one asked for. * So if the last position is 20 and the current position being requested * is 15 then this function will compute the information starting from 0. * If the information for 10 was computed then that should be used instead. * Maybe something like, sort the positions, find closest match lower * than the position and start from there. */ LineInfo makeLineInfo(int last_line_position, int position){ int line = line_info[last_line_position].line; int column = line_info[last_line_position].column; for (int i = last_line_position + 1; i < position; i++){ if (buffer[i] == '\n'){ line += 1; column = 1; } else { column += 1; } } return LineInfo(line, column); } void updateLineInfo(int position){ if (line_info.find(position) == line_info.end()){ if (position > last_line_info){ line_info[position] = makeLineInfo(last_line_info, position); } else { line_info[position] = makeLineInfo(0, position); } last_line_info = position; } } const LineInfo & getLineInfo(int position){ updateLineInfo(position); return line_info[position]; } /* throws a ParseException */ void reportError(const std::string & parsingContext){ std::ostringstream out; int line = 1; int column = 1; for (int i = 0; i < farthest; i++){ if (buffer[i] == '\n'){ line += 1; column = 1; } else { column += 1; } } int context = 15; int left = farthest - context; int right = farthest + context; if (left < 0){ left = 0; } if (right >= max){ right = max; } out << "Error while parsing " << parsingContext << ". Read up till line " << line << " column " << column << std::endl; std::ostringstream show; for (int i = left; i < right; i++){ char c = buffer[i]; switch (buffer[i]){ case '\n' : { show << '\\'; show << 'n'; break; } case '\r' : { show << '\\'; show << 'r'; break; } case '\t' : { show << '\\'; show << 't'; break; } default : show << c; break; } } out << "'" << show.str() << "'" << std::endl; for (int i = 0; i < farthest - left; i++){ out << " "; } out << "^" << std::endl; out << "Last successful rule trace" << std::endl; out << makeBacktrace() << std::endl; throw ParseException(out.str(), line, column); } std::string makeBacktrace(){ std::ostringstream out; bool first = true; for (std::vector<std::string>::iterator it = last_trace.begin(); it != last_trace.end(); it++){ if (!first){ out << " -> "; } else { first = false; } out << *it; } return out.str(); } inline Column & getColumn(const int position){ while (position >= memo_size){ growMemo(); } /* create columns lazily because not every position will have a column. */ if (memo[position] == NULL){ memo[position] = new Column(); } return *(memo[position]); } void update(const int position){ if (position > farthest){ farthest = position; last_trace = rule_backtrace; } } void push_rule(const char * name){ rule_backtrace.push_back(name); } void pop_rule(){ rule_backtrace.pop_back(); } ~Stream(){ delete[] temp; for (int i = 0; i < memo_size; i++){ delete memo[i]; } delete[] memo; } private: char * temp; const char * buffer; /* an array is faster and uses less memory than std::map */ Column ** memo; int memo_size; int max; int farthest; std::vector<std::string> rule_backtrace; std::vector<std::string> last_trace; int last_line_info; std::map<int, LineInfo> line_info; }; static int getCurrentLine(const Value & value){ Stream::LineInfo * info = (Stream::LineInfo*) value.getValue(); return info->line; } static int getCurrentColumn(const Value & value){ Stream::LineInfo * info = (Stream::LineInfo*) value.getValue(); return info->column; } class RuleTrace{ public: RuleTrace(Stream & stream, const char * name): stream(stream){ stream.push_rule(name); } ~RuleTrace(){ stream.pop_rule(); } Stream & stream; }; static inline bool compareChar(const char a, const char b){ return a == b; } static inline char lower(const char x){ if (x >= 'A' && x <= 'Z'){ return x - 'A' + 'a'; } return x; } static inline bool compareCharCase(const char a, const char b){ return lower(a) == lower(b); } std::string ParseException::getReason() const { return message; } int ParseException::getLine() const { return line; } int ParseException::getColumn() const { return column; } Result errorResult(-1); Result rule_start(Stream &, const int); Result rule_line(Stream &, const int, Value current); Result rule_line_end(Stream &, const int); Result rule_section(Stream &, const int); Result rule_section_line(Stream &, const int, Value section); Result rule_section_start(Stream &, const int); Result rule_name(Stream &, const int); Result rule_line_end_or_comment(Stream &, const int); Result rule_filename(Stream &, const int); Result rule_attribute(Stream &, const int); Result rule_attribute_simple(Stream &, const int); Result rule_identifier(Stream &, const int); Result rule_identifier_list(Stream &, const int); Result rule_valuelist(Stream &, const int); Result rule_value(Stream &, const int); Result rule_date(Stream &, const int); Result rule_number(Stream &, const int); Result rule_float_or_integer(Stream &, const int); template<class X> X as(const Value & value){ return (X) value.getValue(); } void addSection(const Value & section_list_value, const Value & section_value){ SectionList * sections = (SectionList*) section_list_value.getValue(); Ast::Section * section = (Ast::Section*) section_value.getValue(); if (section == 0){ throw ParseException("Cannot add null section"); } sections->push_back(section); } Ast::Section * makeSection(const Value & str, int line, int column){ Ast::Section * object = new Ast::Section(as<std::string*>(str), line, column); GC::save(object); return object; } SectionList * makeSectionList(){ SectionList * object = new SectionList(); GC::save(object); return object; } std::string * toString(const Value & input){ std::ostringstream out; for (Value::iterator it = input.getValues().begin(); it != input.getValues().end(); it++){ out << (char) (long) (*it).getValue(); } std::string * object = new std::string(out.str()); GC::save(object); return object; } double * parseDouble(const Value & value){ std::string * str = toString(value); std::istringstream get(*str); double * number = new double; get >> *number; GC::save(number); return number; } double * parseDouble(const Value & left, const Value & right){ std::string * str1 = toString(left); std::string * str2 = toString(right); std::istringstream get(*str1 + "." + *str2); double * number = new double; get >> *number; GC::save(number); return number; } std::string * toString(char front, const Value & input){ std::string * str = toString(input); str->insert(str->begin(), front); return str; } Ast::ValueAttribute * makeValueAttribute(const Value & attribute){ /* FIXME: fix line numbers here */ Ast::ValueAttribute * value = new Ast::ValueAttribute(-1, -1, as<Ast::Attribute*>(attribute)); GC::save(value); return value; } Ast::Attribute * makeAttribute(const Value & line, const Value & id, const Value & data){ Ast::AttributeSimple * object = new Ast::AttributeSimple(getCurrentLine(line), getCurrentColumn(line), as<Ast::Identifier*>(id), as<Ast::Value*>(data)); GC::save(object); return object; } Ast::Attribute * makeAttribute(const Value & id, const Value & data){ Ast::AttributeSimple * object = new Ast::AttributeSimple(as<Ast::Identifier*>(id), as<Ast::Value*>(data)); GC::save(object); return object; } Ast::Attribute * makeAttributeWithInfo(const Value & line, const Value & id){ Ast::AttributeSimple * object = new Ast::AttributeSimple(getCurrentLine(line), getCurrentColumn(line), as<Ast::Identifier*>(id)); GC::save(object); return object; } Ast::Attribute * makeAttribute(const Value & id){ Ast::AttributeSimple * object = new Ast::AttributeSimple(as<Ast::Identifier*>(id)); GC::save(object); return object; } Ast::Attribute * makeAttributeFilename(const Value & id, const Value & data){ /* TODO */ throw ParseException("makeAttributeFilename not implemented"); // return makeAttribute(id, data); } Ast::Attribute * makeIndexedAttribute(const Value & id, const Value & index, const Value & data){ /* TODO: fix this */ throw ParseException("makeIndexedAttribute not implemented"); /* Ast::Attribute * object = new Ast::Attribute(Ast::Attribute::None); GC::save(object); return object; */ } Ast::Keyword * makeKeyword(const Value & value){ /* FIXME: fix line numbers here */ Ast::Keyword * object = new Ast::Keyword(-1, -1, as<char*>(value)); GC::save(object); return object; } Ast::Attribute * makeAttributes(const Value & id, const Value & data){ /* TODO */ throw ParseException("makeAttributes not implemented"); /* Ast::Attribute * object = new Ast::Attribute(Ast::Attribute::None); GC::save(object); return object; */ } /* TODO */ Ast::Value * makeValue(){ /* FIXME: fix line numbers here */ Ast::Number * object = new Ast::Number(-1, -1, 0); GC::save(object); return object; } Ast::Value * makeValueList(const Value & line, const Value & front, const Value & rest){ std::list<Ast::Value*> values; values.push_back(as<Ast::Value*>(front)); for (Value::iterator it = rest.getValues().begin(); it != rest.getValues().end(); it++){ Ast::Value * value = as<Ast::Value*>(Value((*it).getValue())); if (value == 0){ /* FIXME! replace empty with a new node */ value = makeKeyword(Value("empty")); values.push_back(value); } else { values.push_back(value); } } Ast::ValueList * object = new Ast::ValueList(getCurrentLine(line), getCurrentColumn(line), values); GC::save(object); return object; } Ast::Identifier * makeIdentifier(const Value & front, const Value & rest){ std::list<std::string> ids; ids.push_back(*as<std::string*>(front)); for (Value::iterator it = rest.getValues().begin(); it != rest.getValues().end(); it++){ ids.push_back(*as<std::string*>(Value((*it).getValue()))); } Ast::Identifier * object = new Ast::Identifier(ids); GC::save(object); return object; } Ast::Value * makeNumber(const Value & sign, const Value & number){ double value = *(as<double*>(number)); if (sign.getValue() != 0 && strcmp(as<const char *>(sign), "-") == 0){ value = -value; } /* FIXME: fix line numbers here */ Ast::Number * object = new Ast::Number(-1, -1, value); GC::save(object); return object; } Ast::String * makeString(const Value & value){ /* FIXME: fix line numbers here */ Ast::String * object = new Ast::String(-1, -1, toString(value)); GC::save(object); return object; } Ast::Section * asSection(const Value & value){ return as<Ast::Section*>(value); } Ast::Attribute * asAttribute(const Value & value){ return as<Ast::Attribute*>(value); } Ast::Value * asValue(const Value & value){ return as<Ast::Value*>(value); } /* FIXME */ Ast::Value * makeDate(const Value & month, const Value & day, const Value & year){ /* FIXME: fix line numbers here */ Ast::Number * object = new Ast::Number(-1, -1, 0); GC::save(object); return object; } Result rule_start(Stream & stream, const int position){ RuleTrace trace_peg_111(stream, "start"); int myposition = position; try{ Value current; Result result_peg_2(myposition); { { Value value((void*) 0); value = makeSectionList(); result_peg_2.setValue(value); } current = result_peg_2.getValues(); { int position_peg_6 = result_peg_2.getPosition(); result_peg_2.reset(); do{ Result result_peg_8(result_peg_2.getPosition()); { int position_peg_10 = result_peg_8.getPosition(); result_peg_8.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_8.getPosition()))){ result_peg_8.nextPosition(); } else { result_peg_8.setPosition(position_peg_10); goto out_peg_11; } } } goto success_peg_9; out_peg_11: { int position_peg_12 = result_peg_8.getPosition(); result_peg_8.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_8.getPosition()))){ result_peg_8.nextPosition(); } else { result_peg_8.setPosition(position_peg_12); goto out_peg_13; } } } goto success_peg_9; out_peg_13: { int position_peg_14 = result_peg_8.getPosition(); { int position_peg_16 = result_peg_8.getPosition(); { result_peg_8.setValue(Value((void*) ";")); for (int i = 0; i < 1; i++){ if (compareChar(";"[i], stream.get(result_peg_8.getPosition()))){ result_peg_8.nextPosition(); } else { result_peg_8.setPosition(position_peg_16); goto out_peg_18; } } result_peg_8.reset(); do{ Result result_peg_20(result_peg_8.getPosition()); { Result result_peg_23(result_peg_20); result_peg_23.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_23.getPosition()))){ result_peg_23.nextPosition(); } else { goto not_peg_22; } } goto loop_peg_19; not_peg_22: result_peg_20.setValue(Value((void*)0)); char temp_peg_24 = stream.get(result_peg_20.getPosition()); if (temp_peg_24 != '\0'){ result_peg_20.setValue(Value((void*) (long) temp_peg_24)); result_peg_20.nextPosition(); } else { goto loop_peg_19; } } result_peg_8.addResult(result_peg_20); } while (true); loop_peg_19: ; } } goto success_peg_15; out_peg_18: { int position_peg_25 = result_peg_8.getPosition(); { result_peg_8.setValue(Value((void*) "=")); for (int i = 0; i < 1; i++){ if (compareChar("="[i], stream.get(result_peg_8.getPosition()))){ result_peg_8.nextPosition(); } else { result_peg_8.setPosition(position_peg_25); goto out_peg_27; } } result_peg_8.reset(); do{ Result result_peg_29(result_peg_8.getPosition()); { Result result_peg_32(result_peg_29); result_peg_32.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_32.getPosition()))){ result_peg_32.nextPosition(); } else { goto not_peg_31; } } goto loop_peg_28; not_peg_31: result_peg_29.setValue(Value((void*)0)); char temp_peg_33 = stream.get(result_peg_29.getPosition()); if (temp_peg_33 != '\0'){ result_peg_29.setValue(Value((void*) (long) temp_peg_33)); result_peg_29.nextPosition(); } else { goto loop_peg_28; } } result_peg_8.addResult(result_peg_29); } while (true); loop_peg_28: ; } } goto success_peg_15; out_peg_27: { int position_peg_34 = result_peg_8.getPosition(); { result_peg_8.setValue(Value((void*) "-")); for (int i = 0; i < 1; i++){ if (compareChar("-"[i], stream.get(result_peg_8.getPosition()))){ result_peg_8.nextPosition(); } else { result_peg_8.setPosition(position_peg_34); goto out_peg_36; } } result_peg_8.setValue(Value((void*) "-")); for (int i = 0; i < 1; i++){ if (compareChar("-"[i], stream.get(result_peg_8.getPosition()))){ result_peg_8.nextPosition(); } else { result_peg_8.setPosition(position_peg_34); goto out_peg_36; } } result_peg_8.reset(); do{ Result result_peg_39(result_peg_8.getPosition()); { Result result_peg_42(result_peg_39); { int position_peg_44 = result_peg_42.getPosition(); result_peg_42.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_42.getPosition()))){ result_peg_42.nextPosition(); } else { result_peg_42.setPosition(position_peg_44); goto out_peg_45; } } } goto success_peg_43; out_peg_45: { int position_peg_46 = result_peg_42.getPosition(); result_peg_42.setValue(Value((void*) "\r")); for (int i = 0; i < 1; i++){ if (compareChar("\r"[i], stream.get(result_peg_42.getPosition()))){ result_peg_42.nextPosition(); } else { result_peg_42.setPosition(position_peg_46); goto out_peg_47; } } } goto success_peg_43; out_peg_47: goto not_peg_41; success_peg_43: ; goto loop_peg_38; not_peg_41: result_peg_39.setValue(Value((void*)0)); char temp_peg_48 = stream.get(result_peg_39.getPosition()); if (temp_peg_48 != '\0'){ result_peg_39.setValue(Value((void*) (long) temp_peg_48)); result_peg_39.nextPosition(); } else { goto loop_peg_38; } } result_peg_8.addResult(result_peg_39); } while (true); loop_peg_38: ; } } goto success_peg_15; out_peg_36: result_peg_8.setPosition(position_peg_14); goto out_peg_49; success_peg_15: ; } goto success_peg_9; out_peg_49: goto loop_peg_7; success_peg_9: ; result_peg_2.addResult(result_peg_8); } while (true); loop_peg_7: ; } goto success_peg_5; goto out_peg_50; success_peg_5: ; result_peg_2.reset(); do{ Result result_peg_53(result_peg_2.getPosition()); { int position_peg_55 = result_peg_53.getPosition(); result_peg_53.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_53.getPosition()))){ result_peg_53.nextPosition(); } else { result_peg_53.setPosition(position_peg_55); goto out_peg_56; } } } goto success_peg_54; out_peg_56: { int position_peg_57 = result_peg_53.getPosition(); result_peg_53.setValue(Value((void*) "\r")); for (int i = 0; i < 1; i++){ if (compareChar("\r"[i], stream.get(result_peg_53.getPosition()))){ result_peg_53.nextPosition(); } else { result_peg_53.setPosition(position_peg_57); goto out_peg_58; } } } goto success_peg_54; out_peg_58: goto loop_peg_52; success_peg_54: ; result_peg_2.addResult(result_peg_53); } while (true); loop_peg_52: ; result_peg_2.reset(); do{ Result result_peg_61(result_peg_2.getPosition()); { result_peg_61 = rule_line(stream, result_peg_61.getPosition(), current); if (result_peg_61.error()){ goto loop_peg_60; } { int position_peg_65 = result_peg_61.getPosition(); result_peg_61.reset(); do{ Result result_peg_67(result_peg_61.getPosition()); { int position_peg_69 = result_peg_67.getPosition(); result_peg_67.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_67.getPosition()))){ result_peg_67.nextPosition(); } else { result_peg_67.setPosition(position_peg_69); goto out_peg_70; } } } goto success_peg_68; out_peg_70: { int position_peg_71 = result_peg_67.getPosition(); result_peg_67.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_67.getPosition()))){ result_peg_67.nextPosition(); } else { result_peg_67.setPosition(position_peg_71); goto out_peg_72; } } } goto success_peg_68; out_peg_72: { int position_peg_73 = result_peg_67.getPosition(); { int position_peg_75 = result_peg_67.getPosition(); { result_peg_67.setValue(Value((void*) ";")); for (int i = 0; i < 1; i++){ if (compareChar(";"[i], stream.get(result_peg_67.getPosition()))){ result_peg_67.nextPosition(); } else { result_peg_67.setPosition(position_peg_75); goto out_peg_77; } } result_peg_67.reset(); do{ Result result_peg_79(result_peg_67.getPosition()); { Result result_peg_82(result_peg_79); result_peg_82.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_82.getPosition()))){ result_peg_82.nextPosition(); } else { goto not_peg_81; } } goto loop_peg_78; not_peg_81: result_peg_79.setValue(Value((void*)0)); char temp_peg_83 = stream.get(result_peg_79.getPosition()); if (temp_peg_83 != '\0'){ result_peg_79.setValue(Value((void*) (long) temp_peg_83)); result_peg_79.nextPosition(); } else { goto loop_peg_78; } } result_peg_67.addResult(result_peg_79); } while (true); loop_peg_78: ; } } goto success_peg_74; out_peg_77: { int position_peg_84 = result_peg_67.getPosition(); { result_peg_67.setValue(Value((void*) "=")); for (int i = 0; i < 1; i++){ if (compareChar("="[i], stream.get(result_peg_67.getPosition()))){ result_peg_67.nextPosition(); } else { result_peg_67.setPosition(position_peg_84); goto out_peg_86; } } result_peg_67.reset(); do{ Result result_peg_88(result_peg_67.getPosition()); { Result result_peg_91(result_peg_88); result_peg_91.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_91.getPosition()))){ result_peg_91.nextPosition(); } else { goto not_peg_90; } } goto loop_peg_87; not_peg_90: result_peg_88.setValue(Value((void*)0)); char temp_peg_92 = stream.get(result_peg_88.getPosition()); if (temp_peg_92 != '\0'){ result_peg_88.setValue(Value((void*) (long) temp_peg_92)); result_peg_88.nextPosition(); } else { goto loop_peg_87; } } result_peg_67.addResult(result_peg_88); } while (true); loop_peg_87: ; } } goto success_peg_74; out_peg_86: { int position_peg_93 = result_peg_67.getPosition(); { result_peg_67.setValue(Value((void*) "-")); for (int i = 0; i < 1; i++){ if (compareChar("-"[i], stream.get(result_peg_67.getPosition()))){ result_peg_67.nextPosition(); } else { result_peg_67.setPosition(position_peg_93); goto out_peg_95; } } result_peg_67.setValue(Value((void*) "-")); for (int i = 0; i < 1; i++){ if (compareChar("-"[i], stream.get(result_peg_67.getPosition()))){ result_peg_67.nextPosition(); } else { result_peg_67.setPosition(position_peg_93); goto out_peg_95; } } result_peg_67.reset(); do{ Result result_peg_98(result_peg_67.getPosition()); { Result result_peg_101(result_peg_98); { int position_peg_103 = result_peg_101.getPosition(); result_peg_101.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_101.getPosition()))){ result_peg_101.nextPosition(); } else { result_peg_101.setPosition(position_peg_103); goto out_peg_104; } } } goto success_peg_102; out_peg_104: { int position_peg_105 = result_peg_101.getPosition(); result_peg_101.setValue(Value((void*) "\r")); for (int i = 0; i < 1; i++){ if (compareChar("\r"[i], stream.get(result_peg_101.getPosition()))){ result_peg_101.nextPosition(); } else { result_peg_101.setPosition(position_peg_105); goto out_peg_106; } } } goto success_peg_102; out_peg_106: goto not_peg_100; success_peg_102: ; goto loop_peg_97; not_peg_100: result_peg_98.setValue(Value((void*)0)); char temp_peg_107 = stream.get(result_peg_98.getPosition()); if (temp_peg_107 != '\0'){ result_peg_98.setValue(Value((void*) (long) temp_peg_107)); result_peg_98.nextPosition(); } else { goto loop_peg_97; } } result_peg_67.addResult(result_peg_98); } while (true); loop_peg_97: ; } } goto success_peg_74; out_peg_95: result_peg_67.setPosition(position_peg_73); goto out_peg_108; success_peg_74: ; } goto success_peg_68; out_peg_108: goto loop_peg_66; success_peg_68: ; result_peg_61.addResult(result_peg_67); } while (true); loop_peg_66: ; } goto success_peg_64; goto loop_peg_60; success_peg_64: ; int save_peg_109 = result_peg_61.getPosition(); result_peg_61 = rule_line_end(stream, result_peg_61.getPosition()); if (result_peg_61.error()){ result_peg_61 = Result(save_peg_109); result_peg_61.setValue(Value((void*) 0)); } } result_peg_2.addResult(result_peg_61); } while (true); loop_peg_60: ; if ('\0' == stream.get(result_peg_2.getPosition())){ result_peg_2.nextPosition(); result_peg_2.setValue(Value((void *) '\0')); } else { goto out_peg_50; } { Value value((void*) 0); value = current; GC::cleanup(as<SectionList*>(value)); result_peg_2.setValue(value); } } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_50: stream.update(errorResult.getPosition()); } catch (...){ GC::cleanup(0); throw; } return errorResult; } Result rule_line(Stream & stream, const int position, Value current){ RuleTrace trace_peg_70(stream, "line"); int myposition = position; Result result_peg_2(myposition); { { int position_peg_5 = result_peg_2.getPosition(); result_peg_2.reset(); do{ Result result_peg_7(result_peg_2.getPosition()); { int position_peg_9 = result_peg_7.getPosition(); result_peg_7.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_7.getPosition()))){ result_peg_7.nextPosition(); } else { result_peg_7.setPosition(position_peg_9); goto out_peg_10; } } } goto success_peg_8; out_peg_10: { int position_peg_11 = result_peg_7.getPosition(); result_peg_7.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_7.getPosition()))){ result_peg_7.nextPosition(); } else { result_peg_7.setPosition(position_peg_11); goto out_peg_12; } } } goto success_peg_8; out_peg_12: goto loop_peg_6; success_peg_8: ; result_peg_2.addResult(result_peg_7); } while (true); loop_peg_6: ; } goto success_peg_4; goto out_peg_13; success_peg_4: ; { int position_peg_15 = result_peg_2.getPosition(); { result_peg_2.setValue(Value((void*) ";")); for (int i = 0; i < 1; i++){ if (compareChar(";"[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { result_peg_2.setPosition(position_peg_15); goto out_peg_17; } } result_peg_2.reset(); do{ Result result_peg_19(result_peg_2.getPosition()); { Result result_peg_22(result_peg_19); result_peg_22.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_22.getPosition()))){ result_peg_22.nextPosition(); } else { goto not_peg_21; } } goto loop_peg_18; not_peg_21: result_peg_19.setValue(Value((void*)0)); char temp_peg_23 = stream.get(result_peg_19.getPosition()); if (temp_peg_23 != '\0'){ result_peg_19.setValue(Value((void*) (long) temp_peg_23)); result_peg_19.nextPosition(); } else { goto loop_peg_18; } } result_peg_2.addResult(result_peg_19); } while (true); loop_peg_18: ; } } goto success_peg_14; out_peg_17: { int position_peg_24 = result_peg_2.getPosition(); { result_peg_2.setValue(Value((void*) "=")); for (int i = 0; i < 1; i++){ if (compareChar("="[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { result_peg_2.setPosition(position_peg_24); goto out_peg_26; } } result_peg_2.reset(); do{ Result result_peg_28(result_peg_2.getPosition()); { Result result_peg_31(result_peg_28); result_peg_31.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_31.getPosition()))){ result_peg_31.nextPosition(); } else { goto not_peg_30; } } goto loop_peg_27; not_peg_30: result_peg_28.setValue(Value((void*)0)); char temp_peg_32 = stream.get(result_peg_28.getPosition()); if (temp_peg_32 != '\0'){ result_peg_28.setValue(Value((void*) (long) temp_peg_32)); result_peg_28.nextPosition(); } else { goto loop_peg_27; } } result_peg_2.addResult(result_peg_28); } while (true); loop_peg_27: ; } } goto success_peg_14; out_peg_26: { int position_peg_33 = result_peg_2.getPosition(); { result_peg_2.setValue(Value((void*) "-")); for (int i = 0; i < 1; i++){ if (compareChar("-"[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { result_peg_2.setPosition(position_peg_33); goto out_peg_35; } } result_peg_2.setValue(Value((void*) "-")); for (int i = 0; i < 1; i++){ if (compareChar("-"[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { result_peg_2.setPosition(position_peg_33); goto out_peg_35; } } result_peg_2.reset(); do{ Result result_peg_38(result_peg_2.getPosition()); { Result result_peg_41(result_peg_38); { int position_peg_43 = result_peg_41.getPosition(); result_peg_41.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_41.getPosition()))){ result_peg_41.nextPosition(); } else { result_peg_41.setPosition(position_peg_43); goto out_peg_44; } } } goto success_peg_42; out_peg_44: { int position_peg_45 = result_peg_41.getPosition(); result_peg_41.setValue(Value((void*) "\r")); for (int i = 0; i < 1; i++){ if (compareChar("\r"[i], stream.get(result_peg_41.getPosition()))){ result_peg_41.nextPosition(); } else { result_peg_41.setPosition(position_peg_45); goto out_peg_46; } } } goto success_peg_42; out_peg_46: goto not_peg_40; success_peg_42: ; goto loop_peg_37; not_peg_40: result_peg_38.setValue(Value((void*)0)); char temp_peg_47 = stream.get(result_peg_38.getPosition()); if (temp_peg_47 != '\0'){ result_peg_38.setValue(Value((void*) (long) temp_peg_47)); result_peg_38.nextPosition(); } else { goto loop_peg_37; } } result_peg_2.addResult(result_peg_38); } while (true); loop_peg_37: ; } } goto success_peg_14; out_peg_35: goto out_peg_13; success_peg_14: ; } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_13: Result result_peg_48(myposition); { { int position_peg_51 = result_peg_48.getPosition(); result_peg_48.reset(); do{ Result result_peg_53(result_peg_48.getPosition()); { int position_peg_55 = result_peg_53.getPosition(); result_peg_53.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_53.getPosition()))){ result_peg_53.nextPosition(); } else { result_peg_53.setPosition(position_peg_55); goto out_peg_56; } } } goto success_peg_54; out_peg_56: { int position_peg_57 = result_peg_53.getPosition(); result_peg_53.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_53.getPosition()))){ result_peg_53.nextPosition(); } else { result_peg_53.setPosition(position_peg_57); goto out_peg_58; } } } goto success_peg_54; out_peg_58: goto loop_peg_52; success_peg_54: ; result_peg_48.addResult(result_peg_53); } while (true); loop_peg_52: ; } goto success_peg_50; goto out_peg_59; success_peg_50: ; result_peg_48 = rule_section(stream, result_peg_48.getPosition()); if (result_peg_48.error()){ goto out_peg_59; } Result result_peg_60 = result_peg_48; { Value value((void*) 0); addSection(current, result_peg_60.getValues()); result_peg_48.setValue(value); } } stream.update(result_peg_48.getPosition()); return result_peg_48; out_peg_59: Result result_peg_61(myposition); result_peg_61.reset(); do{ Result result_peg_63(result_peg_61.getPosition()); { int position_peg_65 = result_peg_63.getPosition(); result_peg_63.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_63.getPosition()))){ result_peg_63.nextPosition(); } else { result_peg_63.setPosition(position_peg_65); goto out_peg_66; } } } goto success_peg_64; out_peg_66: { int position_peg_67 = result_peg_63.getPosition(); result_peg_63.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_63.getPosition()))){ result_peg_63.nextPosition(); } else { result_peg_63.setPosition(position_peg_67); goto out_peg_68; } } } goto success_peg_64; out_peg_68: goto loop_peg_62; success_peg_64: ; result_peg_61.addResult(result_peg_63); } while (true); loop_peg_62: if (result_peg_61.matches() == 0){ goto out_peg_69; } stream.update(result_peg_61.getPosition()); return result_peg_61; out_peg_69: stream.update(errorResult.getPosition()); return errorResult; } Result rule_line_end(Stream & stream, const int position){ RuleTrace trace_peg_15(stream, "line_end"); int myposition = position; Result result_peg_2(myposition); result_peg_2.reset(); do{ Result result_peg_4(result_peg_2.getPosition()); { int position_peg_6 = result_peg_4.getPosition(); result_peg_4.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_4.getPosition()))){ result_peg_4.nextPosition(); } else { result_peg_4.setPosition(position_peg_6); goto out_peg_7; } } } goto success_peg_5; out_peg_7: { int position_peg_8 = result_peg_4.getPosition(); result_peg_4.setValue(Value((void*) "\r")); for (int i = 0; i < 1; i++){ if (compareChar("\r"[i], stream.get(result_peg_4.getPosition()))){ result_peg_4.nextPosition(); } else { result_peg_4.setPosition(position_peg_8); goto out_peg_9; } } } goto success_peg_5; out_peg_9: goto loop_peg_3; success_peg_5: ; result_peg_2.addResult(result_peg_4); } while (true); loop_peg_3: if (result_peg_2.matches() == 0){ goto out_peg_10; } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_10: Result result_peg_11(myposition); { Result result_peg_13(result_peg_11.getPosition()); if ('\0' == stream.get(result_peg_13.getPosition())){ result_peg_13.nextPosition(); result_peg_13.setValue(Value((void *) '\0')); } else { goto out_peg_14; } } stream.update(result_peg_11.getPosition()); return result_peg_11; out_peg_14: stream.update(errorResult.getPosition()); return errorResult; } Result rule_section(Stream & stream, const int position){ RuleTrace trace_peg_112(stream, "section"); int myposition = position; Value line; Value name; Value ast; Result result_peg_2(myposition); { Stream::LineInfo line_info_peg_4 = stream.getLineInfo(result_peg_2.getPosition()); line = &line_info_peg_4; result_peg_2 = rule_section_start(stream, result_peg_2.getPosition()); if (result_peg_2.error()){ goto out_peg_6; } name = result_peg_2.getValues(); { Value value((void*) 0); value = makeSection(name, getCurrentLine(line), getCurrentColumn(line)); result_peg_2.setValue(value); } ast = result_peg_2.getValues(); { int position_peg_10 = result_peg_2.getPosition(); result_peg_2.reset(); do{ Result result_peg_12(result_peg_2.getPosition()); { int position_peg_14 = result_peg_12.getPosition(); result_peg_12.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_12.getPosition()))){ result_peg_12.nextPosition(); } else { result_peg_12.setPosition(position_peg_14); goto out_peg_15; } } } goto success_peg_13; out_peg_15: { int position_peg_16 = result_peg_12.getPosition(); result_peg_12.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_12.getPosition()))){ result_peg_12.nextPosition(); } else { result_peg_12.setPosition(position_peg_16); goto out_peg_17; } } } goto success_peg_13; out_peg_17: { int position_peg_18 = result_peg_12.getPosition(); { int position_peg_20 = result_peg_12.getPosition(); { result_peg_12.setValue(Value((void*) ";")); for (int i = 0; i < 1; i++){ if (compareChar(";"[i], stream.get(result_peg_12.getPosition()))){ result_peg_12.nextPosition(); } else { result_peg_12.setPosition(position_peg_20); goto out_peg_22; } } result_peg_12.reset(); do{ Result result_peg_24(result_peg_12.getPosition()); { Result result_peg_27(result_peg_24); result_peg_27.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_27.getPosition()))){ result_peg_27.nextPosition(); } else { goto not_peg_26; } } goto loop_peg_23; not_peg_26: result_peg_24.setValue(Value((void*)0)); char temp_peg_28 = stream.get(result_peg_24.getPosition()); if (temp_peg_28 != '\0'){ result_peg_24.setValue(Value((void*) (long) temp_peg_28)); result_peg_24.nextPosition(); } else { goto loop_peg_23; } } result_peg_12.addResult(result_peg_24); } while (true); loop_peg_23: ; } } goto success_peg_19; out_peg_22: { int position_peg_29 = result_peg_12.getPosition(); { result_peg_12.setValue(Value((void*) "=")); for (int i = 0; i < 1; i++){ if (compareChar("="[i], stream.get(result_peg_12.getPosition()))){ result_peg_12.nextPosition(); } else { result_peg_12.setPosition(position_peg_29); goto out_peg_31; } } result_peg_12.reset(); do{ Result result_peg_33(result_peg_12.getPosition()); { Result result_peg_36(result_peg_33); result_peg_36.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_36.getPosition()))){ result_peg_36.nextPosition(); } else { goto not_peg_35; } } goto loop_peg_32; not_peg_35: result_peg_33.setValue(Value((void*)0)); char temp_peg_37 = stream.get(result_peg_33.getPosition()); if (temp_peg_37 != '\0'){ result_peg_33.setValue(Value((void*) (long) temp_peg_37)); result_peg_33.nextPosition(); } else { goto loop_peg_32; } } result_peg_12.addResult(result_peg_33); } while (true); loop_peg_32: ; } } goto success_peg_19; out_peg_31: { int position_peg_38 = result_peg_12.getPosition(); { result_peg_12.setValue(Value((void*) "-")); for (int i = 0; i < 1; i++){ if (compareChar("-"[i], stream.get(result_peg_12.getPosition()))){ result_peg_12.nextPosition(); } else { result_peg_12.setPosition(position_peg_38); goto out_peg_40; } } result_peg_12.setValue(Value((void*) "-")); for (int i = 0; i < 1; i++){ if (compareChar("-"[i], stream.get(result_peg_12.getPosition()))){ result_peg_12.nextPosition(); } else { result_peg_12.setPosition(position_peg_38); goto out_peg_40; } } result_peg_12.reset(); do{ Result result_peg_43(result_peg_12.getPosition()); { Result result_peg_46(result_peg_43); { int position_peg_48 = result_peg_46.getPosition(); result_peg_46.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_46.getPosition()))){ result_peg_46.nextPosition(); } else { result_peg_46.setPosition(position_peg_48); goto out_peg_49; } } } goto success_peg_47; out_peg_49: { int position_peg_50 = result_peg_46.getPosition(); result_peg_46.setValue(Value((void*) "\r")); for (int i = 0; i < 1; i++){ if (compareChar("\r"[i], stream.get(result_peg_46.getPosition()))){ result_peg_46.nextPosition(); } else { result_peg_46.setPosition(position_peg_50); goto out_peg_51; } } } goto success_peg_47; out_peg_51: goto not_peg_45; success_peg_47: ; goto loop_peg_42; not_peg_45: result_peg_43.setValue(Value((void*)0)); char temp_peg_52 = stream.get(result_peg_43.getPosition()); if (temp_peg_52 != '\0'){ result_peg_43.setValue(Value((void*) (long) temp_peg_52)); result_peg_43.nextPosition(); } else { goto loop_peg_42; } } result_peg_12.addResult(result_peg_43); } while (true); loop_peg_42: ; } } goto success_peg_19; out_peg_40: result_peg_12.setPosition(position_peg_18); goto out_peg_53; success_peg_19: ; } goto success_peg_13; out_peg_53: goto loop_peg_11; success_peg_13: ; result_peg_2.addResult(result_peg_12); } while (true); loop_peg_11: ; } goto success_peg_9; goto out_peg_6; success_peg_9: ; result_peg_2.reset(); do{ Result result_peg_56(result_peg_2.getPosition()); { int position_peg_58 = result_peg_56.getPosition(); result_peg_56.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_56.getPosition()))){ result_peg_56.nextPosition(); } else { result_peg_56.setPosition(position_peg_58); goto out_peg_59; } } } goto success_peg_57; out_peg_59: { int position_peg_60 = result_peg_56.getPosition(); result_peg_56.setValue(Value((void*) "\r")); for (int i = 0; i < 1; i++){ if (compareChar("\r"[i], stream.get(result_peg_56.getPosition()))){ result_peg_56.nextPosition(); } else { result_peg_56.setPosition(position_peg_60); goto out_peg_61; } } } goto success_peg_57; out_peg_61: goto loop_peg_55; success_peg_57: ; result_peg_2.addResult(result_peg_56); } while (true); loop_peg_55: if (result_peg_2.matches() == 0){ goto out_peg_6; } result_peg_2.reset(); do{ Result result_peg_64(result_peg_2.getPosition()); { result_peg_64 = rule_section_line(stream, result_peg_64.getPosition(), ast); if (result_peg_64.error()){ goto loop_peg_63; } { int position_peg_68 = result_peg_64.getPosition(); result_peg_64.reset(); do{ Result result_peg_70(result_peg_64.getPosition()); { int position_peg_72 = result_peg_70.getPosition(); result_peg_70.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_70.getPosition()))){ result_peg_70.nextPosition(); } else { result_peg_70.setPosition(position_peg_72); goto out_peg_73; } } } goto success_peg_71; out_peg_73: { int position_peg_74 = result_peg_70.getPosition(); result_peg_70.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_70.getPosition()))){ result_peg_70.nextPosition(); } else { result_peg_70.setPosition(position_peg_74); goto out_peg_75; } } } goto success_peg_71; out_peg_75: { int position_peg_76 = result_peg_70.getPosition(); { int position_peg_78 = result_peg_70.getPosition(); { result_peg_70.setValue(Value((void*) ";")); for (int i = 0; i < 1; i++){ if (compareChar(";"[i], stream.get(result_peg_70.getPosition()))){ result_peg_70.nextPosition(); } else { result_peg_70.setPosition(position_peg_78); goto out_peg_80; } } result_peg_70.reset(); do{ Result result_peg_82(result_peg_70.getPosition()); { Result result_peg_85(result_peg_82); result_peg_85.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_85.getPosition()))){ result_peg_85.nextPosition(); } else { goto not_peg_84; } } goto loop_peg_81; not_peg_84: result_peg_82.setValue(Value((void*)0)); char temp_peg_86 = stream.get(result_peg_82.getPosition()); if (temp_peg_86 != '\0'){ result_peg_82.setValue(Value((void*) (long) temp_peg_86)); result_peg_82.nextPosition(); } else { goto loop_peg_81; } } result_peg_70.addResult(result_peg_82); } while (true); loop_peg_81: ; } } goto success_peg_77; out_peg_80: { int position_peg_87 = result_peg_70.getPosition(); { result_peg_70.setValue(Value((void*) "=")); for (int i = 0; i < 1; i++){ if (compareChar("="[i], stream.get(result_peg_70.getPosition()))){ result_peg_70.nextPosition(); } else { result_peg_70.setPosition(position_peg_87); goto out_peg_89; } } result_peg_70.reset(); do{ Result result_peg_91(result_peg_70.getPosition()); { Result result_peg_94(result_peg_91); result_peg_94.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_94.getPosition()))){ result_peg_94.nextPosition(); } else { goto not_peg_93; } } goto loop_peg_90; not_peg_93: result_peg_91.setValue(Value((void*)0)); char temp_peg_95 = stream.get(result_peg_91.getPosition()); if (temp_peg_95 != '\0'){ result_peg_91.setValue(Value((void*) (long) temp_peg_95)); result_peg_91.nextPosition(); } else { goto loop_peg_90; } } result_peg_70.addResult(result_peg_91); } while (true); loop_peg_90: ; } } goto success_peg_77; out_peg_89: { int position_peg_96 = result_peg_70.getPosition(); { result_peg_70.setValue(Value((void*) "-")); for (int i = 0; i < 1; i++){ if (compareChar("-"[i], stream.get(result_peg_70.getPosition()))){ result_peg_70.nextPosition(); } else { result_peg_70.setPosition(position_peg_96); goto out_peg_98; } } result_peg_70.setValue(Value((void*) "-")); for (int i = 0; i < 1; i++){ if (compareChar("-"[i], stream.get(result_peg_70.getPosition()))){ result_peg_70.nextPosition(); } else { result_peg_70.setPosition(position_peg_96); goto out_peg_98; } } result_peg_70.reset(); do{ Result result_peg_101(result_peg_70.getPosition()); { Result result_peg_104(result_peg_101); { int position_peg_106 = result_peg_104.getPosition(); result_peg_104.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_104.getPosition()))){ result_peg_104.nextPosition(); } else { result_peg_104.setPosition(position_peg_106); goto out_peg_107; } } } goto success_peg_105; out_peg_107: { int position_peg_108 = result_peg_104.getPosition(); result_peg_104.setValue(Value((void*) "\r")); for (int i = 0; i < 1; i++){ if (compareChar("\r"[i], stream.get(result_peg_104.getPosition()))){ result_peg_104.nextPosition(); } else { result_peg_104.setPosition(position_peg_108); goto out_peg_109; } } } goto success_peg_105; out_peg_109: goto not_peg_103; success_peg_105: ; goto loop_peg_100; not_peg_103: result_peg_101.setValue(Value((void*)0)); char temp_peg_110 = stream.get(result_peg_101.getPosition()); if (temp_peg_110 != '\0'){ result_peg_101.setValue(Value((void*) (long) temp_peg_110)); result_peg_101.nextPosition(); } else { goto loop_peg_100; } } result_peg_70.addResult(result_peg_101); } while (true); loop_peg_100: ; } } goto success_peg_77; out_peg_98: result_peg_70.setPosition(position_peg_76); goto out_peg_111; success_peg_77: ; } goto success_peg_71; out_peg_111: goto loop_peg_69; success_peg_71: ; result_peg_64.addResult(result_peg_70); } while (true); loop_peg_69: ; } goto success_peg_67; goto loop_peg_63; success_peg_67: ; result_peg_64 = rule_line_end(stream, result_peg_64.getPosition()); if (result_peg_64.error()){ goto loop_peg_63; } } result_peg_2.addResult(result_peg_64); } while (true); loop_peg_63: ; { Value value((void*) 0); value = ast; result_peg_2.setValue(value); } } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_6: stream.update(errorResult.getPosition()); return errorResult; } Result rule_section_line(Stream & stream, const int position, Value section){ RuleTrace trace_peg_103(stream, "section_line"); int myposition = position; Value data; Result result_peg_2(myposition); { { int position_peg_5 = result_peg_2.getPosition(); result_peg_2.reset(); do{ Result result_peg_7(result_peg_2.getPosition()); { int position_peg_9 = result_peg_7.getPosition(); result_peg_7.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_7.getPosition()))){ result_peg_7.nextPosition(); } else { result_peg_7.setPosition(position_peg_9); goto out_peg_10; } } } goto success_peg_8; out_peg_10: { int position_peg_11 = result_peg_7.getPosition(); result_peg_7.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_7.getPosition()))){ result_peg_7.nextPosition(); } else { result_peg_7.setPosition(position_peg_11); goto out_peg_12; } } } goto success_peg_8; out_peg_12: goto loop_peg_6; success_peg_8: ; result_peg_2.addResult(result_peg_7); } while (true); loop_peg_6: ; } goto success_peg_4; goto out_peg_13; success_peg_4: ; { int position_peg_15 = result_peg_2.getPosition(); { result_peg_2.setValue(Value((void*) ";")); for (int i = 0; i < 1; i++){ if (compareChar(";"[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { result_peg_2.setPosition(position_peg_15); goto out_peg_17; } } result_peg_2.reset(); do{ Result result_peg_19(result_peg_2.getPosition()); { Result result_peg_22(result_peg_19); result_peg_22.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_22.getPosition()))){ result_peg_22.nextPosition(); } else { goto not_peg_21; } } goto loop_peg_18; not_peg_21: result_peg_19.setValue(Value((void*)0)); char temp_peg_23 = stream.get(result_peg_19.getPosition()); if (temp_peg_23 != '\0'){ result_peg_19.setValue(Value((void*) (long) temp_peg_23)); result_peg_19.nextPosition(); } else { goto loop_peg_18; } } result_peg_2.addResult(result_peg_19); } while (true); loop_peg_18: ; } } goto success_peg_14; out_peg_17: { int position_peg_24 = result_peg_2.getPosition(); { result_peg_2.setValue(Value((void*) "=")); for (int i = 0; i < 1; i++){ if (compareChar("="[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { result_peg_2.setPosition(position_peg_24); goto out_peg_26; } } result_peg_2.reset(); do{ Result result_peg_28(result_peg_2.getPosition()); { Result result_peg_31(result_peg_28); result_peg_31.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_31.getPosition()))){ result_peg_31.nextPosition(); } else { goto not_peg_30; } } goto loop_peg_27; not_peg_30: result_peg_28.setValue(Value((void*)0)); char temp_peg_32 = stream.get(result_peg_28.getPosition()); if (temp_peg_32 != '\0'){ result_peg_28.setValue(Value((void*) (long) temp_peg_32)); result_peg_28.nextPosition(); } else { goto loop_peg_27; } } result_peg_2.addResult(result_peg_28); } while (true); loop_peg_27: ; } } goto success_peg_14; out_peg_26: { int position_peg_33 = result_peg_2.getPosition(); { result_peg_2.setValue(Value((void*) "-")); for (int i = 0; i < 1; i++){ if (compareChar("-"[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { result_peg_2.setPosition(position_peg_33); goto out_peg_35; } } result_peg_2.setValue(Value((void*) "-")); for (int i = 0; i < 1; i++){ if (compareChar("-"[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { result_peg_2.setPosition(position_peg_33); goto out_peg_35; } } result_peg_2.reset(); do{ Result result_peg_38(result_peg_2.getPosition()); { Result result_peg_41(result_peg_38); { int position_peg_43 = result_peg_41.getPosition(); result_peg_41.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_41.getPosition()))){ result_peg_41.nextPosition(); } else { result_peg_41.setPosition(position_peg_43); goto out_peg_44; } } } goto success_peg_42; out_peg_44: { int position_peg_45 = result_peg_41.getPosition(); result_peg_41.setValue(Value((void*) "\r")); for (int i = 0; i < 1; i++){ if (compareChar("\r"[i], stream.get(result_peg_41.getPosition()))){ result_peg_41.nextPosition(); } else { result_peg_41.setPosition(position_peg_45); goto out_peg_46; } } } goto success_peg_42; out_peg_46: goto not_peg_40; success_peg_42: ; goto loop_peg_37; not_peg_40: result_peg_38.setValue(Value((void*)0)); char temp_peg_47 = stream.get(result_peg_38.getPosition()); if (temp_peg_47 != '\0'){ result_peg_38.setValue(Value((void*) (long) temp_peg_47)); result_peg_38.nextPosition(); } else { goto loop_peg_37; } } result_peg_2.addResult(result_peg_38); } while (true); loop_peg_37: ; } } goto success_peg_14; out_peg_35: goto out_peg_13; success_peg_14: ; } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_13: Result result_peg_48(myposition); { { int position_peg_51 = result_peg_48.getPosition(); result_peg_48.reset(); do{ Result result_peg_53(result_peg_48.getPosition()); { int position_peg_55 = result_peg_53.getPosition(); result_peg_53.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_53.getPosition()))){ result_peg_53.nextPosition(); } else { result_peg_53.setPosition(position_peg_55); goto out_peg_56; } } } goto success_peg_54; out_peg_56: { int position_peg_57 = result_peg_53.getPosition(); result_peg_53.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_53.getPosition()))){ result_peg_53.nextPosition(); } else { result_peg_53.setPosition(position_peg_57); goto out_peg_58; } } } goto success_peg_54; out_peg_58: goto loop_peg_52; success_peg_54: ; result_peg_48.addResult(result_peg_53); } while (true); loop_peg_52: ; } goto success_peg_50; goto out_peg_59; success_peg_50: ; result_peg_48 = rule_attribute(stream, result_peg_48.getPosition()); if (result_peg_48.error()){ goto out_peg_59; } data = result_peg_48.getValues(); { Value value((void*) 0); asSection(section)->addAttribute(asAttribute(data)); result_peg_48.setValue(value); } } stream.update(result_peg_48.getPosition()); return result_peg_48; out_peg_59: Result result_peg_61(myposition); { { int position_peg_64 = result_peg_61.getPosition(); result_peg_61.reset(); do{ Result result_peg_66(result_peg_61.getPosition()); { int position_peg_68 = result_peg_66.getPosition(); result_peg_66.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_66.getPosition()))){ result_peg_66.nextPosition(); } else { result_peg_66.setPosition(position_peg_68); goto out_peg_69; } } } goto success_peg_67; out_peg_69: { int position_peg_70 = result_peg_66.getPosition(); result_peg_66.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_66.getPosition()))){ result_peg_66.nextPosition(); } else { result_peg_66.setPosition(position_peg_70); goto out_peg_71; } } } goto success_peg_67; out_peg_71: goto loop_peg_65; success_peg_67: ; result_peg_61.addResult(result_peg_66); } while (true); loop_peg_65: ; } goto success_peg_63; goto out_peg_72; success_peg_63: ; { int position_peg_75 = result_peg_61.getPosition(); { result_peg_61.setValue(Value((void*) "loopstart")); for (int i = 0; i < 9; i++){ if (compareCharCase("loopstart"[i], stream.get(result_peg_61.getPosition()))){ result_peg_61.nextPosition(); } else { result_peg_61.setPosition(position_peg_75); goto out_peg_77; } } { Value value((void*) 0); value = makeValue(); result_peg_61.setValue(value); } } } goto success_peg_74; out_peg_77: goto out_peg_72; success_peg_74: ; data = result_peg_61.getValues(); { Value value((void*) 0); asSection(section)->addValue(asValue(data)); result_peg_61.setValue(value); } } stream.update(result_peg_61.getPosition()); return result_peg_61; out_peg_72: Result result_peg_78(myposition); { { int position_peg_81 = result_peg_78.getPosition(); result_peg_78.reset(); do{ Result result_peg_83(result_peg_78.getPosition()); { int position_peg_85 = result_peg_83.getPosition(); result_peg_83.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_83.getPosition()))){ result_peg_83.nextPosition(); } else { result_peg_83.setPosition(position_peg_85); goto out_peg_86; } } } goto success_peg_84; out_peg_86: { int position_peg_87 = result_peg_83.getPosition(); result_peg_83.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_83.getPosition()))){ result_peg_83.nextPosition(); } else { result_peg_83.setPosition(position_peg_87); goto out_peg_88; } } } goto success_peg_84; out_peg_88: goto loop_peg_82; success_peg_84: ; result_peg_78.addResult(result_peg_83); } while (true); loop_peg_82: ; } goto success_peg_80; goto out_peg_89; success_peg_80: ; result_peg_78 = rule_valuelist(stream, result_peg_78.getPosition()); if (result_peg_78.error()){ goto out_peg_89; } data = result_peg_78.getValues(); { Value value((void*) 0); asSection(section)->addValue(asValue(data)); result_peg_78.setValue(value); } } stream.update(result_peg_78.getPosition()); return result_peg_78; out_peg_89: Result result_peg_91(myposition); { result_peg_91.reset(); do{ Result result_peg_94(result_peg_91.getPosition()); { int position_peg_96 = result_peg_94.getPosition(); result_peg_94.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_94.getPosition()))){ result_peg_94.nextPosition(); } else { result_peg_94.setPosition(position_peg_96); goto out_peg_97; } } } goto success_peg_95; out_peg_97: { int position_peg_98 = result_peg_94.getPosition(); result_peg_94.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_94.getPosition()))){ result_peg_94.nextPosition(); } else { result_peg_94.setPosition(position_peg_98); goto out_peg_99; } } } goto success_peg_95; out_peg_99: goto loop_peg_93; success_peg_95: ; result_peg_91.addResult(result_peg_94); } while (true); loop_peg_93: if (result_peg_91.matches() == 0){ goto out_peg_100; } Result result_peg_102(result_peg_91); result_peg_102.setValue(Value((void*) "[")); for (int i = 0; i < 1; i++){ if (compareChar("["[i], stream.get(result_peg_102.getPosition()))){ result_peg_102.nextPosition(); } else { goto not_peg_101; } } goto out_peg_100; not_peg_101: result_peg_91.setValue(Value((void*)0)); } stream.update(result_peg_91.getPosition()); return result_peg_91; out_peg_100: stream.update(errorResult.getPosition()); return errorResult; } Result rule_section_start(Stream & stream, const int position){ RuleTrace trace_peg_33(stream, "section_start"); int myposition = position; Value data; Result result_peg_2(myposition); { result_peg_2.setValue(Value((void*) "[")); for (int i = 0; i < 1; i++){ if (compareChar("["[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { goto out_peg_4; } } { int position_peg_7 = result_peg_2.getPosition(); result_peg_2.reset(); do{ Result result_peg_9(result_peg_2.getPosition()); { int position_peg_11 = result_peg_9.getPosition(); result_peg_9.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_9.getPosition()))){ result_peg_9.nextPosition(); } else { result_peg_9.setPosition(position_peg_11); goto out_peg_12; } } } goto success_peg_10; out_peg_12: { int position_peg_13 = result_peg_9.getPosition(); result_peg_9.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_9.getPosition()))){ result_peg_9.nextPosition(); } else { result_peg_9.setPosition(position_peg_13); goto out_peg_14; } } } goto success_peg_10; out_peg_14: goto loop_peg_8; success_peg_10: ; result_peg_2.addResult(result_peg_9); } while (true); loop_peg_8: ; } goto success_peg_6; goto out_peg_4; success_peg_6: ; result_peg_2.reset(); do{ Result result_peg_17(result_peg_2.getPosition()); { Result result_peg_20(result_peg_17); result_peg_20.setValue(Value((void*) "]")); for (int i = 0; i < 1; i++){ if (compareChar("]"[i], stream.get(result_peg_20.getPosition()))){ result_peg_20.nextPosition(); } else { goto not_peg_19; } } goto loop_peg_16; not_peg_19: result_peg_17.setValue(Value((void*)0)); char temp_peg_21 = stream.get(result_peg_17.getPosition()); if (temp_peg_21 != '\0'){ result_peg_17.setValue(Value((void*) (long) temp_peg_21)); result_peg_17.nextPosition(); } else { goto loop_peg_16; } } result_peg_2.addResult(result_peg_17); } while (true); loop_peg_16: if (result_peg_2.matches() == 0){ goto out_peg_4; } data = result_peg_2.getValues(); { int position_peg_24 = result_peg_2.getPosition(); result_peg_2.reset(); do{ Result result_peg_26(result_peg_2.getPosition()); { int position_peg_28 = result_peg_26.getPosition(); result_peg_26.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_26.getPosition()))){ result_peg_26.nextPosition(); } else { result_peg_26.setPosition(position_peg_28); goto out_peg_29; } } } goto success_peg_27; out_peg_29: { int position_peg_30 = result_peg_26.getPosition(); result_peg_26.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_26.getPosition()))){ result_peg_26.nextPosition(); } else { result_peg_26.setPosition(position_peg_30); goto out_peg_31; } } } goto success_peg_27; out_peg_31: goto loop_peg_25; success_peg_27: ; result_peg_2.addResult(result_peg_26); } while (true); loop_peg_25: ; } goto success_peg_23; goto out_peg_4; success_peg_23: ; result_peg_2.setValue(Value((void*) "]")); for (int i = 0; i < 1; i++){ if (compareChar("]"[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { goto out_peg_4; } } { Value value((void*) 0); value = toString(data); result_peg_2.setValue(value); } } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_4: stream.update(errorResult.getPosition()); return errorResult; } Result rule_name(Stream & stream, const int position){ RuleTrace trace_peg_25(stream, "name"); int myposition = position; Result result_peg_2(myposition); { { int position_peg_5 = result_peg_2.getPosition(); char letter_peg_6 = stream.get(result_peg_2.getPosition()); if (letter_peg_6 != '\0' && strchr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_", letter_peg_6) != NULL){ result_peg_2.nextPosition(); result_peg_2.setValue(Value((void*) (long) letter_peg_6)); } else { result_peg_2.setPosition(position_peg_5); goto out_peg_7; } } goto success_peg_4; out_peg_7: goto out_peg_8; success_peg_4: ; Result result_peg_3 = result_peg_2; result_peg_2.reset(); do{ Result result_peg_11(result_peg_2.getPosition()); { int position_peg_13 = result_peg_11.getPosition(); { int position_peg_15 = result_peg_11.getPosition(); char letter_peg_16 = stream.get(result_peg_11.getPosition()); if (letter_peg_16 != '\0' && strchr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_", letter_peg_16) != NULL){ result_peg_11.nextPosition(); result_peg_11.setValue(Value((void*) (long) letter_peg_16)); } else { result_peg_11.setPosition(position_peg_15); goto out_peg_17; } } goto success_peg_14; out_peg_17: result_peg_11.setPosition(position_peg_13); goto out_peg_18; success_peg_14: ; } goto success_peg_12; out_peg_18: { int position_peg_19 = result_peg_11.getPosition(); { int position_peg_21 = result_peg_11.getPosition(); char letter_peg_22 = stream.get(result_peg_11.getPosition()); if (letter_peg_22 != '\0' && strchr("0123456789", letter_peg_22) != NULL){ result_peg_11.nextPosition(); result_peg_11.setValue(Value((void*) (long) letter_peg_22)); } else { result_peg_11.setPosition(position_peg_21); goto out_peg_23; } } goto success_peg_20; out_peg_23: result_peg_11.setPosition(position_peg_19); goto out_peg_24; success_peg_20: ; } goto success_peg_12; out_peg_24: goto loop_peg_10; success_peg_12: ; result_peg_2.addResult(result_peg_11); } while (true); loop_peg_10: ; Result result_peg_9 = result_peg_2; { Value value((void*) 0); value = toString((char)(long)result_peg_3.getValues().getValue(),result_peg_9.getValues()); result_peg_2.setValue(value); } } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_8: stream.update(errorResult.getPosition()); return errorResult; } Result rule_line_end_or_comment(Stream & stream, const int position){ RuleTrace trace_peg_40(stream, "line_end_or_comment"); int myposition = position; Result result_peg_2(myposition); result_peg_2 = rule_line_end(stream, result_peg_2.getPosition()); if (result_peg_2.error()){ goto out_peg_3; } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_3: Result result_peg_4(myposition); { int position_peg_6 = result_peg_4.getPosition(); { result_peg_4.setValue(Value((void*) ";")); for (int i = 0; i < 1; i++){ if (compareChar(";"[i], stream.get(result_peg_4.getPosition()))){ result_peg_4.nextPosition(); } else { result_peg_4.setPosition(position_peg_6); goto out_peg_8; } } result_peg_4.reset(); do{ Result result_peg_10(result_peg_4.getPosition()); { Result result_peg_13(result_peg_10); result_peg_13.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_13.getPosition()))){ result_peg_13.nextPosition(); } else { goto not_peg_12; } } goto loop_peg_9; not_peg_12: result_peg_10.setValue(Value((void*)0)); char temp_peg_14 = stream.get(result_peg_10.getPosition()); if (temp_peg_14 != '\0'){ result_peg_10.setValue(Value((void*) (long) temp_peg_14)); result_peg_10.nextPosition(); } else { goto loop_peg_9; } } result_peg_4.addResult(result_peg_10); } while (true); loop_peg_9: ; } } goto success_peg_5; out_peg_8: { int position_peg_15 = result_peg_4.getPosition(); { result_peg_4.setValue(Value((void*) "=")); for (int i = 0; i < 1; i++){ if (compareChar("="[i], stream.get(result_peg_4.getPosition()))){ result_peg_4.nextPosition(); } else { result_peg_4.setPosition(position_peg_15); goto out_peg_17; } } result_peg_4.reset(); do{ Result result_peg_19(result_peg_4.getPosition()); { Result result_peg_22(result_peg_19); result_peg_22.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_22.getPosition()))){ result_peg_22.nextPosition(); } else { goto not_peg_21; } } goto loop_peg_18; not_peg_21: result_peg_19.setValue(Value((void*)0)); char temp_peg_23 = stream.get(result_peg_19.getPosition()); if (temp_peg_23 != '\0'){ result_peg_19.setValue(Value((void*) (long) temp_peg_23)); result_peg_19.nextPosition(); } else { goto loop_peg_18; } } result_peg_4.addResult(result_peg_19); } while (true); loop_peg_18: ; } } goto success_peg_5; out_peg_17: { int position_peg_24 = result_peg_4.getPosition(); { result_peg_4.setValue(Value((void*) "-")); for (int i = 0; i < 1; i++){ if (compareChar("-"[i], stream.get(result_peg_4.getPosition()))){ result_peg_4.nextPosition(); } else { result_peg_4.setPosition(position_peg_24); goto out_peg_26; } } result_peg_4.setValue(Value((void*) "-")); for (int i = 0; i < 1; i++){ if (compareChar("-"[i], stream.get(result_peg_4.getPosition()))){ result_peg_4.nextPosition(); } else { result_peg_4.setPosition(position_peg_24); goto out_peg_26; } } result_peg_4.reset(); do{ Result result_peg_29(result_peg_4.getPosition()); { Result result_peg_32(result_peg_29); { int position_peg_34 = result_peg_32.getPosition(); result_peg_32.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_32.getPosition()))){ result_peg_32.nextPosition(); } else { result_peg_32.setPosition(position_peg_34); goto out_peg_35; } } } goto success_peg_33; out_peg_35: { int position_peg_36 = result_peg_32.getPosition(); result_peg_32.setValue(Value((void*) "\r")); for (int i = 0; i < 1; i++){ if (compareChar("\r"[i], stream.get(result_peg_32.getPosition()))){ result_peg_32.nextPosition(); } else { result_peg_32.setPosition(position_peg_36); goto out_peg_37; } } } goto success_peg_33; out_peg_37: goto not_peg_31; success_peg_33: ; goto loop_peg_28; not_peg_31: result_peg_29.setValue(Value((void*)0)); char temp_peg_38 = stream.get(result_peg_29.getPosition()); if (temp_peg_38 != '\0'){ result_peg_29.setValue(Value((void*) (long) temp_peg_38)); result_peg_29.nextPosition(); } else { goto loop_peg_28; } } result_peg_4.addResult(result_peg_29); } while (true); loop_peg_28: ; } } goto success_peg_5; out_peg_26: goto out_peg_39; success_peg_5: ; stream.update(result_peg_4.getPosition()); return result_peg_4; out_peg_39: stream.update(errorResult.getPosition()); return errorResult; } Result rule_filename(Stream & stream, const int position){ RuleTrace trace_peg_34(stream, "filename"); int myposition = position; Value line; Value file; Result result_peg_2(myposition); { Stream::LineInfo line_info_peg_4 = stream.getLineInfo(result_peg_2.getPosition()); line = &line_info_peg_4; Result result_peg_7(result_peg_2); result_peg_7.setValue(Value((void*) "\"")); for (int i = 0; i < 1; i++){ if (compareChar("\""[i], stream.get(result_peg_7.getPosition()))){ result_peg_7.nextPosition(); } else { goto not_peg_6; } } goto out_peg_8; not_peg_6: result_peg_2.setValue(Value((void*)0)); result_peg_2.reset(); do{ Result result_peg_11(result_peg_2.getPosition()); { int position_peg_13 = result_peg_11.getPosition(); { Result result_peg_16(result_peg_11); result_peg_16.setValue(Value((void*) ",")); for (int i = 0; i < 1; i++){ if (compareChar(","[i], stream.get(result_peg_16.getPosition()))){ result_peg_16.nextPosition(); } else { goto not_peg_15; } } result_peg_11.setPosition(position_peg_13); goto out_peg_17; not_peg_15: result_peg_11.setValue(Value((void*)0)); Result result_peg_20(result_peg_11); result_peg_20.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_20.getPosition()))){ result_peg_20.nextPosition(); } else { goto not_peg_19; } } result_peg_11.setPosition(position_peg_13); goto out_peg_17; not_peg_19: result_peg_11.setValue(Value((void*)0)); Result result_peg_23(result_peg_11); result_peg_23.setValue(Value((void*) "[")); for (int i = 0; i < 1; i++){ if (compareChar("["[i], stream.get(result_peg_23.getPosition()))){ result_peg_23.nextPosition(); } else { goto not_peg_22; } } result_peg_11.setPosition(position_peg_13); goto out_peg_17; not_peg_22: result_peg_11.setValue(Value((void*)0)); Result result_peg_26(result_peg_11); result_peg_26.setValue(Value((void*) 13)); if ((unsigned char) stream.get(result_peg_26.getPosition()) == (unsigned char) 13){ result_peg_26.nextPosition(); } else { goto not_peg_25; } result_peg_11.setPosition(position_peg_13); goto out_peg_17; not_peg_25: result_peg_11.setValue(Value((void*)0)); Result result_peg_29(result_peg_11); result_peg_29.setValue(Value((void*) "=")); for (int i = 0; i < 1; i++){ if (compareChar("="[i], stream.get(result_peg_29.getPosition()))){ result_peg_29.nextPosition(); } else { goto not_peg_28; } } result_peg_11.setPosition(position_peg_13); goto out_peg_17; not_peg_28: result_peg_11.setValue(Value((void*)0)); Result result_peg_32(result_peg_11); result_peg_32.setValue(Value((void*) ";")); for (int i = 0; i < 1; i++){ if (compareChar(";"[i], stream.get(result_peg_32.getPosition()))){ result_peg_32.nextPosition(); } else { goto not_peg_31; } } result_peg_11.setPosition(position_peg_13); goto out_peg_17; not_peg_31: result_peg_11.setValue(Value((void*)0)); char temp_peg_33 = stream.get(result_peg_11.getPosition()); if (temp_peg_33 != '\0'){ result_peg_11.setValue(Value((void*) (long) temp_peg_33)); result_peg_11.nextPosition(); } else { result_peg_11.setPosition(position_peg_13); goto out_peg_17; } } } goto success_peg_12; out_peg_17: goto loop_peg_10; success_peg_12: ; result_peg_2.addResult(result_peg_11); } while (true); loop_peg_10: if (result_peg_2.matches() == 0){ goto out_peg_8; } file = result_peg_2.getValues(); { Value value((void*) 0); value = new Ast::Filename(getCurrentLine(line), getCurrentColumn(line), toString(file)); GC::save(as<Ast::Filename*>(value)); result_peg_2.setValue(value); } } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_8: stream.update(errorResult.getPosition()); return errorResult; } Result rule_attribute(Stream & stream, const int position){ RuleTrace trace_peg_142(stream, "attribute"); int myposition = position; Value line; Value id; Value data; Value index; Result result_peg_2(myposition); { Stream::LineInfo line_info_peg_4 = stream.getLineInfo(result_peg_2.getPosition()); line = &line_info_peg_4; result_peg_2 = rule_identifier(stream, result_peg_2.getPosition()); if (result_peg_2.error()){ goto out_peg_6; } id = result_peg_2.getValues(); { int position_peg_9 = result_peg_2.getPosition(); result_peg_2.reset(); do{ Result result_peg_11(result_peg_2.getPosition()); { int position_peg_13 = result_peg_11.getPosition(); result_peg_11.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_11.getPosition()))){ result_peg_11.nextPosition(); } else { result_peg_11.setPosition(position_peg_13); goto out_peg_14; } } } goto success_peg_12; out_peg_14: { int position_peg_15 = result_peg_11.getPosition(); result_peg_11.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_11.getPosition()))){ result_peg_11.nextPosition(); } else { result_peg_11.setPosition(position_peg_15); goto out_peg_16; } } } goto success_peg_12; out_peg_16: goto loop_peg_10; success_peg_12: ; result_peg_2.addResult(result_peg_11); } while (true); loop_peg_10: ; } goto success_peg_8; goto out_peg_6; success_peg_8: ; result_peg_2.setValue(Value((void*) "=")); for (int i = 0; i < 1; i++){ if (compareChar("="[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { goto out_peg_6; } } { int position_peg_20 = result_peg_2.getPosition(); result_peg_2.reset(); do{ Result result_peg_22(result_peg_2.getPosition()); { int position_peg_24 = result_peg_22.getPosition(); result_peg_22.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_22.getPosition()))){ result_peg_22.nextPosition(); } else { result_peg_22.setPosition(position_peg_24); goto out_peg_25; } } } goto success_peg_23; out_peg_25: { int position_peg_26 = result_peg_22.getPosition(); result_peg_22.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_22.getPosition()))){ result_peg_22.nextPosition(); } else { result_peg_22.setPosition(position_peg_26); goto out_peg_27; } } } goto success_peg_23; out_peg_27: goto loop_peg_21; success_peg_23: ; result_peg_2.addResult(result_peg_22); } while (true); loop_peg_21: ; } goto success_peg_19; goto out_peg_6; success_peg_19: ; Result result_peg_29(result_peg_2.getPosition()); result_peg_29 = rule_line_end_or_comment(stream, result_peg_29.getPosition()); if (result_peg_29.error()){ goto out_peg_6; } { Value value((void*) 0); value = makeAttributeWithInfo(line, id); result_peg_2.setValue(value); } } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_6: Result result_peg_30(myposition); { Stream::LineInfo line_info_peg_32 = stream.getLineInfo(result_peg_30.getPosition()); line = &line_info_peg_32; result_peg_30 = rule_identifier(stream, result_peg_30.getPosition()); if (result_peg_30.error()){ goto out_peg_34; } id = result_peg_30.getValues(); { int position_peg_37 = result_peg_30.getPosition(); result_peg_30.reset(); do{ Result result_peg_39(result_peg_30.getPosition()); { int position_peg_41 = result_peg_39.getPosition(); result_peg_39.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_39.getPosition()))){ result_peg_39.nextPosition(); } else { result_peg_39.setPosition(position_peg_41); goto out_peg_42; } } } goto success_peg_40; out_peg_42: { int position_peg_43 = result_peg_39.getPosition(); result_peg_39.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_39.getPosition()))){ result_peg_39.nextPosition(); } else { result_peg_39.setPosition(position_peg_43); goto out_peg_44; } } } goto success_peg_40; out_peg_44: goto loop_peg_38; success_peg_40: ; result_peg_30.addResult(result_peg_39); } while (true); loop_peg_38: ; } goto success_peg_36; goto out_peg_34; success_peg_36: ; result_peg_30.setValue(Value((void*) "=")); for (int i = 0; i < 1; i++){ if (compareChar("="[i], stream.get(result_peg_30.getPosition()))){ result_peg_30.nextPosition(); } else { goto out_peg_34; } } { int position_peg_48 = result_peg_30.getPosition(); result_peg_30.reset(); do{ Result result_peg_50(result_peg_30.getPosition()); { int position_peg_52 = result_peg_50.getPosition(); result_peg_50.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_50.getPosition()))){ result_peg_50.nextPosition(); } else { result_peg_50.setPosition(position_peg_52); goto out_peg_53; } } } goto success_peg_51; out_peg_53: { int position_peg_54 = result_peg_50.getPosition(); result_peg_50.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_50.getPosition()))){ result_peg_50.nextPosition(); } else { result_peg_50.setPosition(position_peg_54); goto out_peg_55; } } } goto success_peg_51; out_peg_55: goto loop_peg_49; success_peg_51: ; result_peg_30.addResult(result_peg_50); } while (true); loop_peg_49: ; } goto success_peg_47; goto out_peg_34; success_peg_47: ; result_peg_30 = rule_valuelist(stream, result_peg_30.getPosition()); if (result_peg_30.error()){ goto out_peg_34; } data = result_peg_30.getValues(); { Value value((void*) 0); value = makeAttribute(line, id, data); result_peg_30.setValue(value); } } stream.update(result_peg_30.getPosition()); return result_peg_30; out_peg_34: Result result_peg_57(myposition); { Stream::LineInfo line_info_peg_59 = stream.getLineInfo(result_peg_57.getPosition()); line = &line_info_peg_59; result_peg_57 = rule_identifier(stream, result_peg_57.getPosition()); if (result_peg_57.error()){ goto out_peg_61; } id = result_peg_57.getValues(); { int position_peg_64 = result_peg_57.getPosition(); result_peg_57.reset(); do{ Result result_peg_66(result_peg_57.getPosition()); { int position_peg_68 = result_peg_66.getPosition(); result_peg_66.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_66.getPosition()))){ result_peg_66.nextPosition(); } else { result_peg_66.setPosition(position_peg_68); goto out_peg_69; } } } goto success_peg_67; out_peg_69: { int position_peg_70 = result_peg_66.getPosition(); result_peg_66.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_66.getPosition()))){ result_peg_66.nextPosition(); } else { result_peg_66.setPosition(position_peg_70); goto out_peg_71; } } } goto success_peg_67; out_peg_71: goto loop_peg_65; success_peg_67: ; result_peg_57.addResult(result_peg_66); } while (true); loop_peg_65: ; } goto success_peg_63; goto out_peg_61; success_peg_63: ; result_peg_57.setValue(Value((void*) "=")); for (int i = 0; i < 1; i++){ if (compareChar("="[i], stream.get(result_peg_57.getPosition()))){ result_peg_57.nextPosition(); } else { goto out_peg_61; } } { int position_peg_75 = result_peg_57.getPosition(); result_peg_57.reset(); do{ Result result_peg_77(result_peg_57.getPosition()); { int position_peg_79 = result_peg_77.getPosition(); result_peg_77.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_77.getPosition()))){ result_peg_77.nextPosition(); } else { result_peg_77.setPosition(position_peg_79); goto out_peg_80; } } } goto success_peg_78; out_peg_80: { int position_peg_81 = result_peg_77.getPosition(); result_peg_77.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_77.getPosition()))){ result_peg_77.nextPosition(); } else { result_peg_77.setPosition(position_peg_81); goto out_peg_82; } } } goto success_peg_78; out_peg_82: goto loop_peg_76; success_peg_78: ; result_peg_57.addResult(result_peg_77); } while (true); loop_peg_76: ; } goto success_peg_74; goto out_peg_61; success_peg_74: ; result_peg_57 = rule_filename(stream, result_peg_57.getPosition()); if (result_peg_57.error()){ goto out_peg_61; } data = result_peg_57.getValues(); { Value value((void*) 0); value = makeAttribute(line, id, data); result_peg_57.setValue(value); } } stream.update(result_peg_57.getPosition()); return result_peg_57; out_peg_61: Result result_peg_84(myposition); { result_peg_84 = rule_identifier(stream, result_peg_84.getPosition()); if (result_peg_84.error()){ goto out_peg_86; } id = result_peg_84.getValues(); { int position_peg_89 = result_peg_84.getPosition(); result_peg_84.reset(); do{ Result result_peg_91(result_peg_84.getPosition()); { int position_peg_93 = result_peg_91.getPosition(); result_peg_91.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_91.getPosition()))){ result_peg_91.nextPosition(); } else { result_peg_91.setPosition(position_peg_93); goto out_peg_94; } } } goto success_peg_92; out_peg_94: { int position_peg_95 = result_peg_91.getPosition(); result_peg_91.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_91.getPosition()))){ result_peg_91.nextPosition(); } else { result_peg_91.setPosition(position_peg_95); goto out_peg_96; } } } goto success_peg_92; out_peg_96: goto loop_peg_90; success_peg_92: ; result_peg_84.addResult(result_peg_91); } while (true); loop_peg_90: ; } goto success_peg_88; goto out_peg_86; success_peg_88: ; result_peg_84.setValue(Value((void*) "(")); for (int i = 0; i < 1; i++){ if (compareChar("("[i], stream.get(result_peg_84.getPosition()))){ result_peg_84.nextPosition(); } else { goto out_peg_86; } } { int position_peg_100 = result_peg_84.getPosition(); result_peg_84.reset(); do{ Result result_peg_102(result_peg_84.getPosition()); { int position_peg_104 = result_peg_102.getPosition(); result_peg_102.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_102.getPosition()))){ result_peg_102.nextPosition(); } else { result_peg_102.setPosition(position_peg_104); goto out_peg_105; } } } goto success_peg_103; out_peg_105: { int position_peg_106 = result_peg_102.getPosition(); result_peg_102.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_102.getPosition()))){ result_peg_102.nextPosition(); } else { result_peg_102.setPosition(position_peg_106); goto out_peg_107; } } } goto success_peg_103; out_peg_107: goto loop_peg_101; success_peg_103: ; result_peg_84.addResult(result_peg_102); } while (true); loop_peg_101: ; } goto success_peg_99; goto out_peg_86; success_peg_99: ; result_peg_84 = rule_number(stream, result_peg_84.getPosition()); if (result_peg_84.error()){ goto out_peg_86; } index = result_peg_84.getValues(); { int position_peg_111 = result_peg_84.getPosition(); result_peg_84.reset(); do{ Result result_peg_113(result_peg_84.getPosition()); { int position_peg_115 = result_peg_113.getPosition(); result_peg_113.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_113.getPosition()))){ result_peg_113.nextPosition(); } else { result_peg_113.setPosition(position_peg_115); goto out_peg_116; } } } goto success_peg_114; out_peg_116: { int position_peg_117 = result_peg_113.getPosition(); result_peg_113.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_113.getPosition()))){ result_peg_113.nextPosition(); } else { result_peg_113.setPosition(position_peg_117); goto out_peg_118; } } } goto success_peg_114; out_peg_118: goto loop_peg_112; success_peg_114: ; result_peg_84.addResult(result_peg_113); } while (true); loop_peg_112: ; } goto success_peg_110; goto out_peg_86; success_peg_110: ; result_peg_84.setValue(Value((void*) ")")); for (int i = 0; i < 1; i++){ if (compareChar(")"[i], stream.get(result_peg_84.getPosition()))){ result_peg_84.nextPosition(); } else { goto out_peg_86; } } { int position_peg_122 = result_peg_84.getPosition(); result_peg_84.reset(); do{ Result result_peg_124(result_peg_84.getPosition()); { int position_peg_126 = result_peg_124.getPosition(); result_peg_124.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_124.getPosition()))){ result_peg_124.nextPosition(); } else { result_peg_124.setPosition(position_peg_126); goto out_peg_127; } } } goto success_peg_125; out_peg_127: { int position_peg_128 = result_peg_124.getPosition(); result_peg_124.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_124.getPosition()))){ result_peg_124.nextPosition(); } else { result_peg_124.setPosition(position_peg_128); goto out_peg_129; } } } goto success_peg_125; out_peg_129: goto loop_peg_123; success_peg_125: ; result_peg_84.addResult(result_peg_124); } while (true); loop_peg_123: ; } goto success_peg_121; goto out_peg_86; success_peg_121: ; result_peg_84.setValue(Value((void*) "=")); for (int i = 0; i < 1; i++){ if (compareChar("="[i], stream.get(result_peg_84.getPosition()))){ result_peg_84.nextPosition(); } else { goto out_peg_86; } } { int position_peg_133 = result_peg_84.getPosition(); result_peg_84.reset(); do{ Result result_peg_135(result_peg_84.getPosition()); { int position_peg_137 = result_peg_135.getPosition(); result_peg_135.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_135.getPosition()))){ result_peg_135.nextPosition(); } else { result_peg_135.setPosition(position_peg_137); goto out_peg_138; } } } goto success_peg_136; out_peg_138: { int position_peg_139 = result_peg_135.getPosition(); result_peg_135.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_135.getPosition()))){ result_peg_135.nextPosition(); } else { result_peg_135.setPosition(position_peg_139); goto out_peg_140; } } } goto success_peg_136; out_peg_140: goto loop_peg_134; success_peg_136: ; result_peg_84.addResult(result_peg_135); } while (true); loop_peg_134: ; } goto success_peg_132; goto out_peg_86; success_peg_132: ; result_peg_84 = rule_valuelist(stream, result_peg_84.getPosition()); if (result_peg_84.error()){ goto out_peg_86; } data = result_peg_84.getValues(); { Value value((void*) 0); value = makeIndexedAttribute(id, index, data); result_peg_84.setValue(value); } } stream.update(result_peg_84.getPosition()); return result_peg_84; out_peg_86: stream.update(errorResult.getPosition()); return errorResult; } Result rule_attribute_simple(Stream & stream, const int position){ RuleTrace trace_peg_27(stream, "attribute_simple"); int myposition = position; Value id; Value data; Result result_peg_2(myposition); { result_peg_2 = rule_identifier(stream, result_peg_2.getPosition()); if (result_peg_2.error()){ goto out_peg_4; } id = result_peg_2.getValues(); { int position_peg_7 = result_peg_2.getPosition(); result_peg_2.reset(); do{ Result result_peg_9(result_peg_2.getPosition()); { int position_peg_11 = result_peg_9.getPosition(); result_peg_9.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_9.getPosition()))){ result_peg_9.nextPosition(); } else { result_peg_9.setPosition(position_peg_11); goto out_peg_12; } } } goto success_peg_10; out_peg_12: { int position_peg_13 = result_peg_9.getPosition(); result_peg_9.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_9.getPosition()))){ result_peg_9.nextPosition(); } else { result_peg_9.setPosition(position_peg_13); goto out_peg_14; } } } goto success_peg_10; out_peg_14: goto loop_peg_8; success_peg_10: ; result_peg_2.addResult(result_peg_9); } while (true); loop_peg_8: ; } goto success_peg_6; goto out_peg_4; success_peg_6: ; result_peg_2.setValue(Value((void*) "=")); for (int i = 0; i < 1; i++){ if (compareChar("="[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { goto out_peg_4; } } { int position_peg_18 = result_peg_2.getPosition(); result_peg_2.reset(); do{ Result result_peg_20(result_peg_2.getPosition()); { int position_peg_22 = result_peg_20.getPosition(); result_peg_20.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_20.getPosition()))){ result_peg_20.nextPosition(); } else { result_peg_20.setPosition(position_peg_22); goto out_peg_23; } } } goto success_peg_21; out_peg_23: { int position_peg_24 = result_peg_20.getPosition(); result_peg_20.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_20.getPosition()))){ result_peg_20.nextPosition(); } else { result_peg_20.setPosition(position_peg_24); goto out_peg_25; } } } goto success_peg_21; out_peg_25: goto loop_peg_19; success_peg_21: ; result_peg_2.addResult(result_peg_20); } while (true); loop_peg_19: ; } goto success_peg_17; goto out_peg_4; success_peg_17: ; result_peg_2 = rule_value(stream, result_peg_2.getPosition()); if (result_peg_2.error()){ goto out_peg_4; } data = result_peg_2.getValues(); { Value value((void*) 0); value = makeAttribute(id, data); result_peg_2.setValue(value); } } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_4: stream.update(errorResult.getPosition()); return errorResult; } Result rule_identifier(Stream & stream, const int position){ RuleTrace trace_peg_9(stream, "identifier"); int myposition = position; Result result_peg_2(myposition); { result_peg_2 = rule_name(stream, result_peg_2.getPosition()); if (result_peg_2.error()){ goto out_peg_4; } Result result_peg_3 = result_peg_2; result_peg_2.reset(); do{ Result result_peg_7(result_peg_2.getPosition()); { result_peg_7.setValue(Value((void*) ".")); for (int i = 0; i < 1; i++){ if (compareChar("."[i], stream.get(result_peg_7.getPosition()))){ result_peg_7.nextPosition(); } else { goto loop_peg_6; } } result_peg_7 = rule_name(stream, result_peg_7.getPosition()); if (result_peg_7.error()){ goto loop_peg_6; } } result_peg_2.addResult(result_peg_7); } while (true); loop_peg_6: ; Result result_peg_5 = result_peg_2; { Value value((void*) 0); value = makeIdentifier(result_peg_3.getValues(),result_peg_5.getValues()); result_peg_2.setValue(value); } } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_4: stream.update(errorResult.getPosition()); return errorResult; } Result rule_identifier_list(Stream & stream, const int position){ RuleTrace trace_peg_28(stream, "identifier_list"); int myposition = position; Result result_peg_2(myposition); { result_peg_2 = rule_identifier(stream, result_peg_2.getPosition()); if (result_peg_2.error()){ goto out_peg_4; } result_peg_2.reset(); do{ Result result_peg_6(result_peg_2.getPosition()); { { int position_peg_9 = result_peg_6.getPosition(); result_peg_6.reset(); do{ Result result_peg_11(result_peg_6.getPosition()); { int position_peg_13 = result_peg_11.getPosition(); result_peg_11.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_11.getPosition()))){ result_peg_11.nextPosition(); } else { result_peg_11.setPosition(position_peg_13); goto out_peg_14; } } } goto success_peg_12; out_peg_14: { int position_peg_15 = result_peg_11.getPosition(); result_peg_11.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_11.getPosition()))){ result_peg_11.nextPosition(); } else { result_peg_11.setPosition(position_peg_15); goto out_peg_16; } } } goto success_peg_12; out_peg_16: goto loop_peg_10; success_peg_12: ; result_peg_6.addResult(result_peg_11); } while (true); loop_peg_10: ; } goto success_peg_8; goto loop_peg_5; success_peg_8: ; result_peg_6.setValue(Value((void*) ",")); for (int i = 0; i < 1; i++){ if (compareChar(","[i], stream.get(result_peg_6.getPosition()))){ result_peg_6.nextPosition(); } else { goto loop_peg_5; } } { int position_peg_20 = result_peg_6.getPosition(); result_peg_6.reset(); do{ Result result_peg_22(result_peg_6.getPosition()); { int position_peg_24 = result_peg_22.getPosition(); result_peg_22.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_22.getPosition()))){ result_peg_22.nextPosition(); } else { result_peg_22.setPosition(position_peg_24); goto out_peg_25; } } } goto success_peg_23; out_peg_25: { int position_peg_26 = result_peg_22.getPosition(); result_peg_22.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_22.getPosition()))){ result_peg_22.nextPosition(); } else { result_peg_22.setPosition(position_peg_26); goto out_peg_27; } } } goto success_peg_23; out_peg_27: goto loop_peg_21; success_peg_23: ; result_peg_6.addResult(result_peg_22); } while (true); loop_peg_21: ; } goto success_peg_19; goto loop_peg_5; success_peg_19: ; result_peg_6 = rule_filename(stream, result_peg_6.getPosition()); if (result_peg_6.error()){ goto loop_peg_5; } } result_peg_2.addResult(result_peg_6); } while (true); loop_peg_5: if (result_peg_2.matches() == 0){ goto out_peg_4; } } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_4: stream.update(errorResult.getPosition()); return errorResult; } Result rule_valuelist(Stream & stream, const int position){ RuleTrace trace_peg_32(stream, "valuelist"); int myposition = position; Value line; Result result_peg_2(myposition); { Stream::LineInfo line_info_peg_4 = stream.getLineInfo(result_peg_2.getPosition()); line = &line_info_peg_4; result_peg_2 = rule_value(stream, result_peg_2.getPosition()); if (result_peg_2.error()){ goto out_peg_6; } Result result_peg_5 = result_peg_2; result_peg_2.reset(); do{ Result result_peg_9(result_peg_2.getPosition()); { { int position_peg_12 = result_peg_9.getPosition(); result_peg_9.reset(); do{ Result result_peg_14(result_peg_9.getPosition()); { int position_peg_16 = result_peg_14.getPosition(); result_peg_14.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_14.getPosition()))){ result_peg_14.nextPosition(); } else { result_peg_14.setPosition(position_peg_16); goto out_peg_17; } } } goto success_peg_15; out_peg_17: { int position_peg_18 = result_peg_14.getPosition(); result_peg_14.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_14.getPosition()))){ result_peg_14.nextPosition(); } else { result_peg_14.setPosition(position_peg_18); goto out_peg_19; } } } goto success_peg_15; out_peg_19: goto loop_peg_13; success_peg_15: ; result_peg_9.addResult(result_peg_14); } while (true); loop_peg_13: ; } goto success_peg_11; goto loop_peg_8; success_peg_11: ; result_peg_9.setValue(Value((void*) ",")); for (int i = 0; i < 1; i++){ if (compareChar(","[i], stream.get(result_peg_9.getPosition()))){ result_peg_9.nextPosition(); } else { goto loop_peg_8; } } { int position_peg_23 = result_peg_9.getPosition(); result_peg_9.reset(); do{ Result result_peg_25(result_peg_9.getPosition()); { int position_peg_27 = result_peg_25.getPosition(); result_peg_25.setValue(Value((void*) " ")); for (int i = 0; i < 1; i++){ if (compareChar(" "[i], stream.get(result_peg_25.getPosition()))){ result_peg_25.nextPosition(); } else { result_peg_25.setPosition(position_peg_27); goto out_peg_28; } } } goto success_peg_26; out_peg_28: { int position_peg_29 = result_peg_25.getPosition(); result_peg_25.setValue(Value((void*) "\t")); for (int i = 0; i < 1; i++){ if (compareChar("\t"[i], stream.get(result_peg_25.getPosition()))){ result_peg_25.nextPosition(); } else { result_peg_25.setPosition(position_peg_29); goto out_peg_30; } } } goto success_peg_26; out_peg_30: goto loop_peg_24; success_peg_26: ; result_peg_9.addResult(result_peg_25); } while (true); loop_peg_24: ; } goto success_peg_22; goto loop_peg_8; success_peg_22: ; int save_peg_31 = result_peg_9.getPosition(); result_peg_9 = rule_value(stream, result_peg_9.getPosition()); if (result_peg_9.error()){ result_peg_9 = Result(save_peg_31); result_peg_9.setValue(Value((void*) 0)); } } result_peg_2.addResult(result_peg_9); } while (true); loop_peg_8: ; Result result_peg_7 = result_peg_2; { Value value((void*) 0); value = makeValueList(line, result_peg_5.getValues(),result_peg_7.getValues()); result_peg_2.setValue(value); } } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_6: stream.update(errorResult.getPosition()); return errorResult; } Result rule_value(Stream & stream, const int position){ RuleTrace trace_peg_163(stream, "value"); int myposition = position; Value data; Result result_peg_2(myposition); { int position_peg_4 = result_peg_2.getPosition(); { result_peg_2.setValue(Value((void*) "\"")); for (int i = 0; i < 1; i++){ if (compareChar("\""[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { result_peg_2.setPosition(position_peg_4); goto out_peg_6; } } result_peg_2.reset(); do{ Result result_peg_9(result_peg_2.getPosition()); { Result result_peg_12(result_peg_9); result_peg_12.setValue(Value((void*) "\"")); for (int i = 0; i < 1; i++){ if (compareChar("\""[i], stream.get(result_peg_12.getPosition()))){ result_peg_12.nextPosition(); } else { goto not_peg_11; } } goto loop_peg_8; not_peg_11: result_peg_9.setValue(Value((void*)0)); Result result_peg_15(result_peg_9); result_peg_15.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_15.getPosition()))){ result_peg_15.nextPosition(); } else { goto not_peg_14; } } goto loop_peg_8; not_peg_14: result_peg_9.setValue(Value((void*)0)); char temp_peg_16 = stream.get(result_peg_9.getPosition()); if (temp_peg_16 != '\0'){ result_peg_9.setValue(Value((void*) (long) temp_peg_16)); result_peg_9.nextPosition(); } else { goto loop_peg_8; } } result_peg_2.addResult(result_peg_9); } while (true); loop_peg_8: ; data = result_peg_2.getValues(); result_peg_2.setValue(Value((void*) "\"")); for (int i = 0; i < 1; i++){ if (compareChar("\""[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { result_peg_2.setPosition(position_peg_4); goto out_peg_6; } } { Value value((void*) 0); value = makeString(data); result_peg_2.setValue(value); } } } goto success_peg_3; out_peg_6: goto out_peg_18; success_peg_3: ; stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_18: Result result_peg_19(myposition); result_peg_19 = rule_date(stream, result_peg_19.getPosition()); if (result_peg_19.error()){ goto out_peg_20; } stream.update(result_peg_19.getPosition()); return result_peg_19; out_peg_20: Result result_peg_21(myposition); { result_peg_21 = rule_number(stream, result_peg_21.getPosition()); if (result_peg_21.error()){ goto out_peg_23; } Result result_peg_22 = result_peg_21; Result result_peg_26(result_peg_21); { int position_peg_28 = result_peg_26.getPosition(); char letter_peg_29 = stream.get(result_peg_26.getPosition()); if (letter_peg_29 != '\0' && strchr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_", letter_peg_29) != NULL){ result_peg_26.nextPosition(); result_peg_26.setValue(Value((void*) (long) letter_peg_29)); } else { result_peg_26.setPosition(position_peg_28); goto out_peg_30; } } goto success_peg_27; out_peg_30: goto not_peg_25; success_peg_27: ; goto out_peg_23; not_peg_25: result_peg_21.setValue(Value((void*)0)); Result result_peg_33(result_peg_21); result_peg_33.setValue(Value((void*) "-")); for (int i = 0; i < 1; i++){ if (compareChar("-"[i], stream.get(result_peg_33.getPosition()))){ result_peg_33.nextPosition(); } else { goto not_peg_32; } } goto out_peg_23; not_peg_32: result_peg_21.setValue(Value((void*)0)); { Value value((void*) 0); value = result_peg_22.getValues(); result_peg_21.setValue(value); } } stream.update(result_peg_21.getPosition()); return result_peg_21; out_peg_23: Result result_peg_34(myposition); { result_peg_34 = rule_attribute_simple(stream, result_peg_34.getPosition()); if (result_peg_34.error()){ goto out_peg_36; } Result result_peg_35 = result_peg_34; { Value value((void*) 0); value = makeValueAttribute(result_peg_35.getValues()); result_peg_34.setValue(value); } } stream.update(result_peg_34.getPosition()); return result_peg_34; out_peg_36: Result result_peg_37(myposition); { { int position_peg_40 = result_peg_37.getPosition(); result_peg_37.setValue(Value((void*) "normal")); for (int i = 0; i < 6; i++){ if (compareChar("normal"[i], stream.get(result_peg_37.getPosition()))){ result_peg_37.nextPosition(); } else { result_peg_37.setPosition(position_peg_40); goto out_peg_41; } } } goto success_peg_39; out_peg_41: { int position_peg_42 = result_peg_37.getPosition(); result_peg_37.setValue(Value((void*) "parallax")); for (int i = 0; i < 8; i++){ if (compareChar("parallax"[i], stream.get(result_peg_37.getPosition()))){ result_peg_37.nextPosition(); } else { result_peg_37.setPosition(position_peg_42); goto out_peg_43; } } } goto success_peg_39; out_peg_43: { int position_peg_44 = result_peg_37.getPosition(); result_peg_37.setValue(Value((void*) "addalpha")); for (int i = 0; i < 8; i++){ if (compareChar("addalpha"[i], stream.get(result_peg_37.getPosition()))){ result_peg_37.nextPosition(); } else { result_peg_37.setPosition(position_peg_44); goto out_peg_45; } } } goto success_peg_39; out_peg_45: { int position_peg_46 = result_peg_37.getPosition(); result_peg_37.setValue(Value((void*) "add1")); for (int i = 0; i < 4; i++){ if (compareChar("add1"[i], stream.get(result_peg_37.getPosition()))){ result_peg_37.nextPosition(); } else { result_peg_37.setPosition(position_peg_46); goto out_peg_47; } } } goto success_peg_39; out_peg_47: { int position_peg_48 = result_peg_37.getPosition(); result_peg_37.setValue(Value((void*) "add")); for (int i = 0; i < 3; i++){ if (compareChar("add"[i], stream.get(result_peg_37.getPosition()))){ result_peg_37.nextPosition(); } else { result_peg_37.setPosition(position_peg_48); goto out_peg_49; } } } goto success_peg_39; out_peg_49: { int position_peg_50 = result_peg_37.getPosition(); result_peg_37.setValue(Value((void*) "sub")); for (int i = 0; i < 3; i++){ if (compareChar("sub"[i], stream.get(result_peg_37.getPosition()))){ result_peg_37.nextPosition(); } else { result_peg_37.setPosition(position_peg_50); goto out_peg_51; } } } goto success_peg_39; out_peg_51: goto out_peg_52; success_peg_39: ; Result result_peg_38 = result_peg_37; Result result_peg_55(result_peg_37); { int position_peg_57 = result_peg_55.getPosition(); { int position_peg_59 = result_peg_55.getPosition(); char letter_peg_60 = stream.get(result_peg_55.getPosition()); if (letter_peg_60 != '\0' && strchr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_", letter_peg_60) != NULL){ result_peg_55.nextPosition(); result_peg_55.setValue(Value((void*) (long) letter_peg_60)); } else { result_peg_55.setPosition(position_peg_59); goto out_peg_61; } } goto success_peg_58; out_peg_61: result_peg_55.setPosition(position_peg_57); goto out_peg_62; success_peg_58: ; } goto success_peg_56; out_peg_62: { int position_peg_63 = result_peg_55.getPosition(); { int position_peg_65 = result_peg_55.getPosition(); char letter_peg_66 = stream.get(result_peg_55.getPosition()); if (letter_peg_66 != '\0' && strchr("0123456789", letter_peg_66) != NULL){ result_peg_55.nextPosition(); result_peg_55.setValue(Value((void*) (long) letter_peg_66)); } else { result_peg_55.setPosition(position_peg_65); goto out_peg_67; } } goto success_peg_64; out_peg_67: result_peg_55.setPosition(position_peg_63); goto out_peg_68; success_peg_64: ; } goto success_peg_56; out_peg_68: goto not_peg_54; success_peg_56: ; goto out_peg_52; not_peg_54: result_peg_37.setValue(Value((void*)0)); { Value value((void*) 0); value = makeKeyword(result_peg_38.getValues()); result_peg_37.setValue(value); } } stream.update(result_peg_37.getPosition()); return result_peg_37; out_peg_52: Result result_peg_69(myposition); { result_peg_69.setValue(Value((void*) "s")); for (int i = 0; i < 1; i++){ if (compareCharCase("s"[i], stream.get(result_peg_69.getPosition()))){ result_peg_69.nextPosition(); } else { goto out_peg_71; } } Result result_peg_70 = result_peg_69; Result result_peg_74(result_peg_69); { int position_peg_76 = result_peg_74.getPosition(); { Result result_peg_79(result_peg_74); result_peg_79.setValue(Value((void*) ",")); for (int i = 0; i < 1; i++){ if (compareChar(","[i], stream.get(result_peg_79.getPosition()))){ result_peg_79.nextPosition(); } else { goto not_peg_78; } } result_peg_74.setPosition(position_peg_76); goto out_peg_80; not_peg_78: result_peg_74.setValue(Value((void*)0)); Result result_peg_83(result_peg_74); result_peg_83.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_83.getPosition()))){ result_peg_83.nextPosition(); } else { goto not_peg_82; } } result_peg_74.setPosition(position_peg_76); goto out_peg_80; not_peg_82: result_peg_74.setValue(Value((void*)0)); Result result_peg_86(result_peg_74); result_peg_86.setValue(Value((void*) "[")); for (int i = 0; i < 1; i++){ if (compareChar("["[i], stream.get(result_peg_86.getPosition()))){ result_peg_86.nextPosition(); } else { goto not_peg_85; } } result_peg_74.setPosition(position_peg_76); goto out_peg_80; not_peg_85: result_peg_74.setValue(Value((void*)0)); Result result_peg_89(result_peg_74); result_peg_89.setValue(Value((void*) 13)); if ((unsigned char) stream.get(result_peg_89.getPosition()) == (unsigned char) 13){ result_peg_89.nextPosition(); } else { goto not_peg_88; } result_peg_74.setPosition(position_peg_76); goto out_peg_80; not_peg_88: result_peg_74.setValue(Value((void*)0)); Result result_peg_92(result_peg_74); result_peg_92.setValue(Value((void*) "=")); for (int i = 0; i < 1; i++){ if (compareChar("="[i], stream.get(result_peg_92.getPosition()))){ result_peg_92.nextPosition(); } else { goto not_peg_91; } } result_peg_74.setPosition(position_peg_76); goto out_peg_80; not_peg_91: result_peg_74.setValue(Value((void*)0)); Result result_peg_95(result_peg_74); result_peg_95.setValue(Value((void*) ";")); for (int i = 0; i < 1; i++){ if (compareChar(";"[i], stream.get(result_peg_95.getPosition()))){ result_peg_95.nextPosition(); } else { goto not_peg_94; } } result_peg_74.setPosition(position_peg_76); goto out_peg_80; not_peg_94: result_peg_74.setValue(Value((void*)0)); char temp_peg_96 = stream.get(result_peg_74.getPosition()); if (temp_peg_96 != '\0'){ result_peg_74.setValue(Value((void*) (long) temp_peg_96)); result_peg_74.nextPosition(); } else { result_peg_74.setPosition(position_peg_76); goto out_peg_80; } } } goto success_peg_75; out_peg_80: goto not_peg_73; success_peg_75: ; goto out_peg_71; not_peg_73: result_peg_69.setValue(Value((void*)0)); Result result_peg_99(result_peg_69); result_peg_99.setValue(Value((void*) ".")); for (int i = 0; i < 1; i++){ if (compareChar("."[i], stream.get(result_peg_99.getPosition()))){ result_peg_99.nextPosition(); } else { goto not_peg_98; } } goto out_peg_71; not_peg_98: result_peg_69.setValue(Value((void*)0)); { Value value((void*) 0); value = makeKeyword(result_peg_70.getValues()); result_peg_69.setValue(value); } } stream.update(result_peg_69.getPosition()); return result_peg_69; out_peg_71: Result result_peg_100(myposition); { result_peg_100.setValue(Value((void*) "h")); for (int i = 0; i < 1; i++){ if (compareCharCase("h"[i], stream.get(result_peg_100.getPosition()))){ result_peg_100.nextPosition(); } else { goto out_peg_102; } } Result result_peg_101 = result_peg_100; Result result_peg_105(result_peg_100); { int position_peg_107 = result_peg_105.getPosition(); { Result result_peg_110(result_peg_105); result_peg_110.setValue(Value((void*) ",")); for (int i = 0; i < 1; i++){ if (compareChar(","[i], stream.get(result_peg_110.getPosition()))){ result_peg_110.nextPosition(); } else { goto not_peg_109; } } result_peg_105.setPosition(position_peg_107); goto out_peg_111; not_peg_109: result_peg_105.setValue(Value((void*)0)); Result result_peg_114(result_peg_105); result_peg_114.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_114.getPosition()))){ result_peg_114.nextPosition(); } else { goto not_peg_113; } } result_peg_105.setPosition(position_peg_107); goto out_peg_111; not_peg_113: result_peg_105.setValue(Value((void*)0)); Result result_peg_117(result_peg_105); result_peg_117.setValue(Value((void*) "[")); for (int i = 0; i < 1; i++){ if (compareChar("["[i], stream.get(result_peg_117.getPosition()))){ result_peg_117.nextPosition(); } else { goto not_peg_116; } } result_peg_105.setPosition(position_peg_107); goto out_peg_111; not_peg_116: result_peg_105.setValue(Value((void*)0)); Result result_peg_120(result_peg_105); result_peg_120.setValue(Value((void*) 13)); if ((unsigned char) stream.get(result_peg_120.getPosition()) == (unsigned char) 13){ result_peg_120.nextPosition(); } else { goto not_peg_119; } result_peg_105.setPosition(position_peg_107); goto out_peg_111; not_peg_119: result_peg_105.setValue(Value((void*)0)); Result result_peg_123(result_peg_105); result_peg_123.setValue(Value((void*) "=")); for (int i = 0; i < 1; i++){ if (compareChar("="[i], stream.get(result_peg_123.getPosition()))){ result_peg_123.nextPosition(); } else { goto not_peg_122; } } result_peg_105.setPosition(position_peg_107); goto out_peg_111; not_peg_122: result_peg_105.setValue(Value((void*)0)); Result result_peg_126(result_peg_105); result_peg_126.setValue(Value((void*) ";")); for (int i = 0; i < 1; i++){ if (compareChar(";"[i], stream.get(result_peg_126.getPosition()))){ result_peg_126.nextPosition(); } else { goto not_peg_125; } } result_peg_105.setPosition(position_peg_107); goto out_peg_111; not_peg_125: result_peg_105.setValue(Value((void*)0)); char temp_peg_127 = stream.get(result_peg_105.getPosition()); if (temp_peg_127 != '\0'){ result_peg_105.setValue(Value((void*) (long) temp_peg_127)); result_peg_105.nextPosition(); } else { result_peg_105.setPosition(position_peg_107); goto out_peg_111; } } } goto success_peg_106; out_peg_111: goto not_peg_104; success_peg_106: ; goto out_peg_102; not_peg_104: result_peg_100.setValue(Value((void*)0)); Result result_peg_130(result_peg_100); result_peg_130.setValue(Value((void*) ".")); for (int i = 0; i < 1; i++){ if (compareChar("."[i], stream.get(result_peg_130.getPosition()))){ result_peg_130.nextPosition(); } else { goto not_peg_129; } } goto out_peg_102; not_peg_129: result_peg_100.setValue(Value((void*)0)); { Value value((void*) 0); value = makeKeyword(result_peg_101.getValues()); result_peg_100.setValue(value); } } stream.update(result_peg_100.getPosition()); return result_peg_100; out_peg_102: Result result_peg_131(myposition); { result_peg_131.setValue(Value((void*) "a")); for (int i = 0; i < 1; i++){ if (compareCharCase("a"[i], stream.get(result_peg_131.getPosition()))){ result_peg_131.nextPosition(); } else { goto out_peg_133; } } Result result_peg_132 = result_peg_131; int save_peg_135 = result_peg_131.getPosition(); result_peg_131 = rule_number(stream, result_peg_131.getPosition()); if (result_peg_131.error()){ result_peg_131 = Result(save_peg_135); result_peg_131.setValue(Value((void*) 0)); } Result result_peg_138(result_peg_131); { int position_peg_140 = result_peg_138.getPosition(); { Result result_peg_143(result_peg_138); result_peg_143.setValue(Value((void*) ",")); for (int i = 0; i < 1; i++){ if (compareChar(","[i], stream.get(result_peg_143.getPosition()))){ result_peg_143.nextPosition(); } else { goto not_peg_142; } } result_peg_138.setPosition(position_peg_140); goto out_peg_144; not_peg_142: result_peg_138.setValue(Value((void*)0)); Result result_peg_147(result_peg_138); result_peg_147.setValue(Value((void*) "\n")); for (int i = 0; i < 1; i++){ if (compareChar("\n"[i], stream.get(result_peg_147.getPosition()))){ result_peg_147.nextPosition(); } else { goto not_peg_146; } } result_peg_138.setPosition(position_peg_140); goto out_peg_144; not_peg_146: result_peg_138.setValue(Value((void*)0)); Result result_peg_150(result_peg_138); result_peg_150.setValue(Value((void*) "[")); for (int i = 0; i < 1; i++){ if (compareChar("["[i], stream.get(result_peg_150.getPosition()))){ result_peg_150.nextPosition(); } else { goto not_peg_149; } } result_peg_138.setPosition(position_peg_140); goto out_peg_144; not_peg_149: result_peg_138.setValue(Value((void*)0)); Result result_peg_153(result_peg_138); result_peg_153.setValue(Value((void*) 13)); if ((unsigned char) stream.get(result_peg_153.getPosition()) == (unsigned char) 13){ result_peg_153.nextPosition(); } else { goto not_peg_152; } result_peg_138.setPosition(position_peg_140); goto out_peg_144; not_peg_152: result_peg_138.setValue(Value((void*)0)); Result result_peg_156(result_peg_138); result_peg_156.setValue(Value((void*) "=")); for (int i = 0; i < 1; i++){ if (compareChar("="[i], stream.get(result_peg_156.getPosition()))){ result_peg_156.nextPosition(); } else { goto not_peg_155; } } result_peg_138.setPosition(position_peg_140); goto out_peg_144; not_peg_155: result_peg_138.setValue(Value((void*)0)); Result result_peg_159(result_peg_138); result_peg_159.setValue(Value((void*) ";")); for (int i = 0; i < 1; i++){ if (compareChar(";"[i], stream.get(result_peg_159.getPosition()))){ result_peg_159.nextPosition(); } else { goto not_peg_158; } } result_peg_138.setPosition(position_peg_140); goto out_peg_144; not_peg_158: result_peg_138.setValue(Value((void*)0)); char temp_peg_160 = stream.get(result_peg_138.getPosition()); if (temp_peg_160 != '\0'){ result_peg_138.setValue(Value((void*) (long) temp_peg_160)); result_peg_138.nextPosition(); } else { result_peg_138.setPosition(position_peg_140); goto out_peg_144; } } } goto success_peg_139; out_peg_144: goto not_peg_137; success_peg_139: ; goto out_peg_133; not_peg_137: result_peg_131.setValue(Value((void*)0)); { Value value((void*) 0); value = makeKeyword(result_peg_132.getValues()); result_peg_131.setValue(value); } } stream.update(result_peg_131.getPosition()); return result_peg_131; out_peg_133: Result result_peg_161(myposition); result_peg_161 = rule_filename(stream, result_peg_161.getPosition()); if (result_peg_161.error()){ goto out_peg_162; } stream.update(result_peg_161.getPosition()); return result_peg_161; out_peg_162: stream.update(errorResult.getPosition()); return errorResult; } Result rule_date(Stream & stream, const int position){ RuleTrace trace_peg_52(stream, "date"); int myposition = position; Result result_peg_2(myposition); { result_peg_2.reset(); do{ Result result_peg_5(result_peg_2.getPosition()); { int position_peg_7 = result_peg_5.getPosition(); char letter_peg_8 = stream.get(result_peg_5.getPosition()); if (letter_peg_8 != '\0' && strchr("0123456789", letter_peg_8) != NULL){ result_peg_5.nextPosition(); result_peg_5.setValue(Value((void*) (long) letter_peg_8)); } else { result_peg_5.setPosition(position_peg_7); goto out_peg_9; } } goto success_peg_6; out_peg_9: goto loop_peg_4; success_peg_6: ; result_peg_2.addResult(result_peg_5); } while (true); loop_peg_4: if (result_peg_2.matches() == 0){ goto out_peg_10; } Result result_peg_3 = result_peg_2; result_peg_2.setValue(Value((void*) ".")); for (int i = 0; i < 1; i++){ if (compareChar("."[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { goto out_peg_10; } } result_peg_2.reset(); do{ Result result_peg_14(result_peg_2.getPosition()); { int position_peg_16 = result_peg_14.getPosition(); char letter_peg_17 = stream.get(result_peg_14.getPosition()); if (letter_peg_17 != '\0' && strchr("0123456789", letter_peg_17) != NULL){ result_peg_14.nextPosition(); result_peg_14.setValue(Value((void*) (long) letter_peg_17)); } else { result_peg_14.setPosition(position_peg_16); goto out_peg_18; } } goto success_peg_15; out_peg_18: goto loop_peg_13; success_peg_15: ; result_peg_2.addResult(result_peg_14); } while (true); loop_peg_13: if (result_peg_2.matches() == 0){ goto out_peg_10; } Result result_peg_12 = result_peg_2; result_peg_2.setValue(Value((void*) ".")); for (int i = 0; i < 1; i++){ if (compareChar("."[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { goto out_peg_10; } } result_peg_2.reset(); do{ Result result_peg_22(result_peg_2.getPosition()); { int position_peg_24 = result_peg_22.getPosition(); char letter_peg_25 = stream.get(result_peg_22.getPosition()); if (letter_peg_25 != '\0' && strchr("0123456789", letter_peg_25) != NULL){ result_peg_22.nextPosition(); result_peg_22.setValue(Value((void*) (long) letter_peg_25)); } else { result_peg_22.setPosition(position_peg_24); goto out_peg_26; } } goto success_peg_23; out_peg_26: goto loop_peg_21; success_peg_23: ; result_peg_2.addResult(result_peg_22); } while (true); loop_peg_21: if (result_peg_2.matches() == 0){ goto out_peg_10; } Result result_peg_20 = result_peg_2; { Value value((void*) 0); value = makeDate(result_peg_3.getValues(),result_peg_12.getValues(),result_peg_20.getValues()); result_peg_2.setValue(value); } } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_10: Result result_peg_27(myposition); { result_peg_27.reset(); do{ Result result_peg_30(result_peg_27.getPosition()); { int position_peg_32 = result_peg_30.getPosition(); char letter_peg_33 = stream.get(result_peg_30.getPosition()); if (letter_peg_33 != '\0' && strchr("0123456789", letter_peg_33) != NULL){ result_peg_30.nextPosition(); result_peg_30.setValue(Value((void*) (long) letter_peg_33)); } else { result_peg_30.setPosition(position_peg_32); goto out_peg_34; } } goto success_peg_31; out_peg_34: goto loop_peg_29; success_peg_31: ; result_peg_27.addResult(result_peg_30); } while (true); loop_peg_29: if (result_peg_27.matches() == 0){ goto out_peg_35; } Result result_peg_28 = result_peg_27; result_peg_27.setValue(Value((void*) "/")); for (int i = 0; i < 1; i++){ if (compareChar("/"[i], stream.get(result_peg_27.getPosition()))){ result_peg_27.nextPosition(); } else { goto out_peg_35; } } result_peg_27.reset(); do{ Result result_peg_39(result_peg_27.getPosition()); { int position_peg_41 = result_peg_39.getPosition(); char letter_peg_42 = stream.get(result_peg_39.getPosition()); if (letter_peg_42 != '\0' && strchr("0123456789", letter_peg_42) != NULL){ result_peg_39.nextPosition(); result_peg_39.setValue(Value((void*) (long) letter_peg_42)); } else { result_peg_39.setPosition(position_peg_41); goto out_peg_43; } } goto success_peg_40; out_peg_43: goto loop_peg_38; success_peg_40: ; result_peg_27.addResult(result_peg_39); } while (true); loop_peg_38: if (result_peg_27.matches() == 0){ goto out_peg_35; } Result result_peg_37 = result_peg_27; result_peg_27.setValue(Value((void*) "/")); for (int i = 0; i < 1; i++){ if (compareChar("/"[i], stream.get(result_peg_27.getPosition()))){ result_peg_27.nextPosition(); } else { goto out_peg_35; } } result_peg_27.reset(); do{ Result result_peg_47(result_peg_27.getPosition()); { int position_peg_49 = result_peg_47.getPosition(); char letter_peg_50 = stream.get(result_peg_47.getPosition()); if (letter_peg_50 != '\0' && strchr("0123456789", letter_peg_50) != NULL){ result_peg_47.nextPosition(); result_peg_47.setValue(Value((void*) (long) letter_peg_50)); } else { result_peg_47.setPosition(position_peg_49); goto out_peg_51; } } goto success_peg_48; out_peg_51: goto loop_peg_46; success_peg_48: ; result_peg_27.addResult(result_peg_47); } while (true); loop_peg_46: if (result_peg_27.matches() == 0){ goto out_peg_35; } Result result_peg_45 = result_peg_27; { Value value((void*) 0); value = makeDate(result_peg_28.getValues(),result_peg_37.getValues(),result_peg_45.getValues()); result_peg_27.setValue(value); } } stream.update(result_peg_27.getPosition()); return result_peg_27; out_peg_35: stream.update(errorResult.getPosition()); return errorResult; } Result rule_number(Stream & stream, const int position){ RuleTrace trace_peg_12(stream, "number"); int myposition = position; Result result_peg_2(myposition); { int save_peg_4 = result_peg_2.getPosition(); { int position_peg_6 = result_peg_2.getPosition(); result_peg_2.setValue(Value((void*) "+")); for (int i = 0; i < 1; i++){ if (compareChar("+"[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { result_peg_2.setPosition(position_peg_6); goto out_peg_7; } } } goto success_peg_5; out_peg_7: { int position_peg_8 = result_peg_2.getPosition(); result_peg_2.setValue(Value((void*) "-")); for (int i = 0; i < 1; i++){ if (compareChar("-"[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { result_peg_2.setPosition(position_peg_8); goto out_peg_9; } } } goto success_peg_5; out_peg_9: result_peg_2 = Result(save_peg_4); result_peg_2.setValue(Value((void*) 0)); success_peg_5: ; Result result_peg_3 = result_peg_2; result_peg_2 = rule_float_or_integer(stream, result_peg_2.getPosition()); if (result_peg_2.error()){ goto out_peg_11; } Result result_peg_10 = result_peg_2; { Value value((void*) 0); value = makeNumber(result_peg_3.getValues(),result_peg_10.getValues()); result_peg_2.setValue(value); } } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_11: stream.update(errorResult.getPosition()); return errorResult; } Result rule_float_or_integer(Stream & stream, const int position){ RuleTrace trace_peg_31(stream, "float_or_integer"); int myposition = position; Value left; Value right; Result result_peg_2(myposition); { result_peg_2.reset(); do{ Result result_peg_5(result_peg_2.getPosition()); { int position_peg_7 = result_peg_5.getPosition(); char letter_peg_8 = stream.get(result_peg_5.getPosition()); if (letter_peg_8 != '\0' && strchr("0123456789", letter_peg_8) != NULL){ result_peg_5.nextPosition(); result_peg_5.setValue(Value((void*) (long) letter_peg_8)); } else { result_peg_5.setPosition(position_peg_7); goto out_peg_9; } } goto success_peg_6; out_peg_9: goto loop_peg_4; success_peg_6: ; result_peg_2.addResult(result_peg_5); } while (true); loop_peg_4: ; left = result_peg_2.getValues(); result_peg_2.setValue(Value((void*) ".")); for (int i = 0; i < 1; i++){ if (compareChar("."[i], stream.get(result_peg_2.getPosition()))){ result_peg_2.nextPosition(); } else { goto out_peg_11; } } result_peg_2.reset(); do{ Result result_peg_14(result_peg_2.getPosition()); { int position_peg_16 = result_peg_14.getPosition(); char letter_peg_17 = stream.get(result_peg_14.getPosition()); if (letter_peg_17 != '\0' && strchr("0123456789", letter_peg_17) != NULL){ result_peg_14.nextPosition(); result_peg_14.setValue(Value((void*) (long) letter_peg_17)); } else { result_peg_14.setPosition(position_peg_16); goto out_peg_18; } } goto success_peg_15; out_peg_18: goto loop_peg_13; success_peg_15: ; result_peg_2.addResult(result_peg_14); } while (true); loop_peg_13: if (result_peg_2.matches() == 0){ goto out_peg_11; } right = result_peg_2.getValues(); { Value value((void*) 0); value = parseDouble(left,right); result_peg_2.setValue(value); } } stream.update(result_peg_2.getPosition()); return result_peg_2; out_peg_11: Result result_peg_19(myposition); { result_peg_19.reset(); do{ Result result_peg_22(result_peg_19.getPosition()); { int position_peg_24 = result_peg_22.getPosition(); char letter_peg_25 = stream.get(result_peg_22.getPosition()); if (letter_peg_25 != '\0' && strchr("0123456789", letter_peg_25) != NULL){ result_peg_22.nextPosition(); result_peg_22.setValue(Value((void*) (long) letter_peg_25)); } else { result_peg_22.setPosition(position_peg_24); goto out_peg_26; } } goto success_peg_23; out_peg_26: goto loop_peg_21; success_peg_23: ; result_peg_19.addResult(result_peg_22); } while (true); loop_peg_21: if (result_peg_19.matches() == 0){ goto out_peg_27; } Result result_peg_20 = result_peg_19; Result result_peg_30(result_peg_19); result_peg_30.setValue(Value((void*) ".")); for (int i = 0; i < 1; i++){ if (compareChar("."[i], stream.get(result_peg_30.getPosition()))){ result_peg_30.nextPosition(); } else { goto not_peg_29; } } goto out_peg_27; not_peg_29: result_peg_19.setValue(Value((void*)0)); { Value value((void*) 0); value = parseDouble(result_peg_20.getValues()); result_peg_19.setValue(value); } } stream.update(result_peg_19.getPosition()); return result_peg_19; out_peg_27: stream.update(errorResult.getPosition()); return errorResult; } static const void * doParse(Stream & stream, bool stats, const std::string & context){ errorResult.setError(); Result done = rule_start(stream, 0); if (done.error()){ stream.reportError(context); } if (stats){ stream.printStats(); } return done.getValues().getValue(); } const void * parse(const std::string & filename, bool stats = false){ Stream stream(filename); return doParse(stream, stats, filename); } const void * parse(const char * in, bool stats = false){ Stream stream(in); return doParse(stream, stats, "memory"); } const void * parse(const char * in, int length, bool stats = false){ Stream stream(in, length); return doParse(stream, stats, "memory"); } } /* Def */ } /* Mugen */
0xflotus/shuttle
spec/lib/importer/ember_intl_spec.rb
<filename>spec/lib/importer/ember_intl_spec.rb # Copyright 2014 Square 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. require 'rails_helper' RSpec.describe Importer::EmberIntl do context "[importing]" do context "[repo with valid files]" do before :each do @project = FactoryBot.create(:project, repository_url: Rails.root.join('spec', 'fixtures', 'repository.git').to_s, only_paths: %w(ember-intl/), skip_imports: Importer::Base.implementations.map(&:ident) - %w(ember_intl)) @commit = @project.commit!('HEAD') end it "should import strings from YAML files" do expect(@project.keys.for_key('root_key_yaml').first.translations.find_by_rfc5646_locale('en-US').copy).to eql('root') expect(@project.keys.for_key('nested_key_yaml.one').first.translations.find_by_rfc5646_locale('en-US').copy).to eql('one') expect(@project.keys.for_key('nested_key_yaml.2').first.translations.find_by_rfc5646_locale('en-US').copy).to eql('two') end it "should import strings from JSON files" do expect(@project.keys.for_key('root_key_json').first.translations.find_by_rfc5646_locale('en-US').copy).to eql('root') expect(@project.keys.for_key('nested_key_json.one').first.translations.find_by_rfc5646_locale('en-US').copy).to eql('one') expect(@project.keys.for_key('nested_key_json.2').first.translations.find_by_rfc5646_locale('en-US').copy).to eql('two') end end context "[repo with broken files]" do before :each do @project = FactoryBot.create(:project, repository_url: Rails.root.join('spec', 'fixtures', 'repository-broken.git').to_s, only_paths: %w(ember-intl-broken/), skip_imports: Importer::Base.implementations.map(&:ident) - %w(ember_intl)) @commit = @project.commit!('b768471579ce072bb8949a40a45c77c2f30cdff4').reload end it "should add error to commit" do expect(@commit.import_errors.map{ |error| error.first }.sort).to eql(%w(JSON::ParserError Psych::SyntaxError).sort) expect(@commit.blobs.where(errored: true).count).to eql(2) expect(@commit.blobs.where(parsed: false).count).to eql(2) expect(@commit.blobs.where(parsed: true).count).to eql(0) end end end end
Diffblue-benchmarks/Xiancloud-xian
xian-core/src/main/java/info/xiancloud/core/test/output_test/UnitResponseTestUnit.java
package info.xiancloud.core.test.output_test; import info.xiancloud.core.*; import info.xiancloud.core.message.UnitRequest; import info.xiancloud.core.message.UnitResponse; import info.xiancloud.core.test.TestGroup; import java.util.HashMap; import java.util.Map; /** * @author happyyangyuan */ public class UnitResponseTestUnit implements Unit { @Override public String getName() { return "responseTestUnit"; } @Override public UnitMeta getMeta() { return UnitMeta.create().setDocApi(false); } @Override public Input getInput() { return null; } public String getThisGetterShouldNotSerialize() { throw new RuntimeException("序列化unit时这个getter方法不应该被调用,否则就是bug"); } @Override public Group getGroup() { return TestGroup.singleton; } @Override public void execute(UnitRequest request, Handler<UnitResponse> consumer) { Map<String, String> map = new HashMap<>(); map.put("这是测试key0", "这是测试值0"); map.put("这是测试key1", "这是测试值1"); consumer.handle(UnitResponse.createSuccess(map)); } }
aryx/principia-softwarica
lib_core/libc/9sys/fork.c
<reponame>aryx/principia-softwarica /*s: libc/9sys/fork.c */ #include <u.h> #include <libc.h> /*s: function [[fork]] */ int fork(void) { return rfork(RFPROC|RFFDG|RFREND); } /*e: function [[fork]] */ /*e: libc/9sys/fork.c */
CyrilenBlu/bookapp
src/main/java/blue/bookapp/controllers/BookController.java
package blue.bookapp.controllers; import blue.bookapp.services.BookService; import blue.bookapp.services.PagesService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @Controller @Slf4j public class BookController { private BookService bookService; private PagesService pagesService; public BookController(BookService bookService, PagesService pagesService) { this.bookService = bookService; this.pagesService = pagesService; } @GetMapping("book/{id}/info") public String viewBook(Model model, @PathVariable String id) { model.addAttribute("book", bookService.findCommandById(Long.valueOf(id))); model.addAttribute("page", pagesService.listPagesByBookId(Long.valueOf(id))); return "book/viewBook"; } @GetMapping("book/{id}/read/page/{pageId}") public String readBook(@PathVariable String id, @PathVariable String pageId, Model model) { model.addAttribute("book", bookService.findCommandById(Long.valueOf(id))); model.addAttribute("pages", pagesService.listPagesByBookId(Long.valueOf(id))); model.addAttribute("page", pagesService.getCommandByBookById(Long.valueOf(id), Long.valueOf(pageId))); return "book/read"; } }
dikshay/hackprinceton
wolfram_java/src/main/java/com/wolfram/alpha/impl/WAPodStateImpl.java
<filename>wolfram_java/src/main/java/com/wolfram/alpha/impl/WAPodStateImpl.java /* * Created on Dec 9, 2009 * */ package com.wolfram.alpha.impl; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.wolfram.alpha.WAException; import com.wolfram.alpha.WAPodState; import com.wolfram.alpha.visitor.Visitable; import com.wolfram.alpha.visitor.Visitor; // TODO: Synchronization needs work... public class WAPodStateImpl implements WAPodState, Visitable, Serializable { private String[] names = EMPTY_STRING_ARRAY; private String[] inputs = EMPTY_STRING_ARRAY; private String current = null; private int currentIndex = -1; private long id = 0; static final WAPodStateImpl[] EMPTY_ARRAY = new WAPodStateImpl[0]; private static final String[] EMPTY_STRING_ARRAY = new String[]{}; private static final String[] DEFAULT_NAME_ARRAY = new String[]{""}; private static final long serialVersionUID = -253401729369983369L; WAPodStateImpl(Element thisElement) throws WAException { createFromDOM(thisElement); } private WAPodStateImpl() {} // Because all podstates stored in a WAQueryParameters are represented as WAPodStates, there is a need // to create a "dummy" podstate from just an input string. This is used by the addPodState(String) signature. // It is only used in performing a query, so its name value is irrelevant. WAPodStateImpl(String input) { this(input, 0); } public WAPodStateImpl(String input, long id) { inputs = new String[]{input}; names = DEFAULT_NAME_ARRAY; currentIndex = 0; this.id = id; } private synchronized void createFromDOM(Element thisElement) throws WAException { // Two types: // // <state name="foo" input="bar"/> // // <statelist count=n value="current"> // <state name="name" input="input"/> // </statelist> String nodeName = thisElement.getNodeName(); if ("state".equals(nodeName)) { String name = thisElement.getAttribute("name"); String input = thisElement.getAttribute("input"); // Old-style API results only have a name and not an input attribute. Support old API // by using name value as input value. This is probably not important, as by the time this // library is in use, all API servers will be running new-style code. if ("".equals(input)) input = name; names = new String[]{name}; inputs = new String[]{input}; } else if ("statelist".equals(nodeName)) { String cur = thisElement.getAttribute("value"); if (!"".equals(cur)) current = cur; // Program defensively and don't assume that every element in a <statelist> is a <state>, // although we have no intention of making such a change in the API output. NodeList states = thisElement.getChildNodes(); int numStates = states.getLength(); List<Node> stateElements = new ArrayList<Node>(numStates); for (int i = 0; i < numStates; i++) { Node stateNode = states.item(i); if ("state".equals(stateNode.getNodeName())) stateElements.add(stateNode); } int numStatesFound = stateElements.size(); names = new String[numStatesFound]; inputs = new String[numStatesFound]; for (int i = 0; i < numStatesFound; i++) { Element stateElement = (Element) stateElements.get(i); String name = stateElement.getAttribute("name"); String input = stateElement.getAttribute("input"); // Old-style API results only have a name and not an input attribute. Support old API // by using name value as input value. This is probably not important, as by the time this // library is in use, all API servers will be running new-style code. if ("".equals(input)) input = name; names[i] = name; inputs[i] = input; } computeID(); } } public String[] getNames() { return names; } public String[] getInputs() { return inputs; } public int getCurrentIndex() { if (currentIndex >= 0) { // Cached value was already computed. return currentIndex; } else if (current == null) { // Not a multi-value type of podstate. currentIndex = 0; } else { // Compute and cache. for (int i = 0; i < names.length; i++) if (current.equals(names[i])) { currentIndex = i; break; } } return currentIndex; } // Only call this for a <statelist> type of podstate. public WAPodState setCurrentIndex(int index) { WAPodStateImpl newState = new WAPodStateImpl(); newState.names = this.names; newState.inputs = this.inputs; newState.currentIndex = index; newState.current = newState.names[index]; newState.computeID(); return newState; } public long getID() { return id; } /////////////////////////////// private void computeID() { // The id is basically a hash of the input strings. id = 17; for (String s : inputs) id += 37*id + s.hashCode(); } /////////////////////////// Visitor interface //////////////////////////// public void accept(Visitor v) { v.visit(this); } }
flatironinstitute/netket
NetKet/Operator/py_ising.hpp
// Copyright 2018 The Simons Foundation, Inc. - 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. #ifndef NETKET_PYISING_HPP #define NETKET_PYISING_HPP #include <pybind11/complex.h> #include <pybind11/eigen.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/stl_bind.h> #include <complex> #include <vector> #include "ising.hpp" namespace py = pybind11; namespace netket { void AddIsing(py::module &subm) { py::class_<Ising, AbstractOperator>(subm, "Ising", R"EOF(An Ising Hamiltonian operator.)EOF") .def(py::init<const AbstractHilbert &, double, double>(), py::keep_alive<1, 2>(), py::arg("hilbert"), py::arg("h"), py::arg("J") = 1.0, R"EOF( Constructs a new ``Ising`` given a hilbert space, a transverse field, and (if specified) a coupling constant. Args: hilbert: Hilbert space the operator acts on. h: The strength of the transverse field. J: The strength of the coupling. Default is 1.0. Examples: Constructs an ``Ising`` operator for a 1D system. ```python >>> import netket as nk >>> g = nk.graph.Hypercube(length=20, n_dim=1, pbc=True) >>> hi = nk.hilbert.Spin(s=0.5, graph=g) >>> op = nk.operator.Ising(h=1.321, hilbert=hi, J=0.5) >>> print(op.hilbert.size) 20 ``` )EOF"); } } // namespace netket #endif
naeramarth7/joynr
javascript/libjoynr-js/src/main/js/joynr/messaging/MessagingQos.js
/*eslint no-useless-escape: "off"*/ /* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ const defaultMessagingSettings = require("../start/settings/defaultMessagingSettings"); const LoggingManager = require("../system/LoggingManager"); const UtilInternal = require("../util/UtilInternal"); const MessagingQosEffort = require("./MessagingQosEffort"); const log = LoggingManager.getLogger("joynr/messaging/MessagingQos"); const defaultSettings = { ttl: 60000, customHeaders: {}, encrypt: false, compress: false }; /** * Constructor of MessagingQos object that is used in the generation of proxy objects * @constructor * @name MessagingQos * * @param {Object} [settings] the settings object for the constructor call * @param {Number} [settings.ttl] Roundtrip timeout for rpc requests, if missing default value is 60 seconds * @param {Boolean} [settings.encrypt] Specifies whether messages will be sent encrypted * @param {Boolean} [settings.compress] Specifies whether messages will be sent compressed * @param {MessagingQosEffort} [settings.effort] effort to expend on ensuring message delivery * * @returns {MessagingQos} a messaging Qos Object */ function MessagingQos(settings) { let errorMsg; if (!(this instanceof MessagingQos)) { // in case someone calls constructor without new keyword (e.g. var c = Constructor({..})) return new MessagingQos(settings); } settings = UtilInternal.extend({}, defaultSettings, settings); if (!MessagingQosEffort.isValid(settings.effort)) { settings.effort = MessagingQosEffort.NORMAL; } /** * The time to live for messages * * @name MessagingQos#ttl * @type Number */ if (settings.ttl > defaultMessagingSettings.MAX_MESSAGING_TTL_MS) { this.ttl = defaultMessagingSettings.MAX_MESSAGING_TTL_MS; errorMsg = `Error in MessageQos. Max allowed ttl: ${ defaultMessagingSettings.MAX_MESSAGING_TTL_MS }. Passed ttl: ${settings.ttl}`; log.warn(errorMsg); } else { this.ttl = settings.ttl; } /** * custom message headers * * @name MessagingQos#customHeaders * @type Object */ this.customHeaders = settings.customHeaders; /** * messaging qos effort * * @name MessagingQos#effort * @type MessagingQosEffort */ this.effort = settings.effort; /** * encrypt * * @name MessagingQos#encrypt * @type Boolean */ this.encrypt = settings.encrypt; if (settings.encrypt !== true && settings.encrypt !== false) { throw new Error("encrypt may only contain a boolean"); } /** * compress * * @name MessagingQos#compress * @type Boolean */ this.compress = settings.compress; if (settings.compress !== true && settings.compress !== false) { throw new Error("compress may only contain a boolean"); } } /** * * @param {String} key * may contain ascii alphanumeric or hyphen. * @param {String} value * may contain alphanumeric, space, semi-colon, colon, comma, plus, ampersand, question mark, hyphen, * dot, star, forward slash and back slash. */ function checkKeyAndValue(key, value) { const keyPattern = /^[a-zA-Z0-9\-]*$/; const valuePattern = /^[a-zA-Z0-9 ;:,+&\?\-\.\*\/\\]*$/; const keyOk = keyPattern.test(key); const valueOk = valuePattern.test(value); if (!keyOk) { throw new Error("custom header key may only contain alphanumeric characters"); } if (!valueOk) { throw new Error("custom header value contains illegal character. See JSDoc for allowed characters"); } return true; } /** * @name MessagingQos#putCustomHeader * @function * * @param {String} key * may contain ascii alphanumeric or hyphen. * @param {String} value * may contain alphanumeric, space, semi-colon, colon, comma, plus, ampersand, question mark, hyphen, * dot, star, forward slash and back slash. * @returns {JoynrMessage} */ Object.defineProperty(MessagingQos.prototype, "putCustomMessageHeader", { enumerable: false, configurable: false, writable: false, value(key, value) { checkKeyAndValue(key, value); this.customHeaders[key] = value; } }); /** * @name MessagingQos.DEFAULT_TTL * @type Number * @default 60000 * @static * @readonly */ MessagingQos.DEFAULT_TTL = defaultSettings.ttl; /** * @name MessagingQos.DEFAULT_ENCRYPT * @type Boolean * @default false * @static * @readonly */ MessagingQos.DEFAULT_ENCRYPT = defaultSettings.encrypt; /** * @name MessagingQos.DEFAULT_COMPRESS * @type Boolean * @default false * @static * @readonly */ MessagingQos.DEFAULT_COMPRESS = defaultSettings.compress; module.exports = MessagingQos;
vamtiger-project/vamtiger-node-typescript-project
build/snippet/json-ld-script.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = `import { ScriptType, url } from './types'; import jsonLd from './json-ld'; import json from './json'; import loadScript from './load-script'; const jsonLdParams = jsonLd.map(data => ({ url, type: ScriptType.jsonLd, data })); const jsonParams = { url, type: ScriptType.json, data: json }; const scriptParams = [ ...jsonLdParams, jsonParams ]; scriptParams.forEach(loadScript); `; //# sourceMappingURL=json-ld-script.js.map
GabrielSturtevant/mage
Mage.Sets/src/mage/cards/z/ZhangFeiFierceWarrior.java
<gh_stars>1000+ package mage.cards.z; import java.util.UUID; import mage.MageInt; import mage.abilities.keyword.HorsemanshipAbility; import mage.abilities.keyword.VigilanceAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.SuperType; /** * * @author LoneFox */ public final class ZhangFeiFierceWarrior extends CardImpl { public ZhangFeiFierceWarrior(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{4}{W}{W}"); this.addSuperType(SuperType.LEGENDARY); this.subtype.add(SubType.HUMAN, SubType.SOLDIER, SubType.WARRIOR); this.power = new MageInt(4); this.toughness = new MageInt(4); // Vigilance; horsemanship this.addAbility(VigilanceAbility.getInstance()); this.addAbility(HorsemanshipAbility.getInstance()); } private ZhangFeiFierceWarrior(final ZhangFeiFierceWarrior card) { super(card); } @Override public ZhangFeiFierceWarrior copy() { return new ZhangFeiFierceWarrior(this); } }
Fogapod/KiwiBot
objects/moduleexceptions.py
<reponame>Fogapod/KiwiBot<filename>objects/moduleexceptions.py class ModuleCallError(Exception): pass class GuildOnly(ModuleCallError): pass class NSFWPermissionDenied(ModuleCallError): pass class NotEnoughArgs(ModuleCallError): pass class TooManyArgs(ModuleCallError): pass class MissingPermissions(ModuleCallError): def __init__(self, *missing): self.missing = missing class Ratelimited(ModuleCallError): def __init__(self, ttl): self.time_left = ttl
itm/shawn
src/apps/testbedservice/virtual_links/virtual_link_task.cpp
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the BSD License. Refer to the shawn-licence.txt ** ** file in the root of the Shawn source tree for further details. ** ************************************************************************/ #include "../buildfiles/_apps_enable_cmake.h" #ifdef ENABLE_TESTBEDSERVICE #include "apps/testbedservice/virtual_links/virtual_link_task.h" #include "apps/testbedservice/virtual_links/virtual_link_transmission_model.h" #include "sys/transm_models/transmission_model_keeper.h" #include "sys/transm_models/chainable_transmission_model.h" #include "sys/simulation/simulation_controller.h" #include "sys/processors/processor_keeper.h" #include "sys/worlds/processor_world_factory.h" #include "sys/misc/random/basic_random.h" #include "sys/misc/tokenize.h" #include "sys/logging/logger.h" #include "sys/world.h" #include "sys/processor.h" namespace testbedservice { TestbedServiceVirtualLinkTask:: TestbedServiceVirtualLinkTask() {} // ---------------------------------------------------------------------- TestbedServiceVirtualLinkTask:: ~TestbedServiceVirtualLinkTask() {} // ---------------------------------------------------------------------- std::string TestbedServiceVirtualLinkTask:: name( void ) const throw() { return "webservice_virtual_link_task"; } // ---------------------------------------------------------------------- std::string TestbedServiceVirtualLinkTask:: description( void ) const throw() { return "Add/remove virtual links."; } // ---------------------------------------------------------------------- void TestbedServiceVirtualLinkTask:: run( shawn::SimulationController& sc ) throw( std::runtime_error ) { require_world( sc ); const shawn::SimulationEnvironment& se = sc.environment(); std::string action = se.required_string_param( "action" ); std::string shawn_urn = se.required_string_param( "shawn_node_urn" ); std::string virtual_urn = se.required_string_param( "virtual_node_urn" ); std::string remote_uri = se.required_string_param( "remote_uri" ); shawn::ChainableTransmissionModel *ctm = dynamic_cast<shawn::ChainableTransmissionModel*> ( &sc.world_w().transmission_model_w() ); if ( !ctm ) throw( std::runtime_error( "VirtualLinkTransmissionModel not found." ) ); while ( ctm ) { VirtualLinkTransmissionModel *vltm = dynamic_cast<VirtualLinkTransmissionModel*>( ctm ); if ( vltm ) { if ( action == "add" ) vltm->add_virtual_link( shawn_urn, virtual_urn, remote_uri ); if ( action == "remove" ) vltm->remove_virtual_link( shawn_urn, virtual_urn ); // Transmission Model found, so end while loop break; } if ( ctm->has_next_transm_model() ) ctm = dynamic_cast<shawn::ChainableTransmissionModel*> ( &ctm->next_transm_model_w() ); else throw( std::runtime_error( "VirtualLinkTransmissionModel not found." ) ); } } } #endif
BaiXiongjun/JavaLearning
src/java/Java2Store/Tree/TwoBinTree/ThreeLinkBinTree.java
package Java2Store.Tree.TwoBinTree; /***Created by moyongzhuo *On 2018/3/23 ***17:45. ******/ /** * Created by ietree * 2017/5/1 */ public class ThreeLinkBinTree<E> { public static class TreeNode { Object data; TreeNode left; TreeNode right; TreeNode parent; public TreeNode() { } public TreeNode(Object data) { this.data = data; } public TreeNode(Object data, TreeNode left, TreeNode right, TreeNode parent) { this.data = data; this.left = left; this.right = right; this.parent = parent; } } private TreeNode root; // 以默认的构造器创建二叉树 public ThreeLinkBinTree() { this.root = new TreeNode(); } // 以指定根元素创建二叉树 public ThreeLinkBinTree(E data) { this.root = new TreeNode(data); } /** * 为指定节点添加子节点 * * @param parent 需要添加子节点的父节点的索引 * @param data 新子节点的数据 * @param isLeft 是否为左节点 * @return 新增的节点 */ public TreeNode addNode(TreeNode parent, E data, boolean isLeft) { if (parent == null) { throw new RuntimeException(parent + "节点为null, 无法添加子节点"); } if (isLeft && parent.left != null) { throw new RuntimeException(parent + "节点已有左子节点,无法添加左子节点"); } if (!isLeft && parent.right != null) { throw new RuntimeException(parent + "节点已有右子节点,无法添加右子节点"); } TreeNode newNode = new TreeNode(data); if (isLeft) { // 让父节点的left引用指向新节点 parent.left = newNode; } else { // 让父节点的left引用指向新节点 parent.right = newNode; } // 让新节点的parent引用到parent节点 newNode.parent = parent; return newNode; } // 判断二叉树是否为空 public boolean empty() { // 根据元素判断二叉树是否为空 return root.data == null; } // 返回根节点 public TreeNode root() { if (empty()) { throw new RuntimeException("树为空,无法访问根节点"); } return root; } // 返回指定节点(非根节点)的父节点 public E parent(TreeNode node) { if (node == null) { throw new RuntimeException("节点为null,无法访问其父节点"); } return (E) node.parent.data; } // 返回指定节点(非叶子)的左子节点,当左子节点不存在时返回null public E leftChild(TreeNode parent) { if (parent == null) { throw new RuntimeException(parent + "节点为null,无法添加子节点"); } return parent.left == null ? null : (E) parent.left.data; } // 返回指定节点(非叶子)的右子节点,当右子节点不存在时返回null public E rightChild(TreeNode parent) { if (parent == null) { throw new RuntimeException(parent + "节点为null,无法添加子节点"); } return parent.right == null ? null : (E) parent.right.data; } // 返回该二叉树的深度 public int deep() { // 获取该树的深度 return deep(root); } // 这是一个递归方法:每一棵子树的深度为其所有子树的最大深度 + 1 private int deep(TreeNode node) { if (node == null) { return 0; } // 没有子树 if (node.left == null && node.right == null) { return 1; } else { int leftDeep = deep(node.left); int rightDeep = deep(node.right); // 记录其所有左、右子树中较大的深度 int max = leftDeep > rightDeep ? leftDeep : rightDeep; // 返回其左右子树中较大的深度 + 1 return max + 1; } } }
Noahhoetger2001/test-infra
gopherage/cmd/junit/junit.go
/* Copyright 2018 The Kubernetes 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 junit import ( "fmt" "io" "os" "github.com/spf13/cobra" "k8s.io/test-infra/gopherage/pkg/cov/junit" "k8s.io/test-infra/gopherage/pkg/util" ) type flags struct { outputFile string threshold float32 } // MakeCommand returns a `junit` command. func MakeCommand() *cobra.Command { flags := &flags{} cmd := &cobra.Command{ Use: "junit [profile]", Short: "Summarize coverage profile and produce the result in junit xml format.", Long: `Summarize coverage profile and produce the result in junit xml format. Summary done at per-file and per-package level. Any coverage below coverage-threshold will be marked with a <failure> tag in the xml produced.`, Run: func(cmd *cobra.Command, args []string) { run(flags, cmd, args) }, } cmd.Flags().StringVarP(&flags.outputFile, "output", "o", "-", "output file") cmd.Flags().Float32VarP(&flags.threshold, "threshold", "t", .8, "code coverage threshold") return cmd } func run(flags *flags, cmd *cobra.Command, args []string) { if len(args) != 1 { fmt.Fprintln(os.Stderr, "Expected exactly one argument: coverage file path") cmd.Usage() os.Exit(2) } if flags.threshold < 0 || flags.threshold > 1 { fmt.Fprintln(os.Stderr, "coverage threshold must be a float number between 0 to 1, inclusively") os.Exit(1) } profilePath := args[0] profiles, err := util.LoadProfile(profilePath) if err != nil { fmt.Fprintf(os.Stderr, "Failed to parse profile file: %v.", err) os.Exit(1) } text, err := junit.ProfileToTestsuiteXML(profiles, flags.threshold) if err != nil { fmt.Fprintf(os.Stderr, "Failed to produce xml from profiles: %v.", err) os.Exit(1) } var file io.WriteCloser if flags.outputFile == "-" { file = os.Stdout } else { file, err = os.Create(flags.outputFile) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create file: %v.", err) os.Exit(1) } defer file.Close() } if _, err = file.Write(text); err != nil { fmt.Fprintf(os.Stderr, "Failed to write xml: %v.", err) os.Exit(1) } }
vidyadeepa/the-coding-interview
problems/remove-duplicates-from-string/remove-duplicates-from-string.py
# Python 2 from string import lower def remove_duplicates(string): seen = [] for ch in lower(string): if not ch in seen: seen.append(ch) return "".join(seen) print remove_duplicates("tree traversal") # tre avsl # Python 3 def remove_dupes(string): seen = [] for ch in string.lower(): if ch not in seen: seen.append(ch) return "".join(seen) print(remove_dupes("tree traversal")) # tre avsl # This is O(n^2) but one-liner def remove_dupes(string): return ''.join(sorted(set(string), key=string.index)) print(remove_dupes("tree traversal")) # tre avsl # Another approach using OrderedDict from collections import OrderedDict def remove_dupes(string): return "".join(OrderedDict.fromkeys(string)) print(remove_dupes("tree traversal")) # tre avsl
udacity/pontoon
pontoon/sync/views.py
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.shortcuts import get_object_or_404, render from pontoon.sync.models import SyncLog def sync_log_list(request): sync_logs = SyncLog.objects.order_by('-start_time') paginator = Paginator(sync_logs, 24) page = request.GET.get('page') try: sync_logs = paginator.page(page) except PageNotAnInteger: sync_logs = paginator.page(1) except EmptyPage: sync_logs = paginator.page(paginator.num_pages) return render(request, 'sync/log_list.html', { 'sync_logs': sync_logs, }) def sync_log_details(request, sync_log_pk): # Prefetch for the end_time queryset = SyncLog.objects.prefetch_related( 'project_sync_logs__repository_sync_logs__repository', 'project_sync_logs__project__repositories', ) sync_log = get_object_or_404(queryset, pk=sync_log_pk) project_sync_logs = sync_log.project_sync_logs.all() repository_sync_logs = { project_log: project_log.repository_sync_logs.all() for project_log in project_sync_logs } return render(request, 'sync/log_details.html', { 'sync_log': sync_log, 'project_sync_logs': project_sync_logs, 'repository_sync_logs': repository_sync_logs, })
YodaEmbedding/experiments
py/rxpy/modules.py
import time import rx from rx import operators as ops from rx.subject import Subject # numbers = rx.from_iterable(i for i in range(10)).pipe( # ops.publish(), # ) # # numbers.pipe( # ops.filter(lambda x: x % 2 == 0) # ).subscribe(lambda x: print(f"Even: {x}")) # # numbers.pipe( # ops.filter(lambda x: x % 2 == 1) # ).subscribe(lambda x: print(f"Odd: {x}")) # # numbers.pipe( # ops.filter(lambda x: x % 3 == 0) # ).subscribe(lambda x: print(f"Triple: {x}")) # # zipping = numbers.pipe( # ops.zip(numbers), # ) # zipping.subscribe(lambda x: print(x)) # # numbers.subscribe(lambda x: print("---------")) # numbers.connect() frames = rx.interval(1) # simulate n seconds of computation? class Module: def to_rx(self, *inputs): if len(inputs) == 0: raise ValueError if len(inputs) == 1: observable = inputs[0] else: observable = rx.zip(*inputs) return observable # return observable.pipe(ops.map(), ops.publish()) # result.connect # frames.subscribe(print) module = Module() module # ... # gate = Subject() # gate.subscribe(lambda x: print(f"received {x}")) # rx.interval(1).pipe( # ops.do_action(lambda x: gate.on_next(f"gate: {x}")), # ).subscribe() time.sleep(10) # As long as we are always using CPU, the thread ordering doesn't really matter
TomCreeper/goldmine
util/xkcd.py
<reponame>TomCreeper/goldmine<gh_stars>1-10 """Async xkcd library.""" from .json import loads as jloads import random import async_timeout import aiohttp XKCD_URL = 'http://www.xkcd.com/' IMAGE_URL = 'http://imgs.xkcd.com/comics/' EXPLAIN_URL = 'http://explainxkcd.com/' LINK_OFFSET = len(IMAGE_URL) class Comic(object): """xkcd comic.""" def __init__(self, number): self.number = number if number <= 0: raise InvalidComic('%s is not a valid comic' % str(number)) self.link = XKCD_URL + str(number) self.jlink = self.link + '/info.0.json' self.explain_url = EXPLAIN_URL + str(number) async def async_init(self): with async_timeout.timeout(6.5): async with aiohttp.request('GET', self.jlink) as r: xkcd = await r.text() data = jloads(xkcd) self.title = data['safe_title'] self.alt_text = data['alt'] self.image_link = data['img'] index = self.image_link.find(IMAGE_URL) self.image_name = self.image_link[index + LINK_OFFSET:] async def fetch(self): with async_timeout.timeout(6.5): async with aiohttp.request('GET', self.image_link) as r: return await r.read() class InvalidComic(Exception): pass async def latest_comic_num(): with async_timeout.timeout(6.5): async with aiohttp.request('GET', 'http://xkcd.com/info.0.json') as r: xkcd = await r.text() return jloads(xkcd)['num'] async def random_comic(): random.seed() num_comics = await latest_comic_num() comic = Comic(random.randint(1, num_comics)) await comic.async_init() return comic async def get_comic(number): num_comics = await latest_comic_num() if number > num_comics or number <= 0: raise InvalidComic('%s is not a valid comic' % str(number)) comic = Comic(number) await comic.async_init() return comic async def latest_comic(): number = await latest_comic_num() comic = Comic(number) await comic.async_init() return comic
NovasomIndustries/Utils-2019.01
rock/app/settings/bluetooth/bluetoothdevicetable.cpp
<reponame>NovasomIndustries/Utils-2019.01 #include "bluetoothdevicetable.h" #include "retranslatemanager.h" #include <QHeaderView> #ifdef DEVICE_EVB int move_distance_next_step = 300; int bluetooth_item_height = 65; #else int move_distance_next_step = 100; int bluetooth_item_height = 35; #endif #define COLUME_ICON 1 #define COLUME_NAME 2 #define COLUME_ADDRESS 3 #define COLUME_STATE 4 BluetoothStateItem::BluetoothStateItem(const QString &text) : QTableWidgetItem(text) { } bool BluetoothStateItem::operator <(const QTableWidgetItem &other) const { BtState state = BtState(this->whatsThis().toInt()); BtState otherState = BtState(other.whatsThis().toInt()); if (state == BT_STATE_CONNECTED) { return false; } else if(state == BT_STATE_PAIRED) { if (otherState == BT_STATE_CONNECTED) return true; else return false; } return QTableWidgetItem::operator <(other); } BluetoothDeviceTable::BluetoothDeviceTable(QWidget *parent) : BaseTableWidget(parent, move_distance_next_step) { init(); } void BluetoothDeviceTable::init() { insertColumn(0); insertColumn(1); insertColumn(2); insertColumn(3); insertColumn(4); verticalHeader()->setDefaultSectionSize(bluetooth_item_height); } void BluetoothDeviceTable::insertIntoTable(const QString &name, const QString &address, BtState state) { int rowcount= rowCount(); insertRow(rowcount); setItem(rowcount, COLUME_ICON, new QTableWidgetItem(QIcon(QPixmap(":/image/setting/bluetooth_item_icon.png")),"")); setItem(rowcount, COLUME_NAME, new QTableWidgetItem(name)); setItem(rowcount, COLUME_ADDRESS, new QTableWidgetItem(address)); setItemState(rowcount, state); item(rowcount, COLUME_NAME)->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); item(rowcount, COLUME_ADDRESS)->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); item(rowcount, COLUME_STATE)->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); sortTable(); } void BluetoothDeviceTable::sortTable() { sortItems(COLUME_STATE, Qt::DescendingOrder); } void BluetoothDeviceTable::setItemState(int itemRow, BtState state) { switch (state) { case BT_STATE_CONNECTED: setItem(itemRow, COLUME_STATE, new BluetoothStateItem(QString(str_bluetooth_item_connected))); break; case BT_STATE_PAIRING: setItem(itemRow, COLUME_STATE, new BluetoothStateItem(QString(str_bluetooth_item_pairing))); break; case BT_STATE_PAIRED: setItem(itemRow, COLUME_STATE, new BluetoothStateItem(QString(str_bluetooth_item_paired))); break; default: setItem(itemRow, COLUME_STATE, new BluetoothStateItem(QString(" "))); break; } item(itemRow, COLUME_STATE)->setWhatsThis(QString::number(state)); } void BluetoothDeviceTable::retranslateTable() { BtState state; for (int i = 0; i < rowCount(); i++) { state = BtState(item(i, COLUME_STATE)->whatsThis().toInt()); setItemState(i, state); } } void BluetoothDeviceTable::clearTable() { for (int i = rowCount(); i > 0; i--) removeRow(0); } QString BluetoothDeviceTable::getItemName(int row) { return item(row, COLUME_NAME)->text(); } QString BluetoothDeviceTable::getItemAddress(int row) { return item(row, COLUME_ADDRESS)->text(); } void BluetoothDeviceTable::resizeEvent(QResizeEvent *event) { #ifdef DEVICE_EVB horizontalHeader()->resizeSection(0, 20); horizontalHeader()->resizeSection(1, 50); horizontalHeader()->resizeSection(2, this->width() - 520); horizontalHeader()->resizeSection(3, 300); horizontalHeader()->resizeSection(4, 150); #else horizontalHeader()->resizeSection(0, 20); horizontalHeader()->resizeSection(1, 20); horizontalHeader()->resizeSection(2, this->width() - 380); horizontalHeader()->resizeSection(3, 220); horizontalHeader()->resizeSection(4, 120); #endif QTableWidget::resizeEvent(event); }
Koichi-Kobayashi/orangesignal-csv
src/main/java/com/orangesignal/jlha/PostLh1Encoder.java
<reponame>Koichi-Kobayashi/orangesignal-csv /** * Copyright (C) 2002 <NAME> All rights reserved. * * 以下の条件に同意するならばソースとバイナリ形式の再配布と使用を * 変更の有無にかかわらず許可する。 * * 1.ソースコードの再配布において著作権表示と この条件のリスト * および下記の声明文を保持しなくてはならない。 * * 2.バイナリ形式の再配布において著作権表示と この条件のリスト * および下記の声明文を使用説明書もしくは その他の配布物内に * 含む資料に記述しなければならない。 * * このソフトウェアは石塚美珠瑠によって無保証で提供され、特定の目 * 的を達成できるという保証、商品価値が有るという保証にとどまらず、 * いかなる明示的および暗示的な保証もしない。 * 石塚美珠瑠は このソフトウェアの使用による直接的、間接的、偶発 * 的、特殊な、典型的な、あるいは必然的な損害(使用によるデータの * 損失、業務の中断や見込まれていた利益の遺失、代替製品もしくは * サービスの導入費等が考えられるが、決してそれだけに限定されない * 損害)に対して、いかなる事態の原因となったとしても、契約上の責 * 任や無過失責任を含む いかなる責任があろうとも、たとえそれが不 * 正行為のためであったとしても、またはそのような損害の可能性が報 * 告されていたとしても一切の責任を負わないものとする。 */ package com.orangesignal.jlha; import java.io.IOException; import java.io.OutputStream; /** * -lh1- 圧縮用の PostLzssEncoder。 <br> * * @author $Author: dangan $ * @version $Revision: 1.1 $ */ public class PostLh1Encoder implements PostLzssEncoder { /** 辞書サイズ */ private static final int DICTIONARY_SIZE = 4096; /** 最大一致長 */ private static final int MAX_MATCH = 60; /** 最小一致長 */ private static final int THRESHOLD = 3; /** * -lh1- 形式の圧縮データの出力先の ビット出力ストリーム */ private BitOutputStream out; /** * Code部圧縮用適応的ハフマン木 */ private DynamicHuffman huffman; /** * offset部の上位6bit圧縮用ハフマン符号の表 */ private int[] offHiCode; /** * offset部の上位6bit圧縮用ハフマン符号長の表 */ private int[] offHiLen; /** * -lh1- 圧縮用 PostLzssEncoder を構築する。 * * @param out 圧縮データを受け取る出力ストリーム */ public PostLh1Encoder(final OutputStream out) { if (out != null) { if (out instanceof BitOutputStream) { this.out = (BitOutputStream) out; } else { this.out = new BitOutputStream(out); } huffman = new DynamicHuffman(314); offHiLen = createLenList(); try { offHiCode = StaticHuffman.LenListToCodeList(offHiLen); } catch (final BadHuffmanTableException exception) { } } else { throw new NullPointerException("out"); } } /** * -lh1- の offsetデコード用StaticHuffmanの ハフマン符号長リストを生成する。 * * @return -lh1- の offsetデコード用StaticHuffmanの ハフマン符号長リスト */ private static int[] createLenList() { final int length = 64; final int[] list = { 3, 0x01, 0x04, 0x0C, 0x18, 0x30, 0 }; final int[] LenList = new int[length]; int index = 0; int len = list[index++]; for (int i = 0; i < length; i++) { if (list[index] == i) { len++; index++; } LenList[i] = len; } return LenList; } // ------------------------------------------------------------------ // method of jp.gr.java_conf.dangan.util.lha.PostLzssEncoder /** * 1byte の LZSS未圧縮のデータもしくは、 LZSS で圧縮された圧縮コードのうち一致長を書きこむ。<br> * * @param code 1byte の LZSS未圧縮のデータもしくは、 LZSS で圧縮された圧縮コードのうち一致長 * @exception IOException 入出力エラーが発生した場合 */ @Override public void writeCode(final int code) throws IOException { int node = huffman.codeToNode(code); int hcode = 0; int hlen = 0; do { hcode >>>= 1; hlen++; if ((node & 1) != 0) { hcode |= 0x80000000; } node = huffman.parentNode(node); } while (node != DynamicHuffman.ROOT); out.writeBits(hlen, hcode >> 32 - hlen); // throws IOException huffman.update(code); } /** * LZSS で圧縮された圧縮コードのうち一致位置を書きこむ。<br> * * @param offset LZSS で圧縮された圧縮コードのうち一致位置 */ @Override public void writeOffset(final int offset) throws IOException { final int offHi = offset >> 6; out.writeBits(offHiLen[offHi], offHiCode[offHi]); // throws IOException out.writeBits(6, offset); // throws IOException } /** * この PostLzssEncoder にバッファリングされている 全ての 8ビット単位のデータを出力先の OutputStream に出力し、 出力先の OutputStream を flush() する。<br> * このメソッドは圧縮率を変化させない。 * * @exception IOException 入出力エラーが発生した場合 * @see PostLzssEncoder#flush() * @see BitOutputStream#flush() */ @Override public void flush() throws IOException { out.flush(); // throws IOException } /** * この出力ストリームと、接続された出力ストリームを閉じ、 使用していたリソースを解放する。<br> * * @exception IOException 入出力エラーが発生した場合 */ @Override public void close() throws IOException { out.close(); // throws IOException out = null; huffman = null; offHiLen = null; offHiCode = null; } /** * -lh1-形式の LZSS辞書のサイズを得る。 * * @return -lh1-形式の LZSS辞書のサイズ */ @Override public int getDictionarySize() { return DICTIONARY_SIZE; } /** * -lh1-形式の LZSSの最大一致長を得る。 * * @return -lz5-形式の LZSSの最大一致長 */ @Override public int getMaxMatch() { return MAX_MATCH; } /** * -lh1-形式の LZSSの圧縮、非圧縮の閾値を得る。 * * @return -lh1-形式の LZSSの圧縮、非圧縮の閾値 */ @Override public int getThreshold() { return THRESHOLD; } }
unyankee/OutterSpace
engine/src/vulkan_device.cpp
<filename>engine/src/vulkan_device.cpp<gh_stars>0 #include "vulkan_device.h" #include <cassert> #include <iostream> #include <vulkan_debug.h> VkBool32 getSupportedDepthFormat(VkPhysicalDevice physicalDevice, VkFormat* depthFormat) { // Since all depth formats may be optional, we need to find a suitable depth format to use // Start with the highest precision packed format std::vector<VkFormat> depthFormats = {VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D32_SFLOAT, VK_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D16_UNORM_S8_UINT, VK_FORMAT_D16_UNORM}; for (auto& format : depthFormats) { VkFormatProperties formatProps; vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &formatProps); // Format must support depth stencil attachment for optimal tiling if (formatProps.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { *depthFormat = format; return true; } } return false; } void VulkanDevice::get_device_properties() { // Store Properties features, limits and properties of the physical device for later use // Device properties also contain limits and sparse properties // vkGetPhysicalDeviceProperties2(m_physical_device, &m_properties); vkGetPhysicalDeviceProperties(m_physical_device, &m_properties); vkGetPhysicalDeviceFeatures(m_physical_device, &m_features); vkGetPhysicalDeviceMemoryProperties(m_physical_device, &m_memoryProperties); // Queue family properties uint32_t queueFamilyCount; vkGetPhysicalDeviceQueueFamilyProperties(m_physical_device, &queueFamilyCount, nullptr); assert(queueFamilyCount > 0); m_queue_family_properties.resize(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(m_physical_device, &queueFamilyCount, m_queue_family_properties.data()); // Get list of supported extensions uint32_t extCount = 0; vkEnumerateDeviceExtensionProperties(m_physical_device, nullptr, &extCount, nullptr); if (extCount > 0) { std::vector<VkExtensionProperties> extensions(extCount); if (vkEnumerateDeviceExtensionProperties(m_physical_device, nullptr, &extCount, &extensions.front()) == VK_SUCCESS) { for (auto ext : extensions) { m_supported_extensions.push_back(ext.extensionName); } } } } VulkanDevice::~VulkanDevice() { if (m_vulkan_device) { vkDestroyDevice(m_vulkan_device, nullptr); } } void VulkanDevice::create_device_instance() { // VkApplicationInfo, contains the data about the application we intend to create, important to add the VULKAN API // version to it in this case, should not be modified, since it is in the extern dir of this project... VkApplicationInfo appInfo = {}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "OutterSpace"; appInfo.pEngineName = "OutterSpace"; appInfo.apiVersion = VK_API_VERSION_1_2; std::vector<const char*> instance_extensions = {VK_KHR_SURFACE_EXTENSION_NAME}; // This surface extension is different for each OS... // Right now this is targetting only WINDOWS instance_extensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME); // Get extensions supported by the instance and store them for later use uint32_t extensions_count = 0; vkEnumerateInstanceExtensionProperties(nullptr, &extensions_count, nullptr); if (extensions_count > 0) { std::vector<VkExtensionProperties> extensions(extensions_count); if (vkEnumerateInstanceExtensionProperties(nullptr, &extensions_count, &extensions.front()) == VK_SUCCESS) { for (VkExtensionProperties extension : extensions) { m_supported_instance_extensions.push_back(extension.extensionName); } } } // Add to the list of extensions, the ones requested via m_enabled_instance_extensions if (m_requested_extensions.size() > 0) { for (const char* enabledExtension : m_requested_extensions) { // Output message if requested extension is not available if (std::find(m_requested_extensions.begin(), m_requested_extensions.end(), enabledExtension) == m_requested_extensions.end()) { std::cerr << "Enabled m_instance extension \"" << enabledExtension << "\" is not present at m_instance level\n"; } instance_extensions.push_back(enabledExtension); } } // Information regarding the VK intance we intent to create VkInstanceCreateInfo instanceCreateInfo = {}; instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; instanceCreateInfo.pNext = NULL; // pointer to any structure extending this structure, or NULL in this case... nothing to extent instanceCreateInfo.pApplicationInfo = &appInfo; if (instance_extensions.size() > 0) { if (m_settings.m_enable_validation_layer) { instance_extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); } instanceCreateInfo.enabledExtensionCount = (uint32_t)instance_extensions.size(); instanceCreateInfo.ppEnabledExtensionNames = instance_extensions.data(); } // if the validation layer has been requested, it needs to find out if is being properly added // by simply checking the list of already requested extensions if (m_settings.m_enable_validation_layer) { const char* validation_layer_name = "VK_LAYER_KHRONOS_validation"; // get the number of requested extensions uint32_t instance_layer_count; vkEnumerateInstanceLayerProperties(&instance_layer_count, nullptr); // the same function will overwrite the vector, with the right values std::vector<VkLayerProperties> instance_layer_properties(instance_layer_count); vkEnumerateInstanceLayerProperties(&instance_layer_count, instance_layer_properties.data()); bool validation_layer_present = false; for (VkLayerProperties layer : instance_layer_properties) { if (strcmp(layer.layerName, validation_layer_name) == 0) { validation_layer_present = true; break; } } if (validation_layer_present) { instanceCreateInfo.ppEnabledLayerNames = &validation_layer_name; instanceCreateInfo.enabledLayerCount = 1; } else { std::cerr << "Validation layer VK_LAYER_KHRONOS_validation not present, m_enable_validation_layer is disabled"; } } if (vkCreateInstance(&instanceCreateInfo, nullptr, &m_vk_instance) != VK_SUCCESS) { assert("Vulkan instance could not be created !!"); }; // If requested, we enable the default validation layers for debugging if (m_settings.m_enable_validation_layer) { // The report flags determine what type of messages for the layers will be displayed // For validating (debugging) an application the error and warning bits should suffice VkDebugReportFlagsEXT debugReportFlags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT; // Additional flags include performance info, loader and layer debug messages, etc. vks::debug::setupDebugging(m_vk_instance, debugReportFlags, VK_NULL_HANDLE); } // Physical device uint32_t gpu_count = 0; // Get number of available physical devices vkEnumeratePhysicalDevices(m_vk_instance, &gpu_count, nullptr); if (gpu_count == 0) { assert("No dedicated gpu found !!"); } // Enumerate devices std::vector<VkPhysicalDevice> physical_devices(gpu_count); vkEnumeratePhysicalDevices(m_vk_instance, &gpu_count, physical_devices.data()); // Just select the first GPU... // TODO: In the future this could be extended to command line, or I guess that might be rebuilt to choose which GPU // to choose etc... uint32_t selectedDevice = 0; m_physical_device = physical_devices[selectedDevice]; // vkGetPhysicalDeviceProperties(m_physical_device, &m_device_properties); vkGetPhysicalDeviceProperties(m_physical_device, &m_device_properties); vkGetPhysicalDeviceFeatures(m_physical_device, &m_device_features); vkGetPhysicalDeviceMemoryProperties(m_physical_device, &m_device_memory_properties); //----------------------------------------------------------------------// // TODO: get enabled features in here, need to search what actually is... //----------------------------------------------------------------------// get_device_properties(); VkResult res = create_logical_device(); if (res != VK_SUCCESS) { assert("Could not create a vk logical device !!"); } // Get all queues from the device // vkGetDeviceQueue(m_vulkan_device, m_graphics_queue_id, 0, &m_graphics_queue); // vkGetDeviceQueue(m_vulkan_device, m_compute_queue_id, 0, &m_compute_queue); // vkGetDeviceQueue(m_vulkan_device, m_transfer_queue_id, 0, &m_transfer_queue); VkBool32 validDepthFormat = getSupportedDepthFormat(m_physical_device, &m_depthFormat); if (!validDepthFormat) { // TODO: ASSERT } } uint32_t VulkanDevice::get_queue_family_index(VkQueueFlagBits queueFlags) const { // Dedicated queue for compute // Try to find a queue family index that supports compute but not graphics if (queueFlags & VK_QUEUE_COMPUTE_BIT) { for (uint32_t i = 0; i < static_cast<uint32_t>(m_queue_family_properties.size()); i++) { if ((m_queue_family_properties[i].queueFlags & queueFlags) && ((m_queue_family_properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) == 0)) { return i; } } } // Dedicated queue for transfer // Try to find a queue family index that supports transfer but not graphics and compute if (queueFlags & VK_QUEUE_TRANSFER_BIT) { for (uint32_t i = 0; i < static_cast<uint32_t>(m_queue_family_properties.size()); i++) { if ((m_queue_family_properties[i].queueFlags & queueFlags) && ((m_queue_family_properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) == 0) && ((m_queue_family_properties[i].queueFlags & VK_QUEUE_COMPUTE_BIT) == 0)) { return i; } } } // For other queue types or if no separate compute queue is present, return the first one to support the requested // flags for (uint32_t i = 0; i < static_cast<uint32_t>(m_queue_family_properties.size()); i++) { if (m_queue_family_properties[i].queueFlags & queueFlags) { return i; } } throw std::runtime_error("Could not find a matching m_graphics_queue family index"); } VkResult VulkanDevice::create_logical_device() { const VkQueueFlags requestedQueueTypes = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT; // Desired queues need to be requested upon logical device creation // Due to differing queue family configurations of Vulkan implementations this can be a bit tricky, especially if // the application requests different queue types std::vector<VkDeviceQueueCreateInfo> queue_create_infos{}; // Get queue family indices for the requested queue family types // Note that the indices may overlap depending on the implementation uint32_t m_graphics_queue_id = VK_NULL_HANDLE; uint32_t m_compute_queue_id = VK_NULL_HANDLE; uint32_t m_transfer_queue_id = VK_NULL_HANDLE; // TODO: this needs to be passed dowm, a priority for each queue... >.> float defaultQueuePriority[16]; for (int i = 0; i < 16; ++i) { defaultQueuePriority[i] = 0.0f; } // Graphics queue if (requestedQueueTypes & VK_QUEUE_GRAPHICS_BIT) { m_graphics_queue_id = get_queue_family_index(VK_QUEUE_GRAPHICS_BIT); VkDeviceQueueCreateInfo queueInfo{}; queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueInfo.queueFamilyIndex = m_graphics_queue_id; queueInfo.queueCount = m_queue_family_properties[m_graphics_queue_id].queueCount; queueInfo.pQueuePriorities = defaultQueuePriority; queue_create_infos.push_back(queueInfo); } // Dedicated compute queue if (requestedQueueTypes & VK_QUEUE_COMPUTE_BIT) { m_compute_queue_id = get_queue_family_index(VK_QUEUE_COMPUTE_BIT); if (m_compute_queue_id != m_graphics_queue_id) { // If compute family index differs, we need an additional queue create info for the compute queue VkDeviceQueueCreateInfo queueInfo{}; queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueInfo.queueFamilyIndex = m_compute_queue_id; queueInfo.queueCount = m_queue_family_properties[m_compute_queue_id].queueCount; queueInfo.pQueuePriorities = defaultQueuePriority; queue_create_infos.push_back(queueInfo); } } // Dedicated transfer queue if (requestedQueueTypes & VK_QUEUE_TRANSFER_BIT) { m_transfer_queue_id = get_queue_family_index(VK_QUEUE_TRANSFER_BIT); if ((m_transfer_queue_id != m_graphics_queue_id) && (m_transfer_queue_id != m_compute_queue_id)) { // If compute family index differs, we need an additional queue create info for the tranfer queue VkDeviceQueueCreateInfo queueInfo{}; queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueInfo.queueFamilyIndex = m_transfer_queue_id; queueInfo.queueCount = m_queue_family_properties[m_transfer_queue_id].queueCount; queueInfo.pQueuePriorities = defaultQueuePriority; queue_create_infos.push_back(queueInfo); } } // Create the logical device representation std::vector<const char*> device_extensions(m_enabledDeviceExtensions); // use swapchain, so, request one via extension { // If the device will be used for presenting to a display via a swapchain we need to request the swapchain // extension device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); device_extensions.push_back(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME); device_extensions.push_back(VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME); // device_extensions.push_back(VK_KHR_get_physical_device_properties2); } VkPhysicalDeviceSynchronization2FeaturesKHR synchronization2_feature = {}; synchronization2_feature.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR; synchronization2_feature.synchronization2 = VK_TRUE; synchronization2_feature.pNext; VkPhysicalDeviceDynamicRenderingFeaturesKHR dynamic_rendering_feature = {}; dynamic_rendering_feature.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR; dynamic_rendering_feature.dynamicRendering = VK_TRUE; dynamic_rendering_feature.pNext = &synchronization2_feature; VkDeviceCreateInfo deviceCreateInfo = {}; deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; deviceCreateInfo.pNext = &dynamic_rendering_feature; deviceCreateInfo.queueCreateInfoCount = static_cast<uint32_t>(queue_create_infos.size()); ; deviceCreateInfo.pQueueCreateInfos = queue_create_infos.data(); deviceCreateInfo.pEnabledFeatures = &m_enabled_features; // If a pNext(Chain) has been passed, we need to add it to the device creation info VkPhysicalDeviceFeatures2 physicalDeviceFeatures2{}; if (m_deviceCreatepNextChain) { physicalDeviceFeatures2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; physicalDeviceFeatures2.features = m_enabled_features; physicalDeviceFeatures2.pNext = m_deviceCreatepNextChain; deviceCreateInfo.pEnabledFeatures = nullptr; deviceCreateInfo.pNext = &physicalDeviceFeatures2; } // Enable the debug marker extension if it is present (likely meaning a debugging tool is present) if (extensionSupported(VK_EXT_DEBUG_MARKER_EXTENSION_NAME)) { device_extensions.push_back(VK_EXT_DEBUG_MARKER_EXTENSION_NAME); m_settings.m_enableDebugMarkers = true; } if (device_extensions.size() > 0) { for (const char* enabledExtension : device_extensions) { if (!extensionSupported(enabledExtension)) { std::cerr << "Enabled m_device extension \"" << enabledExtension << "\" is not present at m_device level\n"; } } deviceCreateInfo.enabledExtensionCount = (uint32_t)device_extensions.size(); deviceCreateInfo.ppEnabledExtensionNames = device_extensions.data(); } VkResult result = vkCreateDevice(m_physical_device, &deviceCreateInfo, nullptr, &m_vulkan_device); if (result != VK_SUCCESS) { return result; } return result; } bool VulkanDevice::extensionSupported(std::string extension) { return (std::find(m_supported_extensions.begin(), m_supported_extensions.end(), extension) != m_supported_extensions.end()); }
jackusz/flowman
flowman-spec/src/main/scala/com/dimajix/flowman/spec/target/BlackholeTarget.scala
<reponame>jackusz/flowman<filename>flowman-spec/src/main/scala/com/dimajix/flowman/spec/target/BlackholeTarget.scala /* * Copyright 2018 <NAME> * * 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.dimajix.flowman.spec.target import com.fasterxml.jackson.annotation.JsonProperty import com.dimajix.common.No import com.dimajix.common.Trilean import com.dimajix.common.Yes import com.dimajix.flowman.execution.Context import com.dimajix.flowman.execution.Executor import com.dimajix.flowman.execution.MappingUtils import com.dimajix.flowman.execution.Phase import com.dimajix.flowman.model.BaseTarget import com.dimajix.flowman.model.MappingOutputIdentifier import com.dimajix.flowman.model.ResourceIdentifier import com.dimajix.flowman.model.Target case class BlackholeTarget( instanceProperties:Target.Properties, mapping:MappingOutputIdentifier ) extends BaseTarget { /** * Returns all phases which are implemented by this target in the execute method * @return */ override def phases : Set[Phase] = Set(Phase.BUILD) /** * Returns a list of physical resources required by this target * @return */ override def requires(phase: Phase) : Set[ResourceIdentifier] = { phase match { case Phase.BUILD => MappingUtils.requires(context, mapping.mapping) case _ => Set() } } /** * Returns the state of the target, specifically of any artifacts produces. If this method return [[Yes]], * then an [[execute]] should update the output, such that the target is not 'dirty' any more. * @param executor * @param phase * @return */ override def dirty(executor: Executor, phase: Phase) : Trilean = { phase match { case Phase.BUILD => Yes case _ => No } } /** * Abstract method which will perform the output operation. All required tables need to be * registered as temporary tables in the Spark session before calling the execute method. * * @param executor */ override def build(executor:Executor) : Unit = { val mapping = context.getMapping(this.mapping.mapping) val df = executor.instantiate(mapping, this.mapping.output) df.write.format("null").save() } } class BlackholeTargetSpec extends TargetSpec { @JsonProperty(value = "mapping", required=true) private var mapping:String = _ override def instantiate(context: Context): BlackholeTarget = { BlackholeTarget( instanceProperties(context), MappingOutputIdentifier.parse(context.evaluate(mapping)) ) } }
VoNgocThuan/KhoaLuanTotNghiep
resources/js/components/layouts/SearchProducts.js
<filename>resources/js/components/layouts/SearchProducts.js import Axios from 'axios'; import React, { Component } from 'react'; import Product from './Product'; import { connect } from "react-redux"; import * as actions from "./../actions/index"; import SearchProduct from './SearchProduct'; class SearchProducts extends Component { constructor(props) { super(props); this.state = { keywords_submit: '', booklist: [], listState: '1', } this.changeSlide = this.changeSlide.bind(this) }; changeSlide(value) { this.setState({ listState: { value } }) console.log(value); } componentDidMount(){ this.searchBook(); this.changeSlide('1') } searchBook = () => { const searchData = { keywords_submit: this.props.searchBook.search } const response = Axios.post('http://localhost:8000/api/tim-kiem', searchData) .then(res => { this.setState({ booklist: res.data, keywords_submit: this.props.searchBook.search }); }); if(response.success){ this.setState({ keywords_submit: '', }); } else { this.setState({ errors: response.errors, }); } } componentWillMount() { } buyItem=(value)=>{ this.props.temp=value; } render() { var namesButton = [ { id: 1, keyid: '1', name: 'Mới' }, { id: 2, keyid: '2', name: '<NAME>' }, { id: 3, keyid: '3', name: '<NAME>' } ] var buttonNames = namesButton.map((btnName, index) => { return <button key={index} className={this.state.listState.value === btnName.keyid ? 'btnCategory active' : 'btnCategory'} onClick={() => { this.changeSlide(btnName.keyid) }}>{btnName.name}</button> }); var listProducts = this.state.booklist.map((product, index) => { if (this.state.listState.value === '1') { if (product.new) { return <SearchProduct key={index} bookId={product.bookId} img={product.image1} name={product.name} author={product.author} price={product.price} temp={(value)=>{this.buyItem(value)}}></SearchProduct> } } else if (this.state.listState.value === '2') { if (product.bestsale) { return <SearchProduct key={index} bookId={product.bookId} img={product.image1} name={product.name} author={product.author} price={product.price} temp={(value)=>{this.buyItem(value)}}></SearchProduct> } } else { if (product.toprating) { return <SearchProduct key={index} bookId={product.bookId} img={product.image1} name={product.name} author={product.author} price={product.price} temp={(value)=>{this.buyItem(value)}}></SearchProduct> } } }) return ( <div className="sanpham"> <div className="container"> <div className="title">SẢN PHẨM <span>CỦA CHÚNG TÔI</span></div> <div className="boxCategory"> {buttonNames} </div> <div className="listProducts"> <div className="row"> {listProducts} </div> </div> </div> </div> ); } } const mapStateToProps = state => { return { searchBook: state.searchBook }; }; export default connect(mapStateToProps, null)(SearchProducts);
lukaszlaszuk/insightconnect-plugins
plugins/openphish/komand_openphish/triggers/save_feed_file/trigger.py
<gh_stars>10-100 import komand import time from .schema import SaveFeedFileInput, SaveFeedFileOutput, Input, Output # Custom imports below import base64 import requests class SaveFeedFile(komand.Trigger): def __init__(self): super(self.__class__, self).__init__( name="save_feed_file", description="Store the results of the feed file locally", input=SaveFeedFileInput(), output=SaveFeedFileOutput(), ) def run(self, params={}): """Run the trigger""" while True: feed_file = self.get_file_if_changed() if feed_file: with komand.helper.open_cachefile("/var/cache/feed.txt") as f: f.write(feed_file.decode("utf-8")) self.send( { Output.STATUSCODE: 200, Output.ENCODEDFEEDFILE: base64.b64encode(feed_file).decode("utf-8"), } ) time.sleep(params.get(Input.INTERVAL, 5)) def get_file_if_changed(self): with komand.helper.open_cachefile("/var/cache/.etag") as f: etag = f.read() if not etag: etag = "" response = requests.get(self.connection.url, headers={"If-None-Match": etag}) if response.status_code == 304: return None if response.status_code == 200: with komand.helper.open_cachefile("/var/cache/.etag") as f: f.write(response.headers.get("etag")) return response.content self.logger.error( "Error: Received HTTP %d status code from OpenPhish. Please check OpenPhish url " "and try again. If the issue persists please contact support. " "Server response was: %s" % (response.status_code, response.text) ) return None
Cubeside/CubeQuest
src/main/java/de/iani/cubequest/commands/StopEditingQuestCommand.java
package de.iani.cubequest.commands; import de.iani.cubequest.CubeQuest; import de.iani.cubequest.util.ChatAndTextUtil; import de.iani.cubesideutils.bukkit.commands.SubCommand; import de.iani.cubesideutils.commands.ArgsParser; import java.util.Collections; import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; public class StopEditingQuestCommand extends SubCommand { public static final String[] COMMAND_PATH = new String[] {"edit", "stop"}; public static final String FULL_COMMAND = "quest " + COMMAND_PATH[0] + " " + COMMAND_PATH[1]; @Override public boolean onCommand(CommandSender sender, Command command, String alias, String commandString, ArgsParser args) { if (!CubeQuest.getInstance().getQuestEditor().stopEdit(sender)) { ChatAndTextUtil.sendWarningMessage(sender, "Du bearbeitest derzeit keine Quest."); } return true; } @Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, ArgsParser args) { return Collections.emptyList(); } @Override public String getRequiredPermission() { return CubeQuest.EDIT_QUESTS_PERMISSION; } }
Fimbure/icebox-1
third_party/virtualbox/src/libs/xpcom18a4/nsprpub/pr/tests/exit.c
<filename>third_party/virtualbox/src/libs/xpcom18a4/nsprpub/pr/tests/exit.c /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Netscape Portable Runtime (NSPR). * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "prio.h" #include "prprf.h" #include "prinit.h" #include "prthread.h" #include "prproces.h" #include "prinrval.h" #include "plgetopt.h" #include <stdlib.h> static PRInt32 dally = 0; static PRFileDesc *err = NULL; static PRBool verbose = PR_FALSE, force = PR_FALSE; static void Help(void) { PR_fprintf(err, "Usage: [-t s] [-h]\n"); PR_fprintf(err, "\t-d Verbose output (default: FALSE)\n"); PR_fprintf(err, "\t-x Forced termination (default: FALSE)\n"); PR_fprintf(err, "\t-t Time for thread to block (default: 10 seconds)\n"); PR_fprintf(err, "\t-h This message and nothing else\n"); } /* Help */ static void Dull(void *arg) { PR_Sleep(PR_SecondsToInterval(dally)); if (verbose && force) PR_fprintf(err, "If you see this, the test failed\n"); } /* Dull */ static PRIntn PR_CALLBACK RealMain(PRIntn argc, char **argv) { PLOptStatus os; PLOptState *opt = PL_CreateOptState(argc, argv, "ht:dx"); err = PR_GetSpecialFD(PR_StandardError); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { if (PL_OPT_BAD == os) continue; switch (opt->option) { case 'd': /* verbosity */ verbose = PR_TRUE; break; case 'x': /* force exit */ force = PR_TRUE; break; case 't': /* seconds to dally in child */ dally = atoi(opt->value); break; case 'h': /* user wants some guidance */ default: Help(); /* so give him an earful */ return 2; /* but not a lot else */ } } PL_DestroyOptState(opt); if (0 == dally) dally = 10; /* * Create LOCAL and GLOBAL threads */ (void)PR_CreateThread( PR_USER_THREAD, Dull, NULL, PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, PR_UNJOINABLE_THREAD, 0); (void)PR_CreateThread( PR_USER_THREAD, Dull, NULL, PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, 0); if (verbose) PR_fprintf( err, "Main is exiting now. Program should exit %s.\n", (force) ? "immediately" : "after child dally time"); if (force) { PR_ProcessExit(0); if (verbose) { PR_fprintf(err, "You should not have gotten here.\n"); return 1; } } return 0; } PRIntn main(PRIntn argc, char *argv[]) { PRIntn rv; PR_STDIO_INIT(); rv = PR_Initialize(RealMain, argc, argv, 0); return rv; } /* main */
GeneralMine/Loomo-Ros-App
loomo-app/src/main/java/de/iteratec/loomo/ros/publisher/OdomHolder.java
package de.iteratec.loomo.ros.publisher; import static java.lang.Math.cos; import static java.lang.Math.sin; import com.segway.robot.algo.Pose2D; import nav_msgs.Odometry; import org.apache.commons.math3.complex.Quaternion; public class OdomHolder { private Odometry odom = null; private Odometry initialodom; private Pose2D originalinitialpose = new Pose2D(0, 0, 0, 0, 0, System.currentTimeMillis()); private Pose2D initialpose = new Pose2D(0, 0, 0, 0, 0, System.currentTimeMillis()); private Quaternion initialq = Quaternion.IDENTITY; private boolean firstime=true; public OdomHolder() { } public Pose2D getInitialpose() { return initialpose; } public void setInitialpose(Pose2D initialpose) { if(firstime){ originalinitialpose=initialpose; firstime=false; } this.initialpose = initialpose; } public Quaternion getInitialq() { return initialq; } public void setInitialq(Quaternion initialq) { this.initialq = initialq; } public Odometry getOdom() { return odom; } public void setOdom(Odometry odom) { this.odom = odom; } public Pose2D getOriginalinitialpose() { return originalinitialpose; } public void setOriginalinitialpose(Pose2D originalinitialpose) { this.originalinitialpose = originalinitialpose; } Quaternion toQuaternion(double pitch, double roll, double yaw) { // Abbreviations for the various angular functions double cy = cos(yaw * 0.5); double sy = sin(yaw * 0.5); double cr = cos(roll * 0.5); double sr = sin(roll * 0.5); double cp = cos(pitch * 0.5); double sp = sin(pitch * 0.5); double w = cy * cr * cp + sy * sr * sp; double x = cy * sr * cp - sy * cr * sp; double y = cy * cr * sp + sy * sr * cp; double z = sy * cr * cp - cy * sr * sp; Quaternion q = new Quaternion(w, x, y, z); return q; } }
wizzifactory/wizzi-history
old_packages/wizzi-lab-spa/lib/artifacts/spa/webpack/gen/main.js
/* artifact generator: /wizzi/lib/artifacts/js/module/gen/main.js primary source IttfDocument: c:\my\wizzi\v2\sources\plugins\wizzi-lab-spa\ittf\lib\artifacts\spa\webpack\gen\main.js.ittf utc time: Mon, 17 Jul 2017 15:07:32 GMT */ 'use strict'; var util = require('util'); var path = require('path'); var wizzi = require('wizzi'); var md = module.exports = {}; var myname = 'spa.webpack.main'; md.gen = function(model, ctx, callback) { var ittfDocumentPath = path.join(__dirname, 'ittf', 'webpack.js.ittf'); wizzi.jsModule(ittfDocumentPath, { spa: model, request: {} }, function(err, result) { if (err) { throw new Error(err); } ctx.w(result); callback(null, ctx); }); };
ARCHTK-prog/utils-tools
utils-netx-extension-flink/src/main/java/com/chua/utils/netx/flink/format/MemOutputFormat.java
package com.chua.utils.netx.flink.format; import com.chua.utils.netx.flink.utils.RowUtils; import com.chua.utils.tools.bean.copy.BeanCopy; import com.chua.utils.tools.empty.EmptyOrBase; import com.chua.utils.tools.util.ClassUtils; import org.apache.flink.table.api.TableColumn; import org.apache.flink.table.api.TableSchema; import org.apache.flink.types.Row; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.chua.utils.tools.constant.NumberConstant.DEFAULT_INITIAL_CAPACITY; /** * mem Output * * @author CH * @version 1.0.0 * @since 2021/1/26 */ public class MemOutputFormat extends FlinkOutputFormat { @Override public void open(int taskNumber, int numTasks) throws IOException { } @Override public void writeRecord(Row record) throws IOException { Class<?> dataType = FormatConnector.getDataType(sign); if (null == dataType) { try { throw new Exception("Unrecognized data"); } catch (Exception e) { e.printStackTrace(); } } if (Map.class.isAssignableFrom(dataType)) { intoMap(record); return; } Object forObject = ClassUtils.forObject(dataType); if (null == forObject) { try { throw new Exception("No valid null parameter construction"); } catch (Exception e) { e.printStackTrace(); } } intoEntity(record, forObject); } /** * 保存记录 * * @param record 记录 * @param forObject 对象 */ private void intoEntity(Row record, Object forObject) { Object item = BeanCopy.of(forObject).with(RowUtils.toMap(record, FormatConnector.getSchema(sign))).create(); FormatConnector.addData(sign, item); } /** * 设置map值 * * @param record 记录 */ private void intoMap(Row record) { TableSchema schema = FormatConnector.getSchema(sign); int arity = record.getArity(); List<TableColumn> tableColumns = schema.getTableColumns(); Map<String, Object> item = new HashMap<>(DEFAULT_INITIAL_CAPACITY); if (tableColumns.size() >= arity) { for (int i = 0; i < arity; i++) { TableColumn tableColumn = schema.getTableColumn(i).get(); item.put(tableColumn.getName(), EmptyOrBase.getTypeConverter(tableColumn.getType().getConversionClass()).convert(record.getField(i))); } } else { for (int i = 0; i < tableColumns.size(); i++) { TableColumn tableColumn = tableColumns.get(i); item.put(tableColumn.getName(), EmptyOrBase.getTypeConverter(tableColumn.getType().getConversionClass()).convert(record.getField(i))); } } FormatConnector.addData(sign, item); } @Override public void close() throws IOException { } }
tcarnoldussen/Menge
src/Plugins/AgtHelbing/HelbingAgent.h
/* Menge Crowd Simulation Framework Copyright and trademark 2012-17 University of North Carolina at Chapel Hill 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 or LICENSE.txt in the root of the Menge repository. Any questions or comments should be sent to the authors <EMAIL> <http://gamma.cs.unc.edu/Menge/> */ /*! @file HelbingAgent.h @brief The agent specification for the pedestrian model based on the Helbing et al., 2000 paper. */ #ifndef __HELBING_AGENT_H__ #define __HELBING_AGENT_H__ #include "MengeCore/Agents/BaseAgent.h" namespace Helbing { /*! @brief Agent definition for the Helbing pedestrian model. */ class Agent : public Menge::Agents::BaseAgent { public: /*! @brief A variant of the copy constructor. */ Agent(); /*! @brief Destroys this agent instance. */ ~Agent(); /*! @brief Computes the new velocity of this agent. */ void computeNewVelocity(); /*! @brief Used by the plugin system to know what artifacts to associate with agents of this type. Every sub-class of must return a globally unique value if it should be associated with unique artifacts. */ virtual std::string getStringId() const { return NAME; } /*! @brief The name identifier for this agent type. */ static const std::string NAME; /*! @brief Compute the force due to another agent. @param other A pointer to a neighboring agent. @returns The force imparted by the other agent on this agent. */ Menge::Math::Vector2 agentForce(const Agent* other) const; /*! @brief Compute the force due to a nearby obstacle. @param obst A pointer to the obstacle. @returns The force imparted by the obstacle on this agent. */ Menge::Math::Vector2 obstacleForce(const Menge::Agents::Obstacle* obst) const; /*! @brief Computes the driving force for the agent. @returns The vector corresponding to the agent's driving force. */ Menge::Math::Vector2 drivingForce() const; /*! @brief The mass of the agent. */ float _mass; }; } // namespace Helbing #endif // __HELBING_AGENT_H__
SciGaP/DEPRECATED-Cipres-Airavata-POC
saminda/cipres-airavata/sdk/src/main/java/org/ngbw/sdk/tool/GridFtpInputStream.java
/* * GridFtpInputStream.java */ package org.ngbw.sdk.tool; import java.io.IOException; import java.io.InputStream; import org.globus.ftp.GridFTPClient; import org.globus.ftp.InputStreamDataSink; import org.globus.ftp.exception.ClientException; import org.globus.ftp.exception.ServerException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * @author <NAME> * */ class GridFtpInputStream extends InputStream { private static final Log log = LogFactory.getLog(GridFtpInputStream.class.getName()); private final GridFTPClient m_client; private final InputStreamDataSink m_sink = new InputStreamDataSink(); private final InputStream m_stream; private boolean m_closed = false; // constructors /** * * @param client * @param fileName * @throws IOException * @throws ClientException * @throws ServerException */ GridFtpInputStream(GridFTPClient client, String fileName) throws IOException, ClientException, ServerException { m_client = client; m_client.asynchGet(fileName, m_sink, null); m_stream = m_sink.getInputStream(); } // public methods /** * * @return * @throws IOException */ @Override public int available() throws IOException { return m_stream.available(); } /** * * @throws IOException */ @Override public void close() throws IOException { try { if (!m_closed) { m_stream.close(); m_sink.close(); m_client.close(); m_closed = true; // can't close m_client multiple times w/o error. } } catch (ServerException serverErr) { throw new IOException(serverErr.getMessage()); } } /** * * @param readlimit */ @Override public void mark(int readlimit) { m_stream.mark(readlimit); } /** * * @return */ @Override public boolean markSupported() { return m_stream.markSupported(); } /** * * @return * @throws IOException */ public int read() throws IOException { return m_stream.read(); } /** * * @param b * @return * @throws IOException */ @Override public int read(byte[] b) throws IOException { return m_stream.read(b); } /** * * @param b * @param off * @param len * @return * @throws IOException */ @Override public int read(byte[] b, int off, int len) throws IOException { return m_stream.read(b, off, len); } /** * * @throws IOException */ @Override public void reset() throws IOException { m_stream.reset(); } /** * * @param n * @return * @throws IOException */ @Override public long skip(long n) throws IOException { return m_stream.skip(n); } }
ChenZhangg/jzy3d-api
jzy3d-core-awt/src/main/java/org/jzy3d/plot3d/rendering/legends/colorbars/policies/MaxShrinkSizingPolicy.java
<gh_stars>100-1000 package org.jzy3d.plot3d.rendering.legends.colorbars.policies; public class MaxShrinkSizingPolicy implements IColorbarSizingPolicy{ public MaxShrinkSizingPolicy() { // TODO Auto-generated constructor stub } }
wnameless/rubycollect4j
src/main/java/net/sf/rubycollect4j/util/ByteUtils.java
/* * * Copyright 2013 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * */ package net.sf.rubycollect4j.util; import static java.nio.ByteOrder.BIG_ENDIAN; import static java.nio.ByteOrder.LITTLE_ENDIAN; import java.lang.reflect.Method; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import net.sf.rubycollect4j.Ruby; import net.sf.rubycollect4j.RubyArray; /** * * {@link ByteUtils} provides functions to manipulate bytes or to convert * variety Objects into bytes. * * @author <NAME> * */ public final class ByteUtils { private static final Logger logger = Logger.getLogger(ByteUtils.class.getName()); private ByteUtils() {}; /** * Converts a byte array to a {@link RubyArray} of Byte. * * @param bytes * a byte array * @return {@link RubyArray} of Byte */ public static RubyArray<Byte> toList(byte[] bytes) { RubyArray<Byte> list = Ruby.Array.create(); for (byte b : bytes) { list.add(b); } return list; } /** * Converts a Collection of Number to a byte array. * * @param bytes * a Collection of Number * @return byte array */ public static byte[] toArray(Collection<? extends Number> bytes) { byte[] array = new byte[bytes.size()]; Iterator<? extends Number> iter = bytes.iterator(); for (int i = 0; i < bytes.size(); i++) { array[i] = iter.next().byteValue(); } return array; } /** * Modifies the length of a byte array by padding zero bytes to the right. * * @param bytes * a byte array * @param width * of the new byte array * @return new byte array */ public static byte[] ljust(byte[] bytes, int width) { if (bytes.length >= width) { return Arrays.copyOf(bytes, width); } else { byte[] ljustied = new byte[width]; System.arraycopy(bytes, 0, ljustied, 0, bytes.length); return ljustied; } } /** * Modifies the length of a byte array by padding zero bytes to the left. * * @param bytes * a byte array * @param width * of the new byte array * @return new byte array */ public static byte[] rjust(byte[] bytes, int width) { if (bytes.length >= width) { return Arrays.copyOfRange(bytes, bytes.length - width, bytes.length); } else { byte[] rjustied = new byte[width]; System.arraycopy(bytes, 0, rjustied, width - bytes.length, bytes.length); return rjustied; } } /** * Reverses a byte array in place. * * @param bytes * to be reversed */ public static void reverse(byte[] bytes) { for (int i = 0; i < bytes.length / 2; i++) { byte temp = bytes[i]; bytes[i] = bytes[bytes.length - 1 - i]; bytes[bytes.length - 1 - i] = temp; } } /** * Converts a byte into a byte array. * * @param b * a byte * @return byte array */ public static byte[] toByteArray(byte b) { return new byte[] { b }; } /** * Converts a short into a byte array by big-endian byte order. * * @param s * a short * @return byte array */ public static byte[] toByteArray(short s) { return ByteBuffer.allocate(2).order(BIG_ENDIAN).putShort(s).array(); } /** * Converts a short into a byte array. * * @param s * a short * @param bo * a ByteOrder * @return byte array */ public static byte[] toByteArray(short s, ByteOrder bo) { return ByteBuffer.allocate(2).order(bo).putShort(s).array(); } /** * Converts an int into a byte array by big-endian byte order. * * @param i * an int * @return byte array */ public static byte[] toByteArray(int i) { return ByteBuffer.allocate(4).order(BIG_ENDIAN).putInt(i).array(); } /** * Converts an int into a byte array. * * @param i * an int * @param bo * a ByteOrder * @return byte array */ public static byte[] toByteArray(int i, ByteOrder bo) { return ByteBuffer.allocate(4).order(bo).putInt(i).array(); } /** * Converts a long into a byte array by big-endian byte order. * * @param l * a long * @return byte array */ public static byte[] toByteArray(long l) { return ByteBuffer.allocate(8).order(BIG_ENDIAN).putLong(l).array(); } /** * Converts a long into a byte array. * * @param l * a long * @param bo * a ByteOrder * @return byte array */ public static byte[] toByteArray(long l, ByteOrder bo) { return ByteBuffer.allocate(8).order(bo).putLong(l).array(); } /** * Converts a float into a byte array by big-endian byte order. * * @param f * a float * @return byte array */ public static byte[] toByteArray(float f) { return ByteBuffer.allocate(4).order(BIG_ENDIAN).putFloat(f).array(); } /** * Converts a float into a byte array. * * @param f * a float * @param bo * a ByteOrder * @return byte array */ public static byte[] toByteArray(float f, ByteOrder bo) { return ByteBuffer.allocate(4).order(bo).putFloat(f).array(); } /** * Converts a double into a byte array by big-endian byte order. * * @param d * a double * @return byte array */ public static byte[] toByteArray(double d) { return ByteBuffer.allocate(8).order(BIG_ENDIAN).putDouble(d).array(); } /** * Converts a double into a byte array. * * @param d * a double * @param bo * a ByteOrder * @return byte array */ public static byte[] toByteArray(double d, ByteOrder bo) { return ByteBuffer.allocate(8).order(bo).putDouble(d).array(); } /** * Converts a boolean into a byte array. * * @param b * a boolean * @return byte array */ public static byte[] toByteArray(boolean b) { return ByteBuffer.allocate(1).put(b ? (byte) 0x01 : (byte) 0x00).array(); } /** * Converts a char into a byte array by big-endian byte order. * * @param c * a char * @return byte array */ public static byte[] toByteArray(char c) { return ByteBuffer.allocate(2).order(BIG_ENDIAN).putChar(c).array(); } /** * Converts a char into a byte array. * * @param c * a char * @param bo * a ByteOrder * @return byte array */ public static byte[] toByteArray(char c, ByteOrder bo) { return ByteBuffer.allocate(2).order(bo).putChar(c).array(); } /** * Converts a String into a byte array. * * @param s * a String * @return byte array */ public static byte[] toByteArray(String s) { return s.getBytes(); } /** * Converts an Object into a byte array by big-endian byte order. ByteOrder * only affects on Java Number. If this Object is not a Java primitive wrapper * Object, a reflection will be performed to search any method which returns a * byte[] and call it directly. Under this circumstance, the ByteOrder won't * take effect too. * * @param o * any Object * @return byte array */ public static byte[] toByteArray(Object o) { return toByteArray(o, BIG_ENDIAN); } /** * Converts an Object into a byte array. ByteOrder only affects on Java * Number. If this Object is not a Java primitive wrapper Object, a reflection * will be performed to search any method which returns a byte[] and call it * directly. Under this circumstance, the ByteOrder won't take effect too. * * @param o * an Object * @param bo * a ByteOrder * @return byte array * @throws TypeConstraintException * if the Object can't be converted into bytes */ public static byte[] toByteArray(Object o, ByteOrder bo) { if (o instanceof Byte) return new byte[] { (Byte) o }; if (o instanceof Short) return ByteBuffer.allocate(2).order(bo).putShort((Short) o).array(); if (o instanceof Integer) return ByteBuffer.allocate(4).order(bo).putInt((Integer) o).array(); if (o instanceof Long) return ByteBuffer.allocate(8).order(bo).putLong((Long) o).array(); if (o instanceof Float) return ByteBuffer.allocate(4).order(bo).putFloat((Float) o).array(); if (o instanceof Double) return ByteBuffer.allocate(8).order(bo).putDouble((Double) o).array(); if (o instanceof Boolean) return (Boolean) o ? new byte[] { '\1' } : new byte[] { '\0' }; if (o instanceof Character) return ByteBuffer.allocate(2).order(bo).putChar((Character) o).array(); try { Class<?> c = o.getClass(); Method mothod = null; for (Method m : c.getMethods()) { if (m.getReturnType() == byte[].class && m.getParameterTypes().length == 0) mothod = m; } return (byte[]) mothod.invoke(o); } catch (Exception e) { logger.log(Level.SEVERE, null, e); throw new ClassCastException("TypeError: no implicit conversion of " + (o == null ? null : o.getClass().getName()) + " into byte[]"); } } /** * Encodes a byte to ASCII-8Bit String character. * * @param b * any byte * @return ISO-8859-1 String character */ public static String toASCII8Bit(byte b) { return new String(new byte[] { b }, Charset.forName("ISO-8859-1")); } /** * Converts a byte array into an ASCII String. * * @param bytes * used to be converted * @param n * length of ASCII String * @param bo * a ByteOrder * @return ASCII String */ public static String toExtendedASCIIs(byte[] bytes, int n, ByteOrder bo) { RubyArray<String> ra = Ruby.Array.create(); if (bo == LITTLE_ENDIAN) { for (int i = 0; i < n; i++) { if (i >= bytes.length) { ra.push("\0"); continue; } byte b = bytes[i]; ra.push(toASCII8Bit(b)); } return ra.join(); } else { for (int i = bytes.length - 1; n > 0; i--) { if (i < 0) { ra.unshift("\0"); n--; continue; } byte b = bytes[i]; ra.unshift(toASCII8Bit(b)); n--; } return ra.join(); } } /** * Converts a byte array into an UTF String. * * @param bytes * used to be converted * @return UTF String * @throws IllegalArgumentException * if codePoint is less than 0 or greater than 0X10FFFF */ public static String toUTF(byte[] bytes) { int codePoint = ByteBuffer.wrap(bytes).getInt(); if (codePoint < 0 || codePoint > 0X10FFFF) throw new IllegalArgumentException( "RangeError: pack(U): value out of range"); return String.valueOf((char) codePoint); } /** * Converts byte array to a binary String by MSB order. * * @param bytes * a byte array * @return binary String */ public static String toBinaryString(byte[] bytes) { return toBinaryString(bytes, true); } /** * Converts a byte array to a binary String. * * @param bytes * a byte array * @param isMSB * true if MSB, false if LSB * @return binary String */ public static String toBinaryString(byte[] bytes, boolean isMSB) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { String binary = String.format("%8s", Integer.toBinaryString(b & 0xFF)) .replace(' ', '0'); if (isMSB) sb.append(binary); else sb.append(new StringBuilder(binary).reverse()); } return sb.toString(); } /** * Converts a byte array to a hex String by HNF order. * * @param bytes * a byte array * @return hex String */ public static String toHexString(byte[] bytes) { return toHexString(bytes, true); } /** * Converts a byte array to a hex String. * * @param bytes * a byte array * @param isHNF * true if HNF(high nibble first), false if LNF(low nibble first) * @return hex String */ public static String toHexString(byte[] bytes, boolean isHNF) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { String hex = String.format("%2s", Integer.toHexString(b & 0xFF)).replace(' ', '0'); if (isHNF) sb.append(hex); else sb.append(new StringBuilder(hex).reverse()); } return sb.toString(); } /** * Converts a binary string into byte array. * * @param binaryStr * a binary string * @return byte array * @throws IllegalArgumentException * if binary string is invalid */ public static byte[] fromBinaryString(String binaryStr) { if (!binaryStr.matches("^[01]*$")) throw new IllegalArgumentException("Invalid binary string"); if (binaryStr.isEmpty()) return new byte[0]; int complementary = binaryStr.length() % 8; if (complementary != 0) binaryStr += Ruby.Array.of("0").multiply(8 - complementary).join(); return rjust(new BigInteger(binaryStr, 2).toByteArray(), binaryStr.length() / 8); } /** * Converts a hexadecimal string into byte array. * * @param hexStr * a hexadecimal string * @return byte array * @throws IllegalArgumentException * if hexadecimal string is invalid */ public static byte[] fromHexString(String hexStr) { if (!hexStr.matches("^[0-9A-Fa-f]*$")) throw new IllegalArgumentException("Invalid hexadecimal string"); if (hexStr.isEmpty()) return new byte[0]; int complementary = hexStr.length() % 2; if (complementary != 0) hexStr += "0"; return rjust(new BigInteger(hexStr, 16).toByteArray(), hexStr.length() / 2); } }
andrewsu/RTX
code/UI/ClientExamples/Python/obsolete/Query_SMEworkflow1.py
<gh_stars>10-100 """ This example demonstrates fetching the results for SME Workflow #1 from RTX using the Translator Reasoning Tool Standardized API. """ #### Import some needed modules import requests import json #### Set the base URL for the reasoner and its endpoint API_BASE_URL = 'https://rtx.ncats.io/api/rtx/v1' url_str = API_BASE_URL + "/query" #### Create a dict of the request, specifying the query type and its parameters request = { "query_type_id": "Q55", "terms": { "disease": "DOID:9352" } } #### Send the request to RTX and check the status response_content = requests.post(url_str, json=request, headers={'accept': 'application/json'}) status_code = response_content.status_code if status_code != 200: print("ERROR returned with status "+str(status_code)) exit() #### Unpack the response content into a dict response_dict = response_content.json() #### Display the summary table of the results if response_dict["table_column_names"]: print("\t".join(response_dict["table_column_names"])) for result in response_dict["result_list"]: print("\t".join(result["row_data"])) #### Or dump the whole detailed JSON response_content data structure print(json.dumps(response_dict, indent=4, sort_keys=True))
NateTheGreatt/phaser
dist/display3d/SetWorld3D.js
import { AddedToWorldEvent, RemovedFromWorldEvent } from "../gameobjects/events"; import { Emit } from "../events/Emit"; export function SetWorld3D(world, ...children) { children.forEach((child) => { if (child.world) { Emit(child.world, RemovedFromWorldEvent, child, child.world); Emit(child, RemovedFromWorldEvent, child, child.world); } child.world = world; Emit(world, AddedToWorldEvent, child, world); Emit(child, AddedToWorldEvent, child, world); }); return children; }
woshidaniu-com/niutal
niutal-core-jwservice/src/main/java/com/woshidaniu/service/utils/PercentageUtils.java
package com.woshidaniu.service.utils; import java.math.BigDecimal; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.http.HttpSession; import com.woshidaniu.web.context.WebContext; /** * *@类名称: PercentageUtils.java *@类描述:完成比计算工具 *@创建人:kangzhidong *@创建时间:Sep 25, 2015 3:10:24 PM *@版本号:v1.0 */ public class PercentageUtils { public static BigDecimal hundred = new BigDecimal(100); /** * *@描述: 根据提供的参数自动计算完成百分比并以指定的key将值放到当前Session中 *@创建人:kangzhidong *@创建时间:Sep 25, 20153:07:18 PM *@param completeCount : 原子计数对象;用于记录已处理总数 *@param maxCount :大数字对象;记录总共需要处理记录数 *@param sessionKey :百分比结果放入session中的key */ public static void setPercentage(AtomicInteger completeCount,BigDecimal maxCount,String sessionKey){ //设置标识到session中 PercentageUtils.setPercentage(WebContext.getSession(), completeCount, maxCount, sessionKey); } public static void setPercentage(HttpSession session,AtomicInteger completeCount,BigDecimal maxCount,String sessionKey){ //成功记录数累加 completeCount.incrementAndGet(); //已完成百分比 float percentum = new BigDecimal(completeCount.get()).divide(maxCount,10, BigDecimal.ROUND_HALF_UP).multiply(hundred).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue(); //设置标识到session中 session.setAttribute(sessionKey, percentum); } public static void main(String[] args) { int i = 100; while ( i > 0) { System.out.println("dddd:" + i); i --; return; } } }
smackedlol/pajbot
pajbot/web/routes/base/pleblist.py
import logging from flask import redirect from flask import render_template from pajbot.managers.db import DBManager from pajbot.models.pleblist import PleblistSong from pajbot.models.stream import Stream from pajbot.models.stream import StreamChunk from pajbot.models.user import User from pajbot.utils import find log = logging.getLogger(__name__) def init(app): @app.route('/pleblist/') def pleblist(): return render_template('pleblist.html') @app.route('/pleblist/host/') def pleblist_host(): return render_template('pleblist_host.html') @app.route('/pleblist/history/') def pleblist_history_redirect(): with DBManager.create_session_scope() as session: current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start.desc()).first() if current_stream is not None: return redirect('/pleblist/history/{}/'.format(current_stream.id), 303) last_stream = session.query(Stream).filter_by(ended=True).order_by(Stream.stream_start.desc()).first() if last_stream is not None: return redirect('/pleblist/history/{}/'.format(last_stream.id), 303) return render_template('pleblist_history_no_stream.html'), 404 @app.route('/pleblist/history/<int:stream_id>/') def pleblist_history_stream(stream_id): with DBManager.create_session_scope() as session: stream = session.query(Stream).filter_by(id=stream_id).one_or_none() if stream is None: return render_template('pleblist_history_404.html'), 404 previous_stream = session.query(Stream).filter_by(id=stream_id - 1).one_or_none() next_stream = session.query(Stream).filter_by(id=stream_id + 1).one_or_none() q = session.query(PleblistSong, User).outerjoin(User, PleblistSong.user_id == User.id).filter(PleblistSong.stream_id == stream.id).order_by(PleblistSong.id.asc(), PleblistSong.id.asc()) songs = [] for song, user in q: song.user = user songs.append(song) total_length_left = sum([song.skip_after or song.song_info.duration if song.date_played is None and song.song_info is not None else 0 for song in songs]) first_unplayed_song = find(lambda song: song.date_played is None, songs) stream_chunks = session.query(StreamChunk).filter(StreamChunk.stream_id == stream.id).all() return render_template('pleblist_history.html', stream=stream, previous_stream=previous_stream, next_stream=next_stream, songs=songs, total_length_left=total_length_left, first_unplayed_song=first_unplayed_song, stream_chunks=stream_chunks)
geransmith/axonius_api_client
axonius_api_client/api/routers.py
# -*- coding: utf-8 -*- """REST API route definitions.""" from ..tools import join_url class Router: """Simple object store for REST API routes.""" def __init__(self, object_type, base, version, **routes): """Object store for REST API routes. Args: object_type (:obj:`str`): object type for this set of routes base (:obj:`str`): base path for this set of routes version (:obj:`int`): api version for this set of routes **routes: routes for this object_type """ self._version = version self._base = base self._object_type = object_type self.root = join_url(base, object_type) self._routes = ["root"] for k, v in routes.items(): self._routes.append(k) setattr(self, k, join_url(self.root, v)) def __str__(self): """Show object info. Returns: :obj:`str` """ msg = "{obj.__class__.__module__}.{obj.__class__.__name__}" msg += "(object_type={obj._object_type!r}, version={obj._version})" return msg.format(obj=self) def __repr__(self): """Show object info. Returns: :obj:`str` """ return self.__str__() class ApiV1: """Routes provided by the Axonius REST API version 1.""" version = 1 base = "api/V{version}".format(version=version) users = Router( object_type="users", base=base, version=version, by_id="{id}", cached="cached", count="count", views="views", view_by_id="views/saved/{id}", labels="labels", fields="fields", destroy="destroy", history_dates="history_dates", ) devices = Router( object_type="devices", base=base, cached="cached", version=version, by_id="{id}", count="count", views="views", view_by_id="views/saved/{id}", labels="labels", fields="fields", destroy="destroy", history_dates="history_dates", ) actions = Router( object_type="actions", base=base, version=version, shell="shell", # nosec deploy="deploy", upload_file="upload_file", ) adapters = Router( object_type="adapters", base=base, version=version, cnxs="{adapter_name_raw}/clients", cnxs_uuid="{adapter_name_raw}/clients/{cnx_uuid}", file_upload="{adapter_name_raw}/{adapter_node_id}/upload_file", # file_download="{name}/{node_id}/download_file", config_set="{adapter_name_raw}/config/{adapter_config_name}", config_get="{adapter_name_plugin}/config/{adapter_config_name}", ) alerts = Router(object_type="alerts", base=base, version=version) system = Router( object_type="system", base=base, version=version, instances="instances", meta_about="meta/about", meta_historical_sizes="meta/historical_sizes", settings_lifecycle="settings/lifecycle", settings_gui="settings/gui", settings_core="settings/core", discover_lifecycle="discover/lifecycle", discover_start="discover/start", discover_stop="discover/stop", roles_default="roles/default", roles="roles", roles_by_uuid="roles/{uuid}", roles_labels="roles/labels", users="users", user="users/{uuid}", central_core="central_core", central_core_restore="central_core/restore", ) all_objects = [ users, devices, actions, adapters, alerts, system, ] API_VERSION = ApiV1
ujjwalsh/gfapy
tests/test_unit_numeric_array.py
import unittest import gfapy class TestUnitNumericArray(unittest.TestCase): def test_integer_type(self): v = {b: 2**(b/2) for b in [8,16,32,64,128]} self.assertEqual("C", gfapy.NumericArray.integer_type((0,v[8]))) self.assertEqual("c", gfapy.NumericArray.integer_type((-1,v[8]))) self.assertEqual("S", gfapy.NumericArray.integer_type((0,v[16]))) self.assertEqual("s", gfapy.NumericArray.integer_type((-1,v[16]))) self.assertEqual("I", gfapy.NumericArray.integer_type((0,v[32]))) self.assertEqual("i", gfapy.NumericArray.integer_type((-1,v[32]))) self.assertRaises(gfapy.ValueError, gfapy.NumericArray.integer_type, (0,v[64])) self.assertRaises(gfapy.ValueError, gfapy.NumericArray.integer_type, (-1,v[64])) self.assertRaises(gfapy.ValueError, gfapy.NumericArray.integer_type, (0,v[128])) self.assertRaises(gfapy.ValueError, gfapy.NumericArray.integer_type, (-1,v[128]))
ggrimes/jvarkit
src/main/java/com/github/lindenb/jvarkit/tools/phased/BamPhased01.java
/* The MIT License (MIT) Copyright (c) 2021 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.github.lindenb.jvarkit.tools.phased; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import com.beust.jcommander.Parameter; import com.github.lindenb.jvarkit.iterator.EqualIterator; import com.github.lindenb.jvarkit.jcommander.OnePassBamLauncher; import com.github.lindenb.jvarkit.lang.StringUtils; import com.github.lindenb.jvarkit.samtools.util.SimplePosition; import com.github.lindenb.jvarkit.util.bio.AcidNucleics; import com.github.lindenb.jvarkit.util.bio.DistanceParser; import com.github.lindenb.jvarkit.util.bio.SequenceDictionaryUtils; import com.github.lindenb.jvarkit.util.jcommander.NoSplitter; import com.github.lindenb.jvarkit.util.jcommander.Program; import com.github.lindenb.jvarkit.util.log.Logger; import com.github.lindenb.jvarkit.variant.vcf.BufferedVCFReader; import com.github.lindenb.jvarkit.variant.vcf.VCFReaderFactory; import htsjdk.samtools.AlignmentBlock; import htsjdk.samtools.SAMException; import htsjdk.samtools.SAMFileHeader; import htsjdk.samtools.SAMFileWriter; import htsjdk.samtools.SAMProgramRecord; import htsjdk.samtools.SAMReadGroupRecord; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SAMSequenceDictionary; import htsjdk.samtools.util.CloseableIterator; import htsjdk.samtools.util.CloserUtil; import htsjdk.samtools.util.RuntimeIOException; import htsjdk.samtools.util.SequenceUtil; import htsjdk.variant.variantcontext.Genotype; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.variantcontext.VariantContextBuilder; import htsjdk.variant.vcf.VCFReader; /** BEGIN_DOC for @isamtalves Only diallelic SNV are supported. ## Example ``` $ java -jar dist/bamphased01.jar \ -V src/test/resources/rotavirus_rf.vcf.gz \ src/test/resources/S4.bam @HD VN:1.6 SO:coordinate @SQ SN:RF01 LN:3302 @SQ SN:RF02 LN:2687 @SQ SN:RF03 LN:2592 @SQ SN:RF04 LN:2362 @SQ SN:RF05 LN:1579 @SQ SN:RF06 LN:1356 @SQ SN:RF07 LN:1074 @SQ SN:RF08 LN:1059 @SQ SN:RF09 LN:1062 @SQ SN:RF10 LN:751 @SQ SN:RF11 LN:666 @RG ID:S4 SM:S4 LB:L4 CN:Nantes @PG ID:0 CL:-V src/test/resources/rotavirus_rf.vcf.gz src/test/resources/S4.bam VN:04c54fe PN:bamphased01 @CO bamphased01. compilation:20210218183501 githash:04c54fe htsjdk:2.23.0 date:20210218183539. cmd:-V src/test/resources/rotavirus_rf.vcf.gz src/test/resources/S4.bam RF10_109_650_2:2:0_2:0:0_13 99 RF10 109 60 70M = 581 542 CGATACTCGAGGATCCAGGGATGGCGTATTATCCTTATCTAGCAACTGTCCTAACAGTTTTGTTCAGGTT 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S4 NM:i:4 XP:Z:RF10_139_T_A;RF10_175_C_G AS:i:51 XS:i:0 RF10_128_592_1:2:0_1:0:0_27 163 RF10 128 60 70M = 523 465 GATGGCGTATTATCCTTAAATAGCATCTGTCCTAACAGTTTTGTTCAGGTTGCACAAAGCATCTATTCCA 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S4 NM:i:3 XP:Z:RF10_139_T_A;RF10_175_C_G AS:i:55 XS:i:0 RF10_133_733_1:2:0_1:0:0_f 99 RF10 133 60 70M = 664 601 CGTATTATCCTTATATAGCAACTGTCCTAACAGTTTTGTTCAGGTTGCACAAAGCATCTATTCCAACAAT 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S4 NM:i:3 XP:Z:RF10_139_T_A;RF10_175_C_G AS:i:55 XS:i:0 RF10_137_727_1:2:0_2:0:0_8 163 RF10 137 60 70M = 658 591 TTATCCTTATATAGCATCTGTCCTAACAGTTTTGTTCAGGTTGCACAAAGCATCTATTGCAACAATGAAA 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S4 NM:i:3 XP:Z:RF10_139_T_A;RF10_175_C_G AS:i:57 XS:i:0 RF10_138_562_1:2:0_1:0:0_1e 163 RF10 138 60 70M = 493 425 TATCCTTATATAGCATCTGTCCTAACAGTTATGTTCAGGTTGCACAAAGCATCTATTCCAACAATGAAAA 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S4 NM:i:3 XP:Z:RF10_139_T_A;RF10_175_C_G AS:i:58 XS:i:0 ``` paired mode: ``` $ samtools sort -n -T xx src/test/resources/S2.bam | \ java -jar dist/bamphased01.jar -V src/test/resources/rotavirus_rf.vcf.gz --min-supporting 2 --paired --ignore-discordant-rg @HD VN:1.6 SO:queryname @SQ SN:RF01 LN:3302 @SQ SN:RF02 LN:2687 @SQ SN:RF03 LN:2592 @SQ SN:RF04 LN:2362 @SQ SN:RF05 LN:1579 @SQ SN:RF06 LN:1356 @SQ SN:RF07 LN:1074 @SQ SN:RF08 LN:1059 @SQ SN:RF09 LN:1062 @SQ SN:RF10 LN:751 @SQ SN:RF11 LN:666 @RG ID:S2 SM:S2 LB:L2 CN:Nantes @PG ID:0 PN:bamphased01 VN:5d263eb CL:-V src/test/resources/rotavirus_rf.vcf.gz --min-supporting 2 --paired --ignore-discordant-rg @CO bamphased01. compilation:20210220193801 githash:5d263eb htsjdk:2.23.0 date:20210220193911. cmd:-V src/test/resources/rotavirus_rf.vcf.gz --min-supporting 2 --paired --ignore-discordant-rg RF03_2142_2592_1:1:0_2:1:0_1c 99 RF03 2142 60 70M = 2523 451 AACTATTTTATTGGAATTAAGTTCAAAAATATACCCTATGAATATGATGATAAAGTACCCCATCTTACAT 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S2 NM:i:2 XP:Z:RF03_2201_G_C;RF03_2573_A_G AS:i:60 XS:i:0 RF03_2142_2592_1:1:0_2:1:0_1c 147 RF03 2523 60 70M = 2142 -451 ATAAAAGGCGACACACTGTTAGATATGACTGAGTGAGCTAAAAACTTAACGCACTGGTCACATCGTGACC 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S2 NM:i:3 XP:Z:RF03_2201_G_C;RF03_2573_A_G AS:i:55 XS:i:0 RF05_813_1307_2:1:0_1:1:0_10 99 RF05 813 60 70M = 1238 495 AAAGCGTGAACGCATATAGTTGATGCTAGAAATTATATTAGTATTATGAACTCATCGTATACTGAGAATT 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S2 NM:i:3 XP:Z:RF05_879_C_A;RF05_1297_T_G AS:i:56 XS:i:0 RF05_813_1307_2:1:0_1:1:0_10 147 RF05 1238 60 70M = 813 -495 CATAAATGGAACGGAGTATGTATTATTAGACTATGAAGTGAACTGGGAAGTGAGGGGACGAGTCAGGCAA 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S2 NM:i:2 XP:Z:RF05_879_C_A;RF05_1297_T_G AS:i:60 XS:i:0 RF05_829_1327_3:1:0_4:1:0_16 99 RF05 829 60 70M = 1258 499 TCGTTGATGCTCGAAATTATATTAGTATTATGAAGTCATCGTATACTGAGAATTACAGTGTGTCACAAAG 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S2 NM:i:4 XP:Z:RF05_879_C_A;RF05_1297_T_G AS:i:53 XS:i:0 RF05_829_1327_3:1:0_4:1:0_16 147 RF05 1258 60 70M = 829 -499 TATTATTAGACTATCAAGTGAACTGGGAAGTGAGGGGACGAGTCATGCATAACAGGGATGCGAAAGTACC 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S2 NM:i:5 XP:Z:RF05_879_C_A;RF05_1297_T_G AS:i:45 XS:i:0 RF05_843_1306_0:1:0_2:1:0_23 83 RF05 1237 60 70M = 843 -464 ACATAAATCGAACCGAGTATGTATTATTAGACTATGAAGTGAACTGGGAAGTGAGGGGACGAGTCATGCA 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S2 NM:i:3 XP:Z:RF05_1297_T_G;RF05_879_C_A AS:i:55 XS:i:0 RF05_843_1306_0:1:0_2:1:0_23 163 RF05 843 60 70M = 1237 464 AATTATATTAGTATTATGAACTCATCGTATACTGAGAATTACAGTGTGTCACAAAGATGTAAATTGTTTA 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S2 NM:i:1 XP:Z:RF05_1297_T_G;RF05_879_C_A AS:i:65 XS:i:0 RF05_857_1394_2:1:0_1:1:0_2f 99 RF05 857 60 70M = 1325 538 TATGAACTCATCGTATACTGAGAATTACAGTGTGTCACAAAGATGTACATTGATTACTAAGTATAAATTT 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S2 NM:i:3 XP:Z:RF05_879_C_A;RF05_1339_A_C AS:i:55 XS:i:0 RF05_857_1394_2:1:0_1:1:0_2f 147 RF05 1325 60 70M = 857 -538 TCCAAGAATTTTGACTATGAATGATACAAAGAAGATACTGAGTGCAATGATATTTGACTGGTTTGACACA 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S2 NM:i:2 XP:Z:RF05_879_C_A;RF05_1339_A_C AS:i:64 XS:i:0 RF05_863_1322_3:1:0_0:1:0_0 83 RF05 1253 60 70M = 863 -460 GTATGTATTATTAGACTATGAAGTGAACTGGGAAGTGAGGGGACGAGTCATGCAAAACATGGATGGGAAA 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S2 NM:i:1 XP:Z:RF05_1297_T_G;RF05_879_C_A AS:i:65 XS:i:0 RF05_863_1322_3:1:0_0:1:0_0 163 RF05 863 60 70M = 1253 460 CTCATCGTATACTGAGAATTACAGTTTGTCACAAAGATGTAAAATGTTTACTAAGTATAAATATGGGATT 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S2 NM:i:4 XP:Z:RF05_1297_T_G;RF05_879_C_A AS:i:50 XS:i:0 RF05_874_1375_3:1:0_1:1:0_4d 99 RF05 874 60 70M = 1306 502 CTGAGAATTACAGTGTGTCACAAAGATTTAAATTGTTTACTAAGTATACATTTGGGATTGTATCAAGATA 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S2 NM:i:4 XP:Z:RF05_879_C_A;RF05_1339_A_C AS:i:54 XS:i:0 RF05_874_1375_3:1:0_1:1:0_4d 147 RF05 1306 60 70M = 874 -502 AAAACATGGATGGGAAAGTACCAAGAATTTTGACTATGAATGATACAAAGAAGATACTCAGTGCAATGAT 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S2 NM:i:2 XP:Z:RF05_879_C_A;RF05_1339_A_C AS:i:60 XS:i:0 RF05_916_1354_3:0:0_1:2:0_53 147 RF05 1285 60 70M = 916 -439 AAGTGAGGGGAAGAGTCATGCAAAACATGGATGGGAAAGTACCAAGAATTTTGACTATGAATGATACAAA 2222222222222222222222222222222222222222222222222222222222222222222222 PG:Z:0 RG:Z:S2 NM:i:3 XP:Z:RF05_1297_T_G;RF05_1339_A_C AS:i:55 XS:i:0 ``` END_DOC */ @Program(name="bamphased01", description="Extract Reads from a SAM/BAM file supporting at least two variants in a VCF file.", keywords={"vcf","phased","genotypes","bam"}, creationDate="20210218", modificationDate="20210218" ) public class BamPhased01 extends OnePassBamLauncher { private static final Logger LOG=Logger.build(BamPhased01.class).make(); private static class PosToCheck extends SimplePosition { final String ref; final Set<Byte> alts; PosToCheck(final VariantContext vc, final Set<Byte> alts) { super(vc.getContig(),vc.getStart()); this.ref = vc.getReference().getDisplayString(); this.alts=alts; } @Override public String toString() { return super.toString()+" "+ alts; } } @Parameter(names={"-V","--vcf"},description="Indexed VCf file",required=true) protected Path vcfFile=null; @Parameter(names={"--buffer-size"},description=BufferedVCFReader.OPT_BUFFER_DESC,splitter=NoSplitter.class,converter=DistanceParser.StringConverter.class) private int buffSizeInBp = 1_000; @Parameter(names={"--tag"},description="Tag in metadata of read containing the variants positions. Ignored if empty") private String XTAG = "XP"; @Parameter(names={"--mapq0"},description="If set. Do not remove the reads failing the test but set the MAPQ to 0.") private boolean failing_mapq0 = false; @Parameter(names={"--min-supporting"},description="Min number of variants that should be supported by one read.") private int num_supporting_variants = 2; @Parameter(names={"--paired"},description="Activate Paired-end mode. Variant can be supported by the read or/and is mate. Input must be sorted on query name using for example 'samtools collate'.") private boolean paired_mode = false; @Parameter(names={"--ignore-discordant-rg"},description="In paired mode, ignore discordant read-groups RG-ID.") private boolean ignore_discordant_rg = false; private VCFReader vcfReader = null; private BufferedVCFReader bufferedVCFReader = null; private Set<String> samplesInBam = new HashSet<>(); private SAMProgramRecord samProgramRecord = null; private VariantContext simplify(final VariantContext vc) { if(!vc.isSNP()) return null; if(!vc.isBiallelic()) return null; if(!samplesInBam.stream(). map(S->vc.getGenotype(S)). anyMatch(G->G!=null && !G.isHomRef() && !G.isNoCall())) return null; return new VariantContextBuilder(vc).noID().passFilters(). log10PError(VariantContext.NO_LOG10_PERROR). attributes(Collections.emptyMap()). make(); } @Override protected int beforeSam() { if(!(this.XTAG.length()==0 || this.XTAG.length()==2)) { LOG.error("tag should be empty of length==2 but got "+this.XTAG); return -1; } if(this.XTAG.length()==2 && !this.XTAG.startsWith("X")) { LOG.error("tag should start with 'X' but got "+this.XTAG); return -1; } if(this.num_supporting_variants<2) { LOG.error("Bad number of supporting variant (should be >=2) "+ this.num_supporting_variants); return -1; } this.vcfReader = VCFReaderFactory.makeDefault().open(this.vcfFile, true); this.bufferedVCFReader = new BufferedVCFReader(this.vcfReader, this.buffSizeInBp); this.bufferedVCFReader.setSimplifier(V->simplify(V)); return 0; } @Override protected void afterSam() { CloserUtil.close(this.bufferedVCFReader); CloserUtil.close(this.vcfReader); } @Override protected SAMFileHeader createOutputHeader(final SAMFileHeader headerIn) { final SAMSequenceDictionary vcfDict = this.vcfReader.getHeader().getSequenceDictionary(); if(vcfDict!=null) { SequenceUtil.assertSequenceDictionariesEqual(vcfDict, SequenceDictionaryUtils.extractRequired(headerIn)); } if(this.paired_mode) { final SAMFileHeader.SortOrder order= headerIn.getSortOrder(); switch(order) { case queryname: break; case unsorted: break; default:throw new SAMException("in paired mode input must be sorted on query name. But got " + order); } } final SAMFileHeader outHeader= super.createOutputHeader(headerIn); this.samProgramRecord = outHeader.createProgramRecord(); this.samProgramRecord.setProgramName(this.getProgramName()); this.samProgramRecord.setProgramVersion(this.getVersion()); this.samProgramRecord.setCommandLine(this.getProgramCommandLine()); if(this.paired_mode) outHeader.setSortOrder(SAMFileHeader.SortOrder.unknown); this.samplesInBam = headerIn.getReadGroups(). stream(). map(RG->RG.getSample()). filter(S->!StringUtils.isBlank(S)). collect(Collectors.toSet()); this.samplesInBam.retainAll(this.vcfReader.getHeader().getSampleNamesInOrder()); if(this.samplesInBam.isEmpty()) { throw new RuntimeIOException("No overlapping samples between the SAM read groups (@RG SM:xxxx) and the vcf file "+this.vcfFile); } return outHeader; } private void failingSAMRecord(final SAMRecord rec,final SAMFileWriter sfw) { if(!failing_mapq0) return; rec.setMappingQuality(0); rec.setAttribute("PG", this.samProgramRecord.getId()); sfw.addAlignment(rec); } @Override protected void scanIterator(final SAMFileHeader headerIn,final CloseableIterator<SAMRecord> iter0,final SAMFileWriter sfw) { if(this.paired_mode) { try(EqualIterator<SAMRecord> iter = new EqualIterator<>(iter0,(A,B)->A.getReadName().compareTo(B.getReadName()))) { while(iter.hasNext()) { final LinkedList<SAMRecord> buffer = new LinkedList<>(iter.next()); SAMRecord R1= null; SAMRecord R2= null; while(!buffer.isEmpty()) { final SAMRecord rec = buffer.pop(); if(rec.getReadUnmappedFlag()){ failingSAMRecord(rec,sfw); } else if(!rec.getReadPairedFlag() || rec.isSecondaryOrSupplementary()) { scanVariants(Collections.singletonList(rec),sfw); } else if(R1==null && rec.getFirstOfPairFlag()) { R1 = rec; } else if(R2==null && rec.getSecondOfPairFlag()) { R2 = rec; } else { failingSAMRecord(rec,sfw); } } if(R1!=null && R2!=null) { if(R1.contigsMatch(R2)) { scanVariants(Arrays.asList(R1,R2),sfw); } else { scanVariants(Collections.singletonList(R1),sfw); scanVariants(Collections.singletonList(R2),sfw); } } else if(R1!=null && R2==null) { scanVariants(Collections.singletonList(R1),sfw); } else if(R2!=null && R1==null) { scanVariants(Collections.singletonList(R2),sfw); } } } } else { while(iter0.hasNext()) { final SAMRecord rec = iter0.next(); if(rec.getReadUnmappedFlag()){ failingSAMRecord(rec,sfw); continue; } scanVariants(Collections.singletonList(rec),sfw); } } } private void scanVariants(final List<SAMRecord> buffer0,final SAMFileWriter sfw) { if(buffer0.isEmpty()) return; final List<SAMRecord> buffer = new ArrayList<>(buffer0); final SAMReadGroupRecord rg0 = buffer.get(0).getReadGroup(); if(rg0==null) { for(SAMRecord rec:buffer) failingSAMRecord(rec, sfw); return; } final String rgid0 = buffer.get(0).getReadGroup().getId(); for(int i=1;!this.ignore_discordant_rg && i< buffer.size();i++) { if(buffer.get(i).getReadGroup()==null || !buffer.get(i).getReadGroup().getId().equals(rgid0)) { /* throw new SAMException("Two paired read without the same RG-ID:\n"+ buffer.get(0).getSAMString()+"\n"+ buffer.get(i).getSAMString() ); */ } } final List<PosToCheck> supporting = new ArrayList<>(); int i=0; while(i<buffer.size()) { final SAMRecord rec = buffer.get(i); final byte[] bases = rec.getReadBases(); if(bases==null || bases==SAMRecord.NULL_QUALS || bases.length==0) { failingSAMRecord(rec,sfw); buffer.remove(i); continue; } final String sn = rg0.getSample(); if(StringUtils.isBlank(sn) || !this.samplesInBam.contains(sn)) { failingSAMRecord(rec,sfw); buffer.remove(i); continue; } final List<PosToCheck> candidates = new ArrayList<>(); try(CloseableIterator<VariantContext> iter=this.bufferedVCFReader.query(rec)) { while(iter.hasNext()) { final VariantContext ctx = iter.next(); final Genotype gt = ctx.getGenotype(sn); if(gt.isHomRef() || gt.isNoCall()) continue; final Set<Byte> alts = gt.getAlleles().stream(). filter(A->A.isCalled() && !A.isReference() && !A.isSymbolic() && A.length()==1 ). filter(A->AcidNucleics.isATGC(A)). map(A->(byte)Character.toUpperCase(A.getDisplayString().charAt(0))). collect(Collectors.toSet()); if(alts.isEmpty()) continue; final PosToCheck pos = new PosToCheck(ctx,alts); candidates.add(pos); } } if(candidates.isEmpty()) { failingSAMRecord(rec,sfw); buffer.remove(i); continue; } final List<PosToCheck> supporting0 = new ArrayList<>(); for(AlignmentBlock ab:rec.getAlignmentBlocks()) { final int readPos1 = ab.getReadStart(); final int refPos1 = ab.getReferenceStart(); for(int x=0;x< ab.getLength();++x) { for(PosToCheck pos:candidates) { if(pos.getPosition() != refPos1+x) continue; final byte readBase = bases [ (readPos1-1) + x ]; if(pos.alts.contains(readBase)) { supporting0.add(pos); break; } } } } if(supporting0.isEmpty()) { failingSAMRecord(rec,sfw); buffer.remove(i); continue; } supporting.addAll(supporting0); i++; } if(supporting.size() < this.num_supporting_variants) { for(SAMRecord rec:buffer) failingSAMRecord(rec, sfw); return; } for(final SAMRecord rec:buffer) { if(!StringUtils.isBlank(this.XTAG)) { rec.setAttribute(this.XTAG, supporting.stream(). map(S->S.getContig()+"_"+S.getStart()+"_"+S.ref+"_"+S.alts.stream().map(B->""+(char)B.byteValue()).collect(Collectors.joining("_"))). collect(Collectors.joining(";")) ); } rec.setAttribute("PG", this.samProgramRecord.getId()); sfw.addAlignment(rec); } } public static void main(final String[] args) { new BamPhased01().instanceMainWithExit(args); } }
cwolsen7905/UbixOS
doc/html/d0/d27/include_2sys_2types_8h.js
<gh_stars>0 var include_2sys_2types_8h = [ [ "__CHAR_BIT", "d0/d27/include_2sys_2types_8h.html#a41549fb35387caed3be025fe977729fe", null ], [ "__ULONG_MAX", "d0/d27/include_2sys_2types_8h.html#a4386baedee1f032ec8217e4358cdecc6", null ], [ "__USHRT_MAX", "d0/d27/include_2sys_2types_8h.html#aeb970b17d73d2ab1c859ee6f5f6f4ef2", null ], [ "_INO_T_DECLARED", "d0/d27/include_2sys_2types_8h.html#a0ef3c142b8588bc220262259df27701e", null ], [ "_INT16_T_DECLARED", "d0/d27/include_2sys_2types_8h.html#a1b0fabea4733d19a8e5d5dadb557b725", null ], [ "_INT32_T_DECLARED", "d0/d27/include_2sys_2types_8h.html#a26096a159bd6727ea6183d1104117552", null ], [ "_INT64_T_DECLARED", "d0/d27/include_2sys_2types_8h.html#ae7e573ebfbd0704ba53e9989484c285e", null ], [ "_INT8_T_DECLARED", "d0/d27/include_2sys_2types_8h.html#a6e84856a3810645941487ddf7cd5daea", null ], [ "_MODE_T_DECLARED", "d0/d27/include_2sys_2types_8h.html#aaeebde70b7f0ab3b4f67834abdac25c8", null ], [ "_QUAD_HIGHWORD", "d0/d27/include_2sys_2types_8h.html#a7eaac45d4115e3143a8775abb93c2eed", null ], [ "_QUAD_LOWWORD", "d0/d27/include_2sys_2types_8h.html#aba97a56cb953e7c610c1877249774951", null ], [ "_TIME_T_DECLARED", "d0/d27/include_2sys_2types_8h.html#a88bd6b29c62a6e7fcc02d8400a3cc48e", null ], [ "B", "d0/d27/include_2sys_2types_8h.html#a111da81ae5883147168bbb8366377b10", null ], [ "CHAR_BIT", "d0/d27/include_2sys_2types_8h.html#a308d9dd2c0028ddb184b455bbd7865de", null ], [ "COMBINE", "d0/d27/include_2sys_2types_8h.html#a152dd91c3a7a672cde53646a9cb62594", null ], [ "H", "d0/d27/include_2sys_2types_8h.html#abec92cc72a096640b821b8cd56a02495", null ], [ "HALF_BITS", "d0/d27/include_2sys_2types_8h.html#a652f8dfd5ad718480293127346c8110f", null ], [ "HHALF", "d0/d27/include_2sys_2types_8h.html#a92c7de42051862b2d44e2f0ccd9ca475", null ], [ "L", "d0/d27/include_2sys_2types_8h.html#aa73214aa5f2f94f63d90bb4e3d99fe53", null ], [ "LHALF", "d0/d27/include_2sys_2types_8h.html#adf04943239a977f38017d6bbf53a4b36", null ], [ "LHUP", "d0/d27/include_2sys_2types_8h.html#a01a040cea26408490b42eb0f2e7b037c", null ], [ "LONG_BITS", "d0/d27/include_2sys_2types_8h.html#a9dd5c03cbd198a43ec05fddbbee622ea", null ], [ "NULL", "d0/d27/include_2sys_2types_8h.html#a070d2ce7b6bb7e5c05602aa8c308d0c4", null ], [ "QUAD_BITS", "d0/d27/include_2sys_2types_8h.html#a187c867e08bb456f8d07eb512e4a93e0", null ], [ "ULONG_MAX", "d0/d27/include_2sys_2types_8h.html#a41c51926a1997aab3503f9083935e06c", null ], [ "USHRT_MAX", "d0/d27/include_2sys_2types_8h.html#a689b119da994dece91d44b5aeac643ed", null ], [ "blkcnt_t", "d0/d27/include_2sys_2types_8h.html#a7da4753cd6945c5ad91f41c00b474b3f", null ], [ "blksize_t", "d0/d27/include_2sys_2types_8h.html#acac8eacbbc225743e88f8e5e8bf93581", null ], [ "caddr_t", "d0/d27/include_2sys_2types_8h.html#a06b0051d3f39d5cd5ad781e5871e49ee", null ], [ "daddr_t", "d0/d27/include_2sys_2types_8h.html#ab4b318e7a68f3cd77c42492443c59895", null ], [ "digit", "d0/d27/include_2sys_2types_8h.html#adac711321b4eea0f286581348e66108c", null ], [ "fflags_t", "d0/d27/include_2sys_2types_8h.html#aee689fd681d6f52c910a90af380155af", null ], [ "gid_t", "d0/d27/include_2sys_2types_8h.html#a9520fe38856d436aa8c5850ff21839ec", null ], [ "ino_t", "d0/d27/include_2sys_2types_8h.html#a73341b7381d39d6e5b80ff9f23379dbd", null ], [ "Int16", "d0/d27/include_2sys_2types_8h.html#a292a71e839a94f0bafde3510df52d972", null ], [ "int16_t", "d0/d27/include_2sys_2types_8h.html#a3542c6a0490e65fc4fc407273126e64f", null ], [ "Int32", "d0/d27/include_2sys_2types_8h.html#a1657cdc78acd17f92fb047e02f7a5f14", null ], [ "int32_t", "d0/d27/include_2sys_2types_8h.html#a6f6221103820f185abcc62b874665a93", null ], [ "int64_t", "d0/d27/include_2sys_2types_8h.html#a96411d49619f50e635418ee57651b95d", null ], [ "Int8", "d0/d27/include_2sys_2types_8h.html#a3832cc814f0e7129add9a1cf7201c7ca", null ], [ "int8_t", "d0/d27/include_2sys_2types_8h.html#a06ffba8acf5d133104191f183e67ac8c", null ], [ "intmax_t", "d0/d27/include_2sys_2types_8h.html#a1a3f3321a0166a004bde0a1e72553f2b", null ], [ "mode_t", "d0/d27/include_2sys_2types_8h.html#ae9f148ba55d84268ecb6f8031ab45076", null ], [ "off_t", "d0/d27/include_2sys_2types_8h.html#afa178be408981cc5edd64227b6332fc6", null ], [ "pid_t", "d0/d27/include_2sys_2types_8h.html#a288e13e815d43b06e75819f8939524df", null ], [ "pidType", "d0/d27/include_2sys_2types_8h.html#ae438ba74394b14d7b24b6df3b3b8c252", null ], [ "ptrdiff_t", "d0/d27/include_2sys_2types_8h.html#a34b856b1e3c67b5e5c1da0ef877b8157", null ], [ "qshift_t", "d0/d27/include_2sys_2types_8h.html#ae5dd834a3b3be98f894d9cb5918840ef", null ], [ "quad_t", "d0/d27/include_2sys_2types_8h.html#aed1098ccbc33ac9e2fe61c0feed081bc", null ], [ "size_t", "d0/d27/include_2sys_2types_8h.html#a7619b847aeded8a6d14cbfa212b2cdfb", null ], [ "ssize_t", "d0/d27/include_2sys_2types_8h.html#a87bd983bf349d8b86901f3200d559e8e", null ], [ "time_t", "d0/d27/include_2sys_2types_8h.html#ac8234dac99fc3a2dcc8b7998afd40d49", null ], [ "u_char", "d0/d27/include_2sys_2types_8h.html#ae2b02ed168fc99cff3851603910b1fb6", null ], [ "u_daddr_t", "d0/d27/include_2sys_2types_8h.html#ad9a0a7c4def8194069484a3c2635602b", null ], [ "u_int", "d0/d27/include_2sys_2types_8h.html#ac319c165d52643e43249fe003e18bdf3", null ], [ "u_int16_t", "d0/d27/include_2sys_2types_8h.html#af7b042408b9b104606f8a9b5035329f3", null ], [ "u_int32_t", "d0/d27/include_2sys_2types_8h.html#aba29fd78d95cce0ecb249c24b58d07da", null ], [ "u_int64_t", "d0/d27/include_2sys_2types_8h.html#a250ac047bf3984b5dae755276a305d64", null ], [ "u_int8_t", "d0/d27/include_2sys_2types_8h.html#ac7c42f52639b9aca7da966a0783996d7", null ], [ "u_long", "d0/d27/include_2sys_2types_8h.html#a8f25a50daf29ce2cee1ec038a4d744ea", null ], [ "u_quad_t", "d0/d27/include_2sys_2types_8h.html#a289ae7cf9c95157e99202b0057d4935c", null ], [ "u_short", "d0/d27/include_2sys_2types_8h.html#aa1a19deefc008737e6397f44d983cfd4", null ], [ "uid_t", "d0/d27/include_2sys_2types_8h.html#a1844226d778badcda0a21b28310830ea", null ], [ "uInt", "d0/d27/include_2sys_2types_8h.html#a87d141052bcd5ec8a80812a565c70369", null ], [ "uInt16", "d0/d27/include_2sys_2types_8h.html#a3b65128d2644e9b80cec9a69bfa7e094", null ], [ "uint16_t", "d0/d27/include_2sys_2types_8h.html#a281b4b5562236420969a830503b0ba19", null ], [ "uInt32", "d0/d27/include_2sys_2types_8h.html#a5847ea0262a5aa61eee48cbe95544a78", null ], [ "uint32_t", "d0/d27/include_2sys_2types_8h.html#a0238af00180b6d9278fa1c6aa790fdf4", null ], [ "uint64_t", "d0/d27/include_2sys_2types_8h.html#a747748dd98cf1e2e89eb8b1fa37113df", null ], [ "uInt8", "d0/d27/include_2sys_2types_8h.html#aa4e0f27a9aca905e340c06d2dcae843c", null ], [ "uint8_t", "d0/d27/include_2sys_2types_8h.html#a2aff71146ab4942b2b38860c749c4074", null ], [ "uintfptr_t", "d0/d27/include_2sys_2types_8h.html#a7b42952a32ead6e8f1aa76969c551443", null ], [ "uintmax_t", "d0/d27/include_2sys_2types_8h.html#a7643e68e022fde0d947e8dc252f716d6", null ], [ "uintptr_t", "d0/d27/include_2sys_2types_8h.html#a09674b9e56fd7a93a2169aa9210deec7", null ], [ "uquad_t", "d0/d27/include_2sys_2types_8h.html#a666be7af7721c1bf7884d7b385e6de8d", null ], [ "vm_offset_t", "d0/d27/include_2sys_2types_8h.html#ad6f327965d9e330cd225ca2153ac0453", null ], [ "bool", "d0/d27/include_2sys_2types_8h.html#af6a258d8f3ee5206d682d799316314b1", [ [ "FALSE", "d0/d27/include_2sys_2types_8h.html#af6a258d8f3ee5206d682d799316314b1aa1e095cc966dbecf6a0d8aad75348d1a", null ], [ "TRUE", "d0/d27/include_2sys_2types_8h.html#af6a258d8f3ee5206d682d799316314b1aa82764c3079aea4e60c80e45befbb839", null ] ] ] ];
sjamboro/kogito-runtimes
jbpm/jbpm-flow/src/main/java/org/jbpm/ruleflow/core/factory/RuleSetNodeFactory.java
<filename>jbpm/jbpm-flow/src/main/java/org/jbpm/ruleflow/core/factory/RuleSetNodeFactory.java /* * Copyright 2010 Red Hat, Inc. and/or 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.jbpm.ruleflow.core.factory; import java.util.function.Supplier; import org.jbpm.process.core.context.variable.Mappable; import org.jbpm.ruleflow.core.RuleFlowNodeContainerFactory; import org.jbpm.workflow.core.NodeContainer; import org.jbpm.workflow.core.node.RuleSetNode; import org.jbpm.workflow.core.node.RuleUnitFactory; import org.kie.api.runtime.KieRuntime; import org.kie.kogito.decision.DecisionModel; public class RuleSetNodeFactory<T extends RuleFlowNodeContainerFactory<T, ?>> extends StateBasedNodeFactory<RuleSetNodeFactory<T>, T> implements MappableNodeFactory<RuleSetNodeFactory<T>> { public static final String METHOD_DECISION = "decision"; public static final String METHOD_PARAMETER = "parameter"; public RuleSetNodeFactory(T nodeContainerFactory, NodeContainer nodeContainer, long id) { super(nodeContainerFactory, nodeContainer, new RuleSetNode(), id); } protected RuleSetNode getRuleSetNode() { return (RuleSetNode) getNode(); } @Override public Mappable getMappableNode() { return getRuleSetNode(); } public RuleSetNodeFactory<T> ruleUnit(String unit, RuleUnitFactory<?> ruleUnit) { getRuleSetNode().setRuleType(RuleSetNode.RuleType.ruleUnit(unit)); getRuleSetNode().setLanguage(RuleSetNode.RULE_UNIT_LANG); getRuleSetNode().setRuleUnitFactory(ruleUnit); return this; } public RuleSetNodeFactory<T> ruleFlowGroup(String ruleFlowGroup, Supplier<KieRuntime> supplier) { getRuleSetNode().setRuleType(RuleSetNode.RuleType.ruleFlowGroup(ruleFlowGroup)); getRuleSetNode().setLanguage(RuleSetNode.DRL_LANG); getRuleSetNode().setKieRuntime(supplier); return this; } public RuleSetNodeFactory<T> decision(String namespace, String model, String decision, Supplier<DecisionModel> supplier) { getRuleSetNode().setRuleType(RuleSetNode.RuleType.decision(namespace, model, decision)); getRuleSetNode().setLanguage(RuleSetNode.DMN_LANG); getRuleSetNode().setDecisionModel(supplier); return this; } public RuleSetNodeFactory<T> parameter(String name, Object value) { getRuleSetNode().setParameter(name, value); return this; } }
mischumok/kogmo-rtdb
rtdb/kogmo_rtdb_utils.c
<reponame>mischumok/kogmo-rtdb<filename>rtdb/kogmo_rtdb_utils.c /*! \file kogmo_rtdb_utils.c * \brief Some Utility Definitions * * Copyright (c) 2003-2006 <NAME> <matthias.goebl*goebl.net> * Lehrstuhl fuer Realzeit-Computersysteme (RCS) * Technische Universitaet Muenchen (TUM) */ #include <stdlib.h> /* malloc */ #include <stdio.h> /* snprintf */ #include <stdarg.h> /* snprintf */ int strprintf (char **strbuf, char **strptr, int *strlen, const char *fmt, ...) { va_list va; const int chunk = 1024; int strspace = 0; int ret = 0; while (1) { // allocate more memory, if this is the first round and there was no // malloc before, or if this is an ineration and there was too little // memory before if ( ret != 0 || *strbuf == NULL ) { *strlen += chunk; *strbuf = (char*)realloc (*strbuf, *strlen); ///printf("alloc %d bytes at %lu\n",*strlen,*strbuf); if (*strbuf == NULL) return -1; if (*strptr == NULL) *strptr = *strbuf; } // Try to print the requested data strspace = *strlen - (*strptr - *strbuf); va_start (va, fmt); ret = vsnprintf (*strptr, strspace, fmt, va); va_end (va); if ( ret >= 0 && ret < strspace ) { *strptr += ret; return ret; } if ( ret >= strspace ) *strlen += ret; } }
lzbrady/oneaweek
oneaweek/src/Admin/Auth.js
<gh_stars>0 import { auth } from "../server/fire"; // Sign In export const doSignInWithEmailAndPassword = (email, password) => auth.signInWithEmailAndPassword(email, password); // Sign out export const doSignOut = () => auth.signOut();
lindsaygelle/nook
animal/fox.go
<filename>animal/fox.go package animal import ( "github.com/lindsaygelle/nook" "golang.org/x/text/language" ) var ( foxNameAmericanEnglish = nook.Name{ Language: language.AmericanEnglish, Value: "Fox"} ) var ( foxName = nook.Languages{ language.AmericanEnglish: foxNameAmericanEnglish} ) var ( Fox = nook.Animal{ Key: nook.Key("Fox"), Name: foxName} )
matthewcpp/RetroDash
src/background.c
#include "background.h" #define BACKGROUND_GRID_SIZE 32 #define BACKGROUND_SPEED 40.0f void background_init(Background* background, Renderer* renderer) { background->_renderer = renderer; background_reset(background); } void background_update(Background* background, float time_delta) { background->_offset -= time_delta * BACKGROUND_SPEED; if (background->_offset < 0.0f) background->_offset += BACKGROUND_GRID_SIZE; } void background_draw(Background* background) { renderer_set_color(background->_renderer, 33, 7, 58, 255); renderer_draw_grid(background->_renderer, (int)background->_offset, BACKGROUND_GRID_SIZE); } void background_reset(Background* background) { background->_offset = (float)BACKGROUND_GRID_SIZE; }
rrehbein/Ariente
src/main/java/mcjty/ariente/facade/MimicBlockSupport.java
package mcjty.ariente.facade; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.nbt.CompoundTag; import net.minecraftforge.registries.ForgeRegistries; import javax.annotation.Nullable; public class MimicBlockSupport { @Nullable private BlockState mimicBlock = null; @Nullable public BlockState getMimicBlock() { return mimicBlock; } public void setMimicBlock(@Nullable BlockState mimicBlock) { this.mimicBlock = mimicBlock; } public void readFromNBT(CompoundTag tagCompound) { if (tagCompound.contains("regName")) { String regName = tagCompound.getString("regName"); // @todo 1.14 meta // int meta = tagCompound.getInt("meta"); Block value = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(regName)); if (value == null) { mimicBlock = Blocks.COBBLESTONE.defaultBlockState(); } else { // @todo 1.14 meta mimicBlock = value.defaultBlockState(); } } else { mimicBlock = null; } } public void writeToNBT(CompoundTag tagCompound) { if (mimicBlock != null) { tagCompound.putString("regName", mimicBlock.getBlock().getRegistryName().toString()); // @todo 1.14 meta // tagCompound.putInt("meta", mimicBlock.getBlock().getMetaFromState(mimicBlock)); } } }
DashW/Ingenuity
Third Party/newton-dynamics-master/packages/dCustomJoints/CustomVehicleControllerBodyState.cpp
/* Copyright (c) <2009> <<NAME>> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely */ // NewtonCustomJoint.cpp: implementation of the NewtonCustomJoint class. // ////////////////////////////////////////////////////////////////////// #include <CustomJointLibraryStdAfx.h> #include <CustomVehicleControllerJoint.h> #include <CustomVehicleControllerManager.h> #include <CustomVehicleControllerComponent.h> #include <CustomVehicleControllerBodyState.h> CustomVehicleControllerBodyState::CustomVehicleControllerBodyState() :dComplemtaritySolver::dBodyState() ,m_controller(NULL) { } void CustomVehicleControllerBodyState::Init(CustomVehicleController* const controller) { m_controller = controller; } dFloat CustomVehicleControllerBodyState::GetMass () const { return dComplemtaritySolver::dBodyState::GetMass(); } const dMatrix& CustomVehicleControllerBodyState::GetMatrix () const { return dComplemtaritySolver::dBodyState::GetMatrix(); } const dMatrix& CustomVehicleControllerBodyState::GetLocalMatrix () const { return dComplemtaritySolver::dBodyState::GetLocalMatrix(); } const dVector& CustomVehicleControllerBodyState::GetCenterOfMass () const { return dComplemtaritySolver::dBodyState::GetCenterOfMass(); } void CustomVehicleControllerBodyState::UpdateInertia() { dComplemtaritySolver::dBodyState::UpdateInertia(); } void CustomVehicleControllerBodyState::IntegrateForce (dFloat timestep, const dVector& force, const dVector& torque) { dComplemtaritySolver::dBodyState::IntegrateForce(timestep, force, torque); } void CustomVehicleControllerBodyState::ApplyNetForceAndTorque (dFloat invTimestep, const dVector& veloc, const dVector& omega) { dComplemtaritySolver::dBodyState::ApplyNetForceAndTorque (invTimestep, veloc, omega); } void CustomVehicleControllerBodyStateContact::Init (CustomVehicleController* const controller, const NewtonBody* const body) { CustomVehicleControllerBodyState::Init (controller); m_newtonBody = (NewtonBody*)body; m_localFrame = dGetIdentityMatrix(); NewtonBodyGetCentreOfMass(body, &m_localFrame[3][0]); NewtonBodyGetMatrix(body, &m_matrix[0][0]); NewtonBodyGetMassMatrix(body, &m_mass, &m_localInertia[0], &m_localInertia[1], &m_localInertia[2]); NewtonBodyGetOmega(body, &m_omega[0]); NewtonBodyGetVelocity(body, &m_veloc[0]); m_globalCentreOfMass = m_matrix.TransformVector(m_localFrame.m_posit); /* dVector force (0.0f, 0.0f, 0.0f, 0.0f); dVector torque (0.0f, 0.0f, 0.0f, 0.0f); if (m_invMass > 0.0f) { const NewtonBody* const otherBody = m_controller->GetBody(); NewtonBodyGetForceAcc(m_newtonBody, &force[0]); NewtonBodyGetTorqueAcc (m_newtonBody, &torque[0]); for (NewtonJoint* joint = NewtonBodyGetFirstContactJoint (m_newtonBody); joint; joint = NewtonBodyGetNextContactJoint (m_newtonBody, joint)) { if (NewtonJointIsActive(joint) && (NewtonJointGetBody0(joint) != otherBody) && (NewtonJointGetBody1(joint) != otherBody)) { for (void* contact = NewtonContactJointGetFirstContact (joint); contact; contact = NewtonContactJointGetNextContact (joint, contact)) { dVector point; dVector normal; dVector tangentDir0; dVector tangentDir1; dVector contactForce; NewtonMaterial* const material = NewtonContactGetMaterial (contact); NewtonMaterialGetContactForce (material, m_newtonBody, &contactForce[0]); NewtonMaterialGetContactPositionAndNormal (material, m_newtonBody, &point[0], &normal[0]); force += contactForce; torque += (point - m_globalCentreOfMass) * contactForce; } } } } m_externalForce = force; m_externalTorque = torque; if (m_mass > 1.0e-3f) { m_invMass = 1.0f / m_mass; m_localInvInertia[0] = 1.0f / m_localInertia[0]; m_localInvInertia[1] = 1.0f / m_localInertia[1]; m_localInvInertia[2] = 1.0f / m_localInertia[2]; } else { m_invMass = 0.0f; m_localInvInertia[0] = 0.0f; m_localInvInertia[1] = 0.0f; m_localInvInertia[2] = 0.0f; } */ m_externalForce = dVector (0.0f, 0.0f, 0.0f, 0.0f); m_externalTorque = dVector (0.0f, 0.0f, 0.0f, 0.0f); m_maxExterenalAccel2 = 50.0f * 50.0f; m_maxExterenalAlpha2 = 100.0 * 100.0f; m_invMass = 0.0f; m_localInvInertia[0] = 0.0f; m_localInvInertia[1] = 0.0f; m_localInvInertia[2] = 0.0f; UpdateInertia(); } void CustomVehicleControllerBodyStateContact::UpdateDynamicInputs() { dAssert (0); } void CustomVehicleControllerBodyStateContact::ApplyNetForceAndTorque (dFloat invTimestep, const dVector& veloc, const dVector& omega) { if (m_invMass > 0.0f) { /* dVector force (m_externalForce + m_foceAcc); dVector torque (m_externalTorque + m_torqueAcc); dVector accel (force.Scale(m_invMass)); dVector alpha (m_invInertia.RotateVector(torque)); dFloat accelMag2 = accel % accel; dFloat alphaMag2 = alpha % alpha; for (int i = 0; (i < 8) && ((accelMag2 > m_maxExterenalAccel2) || (alphaMag2 > m_maxExterenalAlpha2)); i ++) { m_foceAcc = m_foceAcc.Scale (0.9f); m_torqueAcc = m_torqueAcc.Scale (0.9f); force = m_externalForce + m_foceAcc; torque = m_externalForce + m_torqueAcc; accel = force.Scale(m_invMass); alpha = m_invInertia.RotateVector(torque); accelMag2 = accel % accel; alphaMag2 = alpha % alpha; } */ dAssert (0); // NewtonBodyAddForce(m_newtonBody, &m_foceAcc[0]); // NewtonBodyAddTorque(m_newtonBody, &m_torqueAcc[0]); } } void CustomVehicleControllerBodyStateChassis::Init (CustomVehicleController* const controller, const dMatrix& localframe) { CustomVehicleControllerBodyState::Init (controller); NewtonBody* const body = m_controller->GetBody(); m_localFrame = localframe; m_localFrame[3] = m_com + m_comOffset; m_localFrame[3][3] = 1.0f; NewtonBodySetCentreOfMass(body, &m_localFrame[3][0]); NewtonBodyGetMatrix(body, &m_matrix[0][0]); NewtonBodyGetMassMatrix(body, &m_mass, &m_localInertia[0], &m_localInertia[1], &m_localInertia[2]); NewtonBodyGetOmega(body, &m_omega[0]); NewtonBodyGetVelocity(body, &m_veloc[0]); m_invMass = 1.0f / m_mass; m_localInvInertia[0] = 1.0f / m_localInertia[0]; m_localInvInertia[1] = 1.0f / m_localInertia[1]; m_localInvInertia[2] = 1.0f / m_localInertia[2]; UpdateInertia(); } dFloat CustomVehicleControllerBodyStateChassis::GetAerodynamicsDowforceCoeficient () const { return m_aerodynamicsDownForceCoefficient; } void CustomVehicleControllerBodyStateChassis::SetAerodynamicsDownforceCoefficient (dFloat maxDownforceInGravities, dFloat topSpeed) { dFloat Ixx; dFloat Iyy; dFloat Izz; dFloat mass; NewtonBody* const body = m_controller->GetBody(); NewtonBodyGetMassMatrix(body, &mass, &Ixx, &Iyy, &Izz); m_aerodynamicsDownForceCoefficient = mass * maxDownforceInGravities / (topSpeed * topSpeed); } void CustomVehicleControllerBodyStateChassis::SetDryRollingFrictionTorque (dFloat dryRollingFrictionTorque) { m_dryRollingFrictionTorque = dAbs (dryRollingFrictionTorque); } dFloat CustomVehicleControllerBodyStateChassis::GetDryRollingFrictionTorque () const { return m_dryRollingFrictionTorque; } void CustomVehicleControllerBodyStateChassis::UpdateDynamicInputs() { NewtonBody* const body = m_controller->GetBody(); NewtonBodyGetMatrix (body, &m_matrix[0][0]); NewtonBodyGetVelocity (body, &m_veloc[0]); NewtonBodyGetOmega (body, &m_omega[0]); NewtonBodyGetForceAcc (body, &m_externalForce[0]); NewtonBodyGetTorqueAcc (body, &m_externalTorque[0]); m_externalForce.m_w = 0.0f; m_externalTorque.m_w = 0.0f; /* dVector force; dVector torque; NewtonBodyGetForceAcc (body, &force[0]); NewtonBodyGetTorqueAcc (body, &torque[0]); const int maxContacts = int (sizeof (m_controller->m_externalContactJoints) / sizeof (m_controller->m_externalContactJoints[0])); for (NewtonJoint* joint = NewtonBodyGetFirstContactJoint (body); joint && (m_controller->m_externalChassisContactCount < maxContacts); joint = NewtonBodyGetNextContactJoint (body, joint)) { NewtonBody* const otherBody = NewtonJointGetBody1(joint); dAssert (NewtonJointGetBody0(joint) == body); dAssert (otherBody != body); dFloat Ixx; dFloat Iyy; dFloat Izz; dFloat mass; NewtonBodyGetMassMatrix (otherBody, &mass, &Ixx, &Iyy, &Izz); if (mass > 0.0f) { int count = 0; NewtonWorldConvexCastReturnInfo contacts[8]; void* contact = NewtonContactJointGetFirstContact (joint); if (contact) { CustomVehicleControllerBodyStateContact* const externalBody = m_controller->GetContactBody(otherBody); CustomVehicleControllerChassisContactJoint* const externalJoint = &m_controller->m_externalContactJoints[m_controller->m_externalChassisContactCount]; externalJoint->Init(m_controller, externalBody, this); for (; contact && count < (sizeof (contacts) / sizeof (contacts[0])); contact = NewtonContactJointGetNextContact (joint, contact)) { dVector point; dVector normal; dVector tangentDir0; dVector tangentDir1; dVector contactForce; NewtonMaterial* const material = NewtonContactGetMaterial (contact); NewtonMaterialGetContactForce (material, otherBody, &contactForce[0]); NewtonMaterialGetContactPositionAndNormal (material, otherBody, &point[0], &normal[0]); contacts[count].m_point[0] = point.m_x; contacts[count].m_point[1] = point.m_y; contacts[count].m_point[2] = point.m_z; contacts[count].m_normal[0] = normal.m_x; contacts[count].m_normal[1] = normal.m_y; contacts[count].m_normal[2] = normal.m_z; count ++; force += contactForce; torque += (point - m_globalCentreOfMass) * contactForce; externalBody->m_externalForce -= contactForce; externalBody->m_externalTorque -= (point - externalBody->m_globalCentreOfMass) * contactForce; } externalJoint->SetContacts (count, contacts); m_controller->m_externalChassisContactCount ++; } } } */ dFloat frontSpeed = dMin (m_veloc % m_matrix[0], 50.0f); m_externalForce -= m_matrix[1].Scale (m_aerodynamicsDownForceCoefficient * frontSpeed * frontSpeed); m_globalCentreOfMass = m_matrix.TransformVector(m_localFrame.m_posit); UpdateInertia(); } void CustomVehicleControllerBodyStateChassis::PutToSleep() { NewtonBody* const body = m_controller->GetBody(); // dVector force; // dVector torque; // NewtonBodyGetForceAcc (body, &force[0]); // NewtonBodyGetTorqueAcc (body, &torque[0]); // NewtonBodySetForce (body, &force[0]); // NewtonBodySetTorque(body, &torque[0]); dVector zero (0.0f, 0.0f, 0.0f, 0.0f); NewtonBodySetForce (body, &zero[0]); NewtonBodySetTorque(body, &zero[0]); NewtonBodySetOmega(body, &zero[0]); NewtonBodySetVelocity(body, &zero[0]); } bool CustomVehicleControllerBodyStateChassis::IsSleeping () const { const dFloat velocError = 1.0e-4f; dFloat mag2 = m_veloc % m_veloc; if (mag2 < velocError) { mag2 = m_omega % m_omega; if (mag2 < velocError) { const dFloat accelError = 1.0e-2f; NewtonBody* const body = m_controller->GetBody(); dVector force; NewtonBodyGetForce (body, &force[0]); dVector accel (force.Scale(m_invMass)); mag2 = accel % accel; if (mag2 < accelError) { dVector torque; NewtonBodyGetTorque(body, &torque[0]); dVector alpha (m_invInertia.RotateVector(torque)); mag2 = alpha % alpha; return (mag2 < accelError) ? true : false; } } } return false; } void CustomVehicleControllerBodyStateChassis::ApplyNetForceAndTorque (dFloat invTimestep, const dVector& veloc, const dVector& omega) { CustomVehicleControllerBodyState::ApplyNetForceAndTorque (invTimestep, veloc, omega); NewtonBody* const body = m_controller->GetBody(); NewtonBodySetForce (body, &m_externalForce[0]); NewtonBodySetTorque (body, &m_externalTorque[0]); } void CustomVehicleControllerBodyStateTire::Init (CustomVehicleController* const controller, const TireCreationInfo& tireInfo) { CustomVehicleControllerBodyState::Init (controller); NewtonBody* const body = m_controller->GetBody(); const dMatrix& vehicleFrame = m_controller->m_chassisState.m_localFrame; // build a normalized size collision shape and scale to math the tire size, make it is also transparent to collision NewtonCollisionSetScale (m_controller->m_tireCastShape, tireInfo.m_width, tireInfo.m_radio, tireInfo.m_radio); NewtonCollisionSetCollisionMode (m_controller->m_tireCastShape, 0); // calculate the location of the tire matrix m_localFrame = vehicleFrame * dYawMatrix(-3.141592f * 0.5f); m_localFrame.m_posit = tireInfo.m_location + m_localFrame.m_up.Scale (tireInfo.m_suspesionlenght); m_localFrame.m_posit.m_w = 1.0f; NewtonCollisionSetMatrix (m_controller->m_tireCastShape, &m_localFrame[0][0]); // now add a copy of this collision shape to the vehicle collision NewtonCollision* const vehShape = NewtonBodyGetCollision(body); NewtonCompoundCollisionBeginAddRemove(vehShape); void* const tireShapeNode = NewtonCompoundCollisionAddSubCollision (vehShape, m_controller->m_tireCastShape); NewtonCompoundCollisionEndAddRemove (vehShape); // restore the cast shape transform to identity dMatrix identMatrix (dGetIdentityMatrix()); NewtonCollisionSetCollisionMode (m_controller->m_tireCastShape, 1); NewtonCollisionSetMatrix (m_controller->m_tireCastShape, &identMatrix[0][0]); // get the collision shape m_shape = NewtonCompoundCollisionGetCollisionFromNode (vehShape, tireShapeNode); // initialize all constants m_userData = tireInfo.m_userData; m_mass = dMax (tireInfo.m_mass, m_controller->m_chassisState.m_mass / 50.0f); m_invMass = 1.0f / m_mass; m_radio = tireInfo.m_radio; m_width = tireInfo.m_width; m_lateralStiffness = tireInfo.m_lateralStiffness; m_longitudialStiffness = tireInfo.m_longitudialStiffness; m_aligningMomentTrail = tireInfo.m_aligningMomentTrail; m_localInertia[0] = m_mass * (0.50f * m_radio * m_radio); m_localInertia[1] = m_mass * (0.25f * m_radio * m_radio + (1.0f / 12.0f) * m_width * m_width); m_localInertia[2] = m_localInertia[1]; m_localInertia[3] = 0.0f; m_localInvInertia[0] = 1.0f / m_localInertia[0]; m_localInvInertia[1] = 1.0f / m_localInertia[1]; m_localInvInertia[2] = 1.0f / m_localInertia[2]; m_localInvInertia[3] = 0.0f; m_restSprunMass = 0.0f; m_dampingRatio = tireInfo.m_dampingRatio; m_springStrength = tireInfo.m_springStrength; m_suspensionlenght = tireInfo.m_suspesionlenght; // initialize all local variables to default values m_brakeTorque = 0.0f; m_engineTorque = 0.0f; m_rotationalSpeed = 0.0f; m_rotationAngle = 0.0f; m_steeringAngle = 0.0f; m_tireLoad = dVector(0.0f, 0.0f, 0.0f, 0.0f); m_lateralForce = dVector(0.0f, 0.0f, 0.0f, 0.0f); m_longitudinalForce = dVector(0.0f, 0.0f, 0.0f, 0.0f); m_speed = 0.0f; m_posit = m_suspensionlenght; m_matrix = CalculateSteeringMatrix (); UpdateInertia(); // initialize the joints that connect tghsi tire to other vehicle componets; m_chassisJoint.Init(m_controller, &m_controller->m_chassisState, this); } void* CustomVehicleControllerBodyStateTire::GetUserData() const { return m_userData; } dMatrix CustomVehicleControllerBodyStateTire::CalculateSuspensionMatrix () const { dMatrix matrix (m_localFrame); matrix.m_posit -= m_localFrame.m_up.Scale (m_posit); return matrix; } dMatrix CustomVehicleControllerBodyStateTire::CalculateSteeringMatrix () const { return dYawMatrix(m_steeringAngle) * CalculateSuspensionMatrix (); } dMatrix CustomVehicleControllerBodyStateTire::CalculateLocalMatrix () const { return dPitchMatrix(m_rotationAngle) * CalculateSteeringMatrix (); } dMatrix CustomVehicleControllerBodyStateTire::CalculateGlobalMatrix () const { dMatrix matrix; NewtonBodyGetMatrix(m_controller->GetBody(), &matrix[0][0]); return CalculateLocalMatrix () * matrix; } void CustomVehicleControllerBodyStateTire::UpdateTransform() { dMatrix localMatrix (CalculateLocalMatrix ()); NewtonCollisionSetMatrix(m_shape, &localMatrix[0][0]); } void CustomVehicleControllerBodyStateTire::Collide (CustomControllerConvexCastPreFilter& filter, dFloat timestepInv, int threadId) { NewtonBody* const body = m_controller->GetBody(); NewtonWorld* const world = NewtonBodyGetWorld(body); const dMatrix& controllerMatrix = m_controller->m_chassisState.m_matrix; dFloat posit0 = m_posit; m_posit = 0.0f; m_speed = 0.0f; dMatrix localMatrix (CustomVehicleControllerBodyStateTire::CalculateSteeringMatrix ()); m_posit = m_suspensionlenght; dFloat hitParam; dMatrix tireMatrix (localMatrix * controllerMatrix); dVector rayDestination (tireMatrix.TransformVector(localMatrix.m_up.Scale(-m_suspensionlenght))); m_contactCount = 0; NewtonWorldConvexCastReturnInfo contacts[4]; /* NewtonCollision* xxx = NewtonCreateSphere(world, 1.0f, 0, NULL); dMatrix xxxx0 (dGetIdentityMatrix()); dVector xxxx1 (0.0f, 0.0f, 0.0f, 0.0f); xxxx0.m_posit.m_y = 2.0f; //NewtonCollisionSetScale (xxx, 0.3f, 0.5, 0.3f); int xxx3 = NewtonWorldConvexCast (world, &xxxx0[0][0], &xxxx1[0], xxx, &hitParam, &filter, CustomControllerConvexCastPreFilter::Prefilter, contacts, sizeof (contacts) / sizeof (contacts[0]), 0); */ NewtonCollisionSetScale (m_controller->m_tireCastShape, m_width, m_radio, m_radio); int contactCount = NewtonWorldConvexCast (world, &tireMatrix[0][0], &rayDestination[0], m_controller->m_tireCastShape, &hitParam, &filter, CustomControllerConvexCastPreFilter::Prefilter, contacts, sizeof (contacts) / sizeof (contacts[0]), threadId); if (contactCount) { m_posit = hitParam * m_suspensionlenght; m_speed = (posit0 - m_posit) * timestepInv; for (int i = 1; i < contactCount; i ++) { int j = i; NewtonWorldConvexCastReturnInfo tmp (contacts[i]); for (; j && (contacts[j - 1].m_hitBody > tmp.m_hitBody); j --) { contacts[j] = contacts[j - 1]; } contacts[j] = tmp; } for (int index = 0; (index < contactCount) && (m_contactCount < 2); ) { const NewtonBody* const body = contacts[index].m_hitBody; int count = 1; for (int j = index + 1; (j < contactCount) && (contacts[j].m_hitBody == body); j ++) { count ++; } CustomVehicleControllerTireContactJoint* const joint = &m_contactJoint[m_contactCount]; CustomVehicleControllerBodyStateContact* const externalBody = m_controller->GetContactBody (body); joint->Init(m_controller, externalBody, this); joint->SetContacts (count, &contacts[index]); m_contactCount ++; index += count; } } // project contact to the surface of the tire shape for (int i = 0; i < m_contactCount; i ++) { CustomVehicleControllerTireContactJoint& contact = m_contactJoint[i]; for (int j = 0; j < contact.m_contactCount; j ++) { dVector radius (contact.m_contacts[j].m_point - m_matrix[3]); radius -= m_matrix[0].Scale (m_matrix[0] % radius); dAssert ((radius % radius) > 0.0f); radius = radius.Scale (m_radio / dSqrt (radius % radius)); contact.m_contacts[j].m_point = m_matrix[3] + radius; } } } void CustomVehicleControllerBodyStateTire::UpdateDynamicInputs(dFloat timestep) { CustomVehicleControllerBodyStateChassis& chassis = m_controller->m_chassisState; m_matrix = CalculateSteeringMatrix() * chassis.m_matrix; m_globalCentreOfMass = m_matrix.m_posit; UpdateInertia(); // get the velocity state for this tire dVector relPosit (m_matrix.m_posit - chassis.m_globalCentreOfMass); m_omega = chassis.m_omega + m_matrix[0].Scale (m_rotationalSpeed); m_veloc = chassis.m_veloc + chassis.m_omega * relPosit + m_matrix[1].Scale (m_speed); // set the initial force on this tire m_externalForce = chassis.m_gravity.Scale (m_mass); m_externalTorque = dVector (0.0f, 0.0f, 0.0f, 0.0f); m_tireLoad = dVector(0.0f, 0.0f, 0.0f, 0.0f); m_lateralForce = dVector(0.0f, 0.0f, 0.0f, 0.0f); m_longitudinalForce = dVector(0.0f, 0.0f, 0.0f, 0.0f); // calculate force an torque generate by the suspension if (m_contactCount) { dFloat distance = m_suspensionlenght - m_posit; dAssert (distance >= 0.0f); dAssert (distance <= m_suspensionlenght); if (distance <= dFloat(1.0e-3f)) { // now calculate the tire load at the contact point, tire suspension distance also consider hard limit. //dAssert (0); } dFloat load = - NewtonCalculateSpringDamperAcceleration (timestep, m_springStrength, distance, m_dampingRatio, m_speed); if (load < 0.0f) { // tire can not pull the car, this is a symptom of bad suspension spring or damper load = 0.0f; } // calculate the tire load m_tireLoad = m_matrix[1].Scale(load * m_mass); // calculate tire force and torque spring and damper apply to the chassis dVector torque (relPosit * m_tireLoad); chassis.m_externalForce += m_tireLoad; chassis.m_externalTorque += torque; // the spring apply the same force in the opposite direction to the tire m_externalForce -= m_tireLoad; } } void CustomVehicleControllerBodyStateTire::CalculateRollingResistance (dFloat topSpeed) { m_maxAngularVelocity = topSpeed / m_radio; } void CustomVehicleControllerBodyStateTire::ApplyNetForceAndTorque (dFloat invTimestep, const dVector& veloc, const dVector& omega) { CustomVehicleControllerBodyState::ApplyNetForceAndTorque (invTimestep, veloc, omega); const CustomVehicleControllerBodyStateChassis& chassis = m_controller->m_chassisState; // integrate tires angular velocity dVector relOmega (m_omega - chassis.m_omega); m_rotationalSpeed = relOmega % m_matrix[0]; if (dAbs (m_rotationalSpeed) > m_maxAngularVelocity) { m_rotationalSpeed *= 0.9f; m_omega = m_matrix[0].Scale (m_rotationalSpeed) + chassis.m_omega; } m_rotationAngle = dMod (m_rotationAngle + m_rotationalSpeed / invTimestep, 2.0f * 3.141592f); }
greysonmrx/Backpack
src/store/modules/rootSaga.js
<filename>src/store/modules/rootSaga.js import { all } from "redux-saga/effects"; import timetable from "./timetable/sagas"; import task from "./task/sagas"; import notebook from "./notebook/sagas"; import setting from "./setting/sagas"; export default function* rootSagaall() { return yield all([timetable, task, notebook, setting]); }
alex5nader/Conrad
src/main/java/dev/inkwell/conrad/api/gui/EntryBuilderRegistry.java
/* * Copyright 2021 <NAME> * * 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 dev.inkwell.conrad.api.gui; import dev.inkwell.conrad.api.value.ConfigDefinition; import dev.inkwell.conrad.api.value.ValueKey; import dev.inkwell.conrad.api.value.data.Bounds; import dev.inkwell.conrad.api.value.data.Constraint; import dev.inkwell.conrad.api.value.data.DataType; import dev.inkwell.conrad.api.value.lang.Translator; import dev.inkwell.conrad.api.value.util.Array; import dev.inkwell.conrad.api.value.util.ListView; import dev.inkwell.conrad.api.value.util.Table; import dev.inkwell.conrad.impl.Conrad; import dev.inkwell.conrad.impl.data.DataObject; import dev.inkwell.conrad.impl.exceptions.ConfigValueException; import dev.inkwell.conrad.impl.util.ReflectionUtil; import dev.inkwell.vivian.api.screen.ConfigScreen; import dev.inkwell.vivian.api.util.Alignment; import dev.inkwell.vivian.api.widgets.WidgetComponent; import dev.inkwell.vivian.api.widgets.compound.ArrayWidget; import dev.inkwell.vivian.api.widgets.compound.TableWidget; import dev.inkwell.vivian.api.widgets.value.*; import dev.inkwell.vivian.api.widgets.value.entry.*; import dev.inkwell.vivian.api.widgets.value.slider.DoubleSliderWidget; import dev.inkwell.vivian.api.widgets.value.slider.FloatSliderWidget; import dev.inkwell.vivian.api.widgets.value.slider.IntegerSliderWidget; import dev.inkwell.vivian.api.widgets.value.slider.LongSliderWidget; import net.minecraft.text.Text; import net.minecraft.text.TranslatableText; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; public class EntryBuilderRegistry { private static final Map<Class<?>, ValueWidgetFactory<?>> DEFAULT_FACTORIES = new HashMap<>(); static { registerDefaults(); } public static <T> void register(Class<T> clazz, ValueWidgetFactory<T> builder) { for (Class<?> clazz2 : ReflectionUtil.getClasses(clazz)) { DEFAULT_FACTORIES.putIfAbsent(clazz2, builder); } } private static <T extends Number & Comparable<T>> void registerBounded(Class<T> clazz, BoundedWidgetFactory<T> bounded, UnboundedWidgetFactory<T> unBounded) { register(clazz, (screen, x, y, width, name, config, constraints, data, defaultValueSupplier, changedListener, saveConsumer, value) -> { Bounds<T> bounds = null; for (Constraint<T> constraint : constraints) { if (constraint instanceof Bounds) { bounds = (Bounds<T>) constraint; } } if (bounds == null || bounds.getMin().equals(bounds.getAbsoluteMin()) || bounds.getMax().equals(bounds.getAbsoluteMax())) { ValueWidgetComponent<T> widget = unBounded.build(screen, x, y, width, 20, Alignment.RIGHT, defaultValueSupplier, changedListener, saveConsumer, value); widget.addConstraints(constraints); return widget; } else { T min = bounds.getMin(); T max = bounds.getMax(); return bounded.build(screen, x, y, width, 20, defaultValueSupplier, changedListener, saveConsumer, value, min, max); } }); } public static <T> void override(Class<T> clazz, ValueWidgetFactory<T> builder) { DEFAULT_FACTORIES.put(clazz, builder); } @SuppressWarnings("unchecked") public static <T> ValueWidgetFactory<T> get(ValueKey<T> configValue) throws ConfigValueException { ListView<ValueWidgetFactory<?>> widgetBuilders = configValue.getData(DataType.WIDGET); if (!widgetBuilders.isEmpty()) { return (ValueWidgetFactory<T>) widgetBuilders.get(0); } return (ValueWidgetFactory<T>) get(configValue.getDefaultValue().getClass(), t -> Conrad.syncAndSave(configValue.getConfig())); } @SuppressWarnings("unchecked") public static <T> ValueWidgetFactory<T> get(Class<T> type, Consumer<T> outerSaveConsumer) { if (DEFAULT_FACTORIES.containsKey(type)) { return (ValueWidgetFactory<T>) DEFAULT_FACTORIES.get(type); } if (type.isEnum()) { return (ValueWidgetFactory<T>) enumFactory(type); } if (isSimpleCompoundData(type)) { return new DataClassValueWidgetFactory<>(type, outerSaveConsumer); } throw new ConfigValueException("Widget builder not registered for class '" + type.getName() + "' or provided for class '" + type.getName() + "'"); } private static boolean isSimpleCompoundData(Class<?> clazz) { for (Field field : clazz.getDeclaredFields()) { Class<?> fieldType = field.getType(); if (!fieldType.isEnum() && !isSimpleCompoundData(fieldType) && !DEFAULT_FACTORIES.containsKey(fieldType)) { return false; } } return true; } @SuppressWarnings("unchecked") private static <T extends Enum<T>> ValueWidgetFactory<T> enumFactory(Class<?> clazz) { T[] enums = (T[]) clazz.getEnumConstants(); if (enums.length <= 3) { return ((screen, x, y, width, name, config, constraints, data, defaultValueSupplier, changedListener, saveConsumer, value) -> new EnumSelectorComponent<>(screen, x, y, width, 20, defaultValueSupplier, changedListener, saveConsumer, value)); } else { return ((screen, x, y, width, name, config, constraints, data, defaultValueSupplier, changedListener, saveConsumer, value) -> new EnumDropdownWidget<>(screen, x, y, width, 20, defaultValueSupplier, changedListener, saveConsumer, value)); } } @SuppressWarnings("unchecked") private static <T> void registerDefaults() { registerBounded(Integer.class, IntegerSliderWidget::new, IntegerEntryWidget::new); registerBounded(Long.class, LongSliderWidget::new, LongEntryWidget::new); registerBounded(Float.class, FloatSliderWidget::new, FloatEntryWidget::new); registerBounded(Double.class, DoubleSliderWidget::new, DoubleEntryWidget::new); register(String.class, (ConfigScreen screen, int x, int y, int width, Text name, ConfigDefinition<?> config, ListView<Constraint<String>> constraints, DataObject data, Supplier<@NotNull String> defaultValueSupplier, Consumer<String> changedListener, Consumer<String> saveConsumer, @NotNull String value) -> { StringEntryWidget component = new StringEntryWidget(screen, x, y, width, 20, Alignment.RIGHT, defaultValueSupplier, changedListener, saveConsumer, value); component.setTextPredicate(string -> { for (Constraint<String> constraint : constraints) { if (!constraint.passes(value)) { return false; } } return true; }); return component; }); register(Boolean.class, (ConfigScreen screen, int x, int y, int width, Text name, ConfigDefinition<?> config, ListView<Constraint<Boolean>> constraints, DataObject data, Supplier<@NotNull Boolean> defaultValueSupplier, Consumer<Boolean> changedListener, Consumer<Boolean> saveConsumer, @NotNull Boolean value) -> new ToggleComponent(screen, x, y, width, 20, defaultValueSupplier, changedListener, saveConsumer, value, bl -> { String translationKey = (name instanceof TranslatableText ? ((TranslatableText) name).getKey() : name.asString()) + ".value." + (bl ? "true" : "false"); if (Translator.translate(translationKey) == null) { translationKey = config.toString() + ".value." + (bl ? "true" : "false"); } if (Translator.translate(translationKey) == null) { translationKey = bl ? "conrad.value.true" : "conrad.value.false"; } return new TranslatableText(translationKey); }) ); register(Array.class, (screen, x, y, width, name, config, constraints, data, defaultValueSupplier, changedListener, saveConsumer, value) -> { ListView<ValueWidgetFactory<?>> widgetBuilders = data.getData(DataType.WIDGET); ValueWidgetFactory<T> factory = widgetBuilders.isEmpty() ? get(value.getValueClass(), t -> { }) : (ValueWidgetFactory<T>) widgetBuilders.get(0); Consumer<Array<T>> saveAndSave = t -> { saveConsumer.accept(t); Conrad.syncAndSave(config); }; ArrayWidget<T> array = new ArrayWidget<T>(config, screen, x, y, (Supplier<@NotNull Array<T>>) (Object) defaultValueSupplier, (Consumer<Array<T>>) (Object) changedListener, saveAndSave, value, name, factory); if (data.getDataTypes().contains(DataType.SUGGESTION_PROVIDER)) { array.setSuggestions(data.getData(DataType.SUGGESTION_PROVIDER).get(0)); } array.addConstraints((ListView<Constraint<Array<T>>>) (Object) constraints); return array; }); register(Table.class, (screen, x, y, width, name, config, constraints, data, defaultValueSupplier, changedListener, saveConsumer, value) -> { ListView<ValueWidgetFactory<?>> widgetBuilders = data.getData(DataType.WIDGET); ValueWidgetFactory<T> factory = widgetBuilders.isEmpty() ? get(value.getValueClass(), t -> { }) : (ValueWidgetFactory<T>) widgetBuilders.get(0); Consumer<Table<T>> saveAndSave = t -> { saveConsumer.accept(t); Conrad.syncAndSave(config); }; TableWidget<T> table = new TableWidget<T>(config, screen, x, y, (Supplier<@NotNull Table<T>>) (Object) defaultValueSupplier, (Consumer<Table<T>>) (Object) changedListener, saveAndSave, value, name, factory); if (data.getDataTypes().contains(DataType.SUGGESTION_PROVIDER)) { table.setValueSuggestions(data.getData(DataType.SUGGESTION_PROVIDER).get(0)); } table.addConstraints((ListView<Constraint<Table<T>>>) (Object) constraints); if (config.getSerializer().getKeyConstraint() != null) { table.addKeyConstraint(config.getSerializer().getKeyConstraint()); } return table; }); } @FunctionalInterface public interface BoundedWidgetFactory<T> { ValueWidgetComponent<T> build(ConfigScreen parent, int x, int y, int width, int height, Supplier<@NotNull T> defaultValueSupplier, Consumer<T> changedListener, Consumer<T> saveConsumer, @NotNull T value, @NotNull T min, @NotNull T max); } @FunctionalInterface public interface UnboundedWidgetFactory<T> { ValueWidgetComponent<T> build(ConfigScreen parent, int x, int y, int width, int height, Alignment alignment, Supplier<@NotNull T> defaultValueSupplier, Consumer<T> changedListener, Consumer<T> saveConsumer, @NotNull T value); } public static class DataClassValueWidgetFactory<T> implements ValueWidgetFactory<T> { private final Class<T> type; private Consumer<T> outerSaveConsumer; private DataClassValueWidgetFactory(Class<T> type, Consumer<T> outerSaveConsumer) { this.type = type; this.outerSaveConsumer = outerSaveConsumer; } public void setOuterSaveConsumer(Consumer<T> saveConsumer) { this.outerSaveConsumer = saveConsumer; } @Override public WidgetComponent build(ConfigScreen screen, int x, int y, int width, Text name, ConfigDefinition<?> config, ListView<Constraint<T>> constraints, DataObject data, Supplier<@NotNull T> defaultValueSupplier, Consumer<T> changedListener, Consumer<T> saveConsumer, @NotNull T value) { return new DataClassWidgetComponent<>(screen, x, y, config, defaultValueSupplier, changedListener, t -> { saveConsumer.accept(t); outerSaveConsumer.accept(t); }, value, type); } } }
MrAwesomeRocks/caelus-cml
src/libraries/turbulenceModels/compressible/RAS/RASModel/compressibleRASModel.hpp
<filename>src/libraries/turbulenceModels/compressible/RAS/RASModel/compressibleRASModel.hpp /*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CAELUS. If not, see <http://www.gnu.org/licenses/>. Namespace CML::compressible::RASModels Description Namespace for compressible RAS turbulence models. Class CML::compressible::RASModel Description Abstract base class for turbulence models for compressible and combusting flows. SourceFiles compressibleRASModel.cpp \*---------------------------------------------------------------------------*/ #ifndef compressibleRASModel_H #define compressibleRASModel_H #include "compressible/turbulenceModel/compressibleTurbulenceModel.hpp" #include "volFields.hpp" #include "surfaceFields.hpp" #include "nearWallDist.hpp" #include "fvm.hpp" #include "fvc.hpp" #include "fvMatrices.hpp" #include "fluidThermo.hpp" #include "IOdictionary.hpp" #include "Switch.hpp" #include "bound.hpp" #include "autoPtr.hpp" #include "runTimeSelectionTables.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { namespace compressible { /*---------------------------------------------------------------------------*\ Class RASModel Declaration \*---------------------------------------------------------------------------*/ class RASModel : public turbulenceModel, public IOdictionary { protected: // Protected data //- Turbulence on/off flag Switch turbulence_; //- Flag to print the model coeffs at run-time Switch printCoeffs_; //- Model coefficients dictionary dictionary coeffDict_; //- Lower limit of k dimensionedScalar kMin_; //- Lower limit of epsilon dimensionedScalar epsilonMin_; //- Lower limit for omega dimensionedScalar omegaMin_; //- Near wall distance boundary field nearWallDist y_; // Protected Member Functions //- Print model coefficients virtual void printCoeffs(); private: // Private Member Functions //- Disallow default bitwise copy construct RASModel(const RASModel&); //- Disallow default bitwise assignment void operator=(const RASModel&); public: //- Runtime type information TypeName("RASModel"); // Declare run-time constructor selection table declareRunTimeSelectionTable ( autoPtr, RASModel, dictionary, ( const volScalarField& rho, const volVectorField& U, const surfaceScalarField& phi, const fluidThermo& thermoPhysicalModel, const word& turbulenceModelName ), (rho, U, phi, thermoPhysicalModel, turbulenceModelName) ); // Constructors //- Construct from components RASModel ( const word& type, const volScalarField& rho, const volVectorField& U, const surfaceScalarField& phi, const fluidThermo& thermoPhysicalModel, const word& turbulenceModelName = turbulenceModel::typeName ); // Selectors //- Return a reference to the selected RAS model static autoPtr<RASModel> New ( const volScalarField& rho, const volVectorField& U, const surfaceScalarField& phi, const fluidThermo& thermoPhysicalModel, const word& turbulenceModelName = turbulenceModel::typeName ); //- Destructor virtual ~RASModel() {} // Member Functions // Access //- Return the lower allowable limit for k (default: SMALL) const dimensionedScalar& kMin() const { return kMin_; } //- Return the lower allowable limit for epsilon (default: SMALL) const dimensionedScalar& epsilonMin() const { return epsilonMin_; } //- Return the lower allowable limit for omega (default: SMALL) const dimensionedScalar& omegaMin() const { return omegaMin_; } //- Allow kMin to be changed dimensionedScalar& kMin() { return kMin_; } //- Allow epsilonMin to be changed dimensionedScalar& epsilonMin() { return epsilonMin_; } //- Allow omegaMin to be changed dimensionedScalar& omegaMin() { return omegaMin_; } //- Return the near wall distances const nearWallDist& y() const { return y_; } //- Calculate y+ at the edge of the laminar sublayer scalar yPlusLam(const scalar kappa, const scalar E) const; //- Const access to the coefficients dictionary virtual const dictionary& coeffDict() const { return coeffDict_; } //- Return the effective viscosity virtual tmp<volScalarField> muEff() const { return tmp<volScalarField> ( new volScalarField("muEff", mut() + mu()) ); } //- Return the effective turbulent thermal diffusivity virtual tmp<volScalarField> alphaEff() const { return thermo().alphaEff(alphat()); } //- Return the effective turbulent thermal diffusivity for a patch virtual tmp<scalarField> alphaEff(const label patchI) const { return thermo().alphaEff(alphat()().boundaryField()[patchI], patchI); } //- Return the effective turbulent temperature diffusivity virtual tmp<volScalarField> kappaEff() const { return thermo().kappaEff(alphat()); } //- Return the effective turbulent temperature diffusivity for a patch virtual tmp<scalarField> kappaEff(const label patchI) const { return thermo().kappaEff(alphat()().boundaryField()[patchI], patchI); } //- Return yPlus for the given patch virtual tmp<scalarField> yPlus ( const label patchI, const scalar Cmu ) const; //- Solve the turbulence equations and correct the turbulence viscosity virtual void correct(); //- Read RASProperties dictionary virtual bool read(); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace compressible } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
AntonioLuisP/path-to-work
src/reusable/GoTo.js
<gh_stars>0 import React from 'react' import { CTooltip, CLink } from '@coreui/react' const GoTo = ({ go, children }) => { return ( <CLink rel="noreferrer noopener" className="card-header-action text-primary" to={go} > <CTooltip content='Ver' placement='top' > {children} </CTooltip> </CLink> ) } export default React.memo(GoTo)
jnthn/intellij-community
java/java-tests/testData/inspection/commonIfParts/beforeCompleteDuplicateImplicitReturnFoldedIf.java
<reponame>jnthn/intellij-community<gh_stars>1-10 // "Collapse 'if' statement" "true" import java.util.Collection; import java.util.List; import java.util.Set; public class IfStatementWithIdenticalBranches { int work() { if (true) { if<caret> (false) { System.out.println(); return; } } System.out.println(); } }
OpenIchano/Viewer
src/com/zhongyun/viewer/BaseActivity.java
<filename>src/com/zhongyun/viewer/BaseActivity.java<gh_stars>10-100 /* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer; import com.zhongyun.viewer.utils.AppUtils; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.view.Window; public class BaseActivity extends Activity{ protected ProgressDialog dialog = null; private boolean isActivityVisible = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); AppUtils.setStatusBarTransparent(this, getResources().getColor(R.color.title_red)); } public void showProgressDialog(int stringId){ if(isActivityVisible){ if(null == dialog){ dialog = new ProgressDialog(this); dialog.setCanceledOnTouchOutside(false); } dialog.setMessage(getString(stringId)); dialog.show(); } } public void showProgressDialogs(){ if(isActivityVisible){ if(null == dialog){ dialog = new ProgressDialog(this); dialog.setCanceledOnTouchOutside(false); } dialog.show(); } } public void dismissProgressDialog(){ dialog.dismiss(); } @Override protected void onResume() { super.onResume(); isActivityVisible = true; } @Override protected void onPause() { super.onPause(); isActivityVisible = false; } }
ritesh-kanchi/14786-SKYSTONE
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/testing/AutonTest.java
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.util.ElapsedTime; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.robotcore.hardware.DcMotor; @Autonomous(name="AutonTest", group="LinearOpMode") @Disabled public class AutonTest extends LinearOpMode { HardwareRobot robot = new HardwareRobot(); public void robotInit() { robot.init(hardwareMap); } @Override public void runOpMode() { robotInit(); telemetry.addData("Status", "Initialized"); telemetry.update(); // wait for the game to start (driver presses PLAY) waitForStart(); moveYWX(0,0,0.4); sleep(550); moveYWX(0, 0, 0); sleep(500); moveYWX(-0.4, 0, 0); sleep(400); moveYWX(0, 0, 0); sleep(500); moveYWX(0.4, 0, 0); sleep(950); moveYWX(0, 0, 0); sleep(500); moveYWX(-0.4, 0, 0); sleep(2000); moveYWX(0, 0, 0); sleep(500); moveYWX(0,0,0.4); sleep(2000); moveYWX(0, 0, 0); sleep(500); moveYWX(-0.4,0,0); sleep(500); moveYWX(0, 0, 0); sleep(500); moveYWX(0,0,-0.6); sleep(3200); moveYWX(0, 0, 0); sleep(500); moveYWX(-0.4,0,0); sleep(350); moveYWX(0, 0, 0); sleep(500); } public void moveYWX(double forward, double turn, double strafe) { robot.leftFront.setPower(forward + turn + strafe); robot.rightFront.setPower(forward - turn - strafe); robot.leftBack.setPower(forward + turn - strafe); robot.rightBack.setPower(forward - turn + strafe); } }
markzgwu/go-filecoin
app/connectors/fsm_events/connector.go
<reponame>markzgwu/go-filecoin package fsmeventsconnector import ( "context" "github.com/filecoin-project/go-state-types/abi" logging "github.com/ipfs/go-log/v2" "github.com/filecoin-project/venus/pkg/chain" "github.com/filecoin-project/venus/pkg/chainsampler" "github.com/filecoin-project/venus/pkg/encoding" "github.com/filecoin-project/venus/pkg/util/fsm" ) var log = logging.Logger("fsm_events") // nolint: deadcode type FiniteStateMachineEventsConnector struct { scheduler *chainsampler.HeightThresholdScheduler tsp chain.TipSetProvider } var _ fsm.Events = new(FiniteStateMachineEventsConnector) func New(scheduler *chainsampler.HeightThresholdScheduler, tsp chain.TipSetProvider) FiniteStateMachineEventsConnector { return FiniteStateMachineEventsConnector{ scheduler: scheduler, tsp: tsp, } } func (f FiniteStateMachineEventsConnector) ChainAt(hnd fsm.HeightHandler, rev fsm.RevertHandler, confidence int, h abi.ChainEpoch) error { // wait for an epoch past the target that gives us some confidence it won't reorg l := f.scheduler.AddListener(h + abi.ChainEpoch(confidence)) ctx := context.Background() go func() { var handledToken fsm.TipSetToken for { select { case <-l.DoneCh: return case err := <-l.ErrCh: log.Warn(err) return case tsk := <-l.HitCh: ts, err := f.tsp.GetTipSet(tsk) if err != nil { log.Error(err) return } targetTipset, err := chain.FindTipsetAtEpoch(ctx, ts, h, f.tsp) if err != nil { log.Error(err) return } handledToken, err := encoding.Encode(targetTipset.Key()) if err != nil { log.Error(err) return } sampleHeight, err := targetTipset.Height() if err != nil { log.Error(err) return } err = hnd(ctx, handledToken, sampleHeight) if err != nil { log.Error(err) return } case <-l.InvalidCh: err := rev(ctx, handledToken) if err != nil { log.Error(err) return } } } }() return nil }
cas-bigdatalab/vdb-4.0
src/main/java/vdb/report/util/StringUtil.java
<gh_stars>1-10 package vdb.report.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.StringReader; import java.text.NumberFormat; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.XMLOutputter; import org.jdom.xpath.XPath; /** * 字符处理公共类 * * @author suxianming * */ public class StringUtil { /** * 替换XML文档中的字符串 * * @param filePath * XML文档路径 * @param oldStr * 原始字符串 * @param newStr * 目标字符串 */ public static void replaceInFileWithString(String filePath, String oldStr, String newStr) { SAXBuilder builder = new SAXBuilder(); try { Document doc = builder.build(new File(filePath)); Element e = doc.getRootElement(); Element data = (Element) XPath.selectSingleNode(e, oldStr); data.removeContent(); Element ee = (Element) builder.build(new StringReader(newStr)) .getRootElement().clone(); data.addContent(ee); XMLOutputter xmlOut = new XMLOutputter(); xmlOut.output(doc, new FileOutputStream(filePath)); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 将长整型分数转变为百分比字符串 * * @param numerator * @param denominator * @return String 66% */ public String getPercentRate(long numerator, long denominator) { NumberFormat nf = NumberFormat.getPercentInstance(); nf.setMaximumFractionDigits(0); nf.setMaximumIntegerDigits(3); return nf.format(((float) numerator) / denominator); } }
PJB2TY/light-4j
egress-router/src/main/java/com/networknt/router/middleware/HandlerUtils.java
package com.networknt.router.middleware; import com.networknt.utility.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; public class HandlerUtils { private static final Logger logger = LoggerFactory.getLogger(HandlerUtils.class); public static final String DELIMITOR = "@"; protected static final String INTERNAL_KEY_FORMAT = "%s %s"; /** * Looks up the appropriate serviceId for a given requestPath taken directly from exchange. * Returns null if the path does not map to a configured service, otherwise, an array will * be returned with the first element the path prefix and the second element the serviceId. * * @param searchKey search key * @param mapping a map of prefix and service id * @return pathPrefix and serviceId in an array that is found */ public static String[] findServiceEntry(String searchKey, Map<String, String> mapping) { if(logger.isDebugEnabled()) logger.debug("findServiceEntry for " + searchKey); String[] result = null; for (Map.Entry<String, String> entry : mapping.entrySet()) { String prefix = entry.getKey(); if(searchKey.startsWith(prefix)) { if((searchKey.length() == prefix.length() || searchKey.charAt(prefix.length()) == '/')) { result = new String[2]; result[0] = entry.getKey(); result[1] = entry.getValue(); break; } } } if(result == null) { if(logger.isDebugEnabled()) logger.debug("serviceEntry not found!"); } else { if(logger.isDebugEnabled()) logger.debug("prefix = " + result[0] + " serviceId = " + result[1]); } return result; } public static String normalisePath(String requestPath) { if(!requestPath.startsWith("/")) { return "/" + requestPath; } return requestPath; } public static String toInternalKey(String key) { String[] tokens = StringUtils.trimToEmpty(key).split(DELIMITOR); if (tokens.length ==2) { return toInternalKey(tokens[1], tokens[0]); } logger.warn("Invalid key {}", key); return key; } public static String toInternalKey(String method, String path) { return String.format(INTERNAL_KEY_FORMAT, method, HandlerUtils.normalisePath(path)); } }
Fabio-Morais/Learning-Java
TicTacToe/src/sample/GameScreen.java
package sample; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Scanner; public class GameScreen { private char[][] symbols; private int numX; private int numO; private int whoPlay; /* * 0-> FIRST PLAYER * 1-> SECOND PLAYER * */ public String IASymbol; public String enemySymbol; private static Scanner scanner = new Scanner(System.in); /* CONSTRUCTURE*/ public GameScreen() { this.symbols = new char[3][3]; this.resetGame(); } /* RESET VARIABLES AND SET " " TO ARRAY OF SYMBOLS */ public void resetGame() { numX = 0; numO = 0; whoPlay = 0; // I start first for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) this.symbols[i][j] = " ".charAt(0); } this.printGame(); } /* SET SMBOLS BY STRING*/ public void setSymbols(String cells) { System.out.println(cells.length()); if (cells.length() != 11) System.out.println("error"); else { int c = 0; int r = 0; for (int i = 1; i < cells.length() - 1; i++) { if (i == 4 || i == 7) { c++; r = 0; } this.symbols[c][r] = Character.toUpperCase(cells.charAt(i)); if (this.symbols[c][r] == "X".charAt(0)) numX++; else if (this.symbols[c][r] == "O".charAt(0)) numO++; r++; } } } /* INPUT OF START USER/EASY/MEDUM/HARD * RETURN: ARRAY OF PLAYERS, [0]-> first, [1]->second * IE: START EASY USER -> [O]->EASY, [1]-> USER * */ public int[] startMenu() { int[] option = new int[2]; String[] splitStr; while (true) { System.out.print("Input command: "); String string = scanner.nextLine(); splitStr = string.split(" "); if (splitStr.length != 3) System.out.println("Bad parameters!"); else { if (!splitStr[0].toUpperCase().equals("START")) System.out.println("Bad parameters!"); else break; } } if (splitStr[1].toUpperCase().equals("USER")) option[0] = 0; else if (splitStr[1].toUpperCase().equals("EASY")) option[0] = 1; else if (splitStr[1].toUpperCase().equals("MEDIUM")) option[0] = 2; else if (splitStr[1].toUpperCase().equals("HARD")) { option[0] = 3; enemySymbol = "O"; IASymbol = "X"; } if (splitStr[2].toUpperCase().equals("USER")) option[1] = 0; else if (splitStr[2].toUpperCase().equals("EASY")) option[1] = 1; else if (splitStr[2].toUpperCase().equals("MEDIUM")) option[1] = 2; else if (splitStr[2].toUpperCase().equals("HARD")) { option[1] = 3; enemySymbol = "X"; IASymbol = "O"; } return option; } public void printMenu(){ System.out.println("User vs user"); System.out.println("User vs pc"); } public void printMenu2(){ System.out.println("Easy Mode"); System.out.println("Medium Mode"); System.out.println("Hard Mode"); } /* MAKE A MOVE EASY (RANDOM) */ public void makeMoveEasy() { /*1 to 3*/ int x, y; Random random = new Random(); /* * ((Max - Min)+1) + 1 * */ while (true) { x = random.nextInt((3 - 1) + 1) + 1; y = random.nextInt((3 - 1) + 1) + 1; if (this.isEmpty(x, y)) break; } this.setSymbols(x, y); this.changeWhoPlay(); } /* MAKE A MOVE EASY (RANDOM) */ public void makeMoveMedium() { if (!this.winMove()) {// if can't win if (!this.enemyWinMove()) // if can't combat the enemy this.makeMoveEasy();//random move } } public Move makeMoveHard(char[][] board, String player) { Move minimaxResult = new Move(); int bestResult = -11; /* * 0-> Y, i * 1-> X, j * */ int[][] availableSpaces= emptyIndexies(board); if(availableSpaces.length == 8 && board[1][1] == " ".charAt(0)){ minimaxResult.setSimulationResult(10); int[] aux= winning(board, IASymbol); minimaxResult.setxCoordinates(1); minimaxResult.setyCoordinates(1); return minimaxResult; } if(winning(board, IASymbol) != null ){ System.out.println("ia"); minimaxResult.setSimulationResult(10); int[] aux= winning(board, IASymbol); minimaxResult.setxCoordinates(aux[1]); minimaxResult.setyCoordinates(aux[0]); return minimaxResult; }else if(winning(board, enemySymbol) != null){ System.out.println("enem"); minimaxResult.setSimulationResult(-10); int[] aux= winning(board, enemySymbol); minimaxResult.setxCoordinates(aux[1]); minimaxResult.setyCoordinates(aux[0]); return minimaxResult; }else if(availableSpaces.length == 0){ minimaxResult.setSimulationResult(0); minimaxResult.setIsDraw(true); return minimaxResult; } List<Move> moves = new ArrayList<>(); for(int i=0; i<availableSpaces.length; i++){ Move currentResult = new Move(); currentResult.setxCoordinates(availableSpaces[i][1]); currentResult.setyCoordinates(availableSpaces[i][0]); // set the empty spot to the current player board[availableSpaces[i][0]][availableSpaces[i][1]] = player.charAt(0); //if collect the score resulted from calling minimax on the opponent of the current player String aux="X"; if(player.equals(IASymbol)){ aux= enemySymbol; }else if(player.equals(enemySymbol)){ aux= IASymbol; } Move currentResultAux= makeMoveHard(board, aux); currentResult.setSimulationResult(currentResultAux.getSimulationResult()); moves.add(currentResult); board[availableSpaces[i][0]][availableSpaces[i][1]] = " ".charAt(0); /* if(player.equals(IASymbol)){ if(bestResult < currentResult.getSimulationResult() || bestResult == -11){ bestResult = currentResult.getSimulationResult(); minimaxResult.setSimulationResult(currentResult.getSimulationResult()); minimaxResult.setxCoordinates(availableSpaces[i][1]); minimaxResult.setyCoordinates(availableSpaces[i][0]); } }else { if(bestResult > currentResult.getSimulationResult() || bestResult == -11){ bestResult = currentResult.getSimulationResult(); minimaxResult.setSimulationResult(currentResult.getSimulationResult()); minimaxResult.setxCoordinates(availableSpaces[i][1]); minimaxResult.setyCoordinates(availableSpaces[i][0]); } }*/ } int bestMove=0; if(player.equals(IASymbol)){ int bestScore=-10000; for(int i=0; i<moves.size(); i++){ if(moves.get(i).getSimulationResult() > bestScore){ bestScore = moves.get(i).getSimulationResult(); bestMove = i; } } }else{ int bestScore= 10000; for(int i=0; i<moves.size(); i++){ if(moves.get(i).getSimulationResult() < bestScore){ bestScore = moves.get(i).getSimulationResult(); bestMove = i; } } } System.out.println(moves.get(bestMove).getxCoordinates() + " .> "+ moves.get(bestMove).getyCoordinates()); return moves.get(bestMove); } public boolean winMove() { String winV, winH, mySymbol; int r = -1; int c = -1; boolean set = false; if (whoPlay == 0) mySymbol = "X"; else if (whoPlay == 1) mySymbol = "O"; else mySymbol = "error"; for (int i = 0; i < 3; i++) { /*horizontal*/ winH = "" + this.symbols[i][0] + "" + this.symbols[i][1] + "" + this.symbols[i][2]; /*vertical*/ winV = "" + this.symbols[0][i] + "" + this.symbols[1][i] + "" + this.symbols[2][i]; /* HORIZONTAL */ if (winH.equals(" " + mySymbol + mySymbol)) { c = i; r = 0; set = true; break; } else if (winH.equals(mySymbol + " " + mySymbol)) { c = i; r = 1; set = true; break; } else if (winH.equals(mySymbol + mySymbol + " ")) { c = i; r = 2; set = true; break; /* VERTICAL */ } else if (winV.equals(" " + mySymbol + mySymbol)) { c = 0; r = i; set = true; break; /* "X X" */ } else if (winV.equals(mySymbol + " " + mySymbol)) { c = 1; r = i; set = true; break; /* "XX " */ } else if (winV.equals(mySymbol + mySymbol + " ")) { c = 2; r = i; set = true; break; } } /*Diagonal*/ String winD = "" + this.symbols[0][0] + "" + this.symbols[1][1] + "" + this.symbols[2][2] + "" + this.symbols[0][2] + "" + this.symbols[1][1] + "" + this.symbols[2][0]; if (winD.substring(0, 3).equals(mySymbol + mySymbol + " ")) { r = 2; c = 2; set = true; } else if (winD.substring(0, 3).equals(mySymbol + " " + mySymbol)) { r = 1; c = 1; set = true; } else if (winD.substring(0, 3).equals(" " + mySymbol + mySymbol)) { r = 0; c = 0; set = true; } else if (winD.substring(3, 6).equals(mySymbol + mySymbol + " ")) { r = 0; c = 2; set = true; } else if (winD.substring(3, 6).equals(mySymbol + " " + mySymbol)) { r = 1; c = 1; set = true; } else if (winD.substring(3, 6).equals(" " + mySymbol + mySymbol)) { r = 2; c = 0; set = true; } this.setSymbols(r, c, set); return set; } public boolean enemyWinMove() { String winV, winH, enemySymbol; int r = -1; int c = -1; boolean set = false; if (whoPlay == 0) enemySymbol = "O"; else if (whoPlay == 1) enemySymbol = "X"; else enemySymbol = "error"; for (int i = 0; i < 3; i++) { /*horizontal*/ winH = "" + this.symbols[i][0] + "" + this.symbols[i][1] + "" + this.symbols[i][2]; /*vertical*/ winV = "" + this.symbols[0][i] + "" + this.symbols[1][i] + "" + this.symbols[2][i]; /* HORIZONTAL */ if (winH.equals(" " + enemySymbol + enemySymbol)) { c = i; r = 0; set = true; break; } else if (winH.equals(enemySymbol + " " + enemySymbol)) { c = i; r = 1; set = true; break; } else if (winH.equals(enemySymbol + enemySymbol + " ")) { c = i; r = 2; set = true; break; /* VERTICAL */ } else if (winV.equals(" " + enemySymbol + enemySymbol)) { c = 0; r = i; set = true; break; /* "X X" */ } else if (winV.equals(enemySymbol + " " + enemySymbol)) { c = 1; r = i; set = true; break; /* "XX " */ } else if (winV.equals(enemySymbol + enemySymbol + " ")) { c = 2; r = i; set = true; break; } } /*Diagonal*/ String winD = "" + this.symbols[0][0] + "" + this.symbols[1][1] + "" + this.symbols[2][2] + "" + this.symbols[0][2] + "" + this.symbols[1][1] + "" + this.symbols[2][0]; if (winD.substring(0, 3).equals(enemySymbol + enemySymbol + " ")) { r = 2; c = 2; set = true; } else if (winD.substring(0, 3).equals(enemySymbol + " " + enemySymbol)) { r = 1; c = 1; set = true; } else if (winD.substring(0, 3).equals(" " + enemySymbol + enemySymbol)) { r = 0; c = 0; set = true; } else if (winD.substring(3, 6).equals(enemySymbol + enemySymbol + " ")) { r = 0; c = 2; set = true; } else if (winD.substring(3, 6).equals(enemySymbol + " " + enemySymbol)) { r = 1; c = 1; set = true; } else if (winD.substring(3, 6).equals(" " + enemySymbol + enemySymbol)) { r = 2; c = 0; set = true; } this.setSymbols(r, c, set); return set; } public int[] winning(char[][] board, String symbolPlay) { String winV, winH; int r = -1; int c = -1; boolean set = false; for (int i = 0; i < 3; i++) { /*horizontal*/ winH = "" + this.symbols[i][0] + "" + this.symbols[i][1] + "" + this.symbols[i][2]; /*vertical*/ winV = "" + this.symbols[0][i] + "" + this.symbols[1][i] + "" + this.symbols[2][i]; /* HORIZONTAL */ if (winH.equals(" " + symbolPlay + symbolPlay)) { c = i; r = 0; set = true; break; } else if (winH.equals(symbolPlay + " " + symbolPlay)) { c = i; r = 1; set = true; break; } else if (winH.equals(symbolPlay + symbolPlay + " ")) { c = i; r = 2; set = true; break; /* VERTICAL */ } else if (winV.equals(" " + symbolPlay + symbolPlay)) { c = 0; r = i; set = true; break; /* "X X" */ } else if (winV.equals(symbolPlay + " " + symbolPlay)) { c = 1; r = i; set = true; break; /* "XX " */ } else if (winV.equals(symbolPlay + symbolPlay + " ")) { c = 2; r = i; set = true; break; } } /*Diagonal*/ String winD = "" + this.symbols[0][0] + "" + this.symbols[1][1] + "" + this.symbols[2][2] + "" + this.symbols[0][2] + "" + this.symbols[1][1] + "" + this.symbols[2][0]; if (winD.substring(0, 3).equals(symbolPlay + symbolPlay + " ")) { r = 2; c = 2; set = true; } else if (winD.substring(0, 3).equals(symbolPlay + " " + symbolPlay)) { r = 1; c = 1; set = true; } else if (winD.substring(0, 3).equals(" " + symbolPlay + symbolPlay)) { r = 0; c = 0; set = true; } else if (winD.substring(3, 6).equals(symbolPlay + symbolPlay + " ")) { r = 0; c = 2; set = true; } else if (winD.substring(3, 6).equals(symbolPlay + " " + symbolPlay)) { r = 1; c = 1; set = true; } else if (winD.substring(3, 6).equals(" " + symbolPlay + symbolPlay)) { r = 2; c = 0; set = true; } if(r!=-1 && c!= -1){ int[] coord = new int[2]; coord[1]=r; coord[0]=c; return coord; }else return null; } public int[][] emptyIndexies(char[][] board) { int count = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == " ".charAt(0)) { count++; } } } int[][] array = new int[count][2]; count = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == " ".charAt(0)) { array[count][0] = i; array[count][1] = j; count++; } } } return array; } /* REQUEST COORDINATES FOR USER PLAYER */ public boolean requestCoord() { int aux; int x = 4; int y = 4; while (true) { System.out.print("Enter the number: "); if(!scanner.hasNextInt()){ System.out.println("invalid, just numbers allow"); } else{ aux = scanner.nextInt(); if ((aux>9 && aux <1) ) System.out.println("You should enter valid numbers (1-9) !"); else { break; } } } switch (aux){ case 1: x=1; y=1; break; case 2: x=2; y=1; break; case 3: x=3; y=1; break; case 4: x=1; y=2; break; case 5: x=2; y=2; break; case 6: x=3; y=2; break; case 7: x=1; y=3; break; case 8: x=2; y=3; break; case 9: x=3; y=3; break; } this.setSymbols(x, y); this.changeWhoPlay(); return true; } /* CHECK IF IS EMPTY (X,Y) * RETURN: TRUE / FALSE */ public boolean isEmpty(int x, int y) { int x1 = Math.abs(x - 1); int y1 = Math.abs(y - 3); return this.symbols[y1][x1] == " ".charAt(0); } /* PRINT ALL ARRAY OF SYMBOLS */ public void printGame() { for (int i = 0; i < 5; i++) { if (i == 0 || i == 4) System.out.println("---------"); else { System.out.print("| "); for (int j = 0; j < 3; j++) { System.out.print(symbols[i - 1][j] + " "); } System.out.print("|\n"); } } } /* SET SMBOLS BY COORDINATES */ public void setSymbols(int x, int y) { int x1 = Math.abs(x - 1); int y1 = Math.abs(y - 3); if (whoPlay == 0) { this.symbols[y1][x1] = "X".charAt(0); numX++; } else if (whoPlay == 1) { this.symbols[y1][x1] = "O".charAt(0); numO++; } } public void setSymbols(int r, int c, boolean aux) { if (aux) { if (whoPlay == 0) { this.symbols[c][r] = "X".charAt(0); numX++; } else if (whoPlay == 1) { this.symbols[c][r] = "O".charAt(0); numO++; } this.changeWhoPlay();//change turn } } /* CHECK IF GAME IS FINISHED AND PRINT*/ public boolean gameState() { boolean xWins = false; boolean oWins = false; String winV, winH, winD; /*Diagonal*/ winD = "" + this.symbols[0][0] + "" + this.symbols[1][1] + "" + this.symbols[2][2] + "" + this.symbols[0][2] + "" + this.symbols[1][1] + "" + this.symbols[2][0]; for (int i = 0; i < 3; i++) { /*vertical*/ winH = "" + this.symbols[i][0] + "" + this.symbols[i][1] + "" + this.symbols[i][2]; /*horizontal*/ winV = "" + this.symbols[0][i] + "" + this.symbols[1][i] + "" + this.symbols[2][i]; if (winV.equals("XXX") || winH.equals("XXX") || winD.substring(0, 3).equals("XXX") || winD.substring(3, 6).equals("XXX")) xWins = true; else if (winV.equals("OOO") || winH.equals("OOO") || winD.substring(0, 3).equals("OOO") || winD.substring(3, 6).equals("OOO")) oWins = true; } /* Print game state */ if (xWins && oWins || (Math.abs(numX - numO) > 1)) System.out.println("Impossible"); else if (xWins) System.out.println("X wins"); else if (oWins) System.out.println("O wins"); else if ((numO + numX) != 9) { //System.out.println("Move not finished"); return false; } else System.out.println("Draw"); return true; } /* CHANGE THE VALUE OF WHOPLAY VARIABLE*/ public void changeWhoPlay() { if (whoPlay == 0) whoPlay = 1; else if (whoPlay == 1) whoPlay = 0; } public char[][] getSymbols() { return symbols; } public int getWhoPlay() { return whoPlay; } }
ExalDraen/terraform-provider-solace
vendor/github.com/ExalDraen/semp-client/client/msg_vpn/get_msg_vpns_responses.go
<reponame>ExalDraen/terraform-provider-solace<filename>vendor/github.com/ExalDraen/semp-client/client/msg_vpn/get_msg_vpns_responses.go // Code generated by go-swagger; DO NOT EDIT. package msg_vpn // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "io" "github.com/go-openapi/runtime" strfmt "github.com/go-openapi/strfmt" models "github.com/ExalDraen/semp-client/models" ) // GetMsgVpnsReader is a Reader for the GetMsgVpns structure. type GetMsgVpnsReader struct { formats strfmt.Registry } // ReadResponse reads a server response into the received o. func (o *GetMsgVpnsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewGetMsgVpnsOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil default: result := NewGetMsgVpnsDefault(response.Code()) if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } if response.Code()/100 == 2 { return result, nil } return nil, result } } // NewGetMsgVpnsOK creates a GetMsgVpnsOK with default headers values func NewGetMsgVpnsOK() *GetMsgVpnsOK { return &GetMsgVpnsOK{} } /*GetMsgVpnsOK handles this case with default header values. The list of Message VPN objects' attributes, and the request metadata. */ type GetMsgVpnsOK struct { Payload *models.MsgVpnsResponse } func (o *GetMsgVpnsOK) Error() string { return fmt.Sprintf("[GET /msgVpns][%d] getMsgVpnsOK %+v", 200, o.Payload) } func (o *GetMsgVpnsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.MsgVpnsResponse) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetMsgVpnsDefault creates a GetMsgVpnsDefault with default headers values func NewGetMsgVpnsDefault(code int) *GetMsgVpnsDefault { return &GetMsgVpnsDefault{ _statusCode: code, } } /*GetMsgVpnsDefault handles this case with default header values. Error response */ type GetMsgVpnsDefault struct { _statusCode int Payload *models.SempMetaOnlyResponse } // Code gets the status code for the get msg vpns default response func (o *GetMsgVpnsDefault) Code() int { return o._statusCode } func (o *GetMsgVpnsDefault) Error() string { return fmt.Sprintf("[GET /msgVpns][%d] getMsgVpns default %+v", o._statusCode, o.Payload) } func (o *GetMsgVpnsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.SempMetaOnlyResponse) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil }
24601/Jest
src/main/java/io/searchbox/core/MultiSearch.java
package io.searchbox.core; import io.searchbox.AbstractAction; import io.searchbox.Action; import java.util.LinkedHashSet; import java.util.Set; /** * @author <NAME> */ public class MultiSearch extends AbstractAction implements Action { private final Set<Search> searchSet = new LinkedHashSet<Search>(); public void addSearch(Search search) { if (search != null) searchSet.add(search); } public boolean isSearchExist(Search search) { return searchSet.contains(search); } public void removeSearch(Search search) { searchSet.remove(search); } protected Object prepareBulk() { /* {"index" : "test"} {"query" : {"match_all" : {}}, "from" : 0, "size" : 10} {"index" : "test", "search_type" : "count"} {"query" : {"match_all" : {}}} {} {"query" : {"match_all" : {}}} */ StringBuilder sb = new StringBuilder(); for (Search search : searchSet) { if (search.indexSet.size() > 0) { for (String index : search.indexSet) { sb.append("{\"index\" : \"").append(index).append("\"}\n"); sb.append("{\"query\" : ").append(search.getData()).append("}\n"); } } else { sb.append("{}\n"); sb.append("{\"query\" : ").append(search.getData()).append("}\n"); } } return sb.toString(); } @Override public Object getData() { return prepareBulk(); } @Override public String getRestMethodName() { return "POST"; } @Override public String getURI() { return "/_msearch"; } }
Kishanpa3/OakCreekDB
app/uploaders/document_uploader.rb
# require "image_processing/vips" require "image_processing/mini_magick" class DocumentUploader < Shrine # plugins and uploading logic THUMBNAILS = { small: [300, 300], medium: [600, 600], } plugin :remove_attachment plugin :pretty_location, namespace: "/", identifier: :animal_id plugin :validation_helpers plugin :store_dimensions, log_subscriber: nil plugin :derivation_endpoint, prefix: "derivations/image" plugin :default_url plugin :remove_invalid # remove and delete files that failed validation # File validations (requires `validation_helpers` plugin) Attacher.validate do case file.mime_type when /^image\// validate_size 0..50*1024*1024 # 50 MB validate_extension %w[jpg jpeg png webp bmp gif ico cur tiff tif] if validate_mime_type %w[image/jpeg image/png image/webp image/bmp image/gif image/x-icon image/tiff] validate_max_dimensions [5000, 5000] # 5000x5000 end when /^video\// validate_size 0..1024*1024*1024 # 1 GB when /^audio\// validate_size 0..30*1024*1024 # 30 MB when /^application\// validate_size 0..1024*1024*1024 # 1 GB when /^text\// validate_size 0..20*1024*1024 # 20 MB end end # Thumbnails processor (requires `derivatives` plugin) Attacher.derivatives_processor do |original| THUMBNAILS.inject({}) do |result, (name, (width, height))| result.merge! name => THUMBNAILER.call(original, width, height, file.mime_type) end end # Default to dynamic thumbnail URL (requires `default_url` plugin) Attacher.default_url do |derivative: nil, **| file&.derivation_url(:thumbnail, *THUMBNAILS.fetch(derivative)) if derivative end # Dynamic thumbnail definition (requires `derivation_endpoint` plugin) derivation :thumbnail do |file, width, height| THUMBNAILER.call(file, width.to_i, height.to_i, source.mime_type) end THUMBNAILER = -> (file, width, height, type) do if type =~ /^image\// # ImageProcessing::Vips ImageProcessing::MiniMagick .source(file) .resize_to_limit!(width, height) end # case type # when /^image\// # # ImageProcessing::Vips # ImageProcessing::MiniMagick # .source(file) # .resize_to_limit!(width, height) # when /\/pdf$/ # # ImageProcessing::Vips # ImageProcessing::MiniMagick # .source(file) # .loader(page: 0) # specify page number # .resize_to_limit!(width, height) # end end end
tsani/goto
grading/typing/invalid/short_decl1.go
package main func main() { b, c := 2, 3 println(b, c) // No new decl on the lhs of a short decl b, c := 4, 5 println(b, c) }
jploot/jploot
jploot-cli/src/main/java/jploot/cli/InstallerCommand.java
package jploot.cli; import static com.pivovarit.function.ThrowingPredicate.unchecked; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.lang.ProcessBuilder.Redirect; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.PosixFilePermissions; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.pivovarit.function.ThrowingSupplier; import com.vdurmont.semver4j.Semver; import com.vdurmont.semver4j.Semver.SemverType; import com.vdurmont.semver4j.SemverException; import jploot.exceptions.InstallerException; import picocli.CommandLine.Command; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; @Command(name = "installer", mixinStandardHelpOptions = true, description = "Bootstrap jploot", hidden = true) public class InstallerCommand extends AbstractCommand { private static final Logger LOGGER = LoggerFactory.getLogger(InstallerCommand.class); @Option( names = "--java-home", description = { "Provides your own JVM", "Path must be a valid JAVA_HOME value" } ) Path javaHome; @Option( names = "--ignore-java-home", defaultValue = "false", description = { "Ignore JAVA_HOME environment variable" } ) boolean ignoreJavaHomeEnvironment; @Parameters(index = "0..1", description = { "Target folder for jploot installation" }, defaultValue = "${sys:user.home}/.local/share/jploot") Path target; @Option( names = "--activate", defaultValue = "true", description = { "Use --no-activate to disable bashrc activation" }) boolean activate; @Option( names = "--reset", defaultValue = "false", description = { "Remove an already existing jploot install" }) boolean reset; @Override public Integer doCall() { Optional<Path> jplootHomeSource = notBlankString(System.getenv("JPLOOT_HOME")).map(Path::of); if (jplootHomeSource.isEmpty() || !jplootHomeSource.get().toFile().isDirectory()) { LOGGER.error("This jploot installation does not support bootstraping"); LOGGER.error("Aborted"); return 1; } if (reset) { if (target.toFile().exists() && target.resolve("jvm").toFile().exists() && target.resolve("jploot").toFile().exists()) { deleteFolderRecursively(target); LOGGER.info("🔥 Jploot removed: {}", target); } else if (target.toFile().exists()) { LOGGER.error("Target {} exists but not removed as it is not a valid jploot folder. Aborted.", target); return 1; } } if (target.toFile().exists()) { LOGGER.warn("Target directory already exists. Jploot installation skipped"); } else { installJploot(jplootHomeSource.get(), target); LOGGER.info("📌 Jploot installed in {}", target); } Path targetJavaHome = target.resolve("jvm"); if (javaHome != null && !ignoreJavaHomeEnvironment && !validateJavaHome(javaHome)) { return 1; } else if (javaHome != null && !ignoreJavaHomeEnvironment) { targetJavaHome = javaHome; } installJplootScripts(target, targetJavaHome, activate); String activateCommand = String.format("source %s", target.resolve("bin/activate")); if (activate) { if (LOGGER.isInfoEnabled()) { LOGGER.info("⚡ Open a new terminal or load jploot with {}", activateCommand); } } else { LOGGER.info("⚡ Load jploot with {}", activateCommand); } LOGGER.info("⚡ Usage: jploot --help"); return 0; } @Override boolean needsConfig() { return false; } private static void installJploot(Path jplootJavaHome, Path target) { try { if (target.toFile().exists()) { LOGGER.warn("Jploot JRE already exists, skipping install: {}", target); } else { createIfNotExists(target); copyDirectory(jplootJavaHome, target); } } catch (IOException e) { throw new InstallerException("Error installing Jploot", e); } } private static void installJplootScripts(Path jplootHome, Path javaHome, boolean activate) { File binDir = jplootHome.resolve("bin").toFile(); if (!binDir.exists()) { binDir.mkdirs(); } try { Path activateCommandPath = installActivation(jplootHome); if (activate) { installBashrcActivation(activateCommandPath); } installBinJploot(jplootHome, javaHome); } catch (IOException e) { throw new InstallerException("Failed to install jploot scripts", e); } } private static void installBinJploot(Path jplootHome, Path javaHome) throws IOException { Path jplootBin = jplootHome.resolve("bin/jploot"); // create installer script String launcherScript; String resourcePath = "/jploot/scripts/jploot"; launcherScript = readResourceToString(resourcePath); String classpathString = "\"$JPLOOT_HOME/jploot/*\""; launcherScript = launcherScript.replace("[[JAVA_HOME]]", javaHome.toString()); launcherScript = launcherScript.replace("[[CLASSPATH]]", classpathString); launcherScript = launcherScript.replace("[[MAINCLASS]]", JplootMain.class.getName()); String jplootBinContent = ThrowingSupplier.<String>lifted(() -> Files.readString(jplootBin)).get().orElse(""); if (!launcherScript.equals(jplootBinContent)) { // install script and set execution permission Files.writeString( jplootBin, launcherScript, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); Files.setPosixFilePermissions(jplootBin, PosixFilePermissions.fromString("rwxr-xr-x")); LOGGER.debug("📌 Jploot runtime set to {}", javaHome); } else { LOGGER.trace("📌 Jploot runtime already set to {}", javaHome); } } private static void installBashrcActivation(Path activateCommandPath) throws IOException { Path bashrcFile = Path.of(System.getProperty("user.home"), ".bashrc"); if (!bashrcFile.toFile().exists()) { LOGGER.warn("Bashrc file {} not found. Activation script is not installed", bashrcFile); } else { Pattern pattern = Pattern.compile("## jploot activation block\n.*\n## /jploot activation block", Pattern.DOTALL); String activation = "## jploot activation block\n" + "JPLOOT_DISABLE_PROMPT=1\n" + String.format("source %s\n", activateCommandPath) + "## /jploot activation block"; if (updateFile(bashrcFile, pattern, activation)) { LOGGER.debug("📌 Jploot activation script added to {}", bashrcFile); } else { LOGGER.trace("📌 Jploot activation script already present in {}", bashrcFile); } } } private static Path installActivation(Path jplootHome) throws IOException { Path activateCommandPath = jplootHome.resolve("bin/activate"); String activateScript = readResourceToString("/jploot/scripts/activate"); Files.writeString( activateCommandPath, activateScript, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); return activateCommandPath; } private static boolean updateFile(Path source, Pattern pattern, String replacement) throws IOException { String bashrcContent = Files.readString(source); String updatedContent; Matcher matcher = pattern.matcher(bashrcContent); if (matcher.find()) { updatedContent = matcher.replaceFirst(replacement); } else { updatedContent = bashrcContent + "\n" + replacement + "\n"; } if (!bashrcContent.equals(updatedContent)) { Files.writeString(source, updatedContent, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); return true; } else { return false; } } private static String readResourceToString(String resourcePath) throws IOException { try (InputStream is = InstallerCommand.class.getResourceAsStream(resourcePath); InputStreamReader reader = new InputStreamReader(is); StringWriter writer = new StringWriter()) { reader.transferTo(writer); return writer.toString(); } } private static boolean validateJavaHome(Path runtimeJavaHomePath) { if (!runtimeJavaHomePath.toFile().isDirectory() || !runtimeJavaHomePath.resolve("bin/java").toFile().isFile()) { LOGGER.error("Missing JVM environment: {}", runtimeJavaHomePath); return false; } else { String output = extractJavaVersionOutput(runtimeJavaHomePath); if (output == null) { return false; } else { return validateVersion(output); } } } private static String extractJavaVersionOutput(Path runtimeJavaHomePath) { String output = null; List<String> command = List.of(runtimeJavaHomePath.resolve("bin/java").toString(), "-version"); try { Process process = new ProcessBuilder(command).redirectOutput(Redirect.DISCARD) .redirectError(Redirect.PIPE) .start(); try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { while (process.isAlive()) { process.getErrorStream().transferTo(outputStream); } int status = process.waitFor(); if (status != 0) { LOGGER.error("Error running JVM {}", runtimeJavaHomePath); } output = outputStream.toString(); } catch (InterruptedException e1) { LOGGER.error("Process interrupted while checking JVM version"); Thread.currentThread().interrupt(); } } catch (IOException e) { LOGGER.error("Error running JVM {}", runtimeJavaHomePath, e); } return output; } private static boolean validateVersion(String output) { Optional<String> rawVersion = output.lines() .filter(l -> l.contains("openjdk version")) .findFirst() .<String>map(l -> Pattern.compile("(?<=\")[^\"]+(?=\")") .matcher(l).results() .findFirst().map(MatchResult::group).orElse(null)); Optional<Semver> version; Throwable versionException = null; try { version = rawVersion.map(v -> new Semver(v.replace("_", "+"), SemverType.LOOSE)); } catch (SemverException e) { version = Optional.empty(); versionException = e; } if (version.isPresent() && version.get().isGreaterThan(new Semver("11.0.0"))) { return true; } else { if (rawVersion.isPresent()) { if (version.isEmpty()) { LOGGER.error("JVM version cannot be parsed: {}", rawVersion.get(), versionException); } else { LOGGER.error("JVM version does not match requirement: {} < 11", rawVersion.get()); } } else { LOGGER.error("JVM version cannot be extracted: {}", output); } return false; } } public static Optional<String> notBlankString(String value) { if (value == null || value.isBlank()) { return Optional.empty(); } else { return Optional.of(value); } } private static void copyDirectory(Path jplootHomePath, Path target) throws IOException { Path binDir = jplootHomePath.resolve("bin"); copyFilesRecursively(jplootHomePath, target, binDir); } private static void copyFilesRecursively(Path rootFolder, Path targetFolder, Path... ignore) { Predicate<Path> isIgnoredFolder = d -> Arrays.stream(ignore).anyMatch(unchecked(i -> Files.isSameFile(d, i))); try { Files.walkFileTree(rootFolder, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (isIgnoredFolder.test(dir)) { return FileVisitResult.SKIP_SUBTREE; } else { copy(dir); return FileVisitResult.CONTINUE; } } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { copy(file); return FileVisitResult.CONTINUE; } private void copy(Path file) throws IOException { Files.copy(file, targetFolder.resolve(rootFolder.relativize(file)), StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { throw new InstallerException( String.format("Failed to copy %s to %s: %s", rootFolder, targetFolder, file), exc); } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; }}); } catch (IOException e) { LOGGER.error(String.format("Error deleting temp directory %s", rootFolder), e); } } private void deleteFolderRecursively(Path folder) { try { Files.walkFileTree(folder, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.deleteIfExists(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; }}); } catch (IOException e) { LOGGER.error(String.format("Error deleting temp directory %s", folder), e); } } private static void createIfNotExists(Path target) { File file = target.toFile(); if (!file.isDirectory()) { file.mkdirs(); } } }
Kahsolt/OJ-Notes
Notes/Matrix/triband_matrix.c
#include <stdio.h> #define MAXN 4 // 2017-11-21 // 三对角矩阵的线性存储 // 矩阵规模: (MAXN*MAXN) => (3*MAXN-2)个非零元素 int matrix[3 * MAXN - 2] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, }; void index(int x, int y) { if (abs(x-y) > 1) puts("NULL"); else printf("idx=%d\n", 2*x + y); } void ordinate(int idx) { printf("x=%d y=%d\n", (idx+1)/3, (idx+1)/3 + (idx+1)%3 - 1); } int main() { index(1,1); index(1,2); ordinate(4); ordinate(8); }
raghavgarg098/git-plugin
src/test/java/hudson/plugins/git/extensions/impl/WipeWorkspaceTest.java
<filename>src/test/java/hudson/plugins/git/extensions/impl/WipeWorkspaceTest.java package hudson.plugins.git.extensions.impl; import hudson.EnvVars; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Result; import hudson.plugins.git.TestGitRepo; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionTest; import java.util.List; import nl.jqno.equalsverifier.EqualsVerifier; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; import org.jvnet.hudson.test.WithoutJenkins; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; public class WipeWorkspaceTest extends GitSCMExtensionTest { TestGitRepo repo; GitClient git; @Override public void before() throws Exception { // do nothing } @Override protected GitSCMExtension getExtension() { return new WipeWorkspace(); } /** * Test to confirm the behavior of forcing re-clone before checkout by cleaning the workspace first. **/ @Test public void testWipeWorkspace() throws Exception { repo = new TestGitRepo("repo", tmp.newFolder(), listener); git = Git.with(listener, new EnvVars()).in(repo.gitDir).getClient(); FreeStyleProject projectWithMaster = setupBasicProject(repo); git.commit("First commit"); FreeStyleBuild build = build(projectWithMaster, Result.SUCCESS); List<String> buildLog = build.getLog(175); assertThat(buildLog, hasItem("Wiping out workspace first.")); } @Test @WithoutJenkins public void equalsContract() { EqualsVerifier.forClass(WipeWorkspace.class) .usingGetClass() .verify(); } }
FabienCont/flappy
sources/game/scripts/snippets/demo/set-best-score.js
<reponame>FabienCont/flappy<gh_stars>0 import * as memory from 'modules/memory'; export default function setBestScore() { const bestScoreSaved = memory.get('bestScore'); if (bestScoreSaved !== undefined) { return bestScoreSaved; } return 0; }
lechium/tvOS130Headers
System/Library/PrivateFrameworks/UIKitCore.framework/_UISwipeAnimationFactory.h
/* * This header is generated by classdump-dyld 1.0 * on Tuesday, November 5, 2019 at 2:46:11 AM Mountain Standard Time * Operating System: Version 13.0 (Build 17J586) * Image Source: /System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <UIKitCore/UIKitCore-Structs.h> @interface _UISwipeAnimationFactory : NSObject +(id)_animatorForStiffnessFactor:(double)arg1 initialVelocity:(CGVector)arg2 ; +(id)_animatorForDuration:(double)arg1 initialVelocity:(CGVector)arg2 ; +(id)animatorForMoveWithOccurrence:(id)arg1 ; +(id)animatorForTentativeWithOccurrence:(id)arg1 ; +(id)animatorForCollapseWithOccurrence:(id)arg1 ; @end
itcosplay/cryptobot
keyboards/default/admin_keyboard.py
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton def create_kb_coustom_main_menu(user_id): from loader import db from data.config import super_admins if not user_id in super_admins: user_status = db.get_user_status(id=user_id) else: user_status = 'admin' keyboard = ReplyKeyboardMarkup() if user_status == 'admin': keyboard.add(KeyboardButton(text='права пользователей')) keyboard.insert(KeyboardButton(text='информация о смс')) keyboard.add(KeyboardButton(text='создать заявку')) keyboard.insert(KeyboardButton(text='в работе')) keyboard.add(KeyboardButton(text='пропуска')) keyboard.insert(KeyboardButton(text='создать пропуск')) keyboard.add(KeyboardButton(text='балансы')) keyboard.insert(KeyboardButton(text='отчетность')) elif user_status == 'changer': keyboard.add(KeyboardButton(text='создать заявку')) keyboard.insert(KeyboardButton(text='в работе')) keyboard.add(KeyboardButton(text='пропуска')) keyboard.insert(KeyboardButton(text='создать пропуск')) keyboard.add(KeyboardButton(text='балансы')) keyboard.insert(KeyboardButton(text='отчетность')) elif user_status == 'executor': keyboard.add(KeyboardButton(text='в работе')) keyboard.add(KeyboardButton(text='балансы')) keyboard.add(KeyboardButton(text='отчетность')) elif user_status == 'secretary': keyboard.add(KeyboardButton(text='информация о смс')) keyboard.add(KeyboardButton(text='пропуска')) keyboard.add(KeyboardButton(text='создать пропуск')) elif user_status == 'permit': keyboard.add(KeyboardButton(text='создать пропуск')) else: pass keyboard.resize_keyboard = True keyboard.one_time_keyboard = True return keyboard # main_menu = ReplyKeyboardMarkup ( # keyboard = [ # [ # KeyboardButton(text='права пользователей'), # KeyboardButton(text='информация о смс') # ], # [ # KeyboardButton(text='создать заявку'), # KeyboardButton(text='в работе') # ], # [ # KeyboardButton(text='пропуска'), # ] # ], # resize_keyboard=True, # one_time_keyboard=True # )
zigapk/adventofcode
2020/day_19/one.py
<reponame>zigapk/adventofcode<gh_stars>0 rules = {} lines = [l.strip() for l in open('in', 'r').readlines()] rule_lines = lines[:lines.index('')] message_lines = lines[lines.index('') + 1:] for line in rule_lines: rule_id, rule = line.split(':') rule = rule.strip() rules[rule_id] = rule def generate_options(rule): if '"' in rule: return [rule.replace('"', '')] if '|' in rule: parts = [part.strip() for part in rule.split('|')] res = [] for part in parts: res += generate_options(part) return res subrules = rule.split() res = [] for i in range(len(subrules)): current = subrules[i] if i == 0: res = generate_options(rules[current]) else: new_res = [] cross = generate_options(rules[current]) for a in res: for b in cross: new_res.append(a + b) res = new_res return res options = generate_options(rules['0']) count = 0 for message in message_lines: if message in options: count += 1 print(count)
bradennapier/redux-saga-process
src/generators.js
export { nilReducer, reducerReducer, arrayMapReducer, objectMapReducer, nestedObjectMapReducer, objectWildcardMapReducer, } from './process-lib/reducerGenerators'
10088/alipay-sdk-java-all
src/main/java/com/alipay/api/domain/GoodExpirationListDTO.java
<gh_stars>0 package com.alipay.api.domain; import java.util.Date; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 临期食品列表 * * @author auto create * @since 1.0, 2022-03-14 15:42:05 */ public class GoodExpirationListDTO extends AlipayObject { private static final long serialVersionUID = 3676239834272858492L; /** * 商品有效时长,单位:天,有临期食品时可填写,非必填。 */ @ApiField("good_effective_duration") private Long goodEffectiveDuration; /** * 商品有效截止时间(商品过期时间),有临期食品时可填写,非必填。时间格式 yyyy-MM-dd HH:mm:ss */ @ApiField("good_expiration_time") private Date goodExpirationTime; /** * 商品生产时间,有临期食品时可填写,非必填。时间格式 yyyy-MM-dd HH:mm:ss */ @ApiField("good_prd_time") private Date goodPrdTime; public Long getGoodEffectiveDuration() { return this.goodEffectiveDuration; } public void setGoodEffectiveDuration(Long goodEffectiveDuration) { this.goodEffectiveDuration = goodEffectiveDuration; } public Date getGoodExpirationTime() { return this.goodExpirationTime; } public void setGoodExpirationTime(Date goodExpirationTime) { this.goodExpirationTime = goodExpirationTime; } public Date getGoodPrdTime() { return this.goodPrdTime; } public void setGoodPrdTime(Date goodPrdTime) { this.goodPrdTime = goodPrdTime; } }
liuxc123/GTUIKit
components/CommonComponent/TabBar/src/TitleImage/GTUITabBarTitleImageView.h
<reponame>liuxc123/GTUIKit // // GTUITabBarTitleImageView.h // GTCatalog // // Created by liuxc on 2018/12/9. // #import "GTUITabBarTitleView.h" #import "GTUITabBarTitleImageCell.h" #import "GTUITabBarTitleImageCellModel.h" NS_ASSUME_NONNULL_BEGIN @interface GTUITabBarTitleImageView : GTUITabBarTitleView @property (nonatomic, strong) NSArray <NSString *>*imageNames; @property (nonatomic, strong) NSArray <NSURL *>*imageURLs; @property (nonatomic, strong) NSArray <NSString *>*selectedImageNames; @property (nonatomic, strong) NSArray <NSURL *>*selectedImageURLs; @property (nonatomic, strong) NSArray <NSNumber *> *imageTypes; //默认GTUITabBarTitleImageType_LeftImage @property (nonatomic, copy, nullable) void(^loadImageCallback)(UIImageView *imageView, NSURL *imageURL); //使用imageURL从远端下载图片进行加载,建议使用SDWebImage等第三方库进行下载。 @property (nonatomic, assign) CGSize imageSize; //默认CGSizeMake(20, 20) @property (nonatomic, assign) CGFloat titleImageSpacing; //titleLabel和ImageView的间距,默认5 @property (nonatomic, assign) BOOL imageZoomEnabled; //默认为NO @property (nonatomic, assign) CGFloat imageZoomScale; //默认1.2,imageZoomEnabled为YES才生效 @end NS_ASSUME_NONNULL_END
ethulhu/helix
upnpav/connectionmanager/messages.go
// SPDX-FileCopyrightText: 2020 <NAME> // // SPDX-License-Identifier: MIT package connectionmanager import ( "encoding/xml" "fmt" "strings" "github.com/ethulhu/helix/upnpav" "github.com/ethulhu/helix/xmltypes" ) type ( commaSeparatedProtocolInfos []upnpav.ProtocolInfo direction string status string getProtocolInfoRequest struct { XMLName xml.Name `xml:"urn:schemas-upnp-org:service:ConnectionManager:1 GetProtocolInfo"` } getProtocolInfoResponse struct { XMLName xml.Name `xml:"urn:schemas-upnp-org:service:ConnectionManager:1 GetProtocolInfoResponse"` Sources commaSeparatedProtocolInfos `xml:"Source" scpd:"SourceProtocolInfo,string"` Sinks commaSeparatedProtocolInfos `xml:"Sink" scpd:"SinkProtocolInfo,string"` } prepareForConnectionRequest struct { XMLName xml.Name `xml:"urn:schemas-upnp-org:service:ConnectionManager:1 PrepareForConnection"` RemoteProtocolInfo string `xml:"RemoteProtocolInfo" scpd:"A_ARG_TYPE_ProtocolInfo,string"` PeerConnectionManager string `xml:"PeerConnectionManager" scpd:"A_ARG_TYPE_ConnectionManager,string"` PeerConnectionID int `xml:"PeerConnectionID" scpd:"A_ARG_TYPE_ConnectionID,i4"` Direction direction `xml:"Direction" scpd:"A_ARG_TYPE_Direction,string,Input|Output"` } prepareForConnectionResponse struct { XMLName xml.Name `xml:"urn:schemas-upnp-org:service:ConnectionManager:1 PrepareForConnectionResponse"` ConnectionID int `xml:"ConnectionID" scpd:"A_ARG_TYPE_ConnectionID,i4"` AVTransportID int `xml:"AVTransportID" scpd:"A_ARG_TYPE_AVTransportID,i4"` ResID int `xml:"ResID" scpd:"A_ARG_TYPE_ResID,i4"` } connectionCompleteRequest struct { XMLName xml.Name `xml:"urn:schemas-upnp-org:service:ConnectionManager:1 ConnectionComplete"` ConnectionID int `xml:"ConnectionID" scpd:"A_ARG_TYPE_ConnectionID,i4"` } connectionCompleteResponse struct { XMLName xml.Name `xml:"urn:schemas-upnp-org:service:ConnectionManager:1 ConnectionCompleteResponse"` } getCurrentConnectionIDsRequest struct { XMLName xml.Name `xml:"urn:schemas-upnp-org:service:ConnectionManager:1 GetCurrentConnectionIDs"` } getCurrentConnectionIDsResponse struct { XMLName xml.Name `xml:"urn:schemas-upnp-org:service:ConnectionManager:1 GetCurrentConnectionIDsResponse"` ConnectionIDs xmltypes.CommaSeparatedInts `xml:"ConnectionIDs" scpd:"CurrentConnectionIDs,string"` } getCurrentConnectionInfoRequest struct { XMLName xml.Name `xml:"urn:schemas-upnp-org:service:ConnectionManager:1 GetCurrentConnectionInfo"` ConnectionID int `xml:"ConnectionID" scpd:"A_ARG_TYPE_ConnectionID,i4"` } getCurrentConnectionInfoResponse struct { XMLName xml.Name `xml:"urn:schemas-upnp-org:service:ConnectionManager:1 GetCurrentConnectionInfoResponse"` AVTransportID int `xml:"AVTransportID" scpd:"A_ARG_TYPE_AVTransportID,i4"` ResID int `xml:"ResID" scpd:"A_ARG_TYPE_ResID,i4"` ProtocolInfo string `xml:"ProtocolInfo" scpd:"A_ARG_TYPE_ProtocolInfo,string"` PeerConnecitonManager string `xml:"PeerConnecitonManager" scpd:"A_ARG_TYPE_ConnectionManager,string"` PeerConnecitonID int `xml:"PeerConnecitonID" scpd:"A_ARG_TYPE_ConnectionID,i4"` Direction direction `xml:"Direction" scpd:"A_ARG_TYPE_Direction,string,Input|Output"` Status status `xml:"Status" scpd:"A_ARG_TYPE_ConnectionStatus,string,OK|ContentFormatMismatch|InsufficientBandwidth|UnreliableChannel|Unknown"` } ) const ( input = direction("Input") output = direction("Output") ) const ( ok = status("OK") contentFormatMismatch = status("ContentFormatMismatch") insufficientBandwidth = status("InsufficientBandwidth") unreliableChannel = status("UnreliableChannel") unknown = status("Unknown") ) const ( getProtocolInfo = "GetProtocolInfo" prepareForConnection = "PrepareForConnection" connectionComplete = "ConnectionComplete" getCurrentConnectionIDs = "GetCurrentConnectionIDs" getCurrentConnectionInfo = "GetCurrentConnectionInfo" ) func (cspi commaSeparatedProtocolInfos) MarshalText() ([]byte, error) { var piStrings []string for _, p := range cspi { piStrings = append(piStrings, p.String()) } return []byte(strings.Join(piStrings, ",")), nil } func (cspi *commaSeparatedProtocolInfos) UnmarshalText(raw []byte) error { if len(raw) == 0 { *cspi = nil return nil } var protocolInfos []upnpav.ProtocolInfo for _, p := range strings.Split(string(raw), ",") { protocolInfo, err := upnpav.ParseProtocolInfo(p) if err != nil { return fmt.Errorf("could not parse ProtocolInfo %q: %v", p, err) } protocolInfos = append(protocolInfos, protocolInfo) } *cspi = protocolInfos return nil }
pistolove/Lettcode
lettcode/src/reflect/Main.java
<filename>lettcode/src/reflect/Main.java package reflect; import java.io.File; import java.lang.reflect.Field; public class Main { public static void main(String[] args) { String root = "/Users/liqqc/git/mobile/xserver/xserver-lib/src/main/java/xserver/lib/tp"; File rfile = new File(root); if (rfile.exists()) { getConFiles(rfile); } } private static void getConFiles(File dir) { if (dir != null) { File[] listFiles = dir.listFiles(); for (File file : listFiles) { if (file.isFile() && file.getAbsolutePath().endsWith("Request.java")) { getPrams(file); } else if (file.isDirectory()) { getConFiles(file); } } } } private static void getPrams(File file) { String path = file.getAbsolutePath(); try { Class<?> clazz = Class.forName(path.replace(".java", "").replace("/", ".").substring(1)); Object obj = clazz.newInstance(); Field[] fields = clazz.getDeclaredFields(); for (int j = 0; j < fields.length; j++) { fields[j].setAccessible(true); // 字段名 System.out.print(fields[j].getName() + ":"); // 字段值 System.out.print(fields[j].get(obj) + " "); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { e.printStackTrace(); } } }
ApowoGames/phaser-ui
lib/ui/menu/Menu.js
import Buttons from '../buttons/Buttons.js'; import Methods from './Methods.js'; import CreateBackground from './CreateBackground.js'; import CreateButtons from './CreateButtons.js'; import GetDefaultBounds from '../../plugins/utils/defaultbounds/GetDefaultBounds.js'; import MenuSetInteractive from './MenuSetInteractive.js'; import GetEaseConfig from './GetEaseConfig.js'; const GetValue = Phaser.Utils.Objects.GetValue; class Menu extends Buttons { constructor(scene, config) { if (config === undefined) { config = {}; } // Orientation if (!config.hasOwnProperty('orientation')) { config.orientation = 1; // y } // Parent var rootMenu = config._rootMenu; var parentMenu = config._parentMenu; var parentButton = config._parentButton; // Items var items = GetValue(config, 'items', undefined); // Background var createBackgroundCallback = GetValue(config, 'createBackgroundCallback', undefined); var createBackgroundCallbackScope = GetValue(config, 'createBackgroundCallbackScope', undefined); config.background = CreateBackground(scene, items, createBackgroundCallback, createBackgroundCallbackScope); // Buttons var createButtonCallback = GetValue(config, 'createButtonCallback', undefined); var createButtonCallbackScope = GetValue(config, 'createButtonCallbackScope', undefined); config.buttons = CreateButtons(scene, items, createButtonCallback, createButtonCallbackScope); super(scene, config); this.type = 'TooqingMenu'; this.items = items; this.root = (rootMenu === undefined) ? this : rootMenu; this.parentMenu = parentMenu; this.parentButton = parentButton; var isRootMenu = (this.root === this); if (isRootMenu) { // Bounds var bounds = config.bounds; if (bounds === undefined) { bounds = GetDefaultBounds(scene); } this.bounds = bounds; // Expand mode this.expandEventName = GetValue(config, 'expandEvent', 'button.click'); // toggleOrientation mode this.toggleOrientation = GetValue(config, 'toggleOrientation', false); // Transition this.easeIn = GetValue(config, 'easeIn', 0); if (typeof (this.easeIn) === 'number') { this.easeIn = { duration: this.easeIn }; } this.easeOut = GetValue(config, 'easeOut', 0); if (typeof (this.easeOut) === 'number') { this.easeOut = { duration: this.easeOut }; } // Callbacks this.createBackgroundCallback = createBackgroundCallback; this.createBackgroundCallbackScope = createBackgroundCallbackScope; this.createButtonCallback = createButtonCallback; this.createButtonCallbackScope = createButtonCallbackScope; // Event flag this._isPassedEvent = false; } this .setOrigin(0) .layout(); var bounds = this.root.bounds; // Align to parentButton if (isRootMenu) { this.expandOrientation = [ ((this.y < bounds.centerY) ? 1 : 3), // Expand down(1)/up(3) ((this.x < bounds.centerX) ? 0 : 2) // Expand right(0)/left(2) ]; } else { // Sub-menu, align to parent button var expandOrientation = this.root.expandOrientation[parentMenu.orientation]; switch (expandOrientation) { case 0: //Expand right this.alignTop(parentButton.top).alignLeft(parentButton.right); break; case 1: //Expand down this.alignLeft(parentButton.left).alignTop(parentButton.bottom); break; case 2: //Expand left this.alignTop(parentButton.top).alignRight(parentButton.left); break; case 3: //Expand up this.alignLeft(parentButton.left).alignBottom(parentButton.top); break; } } this.pushIntoBounds(bounds); MenuSetInteractive(this); // Ease in menu this.popUp(GetEaseConfig(this, this.root.easeIn)); } isInTouching(pointer) { if (super.isInTouching(pointer)) { return true; } else if (this.childrenMap.subMenu) { return this.childrenMap.subMenu.isInTouching(pointer); } else { return false; } } } Object.assign( Menu.prototype, Methods ); export default Menu;
enriqueescobar-askida/Kinito.Ruby.Patterns
chap09/ex7a_change_instance_demo.rb
<reponame>enriqueescobar-askida/Kinito.Ruby.Patterns<filename>chap09/ex7a_change_instance_demo.rb #!/usr/bin/env ruby require '../example' require 'ex3_renderer' example %q{ bto = BritishTextObject.new('hello', 50.8, :blue) def bto.color colour end def bto.text string end # ... def bto.size_inches return size_mm/25.4 end puts bto.text puts bto.color puts bto.size_inches }
deduper/raml-java-tools
raml-to-pojo-maven-example/src/test/java/foo/foo/impl/UnionsWithNullTest.java
<filename>raml-to-pojo-maven-example/src/test/java/foo/foo/impl/UnionsWithNullTest.java package foo.foo.impl; import foo.foo.NilUnionType; import foo.foo.NilUnionTypeImpl; import org.junit.Test; import static org.junit.Assert.assertTrue; /** * Created. There, you have it. */ public class UnionsWithNullTest { @Test public void simple() { NilUnionType type = new NilUnionTypeImpl(); assertTrue(type.isNil()); } }
friendlyhj/CraftTweaker
src/main/java/com/blamejared/crafttweaker/impl/util/DamageSourceHelper.java
<filename>src/main/java/com/blamejared/crafttweaker/impl/util/DamageSourceHelper.java package com.blamejared.crafttweaker.impl.util; import com.blamejared.crafttweaker.api.annotations.ZenRegister; import com.blamejared.crafttweaker_annotations.annotations.Document; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.DamageSource; import org.openzen.zencode.java.ZenCodeType; /** * The class has some static methods to create some specific damage sources. */ @ZenRegister @Document("vanilla/api/util/DamageSourceHelper") @ZenCodeType.Name("crafttweaker.api.util.DamageSourceHelper") public class DamageSourceHelper { @ZenCodeType.Method public static DamageSource causeBeeStingDamage(LivingEntity bee) { return DamageSource.causeBeeStingDamage(bee); } @ZenCodeType.Method public static DamageSource causeMobDamage(LivingEntity mob) { return DamageSource.causeMobDamage(mob); } @ZenCodeType.Method public static DamageSource causeIndirectDamage(Entity source, LivingEntity indirectEntityIn) { return DamageSource.causeIndirectDamage(source, indirectEntityIn); } @ZenCodeType.Method public static DamageSource causePlayerDamage(PlayerEntity player) { return DamageSource.causePlayerDamage(player); } }
jason-neal/companion_simulations
mingle/models/broadcasted_models.py
"""Companion simulation models using Broadcasting.""" import numpy as np from scipy.interpolate import interp1d def one_comp_model(wav, model1, *, gammas=None): """Make 1 component simulations, broadcasting over gamma values.""" # Enable single scalar inputs (turn to 1d np.array) gammas = check_broadcastable(gammas).squeeze(axis=1) m1 = model1 m1g = np.empty(model1.shape + (len(gammas),)) # am2rvm1g = am2rvm1 with gamma doppler-shift for j, gamma in enumerate(gammas): wav_j = (1 + gamma / 299792.458) * wav m1g[:, j] = interp1d(wav_j, m1, axis=0, bounds_error=False)(wav) assert m1g.shape == (len(model1), len(gammas)), "Dimensions of broadcast output not correct" return interp1d(wav, m1g, axis=0) # pass it the wavelength values to return def check_broadcastable(var): # My version of broadcastable with 1s on the right var = np.atleast_2d(var) v_shape = var.shape # to make it (N, 1) if v_shape[0] == 1 and v_shape[0] < v_shape[1]: var = np.swapaxes(var, 0, 1) return var def two_comp_model(wav, model1, model2, *, alphas=None, rvs=None, gammas=None, kind="quadratic"): """Make 2 component simulations, broadcasting over alpha, rv, gamma values.""" # Enable single scalar inputs (turn to 1d np.array) alphas = check_broadcastable(alphas).squeeze(axis=1) rvs = check_broadcastable(rvs).squeeze(axis=1) gammas = check_broadcastable(gammas).squeeze(axis=1) am2 = model2[:, np.newaxis] * alphas # alpha * Model2 (am2) am2rv = np.empty(am2.shape + (len(rvs),)) # am2rv = am2 with rv doppler-shift for i, rv in enumerate(rvs): wav_i = (1 + rv / 299792.458) * wav am2rv[:, :, i] = interp1d(wav_i, am2, axis=0, kind=kind, bounds_error=False)(wav) # Normalize by (1 / 1 + alpha) am2rv = am2rv / (1 + alphas)[np.newaxis, :, np.newaxis] am2rvm1 = model1[:, np.newaxis, np.newaxis] + am2rv # am2rvm1 = am2rv + model_1 am2rvm1g = np.empty(am2rvm1.shape + (len(gammas),)) # am2rvm1g = am2rvm1 with gamma doppler-shift for j, gamma in enumerate(gammas): wav_j = (1 + gamma / 299792.458) * wav am2rvm1g[:, :, :, j] = interp1d(wav_j, am2rvm1, kind=kind, axis=0, bounds_error=False)(wav) assert am2rvm1g.shape == (len(model1), len(alphas), len(rvs), len(gammas)), "Dimensions of broadcast not correct" return interp1d(wav, am2rvm1g, kind=kind, bounds_error=False, axis=0) # pass it the wavelength values to return def two_comp_model_with_transpose(wav, model1, model2, alphas, *, rvs=None, gammas=None): """Make 2 component simulations, broadcasting over alpha, rv, gamma values.""" # Enable single scalar inputs (turn to 1d np.array) alphas = check_broadcastable(alphas) rvs = check_broadcastable(rvs) gammas = check_broadcastable(gammas) am2 = (model2.T * alphas.T).T # alpha * Model2 (am2) am2rv = np.empty(am2.shape + (len(rvs),)) # am2rv = am2 with rv doppler-shift for i, rv in enumerate(rvs): wav_i = (1 + rv / 299792.458) * wav am2rv[:, :, i] = interp1d(wav_i, am2, axis=0, bounds_error=False)(wav) # Normalize by (1 / 1 + alpha) am2rv = am2rv / (1 + alphas)[np.newaxis, :, np.newaxis] am2rvm1 = (model1.T + am2rv.T).T # am2rvm1 = am2rv + model_1 am2rvm1g = np.empty(am2rvm1.shape + (len(gammas),)) # am2rvm1g = am2rvm1 with gamma doppler-shift for j, gamma in enumerate(gammas): wav_j = (1 + gamma / 299792.458) * wav am2rvm1g[:, :, :, j] = interp1d(wav_j, am2rvm1, axis=0, bounds_error=False)(wav) assert am2rvm1g.shape == (len(model1), len(alphas), len(rvs), len(gammas)), "Dimensions of broadcast not correct" return interp1d(wav, am2rvm1g, axis=0) # pass it the wavelength values to return def inherent_alpha_model(wav, model1, model2, *, rvs=None, gammas=None, kind="linear"): """Make 2 component simulations, broadcasting over, rv, gamma values.""" # Enable single scalar inputs (turn to 1d np.array) rvs = check_broadcastable(rvs) gammas = check_broadcastable(gammas) # am2 = (model2.T * alphas.T).T # alpha * Model2 (am2) m2rv = np.empty(model2.shape + (len(rvs),)) # m2rv = model2 with rv doppler-shift for i, rv in enumerate(rvs): wav_i = (1 + rv / 299792.458) * wav m2rv[:, i] = interp1d(wav_i, model2, axis=0, kind=kind, bounds_error=False)(wav) # print("number of values not finite after doppler shift 1", np.sum(~np.isfinite(m2rv))) # print("m2rv shape", m2rv.shape) # print("locations not finite", np.where(~np.isfinite(m2rv))) # assert np.all(np.isfinite(m2rv)) m2rvm1 = (model1.T + m2rv.T).T # m2rvm1 = am2rv + model_1 m2rvm1g = np.empty(m2rvm1.shape + (len(gammas),)) # m2rvm1g = m2rvm1 with gamma doppler-shift for j, gamma in enumerate(gammas): wav_j = (1 + gamma / 299792.458) * wav m2rvm1g[:, :, j] = interp1d(wav_j, m2rvm1, axis=0, kind=kind, bounds_error=False)(wav) # assert np.all(np.isfinite(m2rvm1g)) # print("number of values not finite after doppler shift 2", np.sum(~np.isfinite(m2rvm1g))) # print("m2rvm1g shape", m2rvm1g.shape) # print("locations not finite", np.where(~np.isfinite(m2rv))) assert m2rvm1g.shape == (len(model1), len(rvs), len(gammas)), "Dimensions of broadcast not correct" return interp1d(wav, m2rvm1g, kind=kind, axis=0, bounds_error=False) # pass it the wavelength values to return # return interp1d(wav, m2rvm1g, axis=0) # pass it the wavelength values to return #
IDontHaveAnyClueWhatToPutHere/ce218-InconvenientSpaceRocks
src/GamePackage/Models/LiterallyJustTheOpeningCredits.java
package GamePackage.Models; import java.io.*; import java.util.ArrayList; class LiterallyJustTheOpeningCredits { static ArrayList<String> OPENING_CREDITS; static { //if it wasn't obvious, yes, this was repurposed from the HighScoreHandler OPENING_CREDITS = new ArrayList<>(); try{ //FileReader fr = new FileReader("textAssets/openingTitleCrawlThing.txt"); //BufferedReader br = new BufferedReader(fr); InputStream in = LiterallyJustTheOpeningCredits.class.getResourceAsStream("/textAssets/openingTitleCrawlThing.txt"); //Thanks, <NAME>! (https://stackoverflow.com/a/20389418) BufferedReader br = new BufferedReader(new InputStreamReader(in)); String currentString; //pretty much setting up the stuff for reading the file //until the end of the file is reached, it will add the current string to the file (even the empty ones) while ((currentString = br.readLine())!=null) { OPENING_CREDITS.add(currentString); } br.close(); //closes the bufferedReader } catch (IOException e) { e.printStackTrace(); } } }
lucasosouza/apps
Node/convenios/isolate-convenio-id.js
<filename>Node/convenios/isolate-convenio-id.js var fs = require('fs'); var http = require('http'); function getConvenioDetails() = { var detalhesConvenios = []; fs.readFile('convenios.json', function(err,data){ var convenios = JSON.parse(data); convenios.forEach(function(convenio){ queryFor(convenio["id"]) }); }); function queryFor(convenio) { query('http://api.convenios.gov.br/siconv/dados/convenio/' + convenio + '.json') } function query(path){ req = http.get(path, function(res){ var data = ""; res.on('readable', function(){ while ((chunk=res.read()) !== null){ data+=chunk; } }); res.on('end', function(){ detalhesConvenios.push(JSON.parse(data).convenios[0]); fs.writeFile('detalhesConvenios.json', JSON.stringify(detalhesConvenios)); }); }) .on('error', function(e) { console.log('Shit happened'); console.log(e); req.end(); }) } } module.exports = getConvenioDetails;
lujingwei002/coord
src/coord/gate/gate_promise.cc
<gh_stars>0 #include "coord/gate/gate_promise.h" #include "coord/coord.h" #include "coord/gate/gate.h" #include "coord/gate/gate_cluster.h" #include "coord/component/script_component.h" #include "coord/builtin/exception.h" #include "coord/builtin/base_request.h" namespace coord { namespace gate { CC_IMPLEMENT(GatePromise, "coord::gate::GatePromise") GatePromise* newGatePromise(Coord* coord) { GatePromise* pomise = new GatePromise(coord); return pomise; } GatePromise::GatePromise(Coord* coord) { this->coord = coord; this->resolveFunc = NULL; this->rejectFunc = NULL; this->reqTime = uv_hrtime(); this->resolveRef = 0; this->rejectRef = 0; this->requestUsing = NULL; } GatePromise::~GatePromise() { this->coord->coreLogDebug("[GatePromise] ~GatePromise"); if(this->resolveRef) { luaL_unref(this->coord->Script->L, LUA_REGISTRYINDEX, this->resolveRef); } if(this->rejectRef) { luaL_unref(this->coord->Script->L, LUA_REGISTRYINDEX, this->rejectRef); } if(this->requestUsing) { this->coord->Destory(this->requestUsing); this->requestUsing = NULL; } } GatePromise* GatePromise::Then(GatePromise_Resolve resolveFunc){ this->resolveFunc = resolveFunc; return this; } GatePromise* GatePromise::Else(GatePromise_Reject rejectFunc){ this->rejectFunc = rejectFunc; return this; } GatePromise* GatePromise::Using(BaseRequest* request) { if(this->requestUsing) { this->coord->Destory(this->requestUsing); this->requestUsing = NULL; } this->requestUsing = request; if(this->requestUsing) { this->coord->DontDestory(this->requestUsing); } return this; } GatePromise* GatePromise::Then(ScriptComponent* object, int ref) { if(this->resolveRef) { luaL_unref(this->coord->Script->L, LUA_REGISTRYINDEX, this->resolveRef); this->resolveRef = 0; } this->resolveRef = ref; this->resolveFunc = std::bind(&ScriptComponent::recvGatePromise, object, std::placeholders::_1, std::placeholders::_2, "recvGatePromise", ref); return this; } GatePromise* GatePromise::Else(ScriptComponent* object, int ref) { if(this->rejectRef) { luaL_unref(this->coord->Script->L, LUA_REGISTRYINDEX, this->rejectRef); this->rejectRef = 0; } this->rejectRef = ref; this->rejectFunc = std::bind(&ScriptComponent::recvGatePromise, object, std::placeholders::_1, std::placeholders::_2, "recvGatePromise", ref); return this; } void GatePromise::resolve(GateSession* session) { //this->coord->coreLogDebug("[GatePromise] resolve"); if(this->resolveFunc == NULL) { this->coord->coreLogDebug("[GatePromise] resolve failed, error='func not found'"); return; } try{ // this->coord->recoverRequestPipeline(this->pipeline); //传递到逻辑层 this->resolveFunc(session, this->requestUsing); // this->coord->popRequestPipeline(); } catch(ScriptException& e){ } } void GatePromise::reject(GateSession* session){ //this->coord->coreLogDebug("[GatePromise] reject"); if(this->rejectFunc == NULL) { this->coord->coreLogDebug("[GatePromise] reject failed, error='func not found'"); return; } try{ // this->coord->recoverRequestPipeline(this->pipeline); //传递到逻辑层 this->rejectFunc(session, this->requestUsing); // this->coord->popRequestPipeline(); } catch(ScriptException& e){ } } int GatePromise::Then(lua_State* L) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype(L,1,"coord::gate::GatePromise",0,&tolua_err) || !tolua_isusertype(L,2,"coord::ScriptComponent",0,&tolua_err) || !tolua_isfunction(L,3,0,&tolua_err) || !tolua_isnoobj(L,4,&tolua_err) ) goto tolua_lerror; else #endif { coord::ScriptComponent* object = ((coord::ScriptComponent*) tolua_tousertype(L,2,0)); lua_pushvalue(L, 3); int ref = luaL_ref(L, LUA_REGISTRYINDEX); if (ref < 0) { tolua_error(L, "error in function 'Then'.\nattempt to set a nil function", NULL); return 0; } GatePromise* tolua_ret = (GatePromise*) this->Then(object,ref); tolua_pushusertype(L,(void*)tolua_ret,"coord::gate::GatePromise"); } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(L,"#ferror in function 'Then'.",&tolua_err); return 0; #endif } int GatePromise::Else(lua_State* L) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype(L,1,"coord::gate::GatePromise",0,&tolua_err) || !tolua_isusertype(L,2,"coord::ScriptComponent",0,&tolua_err) || !tolua_isfunction(L,3,0,&tolua_err) || !tolua_isnoobj(L,4,&tolua_err) ) goto tolua_lerror; else #endif { coord::ScriptComponent* object = ((coord::ScriptComponent*) tolua_tousertype(L,2,0)); lua_pushvalue(L, 3); int ref = luaL_ref(L, LUA_REGISTRYINDEX); if (ref < 0) { tolua_error(L, "error in function 'Else'.\nattempt to set a nil function", NULL); return 0; } GatePromise* tolua_ret = (GatePromise*) this->Else(object,ref); tolua_pushusertype(L,(void*)tolua_ret,"coord::gate::GatePromise"); } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(L,"#ferror in function 'Else'.",&tolua_err); return 0; #endif } } }