text
stringlengths 2
100k
| meta
dict |
---|---|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.imaging.internal;
import java.awt.color.ICC_Profile;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Internal-only debug class. Used for collecting extra information when parsing or
* modifying images or metadata. These methods are useful for troubleshooting and
* issue analysis, but this should not be used directly by end-users, nor extended
* in any way. This may change or be removed at any time.
*/
public final class Debug {
private static final Logger LOGGER = Logger.getLogger(Debug.class.getName());
// public static String newline = System.getProperty("line.separator");
private static final String NEWLINE = "\r\n";
private static long counter;
public static void debug(final String message) {
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest(message);
}
}
public static void debug() {
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest(NEWLINE);
}
}
private static String getDebug(final String message, final int[] v) {
final StringBuilder result = new StringBuilder();
if (v == null) {
result.append(message + " (" + null + ")" + NEWLINE);
} else {
result.append(message + " (" + v.length + ")" + NEWLINE);
for (final int element : v) {
result.append("\t" + element + NEWLINE);
}
result.append(NEWLINE);
}
return result.toString();
}
private static String getDebug(final String message, final byte[] v) {
final int max = 250;
return getDebug(message, v, max);
}
private static String getDebug(final String message, final byte[] v, final int max) {
final StringBuilder result = new StringBuilder();
if (v == null) {
result.append(message + " (" + null + ")" + NEWLINE);
} else {
result.append(message + " (" + v.length + ")" + NEWLINE);
for (int i = 0; i < max && i < v.length; i++) {
final int b = 0xff & v[i];
char c;
if (b == 0 || b == 10 || b == 11 || b == 13) {
c = ' ';
} else {
c = (char) b;
}
result.append("\t" + i + ": " + b + " (" + c + ", 0x"
+ Integer.toHexString(b) + ")" + NEWLINE);
}
if (v.length > max) {
result.append("\t..." + NEWLINE);
}
result.append(NEWLINE);
}
return result.toString();
}
private static String getDebug(final String message, final char[] v) {
final StringBuilder result = new StringBuilder();
if (v == null) {
result.append(message + " (" + null + ")" + NEWLINE);
} else {
result.append(message + " (" + v.length + ")" + NEWLINE);
for (final char element : v) {
result.append("\t" + element + " (" + (0xff & element) + ")" + NEWLINE);
}
result.append(NEWLINE);
}
return result.toString();
}
private static void debug(final String message, final Map<?, ?> map) {
debug(getDebug(message, map));
}
private static String getDebug(final String message, final Map<?, ?> map) {
final StringBuilder result = new StringBuilder();
if (map == null) {
return message + " map: " + null;
}
final List<Object> keys = new ArrayList<>(map.keySet());
result.append(message + " map: " + keys.size() + NEWLINE);
for (int i = 0; i < keys.size(); i++) {
final Object key = keys.get(i);
final Object value = map.get(key);
result.append("\t" + i + ": '" + key + "' -> '" + value + "'" + NEWLINE);
}
result.append(NEWLINE);
return result.toString();
}
private static String byteQuadToString(final int bytequad) {
final byte b1 = (byte) ((bytequad >> 24) & 0xff);
final byte b2 = (byte) ((bytequad >> 16) & 0xff);
final byte b3 = (byte) ((bytequad >> 8) & 0xff);
final byte b4 = (byte) ((bytequad >> 0) & 0xff);
final char c1 = (char) b1;
final char c2 = (char) b2;
final char c3 = (char) b3;
final char c4 = (char) b4;
// return new String(new char[] { c1, c2, c3, c4 });
final StringBuilder buffer = new StringBuilder(31);
buffer.append(new String(new char[]{c1, c2, c3, c4}));
buffer.append(" bytequad: ");
buffer.append(bytequad);
buffer.append(" b1: ");
buffer.append(b1);
buffer.append(" b2: ");
buffer.append(b2);
buffer.append(" b3: ");
buffer.append(b3);
buffer.append(" b4: ");
buffer.append(b4);
return buffer.toString();
}
public static void debug(final String message, final Object value) {
if (value == null) {
debug(message, "null");
} else if (value instanceof char[]) {
debug(message, (char[]) value);
} else if (value instanceof byte[]) {
debug(message, (byte[]) value);
} else if (value instanceof int[]) {
debug(message, (int[]) value);
} else if (value instanceof String) {
debug(message, (String) value);
} else if (value instanceof List) {
debug(message, (List<?>) value);
} else if (value instanceof Map) {
debug(message, (Map<?, ?>) value);
} else if (value instanceof ICC_Profile) {
debug(message, (ICC_Profile) value);
} else if (value instanceof File) {
debug(message, (File) value);
} else if (value instanceof Date) {
debug(message, (Date) value);
} else if (value instanceof Calendar) {
debug(message, (Calendar) value);
} else {
debug(message, value.toString());
}
}
private static void debug(final String message, final byte[] v) {
debug(getDebug(message, v));
}
private static void debug(final String message, final char[] v) {
debug(getDebug(message, v));
}
private static void debug(final String message, final Calendar value) {
final DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH);
debug(message, (value == null) ? "null" : df.format(value.getTime()));
}
private static void debug(final String message, final Date value) {
final DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH);
debug(message, (value == null) ? "null" : df.format(value));
}
private static void debug(final String message, final File file) {
debug(message + ": " + ((file == null) ? "null" : file.getPath()));
}
private static void debug(final String message, final ICC_Profile value) {
debug("ICC_Profile " + message + ": " + ((value == null) ? "null" : value.toString()));
if (value != null) {
debug("\t getProfileClass: " + byteQuadToString(value.getProfileClass()));
debug("\t getPCSType: " + byteQuadToString(value.getPCSType()));
debug("\t getColorSpaceType() : " + byteQuadToString(value.getColorSpaceType()));
}
}
private static void debug(final String message, final int[] v) {
debug(getDebug(message, v));
}
private static void debug(final String message, final List<?> v) {
final String suffix = " [" + counter++ + "]";
debug(message + " (" + v.size() + ")" + suffix);
for (final Object aV : v) {
debug("\t" + aV.toString() + suffix);
}
debug();
}
private static void debug(final String message, final String value) {
debug(message + " " + value);
}
public static void debug(final Throwable e) {
debug(getDebug(e));
}
public static void debug(final Throwable e, final int value) {
debug(getDebug(e, value));
}
private static String getDebug(final Throwable e) {
return getDebug(e, -1);
}
private static String getDebug(final Throwable e, final int max) {
final StringBuilder result = new StringBuilder(35);
final SimpleDateFormat timestamp = new SimpleDateFormat(
"yyyy-MM-dd kk:mm:ss:SSS", Locale.ENGLISH);
final String datetime = timestamp.format(new Date()).toLowerCase();
result.append(NEWLINE);
result.append("Throwable: "
+ ((e == null) ? "" : ("(" + e.getClass().getName() + ")"))
+ ":" + datetime + NEWLINE);
result.append("Throwable: " + ((e == null) ? "null" : e.getLocalizedMessage()) + NEWLINE);
result.append(NEWLINE);
result.append(getStackTrace(e, max));
result.append("Caught here:" + NEWLINE);
result.append(getStackTrace(new Exception(), max, 1));
// Debug.dumpStack();
result.append(NEWLINE);
return result.toString();
}
private static String getStackTrace(final Throwable e, final int limit) {
return getStackTrace(e, limit, 0);
}
private static String getStackTrace(final Throwable e, final int limit, final int skip) {
final StringBuilder result = new StringBuilder();
if (e != null) {
final StackTraceElement[] stes = e.getStackTrace();
if (stes != null) {
for (int i = skip; i < stes.length && (limit < 0 || i < limit); i++) {
final StackTraceElement ste = stes[i];
result.append("\tat " + ste.getClassName() + "."
+ ste.getMethodName() + "(" + ste.getFileName()
+ ":" + ste.getLineNumber() + ")" + NEWLINE);
}
if (limit >= 0 && stes.length > limit) {
result.append("\t..." + NEWLINE);
}
}
// e.printStackTrace(System.out);
result.append(NEWLINE);
}
return result.toString();
}
private Debug() {
}
}
| {
"pile_set_name": "Github"
} |
<mods xmlns="http://www.loc.gov/mods/v3" xmlns:exslt="http://exslt.org/common" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd" version="3.3" ID="P0b002ee18191bfa7">
<name type="corporate">
<namePart>United States Government Printing Office</namePart>
<role>
<roleTerm type="text" authority="marcrelator">printer</roleTerm>
<roleTerm type="code" authority="marcrelator">prt</roleTerm>
</role>
<role>
<roleTerm type="text" authority="marcrelator">distributor</roleTerm>
<roleTerm type="code" authority="marcrelator">dst</roleTerm>
</role>
</name>
<name type="corporate">
<namePart>United States</namePart>
<namePart>United States District Court Eastern District of Michigan</namePart>
<role>
<roleTerm type="text" authority="marcrelator">author</roleTerm>
<roleTerm type="code" authority="marcrelator">aut</roleTerm>
</role>
<description>Government Organization</description>
</name>
<typeOfResource>text</typeOfResource>
<genre authority="marcgt">government publication</genre>
<language>
<languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</language>
<extension>
<collectionCode>USCOURTS</collectionCode>
<category>Judicial Publications</category>
<branch>judicial</branch>
<dateIngested>2012-01-18</dateIngested>
</extension>
<originInfo>
<publisher>Administrative Office of the United States Courts</publisher>
<dateIssued encoding="w3cdtf">2010-01-26</dateIssued>
<issuance>monographic</issuance>
</originInfo>
<physicalDescription>
<note type="source content type">deposited</note>
<digitalOrigin>born digital</digitalOrigin>
</physicalDescription>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="uri">http://www.gpo.gov/fdsys/pkg/USCOURTS-mied-2_10-cr-20056</identifier>
<identifier type="local">P0b002ee18191bfa7</identifier>
<recordInfo>
<recordContentSource authority="marcorg">DGPO</recordContentSource>
<recordCreationDate encoding="w3cdtf">2012-01-18</recordCreationDate>
<recordChangeDate encoding="w3cdtf">2012-01-18</recordChangeDate>
<recordIdentifier source="DGPO">USCOURTS-mied-2_10-cr-20056</recordIdentifier>
<recordOrigin>machine generated</recordOrigin>
<languageOfCataloging>
<languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</languageOfCataloging>
</recordInfo>
<accessCondition type="GPO scope determination">fdlp</accessCondition>
<extension>
<docClass>USCOURTS</docClass>
<accessId>USCOURTS-mied-2_10-cr-20056</accessId>
<courtType>District</courtType>
<courtCode>mied</courtCode>
<courtCircuit>6th</courtCircuit>
<courtState>Michigan</courtState>
<courtSortOrder>2251</courtSortOrder>
<caseNumber>2:10-cr-20056</caseNumber>
<caseOffice>Detroit</caseOffice>
<caseType>criminal</caseType>
<party firstName="Kevin" fullName="Kevin Balfour" lastName="Balfour" role="Defendant"></party>
<party fullName="United States of America" lastName="United States of America" role="Plaintiff"></party>
</extension>
<titleInfo>
<title>United States of America v. Balfour</title>
<partNumber>2:10-cr-20056</partNumber>
</titleInfo>
<location>
<url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/pkg/USCOURTS-mied-2_10-cr-20056/content-detail.html</url>
</location>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="preferred citation">2:10-cr-20056;10-20056</identifier>
<name type="corporate">
<namePart>United States District Court Eastern District of Michigan</namePart>
<namePart>6th Circuit</namePart>
<namePart>Detroit</namePart>
<affiliation>U.S. Courts</affiliation>
<role>
<roleTerm authority="marcrelator" type="text">author</roleTerm>
<roleTerm authority="marcrelator" type="code">aut</roleTerm>
</role>
</name>
<name type="personal">
<displayForm>Kevin Balfour</displayForm>
<namePart type="family">Balfour</namePart>
<namePart type="given">Kevin</namePart>
<namePart type="termsOfAddress"></namePart>
<description>Defendant</description>
</name>
<name type="personal">
<displayForm>United States of America</displayForm>
<namePart type="family">United States of America</namePart>
<namePart type="given"></namePart>
<namePart type="termsOfAddress"></namePart>
<description>Plaintiff</description>
</name>
<extension>
<docClass>USCOURTS</docClass>
<accessId>USCOURTS-mied-2_10-cr-20056</accessId>
<courtType>District</courtType>
<courtCode>mied</courtCode>
<courtCircuit>6th</courtCircuit>
<courtState>Michigan</courtState>
<courtSortOrder>2251</courtSortOrder>
<caseNumber>2:10-cr-20056</caseNumber>
<caseOffice>Detroit</caseOffice>
<caseType>criminal</caseType>
<party firstName="Kevin" fullName="Kevin Balfour" lastName="Balfour" role="Defendant"></party>
<party fullName="United States of America" lastName="United States of America" role="Plaintiff"></party>
<state>Michigan</state>
</extension>
<relatedItem type="constituent" ID="id-USCOURTS-mied-2_10-cr-20056-0" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-mied-2_10-cr-20056/USCOURTS-mied-2_10-cr-20056-0/mods.xml">
<titleInfo>
<title>United States of America v. Balfour</title>
<subTitle>ORDER OF DETENTION PENDING TRIAL as to Kevin Balfour Signed by Magistrate Judge Donald A Scheer. (MLan)[2:10-mj-30024-JU]</subTitle>
<partNumber>0</partNumber>
</titleInfo>
<originInfo>
<dateIssued>2010-01-26</dateIssued>
</originInfo>
<relatedItem xlink:href="http://www.gpo.gov/fdsys/pkg/pdf/USCOURTS-mied-2_10-cr-20056-0.pdf" type="otherFormat">
<identifier type="FDsys Unique ID">D09002ee1819a57e1</identifier>
</relatedItem>
<identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-mied-2_10-cr-20056/USCOURTS-mied-2_10-cr-20056-0</identifier>
<identifier type="former granule identifier">mied-2_10-cr-20056_0.pdf</identifier>
<location>
<url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-mied-2_10-cr-20056/USCOURTS-mied-2_10-cr-20056-0/content-detail.html</url>
<url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-mied-2_10-cr-20056/pdf/USCOURTS-mied-2_10-cr-20056-0.pdf</url>
</location>
<extension>
<searchTitle>USCOURTS 2:10-cr-20056; United States of America v. Balfour; </searchTitle>
<courtName>United States District Court Eastern District of Michigan</courtName>
<state>Michigan</state>
<accessId>USCOURTS-mied-2_10-cr-20056-0</accessId>
<sequenceNumber>0</sequenceNumber>
<dateIssued>2010-01-26</dateIssued>
<docketText>ORDER OF DETENTION PENDING TRIAL as to Kevin Balfour Signed by Magistrate Judge Donald A Scheer. (MLan)[2:10-mj-30024-JU]</docketText>
</extension>
</relatedItem>
</mods> | {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Yaml\Parser as YamlParser;
/**
* YamlFileLoader loads YAML files service definitions.
*
* The YAML format does not support anonymous services (cf. the XML loader).
*
* @author Fabien Potencier <[email protected]>
*/
class YamlFileLoader extends FileLoader
{
private $yamlParser;
/**
* Loads a Yaml file.
*
* @param mixed $file The resource
* @param string $type The resource type
*/
public function load($file, $type = null)
{
$path = $this->locator->locate($file);
$content = $this->loadFile($path);
$this->container->addResource(new FileResource($path));
// empty file
if (null === $content) {
return;
}
// imports
$this->parseImports($content, $file);
// parameters
if (isset($content['parameters'])) {
foreach ($content['parameters'] as $key => $value) {
$this->container->setParameter($key, $this->resolveServices($value));
}
}
// extensions
$this->loadFromExtensions($content);
// services
$this->parseDefinitions($content, $file);
}
/**
* Returns true if this class supports the given resource.
*
* @param mixed $resource A resource
* @param string $type The resource type
*
* @return Boolean true if this class supports the given resource, false otherwise
*/
public function supports($resource, $type = null)
{
return is_string($resource) && 'yml' === pathinfo($resource, PATHINFO_EXTENSION);
}
/**
* Parses all imports
*
* @param array $content
* @param string $file
*/
private function parseImports($content, $file)
{
if (!isset($content['imports'])) {
return;
}
foreach ($content['imports'] as $import) {
$this->setCurrentDir(dirname($file));
$this->import($import['resource'], null, isset($import['ignore_errors']) ? (Boolean) $import['ignore_errors'] : false, $file);
}
}
/**
* Parses definitions
*
* @param array $content
* @param string $file
*/
private function parseDefinitions($content, $file)
{
if (!isset($content['services'])) {
return;
}
foreach ($content['services'] as $id => $service) {
$this->parseDefinition($id, $service, $file);
}
}
/**
* Parses a definition.
*
* @param string $id
* @param array $service
* @param string $file
*
* @throws InvalidArgumentException When tags are invalid
*/
private function parseDefinition($id, $service, $file)
{
if (is_string($service) && 0 === strpos($service, '@')) {
$this->container->setAlias($id, substr($service, 1));
return;
} elseif (isset($service['alias'])) {
$public = !array_key_exists('public', $service) || (Boolean) $service['public'];
$this->container->setAlias($id, new Alias($service['alias'], $public));
return;
}
if (isset($service['parent'])) {
$definition = new DefinitionDecorator($service['parent']);
} else {
$definition = new Definition();
}
if (isset($service['class'])) {
$definition->setClass($service['class']);
}
if (isset($service['scope'])) {
$definition->setScope($service['scope']);
}
if (isset($service['synthetic'])) {
$definition->setSynthetic($service['synthetic']);
}
if (isset($service['synchronized'])) {
$definition->setSynchronized($service['synchronized']);
}
if (isset($service['lazy'])) {
$definition->setLazy($service['lazy']);
}
if (isset($service['public'])) {
$definition->setPublic($service['public']);
}
if (isset($service['abstract'])) {
$definition->setAbstract($service['abstract']);
}
if (isset($service['factory_class'])) {
$definition->setFactoryClass($service['factory_class']);
}
if (isset($service['factory_method'])) {
$definition->setFactoryMethod($service['factory_method']);
}
if (isset($service['factory_service'])) {
$definition->setFactoryService($service['factory_service']);
}
if (isset($service['file'])) {
$definition->setFile($service['file']);
}
if (isset($service['arguments'])) {
$definition->setArguments($this->resolveServices($service['arguments']));
}
if (isset($service['properties'])) {
$definition->setProperties($this->resolveServices($service['properties']));
}
if (isset($service['configurator'])) {
if (is_string($service['configurator'])) {
$definition->setConfigurator($service['configurator']);
} else {
$definition->setConfigurator(array($this->resolveServices($service['configurator'][0]), $service['configurator'][1]));
}
}
if (isset($service['calls'])) {
foreach ($service['calls'] as $call) {
$args = isset($call[1]) ? $this->resolveServices($call[1]) : array();
$definition->addMethodCall($call[0], $args);
}
}
if (isset($service['tags'])) {
if (!is_array($service['tags'])) {
throw new InvalidArgumentException(sprintf('Parameter "tags" must be an array for service "%s" in %s.', $id, $file));
}
foreach ($service['tags'] as $tag) {
if (!isset($tag['name'])) {
throw new InvalidArgumentException(sprintf('A "tags" entry is missing a "name" key for service "%s" in %s.', $id, $file));
}
$name = $tag['name'];
unset($tag['name']);
foreach ($tag as $attribute => $value) {
if (!is_scalar($value)) {
throw new InvalidArgumentException(sprintf('A "tags" attribute must be of a scalar-type for service "%s", tag "%s" in %s.', $id, $name, $file));
}
}
$definition->addTag($name, $tag);
}
}
$this->container->setDefinition($id, $definition);
}
/**
* Loads a YAML file.
*
* @param string $file
*
* @return array The file content
*/
protected function loadFile($file)
{
if (!stream_is_local($file)) {
throw new InvalidArgumentException(sprintf('This is not a local file "%s".', $file));
}
if (!file_exists($file)) {
throw new InvalidArgumentException(sprintf('The service file "%s" is not valid.', $file));
}
if (null === $this->yamlParser) {
$this->yamlParser = new YamlParser();
}
return $this->validate($this->yamlParser->parse(file_get_contents($file)), $file);
}
/**
* Validates a YAML file.
*
* @param mixed $content
* @param string $file
*
* @return array
*
* @throws InvalidArgumentException When service file is not valid
*/
private function validate($content, $file)
{
if (null === $content) {
return $content;
}
if (!is_array($content)) {
throw new InvalidArgumentException(sprintf('The service file "%s" is not valid.', $file));
}
foreach (array_keys($content) as $namespace) {
if (in_array($namespace, array('imports', 'parameters', 'services'))) {
continue;
}
if (!$this->container->hasExtension($namespace)) {
$extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getAlias(); }, $this->container->getExtensions()));
throw new InvalidArgumentException(sprintf(
'There is no extension able to load the configuration for "%s" (in %s). Looked for namespace "%s", found %s',
$namespace,
$file,
$namespace,
$extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none'
));
}
}
return $content;
}
/**
* Resolves services.
*
* @param string $value
*
* @return Reference
*/
private function resolveServices($value)
{
if (is_array($value)) {
$value = array_map(array($this, 'resolveServices'), $value);
} elseif (is_string($value) && 0 === strpos($value, '@')) {
if (0 === strpos($value, '@@')) {
$value = substr($value, 1);
$invalidBehavior = null;
} elseif (0 === strpos($value, '@?')) {
$value = substr($value, 2);
$invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
} else {
$value = substr($value, 1);
$invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
}
if ('=' === substr($value, -1)) {
$value = substr($value, 0, -1);
$strict = false;
} else {
$strict = true;
}
if (null !== $invalidBehavior) {
$value = new Reference($value, $invalidBehavior, $strict);
}
}
return $value;
}
/**
* Loads from Extensions
*
* @param array $content
*/
private function loadFromExtensions($content)
{
foreach ($content as $namespace => $values) {
if (in_array($namespace, array('imports', 'parameters', 'services'))) {
continue;
}
if (!is_array($values)) {
$values = array();
}
$this->container->loadFromExtension($namespace, $values);
}
}
}
| {
"pile_set_name": "Github"
} |
#ifndef __LIBXML_WIN32_CONFIG__
#define __LIBXML_WIN32_CONFIG__
#define HAVE_CTYPE_H
#define HAVE_STDARG_H
#define HAVE_MALLOC_H
#define HAVE_ERRNO_H
#define SEND_ARG2_CAST
#define GETHOSTBYNAME_ARG_CAST
#if defined(_WIN32_WCE)
#undef HAVE_ERRNO_H
#include <windows.h>
#include "wincecompat.h"
#else
#define HAVE_SYS_STAT_H
#define HAVE__STAT
#define HAVE_STAT
#define HAVE_STDLIB_H
#define HAVE_TIME_H
#define HAVE_FCNTL_H
#include <io.h>
#include <direct.h>
#endif
#include <libxml/xmlversion.h>
#ifndef ICONV_CONST
#define ICONV_CONST const
#endif
#ifdef NEED_SOCKETS
#include <wsockcompat.h>
#endif
/*
* Windows platforms may define except
*/
#undef except
#define HAVE_ISINF
#define HAVE_ISNAN
#include <math.h>
#if defined(_MSC_VER) || defined(__BORLANDC__)
/* MS C-runtime has functions which can be used in order to determine if
a given floating-point variable contains NaN, (+-)INF. These are
preferred, because floating-point technology is considered propriatary
by MS and we can assume that their functions know more about their
oddities than we do. */
#include <float.h>
/* Bjorn Reese figured a quite nice construct for isinf() using the _fpclass
function. */
#ifndef isinf
#define isinf(d) ((_fpclass(d) == _FPCLASS_PINF) ? 1 \
: ((_fpclass(d) == _FPCLASS_NINF) ? -1 : 0))
#endif
/* _isnan(x) returns nonzero if (x == NaN) and zero otherwise. */
#ifndef isnan
#define isnan(d) (_isnan(d))
#endif
#else /* _MSC_VER */
#ifndef isinf
static int isinf (double d) {
int expon = 0;
double val = frexp (d, &expon);
if (expon == 1025) {
if (val == 0.5) {
return 1;
} else if (val == -0.5) {
return -1;
} else {
return 0;
}
} else {
return 0;
}
}
#endif
#ifndef isnan
static int isnan (double d) {
int expon = 0;
double val = frexp (d, &expon);
if (expon == 1025) {
if (val == 0.5) {
return 0;
} else if (val == -0.5) {
return 0;
} else {
return 1;
}
} else {
return 0;
}
}
#endif
#endif /* _MSC_VER */
#if defined(_MSC_VER)
#define mkdir(p,m) _mkdir(p)
#if _MSC_VER < 1900
#define snprintf _snprintf
#endif
#if _MSC_VER < 1500
#define vsnprintf(b,c,f,a) _vsnprintf(b,c,f,a)
#endif
#elif defined(__MINGW32__)
#define mkdir(p,m) _mkdir(p)
#endif
/* Threading API to use should be specified here for compatibility reasons.
This is however best specified on the compiler's command-line. */
#if defined(LIBXML_THREAD_ENABLED)
#if !defined(HAVE_PTHREAD_H) && !defined(HAVE_WIN32_THREADS) && !defined(_WIN32_WCE)
#define HAVE_WIN32_THREADS
#endif
#endif
/* Some third-party libraries far from our control assume the following
is defined, which it is not if we don't include windows.h. */
#if !defined(FALSE)
#define FALSE 0
#endif
#if !defined(TRUE)
#define TRUE (!(FALSE))
#endif
#endif /* __LIBXML_WIN32_CONFIG__ */
| {
"pile_set_name": "Github"
} |
<!-- ================================================ -->
<!-- Adempiere Patch Builder -->
<!-- ================================================ -->
<!-- $Header: /cvs/adempiere/utils_dev/build_patch_template.xml -->
<project name="adempiere" default="complete" basedir="../">
<description>
This buildfile is used to build minor version install patches for the Adempiere system.
It includes patches.jar and all other supporting files. The patch is designed to be
extracted over the ADEMPIERE_HOME directory, replacing existing files with new ones.
Patches should be inclusive of all previous patches, so only the latest patch needs
to be installed.
To use the template, copy the file giving it a name specific to the patch and edit it to
include the necessary files for the patch. Run the target "complete" to build the patch
and install it. The target "dist" will generate the patch archives without the install.
</description>
<!-- set global properties for this build -->
<!--<property environment="env"/>-->
<import file="../utils_dev/properties.xml"/>
<property name="base.dir" value="."/>
<property name="src" value="src"/>
<property name="patch.dir" value="install/patch"/>
<!-- Set the package name. This will be used to name the archives.
This should be in the form patches_[bas_version]_[branch]_[date]
-->
<property name="base_version" value="380LTS"/>
<property name="patch_branch" value="hotfix#002"/>
<property name="patch_date" value="20150501"/>
<property name="patch.name" value="patches_${base_version}_${patch_branch}_${patch_date}"/>
<target name="clean">
<!-- Delete the ${patch.dir} directory tree -->
<delete dir="${patch.dir}"/>
</target>
<target name="init" description="initialization target" depends="clean">
<echo message="=========== Build Adempiere Patch - ${env.ENCODING}"/>
<!-- Create the time stamp -->
<tstamp/>
<!-- create the package directory structure used by compile -->
<mkdir dir="${patch.dir}"/>
<mkdir dir="${patch.dir}/jar"/>
<mkdir dir="${patch.dir}/jar/src"/>
</target>
<!-- ======================================================= -->
<!-- Create patches.jar -->
<!-- ======================================================= -->
<target name="build_patches.jar" depends="init">
<!-- This target builds the patches.jar file. It copies all required class
files to the patches/jar/src/patches directory. The list of files is
generated by running git diff and then determining all the class
files from the output. The files included below are for example.
-->
<mkdir dir="${patch.dir}/jar/src/patches"/>
<copy todir="${patch.dir}/jar/src/patches">
<fileset dir="${base.dir}/base/build">
<include name="org/compiere/model/I_M_Locator.class"/>
<include name="org/compiere/model/MLocator.class"/>
<include name="org/compiere/model/MLocatorLookup.class"/>
<include name="org/compiere/model/X_M_Locator.class"/>
</fileset>
<fileset dir="${base.dir}/client/build">
<include name="org/compiere/grid/ed/VLocatorDialog.class"/>
</fileset>
</copy>
<!-- put everything into the patches.jar file -->
<jar
jarfile="${patch.dir}/jar/patches.jar"
index="yes"
duplicate="preserve">
<fileset dir="${patch.dir}/jar/src/patches"/>
<manifest>
<attribute name="Specification-Title" value="Patches"/>
<attribute name="Specification-Version" value="ADempiere ${base_version} ${patch_branch} ${patch_date}"/>
<attribute name="Specification-Vendor" value="Adempiere.org"/>
<attribute name="Implementation-Title" value="ADempiere ${base_version} ${patch_branch} ${patch_date}"/>
<attribute name="Implementation-Version" value="${base_version} ${patch_branch} ${patch_date}"/>
<attribute name="Implementation-Vendor" value="${env.ADEMPIERE_VENDOR}"/>
<attribute name="Implementation-URL" value="http://www.adempiere.org"/>
</manifest>
</jar>
<copy todir="${base.dir}/install/patch/Adempiere/lib">
<fileset dir="${patch.dir}/jar">
<include name="patches.jar"/>
</fileset>
</copy>
</target>
<!-- ======================================================= -->
<!-- Create zkpatches.jar -->
<!-- ======================================================= -->
<target name="build_zkpatches.jar" depends="init">
<!-- This target builds the zkpatches.jar file. It copies all required class
files to the patches/jar/src/zkpatches directory. The list of files is
generated by running git diff and then determining all the class
files from the output. The files included below are for example. Add the
.class and resource files to include in the zkpatch.jar. The top
directory in the .jar should be WEB-INF
-->
<mkdir dir="${patch.dir}/jar/src/zkpatches"/>
<copy todir="${patch.dir}/jar/src/zkpatches">
<fileset dir="${base.dir}/zkwebui/">
<include name="WEB-INF/classes/org/adempiere/webui/window/WLocatorDialog.class"/>
</fileset>
</copy>
<!-- put everything into the patches.jar file -->
<jar
jarfile="${patch.dir}/jar/zkpatches.jar"
index="yes"
duplicate="preserve">
<fileset dir="${patch.dir}/jar/src/zkpatches"/>
<manifest>
<attribute name="Specification-Title" value="ZK Patches"/>
<attribute name="Specification-Version" value="ADempiere ${base_version} ${patch_branch} ${patch_date}"/>
<attribute name="Specification-Vendor" value="Adempiere.org"/>
<attribute name="Implementation-Title" value="ADempiere ${base_version} ${patch_branch} ${patch_date}"/>
<attribute name="Implementation-Version" value="${base_version} ${patch_branch} ${patch_date}"/>
<attribute name="Implementation-Vendor" value="${env.ADEMPIERE_VENDOR}"/>
<attribute name="Implementation-URL" value="http://www.adempiere.org"/>
</manifest>
</jar>
<copy todir="${base.dir}/install/patch/Adempiere/lib">
<fileset dir="${patch.dir}/jar">
<include name="zkpatches.jar"/>
</fileset>
</copy>
</target>
<!-- ======================================================= -->
<!-- Create Patch Distribution Archives -->
<!-- ======================================================= -->
<target name="dist" depends="build_patches.jar, build_zkpatches.jar">
<!-- This target builds the zip and tar archives file. It will include the
patches.jar, zkpatches.jar. Directories and files that also need to
be added to the archives should be copied into the ${patch.dir}/Adempiere/
directory using the same folder structure as the Adempiere install.
-->
<mkdir dir="${patch.dir}"/>
<mkdir dir="${patch.dir}/Adempiere"/>
<!-- Utils Directory -->
<mkdir dir="${patch.dir}/Adempiere/utils"/>
<copy todir="${patch.dir}/Adempiere/utils">
<fileset dir="${base.dir}/utils">
<include name="windows/Adempiere_Service_Install_64.bat" />
<include name="windows/Adempiere_Service_Uninstall_64.bat" />
</fileset>
</copy>
<!-- Migration Directory -->
<!-- Doesn't hurt to take all contents of the dist directory -->
<mkdir dir="${patch.dir}/Adempiere/migration"/>
<copy todir="${patch.dir}/Adempiere/migration">
<fileset dir="${base.dir}/migration/dist">
<include name="**/*.xml"/>
<include name="**/*.sql"/>
</fileset>
</copy>
<!-- JBoss Directory -->
<mkdir dir="${patch.dir}/Adempiere/jboss"/>
<copy todir="${patch.dir}/Adempiere/jboss/">
<fileset dir="${base.dir}/jboss">
<include name="bin/README-service.txt" />
<include name="bin/jbosssvc.exe" />
<include name="bin/jbossweb.x64.exe" />
<include name="bin/jbosswebw.x64.exe" />
<include name="bin/native/openssl.exe" />
<include name="bin/native/tcnative-1.dll" />
<include name="bin/service.bat" />
<include name="server/adempiere/deploy/jboss-web.deployer/serverTemplate.xml" />
</fileset>
</copy>
<!-- zkwebui Directory -->
<mkdir dir="${patch.dir}/Adempiere/zkwebui"/>
<copy todir="${patch.dir}/Adempiere/zkwebui/">
<fileset dir="${base.dir}/zkwebui">
<include name="images/AD10030HB.png"/>
<include name="theme/default/images/login-logo.png"/>
</fileset>
</copy>
<!-- Create Patch Install ZIP -->
<!-- This archive should be extracted over ADEMPIERE_HOME -->
<!-- It includes all patches and associated files. -->
<zip zipfile="${patch.dir}/${patch.name}.zip"
basedir="${patch.dir}"
includes="Adempiere/**" />
<!-- Create Install TAR -->
<tar longfile="gnu" tarfile="${patch.dir}/${patch.name}.tar.gz"
compression="gzip" >
<tarfileset dir="${patch.dir}" includes="Adempiere/**" excludes="Adempiere/**/*.sh" >
</tarfileset>
<!-- <tarfileset dir="${patch.dir}" includes="Adempiere/**/*.sh" filemode="755"> -->
<tarfileset dir="${patch.dir}" includes="Adempiere/**/*.sh">
</tarfileset>
</tar>
<!-- Create Checksums -->
<checksum file="${patch.dir}/${patch.name}.tar.gz"/>
<sleep milliseconds="2000"/>
<loadfile property="myfile" srcFile="${patch.dir}/${patch.name}.tar.gz.MD5">
<filterchain>
<striplinebreaks/>
</filterchain>
</loadfile>
<concat destfile="${patch.dir}/${patch.name}.tar.gz.MD5">${myfile} ${patch.name}.tar.gz</concat>
<!-- Test with md5sum -c Adempiere_251.zip.MD5 -->
<checksum file="${patch.dir}/${patch.name}.zip"/>
<sleep milliseconds="2000"/>
<loadfile property="myfile2" srcFile="${patch.dir}/${patch.name}.zip.MD5">
<filterchain>
<striplinebreaks/>
</filterchain>
</loadfile>
<concat destfile="${patch.dir}/${patch.name}.zip.MD5">${myfile2} ${patch.name}.zip</concat>
</target>
<!-- ================================================ -->
<!-- Adempiere Local Install -->
<!-- ================================================ -->
<target name="install" depends="">
<echo message="=========== Install Adempiere Patches"/>
<copy todir="${env.ADEMPIERE_INSTALL}" verbose="true">
<fileset dir="install/patch" includes="${patch.name}.*" />
</copy>
<!-- Delete Existing stuff, but not utils + data -->
<delete failonerror="false" includeEmptyDirs="true">
<fileset dir="${env.ADEMPIERE_HOME}/migration" includes="**/*" />
<fileset dir="${env.ADEMPIERE_HOME}/lib"/>
<fileset dir="${env.ADEMPIERE_HOME}/jboss"/>
</delete>
<condition property="isWindows">
<os family="windows" />
</condition>
<antcall target="installWin"></antcall>
<antcall target="installNonWin"></antcall>
<echo message="Install of the patch was completed. Execute RUN_Setup or RUN_SilentSetup"/>
<echo message="and then RUN_MigrateXML if new migrations are included in the patch."/>
</target>
<target name="installWin" description="Environment dependent" if="isWindows">
<!-- Unzip Install File -->
<unzip src="install/patch/${patch.name}.zip"
dest="${env.ADEMPIERE_ROOT}"
overwrite="yes"/>
</target>
<target name="installNonWin" description="Environment dependent" unless="isWindows">
<!-- Untar Install File -->
<gunzip src="install/patch/${patch.name}.tar.gz"
dest="${env.ADEMPIERE_ROOT}" />
</target>
<!-- ================================================ -->
<!-- complete -->
<!-- ================================================ -->
<target name="complete" depends="dist, install">
</target>
</project>
| {
"pile_set_name": "Github"
} |
""" Module implementing the Condition Augmentation """
import torch as th
class ConditionAugmentor(th.nn.Module):
""" Perform conditioning augmentation
from the paper -> https://arxiv.org/abs/1710.10916 (StackGAN++)
uses the reparameterization trick from VAE paper.
"""
def __init__(self, input_size, latent_size, use_eql=True, device=th.device("cpu")):
"""
constructor of the class
:param input_size: input size to the augmentor
:param latent_size: required output size
:param use_eql: boolean for whether to use equalized learning rate
:param device: device on which to run the Module
"""
super(ConditionAugmentor, self).__init__()
assert latent_size % 2 == 0, "Latent manifold has odd number of dimensions"
# state of the object
self.device = device
self.input_size = input_size
self.latent_size = latent_size
# required modules:
if use_eql:
from pro_gan_pytorch.CustomLayers import _equalized_linear
self.transformer = _equalized_linear(self.input_size, 2 * self.latent_size).to(device)
else:
self.transformer = th.nn.Linear(self.input_size, 2 * self.latent_size).to(device)
def forward(self, x, epsilon=1e-12):
"""
forward pass (computations)
:param x: input
:param epsilon: a small noise added for numerical stability
:return: c_not_hat, mus, sigmas => augmented text embeddings, means, stds
"""
from torch.nn.functional import relu
# apply the feed forward layer:
combined = self.transformer(x)
# use the reparameterization trick
mid_point = self.latent_size
mus, sigmas = combined[:, :mid_point], combined[:, mid_point:]
# mus don't need to be transformed, but sigmas cannot be negative.
# so, we'll apply a ReLU on top of sigmas
sigmas = relu(sigmas) # hopefully the network will learn a good sigma mapping
sigmas = sigmas + epsilon # small noise added for stability
epsilon = th.randn(*mus.shape).to(self.device)
c_not_hat = (epsilon * sigmas) + mus
return c_not_hat, mus, sigmas
| {
"pile_set_name": "Github"
} |
export default function(ref) {
return {
methods: {
focus() {
this.$refs[ref].focus();
}
}
};
};
| {
"pile_set_name": "Github"
} |
%verify "executed"
%include "mips/binopLit8.S" {"instr":"div zero, a0, a1; mflo a0", "chkzero":"1"}
| {
"pile_set_name": "Github"
} |
/*
* uDig - User Friendly Desktop Internet GIS client
* http://udig.refractions.net
* (C) 2012, Refractions Research Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html), and the Refractions BSD
* License v1.0 (http://udig.refractions.net/files/bsd3-v10.html).
*/
package org.locationtech.udig.ui;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.junit.Before;
import org.junit.Test;
public class ShutdownTaskListTest {
private ShutdownTaskList list;
@Before
public void setUp() throws Exception {
list = new ShutdownTaskList();
}
@Test
public void testPostShutdown() {
final boolean[] ran = new boolean[1];
ran[0] = false;
list.addPostShutdownTask(new TestShutdownTask(){
@Override
public int getProgressMonitorSteps() {
return 6;
}
@Override
public void postShutdown( IProgressMonitor monitor, IWorkbench workbench ) {
ran[0] = true;
}
@Override
public void handlePostShutdownException( Throwable t) {
throw (RuntimeException)t;
}
});
list.postShutdown(PlatformUI.getWorkbench());
assertTrue(ran[0]);
// now handle case where exception is thrown.
ran[0] = false;
final boolean[] exceptionHandled = new boolean[1];
exceptionHandled[0] = false;
final RuntimeException exception = new RuntimeException();
list=new ShutdownTaskList();
list.addPostShutdownTask(new TestShutdownTask(){
@Override
public int getProgressMonitorSteps() {
return 6;
}
@Override
public void postShutdown( IProgressMonitor monitor, IWorkbench workbench ) {
ran[0] = true;
throw exception;
}
@Override
public void handlePostShutdownException( Throwable t ) {
assertEquals(exception, t);
exceptionHandled[0] = true;
}
});
list.postShutdown(PlatformUI.getWorkbench());
assertTrue(ran[0]);
assertTrue(exceptionHandled[0]);
}
@Test
public void testPreShutdown() {
final boolean[] ran = new boolean[1];
ran[0] = false;
final boolean[] forcedVal = new boolean[1];
forcedVal[0]=false;
final boolean[] retVal = new boolean[1];
retVal[0]=false;
list.addPreShutdownTask(new TestShutdownTask(){
@Override
public int getProgressMonitorSteps() {
return 6;
}
@Override
public boolean preShutdown( IProgressMonitor subMonitor, IWorkbench workbench,
boolean forced ) {
assertNotNull(subMonitor);
assertEquals(forcedVal[0], forced);
ran[0] = true;
return retVal[0];
}
@Override
public boolean handlePreShutdownException( Throwable t, boolean forced ) {
if( t instanceof RuntimeException)
throw (RuntimeException)t;
else
throw (Error)t;
}
});
assertFalse(list.preShutdown(PlatformUI.getWorkbench(),forcedVal[0]));
assertTrue(ran[0]);
ran[0]=false;
retVal[0]=true;
forcedVal[0]=false;
assertTrue(list.preShutdown(PlatformUI.getWorkbench(),forcedVal[0]));
assertTrue(ran[0]);
ran[0]=false;
retVal[0]=false;
forcedVal[0]=true;
assertTrue(list.preShutdown(PlatformUI.getWorkbench(),forcedVal[0]));
assertTrue(ran[0]);
// now handle case where exception is thrown.
ran[0] = false;
final boolean[] exceptionHandled = new boolean[1];
exceptionHandled[0] = false;
final RuntimeException exception = new RuntimeException();
list=new ShutdownTaskList();
list.addPreShutdownTask(new TestShutdownTask(){
@Override
public int getProgressMonitorSteps() {
return 6;
}
@Override
public boolean preShutdown( IProgressMonitor subMonitor, IWorkbench workbench,
boolean forced ) {
assertNotNull(subMonitor);
ran[0] = true;
throw exception;
}
@Override
public boolean handlePreShutdownException( Throwable t, boolean forced ) {
assertEquals(exception, t);
exceptionHandled[0] = true;
return retVal[0];
}
});
exceptionHandled[0] = false;
ran[0]=false;
retVal[0]=true;
forcedVal[0]=true;
assertTrue(list.preShutdown(PlatformUI.getWorkbench(),forcedVal[0]));
assertTrue(ran[0]);
assertTrue(exceptionHandled[0]);
ran[0]=false;
exceptionHandled[0] = false;
retVal[0]=false;
forcedVal[0]=true;
assertTrue(list.preShutdown(PlatformUI.getWorkbench(),forcedVal[0]));
assertTrue(ran[0]);
assertTrue(exceptionHandled[0]);
ran[0]=false;
exceptionHandled[0] = false;
retVal[0]=true;
forcedVal[0]=false;
assertTrue(list.preShutdown(PlatformUI.getWorkbench(),forcedVal[0]));
assertTrue(ran[0]);
assertTrue(exceptionHandled[0]);
}
class TestShutdownTask implements PreShutdownTask, PostShutdownTask {
public int getProgressMonitorSteps() {
throw new RuntimeException("Not allowed"); //$NON-NLS-1$
}
public void handlePostShutdownException( Throwable t ) {
throw new RuntimeException("Not allowed"); //$NON-NLS-1$
}
public boolean handlePreShutdownException( Throwable t, boolean forced ) {
throw new RuntimeException("Not allowed"); //$NON-NLS-1$
}
public void postShutdown( IProgressMonitor subMonitor, IWorkbench workbench ) {
throw new RuntimeException("Not allowed"); //$NON-NLS-1$
}
public boolean preShutdown( IProgressMonitor subMonitor, IWorkbench workbench,
boolean forced ) {
throw new RuntimeException("Not allowed"); //$NON-NLS-1$
}
}
}
| {
"pile_set_name": "Github"
} |
<!ELEMENT gridbag (row)*>
<!ELEMENT row (cell)*>
<!ELEMENT cell (bean)>
<!ATTLIST cell gridx CDATA #IMPLIED>
<!ATTLIST cell gridy CDATA #IMPLIED>
<!ATTLIST cell gridwidth CDATA "1">
<!ATTLIST cell gridheight CDATA "1">
<!ATTLIST cell weightx CDATA "0">
<!ATTLIST cell weighty CDATA "0">
<!ATTLIST cell fill (NONE|BOTH|HORIZONTAL|VERTICAL) "NONE">
<!ATTLIST cell anchor
(CENTER|NORTH|NORTHEAST|EAST|SOUTHEAST|SOUTH|SOUTHWEST|WEST|NORTHWEST) "CENTER">
<!ATTLIST cell ipadx CDATA "0">
<!ATTLIST cell ipady CDATA "0">
<!ELEMENT bean (class, property*)>
<!ATTLIST bean id ID #IMPLIED>
<!ELEMENT class (#PCDATA)>
<!ELEMENT property (name, value)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT value (int|string|boolean|bean)>
<!ELEMENT int (#PCDATA)>
<!ELEMENT string (#PCDATA)>
<!ELEMENT boolean (#PCDATA)>
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <Foundation/NSObject.h>
@class NSString;
@interface VSCacheUpdateRequest : NSObject
{
NSString *_modelID;
NSString *_classID;
}
- (id)description;
- (id)coalescedRequest:(id)arg1;
- (id)classIdentifier;
- (id)modelIdentifier;
- (void)dealloc;
- (id)initWithModelIdentifier:(id)arg1 classIdentifier:(id)arg2;
@end
| {
"pile_set_name": "Github"
} |
// Copyright 2018 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
syntax = "proto3";
import "google/protobuf/struct.proto";
package istio.networking.v1alpha3;
option go_package = "istio.io/api/networking/v1alpha3";
// `EnvoyFilter` describes Envoy proxy-specific filters that can be used to
// customize the Envoy proxy configuration generated by Istio networking
// subsystem (Pilot). This feature must be used with care, as incorrect
// configurations could potentially destabilize the entire mesh.
//
// NOTE 1: Since this is break glass configuration, there will not be any
// backward compatibility across different Istio releases. In other words,
// this configuration is subject to change based on internal implementation
// of Istio networking subsystem.
//
// NOTE 2: When multiple EnvoyFilters are bound to the same workload, all filter
// configurations will be processed sequentially in order of creation time.
// The behavior is undefined if multiple EnvoyFilter configurations conflict
// with each other.
//
// The following example for Kubernetes enables Envoy's Lua filter for all
// inbound calls arriving at service port 8080 of the reviews service pod with
// labels "app: reviews".
//
// ```yaml
// apiVersion: networking.istio.io/v1alpha3
// kind: EnvoyFilter
// metadata:
// name: reviews-lua
// spec:
// workloadLabels:
// app: reviews
// filters:
// - listenerMatch:
// portNumber: 8080
// listenerType: SIDECAR_INBOUND #will match with the inbound listener for reviews:8080
// filterName: envoy.lua
// filterType: HTTP
// filterConfig:
// inlineCode: |
// ... lua code ...
// ```
message EnvoyFilter {
// One or more labels that indicate a specific set of pods/VMs whose
// proxies should be configured to use these additional filters. The
// scope of label search is platform dependent. On Kubernetes, for
// example, the scope includes pods running in all reachable
// namespaces. Omitting the selector applies the filter to all proxies in
// the mesh.
// NOTE: There can be only one EnvoyFilter bound to a specific workload.
// The behavior is undefined if multiple EnvoyFilter configurations are
// specified for the same workload.
map<string, string> workload_labels = 1;
// Select a listener to add the filter to based on the match conditions.
// All conditions specified in the ListenerMatch must be met for the filter
// to be applied to a listener.
message ListenerMatch {
// The service port/gateway port to which traffic is being
// sent/received. If not specified, matches all listeners. Even though
// inbound listeners are generated for the instance/pod ports, only
// service ports should be used to match listeners.
uint32 port_number = 1;
// Instead of using specific port numbers, a set of ports matching a
// given port name prefix can be selected. E.g., "mongo" selects ports
// named mongo-port, mongo, mongoDB, MONGO, etc. Matching is case
// insensitive.
string port_name_prefix = 2;
enum ListenerType {
// All listeners
ANY = 0;
// Inbound listener in sidecar
SIDECAR_INBOUND = 1;
// Outbound listener in sidecar
SIDECAR_OUTBOUND = 2;
// Gateway listener
GATEWAY = 3;
};
// Inbound vs outbound sidecar listener or gateway listener. If not specified,
// matches all listeners.
ListenerType listener_type = 3;
enum ListenerProtocol {
// All protocols
ALL = 0;
// HTTP or HTTPS (with termination) / HTTP2/gRPC
HTTP = 1;
// Any non-HTTP listener
TCP = 2;
};
// Selects a class of listeners for the same protocol. If not
// specified, applies to listeners on all protocols. Use the protocol
// selection to select all HTTP listeners (includes HTTP2/gRPC/HTTPS
// where Envoy terminates TLS) or all TCP listeners (includes HTTPS
// passthrough using SNI).
ListenerProtocol listener_protocol = 4;
// One or more IP addresses to which the listener is bound. If
// specified, should match at least one address in the list.
repeated string address = 5;
};
// Indicates the relative index in the filter chain where the filter should be inserted.
message InsertPosition {
// Index/position in the filter chain.
enum Index {
// Insert first
FIRST = 0;
// Insert last
LAST = 1;
// Insert before the named filter.
BEFORE = 2;
// Insert after the named filter.
AFTER = 3;
};
// Position of this filter in the filter chain.
Index index = 1;
// If BEFORE or AFTER position is specified, specify the name of the
// filter relative to which this filter should be inserted.
string relative_to = 2;
};
// Envoy filters to be added to a network or http filter chain.
message Filter {
// Filter will be added to the listener only if the match conditions are true.
// If not specified, the filters will be applied to all listeners.
ListenerMatch listener_match = 1;
// Insert position in the filter chain. Defaults to FIRST
InsertPosition insert_position = 2;
enum FilterType {
// placeholder
INVALID = 0;
// Http filter
HTTP = 1;
// Network filter
NETWORK = 2;
};
// REQUIRED: The type of filter to instantiate.
FilterType filter_type = 3;
// REQUIRED: The name of the filter to instantiate. The name must match a supported
// filter _compiled into_ Envoy.
string filter_name = 4;
// REQUIRED: Filter specific configuration which depends on the filter being
// instantiated.
google.protobuf.Struct filter_config = 5;
};
// REQUIRED: Envoy network filters/http filters to be added to matching
// listeners. When adding network filters to http connections, care
// should be taken to ensure that the filter is added before
// envoy.http_connection_manager.
repeated Filter filters = 2;
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: cde85928c63ecd34d8a93b358f9bec68
timeCreated: 1474757106
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
<!doctype html>
<html>
<head>
<title>Dropdown Filter with Images List | jPList - jQuery Data Grid Controls</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- font libs -->
<link href="http://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css" />
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet" />
<!-- demo page styles -->
<link href="../dist/css/jplist.demo-pages.min.css" rel="stylesheet" type="text/css" />
<!-- additional demo styles -->
<style>
.jplist .list{
background: transparent;
}
.jplist .list img{
margin: 0 15px 15px 0;
border: 3px solid #fff;
box-sizing: border-box;
float: left;
}
</style>
<!-- jQuery lib -->
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<!-- jPList core js and css -->
<link href="../dist/css/jplist.core.min.css" rel="stylesheet" type="text/css" />
<script src="../dist/js/jplist.core.min.js"></script>
<!-- filter dropdown bundle -->
<script src="../dist/js/jplist.filter-dropdown-bundle.min.js"></script>
<!-- jPList start -->
<script>
$('document').ready(function(){
$('#demo').jplist({
itemsBox: '.list'
,itemPath: 'img'
,panelPath: '.jplist-panel'
});
});
</script>
</head>
<body>
<!-- top bar -->
<div id="black-top-bar" class="box">
<div class="center">
<div class="box">
<!-- left menu -->
<ul id="black-top-bar-left-menu" class="hmenu left iphone-hidden">
<li class="glow">
<a title="" href="https://github.com/no81no/jplist/issues?state=open">
<i class="fa fa-asterisk"></i> Request a feature / <i class="fa fa-bug"></i> Report a bug
</a>
</li>
</ul>
<!-- social menu -->
<ul id="social-menu" class="hmenu right">
<li class="glow"><a title="" href="https://www.facebook.com/jplist"><i class="fa fa-facebook"></i> </a></li>
<li class="glow"><a rel="publisher" title="" href="https://plus.google.com/+Jplistjs"><i class="fa fa-google-plus"></i></a></li>
<li class="glow"><a title="" href="https://twitter.com/jquery_jplist"><i class="fa fa-twitter"></i></a></li>
<li class="glow"><a title="" href="https://github.com/no81no/jplist"><i class="fa fa-github"></i></a></li>
</ul>
</div>
</div>
</div>
<!-- header -->
<header id="header" class="box">
<div id="header-box" class="box">
<div class="center">
<div class="box">
<!-- logo -->
<div class="align-center text-shadow" id="logo">
<p>
<img title="jPList - jQuery Data Grid Controls" alt="jPList - jQuery Data Grid Controls" src="http://jplist.com/content/img/common/rocket.png" />
<a title="" href="http://jplist.com">jPList - jQuery Data Grid Controls</a>
</p>
<h1 class="h1-30-normal">Dropdown Filter with Images List</h1>
</div>
</div>
</div>
</div>
</header>
<!-- main content -->
<div class="box">
<div class="center">
<!--<><><><><><><><><><><><><><><><><><><><><><><><><><> DEMO START <><><><><><><><><><><><><><><><><><><><><><><><><><>-->
<div id="demo" class="box jplist" style="margin: 20px 0 50px 0">
<!-- ios button: show/hide panel -->
<div class="jplist-ios-button">
<i class="fa fa-sort"></i>
jPList Actions
</div>
<!-- panel-->
<div class="jplist-panel box panel-top">
<div
class="jplist-drop-down"
data-control-type="filter-drop-down"
data-control-name="category-filter"
data-control-action="filter">
<ul>
<li><span data-path="default">Filter by category</span></li>
<li><span data-path=".architecture">Architecture</span></li>
<li><span data-path=".christmas">Christmas</span></li>
<li><span data-path=".food">Food</span></li>
<li><span data-path=".nature">Nature</span></li>
<li><span data-path=".other">Other</span></li>
</ul>
</div>
</div>
<!-- data -->
<div class="list box text-shadow">
<img src="img/thumbs/arch-2.jpg" alt="" title="" class="architecture"/>
<img src="img/thumbs/autumn-1.jpg" alt="" title="" class="nature"/>
<img src="img/thumbs/boats-1.jpg" alt="" title="" class="other"/>
<img src="img/thumbs/arch-1.jpg" alt="" title="" class="architecture"/>
<img src="img/thumbs/book-1.jpg" alt="" title="" class="other"/>
<img src="img/thumbs/business-1.jpg" alt="" title="" class="other"/>
<img src="img/thumbs/car-1.jpg" alt="" title="" class="other"/>
<img src="img/thumbs/christmas-3.jpg" alt="" title="" class="christmas"/>
<img src="img/thumbs/city-1.jpg" alt="" title="" class="other"/>
<img src="img/thumbs/city-2.jpg" alt="" title="" class="architecture"/>
<img src="img/thumbs/coffee-grass.jpg" alt="" title="" class="food"/>
<img src="img/thumbs/coins.jpg" alt="" title="" class="other"/>
<img src="img/thumbs/crayons.jpg" alt="" title="" class="other"/>
<img src="img/thumbs/cupcakes.jpg" alt="" title="" class="food"/>
<img src="img/thumbs/eggs-nest.jpg" alt="" title="" class="nature"/>
<img src="img/thumbs/flower-1.jpg" alt="" title="" class="nature"/>
<img src="img/thumbs/flower-2.jpg" alt="" title="" class="nature"/>
<img src="img/thumbs/christmas-2.jpg" alt="" title="" class="christmas"/>
<img src="img/thumbs/flower-3.jpg" alt="" title="" class="nature"/>
<img src="img/thumbs/fountain.jpg" alt="" title="" class="other"/>
<img src="img/thumbs/leaves.jpg" alt="" title="" class="nature"/>
<img src="img/thumbs/lichterman.jpg" alt="" title="" class="nature"/>
<img src="img/thumbs/christmas-1.jpg" alt="" title="" class="christmas"/>
<img src="img/thumbs/pinecone.jpg" alt="" title="" class="nature"/>
<img src="img/thumbs/river-1.jpg" alt="" title="" class="nature"/>
<img src="img/thumbs/river-2.jpg" alt="" title="" class="nature"/>
<img src="img/thumbs/sunset-1.jpg" alt="" title="" class="nature"/>
<img src="img/thumbs/tree.jpg" alt="" title="" class="nature"/>
<img src="img/thumbs/winter-1.jpg" alt="" title="" class="nature"/>
<img src="img/thumbs/winter-2.jpg" alt="" title="" class="nature"/>
<img src="img/thumbs/winter-sun.jpg" alt="" title="" class="nature"/>
<img src="img/thumbs/woodstump.jpg" alt="" title="" class="nature"/>
</div>
<div class="box jplist-hidden text-shadow align-center">
<p>No results found</p>
</div>
</div>
<!--<><><><><><><><><><><><><><><><><><><><><><><><><><> DEMO END <><><><><><><><><><><><><><><><><><><><><><><><><><>-->
</div>
</div>
<!-- footer -->
<footer class="box" id="footer">
<div class="center">
<div class="box">
<p id="footer-content" class="align-center glow">
<a href="http://jplist.com" title="">Copyright © <script>document.write(new Date().getFullYear())</script> <b>jPList Software</b></a>
</p>
</div>
</div>
</footer>
</body>
</html> | {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=../../../../libc/type.c_char.html">
</head>
<body>
<p>Redirecting to <a href="../../../../libc/type.c_char.html">../../../../libc/type.c_char.html</a>...</p>
<script>location.replace("../../../../libc/type.c_char.html" + location.search + location.hash);</script>
</body>
</html> | {
"pile_set_name": "Github"
} |
XML error: missing security model when using multiple labels
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClCompile Include="..\..\HelloWorld\Helloworld.cpp" />
</ItemGroup>
</Project>
| {
"pile_set_name": "Github"
} |
// @flow
import { getPlayer } from 'shared/reducers/game';
import { getCurGame } from '../reducers/cur-game';
import { getCurUser } from '../reducers/cur-user';
import type { UserId, User, GameId } from 'shared/types/state';
import type {
ActionId,
JoinGameAction,
Action,
ThunkAction,
Dispatch,
GetState,
} from 'shared/types/actions';
export function joinGame(gameId: GameId, user: User): JoinGameAction {
return {
type: 'JOIN_GAME',
payload: {
actionId: getActionId(0),
prevActionId: 0,
userId: user.id,
gameId,
user,
},
};
}
export function playerReady(): ThunkAction {
return decorateGameAction(({ actionId, prevActionId, userId, gameId }) => ({
type: 'PLAYER_READY',
payload: {
actionId,
prevActionId,
userId,
gameId,
},
}));
}
export function playerPause(): ThunkAction {
return decorateGameAction(({ actionId, prevActionId, userId, gameId }) => ({
type: 'PLAYER_PAUSE',
payload: {
actionId,
prevActionId,
userId,
gameId,
},
}));
}
export function drop(rows: number): ThunkAction {
return decorateGameAction(({ actionId, prevActionId, userId, gameId }) => ({
type: 'DROP',
payload: {
actionId,
prevActionId,
userId,
gameId,
rows,
},
}));
}
export function moveLeft(): ThunkAction {
return decorateGameAction(({ actionId, prevActionId, userId, gameId }) => ({
type: 'MOVE_LEFT',
payload: {
actionId,
prevActionId,
userId,
gameId,
},
}));
}
export function moveRight(): ThunkAction {
return decorateGameAction(({ actionId, prevActionId, userId, gameId }) => ({
type: 'MOVE_RIGHT',
payload: {
actionId,
prevActionId,
userId,
gameId,
},
}));
}
export function rotate(): ThunkAction {
return decorateGameAction(({ actionId, prevActionId, userId, gameId }) => ({
type: 'ROTATE',
payload: {
actionId,
prevActionId,
userId,
gameId,
},
}));
}
export function enableAcceleration(): ThunkAction {
return decorateGameAction(({ actionId, prevActionId, userId, gameId }) => ({
type: 'ENABLE_ACCELERATION',
payload: {
actionId,
prevActionId,
userId,
gameId,
},
}));
}
export function disableAcceleration(): ThunkAction {
return decorateGameAction(({ actionId, prevActionId, userId, gameId }) => ({
type: 'DISABLE_ACCELERATION',
payload: {
actionId,
prevActionId,
userId,
gameId,
},
}));
}
export function appendPendingBlocks(): ThunkAction {
return decorateGameAction(({ actionId, prevActionId, userId, gameId }) => ({
type: 'APPEND_PENDING_BLOCKS',
payload: {
actionId,
prevActionId,
userId,
gameId,
},
}));
}
export function ping(): ThunkAction {
return decorateGameAction(({ actionId, prevActionId, userId, gameId }) => ({
type: 'PING',
payload: {
actionId,
prevActionId,
userId,
gameId,
time: Date.now(),
},
}));
}
type GameActionDecorator = ({
actionId: ActionId,
prevActionId: ActionId,
gameId: GameId,
userId: UserId,
}) => Action;
function decorateGameAction(fn: GameActionDecorator): ThunkAction {
return (dispatch: Dispatch, getState: GetState) => {
const state = getState();
const userId = getCurUser(state).id;
const curGame = getCurGame(state);
const player = getPlayer(curGame, userId);
const { lastActionId: prevActionId } = player;
const actionId = getActionId(prevActionId);
return dispatch(fn({ actionId, prevActionId, userId, gameId: curGame.id }));
};
}
function getActionId(prevActionId: ActionId): ActionId {
// Ensure action ids never duplicate (only relevant if two actions occur
// within the same millisecond)
return Math.max(Date.now(), prevActionId + 1);
}
| {
"pile_set_name": "Github"
} |
{
"type": "bundle",
"id": "bundle--c65924a0-8769-4eeb-8dc7-bf5cfaccf856",
"spec_version": "2.0",
"objects": [
{
"id": "relationship--82e1ab81-89f9-4d96-87fd-69d04c6710f3",
"created_by_ref": "identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5",
"description": "[Dragonfly 2.0](https://attack.mitre.org/groups/G0074) used a batch script to gather folder and file names from victim hosts.(Citation: US-CERT TA18-074A)",
"object_marking_refs": [
"marking-definition--fa42a846-8d90-4e51-bc29-71d5b4802168"
],
"external_references": [
{
"source_name": "US-CERT TA18-074A",
"description": "US-CERT. (2018, March 16). Alert (TA18-074A): Russian Government Cyber Activity Targeting Energy and Other Critical Infrastructure Sectors. Retrieved June 6, 2018.",
"url": "https://www.us-cert.gov/ncas/alerts/TA18-074A"
}
],
"source_ref": "intrusion-set--76d59913-1d24-4992-a8ac-05a3eb093f71",
"relationship_type": "uses",
"target_ref": "attack-pattern--7bc57495-ea59-4380-be31-a64af124ef18",
"type": "relationship",
"modified": "2019-03-22T20:13:49.460Z",
"created": "2018-10-17T00:14:20.652Z"
}
]
} | {
"pile_set_name": "Github"
} |
<?php
declare(strict_types=1);
namespace Oneup\UploaderBundle\Tests\Uploader\Naming;
use Oneup\UploaderBundle\Uploader\File\FilesystemFile;
use Oneup\UploaderBundle\Uploader\Naming\UniqidNamer;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class UniqidNamerTest extends TestCase
{
public function testNamerReturnsName(): void
{
/** @var FilesystemFile&MockObject $file */
$file = $this->createMock(FilesystemFile::class);
$file
->method('getExtension')
->willReturn('jpeg')
;
$namer = new UniqidNamer();
$this->assertRegExp('/[a-z0-9]{13}.jpeg/', $namer->name($file));
}
public function testNamerReturnsUniqueName(): void
{
/** @var FilesystemFile&MockObject $file */
$file = $this->createMock(FilesystemFile::class);
$file
->method('getExtension')
->willReturn('jpeg')
;
$namer = new UniqidNamer();
// get two different names
$name1 = $namer->name($file);
$name2 = $namer->name($file);
$this->assertNotSame($name1, $name2);
}
}
| {
"pile_set_name": "Github"
} |
# stof
* string[meta header]
* std[meta namespace]
* function[meta id-type]
* cpp11[meta cpp]
```cpp
namespace std {
float stof(const std::string& str, std::size_t* idx = nullptr); // (1)
float stof(const std::wstring& str, std::size_t* idx = nullptr); // (2)
}
```
## 概要
文字列`str`を数値として読み取って、`float`型の値に変換する。
## 効果
パラメータ`str`が`string`型であれば`std::strtof(str.c_str(), &end)`、`wstring`であれば`std::wcstof(str.c_str(), &end)`を呼び出して、その戻り値を返す。
パラメータ`idx`が非`nullptr`の場合、変換に使用されなかった要素のインデックス(`end - str.c_str()`)が格納される。
## 戻り値
変換して得られた数値が返される。
## 例外
- 数値への変換が行われなかった場合、[`std::invalid_argument`](/reference/stdexcept.md)が送出される。
- 以下の条件に合致した場合、[`std::out_of_range`](/reference/stdexcept.md)が送出される。
- `std::strtof()`関数が[`errno`](/reference/cerrno/errno.md)変数に[`ERANGE`](/reference/cerrno.md)を設定した場合
- 結果が範囲外の値になった場合 (C++14)
## 備考
### errnoの扱い
- Visual C++ 11やGCC (libstdc++) 4.8.2では、この関数を呼び出すと`errno`の値が変更される。
- Clang (libc++) 3.3では、この関数の呼び出し前後で`errno`の値は変化しない。
### グローバルロケールの影響
この関数は、`setlocale()`関数により挙動が変化する。
- `strtof()`関数での文字列先頭の空白を読み飛ばす処理に、`<cctype>`の`isspace()`関数が使用される。
- 小数点記号は`LC_NUMERIC`で指定されたものが使用される。
## 例
```cpp example
#include <iostream>
#include <string>
int main()
{
// 10進法での変換
std::cout << "---- decimal point" << std::endl;
float a = std::stof("1.5"); // std::stof("1.5", nullptr);
std::cout << a << std::endl;
float aw = std::stof(L"1."); // std::stof(L"1.", nullptr);
std::cout << aw << std::endl;
// 指数表記の変換
std::cout << "---- base = 8" << std::endl;
float b = std::stof("0.5e3", nullptr);
std::cout << b << std::endl;
float bw = std::stof(L".25e3", nullptr);
std::cout << bw << std::endl;
// 16進法での変換
std::cout << "---- base = 16" << std::endl;
float c = std::stof("0x1.2P3", nullptr);
std::cout << c << std::endl;
float cw = std::stof(L"0x1.2P4", nullptr);
std::cout << cw << std::endl;
// 2番目の仮引数の使用例
std::cout << "---- use of idx parameter" << std::endl;
std::string es = "30.75%";
std::size_t ei;
float e = std::stof(es, &ei);
std::cout << e << ' ' << es[ei] << std::endl;
std::wstring ews = L"32%";
std::size_t ewi;
float ew = std::stof(ews, &ewi);
std::cout << ew << ' ' << ewi << std::endl;
// 文字列先頭に空白がある場合
std::cout << "---- space character before number" << std::endl;
std::cout << std::stof(" -1") << std::endl;
std::cout << std::stof(L" -.25") << std::endl;
}
```
* std::stof[color ff0000]
### 出力例
```
1.5
1
500
250
---- base = 16
9
18
---- use of idx parameter
30.75 %
32 2
---- space character before number
-1
-0.25
```
## 実装例
```cpp
float stof(const std::string& str, std::size_t* idx = nullptr) {
const char* p = str.c_str();
char* end;
errno = 0;
double x = std::strtof(p, &end);
if (p == end) {
throw std::invalid_argument("stof");
}
if (errno == ERANGE) {
throw std::out_of_range("stof");
}
if (idx != nullptr) {
*idx = static_cast<std::size_t>(end - p);
}
return static_cast<float>(x);
}
float stof(const std::wstring& str, std::size_t* idx = nullptr) {
const wchar_t* p = str.c_str();
wchar_t* end;
errno = 0;
double x = std::wcstof(p, &end);
if (p == end) {
throw std::invalid_argument("stof");
}
if (errno == ERANGE) {
throw std::out_of_range("stof");
}
if (idx != nullptr) {
*idx = static_cast<std::size_t>(end - p);
}
return static_cast<float>(x);
}
```
* str.c_str()[link basic_string/c_str.md]
* std::invalid_argument[link /reference/stdexcept.md]
* std::out_of_range[link /reference/stdexcept.md]
* errno[link /reference/cerrno/errno.md]
* ERANGE[link /reference/cerrno.md]
## バージョン
### 言語
- C++11
### 処理系
- [Clang](/implementation.md#clang): ?
- [GCC](/implementation.md#gcc): ?
- [ICC](/implementation.md#icc): ?
- [Visual C++](/implementation.md#visual_cpp): 2010, 2012, 2013
ただし、Visual C++ 10.0, 11.0は十六進法に対応していない(12.0は未確認)。
## 関連リンク
### C標準ライブラリに由来する関数
- `atof`: `stold`は`atof`を`std::string`および`std::wsting`に対応させ、戻り値の型を`float`に変更したものと見なせる。
- `strtof`, `wcstof`: `stof`は`strtof`および`wcstof`をそれぞれ`std::string`と`std::wsting`に対応させたものと見なせる。
### ファミリー
- [`stoi`](stoi.md): 戻り値の型が`int`となったもの。
- [`stol`](stol.md): 戻り値の型が`long`となったもの。
- [`stoll`](stoll.md): 戻り値の型が`long long`となったもの。
- [`stoul`](stoul.md): 戻り値の型が`unsigned long`となったもの。
- [`stoull`](stoull.md): 戻り値の型が`unsigned long long`となったもの。
- (`stof`: この関数自身)
- [`stod`](stod.md): 戻り値の型が`double`となったもの。
- [`stold`](stold.md): 戻り値の型が`long double`となったもの。
### ロケール依存しない高速な変換関数
- [`from_chars`](/reference/charconv/from_chars.md)
## 参照
- [N2408 Simple Numeric Access Revision 2](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2408.html)
- [LWG Issue 2009. Reporting out-of-bound values on numeric string conversions](http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#2009)
| {
"pile_set_name": "Github"
} |
title: 微信公众号《五溪》专业技术类文章聚合
date: 2018-06-02 17:27:12
tags: 随想
---
## 2018
- [stdin and stdout which it's ?](https://mp.weixin.qq.com/s/2oeDG1B2Dtl5sDxTsLhWtg)
- [搭建 Private NPM](https://mp.weixin.qq.com/s/pBHSs2s3exylfDD-wt9p-g)
- [Go HTTP](https://mp.weixin.qq.com/s/DfBvuFbv92Nx4dCQIX90Og)
- [Go JSON](https://mp.weixin.qq.com/s/4pEtf8I5D6SFpTWYfEN76Q)
- [Go 标准库](https://mp.weixin.qq.com/s/JOlfMAAtiWNKJYyJweSkqw)
- [Go 如何调试你的应用程序](https://mp.weixin.qq.com/s/wHFMuuWZkgVyuh37VRrhrg)
- [Go 函数也是一等公民](https://mp.weixin.qq.com/s/SMUKl97JeFLj2bdELnGy1g)
- [Go Echo Web Framework](https://mp.weixin.qq.com/s/BlyQvkw84dBhs4mX_SB5DQ)
- [Go struct interface](https://mp.weixin.qq.com/s/OTWNvMzIYOVZEWNWS35Lhg)
- [Android远程调试Web页面](https://mp.weixin.qq.com/s/St8yuvDW8tdgsU0dSdvQUg)
- [为你的eggjs应用启用HTTPS](https://mp.weixin.qq.com/s/yClPCyduxBzJlqwb1ccd1A)
- [我的eggjs应用如何运维](https://mp.weixin.qq.com/s/7156sD97Af6TbJ2ZOnQ5pw)
- [简化的 eggjs debug](https://mp.weixin.qq.com/s/pQr4K0PMsDugomr8Hh9cSw)
- [eggjs工程与分析](https://mp.weixin.qq.com/s/9T_ouZuhGeDAxLwzd_jRrw)
- [使用Node.js开发以太坊ERC 20标准的代币](https://mp.weixin.qq.com/s/nb54Uis1VFTBtpTH4_TC-A)
## 2017
- [地球上最全的Weex踩坑攻略-出自大量实践与沉淀](https://mp.weixin.qq.com/s/hAjT4_deEKw9uIXC1SVe0Q)
- [从零开始,实现你的小程序](https://mp.weixin.qq.com/s/Q2vZgWdDXKAl2dvIlB2lrw)
- [Webpack迁移到Rollup](https://mp.weixin.qq.com/s/gnxH9CanYQAMAsidTnh_KA)
- [JavaScript的“并发模型”](https://mp.weixin.qq.com/s/h3QfVdWyzmiUt-HSSoiJjQ)
- [一行经脉让你看懂Weex Runtime的任督二脉](https://mp.weixin.qq.com/s/Z7Kp_xstwOU7ipLNERRQdA)
- [由构建读懂Vue2.0,为自己的定制实现添砖加瓦](https://mp.weixin.qq.com/s/x7XGIG_wrtDumjag9OJlOw)
- [观《Mr.Robot》到Web安全](https://mp.weixin.qq.com/s/irigHY6Hm8YPkv13NQJKqA)
## 2016
- [《课多周刊》机器人运营中心是如何玩转起来的](https://mp.weixin.qq.com/s/mVUUycMxKTuzEvoMO0Krvw) | {
"pile_set_name": "Github"
} |
// Generated by CoffeeScript 1.9.3
var Rule, StyleSheet;
Rule = require('./Rule');
module.exports = StyleSheet = (function() {
var self;
self = StyleSheet;
function StyleSheet() {
this._rulesBySelector = {};
}
StyleSheet.prototype.setRule = function(selector, styles) {
var key, val;
if (typeof selector === 'string') {
this._setRule(selector, styles);
} else if (typeof selector === 'object') {
for (key in selector) {
val = selector[key];
this._setRule(key, val);
}
}
return this;
};
StyleSheet.prototype._setRule = function(s, styles) {
var i, len, ref, selector;
ref = self.splitSelectors(s);
for (i = 0, len = ref.length; i < len; i++) {
selector = ref[i];
this._setSingleRule(selector, styles);
}
return this;
};
StyleSheet.prototype._setSingleRule = function(s, styles) {
var rule, selector;
selector = self.normalizeSelector(s);
if (!(rule = this._rulesBySelector[selector])) {
rule = new Rule(selector);
this._rulesBySelector[selector] = rule;
}
rule.setStyles(styles);
return this;
};
StyleSheet.prototype.getRulesFor = function(el) {
var ref, rule, rules, selector;
rules = [];
ref = this._rulesBySelector;
for (selector in ref) {
rule = ref[selector];
if (rule.selector.matches(el)) {
rules.push(rule);
}
}
return rules;
};
StyleSheet.normalizeSelector = function(selector) {
return selector.replace(/[\s]+/g, ' ').replace(/[\s]*([>\,\+]{1})[\s]*/g, '$1').trim();
};
StyleSheet.splitSelectors = function(s) {
return s.trim().split(',');
};
return StyleSheet;
})();
| {
"pile_set_name": "Github"
} |
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
object Macros {
def impl(c: Context) = {
c.universe.reify { implicitly[SourceLocation] }
}
implicit def sourceLocation: SourceLocation1 = macro impl
}
trait SourceLocation {
/** Source location of the outermost call */
val outer: SourceLocation
/** The name of the source file */
val fileName: String
/** The line number */
val line: Int
/** The character offset */
val charOffset: Int
}
case class SourceLocation1(val outer: SourceLocation, val fileName: String, val line: Int, val charOffset: Int) extends SourceLocation
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:background="@color/norm_grey"
android:layout_height="match_parent"
tools:context=".ui.activity.MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="52dp"
android:background="@color/colorPrimary"
app:titleTextColor="#ffffff">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="52dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textSize="24sp"
android:padding="4dp"
android:gravity="center"
android:textColor="#ffffff"
android:textStyle="bold"
android:text="Hoo"/>
<Space
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<ImageView
android:id="@+id/iv_camera"
android:layout_width="52dp"
android:layout_height="52dp"
android:padding="14dp"
android:src="@drawable/me_ic_camera"/>
</LinearLayout>
</androidx.appcompat.widget.Toolbar>
<fragment
android:id="@+id/my_nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
app:navGraph="@navigation/main_navigation"
app:defaultNavHost="true"
android:layout_height="0dp"
android:layout_marginBottom="10dp"
android:layout_weight="1"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bnv_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/white"
app:itemIconTint="@drawable/main_bottom_color_selector"
app:itemTextColor="@drawable/main_bottom_color_selector"
app:menu="@menu/menu_main"/>
</LinearLayout> | {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace Composite.Core.Extensions
{
internal static class DictionaryExtensionMethods
{
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TValue> createValue)
{
if (dictionary is ConcurrentDictionary<TKey, TValue> concurrentDictionary)
{
return concurrentDictionary.GetOrAdd(key, k => createValue());
}
TValue value;
if (dictionary.TryGetValue(key, out value))
{
return value;
}
lock (dictionary)
{
if (dictionary.TryGetValue(key, out value))
{
return value;
}
value = createValue();
dictionary.Add(key, value);
}
return value;
}
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TValue> createValue)
{
if (dictionary is ConcurrentDictionary<TKey, TValue> concurrentDictionary)
{
return concurrentDictionary.GetOrAdd(key, createValue);
}
TValue value;
if (dictionary.TryGetValue(key, out value))
{
return value;
}
lock (dictionary)
{
if (dictionary.TryGetValue(key, out value))
{
return value;
}
value = createValue(key);
dictionary.Add(key, value);
}
return value;
}
public static List<KeyValuePair<string, TValue>> SortByKeys<TValue>(this Dictionary<string, TValue> dictionary)
{
var result = dictionary.ToList();
result.Sort((a, b) => string.CompareOrdinal(a.Key, b.Key));
return result;
}
}
}
| {
"pile_set_name": "Github"
} |
/******************************************************************************
* Copyright (c) 2013, NVIDIA CORPORATION. All rights reserved.
*
* 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.
* * Neither the name of the NVIDIA CORPORATION 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 NVIDIA CORPORATION 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.
*
******************************************************************************/
/******************************************************************************
*
* Code and text by Sean Baxter, NVIDIA Research
* See http://nvlabs.github.io/moderngpu for repository and documentation.
*
******************************************************************************/
#pragma once
#include "deviceutil.cuh"
#include "../mgpudevice.cuh"
namespace mgpu {
template<MgpuBounds Bounds, typename IntT, typename It, typename T,
typename Comp>
MGPU_HOST_DEVICE void BinarySearchIt(It data, int& begin, int& end, T key,
int shift, Comp comp) {
IntT scale = (1<< shift) - 1;
int mid = (int)((begin + scale * end)>> shift);
T key2 = data[mid];
bool pred = (MgpuBoundsUpper == Bounds) ?
!comp(key, key2) :
comp(key2, key);
if(pred) begin = mid + 1;
else end = mid;
}
template<MgpuBounds Bounds, typename IntT, typename T, typename It,
typename Comp>
MGPU_HOST_DEVICE int BiasedBinarySearch(It data, int count, T key, int levels,
Comp comp) {
int begin = 0;
int end = count;
if(levels >= 4 && begin < end)
BinarySearchIt<Bounds, IntT>(data, begin, end, key, 9, comp);
if(levels >= 3 && begin < end)
BinarySearchIt<Bounds, IntT>(data, begin, end, key, 7, comp);
if(levels >= 2 && begin < end)
BinarySearchIt<Bounds, IntT>(data, begin, end, key, 5, comp);
if(levels >= 1 && begin < end)
BinarySearchIt<Bounds, IntT>(data, begin, end, key, 4, comp);
while(begin < end)
BinarySearchIt<Bounds, int>(data, begin, end, key, 1, comp);
return begin;
}
template<MgpuBounds Bounds, typename T, typename It, typename Comp>
MGPU_HOST_DEVICE int BinarySearch(It data, int count, T key, Comp comp) {
int begin = 0;
int end = count;
while(begin < end)
BinarySearchIt<Bounds, int>(data, begin, end, key, 1, comp);
return begin;
}
////////////////////////////////////////////////////////////////////////////////
// MergePath search
template<MgpuBounds Bounds, typename It1, typename It2, typename Comp>
MGPU_HOST_DEVICE int MergePath(It1 a, int aCount, It2 b, int bCount, int diag,
Comp comp) {
typedef typename std::iterator_traits<It1>::value_type T;
int begin = max(0, diag - bCount);
int end = min(diag, aCount);
while(begin < end) {
int mid = (begin + end)>> 1;
T aKey = a[mid];
T bKey = b[diag - 1 - mid];
bool pred = (MgpuBoundsUpper == Bounds) ?
comp(aKey, bKey) :
!comp(bKey, aKey);
if(pred) begin = mid + 1;
else end = mid;
}
return begin;
}
////////////////////////////////////////////////////////////////////////////////
// SegmentedMergePath search
template<typename InputIt, typename Comp>
MGPU_HOST_DEVICE int SegmentedMergePath(InputIt keys, int aOffset, int aCount,
int bOffset, int bCount, int leftEnd, int rightStart, int diag, Comp comp) {
// leftEnd and rightStart are defined from the origin, and diag is defined
// from aOffset.
// We only need to run a Merge Path search if the diagonal intersects the
// segment that strides the left and right halves (i.e. is between leftEnd
// and rightStart).
if(aOffset + diag <= leftEnd) return diag;
if(aOffset + diag >= rightStart) return aCount;
bCount = min(bCount, rightStart - bOffset);
int begin = max(max(leftEnd - aOffset, 0), diag - bCount);
int end = min(diag, aCount);
while(begin < end) {
int mid = (begin + end)>> 1;
int ai = aOffset + mid;
int bi = bOffset + diag - 1 - mid;
bool pred = !comp(keys[bi], keys[ai]);
if(pred) begin = mid + 1;
else end = mid;
}
return begin;
}
////////////////////////////////////////////////////////////////////////////////
// BalancedPath search
template<bool Duplicates, typename IntT, typename InputIt1, typename InputIt2,
typename Comp>
MGPU_HOST_DEVICE int2 BalancedPath(InputIt1 a, int aCount, InputIt2 b,
int bCount, int diag, int levels, Comp comp) {
typedef typename std::iterator_traits<InputIt1>::value_type T;
int p = MergePath<MgpuBoundsLower>(a, aCount, b, bCount, diag, comp);
int aIndex = p;
int bIndex = diag - p;
bool star = false;
if(bIndex < bCount) {
if(Duplicates) {
T x = b[bIndex];
// Search for the beginning of the duplicate run in both A and B.
// Because
int aStart = BiasedBinarySearch<MgpuBoundsLower, IntT>(a, aIndex, x,
levels, comp);
int bStart = BiasedBinarySearch<MgpuBoundsLower, IntT>(b, bIndex, x,
levels, comp);
// The distance between the merge path and the lower_bound is the
// 'run'. We add up the a- and b- runs and evenly distribute them to
// get a stairstep path.
int aRun = aIndex - aStart;
int bRun = bIndex - bStart;
int xCount = aRun + bRun;
// Attempt to advance b and regress a.
int bAdvance = max(xCount>> 1, bRun);
int bEnd = min(bCount, bStart + bAdvance + 1);
int bRunEnd = BinarySearch<MgpuBoundsUpper>(b + bIndex,
bEnd - bIndex, x, comp) + bIndex;
bRun = bRunEnd - bStart;
bAdvance = min(bAdvance, bRun);
int aAdvance = xCount - bAdvance;
bool roundUp = (aAdvance == bAdvance + 1) && (bAdvance < bRun);
aIndex = aStart + aAdvance;
if(roundUp) star = true;
} else {
if(aIndex && aCount) {
T aKey = a[aIndex - 1];
T bKey = b[bIndex];
// If the last consumed element in A (aIndex - 1) is the same as
// the next element in B (bIndex), we're sitting at a starred
// partition.
if(!comp(aKey, bKey)) star = true;
}
}
}
return make_int2(aIndex, star);
}
} // namespace mgpu
| {
"pile_set_name": "Github"
} |
\documentclass{article}
\usepackage[fancyhdr,pdf]{latex2man}
\input{common.tex}
\begin{document}
\begin{Name}{3}{unw\_init\_local}{David Mosberger-Tang}{Programming Library}{unw\_init\_local}unw\_init\_local -- initialize cursor for local unwinding
\end{Name}
\section{Synopsis}
\File{\#include $<$libunwind.h$>$}\\
\Type{int} \Func{unw\_init\_local}(\Type{unw\_cursor\_t~*}\Var{c}, \Type{unw\_context\_t~*}\Var{ctxt});\\
\Type{int} \Func{unw\_init\_local2}(\Type{unw\_cursor\_t~*}\Var{c}, \Type{unw\_context\_t~*}\Var{ctxt}, \Type{int} \Var{flag});\\
\section{Description}
The \Func{unw\_init\_local}() routine initializes the unwind cursor
pointed to by \Var{c} with the machine-state in the context structure
pointed to by \Var{ctxt}. As such, the machine-state pointed to by
\Var{ctxt} identifies the initial stack frame at which unwinding
starts. The machine-state is expected to be one provided by a call to
unw_getcontext; as such, the instruction pointer may point to the
instruction after the last instruction of a function, and libunwind
will back-up the instruction pointer before beginning a walk up the
call stack. The machine-state must remain valid for the duration for
which the cursor \Var{c} is in use.
The \Func{unw\_init\_local}() routine can be used only for unwinding in
the address space of the current process (i.e., for local unwinding).
For all other cases, \Func{unw\_init\_remote}() must be used instead.
However, unwind performance may be better when using
\Func{unw\_init\_local}(). Also, \Func{unw\_init\_local}() is
available even when \Const{UNW\_LOCAL\_ONLY} has been defined before
including \File{$<$libunwind.h$>$}, whereas \Func{unw\_init\_remote}()
is not.
If the unw_context_t is known to be a signal frame (i.e., from the
third argument in a sigaction handler on linux),
\Func{unw\_init\_local2}() should be used for correct initialization
on some platforms, passing the UNW_INIT_SIGNAL_FRAME flag.
\section{Return Value}
On successful completion, \Func{unw\_init\_local}() returns 0.
Otherwise the negative value of one of the error-codes below is
returned.
\section{Thread and Signal Safety}
\Func{unw\_init\_local}() is thread-safe as well as safe to use from a
signal handler.
\section{Errors}
\begin{Description}
\item[\Const{UNW\_EINVAL}] \Func{unw\_init\_local}() was called in a
version of \Prog{libunwind} which supports remote unwinding only
(this normally happens when calling \Func{unw\_init\_local}() for a
cross-platform version of \Prog{libunwind}).
\item[\Const{UNW\_EUNSPEC}] An unspecified error occurred.
\item[\Const{UNW\_EBADREG}] A register needed by \Func{unw\_init\_local}()
wasn't accessible.
\end{Description}
\section{See Also}
\SeeAlso{libunwind(3)}, \SeeAlso{unw\_init\_remote(3)}
\section{Author}
\noindent
David Mosberger-Tang\\
Email: \Email{[email protected]}\\
WWW: \URL{http://www.nongnu.org/libunwind/}.
\LatexManEnd
\end{document}
| {
"pile_set_name": "Github"
} |
## go-httpclient
**requires Go 1.1+** as of `v0.4.0` the API has been completely re-written for Go 1.1 (for a Go
1.0.x compatible release see [1adef50](https://github.com/mreiferson/go-httpclient/tree/1adef50))
[](http://travis-ci.org/mreiferson/go-httpclient)
Provides an HTTP Transport that implements the `RoundTripper` interface and
can be used as a built in replacement for the standard library's, providing:
* connection timeouts
* request timeouts
This is a thin wrapper around `http.Transport` that sets dial timeouts and uses
Go's internal timer scheduler to call the Go 1.1+ `CancelRequest()` API.
### Example
```go
transport := &httpclient.Transport{
ConnectTimeout: 1*time.Second,
RequestTimeout: 10*time.Second,
ResponseHeaderTimeout: 5*time.Second,
}
defer transport.Close()
client := &http.Client{Transport: transport}
req, _ := http.NewRequest("GET", "http://127.0.0.1/test", nil)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
```
*Note:* you will want to re-use a single client object rather than creating one for each request, otherwise you will end up [leaking connections](https://code.google.com/p/go/issues/detail?id=4049#c3).
### Reference Docs
For API docs see [godoc](http://godoc.org/github.com/mreiferson/go-httpclient).
| {
"pile_set_name": "Github"
} |
//
// MessagePack for C++ static resolution routine
//
// Copyright (C) 2016 KONDO Takatoshi
//
// 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)
//
#ifndef MSGPACK_V2_DEFINE_DECL_HPP
#define MSGPACK_V2_DEFINE_DECL_HPP
#include "msgpack/cpp_config.hpp"
#if defined(MSGPACK_USE_CPP03)
#include "msgpack/v2/adaptor/detail/cpp03_define_array_decl.hpp"
#include "msgpack/v2/adaptor/detail/cpp03_define_map_decl.hpp"
#else // MSGPACK_USE_CPP03
#include "msgpack/v2/adaptor/detail/cpp11_define_array_decl.hpp"
#include "msgpack/v2/adaptor/detail/cpp11_define_map_decl.hpp"
#endif // MSGPACK_USE_CPP03
#endif // MSGPACK_V2_DEFINE_DECL_HPP
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/audio_processing/audio_buffer.h"
#include <string.h>
#include <cstdint>
#include "common_audio/channel_buffer.h"
#include "common_audio/include/audio_util.h"
#include "common_audio/resampler/push_sinc_resampler.h"
#include "modules/audio_processing/splitting_filter.h"
#include "rtc_base/checks.h"
namespace webrtc {
namespace {
const size_t kSamplesPer16kHzChannel = 160;
const size_t kSamplesPer32kHzChannel = 320;
const size_t kSamplesPer48kHzChannel = 480;
int KeyboardChannelIndex(const StreamConfig& stream_config) {
if (!stream_config.has_keyboard()) {
RTC_NOTREACHED();
return 0;
}
return stream_config.num_channels();
}
size_t NumBandsFromSamplesPerChannel(size_t num_frames) {
size_t num_bands = 1;
if (num_frames == kSamplesPer32kHzChannel ||
num_frames == kSamplesPer48kHzChannel) {
num_bands = rtc::CheckedDivExact(num_frames, kSamplesPer16kHzChannel);
}
return num_bands;
}
} // namespace
AudioBuffer::AudioBuffer(size_t input_num_frames,
size_t num_input_channels,
size_t process_num_frames,
size_t num_process_channels,
size_t output_num_frames)
: input_num_frames_(input_num_frames),
num_input_channels_(num_input_channels),
proc_num_frames_(process_num_frames),
num_proc_channels_(num_process_channels),
output_num_frames_(output_num_frames),
num_channels_(num_process_channels),
num_bands_(NumBandsFromSamplesPerChannel(proc_num_frames_)),
num_split_frames_(rtc::CheckedDivExact(proc_num_frames_, num_bands_)),
mixed_low_pass_valid_(false),
reference_copied_(false),
activity_(AudioFrame::kVadUnknown),
keyboard_data_(NULL),
data_(new IFChannelBuffer(proc_num_frames_, num_proc_channels_)),
output_buffer_(new IFChannelBuffer(output_num_frames_, num_channels_)) {
RTC_DCHECK_GT(input_num_frames_, 0);
RTC_DCHECK_GT(proc_num_frames_, 0);
RTC_DCHECK_GT(output_num_frames_, 0);
RTC_DCHECK_GT(num_input_channels_, 0);
RTC_DCHECK_GT(num_proc_channels_, 0);
RTC_DCHECK_LE(num_proc_channels_, num_input_channels_);
if (input_num_frames_ != proc_num_frames_ ||
output_num_frames_ != proc_num_frames_) {
// Create an intermediate buffer for resampling.
process_buffer_.reset(
new ChannelBuffer<float>(proc_num_frames_, num_proc_channels_));
if (input_num_frames_ != proc_num_frames_) {
for (size_t i = 0; i < num_proc_channels_; ++i) {
input_resamplers_.push_back(std::unique_ptr<PushSincResampler>(
new PushSincResampler(input_num_frames_, proc_num_frames_)));
}
}
if (output_num_frames_ != proc_num_frames_) {
for (size_t i = 0; i < num_proc_channels_; ++i) {
output_resamplers_.push_back(std::unique_ptr<PushSincResampler>(
new PushSincResampler(proc_num_frames_, output_num_frames_)));
}
}
}
if (num_bands_ > 1) {
split_data_.reset(
new IFChannelBuffer(proc_num_frames_, num_proc_channels_, num_bands_));
splitting_filter_.reset(
new SplittingFilter(num_proc_channels_, num_bands_, proc_num_frames_));
}
}
AudioBuffer::~AudioBuffer() {}
void AudioBuffer::CopyFrom(const float* const* data,
const StreamConfig& stream_config) {
RTC_DCHECK_EQ(stream_config.num_frames(), input_num_frames_);
RTC_DCHECK_EQ(stream_config.num_channels(), num_input_channels_);
InitForNewData();
// Initialized lazily because there's a different condition in
// DeinterleaveFrom.
const bool need_to_downmix =
num_input_channels_ > 1 && num_proc_channels_ == 1;
if (need_to_downmix && !input_buffer_) {
input_buffer_.reset(
new IFChannelBuffer(input_num_frames_, num_proc_channels_));
}
if (stream_config.has_keyboard()) {
keyboard_data_ = data[KeyboardChannelIndex(stream_config)];
}
// Downmix.
const float* const* data_ptr = data;
if (need_to_downmix) {
DownmixToMono<float, float>(data, input_num_frames_, num_input_channels_,
input_buffer_->fbuf()->channels()[0]);
data_ptr = input_buffer_->fbuf_const()->channels();
}
// Resample.
if (input_num_frames_ != proc_num_frames_) {
for (size_t i = 0; i < num_proc_channels_; ++i) {
input_resamplers_[i]->Resample(data_ptr[i], input_num_frames_,
process_buffer_->channels()[i],
proc_num_frames_);
}
data_ptr = process_buffer_->channels();
}
// Convert to the S16 range.
for (size_t i = 0; i < num_proc_channels_; ++i) {
FloatToFloatS16(data_ptr[i], proc_num_frames_,
data_->fbuf()->channels()[i]);
}
}
void AudioBuffer::CopyTo(const StreamConfig& stream_config,
float* const* data) {
RTC_DCHECK_EQ(stream_config.num_frames(), output_num_frames_);
RTC_DCHECK(stream_config.num_channels() == num_channels_ ||
num_channels_ == 1);
// Convert to the float range.
float* const* data_ptr = data;
if (output_num_frames_ != proc_num_frames_) {
// Convert to an intermediate buffer for subsequent resampling.
data_ptr = process_buffer_->channels();
}
for (size_t i = 0; i < num_channels_; ++i) {
FloatS16ToFloat(data_->fbuf()->channels()[i], proc_num_frames_,
data_ptr[i]);
}
// Resample.
if (output_num_frames_ != proc_num_frames_) {
for (size_t i = 0; i < num_channels_; ++i) {
output_resamplers_[i]->Resample(data_ptr[i], proc_num_frames_, data[i],
output_num_frames_);
}
}
// Upmix.
for (size_t i = num_channels_; i < stream_config.num_channels(); ++i) {
memcpy(data[i], data[0], output_num_frames_ * sizeof(**data));
}
}
void AudioBuffer::InitForNewData() {
keyboard_data_ = NULL;
mixed_low_pass_valid_ = false;
reference_copied_ = false;
activity_ = AudioFrame::kVadUnknown;
num_channels_ = num_proc_channels_;
data_->set_num_channels(num_proc_channels_);
if (split_data_.get()) {
split_data_->set_num_channels(num_proc_channels_);
}
}
const int16_t* const* AudioBuffer::channels_const() const {
return data_->ibuf_const()->channels();
}
int16_t* const* AudioBuffer::channels() {
mixed_low_pass_valid_ = false;
return data_->ibuf()->channels();
}
const int16_t* const* AudioBuffer::split_bands_const(size_t channel) const {
return split_data_.get() ? split_data_->ibuf_const()->bands(channel)
: data_->ibuf_const()->bands(channel);
}
int16_t* const* AudioBuffer::split_bands(size_t channel) {
mixed_low_pass_valid_ = false;
return split_data_.get() ? split_data_->ibuf()->bands(channel)
: data_->ibuf()->bands(channel);
}
const int16_t* const* AudioBuffer::split_channels_const(Band band) const {
if (split_data_.get()) {
return split_data_->ibuf_const()->channels(band);
} else {
return band == kBand0To8kHz ? data_->ibuf_const()->channels() : nullptr;
}
}
int16_t* const* AudioBuffer::split_channels(Band band) {
mixed_low_pass_valid_ = false;
if (split_data_.get()) {
return split_data_->ibuf()->channels(band);
} else {
return band == kBand0To8kHz ? data_->ibuf()->channels() : nullptr;
}
}
ChannelBuffer<int16_t>* AudioBuffer::data() {
mixed_low_pass_valid_ = false;
return data_->ibuf();
}
const ChannelBuffer<int16_t>* AudioBuffer::data() const {
return data_->ibuf_const();
}
ChannelBuffer<int16_t>* AudioBuffer::split_data() {
mixed_low_pass_valid_ = false;
return split_data_.get() ? split_data_->ibuf() : data_->ibuf();
}
const ChannelBuffer<int16_t>* AudioBuffer::split_data() const {
return split_data_.get() ? split_data_->ibuf_const() : data_->ibuf_const();
}
const float* const* AudioBuffer::channels_const_f() const {
return data_->fbuf_const()->channels();
}
float* const* AudioBuffer::channels_f() {
mixed_low_pass_valid_ = false;
return data_->fbuf()->channels();
}
const float* const* AudioBuffer::split_bands_const_f(size_t channel) const {
return split_data_.get() ? split_data_->fbuf_const()->bands(channel)
: data_->fbuf_const()->bands(channel);
}
float* const* AudioBuffer::split_bands_f(size_t channel) {
mixed_low_pass_valid_ = false;
return split_data_.get() ? split_data_->fbuf()->bands(channel)
: data_->fbuf()->bands(channel);
}
const float* const* AudioBuffer::split_channels_const_f(Band band) const {
if (split_data_.get()) {
return split_data_->fbuf_const()->channels(band);
} else {
return band == kBand0To8kHz ? data_->fbuf_const()->channels() : nullptr;
}
}
float* const* AudioBuffer::split_channels_f(Band band) {
mixed_low_pass_valid_ = false;
if (split_data_.get()) {
return split_data_->fbuf()->channels(band);
} else {
return band == kBand0To8kHz ? data_->fbuf()->channels() : nullptr;
}
}
ChannelBuffer<float>* AudioBuffer::data_f() {
mixed_low_pass_valid_ = false;
return data_->fbuf();
}
const ChannelBuffer<float>* AudioBuffer::data_f() const {
return data_->fbuf_const();
}
ChannelBuffer<float>* AudioBuffer::split_data_f() {
mixed_low_pass_valid_ = false;
return split_data_.get() ? split_data_->fbuf() : data_->fbuf();
}
const ChannelBuffer<float>* AudioBuffer::split_data_f() const {
return split_data_.get() ? split_data_->fbuf_const() : data_->fbuf_const();
}
const int16_t* AudioBuffer::mixed_low_pass_data() {
if (num_proc_channels_ == 1) {
return split_bands_const(0)[kBand0To8kHz];
}
if (!mixed_low_pass_valid_) {
if (!mixed_low_pass_channels_.get()) {
mixed_low_pass_channels_.reset(
new ChannelBuffer<int16_t>(num_split_frames_, 1));
}
DownmixToMono<int16_t, int32_t>(split_channels_const(kBand0To8kHz),
num_split_frames_, num_channels_,
mixed_low_pass_channels_->channels()[0]);
mixed_low_pass_valid_ = true;
}
return mixed_low_pass_channels_->channels()[0];
}
const int16_t* AudioBuffer::low_pass_reference(int channel) const {
if (!reference_copied_) {
return NULL;
}
return low_pass_reference_channels_->channels()[channel];
}
const float* AudioBuffer::keyboard_data() const {
return keyboard_data_;
}
void AudioBuffer::set_activity(AudioFrame::VADActivity activity) {
activity_ = activity;
}
AudioFrame::VADActivity AudioBuffer::activity() const {
return activity_;
}
size_t AudioBuffer::num_channels() const {
return num_channels_;
}
void AudioBuffer::set_num_channels(size_t num_channels) {
num_channels_ = num_channels;
data_->set_num_channels(num_channels);
if (split_data_.get()) {
split_data_->set_num_channels(num_channels);
}
}
size_t AudioBuffer::num_frames() const {
return proc_num_frames_;
}
size_t AudioBuffer::num_frames_per_band() const {
return num_split_frames_;
}
size_t AudioBuffer::num_keyboard_frames() const {
// We don't resample the keyboard channel.
return input_num_frames_;
}
size_t AudioBuffer::num_bands() const {
return num_bands_;
}
// The resampler is only for supporting 48kHz to 16kHz in the reverse stream.
void AudioBuffer::DeinterleaveFrom(AudioFrame* frame) {
RTC_DCHECK_EQ(frame->num_channels_, num_input_channels_);
RTC_DCHECK_EQ(frame->samples_per_channel_, input_num_frames_);
InitForNewData();
// Initialized lazily because there's a different condition in CopyFrom.
if ((input_num_frames_ != proc_num_frames_) && !input_buffer_) {
input_buffer_.reset(
new IFChannelBuffer(input_num_frames_, num_proc_channels_));
}
activity_ = frame->vad_activity_;
int16_t* const* deinterleaved;
if (input_num_frames_ == proc_num_frames_) {
deinterleaved = data_->ibuf()->channels();
} else {
deinterleaved = input_buffer_->ibuf()->channels();
}
// TODO(yujo): handle muted frames more efficiently.
if (num_proc_channels_ == 1) {
// Downmix and deinterleave simultaneously.
DownmixInterleavedToMono(frame->data(), input_num_frames_,
num_input_channels_, deinterleaved[0]);
} else {
RTC_DCHECK_EQ(num_proc_channels_, num_input_channels_);
Deinterleave(frame->data(), input_num_frames_, num_proc_channels_,
deinterleaved);
}
// Resample.
if (input_num_frames_ != proc_num_frames_) {
for (size_t i = 0; i < num_proc_channels_; ++i) {
input_resamplers_[i]->Resample(
input_buffer_->fbuf_const()->channels()[i], input_num_frames_,
data_->fbuf()->channels()[i], proc_num_frames_);
}
}
}
void AudioBuffer::InterleaveTo(AudioFrame* frame, bool data_changed) const {
frame->vad_activity_ = activity_;
if (!data_changed) {
return;
}
RTC_DCHECK(frame->num_channels_ == num_channels_ || num_channels_ == 1);
RTC_DCHECK_EQ(frame->samples_per_channel_, output_num_frames_);
// Resample if necessary.
IFChannelBuffer* data_ptr = data_.get();
if (proc_num_frames_ != output_num_frames_) {
for (size_t i = 0; i < num_channels_; ++i) {
output_resamplers_[i]->Resample(
data_->fbuf()->channels()[i], proc_num_frames_,
output_buffer_->fbuf()->channels()[i], output_num_frames_);
}
data_ptr = output_buffer_.get();
}
// TODO(yujo): handle muted frames more efficiently.
if (frame->num_channels_ == num_channels_) {
Interleave(data_ptr->ibuf()->channels(), output_num_frames_, num_channels_,
frame->mutable_data());
} else {
UpmixMonoToInterleaved(data_ptr->ibuf()->channels()[0], output_num_frames_,
frame->num_channels_, frame->mutable_data());
}
}
void AudioBuffer::CopyLowPassToReference() {
reference_copied_ = true;
if (!low_pass_reference_channels_.get() ||
low_pass_reference_channels_->num_channels() != num_channels_) {
low_pass_reference_channels_.reset(
new ChannelBuffer<int16_t>(num_split_frames_, num_proc_channels_));
}
for (size_t i = 0; i < num_proc_channels_; i++) {
memcpy(low_pass_reference_channels_->channels()[i],
split_bands_const(i)[kBand0To8kHz],
low_pass_reference_channels_->num_frames_per_band() *
sizeof(split_bands_const(i)[kBand0To8kHz][0]));
}
}
void AudioBuffer::SplitIntoFrequencyBands() {
splitting_filter_->Analysis(data_.get(), split_data_.get());
}
void AudioBuffer::MergeFrequencyBands() {
splitting_filter_->Synthesis(split_data_.get(), data_.get());
}
} // namespace webrtc
| {
"pile_set_name": "Github"
} |
using System;
using Xamarin.Forms.CustomAttributes;
using Xamarin.Forms.Internals;
namespace Xamarin.Forms.Controls.Issues
{
[Preserve(AllMembers = true)]
[Issue(IssueTracker.Github, 9962, "NSException thrown when calling NSColor.ControlBackground.ToColor()", PlatformAffected.macOS)]
public class Issue9962 : TestContentPage
{
public Issue9962()
{
}
protected override void Init()
{
var stackLayout = new StackLayout
{
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
};
var debugLabel = new Label
{
Text = "The first button should show an alert with the exception message, second button should retrieve an actual color and put the value in this label and in the BoxView"
};
var boxView = new BoxView
{
BackgroundColor = Color.Blue,
WidthRequest = 100,
HeightRequest = 100
};
var buttonBoom = new Button
{
Text = "This button should throw an Exception"
};
buttonBoom.Clicked += (_, __) =>
{
try
{
var color = DependencyService.Get<INativeColorService>()?.GetConvertedColor(true);
boxView.BackgroundColor = color ?? Color.Black;
}
catch (InvalidOperationException ex)
{
DisplayAlert("Exception!", ex.Message, "Gotcha");
}
};
var buttonNotBoom = new Button
{
Text = "This button should NOT throw an Exception"
};
buttonNotBoom.Clicked += (_, __) =>
{
try
{
var color = DependencyService.Get<INativeColorService>()?.GetConvertedColor(false);
debugLabel.Text = color?.ToString();
boxView.BackgroundColor = color ?? Color.Black;
}
catch (Exception ex)
{
DisplayAlert("Exception!", ex.Message, "Gotcha");
}
};
stackLayout.Children.Add(buttonBoom);
stackLayout.Children.Add(buttonNotBoom);
stackLayout.Children.Add(debugLabel);
stackLayout.Children.Add(boxView);
Content = stackLayout;
}
}
} | {
"pile_set_name": "Github"
} |
################################################################
## Test verifies "assert" commands, in following configurations:
#
# 1. verify assert_eq command
# 2. verify assert_ne command
# 3. verify assert_gt command
# 4. verify assert_ge command
# 5. verify assert command with equal operator (==)
# 6. verify assert command with not equal operator (!=)
# 7. verify assert command with greater operator (>)
# 8. verify assert command with greater or equal operator (>=)
# 9. verify assert command with less operator (<)
# 10. verify assert command with less or equal operator (<=)
# 11. verify assert command with veriable in thrid param
# 12. verify assert command with veriable in first param
#
# 1.
#
ok
# 2.
#
ok
# 3.
#
ok
# 4.
#
ok
# 5.
#
ok
# 6.
#
ok
# 7.
#
ok
# 8.
#
ok
# 9.
#
ok
# 10.
#
ok
# 11.
#
ok
# 12.
#
ok
Mysqlx.Ok {
msg: "bye!"
}
ok
| {
"pile_set_name": "Github"
} |
import * as React from 'react'
import { SemanticShorthandCollection, SemanticVERTICALALIGNMENTS } from '../../generic'
import { TableCellProps } from './TableCell'
export interface TableRowProps extends StrictTableRowProps {
[key: string]: any
}
export interface StrictTableRowProps {
/** An element type to render as (string or function). */
as?: any
/** A row can be active or selected by a user. */
active?: boolean
/** An element type to render as (string or function). */
cellAs?: any
/** Shorthand array of props for TableCell. */
cells?: SemanticShorthandCollection<TableCellProps>
/** Primary content. */
children?: React.ReactNode
/** Additional classes. */
className?: string
/** A row can be disabled. */
disabled?: boolean
/** A row may call attention to an error or a negative value. */
error?: boolean
/** A row may let a user know whether a value is bad. */
negative?: boolean
/** A row may let a user know whether a value is good. */
positive?: boolean
/** A table row can adjust its text alignment. */
textAlign?: 'center' | 'left' | 'right'
/** A table row can adjust its vertical alignment. */
verticalAlign?: SemanticVERTICALALIGNMENTS
/** A row may warn a user. */
warning?: boolean
}
declare const TableRow: React.StatelessComponent<TableRowProps>
export default TableRow
| {
"pile_set_name": "Github"
} |
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.remote.server.log;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
PerSessionLogHandlerUnitTest.class,
LoggingManagerUnitTest.class,
ShortTermMemoryHandlerUnitTest.class
})
public class LoggingTests {}
| {
"pile_set_name": "Github"
} |
pass in from 10.0.0.1 to <regress> label "$srcaddr:$dstaddr"
| {
"pile_set_name": "Github"
} |
/* Licensed under GPLv2+ - see LICENSE file for details */
#include <ccan/opt/opt.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <stdarg.h>
#include <stdint.h>
#include "private.h"
struct opt_table *opt_table;
unsigned int opt_count, opt_num_short, opt_num_short_arg, opt_num_long;
const char *opt_argv0;
struct opt_alloc opt_alloc = {
malloc, realloc, free
};
/* Returns string after first '-'. */
static const char *first_name(const char *names, unsigned *len)
{
*len = strcspn(names + 1, "|= ");
return names + 1;
}
static const char *next_name(const char *names, unsigned *len)
{
names += *len;
if (names[0] == ' ' || names[0] == '=' || names[0] == '\0')
return NULL;
return first_name(names + 1, len);
}
static const char *first_opt(unsigned *i, unsigned *len)
{
for (*i = 0; *i < opt_count; (*i)++) {
if (opt_table[*i].type == OPT_SUBTABLE)
continue;
return first_name(opt_table[*i].names, len);
}
return NULL;
}
static const char *next_opt(const char *p, unsigned *i, unsigned *len)
{
for (; *i < opt_count; (*i)++) {
if (opt_table[*i].type == OPT_SUBTABLE)
continue;
if (!p)
return first_name(opt_table[*i].names, len);
p = next_name(p, len);
if (p)
return p;
}
return NULL;
}
const char *first_lopt(unsigned *i, unsigned *len)
{
const char *p;
for (p = first_opt(i, len); p; p = next_opt(p, i, len)) {
if (p[0] == '-') {
/* Skip leading "-" */
(*len)--;
p++;
break;
}
}
return p;
}
const char *next_lopt(const char *p, unsigned *i, unsigned *len)
{
for (p = next_opt(p, i, len); p; p = next_opt(p, i, len)) {
if (p[0] == '-') {
/* Skip leading "-" */
(*len)--;
p++;
break;
}
}
return p;
}
const char *first_sopt(unsigned *i)
{
const char *p;
unsigned int len = 0 /* GCC bogus warning */;
for (p = first_opt(i, &len); p; p = next_opt(p, i, &len)) {
if (p[0] != '-')
break;
}
return p;
}
const char *next_sopt(const char *p, unsigned *i)
{
unsigned int len = 1;
for (p = next_opt(p, i, &len); p; p = next_opt(p, i, &len)) {
if (p[0] != '-')
break;
}
return p;
}
/* Avoids dependency on err.h or ccan/err */
#ifndef failmsg
#define failmsg(fmt, ...) \
do { fprintf(stderr, fmt, __VA_ARGS__); exit(1); } while(0)
#endif
static void check_opt(const struct opt_table *entry)
{
const char *p;
unsigned len;
if (entry->type != OPT_HASARG && entry->type != OPT_NOARG
&& entry->type != (OPT_EARLY|OPT_HASARG)
&& entry->type != (OPT_EARLY|OPT_NOARG))
failmsg("Option %s: unknown entry type %u",
entry->names, entry->type);
if (!entry->desc)
failmsg("Option %s: description cannot be NULL", entry->names);
if (entry->names[0] != '-')
failmsg("Option %s: does not begin with '-'", entry->names);
for (p = first_name(entry->names, &len); p; p = next_name(p, &len)) {
if (*p == '-') {
if (len == 1)
failmsg("Option %s: invalid long option '--'",
entry->names);
opt_num_long++;
} else {
if (len != 1)
failmsg("Option %s: invalid short option"
" '%.*s'", entry->names, len+1, p-1);
opt_num_short++;
if (entry->type == OPT_HASARG)
opt_num_short_arg++;
}
/* Don't document args unless there are some. */
if (entry->type == OPT_NOARG) {
if (p[len] == ' ' || p[len] == '=')
failmsg("Option %s: does not take arguments"
" '%s'", entry->names, p+len+1);
}
}
}
static void add_opt(const struct opt_table *entry)
{
opt_table = opt_alloc.realloc(opt_table,
sizeof(opt_table[0]) * (opt_count+1));
opt_table[opt_count++] = *entry;
}
void _opt_register(const char *names, enum opt_type type,
char *(*cb)(void *arg),
char *(*cb_arg)(const char *optarg, void *arg),
void (*show)(char buf[OPT_SHOW_LEN], const void *arg),
const void *arg, const char *desc)
{
struct opt_table opt;
opt.names = names;
opt.type = type;
opt.cb = cb;
opt.cb_arg = cb_arg;
opt.show = show;
opt.u.carg = arg;
opt.desc = desc;
check_opt(&opt);
add_opt(&opt);
}
bool opt_unregister(const char *names)
{
int found = -1, i;
for (i = 0; i < opt_count; i++) {
if (opt_table[i].type == OPT_SUBTABLE)
continue;
if (strcmp(opt_table[i].names, names) == 0)
found = i;
}
if (found == -1)
return false;
opt_count--;
memmove(&opt_table[found], &opt_table[found+1],
(opt_count - found) * sizeof(opt_table[found]));
return true;
}
void opt_register_table(const struct opt_table entry[], const char *desc)
{
unsigned int i, start = opt_count;
if (desc) {
struct opt_table heading = OPT_SUBTABLE(NULL, desc);
add_opt(&heading);
}
for (i = 0; entry[i].type != OPT_END; i++) {
if (entry[i].type == OPT_SUBTABLE)
opt_register_table(subtable_of(&entry[i]),
entry[i].desc);
else {
check_opt(&entry[i]);
add_opt(&entry[i]);
}
}
/* We store the table length in arg ptr. */
if (desc)
opt_table[start].u.tlen = (opt_count - start);
}
/* Parse your arguments. */
bool opt_parse(int *argc, char *argv[], void (*errlog)(const char *fmt, ...))
{
int ret;
unsigned offset = 0;
/* This helps opt_usage. */
opt_argv0 = argv[0];
while ((ret = parse_one(argc, argv, 0, &offset, errlog, false)) == 1);
/* parse_one returns 0 on finish, -1 on error */
return (ret == 0);
}
static bool early_parse(int argc, char *argv[],
void (*errlog)(const char *fmt, ...),
bool ignore_unknown)
{
int ret;
unsigned off = 0;
char **tmpargv = opt_alloc.alloc(sizeof(argv[0]) * (argc + 1));
/* We could avoid a copy and skip instead, but this is simple. */
memcpy(tmpargv, argv, sizeof(argv[0]) * (argc + 1));
/* This helps opt_usage. */
opt_argv0 = argv[0];
while ((ret = parse_one(&argc, tmpargv, OPT_EARLY, &off, errlog, ignore_unknown)) == 1);
opt_alloc.free(tmpargv);
/* parse_one returns 0 on finish, -1 on error */
return (ret == 0);
}
bool opt_early_parse(int argc, char *argv[],
void (*errlog)(const char *fmt, ...))
{
return early_parse(argc, argv, errlog, false);
}
bool opt_early_parse_incomplete(int argc, char *argv[],
void (*errlog)(const char *fmt, ...))
{
return early_parse(argc, argv, errlog, true);
}
void opt_free_table(void)
{
opt_alloc.free(opt_table);
opt_table = NULL;
opt_count = opt_num_short = opt_num_short_arg = opt_num_long = 0;
}
void opt_log_stderr(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
void opt_log_stderr_exit(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
exit(1);
}
char *opt_invalid_argument(const char *arg)
{
char *str = opt_alloc.alloc(sizeof("Invalid argument '%s'") + strlen(arg));
sprintf(str, "Invalid argument '%s'", arg);
return str;
}
void opt_set_alloc(void *(*allocfn)(size_t size),
void *(*reallocfn)(void *ptr, size_t size),
void (*freefn)(void *ptr))
{
opt_alloc.alloc = allocfn;
opt_alloc.realloc = reallocfn;
opt_alloc.free = freefn;
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Mongoose v5.6.0: </title><link rel="apple-touch-icon" sizes="57x57" href="images/favicon/apple-icon-57x57.png"><link rel="apple-touch-icon" sizes="60x60" href="images/favicon/apple-icon-60x60.png"><link rel="apple-touch-icon" sizes="72x72" href="images/favicon/apple-icon-72x72.png"><link rel="apple-touch-icon" sizes="76x76" href="images/favicon/apple-icon-76x76.png"><link rel="apple-touch-icon" sizes="114x114" href="images/favicon/apple-icon-114x114.png"><link rel="apple-touch-icon" sizes="120x120" href="images/favicon/apple-icon-120x120.png"><link rel="apple-touch-icon" sizes="144x144" href="images/favicon/apple-icon-144x144.png"><link rel="apple-touch-icon" sizes="152x152" href="images/favicon/apple-icon-152x152.png"><link rel="apple-touch-icon" sizes="180x180" href="images/favicon/apple-icon-180x180.png"><link rel="icon" type="image/png" sizes="192x192" href="images/favicon/android-icon-192x192.png"><link rel="icon" type="image/png" sizes="32x32" href="images/favicon/favicon-32x32.png"><link rel="icon" type="image/png" sizes="96x96" href="images/favicon/favicon-96x96.png"><link rel="icon" type="image/png" sizes="16x16" href="images/favicon/favicon-16x16.png"><link rel="stylesheet" href="https://unpkg.com/[email protected]/build/pure-min.css" integrity="sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w" crossorigin="anonymous"><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans"><link rel="stylesheet" href="/docs/css/github.css"><link rel="stylesheet" href="/docs/css/mongoose5.css"><link rel="apple-touch-icon" sizes="57x57" href="images/favicon/apple-icon-57x57.png"><link rel="apple-touch-icon" sizes="60x60" href="images/favicon/apple-icon-60x60.png"><link rel="apple-touch-icon" sizes="72x72" href="images/favicon/apple-icon-72x72.png"><link rel="apple-touch-icon" sizes="76x76" href="images/favicon/apple-icon-76x76.png"><link rel="apple-touch-icon" sizes="114x114" href="images/favicon/apple-icon-114x114.png"><link rel="apple-touch-icon" sizes="120x120" href="images/favicon/apple-icon-120x120.png"><link rel="apple-touch-icon" sizes="144x144" href="images/favicon/apple-icon-144x144.png"><link rel="apple-touch-icon" sizes="152x152" href="images/favicon/apple-icon-152x152.png"><link rel="apple-touch-icon" sizes="180x180" href="images/favicon/apple-icon-180x180.png"><link rel="icon" type="image/png" sizes="192x192" href="images/favicon/android-icon-192x192.png"><link rel="icon" type="image/png" sizes="32x32" href="images/favicon/favicon-32x32.png"><link rel="icon" type="image/png" sizes="96x96" href="images/favicon/favicon-96x96.png"><link rel="icon" type="image/png" sizes="16x16" href="images/favicon/favicon-16x16.png"><link rel="manifest" href="images/favicon/manifest.json"><meta name="msapplication-TileColor" content="#ffffff"><meta name="msapplication-TileImage" content="images/favicon/ms-icon-144x144.png"><meta name="theme-color" content="#ffffff"><link rel="stylesheet" href="/docs/css/api.css"><link rel="stylesheet" href="/docs/css/inlinecpc.css"><script type="text/javascript" src="/docs/js/native.js"></script><style>.api-nav .nav-item-sub {
display: block !important;
}
.api-content {
margin-top: 3em;
}
</style></head><body><div id="layout"><div id="mobile-menu"><a class="menu-link" id="menuLink" href="#menu"><span></span></a><div id="mobile-logo-container"><a href="/"><img id="logo" src="/docs/images/mongoose5_62x30_transparent.png"><span class="logo-text">mongoose</span></a></div></div><div id="menu"><div class="pure-menu"><div class="pure-menu-heading" id="logo-container"><a href="/"><img id="logo" src="/docs/images/mongoose5_62x30_transparent.png"><span class="logo-text">mongoose</span></a></div><ul class="pure-menu-list" id="navbar"><li class="pure-menu-horizontal pure-menu-item pure-menu-has-children pure-menu-allow-hover version"><a class="pure-menu-link" href="#">Version 5.6.0</a><ul class="pure-menu-children"><li class="pure-menu-item"><a class="pure-menu-link" href="/docs/4.x">Version 4.13.18</a></li><li class="pure-menu-item"><a class="pure-menu-link" href="/docs/3.8.x">Version 3.8.40</a></li></ul></li><li class="pure-menu-item search"><input id="search-input-nav" type="text" placeholder="Search"><button id="search-button-nav"><img src="/docs/images/search.svg"></button></li><li class="pure-menu-item"><a class="pure-menu-link" href="/docs/index.html">Quick Start</a></li><li class="pure-menu-item"><a class="pure-menu-link" href="/docs/guides.html">Guides</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/guide.html">Schemas</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/schematypes.html">SchemaTypes</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/connections.html">Connections</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/models.html">Models</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/documents.html">Documents</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/subdocs.html">Subdocuments</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/queries.html">Queries</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/validation.html">Validation</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/middleware.html">Middleware</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/populate.html">Populate</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/discriminators.html">Discriminators</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/plugins.html">Plugins</a></li><li class="pure-menu-item"><a class="pure-menu-link" href="/docs/api.html">API</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/api/mongoose.html">Mongoose</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/api/schema.html">Schema</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/api/connection.html">Connection</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/api/document.html">Document</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/api/model.html">Model</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/api/query.html">Query</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/api/aggregate.html">Aggregate</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/api/schematype.html">SchemaType</a></li><li class="pure-menu-item sub-item"><a class="pure-menu-link" href="/docs/api/virtualtype.html">VirtualType</a></li><li class="pure-menu-item"><a class="pure-menu-link" href="/docs/compatibility.html">Version Compatibility</a></li><li class="pure-menu-item"><a class="pure-menu-link" href="/docs/faq.html">FAQ</a></li><li class="pure-menu-item"><a class="pure-menu-link" href="/docs/further_reading.html">Further Reading</a></li></ul><div class="cpc-ad"><script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?zoneid=1673&serve=C6AILKT&placement=mongoosejscom" id="_carbonads_js"></script></div></div></div><div class="container"><div id="content"><h1>Virtualtype</h1><div><div class="native-inline">
<a href="#native_link#"><span class="sponsor">Sponsor</span> #native_company# — #native_desc#</a>
</div>
</div><div class="api-nav"><div class="api-nav-content"><div class="nav-item" id="nav-Mongoose"><div class="nav-item-title"><a href="mongoose.html">Mongoose</a></div></div><div class="nav-item" id="nav-Schema"><div class="nav-item-title"><a href="schema.html">Schema</a></div></div><div class="nav-item" id="nav-Connection"><div class="nav-item-title"><a href="connection.html">Connection</a></div></div><div class="nav-item" id="nav-Document"><div class="nav-item-title"><a href="document.html">Document</a></div></div><div class="nav-item" id="nav-Model"><div class="nav-item-title"><a href="model.html">Model</a></div></div><div class="nav-item" id="nav-Query"><div class="nav-item-title"><a href="query.html">Query</a></div></div><div class="nav-item" id="nav-QueryCursor"><div class="nav-item-title"><a href="querycursor.html">QueryCursor</a></div></div><div class="nav-item" id="nav-Aggregate"><div class="nav-item-title"><a href="aggregate.html">Aggregate</a></div></div><div class="nav-item" id="nav-AggregationCursor"><div class="nav-item-title"><a href="aggregationcursor.html">AggregationCursor</a></div></div><div class="nav-item" id="nav-Schematype"><div class="nav-item-title"><a href="schematype.html">Schematype</a></div></div><div class="nav-item" id="nav-Virtualtype"><div class="nav-item-title" style="font-weight: bold"><a href="virtualtype.html">Virtualtype</a></div><ul class="nav-item-sub"><li><a href="#virtualtype_VirtualType">VirtualType()</a></li><li><a href="#virtualtype_VirtualType-applyGetters">VirtualType.prototype.applyGetters()</a></li><li><a href="#virtualtype_VirtualType-applySetters">VirtualType.prototype.applySetters()</a></li><li><a href="#virtualtype_VirtualType-get">VirtualType.prototype.get()</a></li><li><a href="#virtualtype_VirtualType-set">VirtualType.prototype.set()</a></li></ul></div><div class="nav-item" id="nav-Error"><div class="nav-item-title"><a href="error.html">Error</a></div></div><div class="nav-item" id="nav-Array"><div class="nav-item-title"><a href="array.html">Array</a></div></div></div></div><div class="api-content"><ul><li><a href="#virtualtype_VirtualType">VirtualType()</a></li><li><a href="#virtualtype_VirtualType-applyGetters">VirtualType.prototype.applyGetters()</a></li><li><a href="#virtualtype_VirtualType-applySetters">VirtualType.prototype.applySetters()</a></li><li><a href="#virtualtype_VirtualType-get">VirtualType.prototype.get()</a></li><li><a href="#virtualtype_VirtualType-set">VirtualType.prototype.set()</a></li></ul><hr class="separate-api-elements"><h3 id="virtualtype_VirtualType"><a href="#virtualtype_VirtualType">VirtualType()</a></h3><h5>Parameters</h5><ul class="params"><li class="param">options
<span class="method-type">«Object»</span> </li><ul style="margin-top: 0.5em"><li>[options.ref]
<span class="method-type">«string|function»</span> if <code>ref</code> is not nullish, this becomes a <a href="/docs/populate.html#populate-virtuals">populated virtual</a></li></ul><ul style="margin-top: 0.5em"><li>[options.localField]
<span class="method-type">«string|function»</span> the local field to populate on if this is a populated virtual.</li></ul><ul style="margin-top: 0.5em"><li>[options.foreignField]
<span class="method-type">«string|function»</span> the foreign field to populate on if this is a populated virtual.</li></ul><ul style="margin-top: 0.5em"><li>[options.justOne=false]
<span class="method-type">«boolean»</span> by default, a populated virtual is an array. If you set <code>justOne</code>, the populated virtual will be a single doc or <code>null</code>.</li></ul><ul style="margin-top: 0.5em"><li>[options.getters=false]
<span class="method-type">«boolean»</span> if you set this to <code>true</code>, Mongoose will call any custom getters you defined on this virtual</li></ul><ul style="margin-top: 0.5em"><li>[options.count=false]
<span class="method-type">«boolean»</span> if you set this to <code>true</code>, <code>populate()</code> will set this virtual to the number of populated documents, as opposed to the documents themselves, using <a href="./api.html#query_Query-countDocuments"><code>Query#countDocuments()</code></a></li></ul></ul><div><p>VirtualType constructor</p>
<p>This is what mongoose uses to define virtual attributes via <code>Schema.prototype.virtual</code>.</p>
<h4>Example:</h4>
<pre><code><span class="hljs-keyword">const</span> fullname = schema.virtual(<span class="hljs-string">'fullname'</span>);
fullname <span class="hljs-keyword">instanceof</span> mongoose.VirtualType <span class="hljs-comment">// true</span></code></pre> </div><hr class="separate-api-elements"><h3 id="virtualtype_VirtualType-applyGetters"><a href="#virtualtype_VirtualType-applyGetters">VirtualType.prototype.applyGetters()</a></h3><h5>Parameters</h5><ul class="params"><li class="param">value
<span class="method-type">«Object»</span> </li><li class="param">doc
<span class="method-type">«Document»</span> The document this virtual is attached to</li></ul><h5>Returns:</h5><ul><li><span class="method-type">«any»</span> the value after applying all getters</li></ul><div><p>Applies getters to <code>value</code>.</p> </div><hr class="separate-api-elements"><h3 id="virtualtype_VirtualType-applySetters"><a href="#virtualtype_VirtualType-applySetters">VirtualType.prototype.applySetters()</a></h3><h5>Parameters</h5><ul class="params"><li class="param">value
<span class="method-type">«Object»</span> </li><li class="param">doc
<span class="method-type">«Document»</span> </li></ul><h5>Returns:</h5><ul><li><span class="method-type">«any»</span> the value after applying all setters</li></ul><div><p>Applies setters to <code>value</code>.</p> </div><hr class="separate-api-elements"><h3 id="virtualtype_VirtualType-get"><a href="#virtualtype_VirtualType-get">VirtualType.prototype.get()</a></h3><h5>Parameters</h5><ul class="params"><li class="param">VirtualType,
<span class="method-type">«Function(Any|»</span> Document)} fn</li></ul><h5>Returns:</h5><ul><li><span class="method-type">«VirtualType»</span> this</li></ul><div><p>Adds a custom getter to this virtual.</p>
<h2>Mongoose calls the getter function with 3 parameters</h2>
<ul>
<li><code>value</code>: the value returned by the previous getter. If there is only one getter, <code>value</code> will be <code>undefined</code>.</li>
<li><code>virtual</code>: the virtual object you called <code>.get()</code> on</li>
<li><code>doc</code>: the document this virtual is attached to. Equivalent to <code>this</code>.</li>
</ul>
<h4>Example:</h4>
<pre><code><span class="hljs-keyword">var</span> virtual = schema.virtual(<span class="hljs-string">'fullname'</span>);
virtual.get(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">value, virtual, doc</span>) </span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.name.first + <span class="hljs-string">' '</span> + <span class="hljs-keyword">this</span>.name.last;
});</code></pre> </div><hr class="separate-api-elements"><h3 id="virtualtype_VirtualType-set"><a href="#virtualtype_VirtualType-set">VirtualType.prototype.set()</a></h3><h5>Parameters</h5><ul class="params"><li class="param">VirtualType,
<span class="method-type">«Function(Any|»</span> Document)} fn</li></ul><h5>Returns:</h5><ul><li><span class="method-type">«VirtualType»</span> this</li></ul><div><p>Adds a custom setter to this virtual.</p>
<h2>Mongoose calls the setter function with 3 parameters</h2>
<ul>
<li><code>value</code>: the value being set</li>
<li><code>virtual</code>: the virtual object you're calling <code>.set()</code> on</li>
<li><code>doc</code>: the document this virtual is attached to. Equivalent to <code>this</code>.</li>
</ul>
<h4>Example:</h4>
<pre><code><span class="hljs-keyword">const</span> virtual = schema.virtual(<span class="hljs-string">'fullname'</span>);
virtual.set(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">value, virtual, doc</span>) </span>{
<span class="hljs-keyword">var</span> parts = value.split(<span class="hljs-string">' '</span>);
<span class="hljs-keyword">this</span>.name.first = parts[<span class="hljs-number">0</span>];
<span class="hljs-keyword">this</span>.name.last = parts[<span class="hljs-number">1</span>];
});
<span class="hljs-keyword">const</span> Model = mongoose.model(<span class="hljs-string">'Test'</span>, schema);
<span class="hljs-keyword">const</span> doc = <span class="hljs-keyword">new</span> Model();
<span class="hljs-comment">// Calls the setter with `value = 'Jean-Luc Picard'`</span>
doc.fullname = <span class="hljs-string">'Jean-Luc Picard'</span>;
doc.name.first; <span class="hljs-comment">// 'Jean-Luc'</span>
doc.name.last; <span class="hljs-comment">// 'Picard'</span></code></pre> </div></div><script>_native.init("CK7DT53U",{
targetClass: 'native-inline'
});</script></div></div><script type="text/javascript">var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://g0a3nbw0xa.execute-api.us-east-1.amazonaws.com/prod/track', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {};
xhr.send(JSON.stringify({
path: window.location.pathname,
hostname: window.location.hostname,
hash: window.location.hash
}));</script><script type="text/javascript" src="/docs/js/navbar-search.js"></script><script type="text/javascript">(function (window, document) {
var layout = document.getElementById('layout'),
menu = document.getElementById('menu'),
menuLink = document.getElementById('menuLink'),
content = document.getElementById('content');
function toggleClass(element, className) {
var classes = element.className.split(/\s+/),
length = classes.length,
i = 0;
for(; i < length; i++) {
if (classes[i] === className) {
classes.splice(i, 1);
break;
}
}
// The className is not found
if (length === classes.length) {
classes.push(className);
}
element.className = classes.join(' ');
}
function toggleAll(e) {
var active = 'active';
e.preventDefault();
toggleClass(layout, active);
toggleClass(menu, active);
toggleClass(menuLink, active);
}
menuLink.onclick = function (e) {
toggleAll(e);
};
content.onclick = function(e) {
if (menu.className.indexOf('active') !== -1) {
toggleAll(e);
}
};
}(this, this.document));</script></div></body></html> | {
"pile_set_name": "Github"
} |
if isActive:
if not self.repository.retractWithinIsland.value:
locationEnclosureIndex = self.getSmallestEnclosureIndex(location.dropAxis())
if locationEnclosureIndex != self.getSmallestEnclosureIndex(self.oldLocation.dropAxis()):
return None
locationMinusOld = location - self.oldLocation
xyTravel = abs(locationMinusOld.dropAxis())
zTravelMultiplied = locationMinusOld.z * self.zDistanceRatio
return math.sqrt(xyTravel * xyTravel + zTravelMultiplied * zTravelMultiplied)
else:
location = gcodec.getLocationFromSplitLine(location, splitLine) | {
"pile_set_name": "Github"
} |
import { renderHook, cleanup } from '@testing-library/react-hooks';
import useGeolocation from '../dist/useGeolocation';
import GeoLocationApiMock, { watchPositionSpy } from './mocks/GeoLocationApi.mock';
describe('useGeolocation', () => {
before(() => {
window.navigator.geolocation = GeoLocationApiMock;
});
beforeEach(cleanup);
after(() => {
delete window.navigator.geolocation;
});
it('should be a function', () => {
expect(useGeolocation).to.be.a('function');
});
it('should return an array where the first item is a geolocation state and the second an object of setters', () => {
const { result } = renderHook(() => useGeolocation());
expect(result.current).to.be.an('array');
expect(result.current.length).to.equal(2);
expect(result.current[0]).to.be.a('object').that.has.all.deep.keys('isSupported', 'isRetrieving', 'position');
expect(result.current[1]).to.be.an('object').that.has.all.keys('isSupported', 'onChange', 'onError');
});
it('the provided options should be passed down to the other hooks', () => {
const optionsMock = { enableHighAccuracy: true };
renderHook(() => useGeolocation(optionsMock));
GeoLocationApiMock.listeners.s();
GeoLocationApiMock.listeners.e();
expect(watchPositionSpy.called).to.be.true;
const lastOptions = watchPositionSpy.args[watchPositionSpy.callCount - 1][0];
expect(lastOptions).to.equal(optionsMock);
});
});
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>幻灯管理</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel='stylesheet' type='text/css' href='__PUBLIC__/css/admin-style.css' />
<script language="JavaScript" type="text/javascript" charset="utf-8" src="__PUBLIC__/jquery/jquery-1.7.2.min.js"></script>
<script language="JavaScript" type="text/javascript" charset="utf-8" src="__PUBLIC__/js/admin.js"></script>
<script language="javascript">
$(document).ready(function(){
$gxlcms.show.table();
});
</script>
</head>
<body class="body">
<table border="0" cellpadding="0" cellspacing="0" class="table">
<thead><tr><th colspan="3" class="r"><span style="float:left">幻灯贴片管理</span><span style="float:right"><a href="?s=Admin-Slide-Add">添加幻灯贴片</a></span></th></tr></thead>
<volist name="list_slide" id="ppting">
<tbody>
<tr>
<td class="l ct" width="180" style="padding:5px 0px"><a href="{$ppting.slide_pic}" target="_blank"><img src="{$ppting.slide_pic}" width="150px" height="75px" alt="查看原图" style="border:1px solid #CCCCCC;padding:1px;"></a></td>
<td class="l pd" style="line-height:18px;color:#333"><a href="{$ppting.slide_url}" target="_blank"><font style="font-size:14px;font-weight:bold;">{$ppting.slide_name}</font></a><br>{$ppting.slide_content}</td>
<td class="r ct" width="100"><a href="?s=Admin-Slide-Add-id-{$ppting.slide_id}">修改</a> <a href="?s=Admin-Slide-Del-id-{$ppting.slide_id}" onClick="return confirm('确定删除该幻灯片吗?')" title="点击删除幻灯片">删除</a> <eq name="ppting['slide_status']" value="1"><a href="?s=Admin-Slide-Status-id-{$ppting.slide_id}-sid-0" title="点击隐藏幻灯">隐藏</a><else /><a href="?s=Admin-Slide-Status-id-{$ppting.slide_id}-sid-1" title="点击显示幻灯片"><font color="red">显示</font></a></eq></td>
</tr>
</tbody>
</volist>
</table>
<include file="./Public/admin/footer.html" />
</body>
</html> | {
"pile_set_name": "Github"
} |
ints = [1, 2, 3]
floats = [1.1, 2.1, 3.1]
strings = ["a", "b", "c"]
dates = [
1987-07-05T17:45:00Z,
1979-05-27T07:32:00Z,
2006-06-01T11:00:00Z,
]
comments = [
1,
2, #this is ok
]
| {
"pile_set_name": "Github"
} |
/* Area: closure_call
Purpose: Check return value float.
Limitations: none.
PR: none.
Originator: <[email protected]> 20030828 */
/* { dg-do run } */
#include "ffitest.h"
static void cls_ret_float_fn(ffi_cif* cif __UNUSED__, void* resp, void** args,
void* userdata __UNUSED__)
{
*(float *)resp = *(float *)args[0];
printf("%g: %g\n",*(float *)args[0],
*(float *)resp);
}
typedef float (*cls_ret_float)(float);
int main (void)
{
ffi_cif cif;
void *code;
ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
ffi_type * cl_arg_types[2];
float res;
cl_arg_types[0] = &ffi_type_float;
cl_arg_types[1] = NULL;
/* Initialize the cif */
CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
&ffi_type_float, cl_arg_types) == FFI_OK);
CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_float_fn, NULL, code) == FFI_OK);
res = ((((cls_ret_float)code)(-2122.12)));
/* { dg-output "\\-2122.12: \\-2122.12" } */
printf("res: %.6f\n", res);
/* { dg-output "\nres: \-2122.120117" } */
exit(0);
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head><link rel="apple-touch-icon" sizes="180x180" href="/glide/apple-touch-icon.png"><link rel="icon" type="image/png" sizes="32x32" href="/glide/favicon-32x32.png"><link rel="icon" type="image/png" sizes="16x16" href="/glide/favicon-16x16.png"><link rel="manifest" href="/glide/manifest.json">
<!-- Generated by javadoc (1.8.0_221) on Fri Sep 27 11:07:57 PDT 2019 -->
<title>BitmapPool (glide API)</title>
<meta name="date" content="2019-09-27">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="BitmapPool (glide API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6,"i1":6,"i2":6,"i3":6,"i4":6,"i5":6,"i6":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/ArrayPool.html" title="interface in com.bumptech.glide.load.engine.bitmap_recycle"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPoolAdapter.html" title="class in com.bumptech.glide.load.engine.bitmap_recycle"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/bumptech/glide/load/engine/bitmap_recycle/BitmapPool.html" target="_top">Frames</a></li>
<li><a href="BitmapPool.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.bumptech.glide.load.engine.bitmap_recycle</div>
<h2 title="Interface BitmapPool" class="title">Interface BitmapPool</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPoolAdapter.html" title="class in com.bumptech.glide.load.engine.bitmap_recycle">BitmapPoolAdapter</a>, <a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/LruBitmapPool.html" title="class in com.bumptech.glide.load.engine.bitmap_recycle">LruBitmapPool</a></dd>
</dl>
<hr>
<br>
<pre>public interface <span class="typeNameLabel">BitmapPool</span></pre>
<div class="block">An interface for a pool that allows users to reuse <code>Bitmap</code> objects.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPool.html#clearMemory--">clearMemory</a></span>()</code>
<div class="block">Removes all <code>Bitmap</code>s from the pool.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>android.graphics.Bitmap</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPool.html#get-int-int-android.graphics.Bitmap.Config-">get</a></span>(int width,
int height,
android.graphics.Bitmap.Config config)</code>
<div class="block">Returns a <code>Bitmap</code> of exactly the given width, height, and
configuration, and containing only transparent pixels.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>android.graphics.Bitmap</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPool.html#getDirty-int-int-android.graphics.Bitmap.Config-">getDirty</a></span>(int width,
int height,
android.graphics.Bitmap.Config config)</code>
<div class="block">Identical to <a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPool.html#get-int-int-android.graphics.Bitmap.Config-"><code>get(int, int, android.graphics.Bitmap.Config)</code></a> except that any returned
<code>Bitmap</code> may <em>not</em> have been erased and may contain random data.</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>long</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPool.html#getMaxSize--">getMaxSize</a></span>()</code>
<div class="block">Returns the current maximum size of the pool in bytes.</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPool.html#put-android.graphics.Bitmap-">put</a></span>(android.graphics.Bitmap bitmap)</code>
<div class="block">Adds the given <code>Bitmap</code> if it is eligible to be re-used and the pool can
fit it, or calls <code>Bitmap.recycle()</code> on the Bitmap and discards it.</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPool.html#setSizeMultiplier-float-">setSizeMultiplier</a></span>(float sizeMultiplier)</code>
<div class="block">Multiplies the initial size of the pool by the given multiplier to dynamically and
synchronously allow users to adjust the size of the pool.</div>
</td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPool.html#trimMemory-int-">trimMemory</a></span>(int level)</code>
<div class="block">Reduces the size of the cache by evicting items based on the given level.</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getMaxSize--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getMaxSize</h4>
<pre>long getMaxSize()</pre>
<div class="block">Returns the current maximum size of the pool in bytes.</div>
</li>
</ul>
<a name="setSizeMultiplier-float-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setSizeMultiplier</h4>
<pre>void setSizeMultiplier(float sizeMultiplier)</pre>
<div class="block">Multiplies the initial size of the pool by the given multiplier to dynamically and
synchronously allow users to adjust the size of the pool.
<p>If the current total size of the pool is larger than the max size after the given multiplier
is applied, <code>Bitmap</code>s should be evicted until the pool is smaller than the new max size.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>sizeMultiplier</code> - The size multiplier to apply between 0 and 1.</dd>
</dl>
</li>
</ul>
<a name="put-android.graphics.Bitmap-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>put</h4>
<pre>void put(android.graphics.Bitmap bitmap)</pre>
<div class="block">Adds the given <code>Bitmap</code> if it is eligible to be re-used and the pool can
fit it, or calls <code>Bitmap.recycle()</code> on the Bitmap and discards it.
<p>Callers must <em>not</em> continue to use the Bitmap after calling this method.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>bitmap</code> - The <code>Bitmap</code> to attempt to add.</dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><code>Bitmap.isMutable()</code>,
<code>Bitmap.recycle()</code></dd>
</dl>
</li>
</ul>
<a name="get-int-int-android.graphics.Bitmap.Config-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>get</h4>
<pre>@NonNull
android.graphics.Bitmap get(int width,
int height,
android.graphics.Bitmap.Config config)</pre>
<div class="block">Returns a <code>Bitmap</code> of exactly the given width, height, and
configuration, and containing only transparent pixels.
<p>If no Bitmap with the requested attributes is present in the pool, a new one will be
allocated.
<p>Because this method erases all pixels in the <code>Bitmap</code>, this method is slightly slower
than <a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPool.html#getDirty-int-int-android.graphics.Bitmap.Config-"><code>getDirty(int, int, android.graphics.Bitmap.Config)</code></a>. If the <code>Bitmap</code> is being obtained to be used in <code>BitmapFactory</code>
or in any other case where every pixel in the <code>Bitmap</code> will always be
overwritten or cleared, <a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPool.html#getDirty-int-int-android.graphics.Bitmap.Config-"><code>getDirty(int, int, android.graphics.Bitmap.Config)</code></a> will be
faster. When in doubt, use this method to ensure correctness.
<pre>
Implementations can should clear out every returned Bitmap using the following:
<code>
bitmap.eraseColor(Color.TRANSPARENT);
</code>
</pre></div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>width</code> - The width in pixels of the desired <code>Bitmap</code>.</dd>
<dd><code>height</code> - The height in pixels of the desired <code>Bitmap</code>.</dd>
<dd><code>config</code> - The <code>Bitmap.Config</code> of the desired <code>Bitmap</code>.</dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPool.html#getDirty-int-int-android.graphics.Bitmap.Config-"><code>getDirty(int, int, android.graphics.Bitmap.Config)</code></a></dd>
</dl>
</li>
</ul>
<a name="getDirty-int-int-android.graphics.Bitmap.Config-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDirty</h4>
<pre>@NonNull
android.graphics.Bitmap getDirty(int width,
int height,
android.graphics.Bitmap.Config config)</pre>
<div class="block">Identical to <a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPool.html#get-int-int-android.graphics.Bitmap.Config-"><code>get(int, int, android.graphics.Bitmap.Config)</code></a> except that any returned
<code>Bitmap</code> may <em>not</em> have been erased and may contain random data.
<p>If no Bitmap with the requested attributes is present in the pool, a new one will be
allocated.
<p>Although this method is slightly more efficient than <a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPool.html#get-int-int-android.graphics.Bitmap.Config-"><code>get(int, int,
android.graphics.Bitmap.Config)</code></a> it should be used with caution and only when the caller is
sure that they are going to erase the <code>Bitmap</code> entirely before writing
new data to it.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>width</code> - The width in pixels of the desired <code>Bitmap</code>.</dd>
<dd><code>height</code> - The height in pixels of the desired <code>Bitmap</code>.</dd>
<dd><code>config</code> - The <code>Bitmap.Config</code> of the desired <code>Bitmap</code>.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>A <code>Bitmap</code> with exactly the given width, height, and config
potentially containing random image data.</dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPool.html#get-int-int-android.graphics.Bitmap.Config-"><code>get(int, int, android.graphics.Bitmap.Config)</code></a></dd>
</dl>
</li>
</ul>
<a name="clearMemory--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>clearMemory</h4>
<pre>void clearMemory()</pre>
<div class="block">Removes all <code>Bitmap</code>s from the pool.</div>
</li>
</ul>
<a name="trimMemory-int-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>trimMemory</h4>
<pre>void trimMemory(int level)</pre>
<div class="block">Reduces the size of the cache by evicting items based on the given level.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>level</code> - The level from <code>ComponentCallbacks2</code> to use to determine how
many <code>Bitmap</code>s to evict.</dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><code>ComponentCallbacks2</code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/ArrayPool.html" title="interface in com.bumptech.glide.load.engine.bitmap_recycle"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../com/bumptech/glide/load/engine/bitmap_recycle/BitmapPoolAdapter.html" title="class in com.bumptech.glide.load.engine.bitmap_recycle"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/bumptech/glide/load/engine/bitmap_recycle/BitmapPool.html" target="_top">Frames</a></li>
<li><a href="BitmapPool.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"pile_set_name": "Github"
} |
/* Persian (Farsi) Translation for the jQuery UI date picker plugin. */
/* Javad Mowlanezhad -- [email protected] */
/* Jalali calendar should supported soon! (Its implemented but I have to test it) */
jQuery(function($) {
$.datepicker.regional['fa'] = {
closeText: 'بستن',
prevText: '<قبلي',
nextText: 'بعدي>',
currentText: 'امروز',
monthNames: ['فروردين','ارديبهشت','خرداد','تير','مرداد','شهريور',
'مهر','آبان','آذر','دي','بهمن','اسفند'],
monthNamesShort: ['1','2','3','4','5','6','7','8','9','10','11','12'],
dayNames: ['يکشنبه','دوشنبه','سهشنبه','چهارشنبه','پنجشنبه','جمعه','شنبه'],
dayNamesShort: ['ي','د','س','چ','پ','ج', 'ش'],
dayNamesMin: ['ي','د','س','چ','پ','ج', 'ش'],
dateFormat: 'yy/mm/dd', firstDay: 6,
isRTL: true};
$.datepicker.setDefaults($.datepicker.regional['fa']);
}); | {
"pile_set_name": "Github"
} |
package semver
import (
"fmt"
"strconv"
"strings"
"unicode"
)
type wildcardType int
const (
noneWildcard wildcardType = iota
majorWildcard wildcardType = 1
minorWildcard wildcardType = 2
patchWildcard wildcardType = 3
)
func wildcardTypefromInt(i int) wildcardType {
switch i {
case 1:
return majorWildcard
case 2:
return minorWildcard
case 3:
return patchWildcard
default:
return noneWildcard
}
}
type comparator func(Version, Version) bool
var (
compEQ comparator = func(v1 Version, v2 Version) bool {
return v1.Compare(v2) == 0
}
compNE = func(v1 Version, v2 Version) bool {
return v1.Compare(v2) != 0
}
compGT = func(v1 Version, v2 Version) bool {
return v1.Compare(v2) == 1
}
compGE = func(v1 Version, v2 Version) bool {
return v1.Compare(v2) >= 0
}
compLT = func(v1 Version, v2 Version) bool {
return v1.Compare(v2) == -1
}
compLE = func(v1 Version, v2 Version) bool {
return v1.Compare(v2) <= 0
}
)
type versionRange struct {
v Version
c comparator
}
// rangeFunc creates a Range from the given versionRange.
func (vr *versionRange) rangeFunc() Range {
return Range(func(v Version) bool {
return vr.c(v, vr.v)
})
}
// Range represents a range of versions.
// A Range can be used to check if a Version satisfies it:
//
// range, err := semver.ParseRange(">1.0.0 <2.0.0")
// range(semver.MustParse("1.1.1") // returns true
type Range func(Version) bool
// OR combines the existing Range with another Range using logical OR.
func (rf Range) OR(f Range) Range {
return Range(func(v Version) bool {
return rf(v) || f(v)
})
}
// AND combines the existing Range with another Range using logical AND.
func (rf Range) AND(f Range) Range {
return Range(func(v Version) bool {
return rf(v) && f(v)
})
}
// ParseRange parses a range and returns a Range.
// If the range could not be parsed an error is returned.
//
// Valid ranges are:
// - "<1.0.0"
// - "<=1.0.0"
// - ">1.0.0"
// - ">=1.0.0"
// - "1.0.0", "=1.0.0", "==1.0.0"
// - "!1.0.0", "!=1.0.0"
//
// A Range can consist of multiple ranges separated by space:
// Ranges can be linked by logical AND:
// - ">1.0.0 <2.0.0" would match between both ranges, so "1.1.1" and "1.8.7" but not "1.0.0" or "2.0.0"
// - ">1.0.0 <3.0.0 !2.0.3-beta.2" would match every version between 1.0.0 and 3.0.0 except 2.0.3-beta.2
//
// Ranges can also be linked by logical OR:
// - "<2.0.0 || >=3.0.0" would match "1.x.x" and "3.x.x" but not "2.x.x"
//
// AND has a higher precedence than OR. It's not possible to use brackets.
//
// Ranges can be combined by both AND and OR
//
// - `>1.0.0 <2.0.0 || >3.0.0 !4.2.1` would match `1.2.3`, `1.9.9`, `3.1.1`, but not `4.2.1`, `2.1.1`
func ParseRange(s string) (Range, error) {
parts := splitAndTrim(s)
orParts, err := splitORParts(parts)
if err != nil {
return nil, err
}
expandedParts, err := expandWildcardVersion(orParts)
if err != nil {
return nil, err
}
var orFn Range
for _, p := range expandedParts {
var andFn Range
for _, ap := range p {
opStr, vStr, err := splitComparatorVersion(ap)
if err != nil {
return nil, err
}
vr, err := buildVersionRange(opStr, vStr)
if err != nil {
return nil, fmt.Errorf("Could not parse Range %q: %s", ap, err)
}
rf := vr.rangeFunc()
// Set function
if andFn == nil {
andFn = rf
} else { // Combine with existing function
andFn = andFn.AND(rf)
}
}
if orFn == nil {
orFn = andFn
} else {
orFn = orFn.OR(andFn)
}
}
return orFn, nil
}
// splitORParts splits the already cleaned parts by '||'.
// Checks for invalid positions of the operator and returns an
// error if found.
func splitORParts(parts []string) ([][]string, error) {
var ORparts [][]string
last := 0
for i, p := range parts {
if p == "||" {
if i == 0 {
return nil, fmt.Errorf("First element in range is '||'")
}
ORparts = append(ORparts, parts[last:i])
last = i + 1
}
}
if last == len(parts) {
return nil, fmt.Errorf("Last element in range is '||'")
}
ORparts = append(ORparts, parts[last:])
return ORparts, nil
}
// buildVersionRange takes a slice of 2: operator and version
// and builds a versionRange, otherwise an error.
func buildVersionRange(opStr, vStr string) (*versionRange, error) {
c := parseComparator(opStr)
if c == nil {
return nil, fmt.Errorf("Could not parse comparator %q in %q", opStr, strings.Join([]string{opStr, vStr}, ""))
}
v, err := Parse(vStr)
if err != nil {
return nil, fmt.Errorf("Could not parse version %q in %q: %s", vStr, strings.Join([]string{opStr, vStr}, ""), err)
}
return &versionRange{
v: v,
c: c,
}, nil
}
// inArray checks if a byte is contained in an array of bytes
func inArray(s byte, list []byte) bool {
for _, el := range list {
if el == s {
return true
}
}
return false
}
// splitAndTrim splits a range string by spaces and cleans whitespaces
func splitAndTrim(s string) (result []string) {
last := 0
var lastChar byte
excludeFromSplit := []byte{'>', '<', '='}
for i := 0; i < len(s); i++ {
if s[i] == ' ' && !inArray(lastChar, excludeFromSplit) {
if last < i-1 {
result = append(result, s[last:i])
}
last = i + 1
} else if s[i] != ' ' {
lastChar = s[i]
}
}
if last < len(s)-1 {
result = append(result, s[last:])
}
for i, v := range result {
result[i] = strings.Replace(v, " ", "", -1)
}
// parts := strings.Split(s, " ")
// for _, x := range parts {
// if s := strings.TrimSpace(x); len(s) != 0 {
// result = append(result, s)
// }
// }
return
}
// splitComparatorVersion splits the comparator from the version.
// Input must be free of leading or trailing spaces.
func splitComparatorVersion(s string) (string, string, error) {
i := strings.IndexFunc(s, unicode.IsDigit)
if i == -1 {
return "", "", fmt.Errorf("Could not get version from string: %q", s)
}
return strings.TrimSpace(s[0:i]), s[i:], nil
}
// getWildcardType will return the type of wildcard that the
// passed version contains
func getWildcardType(vStr string) wildcardType {
parts := strings.Split(vStr, ".")
nparts := len(parts)
wildcard := parts[nparts-1]
possibleWildcardType := wildcardTypefromInt(nparts)
if wildcard == "x" {
return possibleWildcardType
}
return noneWildcard
}
// createVersionFromWildcard will convert a wildcard version
// into a regular version, replacing 'x's with '0's, handling
// special cases like '1.x.x' and '1.x'
func createVersionFromWildcard(vStr string) string {
// handle 1.x.x
vStr2 := strings.Replace(vStr, ".x.x", ".x", 1)
vStr2 = strings.Replace(vStr2, ".x", ".0", 1)
parts := strings.Split(vStr2, ".")
// handle 1.x
if len(parts) == 2 {
return vStr2 + ".0"
}
return vStr2
}
// incrementMajorVersion will increment the major version
// of the passed version
func incrementMajorVersion(vStr string) (string, error) {
parts := strings.Split(vStr, ".")
i, err := strconv.Atoi(parts[0])
if err != nil {
return "", err
}
parts[0] = strconv.Itoa(i + 1)
return strings.Join(parts, "."), nil
}
// incrementMajorVersion will increment the minor version
// of the passed version
func incrementMinorVersion(vStr string) (string, error) {
parts := strings.Split(vStr, ".")
i, err := strconv.Atoi(parts[1])
if err != nil {
return "", err
}
parts[1] = strconv.Itoa(i + 1)
return strings.Join(parts, "."), nil
}
// expandWildcardVersion will expand wildcards inside versions
// following these rules:
//
// * when dealing with patch wildcards:
// >= 1.2.x will become >= 1.2.0
// <= 1.2.x will become < 1.3.0
// > 1.2.x will become >= 1.3.0
// < 1.2.x will become < 1.2.0
// != 1.2.x will become < 1.2.0 >= 1.3.0
//
// * when dealing with minor wildcards:
// >= 1.x will become >= 1.0.0
// <= 1.x will become < 2.0.0
// > 1.x will become >= 2.0.0
// < 1.0 will become < 1.0.0
// != 1.x will become < 1.0.0 >= 2.0.0
//
// * when dealing with wildcards without
// version operator:
// 1.2.x will become >= 1.2.0 < 1.3.0
// 1.x will become >= 1.0.0 < 2.0.0
func expandWildcardVersion(parts [][]string) ([][]string, error) {
var expandedParts [][]string
for _, p := range parts {
var newParts []string
for _, ap := range p {
if strings.Index(ap, "x") != -1 {
opStr, vStr, err := splitComparatorVersion(ap)
if err != nil {
return nil, err
}
versionWildcardType := getWildcardType(vStr)
flatVersion := createVersionFromWildcard(vStr)
var resultOperator string
var shouldIncrementVersion bool
switch opStr {
case ">":
resultOperator = ">="
shouldIncrementVersion = true
case ">=":
resultOperator = ">="
case "<":
resultOperator = "<"
case "<=":
resultOperator = "<"
shouldIncrementVersion = true
case "", "=", "==":
newParts = append(newParts, ">="+flatVersion)
resultOperator = "<"
shouldIncrementVersion = true
case "!=", "!":
newParts = append(newParts, "<"+flatVersion)
resultOperator = ">="
shouldIncrementVersion = true
}
var resultVersion string
if shouldIncrementVersion {
switch versionWildcardType {
case patchWildcard:
resultVersion, _ = incrementMinorVersion(flatVersion)
case minorWildcard:
resultVersion, _ = incrementMajorVersion(flatVersion)
}
} else {
resultVersion = flatVersion
}
ap = resultOperator + resultVersion
}
newParts = append(newParts, ap)
}
expandedParts = append(expandedParts, newParts)
}
return expandedParts, nil
}
func parseComparator(s string) comparator {
switch s {
case "==":
fallthrough
case "":
fallthrough
case "=":
return compEQ
case ">":
return compGT
case ">=":
return compGE
case "<":
return compLT
case "<=":
return compLE
case "!":
fallthrough
case "!=":
return compNE
}
return nil
}
// MustParseRange is like ParseRange but panics if the range cannot be parsed.
func MustParseRange(s string) Range {
r, err := ParseRange(s)
if err != nil {
panic(`semver: ParseRange(` + s + `): ` + err.Error())
}
return r
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Fling Engine: FlingEngine/Utils/inc/Logger.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="profile_64x64.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">Fling Engine
 <span id="projectnumber">0.00.1</span>
</div>
<div id="projectbrief">Fling Engine is a game engine written in Vulkan</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_dac37bced2577707af14f619e2856e8f.html">FlingEngine</a></li><li class="navelem"><a class="el" href="dir_55ecbc77275e3c815c2a05e27be1f745.html">Utils</a></li><li class="navelem"><a class="el" href="dir_66a1f4f9c0e47618d929524f81e3e53b.html">inc</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">Logger.h</div> </div>
</div><!--header-->
<div class="contents">
<a href="Logger_8h.html">Go to the documentation of this file.</a><div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> <span class="preprocessor">#pragma once</span></div><div class="line"><a name="l00002"></a><span class="lineno"> 2</span> </div><div class="line"><a name="l00003"></a><span class="lineno"> 3</span> <span class="preprocessor">#include "<a class="code" href="Platform_8h.html">Platform.h</a>"</span></div><div class="line"><a name="l00004"></a><span class="lineno"> 4</span> <span class="preprocessor">#include "<a class="code" href="Singleton_8hpp.html">Singleton.hpp</a>"</span></div><div class="line"><a name="l00005"></a><span class="lineno"> 5</span> </div><div class="line"><a name="l00006"></a><span class="lineno"><a class="line" href="Logger_8h.html#a23a1fceae70872ee410be4c0e5d533ff"> 6</a></span> <span class="preprocessor">#define SPDLOG_TRACE_ON</span></div><div class="line"><a name="l00007"></a><span class="lineno"><a class="line" href="Logger_8h.html#a8fcb66a8ecd0d5f3e8cff18463b3a74c"> 7</a></span> <span class="preprocessor">#define SPDLOG_DEBUG_ON</span></div><div class="line"><a name="l00008"></a><span class="lineno"> 8</span> </div><div class="line"><a name="l00009"></a><span class="lineno"> 9</span> <span class="preprocessor">#include "spdlog/spdlog.h"</span></div><div class="line"><a name="l00010"></a><span class="lineno"> 10</span> <span class="preprocessor">#include "spdlog/sinks/stdout_sinks.h"</span></div><div class="line"><a name="l00011"></a><span class="lineno"> 11</span> <span class="preprocessor">#include "spdlog/sinks/basic_file_sink.h"</span></div><div class="line"><a name="l00012"></a><span class="lineno"> 12</span> <span class="preprocessor">#include "spdlog/async.h"</span></div><div class="line"><a name="l00013"></a><span class="lineno"> 13</span> <span class="preprocessor">#include "spdlog/sinks/stdout_color_sinks.h"</span></div><div class="line"><a name="l00014"></a><span class="lineno"> 14</span> <span class="preprocessor">#include "spdlog/fmt/fmt.h"</span></div><div class="line"><a name="l00015"></a><span class="lineno"> 15</span> <span class="preprocessor">#include "spdlog/fmt/ostr.h"</span></div><div class="line"><a name="l00016"></a><span class="lineno"> 16</span> </div><div class="line"><a name="l00017"></a><span class="lineno"> 17</span> <span class="keyword">namespace </span><a class="code" href="namespaceFling.html">Fling</a></div><div class="line"><a name="l00018"></a><span class="lineno"> 18</span> {</div><div class="line"><a name="l00023"></a><span class="lineno"><a class="line" href="classFling_1_1Logger.html"> 23</a></span>  <span class="keyword">class </span><a class="code" href="classFling_1_1Logger.html">Logger</a> : <span class="keyword">public</span> <a class="code" href="classFling_1_1Singleton.html">Singleton</a><Logger></div><div class="line"><a name="l00024"></a><span class="lineno"> 24</span>  {</div><div class="line"><a name="l00025"></a><span class="lineno"> 25</span>  <span class="keyword">public</span>:</div><div class="line"><a name="l00026"></a><span class="lineno"> 26</span> </div><div class="line"><a name="l00027"></a><span class="lineno"> 27</span>  <span class="keyword">virtual</span> <span class="keywordtype">void</span> <a class="code" href="classFling_1_1Logger.html#a4115a90215df6200a96276bb1da0ef8b">Init</a>() <span class="keyword">override</span>;</div><div class="line"><a name="l00028"></a><span class="lineno"> 28</span> </div><div class="line"><a name="l00033"></a><span class="lineno"> 33</span>  <span class="keyword">static</span> std::shared_ptr<spdlog::logger> <a class="code" href="classFling_1_1Logger.html#a213d4af1de4e026e2a0cebd500b383de">GetCurrentConsole</a>();</div><div class="line"><a name="l00034"></a><span class="lineno"> 34</span> </div><div class="line"><a name="l00038"></a><span class="lineno"> 38</span>  <span class="keyword">static</span> std::shared_ptr<spdlog::logger> <a class="code" href="classFling_1_1Logger.html#a6dbddf8afe9e82da81eec7f516e07864">GetCurrentLogFile</a>();</div><div class="line"><a name="l00039"></a><span class="lineno"> 39</span> </div><div class="line"><a name="l00040"></a><span class="lineno"> 40</span> </div><div class="line"><a name="l00041"></a><span class="lineno"> 41</span>  <span class="keyword">protected</span>:</div><div class="line"><a name="l00042"></a><span class="lineno"> 42</span> </div><div class="line"><a name="l00044"></a><span class="lineno"><a class="line" href="classFling_1_1Logger.html#a07d825421fb00d9e5b1ff931b97dc5bd"> 44</a></span>  <span class="keyword">static</span> std::shared_ptr<spdlog::logger> <a class="code" href="classFling_1_1Logger.html#a07d825421fb00d9e5b1ff931b97dc5bd">m_Console</a>;</div><div class="line"><a name="l00045"></a><span class="lineno"> 45</span> </div><div class="line"><a name="l00047"></a><span class="lineno"><a class="line" href="classFling_1_1Logger.html#ade8791b704eabf05d7a1d40a117fb45d"> 47</a></span>  <span class="keyword">static</span> std::shared_ptr<spdlog::logger> <a class="code" href="classFling_1_1Logger.html#ade8791b704eabf05d7a1d40a117fb45d">m_FileLog</a>;</div><div class="line"><a name="l00048"></a><span class="lineno"> 48</span> </div><div class="line"><a name="l00049"></a><span class="lineno"> 49</span>  };</div><div class="line"><a name="l00050"></a><span class="lineno"> 50</span> </div><div class="line"><a name="l00051"></a><span class="lineno"> 51</span> } <span class="comment">// namespace Fling</span></div><div class="line"><a name="l00052"></a><span class="lineno"> 52</span> </div><div class="line"><a name="l00053"></a><span class="lineno"> 53</span> <span class="comment">// Debug/release mode defs</span></div><div class="line"><a name="l00054"></a><span class="lineno"> 54</span> <span class="preprocessor">#if FLING_DEBUG || defined ( F_ENABLE_LOGGING )</span></div><div class="line"><a name="l00055"></a><span class="lineno"> 55</span> </div><div class="line"><a name="l00056"></a><span class="lineno"> 56</span> <span class="preprocessor">#define F_LOG_TRACE( ... ) Fling::Logger::GetCurrentConsole()->info( __VA_ARGS__ ); Fling::Logger::GetCurrentLogFile()->info( __VA_ARGS__ )</span></div><div class="line"><a name="l00057"></a><span class="lineno"> 57</span> <span class="preprocessor">#define F_LOG_WARN( ... ) Fling::Logger::GetCurrentConsole()->warn( __VA_ARGS__ ); Fling::Logger::GetCurrentLogFile()->warn( __VA_ARGS__ )</span></div><div class="line"><a name="l00058"></a><span class="lineno"> 58</span> <span class="preprocessor">#define F_LOG_ERROR( ... ) Fling::Logger::GetCurrentConsole()->error( __VA_ARGS__ ); Fling::Logger::GetCurrentLogFile()->error( __VA_ARGS__ );</span></div><div class="line"><a name="l00059"></a><span class="lineno"> 59</span> </div><div class="line"><a name="l00062"></a><span class="lineno"> 62</span> <span class="preprocessor">#define F_LOG_FATAL( ... ) Fling::Logger::GetCurrentConsole()->error( __VA_ARGS__ ); \</span></div><div class="line"><a name="l00063"></a><span class="lineno"> 63</span> <span class="preprocessor"> throw std::runtime_error( __VA_ARGS__ )</span></div><div class="line"><a name="l00064"></a><span class="lineno"> 64</span> </div><div class="line"><a name="l00065"></a><span class="lineno"> 65</span> <span class="preprocessor">#else</span></div><div class="line"><a name="l00066"></a><span class="lineno"> 66</span> </div><div class="line"><a name="l00067"></a><span class="lineno"><a class="line" href="Logger_8h.html#a073083a6a28c233400ee488e689f3d94"> 67</a></span> <span class="preprocessor">#define F_LOG_TRACE( ... ) </span></div><div class="line"><a name="l00068"></a><span class="lineno"><a class="line" href="Logger_8h.html#a3233b5f2a5e5f1ff0200ee7e82dcb9ca"> 68</a></span> <span class="preprocessor">#define F_LOG_WARN( ... ) </span></div><div class="line"><a name="l00069"></a><span class="lineno"><a class="line" href="Logger_8h.html#a3b44eb747374e4b51695c30efa18a938"> 69</a></span> <span class="preprocessor">#define F_LOG_ERROR( ... ) </span></div><div class="line"><a name="l00070"></a><span class="lineno"> 70</span> </div><div class="line"><a name="l00073"></a><span class="lineno"><a class="line" href="Logger_8h.html#a3786e3632dad7984ff6735325a2aaf3e"> 73</a></span> <span class="preprocessor">#define F_LOG_FATAL( ... ) Fling::Logger::GetCurrentConsole()->error( __VA_ARGS__ ); \</span></div><div class="line"><a name="l00074"></a><span class="lineno"> 74</span> <span class="preprocessor"> throw std::runtime_error( __VA_ARGS__ )</span></div><div class="line"><a name="l00075"></a><span class="lineno"> 75</span> <span class="preprocessor">#endif</span></div><div class="ttc" id="classFling_1_1Logger_html_a07d825421fb00d9e5b1ff931b97dc5bd"><div class="ttname"><a href="classFling_1_1Logger.html#a07d825421fb00d9e5b1ff931b97dc5bd">Fling::Logger::m_Console</a></div><div class="ttdeci">static std::shared_ptr< spdlog::logger > m_Console</div><div class="ttdoc">Pointer to the current console that is being used for logging. </div><div class="ttdef"><b>Definition:</b> Logger.h:44</div></div>
<div class="ttc" id="classFling_1_1Logger_html_a6dbddf8afe9e82da81eec7f516e07864"><div class="ttname"><a href="classFling_1_1Logger.html#a6dbddf8afe9e82da81eec7f516e07864">Fling::Logger::GetCurrentLogFile</a></div><div class="ttdeci">static std::shared_ptr< spdlog::logger > GetCurrentLogFile()</div><div class="ttdoc">Get the current async log file that is being written to. </div><div class="ttdef"><b>Definition:</b> Logger.cpp:42</div></div>
<div class="ttc" id="classFling_1_1Logger_html_a4115a90215df6200a96276bb1da0ef8b"><div class="ttname"><a href="classFling_1_1Logger.html#a4115a90215df6200a96276bb1da0ef8b">Fling::Logger::Init</a></div><div class="ttdeci">virtual void Init() override</div><div class="ttdef"><b>Definition:</b> Logger.cpp:10</div></div>
<div class="ttc" id="classFling_1_1Singleton_html"><div class="ttname"><a href="classFling_1_1Singleton.html">Fling::Singleton</a></div><div class="ttdoc">Class that can have only one instance. </div><div class="ttdef"><b>Definition:</b> Singleton.hpp:11</div></div>
<div class="ttc" id="classFling_1_1Logger_html_a213d4af1de4e026e2a0cebd500b383de"><div class="ttname"><a href="classFling_1_1Logger.html#a213d4af1de4e026e2a0cebd500b383de">Fling::Logger::GetCurrentConsole</a></div><div class="ttdeci">static std::shared_ptr< spdlog::logger > GetCurrentConsole()</div><div class="ttdoc">Gets a reference to the current logging console </div><div class="ttdef"><b>Definition:</b> Logger.cpp:37</div></div>
<div class="ttc" id="classFling_1_1Logger_html"><div class="ttname"><a href="classFling_1_1Logger.html">Fling::Logger</a></div><div class="ttdoc">Singleton class that allows logging to the console as well as async to a file. </div><div class="ttdef"><b>Definition:</b> Logger.h:23</div></div>
<div class="ttc" id="classFling_1_1Logger_html_ade8791b704eabf05d7a1d40a117fb45d"><div class="ttname"><a href="classFling_1_1Logger.html#ade8791b704eabf05d7a1d40a117fb45d">Fling::Logger::m_FileLog</a></div><div class="ttdeci">static std::shared_ptr< spdlog::logger > m_FileLog</div><div class="ttdoc">Pointer to the log file logger. </div><div class="ttdef"><b>Definition:</b> Logger.h:47</div></div>
<div class="ttc" id="namespaceFling_html"><div class="ttname"><a href="namespaceFling.html">Fling</a></div><div class="ttdef"><b>Definition:</b> Engine.h:29</div></div>
<div class="ttc" id="Singleton_8hpp_html"><div class="ttname"><a href="Singleton_8hpp.html">Singleton.hpp</a></div></div>
<div class="ttc" id="Platform_8h_html"><div class="ttname"><a href="Platform_8h.html">Platform.h</a></div></div>
</div><!-- fragment --></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.13
</small></address>
</body>
</html>
| {
"pile_set_name": "Github"
} |
package frameless
import org.scalacheck.Prop
import org.scalacheck.Prop.forAll
import org.scalacheck.Prop._
class FlattenTests extends TypedDatasetSuite {
test("simple flatten test") {
val ds: TypedDataset[(Int,Option[Int])] = TypedDataset.create(Seq((1,Option(1))))
ds.flattenOption('_2): TypedDataset[(Int,Int)]
}
test("different Optional types") {
def prop[A: TypedEncoder](xs: List[X1[Option[A]]]): Prop = {
val tds: TypedDataset[X1[Option[A]]] = TypedDataset.create(xs)
val framelessResults: Seq[Tuple1[A]] = tds.flattenOption('a).collect().run().toVector
val scalaResults = xs.flatMap(_.a).map(Tuple1(_)).toVector
framelessResults ?= scalaResults
}
check(forAll(prop[Long] _))
check(forAll(prop[Int] _))
check(forAll(prop[Char] _))
check(forAll(prop[String] _))
}
}
| {
"pile_set_name": "Github"
} |
/*
* 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.flink.runtime.rest.handler.legacy.messages;
import org.apache.flink.runtime.messages.webmonitor.ClusterOverview;
import org.apache.flink.runtime.messages.webmonitor.JobsOverview;
import org.apache.flink.runtime.rest.messages.ResponseBody;
import org.apache.flink.util.Preconditions;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
/**
* Cluster overview message including the current Flink version and commit id.
*/
public class ClusterOverviewWithVersion extends ClusterOverview implements ResponseBody {
private static final long serialVersionUID = 5000058311783413216L;
public static final String FIELD_NAME_VERSION = "flink-version";
public static final String FIELD_NAME_COMMIT = "flink-commit";
@JsonProperty(FIELD_NAME_VERSION)
private final String version;
@JsonProperty(FIELD_NAME_COMMIT)
private final String commitId;
@JsonCreator
public ClusterOverviewWithVersion(
@JsonProperty(FIELD_NAME_TASKMANAGERS) int numTaskManagersConnected,
@JsonProperty(FIELD_NAME_SLOTS_TOTAL) int numSlotsTotal,
@JsonProperty(FIELD_NAME_SLOTS_AVAILABLE) int numSlotsAvailable,
@JsonProperty(FIELD_NAME_JOBS_RUNNING) int numJobsRunningOrPending,
@JsonProperty(FIELD_NAME_JOBS_FINISHED) int numJobsFinished,
@JsonProperty(FIELD_NAME_JOBS_CANCELLED) int numJobsCancelled,
@JsonProperty(FIELD_NAME_JOBS_FAILED) int numJobsFailed,
@JsonProperty(FIELD_NAME_VERSION) String version,
@JsonProperty(FIELD_NAME_COMMIT) String commitId) {
super(
numTaskManagersConnected,
numSlotsTotal,
numSlotsAvailable,
numJobsRunningOrPending,
numJobsFinished,
numJobsCancelled,
numJobsFailed);
this.version = Preconditions.checkNotNull(version);
this.commitId = Preconditions.checkNotNull(commitId);
}
public ClusterOverviewWithVersion(
int numTaskManagersConnected,
int numSlotsTotal,
int numSlotsAvailable,
JobsOverview jobs1,
JobsOverview jobs2,
String version,
String commitId) {
super(numTaskManagersConnected, numSlotsTotal, numSlotsAvailable, jobs1, jobs2);
this.version = Preconditions.checkNotNull(version);
this.commitId = Preconditions.checkNotNull(commitId);
}
public static ClusterOverviewWithVersion fromStatusOverview(ClusterOverview statusOverview, String version, String commitId) {
return new ClusterOverviewWithVersion(
statusOverview.getNumTaskManagersConnected(),
statusOverview.getNumSlotsTotal(),
statusOverview.getNumSlotsAvailable(),
statusOverview.getNumJobsRunningOrPending(),
statusOverview.getNumJobsFinished(),
statusOverview.getNumJobsCancelled(),
statusOverview.getNumJobsFailed(),
version,
commitId);
}
public String getVersion() {
return version;
}
public String getCommitId() {
return commitId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
ClusterOverviewWithVersion that = (ClusterOverviewWithVersion) o;
return Objects.equals(version, that.getVersion()) && Objects.equals(commitId, that.getCommitId());
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (version != null ? version.hashCode() : 0);
result = 31 * result + (commitId != null ? commitId.hashCode() : 0);
return result;
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>incron: incroncfg.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">incron
 <span id="projectnumber">0.5.10</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.7.5.1 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
</div>
<div class="header">
<div class="summary">
<a href="#nested-classes">Classes</a> </div>
<div class="headertitle">
<div class="title">incroncfg.h File Reference</div> </div>
</div>
<div class="contents">
<p>inotify cron configuration header
<a href="#details">More...</a></p>
<div class="textblock"><code>#include <cstring></code><br/>
<code>#include <map></code><br/>
</div>
<p><a href="incroncfg_8h_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="nested-classes"></a>
Classes</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classIncronCfg.html">IncronCfg</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Configuration class. <a href="classIncronCfg.html#details">More...</a><br/></td></tr>
</table>
<hr/><a name="details" id="details"></a><h2>Detailed Description</h2>
<div class="textblock"><p>inotify cron configuration header </p>
<p>incron configuration</p>
<p>Copyright (C) 2007, 2008 Lukas Jelinek, <<a href="mailto:[email protected]">[email protected]</a>></p>
<p>This program is free software; you can use it, redistribute it and/or modify it under the terms of the GNU General Public License, version 2 (see LICENSE-GPL). </p>
</div></div>
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.7.5.1
</small></address>
</body>
</html>
| {
"pile_set_name": "Github"
} |
# Code of Conduct
The Laravel Code of Conduct can be found in the [Laravel documentation](https://laravel.com/docs/contributions#code-of-conduct).
| {
"pile_set_name": "Github"
} |
<!doctype html>
<html>
<head>
<title>Amazing Just Cause 4 Easter egg</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="copyright" content="Copyright 2018 Imgur, Inc." />
<meta id="viewport" name="viewport" content="width=728, user-scalable=yes" />
<link rel="stylesheet" type="text/css" href="//s.imgur.com/min/sharePlayer.css?1544130495" />
<style type="text/css">
#content, #video {
width: 728px;
height: 408px;
}
#chrome, #progress {
width: 728px;
}
</style>
<link rel="alternate" type="application/json+oembed" href="https://api.imgur.com/oembed.json?url=http://i.imgur.com/lXDyzHY.gifv" title="Amazing Just Cause 4 Easter egg" />
<link rel="alternate" type="application/xml+oembed" href="https://api.imgur.com/oembed.xml?url=http://i.imgur.com/lXDyzHY.gifv" title="Amazing Just Cause 4 Easter egg" />
<link rel="canonical" href="https://i.imgur.com/lXDyzHY.gifv" />
<meta property="og:site_name" content="Imgur" />
<meta property="og:title" content="Amazing Just Cause 4 Easter egg"/>
<meta property="og:description" content="2433301 views and 2489 votes on Imgur" />
<meta property="og:type" content="video.other" />
<meta property="og:url" content="https://i.imgur.com/lXDyzHY.gifv" />
<meta property="og:image" content="https://i.imgur.com/lXDyzHY.jpg?play" />
<meta property="og:video:width" content="728" />
<meta property="og:video:height" content="408" />
<meta property="og:video" content="https://i.imgur.com/lXDyzHY.mp4" />
<meta property="og:video:secure_url" content="https://i.imgur.com/lXDyzHY.mp4" />
<meta property="og:video:type" content="video/mp4" />
<meta name="twitter:site" content="@imgur" />
<meta name="twitter:domain" content="imgur.com" />
<meta name="twitter:app:id:googleplay" content="com.imgur.mobile" />
<meta name="twitter:card" content="player" />
<meta name="twitter:title" content="Amazing Just Cause 4 Easter egg"/>
<meta name="twitter:description" content="2433301 views and 2489 votes on Imgur" />
<meta name="twitter:image" content="https://i.imgur.com/lXDyzHY.jpg?play" />
<meta name="twitter:player" content="https://i.imgur.com/lXDyzHY.gifv?twitter#t" />
<meta name="twitter:player:width" content="728" />
<meta name="twitter:player:height" content="408" />
<meta name="twitter:player:stream" content="https://i.imgur.com/lXDyzHY.mp4" />
<meta name="twitter:player:stream:content_type" content="video/mp4">
<!-- Google Tag Manager -->
<script>
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-M6N38SF');</script>
<!-- End Google Tag Manager -->
<!--[if lte IE 8]><script type="text/javascript" src="//s.imgur.com/min/iepoly.js?1544130495"></script>
<![endif]-->
</head>
<body id="body">
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-M6N38SF"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<div id="content">
<script type="text/javascript">
window.image = 'lXDyzHY';
window.image_size = '29609084';
window.image_width = '728';
window.image_height = '408';
window.cdn_url = '//i.imgur.com';
if(navigator.userAgent.match(/Firefox/)) {
document.body.className = document.body.className + ' firefox';
}
</script>
<div class="vid-container">
<div class="post-image">
<div class="video-container">
<script type="text/javascript">
var videoItem = {
looping: true,
width: 728,
height: 408,
size: 29609084,
gifUrl: '//i.imgur.com/lXDyzHY.gif',
forceGif: false,
prefer_video: true,
hash: 'lXDyzHY',
forceLoadAll: false,
}
</script>
<video poster="//i.imgur.com/lXDyzHYh.jpg"
preload="auto"
autoplay="autoplay"
muted="muted" loop="loop"
webkit-playsinline></video>
<div class="video-elements">
<source src="//i.imgur.com/lXDyzHY.mp4" type="video/mp4">
</div>
<progress value="0" max="100" min="0"></progress>
<div class="video-loader"></div>
<script id="scriptlXDyzHY" type="text/javascript" src="//s.imgur.com/min/imageViewerInline.js?1544130495"></script>
<meta itemprop="thumbnailUrl" content="https://i.imgur.com/lXDyzHYh.jpg" />
<meta itemprop="contentURL" content="https://i.imgur.com/lXDyzHY.mp4" />
<meta itemprop="embedURL" content="https://i.imgur.com/lXDyzHY.gifv" />
</div>
</div>
</div>
<script type="text/javascript">
var pixel_url = '//i.imgur.com/imageview.gif?a=lXDyzHY&r=' + encodeURIComponent(document.referrer);
var pixel = document.createElement('img');
pixel.src = pixel_url;
</script>
<div id="chrome">
<div class="icon">
<a href="//imgur.com/lXDyzHY"><img src="//i.imgur.com/favicon.ico" /></a>
</div>
<div class="imgur">
<a href="//imgur.com/lXDyzHY">Imgur</a>
</div>
<div class="controls">
<a href="//imgur.com/download/lXDyzHY">download</a>
</div>
<div class="clear"></div>
</div>
</div>
<script type="text/javascript" src="//s.imgur.com/min/sharePlayer.js?1544130495"></script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
From [email protected] Mon Sep 2 12:14:58 2002
Return-Path: <[email protected]>
Delivered-To: [email protected]
Received: from localhost (localhost [127.0.0.1])
by phobos.labs.example.com (Postfix) with ESMTP id AFD2E43F99
for <zzzz@localhost>; Mon, 2 Sep 2002 07:14:56 -0400 (EDT)
Received: from mail.webnote.net [193.120.211.219]
by localhost with POP3 (fetchmail-5.9.0)
for zzzz@localhost (single-drop); Mon, 02 Sep 2002 12:14:56 +0100 (IST)
Received: from bluemail.dk (IDENT:nobody@[211.57.216.185])
by webnote.net (8.9.3/8.9.3) with SMTP id WAA12021;
Thu, 29 Aug 2002 22:32:54 +0100
Date: Thu, 29 Aug 2002 22:32:54 +0100
From: [email protected]
Reply-To: <[email protected]>
Message-ID: <006e47b18dec$2455b2e1$6ba87ad3@kodbgc>
To: [email protected]
Subject: FORTUNE 500 COMPANY HIRING, AT HOME REPS.
MiME-Version: 1.0
X-Priority: 3 (Normal)
X-MSMail-Priority: Normal
X-Mailer: Microsoft Outlook Express 5.00.2919.6700
Importance: Normal
Content-Type: text/html; charset="iso-8859-1"
Help wanted. We are a 14 year old fortune 500 company, that is
growing at a tremendous rate. We are looking for individuals who
want to work from home.
This is an opportunity to make an excellent income. No experience
is required. We will train you.
So if you are looking to be employed from home with a career that has
vast opportunities, then go:
http://www.basetel.com:27000/wealthnow
We are looking for energetic and self motivated people. If that is you
than click on the link and fill out the form, and one of our
employement specialist will contact you.
To be removed from our link simple go to:
http://www.basetel.com:27000/remove.html
| {
"pile_set_name": "Github"
} |
Gotchas Encountered when Applying Kitsune
========================================
This document provides a place to record solutions to tricky problems
that you encounter with *using* kitsune.
driver can't find init symbol
-----------------------------
If you run into this error:
driver: driver.c:168: main: Assertion `init_func != ((void *)0)' failed.
when you've definitely included the kitsune library when linking your
shared library, the problem might be that you have no code in your
program that forces the kitsune library to actually be included. This
would be unlikely for a completed program that supports updating, but
could happen during early development or for certain test cases.
The solutions are to either:
1. make use of one of the kitsune functions in the code of the program
2. add "-u kitsune_init_inplace" to your gcc arguments when linking,
which will force the kitsune library to be included to make the
kitsune_init_inplace symbol available. | {
"pile_set_name": "Github"
} |
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !linux
package ipv4
const sizeofICMPFilter = 0x0
type icmpFilter struct {
}
func (f *icmpFilter) accept(typ ICMPType) {
}
func (f *icmpFilter) block(typ ICMPType) {
}
func (f *icmpFilter) setAll(block bool) {
}
func (f *icmpFilter) willBlock(typ ICMPType) bool {
return false
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package com.jeespring.common.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
/**
* 关于异常的工具类.
*
* @author calvin
* @version 2013-01-15
*/
public class Exceptions {
/**
* 将CheckedException转换为UncheckedException.
*/
public static RuntimeException unchecked(Exception e) {
if (e instanceof RuntimeException) {
return RuntimeException.class.cast(e);
} else {
return new RuntimeException(e);
}
}
/**
* 将ErrorStack转化为String.
*/
public static String getStackTraceAsString(Throwable e) {
if (e == null) {
return "";
}
StringWriter stringWriter = new StringWriter();
e.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
/**
* 判断异常是否由某些底层的异常引起.
*/
@SuppressWarnings("unchecked")
public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {
Throwable cause = ex.getCause();
while (cause != null) {
for (Class<? extends Exception> causeClass : causeExceptionClasses) {
if (causeClass.isInstance(cause)) {
return true;
}
}
cause = cause.getCause();
}
return false;
}
/**
* 在request中获取异常类
*
* @param request
* @return
*/
public static Throwable getThrowable(HttpServletRequest request) {
Throwable ex = null;
try {
if (request.getAttribute("exception") != null) {
ex = Throwable.class.cast(request.getAttribute("exception"));
} else if (request.getAttribute("javax.servlet.error.exception") != null) {
ex = Throwable.class.cast(request.getAttribute("javax.servlet.error.exception"));
}
} catch (Exception e) {
e.printStackTrace();
}
return ex;
}
}
| {
"pile_set_name": "Github"
} |
// Locale support (codecvt) -*- C++ -*-
// Copyright (C) 2000-2013 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file bits/codecvt.h
* This is an internal header file, included by other library headers.
* Do not attempt to use it directly. @headername{locale}
*/
//
// ISO C++ 14882: 22.2.1.5 Template class codecvt
//
// Written by Benjamin Kosnik <[email protected]>
#ifndef _CODECVT_H
#define _CODECVT_H 1
#pragma GCC system_header
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
/// Empty base class for codecvt facet [22.2.1.5].
class codecvt_base
{
public:
enum result
{
ok,
partial,
error,
noconv
};
};
/**
* @brief Common base for codecvt functions.
*
* This template class provides implementations of the public functions
* that forward to the protected virtual functions.
*
* This template also provides abstract stubs for the protected virtual
* functions.
*/
template<typename _InternT, typename _ExternT, typename _StateT>
class __codecvt_abstract_base
: public locale::facet, public codecvt_base
{
public:
// Types:
typedef codecvt_base::result result;
typedef _InternT intern_type;
typedef _ExternT extern_type;
typedef _StateT state_type;
// 22.2.1.5.1 codecvt members
/**
* @brief Convert from internal to external character set.
*
* Converts input string of intern_type to output string of
* extern_type. This is analogous to wcsrtombs. It does this by
* calling codecvt::do_out.
*
* The source and destination character sets are determined by the
* facet's locale, internal and external types.
*
* The characters in [from,from_end) are converted and written to
* [to,to_end). from_next and to_next are set to point to the
* character following the last successfully converted character,
* respectively. If the result needed no conversion, from_next and
* to_next are not affected.
*
* The @a state argument should be initialized if the input is at the
* beginning and carried from a previous call if continuing
* conversion. There are no guarantees about how @a state is used.
*
* The result returned is a member of codecvt_base::result. If
* all the input is converted, returns codecvt_base::ok. If no
* conversion is necessary, returns codecvt_base::noconv. If
* the input ends early or there is insufficient space in the
* output, returns codecvt_base::partial. Otherwise the
* conversion failed and codecvt_base::error is returned.
*
* @param __state Persistent conversion state data.
* @param __from Start of input.
* @param __from_end End of input.
* @param __from_next Returns start of unconverted data.
* @param __to Start of output buffer.
* @param __to_end End of output buffer.
* @param __to_next Returns start of unused output area.
* @return codecvt_base::result.
*/
result
out(state_type& __state, const intern_type* __from,
const intern_type* __from_end, const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const
{
return this->do_out(__state, __from, __from_end, __from_next,
__to, __to_end, __to_next);
}
/**
* @brief Reset conversion state.
*
* Writes characters to output that would restore @a state to initial
* conditions. The idea is that if a partial conversion occurs, then
* the converting the characters written by this function would leave
* the state in initial conditions, rather than partial conversion
* state. It does this by calling codecvt::do_unshift().
*
* For example, if 4 external characters always converted to 1 internal
* character, and input to in() had 6 external characters with state
* saved, this function would write two characters to the output and
* set the state to initialized conditions.
*
* The source and destination character sets are determined by the
* facet's locale, internal and external types.
*
* The result returned is a member of codecvt_base::result. If the
* state could be reset and data written, returns codecvt_base::ok. If
* no conversion is necessary, returns codecvt_base::noconv. If the
* output has insufficient space, returns codecvt_base::partial.
* Otherwise the reset failed and codecvt_base::error is returned.
*
* @param __state Persistent conversion state data.
* @param __to Start of output buffer.
* @param __to_end End of output buffer.
* @param __to_next Returns start of unused output area.
* @return codecvt_base::result.
*/
result
unshift(state_type& __state, extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const
{ return this->do_unshift(__state, __to,__to_end,__to_next); }
/**
* @brief Convert from external to internal character set.
*
* Converts input string of extern_type to output string of
* intern_type. This is analogous to mbsrtowcs. It does this by
* calling codecvt::do_in.
*
* The source and destination character sets are determined by the
* facet's locale, internal and external types.
*
* The characters in [from,from_end) are converted and written to
* [to,to_end). from_next and to_next are set to point to the
* character following the last successfully converted character,
* respectively. If the result needed no conversion, from_next and
* to_next are not affected.
*
* The @a state argument should be initialized if the input is at the
* beginning and carried from a previous call if continuing
* conversion. There are no guarantees about how @a state is used.
*
* The result returned is a member of codecvt_base::result. If
* all the input is converted, returns codecvt_base::ok. If no
* conversion is necessary, returns codecvt_base::noconv. If
* the input ends early or there is insufficient space in the
* output, returns codecvt_base::partial. Otherwise the
* conversion failed and codecvt_base::error is returned.
*
* @param __state Persistent conversion state data.
* @param __from Start of input.
* @param __from_end End of input.
* @param __from_next Returns start of unconverted data.
* @param __to Start of output buffer.
* @param __to_end End of output buffer.
* @param __to_next Returns start of unused output area.
* @return codecvt_base::result.
*/
result
in(state_type& __state, const extern_type* __from,
const extern_type* __from_end, const extern_type*& __from_next,
intern_type* __to, intern_type* __to_end,
intern_type*& __to_next) const
{
return this->do_in(__state, __from, __from_end, __from_next,
__to, __to_end, __to_next);
}
int
encoding() const throw()
{ return this->do_encoding(); }
bool
always_noconv() const throw()
{ return this->do_always_noconv(); }
int
length(state_type& __state, const extern_type* __from,
const extern_type* __end, size_t __max) const
{ return this->do_length(__state, __from, __end, __max); }
int
max_length() const throw()
{ return this->do_max_length(); }
protected:
explicit
__codecvt_abstract_base(size_t __refs = 0) : locale::facet(__refs) { }
virtual
~__codecvt_abstract_base() { }
/**
* @brief Convert from internal to external character set.
*
* Converts input string of intern_type to output string of
* extern_type. This function is a hook for derived classes to change
* the value returned. @see out for more information.
*/
virtual result
do_out(state_type& __state, const intern_type* __from,
const intern_type* __from_end, const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const = 0;
virtual result
do_unshift(state_type& __state, extern_type* __to,
extern_type* __to_end, extern_type*& __to_next) const = 0;
virtual result
do_in(state_type& __state, const extern_type* __from,
const extern_type* __from_end, const extern_type*& __from_next,
intern_type* __to, intern_type* __to_end,
intern_type*& __to_next) const = 0;
virtual int
do_encoding() const throw() = 0;
virtual bool
do_always_noconv() const throw() = 0;
virtual int
do_length(state_type&, const extern_type* __from,
const extern_type* __end, size_t __max) const = 0;
virtual int
do_max_length() const throw() = 0;
};
/**
* @brief Primary class template codecvt.
* @ingroup locales
*
* NB: Generic, mostly useless implementation.
*
*/
template<typename _InternT, typename _ExternT, typename _StateT>
class codecvt
: public __codecvt_abstract_base<_InternT, _ExternT, _StateT>
{
public:
// Types:
typedef codecvt_base::result result;
typedef _InternT intern_type;
typedef _ExternT extern_type;
typedef _StateT state_type;
protected:
__c_locale _M_c_locale_codecvt;
public:
static locale::id id;
explicit
codecvt(size_t __refs = 0)
: __codecvt_abstract_base<_InternT, _ExternT, _StateT> (__refs),
_M_c_locale_codecvt(0)
{ }
explicit
codecvt(__c_locale __cloc, size_t __refs = 0);
protected:
virtual
~codecvt() { }
virtual result
do_out(state_type& __state, const intern_type* __from,
const intern_type* __from_end, const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const;
virtual result
do_unshift(state_type& __state, extern_type* __to,
extern_type* __to_end, extern_type*& __to_next) const;
virtual result
do_in(state_type& __state, const extern_type* __from,
const extern_type* __from_end, const extern_type*& __from_next,
intern_type* __to, intern_type* __to_end,
intern_type*& __to_next) const;
virtual int
do_encoding() const throw();
virtual bool
do_always_noconv() const throw();
virtual int
do_length(state_type&, const extern_type* __from,
const extern_type* __end, size_t __max) const;
virtual int
do_max_length() const throw();
};
template<typename _InternT, typename _ExternT, typename _StateT>
locale::id codecvt<_InternT, _ExternT, _StateT>::id;
/// class codecvt<char, char, mbstate_t> specialization.
template<>
class codecvt<char, char, mbstate_t>
: public __codecvt_abstract_base<char, char, mbstate_t>
{
public:
// Types:
typedef char intern_type;
typedef char extern_type;
typedef mbstate_t state_type;
protected:
__c_locale _M_c_locale_codecvt;
public:
static locale::id id;
explicit
codecvt(size_t __refs = 0);
explicit
codecvt(__c_locale __cloc, size_t __refs = 0);
protected:
virtual
~codecvt();
virtual result
do_out(state_type& __state, const intern_type* __from,
const intern_type* __from_end, const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const;
virtual result
do_unshift(state_type& __state, extern_type* __to,
extern_type* __to_end, extern_type*& __to_next) const;
virtual result
do_in(state_type& __state, const extern_type* __from,
const extern_type* __from_end, const extern_type*& __from_next,
intern_type* __to, intern_type* __to_end,
intern_type*& __to_next) const;
virtual int
do_encoding() const throw();
virtual bool
do_always_noconv() const throw();
virtual int
do_length(state_type&, const extern_type* __from,
const extern_type* __end, size_t __max) const;
virtual int
do_max_length() const throw();
};
#ifdef _GLIBCXX_USE_WCHAR_T
/// class codecvt<wchar_t, char, mbstate_t> specialization.
template<>
class codecvt<wchar_t, char, mbstate_t>
: public __codecvt_abstract_base<wchar_t, char, mbstate_t>
{
public:
// Types:
typedef wchar_t intern_type;
typedef char extern_type;
typedef mbstate_t state_type;
protected:
__c_locale _M_c_locale_codecvt;
public:
static locale::id id;
explicit
codecvt(size_t __refs = 0);
explicit
codecvt(__c_locale __cloc, size_t __refs = 0);
protected:
virtual
~codecvt();
virtual result
do_out(state_type& __state, const intern_type* __from,
const intern_type* __from_end, const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const;
virtual result
do_unshift(state_type& __state,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const;
virtual result
do_in(state_type& __state,
const extern_type* __from, const extern_type* __from_end,
const extern_type*& __from_next,
intern_type* __to, intern_type* __to_end,
intern_type*& __to_next) const;
virtual
int do_encoding() const throw();
virtual
bool do_always_noconv() const throw();
virtual
int do_length(state_type&, const extern_type* __from,
const extern_type* __end, size_t __max) const;
virtual int
do_max_length() const throw();
};
#endif //_GLIBCXX_USE_WCHAR_T
/// class codecvt_byname [22.2.1.6].
template<typename _InternT, typename _ExternT, typename _StateT>
class codecvt_byname : public codecvt<_InternT, _ExternT, _StateT>
{
public:
explicit
codecvt_byname(const char* __s, size_t __refs = 0)
: codecvt<_InternT, _ExternT, _StateT>(__refs)
{
if (__builtin_strcmp(__s, "C") != 0
&& __builtin_strcmp(__s, "POSIX") != 0)
{
this->_S_destroy_c_locale(this->_M_c_locale_codecvt);
this->_S_create_c_locale(this->_M_c_locale_codecvt, __s);
}
}
protected:
virtual
~codecvt_byname() { }
};
// Inhibit implicit instantiations for required instantiations,
// which are defined via explicit instantiations elsewhere.
#if _GLIBCXX_EXTERN_TEMPLATE
extern template class codecvt_byname<char, char, mbstate_t>;
extern template
const codecvt<char, char, mbstate_t>&
use_facet<codecvt<char, char, mbstate_t> >(const locale&);
extern template
bool
has_facet<codecvt<char, char, mbstate_t> >(const locale&);
#ifdef _GLIBCXX_USE_WCHAR_T
extern template class codecvt_byname<wchar_t, char, mbstate_t>;
extern template
const codecvt<wchar_t, char, mbstate_t>&
use_facet<codecvt<wchar_t, char, mbstate_t> >(const locale&);
extern template
bool
has_facet<codecvt<wchar_t, char, mbstate_t> >(const locale&);
#endif
#endif
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace std
#endif // _CODECVT_H
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2008, 2016, Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*
* This file is available and licensed under the following license:
*
* 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.
* - Neither the name of Oracle Corporation 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.
*/
package ensemble.samples.language.swing;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javafx.concurrent.Task;
public class SwingInteropTask extends Task<Process> {
private Process proc = null;
public SwingInteropTask() {
}
@Override
protected Process call() throws Exception {
String home = System.getProperty("java.home");
String java = home + File.separator + "bin" + File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = SwingInterop.class.getCanonicalName();
List<String> command = new ArrayList<>();
command.add(java);
command.add("-cp");
command.add(classpath);
command.add(className);
ProcessBuilder pb = new ProcessBuilder(command);
proc = pb.start();
// Assuming there is little output to stdout, stderr
proc.waitFor();
return proc;
}
@Override
protected void cancelled() {
if (proc != null) {
proc.destroy();
}
}
}
| {
"pile_set_name": "Github"
} |
# This source code refers to The Go Authors for copyright purposes.
# The master list of authors is in the main Go distribution,
# visible at http://tip.golang.org/AUTHORS.
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2003 Compaq Corporation. All rights reserved.
// Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved.
package tlc2.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.Random;
public class BigInt extends BigInteger implements Cloneable, ExternalSortable {
public final static BigInt BigZero = new BigInt("0");
public final static BigInt BigOne = new BigInt("1");
public final static BigInt BigTwo = new BigInt("2");
public BigInt(String val) { super(val); }
public BigInt(byte[] val) { super(val); }
public BigInt(int numBits, Random rnd) { super(numBits, rnd); }
/* Returns the fingerprint of this. */
public final long fingerPrint() {
return FP64.New(this.toByteArray());
}
/**
* Returns true iff x is a BigInt whose value is equal to this.value.
* This method is provided so that BigInts can be used as hash keys.
*/
public final boolean equals(Object x) {
return ((x instanceof BigInt) && super.equals(x));
}
public final void write(OutputStream out) throws IOException {
ByteUtils.writeSizeBigInt(out, this);
}
public final BigInt read(InputStream in) throws IOException {
return ByteUtils.readSizeBigInt(in);
}
}
| {
"pile_set_name": "Github"
} |
tstgtgen
gtgen out=xxxlab1 'tiecnvrt +
geotiff=("ModelTiePointTag=(2,3,0,350807.4,5317081.3,0.0)", +
"ModelTiePointTag=(202,103,0,351807.4,5316081.3,0.0)", +
"ModelTiePointTag=(2,103,0,350807.4,5316081.3,0.0)", +
"GTRasterTypeGeoKey=1(RasterPixelIsArea)")
Beginning VICAR task gtgen
gtgen version Fri Jan 11 2008
list xxxlab1 'zeroes
Beginning VICAR task list
BYTE samples are interpreted as BYTE data
Task:GTGEN User:lwk Date_Time:Tue Jan 24 14:30:41 2012
Samp 1
Line
1 0
gtlist xxxlab1
Beginning VICAR task gtlist
gtlist version Wed Jan 2 2008
gen xxxim1 nl=500 ns=500
Beginning VICAR task gen
GEN Version 6
GEN task completed
gtgen inp=xxxim1 out=xxxim2 'tiecnvrt +
geotiff=("ModelTiePointTag=(0,0,0,350807.4,5317081.3,0.0)", +
"ModelTiePointTag=(200,100,0,351807.4,5316081.3,0.0)", +
"ModelTiePointTag=(200,0,0,351807.4,5317081.3,0.0)", +
"GTRasterTypeGeoKey=1(RasterPixelIsArea)")
Beginning VICAR task gtgen
gtgen version Fri Jan 11 2008
label-list xxxim2
Beginning VICAR task label
LABEL version 15-Nov-2010
************************************************************
************ File xxxim2 ************
3 dimensional IMAGE file
File organization is BSQ
Pixels are in BYTE format from a SUN-SOLR host
1 bands
500 lines per band
500 samples per line
0 lines of binary header
0 bytes of binary prefix per line
---- Property: GEOTIFF ----
MODELTIEPOINTTAG='(0,0,0,350807.4,5317081.3,0.0)'
MODELPIXELSCALETAG='(5.0,10.0,0.0)'
GTRASTERTYPEGEOKEY='1(RasterPixelIsArea)'
---- Task: GEN -- User: lwk -- Tue Jan 24 14:30:42 2012 ----
IVAL=0.0
SINC=1.0
LINC=1.0
BINC=1.0
MODULO=0.0
---- Task: GTGEN -- User: lwk -- Tue Jan 24 14:30:42 2012 ----
************************************************************
gtlist xxxim2
Beginning VICAR task gtlist
gtlist version Wed Jan 2 2008
gtgen inp=xxxim2 out=xxxim3 'add +
geotiff=("PCSCitationGeoKey=""UTM Zone 60 N with WGS84""")
Beginning VICAR task gtgen
gtgen version Fri Jan 11 2008
label-list xxxim3
Beginning VICAR task label
LABEL version 15-Nov-2010
************************************************************
************ File xxxim3 ************
3 dimensional IMAGE file
File organization is BSQ
Pixels are in BYTE format from a SUN-SOLR host
1 bands
500 lines per band
500 samples per line
0 lines of binary header
0 bytes of binary prefix per line
---- Property: GEOTIFF ----
MODELTIEPOINTTAG='(0,0,0,350807.4,5317081.3,0.0)'
MODELPIXELSCALETAG='(5.0,10.0,0.0)'
GTRASTERTYPEGEOKEY='1(RasterPixelIsArea)'
PCSCITATIONGEOKEY='"UTM Zone 60 N with WGS84"'
---- Task: GEN -- User: lwk -- Tue Jan 24 14:30:42 2012 ----
IVAL=0.0
SINC=1.0
LINC=1.0
BINC=1.0
MODULO=0.0
---- Task: GTGEN -- User: lwk -- Tue Jan 24 14:30:42 2012 ----
---- Task: GTGEN -- User: lwk -- Tue Jan 24 14:30:42 2012 ----
************************************************************
gtlist xxxim3
Beginning VICAR task gtlist
gtlist version Wed Jan 2 2008
gen xxxim4 nl=40 ns=40
Beginning VICAR task gen
GEN Version 6
GEN task completed
gtgen inp=(xxxim4,xxxim3) out=xxxim5
Beginning VICAR task gtgen
gtgen version Fri Jan 11 2008
label-list xxxim5
Beginning VICAR task label
LABEL version 15-Nov-2010
************************************************************
************ File xxxim5 ************
3 dimensional IMAGE file
File organization is BSQ
Pixels are in BYTE format from a SUN-SOLR host
1 bands
40 lines per band
40 samples per line
0 lines of binary header
0 bytes of binary prefix per line
---- Property: GEOTIFF ----
MODELTIEPOINTTAG='(0,0,0,350807.4,5317081.3,0.0)'
MODELPIXELSCALETAG='(5.0,10.0,0.0)'
GTRASTERTYPEGEOKEY='1(RASTERPIXELISAREA)'
PCSCITATIONGEOKEY='"UTM ZONE 60 N WITH WGS84"'
---- Task: GEN -- User: lwk -- Tue Jan 24 14:30:42 2012 ----
IVAL=0.0
SINC=1.0
LINC=1.0
BINC=1.0
MODULO=0.0
---- Task: GTGEN -- User: lwk -- Tue Jan 24 14:30:42 2012 ----
************************************************************
gtlist xxxim5
Beginning VICAR task gtlist
gtlist version Wed Jan 2 2008
gtgen out=xxxlab1 'tiecnvrt +
geotiff=("ModelTiePointTag=(2,3,0,350807.4,5317081.3,0.0)", +
"ModelTiePointTag=(202,103,0,351807.4,5316081.3,0.0)", +
"ModelTiePointTag=(2,103,0,350807.4,5316081.2,0.0)", +
"GTRasterTypeGeoKey=1(RasterPixelIsArea)")
Beginning VICAR task gtgen
gtgen version Fri Jan 11 2008
gtlist xxxlab1
Beginning VICAR task gtlist
gtlist version Wed Jan 2 2008
gtgen out=xxxlab1 'tiecnvrt 'rectfit +
geotiff=("ModelTiePointTag=(2,3,0,350807.4,5317081.3,0.0)", +
"ModelTiePointTag=(202,103,0,351807.4,5316081.3,0.0)", +
"ModelTiePointTag=(2,103,0,350807.4,5316081.2,0.0)", +
"GTRasterTypeGeoKey=1(RasterPixelIsArea)")
Beginning VICAR task gtgen
gtgen version Fri Jan 11 2008
gtlist xxxlab1
Beginning VICAR task gtlist
gtlist version Wed Jan 2 2008
gtgen out=xxxlab2 'tiecnvrt +
geotiff=("ModelTiePointTag=(2,3,0,35080.74e+01,53170813D-01,0.0)", +
"ModelTiePointTag=(202,103,0,351807.4,5316081.3,0.0)", +
"ModelTiePointTag=(2,103,0,350807.4,5316081.3,0.0)", +
"GTRasterTypeGeoKey=1(RasterPixelIsArea)")
Beginning VICAR task gtgen
gtgen version Fri Jan 11 2008
gtlist xxxlab2
Beginning VICAR task gtlist
gtlist version Wed Jan 2 2008
gen xxxlab3 nl=1 ns=1
Beginning VICAR task gen
GEN Version 6
GEN task completed
gtgen in=xxxlab3 'tiecnvrt +
geotiff=("ModelTiePointTag=(2,3,0,35080.74e+01,53170813D-01,0.0)", +
"ModelTiePointTag=(202,103,0,351807.4,5316081.3,0.0)", +
"ModelTiePointTag=(2,103,0,350807.4,5316081.3,0.0)", +
"GTRasterTypeGeoKey=1(RasterPixelIsArea)")
Beginning VICAR task gtgen
gtgen version Fri Jan 11 2008
gtlist xxxlab3
Beginning VICAR task gtlist
gtlist version Wed Jan 2 2008
gtgen inp=xxxlab3 'add +
geotiff=("PCSCitationGeoKey=""UTM Zone 60 N with WGS84""")
Beginning VICAR task gtgen
gtgen version Fri Jan 11 2008
gtlist xxxlab3
Beginning VICAR task gtlist
gtlist version Wed Jan 2 2008
gtgen in=xxxlab3 'tiecnvrt +
geotiff=("ModelTiePointTag=(12,3,0,35080.74e+01,53170813D-01,0.0)", +
"ModelTiePointTag=(212,103,0,351807.4,5316081.3,0.0)", +
"ModelTiePointTag=(12,103,0,350807.4,5316081.3,0.0)", +
"GTRasterTypeGeoKey=2(RasterPixelIsPoint)")
Beginning VICAR task gtgen
gtgen version Fri Jan 11 2008
gtlist xxxlab3
Beginning VICAR task gtlist
gtlist version Wed Jan 2 2008
gen xxxim1 nl=5 ns=5
Beginning VICAR task gen
GEN Version 6
GEN task completed
gtgen inp=xxxim1 out=xxxim2 'tiecnvrt +
geotiff=("ModelTiePointTag=(0,0,0,-110.,34.,0.0)", +
"ModelTiePointTag=(0,100,0,-110.,33.,0.0)", +
"ModelTiePointTag=(100,0,0,-109.,34.,0.0)", +
"GTRasterTypeGeoKey=1(RasterPixelIsArea)")
Beginning VICAR task gtgen
gtgen version Fri Jan 11 2008
label-list xxxim2
Beginning VICAR task label
LABEL version 15-Nov-2010
************************************************************
************ File xxxim2 ************
3 dimensional IMAGE file
File organization is BSQ
Pixels are in BYTE format from a SUN-SOLR host
1 bands
5 lines per band
5 samples per line
0 lines of binary header
0 bytes of binary prefix per line
---- Property: GEOTIFF ----
MODELTIEPOINTTAG='(0,0,0,-110.,34.,0.0)'
MODELPIXELSCALETAG='(0.01,0.01,0.0)'
GTRASTERTYPEGEOKEY='1(RasterPixelIsArea)'
---- Task: GEN -- User: lwk -- Tue Jan 24 14:30:43 2012 ----
IVAL=0.0
SINC=1.0
LINC=1.0
BINC=1.0
MODULO=0.0
---- Task: GTGEN -- User: lwk -- Tue Jan 24 14:30:43 2012 ----
************************************************************
gtgen inp=xxxim2 out=xxxim3 'add 'tiecnvrt +
geotiff=("ModelTiePointTag=(0,0,0,-110.,34.,0.0)", +
"ModelTiePointTag=(0,50,0,-110.,33.,0.0)", +
"ModelTiePointTag=(50,0,0,-109.,34.,0.0)")
Beginning VICAR task gtgen
gtgen version Fri Jan 11 2008
label-list xxxim3
Beginning VICAR task label
LABEL version 15-Nov-2010
************************************************************
************ File xxxim3 ************
3 dimensional IMAGE file
File organization is BSQ
Pixels are in BYTE format from a SUN-SOLR host
1 bands
5 lines per band
5 samples per line
0 lines of binary header
0 bytes of binary prefix per line
---- Property: GEOTIFF ----
GTRASTERTYPEGEOKEY='1(RasterPixelIsArea)'
MODELTIEPOINTTAG='(0,0,0,-110.,34.,0.0)'
MODELPIXELSCALETAG='(0.02,0.02,0.0)'
---- Task: GEN -- User: lwk -- Tue Jan 24 14:30:43 2012 ----
IVAL=0.0
SINC=1.0
LINC=1.0
BINC=1.0
MODULO=0.0
---- Task: GTGEN -- User: lwk -- Tue Jan 24 14:30:43 2012 ----
---- Task: GTGEN -- User: lwk -- Tue Jan 24 14:30:44 2012 ----
************************************************************
end-proc
disable-log
| {
"pile_set_name": "Github"
} |
# lt~obsolete.m4 -- aclocal satisfying obsolete definitions. -*-Autoconf-*-
#
# Copyright (C) 2004-2005, 2007, 2009, 2011-2015 Free Software
# Foundation, Inc.
# Written by Scott James Remnant, 2004.
#
# This file is free software; the Free Software Foundation gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
# serial 5 lt~obsolete.m4
# These exist entirely to fool aclocal when bootstrapping libtool.
#
# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN),
# which have later been changed to m4_define as they aren't part of the
# exported API, or moved to Autoconf or Automake where they belong.
#
# The trouble is, aclocal is a bit thick. It'll see the old AC_DEFUN
# in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us
# using a macro with the same name in our local m4/libtool.m4 it'll
# pull the old libtool.m4 in (it doesn't see our shiny new m4_define
# and doesn't know about Autoconf macros at all.)
#
# So we provide this file, which has a silly filename so it's always
# included after everything else. This provides aclocal with the
# AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything
# because those macros already exist, or will be overwritten later.
# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6.
#
# Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here.
# Yes, that means every name once taken will need to remain here until
# we give up compatibility with versions before 1.7, at which point
# we need to keep only those names which we still refer to.
# This is to help aclocal find these macros, as it can't see m4_define.
AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])])
m4_ifndef([AC_LIBTOOL_LINKER_OPTION], [AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])])
m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP])])
m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])])
m4_ifndef([_LT_AC_SHELL_INIT], [AC_DEFUN([_LT_AC_SHELL_INIT])])
m4_ifndef([_LT_AC_SYS_LIBPATH_AIX], [AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])])
m4_ifndef([_LT_PROG_LTMAIN], [AC_DEFUN([_LT_PROG_LTMAIN])])
m4_ifndef([_LT_AC_TAGVAR], [AC_DEFUN([_LT_AC_TAGVAR])])
m4_ifndef([AC_LTDL_ENABLE_INSTALL], [AC_DEFUN([AC_LTDL_ENABLE_INSTALL])])
m4_ifndef([AC_LTDL_PREOPEN], [AC_DEFUN([AC_LTDL_PREOPEN])])
m4_ifndef([_LT_AC_SYS_COMPILER], [AC_DEFUN([_LT_AC_SYS_COMPILER])])
m4_ifndef([_LT_AC_LOCK], [AC_DEFUN([_LT_AC_LOCK])])
m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE], [AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])])
m4_ifndef([_LT_AC_TRY_DLOPEN_SELF], [AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])])
m4_ifndef([AC_LIBTOOL_PROG_CC_C_O], [AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])])
m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])])
m4_ifndef([AC_LIBTOOL_OBJDIR], [AC_DEFUN([AC_LIBTOOL_OBJDIR])])
m4_ifndef([AC_LTDL_OBJDIR], [AC_DEFUN([AC_LTDL_OBJDIR])])
m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])])
m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP], [AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])])
m4_ifndef([AC_PATH_MAGIC], [AC_DEFUN([AC_PATH_MAGIC])])
m4_ifndef([AC_PROG_LD_GNU], [AC_DEFUN([AC_PROG_LD_GNU])])
m4_ifndef([AC_PROG_LD_RELOAD_FLAG], [AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])])
m4_ifndef([AC_DEPLIBS_CHECK_METHOD], [AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])])
m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])])
m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])])
m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])])
m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS], [AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])])
m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP], [AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])])
m4_ifndef([LT_AC_PROG_EGREP], [AC_DEFUN([LT_AC_PROG_EGREP])])
m4_ifndef([LT_AC_PROG_SED], [AC_DEFUN([LT_AC_PROG_SED])])
m4_ifndef([_LT_CC_BASENAME], [AC_DEFUN([_LT_CC_BASENAME])])
m4_ifndef([_LT_COMPILER_BOILERPLATE], [AC_DEFUN([_LT_COMPILER_BOILERPLATE])])
m4_ifndef([_LT_LINKER_BOILERPLATE], [AC_DEFUN([_LT_LINKER_BOILERPLATE])])
m4_ifndef([_AC_PROG_LIBTOOL], [AC_DEFUN([_AC_PROG_LIBTOOL])])
m4_ifndef([AC_LIBTOOL_SETUP], [AC_DEFUN([AC_LIBTOOL_SETUP])])
m4_ifndef([_LT_AC_CHECK_DLFCN], [AC_DEFUN([_LT_AC_CHECK_DLFCN])])
m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER], [AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])])
m4_ifndef([_LT_AC_TAGCONFIG], [AC_DEFUN([_LT_AC_TAGCONFIG])])
m4_ifndef([AC_DISABLE_FAST_INSTALL], [AC_DEFUN([AC_DISABLE_FAST_INSTALL])])
m4_ifndef([_LT_AC_LANG_CXX], [AC_DEFUN([_LT_AC_LANG_CXX])])
m4_ifndef([_LT_AC_LANG_F77], [AC_DEFUN([_LT_AC_LANG_F77])])
m4_ifndef([_LT_AC_LANG_GCJ], [AC_DEFUN([_LT_AC_LANG_GCJ])])
m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])])
m4_ifndef([_LT_AC_LANG_C_CONFIG], [AC_DEFUN([_LT_AC_LANG_C_CONFIG])])
m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])])
m4_ifndef([_LT_AC_LANG_CXX_CONFIG], [AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])])
m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])])
m4_ifndef([_LT_AC_LANG_F77_CONFIG], [AC_DEFUN([_LT_AC_LANG_F77_CONFIG])])
m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])])
m4_ifndef([_LT_AC_LANG_GCJ_CONFIG], [AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])])
m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])])
m4_ifndef([_LT_AC_LANG_RC_CONFIG], [AC_DEFUN([_LT_AC_LANG_RC_CONFIG])])
m4_ifndef([AC_LIBTOOL_CONFIG], [AC_DEFUN([AC_LIBTOOL_CONFIG])])
m4_ifndef([_LT_AC_FILE_LTDLL_C], [AC_DEFUN([_LT_AC_FILE_LTDLL_C])])
m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS], [AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])])
m4_ifndef([_LT_AC_PROG_CXXCPP], [AC_DEFUN([_LT_AC_PROG_CXXCPP])])
m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS], [AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])])
m4_ifndef([_LT_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])])
m4_ifndef([_LT_PROG_F77], [AC_DEFUN([_LT_PROG_F77])])
m4_ifndef([_LT_PROG_FC], [AC_DEFUN([_LT_PROG_FC])])
m4_ifndef([_LT_PROG_CXX], [AC_DEFUN([_LT_PROG_CXX])])
| {
"pile_set_name": "Github"
} |
<?php
/**
* ALIPAY API: alipay.marketing.cdp.advertise.create request
*
* @author auto create
* @since 1.0, 2017-04-01 15:29:02
*/
class AlipayMarketingCdpAdvertiseCreateRequest
{
/**
* 提供给ISV、开发者创建广告的接口,创建广告后投放渠道包括钱包APP,聚牛APP等,投放支持的APP应用
**/
private $bizContent;
private $apiParas = array();
private $terminalType;
private $terminalInfo;
private $prodCode;
private $apiVersion="1.0";
private $notifyUrl;
private $returnUrl;
private $needEncrypt=false;
public function setBizContent($bizContent)
{
$this->bizContent = $bizContent;
$this->apiParas["biz_content"] = $bizContent;
}
public function getBizContent()
{
return $this->bizContent;
}
public function getApiMethodName()
{
return "alipay.marketing.cdp.advertise.create";
}
public function setNotifyUrl($notifyUrl)
{
$this->notifyUrl=$notifyUrl;
}
public function getNotifyUrl()
{
return $this->notifyUrl;
}
public function setReturnUrl($returnUrl)
{
$this->returnUrl=$returnUrl;
}
public function getReturnUrl()
{
return $this->returnUrl;
}
public function getApiParas()
{
return $this->apiParas;
}
public function getTerminalType()
{
return $this->terminalType;
}
public function setTerminalType($terminalType)
{
$this->terminalType = $terminalType;
}
public function getTerminalInfo()
{
return $this->terminalInfo;
}
public function setTerminalInfo($terminalInfo)
{
$this->terminalInfo = $terminalInfo;
}
public function getProdCode()
{
return $this->prodCode;
}
public function setProdCode($prodCode)
{
$this->prodCode = $prodCode;
}
public function setApiVersion($apiVersion)
{
$this->apiVersion=$apiVersion;
}
public function getApiVersion()
{
return $this->apiVersion;
}
public function setNeedEncrypt($needEncrypt)
{
$this->needEncrypt=$needEncrypt;
}
public function getNeedEncrypt()
{
return $this->needEncrypt;
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-16"?>
<TestRunConfiguration
id="03845682-d4db-4a01-962a-1a67d70c5d8b"
name="TestRunConfig1" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
<Description>This is a default test run configuration for a local test run.</Description>
<Timeouts />
<Deployment />
<NamingScheme />
<Hosts />
</TestRunConfiguration> | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
| Copyright (c) 2014-2019 libbitcoin-server developers (see COPYING).
|
| GENERATED SOURCE CODE, DO NOT EDIT EXCEPT EXPERIMENTALLY
|
-->
<packages>
<package id="boost" version="1.57.0.0" targetFramework="Native" />
<package id="boost_atomic-vc120" version="1.57.0.0" targetFramework="Native" />
<package id="boost_chrono-vc120" version="1.57.0.0" targetFramework="Native" />
<package id="boost_date_time-vc120" version="1.57.0.0" targetFramework="Native" />
<package id="boost_filesystem-vc120" version="1.57.0.0" targetFramework="Native" />
<package id="boost_iostreams-vc120" version="1.57.0.0" targetFramework="Native" />
<package id="boost_locale-vc120" version="1.57.0.0" targetFramework="Native" />
<package id="boost_log_setup-vc120" version="1.57.0.0" targetFramework="Native" />
<package id="boost_log-vc120" version="1.57.0.0" targetFramework="Native" />
<package id="boost_program_options-vc120" version="1.57.0.0" targetFramework="Native" />
<package id="boost_regex-vc120" version="1.57.0.0" targetFramework="Native" />
<package id="boost_system-vc120" version="1.57.0.0" targetFramework="Native" />
<package id="boost_thread-vc120" version="1.57.0.0" targetFramework="Native" />
<package id="secp256k1_vc120" version="0.1.0.17" targetFramework="Native" />
<package id="libzmq_vc120" version="4.3.2" targetFramework="Native" />
</packages>
| {
"pile_set_name": "Github"
} |
with ada.containers.ordered_sets, ada.text_io;
use ada.text_io;
procedure set_demo is
package cs is new ada.containers.ordered_sets (character); use cs;
function "+" (s : string) return set is
(if s = "" then empty_set else Union(+ s(s'first..s'last - 1), To_Set (s(s'last))));
function "-" (s : Set) return string is
(if s = empty_set then "" else - (s - To_Set (s.last_element)) & s.last_element);
s1, s2 : set;
begin
loop
put ("s1= ");
s1 := + get_line;
exit when s1 = +"Quit!";
put ("s2= ");
s2 := + get_line;
Put_Line("Sets [" & (-s1) & "], [" & (-s2) & "] of size"
& S1.Length'img & " and" & s2.Length'img & ".");
Put_Line("Intersection: [" & (-(Intersection(S1, S2))) & "],");
Put_Line("Union: [" & (-(Union(s1, s2))) & "],");
Put_Line("Difference: [" & (-(Difference(s1, s2))) & "],");
Put_Line("Symmetric Diff: [" & (-(s1 xor s2)) & "],");
Put_Line("Subset: " & Boolean'Image(s1.Is_Subset(s2))
& ", Equal: " & Boolean'Image(s1 = s2) & ".");
end loop;
end set_demo;
| {
"pile_set_name": "Github"
} |
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="fluentassertions" Version="5.9.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.1" />
<PackageReference Include="nunit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.15.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LazyCache.AspNetCore\LazyCache.AspNetCore.csproj" />
<ProjectReference Include="..\LazyCache\LazyCache.csproj" />
</ItemGroup>
</Project> | {
"pile_set_name": "Github"
} |
from __future__ import division
import onmt
import argparse
import torch
import torch.nn as nn
from torch import cuda
from torch.autograd import Variable
import math
import time
import sys
parser = argparse.ArgumentParser(description='train.py')
## Data options
parser.add_argument('-data', required=True,
help='Path to the *-train.pt file from preprocess.py')
parser.add_argument('-save_model', default='model',
help="""Model filename (the model will be saved as
<save_model>_epochN_PPL.pt where PPL is the
validation perplexity""")
parser.add_argument('-train_from_state_dict', default='', type=str,
help="""If training from a checkpoint then this is the
path to the pretrained model's state_dict.""")
parser.add_argument('-train_from', default='', type=str,
help="""If training from a checkpoint then this is the
path to the pretrained model.""")
## Model options
parser.add_argument('-layers', type=int, default=2,
help='Number of layers in the LSTM encoder/decoder')
parser.add_argument('-rnn_size', type=int, default=500,
help='Size of LSTM hidden states')
parser.add_argument('-word_vec_size', type=int, default=300,
help='Word embedding sizes')
parser.add_argument('-input_feed', type=int, default=1,
help="""Feed the context vector at each time step as
additional input (via concatenation with the word
embeddings) to the decoder.""")
parser.add_argument('-brnn', action='store_true',
help='Use a bidirectional encoder')
parser.add_argument('-brnn_merge', default='concat',
help="""Merge action for the bidirectional hidden states:
[concat|sum]""")
## Optimization options
parser.add_argument('-batch_size', type=int, default=64,
help='Maximum batch size')
parser.add_argument('-max_generator_batches', type=int, default=32,
help="""Maximum batches of words in a sequence to run
the generator on in parallel. Higher is faster, but uses
more memory.""")
parser.add_argument('-epochs', type=int, default=13,
help='Number of training epochs')
parser.add_argument('-start_epoch', type=int, default=1,
help='The epoch from which to start')
parser.add_argument('-param_init', type=float, default=0.1,
help="""Parameters are initialized over uniform distribution
with support (-param_init, param_init)""")
parser.add_argument('-optim', default='sgd',
help="Optimization method. [sgd|adagrad|adadelta|adam]")
parser.add_argument('-max_grad_norm', type=float, default=5,
help="""If the norm of the gradient vector exceeds this,
renormalize it to have the norm equal to max_grad_norm""")
parser.add_argument('-dropout', type=float, default=0.3,
help='Dropout probability; applied between LSTM stacks.')
parser.add_argument('-curriculum', action="store_true",
help="""For this many epochs, order the minibatches based
on source sequence length. Sometimes setting this to 1 will
increase convergence speed.""")
parser.add_argument('-extra_shuffle', action="store_true",
help="""By default only shuffle mini-batch order; when true,
shuffle and re-assign mini-batches""")
#learning rate
parser.add_argument('-learning_rate', type=float, default=1.0,
help="""Starting learning rate. If adagrad/adadelta/adam is
used, then this is the global learning rate. Recommended
settings: sgd = 1, adagrad = 0.1, adadelta = 1, adam = 0.001""")
parser.add_argument('-learning_rate_decay', type=float, default=0.5,
help="""If update_learning_rate, decay learning rate by
this much if (i) perplexity does not decrease on the
validation set or (ii) epoch has gone past
start_decay_at""")
parser.add_argument('-start_decay_at', type=int, default=8,
help="""Start decaying every epoch after and including this
epoch""")
#pretrained word vectors
parser.add_argument('-pre_word_vecs_enc',
help="""If a valid path is specified, then this will load
pretrained word embeddings on the encoder side.
See README for specific formatting instructions.""")
parser.add_argument('-pre_word_vecs_dec',
help="""If a valid path is specified, then this will load
pretrained word embeddings on the decoder side.
See README for specific formatting instructions.""")
# GPU
parser.add_argument('-gpus', default=[], nargs='+', type=int,
help="Use CUDA on the listed devices.")
parser.add_argument('-log_interval', type=int, default=50,
help="Print stats at this interval.")
opt = parser.parse_args()
print(opt)
if torch.cuda.is_available() and not opt.gpus:
print("WARNING: You have a CUDA device, so you should probably run with -gpus 0")
if opt.gpus:
cuda.set_device(opt.gpus[0])
def NMTCriterion(vocabSize):
weight = torch.ones(vocabSize)
weight[onmt.Constants.PAD] = 0
crit = nn.NLLLoss(weight, size_average=False)
if opt.gpus:
crit.cuda()
return crit
def memoryEfficientLoss(outputs, targets, generator, crit, eval=False):
# compute generations one piece at a time
num_correct, loss = 0, 0
outputs = Variable(outputs.data, requires_grad=(not eval), volatile=eval)
batch_size = outputs.size(1)
outputs_split = torch.split(outputs, opt.max_generator_batches)
targets_split = torch.split(targets, opt.max_generator_batches)
for i, (out_t, targ_t) in enumerate(zip(outputs_split, targets_split)):
out_t = out_t.view(-1, out_t.size(2))
scores_t = generator(out_t)
loss_t = crit(scores_t, targ_t.view(-1))
pred_t = scores_t.max(1)[1]
num_correct_t = pred_t.data.eq(targ_t.data).masked_select(targ_t.ne(onmt.Constants.PAD).data).sum()
num_correct += num_correct_t
loss += loss_t.data[0]
if not eval:
loss_t.div(batch_size).backward()
grad_output = None if outputs.grad is None else outputs.grad.data
return loss, grad_output, num_correct
def eval(model, criterion, data):
total_loss = 0
total_words = 0
total_num_correct = 0
model.eval()
for i in range(len(data)):
batch = data[i][:-1] # exclude original indices
outputs = model(batch)
targets = batch[1][1:] # exclude <s> from targets
loss, _, num_correct = memoryEfficientLoss(
outputs, targets, model.generator, criterion, eval=True)
total_loss += loss
total_num_correct += num_correct
total_words += targets.data.ne(onmt.Constants.PAD).sum()
model.train()
return total_loss / total_words, total_num_correct / total_words
def trainModel(model, trainData, validData, dataset, optim):
print(model)
sys.stdout.flush()
model.train()
# define criterion of each GPU
criterion = NMTCriterion(dataset['dicts']['tgt'].size())
start_time = time.time()
def trainEpoch(epoch):
if opt.extra_shuffle and epoch > opt.curriculum:
trainData.shuffle()
# shuffle mini batch order
batchOrder = torch.randperm(len(trainData))
total_loss, total_words, total_num_correct = 0, 0, 0
report_loss, report_tgt_words, report_src_words, report_num_correct = 0, 0, 0, 0
start = time.time()
for i in range(len(trainData)):
batchIdx = batchOrder[i] if epoch > opt.curriculum else i
batch = trainData[batchIdx][:-1] # exclude original indices
model.zero_grad()
outputs = model(batch)
targets = batch[1][1:] # exclude <s> from targets
loss, gradOutput, num_correct = memoryEfficientLoss(
outputs, targets, model.generator, criterion)
outputs.backward(gradOutput)
# update the parameters
optim.step()
num_words = targets.data.ne(onmt.Constants.PAD).sum()
report_loss += loss
report_num_correct += num_correct
report_tgt_words += num_words
report_src_words += sum(batch[0][1])
total_loss += loss
total_num_correct += num_correct
total_words += num_words
if i % opt.log_interval == -1 % opt.log_interval:
print("Epoch %2d, %5d/%5d; acc: %6.2f; ppl: %6.2f; %3.0f src tok/s; %3.0f tgt tok/s; %6.0f s elapsed" %
(epoch, i+1, len(trainData),
report_num_correct / report_tgt_words * 100,
math.exp(report_loss / report_tgt_words),
report_src_words/(time.time()-start),
report_tgt_words/(time.time()-start),
time.time()-start_time))
sys.stdout.flush()
report_loss = report_tgt_words = report_src_words = report_num_correct = 0
start = time.time()
return total_loss / total_words, total_num_correct / total_words
for epoch in range(opt.start_epoch, opt.epochs + 1):
print('')
# (1) train for one epoch on the training set
train_loss, train_acc = trainEpoch(epoch)
train_ppl = math.exp(min(train_loss, 100))
print('Train perplexity: %g' % train_ppl)
print('Train accuracy: %g' % (train_acc*100))
# (2) evaluate on the validation set
valid_loss, valid_acc = eval(model, criterion, validData)
valid_ppl = math.exp(min(valid_loss, 100))
print('Validation perplexity: %g' % valid_ppl)
print('Validation accuracy: %g' % (valid_acc*100))
sys.stdout.flush()
# (3) update the learning rate
optim.updateLearningRate(valid_loss, epoch)
model_state_dict = model.module.state_dict() if len(opt.gpus) > 1 else model.state_dict()
model_state_dict = {k: v for k, v in model_state_dict.items() if 'generator' not in k}
generator_state_dict = model.generator.module.state_dict() if len(opt.gpus) > 1 else model.generator.state_dict()
# (4) drop a checkpoint
checkpoint = {
'encoder': model.encoder.state_dict(),
'decoder': model.decoder.state_dict(),
'generator': generator_state_dict,
'dicts': dataset['dicts'],
'opt': opt,
'epoch': epoch,
'optim': optim
}
torch.save(checkpoint,
'%s_acc_%.2f_ppl_%.2f_e%d.pt' % (opt.save_model, 100*valid_acc, valid_ppl, epoch))
def main():
print("Loading data from '%s'" % opt.data)
dataset = torch.load(opt.data)
dict_checkpoint = opt.train_from if opt.train_from else opt.train_from_state_dict
if dict_checkpoint:
print('Loading dicts from checkpoint at %s' % dict_checkpoint)
checkpoint = torch.load(dict_checkpoint)
dataset['dicts'] = checkpoint['dicts']
trainData = onmt.Dataset(dataset['train']['src'],
dataset['train']['tgt'], opt.batch_size, opt.gpus)
validData = onmt.Dataset(dataset['valid']['src'],
dataset['valid']['tgt'], opt.batch_size, opt.gpus,
volatile=True)
dicts = dataset['dicts']
print(' * vocabulary size. source = %d; target = %d' %
(dicts['src'].size(), dicts['tgt'].size()))
print(' * number of training sentences. %d' %
len(dataset['train']['src']))
print(' * maximum batch size. %d' % opt.batch_size)
print('Building model...')
encoder = onmt.Models.Encoder(opt, dicts['src'])
decoder = onmt.Models.Decoder(opt, dicts['tgt'])
generator = nn.Sequential(
nn.Linear(opt.rnn_size, dicts['tgt'].size()),
nn.LogSoftmax())
model = onmt.Models.NMTModel(encoder, decoder)
if opt.train_from:
print('Loading model from checkpoint at %s' % opt.train_from)
chk_model = checkpoint['model']
generator_state_dict = chk_model.generator.state_dict()
model_state_dict = {k: v for k, v in chk_model.state_dict().items() if 'generator' not in k}
model.load_state_dict(model_state_dict)
generator.load_state_dict(generator_state_dict)
opt.start_epoch = checkpoint['epoch'] + 1
if opt.train_from_state_dict:
print('Loading model from checkpoint at %s' % opt.train_from_state_dict)
model.load_state_dict(checkpoint['model'])
generator.load_state_dict(checkpoint['generator'])
opt.start_epoch = checkpoint['epoch'] + 1
if len(opt.gpus) >= 1:
model.cuda()
generator.cuda()
else:
model.cpu()
generator.cpu()
if len(opt.gpus) > 1:
model = nn.DataParallel(model, device_ids=opt.gpus, dim=1)
generator = nn.DataParallel(generator, device_ids=opt.gpus, dim=0)
model.generator = generator
if not opt.train_from_state_dict and not opt.train_from:
for p in model.parameters():
p.data.uniform_(-opt.param_init, opt.param_init)
encoder.load_pretrained_vectors(opt)
decoder.load_pretrained_vectors(opt)
optim = onmt.Optim(
opt.optim, opt.learning_rate, opt.max_grad_norm,
lr_decay=opt.learning_rate_decay,
start_decay_at=opt.start_decay_at
)
else:
print('Loading optimizer from checkpoint:')
optim = checkpoint['optim']
print(optim)
optim.set_parameters(model.parameters())
if opt.train_from or opt.train_from_state_dict:
optim.optimizer.load_state_dict(checkpoint['optim'].optimizer.state_dict())
nParams = sum([p.nelement() for p in model.parameters()])
print('* number of parameters: %d' % nParams)
trainModel(model, trainData, validData, dataset, optim)
if __name__ == "__main__":
main()
| {
"pile_set_name": "Github"
} |
#pragma omp for schedule(static , 3)
#pragma omp parallel
#pragma omp single
| {
"pile_set_name": "Github"
} |
#!./matrix \
-e do-test -s
!#
;;; Authors: David Beazley <[email protected]>, 1999
;;; Martin Froehlich <[email protected]>, 2000
;;;
;;; PURPOSE OF THIS FILE: This file is an example for how to use the guile
;;; scripting options with a little more than trivial script. Example
;;; derived from David Beazley's matrix evaluation example. David
;;; Beazley's annotation: >>Guile script for testing out matrix
;;; operations. Disclaimer : I'm not a very good scheme
;;; programmer<<. Martin Froehlich's annotation: >>I'm not a very good
;;; scheme programmer, too<<.
;;;
;;; Explanation: The three lines at the beginning of this script are
;;; telling the kernel to load the enhanced guile interpreter named
;;; "matrix"; to execute the function "do-test" (-e option) after loading
;;; this script (-s option). There are a lot more options wich allow for
;;; even finer tuning. SEE ALSO: Section "Guile Scripts" in the "Guile
;;; reference manual -- Part I: Preliminaries".
;;;
;;;
;;; This program is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
;;; Create a zero matrix
(define (zero M)
(define (zero-loop M i j)
(if (< i 4)
(if (< j 4) (begin
(set-m M i j 0.0)
(zero-loop M i (+ j 1)))
(zero-loop M (+ i 1) 0))))
(zero-loop M 0 0))
;;; Create an identity matrix
(define (identity M)
(define (iloop M i)
(if (< i 4) (begin
(set-m M i i 1.0)
(iloop M (+ i 1)))))
(zero M)
(iloop M 0))
;;; Rotate around x axis
(define (rotx M r)
(define temp (new-matrix))
(define rd (/ (* r 3.14159) 180.0))
(zero temp)
(set-m temp 0 0 1.0)
(set-m temp 1 1 (cos rd))
(set-m temp 1 2 (- 0 (sin rd)))
(set-m temp 2 1 (sin rd))
(set-m temp 2 2 (cos rd))
(set-m temp 3 3 1.0)
(mat-mult M temp M)
(destroy-matrix temp))
;;; Rotate around y axis
(define (roty M r)
(define temp (new-matrix))
(define rd (/ (* r 3.14159) 180.0))
(zero temp)
(set-m temp 1 1 1.0)
(set-m temp 0 0 (cos rd))
(set-m temp 0 2 (sin rd))
(set-m temp 2 0 (- 0 (sin rd)))
(set-m temp 2 2 (cos rd))
(set-m temp 3 3 1.0)
(mat-mult M temp M)
(destroy-matrix temp))
;;; Rotate around z axis
(define (rotz M r)
(define temp (new-matrix))
(define rd (/ (* r 3.14159) 180.0))
(zero temp)
(set-m temp 0 0 (cos rd))
(set-m temp 0 1 (- 0 (sin rd)))
(set-m temp 1 0 (sin rd))
(set-m temp 1 1 (cos rd))
(set-m temp 2 2 1.0)
(set-m temp 3 3 1.0)
(mat-mult M temp M)
(destroy-matrix temp))
;;; Scale a matrix
(define (scale M s)
(define temp (new-matrix))
(define (sloop m i s)
(if (< i 4) (begin
(set-m m i i s)
(sloop m (+ i 1) s))))
(zero temp)
(sloop temp 0 s)
(mat-mult M temp M)
(destroy-matrix temp))
;;; Make a matrix with random elements
(define (randmat M)
(define (rand-loop M i j)
(if (< i 4)
(if (< j 4)
(begin
(set-m M i j (drand48))
(rand-loop M i (+ j 1)))
(rand-loop M (+ i 1) 0))))
(rand-loop M 0 0))
;;; stray definitions collected here
(define (rot-test M v t i)
(if (< i 360) (begin
(rotx M 1)
(rotz M -0.5)
(transform M v t)
(rot-test M v t (+ i 1)))))
(define (create-matrix) ; Create some matrices
(let loop ((i 0) (result '()))
(if (< i 200)
(loop (+ i 1) (cons (new-matrix) result))
result)))
(define (add-mat M ML)
(define (add-two m1 m2 i j)
(if (< i 4)
(if (< j 4)
(begin
(set-m m1 i j (+ (get-m m1 i j) (get-m m2 i j)))
(add-two m1 m2 i (+ j 1)))
(add-two m1 m2 (+ i 1) 0))))
(if (null? ML) *unspecified*
(begin
(add-two M (car ML) 0 0)
(add-mat M (cdr ML)))))
(define (cleanup ML)
(if (null? ML) *unspecified*
(begin
(destroy-matrix (car ML))
(cleanup (cdr ML)))))
(define (make-random ML) ; Put random values in them
(if (null? ML) *unspecified*
(begin
(randmat (car ML))
(make-random (cdr ML)))))
(define (mul-mat m ML)
(if (null? ML) *unspecified*
(begin
(mat-mult m (car ML) m)
(mul-mat m (cdr ML)))))
;;; Now we'll hammer on things a little bit just to make
;;; sure everything works.
(define M1 (new-matrix)) ; a matrix
(define v (createv 1 2 3 4)) ; a vector
(define t (createv 0 0 0 0)) ; the zero-vector
(define M-list (create-matrix)) ; get list of marices
(define M (new-matrix)) ; yet another matrix
(display "variables defined\n")
(define (do-test x)
(display "Testing matrix program...\n")
(identity M1)
(print-matrix M1)
(display "Rotate-x 45 degrees\n")
(rotx M1 45)
(print-matrix M1)
(display "Rotate y 30 degrees\n")
(roty M1 30)
(print-matrix M1)
(display "Rotate z 15 degrees\n")
(rotz M1 15)
(print-matrix M1)
(display "Scale 0.5\n")
(scale M1 0.5)
(print-matrix M1)
;; Rotating ...
(display "Rotating...\n")
(rot-test M1 v t 0)
(printv t)
(make-random M-list)
(zero M1)
(display "Adding them together (in Guile)\n")
(add-mat M1 M-list)
(print-matrix M1)
(display "Doing 200 multiplications (mostly in C)\n")
(randmat M)
(mul-mat M M-list)
(display "Cleaning up\n")
(cleanup M-list))
| {
"pile_set_name": "Github"
} |
<?php
use LightnCandy\LightnCandy;
use PHPUnit\Framework\TestCase;
require_once('tests/helpers_for_test.php');
class usageTest extends TestCase
{
/**
* @dataProvider compileProvider
*/
public function testUsedFeature($test)
{
LightnCandy::compile($test['template'], $test['options']);
$context = LightnCandy::getContext();
$this->assertEquals($test['expected'], $context['usedFeature']);
}
public function compileProvider()
{
$default = array(
'rootthis' => 0,
'enc' => 0,
'raw' => 0,
'sec' => 0,
'isec' => 0,
'if' => 0,
'else' => 0,
'unless' => 0,
'each' => 0,
'this' => 0,
'parent' => 0,
'with' => 0,
'comment' => 0,
'partial' => 0,
'dynpartial' => 0,
'inlpartial' => 0,
'helper' => 0,
'delimiter' => 0,
'subexp' => 0,
'rawblock' => 0,
'pblock' => 0,
'lookup' => 0,
'log' => 0,
);
$compileCases = array(
array(
'template' => 'abc',
),
array(
'template' => 'abc{{def',
),
array(
'template' => 'abc{{def}}',
'expected' => array(
'enc' => 1
),
),
array(
'template' => 'abc{{{def}}}',
'expected' => array(
'raw' => 1
),
),
array(
'template' => 'abc{{&def}}',
'expected' => array(
'raw' => 1
),
),
array(
'template' => 'abc{{this}}',
'expected' => array(
'enc' => 1
),
),
array(
'template' => 'abc{{this}}',
'options' => array('flags' => LightnCandy::FLAG_THIS),
'expected' => array(
'enc' => 1,
'this' => 1,
'rootthis' => 1,
),
),
array(
'template' => '{{#if abc}}OK!{{/if}}',
'expected' => array(
'if' => 1
),
),
array(
'template' => '{{#unless abc}}OK!{{/unless}}',
'expected' => array(
'unless' => 1
),
),
array(
'template' => '{{#with abc}}OK!{{/with}}',
'expected' => array(
'with' => 1
),
),
array(
'template' => '{{#abc}}OK!{{/abc}}',
'expected' => array(
'sec' => 1
),
),
array(
'template' => '{{^abc}}OK!{{/abc}}',
'expected' => array(
'isec' => 1
),
),
array(
'template' => '{{#each abc}}OK!{{/each}}',
'expected' => array(
'each' => 1
),
),
array(
'template' => '{{! test}}OK!{{! done}}',
'expected' => array(
'comment' => 2
),
),
array(
'template' => '{{../OK}}',
'expected' => array(
'parent' => 1,
'enc' => 1,
),
),
array(
'template' => '{{&../../OK}}',
'expected' => array(
'parent' => 1,
'raw' => 1,
),
),
array(
'template' => '{{&../../../OK}} {{../OK}}',
'options' => array(
'flags' => LightnCandy::FLAG_HANDLEBARSJS,
'helpers' => array(
'mytest' => function ($context) {
return $context;
}
)
),
'expected' => array(
'parent' => 2,
'enc' => 1,
'raw' => 1,
),
),
array(
'template' => '{{mytest ../../../OK}} {{../OK}}',
'options' => array(
'flags' => LightnCandy::FLAG_HANDLEBARSJS,
'helpers' => array(
'mytest' => function ($context) {
return $context;
}
)
),
'expected' => array(
'parent' => 2,
'enc' => 2,
'helper' => 1,
),
),
array(
'template' => '{{mytest . .}}',
'options' => array(
'flags' => LightnCandy::FLAG_HANDLEBARSJS,
'helpers' => array(
'mytest' => function ($a, $b) {
return '';
}
)
),
'expected' => array(
'rootthis' => 2,
'this' => 2,
'enc' => 1,
'helper' => 1,
),
),
array(
'template' => '{{mytest (mytest ..)}}',
'options' => array(
'flags' => LightnCandy::FLAG_HANDLEBARSJS,
'helpers' => array(
'mytest' => function ($context) {
return $context;
}
)
),
'expected' => array(
'parent' => 1,
'enc' => 1,
'helper' => 2,
'subexp' => 1,
),
),
array(
'template' => '{{mytest (mytest ..) .}}',
'options' => array(
'flags' => LightnCandy::FLAG_HANDLEBARSJS,
'helpers' => array(
'mytest' => function ($context) {
return $context;
}
)
),
'expected' => array(
'parent' => 1,
'rootthis' => 1,
'this' => 1,
'enc' => 1,
'helper' => 2,
'subexp' => 1,
),
),
array(
'template' => '{{mytest (mytest (mytest ..)) .}}',
'options' => array(
'flags' => LightnCandy::FLAG_HANDLEBARSJS,
'helpers' => array(
'mytest' => function ($context) {
return $context;
}
)
),
'expected' => array(
'parent' => 1,
'rootthis' => 1,
'this' => 1,
'enc' => 1,
'helper' => 3,
'subexp' => 2,
),
),
array(
'id' => '134',
'template' => '{{#if 1}}{{keys (keys ../names)}}{{/if}}',
'options' => array(
'flags' => LightnCandy::FLAG_HANDLEBARSJS,
'helpers' => array(
'keys' => function ($context) {
return $context;
}
)
),
'expected' => array(
'parent' => 1,
'enc' => 1,
'if' => 1,
'helper' => 2,
'subexp' => 1,
),
),
array(
'id' => '196',
'template' => '{{log "this is a test"}}',
'options' => array(
'flags' => LightnCandy::FLAG_HANDLEBARSJS,
),
'expected' => array(
'log' => 1,
'enc' => 1,
),
),
);
return array_map(function($i) use ($default) {
if (!isset($i['options'])) {
$i['options'] = array('flags' => 0);
}
if (!isset($i['options']['flags'])) {
$i['options']['flags'] = 0;
}
$i['expected'] = array_merge($default, isset($i['expected']) ? $i['expected'] : array());
return array($i);
}, $compileCases);
}
}
| {
"pile_set_name": "Github"
} |
8087
| {
"pile_set_name": "Github"
} |
enable_language(C)
add_library(empty STATIC empty.c)
file(GENERATE
OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt"
CONTENT "[$<TARGET_BUNDLE_DIR:empty>]"
)
| {
"pile_set_name": "Github"
} |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"prije podne",
"popodne"
],
"DAY": [
"nedjelja",
"ponedjeljak",
"utorak",
"srijeda",
"\u010detvrtak",
"petak",
"subota"
],
"ERANAMES": [
"Prije nove ere",
"Nove ere"
],
"ERAS": [
"p. n. e.",
"n. e."
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"januar",
"februar",
"mart",
"april",
"maj",
"juni",
"juli",
"august",
"septembar",
"oktobar",
"novembar",
"decembar"
],
"SHORTDAY": [
"ned",
"pon",
"uto",
"sri",
"\u010det",
"pet",
"sub"
],
"SHORTMONTH": [
"jan",
"feb",
"mar",
"apr",
"maj",
"jun",
"jul",
"aug",
"sep",
"okt",
"nov",
"dec"
],
"STANDALONEMONTH": [
"januar",
"februar",
"mart",
"april",
"maj",
"juni",
"juli",
"august",
"septembar",
"oktobar",
"novembar",
"decembar"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, dd. MMMM y.",
"longDate": "dd. MMMM y.",
"medium": "dd. MMM. y. HH:mm:ss",
"mediumDate": "dd. MMM. y.",
"mediumTime": "HH:mm:ss",
"short": "dd.MM.yy. HH:mm",
"shortDate": "dd.MM.yy.",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "KM",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "bs-latn",
"localeID": "bs_Latn",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (vf.v == 0 && i % 10 == 1 && i % 100 != 11 || vf.f % 10 == 1 && vf.f % 100 != 11) { return PLURAL_CATEGORY.ONE; } if (vf.v == 0 && i % 10 >= 2 && i % 10 <= 4 && (i % 100 < 12 || i % 100 > 14) || vf.f % 10 >= 2 && vf.f % 10 <= 4 && (vf.f % 100 < 12 || vf.f % 100 > 14)) { return PLURAL_CATEGORY.FEW; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| {
"pile_set_name": "Github"
} |
package cli
import (
"os"
"strings"
)
// Run parses the gorram command line args and runs the gorram command.
func Run() int {
env := OSEnv{
Args: make([]string, len(os.Args)),
Stderr: os.Stderr,
Stdout: os.Stdout,
Stdin: os.Stdin,
Env: getenv(os.Environ()),
}
copy(env.Args, os.Args)
return ParseAndRun(env)
}
func getenv(env []string) map[string]string {
ret := make(map[string]string, len(env))
for _, s := range env {
parts := strings.SplitN(s, "=", 2)
if len(parts) != 2 {
panic("invalid environment variable set: " + s)
}
ret[parts[0]] = parts[1]
}
return ret
}
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Reflection;
using Xamarin.Tests;
namespace Xamarin.MMP.Tests
{
public class NativeReferenceTests {
public const string ItemGroupTemplate = @"<ItemGroup>{0}</ItemGroup>";
public const string NativeReferenceTemplate = @"<NativeReference Include=""{0}""><IsCxx>False</IsCxx><Kind>{1}</Kind></NativeReference>";
public static string SimpleDylibPath {
get {
string rootDir = TI.FindRootDirectory ();
string buildLibPath = Path.Combine (rootDir, "../tests/mac-binding-project/bin/SimpleClassDylib.dylib");
Assert.IsTrue (File.Exists (buildLibPath), string.Format ("SimpleDylibPath missing? {0}", buildLibPath));
return buildLibPath;
}
}
public static string SimpleStaticPath {
get {
string rootDir = TI.FindRootDirectory ();
string buildLibPath = Path.Combine (rootDir, "../tests/mac-binding-project/bin/SimpleClassStatic.a");
Assert.IsTrue (File.Exists (buildLibPath), string.Format ("SimpleStaticPath missing? {0}", buildLibPath));
return buildLibPath;
}
}
public static string MobileStaticBindingPath {
get {
string rootDir = TI.FindRootDirectory ();
string buildLibPath = Path.Combine (rootDir, "../tests/mac-binding-project/bin/Mobile-static/MobileBinding.dll");
Assert.IsTrue (File.Exists (buildLibPath), string.Format ("MobileStaticBindingPath missing? {0}", buildLibPath));
return buildLibPath;
}
}
public static string CreateNativeRefInclude (string path, string kind) => string.Format (NativeReferenceTemplate, path, kind);
public static string CreateItemGroup (IEnumerable<string> elements) => string.Format (ItemGroupTemplate, string.Concat (elements));
public static string CreateSingleNativeRef (string path, string kind) => CreateItemGroup (CreateNativeRefInclude (path, kind).FromSingleItem ());
string CreateCopyOfSimpleClassInTestDir (string tmpDir, string fileName = "SimpleClassDylib.dylib")
{
string dylibPath = Path.Combine (tmpDir, "dll/");
string filePath = Path.Combine (dylibPath, fileName);
Directory.CreateDirectory (dylibPath);
File.Copy (Path.Combine (TI.AssemblyDirectory, TI.TestDirectory + "mac-binding-project/bin/SimpleClassDylib.dylib"), filePath);
return filePath;
}
void NativeReferenceTestCore (string tmpDir, TI.UnifiedTestConfig test, string testName, string libraryName, bool buildShouldBeSuccessful, bool libraryShouldNotBeCopied = false, Func<string, bool> processBuildOutput = null)
{
// Mobile
test.XM45 = false;
string buildResults = TI.TestUnifiedExecutable (test, false).BuildOutput;
Assert.IsTrue (!buildShouldBeSuccessful || !buildResults.Contains ("MM2006"), string.Format ("{0} - Mobile had MM2006 state {1} not match expected\n{2}", testName, buildShouldBeSuccessful, buildResults));
if (processBuildOutput != null)
Assert.IsTrue (processBuildOutput (buildResults), string.Format ("{0} - Mobile - We did not see our expected item in the build output: {1}", testName, libraryName));
string mobileBundlePath = Path.Combine (tmpDir, "bin/Debug/UnifiedExample.app/Contents/MonoBundle/");
if (libraryName != null)
Assert.IsTrue (Directory.GetFiles (mobileBundlePath).Any (x => x.Contains (libraryName) == !libraryShouldNotBeCopied), string.Format ("{0} - Mobile - We did not pull in native lib: {1}", testName, libraryName));
// XM45
test.XM45 = true;
buildResults = TI.TestUnifiedExecutable (test, false).BuildOutput;
Assert.IsTrue (!buildShouldBeSuccessful || !buildResults.Contains ("MM2006"), string.Format ("{0} - XM45 had MM2006 state {1} not match expected\n{2}", testName, buildShouldBeSuccessful, buildResults));
if (processBuildOutput != null)
Assert.IsTrue (processBuildOutput (buildResults), string.Format ("{0} - Mobile - We did not see our expected item in the build output: {1}", testName, libraryName));
string xm45BundlePath = Path.Combine (tmpDir, "bin/Debug/XM45Example.app/Contents/MonoBundle/");
if (libraryName != null)
Assert.IsTrue (Directory.GetFiles (xm45BundlePath).Any (x => x.Contains (libraryName) == !libraryShouldNotBeCopied), string.Format ("{0} - XM45 - We did not pull in native lib: {1}", testName, libraryName));
}
[Test]
public void Unified_WithNativeReferences_InMainProjectWorks ()
{
MMPTests.RunMMPTest (tmpDir => {
// Could be any dylib not in /System
const string SystemLibPath = "/Library/Frameworks/Mono.framework/Versions/Current/lib/libsqlite3.0.dylib";
TI.UnifiedTestConfig test = new TI.UnifiedTestConfig (tmpDir) { ItemGroup = CreateSingleNativeRef (SystemLibPath, "Dynamic") };
NativeReferenceTestCore (tmpDir, test, "Unified_WithNativeReferences_InMainProjectWorks - System", "libsqlite3.0.dylib", true);
test.ItemGroup = CreateSingleNativeRef (Path.GetFullPath (SimpleDylibPath), "Dynamic");
NativeReferenceTestCore (tmpDir, test, "Unified_WithNativeReferences_InMainProjectWorks - Local", "SimpleClassDylib.dylib", true);
test.ItemGroup = CreateSingleNativeRef (Path.GetFullPath (SimpleStaticPath), "Static");
NativeReferenceTestCore (tmpDir, test, "Unified_WithNativeReferences_InMainProjectWorks - Static", null, true);
test.ItemGroup = CreateSingleNativeRef ("/Library/Frameworks/iTunesLibrary.framework", "Framework");
NativeReferenceTestCore (tmpDir, test, "Unified_WithNativeReferences_InMainProjectWorks - Framework", null, true);
Assert.True (Directory.Exists (Path.Combine (tmpDir, "bin/Debug/UnifiedExample.app/Contents/Frameworks/iTunesLibrary.framework")));
string binaryPath = Path.Combine (tmpDir, "bin/Debug/UnifiedExample.app/Contents/MacOS/UnifiedExample");
string otoolText = TI.RunAndAssert ("/usr/bin/otool", new [] { "-l", binaryPath }, "Unified_WithNativeReferences_InMainProjectWorks - rpath");
Assert.True (otoolText.Contains ("path @loader_path/../Frameworks"));
});
}
[Test]
public void Unified_WithStaticNativeRef_ClangIncludesOurStaticLib ()
{
MMPTests.RunMMPTest (tmpDir => {
TI.UnifiedTestConfig test = new TI.UnifiedTestConfig (tmpDir) { ItemGroup = CreateSingleNativeRef (SimpleStaticPath, "Static") };
NativeReferenceTestCore (tmpDir, test, "Unified_WithNativeReferences_InMainProjectWorks - Static", null, true, false, s => {
var clangLines = s.Split ('\n').Where (x => x.Contains ("usr/bin/clang"));
var staticLib = clangLines.Where (x => x.Contains ("SimpleClassStatic.a"));
Assert.That (staticLib, Is.Not.Empty, "SimpleClassStatic.a:\n\t{0}", string.Join ("\n\t", clangLines));
return true;
});
});
}
[Test]
public void Unified_WithNativeReferences_MissingLibrariesActAsExpected ()
{
MMPTests.RunMMPTest (tmpDir => {
TI.UnifiedTestConfig test = new TI.UnifiedTestConfig (tmpDir) { ItemGroup = CreateSingleNativeRef ("/Library/Frameworks/ALibThatDoesNotExist.dylib", "Dynamic") };
NativeReferenceTestCore (tmpDir, test, "Unified_WithNativeReferences_MissingLibrariesActAsExpected - Nonexistant", null, false);
// Test a system dylib. Does not matter which one
test.ItemGroup = CreateSingleNativeRef ( "/System/Library/Frameworks/MapKit.framework/Versions/A/Resources/BridgeSupport/MapKit.dylib", "Dynamic");
NativeReferenceTestCore (tmpDir, test, "Unified_WithNativeReferences_MissingLibrariesActAsExpected - System", null, true);
// Test one of the ignored libs
test.ItemGroup = CreateSingleNativeRef ("cups", "Dynamic");
NativeReferenceTestCore (tmpDir, test, "Unified_WithNativeReferences_MissingLibrariesActAsExpected - Ignored", null, true);
});
}
[Test]
public void Unified_WithNativeReferences_IgnoredWorks ()
{
MMPTests.RunMMPTest (tmpDir => {
TI.UnifiedTestConfig test = new TI.UnifiedTestConfig (tmpDir) {
ItemGroup = CreateSingleNativeRef (Path.GetFullPath (SimpleDylibPath), "Dynamic"),
CSProjConfig = string.Format (@"<MonoBundlingExtraArgs>--ignore-native-library=""{0}""</MonoBundlingExtraArgs>", Path.GetFullPath (SimpleDylibPath))
};
NativeReferenceTestCore (tmpDir, test, "Unified_WithNativeReferences_InMainProjectWorks - Local", null, true, true);
});
}
[Test]
public void Unified_WithNativeReferences_ReadOnlyNativeLib ()
{
MMPTests.RunMMPTest (tmpDir => {
string filePath = CreateCopyOfSimpleClassInTestDir (tmpDir);
File.SetAttributes (filePath, FileAttributes.ReadOnly);
string itemGroup = CreateSingleNativeRef (@".\dll\SimpleClassDylib.dylib", "Dynamic");
TI.UnifiedTestConfig test = new TI.UnifiedTestConfig (tmpDir) { ProjectName = "UnifiedExample.csproj", ItemGroup = itemGroup };
NativeReferenceTestCore (tmpDir, test, "Unified_WithNativeReferences_ReadOnlyLib", null, true, true);
});
}
[Test]
public void NativeReference_WithDllImportOfSamePath_Builds ()
{
MMPTests.RunMMPTest (tmpDir => {
string filePath = CreateCopyOfSimpleClassInTestDir (tmpDir);
// Use absolute path here and in TestDecl to trigger bug
TI.UnifiedTestConfig test = new TI.UnifiedTestConfig (tmpDir)
{
ProjectName = "UnifiedExample.csproj",
ItemGroup = CreateSingleNativeRef (filePath, "Dynamic"),
TestDecl = string.Format ("[System.Runtime.InteropServices.DllImport (\"{0}\")]public static extern int GetFour ();", filePath),
TestCode = "GetFour ();"
};
NativeReferenceTestCore (tmpDir, test, "NativeReference_WithDllImportOfSamePath_Builds", null, true, true);
});
}
[Test]
public void MultipleNativeReferences_OnlyInvokeMMPOneTime_AndCopyEverythingIn ()
{
MMPTests.RunMMPTest (tmpDir => {
string firstPath = CreateCopyOfSimpleClassInTestDir (tmpDir);
string secondPath = CreateCopyOfSimpleClassInTestDir (tmpDir, "SeconClassDylib.dylib");
TI.UnifiedTestConfig test = new TI.UnifiedTestConfig (tmpDir) {
ProjectName = "UnifiedExample.csproj",
CSProjConfig = "<EnableCodeSigning>true</EnableCodeSigning>",
ItemGroup = CreateItemGroup (new string[] { CreateNativeRefInclude (firstPath, "Dynamic"), CreateNativeRefInclude (secondPath, "Dynamic") }),
};
NativeReferenceTestCore (tmpDir, test, "MultipleNativeReferences_OnlyInvokeMMPOneTime_AndCopyEverythingIn", null, true);
});
}
[Test]
public void ReferenceNativeRefNoCodeUsage_ShouldStillCopy ()
{
MMPTests.RunMMPTest (tmpDir => {
TI.UnifiedTestConfig test = new TI.UnifiedTestConfig (tmpDir) {
XM45 = true,
ItemGroup = CreateSingleNativeRef ("/Library/Frameworks/Mono.framework/Libraries/libintl.dylib", "Dynamic")
};
var log = TI.TestUnifiedExecutable (test);
Console.WriteLine (log.BuildOutput);
Assert.True (File.Exists (Path.Combine (tmpDir, "bin/Debug/XM45Example.app/Contents/MonoBundle/libintl.dylib")));
});
}
}
}
| {
"pile_set_name": "Github"
} |
import React from 'react';
import { formatName } from '../utils/helpers';
export default function ClaimantView({ formData }) {
const { name, relationshipToVet } = formData.claimant;
let relationship;
switch (relationshipToVet.type) {
case 1:
relationship = 'Service member';
break;
case 2:
relationship = 'Spouse';
break;
case 3:
relationship = 'Child';
break;
default:
// Invalid case; show nothing for relationship.
}
return (
<div>
<div>
<strong>{formatName(name)}</strong>
</div>
<div>{relationship}</div>
</div>
);
}
| {
"pile_set_name": "Github"
} |
# Copyright 2016 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.
# ==============================================================================
"""
IMPORTANT: This code is taken directly from Tensorflow
(https://github.com/tensorflow/tensorflow) and is copied temporarily
until it is available in a packaged Tensorflow version on pypi.
TODO(dennybritz): Delete this code when it becomes available in TF.
Seq2seq layer operations for use in neural networks.
"""
# pylint: skip-file
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import six
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import tensor_array_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.util import nest
__all__ = ["Decoder", "dynamic_decode"]
def _transpose_batch_time(x):
"""Transpose the batch and time dimensions of a Tensor.
Retains as much of the static shape information as possible.
Args:
x: A tensor of rank 2 or higher.
Returns:
x transposed along the first two dimensions.
Raises:
ValueError: if `x` is rank 1 or lower.
"""
x_static_shape = x.get_shape()
if x_static_shape.ndims is not None and x_static_shape.ndims < 2:
raise ValueError(
"Expected input tensor %s to have rank at least 2, but saw shape: %s" %
(x, x_static_shape))
x_rank = array_ops.rank(x)
x_t = array_ops.transpose(
x, array_ops.concat(
([1, 0], math_ops.range(2, x_rank)), axis=0))
x_t.set_shape(
tensor_shape.TensorShape([
x_static_shape[1].value, x_static_shape[0].value
]).concatenate(x_static_shape[2:]))
return x_t
@six.add_metaclass(abc.ABCMeta)
class Decoder(object):
"""An RNN Decoder abstract interface object."""
@property
def batch_size(self):
"""The batch size of the inputs returned by `sample`."""
raise NotImplementedError
@property
def output_size(self):
"""A (possibly nested tuple of...) integer[s] or `TensorShape` object[s]."""
raise NotImplementedError
@property
def output_dtype(self):
"""A (possibly nested tuple of...) dtype[s]."""
raise NotImplementedError
@abc.abstractmethod
def initialize(self, name=None):
"""Called before any decoding iterations.
Args:
name: Name scope for any created operations.
Returns:
`(finished, first_inputs, initial_state)`.
"""
raise NotImplementedError
@abc.abstractmethod
def step(self, time, inputs, state, name=None):
"""Called per step of decoding (but only once for dynamic decoding).
Args:
time: Scalar `int32` tensor.
inputs: Input (possibly nested tuple of) tensor[s] for this time step.
state: State (possibly nested tuple of) tensor[s] from previous time step.
name: Name scope for any created operations.
Returns:
`(outputs, next_state, next_inputs, finished)`.
"""
raise NotImplementedError
def _create_zero_outputs(size, dtype, batch_size):
"""Create a zero outputs Tensor structure."""
def _t(s):
return (s if isinstance(s, ops.Tensor) else constant_op.constant(
tensor_shape.TensorShape(s).as_list(),
dtype=dtypes.int32,
name="zero_suffix_shape"))
def _create(s, d):
return array_ops.zeros(
array_ops.concat(
([batch_size], _t(s)), axis=0), dtype=d)
return nest.map_structure(_create, size, dtype)
def dynamic_decode(decoder,
output_time_major=False,
impute_finished=False,
maximum_iterations=None,
parallel_iterations=32,
swap_memory=False,
scope=None):
"""Perform dynamic decoding with `decoder`.
Args:
decoder: A `Decoder` instance.
output_time_major: Python boolean. Default: `False` (batch major). If
`True`, outputs are returned as time major tensors (this mode is faster).
Otherwise, outputs are returned as batch major tensors (this adds extra
time to the computation).
impute_finished: Python boolean. If `True`, then states for batch
entries which are marked as finished get copied through and the
corresponding outputs get zeroed out. This causes some slowdown at
each time step, but ensures that the final state and outputs have
the correct values and that backprop ignores time steps that were
marked as finished.
maximum_iterations: `int32` scalar, maximum allowed number of decoding
steps. Default is `None` (decode until the decoder is fully done).
parallel_iterations: Argument passed to `tf.while_loop`.
swap_memory: Argument passed to `tf.while_loop`.
scope: Optional variable scope to use.
Returns:
`(final_outputs, final_state)`.
Raises:
TypeError: if `decoder` is not an instance of `Decoder`.
ValueError: if maximum_iterations is provided but is not a scalar.
"""
if not isinstance(decoder, Decoder):
raise TypeError("Expected decoder to be type Decoder, but saw: %s" %
type(decoder))
with variable_scope.variable_scope(scope or "decoder") as varscope:
# Properly cache variable values inside the while_loop
if varscope.caching_device is None:
varscope.set_caching_device(lambda op: op.device)
if maximum_iterations is not None:
maximum_iterations = ops.convert_to_tensor(
maximum_iterations, dtype=dtypes.int32, name="maximum_iterations")
if maximum_iterations.get_shape().ndims != 0:
raise ValueError("maximum_iterations must be a scalar")
initial_finished, initial_inputs, initial_state = decoder.initialize()
zero_outputs = _create_zero_outputs(decoder.output_size,
decoder.output_dtype,
decoder.batch_size)
if maximum_iterations is not None:
initial_finished = math_ops.logical_or(
initial_finished, 0 >= maximum_iterations)
initial_time = constant_op.constant(0, dtype=dtypes.int32)
def _shape(batch_size, from_shape):
if not isinstance(from_shape, tensor_shape.TensorShape):
return tensor_shape.TensorShape(None)
else:
batch_size = tensor_util.constant_value(
ops.convert_to_tensor(
batch_size, name="batch_size"))
return tensor_shape.TensorShape([batch_size]).concatenate(from_shape)
def _create_ta(s, d):
return tensor_array_ops.TensorArray(
dtype=d,
size=0,
dynamic_size=True,
element_shape=_shape(decoder.batch_size, s))
initial_outputs_ta = nest.map_structure(_create_ta, decoder.output_size,
decoder.output_dtype)
def condition(unused_time, unused_outputs_ta, unused_state, unused_inputs,
finished):
return math_ops.logical_not(math_ops.reduce_all(finished))
def body(time, outputs_ta, state, inputs, finished):
"""Internal while_loop body.
Args:
time: scalar int32 tensor.
outputs_ta: structure of TensorArray.
state: (structure of) state tensors and TensorArrays.
inputs: (structure of) input tensors.
finished: 1-D bool tensor.
Returns:
`(time + 1, outputs_ta, next_state, next_inputs, next_finished)`.
"""
(next_outputs, decoder_state, next_inputs,
decoder_finished) = decoder.step(time, inputs, state)
next_finished = math_ops.logical_or(decoder_finished, finished)
if maximum_iterations is not None:
next_finished = math_ops.logical_or(
next_finished, time + 1 >= maximum_iterations)
nest.assert_same_structure(state, decoder_state)
nest.assert_same_structure(outputs_ta, next_outputs)
nest.assert_same_structure(inputs, next_inputs)
# Zero out output values past finish
if impute_finished:
emit = nest.map_structure(
lambda out, zero: array_ops.where(finished, zero, out),
next_outputs,
zero_outputs)
else:
emit = next_outputs
# Copy through states past finish
def _maybe_copy_state(new, cur):
# TensorArrays and scalar states get passed through.
if isinstance(cur, tensor_array_ops.TensorArray):
pass_through = True
else:
new.set_shape(cur.shape)
pass_through = (new.shape.ndims == 0)
return new if pass_through else array_ops.where(finished, cur, new)
if impute_finished:
next_state = nest.map_structure(
_maybe_copy_state, decoder_state, state)
else:
next_state = decoder_state
outputs_ta = nest.map_structure(lambda ta, out: ta.write(time, out),
outputs_ta, emit)
return (time + 1, outputs_ta, next_state, next_inputs, next_finished)
res = control_flow_ops.while_loop(
condition,
body,
loop_vars=[
initial_time, initial_outputs_ta, initial_state, initial_inputs,
initial_finished
],
parallel_iterations=parallel_iterations,
swap_memory=swap_memory)
final_outputs_ta = res[1]
final_state = res[2]
final_outputs = nest.map_structure(lambda ta: ta.stack(), final_outputs_ta)
if not output_time_major:
final_outputs = nest.map_structure(_transpose_batch_time, final_outputs)
return final_outputs, final_state
| {
"pile_set_name": "Github"
} |
/**
* SyntaxHighlighter
* http://alexgorbatchev.com/SyntaxHighlighter
*
* SyntaxHighlighter is donationware. If you are using it, please donate.
* http://alexgorbatchev.com/SyntaxHighlighter/donate.html
*
* @version
* 3.0.83 (July 02 2010)
*
* @copyright
* Copyright (C) 2004-2010 Alex Gorbatchev.
*
* @license
* Dual licensed under the MIT and GPL licenses.
*/
.syntaxhighlighter {
background-color: white !important;
}
.syntaxhighlighter .line.alt1 {
background-color: white !important;
}
.syntaxhighlighter .line.alt2 {
background-color: white !important;
}
.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
background-color: #c3defe !important;
}
.syntaxhighlighter .line.highlighted.number {
color: white !important;
}
.syntaxhighlighter table caption {
color: black !important;
}
.syntaxhighlighter .gutter {
color: #787878 !important;
}
.syntaxhighlighter .gutter .line {
border-right: 3px solid #d4d0c8 !important;
}
.syntaxhighlighter .gutter .line.highlighted {
background-color: #d4d0c8 !important;
color: white !important;
}
.syntaxhighlighter.printing .line .content {
border: none !important;
}
.syntaxhighlighter.collapsed {
overflow: visible !important;
}
.syntaxhighlighter.collapsed .toolbar {
color: #3f5fbf !important;
background: white !important;
border: 1px solid #d4d0c8 !important;
}
.syntaxhighlighter.collapsed .toolbar a {
color: #3f5fbf !important;
}
.syntaxhighlighter.collapsed .toolbar a:hover {
color: #aa7700 !important;
}
.syntaxhighlighter .toolbar {
color: #a0a0a0 !important;
background: #d4d0c8 !important;
border: none !important;
}
.syntaxhighlighter .toolbar a {
color: #a0a0a0 !important;
}
.syntaxhighlighter .toolbar a:hover {
color: red !important;
}
.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
color: black !important;
}
.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
color: #3f5fbf !important;
}
.syntaxhighlighter .string, .syntaxhighlighter .string a {
color: #2a00ff !important;
}
.syntaxhighlighter .keyword {
color: #7f0055 !important;
}
.syntaxhighlighter .preprocessor {
color: #646464 !important;
}
.syntaxhighlighter .variable {
color: #aa7700 !important;
}
.syntaxhighlighter .value {
color: #009900 !important;
}
.syntaxhighlighter .functions {
color: #ff1493 !important;
}
.syntaxhighlighter .constants {
color: #0066cc !important;
}
.syntaxhighlighter .script {
font-weight: bold !important;
color: #7f0055 !important;
background-color: none !important;
}
.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
color: gray !important;
}
.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
color: #ff1493 !important;
}
.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
color: red !important;
}
.syntaxhighlighter .keyword {
font-weight: bold !important;
}
.syntaxhighlighter .xml .keyword {
color: #3f7f7f !important;
font-weight: normal !important;
}
.syntaxhighlighter .xml .color1, .syntaxhighlighter .xml .color1 a {
color: #7f007f !important;
}
.syntaxhighlighter .xml .string {
font-style: italic !important;
color: #2a00ff !important;
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2018, EnMasse authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.enmasse.admin.model.v1;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.enmasse.common.model.DefaultCustomResource;
import io.fabric8.kubernetes.api.model.Doneable;
import io.sundr.builder.annotations.Buildable;
import io.sundr.builder.annotations.BuildableReference;
import io.sundr.builder.annotations.Inline;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@Buildable(
editableEnabled = false,
generateBuilderPackage = false,
builderPackage = "io.fabric8.kubernetes.api.builder",
refs= {@BuildableReference(AbstractHasMetadataWithAdditionalProperties.class)},
inline = @Inline(type = Doneable.class, prefix = "Doneable", value = "done")
)
@DefaultCustomResource
@SuppressWarnings("serial")
public class AddressSpacePlan extends AbstractHasMetadataWithAdditionalProperties<AddressSpacePlan> implements io.enmasse.admin.model.AddressSpacePlan {
public static final String KIND = "AddressSpacePlan";
private AddressSpacePlanSpec spec;
private AddressSpacePlanStatus status;
public AddressSpacePlan() {
super(KIND, AdminCrd.API_VERSION_V1BETA2);
}
public void setSpec(AddressSpacePlanSpec spec) {
this.spec = spec;
}
public AddressSpacePlanSpec getSpec() {
return spec;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AddressSpacePlan that = (AddressSpacePlan) o;
return Objects.equals(getMetadata(), that.getMetadata()) &&
Objects.equals(spec, that.getSpec()) &&
Objects.equals(status, that.getStatus());
}
@Override
public int hashCode() {
return Objects.hash(getMetadata(), spec, status);
}
@Override
public String toString() {
return "AddressSpacePlan{" +
"metadata='" + getMetadata()+ '\'' +
", spec='" + spec + '\'' +
", status='" + status + '\'' +
'}';
}
@JsonIgnore
@Override
public Map<String, Double> getResourceLimits() {
return spec.getResourceLimits();
}
@JsonIgnore
@Override
public List<String> getAddressPlans() {
return spec.getAddressPlans();
}
@JsonIgnore
@Override
public String getShortDescription() {
return spec.getShortDescription();
}
@JsonIgnore
@Override
public String getDisplayName() {
String displayName = getMetadata().getName();
if (spec != null && spec.getDisplayName() != null) {
displayName = spec.getDisplayName();
}
return displayName;
}
@JsonIgnore
@Override
public int getDisplayOrder() {
int order = 0;
if (spec != null && spec.getDisplayOrder() != null) {
order = spec.getDisplayOrder();
}
return order;
}
@JsonIgnore
@Override
public String getAddressSpaceType() {
return spec.getAddressSpaceType();
}
@JsonIgnore
@Override
public String getInfraConfigRef() {
return spec.getInfraConfigRef();
}
public AddressSpacePlanStatus getStatus() {
return status;
}
public void setStatus(AddressSpacePlanStatus status) {
this.status = status;
}
}
| {
"pile_set_name": "Github"
} |
0 0 -25.0367
0.131622 -0.859071 -0.179196 -0.437678
| {
"pile_set_name": "Github"
} |
syntax = "proto3";
package POGOProtos.Data.Badge;
message GymBadgeStats {
uint64 total_time_defended_ms = 1;
uint32 num_battles_won = 2;
uint32 num_battles_lost = 5;
uint32 num_berries_fed = 3;
uint32 num_deploys = 4;
}
| {
"pile_set_name": "Github"
} |
<resources>
<string name="app_name">sndcpy</string>
<string name="notification_waiting">Waiting for connection…</string>
<string name="notification_forwarding">Audio forwarding enabled</string>
<string name="action_stop">Stop</string>
</resources>
| {
"pile_set_name": "Github"
} |
# frozen_string_literal: false
require 'test/unit'
class TestFuncall < Test::Unit::TestCase
module Relay
def self.target(*args, &block)
yield(*args) if block
end
end
require '-test-/funcall'
def test_with_funcall2
ok = nil
Relay.with_funcall2("feature#4504") {|arg| ok = arg || true}
assert_nil(ok)
end
def test_with_funcall_passing_block
ok = nil
Relay.with_funcall_passing_block("feature#4504") {|arg| ok = arg || true}
assert_equal("feature#4504", ok)
end
end
| {
"pile_set_name": "Github"
} |
import numpy as np
from numpy.testing import assert_equal, assert_allclose
from scipy.integrate import odeint
import scipy.integrate._test_odeint_banded as banded5x5
def rhs(y, t):
dydt = np.zeros_like(y)
banded5x5.banded5x5(t, y, dydt)
return dydt
def jac(y, t):
n = len(y)
jac = np.zeros((n, n), order='F')
banded5x5.banded5x5_jac(t, y, 1, 1, jac)
return jac
def bjac(y, t):
n = len(y)
bjac = np.zeros((4, n), order='F')
banded5x5.banded5x5_bjac(t, y, 1, 1, bjac)
return bjac
JACTYPE_FULL = 1
JACTYPE_BANDED = 4
def check_odeint(jactype):
if jactype == JACTYPE_FULL:
ml = None
mu = None
jacobian = jac
elif jactype == JACTYPE_BANDED:
ml = 2
mu = 1
jacobian = bjac
else:
raise ValueError("invalid jactype: %r" % (jactype,))
y0 = np.arange(1.0, 6.0)
# These tolerances must match the tolerances used in banded5x5.f.
rtol = 1e-11
atol = 1e-13
dt = 0.125
nsteps = 64
t = dt * np.arange(nsteps+1)
sol, info = odeint(rhs, y0, t,
Dfun=jacobian, ml=ml, mu=mu,
atol=atol, rtol=rtol, full_output=True)
yfinal = sol[-1]
odeint_nst = info['nst'][-1]
odeint_nfe = info['nfe'][-1]
odeint_nje = info['nje'][-1]
y1 = y0.copy()
# Pure Fortran solution. y1 is modified in-place.
nst, nfe, nje = banded5x5.banded5x5_solve(y1, nsteps, dt, jactype)
# It is likely that yfinal and y1 are *exactly* the same, but
# we'll be cautious and use assert_allclose.
assert_allclose(yfinal, y1, rtol=1e-12)
assert_equal((odeint_nst, odeint_nfe, odeint_nje), (nst, nfe, nje))
def test_odeint_full_jac():
check_odeint(JACTYPE_FULL)
def test_odeint_banded_jac():
check_odeint(JACTYPE_BANDED)
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2011 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 "net/socket/tcp_server_socket_libevent.h"
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <sys/socket.h>
#include "build/build_config.h"
#if defined(OS_POSIX)
#include <netinet/in.h>
#endif
#include "base/eintr_wrapper.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/socket/tcp_client_socket.h"
namespace net {
namespace {
const int kInvalidSocket = -1;
} // namespace
TCPServerSocketLibevent::TCPServerSocketLibevent(
net::NetLog* net_log,
const net::NetLog::Source& source)
: socket_(kInvalidSocket),
accept_socket_(NULL),
net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_SOCKET)) {
scoped_refptr<NetLog::EventParameters> params;
if (source.is_valid())
params = new NetLogSourceParameter("source_dependency", source);
net_log_.BeginEvent(NetLog::TYPE_SOCKET_ALIVE, params);
}
TCPServerSocketLibevent::~TCPServerSocketLibevent() {
if (socket_ != kInvalidSocket)
Close();
net_log_.EndEvent(NetLog::TYPE_SOCKET_ALIVE, NULL);
}
int TCPServerSocketLibevent::Listen(const IPEndPoint& address, int backlog) {
DCHECK(CalledOnValidThread());
DCHECK_GT(backlog, 0);
DCHECK_EQ(socket_, kInvalidSocket);
socket_ = socket(address.GetFamily(), SOCK_STREAM, IPPROTO_TCP);
if (socket_ < 0) {
PLOG(ERROR) << "socket() returned an error";
return MapSystemError(errno);
}
if (SetNonBlocking(socket_)) {
int result = MapSystemError(errno);
Close();
return result;
}
struct sockaddr_storage addr_storage;
size_t addr_len = sizeof(addr_storage);
struct sockaddr* addr = reinterpret_cast<struct sockaddr*>(&addr_storage);
if (!address.ToSockAddr(addr, &addr_len))
return ERR_INVALID_ARGUMENT;
int result = bind(socket_, addr, addr_len);
if (result < 0) {
PLOG(ERROR) << "bind() returned an error";
result = MapSystemError(errno);
Close();
return result;
}
result = listen(socket_, backlog);
if (result < 0) {
PLOG(ERROR) << "listen() returned an error";
result = MapSystemError(errno);
Close();
return result;
}
return OK;
}
int TCPServerSocketLibevent::GetLocalAddress(IPEndPoint* address) const {
DCHECK(CalledOnValidThread());
DCHECK(address);
struct sockaddr_storage addr_storage;
socklen_t addr_len = sizeof(addr_storage);
struct sockaddr* addr = reinterpret_cast<struct sockaddr*>(&addr_storage);
if (getsockname(socket_, addr, &addr_len) < 0)
return MapSystemError(errno);
if (!address->FromSockAddr(addr, addr_len))
return ERR_FAILED;
return OK;
}
int TCPServerSocketLibevent::Accept(
scoped_ptr<StreamSocket>* socket, const CompletionCallback& callback) {
DCHECK(CalledOnValidThread());
DCHECK(socket);
DCHECK(!callback.is_null());
DCHECK(accept_callback_.is_null());
net_log_.BeginEvent(NetLog::TYPE_TCP_ACCEPT, NULL);
int result = AcceptInternal(socket);
if (result == ERR_IO_PENDING) {
if (!MessageLoopForIO::current()->WatchFileDescriptor(
socket_, true, MessageLoopForIO::WATCH_READ,
&accept_socket_watcher_, this)) {
PLOG(ERROR) << "WatchFileDescriptor failed on read";
return MapSystemError(errno);
}
accept_socket_ = socket;
accept_callback_ = callback;
}
return result;
}
int TCPServerSocketLibevent::AcceptInternal(
scoped_ptr<StreamSocket>* socket) {
struct sockaddr_storage addr_storage;
socklen_t addr_len = sizeof(addr_storage);
struct sockaddr* addr = reinterpret_cast<struct sockaddr*>(&addr_storage);
int new_socket = HANDLE_EINTR(accept(socket_, addr, &addr_len));
if (new_socket < 0) {
int net_error = MapSystemError(errno);
if (net_error != ERR_IO_PENDING)
net_log_.EndEventWithNetErrorCode(NetLog::TYPE_TCP_ACCEPT, net_error);
return net_error;
}
IPEndPoint address;
if (!address.FromSockAddr(addr, addr_len)) {
NOTREACHED();
if (HANDLE_EINTR(close(new_socket)) < 0)
PLOG(ERROR) << "close";
net_log_.EndEventWithNetErrorCode(NetLog::TYPE_TCP_ACCEPT, ERR_FAILED);
return ERR_FAILED;
}
scoped_ptr<TCPClientSocket> tcp_socket(new TCPClientSocket(
AddressList::CreateFromIPAddress(address.address(), address.port()),
net_log_.net_log(), net_log_.source()));
int adopt_result = tcp_socket->AdoptSocket(new_socket);
if (adopt_result != OK) {
if (HANDLE_EINTR(close(new_socket)) < 0)
PLOG(ERROR) << "close";
net_log_.EndEventWithNetErrorCode(NetLog::TYPE_TCP_ACCEPT, adopt_result);
return adopt_result;
}
socket->reset(tcp_socket.release());
net_log_.EndEvent(NetLog::TYPE_TCP_ACCEPT,
make_scoped_refptr(new NetLogStringParameter(
"address", address.ToString())));
return OK;
}
void TCPServerSocketLibevent::Close() {
if (socket_ != kInvalidSocket) {
bool ok = accept_socket_watcher_.StopWatchingFileDescriptor();
DCHECK(ok);
if (HANDLE_EINTR(close(socket_)) < 0)
PLOG(ERROR) << "close";
socket_ = kInvalidSocket;
}
}
void TCPServerSocketLibevent::OnFileCanReadWithoutBlocking(int fd) {
DCHECK(CalledOnValidThread());
int result = AcceptInternal(accept_socket_);
if (result != ERR_IO_PENDING) {
accept_socket_ = NULL;
bool ok = accept_socket_watcher_.StopWatchingFileDescriptor();
DCHECK(ok);
CompletionCallback callback = accept_callback_;
accept_callback_.Reset();
callback.Run(result);
}
}
void TCPServerSocketLibevent::OnFileCanWriteWithoutBlocking(int fd) {
NOTREACHED();
}
} // namespace net
| {
"pile_set_name": "Github"
} |
#import "JXCategoryBaseView.h"
#import "JXCategoryIndicatorView.h"
#import "JXCategoryTitleView.h"
#import "JXCategoryImageView.h"
#import "JXCategoryTitleImageView.h"
#import "JXCategoryNumberView.h"
#import "JXCategoryDotView.h"
#import "JXCategoryFactory.h"
#import "JXCategoryIndicatorProtocol.h"
#import "JXCategoryViewDefines.h"
#import "JXCategoryListContainerView.h"
#import "JXCategoryIndicatorComponentView.h"
#import "JXCategoryIndicatorLineView.h"
#import "JXCategoryIndicatorTriangleView.h"
#import "JXCategoryIndicatorImageView.h"
#import "JXCategoryIndicatorBackgroundView.h"
#import "JXCategoryIndicatorBallView.h"
#import "JXCategoryIndicatorRainbowLineView.h"
| {
"pile_set_name": "Github"
} |
<component name="libraryTable">
<library name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.8">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/datatype/jackson-datatype-jsr310/2.9.8/jackson-datatype-jsr310-2.9.8.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/datatype/jackson-datatype-jsr310/2.9.8/jackson-datatype-jsr310-2.9.8-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/datatype/jackson-datatype-jsr310/2.9.8/jackson-datatype-jsr310-2.9.8-sources.jar!/" />
</SOURCES>
</library>
</component> | {
"pile_set_name": "Github"
} |
#region Copyright (C) 2019-2020 Dylech30th. All rights reserved.
// Pixeval - A Strong, Fast and Flexible Pixiv Client
// Copyright (C) 2019-2020 Dylech30th
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#endregion
using System.Collections.Generic;
namespace Pixeval.Core
{
/// <summary>
/// A base class provides several functions to browse the Pixiv content
/// </summary>
/// <typeparam name="T">the correspond data type</typeparam>
public interface IPixivAsyncEnumerable<T> : IAsyncEnumerable<T>, ICancellable
{
/// <summary>
/// Indicates how many pages have been requested
/// </summary>
int RequestedPages { get; }
/// <summary>
/// Basically, this method SHOULD increase the value of <see cref="RequestedPages" />
/// </summary>
void ReportRequestedPages();
/// <summary>
/// Tell the <see cref="IPixivAsyncEnumerable{T}" /> how to insert <see cref="item" /> to a <see cref="IList{T}" />
/// </summary>
/// <param name="item"></param>
/// <param name="collection"></param>
void InsertionPolicy(T item, IList<T> collection);
/// <summary>
/// Check if the <see cref="item" /> has the rationality to be inserted to the <see cref="IList{T}" />
/// </summary>
/// <param name="item"></param>
/// <param name="collection"></param>
/// <returns></returns>
bool VerifyRationality(T item, IList<T> collection);
}
} | {
"pile_set_name": "Github"
} |
ifdef FOO
$(error FOO is not defined!)
endif
FOO = foo
FOOFOUND = false
BARFOUND = false
BAZFOUND = false
ifdef FOO
FOOFOUND = true
else ifdef BAR
BARFOUND = true
else
BAZFOUND = true
endif
BAR2 = bar2
FOO2FOUND = false
BAR2FOUND = false
BAZ2FOUND = false
ifdef FOO2
FOO2FOUND = true
else ifdef BAR2
BAR2FOUND = true
else
BAZ2FOUND = true
endif
FOO3FOUND = false
BAR3FOUND = false
BAZ3FOUND = false
ifdef FOO3
FOO3FOUND = true
else ifdef BAR3
BAR3FOUND = true
else
BAZ3FOUND = true
endif
ifdef RANDOM
CONTINUATION = \
else \
endif
endif
ifndef ASDFJK
else
$(error ASFDJK was not set)
endif
TESTSET =
ifdef TESTSET
$(error TESTSET was not set)
endif
TESTEMPTY = $(NULL)
ifndef TESTEMPTY
$(error TEST-FAIL TESTEMPTY was probably expanded!)
endif
# ifneq ( a,a)
# $(error Arguments to ifeq should be stripped before evaluation)
# endif
XSPACE = x # trick
ifneq ($(NULL),$(NULL))
$(error TEST-FAIL ifneq)
endif
ifneq (x , x)
$(error argument-stripping1)
endif
ifeq ( x,x )
$(error argument-stripping2)
endif
ifneq ($(XSPACE), x )
$(error argument-stripping3)
endif
ifeq 'x ' ' x'
$(error TEST-FAIL argument-stripping4)
endif
all:
test $(FOOFOUND) = true # FOOFOUND
test $(BARFOUND) = false # BARFOUND
test $(BAZFOUND) = false # BAZFOUND
test $(FOO2FOUND) = false # FOO2FOUND
test $(BAR2FOUND) = true # BAR2FOUND
test $(BAZ2FOUND) = false # BAZ2FOUND
test $(FOO3FOUND) = false # FOO3FOUND
test $(BAR3FOUND) = false # BAR3FOUND
test $(BAZ3FOUND) = true # BAZ3FOUND
ifneq ($(FOO),foo)
echo TEST-FAIL 'FOO neq foo: "$(FOO)"'
endif
ifneq ($(FOO), foo) # Whitespace after the comma is stripped
echo TEST-FAIL 'FOO plus whitespace'
endif
ifeq ($(FOO), foo ) # But not trailing whitespace
echo TEST-FAIL 'FOO plus trailing whitespace'
endif
ifeq ( $(FOO),foo) # Not whitespace after the paren
echo TEST-FAIL 'FOO with leading whitespace'
endif
ifeq ($(FOO),$(NULL) foo) # Nor whitespace after expansion
echo TEST-FAIL 'FOO with embedded ws'
endif
ifeq ($(BAR2),bar)
echo TEST-FAIL 'BAR2 eq bar'
endif
ifeq '$(BAR3FOUND)' 'false'
echo BAR3FOUND is ok
else
echo TEST-FAIL BAR3FOUND is not ok
endif
ifndef FOO
echo TEST-FAIL "foo not defined?"
endif
@echo TEST-PASS
| {
"pile_set_name": "Github"
} |
These are example configurations for the low-cost [Acrylic Prusa I3 pro B 3D Printer DIY kit](http://www.geeetech.com/acrylic-geeetech-prusa-i3-pro-b-3d-printer-diy-kit-p-917.html) and the [3DTouch auto bed leveling sensor](http://www.geeetech.com/geeetech-3dtouch-auto-bed-leveling-sensor-for-3d-printer-p-1010.html) based on:
- `../GT2560/`
- [Marlin 1.1.4 With 3DTouch / BLTouch for i3 Pro B](https://www.geeetech.com/forum/viewtopic.php?t=19846)
The main characteristics of these configurations are:
- The defined motherboard is `BOARD_GT2560_REV_A_PLUS`.
- Travel limits are adjusted to the printer bed size and position.
- An example `SKEW_CORRECTION` for a particular printer is enabled. See comments below about how to adjust it to a particular printer.
- Using the LCD controller for bed leveling is enabled.
- `PROBE_MANUALLY` is enabled, which *provides a means to do "Auto" Bed Leveling without a probe*.
- The `LEVEL_BED_CORNERS` option for manual bed adjustment is enabled.
- Bilinear bed leveling is enabled, the boundaries for probing are adjusted to the glass size, and extrapolation is enabled.
- `PRINTCOUNTER` is enabled, in order to track statistical data.
- `INDIVIDUAL_AXIS_HOMING_MENU` is enabled, which adds individual axis homing items (Home X, Home Y, and Home Z) to the LCD menu.
- The speaker is enabled for the UI feedback.
- `bltouch` variant:
- `USE_ZMAX_PLUG` is enabled. See comments about connections below.
- Heaters and fans are turned off when probing.
- Multiple probing is set to 3.
# First-time configuration
## Skew factor
The skew factor must be adjusted for each printer:
- First, uncomment `#define XY_SKEW_FACTOR 0.0`, compile and upload the firmware.
- Then, print [YACS (Yet Another Calibration Square)](https://www.thingiverse.com/thing:2563185). Hint, scale it considering a margin for brim (if used). The larger, the better to make error measurements.
- Measure the printed part according to the comments in the example configuration file, and set `XY_DIAG_AC`, `XY_DIAG_BD` and `Y_SIDE_AD`.
- Last, comment `#define XY_SKEW_FACTOR 0.0` again, compile and upload.
## 3DTouch auto leveling sensor
- Print a suitable mount to attach the sensor to the printer. The example configuration file is adjusted to http://www.geeetech.com/wiki/images/6/61/3DTouch_auto_leveling_sensor-1.zip
- Unlike suggested in [geeetech.com/wiki/index.php/3DTouch_Auto_Leveling_Sensor](https://www.geeetech.com/wiki/index.php/3DTouch_Auto_Leveling_Sensor), the existing end stop switch is expected to be kept connected to Z_MIN. So, the sensor is to be connected to Z_MAX, according to Marlin's default settings. Furthermore, GT2560-A+ provides a connector for the servo next to thermistor connectors (see [GT2560](https://www.geeetech.com/wiki/images/thumb/4/45/GT2560_wiring.jpg/700px-GT2560_wiring.jpg) and [GT2560-A+](http://i.imgur.com/E0t34VU.png)).
- Be careful to respect the polarity of the sensor when connecting it to the GT2560-A+. Unlike end stops, reversing the connection will prevent the sensor from working properly.
- [Test](http://www.geeetech.com/wiki/index.php/3DTouch_Auto_Leveling_Sensor#Testing) and [calibrate](https://www.geeetech.com/wiki/index.php/3DTouch_Auto_Leveling_Sensor#Calibration) the sensor. | {
"pile_set_name": "Github"
} |
using BenchmarkDotNet.Attributes;
using Unity;
namespace Performance.Tests
{
public class PreResolved : BasicBase
{
const string name = nameof(PreResolved);
[IterationSetup]
public override void SetupContainer()
{
_container = new UnityContainer().AddExtension(new ForceActivation());
base.SetupContainer();
for (var i = 0; i < 3; i++)
{
base.UnityContainer();
base.LegacyFactory();
base.Factory();
base.Instance();
base.Unregistered();
base.Transient();
base.Mapping();
base.MappingToSingleton();
base.GenericInterface();
base.Array();
base.Enumerable();
}
}
[Benchmark(Description = "(" + name + ") IUnityContainer", OperationsPerInvoke = 20)]
public override object UnityContainer() => base.UnityContainer();
[Benchmark(Description = " IUnityContainerAsync", OperationsPerInvoke = 20)]
public override object UnityContainerAsync() => base.UnityContainerAsync();
[Benchmark(Description = "Factory (c,t,n)=>new Foo()", OperationsPerInvoke = 20)]
public override object Factory() => base.Factory();
[Benchmark(Description = "Factory (with name)", OperationsPerInvoke = 20)]
public override object LegacyFactory() => base.LegacyFactory();
[Benchmark(Description = "Instance", OperationsPerInvoke = 20)]
public override object Instance() => base.Instance();
[Benchmark(Description = "Unregistered type", OperationsPerInvoke = 20)]
public override object Unregistered() => base.Unregistered();
[Benchmark(Description = "Registered type with dependencies", OperationsPerInvoke = 20)]
public override object Transient() => base.Transient();
[Benchmark(Description = "Registered interface to type mapping", OperationsPerInvoke = 20)]
public override object Mapping() => base.Mapping();
[Benchmark(Description = "Registered generic type mapping", OperationsPerInvoke = 20)]
public override object GenericInterface() => base.GenericInterface();
[Benchmark(Description = "Mapping to Singleton", OperationsPerInvoke = 20)]
public override object MappingToSingleton() => base.MappingToSingleton();
[Benchmark(Description = "Array", OperationsPerInvoke = 20)]
public override object Array() => base.Array();
[Benchmark(Description = "Enumerable", OperationsPerInvoke = 20)]
public override object Enumerable() => base.Enumerable();
}
}
| {
"pile_set_name": "Github"
} |
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <random>
// template<class RealType = double>
// class lognormal_distribution
// {
// class param_type;
#include <random>
#include <limits>
#include <cassert>
int main()
{
{
typedef std::lognormal_distribution<> D;
typedef D::param_type param_type;
param_type p0(.75, 6);
param_type p;
p = p0;
assert(p.m() == .75);
assert(p.s() == 6);
}
}
| {
"pile_set_name": "Github"
} |
import { ICandidateInterview } from '@gauzy/models';
import { Component, OnDestroy, Input } from '@angular/core';
import { NbDialogRef, NbToastrService } from '@nebular/theme';
import { Subject } from 'rxjs';
import { TranslateService } from '@ngx-translate/core';
import { TranslationBaseComponent } from '../../../language-base/translation-base.component';
import { CandidateTechnologiesService } from 'apps/gauzy/src/app/@core/services/candidate-technologies.service';
import { CandidatePersonalQualitiesService } from 'apps/gauzy/src/app/@core/services/candidate-personal-qualities.service';
import { CandidateInterviewersService } from 'apps/gauzy/src/app/@core/services/candidate-interviewers.service';
import { CandidateInterviewService } from 'apps/gauzy/src/app/@core/services/candidate-interview.service';
@Component({
selector: 'ga-delete-interview',
templateUrl: 'delete-interview.component.html',
styleUrls: ['delete-interview.component.scss']
})
export class DeleteInterviewComponent extends TranslationBaseComponent
implements OnDestroy {
@Input() interview: ICandidateInterview;
private _ngDestroy$ = new Subject<void>();
constructor(
protected dialogRef: NbDialogRef<DeleteInterviewComponent>,
readonly translateService: TranslateService,
private toastrService: NbToastrService,
private candidateInterviewService: CandidateInterviewService,
private candidateTechnologiesService: CandidateTechnologiesService,
private candidatePersonalQualitiesService: CandidatePersonalQualitiesService,
private candidateInterviewersService: CandidateInterviewersService
) {
super(translateService);
}
async delete() {
try {
if (this.interview.personalQualities.length > 0) {
await this.candidatePersonalQualitiesService.deleteBulkByInterviewId(
this.interview.id
);
}
if (this.interview.technologies.length > 0) {
await this.candidateTechnologiesService.deleteBulkByInterviewId(
this.interview.id
);
}
await this.candidateInterviewersService.deleteBulkByInterviewId(
this.interview.id
);
await this.candidateInterviewService.delete(this.interview.id);
this.dialogRef.close(this.interview);
} catch (error) {
this.toastrError(error);
}
}
private toastrError(error) {
this.toastrService.danger(
this.getTranslation('NOTES.CANDIDATE.EXPERIENCE.ERROR', {
error: error.error ? error.error.message : error.message
}),
this.getTranslation('TOASTR.TITLE.ERROR')
);
}
closeDialog() {
this.dialogRef.close();
}
ngOnDestroy() {
this._ngDestroy$.next();
this._ngDestroy$.complete();
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* DO NOT EDIT THIS FILE!
*
* This file was automatically generated from external sources.
*
* Any manual change here will be lost the next time the SDK
* is updated. You've been warned!
*/
namespace DTS\eBaySDK\Inventory\Types;
/**
*
* @property boolean $applyTax
* @property string $thirdPartyTaxCategory
* @property double $vatPercentage
*/
class Tax extends \DTS\eBaySDK\Types\BaseType
{
/**
* @var array Properties belonging to objects of this class.
*/
private static $propertyTypes = [
'applyTax' => [
'type' => 'boolean',
'repeatable' => false,
'attribute' => false,
'elementName' => 'applyTax'
],
'thirdPartyTaxCategory' => [
'type' => 'string',
'repeatable' => false,
'attribute' => false,
'elementName' => 'thirdPartyTaxCategory'
],
'vatPercentage' => [
'type' => 'double',
'repeatable' => false,
'attribute' => false,
'elementName' => 'vatPercentage'
]
];
/**
* @param array $values Optional properties and values to assign to the object.
*/
public function __construct(array $values = [])
{
list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);
parent::__construct($parentValues);
if (!array_key_exists(__CLASS__, self::$properties)) {
self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
}
$this->setValues(__CLASS__, $childValues);
}
}
| {
"pile_set_name": "Github"
} |
/*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* 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.
*
* Author:
* Franz Wilhelmstötter ([email protected])
*/
/**
* This is the base package of the Jenetics library and contains all domain
* classes, like Gene, Chromosome or Genotype. Most of this types are immutable
* data classes and doesn't implement any behavior. It also contains the Selector
* and Alterer interfaces and its implementations. The classes in this package
* are (almost) sufficient to implement an own GA.
*
* <b>Introduction</b>
* <p><strong>Jenetics</strong> is an <strong>Genetic Algorithm</strong>,
* respectively an <strong>Evolutionary Algorithm</strong>, library written in
* Java. It is designed with a clear separation of the several concepts of the
* algorithm, e. g. Gene, Chromosome, Genotype, Phenotype, Population and
* fitness Function. <strong>Jenetics</strong> allows you to minimize and
* maximize the given fitness function without tweaking it. In contrast to other
* GA implementations, the library uses the concept of an evolution stream
* (EvolutionStream) for executing the evolution steps. Since the
* EvolutionStream implements the Java Stream interface, it works smoothly with
* the rest of the Java streaming API.</p>
*
* <b>Getting Started</b>
* <p>The minimum evolution Engine setup needs a genotype factory,
* Factory<Genotype<?>>, and a fitness Function. The Genotype
* implements the Factory interface and can therefore be used as prototype for
* creating the initial Population and for creating new random Genotypes.</p>
*
* <pre>{@code
* import io.jenetics.BitChromosome;
* import io.jenetics.BitGene;
* import io.jenetics.Genotype;
* import io.jenetics.engine.Engine;
* import io.jenetics.engine.EvolutionResult;
* import io.jenetics.util.Factory;
*
* public class HelloWorld {
* // 2.) Definition of the fitness function.
* private static Integer eval(Genotype<BitGene> gt) {
* return ((BitChromosome)gt.chromosome()).bitCount();
* }
*
* public static void main(String[] args) {
* // 1.) Define the genotype (factory) suitable
* // for the problem.
* Factory<Genotype<BitGene>> gtf =
* Genotype.of(BitChromosome.of(10, 0.5));
*
* // 3.) Create the execution environment.
* Engine<BitGene, Integer> engine = Engine
* .builder(HelloWorld::eval, gtf)
* .build();
*
* // 4.) Start the execution (evolution) and
* // collect the result.
* Genotype<BitGene> result = engine.stream()
* .limit(100)
* .collect(EvolutionResult.toBestGenotype());
*
* System.out.println("Hello World:\n" + result);
* }
* }
* }</pre>
*
* <p>In contrast to other GA implementations, the library uses the concept of
* an evolution stream (EvolutionStream) for executing the evolution steps.
* Since the EvolutionStream implements the Java Stream interface, it works
* smoothly with the rest of the Java streaming API. Now let's have a closer
* look at listing above and discuss this simple program step by step:</p>
* <ol>
* <li>The probably most challenging part, when setting up a new evolution
* Engine, is to transform the problem domain into a appropriate Genotype
* (factory) representation. In our example we want to count the number of ones
* of a BitChromosome. Since we are counting only the ones of one chromosome,
* we are adding only one BitChromosome to our Genotype. In general, the
* Genotype can be created with 1 to n chromosomes.</li>
* <li>Once this is done, the fitness function which should be maximized, can be
* defined. Utilizing the new language features introduced in Java 8, we simply
* write a private static method, which takes the genotype we defined and
* calculate it's fitness value. If we want to use the optimized bit-counting
* method, bitCount(), we have to cast the Chromosome<BitGene> class to
* the actual used BitChromosome class. Since we know for sure that we created
* the Genotype with a BitChromosome, this can be done safely. A reference to
* the eval method is then used as fitness function and passed to the
* Engine.build method.</li>
* <li>In the third step we are creating the evolution Engine, which is
* responsible for changing, respectively evolving, a given population. The
* Engine is highly configurable and takes parameters for controlling the
* evolutionary and the computational environment. For changing the evolutionary
* behavior, you can set different alterers and selectors. By changing the used
* Executor service, you control the number of threads, the Engine is allowed to
* use. An new Engine instance can only be created via its builder, which is
* created by calling the Engine.builder method.</li>
* <li>In the last step, we can create a new EvolutionStream from our Engine.
* The EvolutionStream is the model or view of the evolutionary process. It
* serves as a »process handle« and also allows you, among other things, to
* control the termination of the evolution. In our example, we simply truncate
* the stream after 100 generations. If you don't limit the stream, the
* EvolutionStream will not terminate and run forever. Since the EvolutionStream
* extends the java.util.stream.Stream interface, it integrates smoothly with
* the rest of the Java streaming API. The final result, the best Genotype in
* our example, is then collected with one of the predefined collectors of the
* EvolutionResult class.</li>
* </ol>
*
* @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a>
* @since 1.0
* @version 3.1
*/
package io.jenetics;
| {
"pile_set_name": "Github"
} |
/*
* 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.
*/
/* $Id$ */
package org.apache.fop.afp;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Test case for {@link AFPPaintingState}.
*/
public class AFPPaintingStateTestCase {
private AFPPaintingState sut;
/**
* Set up the system under test
*/
@Before
public void setUp() {
sut = new AFPPaintingState();
}
/**
* Test {get,set}BitmapEncodingQuality()
*/
@Test
public void testGetSetBitmapEncodingQuality() {
sut.setBitmapEncodingQuality(0.5f);
assertEquals(0.5f, sut.getBitmapEncodingQuality(), 0.01f);
sut.setBitmapEncodingQuality(0.9f);
assertEquals(0.9f, sut.getBitmapEncodingQuality(), 0.01f);
}
/**
* Test {,set}CanEmbedJpeg
*/
public void testGetSetCanEmbedJpeg() {
assertEquals(false, sut.canEmbedJpeg());
sut.setCanEmbedJpeg(true);
assertEquals(true, sut.canEmbedJpeg());
}
}
| {
"pile_set_name": "Github"
} |
/*
* LibrePCB - Professional EDA for everyone!
* Copyright (C) 2013 LibrePCB Developers, see AUTHORS.md for contributors.
* https://librepcb.org/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*******************************************************************************
* Includes
******************************************************************************/
#include "angleedit.h"
#include "doublespinbox.h"
/*******************************************************************************
* Namespace
******************************************************************************/
namespace librepcb {
/*******************************************************************************
* Constructors / Destructor
******************************************************************************/
AngleEdit::AngleEdit(QWidget* parent) noexcept
: NumberEditBase(parent), mValue(0) {
mSpinBox->setMinimum(-361.0); // < -360° to avoid rounding issues
mSpinBox->setMaximum(361.0); // > 360° to avoid rounding issues
mSpinBox->setSuffix("°");
updateSpinBox();
}
AngleEdit::~AngleEdit() noexcept {
}
/*******************************************************************************
* Setters
******************************************************************************/
void AngleEdit::setValue(const Angle& value) noexcept {
if (value != mValue) {
mValue = value;
updateSpinBox();
}
}
/*******************************************************************************
* Private Methods
******************************************************************************/
void AngleEdit::updateSpinBox() noexcept {
mSpinBox->setValue(mValue.toDeg());
}
void AngleEdit::spinBoxValueChanged(double value) noexcept {
try {
mValue = Angle::fromDeg(value); // can throw
emit valueChanged(mValue);
} catch (const Exception& e) {
// This should actually never happen, thus no user visible message here.
qWarning() << "Invalid angle entered:" << e.getMsg();
}
}
/*******************************************************************************
* End of File
******************************************************************************/
} // namespace librepcb
| {
"pile_set_name": "Github"
} |
using Shouldly.Tests.Strings;
using Shouldly.Tests.TestHelpers;
using Xunit;
namespace Shouldly.Tests.ShouldContain
{
public class FloatWithToleranceScenario
{
[Fact]
[UseCulture("en-US")]
public void FloatWithToleranceScenarioShouldFail()
{
Verify.ShouldFail(() =>
new[] { 1f, 2f, 3f }.ShouldContain(1.8f, 0.1d, "Some additional context"),
errorWithSource:
@"new[] { 1f, 2f, 3f }
should contain
1.8f
within
0.1d
but was
[1f, 2f, 3f]
Additional Info:
Some additional context",
errorWithoutSource:
@"[1f, 2f, 3f]
should contain
1.8f
within
0.1d
but was not
Additional Info:
Some additional context");
}
[Fact]
public void ShouldPass()
{
new[] { 1f, 2f, 3f }.ShouldContain(1.91f, 0.1d);
}
}
} | {
"pile_set_name": "Github"
} |
============
gedit 2.30.4
============
New Features and Fixes
======================
- Add mallard snippets (Paul Cutler)
New and updated translations
============================
- ca (Carles Ferrando Garcia)
- cs (Marek Černocký)
- de (Mario Blättermann)
- el (Michael Kotsarinis)
- es (Jorge González)
- fr (Claude Paroz)
- he (Yaron Shahrabani)
- hu (Gabor Kelemen)
- id (Andika Triwidada)
- ja (Hideki Yamane (Debian-JP))
- kk (Baurzhan Muftakhidinov)
- kn (Shankar Prasad)
- zh_CN (du baodao)
- zh_CN (朱涛)
============
gedit 2.30.3
============
New Features and Fixes
======================
- Misc bugfixes
New and updated translations
============================
- ca (Gil Forcada)
- ca@valencia (Gil Forcada)
- de (Mario Blättermann)
- et (Ivar Smolin)
- fi (Tommi Vainikainen)
- hu (Gabor Kelemen)
- kn (Shankar Prasad)
- or (Manoj Kumar Giri)
- th (Kittiphong Meesawat)
- uk (Maxim Dziumanenko)
============
gedit 2.30.2
============
New Features and Fixes
======================
- Fix cut and paste typo that broke syntax detection (Jesse van den Kieboom)
============
gedit 2.30.1
============
New Features and Fixes
======================
- Properly handle encoding conversion errors when saving (Jesse van den Kieboom)
- New logo (Henry Peters)
- Misc bugfixes
New and updated translations
============================
- ast (Xandru Armesto)
- bn_IN (Runa Bhattacharjee)
- crh (Reşat SABIQ)
- cs (Petr Kovar)
- hu (Gabor Kelemen)
- id (Andika Triwidada)
- ko (Changwoo Ryu)
- nl (Hannie Dumoleyn)
- ro (Adi Roiban)
- ru (Alexander Saprykin)
- th (Kittiphong Meesawat)
============
gedit 2.30.0
============
New Features and Fixes
======================
- Fix a crash in the new file saving code (Paolo Borelli)
- Misc bugfixes
New and updated translations
============================
- bn (Sadia Afroz)
- ca (Gil Forcada)
- crh (Reşat SABIQ)
- cs (Marek Černocký)
- da (Ask Hjorth Larsen)
- el (Kostas Papadimas)
- et (Mattias Põldaru)
- eu (Iñaki Larrañaga Murgoitio)
- fi (Tommi Vainikainen)
- hu (Gabor Kelemen)
- ja (Hideki Yamane (Debian-JP))
- ko (Changwoo Ryu)
- lt (Gintautas Miliauskas)
- lv (Rūdolfs Mazurs)
- ml ("Last-Translator: \n")
- pt (Duarte Loreto)
- ro (Adi Roiban)
- ru (Alexander Saprykin)
- zh_CN (Eleanor Chen)
============
gedit 2.29.9
============
New Features and Fixes
======================
- Fix a file corruption bug in the new file saving code (Paolo Borelli)
- Misc bugfixes
New and updated translations
============================
- ar (Khaled Hosny)
- bg (Krasimir Chonov)
- de (Hendrik Richter)
- en_GB (Philip Withnall)
- eu (Iñaki Larrañaga Murgoitio)
- fr (Claude Paroz)
- gl (Antón Méixome)
- hu (Gabor Kelemen)
- it (Milo Casagrande)
- nb (Kjartan Maraas)
- pa (A S Alam)
- pt_BR (Og Maciel)
- ru (Leonid Kanter)
- sr@latin (Goran Rakić)
- sr (Горан Ракић)
- sv (Daniel Nylander)
- ta (Dr,T,Vasudevan)
- uk (Maxim Dziumanenko)
============
gedit 2.29.8
============
New Features and Fixes
======================
- Rework encoding validation (Paolo Borelli)
- Misc bugfixes
New and updated translations
============================
- bg (Krasimir Chonov)
- de (Mario Blättermann)
- en_GB (Bruce Cowan)
- es (Jorge González)
- fr (Claude Paroz)
- gl (Fran Diéguez)
- he (Liel Fridman)
- nb (Kjartan Maraas)
- nn (Torstein Adolf Winterseth)
- pl (Piotr Drąg)
- sl (Matej Urbančič)
- zh_HK (Chao-Hsiung Liao)
- zh_TW (Chao-Hsiung Liao)
============
gedit 2.29.7
============
New Features and Fixes
======================
- Many string fixes (Philip Withnall)
- Misc bugfixes
New and updated translations
============================
- ar (Khaled Hosny)
- cs (Petr Kovar)
- de (Mario Blättermann)
- en_GB (Philip Withnall)
- es (Jorge González)
- et (Mattias Põldaru)
- fr (Claude Paroz)
- gl (Fran Diéguez)
- nb (Kjartan Maraas)
- pt_BR (Vladimir Melo)
- ro (Adi Roiban)
- sl (Matej Urbančič)
- ta (Dr,T,Vasudevan)
- zh_HK (Chao-Hsiung Liao)
- zh_TW (Chao-Hsiung Liao)
============
gedit 2.29.6
============
New Features and Fixes
======================
- Add "Open" to the filebrowser context menu (Paolo Borelli)
- Add option to ignore a version until the next is released
in the checkupdate plugin (Ignacio Casal Quinteiro)
- Misc bugfixes
New and updated translations
============================
- ar (Khaled Hosny)
- bg (Alexander Shopov)
- de (Christian Kirbach)
- es (Jorge González)
- et (Mattias Põldaru)
- pt_BR (Henrique P. Machado)
- sl (Matej Urbančič)
- zh_HK (Chao-Hsiung Liao)
- zh_TW (Chao-Hsiung Liao)
============
gedit 2.29.5
============
New Features and Fixes
======================
- Rework file saving and file loading to always use gio and take
advantage of gio stream converters to perform encoding conversion
and manage line terminators (Ignacio Casal Quinteiro,
Jesse van den Kieboom, Paolo Borelli)
- Experimental python support on win32 (Ignacio Casal Quinteiro)
- Misc bugfixes
New and updated translations
============================
- ar (Khaled Hosny)
- bg (Alexander Shopov)
- bn (Sadia Afroz)
- es (Jorge González)
- fr (Claude Paroz)
- nb (Kjartan Maraas)
- ta (Dr,T,Vasudevan)
============
gedit 2.29.4
============
New Features and Fixes
======================
- Several refactorings (Paolo Borelli)
- Don't check words that are marked no-spell-check (Jesse van den Kieboom)
- Tools outputpanel refactored (Per Arneng)
- Added support for platform specific tools (Jesse van den Kieboom)
- Improved menu integration and several fixes on OS X (Jesse van den Kieboom)
- Add xslt and html snippets (Paolo Borelli)
- Remember autospell per document (Ignacio Casal Quinteiro)
- Misc bugfixes
New and updated translations
============================
- cs (Marek Černocký)
- et (Mattias Põldaru)
- hu (Gabor Kelemen)
- nds (Nils-Christoph Fiedler)
- ro (Adi Roiban)
- sv (Daniel Nylander)
- uk (Maxim Dziumanenko)
- zh_CN (樊栖江(Fan Qijiang))
============
gedit 2.29.3
============
New Features and Fixes
======================
- Use gio metadata system
- Misc bugfixes
New and updated translations
============================
- el (Nikos Charonitakis)
============
gedit 2.29.2
============
New Features and Fixes
======================
- Order hidden files after normal files on filebrowser (Jesse van den Kieboom)
- Removed indent plugin, this is now supported by gtksourceview (Jesse van den Kieboom)
- Implemented file open support on OS X (Jesse van den Kieboom)
- Fixed OS X native vs X11 built (Jesse van den Kieboom)
- Basic mac OS X integration (Jesse van den Kieboom)
- Use GtkSpinner instead of GeditSpinner (Ignacio Casal Quinteiro)
- Misc bugfixes
New and updated translations
============================
- crh (Reşat SABIQ)
- en@shaw (Thomas Thurman)
- es (Jorge González)
- lv (Rūdolfs Mazurs)
- ro (Adi Roiban)
- sl (Matej Urbančič)
- ta (Dr,T,Vasudevan)
- th (อาคม โชติพันธวานนท์)
- th (Theppitak Karoonboonyanan)
- zh_CN (樊栖江(Fan Qijiang))
============
gedit 2.29.1
============
New Features and Fixes
======================
- Use the new completion framework in the snippets plugin (Jesse van den Kieboom)
- Misc bugfixes
New and updated translations
============================
- br (Denis ARNAUD)
- ca (Gil Forcada)
- sl (Matej Urbančič)
- zh_CN (Richard Ma)
============
gedit 2.28.0
============
New Features and Fixes
======================
- Misc bugfixes
New and updated translations
============================
- as (Amitakhya Phukan)
- bg (Alexander Shopov)
- bn_IN (Runa Bhattacharjee)
- br (Denis Arnaud)
- ca (Gil Forcada)
- cs (Jiri Eischmann)
- da (Ask H. Larsen)
- en_GB (Philip Withnall)
- et (Ivar Smolin)
- fi (Tommi Vainikainen)
- gl (Antón Méixome)
- gu (Sweta Kothari)
- hi (Rajesh Ranjan)
- kn (Shankar Prasad)
- lt (Gintautas Miliauskas)
- mai (Sangeeta Kumari)
- ml (Ani)
- mr (Sandeep Shedmake)
- nb (Kjartan Maraas)
- or (Manoj Kumar Giri)
- pa (A S Alam)
- pt_BR (Carlos José Pereira)
- ro (Adi Roiban)
- sl (Matej Urbančič)
- sr (Miloš Popović)
- ta (ifelix)
- te (krishnababu k)
- tr (Baris Cicek)
- uk (Maxim V. Dziumanenko)
- zh_HK (Chao-Hsiung Liao)
- zh_TW (Chao-Hsiung Liao)
============
gedit 2.27.6
============
New Features and Fixes
======================
- Misc bugfixes
New and updated translations
============================
- ar (Khaled Hosny)
- bn_IN (Runa Bhattacharjee)
- bn (Maruf Ovee)
- br (Denis Arnaud)
- cs (Jiri Eischmann)
- de (Mario Blättermann)
- el (Μάριος Ζηντίλης)
- es (Jorge González)
- et (Ivar Smolin)
- eu (Iñaki Larrañaga Murgoitio)
- fr (Claude Paroz)
- gu (Sweta Kothari)
- hu (Gabor Kelemen)
- it (Milo Casagrande)
- kn (Shankar Prasad)
- ko (Changwoo Ryu)
- nb (Kjartan Maraas)
- pl (Tomasz Dominikowski)
- pt_BR (Fábio Nogueira)
- pt_BR (Rodrigo L. M. Flores)
- pt (Duarte Loreto)
- sr@latin (Goran Rakić)
- sr (Горан Ракић)
- sv (Daniel Nylander)
- ta (I. Felix)
- tr (Baris Cicek)
- zh_HK (Chao-Hsiung Liao)
- zh_TW (Chao-Hsiung Liao)
============
gedit 2.27.5
============
New Features and Fixes
======================
- Misc bugfixes
New and updated translations
============================
- ar (Khaled Hosny)
- bg (Yavor Doganov)
- br (Denis Arnaud)
- ca (Gil Forcada)
- ca@valencia (Carles Ferrando Garcia)
- eo (Jacob Nordfalk)
- es (Jorge González)
- et (Ivar Smolin)
- fi (Tommi Vainikainen)
- gl (Antón Méixome)
- pl (Piotr Drąg)
- pt_BR (André Gondim)
- ro (Lucian Adrian Grijincu)
- sv (Daniel Nylander)
- th (Akom C.)
============
gedit 2.27.4
============
New Features and Fixes
======================
- Misc bugfixes
New and updated translations
============================
- ar (Khaled Hosny)
- cy (Iestyn Pryce)
- de (Christian Kirbach)
- es (Jorge González)
- et (Ivar Smolin)
- ga (Seán de Búrca)
- nb (Kjartan Maraas)
- ta (Dr.T.Vasudevan)
============
gedit 2.27.3
============
New Features and Fixes
======================
- Misc bugfixes
New and updated translations
============================
- cs (Marek Černocký)
- cs (Petr Kovar)
- de (Mario Blättermann)
- es (Jorge González)
- et (Ivar Smolin)
- gl (Antón Méixome)
- gu (Sweta Kothari)
- pt_BR (César Veiga)
- sv (Daniel Nylander)
- ta (Dr.T.Vasudevan)
- uk (wanderlust)
============
gedit 2.27.2
============
New Features and Fixes
======================
- New Check Update plugin (Ignacio Casal Quinteiro)
- Remember the search dialog position (Ignacio Casal Quinteiro)
- Do not append the final endline for empty files (Paolo Borelli)
- Mac osx dmg package (Jesse van den Kieboom)
- Misc bugfixes
New and updated translations
============================
- ca (Gil Forcada)
- da (Kenneth Nielsen)
- es (Jorge González)
- et (Ivar Smolin)
- eu (Iñaki Larrañaga Murgoitio)
- ml (Praveen Arimbrathodiyil)
- nb (Kjartan Maraas)
============
gedit 2.27.1
============
New Features and Fixes
======================
- Remove the mmap document loader (Paolo Borelli)
- Remove open location dialog and sample plugin (Paolo Borelli)
- Added public API for document saving (Jesse van den Kieboom)
- Put external tools in a submenu (Jesse van den Kieboom)
- Added language support for external tools (Jesse van den Kieboom)
- Implemented asynchronous reading and writing on external tools (Jesse van den Kieboom)
- Add Quick Open plugin (Jesse van den Kieboom)
- Misc bugfixes
New and updated translations
============================
- bn (Runa Bhattacharjee)
- es (Jorge González)
- fr (Claude Paroz)
- id (Mohammad DAMT)
- ta (Dr.T.Vaasudevan)
============
gedit 2.26.2
============
New Features and Fixes
======================
- Misc bugfixes
New and updated translations
============================
- ar (Khaled Hosny)
- ca (Joan Duran)
- el (Michael Kotsarinis)
- es (Jorge González)
- et (Mattias Põldaru)
- zh_CN (TeliuTe)
============
gedit 2.26.1
============
New Features and Fixes
======================
- Ensure plugins are resident modules (Paolo Borelli)
- Add Fortran 95 snippets (Jens Domke)
- Misc bugfixes
New and updated translations
============================
- Jorge Gonzalez (es)
- Miloš Popović (sr)
- Osama Khalid (ar)
- Raivis Dejus (lv)
- Reşat SABIQ (crh)
- Shankar Prasad (kn)
- Takeshi AIHANA (ja)
- Thanos Lefteris (el)
============
gedit 2.26.0
============
New Features and Fixes
======================
- Misc bugfixes
New and updated translations
============================
- Amitakhya Phukan (as)
- Gintautas Miliauskas (lt)
- I. Felix (ta)
- Ignacio Casal Quinteiro (gl)
- Jennie Petoumenou (el)
- Krishnababu K (te)
- Manoj Kumar Giri (or)
- Rajesh Ranjan (hi)
- Runa Bhattacharjee (bn_IN)
- Yuriy Penkin (ru)
============
gedit 2.25.8
============
New Features and Fixes
======================
- Misc bugfixes
New and updated translations
============================
- Baris Cicek (tr)
- Claude Paroz (fr)
- Duarte Loreto (pt)
- Gabor Kelemen (hu)
- Jesse van den Kieboom (nl)
- Mattias Põldaru (et)
- Milo Casagrande (it)
- Philip Withnall (en_GB)
- Rajesh Ranjan (hi)
- Rajesh Ranjan (mai)
- Sandeep Shedmake (mr)
- Sweta Kothari (gu)
- Takeshi AIHANA (ja)
- Theppitak Karoonboonyanan (th)
============
gedit 2.25.7
============
New Features and Fixes
======================
- Misc bugfixes
New and updated translations
============================
- Adi Roiban (ro)
- Alexander Shopov (bg)
- Chao-Hsiung Liao (zh_HK)
- Chao-Hsiung Liao (zh_TW)
- Clytie Siddall (vi)
- Duarte Loreto (pt)
- Ihar Hrachyshka (be@latin)
- Inaki Larranaga Murgoitio (eu)
- Kenneth Nielsen (da)
- Mikel González (ast)
- Sweta Kothari (gu)
- Tomasz Dominikowski (pl)
- Wouter Bolsterlee (nl)
============
gedit 2.25.6
============
New Features and Fixes
======================
- Misc bugfixes
New and updated translations
============================
- Andre Gondim (pt_BR)
- Andre Klapper (de)
- Changwoo Ryu (ko)
- Christian Kirbach (de)
- Gabor Kelemen (hu)
- Gil Forcada (ca)
- Raivis DEjus (lv)
- Yair Hershkovitz (he)
- 甘露(Gan Lu) (zh_CN.po)
============
gedit 2.25.5
============
New Features and Fixes
======================
- Add Fullscreen Mode (Ignacio Casal Quinteiro)
- Add a configuration dialog for the python console (B. Clausius)
- Rescan plugins when opening the preference dialog (Ignacio Casal Quinteiro)
- Misc bugfixes
New and updated translations
============================
- Daniel Nylander (sv)
- Ilkka Tuohela (fi)
- Ivar Smolin (et)
- Joan Duran (ca)
- Jorge Gonzalez (es)
- Kamil Paral (cs)
- Kjartan Maraas (nb)
- Marcel Telka (sk)
- Petr Kovar (cs)
- Shankar Prasad (kn)
- Theppitak Karoonboonyanan (th)
============
gedit 2.25.4
============
New Features and Fixes
======================
- Add quick syntax highlightig and tab width selection in the statusbar (Jesse van den Kieboom)
- More work on the internal bus system (Jesse van den Kieboom)
- Bugfixes and features for the snippets plugin (Jesse van den Kieboom)
- Parse syntax highlighting language from modelines (Sergej Chodarev)
- Misc bugfixes
New and updated translations
============================
- César Veiga (pt_BR)
- Jorge Gonzalez (es)
============
gedit 2.25.3
============
New Features and Fixes
======================
- Win32 port with installer (Ignacio Casal Quinteiro)
- Internal bus system to allow plugin intercomminication (Jesse van den Kieboom)
- Use GtkSourceView to detect language highlighting (Paolo Borelli)
- Misc bugfixes
New and updated translations
============================
- Jorge Gonzalez (es)
- Theppitak Karoonboonyanan (th)
- Alexander Shopov (bg)
- Claude Paroz (fr)
============
gedit 2.25.2
============
New Features and Fixes
======================
- Fixes to the new plugin system (Paolo Borelli)
New and updated translations
============================
- Daniel Nylander (sv)
============
gedit 2.25.1
============
New Features and Fixes
======================
- Rework the plugin system to have loaders as shared objects (Jesse van den Kieboom)
- Fix build on OSX (Jesse van den Kieboom)
New and updated translations
============================
- Jorge Gonzalez (es)
- Yuriy Penkin (ru)
============
gedit 2.24.2
============
New Features and Fixes
======================
- Fix icon lookup in the filebrowser plugin (Jesse van den Kieboom)
- Allow to move to a line relative to the current line (Ignacio Casal Quinteiro)
- Misc bugfixes
New and updated translations
============================
- Ignacio Casal Quinteiro (gl)
- Leonardo Ferreira Fontenelle (pt_BR)
- Rafael Garcia (la)
============
gedit 2.24.1
============
New Features and Fixes
======================
- Fix performance problem with large dirs in the filebrowser
plugin (Paolo Borelli, Jesse van den Kieboom)
- Misc bugfixes
New and updated translations
============================
- Robert Sedak (hr)
- Anas Afif Emad (ar)
- Ask H. Larsen (da)
- Vladimir Melo (pt_BR)
============
gedit 2.24.0
============
New and updated translations
============================
- Anas Afif Emad (ar)
- I. Felix (ta)
- Ivar Smolin (et)
- Jiri Eischmann (cs)
- Kenneth Nielsen (da)
- Konstantinos Kouratoras (el)
- Mişu Moldovan (ro)
- Tomasz Dominikowski (pl)
- Yuriy Penkin (ru)
=============
gedit 2.23.92
=============
New Features and Fixes
======================
- Revert a workaround for a gvfs bug that has now been fixed (Paolo Borelli)
New and updated translations
============================
- Alexander Shopov (bg)
- Baris Cicek (tr)
- Changwoo Ryu (ko)
- Christian Kirbach (de)
- Gabor Kelemen (hu)
- Gil Forcada (ca)
- Gintautas Miliauskas (lt)
- Hendrik Richter (de)
- Khaled Hosny (ar)
- Laurent Dhima (sq)
- Milo Casagrande (it)
- Miloš Popović (sr)
- Pema Geyleg (dz)
- Praveen Arimbrathodiyil (ml)
- Robert Sedak (hr)
- Sandeep Shedmake (mr)
- Vladimir Melo (pt_BR)
=============
gedit 2.23.92
=============
New Features and Fixes
======================
- Bugfixes related to the gio port (Jesse van den Kieboom, Paolo Borelli)
New and updated translations
============================
- Duarte Loreto (pt)
- Funda Wang (zh_CN)
- Laurent Dhima (sq)
- Nguyễn Thái Ngọc Duy (vi)
- Philip Withnall (en_GB)
- Praveen Arimbrathodiyil (ml)
- Robert Sedak (hr)
- Runa Bhattacharjee (bn_IN)
- Seán de Búrca (ga)
- Sweta Kothari (gu.po)
- Wouter Bolsterlee (nl)
=============
gedit 2.23.91
=============
New Features and Fixes
======================
- Misc bugfixes
New and updated translations
============================
- Arangel Angov (mk)
- Chao-Hsiung Liao (zh_HK)
- Chao-Hsiung Liao (zh_TW)
- Daniel Nylander (sv)
- Fábio Nogueira, Vladimir Melo (pt_BR)
- Goran Rakic (sr@latin)
- Ilkka Tuohela (fi)
- Inaki Larranaga Murgoitio (eu)
- Ivar Smolin (et)
- Jorge Gonzalez (es)
- Kjartan Maraas (nb)
- Manoj Kumar Giri (or)
- Robert-André Mauchin (fr)
- Seán de Búrca (ga)
- Shankar Prasad (kn)
- Sweta Kothari (gu)
- Takeshi AIHANA (ja)
- Theppitak Karoonboonyanan (th)
=============
gedit 2.23.90
=============
New Features and Fixes
======================
- Misc bugfixes related to the gio migration (Jesse van den Kieboom)
New and updated translations
============================
- Ignacio Casal Quinteiro (gl)
- Jorge Gonzalez (es)
- Takeshi AIHANA (ja)
- Christian Kirbach (de)
- Ivar Smolin (et)
- Kjartan Maraas (nb)
- Gil Forcada (ca)
- Ilkka Tuohela (fi)
- Runa Bhattacharjee (bn_IN)
============
gedit 2.23.2
============
New Features and Fixes
======================
- remove libgnome dependency, use eggsmclient for XSMP support (Johan Dahlin, Dan Winship)
============
gedit 2.23.2
============
New Features and Fixes
======================
- Port to gio/vfs, remove gnome-vfs dependency (Jesse van den Kieboom)
- Port to gtkbuilder, remove libglade dependency (Jesse van den Kieboom)
New and updated translations
============================
- Andre Klapper (de)
- Clytie Siddall (vi)
- Daniel Nylander (sv)
- Djihed Afifi (ar)
- Duarte Loreto (pt)
- Fábio Nogueira (pt_BR)
- Gabor Kelemen (hu)
- Gil Forcada (ca)
- Ignacio Casal Quinteiro (gl)
- Ilkka Tuohela (fi)
- Inaki Larranaga Murgoitio (eu)
- Ivar Smolin (et)
- Jorge Gonzalez (es)
- Khaled Hosny (ar)
- Leonardo Ferreira Fontenelle (pt_BR)
- Luca Ferretti (it)
- Máté Őry (hu)
- Philipp Kerling (de)
- Rajesh Ranjan (mai)
- Sweta Kothari (gu)
- Theppitak Karoonboonyanan (th)
- Wouter Bolsterlee (nl)
- Yair Hershkovitz (he)
- Yannig Marchegay (oc)
- Zabeeh Khan (ps)
============
gedit 2.23.1
============
New Features and Fixes
======================
- port the filebrowser plugin to gio/gvfs (Mikael Hermansson, Jesse van den Kieboom)
- start porting internals to gio/gvfs (Paolo Borelli)
- rework some of the python plugins core code (Steve Frécinaux)
New and updated translations
============================
- Jorge Gonzalez (es)
- Claude Paroz (fr)
- Kjartan Maraas (nb)
- Jiri Eischmann (cs)
- Yavor Doganov (bg)
============
gedit 2.22.1
============
New Features and Fixes
======================
- Make Ctrl+D delete the current line
- Misc bugfixes
New and updated translations
============================
- Yair Hershkovitz (he)
- Philip Withnall (en_GB.po)
- Ivar Smolin (et)
- Artur Flinta (pl)
- Claude Paroz (fr)
- Praveen Arimbrathodiyil (ml)
- Jorge Gonzalez (es)
============
gedit 2.22.0
============
New Features and Fixes
======================
- Misc bugfixes
New and updated translations
============================
- Ankit Patel (gu)
- Baris Cicek (tr)
- Changwoo Ryu (ko)
- Djihed Afifi (ar)
- Duarte Loreto (pt)
- Friedel Wolff (af)
- Gabor Kelemen (hu)
- Gintautas Miliauskas (lt)
- Guntupalli Karunakar (hi)
- Ivar Smolin (et)
- Jiri Eischmann (cs)
- Jorge Gonzalez (es)
- Kostas Papadimas (el)
- Luca Ferretti (it)
- Maxim Dziumanenko (uk)
- Rahul Bhalerao (mr)
- Runa Bhattacharjee (bn_IN)
- Stéphane Raimbault (fr)
- Yuri Kozlov (ru)
============
gedit 2.21.2
============
New Features and Fixes
======================
- Misc bugfixes
New and updated translations
============================
- Arangel Angov (mk)
- Artur Flinta (pl)
- Chao-Hsiung Liao (zh_HK)
- Chao-Hsiung Liao (zh_TW)
- Claude Paroz (fr)
- Daniel Nylander (sv)
- David Lodge (en_GB)
- Djihed Afifi (ar)
- Duarte Loreto (pt)
- Gil Forcada (ca)
- Hendrik Brandt (de)
- Ignacio Casal Quinteiro (gl)
- Ihar Hrachyshka (be@latin)
- Ilkka Tuohela (fi)
- Inaki Larranaga Murgoitio (eu)
- Ivar Smolin (et)
- Jiri Eischmann (cs)
- Jonh Wendell (pt_BR)
- Jorge Gonzalez (es)
- Kenneth Nielsen (da)
- Kjartan Maraas (nb)
- Luca Ferretti (it)
- Mark Krapviner (he)
- Nikos Charonitakis (el)
- Pawan Chitrakar (ne)
- Sandeep Shedmake (mr)
- Takeshi AIHANA (ja)
- Theppitak Karoonboonyanan (th)
- Wouter Bolsterlee (nl)
- Yannig Marchegay (oc)
============
gedit 2.21.1
============
New Features and Fixes
======================
- Reimplemented printing using GtkPrint and remove libgnomeprint[ui]
dependency (Paolo Maggi, Paolo Borelli)
- Improvements to the plugin system code (Steve Frécinaux)
- Handle viewports as well as workspaces (Steve Frécinaux)
- Misc bugfixes
New and updated translations
============================
- Alexander Shopov (bg)
- Amitakhya Phukan (as)
- Andre Klapper (de)
- Ani Peter (ml)
- Clytie Siddall (vi)
- Gabor Kelemen (hu)
- Ignacio Casal Quinteiro (gl)
- Ilkka Tuohela (fi)
- Inaki Larranaga Murgoitio (eu)
- Ivar Smolin (et)
- Kjartan Maraas (nb)
- Krishna Babu K (te)
- Matej Urbančič (sl)
- Og Maciel (pt_BR)
- Seán de Búrca (ga)
- Shankar Prasad (kn)
- Sohaib Afifi (ar)
- Takeshi AIHANA (ja)
- Yair Hershkovitz (he)
- Yannig Marchegay (oc)
============
gedit 2.20.3
============
New Features and Fixes
======================
- Properly preserve file permissions and ownership when saving (Paolo Borelli)
New and updated translations
============================
- Gabor Kelemen (hu)
- Ivar Smolin (et)
============
gedit 2.20.2
============
New Features and Fixes
======================
- Fix tools loading in External Tools plugin (Curtis Hovey)
- Fix crash when gtksourceview doesn't find any highlighting file (Paolo Borelli)
- Misc bugfixes
New and updated translations
============================
- Aleś Navicki (be@latin)
- Alexander Shopov (bg)
- Ankit Patel (gu)
- Claude Paroz (fr)
- Daniel Nylander (sv)
- Duarte Loreto (pt)
- Gintautas Miliauskas (lt)
- Ignacio Casal Quinteiro (gl)
- Ihar Hrachyshka (be)
- Ilkka Tuohela (fi)
- Jorge Gonzalez (es)
- Kenneth Nielsen (da)
- Milo Casagrande (it)
- Rhys Jones (cy)
- Tino Meinen (nl)
============
gedit 2.20.1
============
New Features and Fixes
======================
- Fix crash with invalid taglist file in taglist plugin (Paolo Borelli)
- Fix slash-escaping in the find dialog history (Paolo Borelli)
- Support .hidden file in the file browser plugin (Paolo Borelli)
- Bugfixes to the snippet plugin (Paolo Borelli, Jesse van den Kieboom)
New and updated translations
============================
- Baris Cicek (tr)
- Gintautas Miliauskas (lt)
- Takeshi AIHANA (ja)
- Vincent van Adrighem (nl)
============
gedit 2.20.0
============
New and updated translations
============================
- Alexander Shopov (bg)
- Artur Flinta (pl)
- Gabor Kelemen (hu)
- Gintautas Miliauskas (lt)
- Hendrik Richter (de)
- Jamil Ahmed (bn)
- Jorge Gonzalez (es)
- Kiran Chandra (te)
- Laurent Dhima (sq)
- Maxim Dziumanenko (uk)
- Nickolay V. Shmyrev (ru)
- Shankar Prasad (kn)
- Sohaib Afifi (ar)
- Yannig Marchegay (oc)
=============
gedit 2.19.92
=============
New Features and Fixes
======================
- Fix themeing of the message areas with new GTK+ (Ignacio Casal Quinteiro)
- Misc bugfixes
New and updated translations
============================
- Ani Peter (ml)
- Clytie Siddall (vi)
- Duarte Loreto (pt)
- Gabor Kelemen (hu)
- Goran Rakić (sr.po, sr@Latn)
- Inaki Larranaga Murgoitio (eu)
- Ivar Smolin (et)
- Josep Puigdemont i Casamajó (ca)
- Jovan Naumovski (mk)
- Kenneth Nielsen (da)
- Kjartan Maraas (nb)
- Milo Casagrande (it)
- Og Maciel (pt_BR)
- Rajesh Ranjan (hi)
- Takeshi AIHANA (ja)
- Tirumurthi Vasudevan (ta)
=============
gedit 2.19.91
=============
New Features and Fixes
======================
- Escape slashes when selecting text to search (Paolo Maggi)
- Support indent-width setting in modeline (Paolo Borelli)
- Adapt to the latest GtkSourceView changes (Paolo M., Paolo B.)
- Misc bugfixes
New and updated translations
============================
- Ani Peter (ml)
- Ankit Patel (gu)
- Funda Wang (zh_CN)
- Gabor Kelemen (hu)
- Ivar Smolin (et)
- Jorge Gonzalez (es)
- Josep Puigdemont i Casamajó (ca)
- Stéphane Raimbault (fr)
- Takeshi AIHANA (ja)
- Theppitak Karoonboonyanan (th)
- Young-Ho Cha (ko)
=============
gedit 2.19.90
=============
New Features and Fixes
======================
- User Interface to install and uninstall style schemes (Paolo Maggi)
- Make search match color customizable in the style scheme (Paolo M.)
- Tooltips on the document list and tag list (Alexandre Mazari)
- Misc bugfixes
New and updated translations
============================
- Ankit Patel (gu)
- Daniel Nylander (sv)
- Danishka Navin (si)
- Hendrik Richter (de)
- Ilkka Tuohela (fi)
- Inaki Larranaga Murgoitio (eu)
- Jorge Gonzalez (es)
- Kjartan Maraas (nb)
- Kostas Papadimas (el)
- Leonardo Ferreira Fontenelle (pt_BR)
- Takeshi AIHANA (ja)
- Theppitak Karoonboonyanan (th)
- Tirumurthi Vasudevan (ta)
- Žygimantas Beručka (lt)
============
gedit 2.19.3
============
New Features and Fixes
======================
- Remove color settings and syntax highlighting editor from the
preferences dialog and use a style scheme selector (Paolo Borelli,
Paolo Maggi)
- Many improvements to the snippets plugin, notably support for importing
and exporting snippets, support for regex snippets and support for
activating snippets on drag'n'drop (Jesse van den Kieboom)
- Split DocumentLoader and DocumentSaver in abstract class and
subclasses for easier maintainance (Steve Frécinaux)
- Add a gconf preference for smart-home-end (Paolo Borelli)
- Fix external tool saving bug (Alexandre Mazari)
- Adapt to latest GtkSourceView API changes
- Misc Bugfixes
New and updated translations
============================
- Ankit Patel (gu)
- Changwoo Ryu (ko)
- Daniel Nylander (sv)
- Danishka Navin (si)
- Funda Wang (zh_CN)
- Ilkka Tuohela (fi)
- Inaki Larranaga Murgoitio (eu)
- Ivar Smolin (et)
- Jorge Gonzalez (es)
- Luca Ferretti (it)
- Máté Őry (hu)
- Reinout van Schouwen (nl)
- Takeshi AIHANA (ja)
- Theppitak Karoonboonyanan (th)
- Tirumurthi Vasudevan (ta)
============
gedit 2.19.2
============
New Features and Fixes
======================
- Many improvements and fixes to the snippets plugin, in particular
support regex substitution inside snippet placeholders (Jesse van den Kieboom)
- Add a Document::save signal to notify the start of the saving
operation (Alex Cornejo, Steve Frécinaux)
- Adapt to latest GtkSourceView API changes (Paolo Borelli)
- Misc Bugfixes
- Remove Syntax Highlighting configuration from the preference dialog
since it was a pain to use and needs to be rethought to support
gtksourceview 2 style schemes.
New and updated translations
============================
- Changwoo Ryu (ko)
- Clytie Siddall (vi)
- Daniel Nylander (sv)
- Jorge Gonzalez (es)
- Jovan Naumovski (mk)
- Nguyễn Thái Ngọc Duy (vi)
============
gedit 2.19.1
============
New Features and Fixes
======================
- Port to gtksourceview 2: gedit now depends on gtksourceview 1.90.1
and on pygtksourceview 1.90.1 (if python plugins are enabled)
This brings to gedit a way more accurate and powerful highlighting
engine.
- Remove Syntax Highlighting configuration from the preference dialog
since it was a pain to use and needs to be rethought to support
gtksourceview 2 style schemes.
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.