code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
# # Copyright 2015, SUSE Linux 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. # require_relative "../../../../spec_helper" describe "Crowbar::Client::Command::Proposal::Create" do include_context "command_context" subject do ::Crowbar::Client::Command::Proposal::Create.new( stdin, stdout, stderr ) end it "should always return a request class" do subject.args[:barclamp] = "testing" subject.options[:merge] = true subject.options[:data] = "{}" stub_request(:get, "http://crowbar/crowbar/testing/1.0/proposals/template") .with( headers: { "Accept" => "application/json", "Content-Type" => "application/json" } ) .to_return( status: 200, body: "{}", headers: {} ) expect(subject.request).to( be_a( ::Crowbar::Client::Request::Proposal::Create ) ) end pending end
SUSE-Cloud/crowbar-client
spec/crowbar/client/command/proposal/create_spec.rb
Ruby
apache-2.0
1,440
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.exec; import java.io.IOException; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.ql.CompilationOpContext; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.plan.DynamicPartitionCtx; import org.apache.hadoop.hive.ql.plan.FileMergeDesc; import org.apache.hadoop.mapred.JobConf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; /** * Fast file merge operator for ORC and RCfile. This is an abstract class which * does not process any rows. Refer {@link org.apache.hadoop.hive.ql.exec.OrcFileMergeOperator} * or {@link org.apache.hadoop.hive.ql.exec.RCFileMergeOperator} for more details. */ public abstract class AbstractFileMergeOperator<T extends FileMergeDesc> extends Operator<T> implements Serializable { public static final String BACKUP_PREFIX = "_backup."; public static final String UNION_SUDBIR_PREFIX = "HIVE_UNION_SUBDIR_"; public static final Logger LOG = LoggerFactory.getLogger(AbstractFileMergeOperator.class); protected JobConf jc; protected FileSystem fs; private boolean autoDelete; private Path outPath; // The output path used by the subclasses. private Path finalPath; // Used as a final destination; same as outPath for MM tables. private Path dpPath; private Path tmpPath; // Only stored to update based on the original in fixTmpPath. private Path taskTmpPath; // Only stored to update based on the original in fixTmpPath. private int listBucketingDepth; private boolean hasDynamicPartitions; private boolean isListBucketingAlterTableConcatenate; private boolean tmpPathFixedConcatenate; private boolean tmpPathFixed; private Set<Path> incompatFileSet; private transient DynamicPartitionCtx dpCtx; private boolean isMmTable; private String taskId; /** Kryo ctor. */ protected AbstractFileMergeOperator() { super(); } public AbstractFileMergeOperator(CompilationOpContext ctx) { super(ctx); } @Override public void initializeOp(Configuration hconf) throws HiveException { super.initializeOp(hconf); this.jc = new JobConf(hconf); incompatFileSet = new HashSet<Path>(); autoDelete = false; tmpPathFixed = false; tmpPathFixedConcatenate = false; dpPath = null; dpCtx = conf.getDpCtx(); hasDynamicPartitions = conf.hasDynamicPartitions(); isListBucketingAlterTableConcatenate = conf .isListBucketingAlterTableConcatenate(); listBucketingDepth = conf.getListBucketingDepth(); Path specPath = conf.getOutputPath(); isMmTable = conf.getIsMmTable(); if (isMmTable) { updatePaths(specPath, null); } else { updatePaths(Utilities.toTempPath(specPath), Utilities.toTaskTempPath(specPath)); } try { fs = specPath.getFileSystem(hconf); if (!isMmTable) { // Do not delete for MM tables. We either want the file if we succeed, or we must // delete is explicitly before proceeding if the merge fails. autoDelete = fs.deleteOnExit(outPath); } } catch (IOException e) { throw new HiveException("Failed to initialize AbstractFileMergeOperator", e); } } // sets up temp and task temp path private void updatePaths(Path tp, Path ttp) { if (taskId == null) { taskId = Utilities.getTaskId(jc); } tmpPath = tp; if (isMmTable) { taskTmpPath = null; // Make sure we don't collide with the source. outPath = finalPath = new Path(tmpPath, taskId + ".merged"); } else { taskTmpPath = ttp; finalPath = new Path(tp, taskId); outPath = new Path(ttp, Utilities.toTempPath(taskId)); } if (Utilities.FILE_OP_LOGGER.isTraceEnabled()) { Utilities.FILE_OP_LOGGER.trace("Paths for merge " + taskId + ": tmp " + tmpPath + ", task " + taskTmpPath + ", final " + finalPath + ", out " + outPath); } } /** * Fixes tmpPath to point to the correct partition. Initialize operator will * set tmpPath and taskTmpPath based on root table directory. So initially, * tmpPath will be &lt;prefix&gt;/_tmp.-ext-10000 and taskTmpPath will be * &lt;prefix&gt;/_task_tmp.-ext-10000. The depth of these two paths will be 0. * Now, in case of dynamic partitioning or list bucketing the inputPath will * have additional sub-directories under root table directory. This function * updates the tmpPath and taskTmpPath to reflect these additional * subdirectories. It updates tmpPath and taskTmpPath in the following way * 1. finds out the difference in path based on depthDiff provided * and saves the path difference in newPath * 2. newPath is used to update the existing tmpPath and taskTmpPath similar * to the way initializeOp() does. * * Note: The path difference between inputPath and tmpDepth can be DP or DP+LB. * This method will automatically handle it. * * Continuing the example above, if inputPath is &lt;prefix&gt;/-ext-10000/hr=a1/, * newPath will be hr=a1/. Then, tmpPath and taskTmpPath will be updated to * &lt;prefix&gt;/-ext-10000/hr=a1/_tmp.ext-10000 and * &lt;prefix&gt;/-ext-10000/hr=a1/_task_tmp.ext-10000 respectively. * We have list_bucket_dml_6.q cover this case: DP + LP + multiple skewed * values + merge. * * @param inputPath - input path * @throws java.io.IOException */ protected void fixTmpPath(Path inputPath, int depthDiff) throws IOException { // don't need to update tmp paths when there is no depth difference in paths if (depthDiff <= 0) { return; } dpPath = inputPath; Path newPath = new Path("."); // Build the path from bottom up while (inputPath != null && depthDiff > 0) { newPath = new Path(inputPath.getName(), newPath); depthDiff--; inputPath = inputPath.getParent(); } Path newTmpPath = new Path(tmpPath, newPath); if (!fs.exists(newTmpPath)) { if (Utilities.FILE_OP_LOGGER.isTraceEnabled()) { Utilities.FILE_OP_LOGGER.trace("Creating " + newTmpPath); } fs.mkdirs(newTmpPath); } Path newTaskTmpPath = (taskTmpPath != null) ? new Path(taskTmpPath, newPath) : null; updatePaths(newTmpPath, newTaskTmpPath); } /** * Validates that each input path belongs to the same partition since each * mapper merges the input to a single output directory * * @param inputPath - input path */ protected void checkPartitionsMatch(Path inputPath) throws IOException { if (!dpPath.equals(inputPath)) { // Temp partition input path does not match exist temp path String msg = "Multiple partitions for one merge mapper: " + dpPath + " NOT EQUAL TO " + inputPath; LOG.error(msg); throw new IOException(msg); } } protected void fixTmpPath(Path path) throws IOException { if (Utilities.FILE_OP_LOGGER.isTraceEnabled()) { Utilities.FILE_OP_LOGGER.trace("Calling fixTmpPath with " + path); } // Fix temp path for alter table ... concatenate if (isListBucketingAlterTableConcatenate) { if (this.tmpPathFixedConcatenate) { checkPartitionsMatch(path); } else { fixTmpPath(path, listBucketingDepth); tmpPathFixedConcatenate = true; } } else { if (hasDynamicPartitions || (listBucketingDepth > 0)) { // In light of results from union queries, we need to be aware that // sub-directories can exist in the partition directory. We want to // ignore these sub-directories and promote merged files to the // partition directory. String name = path.getName(); Path realPartitionPath = name.startsWith(UNION_SUDBIR_PREFIX) ? path.getParent() : path; if (tmpPathFixed) { checkPartitionsMatch(realPartitionPath); } else { // We haven't fixed the TMP path for this mapper yet int depthDiff = realPartitionPath.depth() - tmpPath.depth(); fixTmpPath(realPartitionPath, depthDiff); tmpPathFixed = true; } } } } @Override public void closeOp(boolean abort) throws HiveException { try { if (abort) { if (!autoDelete || isMmTable) { fs.delete(outPath, true); } return; } // if outPath does not exist, then it means all paths within combine split are skipped as // they are incompatible for merge (for example: files without stripe stats). // Those files will be added to incompatFileSet if (fs.exists(outPath)) { FileStatus fss = fs.getFileStatus(outPath); if (!isMmTable) { if (!fs.rename(outPath, finalPath)) { throw new IOException("Unable to rename " + outPath + " to " + finalPath); } LOG.info("Renamed path " + outPath + " to " + finalPath + "(" + fss.getLen() + " bytes)."); } else { assert finalPath.equals(outPath); // There's always just one file that we have merged. // The union/DP/etc. should already be account for in the path. Utilities.writeMmCommitManifest(Lists.newArrayList(outPath), tmpPath.getParent(), fs, taskId, conf.getWriteId(), conf.getStmtId(), null, false); LOG.info("Merged into " + finalPath + "(" + fss.getLen() + " bytes)."); } } // move any incompatible files to final path if (incompatFileSet != null && !incompatFileSet.isEmpty()) { if (isMmTable) { // We only support query-time merge for MM tables, so don't handle this. throw new HiveException("Incompatible files should not happen in MM tables."); } Path destDir = finalPath.getParent(); Path destPath = destDir; // move any incompatible files to final path if (incompatFileSet != null && !incompatFileSet.isEmpty()) { for (Path incompatFile : incompatFileSet) { // check if path conforms to Hive's file name convention. Hive expects filenames to be in specific format // like 000000_0, but "LOAD DATA" commands can let you add any files to any partitions/tables without // renaming. This can cause MoveTask to remove files in some cases where MoveTask assumes the files are // are generated by speculatively executed tasks. // Example: MoveTask thinks the following files are same // part-m-00000_1417075294718 // part-m-00001_1417075294718 // Assumes 1417075294718 as taskId and retains only large file supposedly generated by speculative execution. // This can result in data loss in case of CONCATENATE/merging. Filter out files that does not match Hive's // filename convention. if (!Utilities.isHiveManagedFile(incompatFile)) { // rename un-managed files to conform to Hive's naming standard // Example: // /warehouse/table/part-m-00000_1417075294718 will get renamed to /warehouse/table/.hive-staging/000000_0 // If staging directory already contains the file, taskId_copy_N naming will be used. final String taskId = Utilities.getTaskId(jc); Path destFilePath = new Path(destDir, new Path(taskId)); for (int counter = 1; fs.exists(destFilePath); counter++) { destFilePath = new Path(destDir, taskId + (Utilities.COPY_KEYWORD + counter)); } LOG.warn("Path doesn't conform to Hive's expectation. Renaming {} to {}", incompatFile, destFilePath); destPath = destFilePath; } try { Utilities.renameOrMoveFiles(fs, incompatFile, destPath); LOG.info("Moved incompatible file " + incompatFile + " to " + destPath); } catch (HiveException e) { LOG.error("Unable to move " + incompatFile + " to " + destPath); throw new IOException(e); } } } } } catch (IOException e) { throw new HiveException("Failed to close AbstractFileMergeOperator", e); } } @Override public void jobCloseOp(Configuration hconf, boolean success) throws HiveException { try { Path outputDir = conf.getOutputPath(); FileSystem fs = outputDir.getFileSystem(hconf); Long mmWriteId = conf.getWriteId(); int stmtId = conf.getStmtId(); if (!isMmTable) { Path backupPath = backupOutputPath(fs, outputDir); Utilities.mvFileToFinalPath( outputDir, hconf, success, LOG, conf.getDpCtx(), null, reporter); if (success) { LOG.info("jobCloseOp moved merged files to output dir: " + outputDir); } if (backupPath != null) { fs.delete(backupPath, true); } } else { int dpLevels = dpCtx == null ? 0 : dpCtx.getNumDPCols(), lbLevels = conf.getListBucketingDepth(); // We don't expect missing buckets from mere (actually there should be no buckets), // so just pass null as bucketing context. Union suffix should also be accounted for. Utilities.handleMmTableFinalPath(outputDir.getParent(), null, hconf, success, dpLevels, lbLevels, null, mmWriteId, stmtId, reporter, isMmTable, false, false); } } catch (IOException e) { throw new HiveException("Failed jobCloseOp for AbstractFileMergeOperator", e); } super.jobCloseOp(hconf, success); } private Path backupOutputPath(FileSystem fs, Path outpath) throws IOException, HiveException { if (fs.exists(outpath)) { Path backupPath = new Path(outpath.getParent(), BACKUP_PREFIX + outpath.getName()); Utilities.rename(fs, outpath, backupPath); return backupPath; } else { return null; } } @Override public String getName() { return AbstractFileMergeOperator.getOperatorName(); } public static String getOperatorName() { return "MERGE"; } protected final Path getOutPath() { return outPath; } protected final void addIncompatibleFile(Path path) { incompatFileSet.add(path); } }
alanfgates/hive
ql/src/java/org/apache/hadoop/hive/ql/exec/AbstractFileMergeOperator.java
Java
apache-2.0
15,244
package com.code5team.web.servlet; import java.io.IOException; import java.io.PrintWriter; public class HelloServlet { public void test() { } }
Code5Team/JavaCode
study/src/com/code5team/web/servlet/HelloServlet.java
Java
apache-2.0
152
%% these imports are added to all gx files :- if(current_prolog_flag(dialect, ciao)). :- use_module(library(terms_vars)). :- else. varset(A,B) :- term_variables(A,B). :- endif.
leuschel/logen
gxmodules.pl
Perl
apache-2.0
177
/*! Pixel buffers are buffers that contain two-dimensional texture data. Contrary to textures, pixel buffers are stored in a client-defined format. They are used to transfer data to or from the video memory, before or after being turned into a texture. */ use std::borrow::Cow; use std::cell::Cell; use std::ops::{Deref, DerefMut}; use backend::Facade; use GlObject; use BufferViewExt; use buffer::{ReadError, BufferView, BufferType}; use gl; use texture::PixelValue; use texture::Texture2dDataSink; /// Buffer that stores the content of a texture. /// /// The generic type represents the type of pixels that the buffer contains. pub struct PixelBuffer<T> where T: PixelValue { buffer: BufferView<[T]>, dimensions: Cell<Option<(u32, u32)>>, } impl<T> PixelBuffer<T> where T: PixelValue { /// Builds a new buffer with an uninitialized content. pub fn new_empty<F>(facade: &F, capacity: usize) -> PixelBuffer<T> where F: Facade { PixelBuffer { buffer: BufferView::empty_array(facade, BufferType::PixelPackBuffer, capacity, false).unwrap(), dimensions: Cell::new(None), } } /// Reads the content of the pixel buffer. pub fn read_as_texture_2d<S>(&self) -> Result<S, ReadError> where S: Texture2dDataSink<T> { let dimensions = self.dimensions.get().expect("The pixel buffer is empty"); let data = try!(self.read()); Ok(S::from_raw(Cow::Owned(data), dimensions.0, dimensions.1)) } } impl<T> Deref for PixelBuffer<T> where T: PixelValue { type Target = BufferView<[T]>; fn deref(&self) -> &BufferView<[T]> { &self.buffer } } impl<T> DerefMut for PixelBuffer<T> where T: PixelValue { fn deref_mut(&mut self) -> &mut BufferView<[T]> { &mut self.buffer } } // TODO: rework this impl<T> GlObject for PixelBuffer<T> where T: PixelValue { type Id = gl::types::GLuint; fn get_id(&self) -> gl::types::GLuint { self.buffer.get_buffer_id() } } // TODO: remove this hack #[doc(hidden)] pub fn store_infos<T>(b: &PixelBuffer<T>, dimensions: (u32, u32)) where T: PixelValue { b.dimensions.set(Some(dimensions)); }
TyOverby/glium
src/pixel_buffer.rs
Rust
apache-2.0
2,208
<ion-header> <ion-navbar core-back-button> <ion-title><core-format-text *ngIf="quiz" [text]="quiz.name"></core-format-text></ion-title> </ion-navbar> </ion-header> <ion-content> <ion-refresher [enabled]="loaded" (ionRefresh)="doRefresh($event)"> <ion-refresher-content pullingText="{{ 'core.pulltorefresh' | translate }}"></ion-refresher-content> </ion-refresher> <core-loading [hideUntil]="loaded"> <ion-list *ngIf="attempt"> <ion-item text-wrap> <p class="item-heading">{{ 'addon.mod_quiz.attemptnumber' | translate }}</p> <p *ngIf="attempt.preview">{{ 'addon.mod_quiz.preview' | translate }}</p> <p *ngIf="!attempt.preview">{{ attempt.attempt }}</p> </ion-item> <ion-item text-wrap> <p class="item-heading">{{ 'addon.mod_quiz.attemptstate' | translate }}</p> <p *ngFor="let sentence of attempt.readableState">{{ sentence }}</p> </ion-item> <ion-item text-wrap *ngIf="quiz.showMarkColumn && attempt.readableMark !== ''"> <p class="item-heading">{{ 'addon.mod_quiz.marks' | translate }} / {{ quiz.sumGradesFormatted }}</p> <p>{{ attempt.readableMark }}</p> </ion-item> <ion-item text-wrap *ngIf="quiz.showGradeColumn && attempt.readableGrade !== ''"> <p class="item-heading">{{ 'addon.mod_quiz.grade' | translate }} / {{ quiz.gradeFormatted }}</p> <p>{{ attempt.readableGrade }}</p> </ion-item> <ion-item text-wrap *ngIf="quiz.showFeedbackColumn && attempt.feedback"> <p class="item-heading">{{ 'addon.mod_quiz.feedback' | translate }}</p> <p><core-format-text [component]="component" [componentId]="componentId" [text]="attempt.feedback"></core-format-text></p> </ion-item> <ion-item *ngIf="quiz.showReviewColumn && attempt.finished"> <button ion-button block icon-start [navPush]="'AddonModQuizReviewPage'" [navParams]="{courseId: courseId, quizId: quiz.id, attemptId: attempt.id}"> <ion-icon name="search"></ion-icon> {{ 'addon.mod_quiz.review' | translate }} </button> </ion-item> <ion-item text-wrap class="core-danger-item" *ngIf="!quiz.showReviewColumn"> <p>{{ 'addon.mod_quiz.noreviewattempt' | translate }}</p> </ion-item> </ion-list> </core-loading> </ion-content>
jleyva/moodlemobile2
src/addon/mod/quiz/pages/attempt/attempt.html
HTML
apache-2.0
2,564
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="refresh" content="0;URL=type.P194.html"> </head> <body> <p>Redirecting to <a href="type.P194.html">type.P194.html</a>...</p> <script>location.replace("type.P194.html" + location.search + location.hash);</script> </body> </html>
nitro-devs/nitro-game-engine
docs/typenum/consts/P194.t.html
HTML
apache-2.0
297
package se.l4.dust.core.internal.expression.ast; /** * Node for an operation that adds the right side to the left. * * @author Andreas Holstenson * */ public class AddNode extends LeftRightNode { public AddNode(int line, int position, Node left, Node right) { super(line, position, left, right); } }
LevelFourAB/dust
dust-core/src/main/java/se/l4/dust/core/internal/expression/ast/AddNode.java
Java
apache-2.0
314
namespace Test.NDatabase.Odb.Test.VO.Inheritance { public class OutdoorPlayer : Player { private string groundName; //1 public string GroundName { get { return groundName; } set { groundName = value; } } } }
WaltChen/NDatabase
tests/NDatabase.Old.UnitTests/NDatabase/Odb/Test/VO/Inheritance/OutdoorPlayer.cs
C#
apache-2.0
288
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int vec[50], i,aux,suma,promedio,mayor,menor; mayor=-999; menor=999; srand(time(0)); for(i=0;i<50;i++) { vec[i]=rand()%90+10; } for(i=0;i<50;i++) { aux=vec[i]; vec[i]=vec[i+1]; vec[i+1]=aux; suma=suma+vec[i]; promedio=suma/50; if(vec[i]>mayor) { mayor=vec[i]; } if(vec[i]<menor) { menor=vec[i]; } } for(i=0;i<50;i++) { printf("%d\n", vec[i]); } printf("La Suma de los numeros del Vector es: %d\n", suma); printf("El Promedio del Vector es: %d\n", promedio); printf("El Numero Mayor es: %d\n", mayor); printf("El Numero Menor es: %d\n", menor); system("pause"); return 0; }
moises1747/Unidad-2
Ejercicio 3.c
C
apache-2.0
765
/** * Copyright 2011-2016 Asakusa Framework Team. * * 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.asakusafw.lang.compiler.extension.directio; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.Set; import java.util.TreeMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.asakusafw.lang.compiler.api.ExternalPortProcessor; import com.asakusafw.lang.compiler.api.reference.DataModelReference; import com.asakusafw.lang.compiler.api.reference.ExternalInputReference; import com.asakusafw.lang.compiler.api.reference.ExternalOutputReference; import com.asakusafw.lang.compiler.api.reference.TaskReference; import com.asakusafw.lang.compiler.api.reference.TaskReference.Phase; import com.asakusafw.lang.compiler.common.BasicDiagnostic; import com.asakusafw.lang.compiler.common.Diagnostic; import com.asakusafw.lang.compiler.common.DiagnosticException; import com.asakusafw.lang.compiler.common.Location; import com.asakusafw.lang.compiler.common.util.EnumUtil; import com.asakusafw.lang.compiler.extension.directio.emitter.OutputStageEmitter; import com.asakusafw.lang.compiler.extension.directio.emitter.OutputStageInfo; import com.asakusafw.lang.compiler.extension.externalio.AbstractExternalPortProcessor; import com.asakusafw.lang.compiler.extension.externalio.ExternalPortStageInfo; import com.asakusafw.lang.compiler.extension.externalio.Naming; import com.asakusafw.lang.compiler.hadoop.HadoopFormatExtension; import com.asakusafw.lang.compiler.hadoop.HadoopTaskReference; import com.asakusafw.lang.compiler.javac.JavaSourceExtension; import com.asakusafw.lang.compiler.mapreduce.CopyStageEmitter; import com.asakusafw.lang.compiler.mapreduce.CopyStageInfo; import com.asakusafw.lang.compiler.mapreduce.MapReduceUtil; import com.asakusafw.lang.compiler.mapreduce.SourceInfo; import com.asakusafw.lang.compiler.mapreduce.StageInfo; import com.asakusafw.lang.compiler.model.description.ClassDescription; import com.asakusafw.lang.compiler.model.description.Descriptions; import com.asakusafw.lang.compiler.model.description.ValueDescription; import com.asakusafw.lang.compiler.model.info.ExternalInputInfo; import com.asakusafw.lang.compiler.model.info.ExternalOutputInfo; import com.asakusafw.lang.compiler.model.info.ExternalPortInfo; import com.asakusafw.runtime.directio.DataFormat; import com.asakusafw.runtime.directio.DirectDataSourceConstants; import com.asakusafw.runtime.directio.FilePattern; import com.asakusafw.runtime.directio.FilePattern.PatternElementKind; import com.asakusafw.runtime.util.VariableTable; import com.asakusafw.vocabulary.directio.DirectFileInputDescription; import com.asakusafw.vocabulary.directio.DirectFileOutputDescription; /** * An implementation of {@link ExternalPortProcessor} for Direct file I/O. */ public class DirectFileIoPortProcessor extends AbstractExternalPortProcessor<DirectFileInputDescription, DirectFileOutputDescription> { static final Logger LOG = LoggerFactory.getLogger(DirectFileIoPortProcessor.class); static final TaskReference.Phase PHASE_INPUT = TaskReference.Phase.PROLOGUE; static final TaskReference.Phase PHASE_OUTPUT = TaskReference.Phase.EPILOGUE; static final String PREFIX_OPTION = "directio."; //$NON-NLS-1$ /** * The compiler option name whether filter feature is enabled or not. * @see #DEFAULT_FILTER_ENABLED */ public static final String OPTION_FILTER_ENABLED = PREFIX_OPTION + "input.filter.enabled"; //$NON-NLS-1$ /** * The default value of {@link #OPTION_FILTER_ENABLED}. */ public static final boolean DEFAULT_FILTER_ENABLED = true; private static final Set<PatternElementKind> INVALID_BASE_PATH_KIND = EnumUtil.freeze(new PatternElementKind[] { PatternElementKind.WILDCARD, PatternElementKind.SELECTION, }); private static final String PATTERN_DUMMY_INPUT = "directio:%s/%s"; //$NON-NLS-1$ @Override protected String getModuleName() { return DirectFileIoConstants.MODULE_NAME; } @Override protected Class<DirectFileInputDescription> getInputDescriptionType() { return DirectFileInputDescription.class; } @Override protected Class<DirectFileOutputDescription> getOutputDescriptionType() { return DirectFileOutputDescription.class; } @Override protected ValueDescription analyzeInputProperties( AnalyzeContext context, String name, DirectFileInputDescription description) { DirectFileInputModel model = analyzeDescription(context, description); return Descriptions.valueOf(model); } @Override protected ValueDescription analyzeOutputProperties( AnalyzeContext context, String name, DirectFileOutputDescription description) { DirectFileOutputModel model = analyzeDescription(context, description); return Descriptions.valueOf(model); } private DirectFileInputModel analyzeDescription(AnalyzeContext context, DirectFileInputDescription description) { ValidateContext validate = new ValidateContext(context, Descriptions.classOf(description.getClass())); assertPresent(validate, description.getBasePath(), "getBasePath"); //$NON-NLS-1$ assertPresent(validate, description.getResourcePattern(), "getResourcePattern"); //$NON-NLS-1$ assertPresent(validate, description.getFormat(), "getFormat"); //$NON-NLS-1$ validate.raiseException(); return new DirectFileInputModel(description); } private DirectFileOutputModel analyzeDescription(AnalyzeContext context, DirectFileOutputDescription description) { ValidateContext validate = new ValidateContext(context, Descriptions.classOf(description.getClass())); assertPresent(validate, description.getBasePath(), "getBasePath"); //$NON-NLS-1$ assertPresent(validate, description.getResourcePattern(), "getResourcePattern"); //$NON-NLS-1$ assertPresent(validate, description.getFormat(), "getFormat"); //$NON-NLS-1$ assertPresent(validate, description.getOrder(), "getOrder"); //$NON-NLS-1$ assertPresent(validate, description.getDeletePatterns(), "getDeletePatterns"); //$NON-NLS-1$ validate.raiseException(); return new DirectFileOutputModel(description); } @Override protected Set<OutputAttribute> analyzeOutputAttributes( AnalyzeContext context, String name, DirectFileOutputDescription description) { // Direct I/O file output must be GENERATOR only if it declares delete-patterns if (description.getDeletePatterns().isEmpty()) { return Collections.emptySet(); } else { return EnumSet.of(OutputAttribute.GENERATOR); } } @Override protected Set<String> analyzeInputParameterNames( AnalyzeContext context, String name, DirectFileInputDescription description) { try { // FIXME collect parameter names from filters Set<String> results = new HashSet<>(); results.addAll(VariableTable.collectVariableNames(description.getBasePath())); results.addAll(VariableTable.collectVariableNames(description.getResourcePattern())); return results; } catch (NullPointerException | IllegalArgumentException e) { if (LOG.isDebugEnabled()) { LOG.debug("error occurred while analyzing: {}", description, e); //$NON-NLS-1$ } return Collections.emptySet(); } } @Override protected Set<String> analyzeOutputParameterNames( AnalyzeContext context, String name, DirectFileOutputDescription description) { try { Set<String> results = new HashSet<>(); results.addAll(VariableTable.collectVariableNames(description.getBasePath())); results.addAll(VariableTable.collectVariableNames(description.getResourcePattern())); for (String s : description.getDeletePatterns()) { results.addAll(VariableTable.collectVariableNames(s)); } return results; } catch (NullPointerException | IllegalArgumentException e) { if (LOG.isDebugEnabled()) { LOG.debug("error occurred while analyzing: {}", description, e); //$NON-NLS-1$ } return Collections.emptySet(); } } private void assertPresent(ValidateContext context, Object value, String method) { if (value != null) { return; } context.error(MessageFormat.format( "{0}.{1}() must be set", context.target.getClassName(), method)); } @Override public void validate( AnalyzeContext context, Map<String, ExternalInputInfo> inputs, Map<String, ExternalOutputInfo> outputs) { List<Diagnostic> diagnostics = new ArrayList<>(); List<ResolvedInput> resolvedInputs = new ArrayList<>(); List<ResolvedOutput> resolvedOutputs = new ArrayList<>(); for (Map.Entry<String, ExternalInputInfo> entry : inputs.entrySet()) { try { resolvedInputs.add(restoreModel(context, entry.getKey(), entry.getValue())); } catch (DiagnosticException e) { diagnostics.addAll(e.getDiagnostics()); } } for (Map.Entry<String, ExternalOutputInfo> entry : outputs.entrySet()) { try { resolvedOutputs.add(restoreModel(context, entry.getKey(), entry.getValue())); } catch (DiagnosticException e) { diagnostics.addAll(e.getDiagnostics()); } } if (diagnostics.isEmpty() == false) { throw new DiagnosticException(diagnostics); } checkConflict(context, resolvedInputs, resolvedOutputs); } private String normalizePath(String path) { assert path != null; return Location.of(path).toPath() + '/'; } static ResolvedInput restoreModel(AnalyzeContext context, String name, ExternalInputInfo info) { DirectFileInputModel model = resolveContents(context, info, DirectFileInputModel.class); ValidateContext validate = new ValidateContext(context, info.getDescriptionClass()); analyzeModel(validate, model, info.getDataModelClass()); validate.raiseException(); return new ResolvedInput(name, info, model); } static ResolvedOutput restoreModel(AnalyzeContext context, String name, ExternalOutputInfo info) { DirectFileOutputModel model = resolveContents(context, info, DirectFileOutputModel.class); ValidateContext validate = new ValidateContext(context, info.getDescriptionClass()); analyzeModel(validate, model, info.getDataModelClass()); validate.raiseException(); return new ResolvedOutput(name, info, model); } private static <T> T resolveContents(AnalyzeContext context, ExternalPortInfo info, Class<T> type) { ValueDescription contents = info.getContents(); if (contents == null) { throw new DiagnosticException(Diagnostic.Level.ERROR, MessageFormat.format( "failed to restore external port detail: {0}", info)); } try { Object resolved = contents.resolve(context.getClassLoader()); return type.cast(resolved); } catch (ReflectiveOperationException | ClassCastException e) { throw new DiagnosticException(Diagnostic.Level.ERROR, MessageFormat.format( "failed to restore external port detail: {0}", info), e); } } private static void analyzeModel(ValidateContext context, DirectFileInputModel model, ClassDescription dataType) { checkBasePath(context, model.getBasePath()); checkInputPattern(context, model.getResourcePattern()); checkFormatClass(context, model.getFormatClass(), dataType); } private static void analyzeModel(ValidateContext context, DirectFileOutputModel model, ClassDescription dataType) { checkBasePath(context, model.getBasePath()); checkOutput(context, model, dataType); checkDeletePatterns(context, model.getDeletePatterns()); checkFormatClass(context, model.getFormatClass(), dataType); } private static void checkBasePath(ValidateContext context, String value) { try { FilePattern pattern = FilePattern.compile(value); if (pattern.containsTraverse()) { context.error(MessageFormat.format( "base path must not contain wildcards (**) ({0}.getBasePath())", context.target.getClassName())); } Set<PatternElementKind> kinds = pattern.getPatternElementKinds(); for (PatternElementKind kind : kinds) { if (INVALID_BASE_PATH_KIND.contains(kind)) { context.error(MessageFormat.format( "base path must not contain \"{1}\" ({0}.getBasePath())", context.target.getClassName(), kind.getSymbol())); } } } catch (IllegalArgumentException e) { context.error(MessageFormat.format( "failed to compile base path ({0}.getBasePath()): {1}", context.target.getClassName(), e.getMessage())); } } private static void checkInputPattern(ValidateContext context, String value) { try { FilePattern.compile(value); } catch (IllegalArgumentException e) { context.error(MessageFormat.format( "failed to compile input resource pattern ({0}.getResourcePattern()): {1}", context.target.getClassName(), e.getMessage())); } } private static void checkOutput(ValidateContext context, DirectFileOutputModel model, ClassDescription dataType) { DataModelReference dataModel = context.context.getDataModelLoader().load(dataType); List<OutputPattern.CompiledSegment> resourcePattern; try { resourcePattern = OutputPattern.compileResourcePattern(model.getResourcePattern(), dataModel); } catch (IllegalArgumentException e) { context.error(MessageFormat.format( "failed to compile output resource pattern ({0}.getResourcePattern()): {1}", context.target.getClassName(), e.getMessage())); resourcePattern = null; } List<OutputPattern.CompiledOrder> orders; try { orders = OutputPattern.compileOrder(model.getOrder(), dataModel); } catch (IllegalArgumentException e) { context.error(MessageFormat.format( "failed to compile record order ({0}.getOrder()): {1}", context.target.getClassName(), e.getMessage())); orders = null; } if (resourcePattern == null || orders == null) { return; } if (OutputPattern.isContextRequired(resourcePattern)) { if (OutputPattern.isGatherRequired(resourcePattern)) { context.error(MessageFormat.format( "output resource pattern with wildcards (*) " + "must not contain any properties ('{'name'}') nor random numbers ([m..n]) " + "({0}.getResourcePattern()): {1}", context.target.getClassName())); } if (orders.isEmpty() == false) { context.error(MessageFormat.format( "output resource pattern with wildcards (*) must not contain any orders " + "({0}.getOrder()): {1}", context.target.getClassName())); } } } private static void checkDeletePatterns(ValidateContext context, List<String> values) { for (int index = 0, n = values.size(); index < n; index++) { String value = values.get(index); try { FilePattern.compile(value); } catch (IllegalArgumentException e) { context.error(MessageFormat.format( "failed to compile delete resource pattern ({0}.getDeletePatterns()@1): {2}", context.target.getClassName(), index, e.getMessage())); } } } private static void checkFormatClass( ValidateContext context, ClassDescription formatClass, ClassDescription dataType) { Class<?> resolvedDataType; try { resolvedDataType = dataType.resolve(context.context.getClassLoader()); } catch (ReflectiveOperationException e) { context.error(MessageFormat.format( "failed to resolve data model class: {0}", dataType.getClassName()), e); return; } DataFormat<?> formatObject; try { Class<?> resolvedFormatClass = formatClass.resolve(context.context.getClassLoader()); if (DataFormat.class.isAssignableFrom(resolvedFormatClass) == false) { throw new ReflectiveOperationException(MessageFormat.format( "data format must be a subtype of {0}: {1}", DataFormat.class.getName(), formatClass.getClassName())); } formatObject = (DataFormat<?>) resolvedFormatClass.getConstructor().newInstance(); } catch (ReflectiveOperationException e) { context.error(MessageFormat.format( "failed to resolve data format ({0}.getFormatClass()): {1}", context.target.getClassName(), formatClass.getClassName()), e); return; } if (formatObject.getSupportedType().isAssignableFrom(resolvedDataType) == false) { context.error(MessageFormat.format( "data format must support \"{2}\" ({0}.getFormatClass()): {1}", context.target.getClassName(), formatClass.getClassName(), dataType.getClassName())); } } private void checkConflict(AnalyzeContext context, List<ResolvedInput> inputs, List<ResolvedOutput> outputs) { assert inputs != null; assert outputs != null; ValidateContext c = new ValidateContext(context, null); NavigableMap<String, ResolvedInput> inputPaths = new TreeMap<>(); for (ResolvedInput input : inputs) { String path = normalizePath(input.model.getBasePath()); inputPaths.put(path, input); } NavigableMap<String, ResolvedOutput> outputPaths = new TreeMap<>(); for (ResolvedOutput self : outputs) { String path = normalizePath(self.model.getBasePath()); for (Map.Entry<String, ResolvedInput> entry : inputPaths.tailMap(path, true).entrySet()) { if (entry.getKey().startsWith(path) == false) { break; } ResolvedInput other = entry.getValue(); c.error(MessageFormat.format( "conflict input/output base paths: {0}[{1}] -> {2}[{3}]", self.info.getDescriptionClass().getClassName(), self.model.getBasePath(), other.info.getDescriptionClass().getClassName(), other.model.getBasePath())); } if (outputPaths.containsKey(path)) { ResolvedOutput other = outputPaths.get(path); c.error(MessageFormat.format( "conflict output/output base paths: {0}[{1}] <-> {2}[{3}]", self.info.getDescriptionClass().getClassName(), self.model.getBasePath(), other.info.getDescriptionClass().getClassName(), other.model.getBasePath())); } else { outputPaths.put(path, self); } } for (Map.Entry<String, ResolvedOutput> base : outputPaths.entrySet()) { String path = base.getKey(); for (Map.Entry<String, ResolvedOutput> entry : outputPaths.tailMap(path, false).entrySet()) { if (entry.getKey().startsWith(path) == false) { break; } ResolvedOutput self = base.getValue(); ResolvedOutput other = entry.getValue(); c.error(MessageFormat.format( "conflict input/output base paths: {0}[{1}] -> {2}[{3}]", self.info.getDescriptionClass().getClassName(), self.model.getBasePath(), other.info.getDescriptionClass().getClassName(), other.model.getBasePath())); } } c.raiseException(); } @Override protected Set<String> computeInputPaths(Context context, String name, ExternalInputInfo info) { String base = getTemporaryPath(context, PHASE_INPUT, null); String path = MapReduceUtil.getStageOutputPath(base, MapReduceUtil.quoteOutputName(name)); return Collections.singleton(path); } @Override public void process( Context context, List<ExternalInputReference> inputs, List<ExternalOutputReference> outputs) throws IOException { LOG.debug("processing Direct file I/O ports: {}/{}", context.getBatchId(), context.getFlowId()); //$NON-NLS-1$ processInputs(context, inputs); processOutputs(context, outputs); } private void processInputs(Context context, List<ExternalInputReference> ports) throws IOException { if (ports.isEmpty()) { return; } List<CopyStageInfo.Operation> operations = new ArrayList<>(); for (ExternalInputReference port : ports) { LOG.debug("processing Direct file input: {}={}", port.getName(), port.getDescriptionClass()); //$NON-NLS-1$ CopyStageInfo.Operation operation = processInput(context, port); operations.add(operation); } String stageId = Naming.getStageId(getModuleName(), PHASE_INPUT); CopyStageInfo info = new CopyStageInfo( new StageInfo(context.getBatchId(), context.getFlowId(), stageId), operations, getTemporaryPath(context, PHASE_INPUT, null)); ClassDescription clientClass = Naming.getClass(getModuleName(), PHASE_INPUT, "StageClient"); //$NON-NLS-1$ CopyStageEmitter.emit(clientClass, info, getJavaCompiler(context)); registerJob(context, PHASE_INPUT, clientClass); } private void processOutputs(Context context, List<ExternalOutputReference> ports) throws IOException { if (ports.isEmpty()) { return; } List<OutputStageInfo.Operation> operations = new ArrayList<>(); for (ExternalOutputReference port : ports) { LOG.debug("processing Direct file output: {}={}", port.getName(), port.getDescriptionClass()); //$NON-NLS-1$ OutputStageInfo.Operation operation = processOutput(context, port); operations.add(operation); } OutputStageInfo info = new OutputStageInfo( new ExternalPortStageInfo(getModuleName(), context.getBatchId(), context.getFlowId(), PHASE_OUTPUT), operations, getTemporaryPath(context, PHASE_OUTPUT, null)); ClassDescription clientClass = OutputStageEmitter.emit(info, getJavaCompiler(context)); registerJob(context, PHASE_OUTPUT, clientClass); } private JavaSourceExtension getJavaCompiler(Context context) { JavaSourceExtension extension = context.getExtension(JavaSourceExtension.class); if (extension == null) { throw new DiagnosticException(Diagnostic.Level.ERROR, "Java compiler must be supported"); } return extension; } private CopyStageInfo.Operation processInput(Context context, ExternalInputReference reference) { ResolvedInput resolved = restoreModel(context, reference.getName(), reference); String dummyInputPath = String.format(PATTERN_DUMMY_INPUT, reference.getName(), resolved.model.getBasePath()); Map<String, String> inputAttributes = getInputAttributes(context, resolved); return new CopyStageInfo.Operation( MapReduceUtil.quoteOutputName(reference.getName()), new SourceInfo( dummyInputPath, reference.getDataModelClass(), DirectFileIoConstants.CLASS_INPUT_FORMAT, inputAttributes), HadoopFormatExtension.getOutputFormat(context), Collections.emptyMap()); } private Map<String, String> getInputAttributes(Context context, ResolvedInput resolved) { Map<String, String> results = new LinkedHashMap<>(); results.put(DirectDataSourceConstants.KEY_DATA_CLASS, resolved.info.getDataModelClass().getBinaryName()); results.put(DirectDataSourceConstants.KEY_FORMAT_CLASS, resolved.model.getFormatClass().getBinaryName()); results.put(DirectDataSourceConstants.KEY_BASE_PATH, resolved.model.getBasePath()); results.put(DirectDataSourceConstants.KEY_RESOURCE_PATH, resolved.model.getResourcePattern()); ClassDescription filter = resolved.model.getFilterClass(); if (filter != null) { if (isFilterEnabled(context)) { results.put(DirectDataSourceConstants.KEY_FILTER_CLASS, filter.getBinaryName()); } else { LOG.info(MessageFormat.format( "Direct I/O input filter is disabled in current setting: {0} ({1})", resolved.info.getDescriptionClass().getClassName(), filter.getClassName())); } } results.put(DirectDataSourceConstants.KEY_OPTIONAL, String.valueOf(resolved.model.isOptional())); return results; } static boolean isFilterEnabled(Context context) { return context.getOptions().get(OPTION_FILTER_ENABLED, DEFAULT_FILTER_ENABLED); } private OutputStageInfo.Operation processOutput(Context context, ExternalOutputReference reference) { DirectFileOutputModel model = restoreModel(context, reference.getName(), reference).model; DataModelReference dataModel = context.getDataModelLoader().load(reference.getDataModelClass()); List<FilePattern> deletePatterns = new ArrayList<>(); for (String pattern : model.getDeletePatterns()) { deletePatterns.add(FilePattern.compile(pattern)); } return new OutputStageInfo.Operation( reference.getName(), dataModel, Collections.singletonList(new SourceInfo( reference.getPaths(), reference.getDataModelClass(), HadoopFormatExtension.getInputFormat(context), Collections.emptyMap())), model.getBasePath(), OutputPattern.compile(dataModel, model.getResourcePattern(), model.getOrder()), deletePatterns, model.getFormatClass()); } private void registerJob(Context context, Phase phase, ClassDescription clientClass) { LOG.debug("registering Direct file I/O job: {}->{}", phase, clientClass); //$NON-NLS-1$ context.addTask(phase, new HadoopTaskReference( getModuleName(), clientClass, Collections.emptyList())); } @Override protected <T> T getAdapter(Class<T> adapterType) { if (adapterType.isAssignableFrom(DirectFileInputFormatInfoSupport.class)) { return adapterType.cast(new DirectFileInputFormatInfoSupport()); } return super.getAdapter(adapterType); } private static class ValidateContext { final AnalyzeContext context; final ClassDescription target; final List<Diagnostic> diagnostics = new ArrayList<>(); ValidateContext(AnalyzeContext context, ClassDescription target) { this.context = context; this.target = target; } void error(String message) { error(message, null); } void error(String message, Exception cause) { diagnostics.add(new BasicDiagnostic(Diagnostic.Level.ERROR, message, cause)); } void raiseException() { if (diagnostics.isEmpty() == false) { throw new DiagnosticException(diagnostics); } } } static class ResolvedInput { final ExternalInputInfo info; final DirectFileInputModel model; ResolvedInput(String name, ExternalInputInfo info, DirectFileInputModel model) { this.info = info; this.model = model; } } static class ResolvedOutput { final ExternalOutputInfo info; final DirectFileOutputModel model; ResolvedOutput(String name, ExternalOutputInfo info, DirectFileOutputModel model) { this.info = info; this.model = model; } } }
akirakw/asakusafw-compiler
compiler-project/extension-directio/src/main/java/com/asakusafw/lang/compiler/extension/directio/DirectFileIoPortProcessor.java
Java
apache-2.0
30,587
"""cmput404project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views as auth_views from rest_framework import routers from service import views urlpatterns = [ url(r'^', include('service.urls')), url(r'^docs/', include('rest_framework_docs.urls')), url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ]
CMPUT404Team/CMPUT404-project-socialdistribution
cmput404project/cmput404project/urls.py
Python
apache-2.0
1,075
# Ganoderma subrenatum (Murrill) Sacc. & Trotter SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Amauroderma subrenatum Murrill ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Ganodermataceae/Ganoderma/Ganoderma subrenatum/README.md
Markdown
apache-2.0
205
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: John Abraham <john.abraham.in@gmail.com> */ #include "animxmlparser.h" #include "animatormode.h" #include "animatorscene.h" #include "animpacket.h" #include "animlink.h" #include "animresource.h" #include "animnode.h" namespace netanim { NS_LOG_COMPONENT_DEFINE ("Animxmlparser"); Animxmlparser::Animxmlparser (QString traceFileName): m_traceFileName (traceFileName), m_parsingComplete (false), m_reader (0), m_maxSimulationTime (0), m_fileIsValid (true), m_lastPacketEventTime (-1), m_thousandThPacketTime (-1), m_firstPacketTime (65535), m_minNodeX (0), m_minNodeY (0), m_maxNodeX (0), m_maxNodeY (0) { m_version = 0; if (m_traceFileName == "") return; m_traceFile = new QFile (m_traceFileName); if (!m_traceFile->open (QIODevice::ReadOnly | QIODevice::Text)) { //qDebug (QString ("Critical:Trace file is invalid")); m_fileIsValid = false; return; } //qDebug (m_traceFileName); m_reader = new QXmlStreamReader (m_traceFile); } Animxmlparser::~Animxmlparser () { if (m_traceFile) delete m_traceFile; if (m_reader) delete m_reader; } void Animxmlparser::searchForVersion () { QFile * f = new QFile (m_traceFileName); if (f->open (QIODevice::ReadOnly | QIODevice::Text)) { QString firstLine = QString (f->readLine ()); int startIndex = 0; int endIndex = 0; QString versionField = VERSION_FIELD_DEFAULT; startIndex = firstLine.indexOf (versionField); endIndex = firstLine.lastIndexOf ("\""); if ((startIndex != -1) && (endIndex > startIndex)) { int adjustedStartIndex = startIndex + versionField.length (); QString v = firstLine.mid (adjustedStartIndex, endIndex-adjustedStartIndex); m_version = v.toDouble (); } f->close (); delete f; } } uint64_t Animxmlparser::getRxCount () { searchForVersion (); uint64_t count = 0; QFile * f = new QFile (m_traceFileName); if (f->open (QIODevice::ReadOnly | QIODevice::Text)) { QString allContent = QString (f->readAll ()); int j = 0; QString searchString = " toId="; if (m_version >= 3.102) searchString = " tId"; while ( (j = allContent.indexOf (searchString, j)) != -1) { ++j; ++count; } f->close (); delete f; //qDebug (QString::number (count)); return count; } return count; } bool Animxmlparser::isFileValid () { return m_fileIsValid; } bool Animxmlparser::isParsingComplete () { return m_parsingComplete; } qreal Animxmlparser::getLastPacketEventTime () { return m_lastPacketEventTime; } qreal Animxmlparser::getFirstPacketTime () { return m_firstPacketTime; } QPointF Animxmlparser::getMinPoint () { return QPointF (m_minNodeX, m_minNodeY); } QPointF Animxmlparser::getMaxPoint () { return QPointF (m_maxNodeX, m_maxNodeY); } qreal Animxmlparser::getThousandthPacketTime () { return m_thousandThPacketTime; } void Animxmlparser::doParse () { uint64_t parsedElementCount = 0; AnimatorMode * pAnimatorMode = AnimatorMode::getInstance (); while (!isParsingComplete ()) { if (AnimatorMode::getInstance ()->keepAppResponsive ()) { AnimatorMode::getInstance ()->setParsingCount (parsedElementCount); } ParsedElement parsedElement = parseNext (); switch (parsedElement.type) { case XML_ANIM: { AnimatorMode::getInstance ()->setVersion (parsedElement.version); //qDebug (QString ("XML Version:") + QString::number (version)); break; } case XML_NODE: { m_minNodeX = qMin (m_minNodeX, parsedElement.node_x); m_minNodeY = qMin (m_minNodeY, parsedElement.node_y); m_maxNodeX = qMax (m_maxNodeX, parsedElement.node_x); m_maxNodeY = qMax (m_maxNodeY, parsedElement.node_y); AnimNodeAddEvent * ev = new AnimNodeAddEvent (parsedElement.nodeId, parsedElement.node_x, parsedElement.node_y, parsedElement.nodeDescription, parsedElement.node_r, parsedElement.node_g, parsedElement.node_b); pAnimatorMode->addAnimEvent (0, ev); AnimNodeMgr::getInstance ()->addAPosition (parsedElement.nodeId, 0, QPointF (parsedElement.node_x, parsedElement.node_y)); break; } case XML_WPACKET_RX: case XML_PACKET_RX: { m_firstPacketTime = qMin (m_firstPacketTime, parsedElement.packetrx_fbTx); if (parsedElement.packetrx_fromId == parsedElement.packetrx_toId) break; uint8_t numWirelessSlots = 3; AnimPacketEvent * ev = new AnimPacketEvent (parsedElement.packetrx_fromId, parsedElement.packetrx_toId, parsedElement.packetrx_fbTx, parsedElement.packetrx_fbRx, parsedElement.packetrx_lbTx, parsedElement.packetrx_lbRx, parsedElement.isWpacket, parsedElement.meta_info, numWirelessSlots); pAnimatorMode->addAnimEvent (parsedElement.packetrx_fbTx, ev); ++parsedElementCount; m_lastPacketEventTime = parsedElement.packetrx_fbRx; if (parsedElementCount == 50) m_thousandThPacketTime = parsedElement.packetrx_lbRx; if (!parsedElement.isWpacket) { qreal fullDuration = parsedElement.packetrx_lbRx - parsedElement.packetrx_fbTx; uint32_t numSlots = WIRED_PACKET_SLOTS; qreal step = fullDuration/numSlots; for (uint32_t i = 1; i <= numSlots; ++i) { qreal point = parsedElement.packetrx_fbTx + (i * step); //NS_LOG_DEBUG ("Point:" << point); pAnimatorMode->addAnimEvent (point, new AnimWiredPacketUpdateEvent ()); } } //NS_LOG_DEBUG ("Packet Last Time:" << m_lastPacketEventTime); break; } case XML_LINK: { //AnimLinkMgr::getInstance ()->add (parsedElement.link_fromId, parsedElement.link_toId); AnimLinkAddEvent * ev = new AnimLinkAddEvent (parsedElement.link_fromId, parsedElement.link_toId, parsedElement.linkDescription, parsedElement.fromNodeDescription, parsedElement.toNodeDescription); pAnimatorMode->addAnimEvent (0, ev); break; } case XML_NONP2P_LINK: { AnimLinkAddEvent * ev = new AnimLinkAddEvent (parsedElement.link_fromId, parsedElement.link_toId, parsedElement.linkDescription, parsedElement.fromNodeDescription, parsedElement.toNodeDescription, false); pAnimatorMode->addAnimEvent (0, ev); break; } case XML_LINKUPDATE: { AnimLinkUpdateEvent * ev = new AnimLinkUpdateEvent (parsedElement.link_fromId, parsedElement.link_toId, parsedElement.linkDescription); pAnimatorMode->addAnimEvent (parsedElement.updateTime, ev); break; } case XML_BACKGROUNDIMAGE: { BackgroudImageProperties_t bgProp; bgProp.fileName = parsedElement.fileName; bgProp.x = parsedElement.x; bgProp.y = parsedElement.y; bgProp.scaleX = parsedElement.scaleX; bgProp.scaleY = parsedElement.scaleY; bgProp.opacity = parsedElement.opacity; AnimatorMode::getInstance ()->setBackgroundImageProperties (bgProp); break; } case XML_RESOURCE: { AnimResourceManager::getInstance ()->add (parsedElement.resourceId, parsedElement.resourcePath); break; } case XML_CREATE_NODE_COUNTER: { AnimCreateNodeCounterEvent * ev = 0; if (parsedElement.nodeCounterType == ParsedElement::UINT32_COUNTER) ev = new AnimCreateNodeCounterEvent (parsedElement.nodeCounterId, parsedElement.nodeCounterName, AnimCreateNodeCounterEvent::UINT32_COUNTER); if (parsedElement.nodeCounterType == ParsedElement::DOUBLE_COUNTER) ev = new AnimCreateNodeCounterEvent (parsedElement.nodeCounterId, parsedElement.nodeCounterName, AnimCreateNodeCounterEvent::DOUBLE_COUNTER); if (ev) { pAnimatorMode->addAnimEvent (0, ev); } break; } case XML_NODECOUNTER_UPDATE: { AnimNodeCounterUpdateEvent * ev = new AnimNodeCounterUpdateEvent (parsedElement.nodeCounterId, parsedElement.nodeId, parsedElement.nodeCounterValue); pAnimatorMode->addAnimEvent (parsedElement.updateTime, ev); break; } case XML_NODEUPDATE: { if (parsedElement.nodeUpdateType == ParsedElement::POSITION) { AnimNodePositionUpdateEvent * ev = new AnimNodePositionUpdateEvent (parsedElement.nodeId, parsedElement.node_x, parsedElement.node_y); pAnimatorMode->addAnimEvent (parsedElement.updateTime, ev); AnimNodeMgr::getInstance ()->addAPosition (parsedElement.nodeId, parsedElement.updateTime, QPointF (parsedElement.node_x, parsedElement.node_y)); m_minNodeX = qMin (m_minNodeX, parsedElement.node_x); m_minNodeY = qMin (m_minNodeY, parsedElement.node_y); m_maxNodeX = qMax (m_maxNodeX, parsedElement.node_x); m_maxNodeY = qMax (m_maxNodeY, parsedElement.node_y); } if (parsedElement.nodeUpdateType == ParsedElement::COLOR) { AnimNodeColorUpdateEvent * ev = new AnimNodeColorUpdateEvent (parsedElement.nodeId, parsedElement.node_r, parsedElement.node_g, parsedElement.node_b); pAnimatorMode->addAnimEvent (parsedElement.updateTime, ev); } if (parsedElement.nodeUpdateType == ParsedElement::DESCRIPTION) { AnimNodeDescriptionUpdateEvent * ev = new AnimNodeDescriptionUpdateEvent (parsedElement.nodeId, parsedElement.nodeDescription); pAnimatorMode->addAnimEvent (parsedElement.updateTime, ev); } if (parsedElement.nodeUpdateType == ParsedElement::SIZE) { AnimNodeSizeUpdateEvent * ev = new AnimNodeSizeUpdateEvent (parsedElement.nodeId, parsedElement.node_width, parsedElement.node_height); pAnimatorMode->addAnimEvent (parsedElement.updateTime, ev); } if (parsedElement.nodeUpdateType == ParsedElement::IMAGE) { AnimNodeImageUpdateEvent * ev = new AnimNodeImageUpdateEvent (parsedElement.nodeId, parsedElement.resourceId); pAnimatorMode->addAnimEvent (parsedElement.updateTime, ev); } break; } case XML_INVALID: default: { //qDebug ("Invalid XML element"); } } //switch } // while loop } ParsedElement Animxmlparser::parseNext () { ParsedElement parsedElement; parsedElement.type = XML_INVALID; parsedElement.version = m_version; parsedElement.isWpacket = false; if (m_reader->atEnd () || m_reader->hasError ()) { m_parsingComplete = true; m_traceFile->close (); return parsedElement; } QXmlStreamReader::TokenType token = m_reader->readNext (); if (token == QXmlStreamReader::StartDocument) return parsedElement; if (token == QXmlStreamReader::StartElement) { if (m_reader->name () == "anim") { parsedElement = parseAnim (); } if (m_reader->name () == "topology") { parsedElement = parseTopology (); } if (m_reader->name () == "node") { parsedElement = parseNode (); } if (m_reader->name () == "packet") { parsedElement = parsePacket (); } if (m_reader->name () == "p") { parsedElement = parseP (); } if (m_reader->name () == "wp") { parsedElement = parseWp (); } if (m_reader->name () == "wpacket") { parsedElement = parseWPacket (); } if (m_reader->name () == "link") { parsedElement = parseLink (); } if (m_reader->name () == "nonp2plinkproperties") { parsedElement = parseNonP2pLink (); } if (m_reader->name () == "linkupdate") { parsedElement = parseLinkUpdate (); } if (m_reader->name () == "nu") { parsedElement = parseNodeUpdate (); } if (m_reader->name () == "res") { parsedElement = parseResource (); } if (m_reader->name () == "bg") { parsedElement = parseBackground (); } if (m_reader->name () == "ncs") { parsedElement = parseCreateNodeCounter (); } if (m_reader->name () == "nc") { parsedElement = parseNodeCounterUpdate (); } //qDebug (m_reader->name ().toString ()); } if (m_reader->atEnd ()) { m_parsingComplete = true; m_traceFile->close (); } return parsedElement; } ParsedElement Animxmlparser::parseAnim () { ParsedElement parsedElement; parsedElement.type = XML_ANIM; parsedElement.version = m_version; QString v = m_reader->attributes ().value ("ver").toString (); if (!v.contains ("netanim-")) return parsedElement; v = v.replace ("netanim-",""); m_version = v.toDouble (); if (m_version < ANIM_MIN_VERSION) { AnimatorMode::getInstance ()->showPopup ("This XML format is not supported. Minimum Version:" + QString::number (ANIM_MIN_VERSION)); NS_FATAL_ERROR ("This XML format is not supported. Minimum Version:" << ANIM_MIN_VERSION); } parsedElement.version = m_version; //qDebug (QString::number (m_version)); return parsedElement; } ParsedElement Animxmlparser::parseTopology () { ParsedElement parsedElement; parsedElement.type = XML_TOPOLOGY; parsedElement.topo_width = m_reader->attributes ().value ("maxX").toString ().toDouble (); parsedElement.topo_height = m_reader->attributes ().value ("maxY").toString ().toDouble (); return parsedElement; } ParsedElement Animxmlparser::parseLink () { ParsedElement parsedElement; parsedElement.type = XML_LINK; parsedElement.link_fromId = m_reader->attributes ().value ("fromId").toString ().toUInt (); parsedElement.link_toId = m_reader->attributes ().value ("toId").toString ().toDouble (); parsedElement.fromNodeDescription = m_reader->attributes ().value ("fd").toString (); parsedElement.toNodeDescription = m_reader->attributes ().value ("td").toString (); parsedElement.linkDescription = m_reader->attributes ().value ("ld").toString (); return parsedElement; } ParsedElement Animxmlparser::parseBackground () { ParsedElement parsedElement; parsedElement.type = XML_BACKGROUNDIMAGE; parsedElement.fileName = m_reader->attributes ().value ("f").toString (); parsedElement.x = m_reader->attributes ().value ("x").toString ().toDouble (); parsedElement.y = m_reader->attributes ().value ("y").toString ().toDouble (); parsedElement.scaleX = m_reader->attributes ().value ("sx").toString ().toDouble (); parsedElement.scaleY = m_reader->attributes ().value ("sy").toString ().toDouble (); parsedElement.opacity = m_reader->attributes ().value ("o").toString ().toDouble (); return parsedElement; } ParsedElement Animxmlparser::parseNonP2pLink () { ParsedElement parsedElement; parsedElement.type = XML_NONP2P_LINK; parsedElement.link_fromId = m_reader->attributes ().value ("id").toString ().toUInt (); parsedElement.fromNodeDescription = m_reader->attributes ().value ("ipv4Address").toString (); return parsedElement; } ParsedElement Animxmlparser::parseLinkUpdate () { ParsedElement parsedElement; parsedElement.type = XML_LINKUPDATE; parsedElement.link_fromId = m_reader->attributes ().value ("fromId").toString ().toUInt (); parsedElement.link_toId = m_reader->attributes ().value ("toId").toString ().toDouble (); parsedElement.linkDescription = m_reader->attributes ().value ("ld").toString (); parsedElement.updateTime = m_reader->attributes ().value ("t").toString ().toDouble (); setMaxSimulationTime (parsedElement.updateTime); return parsedElement; } ParsedElement Animxmlparser::parseNode () { ParsedElement parsedElement; parsedElement.type = XML_NODE; parsedElement.nodeId = m_reader->attributes ().value ("id").toString ().toUInt (); parsedElement.node_x = m_reader->attributes ().value ("locX").toString ().toDouble (); parsedElement.node_y = m_reader->attributes ().value ("locY").toString ().toDouble (); parsedElement.node_batteryCapacity = m_reader->attributes ().value ("rc").toString ().toDouble (); parsedElement.nodeDescription = m_reader->attributes ().value ("descr").toString (); parsedElement.node_r = m_reader->attributes ().value ("r").toString ().toUInt (); parsedElement.node_g = m_reader->attributes ().value ("g").toString ().toUInt (); parsedElement.node_b = m_reader->attributes ().value ("b").toString ().toUInt (); parsedElement.hasColorUpdate = !m_reader->attributes ().value ("r").isEmpty (); parsedElement.hasBattery = !m_reader->attributes ().value ("rc").isEmpty (); return parsedElement; } ParsedElement Animxmlparser::parseNodeUpdate () { ParsedElement parsedElement; parsedElement.type = XML_NODEUPDATE; QString nodeUpdateString = m_reader->attributes ().value ("p").toString (); if (nodeUpdateString == "p") parsedElement.nodeUpdateType = ParsedElement::POSITION; if (nodeUpdateString == "c") parsedElement.nodeUpdateType = ParsedElement::COLOR; if (nodeUpdateString == "d") parsedElement.nodeUpdateType = ParsedElement::DESCRIPTION; if (nodeUpdateString == "s") parsedElement.nodeUpdateType = ParsedElement::SIZE; if (nodeUpdateString == "i") parsedElement.nodeUpdateType = ParsedElement::IMAGE; parsedElement.updateTime = m_reader->attributes ().value ("t").toString ().toDouble (); setMaxSimulationTime (parsedElement.updateTime); parsedElement.nodeId = m_reader->attributes ().value ("id").toString ().toUInt (); switch (parsedElement.nodeUpdateType) { case ParsedElement::POSITION: parsedElement.node_x = m_reader->attributes ().value ("x").toString ().toDouble (); parsedElement.node_y = m_reader->attributes ().value ("y").toString ().toDouble (); break; case ParsedElement::COLOR: parsedElement.node_r = m_reader->attributes ().value ("r").toString ().toUInt (); parsedElement.node_g = m_reader->attributes ().value ("g").toString ().toUInt (); parsedElement.node_b = m_reader->attributes ().value ("b").toString ().toUInt (); break; case ParsedElement::DESCRIPTION: parsedElement.nodeDescription = m_reader->attributes ().value ("descr").toString (); break; case ParsedElement::SIZE: parsedElement.node_width = m_reader->attributes ().value ("w").toString ().toDouble (); parsedElement.node_height = m_reader->attributes ().value ("h").toString ().toDouble (); break; case ParsedElement::IMAGE: parsedElement.resourceId = m_reader->attributes ().value ("rid").toString ().toUInt (); break; } return parsedElement; } ParsedElement Animxmlparser::parseNodeCounterUpdate () { ParsedElement parsedElement; parsedElement.type = XML_NODECOUNTER_UPDATE; parsedElement.nodeCounterId = m_reader->attributes ().value ("c").toString ().toUInt (); parsedElement.nodeId = m_reader->attributes ().value ("i").toString ().toUInt (); parsedElement.updateTime = m_reader->attributes ().value ("t").toString ().toDouble (); parsedElement.nodeCounterValue = m_reader->attributes ().value ("v").toString ().toDouble (); setMaxSimulationTime (parsedElement.updateTime); return parsedElement; } ParsedElement Animxmlparser::parseCreateNodeCounter () { ParsedElement parsedElement; parsedElement.type = XML_CREATE_NODE_COUNTER; parsedElement.nodeCounterId = m_reader->attributes ().value ("ncId").toString ().toUInt (); parsedElement.nodeCounterName = m_reader->attributes ().value ("n").toString (); QString counterType = m_reader->attributes ().value ("t").toString (); if (counterType == "UINT32") parsedElement.nodeCounterType = ParsedElement::UINT32_COUNTER; if (counterType == "DOUBLE") parsedElement.nodeCounterType = ParsedElement::DOUBLE_COUNTER; return parsedElement; } ParsedElement Animxmlparser::parseResource () { ParsedElement parsedElement; parsedElement.type = XML_RESOURCE; parsedElement.resourceId = m_reader->attributes ().value ("rid").toString ().toUInt (); parsedElement.resourcePath = m_reader->attributes ().value ("p").toString (); return parsedElement; } void Animxmlparser::parseGeneric (ParsedElement & parsedElement) { parsedElement.packetrx_fromId = m_reader->attributes ().value ("fId").toString ().toUInt (); parsedElement.packetrx_fbTx = m_reader->attributes ().value ("fbTx").toString ().toDouble (); parsedElement.packetrx_lbTx = m_reader->attributes ().value ("lbTx").toString ().toDouble (); setMaxSimulationTime (parsedElement.packetrx_lbTx); parsedElement.packetrx_toId = m_reader->attributes ().value ("tId").toString ().toUInt (); parsedElement.packetrx_fbRx = m_reader->attributes ().value ("fbRx").toString ().toDouble (); parsedElement.packetrx_lbRx = m_reader->attributes ().value ("lbRx").toString ().toDouble (); setMaxSimulationTime (parsedElement.packetrx_lbRx); parsedElement.meta_info = m_reader->attributes ().value ("meta-info").toString (); if (parsedElement.meta_info == "") { parsedElement.meta_info = "null"; } } ParsedElement Animxmlparser::parseP () { ParsedElement parsedElement; parsedElement.isWpacket = false; parsedElement.type = XML_PACKET_RX; parseGeneric (parsedElement); return parsedElement; } ParsedElement Animxmlparser::parseWp () { ParsedElement parsedElement; parsedElement.type = XML_WPACKET_RX; parsedElement.isWpacket = true; parseGeneric (parsedElement); return parsedElement; } ParsedElement Animxmlparser::parsePacket () { ParsedElement parsedElement; parsedElement.type = XML_PACKET_RX; parsedElement.packetrx_fromId = m_reader->attributes ().value ("fromId").toString ().toUInt (); parsedElement.packetrx_fbTx = m_reader->attributes ().value ("fbTx").toString ().toDouble (); parsedElement.packetrx_lbTx = m_reader->attributes ().value ("lbTx").toString ().toDouble (); parsedElement.meta_info = "null"; setMaxSimulationTime (parsedElement.packetrx_lbTx); while (m_reader->name () != "rx") m_reader->readNext (); if (m_reader->atEnd () || m_reader->hasError ()) { m_parsingComplete = true; m_traceFile->close (); return parsedElement; } parsedElement.packetrx_toId = m_reader->attributes ().value ("toId").toString ().toUInt (); parsedElement.packetrx_fbRx = m_reader->attributes ().value ("fbRx").toString ().toDouble (); parsedElement.packetrx_lbRx = m_reader->attributes ().value ("lbRx").toString ().toDouble (); setMaxSimulationTime (parsedElement.packetrx_lbRx); while (m_reader->name () == "rx") m_reader->readNext (); if (m_reader->name () == "packet") return parsedElement; m_reader->readNext (); if (m_reader->name () != "meta") return parsedElement; parsedElement.meta_info = m_reader->attributes ().value ("info").toString (); //qDebug (parsedElement.meta_info); return parsedElement; } ParsedElement Animxmlparser::parseWPacket () { ParsedElement parsedElement; parsedElement.type = XML_WPACKET_RX; parsedElement.packetrx_fromId = m_reader->attributes ().value ("fromId").toString ().toUInt (); parsedElement.packetrx_fbTx = m_reader->attributes ().value ("fbTx").toString ().toDouble (); parsedElement.packetrx_lbTx = m_reader->attributes ().value ("lbTx").toString ().toDouble (); parsedElement.meta_info = "null"; setMaxSimulationTime (parsedElement.packetrx_lbTx); while (m_reader->name () != "rx") m_reader->readNext (); if (m_reader->atEnd () || m_reader->hasError ()) { m_parsingComplete = true; m_traceFile->close (); return parsedElement; } //qDebug (m_reader->name ().toString ()+"parseWpacket"); parsedElement.packetrx_toId = m_reader->attributes ().value ("toId").toString ().toUInt (); parsedElement.packetrx_fbRx = m_reader->attributes ().value ("fbRx").toString ().toDouble (); parsedElement.packetrx_lbRx = m_reader->attributes ().value ("lbRx").toString ().toDouble (); setMaxSimulationTime (parsedElement.packetrx_lbRx); while (m_reader->name () == "rx") m_reader->readNext (); if (m_reader->name () == "wpacket") return parsedElement; m_reader->readNext (); if (m_reader->name () != "meta") return parsedElement; parsedElement.meta_info = m_reader->attributes ().value ("info").toString (); //qDebug (parsedElement.meta_info); return parsedElement; } void Animxmlparser::setMaxSimulationTime (qreal t) { m_maxSimulationTime = std::max (m_maxSimulationTime, t); } double Animxmlparser::getMaxSimulationTime () { return m_maxSimulationTime; } } // namespace netanim
igodip/NetAnim
animxmlparser.cpp
C++
apache-2.0
26,765
package org.codelogger.utils; import static org.junit.Assert.assertEquals; import org.codelogger.utils.ValueUtils; import org.junit.Test; public class ValueUtilsTest { @Test public void getValue() { Long testLong = null; Long expectedLongValue = 0L; Long longValueOrNull = ValueUtils.getValue(testLong); assertEquals(expectedLongValue, longValueOrNull); testLong = 21L; longValueOrNull = ValueUtils.getValue(testLong); assertEquals(testLong, longValueOrNull); Integer testInteger = null; Integer expectedIntegerValue = 0; Integer intValueOrNull = ValueUtils.getValue(testInteger); assertEquals(expectedIntegerValue, intValueOrNull); testInteger = 21; intValueOrNull = ValueUtils.getValue(testInteger); assertEquals(testInteger, intValueOrNull); Double testDouble = null; Double expectedDoubleValue = 0D; Double doubleValueOrNull = ValueUtils.getValue(testDouble); assertEquals(expectedDoubleValue, doubleValueOrNull); testDouble = 21D; doubleValueOrNull = ValueUtils.getValue(testDouble); assertEquals(testDouble, doubleValueOrNull); Float testFloat = null; Float expectedFloatValue = 0F; Float floatValueOrNull = ValueUtils.getValue(testFloat); assertEquals(expectedFloatValue, floatValueOrNull); testFloat = 21F; floatValueOrNull = ValueUtils.getValue(testFloat); assertEquals(testFloat, floatValueOrNull); Number testNumber = null; Number expectedNumberValue = 0; Number numberValueOrNull = ValueUtils.getValue(testNumber); assertEquals(expectedNumberValue, numberValueOrNull); testNumber = 21F; numberValueOrNull = ValueUtils.getValue(testNumber); assertEquals(testNumber, numberValueOrNull); Boolean testBoolean = null; Boolean expectedBooleanValue = false; Boolean actualValue = ValueUtils.getValue(testBoolean); assertEquals(expectedBooleanValue, actualValue); testBoolean = false; actualValue = ValueUtils.getValue(testBoolean); assertEquals(expectedBooleanValue, actualValue); testBoolean = true; expectedBooleanValue = true; actualValue = ValueUtils.getValue(testBoolean); assertEquals(expectedBooleanValue, actualValue); } @Test public void toString_long() { String expected = "321396"; System.out.println(ValueUtils.toString(321396, 5)); String actual = ValueUtils.toString(321396, 5); assertEquals(expected, actual); expected = "000000000321396"; System.out.println(ValueUtils.toString(321396, 15)); actual = ValueUtils.toString(321396, 15); assertEquals(expected, actual); } }
defei/codelogger-utils
src/test/java/org/codelogger/utils/ValueUtilsTest.java
Java
apache-2.0
2,862
using System; using System.Reflection; namespace Foundation.ExtensionMethods { public static class TypeExtensions { /// <summary> /// Looks for a property of the specified type. If more than 1 matching property is found, an exception is thrown. /// </summary> /// <param name="type"></param> /// <param name="propertyType"></param> /// <returns></returns> public static PropertyInfo GetProperty(this Type type, Type propertyType) { if (type == null) throw new ArgumentNullException("type"); PropertyInfo propertyInfo = null; foreach( var property in type.GetProperties() ) { if( !property.PropertyType.Equals(propertyType) ) continue; // Have we already found a matching property? ThrowException.IfTrue<FoundationException>(propertyInfo != null, "More than 1 property with type {0} found in {1}", propertyType, type); propertyInfo = property; } return propertyInfo; } } }
DavidMoore/Foundation
Code/Foundation/ExtensionMethods/TypeExtensions.cs
C#
apache-2.0
1,150
# AUTOGENERATED FILE FROM balenalib/firefly-rk3288-debian:bookworm-build # remove several traces of debian python RUN apt-get purge -y python.* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 3.6.15 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.3.1 ENV SETUPTOOLS_VERSION 60.5.4 RUN set -x \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-armv7hf-libffi3.3.tar.gz" \ && echo "7ff252a91617ecbb724b79575986b5e5eb9398c6e500011d9359d7e729b36831 Python-$PYTHON_VERSION.linux-armv7hf-libffi3.3.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-armv7hf-libffi3.3.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-armv7hf-libffi3.3.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # install "virtualenv", since the vast majority of users of this image will want it RUN pip3 install --no-cache-dir virtualenv ENV PYTHON_DBUS_VERSION 1.2.18 # install dbus-python dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ libdbus-1-dev \ libdbus-glib-1-dev \ && rm -rf /var/lib/apt/lists/* \ && apt-get -y autoremove # install dbus-python RUN set -x \ && mkdir -p /usr/src/dbus-python \ && curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz" -o dbus-python.tar.gz \ && curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz.asc" -o dbus-python.tar.gz.asc \ && gpg --verify dbus-python.tar.gz.asc \ && tar -xzC /usr/src/dbus-python --strip-components=1 -f dbus-python.tar.gz \ && rm dbus-python.tar.gz* \ && cd /usr/src/dbus-python \ && PYTHON_VERSION=$(expr match "$PYTHON_VERSION" '\([0-9]*\.[0-9]*\)') ./configure \ && make -j$(nproc) \ && make install -j$(nproc) \ && cd / \ && rm -rf /usr/src/dbus-python # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config # set PYTHONPATH to point to dist-packages ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \ && echo "Running test-stack@python" \ && chmod +x test-stack@python.sh \ && bash test-stack@python.sh \ && rm -rf test-stack@python.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Bookworm \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.6.15, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
resin-io-library/base-images
balena-base-images/python/firefly-rk3288/debian/bookworm/3.6.15/build/Dockerfile
Dockerfile
apache-2.0
4,862
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alphadraco.watchface.analog; import android.app.Activity; import android.content.ComponentName; import android.os.Bundle; import android.support.wearable.companion.WatchFaceCompanion; import android.widget.TextView; public class AnalogConfigActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_analog_watch_face_config); ComponentName name = getIntent().getParcelableExtra(WatchFaceCompanion.EXTRA_WATCH_FACE_COMPONENT); TextView label = (TextView) findViewById(R.id.label); label.setText(label.getText() + " (" + name.getClassName() + ")"); } }
101010b/ADWatchFaceAnalog
Application/src/main/java/com/alphadraco/watchface/analog/AnalogConfigActivity.java
Java
apache-2.0
1,358
<!DOCTYPE html> <!--[if IE]><![endif]--> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Class iOSCallbackScheduler | Sensus Documentation </title> <meta name="viewport" content="width=device-width"> <meta name="title" content="Class iOSCallbackScheduler | Sensus Documentation "> <meta name="generator" content="docfx 2.31.0.0"> <link rel="shortcut icon" href="../images/favicon.ico"> <link rel="stylesheet" href="../styles/docfx.vendor.css"> <link rel="stylesheet" href="../styles/docfx.css"> <link rel="stylesheet" href="../styles/main.css"> <meta property="docfx:navrel" content="../toc.html"> <meta property="docfx:tocrel" content="toc.html"> <meta property="docfx:rel" content="../"> </head> <body data-spy="scroll" data-target="#affix"> <div id="wrapper"> <header> <nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../index.html"> <img id="logo" class="svg" src="../images/group-of-members-users-icon.png" alt=""> </a> </div> <div class="collapse navbar-collapse" id="navbar"> <form class="navbar-form navbar-right" role="search" id="search"> <div class="form-group"> <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off"> </div> </form> </div> </div> </nav> <div class="subnav navbar navbar-default"> <div class="container hide-when-search" id="breadcrumb"> <ul class="breadcrumb"> <li></li> </ul> </div> </div> </header> <div class="container body-content"> <div id="search-results"> <div class="search-list"></div> <div class="sr-items"></div> <ul id="pagination"></ul> </div> </div> <div role="main" class="container body-content hide-when-search"> <div class="sidenav hide-when-search"> <a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a> <div class="sidetoggle collapse" id="sidetoggle"> <div id="sidetoc"></div> </div> </div> <div class="article row grid-right"> <div class="col-md-10"> <article class="content wrap" id="_content" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler"> <h1 id="Sensus_iOS_Callbacks_iOSCallbackScheduler" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler" class="text-break">Class iOSCallbackScheduler </h1> <div class="markdown level0 summary"></div> <div class="markdown level0 conceptual"></div> <div class="inheritance"> <h5>Inheritance</h5> <div class="level0"><span class="xref">System.Object</span></div> <div class="level1"><a class="xref" href="Sensus.Callbacks.CallbackScheduler.html">CallbackScheduler</a></div> <div class="level2"><span class="xref">iOSCallbackScheduler</span></div> <div class="level3"><a class="xref" href="Sensus.iOS.Callbacks.UILocalNotifications.UILocalNotificationCallbackScheduler.html">UILocalNotificationCallbackScheduler</a></div> <div class="level3"><a class="xref" href="Sensus.iOS.Callbacks.UNUserNotifications.UNUserNotificationCallbackScheduler.html">UNUserNotificationCallbackScheduler</a></div> </div> <div classs="implements"> <h5>Implements</h5> <div><a class="xref" href="Sensus.iOS.Callbacks.IiOSCallbackScheduler.html">IiOSCallbackScheduler</a></div> <div><a class="xref" href="Sensus.Callbacks.ICallbackScheduler.html">ICallbackScheduler</a></div> </div> <div class="inheritedMembers"> <h5>Inherited Members</h5> <div> <a class="xref" href="Sensus.Callbacks.CallbackScheduler.html#Sensus_Callbacks_CallbackScheduler_SENSUS_CALLBACK_KEY">CallbackScheduler.SENSUS_CALLBACK_KEY</a> </div> <div> <a class="xref" href="Sensus.Callbacks.CallbackScheduler.html#Sensus_Callbacks_CallbackScheduler_ScheduleCallbackPlatformSpecific_Sensus_Callbacks_ScheduledCallback_">CallbackScheduler.ScheduleCallbackPlatformSpecific(ScheduledCallback)</a> </div> <div> <a class="xref" href="Sensus.Callbacks.CallbackScheduler.html#Sensus_Callbacks_CallbackScheduler_UnscheduleCallbackPlatformSpecific_Sensus_Callbacks_ScheduledCallback_">CallbackScheduler.UnscheduleCallbackPlatformSpecific(ScheduledCallback)</a> </div> <div> <a class="xref" href="Sensus.Callbacks.CallbackScheduler.html#Sensus_Callbacks_CallbackScheduler_ScheduleCallback_Sensus_Callbacks_ScheduledCallback_">CallbackScheduler.ScheduleCallback(ScheduledCallback)</a> </div> <div> <a class="xref" href="Sensus.Callbacks.CallbackScheduler.html#Sensus_Callbacks_CallbackScheduler_ContainsCallback_Sensus_Callbacks_ScheduledCallback_">CallbackScheduler.ContainsCallback(ScheduledCallback)</a> </div> <div> <a class="xref" href="Sensus.Callbacks.CallbackScheduler.html#Sensus_Callbacks_CallbackScheduler_TryGetCallback_System_String_">CallbackScheduler.TryGetCallback(String)</a> </div> <div> <a class="xref" href="Sensus.Callbacks.CallbackScheduler.html#Sensus_Callbacks_CallbackScheduler_RaiseCallbackAsync_Sensus_Callbacks_ScheduledCallback_System_Boolean_System_Action_System_Action_">CallbackScheduler.RaiseCallbackAsync(ScheduledCallback, Boolean, Action, Action)</a> </div> <div> <a class="xref" href="Sensus.Callbacks.CallbackScheduler.html#Sensus_Callbacks_CallbackScheduler_TestHealth">CallbackScheduler.TestHealth()</a> </div> <div> <a class="xref" href="Sensus.Callbacks.CallbackScheduler.html#Sensus_Callbacks_CallbackScheduler_CancelRaisedCallback_Sensus_Callbacks_ScheduledCallback_">CallbackScheduler.CancelRaisedCallback(ScheduledCallback)</a> </div> <div> <a class="xref" href="Sensus.Callbacks.CallbackScheduler.html#Sensus_Callbacks_CallbackScheduler_UnscheduleCallback_Sensus_Callbacks_ScheduledCallback_">CallbackScheduler.UnscheduleCallback(ScheduledCallback)</a> </div> </div> <h6><strong>Namespace</strong>: <a class="xref" href="Sensus.iOS.Callbacks.html">Sensus.iOS.Callbacks</a></h6> <h6><strong>Assembly</strong>: SensusiOS.dll</h6> <h5 id="Sensus_iOS_Callbacks_iOSCallbackScheduler_syntax">Syntax</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public abstract class iOSCallbackScheduler : CallbackScheduler, IiOSCallbackScheduler, ICallbackScheduler</code></pre> </div> <h3 id="constructors">Constructors </h3> <a id="Sensus_iOS_Callbacks_iOSCallbackScheduler__ctor_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.#ctor*"></a> <h4 id="Sensus_iOS_Callbacks_iOSCallbackScheduler__ctor" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.#ctor">iOSCallbackScheduler()</h4> <div class="markdown level1 summary"></div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">protected iOSCallbackScheduler()</code></pre> </div> <h3 id="fields">Fields </h3> <h4 id="Sensus_iOS_Callbacks_iOSCallbackScheduler_CALLBACK_NOTIFICATION_HORIZON_THRESHOLD" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.CALLBACK_NOTIFICATION_HORIZON_THRESHOLD">CALLBACK_NOTIFICATION_HORIZON_THRESHOLD</h4> <div class="markdown level1 summary"><p>The callback notification horizon threshold. When using notifications to schedule the timing of callbacks, we must decide when the delay of a callback execution necessitates a notification rather than executing immediately. This is in part a practical question, in that executing a callback immediately rather than using a notification can improve performance -- imagine the app coming to the foreground and executing the callback right away versus deferring it to a future notification. This is also an iOS API consideration, as the iOS system will not schedule a notification if its fire date is in the past by the time it gets around to doing the scheduling.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public static readonly TimeSpan CALLBACK_NOTIFICATION_HORIZON_THRESHOLD</code></pre> </div> <h5 class="fieldValue">Field Value</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.TimeSpan</span></td> <td></td> </tr> </tbody> </table> <h3 id="properties">Properties </h3> <a id="Sensus_iOS_Callbacks_iOSCallbackScheduler_CallbackIds_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.CallbackIds*"></a> <h4 id="Sensus_iOS_Callbacks_iOSCallbackScheduler_CallbackIds" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.CallbackIds">CallbackIds</h4> <div class="markdown level1 summary"></div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public abstract List&lt;string&gt; CallbackIds { get; }</code></pre> </div> <h5 class="propertyValue">Property Value</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.Collections.Generic.List</span>&lt;<span class="xref">System.String</span>&gt;</td> <td></td> </tr> </tbody> </table> <h3 id="methods">Methods </h3> <a id="Sensus_iOS_Callbacks_iOSCallbackScheduler_CancelSilentNotifications_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.CancelSilentNotifications*"></a> <h4 id="Sensus_iOS_Callbacks_iOSCallbackScheduler_CancelSilentNotifications" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.CancelSilentNotifications">CancelSilentNotifications()</h4> <div class="markdown level1 summary"><p>Cancels the silent notifications (e.g., those for health test) when the app is going into the background.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public abstract void CancelSilentNotifications()</code></pre> </div> <a id="Sensus_iOS_Callbacks_iOSCallbackScheduler_GetCallbackInfo_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.GetCallbackInfo*"></a> <h4 id="Sensus_iOS_Callbacks_iOSCallbackScheduler_GetCallbackInfo_Sensus_Callbacks_ScheduledCallback_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.GetCallbackInfo(Sensus.Callbacks.ScheduledCallback)">GetCallbackInfo(ScheduledCallback)</h4> <div class="markdown level1 summary"></div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public NSMutableDictionary GetCallbackInfo(ScheduledCallback callback)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="Sensus.Callbacks.ScheduledCallback.html">ScheduledCallback</a></td> <td><span class="parametername">callback</span></td> <td></td> </tr> </tbody> </table> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">Foundation.NSMutableDictionary</span></td> <td></td> </tr> </tbody> </table> <a id="Sensus_iOS_Callbacks_iOSCallbackScheduler_IsCallback_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.IsCallback*"></a> <h4 id="Sensus_iOS_Callbacks_iOSCallbackScheduler_IsCallback_Foundation_NSDictionary_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.IsCallback(Foundation.NSDictionary)">IsCallback(NSDictionary)</h4> <div class="markdown level1 summary"></div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public bool IsCallback(NSDictionary callbackInfo)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">Foundation.NSDictionary</span></td> <td><span class="parametername">callbackInfo</span></td> <td></td> </tr> </tbody> </table> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.Boolean</span></td> <td></td> </tr> </tbody> </table> <a id="Sensus_iOS_Callbacks_iOSCallbackScheduler_OpenDisplayPage_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.OpenDisplayPage*"></a> <h4 id="Sensus_iOS_Callbacks_iOSCallbackScheduler_OpenDisplayPage_Foundation_NSDictionary_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.OpenDisplayPage(Foundation.NSDictionary)">OpenDisplayPage(NSDictionary)</h4> <div class="markdown level1 summary"></div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public void OpenDisplayPage(NSDictionary notificationInfo)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">Foundation.NSDictionary</span></td> <td><span class="parametername">notificationInfo</span></td> <td></td> </tr> </tbody> </table> <a id="Sensus_iOS_Callbacks_iOSCallbackScheduler_ReissueSilentNotification_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.ReissueSilentNotification*"></a> <h4 id="Sensus_iOS_Callbacks_iOSCallbackScheduler_ReissueSilentNotification_System_String_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.ReissueSilentNotification(System.String)">ReissueSilentNotification(String)</h4> <div class="markdown level1 summary"></div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">protected abstract void ReissueSilentNotification(string id)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.String</span></td> <td><span class="parametername">id</span></td> <td></td> </tr> </tbody> </table> <a id="Sensus_iOS_Callbacks_iOSCallbackScheduler_ServiceCallbackAsync_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.ServiceCallbackAsync*"></a> <h4 id="Sensus_iOS_Callbacks_iOSCallbackScheduler_ServiceCallbackAsync_Foundation_NSDictionary_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.ServiceCallbackAsync(Foundation.NSDictionary)">ServiceCallbackAsync(NSDictionary)</h4> <div class="markdown level1 summary"></div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public Task ServiceCallbackAsync(NSDictionary callbackInfo)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">Foundation.NSDictionary</span></td> <td><span class="parametername">callbackInfo</span></td> <td></td> </tr> </tbody> </table> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.Threading.Tasks.Task</span></td> <td></td> </tr> </tbody> </table> <a id="Sensus_iOS_Callbacks_iOSCallbackScheduler_ServiceCallbackAsync_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.ServiceCallbackAsync*"></a> <h4 id="Sensus_iOS_Callbacks_iOSCallbackScheduler_ServiceCallbackAsync_Sensus_Callbacks_ScheduledCallback_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.ServiceCallbackAsync(Sensus.Callbacks.ScheduledCallback)">ServiceCallbackAsync(ScheduledCallback)</h4> <div class="markdown level1 summary"></div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public Task ServiceCallbackAsync(ScheduledCallback callback)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="Sensus.Callbacks.ScheduledCallback.html">ScheduledCallback</a></td> <td><span class="parametername">callback</span></td> <td></td> </tr> </tbody> </table> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.Threading.Tasks.Task</span></td> <td></td> </tr> </tbody> </table> <a id="Sensus_iOS_Callbacks_iOSCallbackScheduler_TryGetCallback_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.TryGetCallback*"></a> <h4 id="Sensus_iOS_Callbacks_iOSCallbackScheduler_TryGetCallback_Foundation_NSDictionary_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.TryGetCallback(Foundation.NSDictionary)">TryGetCallback(NSDictionary)</h4> <div class="markdown level1 summary"></div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public ScheduledCallback TryGetCallback(NSDictionary callbackInfo)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">Foundation.NSDictionary</span></td> <td><span class="parametername">callbackInfo</span></td> <td></td> </tr> </tbody> </table> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="Sensus.Callbacks.ScheduledCallback.html">ScheduledCallback</a></td> <td></td> </tr> </tbody> </table> <a id="Sensus_iOS_Callbacks_iOSCallbackScheduler_UpdateCallbacksAsync_" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.UpdateCallbacksAsync*"></a> <h4 id="Sensus_iOS_Callbacks_iOSCallbackScheduler_UpdateCallbacksAsync" data-uid="Sensus.iOS.Callbacks.iOSCallbackScheduler.UpdateCallbacksAsync">UpdateCallbacksAsync()</h4> <div class="markdown level1 summary"><p>Updates the callbacks by running any that should have already been serviced or will be serviced in the near future. Also reissues all silent notifications, which would have been canceled when the app went into the background.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public Task UpdateCallbacksAsync()</code></pre> </div> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">System.Threading.Tasks.Task</span></td> <td><p>Async task.</p> </td> </tr> </tbody> </table> <h3 id="implements">Implements</h3> <div> <a class="xref" href="Sensus.iOS.Callbacks.IiOSCallbackScheduler.html">IiOSCallbackScheduler</a> </div> <div> <a class="xref" href="Sensus.Callbacks.ICallbackScheduler.html">ICallbackScheduler</a> </div> </article> </div> <div class="hidden-sm col-md-2" role="complementary"> <div class="sideaffix"> <div class="contribution"> <ul class="nav"> </ul> </div> <nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix"> <!-- <p><a class="back-to-top" href="#top">Back to top</a><p> --> </nav> </div> </div> </div> </div> <footer> <div class="grad-bottom"></div> <div class="footer"> <div class="container"> <span class="pull-right"> <a href="#top">Back to top</a> </span> Copyright © 2014-2018 University of Virginia<br>Generated by <strong>DocFX</strong> </div> </div> </footer> </div> <script type="text/javascript" src="../styles/docfx.vendor.js"></script> <script type="text/javascript" src="../styles/docfx.js"></script> <script type="text/javascript" src="../styles/main.js"></script> </body> </html>
jtb8vm/sensus
docs/api/Sensus.iOS.Callbacks.iOSCallbackScheduler.html
HTML
apache-2.0
24,025
/** * Autogenerated by Thrift for src/module.thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated @nocommit */ #include "thrift/compiler/test/fixtures/basic-structured-annotations/gen-cpp2/MyServiceAsyncClient.h" #include <thrift/lib/cpp2/gen/client_cpp.h> namespace cpp2 { typedef apache::thrift::ThriftPresult<false> MyService_first_pargs; typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::string, ::cpp2::annotated_inline_string*>> MyService_first_presult; typedef apache::thrift::ThriftPresult<false, apache::thrift::FieldData<1, ::apache::thrift::type_class::integral, ::std::int64_t*>> MyService_second_pargs; typedef apache::thrift::ThriftPresult<true, apache::thrift::FieldData<0, ::apache::thrift::type_class::integral, bool*>> MyService_second_presult; template <typename Protocol_, typename RpcOptions> void MyServiceAsyncClient::firstT(Protocol_* prot, RpcOptions&& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback) { MyService_first_pargs args; auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); }; auto writer = [&](Protocol_* p) { args.write(p); }; static ::apache::thrift::MethodMetadata::Data* methodMetadata = new ::apache::thrift::MethodMetadata::Data( "first", ::apache::thrift::FunctionQualifier::Unspecified); apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::forward<RpcOptions>(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer); } template <typename Protocol_, typename RpcOptions> void MyServiceAsyncClient::secondT(Protocol_* prot, RpcOptions&& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::std::int64_t p_count) { MyService_second_pargs args; args.get<0>().value = &p_count; auto sizer = [&](Protocol_* p) { return args.serializedSizeZC(p); }; auto writer = [&](Protocol_* p) { args.write(p); }; static ::apache::thrift::MethodMetadata::Data* methodMetadata = new ::apache::thrift::MethodMetadata::Data( "second", ::apache::thrift::FunctionQualifier::Unspecified); apache::thrift::clientSendT<apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, Protocol_>(prot, std::forward<RpcOptions>(rpcOptions), std::move(callback), contextStack, std::move(header), channel_.get(), ::apache::thrift::MethodMetadata::from_static(methodMetadata), writer, sizer); } void MyServiceAsyncClient::first(std::unique_ptr<apache::thrift::RequestCallback> callback) { ::apache::thrift::RpcOptions rpcOptions; first(rpcOptions, std::move(callback)); } void MyServiceAsyncClient::first(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback) { auto [ctx, header] = firstCtx(&rpcOptions); apache::thrift::RequestCallback::Context callbackContext; callbackContext.protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId(); auto* contextStack = ctx.get(); if (callback) { callbackContext.ctx = std::move(ctx); } auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext)); firstImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback)); } void MyServiceAsyncClient::firstImpl(apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, bool stealRpcOptions) { switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) { case apache::thrift::protocol::T_BINARY_PROTOCOL: { apache::thrift::BinaryProtocolWriter writer; if (stealRpcOptions) { firstT(&writer, std::move(rpcOptions), std::move(header), contextStack, std::move(callback)); } else { firstT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback)); } break; } case apache::thrift::protocol::T_COMPACT_PROTOCOL: { apache::thrift::CompactProtocolWriter writer; if (stealRpcOptions) { firstT(&writer, std::move(rpcOptions), std::move(header), contextStack, std::move(callback)); } else { firstT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback)); } break; } default: { apache::thrift::detail::ac::throw_app_exn("Could not find Protocol"); } } } std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> MyServiceAsyncClient::firstCtx(apache::thrift::RpcOptions* rpcOptions) { auto header = std::make_shared<apache::thrift::transport::THeader>( apache::thrift::transport::THeader::ALLOW_BIG_FRAMES); header->setProtocolId(channel_->getProtocolId()); if (rpcOptions) { header->setHeaders(rpcOptions->releaseWriteHeaders()); } auto ctx = apache::thrift::ContextStack::createWithClientContext( handlers_, getServiceName(), "MyService.first", *header); return {std::move(ctx), std::move(header)}; } void MyServiceAsyncClient::sync_first(::cpp2::annotated_inline_string& _return) { ::apache::thrift::RpcOptions rpcOptions; sync_first(rpcOptions, _return); } void MyServiceAsyncClient::sync_first(apache::thrift::RpcOptions& rpcOptions, ::cpp2::annotated_inline_string& _return) { apache::thrift::ClientReceiveState returnState; apache::thrift::ClientSyncCallback<false> callback(&returnState); auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId(); auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase(); auto ctxAndHeader = firstCtx(&rpcOptions); auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback); callback.waitUntilDone( evb, [&] { firstImpl(rpcOptions, std::move(ctxAndHeader.second), ctxAndHeader.first.get(), std::move(wrappedCallback)); }); if (returnState.isException()) { returnState.exception().throw_exception(); } returnState.resetProtocolId(protocolId); returnState.resetCtx(std::move(ctxAndHeader.first)); SCOPE_EXIT { if (returnState.header() && !returnState.header()->getHeaders().empty()) { rpcOptions.setReadHeaders(returnState.header()->releaseHeaders()); } }; return folly::fibers::runInMainContext([&] { recv_first(_return, returnState); }); } folly::Future<::cpp2::annotated_inline_string> MyServiceAsyncClient::future_first() { ::apache::thrift::RpcOptions rpcOptions; return future_first(rpcOptions); } folly::SemiFuture<::cpp2::annotated_inline_string> MyServiceAsyncClient::semifuture_first() { ::apache::thrift::RpcOptions rpcOptions; return semifuture_first(rpcOptions); } folly::Future<::cpp2::annotated_inline_string> MyServiceAsyncClient::future_first(apache::thrift::RpcOptions& rpcOptions) { folly::Promise<::cpp2::annotated_inline_string> promise; auto future = promise.getFuture(); auto callback = std::make_unique<apache::thrift::FutureCallback<::cpp2::annotated_inline_string>>(std::move(promise), recv_wrapped_first, channel_); first(rpcOptions, std::move(callback)); return future; } folly::SemiFuture<::cpp2::annotated_inline_string> MyServiceAsyncClient::semifuture_first(apache::thrift::RpcOptions& rpcOptions) { auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_first, channel_); auto callback = std::move(callbackAndFuture.first); first(rpcOptions, std::move(callback)); return std::move(callbackAndFuture.second); } folly::Future<std::pair<::cpp2::annotated_inline_string, std::unique_ptr<apache::thrift::transport::THeader>>> MyServiceAsyncClient::header_future_first(apache::thrift::RpcOptions& rpcOptions) { folly::Promise<std::pair<::cpp2::annotated_inline_string, std::unique_ptr<apache::thrift::transport::THeader>>> promise; auto future = promise.getFuture(); auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<::cpp2::annotated_inline_string>>(std::move(promise), recv_wrapped_first, channel_); first(rpcOptions, std::move(callback)); return future; } folly::SemiFuture<std::pair<::cpp2::annotated_inline_string, std::unique_ptr<apache::thrift::transport::THeader>>> MyServiceAsyncClient::header_semifuture_first(apache::thrift::RpcOptions& rpcOptions) { auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_first, channel_); auto callback = std::move(callbackAndFuture.first); first(rpcOptions, std::move(callback)); return std::move(callbackAndFuture.second); } void MyServiceAsyncClient::first(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback) { first(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback))); } #if FOLLY_HAS_COROUTINES #endif // FOLLY_HAS_COROUTINES folly::exception_wrapper MyServiceAsyncClient::recv_wrapped_first(::cpp2::annotated_inline_string& _return, ::apache::thrift::ClientReceiveState& state) { if (state.isException()) { return std::move(state.exception()); } if (!state.hasResponseBuffer()) { return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result"); } using result = MyService_first_presult; switch (state.protocolId()) { case apache::thrift::protocol::T_BINARY_PROTOCOL: { apache::thrift::BinaryProtocolReader reader; return apache::thrift::detail::ac::recv_wrapped<result>( &reader, state, _return); } case apache::thrift::protocol::T_COMPACT_PROTOCOL: { apache::thrift::CompactProtocolReader reader; return apache::thrift::detail::ac::recv_wrapped<result>( &reader, state, _return); } default: { } } return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol"); } void MyServiceAsyncClient::recv_first(::cpp2::annotated_inline_string& _return, ::apache::thrift::ClientReceiveState& state) { auto ew = recv_wrapped_first(_return, state); if (ew) { ew.throw_exception(); } } void MyServiceAsyncClient::recv_instance_first(::cpp2::annotated_inline_string& _return, ::apache::thrift::ClientReceiveState& state) { return recv_first(_return, state); } folly::exception_wrapper MyServiceAsyncClient::recv_instance_wrapped_first(::cpp2::annotated_inline_string& _return, ::apache::thrift::ClientReceiveState& state) { return recv_wrapped_first(_return, state); } void MyServiceAsyncClient::second(std::unique_ptr<apache::thrift::RequestCallback> callback, ::std::int64_t p_count) { ::apache::thrift::RpcOptions rpcOptions; second(rpcOptions, std::move(callback), p_count); } void MyServiceAsyncClient::second(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, ::std::int64_t p_count) { auto [ctx, header] = secondCtx(&rpcOptions); apache::thrift::RequestCallback::Context callbackContext; callbackContext.protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId(); auto* contextStack = ctx.get(); if (callback) { callbackContext.ctx = std::move(ctx); } auto wrappedCallback = apache::thrift::toRequestClientCallbackPtr(std::move(callback), std::move(callbackContext)); secondImpl(rpcOptions, std::move(header), contextStack, std::move(wrappedCallback), p_count); } void MyServiceAsyncClient::secondImpl(apache::thrift::RpcOptions& rpcOptions, std::shared_ptr<apache::thrift::transport::THeader> header, apache::thrift::ContextStack* contextStack, apache::thrift::RequestClientCallback::Ptr callback, ::std::int64_t p_count, bool stealRpcOptions) { switch (apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId()) { case apache::thrift::protocol::T_BINARY_PROTOCOL: { apache::thrift::BinaryProtocolWriter writer; if (stealRpcOptions) { secondT(&writer, std::move(rpcOptions), std::move(header), contextStack, std::move(callback), p_count); } else { secondT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_count); } break; } case apache::thrift::protocol::T_COMPACT_PROTOCOL: { apache::thrift::CompactProtocolWriter writer; if (stealRpcOptions) { secondT(&writer, std::move(rpcOptions), std::move(header), contextStack, std::move(callback), p_count); } else { secondT(&writer, rpcOptions, std::move(header), contextStack, std::move(callback), p_count); } break; } default: { apache::thrift::detail::ac::throw_app_exn("Could not find Protocol"); } } } std::pair<std::unique_ptr<::apache::thrift::ContextStack>, std::shared_ptr<::apache::thrift::transport::THeader>> MyServiceAsyncClient::secondCtx(apache::thrift::RpcOptions* rpcOptions) { auto header = std::make_shared<apache::thrift::transport::THeader>( apache::thrift::transport::THeader::ALLOW_BIG_FRAMES); header->setProtocolId(channel_->getProtocolId()); if (rpcOptions) { header->setHeaders(rpcOptions->releaseWriteHeaders()); } auto ctx = apache::thrift::ContextStack::createWithClientContext( handlers_, getServiceName(), "MyService.second", *header); return {std::move(ctx), std::move(header)}; } bool MyServiceAsyncClient::sync_second(::std::int64_t p_count) { ::apache::thrift::RpcOptions rpcOptions; return sync_second(rpcOptions, p_count); } bool MyServiceAsyncClient::sync_second(apache::thrift::RpcOptions& rpcOptions, ::std::int64_t p_count) { apache::thrift::ClientReceiveState returnState; apache::thrift::ClientSyncCallback<false> callback(&returnState); auto protocolId = apache::thrift::GeneratedAsyncClient::getChannel()->getProtocolId(); auto evb = apache::thrift::GeneratedAsyncClient::getChannel()->getEventBase(); auto ctxAndHeader = secondCtx(&rpcOptions); auto wrappedCallback = apache::thrift::RequestClientCallback::Ptr(&callback); callback.waitUntilDone( evb, [&] { secondImpl(rpcOptions, std::move(ctxAndHeader.second), ctxAndHeader.first.get(), std::move(wrappedCallback), p_count); }); if (returnState.isException()) { returnState.exception().throw_exception(); } returnState.resetProtocolId(protocolId); returnState.resetCtx(std::move(ctxAndHeader.first)); SCOPE_EXIT { if (returnState.header() && !returnState.header()->getHeaders().empty()) { rpcOptions.setReadHeaders(returnState.header()->releaseHeaders()); } }; return folly::fibers::runInMainContext([&] { return recv_second(returnState); }); } folly::Future<bool> MyServiceAsyncClient::future_second(::std::int64_t p_count) { ::apache::thrift::RpcOptions rpcOptions; return future_second(rpcOptions, p_count); } folly::SemiFuture<bool> MyServiceAsyncClient::semifuture_second(::std::int64_t p_count) { ::apache::thrift::RpcOptions rpcOptions; return semifuture_second(rpcOptions, p_count); } folly::Future<bool> MyServiceAsyncClient::future_second(apache::thrift::RpcOptions& rpcOptions, ::std::int64_t p_count) { folly::Promise<bool> promise; auto future = promise.getFuture(); auto callback = std::make_unique<apache::thrift::FutureCallback<bool>>(std::move(promise), recv_wrapped_second, channel_); second(rpcOptions, std::move(callback), p_count); return future; } folly::SemiFuture<bool> MyServiceAsyncClient::semifuture_second(apache::thrift::RpcOptions& rpcOptions, ::std::int64_t p_count) { auto callbackAndFuture = makeSemiFutureCallback(recv_wrapped_second, channel_); auto callback = std::move(callbackAndFuture.first); second(rpcOptions, std::move(callback), p_count); return std::move(callbackAndFuture.second); } folly::Future<std::pair<bool, std::unique_ptr<apache::thrift::transport::THeader>>> MyServiceAsyncClient::header_future_second(apache::thrift::RpcOptions& rpcOptions, ::std::int64_t p_count) { folly::Promise<std::pair<bool, std::unique_ptr<apache::thrift::transport::THeader>>> promise; auto future = promise.getFuture(); auto callback = std::make_unique<apache::thrift::HeaderFutureCallback<bool>>(std::move(promise), recv_wrapped_second, channel_); second(rpcOptions, std::move(callback), p_count); return future; } folly::SemiFuture<std::pair<bool, std::unique_ptr<apache::thrift::transport::THeader>>> MyServiceAsyncClient::header_semifuture_second(apache::thrift::RpcOptions& rpcOptions, ::std::int64_t p_count) { auto callbackAndFuture = makeHeaderSemiFutureCallback(recv_wrapped_second, channel_); auto callback = std::move(callbackAndFuture.first); second(rpcOptions, std::move(callback), p_count); return std::move(callbackAndFuture.second); } void MyServiceAsyncClient::second(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, ::std::int64_t p_count) { second(std::make_unique<apache::thrift::FunctionReplyCallback>(std::move(callback)), p_count); } #if FOLLY_HAS_COROUTINES #endif // FOLLY_HAS_COROUTINES folly::exception_wrapper MyServiceAsyncClient::recv_wrapped_second(bool& _return, ::apache::thrift::ClientReceiveState& state) { if (state.isException()) { return std::move(state.exception()); } if (!state.hasResponseBuffer()) { return folly::make_exception_wrapper<apache::thrift::TApplicationException>("recv_ called without result"); } using result = MyService_second_presult; switch (state.protocolId()) { case apache::thrift::protocol::T_BINARY_PROTOCOL: { apache::thrift::BinaryProtocolReader reader; return apache::thrift::detail::ac::recv_wrapped<result>( &reader, state, _return); } case apache::thrift::protocol::T_COMPACT_PROTOCOL: { apache::thrift::CompactProtocolReader reader; return apache::thrift::detail::ac::recv_wrapped<result>( &reader, state, _return); } default: { } } return folly::make_exception_wrapper<apache::thrift::TApplicationException>("Could not find Protocol"); } bool MyServiceAsyncClient::recv_second(::apache::thrift::ClientReceiveState& state) { bool _return; auto ew = recv_wrapped_second(_return, state); if (ew) { ew.throw_exception(); } return _return; } bool MyServiceAsyncClient::recv_instance_second(::apache::thrift::ClientReceiveState& state) { return recv_second(state); } folly::exception_wrapper MyServiceAsyncClient::recv_instance_wrapped_second(bool& _return, ::apache::thrift::ClientReceiveState& state) { return recv_wrapped_second(_return, state); } } // cpp2
facebook/fbthrift
thrift/compiler/test/fixtures/basic-structured-annotations/gen-cpp2/MyServiceAsyncClient.cpp
C++
apache-2.0
18,918
package com.happy.business.service; import java.util.List; import com.happy.business.User; /** * * @author Administrator * */ public interface UserService { public List<User> selectAll(); }
zyl-githab/happy
test-manager/manager-service/src/main/java/com/happy/business/service/UserService.java
Java
apache-2.0
200
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <HTML> <HEAD> <TITLE> DOM XSS Active Scan Rule - About </TITLE> </HEAD> <BODY BGCOLOR="#ffffff"> <H1>DOM XSS Active Scan Rule - About</H1> <H2>Source Code</H2> <a href="https://github.com/zaproxy/zap-extensions/tree/master/addOns/domxss">https://github.com/zaproxy/zap-extensions/tree/master/addOns/domxss</a> <H2>Authors</H2> Aabha Biyani, and the ZAP Dev Team <H2>History</H2> <H3>Version 9 - 2019-06-12</H3> <ul> <li>Use default browser when no browser is specified in the configuration rule.</li> </ul> <H3>Version 8 - 2019-06-07</H3> <ul> <li>Run with Firefox headless by default (Issue 3866).</li> <li>Depend on newer version of Selenium add-on.</li> </ul> <H3>Version 7</H3> <ul> <li>Issue 2918: Added an option to attack URL parameters.</li> </ul> <H3>Version 6</H3> <ul> <li>Minor code changes.</li> <li>Add XSS Polyglot (Issue 2322).</li> </ul> <H3>Version 5</H3> <ul> <li>Updated for 2.7.0.</li> </ul> <H3>Version 4</H3> <ul> <li>Allow to use newer versions of Firefox (Issue 3396).</li> <li>Provide the reason why the scanner was skipped.</li> </ul> </BODY> </HTML>
veggiespam/zap-extensions
addOns/domxss/src/main/javahelp/org/zaproxy/zap/extension/domxss/resources/help/contents/about.html
HTML
apache-2.0
1,153
// Copyright 2020 DeepMind Technologies Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <array> #include <ostream> #include <vector> #include "dm_robotics/support/status-matchers.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/btree_set.h" #include "absl/memory/memory.h" #include "absl/strings/str_join.h" #include "absl/types/span.h" #include "dm_robotics/controllers/lsqp/cartesian_6d_velocity_task.h" #include "dm_robotics/controllers/lsqp/collision_avoidance_constraint.h" #include "dm_robotics/controllers/lsqp/test_utils.h" #include "dm_robotics/least_squares_qp/common/identity_task.h" #include "dm_robotics/least_squares_qp/core/lsqp_stack_of_tasks_solver.h" #include "dm_robotics/mujoco/defs.h" #include "dm_robotics/mujoco/mjlib.h" #include "dm_robotics/mujoco/test_with_mujoco_model.h" #include "dm_robotics/mujoco/utils.h" #include "Eigen/Core" namespace dm_robotics { namespace { using ::dm_robotics::testing::ComputeObject6dJacobianForJoints; using ::dm_robotics::testing::ComputeObjectCartesian6dVelocityWithJacobian; using ::dm_robotics::testing::SetSubsetOfJointVelocities; using ::dm_robotics::testing::TestWithMujocoModel; using ::testing::ValuesIn; using ::testing::WithParamInterface; using IdentityTaskAndCollisionAvoidanceIntegrationTest = TestWithMujocoModel; std::string ToString(mjtObj obj) { switch (obj) { case mjtObj::mjOBJ_GEOM: return "Geom"; case mjtObj::mjOBJ_SITE: return "Site"; case mjtObj::mjOBJ_BODY: return "Body"; default: return "Unknown"; } } // Parameters and fixture for tests on a variety of MuJoCo objects. // Note: Only 1 DoF joints are used. struct Cartesian6dVelocityTaskTestParams { std::string object_name; mjtObj object_type; std::array<double, 6> target_velocity; absl::btree_set<int> joint_ids; friend std::ostream& operator<<( std::ostream& stream, const Cartesian6dVelocityTaskTestParams& param) { return stream << "(object_name[" << param.object_name << "], object_type[" << ToString(param.object_type) << "], target_velocity[" << absl::StrJoin(param.target_velocity.begin(), param.target_velocity.end(), ", ") << "], joint_ids[" << absl::StrJoin(param.joint_ids.begin(), param.joint_ids.end(), ", ") << "])"; } }; const Cartesian6dVelocityTaskTestParams& GetRightHandGeomTestParams() { static const Cartesian6dVelocityTaskTestParams* const kRightHandGeomTestParams = new Cartesian6dVelocityTaskTestParams{ "right_hand", mjtObj::mjOBJ_GEOM, {0.0450566, 0.0199436, 0.0199436, 0, 0.0071797, -0.0071797}, {16, 17, 18}}; return *kRightHandGeomTestParams; } const Cartesian6dVelocityTaskTestParams& GetLeftHandSiteTestParams() { static const Cartesian6dVelocityTaskTestParams* const kLeftHandSiteTestParams = new Cartesian6dVelocityTaskTestParams{ "left_hand", mjtObj::mjOBJ_SITE, {0.0312323, -0.0138245, 0.0138245, 0, 0.00497681, 0.00497681}, {19, 20, 21}}; return *kLeftHandSiteTestParams; } const Cartesian6dVelocityTaskTestParams& GetRightFootBodyTestParams() { static const Cartesian6dVelocityTaskTestParams* const kRightFootBodyTestParams = new Cartesian6dVelocityTaskTestParams{"right_foot", mjtObj::mjOBJ_BODY, {1.0, 0, 0, 0, 0, 0}, {1, 2, 3, 4, 5, 6, 7, 8, 9}}; return *kRightFootBodyTestParams; } class ParameterizedCartesian6dVelocityTaskTest : public WithParamInterface<Cartesian6dVelocityTaskTestParams>, public TestWithMujocoModel {}; INSTANTIATE_TEST_SUITE_P(ParameterizedCartesian6dVelocityTaskTests, ParameterizedCartesian6dVelocityTaskTest, ValuesIn({GetRightHandGeomTestParams(), GetLeftHandSiteTestParams(), GetRightFootBodyTestParams()})); // Tests that the computed joint velocities never result in collisions when // integrated, even when an identity task is biasing the resultant velocities // towards a Qpos in collision. TEST_F(IdentityTaskAndCollisionAvoidanceIntegrationTest, ComputedJointVelocitiesDoNotResultInCollisionsWhenIntegrated) { LoadModelFromXmlPath(kDmControlSuiteHumanoidXmlPath); constexpr double kCollisionDistanceTolerance = 1.0e-3; constexpr double kIntegrationTimestepSeconds = 1.0; CollisionAvoidanceConstraint::Parameters params; params.lib = mjlib_; params.model = model_.get(); params.collision_detection_distance = 0.3; params.minimum_normal_distance = 0.05; params.gain = 0.85 / kIntegrationTimestepSeconds; for (int i = 1; i < model_->njnt; ++i) { params.joint_ids.insert(i); } for (int i = 0; i < model_->ngeom; ++i) { for (int j = i + 1; j < model_->ngeom; ++j) { params.geom_pairs.insert(std::make_pair(i, j)); } } Eigen::VectorXd qvel_to_collision( Eigen::VectorXd::Zero(params.joint_ids.size())); // Instantiate a solver and add a task to move towards a pre-determined qpos // in collision, and a constraint to avoid collisions. Note that this is a // difficult problem to solve, with 326 constraint rows and 21 DoF, where the // target velocity is infeasible. LsqpStackOfTasksSolver qp_solver(LsqpStackOfTasksSolver::Parameters{ /*use_adaptive_rho=*/false, /*return_error_on_nullspace_failure=*/false, /*verbosity=*/LsqpStackOfTasksSolver::Parameters::VerboseFlags::kNone, /*absolute_tolerance=*/kCollisionDistanceTolerance, /*relative_tolerance=*/0.0, /*hierarchical_projection_slack=*/1.0e-5, /*primal_infeasibility_tolerance=*/1.0e-6, /*dual_infeasibility_tolerance=*/1.0e-6}); auto task = qp_solver.AddNewTaskHierarchy(10000) ->InsertOrAssignTask( "MoveToCollision", absl::make_unique<IdentityTask>(qvel_to_collision), 1.0, false) .first; auto constraint = qp_solver .InsertOrAssignConstraint( "CollisionAvoidance", absl::make_unique<CollisionAvoidanceConstraint>(params, *data_)) .first; ASSERT_OK(qp_solver.SetupProblem()); // Go through 1k integrations, to ensure that the computed velocities do not // eventually cause collisions. for (int i = 0; i < 1000; ++i) { // Set the collision velocities to move towards a collision position, and // update the collision avoidance constraint with the latest mjData. int joint_id_idx = 0; for (int joint_id : params.joint_ids) { const int qpos_adr = model_->jnt_qposadr[joint_id]; const double hi_lim = model_->jnt_range[2 * joint_id + 1]; const double low_lim = model_->jnt_range[2 * joint_id]; const double collision_qpos = 0.1 * hi_lim + 0.9 * low_lim; qvel_to_collision[joint_id_idx] = (collision_qpos - data_->qpos[qpos_adr]) / kIntegrationTimestepSeconds; ++joint_id_idx; } task->SetTarget(qvel_to_collision); constraint->UpdateCoefficientsAndBounds(*data_); // Solve the problem. Note that sparsity of the coefficient matrix may // change, and thus the solver may need to re-allocate memory. ASSERT_OK_AND_ASSIGN(absl::Span<const double> solution, qp_solver.Solve()); // Integrate the computed joint velocities in MuJoCo, and ensure that no // contacts are detected. joint_id_idx = 0; for (int joint_id : params.joint_ids) { const int dof_adr = model_->jnt_dofadr[joint_id]; data_->qvel[dof_adr] = solution[joint_id_idx]; ++joint_id_idx; } mjlib_->mj_integratePos(model_.get(), data_->qpos, data_->qvel, kIntegrationTimestepSeconds); mjlib_->mj_fwdPosition(model_.get(), data_.get()); EXPECT_EQ(data_->ncon, 0); } } // Tests that the computed joint velocities realize the target Cartesian // velocity. TEST_P(ParameterizedCartesian6dVelocityTaskTest, ComputedJointVelocitiesResultInTargetCartesian6dVelocities) { constexpr double kSolutionTolerance = 1.0e-10; LoadModelFromXmlPath(kDmControlSuiteHumanoidXmlPath); auto [kObjectName, kObjectType, kTargetVelocity, kJointIds] = GetParam(); Cartesian6dVelocityTask::Parameters params; params.lib = mjlib_; params.model = model_.get(); params.joint_ids = kJointIds; params.object_type = kObjectType; params.object_name = kObjectName; // Instantiate the solver and find a solution to the problem. LsqpStackOfTasksSolver qp_solver(LsqpStackOfTasksSolver::Parameters{ /*use_adaptive_rho=*/false, /*return_error_on_nullspace_failure=*/false, /*verbosity=*/LsqpStackOfTasksSolver::Parameters::VerboseFlags::kNone, /*absolute_tolerance=*/kSolutionTolerance, /*relative_tolerance=*/0.0, /*primal_infeasibility_tolerance=*/0.1 * kSolutionTolerance, /*dual_infeasibility_tolerance=*/0.1 * kSolutionTolerance}); qp_solver.AddNewTaskHierarchy(10000)->InsertOrAssignTask( "Cartesian", absl::make_unique<Cartesian6dVelocityTask>(params, *data_, kTargetVelocity), 1.0, false); ASSERT_OK(qp_solver.SetupProblem()); Eigen::internal::set_is_malloc_allowed(false); ASSERT_OK_AND_ASSIGN(absl::Span<const double> solution, qp_solver.Solve()); Eigen::internal::set_is_malloc_allowed(true); // Compute the realized Cartesian velocity and compare it with the target // Cartesian velocity. SetSubsetOfJointVelocities(*model_, kJointIds, solution, data_.get()); Eigen::Vector<double, 6> realized_cartesian_6d_vel( ComputeObjectCartesian6dVelocityWithJacobian(*mjlib_, *model_, *data_, kObjectName, kObjectType) .data()); Eigen::Map<Eigen::Vector<double, 6>> target_cartesian_6d_vel( kTargetVelocity.data()); // Ensure the realized Cartesian velocity is within tolerance of the target // velocity. // Note that for an unconstrained stack-of-tasks problem with one task that is // realizable, the `absolute_tolerance` represents how far from optimality the // solution is, measured by: // e_dual = W ||J^T J qvel - (xdot_target^T J)^T||_inf // e_dual = W ||J^T xdot_target - J^T xdot_realized||_inf Eigen::MatrixXd jacobian = Eigen::Map<Eigen::MatrixXd>( ComputeObject6dJacobianForJoints(*mjlib_, *model_, *data_, kObjectType, kObjectName, kJointIds) .data(), 6, kJointIds.size()); double e_dual = (jacobian.transpose() * (realized_cartesian_6d_vel - target_cartesian_6d_vel)) .lpNorm<Eigen::Infinity>(); EXPECT_LE(e_dual, kSolutionTolerance); } // Tests that UpdateCoefficientsAndBias updates the coefficients matrix and bias // to the correct values. TEST_P(ParameterizedCartesian6dVelocityTaskTest, UpdateCoefficientsAndBiasUpdatesCoefficientMatrixAndBias) { constexpr double kSolutionTolerance = 1.0e-10; LoadModelFromXmlPath(kDmControlSuiteHumanoidXmlPath); auto [kObjectName, kObjectType, kTargetVelocity, kJointIds] = GetParam(); Cartesian6dVelocityTask::Parameters params; params.lib = mjlib_; params.model = model_.get(); params.joint_ids = kJointIds; params.object_type = kObjectType; params.object_name = kObjectName; // Instantiate the solver and set up the problem, but do not solve yet. LsqpStackOfTasksSolver qp_solver(LsqpStackOfTasksSolver::Parameters{ /*use_adaptive_rho=*/false, /*return_error_on_nullspace_failure=*/false, /*verbosity=*/LsqpStackOfTasksSolver::Parameters::VerboseFlags::kNone, /*absolute_tolerance=*/kSolutionTolerance, /*relative_tolerance=*/0.0, /*primal_infeasibility_tolerance=*/1.0e-6, /*dual_infeasibility_tolerance=*/1.0e-6}); auto hierarchy = qp_solver.AddNewTaskHierarchy(10000); auto [task, is_inserted] = hierarchy->InsertOrAssignTask("Cartesian", absl::make_unique<Cartesian6dVelocityTask>( params, *data_, kTargetVelocity), 1.0, false); ASSERT_OK(qp_solver.SetupProblem()); // Update coefficients and bias to set the object target velocity to zero, and // solve the problem. task->UpdateCoefficientsAndBias(*data_, {0, 0, 0, 0, 0, 0}); Eigen::internal::set_is_malloc_allowed(false); ASSERT_OK_AND_ASSIGN(absl::Span<const double> solution, qp_solver.Solve()); Eigen::internal::set_is_malloc_allowed(true); // Compute the realized Cartesian velocity and compare it with the target // Cartesian velocity. SetSubsetOfJointVelocities(*model_, kJointIds, solution, data_.get()); Eigen::Vector<double, 6> realized_cartesian_6d_vel( ComputeObjectCartesian6dVelocityWithJacobian(*mjlib_, *model_, *data_, kObjectName, kObjectType) .data()); // Ensure the realized Cartesian velocity is within tolerance of the target // velocity. // Note that for an unconstrained stack-of-tasks problem with one task that is // realizable, the `absolute_tolerance` represents how far from optimality the // solution is, measured by: // e_dual = W ||J^T J qvel - (xdot_target^T J)^T||_inf // e_dual = W ||J^T xdot_target - J^T xdot_realized||_inf Eigen::MatrixXd jacobian = Eigen::Map<Eigen::MatrixXd>( ComputeObject6dJacobianForJoints(*mjlib_, *model_, *data_, kObjectType, kObjectName, kJointIds) .data(), 6, kJointIds.size()); double e_dual = (jacobian.transpose() * realized_cartesian_6d_vel) .lpNorm<Eigen::Infinity>(); EXPECT_LE(e_dual, kSolutionTolerance); } } // namespace } // namespace dm_robotics
deepmind/dm_robotics
cpp/controllers/lsqp/tests/integration_test.cc
C++
apache-2.0
14,587
package com.github.upelsin.streamProxy; import com.squareup.okhttp.Headers; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import okio.BufferedSink; import okio.BufferedSource; import okio.Okio; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.ServerSocket; import java.net.Socket; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.logging.Level; import java.util.logging.Logger; import static com.github.upelsin.streamProxy.Utils.*; public class StreamProxy implements Runnable { private Logger logger = Logger.getLogger(StreamProxy.class.getName()); private ServerSocket serverSocket; private Thread serverThread; private ExecutorService executor; private ForkedStreamFactory streamFactory; private Set<Socket> clientSockets = Collections.newSetFromMap(new ConcurrentHashMap<Socket, Boolean>()); private OkHttpClient client; public StreamProxy(ForkedStreamFactory streamFactory) { this.streamFactory = streamFactory; } public void start(int port) { try { serverSocket = new ServerSocket(port); serverSocket.setReuseAddress(port != 0); } catch (IOException e) { throw new ProxyNotStartedException(e); } client = new OkHttpClient(); ThreadFactory threadFactory = ExceptionHandlingThreadFactory.loggingExceptionThreadFactory(); executor = Executors.newCachedThreadPool(threadFactory); serverThread = threadFactory.newThread(this); serverThread.start(); } public void start() { start(0); } public void shutdown() { if (serverThread == null) { throw new IllegalStateException("Cannot shutdown proxy, it has not been started"); } executor.shutdownNow(); closeClientSockets(); serverThread.interrupt(); closeQuietly(serverSocket); joinUninterruptibly(serverThread); serverThread = null; } private void closeClientSockets() { for (Iterator<Socket> s = clientSockets.iterator(); s.hasNext(); ) { closeQuietly(s.next()); s.remove(); } } @Override public void run() { if (serverThread == null) { throw new IllegalStateException("Proxy must be started first"); } while (!Thread.currentThread().isInterrupted()) { try { final Socket clientSocket = serverSocket.accept(); executor.execute(new Runnable() { @Override public void run() { serveClientRequest(clientSocket); } }); } catch (RuntimeException e) { // protect while(){} from any runtime exception Thread t = Thread.currentThread(); t.getUncaughtExceptionHandler().uncaughtException(t, e); } catch (IOException e) { logger.log(Level.WARNING, "Exception while accepting connection from client", e); } } } private void serveClientRequest(final Socket clientSocket) { clientSockets.add(clientSocket); BufferedSource source = null; try { source = Okio.buffer(Okio.source(clientSocket)); String url = parseGetRequestUrl(source); Properties queryParams = parseQueryParams(url); Response response = executeRealRequest(source, url); if (Thread.currentThread().isInterrupted()) return; writeClientResponse(clientSocket, response, queryParams); } catch (IOException e) { logger.log(Level.WARNING, "Exception while serving client request", e); } finally { closeQuietly(source); clientSockets.remove(clientSocket); } } private Properties parseQueryParams(String url) throws UnsupportedEncodingException { Properties queryParams = new Properties(); Map<String, List<String>> mappedParams = getUrlParameters(url); for (Map.Entry<String, List<String>> entry : mappedParams.entrySet()) { queryParams.setProperty(entry.getKey(), entry.getValue().get(0)); } return queryParams; } private String parseGetRequestUrl(BufferedSource source) throws IOException { String requestLine = source.readUtf8LineStrict(); StringTokenizer st = new StringTokenizer(requestLine); String method = st.nextToken(); if (!method.equalsIgnoreCase("GET")) { throw new ProxyRequestNotSupportedException("Unable to serve request, only GET is supported"); } String url = st.nextToken(); return url.substring(1); // skip leading "/" } private Headers.Builder buildHeaders(BufferedSource source) throws IOException { Headers.Builder headers = new Headers.Builder(); String header; while ((header = source.readUtf8LineStrict()).length() != 0) { headers.add(header); } return headers; } private Response executeRealRequest(BufferedSource source, String realUri) throws IOException { Headers.Builder headers = buildHeaders(source); Request request = new Request.Builder() .url(realUri) .headers(headers.build()) .build(); return client.newCall(request).execute(); } private void writeClientResponse(Socket clientSocket, Response response, Properties props) throws IOException { ForkedStream forkedStream = streamFactory.createForkedStream(props); try { writeResponse(clientSocket, response, forkedStream); } catch (IOException e) { forkedStream.abort(); throw e; } finally { if (Thread.currentThread().isInterrupted()) { // might be called twice, but that's fine forkedStream.abort(); } } } private void writeResponse(Socket clientSocket, Response response, ForkedStream forkedStream) throws IOException { BufferedSource source = response.body().source(); BufferedSink sink = Okio.buffer(Okio.sink(clientSocket)); try { writeStatusLine(response, sink); writeHeaders(response, sink); sink.flush(); byte[] buffer = new byte[16384]; while (!Thread.currentThread().isInterrupted()) { int read = source.read(buffer); if (read == -1) { break; } sink.write(buffer, 0, read); sink.flush(); forkedStream.write(buffer, 0, read); forkedStream.flush(); } } finally { closeQuietly(source); closeQuietly(sink); closeQuietly(forkedStream); } } private void writeStatusLine(Response response, BufferedSink sink) throws IOException { String protocol = response.protocol().toString().toUpperCase(Locale.US); String statusLine = String.format("%s %d %s\r\n", protocol, response.code(), response.message()); sink.writeUtf8(statusLine); } private void writeHeaders(Response response, BufferedSink sink) throws IOException { Headers headers = response.headers(); for (int i = 0, size = headers.size(); i < size; i++) { sink.writeUtf8(headers.name(i)); sink.writeUtf8(": "); sink.writeUtf8(headers.value(i)); sink.writeUtf8("\r\n"); } sink.writeUtf8("\r\n"); } public int getPort() { if (serverThread == null) { throw new IllegalStateException("Proxy must be started before obtaining port number"); } return serverSocket.getLocalPort(); } public ForkedStreamFactory getForkedStreamFactory() { return streamFactory; } }
upelsin/MediaStreamProxy
src/main/java/com/github/upelsin/streamProxy/StreamProxy.java
Java
apache-2.0
8,255
package com.zxh.ssm.module.dynamicOutbreak.mapper; import com.zxh.ssm.module.dynamicOutbreak.pojo.Pretreatment; import org.apache.ibatis.annotations.Param; import java.util.List; /** * Created by 郑晓辉 on 2016/10/20. */ public interface PretreatmentMapper { List<Pretreatment> selectStandardPosition(@Param("province") String province) throws Exception; List<String> selectDisProvinces()throws Exception; }
Harveychn/MalariaProject
src/main/java/com/zxh/ssm/module/dynamicOutbreak/mapper/PretreatmentMapper.java
Java
apache-2.0
425
namespace NugetVisualizer.Core.FileSystem { using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using NugetVisualizer.Core.Domain; public class FileSystemRepositoryReader : IRepositoryReader { public List<IProjectIdentifier> GetProjects(string rootPath, string[] filters) { var projects = new List<IProjectIdentifier>(); ParseDirectory(rootPath, projects, SearchOption.TopDirectoryOnly); var projectDirectories = Directory.GetDirectories(rootPath, $"*{string.Join("*", filters)}*"); foreach (var projectDirectory in projectDirectories) { ParseDirectory(projectDirectory, projects, SearchOption.AllDirectories); } return projects.OrderBy(proj => proj.RepositoryName).ToList(); } public Task<List<IProjectIdentifier>> GetProjectsAsync(string rootPath, string[] filters) { return Task.FromResult(GetProjects(rootPath, filters)); } private void ParseDirectory(string projectDirectory, List<IProjectIdentifier> projects, SearchOption searchOption) { var allSolutions = Directory.GetFiles(projectDirectory, "*.sln", searchOption); foreach (var solution in allSolutions) { var fileName = Path.GetFileName(solution); var directoryName = Path.GetDirectoryName(solution); projects.Add(new ProjectIdentifier(fileName.Substring(0, fileName.Length - 4), directoryName, directoryName)); } } } }
sepharg/NugetVisualizer
NugetVisualizer/Core/FileSystem/FileSystemRepositoryReader.cs
C#
apache-2.0
1,650
package cn.edu.chd.adapter; import java.util.List; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Point; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import cn.edu.chd.domain.ImageBean; import cn.edu.chd.utils.NativeImageLoader; import cn.edu.chd.utils.NativeImageLoader.NativeImageLoaderCallback; import cn.edu.chd.yitu.R; public class GroupAdapter extends BaseAdapter { private List<ImageBean> list; private LayoutInflater inflater; private GridView mGridView; private Point mPoint; public GroupAdapter(List<ImageBean> list,GridView mGridView,Context context,Point point) { this.list = list; this.inflater = LayoutInflater.from(context); this.mGridView = mGridView; this.mPoint = point; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder vHolder = null; ImageBean bean = list.get(position); if(convertView == null) { convertView = inflater.inflate(R.layout.grid_group_item,null); vHolder = new ViewHolder(); vHolder.iv = (ImageView) convertView.findViewById(R.id.group_image); vHolder.tv = (TextView) convertView.findViewById(R.id.group_title); convertView.setTag(vHolder); }else { vHolder = (ViewHolder) convertView.getTag(); } vHolder.iv.setImageResource(R.drawable.pictures_no); vHolder.tv.setText(bean.getFolderName()); vHolder.iv.setTag(bean.getTopImagePath()); Bitmap bitmap = NativeImageLoader.getInstance().loadNativeImage(bean.getTopImagePath(), mPoint, new NativeImageLoaderCallback() { @Override public void onImageLoad(Bitmap bitmap, String path) { ImageView mImageView = (ImageView) mGridView.findViewWithTag(path); if(mImageView!=null && bitmap!=null) { mImageView.setImageBitmap(bitmap); } } }); if(bitmap!=null) { vHolder.iv.setImageBitmap(bitmap); } else { vHolder.iv.setImageResource(R.drawable.pictures_no); } return convertView; } private static class ViewHolder { ImageView iv; TextView tv; } }
Rowandjj/yitu
Yitu/src/cn/edu/chd/adapter/GroupAdapter.java
Java
apache-2.0
2,580
package com.example.eventbustest; import de.greenrobot.event.EventBus; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { TextView tv_1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EventBus.getDefault().register(this); tv_1 = (TextView) findViewById(R.id.tv_1); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } public void doClick(View view){ if(view.getId() == R.id.btn_1){ Intent intent = new Intent(this, SecondActivity.class); startActivity(intent); } else if(view.getId() == R.id.btn_2){ EventBus.getDefault().postSticky(new SecondEvent("second Event btn clicked")); } } public void onEventMainThread(FirstEvent event){ tv_1.setText(event.getMsg()); Toast.makeText(this, event.getMsg(), Toast.LENGTH_LONG).show(); } }
happyjie/eventBusTest
src/com/example/eventbustest/MainActivity.java
Java
apache-2.0
1,270
package org.visallo.webster; import org.visallo.webster.parameterProviders.ParameterProvider; import org.visallo.webster.parameterProviders.ParameterProviderFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.annotation.Annotation; import java.lang.reflect.Method; public class TestUserParameterProviderFactory extends ParameterProviderFactory<TestUser> { @Override public boolean isHandled(Method handleMethod, Class<? extends TestUser> parameterType, Annotation[] parameterAnnotations) { return TestUser.class.isAssignableFrom(parameterType); } @Override public ParameterProvider<TestUser> createParameterProvider(Method handleMethod, Class<?> parameterType, Annotation[] parameterAnnotations) { return new ParameterProvider<TestUser>() { @Override public TestUser getParameter(HttpServletRequest request, HttpServletResponse response, HandlerChain chain) { return new TestUser(request.getParameter("userId")); } }; } }
v5analytics/webster
webster/src/test/java/org/visallo/webster/TestUserParameterProviderFactory.java
Java
apache-2.0
1,093
import { DataEntity, get, set } from '@terascope/utils'; import { PostProcessConfig, InputOutputCardinality } from '../../../interfaces'; import TransformOpBase from './base'; export default class MakeArray extends TransformOpBase { private fields!: string[]; static cardinality: InputOutputCardinality = 'many-to-one'; constructor(config: PostProcessConfig) { super(config); } // source work differently here so we do not use the inherited validate protected validateConfig(config: PostProcessConfig): void { const { target: tField } = config; const fields = config.fields || config.sources; if (!tField || typeof tField !== 'string' || tField.length === 0) { const { name } = this.constructor; throw new Error( `could not find target for ${name} validation or it is improperly formatted, config: ${JSON.stringify(config)}` ); } if (!fields || !Array.isArray(fields) || fields.length === 0) { throw new Error(`array creation configuration is misconfigured, could not determine fields to join ${JSON.stringify(config)}`); } this.fields = fields; this.target = tField; } run(doc: DataEntity): DataEntity { const results: any[] = []; this.fields.forEach((field) => { const data = get(doc, field); if (data !== undefined) { if (Array.isArray(data)) { results.push(...data); } else { results.push(data); } } }); if (results.length > 0) set(doc, this.target, results); return doc; } }
terascope/teraslice
packages/ts-transforms/src/operations/lib/transforms/array.ts
TypeScript
apache-2.0
1,722
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifier */ /** * Smarty date_format modifier plugin * Type: modifier<br> * Name: date_format<br> * Purpose: format datestamps via strftime<br> * Input:<br> * - string: input date string * - format: strftime format for output * - default_date: default date if $string is empty * * @link http://www.smarty.net/manual/en/language.modifier.date.format.php date_format (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * * @param string $string input date string * @param string $format strftime format for output * @param string $default_date default date if $string is empty * @param string $formatter either 'strftime' or 'auto' * * @return string |void * @uses smarty_make_timestamp() */ function smarty_modifier_date_format($string, $format = null, $default_date = '', $formatter = 'auto') { if ($format === null) { $format = Smarty::$_DATE_FORMAT; } /** * require_once the {@link shared.make_timestamp.php} plugin */ require_once(SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php'); if ($string != '' && $string != '0000-00-00' && $string != '0000-00-00 00:00:00') { $timestamp = smarty_make_timestamp($string); } elseif ($default_date != '') { $timestamp = smarty_make_timestamp($default_date); } else { return; } if (false !== strpos($format, '#w')) { $weeks = ['天', '一', '二', '三', '四', '五', '六']; $week = $weeks[ date('w', $timestamp) ]; $format = str_replace('#w', $week, $format); } if ($formatter == 'strftime' || ($formatter == 'auto' && strpos($format, '%') !== false)) { if (DS == '\\') { $_win_from = ['%D', '%h', '%n', '%r', '%R', '%t', '%T']; $_win_to = ['%m/%d/%y', '%b', "\n", '%I:%M:%S %p', '%H:%M', "\t", '%H:%M:%S']; if (strpos($format, '%e') !== false) { $_win_from[] = '%e'; $_win_to[] = sprintf('%\' 2d', date('j', $timestamp)); } if (strpos($format, '%l') !== false) { $_win_from[] = '%l'; $_win_to[] = sprintf('%\' 2d', date('h', $timestamp)); } $format = str_replace($_win_from, $_win_to, $format); } return strftime($format, $timestamp); } else { return date($format, $timestamp); } }
songdent/PandaPHP
framework/sysvender/smarty/plugins/modifier.date_format.php
PHP
apache-2.0
2,487
# Copyright 2016-2017 Capital One Services, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. """ Cloud-Custodian AWS Lambda Entry Point """ from __future__ import absolute_import, division, print_function, unicode_literals import os import logging import json from c7n.config import Config from c7n.structure import StructureParser from c7n.resources import load_resources from c7n.policy import PolicyCollection from c7n.utils import format_event, get_account_id_from_sts, local_session import boto3 logging.root.setLevel(logging.DEBUG) logging.getLogger('botocore').setLevel(logging.WARNING) logging.getLogger('urllib3').setLevel(logging.WARNING) log = logging.getLogger('custodian.lambda') ########################################## # # Env var AWS Lambda specific configuration options, these are part of # our "public" interface and hence are subject to compatiblity constraints. # # Control whether custodian lambda policy skips events that represent errors. # We default to skipping events which denote they have errors. # Set with `export C7N_SKIP_EVTERR=no` to process error events C7N_SKIP_EVTERR = True # Control whether the triggering event is logged. # Set with `export C7N_DEBUG_EVENT=no` to disable event logging. C7N_DEBUG_EVENT = True # Control whether a policy failure will result in a lambda execution failure. # Lambda on error will report error metrics and depending on event source # automatically retry. # Set with `export C7N_CATCH_ERR=yes` C7N_CATCH_ERR = False ########################################## # # Internal global variables # # config.json policy data dict policy_data = None # execution options for the policy policy_config = None def init_env_globals(): """Set module level values from environment variables. Encapsulated here to enable better testing. """ global C7N_SKIP_EVTERR, C7N_DEBUG_EVENT, C7N_CATCH_ERR C7N_SKIP_EVTERR = os.environ.get( 'C7N_SKIP_ERR_EVENT', 'yes') == 'yes' and True or False C7N_DEBUG_EVENT = os.environ.get( 'C7N_DEBUG_EVENT', 'yes') == 'yes' and True or False C7N_CATCH_ERR = os.environ.get( 'C7N_CATCH_ERR', 'no').strip().lower() == 'yes' and True or False def init_config(policy_config): """Get policy lambda execution configuration. cli parameters are serialized into the policy lambda config, we merge those with any policy specific execution options. --assume role and -s output directory get special handling, as to disambiguate any cli context. account id is sourced from the config options or from api call and cached as a global. Todo: this should get refactored out to mu.py as part of the write out of configuration, instead of runtime processed. """ exec_options = policy_config.get('execution-options', {}) # Remove some configuration options that don't make sense to translate from # cli to lambda automatically. # - assume role on cli doesn't translate, it is the default lambda role and # used to provision the lambda. # - profile doesnt translate to lambda its `home` dir setup dependent # - dryrun doesn't translate (and shouldn't be present) # - region doesn't translate from cli (the lambda is bound to a region), and # on the cli represents the region the lambda is provisioned in. for k in ('assume_role', 'profile', 'region', 'dryrun', 'cache'): exec_options.pop(k, None) # a cli local directory doesn't translate to lambda if not exec_options.get('output_dir', '').startswith('s3'): exec_options['output_dir'] = '/tmp' account_id = None # we can source account id from the cli parameters to avoid the sts call if exec_options.get('account_id'): account_id = exec_options['account_id'] # merge with policy specific configuration exec_options.update( policy_config['policies'][0].get('mode', {}).get('execution-options', {})) # if using assume role in lambda ensure that the correct # execution account is captured in options. if 'assume_role' in exec_options: account_id = exec_options['assume_role'].split(':')[4] elif account_id is None: session = local_session(boto3.Session) account_id = get_account_id_from_sts(session) exec_options['account_id'] = account_id # Historical compatibility with manually set execution options # previously this was a boolean, its now a string value with the # boolean flag triggering a string value of 'aws' if 'metrics_enabled' in exec_options \ and isinstance(exec_options['metrics_enabled'], bool) \ and exec_options['metrics_enabled']: exec_options['metrics_enabled'] = 'aws' return Config.empty(**exec_options) # One time initilization of global environment settings init_env_globals() def dispatch_event(event, context): error = event.get('detail', {}).get('errorCode') if error and C7N_SKIP_EVTERR: log.debug("Skipping failed operation: %s" % error) return # one time initialization for cold starts. global policy_config, policy_data if policy_config is None: with open('config.json') as f: policy_data = json.load(f) policy_config = init_config(policy_data) load_resources(StructureParser().get_resource_types(policy_data)) if C7N_DEBUG_EVENT: event['debug'] = True log.info("Processing event\n %s", format_event(event)) if not policy_data or not policy_data.get('policies'): return False policies = PolicyCollection.from_data(policy_data, policy_config) for p in policies: try: # validation provides for an initialization point for # some filters/actions. p.validate() p.push(event, context) except Exception: log.exception("error during policy execution") if C7N_CATCH_ERR: continue raise return True
kapilt/cloud-custodian
c7n/handler.py
Python
apache-2.0
6,491
#import "ViewController.h" @protocol MWMSearchDownloadProtocol <NSObject> - (void)selectMapsAction; @end @interface MWMSearchDownloadViewController : ViewController - (nonnull instancetype)init __attribute__((unavailable("init is not available"))); - (nonnull instancetype)initWithDelegate:(nonnull id<MWMSearchDownloadProtocol>)delegate; - (void)downloadProgress:(CGFloat)progress countryName:(nonnull NSString *)countryName; - (void)setDownloadFailed; @end
Endika/omim
iphone/Maps/Classes/CustomViews/MapViewControls/Search/DownloadView/MWMSearchDownloadViewController.h
C
apache-2.0
466
<?php namespace service; require_once(__DIR__.'/../../lib.url.php'); require_once(__DIR__.'/../../class.exception.php'); class dispatch { function __construct($params) { $this->rules = $params; $this->root($_SERVER['REQUEST_URI']); } // // Getter for the matched parameters // public function url_pattern() {return $this->url_pattern;} public function request_url() {return $this->request_url;} public function frontend() {return $this->frontend;} public function frontend_path() {return __DIR__.'/../../../frontend/'.$this->frontend.'.php';} public function assignments() {return $this->assignments;} // // Walks over rules and tries to find a match for the // given request url. Stores the result in the class. // protected function root($request_url) { $this->request_url = \url\clean($request_url); foreach($this->rules as $rule) { $pattern = '@^' . $rule['url'] . '$@'; if (preg_match($pattern, $this->request_url)!==1) continue; $this->url_pattern = $rule['url']; $this->frontend = $rule['frontend']; $this->assignments = (isset($rule['assign']) ? $rule['assign'] : NULL); break; } $this->selfcheck(); } protected function selfcheck() { if (!file_exists($this->frontend_path())) { throw new \yawf_exception( 'Script file for frontend ['.$this->frontend().'] not found.', 'Provide the file or check its naming. The file is expected to reside at location: ['.\url\normalize($this->frontend_path()).']', 'While running *dispatch* service with parameters from config.yml'); } } protected $rules; protected $url_pattern; protected $request_url; protected $frontend; protected $assignments; } ?>
jotaen/yawf
core/service/dispatch/dispatch.php
PHP
apache-2.0
1,757
// THIS FILE WAS AUTO-GENERATED BY ADKGEN -- DO NOT MODIFY! // // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // using System; using System.Text; using System.Security.Permissions; using System.Runtime.Serialization; using OpenADK.Library; using OpenADK.Library.Global; using OpenADK.Library.au.Common; namespace OpenADK.Library.au.Sif3assessment{ /// <summary>A FormAccommodationList</summary> /// <remarks> /// /// <para>Author: Generated by adkgen</para> /// <para>Version: 2.6</para> /// <para>Since: 2.6</para> /// </remarks> [Serializable] public class FormAccommodationList : SifKeyedList<FormAccommodation> { /// <summary> /// Creates an instance of a FormAccommodationList /// </summary> public FormAccommodationList() : base ( Sif3assessmentDTD.FORMACCOMMODATIONLIST ){} /// <summary> /// Constructor that accepts values for all mandatory fields /// </summary> ///<param name="formAccommodation">A FormAccommodation</param> /// public FormAccommodationList( FormAccommodation formAccommodation ) : base( Sif3assessmentDTD.FORMACCOMMODATIONLIST ) { this.SafeAddChild( Sif3assessmentDTD.FORMACCOMMODATIONLIST_FORMACCOMMODATION, formAccommodation ); } /// <summary> /// Constructor used by the .Net Serialization formatter /// </summary> [SecurityPermission( SecurityAction.Demand, SerializationFormatter=true )] protected FormAccommodationList( SerializationInfo info, StreamingContext context ) : base( info, context ) {} /// <summary> /// Gets the metadata fields that make up the key of this object /// </summary> /// <value> /// an array of metadata fields that make up the object's key /// </value> public IElementDef[] KeyFields { get { return new IElementDef[] { Sif3assessmentDTD.FORMACCOMMODATIONLIST_FORMACCOMMODATION }; } } ///<summary>Adds the value of the <c>&lt;FormAccommodation&gt;</c> element.</summary> /// <param name="Value">Gets or sets the content value of the &amp;lt;FormAccommodation&amp;gt; element</param> ///<remarks> /// <para>This form of <c>setFormAccommodation</c> is provided as a convenience method /// that is functionally equivalent to the method <c>AddFormAccommodation</c></para> /// <para>Version: 2.6</para> /// <para>Since: 2.6</para> /// </remarks> public void AddFormAccommodation( FormAccommodationType Value ) { AddChild( Sif3assessmentDTD.FORMACCOMMODATIONLIST_FORMACCOMMODATION, new FormAccommodation( Value ) ); } }}
open-adk/OpenADK-csharp
src/au/sdo/Sif3assessment/FormAccommodationList.cs
C#
apache-2.0
2,473
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_12-ea) on Wed Feb 05 23:03:17 CET 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>NoMigration (JCloudScale 0.4.1-SNAPSHOT API)</title> <meta name="date" content="2014-02-05"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="NoMigration (JCloudScale 0.4.1-SNAPSHOT API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/NoMigration.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../at/ac/tuwien/infosys/jcloudscale/migration/annotations/MigrationTransient.html" title="annotation in at.ac.tuwien.infosys.jcloudscale.migration.annotations"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../../at/ac/tuwien/infosys/jcloudscale/migration/annotations/PostMigration.html" title="annotation in at.ac.tuwien.infosys.jcloudscale.migration.annotations"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?at/ac/tuwien/infosys/jcloudscale/migration/annotations/NoMigration.html" target="_top">Frames</a></li> <li><a href="NoMigration.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Required&nbsp;|&nbsp;</li> <li>Optional</li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Element</li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">at.ac.tuwien.infosys.jcloudscale.migration.annotations</div> <h2 title="Annotation Type NoMigration" class="title">Annotation Type NoMigration</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Target.html?is-external=true" title="class or interface in java.lang.annotation">@Target</a>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Target.html?is-external=true#value()" title="class or interface in java.lang.annotation">value</a>=<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/ElementType.html?is-external=true#TYPE" title="class or interface in java.lang.annotation">TYPE</a>) <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Retention.html?is-external=true" title="class or interface in java.lang.annotation">@Retention</a>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Retention.html?is-external=true#value()" title="class or interface in java.lang.annotation">value</a>=<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/RetentionPolicy.html?is-external=true#RUNTIME" title="class or interface in java.lang.annotation">RUNTIME</a>) <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Documented.html?is-external=true" title="class or interface in java.lang.annotation">@Documented</a> public @interface <span class="strong">NoMigration</span></pre> <div class="block">Classes annotated with <a href="../../../../../../../at/ac/tuwien/infosys/jcloudscale/migration/annotations/NoMigration.html" title="annotation in at.ac.tuwien.infosys.jcloudscale.migration.annotations"><code>NoMigration</code></a> are (by default) excluded from automatic migrations. If the user wants to migrate such an object she has to explicitly call an appropriate migration method using the <a href="../../../../../../../at/ac/tuwien/infosys/jcloudscale/annotations/CloudObject.html" title="annotation in at.ac.tuwien.infosys.jcloudscale.annotations"><code>CloudObject</code></a> 's id as parameter.</div> <dl><dt><span class="strong">See Also:</span></dt><dd><code>MigrationConfiguration</code></dd></dl> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/NoMigration.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../at/ac/tuwien/infosys/jcloudscale/migration/annotations/MigrationTransient.html" title="annotation in at.ac.tuwien.infosys.jcloudscale.migration.annotations"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../../at/ac/tuwien/infosys/jcloudscale/migration/annotations/PostMigration.html" title="annotation in at.ac.tuwien.infosys.jcloudscale.migration.annotations"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?at/ac/tuwien/infosys/jcloudscale/migration/annotations/NoMigration.html" target="_top">Frames</a></li> <li><a href="NoMigration.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Required&nbsp;|&nbsp;</li> <li>Optional</li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Element</li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2014. All Rights Reserved.</small></p> </body> </html>
xLeitix/jcloudscale
docs/javadoc/apidocs/at/ac/tuwien/infosys/jcloudscale/migration/annotations/NoMigration.html
HTML
apache-2.0
7,677
/* * Copyright 2014 Facebook, 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. */ #ifndef FOLLY_IO_HUGEPAGES_H_ #define FOLLY_IO_HUGEPAGES_H_ #include <sys/stat.h> #include <sys/types.h> #include <cstddef> #include <string> #include <unistd.h> #include <utility> #include <vector> #include <boost/operators.hpp> #include <folly/Range.h> #include <folly/experimental/io/FsUtil.h> namespace folly { struct HugePageSize : private boost::totally_ordered<HugePageSize> { explicit HugePageSize(size_t s) : size(s) { } fs::path filePath(const fs::path& relpath) const { return mountPoint / relpath; } size_t size = 0; fs::path mountPoint; dev_t device = 0; }; inline bool operator<(const HugePageSize& a, const HugePageSize& b) { return a.size < b.size; } inline bool operator==(const HugePageSize& a, const HugePageSize& b) { return a.size == b.size; } /** * Vector of (huge_page_size, mount_point), sorted by huge_page_size. * mount_point might be empty if no hugetlbfs file system is mounted for * that size. */ typedef std::vector<HugePageSize> HugePageSizeVec; /** * Get list of supported huge page sizes and their mount points, if * hugetlbfs file systems are mounted for those sizes. */ const HugePageSizeVec& getHugePageSizes(); /** * Return the mount point for the requested huge page size. * 0 = use smallest available. * Returns nullptr if the requested huge page size is not available. */ const HugePageSize* getHugePageSize(size_t size = 0); /** * Return the huge page size for a device. * returns nullptr if device does not refer to a huge page filesystem. */ const HugePageSize* getHugePageSizeForDevice(dev_t device); } // namespace folly #endif /* FOLLY_IO_HUGEPAGES_H_ */
xliux/chess
folly/experimental/io/HugePages.h
C
apache-2.0
2,248
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import proto # type: ignore from google.protobuf import any_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( package="grafeas.v1", manifest={ "Recipe", "Completeness", "Metadata", "BuilderConfig", "InTotoProvenance", }, ) class Recipe(proto.Message): r"""Steps taken to build the artifact. For a TaskRun, typically each container corresponds to one step in the recipe. Attributes: type_ (str): URI indicating what type of recipe was performed. It determines the meaning of recipe.entryPoint, recipe.arguments, recipe.environment, and materials. defined_in_material (int): Index in materials containing the recipe steps that are not implied by recipe.type. For example, if the recipe type were "make", then this would point to the source containing the Makefile, not the make program itself. Set to -1 if the recipe doesn't come from a material, as zero is default unset value for int64. entry_point (str): String identifying the entry point into the build. This is often a path to a configuration file and/or a target label within that file. The syntax and meaning are defined by recipe.type. For example, if the recipe type were "make", then this would reference the directory in which to run make as well as which target to use. arguments (Sequence[google.protobuf.any_pb2.Any]): Collection of all external inputs that influenced the build on top of recipe.definedInMaterial and recipe.entryPoint. For example, if the recipe type were "make", then this might be the flags passed to make aside from the target, which is captured in recipe.entryPoint. Since the arguments field can greatly vary in structure, depending on the builder and recipe type, this is of form "Any". environment (Sequence[google.protobuf.any_pb2.Any]): Any other builder-controlled inputs necessary for correctly evaluating the recipe. Usually only needed for reproducing the build but not evaluated as part of policy. Since the environment field can greatly vary in structure, depending on the builder and recipe type, this is of form "Any". """ type_ = proto.Field(proto.STRING, number=1,) defined_in_material = proto.Field(proto.INT64, number=2,) entry_point = proto.Field(proto.STRING, number=3,) arguments = proto.RepeatedField(proto.MESSAGE, number=4, message=any_pb2.Any,) environment = proto.RepeatedField(proto.MESSAGE, number=5, message=any_pb2.Any,) class Completeness(proto.Message): r"""Indicates that the builder claims certain fields in this message to be complete. Attributes: arguments (bool): If true, the builder claims that recipe.arguments is complete, meaning that all external inputs are properly captured in the recipe. environment (bool): If true, the builder claims that recipe.environment is claimed to be complete. materials (bool): If true, the builder claims that materials are complete, usually through some controls to prevent network access. Sometimes called "hermetic". """ arguments = proto.Field(proto.BOOL, number=1,) environment = proto.Field(proto.BOOL, number=2,) materials = proto.Field(proto.BOOL, number=3,) class Metadata(proto.Message): r"""Other properties of the build. Attributes: build_invocation_id (str): Identifies the particular build invocation, which can be useful for finding associated logs or other ad-hoc analysis. The value SHOULD be globally unique, per in-toto Provenance spec. build_started_on (google.protobuf.timestamp_pb2.Timestamp): The timestamp of when the build started. build_finished_on (google.protobuf.timestamp_pb2.Timestamp): The timestamp of when the build completed. completeness (grafeas.grafeas_v1.types.Completeness): Indicates that the builder claims certain fields in this message to be complete. reproducible (bool): If true, the builder claims that running the recipe on materials will produce bit-for-bit identical output. """ build_invocation_id = proto.Field(proto.STRING, number=1,) build_started_on = proto.Field( proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) build_finished_on = proto.Field( proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, ) completeness = proto.Field(proto.MESSAGE, number=4, message="Completeness",) reproducible = proto.Field(proto.BOOL, number=5,) class BuilderConfig(proto.Message): r""" Attributes: id (str): """ id = proto.Field(proto.STRING, number=1,) class InTotoProvenance(proto.Message): r""" Attributes: builder_config (grafeas.grafeas_v1.types.BuilderConfig): required recipe (grafeas.grafeas_v1.types.Recipe): Identifies the configuration used for the build. When combined with materials, this SHOULD fully describe the build, such that re-running this recipe results in bit-for-bit identical output (if the build is reproducible). metadata (grafeas.grafeas_v1.types.Metadata): materials (Sequence[str]): The collection of artifacts that influenced the build including sources, dependencies, build tools, base images, and so on. This is considered to be incomplete unless metadata.completeness.materials is true. Unset or null is equivalent to empty. """ builder_config = proto.Field(proto.MESSAGE, number=1, message="BuilderConfig",) recipe = proto.Field(proto.MESSAGE, number=2, message="Recipe",) metadata = proto.Field(proto.MESSAGE, number=3, message="Metadata",) materials = proto.RepeatedField(proto.STRING, number=4,) __all__ = tuple(sorted(__protobuf__.manifest))
googleapis/python-grafeas
grafeas/grafeas_v1/types/intoto_provenance.py
Python
apache-2.0
7,148
namespace kafka4net.Protocols.Requests { class MessageData { /// <summary>This byte holds metadata attributes about the message. The lowest 2 bits contain /// the compression codec used for the message. The other bits should be set to 0</summary> //public byte Attributes; /// <summary> The key is an optional message key that was used for partition assignment. /// The key can be null</summary> public byte[] Key; /// <summary>The value is the actual message contents as an opaque byte array. /// Kafka supports recursive messages in which case this may itself contain a message set. /// The message can be null</summary> public byte[] Value; } }
vikmv/kafka4net
src/Protocols/Requests/MessageData.cs
C#
apache-2.0
765
// Copyright 2010 Google 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. /** * @fileoverview This file contains RPF's setting dialog. * It gets popped up when user clicks the settings button. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.SettingDialog'); goog.require('Bite.Constants'); goog.require('bite.common.mvc.helper'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.events'); goog.require('goog.ui.Dialog'); goog.require('rpf.Console.Messenger'); goog.require('rpf.MiscHelper'); goog.require('rpf.soy.Dialog'); /** * A class for showing setting dialog. * This dialog shows user options to set playback interval, * or test user's specified script. * @param {function(Bite.Constants.UiCmds, Object, Event)} onUiEvents * The function to handle the specific event. * @constructor * @export */ rpf.SettingDialog = function(onUiEvents) { /** * The setting dialog. * @type Object * @private */ this.settingDialog_ = new goog.ui.Dialog(); /** * The messenger. * @type {rpf.Console.Messenger} * @private */ this.messenger_ = rpf.Console.Messenger.getInstance(); /** * The function to handle the specific event. * @type {function(Bite.Constants.UiCmds, Object, Event)} * @private */ this.onUiEvents_ = onUiEvents; /** * Inits the setting dialog. */ this.initSettingDialog_(); }; /** * Localstorage name for whether takes screenshots. * @type {string} * @private */ rpf.SettingDialog.TAKE_SCREENSHOTS_ = 'takeScreenshots'; /** * Localstorage name for whether uses xpath. * @type {string} * @private */ rpf.SettingDialog.USE_XPATH_ = 'useXpath'; /** * Localstorage name for whether to show tips. * @type {string} * @private */ rpf.SettingDialog.SHOW_TIPS_ = 'showTips'; /** * Inits the setting dialog. * @private */ rpf.SettingDialog.prototype.initSettingDialog_ = function() { var dialogElem = this.settingDialog_.getContentElement(); bite.common.mvc.helper.renderModelFor(dialogElem, rpf.soy.Dialog.settingsContent); this.settingDialog_.setTitle('Settings'); this.settingDialog_.setButtonSet(null); this.settingDialog_.setVisible(true); this.registerListeners_(); this.initPlaybackInterval_(); this.initTimeout_(); this.initTakeScreenshotsCheckbox_(); this.initUseXpath_(); this.initShowTips_(); this.settingDialog_.setVisible(false); }; /** * Generates the webdriver code directly. * @private */ rpf.SettingDialog.prototype.registerListeners_ = function() { goog.events.listen( goog.dom.getElement('playbackintervalbutton'), 'click', goog.bind(this.setPlaybackInterval_, this)); goog.events.listen( goog.dom.getElement('defaulttimeoutbutton'), 'click', goog.bind(this.setTimeout_, this)); goog.events.listen( goog.dom.getElement('whethertakescreenshot'), 'click', goog.bind(this.setTakeScreenshot_, this)); goog.events.listen( goog.dom.getElement('whetherUseXpath'), 'click', goog.bind(this.setUseXpath_, this)); goog.events.listen( goog.dom.getElement('whetherShowTips'), 'click', goog.bind(this.setShowTips_, this)); }; /** * Sets whether take the screenshots while recording. * @private */ rpf.SettingDialog.prototype.initTakeScreenshotsCheckbox_ = function() { var takes = goog.global.localStorage.getItem( rpf.SettingDialog.TAKE_SCREENSHOTS_); if (!takes || takes == 'true') { goog.dom.getElement('whethertakescreenshot').checked = true; } else { this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_TAKE_SCREENSHOT, 'params': {'isTaken': false}}); } }; /** * Sets whether take the screenshots while recording. * @private */ rpf.SettingDialog.prototype.setTakeScreenshot_ = function() { var checked = goog.dom.getElement('whethertakescreenshot').checked; goog.global.localStorage[ rpf.SettingDialog.TAKE_SCREENSHOTS_] = checked; this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_TAKE_SCREENSHOT, 'params': {'isTaken': checked}}); }; /** * Gets whether to use xpath. * @return {boolean} Whether to use xpath. */ rpf.SettingDialog.prototype.getUseXpath = function() { return goog.dom.getElement('whetherUseXpath').checked; }; /** * Sets whether uses the xpath to replay. * @private */ rpf.SettingDialog.prototype.setUseXpath_ = function() { var checked = goog.dom.getElement('whetherUseXpath').checked; goog.global.localStorage[rpf.SettingDialog.USE_XPATH_] = checked; this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_USE_XPATH, 'params': {'use': checked}}); }; /** * Sets whether uses xpath. * @private */ rpf.SettingDialog.prototype.initUseXpath_ = function() { var use = goog.global.localStorage.getItem(rpf.SettingDialog.USE_XPATH_); if (use && use == 'true') { goog.dom.getElement('whetherUseXpath').checked = true; this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_USE_XPATH, 'params': {'use': true}}); } }; /** * Gets whether to show tips. * @return {boolean} Whether to show tips. */ rpf.SettingDialog.prototype.getShowTips = function() { return goog.dom.getElement('whetherShowTips').checked; }; /** * Sets whether to show tips. * @param {boolean} show Whether to show the tips. * @export */ rpf.SettingDialog.prototype.automateShowTips = function(show) { goog.dom.getElement('whetherShowTips').checked = show; this.setShowTips_(); }; /** * Sets whether to show tips. * @private */ rpf.SettingDialog.prototype.setShowTips_ = function() { var checked = goog.dom.getElement('whetherShowTips').checked; goog.global.localStorage[rpf.SettingDialog.SHOW_TIPS_] = checked; this.onUiEvents_( Bite.Constants.UiCmds.SET_SHOW_TIPS, {'show': checked}, /** @type {Event} */ ({})); }; /** * Sets whether to show tips. * @private */ rpf.SettingDialog.prototype.initShowTips_ = function() { var show = goog.global.localStorage.getItem(rpf.SettingDialog.SHOW_TIPS_); if (!show || show == 'true') { goog.dom.getElement('whetherShowTips').checked = true; } else { this.onUiEvents_( Bite.Constants.UiCmds.SET_SHOW_TIPS, {'show': false}, /** @type {Event} */ ({})); } }; /** * Inits the playback redirection timeout. * @private */ rpf.SettingDialog.prototype.initTimeout_ = function() { goog.dom.getElement('defaulttimeout').value = Bite.Constants.RPF_PLAYBACK.REDIRECTION_TIMEOUT / 1000; }; /** * Sets time out. * @private */ rpf.SettingDialog.prototype.setTimeout_ = function() { var time = parseInt(goog.dom.getElement('defaulttimeout').value, 10); if (isNaN(time)) { alert('Invalid input, please type in a number.'); return; } time = time * 1000; this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_DEFAULT_TIMEOUT, 'params': {'time': time}}); this.onUiEvents_( Bite.Constants.UiCmds.SET_CONSOLE_STATUS, {'message': 'Saved the playback timeout successfully.', 'color': 'green'}, /** @type {Event} */ ({})); }; /** * Inits the playback interval box. * @private */ rpf.SettingDialog.prototype.initPlaybackInterval_ = function() { goog.dom.getElement('playbackinterval').value = Bite.Constants.RPF_PLAYBACK.INTERVAL * 1.0 / 1000; }; /** * Sets the playback interval in seconds. * @private */ rpf.SettingDialog.prototype.setPlaybackInterval_ = function() { var interval = parseFloat(goog.dom.getElement('playbackinterval').value); if (isNaN(interval)) { alert('Invalid input, please type in a float number.'); return; } this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_PLAYBACK_INTERVAL, 'params': {'interval': interval}}); this.onUiEvents_( Bite.Constants.UiCmds.SET_CONSOLE_STATUS, {'message': 'Saved the playback interval successfully.', 'color': 'green'}, /** @type {Event} */ ({})); }; /** * Sets the visibility of the setting dialog. * @param {boolean} display Whether to show the dialog. * @export */ rpf.SettingDialog.prototype.setVisible = function(display) { this.settingDialog_.setVisible(display); };
adambyram/bite-project-mod
tools/rpf/extension/src/libs/settingdialog.js
JavaScript
apache-2.0
8,888
package com.box.boxjavalibv2.requests; import java.io.IOException; import junit.framework.Assert; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.entity.StringEntity; import org.junit.Test; import com.box.boxjavalibv2.BoxConfig; import com.box.boxjavalibv2.exceptions.AuthFatalFailureException; import com.box.boxjavalibv2.exceptions.BoxJSONException; import com.box.boxjavalibv2.jsonentities.MapJSONStringEntity; import com.box.boxjavalibv2.requests.requestobjects.BoxUserRequestObject; import com.box.restclientv2.RestMethod; import com.box.restclientv2.exceptions.BoxRestException; public class AddEmailAliasRequestTest extends RequestTestBase { @Test public void testUri() { Assert.assertEquals("/users/123/email_aliases", CreateEmailAliasRequest.getUri("123")); } @Test public void testRequestIsWellFormed() throws BoxRestException, IllegalStateException, IOException, AuthFatalFailureException, BoxJSONException { String userId = "testuserid"; String email = "testeamail@box.com"; CreateEmailAliasRequest request = new CreateEmailAliasRequest(CONFIG, JSON_PARSER, userId, BoxUserRequestObject.addEmailAliasRequestObject(email)); testRequestIsWellFormed(request, BoxConfig.getInstance().getApiUrlAuthority(), BoxConfig.getInstance().getApiUrlPath().concat(CreateEmailAliasRequest.getUri(userId)), HttpStatus.SC_CREATED, RestMethod.POST); HttpEntity entity = request.getRequestEntity(); Assert.assertTrue(entity instanceof StringEntity); MapJSONStringEntity mEntity = new MapJSONStringEntity(); mEntity.put("email", email); assertEqualStringEntity(mEntity, entity); } }
ElectroJunkie/box-java-sdk-v2-master
BoxJavaLibraryV2/tst/com/box/boxjavalibv2/requests/AddEmailAliasRequestTest.java
Java
apache-2.0
1,746
# https://djangosnippets.org/snippets/690/ import re from django.template.defaultfilters import slugify def unique_slugify(instance, value, slug_field_name='slug', queryset=None, slug_separator='-'): """ Calculates and stores a unique slug of ``value`` for an instance. ``slug_field_name`` should be a string matching the name of the field to store the slug in (and the field to check against for uniqueness). ``queryset`` usually doesn't need to be explicitly provided - it'll default to using the ``.all()`` queryset from the model's default manager. """ slug_field = instance._meta.get_field(slug_field_name) slug = getattr(instance, slug_field.attname) slug_len = slug_field.max_length # Sort out the initial slug, limiting its length if necessary. slug = slugify(value) if slug_len: slug = slug[:slug_len] slug = _slug_strip(slug, slug_separator) original_slug = slug # Create the queryset if one wasn't explicitly provided and exclude the # current instance from the queryset. if queryset is None: queryset = instance.__class__._default_manager.all() if instance.pk: queryset = queryset.exclude(pk=instance.pk) # Find a unique slug. If one matches, at '-2' to the end and try again # (then '-3', etc). next = 2 while not slug or queryset.filter(**{slug_field_name: slug}): slug = original_slug end = '%s%s' % (slug_separator, next) if slug_len and len(slug) + len(end) > slug_len: slug = slug[:slug_len-len(end)] slug = _slug_strip(slug, slug_separator) slug = '%s%s' % (slug, end) next += 1 setattr(instance, slug_field.attname, slug) def _slug_strip(value, separator='-'): """ Cleans up a slug by removing slug separator characters that occur at the beginning or end of a slug. If an alternate separator is used, it will also replace any instances of the default '-' separator with the new separator. """ separator = separator or '' if separator == '-' or not separator: re_sep = '-' else: re_sep = '(?:-|%s)' % re.escape(separator) # Remove multiple instances and if an alternate separator is provided, # replace the default '-' separator. if separator != re_sep: value = re.sub('%s+' % re_sep, separator, value) # Remove separator from the beginning and end of the slug. if separator: if separator != '-': re_sep = re.escape(separator) value = re.sub(r'^%s+|%s+$' % (re_sep, re_sep), '', value) return value
thelabnyc/wagtail_blog
blog/utils.py
Python
apache-2.0
2,644
'''Trains a simple convnet on the Fashion MNIST dataset. Gets to % test accuracy after 12 epochs (there is still a lot of margin for parameter tuning). ''' from __future__ import print_function import keras from keras.datasets import fashion_mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras import backend as K batch_size = 128 num_classes = 10 epochs = 12 # input image dimensions img_rows, img_cols = 28, 28 # the data, shuffled and split between train and test sets (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data() if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1])
erramuzpe/seattle-perceptual-learning
perclearn/scripts/fashion_mnist_cnn.py
Python
apache-2.0
2,248
<!DOCTYPE html> <html> <head> <title>Shortify.me</title> <link rel="stylesheet" href="css/style.css" /> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> </head> <body> <div id="container" class="centered"> <div class="animated fadeIn centeredText"> <img alt="Shortify.me" src="images/shortify_logo.png" /> </div> <div id="errorDiv" class="centeredText alert alert-danger animated fadeIn"> <p>ShortUrl doesn't exist! </p> <p>Return to <a href="index.html">HOME PAGE</a></p> </div> </div> </body> </html>
GruppoPBDMNG-7/shortify.me
ClientAngular/404.html
HTML
apache-2.0
704
/* * Copyright 2016 Hippo Seven * * 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.hippo.ehviewer.client; import android.content.Context; import android.graphics.Color; import android.text.TextUtils; import androidx.annotation.Nullable; import com.hippo.ehviewer.EhApplication; import com.hippo.ehviewer.Settings; import com.hippo.ehviewer.client.data.GalleryInfo; import java.util.regex.Pattern; public class EhUtils { public static final int NONE = -1; // Use it for homepage public static final int UNKNOWN = 0x400; public static final int ALL_CATEGORY = EhUtils.UNKNOWN - 1; //DOUJINSHI|MANGA|ARTIST_CG|GAME_CG|WESTERN|NON_H|IMAGE_SET|COSPLAY|ASIAN_PORN|MISC; public static final int BG_COLOR_DOUJINSHI = 0xfff44336; public static final int BG_COLOR_MANGA = 0xffff9800; public static final int BG_COLOR_ARTIST_CG = 0xfffbc02d; public static final int BG_COLOR_GAME_CG = 0xff4caf50; public static final int BG_COLOR_WESTERN = 0xff8bc34a; public static final int BG_COLOR_NON_H = 0xff2196f3; public static final int BG_COLOR_IMAGE_SET = 0xff3f51b5; public static final int BG_COLOR_COSPLAY = 0xff9c27b0; public static final int BG_COLOR_ASIAN_PORN = 0xff9575cd; public static final int BG_COLOR_MISC = 0xfff06292; public static final int BG_COLOR_UNKNOWN = Color.BLACK; // Remove [XXX], (XXX), {XXX}, ~XXX~ stuff public static final Pattern PATTERN_TITLE_PREFIX = Pattern.compile( "^(?:(?:\\([^\\)]*\\))|(?:\\[[^\\]]*\\])|(?:\\{[^\\}]*\\})|(?:~[^~]*~)|\\s+)*"); // Remove [XXX], (XXX), {XXX}, ~XXX~ stuff and something like ch. 1-23 public static final Pattern PATTERN_TITLE_SUFFIX = Pattern.compile( "(?:\\s+ch.[\\s\\d-]+)?(?:(?:\\([^\\)]*\\))|(?:\\[[^\\]]*\\])|(?:\\{[^\\}]*\\})|(?:~[^~]*~)|\\s+)*$", Pattern.CASE_INSENSITIVE); private static final int[] CATEGORY_VALUES = { EhConfig.MISC, EhConfig.DOUJINSHI, EhConfig.MANGA, EhConfig.ARTIST_CG, EhConfig.GAME_CG, EhConfig.IMAGE_SET, EhConfig.COSPLAY, EhConfig.ASIAN_PORN, EhConfig.NON_H, EhConfig.WESTERN, UNKNOWN }; private static final String[][] CATEGORY_STRINGS = { new String[] { "misc" }, new String[] { "doujinshi" }, new String[] { "manga" }, new String[] { "artistcg", "Artist CG Sets", "Artist CG" }, new String[] { "gamecg", "Game CG Sets", "Game CG" }, new String[] { "imageset", "Image Sets", "Image Set" }, new String[] { "cosplay" }, new String[] { "asianporn", "Asian Porn" }, new String[] { "non-h" }, new String[] { "western" }, new String[] { "unknown" } }; public static int getCategory(String type) { int i; for (i = 0; i < CATEGORY_STRINGS.length - 1; i++) { for (String str : CATEGORY_STRINGS[i]) if (str.equalsIgnoreCase(type)) return CATEGORY_VALUES[i]; } return CATEGORY_VALUES[i]; } public static String getCategory(int type) { int i; for (i = 0; i < CATEGORY_VALUES.length - 1; i++) { if (CATEGORY_VALUES[i] == type) break; } return CATEGORY_STRINGS[i][0]; } public static int getCategoryColor(int category) { switch (category) { case EhConfig.DOUJINSHI: return BG_COLOR_DOUJINSHI; case EhConfig.MANGA: return BG_COLOR_MANGA; case EhConfig.ARTIST_CG: return BG_COLOR_ARTIST_CG; case EhConfig.GAME_CG: return BG_COLOR_GAME_CG; case EhConfig.WESTERN: return BG_COLOR_WESTERN; case EhConfig.NON_H: return BG_COLOR_NON_H; case EhConfig.IMAGE_SET: return BG_COLOR_IMAGE_SET; case EhConfig.COSPLAY: return BG_COLOR_COSPLAY; case EhConfig.ASIAN_PORN: return BG_COLOR_ASIAN_PORN; case EhConfig.MISC: return BG_COLOR_MISC; default: return BG_COLOR_UNKNOWN; } } public static void signOut(Context context) { EhApplication.getEhCookieStore(context).signOut(); Settings.putAvatar(null); Settings.putDisplayName(null); Settings.putNeedSignIn(true); } public static boolean needSignedIn(Context context) { return Settings.getNeedSignIn() && !EhApplication.getEhCookieStore(context).hasSignedIn(); } public static String getSuitableTitle(GalleryInfo gi) { if (Settings.getShowJpnTitle()) { return TextUtils.isEmpty(gi.titleJpn) ? gi.title : gi.titleJpn; } else { return TextUtils.isEmpty(gi.title) ? gi.titleJpn : gi.title; } } @Nullable public static String extractTitle(String title) { if (null == title) { return null; } title = PATTERN_TITLE_PREFIX.matcher(title).replaceFirst(""); title = PATTERN_TITLE_SUFFIX.matcher(title).replaceFirst(""); // Sometimes title is combined by romaji and english translation. // Only need romaji. // TODO But not sure every '|' means that int index = title.indexOf('|'); if (index >= 0) { title = title.substring(0, index); } if (title.isEmpty()) { return null; } else { return title; } } public static String handleThumbUrlResolution(String url) { if (null == url) { return null; } String resolution; switch (Settings.getThumbResolution()) { default: case 0: // Auto return url; case 1: // 250 resolution = "250"; break; case 2: // 300 resolution = "300"; break; } int index1 = url.lastIndexOf('_'); int index2 = url.lastIndexOf('.'); if (index1 >= 0 && index2 >= 0 && index1 < index2) { return url.substring(0, index1 + 1) + resolution + url.substring(index2); } else { return url; } } }
seven332/EhViewer
app/src/main/java/com/hippo/ehviewer/client/EhUtils.java
Java
apache-2.0
6,944
/** * This script is a demonstration of how you can use a basic spritesheet. This covers loading of spritesheets and changing the cell gameobjects will use. **/ var Spritesheets = new Kiwi.State('Spritesheets'); Spritesheets.preload = function () { //Just making the stage smaller this.game.stage.resize(800, 250); // Load our spritesheet we want to use. /** * When loading spritesheets you have to pass slightly more information. * - Parameter One - Name of the spritesheet for your reference. * - Parameter Two - The URL to the spritesheet. * - Parameter Three - The width of each cell * - Parameter Four - The height of each cell **/ this.addSpriteSheet('characters', 'assets/spritesheets/characters.png', 150, 117); } Spritesheets.create = function () { /** * To change which cell the sprite is using we can change the CELL INDEX which is on both the sprite and static image objects. **/ this.skele = new Kiwi.GameObjects.Sprite(this, this.textures.characters, 10, 30); this.skele.cellIndex = 2; this.robot = new Kiwi.GameObjects.Sprite(this, this.textures.characters, 210, 30); this.robot.cellIndex = 8; this.spartan = new Kiwi.GameObjects.Sprite(this, this.textures.characters, 410, 30); this.spartan.cellIndex = 5; //add them all to the stage this.addChild(this.skele); this.addChild(this.robot); this.addChild(this.spartan); } //Create's a new Kiwi.Game. /* * Param One - DOMID - String - ID of a DOMElement that the game will reside in. * Param Two - GameName - String - Name that the game will be given. * Param Three - State - Object - The state that is to be loaded by default. * Param Four - Options - Object - Optional options that the game will use whilst playing. Currently this is used to to choose the renderer/debugmode/device to target */ if(typeof gameOptions == "undefined") gameOptions = {}; var game = new Kiwi.Game('game', 'KiwiExample', Spritesheets, gameOptions);
dfu23/swim-meet
lib/kiwi.js/examples/Introduction/Spritesheets.js
JavaScript
apache-2.0
1,998
Description =========== Installs kafka 0.7.1 Requirements ============ * Java cookbook version >= 1.5 * Runit cookbook Attributes ========== * kafa.version - The Kafka version to pull and use * kafa.install_dir - Location for Kafka to be installed * kafa.data_dir - Location for Kafka logs * kafa.log_dir - Location for Kafka log4j logs * kafa.broker_id - The id of the broker. This must be set to a unique integer for each broker. If not set, it defaults to the machine's ip address without the '.'. * kafa.broker_host_name - Hostname the broker will advertise to consumers. If not set, kafka will use the host name for the server being deployed to.. * kafa.port - The port the socket server listens on * kafa.threads - The number of processor threads the socket server uses for receiving and answering requests. If not set, defaults to the number of cores on the machine * kafa.log_flush_interval - The number of messages to accept before forcing a flush of data to disk * kafa.log_flush_time_interval - The maximum amount of time (ms) a message can sit in a log before we force a flush * kafa.log_flush_scheduler_time_interval - The interval (in ms) at which logs are checked to see if they need to be flushed to disk * kafa.log_retention_hours - The minimum age of a log file to be eligible for deletion Usage ===== * kafka - Install a Kafka broker. = LICENSE and AUTHOR: Author:: Ivan von Nagy () Copyright:: 2012, Webtrends, 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.
jreichhold/chef-repo
site-cookbooks/kafka/README.md
Markdown
apache-2.0
1,969
from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import torch import torch.utils.data import ray from ray.experimental.sgd.pytorch import pytorch_utils from ray.experimental.sgd import utils logger = logging.getLogger(__name__) class PyTorchRunner(object): """Manages a PyTorch model for training.""" def __init__(self, model_creator, data_creator, optimizer_creator, config=None, batch_size=16): """Initializes the runner. Args: model_creator (dict -> torch.nn.Module): see pytorch_trainer.py. data_creator (dict -> Dataset, Dataset): see pytorch_trainer.py. optimizer_creator (torch.nn.Module, dict -> loss, optimizer): see pytorch_trainer.py. config (dict): see pytorch_trainer.py. batch_size (int): see pytorch_trainer.py. """ self.model_creator = model_creator self.data_creator = data_creator self.optimizer_creator = optimizer_creator self.config = {} if config is None else config self.batch_size = batch_size self.verbose = True self.epoch = 0 self._timers = { k: utils.TimerStat(window_size=1) for k in [ "setup_proc", "setup_model", "get_state", "set_state", "validation", "training" ] } def setup(self): """Initializes the model.""" logger.debug("Creating model") self.model = self.model_creator(self.config) if torch.cuda.is_available(): self.model = self.model.cuda() logger.debug("Creating optimizer") self.criterion, self.optimizer = self.optimizer_creator( self.model, self.config) if torch.cuda.is_available(): self.criterion = self.criterion.cuda() logger.debug("Creating dataset") self.training_set, self.validation_set = self.data_creator(self.config) self.train_loader = torch.utils.data.DataLoader( self.training_set, batch_size=self.batch_size, shuffle=True, num_workers=2, pin_memory=False) self.validation_loader = torch.utils.data.DataLoader( self.validation_set, batch_size=self.batch_size, shuffle=True, num_workers=2, pin_memory=False) def get_node_ip(self): """Returns the IP address of the current node.""" return ray.services.get_node_ip_address() def find_free_port(self): """Finds a free port on the current node.""" return utils.find_free_port() def step(self): """Runs a training epoch and updates the model parameters.""" logger.debug("Begin Training Epoch {}".format(self.epoch + 1)) with self._timers["training"]: train_stats = pytorch_utils.train(self.train_loader, self.model, self.criterion, self.optimizer) train_stats["epoch"] = self.epoch self.epoch += 1 train_stats.update(self.stats()) return train_stats def validate(self): """Evaluates the model on the validation data set.""" with self._timers["validation"]: validation_stats = pytorch_utils.validate( self.validation_loader, self.model, self.criterion) validation_stats.update(self.stats()) return validation_stats def stats(self): """Returns a dictionary of statistics collected.""" stats = {"epoch": self.epoch} for k, t in self._timers.items(): stats[k + "_time_mean"] = t.mean stats[k + "_time_total"] = t.sum t.reset() return stats def get_state(self): """Returns the state of the runner.""" return { "epoch": self.epoch, "model": self.model.state_dict(), "optimizer": self.optimizer.state_dict(), "stats": self.stats() } def set_state(self, state): """Sets the state of the model.""" # TODO: restore timer stats self.model.load_state_dict(state["model"]) self.optimizer.load_state_dict(state["optimizer"]) self.epoch = state["stats"]["epoch"] def shutdown(self): """Attempts to shut down the worker.""" del self.validation_loader del self.validation_set del self.train_loader del self.training_set del self.criterion del self.optimizer del self.model if torch.cuda.is_available(): torch.cuda.empty_cache()
ujvl/ray-ng
python/ray/experimental/sgd/pytorch/pytorch_runner.py
Python
apache-2.0
4,800
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_07) on Wed Jan 29 10:36:10 GMT 2014 --> <title>Uses of Class com.gravspace.bases.TaskBase</title> <meta name="date" content="2014-01-29"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.gravspace.bases.TaskBase"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../com/gravspace/bases/TaskBase.html" title="class in com.gravspace.bases">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/gravspace/bases/class-use/TaskBase.html" target="_top">Frames</a></li> <li><a href="TaskBase.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.gravspace.bases.TaskBase" class="title">Uses of Class<br>com.gravspace.bases.TaskBase</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../com/gravspace/bases/TaskBase.html" title="class in com.gravspace.bases">TaskBase</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.gravspace.page">com.gravspace.page</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.gravspace.page"> <!-- --> </a> <h3>Uses of <a href="../../../../com/gravspace/bases/TaskBase.html" title="class in com.gravspace.bases">TaskBase</a> in <a href="../../../../com/gravspace/page/package-summary.html">com.gravspace.page</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../com/gravspace/bases/TaskBase.html" title="class in com.gravspace.bases">TaskBase</a> in <a href="../../../../com/gravspace/page/package-summary.html">com.gravspace.page</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../com/gravspace/page/ProfileTask.html" title="class in com.gravspace.page">ProfileTask</a></strong></code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../com/gravspace/bases/TaskBase.html" title="class in com.gravspace.bases">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/gravspace/bases/class-use/TaskBase.html" target="_top">Frames</a></li> <li><a href="TaskBase.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
ranoble/Megapode
javadocs/com/gravspace/bases/class-use/TaskBase.html
HTML
apache-2.0
5,727
package com.grafixartist.bottomnav; import android.app.Application; import android.support.v7.app.AppCompatDelegate; /** * BottomNav * Created by Suleiman19 on 8/2/16. * Copyright (c) 2016. Suleiman Ali Shakir. All rights reserved. */ public class MyApp extends Application { static { AppCompatDelegate.setDefaultNightMode( AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM); } }
Suleiman19/Bottom-Navigation-Demo
app/src/main/java/com/grafixartist/bottomnav/MyApp.java
Java
apache-2.0
413
/******************************************************************************* * In the Hi-WAY project we propose a novel approach of executing scientific * workflows processing Big Data, as found in NGS applications, on distributed * computational infrastructures. The Hi-WAY software stack comprises the func- * tional workflow language Cuneiform as well as the Hi-WAY ApplicationMaster * for Apache Hadoop 2.x (YARN). * * List of Contributors: * * Jörgen Brandt (HU Berlin) * Marc Bux (HU Berlin) * Ulf Leser (HU Berlin) * * Jörgen Brandt is funded by the European Commission through the BiobankCloud * project. Marc Bux is funded by the Deutsche Forschungsgemeinschaft through * research training group SOAMED (GRK 1651). * * Copyright 2014 Humboldt-Universität zu Berlin * * 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 de.huberlin.cuneiform.dag; public interface Container { public int size() throws NotDerivableException; public Resolveable get( int idx ) throws NotDerivableException; }
joergen7/cuneiform-legacy
src/main/java/de/huberlin/cuneiform/dag/Container.java
Java
apache-2.0
1,621
from django.db import models from django.contrib.auth.models import User from datetime import date # Create your models here. class Genre(models.Model): """ Model representing a book genre (e.g. Science Fiction, Non Fiction). """ name = models.CharField(max_length=200, help_text="Enter a book genre (e.g. Science Fiction, French Poetry etc.)") def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return self.name from django.urls import reverse #Used to generate URLs by reversing the URL patterns class Book(models.Model): class Meta: permissions = (("can_edit_book", "Edit book"),) """ Model representing a book (but not a specific copy of a book). """ title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) # Foreign Key used because book can only have one author, but authors can have multiple books # Author as a string rather than object because it hasn't been declared yet in the file. summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book") isbn = models.CharField('ISBN',max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') genre = models.ManyToManyField(Genre, help_text="Select a genre for this book") # ManyToManyField used because genre can contain many books. Books can cover many genres. # Genre class has already been defined so we can specify the object above. language = models.ForeignKey('Language', on_delete=models.SET_NULL, null=True) def __str__(self): """ String for representing the Model object. """ return self.title def get_absolute_url(self): """ Returns the url to access a particular book instance. """ return reverse('book-detail', args=[str(self.id)]) def display_genre(self): """ Creates a string for the Genre. This is required to display genre in Admin. """ return ', '.join([ genre.name for genre in self.genre.all()[:3] ]) display_genre.short_description = 'Genre' import uuid # Required for unique book instances class BookInstance(models.Model): class Meta: permissions = (("can_mark_returned", "Set book as returned"),) ordering = ["due_back"] """ Model representing a specific copy of a book (i.e. that can be borrowed from the library). """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular book across whole library") book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) imprint = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) status = models.CharField(max_length=1, choices=LOAN_STATUS, blank=True, default='d', help_text='Book availability') def __str__(self): """ String for representing the Model object """ return '%s (%s)' % (self.id,self.book.title) @property def is_overdue(self): if self.due_back and date.today() > self.due_back: return True return False class Author(models.Model): """ Model representing an author. """ class Meta: permissions = (("can_edit_author", "Edit author"),) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('Died', null=True, blank=True) def get_absolute_url(self): """ Returns the url to access a particular author instance. """ return reverse('author-detail', args=[str(self.id)]) def __str__(self): """ String for representing the Model object. """ return '%s, %s' % (self.last_name, self.first_name) class Language(models.Model): """ Model representing a Language (e.g. English, French, Japanese, etc.) """ name = models.CharField(max_length=200, help_text="Enter a the book's natural language (e.g. English, French, Japanese etc.)") def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return self.name
byronlin92/django_local_library
catalog/models.py
Python
apache-2.0
4,639
# dl-twitch-series Notebook from the Deep Learning Twitch Series on AWS (https://twitch.tv/aws) * Episode 1: Neural Network Basics and Sentiment Analysis with Multi Layer Perceptron * Episode 2: Sequence Modeling: Model learns to do basic math and model to pronounce english words * Episode 3: Convolutional Neural Networks: Fashion MNIST and Finetuning * Episode 4: Sockeye and Chatbots * Episode 5: Timeseries modeling: Predicting Amazon ec2 instance spot price Other cool stuff in the repo * CNNs made simpler with [Gluon](https://github.com/sunilmallya/dl-twitch-series/blob/master/cnn_mnist_gluon_simplified.ipynb) * Extensible RNN Regression class with Gluon [code](https://github.com/sunilmallya/dl-twitch-series/blob/master/base_rnn_regressor.py) * Multivariate Timeseries forecasting with Symbolic MXNet and Gluon [notebook](https://github.com/sunilmallya/dl-twitch-series/blob/master/multivariate_timeseries_forecasting.ipynb)
sunilmallya/dl-twitch-series
README.md
Markdown
apache-2.0
949
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_ARITHMETIC_OPTIMIZER_TEST_UTILS_H_ #define TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_ARITHMETIC_OPTIMIZER_TEST_UTILS_H_ #include "tensorflow/core/grappler/optimizers/arithmetic_optimizer.h" #include "tensorflow/core/grappler/optimizers/common_subgraph_elimination.h" #include "tensorflow/core/grappler/optimizers/constant_folding.h" #include "tensorflow/core/grappler/optimizers/model_pruner.h" #include "tensorflow/core/grappler/utils/grappler_test.h" #include "tensorflow/core/lib/core/status_test_util.h" namespace tensorflow { namespace grappler { class ArithmeticOptimizerTest : public GrapplerTest { protected: // Optimize a graph using optimizer and prune all the nodes that no // longer have any output consumers. void OptimizeAndPrune(GraphOptimizer* optimizer, GrapplerItem* item, GraphDef* output) { TF_EXPECT_OK(optimizer->Optimize(nullptr, *item, output)); item->graph.Swap(output); output->Clear(); TF_EXPECT_OK(ModelPruner().Optimize(nullptr, *item, output)); } // Run optimizer twice to make sure the rewrite is idempotent. void DedupAndOptimizeTwiceAndPrune(GraphOptimizer* optimizer, GrapplerItem* item, GraphDef* output) { TF_EXPECT_OK(CommonSubgraphElimination().Optimize(nullptr, *item, output)); item->graph.Swap(output); output->Clear(); TF_EXPECT_OK(optimizer->Optimize(nullptr, *item, output)); item->graph.Swap(output); output->Clear(); TF_EXPECT_OK(optimizer->Optimize(nullptr, *item, output)); item->graph.Swap(output); output->Clear(); TF_EXPECT_OK(ModelPruner().Optimize(nullptr, *item, output)); } // Run optimizer twice to make sure the rewrite is idempotent. void OptimizeTwice(GraphOptimizer* optimizer, GrapplerItem* item, GraphDef* output) { TF_EXPECT_OK(optimizer->Optimize(nullptr, *item, output)); item->graph.Swap(output); output->Clear(); TF_EXPECT_OK(optimizer->Optimize(nullptr, *item, output)); } // Run optimizer twice to make sure the rewrite is idempotent. // Optionally run a constant folding pass before pruning. void OptimizeTwiceAndPrune(GraphOptimizer* optimizer, GrapplerItem* item, GraphDef* output, bool const_folding = false) { TF_EXPECT_OK(optimizer->Optimize(nullptr, *item, output)); item->graph.Swap(output); output->Clear(); TF_EXPECT_OK(optimizer->Optimize(nullptr, *item, output)); if (const_folding) { item->graph.Swap(output); output->Clear(); TF_EXPECT_OK(ConstantFolding(/*cpu_device=*/nullptr) .Optimize(nullptr, *item, output)); } item->graph.Swap(output); output->Clear(); TF_EXPECT_OK(ModelPruner().Optimize(nullptr, *item, output)); } void DisableAddToAddNCombining(ArithmeticOptimizer* optimizer) { optimizer->options_.combine_add_to_addn = false; } void EnableOnlyAddToAddNCombining(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.combine_add_to_addn = true; } void EnableOnlyFoldConjugateIntoTranspose(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.fold_conjugate_into_transpose = true; } void EnableOnlyFoldMultipleIntoConv(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.fold_multiply_into_conv = true; } void EnableOnlyFoldTransposeIntoMatMul(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.fold_transpose_into_matmul = true; } void EnableOnlyHoistCommonFactor(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.hoist_common_factor_out_of_aggregation = true; } void EnableOnlyMinimizeBroadcasts(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.minimize_broadcasts = true; } void EnableOnlyRemoveIdentityTranspose(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.remove_identity_transpose = true; } void EnableOnlyRemoveInvolution(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.remove_involution = true; } void EnableOnlyRemoveRedundantBitcast(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.remove_redundant_bitcast = true; } void EnableOnlyRemoveRedundantCast(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.remove_redundant_cast = true; } void EnableOnlyReorderReshapeAroundUnary(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.reorder_reshape_around_unary = true; } void EnableOnlyReduceUpsamplingDims(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.reduce_upsampling_dims = true; } void EnableOnlyRemoveRedundantReshape(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.remove_redundant_reshape = true; } void EnableOnlyRemoveNegation(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.remove_negation = true; } void EnableOnlyReorderCastAndTranspose(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.reorder_cast_like_and_value_preserving = true; } void EnableOnlyReplaceMulWithBroadcastByTile(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.replace_mul_with_tile = true; } void EnableOnlyReplaceMulWithSquare(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.replace_mul_with_square = true; } void EnableOnlyReplacePackWithTileReshape(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.replace_pack_with_tile_reshape = true; } void EnableOnlyHoistCWiseUnaryChains(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.hoist_cwise_unary_chains = true; } void EnableOnlySqrtDivToRsqrtMul(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.convert_sqrt_div_to_rsqrt_mul = true; } void EnableOnlyLogSoftmax(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.convert_log_softmax = true; } void EnableOnlyConvertPow(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.convert_pow = true; } void EnableOnlyFuseSquaredDiff(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.fuse_squared_diff = true; } void EnableOnlyRemoveIdempotent(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.remove_idempotent = true; } void EnableOnlyRemoveLogicalNot(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.remove_logical_not = true; } void EnableOnlySimplifyAggregation(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.simplify_aggregation = true; } void EnableOnlyLog1p(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.convert_log1p = true; } void EnableOnlyOptimizeMaxOrMinOfMonotonic(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.optimize_max_or_min_of_monotonic = true; } void EnableOnlyExpm1(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.convert_expm1 = true; } void EnableOnlyUnaryOpsComposition(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.unary_ops_composition = true; } void EnableOnlyRemoveStackSliceSameAxis(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.remove_stack_slice_same_axis = true; } void EnableOnlySimplifyEmbeddingLookup(ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.simplify_embedding_lookup = true; } void EnableOnlyRemoveCastIntoSegmentReduction( ArithmeticOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.remove_cast_into_segment_reduction = true; } private: void DisableAllStages(ArithmeticOptimizer* optimizer) { ArithmeticOptimizer::ArithmeticOptimizerOptions options; options.dedup_computations = false; options.combine_add_to_addn = false; options.convert_sqrt_div_to_rsqrt_mul = false; options.convert_pow = false; options.convert_log1p = false; options.optimize_max_or_min_of_monotonic = false; options.fold_conjugate_into_transpose = false; options.fold_multiply_into_conv = false; options.fold_transpose_into_matmul = false; options.hoist_common_factor_out_of_aggregation = false; options.hoist_cwise_unary_chains = false; options.minimize_broadcasts = false; options.remove_identity_transpose = false; options.remove_involution = false; options.remove_idempotent = false; options.remove_redundant_bitcast = false; options.remove_redundant_cast = false; options.remove_redundant_reshape = false; options.remove_negation = false; options.remove_logical_not = false; options.reorder_cast_like_and_value_preserving = false; options.replace_mul_with_tile = false; options.replace_mul_with_square = false; options.simplify_aggregation = false; options.unary_ops_composition = false; options.simplify_embedding_lookup = false; options.remove_cast_into_segment_reduction = false; optimizer->options_ = options; } }; } // end namespace grappler } // end namespace tensorflow #endif // TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_ARITHMETIC_OPTIMIZER_TEST_UTILS_H_
petewarden/tensorflow
tensorflow/core/grappler/optimizers/arithmetic_optimizer_test_utils.h
C
apache-2.0
10,639
/* * 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. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. */ package lizard.node; import java.util.ArrayList ; import java.util.Arrays ; import java.util.Collection ; import java.util.List ; import lizard.comms.CommsException ; import lizard.comms.ConnState ; import org.apache.jena.atlas.lib.BitsLong ; import org.apache.jena.atlas.lib.Bytes ; import org.apache.jena.atlas.lib.InternalErrorException ; import org.apache.jena.ext.com.google.common.collect.ArrayListMultimap ; import org.apache.jena.ext.com.google.common.collect.ListMultimap ; import org.apache.jena.graph.Node ; import org.apache.jena.tdb2.lib.NodeLib ; import org.apache.jena.tdb2.store.Hash ; import org.apache.jena.tdb2.store.NodeId ; import org.apache.jena.tdb2.sys.SystemTDB ; /** Distribute by segment (in Nodeid) * OLD CODE */ public class DistributorNodesBySegment implements DistributorNodes { //@@ Replication. ListMultimap<Long, NodeTableRemote> places = ArrayListMultimap.create() ; private final int size ; private final String localVNode ; public DistributorNodesBySegment(String localVNode, int N) { this.localVNode = localVNode ; this.size = N ; } // segment = hashKey+1 public void add(Long hashKey, NodeTableRemote... nodeTables) { add(hashKey, Arrays.asList(nodeTables)) ; } public void add(Long hashKey, List<NodeTableRemote> nodeTables) { for ( NodeTableRemote nt : nodeTables ) places.put(hashKey+1, nt) ; } @Override public List<NodeTableRemote> storeAt(Node node) { return locateWrite(node) ; } @Override public List<NodeTableRemote> findAt(NodeId nodeid) { return locateRead(nodeid) ; } @Override public List<NodeTableRemote> findAt(Node node) { return locateRead(node) ; } @Override public List<NodeTableRemote> allFind() { List<NodeTableRemote> placesToGo = new ArrayList<>() ; for ( Long x : places.keys() ) { List<NodeTableRemote> z = places.get(x) ; NodeTableRemote ntr = chooseOne(z) ; if ( ntr == null ) throw new CommsException("Can't allFind - a segment is completely unavailable") ; placesToGo.add(ntr) ; } return placesToGo ; } /** Choose one remote, preferring a local vnode */ private NodeTableRemote chooseOne(List<NodeTableRemote> z) { NodeTableRemote maybe = null ; for ( NodeTableRemote ntr : z ) { // For each key, find one place if ( ntr.getStatus() == ConnState.OK ) { if ( localVNode == null ) return ntr ; if ( ntr.getRemoteVNode().equals(localVNode) ) return ntr ; maybe = ntr ; } } return maybe ; } @Override public Collection<NodeTableRemote> allStore() { Collection<NodeTableRemote> placesToGo = allRemotes() ; for ( NodeTableRemote ntr : placesToGo ) { if ( ntr.getStatus() != ConnState.OK ) throw new CommsException("Can't store - an index is unavailable") ; } return placesToGo ; } @Override public Collection<NodeTableRemote> allRemotes() { return places.values() ; } private List<NodeTableRemote> locateRead(Node node) { // Any place we coudl have written it to. return locateWrite(node) ; } private List<NodeTableRemote> locateRead(NodeId nodeId) { long segment = segment(nodeId) ; if ( segment == 0 || segment > 15 ) throw new InternalErrorException("Segment out of range: got="+segment) ; List<NodeTableRemote> possibilities = places.get(segment) ; // Get first active for ( NodeTableRemote idx : possibilities ) { if ( idx.getStatus() == ConnState.OK ) return Arrays.asList(idx) ; } throw new CommsException("No segements available") ; } private List<NodeTableRemote> locateWrite(Node node) { if ( ! node.isConcrete() ) throw new CommsException("Can't store node: "+node ) ; long segment = segment(node) ; List<NodeTableRemote> possibilities = places.get(segment) ; // Check all available for ( NodeTableRemote ntr : possibilities ) { if ( ntr.getStatus() != ConnState.OK ) throw new CommsException("Can't store - a segment is unavailable: "+ntr.toString()+" is "+ntr.getStatus()) ; } return possibilities ; } // private List<TupleIndexRemote> locate(Tuple<NodeId> tuple) { // NodeId n = tuple.get(0) ; // if ( NodeId.isAny(n) ) // return allStore() ; // long segment = segment(n) ; // if ( segment == 0 || segment > size ) // Log.fatal(this, "locateWrite -- hash >= size :: "+hash+" > "+size) ; // List<TupleIndexRemote> possibilities = places.get(hash) ; // if ( possibilities == null ) // Log.fatal(this, "No places to go for tuple: "+tuple+"("+hash+"/"+size+")") ; // return possibilities ; // } private long segment(Node node) { // @@ Overly expensive Hash hash = new Hash(SystemTDB.LenNodeHash) ; NodeLib.setHash(hash, node) ; byte k[] = hash.getBytes() ; // Positive int x = Bytes.getInt(k, 0) & 0x8FFFFFF ; // Range 1 to 15 - zero is kept as an error marker. x = (x%size)+1 ; return x ; } private long segment(NodeId nodeId) { //long x = BitsLong.unpack(nodeId.getId(), 48, 56) ; long x = BitsLong.unpack(nodeId.getPtrLocation(), 48, 56); if ( x <= 0 || x > size ) throw new InternalErrorException("Node segment out of range (0X"+Long.toHexString(x)+")") ; return x ; } @Override public String toString() { return "Nodes:"+places.toString() ; } // private List<NodeTable> locate(NodeId nodeId) { // long x = BitsLong.unpack(nodeId.getId(), 52, 56) ; // if ( x <= 0 || x > size ) // throw new InternalErrorException("Node segement out of range") ; // return places.get(x) ; // } }
afs/lizard
lizard-node-server/src/main/java/lizard/node/DistributorNodesBySegment.java
Java
apache-2.0
6,963
// // OldStuff.h // MacNagios // // Created by Kiko Albiol on 21/11/15. // Copyright © 2015 BGP. All rights reserved. // #import <Foundation/Foundation.h> /** * @brief Old stuff */ @interface AppDelegateOld : NSObject <NSApplicationDelegate, NSUserNotificationCenterDelegate> @property (assign) IBOutlet NSWindow *window; @property WebView *webView; @property NSStatusItem *statusItem; @property NSTimer *timer; @property NSDictionary *configData; // data loaded from config plist @property NSArray *checkResults; // the results of the checking @property NSMutableArray *checkMessages; // an array of strings which are the messages that go into the next alert @property NSString *lastStatusString; // the last overall status string we had @property NSMutableDictionary *serviceStatusDict; // keep track of the last status of each service - so we can make a list of what changed //@property NSMenu *menu; @end
kikoalbiol/IFICNagios
IFICNagios/OldStuff.h
C
apache-2.0
974
def benchmark_hash_data(): """ CommandLine: python ~/code/ubelt/dev/bench_hash.py --convert=True --show python ~/code/ubelt/dev/bench_hash.py --convert=False --show """ import ubelt as ub #ITEM = 'JUST A STRING' * 100 ITEM = [0, 1, 'a', 'b', ['JUST A STRING'] * 4] HASHERS = ['sha1', 'sha512', 'xxh32', 'xxh64', 'blake3'] scales = list(range(5, 13)) results = ub.AutoDict() # Use json is faster or at least as fast it most cases # xxhash is also significantly faster than sha512 convert = ub.argval('--convert', default='True').lower() == 'True' print('convert = {!r}'.format(convert)) ti = ub.Timerit(9, bestof=3, verbose=1, unit='ms') for s in ub.ProgIter(scales, desc='benchmark', verbose=3): N = 2 ** s print(' --- s={s}, N={N} --- '.format(s=s, N=N)) data = [ITEM] * N for hasher in HASHERS: for timer in ti.reset(hasher): ub.hash_data(data, hasher=hasher, convert=convert) results[hasher].update({N: ti.mean()}) col = {h: results[h][N] for h in HASHERS} sortx = ub.argsort(col) ranking = ub.dict_subset(col, sortx) print('walltime: ' + ub.repr2(ranking, precision=9, nl=0)) best = next(iter(ranking)) #pairs = list(ub.iter_window( 2)) pairs = [(k, best) for k in ranking] ratios = [ranking[k1] / ranking[k2] for k1, k2 in pairs] nicekeys = ['{}/{}'.format(k1, k2) for k1, k2 in pairs] relratios = ub.odict(zip(nicekeys, ratios)) print('speedup: ' + ub.repr2(relratios, precision=4, nl=0)) # xdoc +REQUIRES(--show) # import pytest # pytest.skip() import pandas as pd df = pd.DataFrame.from_dict(results) df.columns.name = 'hasher' df.index.name = 'N' ratios = df.copy().drop(columns=df.columns) for k1, k2 in [('sha512', 'xxh32'), ('sha1', 'xxh32'), ('xxh64', 'xxh32')]: ratios['{}/{}'.format(k1, k2)] = df[k1] / df[k2] print() print('Seconds per iteration') print(df.to_string(float_format='%.9f')) print() print('Ratios of seconds') print(ratios.to_string(float_format='%.2f')) print() print('Average Ratio (over all N)') print('convert = {!r}'.format(convert)) print(ratios.mean().sort_values()) if ub.argflag('--show'): import kwplot kwplot.autompl() xdata = sorted(ub.peek(results.values()).keys()) ydata = ub.map_vals(lambda d: [d[x] for x in xdata], results) kwplot.multi_plot(xdata, ydata, xlabel='N', ylabel='seconds', title='convert = {}'.format(convert)) kwplot.show_if_requested() if __name__ == '__main__': """ CommandLine: python ~/code/ubelt/dev/bench_hash.py """ benchmark_hash_data()
Erotemic/ubelt
dev/bench/bench_hash.py
Python
apache-2.0
2,805
#!/usr/bin/python # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pandas as pd from google.cloud import datacatalog from google.protobuf import timestamp_pb2 from google.datacatalog_connectors.commons.prepare.base_entry_factory import \ BaseEntryFactory from google.datacatalog_connectors.rdbms.common import constants class DataCatalogEntryFactory(BaseEntryFactory): NO_VALUE_SPECIFIED = 'UNDEFINED' EMPTY_TOKEN = '?' def __init__(self, project_id, location_id, entry_resource_url_prefix, entry_group_id, metadata_definition): self.__project_id = project_id self.__location_id = location_id self.__entry_resource_url_prefix = entry_resource_url_prefix self.__entry_group_id = entry_group_id self.__metadata_definition = metadata_definition def make_entries_for_table_container(self, table_container): """Create Datacatalog entries from a table container dict. :param table_container: :return: entry_id, entry """ entry_id = self._format_id(table_container['name']) entry = datacatalog.Entry() entry.user_specified_type = self.__metadata_definition[ 'table_container_def']['type'] entry.user_specified_system = self.__entry_group_id entry.display_name = self._format_display_name(table_container['name']) create_time, update_time = \ DataCatalogEntryFactory.__convert_source_system_timestamp_fields( table_container.get('create_time'), table_container.get('update_time')) if create_time and update_time: created_timestamp = timestamp_pb2.Timestamp() created_timestamp.FromSeconds(create_time) entry.source_system_timestamps.create_time = created_timestamp updated_timestamp = timestamp_pb2.Timestamp() updated_timestamp.FromSeconds(update_time) entry.source_system_timestamps.update_time = updated_timestamp desc = table_container.get('desc') if pd.isna(desc): desc = '' entry.description = desc entry.name = datacatalog.DataCatalogClient.entry_path( self.__project_id, self.__location_id, self.__entry_group_id, entry_id) entry.linked_resource = '{}/{}'.format( self.__entry_resource_url_prefix, entry_id) return entry_id, entry def make_entry_for_tables(self, table, table_container_name): """Create Datacatalog entries from a table dict. :param table: :param table_container_name: :return: entry_id, entry """ entry_id = self._format_id('{}__{}'.format(table_container_name, table['name'])) entry = datacatalog.Entry() # some RDBMS' store views and tables definitions in the same # system table, and the name is not user friendly, so we only # keep it if it's a VIEW type. table_type = table.get(constants.TABLE_TYPE_KEY) if table_type and table_type.lower() == \ constants.VIEW_TYPE_VALUE: table_type = table_type.lower() else: table_type = self.__metadata_definition['table_def']['type'] entry.user_specified_type = table_type entry.user_specified_system = self.__entry_group_id entry.display_name = self._format_display_name(table['name']) entry.name = datacatalog.DataCatalogClient.entry_path( self.__project_id, self.__location_id, self.__entry_group_id, entry_id) desc = table.get('desc') if pd.isna(desc): desc = '' entry.description = desc entry.linked_resource = '{}/{}/{}'.format( self.__entry_resource_url_prefix, table_container_name, self._format_id(table['name'])) create_time, update_time = \ DataCatalogEntryFactory.__convert_source_system_timestamp_fields( table.get('create_time'), table.get('update_time')) if create_time and update_time: created_timestamp = timestamp_pb2.Timestamp() created_timestamp.FromSeconds(create_time) entry.source_system_timestamps.create_time = created_timestamp updated_timestamp = timestamp_pb2.Timestamp() updated_timestamp.FromSeconds(update_time) entry.source_system_timestamps.update_time = updated_timestamp columns = [] for column in table['columns']: desc = column.get('desc') if pd.isna(desc): desc = '' columns.append( datacatalog.ColumnSchema( column=self._format_id(column['name']), description=desc, type=DataCatalogEntryFactory.__format_entry_column_type( column['type']))) entry.schema.columns.extend(columns) return entry_id, entry @staticmethod def __convert_date_value_to_epoch(date_value): if pd.notnull(date_value): return int(date_value.timestamp()) @staticmethod def __convert_source_system_timestamp_fields(raw_create_time, raw_update_time): create_time = DataCatalogEntryFactory. \ __convert_date_value_to_epoch(raw_create_time) if not pd.isnull(raw_update_time): update_time = DataCatalogEntryFactory. \ __convert_date_value_to_epoch(raw_update_time) else: update_time = create_time return create_time, update_time @staticmethod def __format_entry_column_type(source_name): if isinstance(source_name, bytes): # We've noticed some MySQL instances use bytes-like objects # instead of `str` to specify the column types. We are using UTF-8 # to decode such objects when it happens because UTF-8 is the # default character set for MySQL 8.0 onwards. # # We didn't notice similar behavior with other RDBMS but, if so, # we should handle encoding as a configuration option that each # RDBMS connector would have to set up. It might be exposed as a # CLI arg, so users could easily change that. There is also the # option to scrape that config directly from the DB. source_name = source_name.decode("utf-8") formatted_name = source_name.replace('&', '_') formatted_name = formatted_name.replace(':', '_') formatted_name = formatted_name.replace('/', '_') formatted_name = formatted_name.replace(' ', '_') if formatted_name == DataCatalogEntryFactory.EMPTY_TOKEN: formatted_name = DataCatalogEntryFactory.NO_VALUE_SPECIFIED return formatted_name
GoogleCloudPlatform/datacatalog-connectors-rdbms
google-datacatalog-rdbms-connector/src/google/datacatalog_connectors/rdbms/prepare/datacatalog_entry_factory.py
Python
apache-2.0
7,500
package io.quarkus.smallrye.health.test; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.is; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.quarkus.test.QuarkusUnitTest; import io.restassured.RestAssured; import io.restassured.parsing.Parser; public class HealthUnitTest { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(BasicHealthCheck.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")); @Test public void testHealth() { // the health check does not set a content type so we need to force the parser try { RestAssured.defaultParser = Parser.JSON; RestAssured.when().get("/q/health/live").then() .body("status", is("UP"), "checks.status", contains("UP"), "checks.name", contains("basic")); } finally { RestAssured.reset(); } } }
quarkusio/quarkus
extensions/smallrye-health/deployment/src/test/java/io/quarkus/smallrye/health/test/HealthUnitTest.java
Java
apache-2.0
1,184
Bloc Jams Angular ========= Bloc Jams Angular is [Bloc Jams](https://github.com/ipaulson/bloc-jams) refactored using Angular - HTML - CSS - Javascript - Angular & other resources: - Buzz Library - Fonts from Google - Icons from [Ionic](https://ionicframework.com/docs/ionicons/) - jQuery Clone It and Run It Yourself ---------------------------- ``` git clone https://github.com/ipaulson/bloc-jams-angular ``` Open `index.html` to check it out! ------ Made with the help of my mentor at [Bloc](http://bloc.io)
ipaulson/bloc-jams-angular
README.md
Markdown
apache-2.0
520
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.util; import java.io.Serializable; import org.apache.commons.math3.exception.MathIllegalArgumentException; /** * Classic median of 3 strategy given begin and end indices. * @version $Id: MedianOf3PivotingStrategy.java 1610141 2014-07-13 08:52:29Z luc $ * @since 3.4 */ public class MedianOf3PivotingStrategy implements PivotingStrategyInterface, Serializable { /** Serializable UID. */ private static final long serialVersionUID = 20140713L; /**{@inheritDoc} * This in specific makes use of median of 3 pivoting. * @return The index corresponding to a pivot chosen between the * first, middle and the last indices of the array slice * @throws MathIllegalArgumentException when indices exceeds range */ public int pivotIndex(final double[] work, final int begin, final int end) throws MathIllegalArgumentException { MathArrays.verifyValues(work, begin, end-begin); final int inclusiveEnd = end - 1; final int middle = begin + (inclusiveEnd - begin) / 2; final double wBegin = work[begin]; final double wMiddle = work[middle]; final double wEnd = work[inclusiveEnd]; if (wBegin < wMiddle) { if (wMiddle < wEnd) { return middle; } else { return wBegin < wEnd ? inclusiveEnd : begin; } } else { if (wBegin < wEnd) { return begin; } else { return wMiddle < wEnd ? inclusiveEnd : middle; } } } }
tknandu/CommonsMath_Modifed
math (trunk)/src/main/java/org/apache/commons/math3/util/MedianOf3PivotingStrategy.java
Java
apache-2.0
2,399
#!/usr/bin/env python # -*- python -*- #BEGIN_LEGAL # #Copyright (c) 2016 Intel Corporation # # 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. # #END_LEGAL ############################################################################ ## START OF IMPORTS SETUP ############################################################################ import sys import os import re import copy import glob import types try: from . import base from . import dag from . import util from . import plan except: s = "\nXED ERROR: mfile.py could not find mbuild." + \ " Should be a sibling of the xed2 directory.\n\n" sys.stderr.write(s) sys.exit(1) ########################################################################### ## DOXYGEN SUPPORT ########################################################################### def _doxygen_version_okay(s, want_major, want_minor, want_fix): values = s.split('.') maj =int(values[0]) minor = int(values[1]) fix = 0 if len(values) > 2: # remove everything after the dash for things like: 'Doxygen # 1.5.1-p1' values[2] = re.sub(r'-.*$','',values[2]) try: fix = int(values[2]) except ValueError as v: pass if (maj > 1) or \ (maj == want_major and minor > want_minor) or \ (maj == want_major and minor == want_minor and fix >= want_fix): return True return False def _find_doxygen(env): """Find the right version of doxygen. Return a tuple of the command name and a boolean indicating whether or not the version checked out.""" if env['doxygen_cmd'] == '': doxygen_cmd_intel = "/usr/intel/bin/doxygen" doxygen_cmd_cygwin = "C:/cygwin/bin/doxygen" doxygen_cmd_mac = \ "/Applications/Doxygen.app/Contents/Resources/doxygen" doxygen_cmd = "doxygen" if env['build_os'] == 'win': if os.path.exists(doxygen_cmd_cygwin): doxygen_cmd = doxygen_cmd_cygwin else: base.msgb('DOXYGEN',"Could not find cygwin's doxygen," + "trying doxygen from PATH") elif env['build_os'] == 'lin': if base.verbose(2): base.msgb("CHECKING FOR", doxygen_cmd_intel) if os.path.exists(doxygen_cmd_intel): doxygen_cmd = doxygen_cmd_intel elif env['build_os'] == 'mac': if base.verbose(2): base.msgb("CHECKING FOR", doxygen_cmd_mac) if os.path.exists(doxygen_cmd_mac): doxygen_cmd = doxygen_cmd_mac else: doxygen_cmd = env['doxygen_cmd'] doxygen_cmd = env.escape_string(doxygen_cmd) doxygen_okay = False if base.verbose(2): base.msgb('Checking doxygen version','...') if base.check_python_version(2,4): try: (retval, output, error_output) = \ util.run_command(doxygen_cmd + " --version") if retval==0: if len(output) > 0: first_line = output[0].strip() if base.verbose(2): base.msgb("Doxygen version", first_line) doxygen_okay = _doxygen_version_okay(first_line, 1,4,6) else: for o in output: base.msgb("Doxygen-version-check STDOUT", o) if error_output: for line in error_output: base.msgb("STDERR ",line.rstrip()) except: base.die("Doxygen required by the command line options " + "but no doxygen found") return (doxygen_cmd, doxygen_okay) def _replace_match(istring, mtch, newstring, group_name): """This is a lame way of avoiding regular expression backslashing issues""" x1= mtch.start(group_name) x2= mtch.end(group_name) ostring = istring[0:x1] + newstring + istring[x2:] return ostring def _customize_doxygen_file(env, subs): """Change the $(*) strings to the proper value in the config file. Returns True on success""" # doxygen wants quotes around paths with spaces for k,s in iter(subs.items()): if re.search(' ',s): if not re.search('^".*"$',s): base.die("Doxygen requires quotes around strings with spaces: [%s]->[%s]" % ( k,s)) return False # input and output files try: lines = open(env['doxygen_config']).readlines() except: base.msgb("Could not open input file: " + env['doxygen_config']) return False env['doxygen_config_customized'] = \ env.build_dir_join(os.path.basename(env['doxygen_config']) + '.customized') try: ofile = open(env['doxygen_config_customized'],'w') except: base.msgb("Could not open output file: " + env['doxygen_config_customized']) return False # compile the patterns rsubs = {} for k,v in iter(subs.items()): rsubs[k]=re.compile(r'(?P<tag>[$][(]' + k + '[)])') olines = [] for line in lines: oline = line for k,p in iter(rsubs.items()): #print ('searching for', k, 'to replace it with', subs[k]) m = p.search(oline) while m: #print ('replacing', k, 'with', subs[k]) oline = _replace_match(oline, m, subs[k], 'tag') m = p.search(oline) olines.append(oline) try: for line in olines: ofile.write(line) except: ofile.close() base.msgb("Could not write output file: " + env['doxygen_config_customized']) return False ofile.close() return True def _build_doxygen_main(args, env): """Customize the doxygen input file. Run the doxygen command, copy in any images, and put the output in the right place.""" if isinstance(args, list): if len(args) < 2: base.die("Need subs dictionary and dummy file arg for the doxygen command " + "to indicate its processing") else: base.die("Need a list for _build_doxygen_main with the subs " + "dictionary and the dummy file name") (subs,dummy_file) = args (doxygen_cmd, doxygen_okay) = _find_doxygen(env) if not doxygen_okay: msg = 'No good doxygen available on this system; ' + \ 'Your command line arguments\n\trequire it to be present. ' + \ 'Consider dropping the "doc" and "doc-build" options\n\t or ' + \ 'specify a path to doxygen with the --doxygen knob.\n\n\n' return (1, [msg]) # failure else: env['DOXYGEN'] = doxygen_cmd try: okay = _customize_doxygen_file(env, subs) except: base.die("CUSTOMIZE DOXYGEN INPUT FILE FAILED") if not okay: return (1, ['Doxygen customization failed']) cmd = env['DOXYGEN'] + ' ' + \ env.escape_string(env['doxygen_config_customized']) if base.verbose(2): base.msgb("RUN DOXYGEN", cmd) (retval, output, error_output) = util.run_command(cmd) for line in output: base.msgb("DOX",line.rstrip()) if error_output: for line in error_output: base.msgb("DOX-ERROR",line.rstrip()) if retval != 0: base.msgb("DOXYGEN FAILED") base.die("Doxygen run failed. Retval=", str(retval)) util.touch(dummy_file) base.msgb("DOXYGEN","succeeded") return (0, []) # success ########################################################################### # Doxygen build ########################################################################### def _empty_dir(d): """return True if the directory d does not exist or if it contains no files/subdirectories.""" if not os.path.exists(d): return True for (root, subdirs, subfiles) in os.walk(d): if len(subfiles) or len(subdirs): return False return True def _make_doxygen_reference_manual(env, doxygen_inputs, subs, work_queue, hash_file_name='dox'): """Install the doxygen reference manual the doyxgen_output_dir directory. doxygen_inputs is a list of files """ dox_dag = dag.dag_t(hash_file_name,env=env) # so that the scanner can find them dirs = {} for f in doxygen_inputs: dirs[os.path.dirname(f)]=True for d in dirs.keys(): env.add_include_dir(d) # make sure the config and top file are in the inptus list doxygen_inputs.append(env['doxygen_config']) doxygen_inputs.append(env['doxygen_top_src']) dummy = env.build_dir_join('dummy-doxygen-' + hash_file_name) # Run it via the builder to make it dependence driven run_always = False if _empty_dir(env['doxygen_install']): run_always = True if run_always: _build_doxygen_main([subs,dummy], env) else: c1 = plan.plan_t(command=_build_doxygen_main, args= [subs,dummy], env= env, input= doxygen_inputs, output= dummy) dox1 = dox_dag.add(env,c1) okay = work_queue.build(dag=dox_dag) phase = "DOXYGEN" if not okay: base.die("[%s] failed. dying..." % phase) if base.verbose(2): base.msgb(phase, "build succeeded") ############################################################ def doxygen_env(env): """Add the doxygen variables to the environment""" doxygen_defaults = dict( doxygen_config='', doxygen_top_src='', doxygen_install='', doxygen_cmd='' ) env.update_dict(doxygen_defaults) def doxygen_args(env): """Add the knobs to the command line knobs parser""" env.parser.add_option("--doxygen-install", dest="doxygen_install", action="store", default='', help="Doxygen installation directory") env.parser.add_option("--doxygen-config", dest="doxygen_config", action="store", default='', help="Doxygen config file") env.parser.add_option("--doxygen-top-src", dest="doxygen_top_src", action="store", default='', help="Doxygen top source file") env.parser.add_option("--doxygen-cmd", dest="doxygen_cmd", action="store", default='', help="Doxygen command name") def doxygen_run(env, inputs, subs, work_queue, hash_file_name='dox'): """Run doxygen assuming certain values are in the environment env. @type env: env_t @param env: the environment @type inputs: list @param inputs: list of input files to scan for dependences @type subs: dictionary @param subs: replacements in the config file @type work_queue: work_queue_t @param work_queue: a work queue for the build @type hash_file_name: string @param hash_file_name: used for the dummy file and mbuild hash suffix """ _make_doxygen_reference_manual(env, inputs, subs, work_queue, hash_file_name)
intelxed/mbuild
mbuild/doxygen.py
Python
apache-2.0
12,057
package ma.glasnost.orika.generated; /** * This interface is used as a parameter during class generation in order to be able to avoid Illegal reflective access */ public interface GeneratedPackageClass { }
orika-mapper/orika
core/src/main/java/ma/glasnost/orika/generated/GeneratedPackageClass.java
Java
apache-2.0
209
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.apigateway.model; import java.io.Serializable; import javax.annotation.Generated; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteUsagePlanResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteUsagePlanResult == false) return false; DeleteUsagePlanResult other = (DeleteUsagePlanResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public DeleteUsagePlanResult clone() { try { return (DeleteUsagePlanResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/DeleteUsagePlanResult.java
Java
apache-2.0
2,187
/********************************************************************************** * $URL: https://source.sakaiproject.org/svn/kernel/tags/sakai-10.6/kernel-impl/src/main/java/org/sakaiproject/user/impl/UserServiceSql.java $ * $Id: UserServiceSql.java 105077 2012-02-24 22:54:29Z ottenhoff@longsight.com $ *********************************************************************************** * * Copyright (c) 2007, 2008 Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.user.impl; /** * database methods. */ public interface UserServiceSql { /** * return the sql statement which deletes an external user id for a given user from the sakai_user_id_map table. */ String getDeleteUserIdSql(); /** * return the sql statement which inserts a user id and an external user id into the sakai_user_id_map table. */ String getInsertUserIdSql(); /** * return the sql statement which updates an external user id for a given user in the sakai_user_id_map table. */ String getUpdateUserIdSql(); /** * return the sql statement which retrieves an external user id for a given user from the sakai_user_id_map table. */ String getUserEidSql(); /** * return the sql statement which retrieves the user id for a given user from the sakai_user_id_map table. */ String getUserIdSql(); /** * return the sql statement which retrieves the where clause from the sakai_user_id_map table. */ String getUserWhereSql(); /** * Return a "SELECT... WHERE... IN" statement to find multiple user records by EID in a single query. * The EID value count is used to generate the correct "(?, ?, ?)" string. */ String getUsersWhereEidsInSql(int numberOfSearchValues); /** * Return a "SELECT... WHERE... IN" statement to find multiple user records (with their EIDs) by ID * in a single query. The ID value count is used to generate the correct "(?, ?, ?)" string. */ String getUsersWhereIdsInSql(int numberOfSearchValues); /** * The maximum size of a "SELECT... WHERE... IN" query varies by database, but when it's reached, the * error can be difficult to interpret. This should be set to a reasonably safe value and used by * clients to break very long queries into a set of somewhat shorter ones. */ int getMaxInputsForSelectWhereInQueries(); }
eemirtekin/Sakai-10.6-TR
kernel/kernel-impl/src/main/java/org/sakaiproject/user/impl/UserServiceSql.java
Java
apache-2.0
2,946
/* GObject - GLib Type, Object, Parameter and Signal Library * Copyright (C) 2000-2001 Red Hat, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ #if !defined (__GLIB_GOBJECT_H_INSIDE__) && !defined (GOBJECT_COMPILATION) #error "Only <glib-object.h> can be included directly." #endif #ifndef __G_CLOSURE_H__ #define __G_CLOSURE_H__ #include <gobject/gtype.h> G_BEGIN_DECLS /* --- defines --- */ #define G_CLOSURE_NEEDS_MARSHAL(closure) (((GClosure*) (closure))->marshal == NULL) #define G_CLOSURE_N_NOTIFIERS(cl) ((cl)->meta_marshal + ((cl)->n_guards << 1L) + \ (cl)->n_fnotifiers + (cl)->n_inotifiers) #define G_CCLOSURE_SWAP_DATA(cclosure) (((GClosure*) (closure))->derivative_flag) #define G_CALLBACK(f) ((GCallback) (f)) /* -- typedefs --- */ typedef struct _GClosure GClosure; typedef struct _GClosureNotifyData GClosureNotifyData; typedef void (*GCallback) (void); typedef void (*GClosureNotify) (gpointer data, GClosure *closure); typedef void (*GClosureMarshal) (GClosure *closure, GValue *return_value, guint n_param_values, const GValue *param_values, gpointer invocation_hint, gpointer marshal_data); typedef struct _GCClosure GCClosure; /* --- structures --- */ struct _GClosureNotifyData { gpointer data; GClosureNotify notify; }; struct _GClosure { /*< private >*/ guint ref_count : 15; /*< private >*/ guint meta_marshal : 1; /*< private >*/ guint n_guards : 1; /*< private >*/ guint n_fnotifiers : 2; /* finalization notifiers */ /*< private >*/ guint n_inotifiers : 8; /* invalidation notifiers */ /*< private >*/ guint in_inotify : 1; /*< private >*/ guint floating : 1; /*< protected >*/ guint derivative_flag : 1; /*< public >*/ guint in_marshal : 1; /*< public >*/ guint is_invalid : 1; /*< private >*/ void (*marshal) (GClosure *closure, GValue /*out*/ *return_value, guint n_param_values, const GValue *param_values, gpointer invocation_hint, gpointer marshal_data); /*< protected >*/ gpointer data; /*< private >*/ GClosureNotifyData *notifiers; /* invariants/constrains: * - ->marshal and ->data are _invalid_ as soon as ->is_invalid==TRUE * - invocation of all inotifiers occours prior to fnotifiers * - order of inotifiers is random * inotifiers may _not_ free/invalidate parameter values (e.g. ->data) * - order of fnotifiers is random * - each notifier may only be removed before or during its invocation * - reference counting may only happen prior to fnotify invocation * (in that sense, fnotifiers are really finalization handlers) */ }; /* closure for C function calls, callback() is the user function */ struct _GCClosure { GClosure closure; gpointer callback; }; /* --- prototypes --- */ GClosure* g_cclosure_new (GCallback callback_func, gpointer user_data, GClosureNotify destroy_data); GClosure* g_cclosure_new_swap (GCallback callback_func, gpointer user_data, GClosureNotify destroy_data); GClosure* g_signal_type_cclosure_new (GType itype, guint struct_offset); /* --- prototypes --- */ GClosure* g_closure_ref (GClosure *closure); void g_closure_sink (GClosure *closure); void g_closure_unref (GClosure *closure); /* intimidating */ GClosure* g_closure_new_simple (guint sizeof_closure, gpointer data); void g_closure_add_finalize_notifier (GClosure *closure, gpointer notify_data, GClosureNotify notify_func); void g_closure_remove_finalize_notifier (GClosure *closure, gpointer notify_data, GClosureNotify notify_func); void g_closure_add_invalidate_notifier (GClosure *closure, gpointer notify_data, GClosureNotify notify_func); void g_closure_remove_invalidate_notifier (GClosure *closure, gpointer notify_data, GClosureNotify notify_func); void g_closure_add_marshal_guards (GClosure *closure, gpointer pre_marshal_data, GClosureNotify pre_marshal_notify, gpointer post_marshal_data, GClosureNotify post_marshal_notify); void g_closure_set_marshal (GClosure *closure, GClosureMarshal marshal); void g_closure_set_meta_marshal (GClosure *closure, gpointer marshal_data, GClosureMarshal meta_marshal); void g_closure_invalidate (GClosure *closure); void g_closure_invoke (GClosure *closure, GValue /*out*/ *return_value, guint n_param_values, const GValue *param_values, gpointer invocation_hint); /* FIXME: OK: data_object::destroy -> closure_invalidate(); MIS: closure_invalidate() -> disconnect(closure); MIS: disconnect(closure) -> (unlink) closure_unref(); OK: closure_finalize() -> g_free (data_string); random remarks: - need marshaller repo with decent aliasing to base types - provide marshaller collection, virtually covering anything out there */ G_END_DECLS #endif /* __G_CLOSURE_H__ */
easion/os_sdk
uclibc/include/glib-2.0/gobject/gclosure.h
C
apache-2.0
5,890
# mtgz [![Build Status](https://travis-ci.org/jefperito/mtgz.svg?branch=master)](http://travis-ci.org/#!/jefperito/mtgz) # Installation * Requires Python 3.x, setuptools and pip * execute: pip install .
jefperito/mtgz
README.md
Markdown
apache-2.0
206
package com.tjazi.infra.turbineserver.core; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = TurbineServerApplication.class) public class TurbineServerApplicationTests { @Test public void contextLoads() { } }
tjazi-com/infra_turbine_server
core/src/test/java/com/tjazi/infra/turbineserver/core/TurbineServerApplicationTests.java
Java
apache-2.0
446
package com.qdong.hcp.activity;/** * Created by AA on 2016/7/7. */ import android.app.Activity; import android.app.Application; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import com.baidu.mapapi.SDKInitializer; import com.qdong.communal.library.BuildConfig; import com.qdong.communal.library.util.SharedPreferencesUtil; import com.qdong.greendao.DaoMaster; import com.qdong.greendao.DaoSession; import com.qdong.hcp.enums.ActivityLifecycleStatus; import com.qdong.hcp.green_dao.CustomDbUpdateHelper; import com.qdong.hcp.utils.Constants; import com.qdong.hcp.utils.LogUtil; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * AppLoader * 责任人: Chuck * 修改人: Chuck * 创建/修改时间: 2016/7/7 14:13 * Copyright : 趣动智能科技有限公司-版权所有 **/ public class AppLoader extends Application { private static final String TAG = AppLoader.class.getSimpleName(); private static AppLoader ourInstance; /**activity生命周期监测**/ private ActivityLifecycleCallbacksImpl mActivityLifecycleCallbacksImpl; /**手机状态栏的高度**/ public static int STATUS_BAR_HEIGHT;//在LuanchActivity里赋值 /**手机屏幕高度**/ public static int SCREEN_HEIGHT;//在LuanchActivity里赋值 /**手机屏幕宽度**/ public static int SCREEN_WIDTH;//在LuanchActivity里赋值 public static AppLoader getInstance() { return ourInstance; } /**key是activity类名,value是他此时的状态**/ private HashMap<String,ActivityLifecycleStatus> mActivityStack=new HashMap<String,ActivityLifecycleStatus>(); @Override public void onCreate() { super.onCreate(); ourInstance=this; mActivityLifecycleCallbacksImpl=new ActivityLifecycleCallbacksImpl(); this.registerActivityLifecycleCallbacks(mActivityLifecycleCallbacksImpl); // 在使用 SDK 各组间之前初始化 context 信息,传入 ApplicationContext SDKInitializer.initialize(this); } /** * @method name:getScreenHeight * @des:获取屏幕高度 * @param :[] * @return type:int * @date 创建时间:2016/7/12 * @author Chuck **/ public int getScreenHeight(){ if(SCREEN_HEIGHT<=0){ SCREEN_HEIGHT=SharedPreferencesUtil.getInstance(ourInstance).getInt(Constants.SCREEN_HEIGHT,1280); } return SCREEN_HEIGHT; } /** * @method name:getScreenWidth * @des:获取屏幕宽度 * @param :[] * @return type:int * @date 创建时间:2016/7/12 * @author Chuck **/ public int getScreenWidth(){ if(SCREEN_WIDTH<=0){ SCREEN_WIDTH=SharedPreferencesUtil.getInstance(ourInstance).getInt(Constants.SCREEN_WIDTH,720); } return SCREEN_WIDTH; } /** * @method name:getStateBarHeight * @des:获取顶部状态栏的高度 * @param :[] * @return type:int * @date 创建时间:2016/7/7 * @author Chuck **/ public static int getStateBarHeight() { if(STATUS_BAR_HEIGHT== 0) { STATUS_BAR_HEIGHT = SharedPreferencesUtil.getInstance(ourInstance).getInt(SharedPreferencesUtil.STATEBARHEIGHT, 0); } return STATUS_BAR_HEIGHT; } /** * @method name:isAppFront * @des:app此时是否有界面处在前台 * @param :[] * @return type:boolean * @date 创建时间:2016/7/7 * @author Chuck **/ public boolean isAppFront(){ Set set = mActivityStack.entrySet(); for(Iterator iter = set.iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry)iter.next(); ActivityLifecycleStatus value = (ActivityLifecycleStatus)entry.getValue(); if(value!=null){ if(value==ActivityLifecycleStatus.RESUMED){//有界面处于RESUMED return true; } } } return false; } /** * @method name:getFrontActivityClassName * @des:获取最前台那个activity的类名(如果在前台) * @param :[] * @return type:java.lang.String * @date 创建时间:2016/7/7 * @author Chuck **/ public String getFrontActivityClassName(){ Set set = mActivityStack.entrySet(); for(Iterator iter = set.iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry)iter.next(); ActivityLifecycleStatus value = (ActivityLifecycleStatus)entry.getValue(); if(value!=null){ if(value==ActivityLifecycleStatus.RESUMED){//有界面处于Resumed return (String)entry.getKey(); } } } return null; } private class ActivityLifecycleCallbacksImpl implements ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { LogUtil.e("AppLoader", "onActivityCreated:" + activity.getClass().getName()); mActivityStack.put(activity.getClass().getName(), ActivityLifecycleStatus.CREATED); } @Override public void onActivityStarted(Activity activity) { LogUtil.e("AppLoader", "onActivityStarted:" + activity.getClass().getName()); mActivityStack.put(activity.getClass().getName(), ActivityLifecycleStatus.STARTED); } @Override public void onActivityResumed(Activity activity) { LogUtil.e("AppLoader", "onActivityResumed:" + activity.getClass().getName()); mActivityStack.put(activity.getClass().getName(), ActivityLifecycleStatus.RESUMED); } @Override public void onActivityPaused(Activity activity) { LogUtil.e("AppLoader", "onActivityPaused:" + activity.getClass().getName()); mActivityStack.put(activity.getClass().getName(), ActivityLifecycleStatus.PAUSED); } @Override public void onActivityStopped(Activity activity) { LogUtil.e("AppLoader", "onActivityStopped:" + activity.getClass().getName()); mActivityStack.put(activity.getClass().getName(), ActivityLifecycleStatus.STOPPED); } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { LogUtil.e("AppLoader", "onActivityDestroyed:" + activity.getClass().getName()); try { mActivityStack.remove(activity.getClass().getName()); } catch (Exception e) { e.printStackTrace(); } } } /*** * GreenDao相关 */ private static DaoMaster daoMaster; private static DaoSession daoSession; public static SQLiteDatabase db; public static final String DB_NAME = com.qdong.hcp.BuildConfig.DB_NAME;//gradle里面配置数据库名,编译时动态生成 public static DaoMaster getDaoMaster(Context context) { if (daoMaster == null) { CustomDbUpdateHelper helper = new CustomDbUpdateHelper(context,DB_NAME, null); daoMaster = new DaoMaster(helper.getWritableDatabase()); } return daoMaster; } public static DaoSession getDaoSession(Context context) { if (daoSession == null) { if (daoMaster == null) { daoMaster = getDaoMaster(context); } daoSession = daoMaster.newSession(); } return daoSession; } public static SQLiteDatabase getSQLDatebase(Context context) { if (daoSession == null) { if (daoMaster == null) { daoMaster = getDaoMaster(context); } db = daoMaster.getDatabase(); } return db; } /** * @method name:getAutoLoginParameterMap * @des:为自动登录提供登录参数 * @param :[] * @return type:java.util.HashMap<java.lang.String,java.lang.String> * @date 创建时间:2016/8/22 * @author Chuck **/ public HashMap<String, String> getAutoLoginParameterMap() { HashMap<String, String> map = new HashMap<>(); /**测试代码,实际从缓存里获取**/ map.put("account", "15262592514"); map.put("password", "FC9DDCCA42C8FC33"); map.put("deviceMac", "c4072f244658"); map.put("gpsLong", "100"); map.put("deviceName", "HUAWEI"); map.put("deviceSystem", "3"); map.put("gpsLat", "60"); return map; } }
506954774/android_communal_library
HCP/src/main/java/com/qdong/hcp/activity/AppLoader.java
Java
apache-2.0
8,754
--- layout: base title: 'Statistics of cop in UD_Slovenian' udver: '2' --- ## Treebank Statistics: UD_Slovenian: Relations: `cop` This relation is universal. 2826 nodes (2%) are attached to their parents as `cop`. 2540 instances of `cop` (90%) are right-to-left (child precedes parent). Average distance between parent and child is 2.53715498938429. The following 6 pairs of parts of speech are connected with `cop`: <tt><a href="sl-pos-ADJ.html">ADJ</a></tt>-<tt><a href="sl-pos-AUX.html">AUX</a></tt> (1910; 68% instances), <tt><a href="sl-pos-NOUN.html">NOUN</a></tt>-<tt><a href="sl-pos-AUX.html">AUX</a></tt> (813; 29% instances), <tt><a href="sl-pos-DET.html">DET</a></tt>-<tt><a href="sl-pos-AUX.html">AUX</a></tt> (56; 2% instances), <tt><a href="sl-pos-PROPN.html">PROPN</a></tt>-<tt><a href="sl-pos-AUX.html">AUX</a></tt> (25; 1% instances), <tt><a href="sl-pos-PRON.html">PRON</a></tt>-<tt><a href="sl-pos-AUX.html">AUX</a></tt> (20; 1% instances), <tt><a href="sl-pos-NUM.html">NUM</a></tt>-<tt><a href="sl-pos-AUX.html">AUX</a></tt> (2; 0% instances). ~~~ conllu # visual-style 6 bgColor:blue # visual-style 6 fgColor:white # visual-style 10 bgColor:blue # visual-style 10 fgColor:white # visual-style 10 6 cop color:blue 1 Zakonodaja zakonodaja NOUN Ncfsn Case=Nom|Gender=Fem|Number=Sing 10 nsubj _ Dep=6|Rel=Sb 2 in in CCONJ Cc _ 3 cc _ Dep=3|Rel=Conj 3 trg trg NOUN Ncmsn Case=Nom|Gender=Masc|Number=Sing 1 conj _ Dep=1|Rel=Coord 4 delovne deloven ADJ Agpfsg Case=Gen|Degree=Pos|Gender=Fem|Number=Sing 5 amod _ Dep=5|Rel=Atr 5 sile sila NOUN Ncfsg Case=Gen|Gender=Fem|Number=Sing 3 nmod _ Dep=3|Rel=Atr 6 sta biti AUX Va-r3d-n Mood=Ind|Number=Dual|Person=3|Polarity=Pos|Tense=Pres|VerbForm=Fin 10 cop _ Dep=0|Rel=Root 7 med med ADP Si Case=Ins 8 case _ Dep=8|Rel=Atr 8 seboj se PRON Px---i Case=Ins|PronType=Prs|Reflex=Yes 10 nmod _ Dep=10|Rel=Atr 9 tesno tesno ADV Rgp Degree=Pos 10 advmod _ Dep=10|Rel=Atr 10 povezana povezan ADJ Appmdn Case=Nom|Degree=Pos|Gender=Masc|Number=Dual|VerbForm=Part 0 root _ SpaceAfter=No|Dep=6|Rel=Atr 11 . . PUNCT Z _ 10 punct _ Dep=0|Rel=Root ~~~ ~~~ conllu # visual-style 3 bgColor:blue # visual-style 3 fgColor:white # visual-style 4 bgColor:blue # visual-style 4 fgColor:white # visual-style 4 3 cop color:blue 1 Toda toda CCONJ Cc _ 4 cc _ Dep=3|Rel=Conj 2 kaj kaj PRON Pq-nsn Case=Nom|Gender=Neut|Number=Sing|PronType=Int 4 nsubj _ Dep=3|Rel=Sb 3 je biti AUX Va-r3s-n Mood=Ind|Number=Sing|Person=3|Polarity=Pos|Tense=Pres|VerbForm=Fin 4 cop _ Dep=0|Rel=Root 4 energija energija NOUN Ncfsn Case=Nom|Gender=Fem|Number=Sing 0 root _ SpaceAfter=No|Dep=3|Rel=Atr 5 " " PUNCT Z _ 6 punct _ Dep=0|Rel=Root 6 nacionalizma nacionalizem NOUN Ncmsg Case=Gen|Gender=Masc|Number=Sing 4 nmod _ SpaceAfter=No|Dep=4|Rel=Atr 7 " " PUNCT Z _ 6 punct _ SpaceAfter=No|Dep=0|Rel=Root 8 ? ? PUNCT Z _ 4 punct _ Dep=0|Rel=Root ~~~ ~~~ conllu # visual-style 2 bgColor:blue # visual-style 2 fgColor:white # visual-style 1 bgColor:blue # visual-style 1 fgColor:white # visual-style 1 2 cop color:blue 1 Kakšno kakšen DET Pq-nsn Case=Nom|Gender=Neut|Number=Sing|PronType=Int 0 root _ Dep=2|Rel=Atr 2 je biti AUX Va-r3s-n Mood=Ind|Number=Sing|Person=3|Polarity=Pos|Tense=Pres|VerbForm=Fin 1 cop _ Dep=0|Rel=Root 3 sploh sploh PART Q _ 1 advmod _ Dep=0|Rel=Root 4 mariborsko mariborski ADJ Agpnsn Case=Nom|Degree=Pos|Gender=Neut|Number=Sing 5 amod _ Dep=5|Rel=Atr 5 stališče stališče NOUN Ncnsn Case=Nom|Gender=Neut|Number=Sing 1 nsubj _ Dep=2|Rel=Sb 6 ob ob ADP Sl Case=Loc 7 case _ Dep=7|Rel=Atr 7 tem ta DET Pd-nsl Case=Loc|Gender=Neut|Number=Sing|PronType=Dem 1 obl _ SpaceAfter=No|Dep=2|Rel=AdvO 8 , , PUNCT Z _ 11 punct _ Dep=0|Rel=Root 9 ga on PRON Pp3msa--y Case=Acc|Gender=Masc|Number=Sing|Person=3|PronType=Prs|Variant=Short 11 obj _ Dep=11|Rel=Obj 10 sploh sploh PART Q _ 11 advmod _ Dep=0|Rel=Root 11 imamo imeti VERB Vmpr1p-n Aspect=Imp|Mood=Ind|Number=Plur|Person=1|Polarity=Pos|Tense=Pres|VerbForm=Fin 1 parataxis _ SpaceAfter=No|Dep=0|Rel=Root 12 ! ! PUNCT Z _ 1 punct _ Dep=0|Rel=Root ~~~
UniversalDependencies/docs
treebanks/sl_ssj/sl-dep-cop.md
Markdown
apache-2.0
4,055
--- layout: default id: 2016-08-23-Qian-Xinyuan surname: Qian name: Xinyuan university: Queen Mary University of London date: 23/08/2016 aboutme: from: China research_topic: Queen Mary University of London abstract: advisor: Omologo Maurizio keywords: website: img: qian.jpg email: qian<i class="fa fa-at" aria-hidden="true"></i>fbk.eu alt: Xinyuan Qian modal-id: stud114 ---
phdfbk/phdfbk.github.io
students/_posts/2016-08-23-qian.md
Markdown
apache-2.0
381
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CenturyLinkCloudSDK.ServiceModels { public class ServerState { public string ServerId { get; set; } public string ServerName { get; set; } public bool InMaintenanceMode { get; set; } public string PowerState { get; set; } public bool Selected { get; set; } } }
CenturyLinkCloud/clc-net-sdk
src/CenturyLinkCloudSDK/ServiceModels/Domain/ServerState.cs
C#
apache-2.0
447
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver13; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import io.netty.buffer.ByteBuf; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFOxmConnTrackingNwSrcMaskedVer13 implements OFOxmConnTrackingNwSrcMasked { private static final Logger logger = LoggerFactory.getLogger(OFOxmConnTrackingNwSrcMaskedVer13.class); // version: 1.3 final static byte WIRE_VERSION = 4; final static int LENGTH = 12; private final static U32 DEFAULT_VALUE = U32.ZERO; private final static U32 DEFAULT_VALUE_MASK = U32.ZERO; // OF message fields private final U32 value; private final U32 mask; // // Immutable default instance final static OFOxmConnTrackingNwSrcMaskedVer13 DEFAULT = new OFOxmConnTrackingNwSrcMaskedVer13( DEFAULT_VALUE, DEFAULT_VALUE_MASK ); // package private constructor - used by readers, builders, and factory OFOxmConnTrackingNwSrcMaskedVer13(U32 value, U32 mask) { if(value == null) { throw new NullPointerException("OFOxmConnTrackingNwSrcMaskedVer13: property value cannot be null"); } if(mask == null) { throw new NullPointerException("OFOxmConnTrackingNwSrcMaskedVer13: property mask cannot be null"); } this.value = value; this.mask = mask; } // Accessors for OF message fields @Override public long getTypeLen() { return 0x1f108L; } @Override public U32 getValue() { return value; } @Override public U32 getMask() { return mask; } @Override public MatchField<U32> getMatchField() { return MatchField.CONN_TRACKING_NW_SRC; } @Override public boolean isMasked() { return true; } public OFOxm<U32> getCanonical() { if (U32.NO_MASK.equals(mask)) { return new OFOxmConnTrackingNwSrcVer13(value); } else if(U32.FULL_MASK.equals(mask)) { return null; } else { return this; } } @Override public OFVersion getVersion() { return OFVersion.OF_13; } public OFOxmConnTrackingNwSrcMasked.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFOxmConnTrackingNwSrcMasked.Builder { final OFOxmConnTrackingNwSrcMaskedVer13 parentMessage; // OF message fields private boolean valueSet; private U32 value; private boolean maskSet; private U32 mask; BuilderWithParent(OFOxmConnTrackingNwSrcMaskedVer13 parentMessage) { this.parentMessage = parentMessage; } @Override public long getTypeLen() { return 0x1f108L; } @Override public U32 getValue() { return value; } @Override public OFOxmConnTrackingNwSrcMasked.Builder setValue(U32 value) { this.value = value; this.valueSet = true; return this; } @Override public U32 getMask() { return mask; } @Override public OFOxmConnTrackingNwSrcMasked.Builder setMask(U32 mask) { this.mask = mask; this.maskSet = true; return this; } @Override public MatchField<U32> getMatchField() { return MatchField.CONN_TRACKING_NW_SRC; } @Override public boolean isMasked() { return true; } @Override public OFOxm<U32> getCanonical()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property canonical not supported in version 1.3"); } @Override public OFVersion getVersion() { return OFVersion.OF_13; } @Override public OFOxmConnTrackingNwSrcMasked build() { U32 value = this.valueSet ? this.value : parentMessage.value; if(value == null) throw new NullPointerException("Property value must not be null"); U32 mask = this.maskSet ? this.mask : parentMessage.mask; if(mask == null) throw new NullPointerException("Property mask must not be null"); // return new OFOxmConnTrackingNwSrcMaskedVer13( value, mask ); } } static class Builder implements OFOxmConnTrackingNwSrcMasked.Builder { // OF message fields private boolean valueSet; private U32 value; private boolean maskSet; private U32 mask; @Override public long getTypeLen() { return 0x1f108L; } @Override public U32 getValue() { return value; } @Override public OFOxmConnTrackingNwSrcMasked.Builder setValue(U32 value) { this.value = value; this.valueSet = true; return this; } @Override public U32 getMask() { return mask; } @Override public OFOxmConnTrackingNwSrcMasked.Builder setMask(U32 mask) { this.mask = mask; this.maskSet = true; return this; } @Override public MatchField<U32> getMatchField() { return MatchField.CONN_TRACKING_NW_SRC; } @Override public boolean isMasked() { return true; } @Override public OFOxm<U32> getCanonical()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property canonical not supported in version 1.3"); } @Override public OFVersion getVersion() { return OFVersion.OF_13; } // @Override public OFOxmConnTrackingNwSrcMasked build() { U32 value = this.valueSet ? this.value : DEFAULT_VALUE; if(value == null) throw new NullPointerException("Property value must not be null"); U32 mask = this.maskSet ? this.mask : DEFAULT_VALUE_MASK; if(mask == null) throw new NullPointerException("Property mask must not be null"); return new OFOxmConnTrackingNwSrcMaskedVer13( value, mask ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFOxmConnTrackingNwSrcMasked> { @Override public OFOxmConnTrackingNwSrcMasked readFrom(ByteBuf bb) throws OFParseError { // fixed value property typeLen == 0x1f108L int typeLen = bb.readInt(); if(typeLen != 0x1f108) throw new OFParseError("Wrong typeLen: Expected=0x1f108L(0x1f108L), got="+typeLen); U32 value = U32.of(bb.readInt()); U32 mask = U32.of(bb.readInt()); OFOxmConnTrackingNwSrcMaskedVer13 oxmConnTrackingNwSrcMaskedVer13 = new OFOxmConnTrackingNwSrcMaskedVer13( value, mask ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", oxmConnTrackingNwSrcMaskedVer13); return oxmConnTrackingNwSrcMaskedVer13; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFOxmConnTrackingNwSrcMaskedVer13Funnel FUNNEL = new OFOxmConnTrackingNwSrcMaskedVer13Funnel(); static class OFOxmConnTrackingNwSrcMaskedVer13Funnel implements Funnel<OFOxmConnTrackingNwSrcMaskedVer13> { private static final long serialVersionUID = 1L; @Override public void funnel(OFOxmConnTrackingNwSrcMaskedVer13 message, PrimitiveSink sink) { // fixed value property typeLen = 0x1f108L sink.putInt(0x1f108); message.value.putTo(sink); message.mask.putTo(sink); } } public void writeTo(ByteBuf bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFOxmConnTrackingNwSrcMaskedVer13> { @Override public void write(ByteBuf bb, OFOxmConnTrackingNwSrcMaskedVer13 message) { // fixed value property typeLen = 0x1f108L bb.writeInt(0x1f108); bb.writeInt(message.value.getRaw()); bb.writeInt(message.mask.getRaw()); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFOxmConnTrackingNwSrcMaskedVer13("); b.append("value=").append(value); b.append(", "); b.append("mask=").append(mask); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFOxmConnTrackingNwSrcMaskedVer13 other = (OFOxmConnTrackingNwSrcMaskedVer13) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; if (mask == null) { if (other.mask != null) return false; } else if (!mask.equals(other.mask)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); result = prime * result + ((mask == null) ? 0 : mask.hashCode()); return result; } }
floodlight/loxigen-artifacts
openflowj/gen-src/main/java/org/projectfloodlight/openflow/protocol/ver13/OFOxmConnTrackingNwSrcMaskedVer13.java
Java
apache-2.0
10,963
// // ViewController.h // adfadsf // // Created by lisongfa on 16/6/16. // Copyright © 2016年 lisongfa. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
hgjlsongfa/02ARepository01
adfadsf/adfadsf/ViewController.h
C
apache-2.0
213
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bpmscript.test.hibernate; import java.util.Properties; import org.apache.commons.dbcp.BasicDataSource; import org.bpmscript.test.IServiceLookup; import org.bpmscript.test.ITestCallback; import org.bpmscript.test.ITestSupport; import org.bpmscript.test.ServiceLookup; import org.hibernate.SessionFactory; import org.hibernate.dialect.H2Dialect; import org.springframework.jdbc.support.lob.DefaultLobHandler; import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean; /** * */ public class SpringSessionFactoryTestSupport implements ITestSupport<IServiceLookup> { private final Class<?>[] classes; public SpringSessionFactoryTestSupport(Class<?>... classes) { super(); this.classes = classes; } // <bean id="databaseDriver" class="java.lang.String"><constructor-arg // value="org.h2.Driver"/></bean> // <bean id="databaseUrl" class="java.lang.String"><constructor-arg // value="jdbc:h2:~/bpmscript"/></bean> // <bean id="databaseUsername" class="java.lang.String"><constructor-arg value="sa"/></bean> // <bean id="databasePassword" class="java.lang.String"><constructor-arg value=""/></bean> // <bean id="databaseDialect" class="java.lang.String"><constructor-arg // value="org.hibernate.dialect.H2Dialect"/></bean> public void execute(ITestCallback<IServiceLookup> callback) throws Exception { // final BasicDataSource dataSource = new BasicDataSource(); // dataSource.setDriverClassName("com.mysql.jdbc.Driver"); // dataSource.setUrl("jdbc:mysql://localhost:3306/bpmscript"); // dataSource.setUsername("bpmscript"); // dataSource.setPassword("sa"); // // Properties properties = new Properties(); // properties.setProperty("hibernate.hbm2ddl.auto", "create"); // properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); // properties.setProperty("hibernate.show_sql", "false"); final BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("org.h2.Driver"); dataSource.setUrl("jdbc:h2:~/bpmscript"); dataSource.setUsername("sa"); dataSource.setPassword(""); Properties properties = new Properties(); properties.setProperty("hibernate.hbm2ddl.auto", "create"); properties.setProperty("hibernate.dialect", H2Dialect.class.getName()); properties.setProperty("hibernate.show_sql", "false"); // final BasicDataSource dataSource = new BasicDataSource(); // dataSource.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver"); // dataSource.setUrl("jdbc:derby:test;create=true"); // dataSource.setUsername("sa"); // dataSource.setPassword("sa"); // // Properties properties = new Properties(); // properties.setProperty("hibernate.hbm2ddl.auto", "update"); // properties.setProperty("hibernate.dialect", "org.hibernate.dialect.DerbyDialect"); // properties.setProperty("hibernate.query.substitutions", "true 1, false 0"); // properties.setProperty("hibernate.show_sql", "false"); ServiceLookup lookup = new ServiceLookup(); final AnnotationSessionFactoryBean sessionFactoryBean = new AnnotationSessionFactoryBean(); sessionFactoryBean.setLobHandler(new DefaultLobHandler()); sessionFactoryBean.setHibernateProperties(properties); sessionFactoryBean.setAnnotatedClasses(classes); sessionFactoryBean.setDataSource(dataSource); sessionFactoryBean.afterPropertiesSet(); SessionFactory sessionFactory = (SessionFactory) sessionFactoryBean.getObject(); lookup.addService("sessionFactory", sessionFactory); try { callback.execute(lookup); } finally { sessionFactory.close(); sessionFactoryBean.destroy(); } } }
jamiemccrindle/bpmscript
bpmscript-core/src/test/java/org/bpmscript/test/hibernate/SpringSessionFactoryTestSupport.java
Java
apache-2.0
4,756
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v8/services/ad_group_ad_label_service.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Holder for reflection information generated from google/ads/googleads/v8/services/ad_group_ad_label_service.proto</summary> public static partial class AdGroupAdLabelServiceReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v8/services/ad_group_ad_label_service.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AdGroupAdLabelServiceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CkBnb29nbGUvYWRzL2dvb2dsZWFkcy92OC9zZXJ2aWNlcy9hZF9ncm91cF9h", "ZF9sYWJlbF9zZXJ2aWNlLnByb3RvEiBnb29nbGUuYWRzLmdvb2dsZWFkcy52", "OC5zZXJ2aWNlcxo5Z29vZ2xlL2Fkcy9nb29nbGVhZHMvdjgvcmVzb3VyY2Vz", "L2FkX2dyb3VwX2FkX2xhYmVsLnByb3RvGhxnb29nbGUvYXBpL2Fubm90YXRp", "b25zLnByb3RvGhdnb29nbGUvYXBpL2NsaWVudC5wcm90bxofZ29vZ2xlL2Fw", "aS9maWVsZF9iZWhhdmlvci5wcm90bxoZZ29vZ2xlL2FwaS9yZXNvdXJjZS5w", "cm90bxoXZ29vZ2xlL3JwYy9zdGF0dXMucHJvdG8iYgoYR2V0QWRHcm91cEFk", "TGFiZWxSZXF1ZXN0EkYKDXJlc291cmNlX25hbWUYASABKAlCL+BBAvpBKQon", "Z29vZ2xlYWRzLmdvb2dsZWFwaXMuY29tL0FkR3JvdXBBZExhYmVsIrwBChxN", "dXRhdGVBZEdyb3VwQWRMYWJlbHNSZXF1ZXN0EhgKC2N1c3RvbWVyX2lkGAEg", "ASgJQgPgQQISUgoKb3BlcmF0aW9ucxgCIAMoCzI5Lmdvb2dsZS5hZHMuZ29v", "Z2xlYWRzLnY4LnNlcnZpY2VzLkFkR3JvdXBBZExhYmVsT3BlcmF0aW9uQgPg", "QQISFwoPcGFydGlhbF9mYWlsdXJlGAMgASgIEhUKDXZhbGlkYXRlX29ubHkY", "BCABKAgifQoXQWRHcm91cEFkTGFiZWxPcGVyYXRpb24SQwoGY3JlYXRlGAEg", "ASgLMjEuZ29vZ2xlLmFkcy5nb29nbGVhZHMudjgucmVzb3VyY2VzLkFkR3Jv", "dXBBZExhYmVsSAASEAoGcmVtb3ZlGAIgASgJSABCCwoJb3BlcmF0aW9uIqEB", "Ch1NdXRhdGVBZEdyb3VwQWRMYWJlbHNSZXNwb25zZRIxChVwYXJ0aWFsX2Zh", "aWx1cmVfZXJyb3IYAyABKAsyEi5nb29nbGUucnBjLlN0YXR1cxJNCgdyZXN1", "bHRzGAIgAygLMjwuZ29vZ2xlLmFkcy5nb29nbGVhZHMudjguc2VydmljZXMu", "TXV0YXRlQWRHcm91cEFkTGFiZWxSZXN1bHQiMwoaTXV0YXRlQWRHcm91cEFk", "TGFiZWxSZXN1bHQSFQoNcmVzb3VyY2VfbmFtZRgBIAEoCTKjBAoVQWRHcm91", "cEFkTGFiZWxTZXJ2aWNlEs0BChFHZXRBZEdyb3VwQWRMYWJlbBI6Lmdvb2ds", "ZS5hZHMuZ29vZ2xlYWRzLnY4LnNlcnZpY2VzLkdldEFkR3JvdXBBZExhYmVs", "UmVxdWVzdBoxLmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY4LnJlc291cmNlcy5B", "ZEdyb3VwQWRMYWJlbCJJgtPkkwIzEjEvdjgve3Jlc291cmNlX25hbWU9Y3Vz", "dG9tZXJzLyovYWRHcm91cEFkTGFiZWxzLyp92kENcmVzb3VyY2VfbmFtZRLy", "AQoVTXV0YXRlQWRHcm91cEFkTGFiZWxzEj4uZ29vZ2xlLmFkcy5nb29nbGVh", "ZHMudjguc2VydmljZXMuTXV0YXRlQWRHcm91cEFkTGFiZWxzUmVxdWVzdBo/", "Lmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY4LnNlcnZpY2VzLk11dGF0ZUFkR3Jv", "dXBBZExhYmVsc1Jlc3BvbnNlIliC0+STAjkiNC92OC9jdXN0b21lcnMve2N1", "c3RvbWVyX2lkPSp9L2FkR3JvdXBBZExhYmVsczptdXRhdGU6ASraQRZjdXN0", "b21lcl9pZCxvcGVyYXRpb25zGkXKQRhnb29nbGVhZHMuZ29vZ2xlYXBpcy5j", "b23SQSdodHRwczovL3d3dy5nb29nbGVhcGlzLmNvbS9hdXRoL2Fkd29yZHNC", "gQIKJGNvbS5nb29nbGUuYWRzLmdvb2dsZWFkcy52OC5zZXJ2aWNlc0IaQWRH", "cm91cEFkTGFiZWxTZXJ2aWNlUHJvdG9QAVpIZ29vZ2xlLmdvbGFuZy5vcmcv", "Z2VucHJvdG8vZ29vZ2xlYXBpcy9hZHMvZ29vZ2xlYWRzL3Y4L3NlcnZpY2Vz", "O3NlcnZpY2VzogIDR0FBqgIgR29vZ2xlLkFkcy5Hb29nbGVBZHMuVjguU2Vy", "dmljZXPKAiBHb29nbGVcQWRzXEdvb2dsZUFkc1xWOFxTZXJ2aWNlc+oCJEdv", "b2dsZTo6QWRzOjpHb29nbGVBZHM6OlY4OjpTZXJ2aWNlc2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Ads.GoogleAds.V8.Resources.AdGroupAdLabelReflection.Descriptor, global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Api.ClientReflection.Descriptor, global::Google.Api.FieldBehaviorReflection.Descriptor, global::Google.Api.ResourceReflection.Descriptor, global::Google.Rpc.StatusReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V8.Services.GetAdGroupAdLabelRequest), global::Google.Ads.GoogleAds.V8.Services.GetAdGroupAdLabelRequest.Parser, new[]{ "ResourceName" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupAdLabelsRequest), global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupAdLabelsRequest.Parser, new[]{ "CustomerId", "Operations", "PartialFailure", "ValidateOnly" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V8.Services.AdGroupAdLabelOperation), global::Google.Ads.GoogleAds.V8.Services.AdGroupAdLabelOperation.Parser, new[]{ "Create", "Remove" }, new[]{ "Operation" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupAdLabelsResponse), global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupAdLabelsResponse.Parser, new[]{ "PartialFailureError", "Results" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupAdLabelResult), global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupAdLabelResult.Parser, new[]{ "ResourceName" }, null, null, null, null) })); } #endregion } #region Messages /// <summary> /// Request message for [AdGroupAdLabelService.GetAdGroupAdLabel][google.ads.googleads.v8.services.AdGroupAdLabelService.GetAdGroupAdLabel]. /// </summary> public sealed partial class GetAdGroupAdLabelRequest : pb::IMessage<GetAdGroupAdLabelRequest> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<GetAdGroupAdLabelRequest> _parser = new pb::MessageParser<GetAdGroupAdLabelRequest>(() => new GetAdGroupAdLabelRequest()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<GetAdGroupAdLabelRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V8.Services.AdGroupAdLabelServiceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public GetAdGroupAdLabelRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public GetAdGroupAdLabelRequest(GetAdGroupAdLabelRequest other) : this() { resourceName_ = other.resourceName_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public GetAdGroupAdLabelRequest Clone() { return new GetAdGroupAdLabelRequest(this); } /// <summary>Field number for the "resource_name" field.</summary> public const int ResourceNameFieldNumber = 1; private string resourceName_ = ""; /// <summary> /// Required. The resource name of the ad group ad label to fetch. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string ResourceName { get { return resourceName_; } set { resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as GetAdGroupAdLabelRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(GetAdGroupAdLabelRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ResourceName != other.ResourceName) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (ResourceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(GetAdGroupAdLabelRequest other) { if (other == null) { return; } if (other.ResourceName.Length != 0) { ResourceName = other.ResourceName; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { ResourceName = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { ResourceName = input.ReadString(); break; } } } } #endif } /// <summary> /// Request message for [AdGroupAdLabelService.MutateAdGroupAdLabels][google.ads.googleads.v8.services.AdGroupAdLabelService.MutateAdGroupAdLabels]. /// </summary> public sealed partial class MutateAdGroupAdLabelsRequest : pb::IMessage<MutateAdGroupAdLabelsRequest> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<MutateAdGroupAdLabelsRequest> _parser = new pb::MessageParser<MutateAdGroupAdLabelsRequest>(() => new MutateAdGroupAdLabelsRequest()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<MutateAdGroupAdLabelsRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V8.Services.AdGroupAdLabelServiceReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public MutateAdGroupAdLabelsRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public MutateAdGroupAdLabelsRequest(MutateAdGroupAdLabelsRequest other) : this() { customerId_ = other.customerId_; operations_ = other.operations_.Clone(); partialFailure_ = other.partialFailure_; validateOnly_ = other.validateOnly_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public MutateAdGroupAdLabelsRequest Clone() { return new MutateAdGroupAdLabelsRequest(this); } /// <summary>Field number for the "customer_id" field.</summary> public const int CustomerIdFieldNumber = 1; private string customerId_ = ""; /// <summary> /// Required. ID of the customer whose ad group ad labels are being modified. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string CustomerId { get { return customerId_; } set { customerId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "operations" field.</summary> public const int OperationsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Ads.GoogleAds.V8.Services.AdGroupAdLabelOperation> _repeated_operations_codec = pb::FieldCodec.ForMessage(18, global::Google.Ads.GoogleAds.V8.Services.AdGroupAdLabelOperation.Parser); private readonly pbc::RepeatedField<global::Google.Ads.GoogleAds.V8.Services.AdGroupAdLabelOperation> operations_ = new pbc::RepeatedField<global::Google.Ads.GoogleAds.V8.Services.AdGroupAdLabelOperation>(); /// <summary> /// Required. The list of operations to perform on ad group ad labels. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Ads.GoogleAds.V8.Services.AdGroupAdLabelOperation> Operations { get { return operations_; } } /// <summary>Field number for the "partial_failure" field.</summary> public const int PartialFailureFieldNumber = 3; private bool partialFailure_; /// <summary> /// If true, successful operations will be carried out and invalid /// operations will return errors. If false, all operations will be carried /// out in one transaction if and only if they are all valid. /// Default is false. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool PartialFailure { get { return partialFailure_; } set { partialFailure_ = value; } } /// <summary>Field number for the "validate_only" field.</summary> public const int ValidateOnlyFieldNumber = 4; private bool validateOnly_; /// <summary> /// If true, the request is validated but not executed. Only errors are /// returned, not results. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool ValidateOnly { get { return validateOnly_; } set { validateOnly_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as MutateAdGroupAdLabelsRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(MutateAdGroupAdLabelsRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (CustomerId != other.CustomerId) return false; if(!operations_.Equals(other.operations_)) return false; if (PartialFailure != other.PartialFailure) return false; if (ValidateOnly != other.ValidateOnly) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (CustomerId.Length != 0) hash ^= CustomerId.GetHashCode(); hash ^= operations_.GetHashCode(); if (PartialFailure != false) hash ^= PartialFailure.GetHashCode(); if (ValidateOnly != false) hash ^= ValidateOnly.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (CustomerId.Length != 0) { output.WriteRawTag(10); output.WriteString(CustomerId); } operations_.WriteTo(output, _repeated_operations_codec); if (PartialFailure != false) { output.WriteRawTag(24); output.WriteBool(PartialFailure); } if (ValidateOnly != false) { output.WriteRawTag(32); output.WriteBool(ValidateOnly); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (CustomerId.Length != 0) { output.WriteRawTag(10); output.WriteString(CustomerId); } operations_.WriteTo(ref output, _repeated_operations_codec); if (PartialFailure != false) { output.WriteRawTag(24); output.WriteBool(PartialFailure); } if (ValidateOnly != false) { output.WriteRawTag(32); output.WriteBool(ValidateOnly); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (CustomerId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(CustomerId); } size += operations_.CalculateSize(_repeated_operations_codec); if (PartialFailure != false) { size += 1 + 1; } if (ValidateOnly != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(MutateAdGroupAdLabelsRequest other) { if (other == null) { return; } if (other.CustomerId.Length != 0) { CustomerId = other.CustomerId; } operations_.Add(other.operations_); if (other.PartialFailure != false) { PartialFailure = other.PartialFailure; } if (other.ValidateOnly != false) { ValidateOnly = other.ValidateOnly; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { CustomerId = input.ReadString(); break; } case 18: { operations_.AddEntriesFrom(input, _repeated_operations_codec); break; } case 24: { PartialFailure = input.ReadBool(); break; } case 32: { ValidateOnly = input.ReadBool(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { CustomerId = input.ReadString(); break; } case 18: { operations_.AddEntriesFrom(ref input, _repeated_operations_codec); break; } case 24: { PartialFailure = input.ReadBool(); break; } case 32: { ValidateOnly = input.ReadBool(); break; } } } } #endif } /// <summary> /// A single operation (create, remove) on an ad group ad label. /// </summary> public sealed partial class AdGroupAdLabelOperation : pb::IMessage<AdGroupAdLabelOperation> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<AdGroupAdLabelOperation> _parser = new pb::MessageParser<AdGroupAdLabelOperation>(() => new AdGroupAdLabelOperation()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<AdGroupAdLabelOperation> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V8.Services.AdGroupAdLabelServiceReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AdGroupAdLabelOperation() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AdGroupAdLabelOperation(AdGroupAdLabelOperation other) : this() { switch (other.OperationCase) { case OperationOneofCase.Create: Create = other.Create.Clone(); break; case OperationOneofCase.Remove: Remove = other.Remove; break; } _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AdGroupAdLabelOperation Clone() { return new AdGroupAdLabelOperation(this); } /// <summary>Field number for the "create" field.</summary> public const int CreateFieldNumber = 1; /// <summary> /// Create operation: No resource name is expected for the new ad group ad /// label. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Ads.GoogleAds.V8.Resources.AdGroupAdLabel Create { get { return operationCase_ == OperationOneofCase.Create ? (global::Google.Ads.GoogleAds.V8.Resources.AdGroupAdLabel) operation_ : null; } set { operation_ = value; operationCase_ = value == null ? OperationOneofCase.None : OperationOneofCase.Create; } } /// <summary>Field number for the "remove" field.</summary> public const int RemoveFieldNumber = 2; /// <summary> /// Remove operation: A resource name for the ad group ad label /// being removed, in this format: /// /// `customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id} /// _{label_id}` /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Remove { get { return operationCase_ == OperationOneofCase.Remove ? (string) operation_ : ""; } set { operation_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); operationCase_ = OperationOneofCase.Remove; } } private object operation_; /// <summary>Enum of possible cases for the "operation" oneof.</summary> public enum OperationOneofCase { None = 0, Create = 1, Remove = 2, } private OperationOneofCase operationCase_ = OperationOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public OperationOneofCase OperationCase { get { return operationCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearOperation() { operationCase_ = OperationOneofCase.None; operation_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as AdGroupAdLabelOperation); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(AdGroupAdLabelOperation other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Create, other.Create)) return false; if (Remove != other.Remove) return false; if (OperationCase != other.OperationCase) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (operationCase_ == OperationOneofCase.Create) hash ^= Create.GetHashCode(); if (operationCase_ == OperationOneofCase.Remove) hash ^= Remove.GetHashCode(); hash ^= (int) operationCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (operationCase_ == OperationOneofCase.Create) { output.WriteRawTag(10); output.WriteMessage(Create); } if (operationCase_ == OperationOneofCase.Remove) { output.WriteRawTag(18); output.WriteString(Remove); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (operationCase_ == OperationOneofCase.Create) { output.WriteRawTag(10); output.WriteMessage(Create); } if (operationCase_ == OperationOneofCase.Remove) { output.WriteRawTag(18); output.WriteString(Remove); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (operationCase_ == OperationOneofCase.Create) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Create); } if (operationCase_ == OperationOneofCase.Remove) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Remove); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(AdGroupAdLabelOperation other) { if (other == null) { return; } switch (other.OperationCase) { case OperationOneofCase.Create: if (Create == null) { Create = new global::Google.Ads.GoogleAds.V8.Resources.AdGroupAdLabel(); } Create.MergeFrom(other.Create); break; case OperationOneofCase.Remove: Remove = other.Remove; break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { global::Google.Ads.GoogleAds.V8.Resources.AdGroupAdLabel subBuilder = new global::Google.Ads.GoogleAds.V8.Resources.AdGroupAdLabel(); if (operationCase_ == OperationOneofCase.Create) { subBuilder.MergeFrom(Create); } input.ReadMessage(subBuilder); Create = subBuilder; break; } case 18: { Remove = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { global::Google.Ads.GoogleAds.V8.Resources.AdGroupAdLabel subBuilder = new global::Google.Ads.GoogleAds.V8.Resources.AdGroupAdLabel(); if (operationCase_ == OperationOneofCase.Create) { subBuilder.MergeFrom(Create); } input.ReadMessage(subBuilder); Create = subBuilder; break; } case 18: { Remove = input.ReadString(); break; } } } } #endif } /// <summary> /// Response message for an ad group ad labels mutate. /// </summary> public sealed partial class MutateAdGroupAdLabelsResponse : pb::IMessage<MutateAdGroupAdLabelsResponse> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<MutateAdGroupAdLabelsResponse> _parser = new pb::MessageParser<MutateAdGroupAdLabelsResponse>(() => new MutateAdGroupAdLabelsResponse()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<MutateAdGroupAdLabelsResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V8.Services.AdGroupAdLabelServiceReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public MutateAdGroupAdLabelsResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public MutateAdGroupAdLabelsResponse(MutateAdGroupAdLabelsResponse other) : this() { partialFailureError_ = other.partialFailureError_ != null ? other.partialFailureError_.Clone() : null; results_ = other.results_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public MutateAdGroupAdLabelsResponse Clone() { return new MutateAdGroupAdLabelsResponse(this); } /// <summary>Field number for the "partial_failure_error" field.</summary> public const int PartialFailureErrorFieldNumber = 3; private global::Google.Rpc.Status partialFailureError_; /// <summary> /// Errors that pertain to operation failures in the partial failure mode. /// Returned only when partial_failure = true and all errors occur inside the /// operations. If any errors occur outside the operations (e.g. auth errors), /// we return an RPC level error. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Rpc.Status PartialFailureError { get { return partialFailureError_; } set { partialFailureError_ = value; } } /// <summary>Field number for the "results" field.</summary> public const int ResultsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupAdLabelResult> _repeated_results_codec = pb::FieldCodec.ForMessage(18, global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupAdLabelResult.Parser); private readonly pbc::RepeatedField<global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupAdLabelResult> results_ = new pbc::RepeatedField<global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupAdLabelResult>(); /// <summary> /// All results for the mutate. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupAdLabelResult> Results { get { return results_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as MutateAdGroupAdLabelsResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(MutateAdGroupAdLabelsResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(PartialFailureError, other.PartialFailureError)) return false; if(!results_.Equals(other.results_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (partialFailureError_ != null) hash ^= PartialFailureError.GetHashCode(); hash ^= results_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else results_.WriteTo(output, _repeated_results_codec); if (partialFailureError_ != null) { output.WriteRawTag(26); output.WriteMessage(PartialFailureError); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { results_.WriteTo(ref output, _repeated_results_codec); if (partialFailureError_ != null) { output.WriteRawTag(26); output.WriteMessage(PartialFailureError); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (partialFailureError_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(PartialFailureError); } size += results_.CalculateSize(_repeated_results_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(MutateAdGroupAdLabelsResponse other) { if (other == null) { return; } if (other.partialFailureError_ != null) { if (partialFailureError_ == null) { PartialFailureError = new global::Google.Rpc.Status(); } PartialFailureError.MergeFrom(other.PartialFailureError); } results_.Add(other.results_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 18: { results_.AddEntriesFrom(input, _repeated_results_codec); break; } case 26: { if (partialFailureError_ == null) { PartialFailureError = new global::Google.Rpc.Status(); } input.ReadMessage(PartialFailureError); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 18: { results_.AddEntriesFrom(ref input, _repeated_results_codec); break; } case 26: { if (partialFailureError_ == null) { PartialFailureError = new global::Google.Rpc.Status(); } input.ReadMessage(PartialFailureError); break; } } } } #endif } /// <summary> /// The result for an ad group ad label mutate. /// </summary> public sealed partial class MutateAdGroupAdLabelResult : pb::IMessage<MutateAdGroupAdLabelResult> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<MutateAdGroupAdLabelResult> _parser = new pb::MessageParser<MutateAdGroupAdLabelResult>(() => new MutateAdGroupAdLabelResult()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<MutateAdGroupAdLabelResult> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V8.Services.AdGroupAdLabelServiceReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public MutateAdGroupAdLabelResult() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public MutateAdGroupAdLabelResult(MutateAdGroupAdLabelResult other) : this() { resourceName_ = other.resourceName_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public MutateAdGroupAdLabelResult Clone() { return new MutateAdGroupAdLabelResult(this); } /// <summary>Field number for the "resource_name" field.</summary> public const int ResourceNameFieldNumber = 1; private string resourceName_ = ""; /// <summary> /// Returned for successful operations. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string ResourceName { get { return resourceName_; } set { resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as MutateAdGroupAdLabelResult); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(MutateAdGroupAdLabelResult other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ResourceName != other.ResourceName) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (ResourceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(MutateAdGroupAdLabelResult other) { if (other == null) { return; } if (other.ResourceName.Length != 0) { ResourceName = other.ResourceName; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { ResourceName = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { ResourceName = input.ReadString(); break; } } } } #endif } #endregion } #endregion Designer generated code
googleads/google-ads-dotnet
src/V8/Services/AdGroupAdLabelService.g.cs
C#
apache-2.0
51,766
/* * Copyright 2021 HM Revenue & Customs * * 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 uk.gov.hmrc.ct.computations.calculations import org.scalatest.{Matchers, WordSpec} import uk.gov.hmrc.ct.CATO01 import uk.gov.hmrc.ct.computations.{CP118, CP997, CP998, CPQ19} class LossesSetAgainstOtherProfitsCalculatorSpec extends WordSpec with Matchers { "Losses Set Against Other Profits Calculator" should { "return CP118 when CP118 is less than CATO01 and CP118 is positive" in new LossesSetAgainstOtherProfitsCalculator { calculateLossesSetAgainstProfits(cato01 = CATO01(10), cp997 = CP997(None), cp118 = CP118(9), cpq19 = CPQ19(Some(true))) shouldBe CP998(Some(9)) } "return CATO01 when CATO01 is less CP118, CP997 is None and CP118 is positive" in new LossesSetAgainstOtherProfitsCalculator { calculateLossesSetAgainstProfits(cato01 = CATO01(10), cp997 = CP997(None), cp118 = CP118(19), cpq19 = CPQ19(Some(true))) shouldBe CP998(Some(10)) } "return CATO01 when CATO01 is less CP118, CP997 is 0 and CP118 is positive" in new LossesSetAgainstOtherProfitsCalculator { calculateLossesSetAgainstProfits(cato01 = CATO01(10), cp997 = CP997(Some(0)), cp118 = CP118(19), cpq19 = CPQ19(Some(true))) shouldBe CP998(Some(10)) } "return CATO01 minus CP997 when CATO01 is less CP118, CP997 is positive and CP118 is positive" in new LossesSetAgainstOtherProfitsCalculator { calculateLossesSetAgainstProfits(cato01 = CATO01(10), cp997 = CP997(Some(1)), cp118 = CP118(19), cpq19 = CPQ19(Some(true))) shouldBe CP998(Some(9)) } "return CATO01 when CATO01 equals absolute CP118 and CP118 is positive" in new LossesSetAgainstOtherProfitsCalculator { calculateLossesSetAgainstProfits(cato01 = CATO01(10), cp997 = CP997(None), cp118 = CP118(10), cpq19 = CPQ19(Some(true))) shouldBe CP998(Some(10)) } "return None when CPQ19 is None" in new LossesSetAgainstOtherProfitsCalculator { calculateLossesSetAgainstProfits(cato01 = CATO01(10), cp997 = CP997(None), cp118 = CP118(10), cpq19 = CPQ19(None)) shouldBe CP998(None) } "return None when CPQ19 is false" in new LossesSetAgainstOtherProfitsCalculator { calculateLossesSetAgainstProfits(cato01 = CATO01(10), cp997 = CP997(None), cp118 = CP118(10), cpq19 = CPQ19(Some(false))) shouldBe CP998(None) } } }
hmrc/ct-calculations
src/test/scala/uk/gov/hmrc/ct/computations/calculations/LossesSetAgainstOtherProfitsCalculatorSpec.scala
Scala
apache-2.0
2,854
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="zh"> <head> <!-- Generated by javadoc (1.8.0_151) on Sat Jan 27 21:26:54 CST 2018 --> <title>DefaultMessageCallbackHandler</title> <meta name="date" content="2018-01-27"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="DefaultMessageCallbackHandler"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../../../../org/dsngroup/broke/client/handler/callback/IMessageCallbackHandler.html" title="interface in org.dsngroup.broke.client.handler.callback"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/dsngroup/broke/client/handler/callback/DefaultMessageCallbackHandler.html" target="_top">Frames</a></li> <li><a href="DefaultMessageCallbackHandler.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.dsngroup.broke.client.handler.callback</div> <h2 title="Class DefaultMessageCallbackHandler" class="title">Class DefaultMessageCallbackHandler</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.dsngroup.broke.client.handler.callback.DefaultMessageCallbackHandler</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd><a href="../../../../../../org/dsngroup/broke/client/handler/callback/IMessageCallbackHandler.html" title="interface in org.dsngroup.broke.client.handler.callback">IMessageCallbackHandler</a></dd> </dl> <hr> <br> <pre>public class <span class="typeNameLabel">DefaultMessageCallbackHandler</span> extends java.lang.Object implements <a href="../../../../../../org/dsngroup/broke/client/handler/callback/IMessageCallbackHandler.html" title="interface in org.dsngroup.broke.client.handler.callback">IMessageCallbackHandler</a></pre> <div class="block">Default message callback handler. Default behaviors of messageArrive() and connectionLost().</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>private static org.slf4j.Logger</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/dsngroup/broke/client/handler/callback/DefaultMessageCallbackHandler.html#logger">logger</a></span></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/dsngroup/broke/client/handler/callback/DefaultMessageCallbackHandler.html#DefaultMessageCallbackHandler--">DefaultMessageCallbackHandler</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/dsngroup/broke/client/handler/callback/DefaultMessageCallbackHandler.html#connectionLost-java.lang.Throwable-">connectionLost</a></span>(java.lang.Throwable&nbsp;cause)</code> <div class="block">Log the connection lost error message.</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/dsngroup/broke/client/handler/callback/DefaultMessageCallbackHandler.html#messageArrive-io.netty.buffer.ByteBuf-">messageArrive</a></span>(io.netty.buffer.ByteBuf&nbsp;payload)</code> <div class="block">Print the publish message.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="logger"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>logger</h4> <pre>private static final&nbsp;org.slf4j.Logger logger</pre> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="DefaultMessageCallbackHandler--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>DefaultMessageCallbackHandler</h4> <pre>public&nbsp;DefaultMessageCallbackHandler()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="messageArrive-io.netty.buffer.ByteBuf-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>messageArrive</h4> <pre>public&nbsp;void&nbsp;messageArrive(io.netty.buffer.ByteBuf&nbsp;payload)</pre> <div class="block">Print the publish message.</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../../../../../org/dsngroup/broke/client/handler/callback/IMessageCallbackHandler.html#messageArrive-io.netty.buffer.ByteBuf-">messageArrive</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../../../org/dsngroup/broke/client/handler/callback/IMessageCallbackHandler.html" title="interface in org.dsngroup.broke.client.handler.callback">IMessageCallbackHandler</a></code></dd> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>payload</code> - The payload of the incoming publish message.</dd> </dl> </li> </ul> <a name="connectionLost-java.lang.Throwable-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>connectionLost</h4> <pre>public&nbsp;void&nbsp;connectionLost(java.lang.Throwable&nbsp;cause)</pre> <div class="block">Log the connection lost error message.</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../../../../../org/dsngroup/broke/client/handler/callback/IMessageCallbackHandler.html#connectionLost-java.lang.Throwable-">connectionLost</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../../../org/dsngroup/broke/client/handler/callback/IMessageCallbackHandler.html" title="interface in org.dsngroup.broke.client.handler.callback">IMessageCallbackHandler</a></code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../../../../org/dsngroup/broke/client/handler/callback/IMessageCallbackHandler.html" title="interface in org.dsngroup.broke.client.handler.callback"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/dsngroup/broke/client/handler/callback/DefaultMessageCallbackHandler.html" target="_top">Frames</a></li> <li><a href="DefaultMessageCallbackHandler.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
dsngroup/broke
docs/javadoc/org/dsngroup/broke/client/handler/callback/DefaultMessageCallbackHandler.html
HTML
apache-2.0
13,200
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =======================================================================*/ // This class has been generated, DO NOT EDIT! package org.tensorflow.op.nn; import java.util.Arrays; import org.tensorflow.GraphOperation; import org.tensorflow.Operand; import org.tensorflow.Operation; import org.tensorflow.OperationBuilder; import org.tensorflow.Output; import org.tensorflow.op.RawOp; import org.tensorflow.op.RawOpInputs; import org.tensorflow.op.Scope; import org.tensorflow.op.annotation.Endpoint; import org.tensorflow.op.annotation.OpInputsMetadata; import org.tensorflow.op.annotation.OpMetadata; import org.tensorflow.proto.framework.DataType; import org.tensorflow.types.family.TNumber; /** * Computes softsign gradients for a softsign operation. * * @param <T> data type for {@code backprops} output */ @OpMetadata( opType = SoftsignGrad.OP_NAME, inputsClass = SoftsignGrad.Inputs.class ) public final class SoftsignGrad<T extends TNumber> extends RawOp implements Operand<T> { /** * The name of this op, as known by TensorFlow core engine */ public static final String OP_NAME = "SoftsignGrad"; private Output<T> backprops; public SoftsignGrad(Operation operation) { super(operation, OP_NAME); int outputIdx = 0; backprops = operation.output(outputIdx++); } /** * Factory method to create a class wrapping a new SoftsignGrad operation. * * @param scope current scope * @param gradients The backpropagated gradients to the corresponding softsign operation. * @param features The features passed as input to the corresponding softsign operation. * @param <T> data type for {@code SoftsignGrad} output and operands * @return a new instance of SoftsignGrad */ @Endpoint( describeByClass = true ) public static <T extends TNumber> SoftsignGrad<T> create(Scope scope, Operand<T> gradients, Operand<T> features) { OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "SoftsignGrad"); opBuilder.addInput(gradients.asOutput()); opBuilder.addInput(features.asOutput()); return new SoftsignGrad<>(opBuilder.build()); } /** * Gets backprops. * The gradients: {@code gradients / (1 + abs(features)) ** 2}. * @return backprops. */ public Output<T> backprops() { return backprops; } @Override public Output<T> asOutput() { return backprops; } @OpInputsMetadata( outputsClass = SoftsignGrad.class ) public static class Inputs<T extends TNumber> extends RawOpInputs<SoftsignGrad<T>> { /** * The backpropagated gradients to the corresponding softsign operation. */ public final Operand<T> gradients; /** * The features passed as input to the corresponding softsign operation. */ public final Operand<T> features; /** * The T attribute */ public final DataType T; public Inputs(GraphOperation op) { super(new SoftsignGrad<>(op), op, Arrays.asList("T")); int inputIndex = 0; gradients = (Operand<T>) op.input(inputIndex++); features = (Operand<T>) op.input(inputIndex++); T = op.attributes().getAttrType("T"); } } }
tensorflow/java
tensorflow-core/tensorflow-core-api/src/gen/java/org/tensorflow/op/nn/SoftsignGrad.java
Java
apache-2.0
3,743
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.nio.channels; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.spi.AbstractInterruptibleChannel; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.attribute.FileAttribute; import java.util.Set; public class FileChannel extends AbstractInterruptibleChannel implements SeekableByteChannel, GatheringByteChannel, ScatteringByteChannel { protected FileChannel() { } native protected void implCloseChannel() throws IOException; native public static FileChannel open(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException; native public static FileChannel open(Path path, OpenOption... options) throws IOException; public native int read(ByteBuffer dst) throws IOException; public native long read(ByteBuffer[] dsts, int offset, int length) throws IOException; public final long read(ByteBuffer[] dsts) throws IOException { return read(dsts, 0, dsts.length); } public native int write(ByteBuffer src) throws IOException; public native long write(ByteBuffer[] srcs, int offset, int length) throws IOException; public final long write(ByteBuffer[] srcs) throws IOException { return write(srcs, 0, srcs.length); } public native long position() throws IOException; public native FileChannel position(long newPosition) throws IOException; public native long size() throws IOException; public native FileChannel truncate(long size) throws IOException; public native void force(boolean metaData) throws IOException; public native long transferTo(long position, long count, WritableByteChannel target) throws IOException; public native long transferFrom(ReadableByteChannel src, long position, long count) throws IOException; public native int read(ByteBuffer dst, long position) throws IOException; public native int write(ByteBuffer src, long position) throws IOException; public static class MapMode { public static final MapMode READ_ONLY = new MapMode("READ_ONLY"); public static final MapMode READ_WRITE = new MapMode("READ_WRITE"); public static final MapMode PRIVATE = new MapMode("PRIVATE"); private final String name; private MapMode(String name) { this.name = name; } public String toString() { return name; } } //public native MappedByteBuffer map(MapMode mode, long position, long size) throws IOException; public native FileLock lock(long position, long size, boolean shared) throws IOException; public final FileLock lock() throws IOException { return lock(0L, Long.MAX_VALUE, false); } public native FileLock tryLock(long position, long size, boolean shared) throws IOException; public final FileLock tryLock() throws IOException { return tryLock(0L, Long.MAX_VALUE, false); } }
jtransc/jtransc
jtransc-rt/src/java/nio/channels/FileChannel.java
Java
apache-2.0
3,632
public class Foo { { <caret> x = 3; } }
joewalnes/idea-community
java/java-tests/testData/codeInsight/completeStatement/BeforeStatement_after.java
Java
apache-2.0
63
/* * Copyright (c) 2014 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.werval.util; import java.util.HashMap; import java.util.Map; import java.util.SortedMap; import org.junit.Test; import static io.werval.util.Maps.fromMap; import static io.werval.util.Maps.newConcurrentHashMap; import static io.werval.util.Maps.newConcurrentSkipListMap; import static io.werval.util.Maps.newHashMap; import static io.werval.util.Maps.newIdentityHashMap; import static io.werval.util.Maps.newLinkedHashMap; import static io.werval.util.Maps.newLinkedMultiValueMap; import static io.werval.util.Maps.newTreeMap; import static io.werval.util.Maps.newWeakHashMap; import static io.werval.util.Maps.unmodifiableMultiValueMap; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; /** * Maps Utilities Test. */ public class MapsTest { @Test public void mapBuilder() { Map<String, String> map = fromMap( new HashMap<String, String>() ) .put( "foo", "bar" ) .put( "bazar", "cathedral" ) .toMap(); assertThat( map.size(), is( 2 ) ); assertThat( map.get( "foo" ), equalTo( "bar" ) ); assertThat( map.get( "bazar" ), equalTo( "cathedral" ) ); } @Test public void multiValueMapBuilder() { MultiValueMap<String, String> map = fromMap( new LinkedMultiValueMap<String, String>() ) .add( "foo", "bar" ) .add( "nil", "null", "undefined" ) .toMap(); assertThat( map.size(), is( 2 ) ); assertThat( map.getFirst( "nil" ), equalTo( "null" ) ); assertThat( map.getLast( "nil" ), equalTo( "undefined" ) ); assertThat( map.getSingle( "foo" ), equalTo( "bar" ) ); } @Test public void mapBuilderUsages() { Map<String, String> hMap = newHashMap( String.class, String.class ) .put( "foo", "bar" ) .toMap(); Map<String, String> lhMap = newLinkedHashMap( String.class, String.class ) .put( "foo", "bar" ) .toMap(); SortedMap<String, String> tMap = newTreeMap( String.class, String.class ) .put( "foo", "bar" ) .toMap(); SortedMap<String, String> tMapC = newTreeMap( String.class, String.class, (left, right) -> left.compareTo( right ) ) .put( "foo", "bar" ) .toMap(); Map<String, String> ihMap = newIdentityHashMap( String.class, String.class ) .put( "foo", "bar" ) .toMap(); Map<String, String> whMap = newWeakHashMap( String.class, String.class ) .put( "foo", "bar" ) .toMap(); Map<String, String> chMap = newConcurrentHashMap( String.class, String.class ) .put( "foo", "bar" ) .toMap(); SortedMap<String, String> cslMap = newConcurrentSkipListMap( String.class, String.class ) .put( "foo", "bar" ) .toMap(); SortedMap<String, String> cslMapC = newConcurrentSkipListMap( String.class, String.class, (left, right) -> left.compareTo( right ) ) .put( "foo", "bar" ) .toMap(); MultiValueMap<String, String> lmvMap = newLinkedMultiValueMap( String.class, String.class ) .add( "foo", "bar" ) .toMap(); } @Test public void unmodifiableMVMap() { MultiValueMap<String, String> mvmap = newLinkedMultiValueMap( String.class, String.class ) .add( "foo", "bar", "bazar" ) .toMap(); MultiValueMap<String, String> unmodifiable = unmodifiableMultiValueMap( mvmap ); try { unmodifiable.keySet().remove( unmodifiable.keySet().iterator().next() ); fail( "UnmodifiableMultiValueMap is modifiable!" ); } catch( UnsupportedOperationException expected ) { } } }
werval/werval
io.werval/io.werval.api/src/test/java/io/werval/util/MapsTest.java
Java
apache-2.0
4,769
# audiospool The <a href="http://epeus.blogspot.com/2003/10/bloggercon-live-video.html">original podcast downloading script</a>, when they were still called audioblogs. This downloads a feed and puts the audio files into a playlist in iTunes, for you to sync with your iPod. You'll need a copy of <a href="https://github.com/kevinmarks/feedparser">feedparser</a> in the same folder, but this does still work, as Chris Lydon's feed is still up. Mind you, I haven't synced an iPod with iTunes in years
kevinmarks/audiospool
README.md
Markdown
apache-2.0
503
/** * Copyright (C) 2014 Next Generation Mobile Service JSC., (NMS). All rights * reserved. */ package com.nms.vnm.eip.web.util; import com.nms.vnm.eip.exception.AppException; import java.util.Iterator; import java.util.List; import java.util.function.Consumer; import javax.ejb.EJBException; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.component.UISelectItem; import javax.faces.component.UISelectItems; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.model.SelectItem; /** * JsfUtil functionalitis. * * @author Nguyen Trong Cuong (cuongnt1987@gmail.com) * @since 08/26/2014 * @version 1.0 */ public class JsfUtil { /** * Build array selectItem form list of object * * @param entities * @param selectOne * @return */ public static SelectItem[] getSelectItems(List<?> entities, boolean selectOne) { int size = selectOne ? entities.size() + 1 : entities.size(); SelectItem[] selectItems = new SelectItem[size]; int i = 0; // Insert null value if select one. if (selectOne) { selectItems[0] = new SelectItem("", "---"); i++; } for (Object x : entities) { selectItems[i++] = new SelectItem(x, x.toString()); } return selectItems; } /** * Check a list component with item has label is 'value' is dummy? * * @param component * @param value dummy label * @return */ public static boolean isDummySelectItem(UIComponent component, String value) { for (UIComponent children : component.getChildren()) { /* First check if children is UISelectItem */ if (children instanceof UISelectItem) { UISelectItem item = (UISelectItem) children; if (item.getItemValue() == null && item.getItemLabel().equals(value)) { return true; } break; /* Second check is children is UISelectItems */ } else if (children instanceof UISelectItems) { UISelectItems items = (UISelectItems) children; Object itemsObject = items.getValue(); if (itemsObject instanceof SelectItem[]) { SelectItem[] itemSi = (SelectItem[]) itemsObject; for (SelectItem si : itemSi) { if (si.getValue() == null && si.getLabel().equals(value)) { return true; } break; } } } } return false; } public static String getRequestParameter(String key) { return FacesContext.getCurrentInstance() .getExternalContext().getRequestParameterMap().get(key); } public static Object getObjectFromRequestParameter(String requestParameter, Converter converter, UIComponent component) { String theId = getRequestParameter(requestParameter); return converter.getAsObject(FacesContext.getCurrentInstance(), component, theId); } public static Throwable getRootCause(Throwable cause) { if (cause != null) { Throwable source = cause.getCause(); if (source != null) { return getRootCause(source); } else { return cause; } } return null; } public static void addErrorMessage(Exception ex, String defaultMsg) { String msg = ex.getLocalizedMessage(); if (msg != null && msg.length() > 0) { addErrorMessage(msg); } else { addErrorMessage(defaultMsg); } } public static void addErrorMessages(List<String> messages) { messages.stream().forEach((message) -> { addErrorMessage(message); }); } /** * Process action on * * @param <T> * @param consumer * @param t * @param successMessage * @param errorMessage */ public static <T> void processAction(Consumer<T> consumer, T t, String successMessage, String errorMessage) { try { consumer.accept(t); MessageUtil.addGlobalInfoMessage(successMessage); } catch (Exception e) { handleException(e, errorMessage); } } public static void addErrorMessage(String msg) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg); FacesContext.getCurrentInstance().addMessage(null, facesMsg); FacesContext.getCurrentInstance().validationFailed(); // Invalidate JSF page if we raise an error message } public static void addSuccessMessage(String msg) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg); FacesContext.getCurrentInstance().addMessage("successInfo", facesMsg); } public static boolean isValidationFailed() { return FacesContext.getCurrentInstance().isValidationFailed(); } public static String getComponentMessages(String clientComponent, String defaultMessage) { FacesContext fc = FacesContext.getCurrentInstance(); UIComponent component = UIComponent.getCurrentComponent(fc).findComponent(clientComponent); if (component instanceof UIInput) { UIInput inputComponent = (UIInput) component; if (inputComponent.isValid()) { return defaultMessage; } else { Iterator<FacesMessage> iter = fc.getMessages(inputComponent.getClientId()); if (iter.hasNext()) { return iter.next().getDetail(); } } } return ""; } public static void handleException(Exception e, String defaultMessage) { if (e instanceof AppException) { MessageUtil.addGlobalErrorMessage(e); } else { Throwable t = getRootCause(e); if (t instanceof EJBException) { MessageUtil.addGlobalErrorMessage(t); } else { MessageUtil.addGlobalErrorMessage(defaultMessage, t); } } } }
nms-htc/eip-vnm
src/main/java/com/nms/vnm/eip/web/util/JsfUtil.java
Java
apache-2.0
6,580
import React from 'react'; import { Box, Button, CheckBox, FileInput, Form, FormField, Grommet, RadioButtonGroup, RangeInput, Select, TextArea, } from 'grommet'; import { grommet } from 'grommet/themes'; export const FieldWithComponentProp = () => ( <Grommet full theme={grommet}> <Box fill overflow="auto" align="center" justify="center" pad="large"> <Box flex={false} width="medium"> <Form onReset={event => console.log(event)} onSubmit={({ value, touched }) => console.log('Submit', value, touched) } > <FormField label="Name" name="name" required validate={[ { regexp: /^[a-z]/i }, name => { if (name && name.length === 1) return 'must be >1 character'; return undefined; }, name => { if (name && name.length <= 2) return { message: "that's short", status: 'info' }; return undefined; }, ]} /> <FormField label="Email" name="email" type="email" required /> <FormField label="Employee ID" name="employeeId" required validate={{ regexp: /^[0-9]{4,6}$/, message: '4-6 digits' }} /> <FormField name="subscribe" component={CheckBox} label="Subscribe?" /> <FormField name="ampm" component={RadioButtonGroup} options={['morning', 'evening']} /> <FormField label="Size" name="size" component={Select} onChange={event => console.log(event)} options={['small', 'medium', 'large', 'xlarge']} /> <FormField label="Comments" name="comments" component={TextArea} /> <FormField label="Age" name="age" component={RangeInput} pad min={15} max={75} /> <FormField label="File" name="file" component={FileInput} /> <FormField label="Custom" name="custom" component={props => <input {...props} />} /> <Box direction="row" justify="between" margin={{ top: 'medium' }}> <Button label="Cancel" /> <Button type="reset" label="Reset" /> <Button type="submit" label="Update" primary /> </Box> </Form> </Box> </Box> </Grommet> ); FieldWithComponentProp.storyName = 'Field with component prop'; export default { title: 'Input/Form/Field with component prop', };
HewlettPackard/grommet
src/js/components/Form/stories/FieldWithComponentProp.js
JavaScript
apache-2.0
2,735
'use strict'; var DEFAULT_ICON_SIZE = 22; // px var SUPPORTED_TYPES = ['Link', 'Text', 'Widget']; var Annotation = (function AnnotationClosure() { // // 12.5.5: Algorithm: Appearance streams // function getTransformMatrix(rect, bbox, matrix) { // var bounds = Util.getAxialAlignedBoundingBox(bbox, matrix); // var minX = bounds[0]; // var minY = bounds[1]; // var maxX = bounds[2]; // var maxY = bounds[3]; // // if (minX === maxX || minY === maxY) { // // From real-life file, bbox was [0, 0, 0, 0]. In this case, // // just apply the transform for rect // return [1, 0, 0, 1, rect[0], rect[1]]; // } // // var xRatio = (rect[2] - rect[0]) / (maxX - minX); // var yRatio = (rect[3] - rect[1]) / (maxY - minY); // return [ // xRatio, // 0, // 0, // yRatio, // rect[0] - minX * xRatio, // rect[1] - minY * yRatio // ]; // } // // function getDefaultAppearance(dict) { // var appearanceState = dict.get('AP'); // if (!isDict(appearanceState)) { // return; // } // // var appearance; // var appearances = appearanceState.get('N'); // if (isDict(appearances)) { // var as_ = dict.get('AS'); // if (as_ && appearances.has(as_.name)) { // appearance = appearances.get(as_.name); // } // } else { // appearance = appearances; // } // return appearance; // } // // function Annotation(params) { // var dict = params.dict; // var data = this.data = {}; // // data.subtype = dict.get('Subtype').name; // var rect = dict.get('Rect') || [0, 0, 0, 0]; // data.rect = Util.normalizeRect(rect); // data.annotationFlags = dict.get('F'); // // var color = dict.get('C'); // if (!color) { // // The PDF spec does not mention how a missing color array is interpreted. // // Adobe Reader seems to default to black in this case. // data.color = [0, 0, 0]; // } else if (isArray(color)) { // switch (color.length) { // case 0: // // Empty array denotes transparent border. // data.color = null; // break; // case 1: // // TODO: implement DeviceGray // break; // case 3: // data.color = color; // break; // case 4: // // TODO: implement DeviceCMYK // break; // } // } // // this.borderStyle = data.borderStyle = new AnnotationBorderStyle(); // this.setBorderStyle(dict); // // this.appearance = getDefaultAppearance(dict); // data.hasAppearance = !!this.appearance; // data.id = params.ref.num; // } // // Annotation.prototype = { // setBorderStyle: function Annotation_setBorderStyle(borderStyle) { // if (!isDict(borderStyle)) { // return; // } // if (borderStyle.has('BS')) { // var dict = borderStyle.get('BS'); // var dictType; // // if (!dict.has('Type') || (isName(dictType = dict.get('Type')) && // dictType.name === 'Border')) { // this.borderStyle.setWidth(dict.get('W')); // this.borderStyle.setStyle(dict.get('S')); // this.borderStyle.setDashArray(dict.get('D')); // } // } else if (borderStyle.has('Border')) { // var array = borderStyle.get('Border'); // if (isArray(array) && array.length >= 3) { // this.borderStyle.setHorizontalCornerRadius(array[0]); // this.borderStyle.setVerticalCornerRadius(array[1]); // this.borderStyle.setWidth(array[2]); // this.borderStyle.setStyle('S'); // // if (array.length === 4) { // Dash array available // this.borderStyle.setDashArray(array[3]); // } // } // } else { // // There are no border entries in the dictionary. According to the // // specification, we should draw a solid border of width 1 in that // // case, but Adobe Reader did not implement that part of the // // specification and instead draws no border at all, so we do the same. // // See also https://github.com/mozilla/pdf.js/issues/6179. // this.borderStyle.setWidth(0); // } // }, // // getData: function Annotation_getData() { // return this.data; // }, // // isInvisible: function Annotation_isInvisible() { // var data = this.data; // if (data && SUPPORTED_TYPES.indexOf(data.subtype) !== -1) { // return false; // } else { // return !!(data && // data.annotationFlags && // Default: not invisible // data.annotationFlags & 0x1); // Invisible // } // }, // // isViewable: function Annotation_isViewable() { // var data = this.data; // return !!(!this.isInvisible() && // data && // (!data.annotationFlags || // !(data.annotationFlags & 0x22)) && // Hidden or NoView // data.rect); // rectangle is necessary // }, // // isPrintable: function Annotation_isPrintable() { // var data = this.data; // return !!(!this.isInvisible() && // data && // data.annotationFlags && // Default: not printable // data.annotationFlags & 0x4 && // Print // !(data.annotationFlags & 0x2) && // Hidden // data.rect); // rectangle is necessary // }, // // loadResources: function Annotation_loadResources(keys) { // return new Promise(function (resolve, reject) { // this.appearance.dict.getAsync('Resources').then(function (resources) { // if (!resources) { // resolve(); // return; // } // var objectLoader = new ObjectLoader(resources.map, // keys, // resources.xref); // objectLoader.load().then(function() { // resolve(resources); // }, reject); // }, reject); // }.bind(this)); // }, // // getOperatorList: function Annotation_getOperatorList(evaluator) { // // if (!this.appearance) { // return Promise.resolve(new OperatorList()); // } // // var data = this.data; // // var appearanceDict = this.appearance.dict; // var resourcesPromise = this.loadResources([ // 'ExtGState', // 'ColorSpace', // 'Pattern', // 'Shading', // 'XObject', // 'Font' // // ProcSet // // Properties // ]); // var bbox = appearanceDict.get('BBox') || [0, 0, 1, 1]; // var matrix = appearanceDict.get('Matrix') || [1, 0, 0, 1, 0 ,0]; // var transform = getTransformMatrix(data.rect, bbox, matrix); // var self = this; // // return resourcesPromise.then(function(resources) { // var opList = new OperatorList(); // opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]); // return evaluator.getOperatorList(self.appearance, resources, opList). // then(function () { // opList.addOp(OPS.endAnnotation, []); // self.appearance.reset(); // return opList; // }); // }); // } // }; // // Annotation.getConstructor = function Annotation_getConstructor(subtype, fieldType) { // // if (!subtype) { // return; // } // // // TODO(mack): Implement FreeText annotations // if (subtype === 'Link') { // return LinkAnnotation; // } else if (subtype === 'Text') { // return TextAnnotation; // } else if (subtype === 'Widget') { // if (!fieldType) { // return; // } // // if (fieldType === 'Tx') { // return TextWidgetAnnotation; // } else { // return WidgetAnnotation; // } // } else { // return Annotation; // } // }; // // Annotation.fromRef = function Annotation_fromRef(xref, ref) { // // var dict = xref.fetchIfRef(ref); // if (!isDict(dict)) { // return; // } // // var subtype = dict.get('Subtype'); // subtype = isName(subtype) ? subtype.name : ''; // if (!subtype) { // return; // } // // var fieldType = Util.getInheritableProperty(dict, 'FT'); // fieldType = isName(fieldType) ? fieldType.name : ''; // // var Constructor = Annotation.getConstructor(subtype, fieldType); // if (!Constructor) { // return; // } // // var params = { // dict: dict, // ref: ref // }; // // var annotation = new Constructor(params); // // if (annotation.isViewable() || annotation.isPrintable()) { // return annotation; // } else { // if (SUPPORTED_TYPES.indexOf(subtype) === -1) { // warn('unimplemented annotation type: ' + subtype); // } // } // }; // // Annotation.appendToOperatorList = function Annotation_appendToOperatorList( // annotations, opList, pdfManager, partialEvaluator, intent) { // // function reject(e) { // annotationsReadyCapability.reject(e); // } // // var annotationsReadyCapability = createPromiseCapability(); // // var annotationPromises = []; // for (var i = 0, n = annotations.length; i < n; ++i) { // if (intent === 'display' && annotations[i].isViewable() || // intent === 'print' && annotations[i].isPrintable()) { // annotationPromises.push( // annotations[i].getOperatorList(partialEvaluator)); // } // } // Promise.all(annotationPromises).then(function(datas) { // opList.addOp(OPS.beginAnnotations, []); // for (var i = 0, n = datas.length; i < n; ++i) { // var annotOpList = datas[i]; // opList.addOpList(annotOpList); // } // opList.addOp(OPS.endAnnotations, []); // annotationsReadyCapability.resolve(); // }, reject); // // return annotationsReadyCapability.promise; // }; // // return Annotation; //})(); // //var AnnotationBorderStyle = (function AnnotationBorderStyleClosure() { // // function AnnotationBorderStyle() { // this.width = 1; // this.style = AnnotationBorderStyleType.SOLID; // this.dashArray = [3]; // this.horizontalCornerRadius = 0; // this.verticalCornerRadius = 0; // } // // AnnotationBorderStyle.prototype = { // // setWidth: function AnnotationBorderStyle_setWidth(width) { // if (width === (width | 0)) { // this.width = width; // } // }, // // setStyle: function AnnotationBorderStyle_setStyle(style) { // if (!style) { // return; // } // switch (style.name) { // case 'S': // this.style = AnnotationBorderStyleType.SOLID; // break; // // case 'D': // this.style = AnnotationBorderStyleType.DASHED; // break; // // case 'B': // this.style = AnnotationBorderStyleType.BEVELED; // break; // // case 'I': // this.style = AnnotationBorderStyleType.INSET; // break; // // case 'U': // this.style = AnnotationBorderStyleType.UNDERLINE; // break; // // default: // break; // } // }, // // /** // * Set the dash array. // * // * @public // * @memberof AnnotationBorderStyle // * @param {Array} dashArray - The dash array with at least one element // */ // setDashArray: function AnnotationBorderStyle_setDashArray(dashArray) { // // We validate the dash array, but we do not use it because CSS does not // // allow us to change spacing of dashes. For more information, visit // // http://www.w3.org/TR/css3-background/#the-border-style. // if (isArray(dashArray) && dashArray.length > 0) { // // According to the PDF specification: the elements in a dashArray // // shall be numbers that are nonnegative and not all equal to zero. // var isValid = true; // var allZeros = true; // for (var i = 0, len = dashArray.length; i < len; i++) { // var element = dashArray[i]; // var validNumber = (+element >= 0); // if (!validNumber) { // isValid = false; // break; // } else if (element > 0) { // allZeros = false; // } // } // if (isValid && !allZeros) { // this.dashArray = dashArray; // } else { // this.width = 0; // Adobe behavior when the array is invalid. // } // } else if (dashArray) { // this.width = 0; // Adobe behavior when the array is invalid. // } // }, // // /** // * Set the horizontal corner radius (from a Border dictionary). // * // * @public // * @memberof AnnotationBorderStyle // * @param {integer} radius - The horizontal corner radius // */ // setHorizontalCornerRadius: // function AnnotationBorderStyle_setHorizontalCornerRadius(radius) { // if (radius === (radius | 0)) { // this.horizontalCornerRadius = radius; // } // }, // // /** // * Set the vertical corner radius (from a Border dictionary). // * // * @public // * @memberof AnnotationBorderStyle // * @param {integer} radius - The vertical corner radius // */ // setVerticalCornerRadius: // function AnnotationBorderStyle_setVerticalCornerRadius(radius) { // if (radius === (radius | 0)) { // this.verticalCornerRadius = radius; // } // } // }; // // return AnnotationBorderStyle; //})(); // //var WidgetAnnotation = (function WidgetAnnotationClosure() { // // function WidgetAnnotation(params) { // Annotation.call(this, params); // // var dict = params.dict; // var data = this.data; // // data.fieldValue = stringToPDFString( // Util.getInheritableProperty(dict, 'V') || ''); // data.alternativeText = stringToPDFString(dict.get('TU') || ''); // data.defaultAppearance = Util.getInheritableProperty(dict, 'DA') || ''; // var fieldType = Util.getInheritableProperty(dict, 'FT'); // data.fieldType = isName(fieldType) ? fieldType.name : ''; // data.fieldFlags = Util.getInheritableProperty(dict, 'Ff') || 0; // this.fieldResources = Util.getInheritableProperty(dict, 'DR') || Dict.empty; // // // Building the full field name by collecting the field and // // its ancestors 'T' data and joining them using '.'. // var fieldName = []; // var namedItem = dict; // var ref = params.ref; // while (namedItem) { // var parent = namedItem.get('Parent'); // var parentRef = namedItem.getRaw('Parent'); // var name = namedItem.get('T'); // if (name) { // fieldName.unshift(stringToPDFString(name)); // } else if (parent && ref) { // // The field name is absent, that means more than one field // // with the same name may exist. Replacing the empty name // // with the '`' plus index in the parent's 'Kids' array. // // This is not in the PDF spec but necessary to id the // // the input controls. // var kids = parent.get('Kids'); // var j, jj; // for (j = 0, jj = kids.length; j < jj; j++) { // var kidRef = kids[j]; // if (kidRef.num === ref.num && kidRef.gen === ref.gen) { // break; // } // } // fieldName.unshift('`' + j); // } // namedItem = parent; // ref = parentRef; // } // data.fullName = fieldName.join('.'); // } // // var parent = Annotation.prototype; // Util.inherit(WidgetAnnotation, Annotation, { // isViewable: function WidgetAnnotation_isViewable() { // if (this.data.fieldType === 'Sig') { // warn('unimplemented annotation type: Widget signature'); // return false; // } // // return parent.isViewable.call(this); // } // }); // // return WidgetAnnotation; //})(); // //var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() { // function TextWidgetAnnotation(params) { // WidgetAnnotation.call(this, params); // // this.data.textAlignment = Util.getInheritableProperty(params.dict, 'Q'); // this.data.annotationType = AnnotationType.WIDGET; // this.data.hasHtml = !this.data.hasAppearance && !!this.data.fieldValue; // } // // Util.inherit(TextWidgetAnnotation, WidgetAnnotation, { // getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator) { // if (this.appearance) { // return Annotation.prototype.getOperatorList.call(this, evaluator); // } // // var opList = new OperatorList(); // var data = this.data; // // // Even if there is an appearance stream, ignore it. This is the // // behaviour used by Adobe Reader. // if (!data.defaultAppearance) { // return Promise.resolve(opList); // } // // var stream = new Stream(stringToBytes(data.defaultAppearance)); // return evaluator.getOperatorList(stream, this.fieldResources, opList). // then(function () { // return opList; // }); // } // }); // // return TextWidgetAnnotation; //})(); // //var TextAnnotation = (function TextAnnotationClosure() { // function TextAnnotation(params) { // Annotation.call(this, params); // // var dict = params.dict; // var data = this.data; // // var content = dict.get('Contents'); // var title = dict.get('T'); // data.annotationType = AnnotationType.TEXT; // data.content = stringToPDFString(content || ''); // data.title = stringToPDFString(title || ''); // data.hasHtml = true; // // if (data.hasAppearance) { // data.name = 'NoIcon'; // } else { // data.rect[1] = data.rect[3] - DEFAULT_ICON_SIZE; // data.rect[2] = data.rect[0] + DEFAULT_ICON_SIZE; // data.name = dict.has('Name') ? dict.get('Name').name : 'Note'; // } // // if (dict.has('C')) { // data.hasBgColor = true; // } // } // // Util.inherit(TextAnnotation, Annotation, { }); // // return TextAnnotation; //})(); // //var LinkAnnotation = (function LinkAnnotationClosure() { // function LinkAnnotation(params) { // Annotation.call(this, params); // // var dict = params.dict; // var data = this.data; // data.annotationType = AnnotationType.LINK; // data.hasHtml = true; // // var action = dict.get('A'); // if (action && isDict(action)) { // var linkType = action.get('S').name; // if (linkType === 'URI') { // var url = action.get('URI'); // if (isName(url)) { // // Some bad PDFs do not put parentheses around relative URLs. // url = '/' + url.name; // } else if (url) { // url = addDefaultProtocolToUrl(url); // } // // TODO: pdf spec mentions urls can be relative to a Base // // entry in the dictionary. // if (!isValidUrl(url, false)) { // url = ''; // } // // According to ISO 32000-1:2008, section 12.6.4.7, // // URI should to be encoded in 7-bit ASCII. // // Some bad PDFs may have URIs in UTF-8 encoding, see Bugzilla 1122280. // try { // data.url = stringToUTF8String(url); // } catch (e) { // // Fall back to a simple copy. // data.url = url; // } // } else if (linkType === 'GoTo') { // data.dest = action.get('D'); // } else if (linkType === 'GoToR') { // var urlDict = action.get('F'); // if (isDict(urlDict)) { // // We assume that the 'url' is a Filspec dictionary // // and fetch the url without checking any further // url = urlDict.get('F') || ''; // } // // // TODO: pdf reference says that GoToR // // can also have 'NewWindow' attribute // if (!isValidUrl(url, false)) { // url = ''; // } // data.url = url; // data.dest = action.get('D'); // } else if (linkType === 'Named') { // data.action = action.get('N').name; // } else { // warn('unrecognized link type: ' + linkType); // } // } else if (dict.has('Dest')) { // // simple destination link // var dest = dict.get('Dest'); // data.dest = isName(dest) ? dest.name : dest; // } // } // // // Lets URLs beginning with 'www.' default to using the 'http://' protocol. // function addDefaultProtocolToUrl(url) { // if (url && url.indexOf('www.') === 0) { // return ('http://' + url); // } // return url; // } // // Util.inherit(LinkAnnotation, Annotation, { }); // // return LinkAnnotation; })();
luisvt/jsparser
bin/sample.js
JavaScript
apache-2.0
20,493
/* Copyright 2010-2013 SourceGear, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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. */ /** * * @file sg_variant.h * * @details SG_variant is a struct which can represent any of the * values that can appear in a JSON object. * * Note that storing a null pointer in a variant MUST be as * SG_VARIANT_TYPE_NULL. You may NOT use SG_VARIANT_TYPE_VHASH * (or the others like it) and then set pv->v.val_vhash to NULL. * */ #ifndef H_SG_VARIANT_H #define H_SG_VARIANT_H BEGIN_EXTERN_C #define SG_VARIANT_TYPE_NULL 1 #define SG_VARIANT_TYPE_INT64 2 #define SG_VARIANT_TYPE_DOUBLE 4 #define SG_VARIANT_TYPE_BOOL 8 #define SG_VARIANT_TYPE_SZ 16 #define SG_VARIANT_TYPE_VHASH 32 #define SG_VARIANT_TYPE_VARRAY 64 typedef union { SG_int64 val_int64; const char* val_sz; SG_vhash* val_vhash; SG_varray* val_varray; SG_bool val_bool; double val_double; } SG_variant_value; typedef struct _sg_variant { SG_variant_value v; /* we declare the type as 2 bytes instead of 1, for two * reasons: * * 1. to leave room for future expansion * * 2. the compiler is probably going to insert padding for * alignment purposes anyway * */ SG_uint16 type; } SG_variant; /** * The following functions are used to access the value of a variant * as its actual type. If the variant is not of the proper type, * the error will be SG_ERR_VARIANT_INVALIDTYPE. * * For nullable types, if the variant is of type NULL, then the * result will be NULL. This includes id, sz, vhash and varray. * For int64, bool and double, if the variant is of type NULL, the * result will be SG_ERR_VARIANT_INVALIDTYPE. * * These routines do NOT convert sz to/from int64, bool or double. If * you want int64 from a variant which is a string, get the string and * parse the int64 yourself. * * @defgroup SG_variant__get Functions to convert a variant to other types. * * @{ * */ void SG_variant__get__sz( SG_context* pCtx, const SG_variant* pv, const char** pputf8Value ); void SG_variant__get__int64( SG_context* pCtx, const SG_variant* pv, SG_int64* pResult ); void SG_variant__get__uint64( SG_context* pCtx, const SG_variant* pv, SG_uint64* pResult ); void SG_variant__get__int64_or_double( SG_context* pCtx, const SG_variant* pv, SG_int64* pResult ); void SG_variant__get__bool( SG_context* pCtx, const SG_variant* pv, SG_bool* pResult ); void SG_variant__get__double( SG_context* pCtx, const SG_variant* pv, double* pResult ); void SG_variant__get__vhash( SG_context* pCtx, const SG_variant* pv, SG_vhash** pResult ); void SG_variant__get__varray( SG_context* pCtx, const SG_variant* pv, SG_varray** pResult ); /** @} */ void SG_variant__compare(SG_context* pCtx, const SG_variant* pv1, const SG_variant* pv2, int* piResult); void SG_variant__equal( SG_context* pCtx, const SG_variant* pv1, const SG_variant* pv2, SG_bool* pbResult ); void SG_variant__can_be_sorted( SG_context* pCtx, const SG_variant* pv1, const SG_variant* pv2, SG_bool* pbResult ); void SG_variant__to_string( SG_context* pCtx, const SG_variant* pv, SG_string** ppstr ); /** * Creates a deep copy of a variant. */ void SG_variant__copy( SG_context* pCtx, //< [in] [out] Error and context info. const SG_variant* pSource, //< [in] The variant to copy. SG_variant** ppDest //< [out] A deep copy of the given variant. ); void SG_variant__free( SG_context* pCtx, SG_variant* pv ); const char* sg_variant__type_name(SG_uint16 t); ////////////////////////////////////////////////////////////////// /** * Normal increasing, case sensitive ordering. */ SG_qsort_compare_function SG_variant_sort_callback__increasing; int SG_variant_sort_callback__increasing(SG_context * pCtx, const void * pVoid_ppv1, // const SG_variant ** ppv1 const void * pVoid_ppv2, // const SG_variant ** ppv2 void * pVoidCallerData); ////////////////////////////////////////////////////////////////// END_EXTERN_C #endif
glycerine/vj
src/veracity/src/libraries/include/sg_variant.h
C
apache-2.0
4,580
// SmoothScroll v1.2.1 // Licensed under the terms of the MIT license. // People involved // - Balazs Galambosi (maintainer) // - Patrick Brunner (original idea) // - Michael Herf (Pulse Algorithm) // - Justin Force (Resurect) if (navigator.appVersion.indexOf("Mac") == -1) { // Scroll Variables (tweakable) var framerate = 150; // [Hz] var animtime = 500; // [px] var stepsize = 150; // [px] // Pulse (less tweakable) // ratio of "tail" to "acceleration" var pulseAlgorithm = true; var pulseScale = 8; var pulseNormalize = 1; // Acceleration var acceleration = true; var accelDelta = 10; // 20 var accelMax = 1; // 1 // Keyboard Settings var keyboardsupport = true; // option var disableKeyboard = false; // other reasons var arrowscroll = 50; // [px] // Excluded pages var exclude = ""; var disabled = false; // Other Variables var frame = false; var direction = { x: 0, y: 0 }; var initdone = false; var fixedback = true; var root = document.documentElement; var activeElement; var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 }; /** * Sets up scrolls array, determines if frames are involved. */ function init() { if (!document.body) return; var body = document.body; var html = document.documentElement; var windowHeight = window.innerHeight; var scrollHeight = body.scrollHeight; // check compat mode for root element root = (document.compatMode.indexOf('CSS') >= 0) ? html : body; activeElement = body; initdone = true; // Checks if this script is running in a frame if (top != self) { frame = true; } /** * This fixes a bug where the areas left and right to * the content does not trigger the onmousewheel event * on some pages. e.g.: html, body { height: 100% } */ else if (scrollHeight > windowHeight && (body.offsetHeight <= windowHeight || html.offsetHeight <= windowHeight)) { // DOMChange (throttle): fix height var pending = false; var refresh = function() { if (!pending && html.scrollHeight != document.height) { pending = true; // add a new pending action setTimeout(function(){ html.style.height = document.height + 'px'; pending = false; }, 500); // act rarely to stay fast } }; html.style.height = ''; setTimeout(refresh, 10); addEvent("DOMNodeInserted", refresh); addEvent("DOMNodeRemoved", refresh); // clearfix if (root.offsetHeight <= windowHeight) { var underlay = document.createElement("div"); underlay.style.clear = "both"; body.appendChild(underlay); } } // gmail performance fix if (document.URL.indexOf("mail.google.com") > -1) { var s = document.createElement("style"); s.innerHTML = ".iu { visibility: hidden }"; (document.getElementsByTagName("head")[0] || html).appendChild(s); } // disable fixed background if (!fixedback && !disabled) { body.style.backgroundAttachment = "scroll"; html.style.backgroundAttachment = "scroll"; } } /************************************************ * SCROLLING ************************************************/ var que = []; var pending = false; var lastScroll = +new Date; /** * Pushes scroll actions to the scrolling queue. */ function scrollArray(elem, left, top, delay) { delay || (delay = 1000); directionCheck(left, top); if (acceleration) { var now = +new Date; var elapsed = now - lastScroll; if (elapsed < accelDelta) { var factor = (1 + (30 / elapsed)) / 2; if (factor > 1) { factor = Math.min(factor, accelMax); left *= factor; top *= factor; } } lastScroll = +new Date; } // push a scroll command que.push({ x: left, y: top, lastX: (left < 0) ? 0.99 : -0.99, lastY: (top < 0) ? 0.99 : -0.99, start: +new Date }); // don't act if there's a pending queue if (pending) { return; } var scrollWindow = (elem === document.body); var step = function() { var now = +new Date; var scrollX = 0; var scrollY = 0; for (var i = 0; i < que.length; i++) { var item = que[i]; var elapsed = now - item.start; var finished = (elapsed >= animtime); // scroll position: [0, 1] var position = (finished) ? 1 : elapsed / animtime; // easing [optional] if (pulseAlgorithm) { position = pulse(position); } // only need the difference var x = (item.x * position - item.lastX) >> 0; var y = (item.y * position - item.lastY) >> 0; // add this to the total scrolling scrollX += x; scrollY += y; // update last values item.lastX += x; item.lastY += y; // delete and step back if it's over if (finished) { que.splice(i, 1); i--; } } // scroll left and top if (scrollWindow) { window.scrollBy(scrollX, scrollY) } else { if (scrollX) elem.scrollLeft += scrollX; if (scrollY) elem.scrollTop += scrollY; } // clean up if there's nothing left to do if (!left && !top) { que = []; } if (que.length) { requestFrame(step, elem, (delay / framerate + 1)); } else { pending = false; } } // start a new queue of actions requestFrame(step, elem, 0); pending = true; } /*********************************************** * EVENTS ***********************************************/ /** * Mouse wheel handler. * @param {Object} event */ function wheel(event) { if (!initdone) { init(); } var target = event.target; var overflowing = overflowingAncestor(target); // use default if there's no overflowing // element or default action is prevented if (!overflowing || event.defaultPrevented || isNodeName(activeElement, "embed") || (isNodeName(target, "embed") && /\.pdf/i.test(target.src))) { return true; } var deltaX = event.wheelDeltaX || 0; var deltaY = event.wheelDeltaY || 0; // use wheelDelta if deltaX/Y is not available if (!deltaX && !deltaY) { deltaY = event.wheelDelta || 0; } // scale by step size // delta is 120 most of the time // synaptics seems to send 1 sometimes if (Math.abs(deltaX) > 1.2) { deltaX *= stepsize / 120; } if (Math.abs(deltaY) > 1.2) { deltaY *= stepsize / 120; } scrollArray(overflowing, -deltaX, -deltaY); event.preventDefault(); } /** * Keydown event handler. * @param {Object} event */ function keydown(event) { var target = event.target; var modifier = event.ctrlKey || event.altKey || event.metaKey || (event.shiftKey && event.keyCode !== key.spacebar); // do nothing if user is editing text // or using a modifier key (except shift) // or in a dropdown if ( /input|textarea|select|embed/i.test(target.nodeName) || target.isContentEditable || event.defaultPrevented || modifier ) { return true; } // spacebar should trigger button press if (isNodeName(target, "button") && event.keyCode === key.spacebar) { return true; } var shift, x = 0, y = 0; var elem = overflowingAncestor(activeElement); var clientHeight = elem.clientHeight; if (elem == document.body) { clientHeight = window.innerHeight; } switch (event.keyCode) { case key.up: y = -arrowscroll; break; case key.down: y = arrowscroll; break; case key.spacebar: // (+ shift) shift = event.shiftKey ? 1 : -1; y = -shift * clientHeight * 0.9; break; case key.pageup: y = -clientHeight * 0.9; break; case key.pagedown: y = clientHeight * 0.9; break; case key.home: y = -elem.scrollTop; break; case key.end: var damt = elem.scrollHeight - elem.scrollTop - clientHeight; y = (damt > 0) ? damt+10 : 0; break; case key.left: x = -arrowscroll; break; case key.right: x = arrowscroll; break; default: return true; // a key we don't care about } scrollArray(elem, x, y); event.preventDefault(); } /** * Mousedown event only for updating activeElement */ function mousedown(event) { activeElement = event.target; } /*********************************************** * OVERFLOW ***********************************************/ var cache = {}; // cleared out every once in while setInterval(function(){ cache = {}; }, 10 * 1000); var uniqueID = (function() { var i = 0; return function (el) { return el.uniqueID || (el.uniqueID = i++); }; })(); function setCache(elems, overflowing) { for (var i = elems.length; i--;) cache[uniqueID(elems[i])] = overflowing; return overflowing; } function overflowingAncestor(el) { var elems = []; var rootScrollHeight = root.scrollHeight; do { var cached = cache[uniqueID(el)]; if (cached) { return setCache(elems, cached); } elems.push(el); if (rootScrollHeight === el.scrollHeight) { if (!frame || root.clientHeight + 10 < rootScrollHeight) { return setCache(elems, document.body); // scrolling root in WebKit } } else if (el.clientHeight + 10 < el.scrollHeight) { overflow = getComputedStyle(el, "").getPropertyValue("overflow-y"); if (overflow === "scroll" || overflow === "auto") { return setCache(elems, el); } } } while (el = el.parentNode); } /*********************************************** * HELPERS ***********************************************/ function addEvent(type, fn, bubble) { window.addEventListener(type, fn, (bubble||false)); } function removeEvent(type, fn, bubble) { window.removeEventListener(type, fn, (bubble||false)); } function isNodeName(el, tag) { return (el.nodeName||"").toLowerCase() === tag.toLowerCase(); } function directionCheck(x, y) { x = (x > 0) ? 1 : -1; y = (y > 0) ? 1 : -1; if (direction.x !== x || direction.y !== y) { direction.x = x; direction.y = y; que = []; lastScroll = 0; } } var requestFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || function(callback, element, delay){ window.setTimeout(callback, delay || (1000/60)); }; })(); /*********************************************** * PULSE ***********************************************/ /** * Viscous fluid with a pulse for part and decay for the rest. * - Applies a fixed force over an interval (a damped acceleration), and * - Lets the exponential bleed away the velocity over a longer interval * - Michael Herf, http://stereopsis.com/stopping/ */ function pulse_(x) { var val, start, expx; // test x = x * pulseScale; if (x < 1) { // acceleartion val = x - (1 - Math.exp(-x)); } else { // tail // the previous animation ended here: start = Math.exp(-1); // simple viscous drag x -= 1; expx = 1 - Math.exp(-x); val = start + (expx * (1 - start)); } return val * pulseNormalize; } function pulse(x) { if (x >= 1) return 1; if (x <= 0) return 0; if (pulseNormalize == 1) { pulseNormalize /= pulse_(1); } return pulse_(x); } addEvent("mousedown", mousedown); addEvent("mousewheel", wheel); addEvent("load", init); }
cmuhirwa/uplus
casual/vendors/smooth-scroll/SmoothScroll.js
JavaScript
apache-2.0
12,102
<div class="row"> <div class="col-xs-12"> <form class="form-horizontal" role="form" name="myForm" > <div class="form-group"> <label for="destination" class="col-xs-2 control-label">Destino</label> <div class="col-xs-7"> <select id="destination" ng-model="trip.destination" ng-options="destination.name+','+destination.country.name for destination in cities | orderBy:'name'" class="form-control"></select> </div> <div class="col-xs-1"> <button class="btn btn-primary pull-right" id="btn_create_destination" data-toggle="modal" data-target="#createDestinationModal"> Crear Destino Nuevo </button> </div> </div> <div class="form-group"> <label for="title" class="col-xs-4 control-label">Título:</label> <div class="col-xs-6"> <input type="text" id="title" placeholder="Ingrese el titulo del Viaje" class="form-control" ng-model="trip.title"/> </div> </div> </form> </div> </div> <div class="row"> <div class="col-xs-6 col-sm-offset-6"> <button class="btn btn-danger" id="btn_cancel" ng-click="go('/trip');"> Cancelar </button> <button class="btn btn-default" id="btn_clean" ng-click="clean();"> Limpiar </button> <button class="btn btn-success" id="btn_create" ng-click="create();"> Guardar </button> </div> </div> <!-- Modal --> <div class="modal fade" id="createDestinationModal" tabindex="-1" role="dialog" aria-labelledby="createDestinationModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="createDestinationModalLabel">Nuevo Destino</h4> </div> <div class="modal-body"> <form class="form-horizontal" role="form" name="newDestination"> <div class="form-group"> <label for="countrySelect" class="col-xs-4 control-label">País:</label> <div class="col-xs-6"> <select id="countrySelect" ng-model="selectedCountry" class="form-control" ng-options="c as c.name for c in countries | orderBy:'name'" ng-click="otherCountry = (selectedCountry.id==null)"></select> </div> </div> <div class="form-group" ng-show="otherCountry"> <label for="country" class="col-xs-4 control-label">Nombre del País:</label> <div class="col-xs-6"> <input type="text" id="country" placeholder="Ingrese el nombre del País" class="form-control" ng-model="country.name"/> </div> </div> <div class="form-group"> <label for="city" class="col-xs-4 control-label">Ciudad:</label> <div class="col-xs-6"> <input type="text" id="city" placeholder="Ingrese el nombre de la ciudad" class="form-control" ng-model="city.name"/> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal" ng-click="city={};country={};">Cancelar</button> <button type="button" class="btn btn-primary" ng-click="createDestination()">Guardar</button> </div> </div> </div> </div>
AxelCB/TripSplitterClone
web/app/views/trip/createTrip.html
HTML
apache-2.0
3,911
/* * Created on Jul 16, 2008 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright @2008-2013 the original author or authors. */ package org.fest.swing.core.matcher; import static org.fest.assertions.Assertions.assertThat; import static org.fest.swing.test.builder.JTextFields.textField; import javax.swing.JTextField; import org.fest.swing.test.core.EDTSafeTestCase; import org.junit.Test; /** * Tests for {@link JTextComponentMatcher#matches(java.awt.Component)}. * * @author Alex Ruiz * @author Yvonne Wang */ public class JTextComponentMatcher_matches_byText_Test extends EDTSafeTestCase { @Test public void should_return_true_if_text_is_equal_to_expected() { String text = "Hello"; JTextComponentMatcher matcher = JTextComponentMatcher.withText(text); JTextField textField = textField().withText(text).createNew(); assertThat(matcher.matches(textField)).isTrue(); } @Test public void should_return_true_if_text_matches_pattern() { JTextComponentMatcher matcher = JTextComponentMatcher.withText("Hello"); JTextField textField = textField().withText("Bye").createNew(); assertThat(matcher.matches(textField)).isFalse(); } @Test public void should_return_false_if_text_is_not_equal_to_expected() { JTextComponentMatcher matcher = JTextComponentMatcher.withText("He.*"); JTextField textField = textField().withText("Bye").createNew(); assertThat(matcher.matches(textField)).isFalse(); } }
google/fest
third_party/fest-swing/src/test/java/org/fest/swing/core/matcher/JTextComponentMatcher_matches_byText_Test.java
Java
apache-2.0
1,973
/** * @author ${kekkaishivn} - dattl@ifi.uio.no * * ${tags} */ #ifndef SGX_SYSSTAT_UTIL_H #define SGX_SYSSTAT_UTIL_H #include <sgx/sys/types.h> #ifdef __cplusplus extern "C" { #endif extern int sgx_wrapper_stat(const char *path, struct stat *buf); extern int sgx_wrapper_fstat(int fd, struct stat *buf); extern int sgx_wrapper_lstat(const char *path, struct stat *buf); extern int sgx_wrapper_chmod(const char *file, mode_t mode); extern int sgx_wrapper_fchmod(int fd, mode_t mode); extern int sgx_wrapper_fchmodat(int fd, const char *file, mode_t mode, int flag); extern mode_t sgx_wrapper_umask(mode_t mask); extern int sgx_wrapper_mkdir(const char *path, mode_t mode); extern int sgx_wrapper_mkdirat(int fd, const char *path, mode_t mode); extern int sgx_wrapper_mkfifo(const char *path, mode_t mode); extern int sgx_wrapper_mkfifoat(int fd, const char *path, mode_t mode); #ifdef __cplusplus } #endif #define stat(A, B) sgx_wrapper_stat(A, B) #define fstat(A, B) sgx_wrapper_fstat(A, B) #define lstat(A, B) sgx_wrapper_lstat(A, B) #define chmod(A, B) sgx_wrapper_chmod(A, B) #define fchmod(A, B) sgx_wrapper_fchmod(A, B) #define fchmodat(A, B, C) sgx_wrapper_fchmodat(A, B, C) #define umask(A) sgx_wrapper_umask(A) #define mkdir(A, B) sgx_wrapper_mkdir(A, B) #define mkdirat(A, B, C) sgx_wrapper_mkdirat(A, B, C) #define mkfifo(A, B) sgx_wrapper_mkfifo(A, B) #define mkfifoat(A, B, C) sgx_wrapper_mkfifoat(A, B, C) #endif
shwetasshinde24/Panoply
benchmarks/lmbench/src/MyEnclave/include/sgx_sysstat_util.h
C
apache-2.0
1,437
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AsyncWebApiPerformance")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AsyncWebApiPerformance")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("00375d55-5e9f-424c-abe7-42123ea46d59")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
dotnetcurry/web-api-performance-dncmag-08
AsyncWebApiPerformance/AsyncWebApiPerformance/Properties/AssemblyInfo.cs
C#
apache-2.0
1,380
from invoke import task, run #from fabric.api import local, lcd, get, env #from fabric.operations import require, prompt #from fabric.utils import abort import requests import rdflib import getpass import os.path import os import setlr from os import listdir from rdflib import * import logging CHEAR_DIR='chear.d/' HHEAR_DIR='hhear.d/' SETL_FILE='ontology.setl.ttl' ontology_setl = Namespace('https://hadatac.org/setl/') setl = Namespace('http://purl.org/twc/vocab/setl/') prov = Namespace('http://www.w3.org/ns/prov#') dc = Namespace('http://purl.org/dc/terms/') pv = Namespace('http://purl.org/net/provenance/ns#') logging_level = logging.INFO logging.basicConfig(level=logging_level) @task def buildchear(ctx): setl_graph = Graph() setl_graph.parse(SETL_FILE,format="turtle") cwd = os.getcwd() formats = ['ttl','owl','json'] ontology_output_files = [setl_graph.resource(URIRef('file://'+cwd+'/chear.'+x)) for x in formats] print (len(setl_graph)) for filename in os.listdir(CHEAR_DIR): if not filename.endswith('.ttl') or filename.startswith('#'): continue print('Adding fragment', filename) fragment = setl_graph.resource(BNode()) for ontology_output_file in ontology_output_files: print(ontology_output_file.identifier, list(ontology_output_file[prov.wasGeneratedBy])) ontology_output_file.value(prov.wasGeneratedBy).add(prov.used, fragment) fragment.add(RDF.type, setlr.void.Dataset) fragment_extract = setl_graph.resource(BNode()) fragment.add(prov.wasGeneratedBy, fragment_extract) fragment_extract.add(RDF.type, setl.Extract) fragment_extract.add(prov.used, URIRef('file://'+CHEAR_DIR+filename)) setlr._setl(setl_graph) @task def buildhhear(ctx): setl_graph = Graph() setl_graph.parse('hhear-ontology.setl.ttl',format="turtle") cwd = os.getcwd() formats = ['ttl','owl','json'] ontology_output_files = [setl_graph.resource(URIRef('file://'+cwd+'/hhear.'+x)) for x in formats] print (len(setl_graph)) for filename in os.listdir(HHEAR_DIR): if not filename.endswith('.ttl') or filename.startswith('#'): continue print('Adding fragment', filename) fragment = setl_graph.resource(BNode()) for ontology_output_file in ontology_output_files: print(ontology_output_file.identifier, list(ontology_output_file[prov.wasGeneratedBy])) ontology_output_file.value(prov.wasGeneratedBy).add(prov.used, fragment) fragment.add(RDF.type, setlr.void.Dataset) fragment_extract = setl_graph.resource(BNode()) fragment.add(prov.wasGeneratedBy, fragment_extract) fragment_extract.add(RDF.type, setl.Extract) fragment_extract.add(prov.used, URIRef('file://'+HHEAR_DIR+filename)) setlr._setl(setl_graph) @task def chear2hhear(c, inputfile, outputfile): import openpyxl import re import pandas as pd mappings = {} mappings.update(dict([(row['label_uri'], row['numeric_uri']) for i, row in pd.read_csv('sio_mappings.csv').iterrows()])) mappings.update(dict([(row['label_uri'], row['numeric_uri']) for i, row in pd.read_csv('chear2hhear_mappings.csv').iterrows()])) wb = openpyxl.load_workbook(inputfile) for sheet in wb: for row in sheet.rows: for cell in row: if isinstance(cell.value, str): cellValues = [] for c in re.split('\\s*[,&]\\s*', cell.value): if c in mappings: print('Replacing',c,'with',mappings[c]) c = mappings[c] cellValues.append(c) cell.value = ', '.join(cellValues) wb.save(outputfile)
tetherless-world/chear-ontology
tasks.py
Python
apache-2.0
3,872
-------------------------------- -- @module Motion -- @extend Ref -- @parent_module cc -------------------------------- -- -- @function [parent=#Motion] isRemoving -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#Motion] isRunning -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#Motion] getKey -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#Motion] ended -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#Motion] onRemove -- @param self -- @return Motion#Motion self (return value: cc.Motion) -------------------------------- -- -- @function [parent=#Motion] stop -- @param self -- @return Motion#Motion self (return value: cc.Motion) -------------------------------- -- -- @function [parent=#Motion] update -- @param self -- @param #float dt -- @return Motion#Motion self (return value: cc.Motion) -------------------------------- -- -- @function [parent=#Motion] onStart -- @param self -- @return Motion#Motion self (return value: cc.Motion) -------------------------------- -- -- @function [parent=#Motion] prepareProperties -- @param self -- @param #cc.MotionFactory factory -- @param #cc.MotionContext context -- @return Motion#Motion self (return value: cc.Motion) -------------------------------- -- -- @function [parent=#Motion] start -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#Motion] pause -- @param self -- @return Motion#Motion self (return value: cc.Motion) -------------------------------- -- -- @function [parent=#Motion] isPause -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#Motion] onPopFromPool -- @param self -- @return Motion#Motion self (return value: cc.Motion) -------------------------------- -- -- @function [parent=#Motion] onPushToPool -- @param self -- @return Motion#Motion self (return value: cc.Motion) -------------------------------- -- -- @function [parent=#Motion] onEnd -- @param self -- @return Motion#Motion self (return value: cc.Motion) -------------------------------- -- -- @function [parent=#Motion] create -- @param self -- @return Motion#Motion ret (return value: cc.Motion) -------------------------------- -- -- @function [parent=#Motion] resetPool -- @param self -- @return Motion#Motion self (return value: cc.Motion) -------------------------------- -- -- @function [parent=#Motion] poolName -- @param self -- @return char#char ret (return value: char) -------------------------------- -- -- @function [parent=#Motion] getPoolName -- @param self -- @return char#char ret (return value: char) return nil
weiDDD/WSSParticleSystem
cocos2d/cocos/scripting/lua-bindings/auto/api/Motion.lua
Lua
apache-2.0
3,225
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.indices.recovery; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexCommit; import org.apache.lucene.index.IndexFormatTooNewException; import org.apache.lucene.index.IndexFormatTooOldException; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.RateLimiter; import org.apache.lucene.util.ArrayUtil; import org.apache.lucene.util.IOUtils; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.Version; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.cluster.routing.IndexShardRoutingTable; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.StopWatch; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.io.Streams; import org.elasticsearch.common.lease.Releasable; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.lucene.store.InputStreamIndexInput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.util.CancellableThreads; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.engine.RecoveryEngineException; import org.elasticsearch.index.seqno.LocalCheckpointTracker; import org.elasticsearch.index.seqno.SequenceNumbers; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.shard.IndexShardClosedException; import org.elasticsearch.index.shard.IndexShardRelocatedException; import org.elasticsearch.index.shard.IndexShardState; import org.elasticsearch.index.store.Store; import org.elasticsearch.index.store.StoreFileMetaData; import org.elasticsearch.index.translog.Translog; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.RemoteTransportException; import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.StreamSupport; /** * RecoverySourceHandler handles the three phases of shard recovery, which is * everything relating to copying the segment files as well as sending translog * operations across the wire once the segments have been copied. * * Note: There is always one source handler per recovery that handles all the * file and translog transfer. This handler is completely isolated from other recoveries * while the {@link RateLimiter} passed via {@link RecoverySettings} is shared across recoveries * originating from this nodes to throttle the number bytes send during file transfer. The transaction log * phase bypasses the rate limiter entirely. */ public class RecoverySourceHandler { protected final Logger logger; // Shard that is going to be recovered (the "source") private final IndexShard shard; private final int shardId; // Request containing source and target node information private final StartRecoveryRequest request; private final int chunkSizeInBytes; private final RecoveryTargetHandler recoveryTarget; protected final RecoveryResponse response; private final CancellableThreads cancellableThreads = new CancellableThreads() { @Override protected void onCancel(String reason, @Nullable Exception suppressedException) { RuntimeException e; if (shard.state() == IndexShardState.CLOSED) { // check if the shard got closed on us e = new IndexShardClosedException(shard.shardId(), "shard is closed and recovery was canceled reason [" + reason + "]"); } else { e = new ExecutionCancelledException("recovery was canceled reason [" + reason + "]"); } if (suppressedException != null) { e.addSuppressed(suppressedException); } throw e; } }; public RecoverySourceHandler(final IndexShard shard, RecoveryTargetHandler recoveryTarget, final StartRecoveryRequest request, final int fileChunkSizeInBytes, final Settings nodeSettings) { this.shard = shard; this.recoveryTarget = recoveryTarget; this.request = request; this.shardId = this.request.shardId().id(); this.logger = Loggers.getLogger(getClass(), nodeSettings, request.shardId(), "recover to " + request.targetNode().getName()); this.chunkSizeInBytes = fileChunkSizeInBytes; this.response = new RecoveryResponse(); } public StartRecoveryRequest getRequest() { return request; } /** * performs the recovery from the local engine to the target */ public RecoveryResponse recoverToTarget() throws IOException { runUnderPrimaryPermit(() -> { final IndexShardRoutingTable routingTable = shard.getReplicationGroup().getRoutingTable(); ShardRouting targetShardRouting = routingTable.getByAllocationId(request.targetAllocationId()); if (targetShardRouting == null) { logger.debug("delaying recovery of {} as it is not listed as assigned to target node {}", request.shardId(), request.targetNode()); throw new DelayRecoveryException("source node does not have the shard listed in its state as allocated on the node"); } assert targetShardRouting.initializing() : "expected recovery target to be initializing but was " + targetShardRouting; }); try (Closeable ignored = shard.acquireTranslogRetentionLock()) { final Translog translog = shard.getTranslog(); final long startingSeqNo; final long requiredSeqNoRangeStart; final boolean isSequenceNumberBasedRecovery = request.startingSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO && isTargetSameHistory() && isTranslogReadyForSequenceNumberBasedRecovery(); if (isSequenceNumberBasedRecovery) { logger.trace("performing sequence numbers based recovery. starting at [{}]", request.startingSeqNo()); startingSeqNo = request.startingSeqNo(); requiredSeqNoRangeStart = startingSeqNo; } else { final Engine.IndexCommitRef phase1Snapshot; try { phase1Snapshot = shard.acquireIndexCommit(true, false); } catch (final Exception e) { throw new RecoveryEngineException(shard.shardId(), 1, "snapshot failed", e); } // we set this to 0 to create a translog roughly according to the retention policy // on the target. Note that it will still filter out legacy operations with no sequence numbers startingSeqNo = 0; // but we must have everything above the local checkpoint in the commit requiredSeqNoRangeStart = Long.parseLong(phase1Snapshot.getIndexCommit().getUserData().get(SequenceNumbers.LOCAL_CHECKPOINT_KEY)) + 1; try { phase1(phase1Snapshot.getIndexCommit(), translog::totalOperations); } catch (final Exception e) { throw new RecoveryEngineException(shard.shardId(), 1, "phase1 failed", e); } finally { try { IOUtils.close(phase1Snapshot); } catch (final IOException ex) { logger.warn("releasing snapshot caused exception", ex); } } } assert startingSeqNo >= 0 : "startingSeqNo must be non negative. got: " + startingSeqNo; assert requiredSeqNoRangeStart >= startingSeqNo : "requiredSeqNoRangeStart [" + requiredSeqNoRangeStart + "] is lower than [" + startingSeqNo + "]"; runUnderPrimaryPermit(() -> shard.initiateTracking(request.targetAllocationId())); try { // For a sequence based recovery, the target can keep its local translog prepareTargetForTranslog(isSequenceNumberBasedRecovery == false, translog.estimateTotalOperationsFromMinSeq(startingSeqNo)); } catch (final Exception e) { throw new RecoveryEngineException(shard.shardId(), 1, "prepare target for translog failed", e); } final long endingSeqNo = shard.seqNoStats().getMaxSeqNo(); /* * We need to wait for all operations up to the current max to complete, otherwise we can not guarantee that all * operations in the required range will be available for replaying from the translog of the source. */ cancellableThreads.execute(() -> shard.waitForOpsToComplete(endingSeqNo)); logger.trace("all operations up to [{}] completed, which will be used as an ending sequence number", endingSeqNo); logger.trace("snapshot translog for recovery; current size is [{}]", translog.estimateTotalOperationsFromMinSeq(startingSeqNo)); final long targetLocalCheckpoint; try(Translog.Snapshot snapshot = translog.newSnapshotFromMinSeqNo(startingSeqNo)) { targetLocalCheckpoint = phase2(startingSeqNo, requiredSeqNoRangeStart, endingSeqNo, snapshot); } catch (Exception e) { throw new RecoveryEngineException(shard.shardId(), 2, "phase2 failed", e); } finalizeRecovery(targetLocalCheckpoint); } return response; } private boolean isTargetSameHistory() { final String targetHistoryUUID = request.metadataSnapshot().getHistoryUUID(); assert targetHistoryUUID != null || shard.indexSettings().getIndexVersionCreated().before(Version.V_6_0_0_rc1) : "incoming target history N/A but index was created after or on 6.0.0-rc1"; return targetHistoryUUID != null && targetHistoryUUID.equals(shard.getHistoryUUID()); } private void runUnderPrimaryPermit(CancellableThreads.Interruptable runnable) { cancellableThreads.execute(() -> { final PlainActionFuture<Releasable> onAcquired = new PlainActionFuture<>(); shard.acquirePrimaryOperationPermit(onAcquired, ThreadPool.Names.SAME); try (Releasable ignored = onAcquired.actionGet()) { // check that the IndexShard still has the primary authority. This needs to be checked under operation permit to prevent // races, as IndexShard will change to RELOCATED only when it holds all operation permits, see IndexShard.relocated() if (shard.state() == IndexShardState.RELOCATED) { throw new IndexShardRelocatedException(shard.shardId()); } runnable.run(); } }); } /** * Determines if the source translog is ready for a sequence-number-based peer recovery. The main condition here is that the source * translog contains all operations above the local checkpoint on the target. We already know the that translog contains or will contain * all ops above the source local checkpoint, so we can stop check there. * * @return {@code true} if the source is ready for a sequence-number-based recovery * @throws IOException if an I/O exception occurred reading the translog snapshot */ boolean isTranslogReadyForSequenceNumberBasedRecovery() throws IOException { final long startingSeqNo = request.startingSeqNo(); assert startingSeqNo >= 0; final long localCheckpoint = shard.getLocalCheckpoint(); logger.trace("testing sequence numbers in range: [{}, {}]", startingSeqNo, localCheckpoint); // the start recovery request is initialized with the starting sequence number set to the target shard's local checkpoint plus one if (startingSeqNo - 1 <= localCheckpoint) { final LocalCheckpointTracker tracker = new LocalCheckpointTracker(startingSeqNo, startingSeqNo - 1); try (Translog.Snapshot snapshot = shard.getTranslog().newSnapshotFromMinSeqNo(startingSeqNo)) { Translog.Operation operation; while ((operation = snapshot.next()) != null) { if (operation.seqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO) { tracker.markSeqNoAsCompleted(operation.seqNo()); } } } return tracker.getCheckpoint() >= localCheckpoint; } else { return false; } } /** * Perform phase1 of the recovery operations. Once this {@link IndexCommit} * snapshot has been performed no commit operations (files being fsync'd) * are effectively allowed on this index until all recovery phases are done * <p> * Phase1 examines the segment files on the target node and copies over the * segments that are missing. Only segments that have the same size and * checksum can be reused */ public void phase1(final IndexCommit snapshot, final Supplier<Integer> translogOps) { cancellableThreads.checkForCancel(); // Total size of segment files that are recovered long totalSize = 0; // Total size of segment files that were able to be re-used long existingTotalSize = 0; final Store store = shard.store(); store.incRef(); try { StopWatch stopWatch = new StopWatch().start(); final Store.MetadataSnapshot recoverySourceMetadata; try { recoverySourceMetadata = store.getMetadata(snapshot); } catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) { shard.failShard("recovery", ex); throw ex; } for (String name : snapshot.getFileNames()) { final StoreFileMetaData md = recoverySourceMetadata.get(name); if (md == null) { logger.info("Snapshot differs from actual index for file: {} meta: {}", name, recoverySourceMetadata.asMap()); throw new CorruptIndexException("Snapshot differs from actual index - maybe index was removed metadata has " + recoverySourceMetadata.asMap().size() + " files", name); } } // Generate a "diff" of all the identical, different, and missing // segment files on the target node, using the existing files on // the source node String recoverySourceSyncId = recoverySourceMetadata.getSyncId(); String recoveryTargetSyncId = request.metadataSnapshot().getSyncId(); final boolean recoverWithSyncId = recoverySourceSyncId != null && recoverySourceSyncId.equals(recoveryTargetSyncId); if (recoverWithSyncId) { final long numDocsTarget = request.metadataSnapshot().getNumDocs(); final long numDocsSource = recoverySourceMetadata.getNumDocs(); if (numDocsTarget != numDocsSource) { throw new IllegalStateException("try to recover " + request.shardId() + " from primary shard with sync id but number " + "of docs differ: " + numDocsSource + " (" + request.sourceNode().getName() + ", primary) vs " + numDocsTarget + "(" + request.targetNode().getName() + ")"); } // we shortcut recovery here because we have nothing to copy. but we must still start the engine on the target. // so we don't return here logger.trace("skipping [phase1]- identical sync id [{}] found on both source and target", recoverySourceSyncId); } else { final Store.RecoveryDiff diff = recoverySourceMetadata.recoveryDiff(request.metadataSnapshot()); for (StoreFileMetaData md : diff.identical) { response.phase1ExistingFileNames.add(md.name()); response.phase1ExistingFileSizes.add(md.length()); existingTotalSize += md.length(); if (logger.isTraceEnabled()) { logger.trace("recovery [phase1]: not recovering [{}], exist in local store and has checksum [{}]," + " size [{}]", md.name(), md.checksum(), md.length()); } totalSize += md.length(); } List<StoreFileMetaData> phase1Files = new ArrayList<>(diff.different.size() + diff.missing.size()); phase1Files.addAll(diff.different); phase1Files.addAll(diff.missing); for (StoreFileMetaData md : phase1Files) { if (request.metadataSnapshot().asMap().containsKey(md.name())) { logger.trace("recovery [phase1]: recovering [{}], exists in local store, but is different: remote [{}], local [{}]", md.name(), request.metadataSnapshot().asMap().get(md.name()), md); } else { logger.trace("recovery [phase1]: recovering [{}], does not exist in remote", md.name()); } response.phase1FileNames.add(md.name()); response.phase1FileSizes.add(md.length()); totalSize += md.length(); } response.phase1TotalSize = totalSize; response.phase1ExistingTotalSize = existingTotalSize; logger.trace("recovery [phase1]: recovering_files [{}] with total_size [{}], reusing_files [{}] with total_size [{}]", response.phase1FileNames.size(), new ByteSizeValue(totalSize), response.phase1ExistingFileNames.size(), new ByteSizeValue(existingTotalSize)); cancellableThreads.execute(() -> recoveryTarget.receiveFileInfo(response.phase1FileNames, response.phase1FileSizes, response.phase1ExistingFileNames, response.phase1ExistingFileSizes, translogOps.get())); // How many bytes we've copied since we last called RateLimiter.pause final Function<StoreFileMetaData, OutputStream> outputStreamFactories = md -> new BufferedOutputStream(new RecoveryOutputStream(md, translogOps), chunkSizeInBytes); sendFiles(store, phase1Files.toArray(new StoreFileMetaData[phase1Files.size()]), outputStreamFactories); // Send the CLEAN_FILES request, which takes all of the files that // were transferred and renames them from their temporary file // names to the actual file names. It also writes checksums for // the files after they have been renamed. // // Once the files have been renamed, any other files that are not // related to this recovery (out of date segments, for example) // are deleted try { cancellableThreads.executeIO(() -> recoveryTarget.cleanFiles(translogOps.get(), recoverySourceMetadata)); } catch (RemoteTransportException | IOException targetException) { final IOException corruptIndexException; // we realized that after the index was copied and we wanted to finalize the recovery // the index was corrupted: // - maybe due to a broken segments file on an empty index (transferred with no checksum) // - maybe due to old segments without checksums or length only checks if ((corruptIndexException = ExceptionsHelper.unwrapCorruption(targetException)) != null) { try { final Store.MetadataSnapshot recoverySourceMetadata1 = store.getMetadata(snapshot); StoreFileMetaData[] metadata = StreamSupport.stream(recoverySourceMetadata1.spliterator(), false).toArray(StoreFileMetaData[]::new); ArrayUtil.timSort(metadata, Comparator.comparingLong(StoreFileMetaData::length)); // check small files first for (StoreFileMetaData md : metadata) { cancellableThreads.checkForCancel(); logger.debug("checking integrity for file {} after remove corruption exception", md); if (store.checkIntegrityNoException(md) == false) { // we are corrupted on the primary -- fail! shard.failShard("recovery", corruptIndexException); logger.warn("Corrupted file detected {} checksum mismatch", md); throw corruptIndexException; } } } catch (IOException ex) { targetException.addSuppressed(ex); throw targetException; } // corruption has happened on the way to replica RemoteTransportException exception = new RemoteTransportException("File corruption occurred on recovery but " + "checksums are ok", null); exception.addSuppressed(targetException); logger.warn( (org.apache.logging.log4j.util.Supplier<?>) () -> new ParameterizedMessage( "{} Remote file corruption during finalization of recovery on node {}. local checksum OK", shard.shardId(), request.targetNode()), corruptIndexException); throw exception; } else { throw targetException; } } } logger.trace("recovery [phase1]: took [{}]", stopWatch.totalTime()); response.phase1Time = stopWatch.totalTime().millis(); } catch (Exception e) { throw new RecoverFilesRecoveryException(request.shardId(), response.phase1FileNames.size(), new ByteSizeValue(totalSize), e); } finally { store.decRef(); } } void prepareTargetForTranslog(final boolean createNewTranslog, final int totalTranslogOps) throws IOException { StopWatch stopWatch = new StopWatch().start(); logger.trace("recovery [phase1]: prepare remote engine for translog"); final long startEngineStart = stopWatch.totalTime().millis(); // Send a request preparing the new shard's translog to receive operations. This ensures the shard engine is started and disables // garbage collection (not the JVM's GC!) of tombstone deletes. cancellableThreads.executeIO(() -> recoveryTarget.prepareForTranslogOperations(createNewTranslog, totalTranslogOps)); stopWatch.stop(); response.startTime = stopWatch.totalTime().millis() - startEngineStart; logger.trace("recovery [phase1]: remote engine start took [{}]", stopWatch.totalTime()); } /** * Perform phase two of the recovery process. * <p> * Phase two uses a snapshot of the current translog *without* acquiring the write lock (however, the translog snapshot is * point-in-time view of the translog). It then sends each translog operation to the target node so it can be replayed into the new * shard. * * @param startingSeqNo the sequence number to start recovery from, or {@link SequenceNumbers#UNASSIGNED_SEQ_NO} if all * ops should be sent * @param requiredSeqNoRangeStart the lower sequence number of the required range (ending with endingSeqNo) * @param endingSeqNo the highest sequence number that should be sent * @param snapshot a snapshot of the translog * @return the local checkpoint on the target */ long phase2(final long startingSeqNo, long requiredSeqNoRangeStart, long endingSeqNo, final Translog.Snapshot snapshot) throws IOException { if (shard.state() == IndexShardState.CLOSED) { throw new IndexShardClosedException(request.shardId()); } cancellableThreads.checkForCancel(); final StopWatch stopWatch = new StopWatch().start(); logger.trace("recovery [phase2]: sending transaction log operations (seq# from [" + startingSeqNo + "], " + "required [" + requiredSeqNoRangeStart + ":" + endingSeqNo + "]"); // send all the snapshot's translog operations to the target final SendSnapshotResult result = sendSnapshot(startingSeqNo, requiredSeqNoRangeStart, endingSeqNo, snapshot); stopWatch.stop(); logger.trace("recovery [phase2]: took [{}]", stopWatch.totalTime()); response.phase2Time = stopWatch.totalTime().millis(); response.phase2Operations = result.totalOperations; return result.targetLocalCheckpoint; } /* * finalizes the recovery process */ public void finalizeRecovery(final long targetLocalCheckpoint) throws IOException { if (shard.state() == IndexShardState.CLOSED) { throw new IndexShardClosedException(request.shardId()); } cancellableThreads.checkForCancel(); StopWatch stopWatch = new StopWatch().start(); logger.trace("finalizing recovery"); /* * Before marking the shard as in-sync we acquire an operation permit. We do this so that there is a barrier between marking a * shard as in-sync and relocating a shard. If we acquire the permit then no relocation handoff can complete before we are done * marking the shard as in-sync. If the relocation handoff holds all the permits then after the handoff completes and we acquire * the permit then the state of the shard will be relocated and this recovery will fail. */ runUnderPrimaryPermit(() -> shard.markAllocationIdAsInSync(request.targetAllocationId(), targetLocalCheckpoint)); final long globalCheckpoint = shard.getGlobalCheckpoint(); cancellableThreads.executeIO(() -> recoveryTarget.finalizeRecovery(globalCheckpoint)); runUnderPrimaryPermit(() -> shard.updateGlobalCheckpointForShard(request.targetAllocationId(), globalCheckpoint)); if (request.isPrimaryRelocation()) { logger.trace("performing relocation hand-off"); // this acquires all IndexShard operation permits and will thus delay new recoveries until it is done cancellableThreads.execute(() -> shard.relocated("to " + request.targetNode(), recoveryTarget::handoffPrimaryContext)); /* * if the recovery process fails after setting the shard state to RELOCATED, both relocation source and * target are failed (see {@link IndexShard#updateRoutingEntry}). */ } stopWatch.stop(); logger.trace("finalizing recovery took [{}]", stopWatch.totalTime()); } static class SendSnapshotResult { final long targetLocalCheckpoint; final int totalOperations; SendSnapshotResult(final long targetLocalCheckpoint, final int totalOperations) { this.targetLocalCheckpoint = targetLocalCheckpoint; this.totalOperations = totalOperations; } } /** * Send the given snapshot's operations with a sequence number greater than the specified staring sequence number to this handler's * target node. * <p> * Operations are bulked into a single request depending on an operation count limit or size-in-bytes limit. * * @param startingSeqNo the sequence number for which only operations with a sequence number greater than this will be sent * @param requiredSeqNoRangeStart the lower sequence number of the required range * @param endingSeqNo the upper bound of the sequence number range to be sent (inclusive) * @param snapshot the translog snapshot to replay operations from @return the local checkpoint on the target and the * total number of operations sent * @throws IOException if an I/O exception occurred reading the translog snapshot */ protected SendSnapshotResult sendSnapshot(final long startingSeqNo, long requiredSeqNoRangeStart, long endingSeqNo, final Translog.Snapshot snapshot) throws IOException { assert requiredSeqNoRangeStart <= endingSeqNo + 1: "requiredSeqNoRangeStart " + requiredSeqNoRangeStart + " is larger than endingSeqNo " + endingSeqNo; assert startingSeqNo <= requiredSeqNoRangeStart : "startingSeqNo " + startingSeqNo + " is larger than requiredSeqNoRangeStart " + requiredSeqNoRangeStart; int ops = 0; long size = 0; int skippedOps = 0; int totalSentOps = 0; final AtomicLong targetLocalCheckpoint = new AtomicLong(SequenceNumbers.UNASSIGNED_SEQ_NO); final List<Translog.Operation> operations = new ArrayList<>(); final LocalCheckpointTracker requiredOpsTracker = new LocalCheckpointTracker(endingSeqNo, requiredSeqNoRangeStart - 1); final int expectedTotalOps = snapshot.totalOperations(); if (expectedTotalOps == 0) { logger.trace("no translog operations to send"); } final CancellableThreads.IOInterruptable sendBatch = () -> targetLocalCheckpoint.set(recoveryTarget.indexTranslogOperations(operations, expectedTotalOps)); // send operations in batches Translog.Operation operation; while ((operation = snapshot.next()) != null) { if (shard.state() == IndexShardState.CLOSED) { throw new IndexShardClosedException(request.shardId()); } cancellableThreads.checkForCancel(); final long seqNo = operation.seqNo(); if (seqNo < startingSeqNo || seqNo > endingSeqNo) { skippedOps++; continue; } operations.add(operation); ops++; size += operation.estimateSize(); totalSentOps++; requiredOpsTracker.markSeqNoAsCompleted(seqNo); // check if this request is past bytes threshold, and if so, send it off if (size >= chunkSizeInBytes) { cancellableThreads.executeIO(sendBatch); logger.trace("sent batch of [{}][{}] (total: [{}]) translog operations", ops, new ByteSizeValue(size), expectedTotalOps); ops = 0; size = 0; operations.clear(); } } if (!operations.isEmpty() || totalSentOps == 0) { // send the leftover operations or if no operations were sent, request the target to respond with its local checkpoint cancellableThreads.executeIO(sendBatch); } assert expectedTotalOps == snapshot.overriddenOperations() + skippedOps + totalSentOps : String.format(Locale.ROOT, "expected total [%d], overridden [%d], skipped [%d], total sent [%d]", expectedTotalOps, snapshot.overriddenOperations(), skippedOps, totalSentOps); if (requiredOpsTracker.getCheckpoint() < endingSeqNo) { throw new IllegalStateException("translog replay failed to cover required sequence numbers" + " (required range [" + requiredSeqNoRangeStart + ":" + endingSeqNo + "). first missing op is [" + (requiredOpsTracker.getCheckpoint() + 1) + "]"); } logger.trace("sent final batch of [{}][{}] (total: [{}]) translog operations", ops, new ByteSizeValue(size), expectedTotalOps); return new SendSnapshotResult(targetLocalCheckpoint.get(), totalSentOps); } /** * Cancels the recovery and interrupts all eligible threads. */ public void cancel(String reason) { cancellableThreads.cancel(reason); } @Override public String toString() { return "ShardRecoveryHandler{" + "shardId=" + request.shardId() + ", sourceNode=" + request.sourceNode() + ", targetNode=" + request.targetNode() + '}'; } final class RecoveryOutputStream extends OutputStream { private final StoreFileMetaData md; private final Supplier<Integer> translogOps; private long position = 0; RecoveryOutputStream(StoreFileMetaData md, Supplier<Integer> translogOps) { this.md = md; this.translogOps = translogOps; } @Override public void write(int b) throws IOException { throw new UnsupportedOperationException("we can't send single bytes over the wire"); } @Override public void write(byte[] b, int offset, int length) throws IOException { sendNextChunk(position, new BytesArray(b, offset, length), md.length() == position + length); position += length; assert md.length() >= position : "length: " + md.length() + " but positions was: " + position; } private void sendNextChunk(long position, BytesArray content, boolean lastChunk) throws IOException { // Actually send the file chunk to the target node, waiting for it to complete cancellableThreads.executeIO(() -> recoveryTarget.writeFileChunk(md, position, content, lastChunk, translogOps.get()) ); if (shard.state() == IndexShardState.CLOSED) { // check if the shard got closed on us throw new IndexShardClosedException(request.shardId()); } } } void sendFiles(Store store, StoreFileMetaData[] files, Function<StoreFileMetaData, OutputStream> outputStreamFactory) throws Exception { store.incRef(); try { ArrayUtil.timSort(files, Comparator.comparingLong(StoreFileMetaData::length)); // send smallest first for (int i = 0; i < files.length; i++) { final StoreFileMetaData md = files[i]; try (IndexInput indexInput = store.directory().openInput(md.name(), IOContext.READONCE)) { // it's fine that we are only having the indexInput in the try/with block. The copy methods handles // exceptions during close correctly and doesn't hide the original exception. Streams.copy(new InputStreamIndexInput(indexInput, md.length()), outputStreamFactory.apply(md)); } catch (Exception e) { final IOException corruptIndexException; if ((corruptIndexException = ExceptionsHelper.unwrapCorruption(e)) != null) { if (store.checkIntegrityNoException(md) == false) { // we are corrupted on the primary -- fail! logger.warn("{} Corrupted file detected {} checksum mismatch", shardId, md); failEngine(corruptIndexException); throw corruptIndexException; } else { // corruption has happened on the way to replica RemoteTransportException exception = new RemoteTransportException("File corruption occurred on recovery but " + "checksums are ok", null); exception.addSuppressed(e); logger.warn( (org.apache.logging.log4j.util.Supplier<?>) () -> new ParameterizedMessage( "{} Remote file corruption on node {}, recovering {}. local checksum OK", shardId, request.targetNode(), md), corruptIndexException); throw exception; } } else { throw e; } } } } finally { store.decRef(); } } protected void failEngine(IOException cause) { shard.failShard("recovery", cause); } }
fred84/elasticsearch
server/src/main/java/org/elasticsearch/indices/recovery/RecoverySourceHandler.java
Java
apache-2.0
38,100
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.viewer.wicket.ui.panels; import java.util.List; import com.google.common.collect.Lists; import org.apache.wicket.Component; import org.apache.wicket.MarkupContainer; import org.apache.wicket.Page; import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; import org.apache.wicket.ajax.markup.html.form.AjaxButton; import org.apache.wicket.event.Broadcast; import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxButton; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.JavaScriptContentHeaderItem; import org.apache.wicket.markup.head.OnDomReadyHeaderItem; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.model.IModel; import org.apache.wicket.model.ResourceModel; import org.apache.wicket.util.string.AppendingStringBuffer; import org.apache.isis.applib.annotation.PromptStyle; import org.apache.isis.core.metamodel.adapter.ObjectAdapter; import org.apache.isis.viewer.wicket.model.hints.UiHintContainer; import org.apache.isis.viewer.wicket.model.isis.WicketViewerSettings; import org.apache.isis.viewer.wicket.model.models.ActionPrompt; import org.apache.isis.viewer.wicket.model.models.ActionPromptProvider; import org.apache.isis.viewer.wicket.model.models.BookmarkableModel; import org.apache.isis.viewer.wicket.model.models.FormExecutor; import org.apache.isis.viewer.wicket.model.models.FormExecutorContext; import org.apache.isis.viewer.wicket.model.models.ParentEntityModelProvider; import org.apache.isis.viewer.wicket.ui.components.scalars.ScalarModelSubscriber2; import org.apache.isis.viewer.wicket.ui.components.scalars.ScalarPanelAbstract2; import org.apache.isis.viewer.wicket.ui.components.widgets.formcomponent.FormFeedbackPanel; import org.apache.isis.viewer.wicket.ui.errors.JGrowlBehaviour; import org.apache.isis.viewer.wicket.ui.pages.PageAbstract; import org.apache.isis.viewer.wicket.ui.pages.entity.EntityPage; public abstract class PromptFormAbstract<T extends BookmarkableModel<ObjectAdapter> & ParentEntityModelProvider & IModel<ObjectAdapter> & FormExecutorContext> extends FormAbstract<ObjectAdapter> implements ScalarModelSubscriber2 { private static final String ID_OK_BUTTON = "okButton"; private static final String ID_CANCEL_BUTTON = "cancelButton"; private static final String ID_FEEDBACK = "feedback"; protected final List<ScalarPanelAbstract2> paramPanels = Lists.newArrayList(); private final Component parentPanel; private final WicketViewerSettings settings; private final T formExecutorContext; private final AjaxButton okButton; private final AjaxButton cancelButton; public PromptFormAbstract( final String id, final Component parentPanel, final WicketViewerSettings settings, final T model) { super(id, model); this.parentPanel = parentPanel; this.settings = settings; this.formExecutorContext = model; setOutputMarkupId(true); // for ajax button addParameters(); FormFeedbackPanel formFeedback = new FormFeedbackPanel(ID_FEEDBACK); addOrReplace(formFeedback); okButton = addOkButton(); cancelButton = addCancelButton(); doConfigureOkButton(okButton); doConfigureCancelButton(cancelButton); } @Override public void renderHead(final IHeaderResponse response) { super.renderHead(response); response.render(OnDomReadyHeaderItem.forScript( String.format("Wicket.Event.publish(Isis.Topic.FOCUS_FIRST_PARAMETER, '%s')", getMarkupId()))); } protected abstract void addParameters(); protected AjaxButton addOkButton() { AjaxButton okButton = settings.isUseIndicatorForFormSubmit() ? new IndicatingAjaxButton(ID_OK_BUTTON, new ResourceModel("okLabel")) { private static final long serialVersionUID = 1L; @Override public void onSubmit(AjaxRequestTarget target, Form<?> form) { onOkSubmittedOf(target, form, this); } @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { if (settings.isPreventDoubleClickForFormSubmit()) { PanelUtil.disableBeforeReenableOnComplete(attributes, this); } } @Override protected void onError(AjaxRequestTarget target, Form<?> form) { target.add(form); } } : new AjaxButton(ID_OK_BUTTON, new ResourceModel("okLabel")) { private static final long serialVersionUID = 1L; @Override public void onSubmit(AjaxRequestTarget target, Form<?> form) { onOkSubmittedOf(target, form, this); } @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { if (settings.isPreventDoubleClickForFormSubmit()) { PanelUtil.disableBeforeReenableOnComplete(attributes, this); } } @Override protected void onError(AjaxRequestTarget target, Form<?> form) { target.add(form); } }; okButton.add(new JGrowlBehaviour()); setDefaultButton(okButton); add(okButton); return okButton; } protected AjaxButton addCancelButton() { final AjaxButton cancelButton = new AjaxButton(ID_CANCEL_BUTTON, new ResourceModel("cancelLabel")) { private static final long serialVersionUID = 1L; @Override public void onSubmit(final AjaxRequestTarget target, Form<?> form) { closePromptIfAny(target); onCancelSubmitted(target); } }; // so can submit with invalid content (eg mandatory params missing) cancelButton.setDefaultFormProcessing(false); if (formExecutorContext.getPromptStyle().isInlineOrInlineAsIfEdit()) { cancelButton.add(new FireOnEscapeKey() { @Override protected void respond(final AjaxRequestTarget target) { onCancelSubmitted(target); } }); } add(cancelButton); return cancelButton; } protected void closePromptIfAny(final AjaxRequestTarget target) { final ActionPrompt actionPromptIfAny = ActionPromptProvider.Util.getFrom(parentPanel).getActionPrompt(); if (actionPromptIfAny != null) { actionPromptIfAny.closePrompt(target); } } /** * Optional hook */ protected void doConfigureOkButton(final AjaxButton okButton) { } /** * Optional hook */ protected void doConfigureCancelButton(final AjaxButton cancelButton) { } private UiHintContainer getPageUiHintContainerIfAny() { Page page = getPage(); if (page instanceof EntityPage) { EntityPage entityPage = (EntityPage) page; return entityPage.getUiHintContainerIfAny(); } return null; } private void onOkSubmittedOf( final AjaxRequestTarget target, final Form<?> form, final AjaxButton okButton) { setLastFocusHint(); final FormExecutor formExecutor = new FormExecutorDefault<>(getFormExecutorStrategy()); boolean succeeded = formExecutor.executeAndProcessResults(target.getPage(), target, form); if (succeeded) { completePrompt(target); okButton.send(target.getPage(), Broadcast.EXACT, newCompletedEvent(target, form)); target.add(form); } } protected abstract FormExecutorStrategy<T> getFormExecutorStrategy(); private void setLastFocusHint() { final UiHintContainer entityModel = getPageUiHintContainerIfAny(); if (entityModel == null) { return; } MarkupContainer parent = this.parentPanel.getParent(); if (parent != null) { entityModel.setHint(getPage(), PageAbstract.UIHINT_FOCUS, parent.getPageRelativePath()); } } protected abstract Object newCompletedEvent( final AjaxRequestTarget target, final Form<?> form); @Override public void onError(AjaxRequestTarget target, ScalarPanelAbstract2 scalarPanel) { if (scalarPanel != null) { // ensure that any feedback error associated with the providing component is shown. target.add(scalarPanel); } } public void onCancelSubmitted(final AjaxRequestTarget target) { setLastFocusHint(); completePrompt(target); } private void completePrompt(final AjaxRequestTarget target) { final PromptStyle promptStyle = formExecutorContext.getPromptStyle(); if (promptStyle.isInlineOrInlineAsIfEdit() && formExecutorContext.getInlinePromptContext() != null) { formExecutorContext.reset(); rebuildGuiAfterInlinePromptDone(target); } else { closePromptIfAny(target); } } private void rebuildGuiAfterInlinePromptDone(final AjaxRequestTarget target) { // replace final String id = parentPanel.getId(); final MarkupContainer parent = parentPanel.getParent(); final WebMarkupContainer replacementPropertyEditFormPanel = new WebMarkupContainer(id); replacementPropertyEditFormPanel.setVisible(false); parent.addOrReplace(replacementPropertyEditFormPanel); // change visibility of inline components formExecutorContext.getInlinePromptContext().onCancel(); // redraw MarkupContainer scalarTypeContainer = formExecutorContext.getInlinePromptContext() .getScalarTypeContainer(); if (scalarTypeContainer != null) { String markupId = scalarTypeContainer.getMarkupId(); target.appendJavaScript( String.format("Wicket.Event.publish(Isis.Topic.FOCUS_FIRST_PROPERTY, '%s')", markupId)); } target.add(parent); } private AjaxButton defaultSubmittingComponent() { return okButton; } // workaround for https://issues.apache.org/jira/browse/WICKET-6364 @Override protected void appendDefaultButtonField() { AppendingStringBuffer buffer = new AppendingStringBuffer(); buffer.append( "<div style=\"width:0px;height:0px;position:absolute;left:-100px;top:-100px;overflow:hidden\">"); buffer.append("<input type=\"text\" tabindex=\"-1\" autocomplete=\"off\"/>"); Component submittingComponent = (Component) this.defaultSubmittingComponent(); buffer.append("<input type=\"submit\" tabindex=\"-1\" name=\""); buffer.append(this.defaultSubmittingComponent().getInputName()); buffer.append("\" onclick=\" var b=document.getElementById(\'"); buffer.append(submittingComponent.getMarkupId()); buffer.append( "\'); if (b!=null&amp;&amp;b.onclick!=null&amp;&amp;typeof(b.onclick) != \'undefined\') { var r = Wicket.bind(b.onclick, b)(); if (r != false) b.click(); } else { b.click(); }; return false;\" "); buffer.append(" />"); buffer.append("</div>"); this.getResponse().write(buffer); } static abstract class FireOnEscapeKey extends AbstractDefaultAjaxBehavior { private static final String PRE_JS = "" + "$(document).ready( function() { \n" + " $(document).bind('keyup', function(evt) { \n" + " if (evt.keyCode == 27) { \n"; private static final String POST_JS = "" + " evt.preventDefault(); \n " + " } \n" + " }); \n" + "});"; @Override public void renderHead(final Component component, final IHeaderResponse response) { super.renderHead(component, response); final String javascript = PRE_JS + getCallbackScript() + POST_JS; response.render( JavaScriptContentHeaderItem.forScript(javascript, null, null)); } @Override protected abstract void respond(final AjaxRequestTarget target); } }
oscarbou/isis
core/viewer-wicket-ui/src/main/java/org/apache/isis/viewer/wicket/ui/panels/PromptFormAbstract.java
Java
apache-2.0
13,645
--- external help file: Microsoft.Azure.Commands.ContainerInstance.dll-Help.xml Module Name: AzureRM.ContainerInstance online version: https://docs.microsoft.com/en-us/powershell/module/azurerm.containerinstance/new-azurermcontainergroup schema: 2.0.0 --- # New-AzureRmContainerGroup ## SYNOPSIS Creates a container group. ## SYNTAX ### CreateContainerGroupBaseParamSet (Default) ``` New-AzureRmContainerGroup [-ResourceGroupName] <String> [-Name] <String> [-Image] <String> [-Location <String>] [-OsType <String>] [-RestartPolicy <String>] [-Cpu <Int32>] [-MemoryInGB <Double>] [-IpAddressType <String>] [-Port <Int32[]>] [-Command <String>] [-EnvironmentVariable <Hashtable>] [-Tag <Hashtable>] [-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### CreateContainerGroupWithRegistryParamSet ``` New-AzureRmContainerGroup [-ResourceGroupName] <String> [-Name] <String> [-Image] <String> -RegistryCredential <PSCredential> [-Location <String>] [-OsType <String>] [-RestartPolicy <String>] [-Cpu <Int32>] [-MemoryInGB <Double>] [-IpAddressType <String>] [-Port <Int32[]>] [-Command <String>] [-EnvironmentVariable <Hashtable>] [-RegistryServerDomain <String>] [-Tag <Hashtable>] [-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### CreateContainerGroupWithAzureFileMountParamSet ``` New-AzureRmContainerGroup [-ResourceGroupName] <String> [-Name] <String> [-Image] <String> -AzureFileVolumeShareName <String> -AzureFileVolumeAccountCredential <PSCredential> -AzureFileVolumeMountPath <String> [-Location <String>] [-OsType <String>] [-RestartPolicy <String>] [-Cpu <Int32>] [-MemoryInGB <Double>] [-IpAddressType <String>] [-Port <Int32[]>] [-Command <String>] [-EnvironmentVariable <Hashtable>] [-Tag <Hashtable>] [-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The **New-AzureRmContainerGroup** cmdlets creates a container group. ## EXAMPLES ### Example 1 ``` PS C:\> New-AzureRmContainerGroup -ResourceGroupName demo -Name mycontainer -Image nginx -OsType Linux -IpAddressType Public -Ports @(8000) ResourceGroupName : demo Id : /subscriptions/ae43b1e3-c35d-4c8c-bc0d-f148b4c52b78/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/mycontainer Name : mycontainer Type : Microsoft.ContainerInstance/containerGroups Location : westus Tags : ProvisioningState : Creating Containers : {mycontainer} ImageRegistryCredentials : RestartPolicy : IpAddress : 13.88.10.240 Ports : {8000} OsType : Linux Volumes : State : Running Events : {} ``` This commands creates a container group using latest nginx image and requests a public IP address with opening port 8000. ### Example 2 ``` PS C:\> New-AzureRmContainerGroup -ResourceGroupName demo -Name mycontainer -Image alpine -OsType Linux -Command "/bin/sh -c myscript.sh" -EnvironmentVariable @{"env1"="value1";"env2"="value2"} ResourceGroupName : demo Id : /subscriptions/ae43b1e3-c35d-4c8c-bc0d-f148b4c52b78/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/mycontainer Name : mycontainer Type : Microsoft.ContainerInstance/containerGroups Location : westus Tags : ProvisioningState : Creating Containers : {mycontainer} ImageRegistryCredentials : RestartPolicy : IpAddress : Ports : OsType : Linux Volumes : State : Running Events : {} ``` This commands creates a container group and runs a custom script inside the container. ### Example 3: Creates a run-to-completion container group. ``` PS C:\> New-AzureRmContainerGroup -ResourceGroupName demo -Name mycontainer -Image alpine -OsType Linux -Command "echo hello" -RestartPolicy Never ResourceGroupName : demo Id : /subscriptions/ae43b1e3-c35d-4c8c-bc0d-f148b4c52b78/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/mycontainer Name : mycontainer Type : Microsoft.ContainerInstance/containerGroups Location : westus Tags : ProvisioningState : Creating Containers : {mycontainer} ImageRegistryCredentials : RestartPolicy : IpAddress : Ports : OsType : Linux Volumes : State : Running Events : {} ``` This commands creates a container group which prints out 'hello' and stops. ### Example 4: Creates a container group using image in Azure Container Registry ``` PS C:\> $secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force PS C:\> $mycred = New-Object System.Management.Automation.PSCredential ("myacr", $secpasswd) PS C:\> New-AzureRmContainerGroup -ResourceGroupName demo -Name mycontainer -Image myacr.azurecr.io/nginx:latest -IpAddressType Public -RegistryCredential $mycred ResourceGroupName : demo Id : /subscriptions/ae43b1e3-c35d-4c8c-bc0d-f148b4c52b78/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/mycontainer Name : mycontainer Type : Microsoft.ContainerInstance/containerGroups Location : westus Tags : ProvisioningState : Creating Containers : {mycontainer} ImageRegistryCredentials : {myacr} RestartPolicy : IpAddress : 13.88.10.240 Ports : {80} OsType : Linux Volumes : State : Running Events : {} ``` This commands creates a container group using a nginx image in Azure Container Registry. ### Example 5: Creates a container group using image in custom container image registry ``` PS C:\> $secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force PS C:\> $mycred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd) PS C:\> New-AzureRmContainerGroup -ResourceGroupName MyResourceGroup -Name MyContainer -Image myserver.com/myimage:latest -RegistryServer myserver.com -RegistryCredential $mycred ResourceGroupName : demo Id : /subscriptions/ae43b1e3-c35d-4c8c-bc0d-f148b4c52b78/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/mycontainer Name : mycontainer Type : Microsoft.ContainerInstance/containerGroups Location : westus Tags : ProvisioningState : Creating Containers : {mycontainer} ImageRegistryCredentials : {myserver.com} RestartPolicy : IpAddress : 13.88.10.240 Ports : {80} OsType : Linux Volumes : State : Running Events : {} ``` This commands creates a container group using a custom image from a custom container image registry. ### Example 6: Creates a container group that mounts Azure File volume ``` PS C:\> $secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force PS C:\> $mycred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd) PS C:\> New-AzureRmContainerGroup -ResourceGroupName MyResourceGroup -Name MyContainer -Image alpine -AzureFileVolumeShareName myshare -AzureFileVolumeAccountKey $mycred -AzureFileVolumeMountPath /mnt/azfile ResourceGroupName : demo Id : /subscriptions/ae43b1e3-c35d-4c8c-bc0d-f148b4c52b78/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/mycontainer Name : mycontainer Type : Microsoft.ContainerInstance/containerGroups Location : westus Tags : ProvisioningState : Creating Containers : {mycontainer} ImageRegistryCredentials : {myserver.com} RestartPolicy : IpAddress : 13.88.10.240 Ports : {80} OsType : Linux Volumes : {AzureFile} State : Running Events : {} ``` This commands creates a container group that mounts the provided Azure File share to `/mnt/azfile`. ## PARAMETERS ### -AzureFileVolumeAccountCredential The storage account credential of the Azure File share to mount where the username is the storage account name and the key is the storage account key. ```yaml Type: PSCredential Parameter Sets: CreateContainerGroupWithAzureFileMountParamSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -AzureFileVolumeMountPath The mount path for the Azure File volume. ```yaml Type: String Parameter Sets: CreateContainerGroupWithAzureFileMountParamSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -AzureFileVolumeShareName The name of the Azure File share to mount. ```yaml Type: String Parameter Sets: CreateContainerGroupWithAzureFileMountParamSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Command The command to run in the container. ```yaml Type: String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Cpu The required CPU cores. Default: 1 ```yaml Type: Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DefaultProfile The credentials, account, tenant, and subscription used for communication with azure. ```yaml Type: IAzureContextContainer Parameter Sets: (All) Aliases: AzureRmContext, AzureCredential Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -EnvironmentVariable The container environment variables. ```yaml Type: Hashtable Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Image The container image. ```yaml Type: String Parameter Sets: (All) Aliases: Required: True Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -IpAddressType The IP address type. ```yaml Type: String Parameter Sets: (All) Aliases: Accepted values: Public Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Location The container group Location. Default to the location of the resource group. ```yaml Type: String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MemoryInGB The required memory in GB. Default: 1.5 ```yaml Type: Double Parameter Sets: (All) Aliases: Memory Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name The container group name. ```yaml Type: String Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -OsType The container OS type. Default: Linux ```yaml Type: String Parameter Sets: (All) Aliases: Accepted values: Linux, Windows Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Port The port(s) to open. Default: [80] ```yaml Type: Int32[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RegistryCredential The custom container registry credential. ```yaml Type: PSCredential Parameter Sets: CreateContainerGroupWithRegistryParamSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RegistryServerDomain The custom container registry login server. ```yaml Type: String Parameter Sets: CreateContainerGroupWithRegistryParamSet Aliases: RegistryServer Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ResourceGroupName The resource group name. ```yaml Type: String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -RestartPolicy The container restart policy. Default: Always ```yaml Type: String Parameter Sets: (All) Aliases: Accepted values: Always, Never, OnFailure Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Tag {{Fill Tag Description}} ```yaml Type: Hashtable Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String System.Collections.Hashtable ## OUTPUTS ### Microsoft.Azure.Commands.ContainerInstance.Models.PSContainerGroup ## NOTES ## RELATED LINKS
naveedaz/azure-powershell
src/ResourceManager/ContainerInstance/Commands.ContainerInstance/help/New-AzureRmContainerGroup.md
Markdown
apache-2.0
14,729
/** * Licensed to niosmtpproxy developers ('niosmtpproxy') under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * niosmtpproxy licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.normanmaurer.niosmtpproxy.handlers; import me.normanmaurer.niosmtp.core.SMTPRequestImpl; import me.normanmaurer.niosmtp.transport.SMTPClientSession; import me.normanmaurer.niosmtpproxy.SMTPProxyConstants; import org.apache.james.protocols.api.Request; import org.apache.james.protocols.api.Response; import org.apache.james.protocols.api.ProtocolSession.State; import org.apache.james.protocols.api.future.FutureResponseImpl; import org.apache.james.protocols.api.handler.CommandHandler; import org.apache.james.protocols.api.handler.UnknownCommandHandler; import org.apache.james.protocols.smtp.SMTPSession; /** * {@link CommandHandler} which just forwards all {@link Request} to an remote SMTP-Server. Once it get the {@link Response} of it, it will write * it back the SMTP Client. * * So this acts as a pure proxy * * @author Norman Maurer * */ public class SMTPProxyCmdHandler extends UnknownCommandHandler<SMTPSession> implements SMTPProxyConstants { @Override public Response onCommand(SMTPSession session, final Request request) { final FutureResponseImpl futureResponse = new FutureResponseImpl(); final SMTPClientSession clientSession = (SMTPClientSession) session.getAttachment(SMTP_CLIENT_SESSION_KEY, State.Connection); clientSession.send(new SMTPRequestImpl(request.getCommand(), request.getArgument())).addListener(createListener(futureResponse, session, request, clientSession)); return futureResponse; } /** * Create a new {@link SMTPProxyFutureListener} * * @param response * @param session * @param request * @param clientSession * @return */ protected SMTPProxyFutureListener createListener(FutureResponseImpl response, SMTPSession session, Request request, SMTPClientSession clientSession) { return new SMTPProxyFutureListener(response); } }
normanmaurer/niosmtpproxy
src/main/java/me/normanmaurer/niosmtpproxy/handlers/SMTPProxyCmdHandler.java
Java
apache-2.0
2,701
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import firebase from 'firebase'; import ReduxThunk from 'redux-thunk'; import reducers from './src/reducers'; // import LoginForm from './src/components/LoginForm'; import Router from './src/Router'; class App extends Component { componentWillMount() { // Initialize Firebase const config = { apiKey: 'AIzaSyBlE5TJxuDiBiGmhGH1eLymxCmAer7d5Rg', authDomain: 'manager-bab0a.firebaseapp.com', databaseURL: 'https://manager-bab0a.firebaseio.com', projectId: 'manager-bab0a', storageBucket: 'manager-bab0a.appspot.com', messagingSenderId: '607355351109' }; firebase.initializeApp(config); } render() { const store = createStore(reducers, {}, applyMiddleware(ReduxThunk)); return ( <Provider store={store}> <Router /> </Provider> ); } } export default App;
parammehta/TravLendar
mobile/mock ups/manager/App.js
JavaScript
apache-2.0
958
# -*- coding: ISO-8859-1 -*- # Copyright 2010 Dirk Holtwick, holtwick.it # # 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. __reversion__ = "$Revision: 20 $" __author__ = "$Author: holtwick $" __date__ = "$Date: 2007-10-09 12:58:24 +0200 (Di, 09 Okt 2007) $" from reportlab.lib.units import inch, cm from reportlab.lib.styles import * from reportlab.lib.enums import * from reportlab.lib.colors import * from reportlab.lib.pagesizes import * from reportlab.pdfbase import pdfmetrics # from reportlab.platypus import * # from reportlab.platypus.flowables import Flowable # from reportlab.platypus.tableofcontents import TableOfContents # from reportlab.platypus.para import Para, PageNumberObject, UNDERLINE, HotLink import reportlab import copy import types import os import os.path import pprint import sys import string import re import base64 import urlparse import mimetypes import urllib2 import urllib import httplib import tempfile import shutil rgb_re = re.compile("^.*?rgb[(]([0-9]+).*?([0-9]+).*?([0-9]+)[)].*?[ ]*$") _reportlab_version = tuple(map(int, reportlab.Version.split('.'))) if _reportlab_version < (2,1): raise ImportError("Reportlab Version 2.1+ is needed!") REPORTLAB22 = _reportlab_version >= (2, 2) #if not(reportlab.Version[0] == "2" and reportlab.Version[2] >= "1"): # raise ImportError("Reportlab Version 2.1+ is needed!") # #REPORTLAB22 = (reportlab.Version[0] == "2" and reportlab.Version[2] >= "2") # print "***", reportlab.Version, REPORTLAB22, reportlab.__file__ import logging log = logging.getLogger("ho.pisa") try: import cStringIO as StringIO except: import StringIO try: import pyPdf except: pyPdf = None try: from reportlab.graphics import renderPM except: renderPM = None try: from reportlab.graphics import renderSVG except: renderSVG = None def ErrorMsg(): """ Helper to get a nice traceback as string """ import traceback, sys, cgi type = value = tb = limit = None type, value, tb = sys.exc_info() list = traceback.format_tb(tb, limit) + traceback.format_exception_only(type, value) return "Traceback (innermost last):\n" + "%-20s %s" % ( string.join(list[: - 1], ""), list[ - 1]) def toList(value): if type(value) not in (types.ListType, types.TupleType): return [value] return list(value) def flatten(x): """flatten(sequence) -> list copied from http://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). Examples: >>> [1, 2, [3,4], (5,6)] [1, 2, [3, 4], (5, 6)] >>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)]) [1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]""" result = [] for el in x: #if isinstance(el, (list, tuple)): if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) return result def _toColor(arg, default=None): '''try to map an arbitrary arg to a color instance''' if isinstance(arg, Color): return arg tArg = type(arg) if tArg in (types.ListType, types.TupleType): assert 3 <= len(arg) <= 4, 'Can only convert 3 and 4 sequences to color' assert 0 <= min(arg) and max(arg) <= 1 return len(arg) == 3 and Color(arg[0], arg[1], arg[2]) or CMYKColor(arg[0], arg[1], arg[2], arg[3]) elif tArg == types.StringType: C = getAllNamedColors() s = arg.lower() if C.has_key(s): return C[s] try: return toColor(eval(arg)) except: pass try: return HexColor(arg) except: if default is None: raise ValueError('Invalid color value %r' % arg) return default def getColor(value, default=None): " Convert to color value " try: original = value if isinstance(value, Color): return value value = str(value).strip().lower() if value == "transparent" or value == "none": return default if value in COLOR_BY_NAME: return COLOR_BY_NAME[value] if value.startswith("#") and len(value) == 4: value = "#" + value[1] + value[1] + value[2] + value[2] + value[3] + value[3] elif rgb_re.search(value): # e.g., value = "<css function: rgb(153, 51, 153)>", go figure: r, g, b = [int(x) for x in rgb_re.search(value).groups()] value = "#%02x%02x%02x" % (r, g, b) else: # Shrug pass # XXX Throws illegal in 2.1 e.g. toColor('none'), # therefore we have a workaround here return _toColor(value) except ValueError, e: log.warn("Unknown color %r", original) return default def getBorderStyle(value, default=None): # log.debug(value) if value and (str(value).lower() not in ("none", "hidden")): return value return default mm = cm / 10.0 dpi96 = (1.0 / 96.0 * inch) _absoluteSizeTable = { "1": 50.0 / 100.0, "xx-small": 50.0 / 100.0, "x-small": 50.0 / 100.0, "2": 75.0 / 100.0, "small": 75.0 / 100.0, "3": 100.0 / 100.0, "medium": 100.0 / 100.0, "4": 125.0 / 100.0, "large": 125.0 / 100.0, "5": 150.0 / 100.0, "x-large": 150.0 / 100.0, "6": 175.0 / 100.0, "xx-large": 175.0 / 100.0, "7": 200.0 / 100.0, "xxx-large": 200.0 / 100.0, #"xx-small" : 3./5., #"x-small": 3./4., #"small": 8./9., #"medium": 1./1., #"large": 6./5., #"x-large": 3./2., #"xx-large": 2./1., #"xxx-large": 3./1., } _relativeSizeTable = { "larger": 1.25, "smaller": 0.75, "+4": 200.0 / 100.0, "+3": 175.0 / 100.0, "+2": 150.0 / 100.0, "+1": 125.0 / 100.0, "-1": 75.0 / 100.0, "-2": 50.0 / 100.0, "-3": 25.0 / 100.0, } MIN_FONT_SIZE = 1.0 def getSize(value, relative=0, base=None, default=0.0): """ Converts strings to standard sizes """ try: original = value if value is None: return relative elif type(value) is types.FloatType: return value elif type(value) is types.IntType: return float(value) elif type(value) in (types.TupleType, types.ListType): value = "".join(value) value = str(value).strip().lower().replace(",", ".") if value[ - 2:] == 'cm': return float(value[: - 2].strip()) * cm elif value[ - 2:] == 'mm': return (float(value[: - 2].strip()) * mm) # 1mm = 0.1cm elif value[ - 2:] == 'in': return float(value[: - 2].strip()) * inch # 1pt == 1/72inch elif value[ - 2:] == 'inch': return float(value[: - 4].strip()) * inch # 1pt == 1/72inch elif value[ - 2:] == 'pt': return float(value[: - 2].strip()) elif value[ - 2:] == 'pc': return float(value[: - 2].strip()) * 12.0 # 1pc == 12pt elif value[ - 2:] == 'px': return float(value[: - 2].strip()) * dpi96 # XXX W3C says, use 96pdi http://www.w3.org/TR/CSS21/syndata.html#length-units elif value[ - 1:] == 'i': # 1pt == 1/72inch return float(value[: - 1].strip()) * inch elif value in ("none", "0", "auto"): return 0.0 elif relative: if value[ - 2:] == 'em': # XXX return (float(value[: - 2].strip()) * relative) # 1em = 1 * fontSize elif value[ - 2:] == 'ex': # XXX return (float(value[: - 2].strip()) * (relative / 2.0)) # 1ex = 1/2 fontSize elif value[ - 1:] == '%': # print "%", value, relative, (relative * float(value[:-1].strip())) / 100.0 return (relative * float(value[: - 1].strip())) / 100.0 # 1% = (fontSize * 1) / 100 elif value in ("normal", "inherit"): return relative elif _relativeSizeTable.has_key(value): if base: return max(MIN_FONT_SIZE, base * _relativeSizeTable[value]) return max(MIN_FONT_SIZE, relative * _relativeSizeTable[value]) elif _absoluteSizeTable.has_key(value): if base: return max(MIN_FONT_SIZE, base * _absoluteSizeTable[value]) return max(MIN_FONT_SIZE, relative * _absoluteSizeTable[value]) try: value = float(value) except: log.warn("getSize: Not a float %r", value) return default #value = 0 return max(0, value) except Exception: log.warn("getSize %r %r", original, relative, exc_info=1) # print "ERROR getSize", repr(value), repr(value), e return default def getCoords(x, y, w, h, pagesize): """ As a stupid programmer I like to use the upper left corner of the document as the 0,0 coords therefore we need to do some fancy calculations """ #~ print pagesize ax, ay = pagesize if x < 0: x = ax + x if y < 0: y = ay + y if w != None and h != None: if w <= 0: w = (ax - x + w) if h <= 0: h = (ay - y + h) return x, (ay - y - h), w, h return x, (ay - y) def getBox(box, pagesize): """ Parse sizes by corners in the form: <X-Left> <Y-Upper> <Width> <Height> The last to values with negative values are interpreted as offsets form the right and lower border. """ box = str(box).split() if len(box) != 4: raise Exception, "box not defined right way" x, y, w, h = map(getSize, box) return getCoords(x, y, w, h, pagesize) def getPos(position, pagesize): """ Pair of coordinates """ position = str(position).split() if len(position) != 2: raise Exception, "position not defined right way" x, y = map(getSize, position) return getCoords(x, y, None, None, pagesize) def getBool(s): " Is it a boolean? " return str(s).lower() in ("y", "yes", "1", "true") _uid = 0 def getUID(): " Unique ID " global _uid _uid += 1 return str(_uid) _alignments = { "left": TA_LEFT, "center": TA_CENTER, "middle": TA_CENTER, "right": TA_RIGHT, "justify": TA_JUSTIFY, } def getAlign(value, default=TA_LEFT): return _alignments.get(str(value).lower(), default) #def getVAlign(value): # # Unused # return str(value).upper() GAE = "google.appengine" in sys.modules if GAE: STRATEGIES = ( StringIO.StringIO, StringIO.StringIO) else: STRATEGIES = ( StringIO.StringIO, tempfile.NamedTemporaryFile) class pisaTempFile(object): """A temporary file implementation that uses memory unless either capacity is breached or fileno is requested, at which point a real temporary file will be created and the relevant details returned If capacity is -1 the second strategy will never be used. Inspired by: http://code.activestate.com/recipes/496744/ """ STRATEGIES = STRATEGIES CAPACITY = 10 * 1024 def __init__(self, buffer="", capacity=CAPACITY): """Creates a TempFile object containing the specified buffer. If capacity is specified, we use a real temporary file once the file gets larger than that size. Otherwise, the data is stored in memory. """ #if hasattr(buffer, "read"): #shutil.copyfileobj( fsrc, fdst[, length]) self.capacity = capacity self.strategy = int(len(buffer) > self.capacity) try: self._delegate = self.STRATEGIES[self.strategy]() except: # Fallback for Google AppEnginge etc. self._delegate = self.STRATEGIES[0]() self.write(buffer) def makeTempFile(self): " Switch to next startegy. If an error occured stay with the first strategy " if self.strategy == 0: try: new_delegate = self.STRATEGIES[1]() new_delegate.write(self.getvalue()) self._delegate = new_delegate self.strategy = 1 log.warn("Created temporary file %s", self.name) except: self.capacity = - 1 def getFileName(self): " Get a named temporary file " self.makeTempFile() return self.name def fileno(self): """Forces this buffer to use a temporary file as the underlying. object and returns the fileno associated with it. """ self.makeTempFile() return self._delegate.fileno() def getvalue(self): " Get value of file. Work around for second strategy " if self.strategy == 0: return self._delegate.getvalue() self._delegate.flush() self._delegate.seek(0) return self._delegate.read() def write(self, value): " If capacity != -1 and length of file > capacity it is time to switch " if self.capacity > 0 and self.strategy == 0: len_value = len(value) if len_value >= self.capacity: needs_new_strategy = True else: self.seek(0, 2) # find end of file needs_new_strategy = \ (self.tell() + len_value) >= self.capacity if needs_new_strategy: self.makeTempFile() self._delegate.write(value) def __getattr__(self, name): try: return getattr(self._delegate, name) except AttributeError: # hide the delegation e = "object '%s' has no attribute '%s'" \ % (self.__class__.__name__, name) raise AttributeError(e) _rx_datauri = re.compile("^data:(?P<mime>[a-z]+/[a-z]+);base64,(?P<data>.*)$", re.M | re.DOTALL) class pisaFileObject: """ XXX """ def __init__(self, uri, basepath=None): self.basepath = basepath self.mimetype = None self.file = None self.data = None self.uri = None self.local = None self.tmp_file = None uri = str(uri) log.debug("FileObject %r, Basepath: %r", uri, basepath) # Data URI if uri.startswith("data:"): m = _rx_datauri.match(uri) self.mimetype = m.group("mime") self.data = base64.decodestring(m.group("data")) else: # Check if we have an external scheme if basepath and not (uri.startswith("http://") or uri.startswith("https://")): urlParts = urlparse.urlparse(basepath) else: urlParts = urlparse.urlparse(uri) log.debug("URLParts: %r", urlParts) # Drive letters have len==1 but we are looking for things like http: if len(urlParts[0]) > 1 : # External data if basepath: uri = urlparse.urljoin(basepath, uri) #path = urlparse.urlsplit(url)[2] #mimetype = getMimeType(path) # Using HTTPLIB server, path = urllib.splithost(uri[uri.find("//"):]) if uri.startswith("https://"): conn = httplib.HTTPSConnection(server) else: conn = httplib.HTTPConnection(server) conn.request("GET", path) r1 = conn.getresponse() # log.debug("HTTP %r %r %r %r", server, path, uri, r1) if (r1.status, r1.reason) == (200, "OK"): # data = r1.read() self.mimetype = r1.getheader("Content-Type", None).split(";")[0] self.uri = uri if r1.getheader("content-encoding") == "gzip": # zbuf = cStringIO.StringIO(data) import gzip self.file = gzip.GzipFile(mode="rb", fileobj=r1) #data = zfile.read() #zfile.close() else: self.file = r1 # self.file = urlResponse else: urlResponse = urllib2.urlopen(uri) self.mimetype = urlResponse.info().get("Content-Type", None).split(";")[0] self.uri = urlResponse.geturl() self.file = urlResponse else: # Local data if basepath: uri = os.path.normpath(os.path.join(basepath, uri)) if os.path.isfile(uri): self.uri = uri self.local = uri self.setMimeTypeByName(uri) self.file = open(uri, "rb") def getFile(self): if self.file is not None: return self.file if self.data is not None: return pisaTempFile(self.data) return None def getNamedFile(self): if self.notFound(): return None if self.local: return str(self.local) if not self.tmp_file: self.tmp_file = tempfile.NamedTemporaryFile() if self.file: shutil.copyfileobj(self.file, self.tmp_file) else: self.tmp_file.write(self.getData()) self.tmp_file.flush() return self.tmp_file.name def getData(self): if self.data is not None: return self.data if self.file is not None: self.data = self.file.read() return self.data return None def notFound(self): return (self.file is None) and (self.data is None) def setMimeTypeByName(self, name): " Guess the mime type " mimetype = mimetypes.guess_type(name)[0] if mimetype is not None: self.mimetype = mimetypes.guess_type(name)[0].split(";")[0] def getFile(*a , **kw): file = pisaFileObject(*a, **kw) if file.notFound(): return None return file COLOR_BY_NAME = { 'activeborder': Color(212, 208, 200), 'activecaption': Color(10, 36, 106), 'aliceblue': Color(.941176, .972549, 1), 'antiquewhite': Color(.980392, .921569, .843137), 'appworkspace': Color(128, 128, 128), 'aqua': Color(0, 1, 1), 'aquamarine': Color(.498039, 1, .831373), 'azure': Color(.941176, 1, 1), 'background': Color(58, 110, 165), 'beige': Color(.960784, .960784, .862745), 'bisque': Color(1, .894118, .768627), 'black': Color(0, 0, 0), 'blanchedalmond': Color(1, .921569, .803922), 'blue': Color(0, 0, 1), 'blueviolet': Color(.541176, .168627, .886275), 'brown': Color(.647059, .164706, .164706), 'burlywood': Color(.870588, .721569, .529412), 'buttonface': Color(212, 208, 200), 'buttonhighlight': Color(255, 255, 255), 'buttonshadow': Color(128, 128, 128), 'buttontext': Color(0, 0, 0), 'cadetblue': Color(.372549, .619608, .627451), 'captiontext': Color(255, 255, 255), 'chartreuse': Color(.498039, 1, 0), 'chocolate': Color(.823529, .411765, .117647), 'coral': Color(1, .498039, .313725), 'cornflowerblue': Color(.392157, .584314, .929412), 'cornsilk': Color(1, .972549, .862745), 'crimson': Color(.862745, .078431, .235294), 'cyan': Color(0, 1, 1), 'darkblue': Color(0, 0, .545098), 'darkcyan': Color(0, .545098, .545098), 'darkgoldenrod': Color(.721569, .52549, .043137), 'darkgray': Color(.662745, .662745, .662745), 'darkgreen': Color(0, .392157, 0), 'darkgrey': Color(.662745, .662745, .662745), 'darkkhaki': Color(.741176, .717647, .419608), 'darkmagenta': Color(.545098, 0, .545098), 'darkolivegreen': Color(.333333, .419608, .184314), 'darkorange': Color(1, .54902, 0), 'darkorchid': Color(.6, .196078, .8), 'darkred': Color(.545098, 0, 0), 'darksalmon': Color(.913725, .588235, .478431), 'darkseagreen': Color(.560784, .737255, .560784), 'darkslateblue': Color(.282353, .239216, .545098), 'darkslategray': Color(.184314, .309804, .309804), 'darkslategrey': Color(.184314, .309804, .309804), 'darkturquoise': Color(0, .807843, .819608), 'darkviolet': Color(.580392, 0, .827451), 'deeppink': Color(1, .078431, .576471), 'deepskyblue': Color(0, .74902, 1), 'dimgray': Color(.411765, .411765, .411765), 'dimgrey': Color(.411765, .411765, .411765), 'dodgerblue': Color(.117647, .564706, 1), 'firebrick': Color(.698039, .133333, .133333), 'floralwhite': Color(1, .980392, .941176), 'forestgreen': Color(.133333, .545098, .133333), 'fuchsia': Color(1, 0, 1), 'gainsboro': Color(.862745, .862745, .862745), 'ghostwhite': Color(.972549, .972549, 1), 'gold': Color(1, .843137, 0), 'goldenrod': Color(.854902, .647059, .12549), 'gray': Color(.501961, .501961, .501961), 'graytext': Color(128, 128, 128), 'green': Color(0, .501961, 0), 'greenyellow': Color(.678431, 1, .184314), 'grey': Color(.501961, .501961, .501961), 'highlight': Color(10, 36, 106), 'highlighttext': Color(255, 255, 255), 'honeydew': Color(.941176, 1, .941176), 'hotpink': Color(1, .411765, .705882), 'inactiveborder': Color(212, 208, 200), 'inactivecaption': Color(128, 128, 128), 'inactivecaptiontext': Color(212, 208, 200), 'indianred': Color(.803922, .360784, .360784), 'indigo': Color(.294118, 0, .509804), 'infobackground': Color(255, 255, 225), 'infotext': Color(0, 0, 0), 'ivory': Color(1, 1, .941176), 'khaki': Color(.941176, .901961, .54902), 'lavender': Color(.901961, .901961, .980392), 'lavenderblush': Color(1, .941176, .960784), 'lawngreen': Color(.486275, .988235, 0), 'lemonchiffon': Color(1, .980392, .803922), 'lightblue': Color(.678431, .847059, .901961), 'lightcoral': Color(.941176, .501961, .501961), 'lightcyan': Color(.878431, 1, 1), 'lightgoldenrodyellow': Color(.980392, .980392, .823529), 'lightgray': Color(.827451, .827451, .827451), 'lightgreen': Color(.564706, .933333, .564706), 'lightgrey': Color(.827451, .827451, .827451), 'lightpink': Color(1, .713725, .756863), 'lightsalmon': Color(1, .627451, .478431), 'lightseagreen': Color(.12549, .698039, .666667), 'lightskyblue': Color(.529412, .807843, .980392), 'lightslategray': Color(.466667, .533333, .6), 'lightslategrey': Color(.466667, .533333, .6), 'lightsteelblue': Color(.690196, .768627, .870588), 'lightyellow': Color(1, 1, .878431), 'lime': Color(0, 1, 0), 'limegreen': Color(.196078, .803922, .196078), 'linen': Color(.980392, .941176, .901961), 'magenta': Color(1, 0, 1), 'maroon': Color(.501961, 0, 0), 'mediumaquamarine': Color(.4, .803922, .666667), 'mediumblue': Color(0, 0, .803922), 'mediumorchid': Color(.729412, .333333, .827451), 'mediumpurple': Color(.576471, .439216, .858824), 'mediumseagreen': Color(.235294, .701961, .443137), 'mediumslateblue': Color(.482353, .407843, .933333), 'mediumspringgreen': Color(0, .980392, .603922), 'mediumturquoise': Color(.282353, .819608, .8), 'mediumvioletred': Color(.780392, .082353, .521569), 'menu': Color(212, 208, 200), 'menutext': Color(0, 0, 0), 'midnightblue': Color(.098039, .098039, .439216), 'mintcream': Color(.960784, 1, .980392), 'mistyrose': Color(1, .894118, .882353), 'moccasin': Color(1, .894118, .709804), 'navajowhite': Color(1, .870588, .678431), 'navy': Color(0, 0, .501961), 'oldlace': Color(.992157, .960784, .901961), 'olive': Color(.501961, .501961, 0), 'olivedrab': Color(.419608, .556863, .137255), 'orange': Color(1, .647059, 0), 'orangered': Color(1, .270588, 0), 'orchid': Color(.854902, .439216, .839216), 'palegoldenrod': Color(.933333, .909804, .666667), 'palegreen': Color(.596078, .984314, .596078), 'paleturquoise': Color(.686275, .933333, .933333), 'palevioletred': Color(.858824, .439216, .576471), 'papayawhip': Color(1, .937255, .835294), 'peachpuff': Color(1, .854902, .72549), 'peru': Color(.803922, .521569, .247059), 'pink': Color(1, .752941, .796078), 'plum': Color(.866667, .627451, .866667), 'powderblue': Color(.690196, .878431, .901961), 'purple': Color(.501961, 0, .501961), 'red': Color(1, 0, 0), 'rosybrown': Color(.737255, .560784, .560784), 'royalblue': Color(.254902, .411765, .882353), 'saddlebrown': Color(.545098, .270588, .07451), 'salmon': Color(.980392, .501961, .447059), 'sandybrown': Color(.956863, .643137, .376471), 'scrollbar': Color(212, 208, 200), 'seagreen': Color(.180392, .545098, .341176), 'seashell': Color(1, .960784, .933333), 'sienna': Color(.627451, .321569, .176471), 'silver': Color(.752941, .752941, .752941), 'skyblue': Color(.529412, .807843, .921569), 'slateblue': Color(.415686, .352941, .803922), 'slategray': Color(.439216, .501961, .564706), 'slategrey': Color(.439216, .501961, .564706), 'snow': Color(1, .980392, .980392), 'springgreen': Color(0, 1, .498039), 'steelblue': Color(.27451, .509804, .705882), 'tan': Color(.823529, .705882, .54902), 'teal': Color(0, .501961, .501961), 'thistle': Color(.847059, .74902, .847059), 'threeddarkshadow': Color(64, 64, 64), 'threedface': Color(212, 208, 200), 'threedhighlight': Color(255, 255, 255), 'threedlightshadow': Color(212, 208, 200), 'threedshadow': Color(128, 128, 128), 'tomato': Color(1, .388235, .278431), 'turquoise': Color(.25098, .878431, .815686), 'violet': Color(.933333, .509804, .933333), 'wheat': Color(.960784, .870588, .701961), 'white': Color(1, 1, 1), 'whitesmoke': Color(.960784, .960784, .960784), 'window': Color(255, 255, 255), 'windowframe': Color(0, 0, 0), 'windowtext': Color(0, 0, 0), 'yellow': Color(1, 1, 0), 'yellowgreen': Color(.603922, .803922, .196078)}
rcucui/Pisa-util-fix
sx/pisa3/pisa_util.py
Python
apache-2.0
26,330