text
stringlengths
2
100k
meta
dict
#include "csvserializer.h" #include <QStringList> #include <QList> #include <QDebug> #include <QTime> template <class C> bool isCsvSeparator(QList<C>& ahead, const C& theChar, const QStringList& separators) { for (const QString& sep : separators) if (isCsvSeparator(ahead, theChar, sep)) return true; return false; } template <class C> bool isCsvSeparator(QList<C>& ahead, const C& theChar, const QString& singleSeparator) { if (singleSeparator[0] != theChar) return false; typename QList<C>::const_iterator aheadIter = ahead.begin(); int singleSeparatorSize = singleSeparator.size(); int i = 1; while (aheadIter != ahead.end() && i < singleSeparatorSize) { if (singleSeparator[i++] != *aheadIter++) return false; } if (i < singleSeparatorSize) return false; for (int i = 1, total = singleSeparator.size(); i < total; ++i) ahead.removeFirst(); return true; } template <class C> bool isCsvColumnSeparator(QList<C>& ahead, const C& theChar, const CsvFormat& format) { if (!format.strictColumnSeparator) return format.columnSeparator.contains(theChar); // Strict checking (characters in defined order make a separator) if (format.multipleColumnSeparators) return isCsvSeparator(ahead, theChar, format.columnSeparators); return isCsvSeparator(ahead, theChar, format.columnSeparator); } template <class C> bool isCsvRowSeparator(QList<C>& ahead, const C& theChar, const CsvFormat& format) { if (!format.strictRowSeparator) return format.rowSeparator.contains(theChar); // Strict checking (characters in defined order make a separator) if (format.multipleRowSeparators) return isCsvSeparator(ahead, theChar, format.rowSeparators); return isCsvSeparator(ahead, theChar, format.rowSeparator); } template <class C> void readAhead(QTextStream& data, QList<C>& ahead, int desiredSize) { C singleValue; while (!data.atEnd() && ahead.size() < desiredSize) { data >> singleValue; ahead << singleValue; } } template <class T, class C> void typedDeserializeInternal(QTextStream& data, const CsvFormat& format, QList<T>* cells, QList<QList<T>>* rows) { bool quotes = false; bool sepAsLast = false; int separatorMaxAhead = qMax(format.maxColumnSeparatorLength, format.maxRowSeparatorLength) - 1; T field = ""; field.reserve(3); C theChar; QList<C> ahead; while (!data.atEnd() || !ahead.isEmpty()) { if (!ahead.isEmpty()) theChar = ahead.takeFirst(); else data >> theChar; sepAsLast = false; if (!quotes && theChar == '"' ) { quotes = true; } else if (quotes && theChar == '"' ) { if (!data.atEnd()) { readAhead(data, ahead, 1); if (ahead.isEmpty()) { field += theChar; } else if (ahead.first() == '"' ) { field += theChar; ahead.removeFirst(); } else { quotes = false; } } else { if (field.length() == 0) *cells << field; quotes = false; } } else if (!quotes) { readAhead(data, ahead, separatorMaxAhead); if (isCsvColumnSeparator(ahead, theChar, format)) { *cells << field; field.truncate(0); sepAsLast = true; } else if (isCsvRowSeparator(ahead, theChar, format)) { *cells << field; field.truncate(0); if (rows) { *rows << *cells; cells->clear(); } else { break; } } else { field += theChar; } } else { field += theChar; } } if (field.size() > 0 || sepAsLast) *cells << field; if (rows && cells->size() > 0) *rows << *cells; } template <class T, class C> QList<QList<T>> typedDeserialize(QTextStream& data, const CsvFormat& format) { QList<QList<T>> rows; QList<T> cells; typedDeserializeInternal<T, C>(data, format, &cells, &rows); return rows; } template <class T, class C> QList<T> typedDeserializeOneEntry(QTextStream& data, const CsvFormat& format) { QList<T> cells; typedDeserializeInternal<T, C>(data, format, &cells, nullptr); return cells; } QString CsvSerializer::serialize(const QList<QStringList>& data, const CsvFormat& format) { QStringList outputRows; for (const QStringList& dataRow : data) outputRows << serialize(dataRow, format); return outputRows.join(format.rowSeparator); } QString CsvSerializer::serialize(const QStringList& data, const CsvFormat& format) { QString value; bool hasQuote; QStringList outputCells; for (const QString& rowValue : data) { value = rowValue; hasQuote = value.contains("\""); if (hasQuote) value.replace("\"", "\"\""); if (hasQuote || value.contains(format.columnSeparator) || value.contains(format.rowSeparator)) value = "\""+value+"\""; outputCells << value; } return outputCells.join(format.columnSeparator); } QStringList CsvSerializer::deserializeOneEntry(QTextStream& data, const CsvFormat& format) { QList<QString> deserialized = typedDeserializeOneEntry<QString, QChar>(data, format); return QStringList(deserialized); } QList<QList<QByteArray>> CsvSerializer::deserialize(const QByteArray& data, const CsvFormat& format) { QTextStream stream(data, QIODevice::ReadWrite); return typedDeserialize<QByteArray,char>(stream, format); } QList<QStringList> CsvSerializer::deserialize(QTextStream& data, const CsvFormat& format) { QList<QList<QString>> deserialized = typedDeserialize<QString, QChar>(data, format); QList<QStringList> finalList; for (const QList<QString>& resPart : deserialized) finalList << QStringList(resPart); return finalList; } QList<QStringList> CsvSerializer::deserialize(const QString& data, const CsvFormat& format) { QString dataString = data; QTextStream stream(&dataString, QIODevice::ReadWrite); return deserialize(stream, format); }
{ "pile_set_name": "Github" }
{ "_from": "escape-html@^1.0.3", "_id": "[email protected]", "_inBundle": false, "_integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=", "_location": "/escape-html", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, "raw": "escape-html@^1.0.3", "name": "escape-html", "escapedName": "escape-html", "rawSpec": "^1.0.3", "saveSpec": null, "fetchSpec": "^1.0.3" }, "_requiredBy": [ "/utility" ], "_resolved": "https://registry.npm.taobao.org/escape-html/download/escape-html-1.0.3.tgz", "_shasum": "0258eae4d3d0c0974de1c169188ef0051d1d1988", "_spec": "escape-html@^1.0.3", "_where": "E:\\校园二手书新版\\cloudfunctions\\pay\\node_modules\\utility", "bugs": { "url": "https://github.com/component/escape-html/issues" }, "bundleDependencies": false, "deprecated": false, "description": "Escape string for use in HTML", "devDependencies": { "beautify-benchmark": "0.2.4", "benchmark": "1.0.0" }, "files": [ "LICENSE", "Readme.md", "index.js" ], "homepage": "https://github.com/component/escape-html#readme", "keywords": [ "escape", "html", "utility" ], "license": "MIT", "name": "escape-html", "repository": { "type": "git", "url": "git+https://github.com/component/escape-html.git" }, "scripts": { "bench": "node benchmark/index.js" }, "version": "1.0.3" }
{ "pile_set_name": "Github" }
/** @page open_default_stream Opening a Stream Using Defaults @ingroup tutorial The next step is to open a stream, which is similar to opening a file. You can specify whether you want audio input and/or output, how many channels, the data format, sample rate, etc. Opening a ''default'' stream means opening the default input and output devices, which saves you the trouble of getting a list of devices and choosing one from the list. (We'll see how to do that later.) @code #define SAMPLE_RATE (44100) static paTestData data; ..... PaStream *stream; PaError err; /* Open an audio I/O stream. */ err = Pa_OpenDefaultStream( &stream, 0, /* no input channels */ 2, /* stereo output */ paFloat32, /* 32 bit floating point output */ SAMPLE_RATE, 256, /* frames per buffer, i.e. the number of sample frames that PortAudio will request from the callback. Many apps may want to use paFramesPerBufferUnspecified, which tells PortAudio to pick the best, possibly changing, buffer size.*/ patestCallback, /* this is your callback function */ &data ); /*This is a pointer that will be passed to your callback*/ if( err != paNoError ) goto error; @endcode The data structure and callback are described in \ref writing_a_callback. The above example opens the stream for writing, which is sufficient for playback. It is also possible to open a stream for reading, to do recording, or both reading and writing, for simultaneous recording and playback or even real-time audio processing. If you plan to do playback and recording at the same time, open only one stream with valid input and output parameters. There are some caveats to note about simultaneous read/write: - Some platforms can only open a read/write stream using the same device. - Although multiple streams can be opened, it is difficult to synchronize them. - Some platforms don't support opening multiple streams on the same device. - Using multiple streams may not be as well tested as other features. - The PortAudio library calls must be made from the same thread or synchronized by the user. Previous: \ref initializing_portaudio | Next: \ref start_stop_abort */
{ "pile_set_name": "Github" }
#define PCMCIA 1 #include "fdomain.c"
{ "pile_set_name": "Github" }
# Image: introlab3it/rtabmap:android-deps FROM ubuntu:18.04 # Install build dependencies RUN apt-get update && apt-get install -y --no-install-recommends apt-utils RUN apt-get update && apt-get install -y \ git unzip wget ant cmake \ g++ lib32stdc++6 lib32z1 \ software-properties-common \ freeglut3-dev \ openjdk-8-jdk openjdk-8-jre ENV ANDROID_NDK_VERSION=r21 ENV ANDROID_HOME=/opt/android-sdk ENV PATH=$PATH:/opt/android-sdk/tools:/opt/android-sdk/platform-tools:/opt/android-ndk-$ANDROID_NDK_VERSION ENV ANDROID_NDK=/opt/android-ndk-$ANDROID_NDK_VERSION ENV JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64 WORKDIR /root/ # Setup android sdk RUN wget -nv https://dl.google.com/android/repository/tools_r25.2.3-linux.zip && \ unzip -qq tools_r25.2.3-linux.zip && \ rm tools_r25.2.3-linux.zip && \ mkdir $ANDROID_HOME && \ mv tools $ANDROID_HOME/. RUN echo y | android update sdk --no-ui --all --filter platform-tools,android-23,android-24,android-26,build-tools-29.0.3 # Setup android ndk RUN wget -nv https://dl.google.com/android/repository/android-ndk-$ANDROID_NDK_VERSION-linux-x86_64.zip && \ unzip -qq android-ndk-$ANDROID_NDK_VERSION-linux-x86_64.zip && \ rm android-ndk-$ANDROID_NDK_VERSION-linux-x86_64.zip && \ mv android-ndk-$ANDROID_NDK_VERSION /opt/. ADD deps.bash /root/deps.bash RUN chmod +x deps.bash RUN /bin/bash -c "./deps.bash /opt/android"
{ "pile_set_name": "Github" }
(function() { Sheet.Cell.prototype.addDependency = function(cell) { if (cell === undefined || cell === null) return; if (cell.type !== Sheet.Cell) { throw new Error('Wrong Type'); } if (this.dependencies.indexOf(cell) < 0 && this !== cell) { cell.trace = cell.trace || []; cell.trace.push(this); this.dependencies.push(cell); if (this.loader !== null) { this.loader.addDependency(this, cell); } } }; Sheet.Cell.prototype.traceRoute = function(callback, rootSheetIndex) { if (rootSheetIndex === undefined) { rootSheetIndex = this.sheetIndex; this.setNeedsUpdated(true); } this.updateValue(function() { this.trace = this.trace || []; var route = { name: this.id, children: [] }, trace = this.trace, max = trace.length, progress = 0, i = 0; if (!route.name) { route.name = (rootSheetIndex !== this.sheetIndex ? '"' + this.jS.getSpreadsheetTitleByIndex(this.sheetIndex) + '"!' : ''); route.name += jQuery.sheet.engine.columnLabelString(this.columnIndex) + this.rowIndex; route.name += ' : ' + this.value; if (this.formula) { route.name += ' : "=' + this.formula + '"'; } } console.log(route.name); for(;i < max;i++) { (function(i, tracedCell) { //to avoid "too much recursion" setTimeout(function() { tracedCell.traceRoute(function(childRoute) { progress++; route.children[i] = childRoute; console.log('Progress: ' + progress + ', index: ' + i + ', max: ' + max); }, rootSheetIndex); }, 0); })(i, trace[i]); } callback(route); }); }; })();
{ "pile_set_name": "Github" }
import { Go } from './wasm-exec-go' export async function wasmLoader(wasmUrl) { const go = new Go() // Defined in wasm_exec.js var wasm if ('instantiateStreaming' in WebAssembly) { WebAssembly.instantiateStreaming(fetch(wasmUrl), go.importObject).then(function (obj) { wasm = obj.instance go.run(wasm) }) } else { fetch(wasmUrl) .then((resp) => resp.arrayBuffer()) .then((bytes) => WebAssembly.instantiate(bytes, go.importObject).then(function (obj) { wasm = obj.instance go.run(wasm) }) ) } }
{ "pile_set_name": "Github" }
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../../../shared/file/size', __FILE__) describe "File.size?" do it_behaves_like :file_size, :size?, File end describe "File.size?" do it_behaves_like :file_size_to_io, :size?, File end describe "File.size?" do it_behaves_like :file_size_nil_when_missing, :size?, File end describe "File.size?" do it_behaves_like :file_size_nil_when_empty, :size?, File end describe "File.size?" do it_behaves_like :file_size_with_file_argument, :size?, File end describe "File.size" do it_behaves_like :file_size, :size, File end describe "File.size" do it_behaves_like :file_size_to_io, :size, File end describe "File.size" do it_behaves_like :file_size_raise_when_missing, :size, File end describe "File.size" do it_behaves_like :file_size_0_when_empty, :size, File end describe "File.size" do it_behaves_like :file_size_with_file_argument, :size, File end ruby_version_is "1.9" do describe "File#size" do before :each do @name = tmp('i_exist') touch(@name) { |f| f.write 'rubinius' } @file = File.new @name @file_org = @file end after :each do @file_org.close unless @file_org.closed? rm_r @name end it "is an instance method" do @file.respond_to?(:size).should be_true end it "returns the file's size as a Fixnum" do @file.size.should be_an_instance_of(Fixnum) end it "returns the file's size in bytes" do @file.size.should == 8 end platform_is_not :windows do # impossible to remove opened file on Windows it "returns the cached size of the file if subsequently deleted" do rm_r @file @file.size.should == 8 end end it "returns the file's current size even if modified" do File.open(@file,'a') {|f| f.write '!'} @file.size.should == 9 end #it "raises an IOError on a closed file" do # @file.close # lambda { @file.size }.should raise_error(IOError) #end platform_is_not :windows do it "follows symlinks if necessary" do ln_file = tmp('i_exist_ln') rm_r ln_file begin File.symlink(@file.path, ln_file).should == 0 file = File.new(ln_file) file.size.should == 8 ensure file.close if file && !file.closed? File.unlink(ln_file) if File.exists?(ln_file) end end end end describe "File#size for an empty file" do before :each do @name = tmp('empty') touch(@name) @file = File.new @name end after :each do @file.close unless @file.closed? rm_r @name end it "returns 0" do @file.size.should == 0 end end end
{ "pile_set_name": "Github" }
<?php /** * Template Lite generate_debug_output template internal module * * Type: template * Name: generate_debug_output */ function generate_compiler_debug_output(&$object) { $debug_output = "\$assigned_vars = \$this->_vars;\n"; $debug_output .= "ksort(\$assigned_vars);\n"; $debug_output .= "if (@is_array(\$this->_config[0])) {\n"; $debug_output .= " \$config_vars = \$this->_config[0];\n"; $debug_output .= " ksort(\$config_vars);\n"; $debug_output .= " \$this->assign('_debug_config_keys', array_keys(\$config_vars));\n"; $debug_output .= " \$this->assign('_debug_config_vals', array_values(\$config_vars));\n"; $debug_output .= "} \n"; $debug_output .= "\$included_templates = \$this->_templatelite_debug_info;\n"; $debug_output .= "\$this->assign('_debug_keys', array_keys(\$assigned_vars));\n"; $debug_output .= "\$this->assign('_debug_vals', array_values(\$assigned_vars));\n"; $debug_output .= "\$this->assign('_debug_tpls', \$included_templates);\n"; $debug_output .= "\$this->_templatelite_debug_loop = true;\n"; $debug_output .= "\$this->_templatelite_debug_dir = \$this->template_dir;\n"; $debug_output .= "\$this->template_dir = TEMPLATE_LITE_DIR . 'internal/';\n"; $debug_output .= "echo \$this->_fetch_compile('debug.tpl');\n"; $debug_output .= "\$this->template_dir = \$this->_templatelite_debug_dir;\n"; $debug_output .= "\$this->_templatelite_debug_loop = false; \n"; return $debug_output; } ?>
{ "pile_set_name": "Github" }
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Framework\Stdlib\Cookie; /** * CookieReaderInterface provides the ability to read cookies sent in a request. * @api */ interface CookieReaderInterface { /** * Retrieve a value from a cookie. * * @param string $name * @param string|null $default The default value to return if no value could be found for the given $name. * @return string|null */ public function getCookie($name, $default = null); }
{ "pile_set_name": "Github" }
<proxy xmlns="http://ws.apache.org/ns/synapse" name="iterateWithNullNamespaceForExpressionTestProxy" transports="http" startOnLoad="true" trace="disable"> <target> <inSequence> <iterate id="iterator" expression="//m1:getQuote/m1:request" preservePayload="true" attachPath="//m0:getQuote" xmlns:m0="http://services.samples"> <target> <sequence> <send> <endpoint> <address uri="http://localhost:9000/services/SimpleStockQuoteService"/> </endpoint> </send> </sequence> </target> </iterate> </inSequence> <outSequence> <sequence key="aggregateMessagesForIterateTests"/> </outSequence> </target> </proxy>
{ "pile_set_name": "Github" }
/* * Knowage, Open Source Business Intelligence suite * Copyright (C) 2016 Engineering Ingegneria Informatica S.p.A. * * Knowage 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. * * Knowage 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 <http://www.gnu.org/licenses/>. */ package it.eng.spagobi.sdk.proxy; import java.rmi.Remote; import org.apache.axis.client.Stub; import org.apache.ws.security.handler.WSHandlerConstants; import it.eng.spagobi.sdk.callbacks.ClientCredentialsHolder; import it.eng.spagobi.sdk.maps.stub.MapsSDKService; import it.eng.spagobi.sdk.maps.stub.MapsSDKServiceServiceLocator; public class MapsSDKServiceProxy extends AbstractSDKServiceProxy implements MapsSDKService { private String _endpoint = null; private MapsSDKService mapsSDKService = null; private ClientCredentialsHolder cch = null; public MapsSDKServiceProxy() { _initMapsSDKServiceProxy(); } public MapsSDKServiceProxy(String user, String pwd) { cch = new ClientCredentialsHolder(user, pwd); _initMapsSDKServiceProxy(); } public MapsSDKServiceProxy(String endpoint) { _endpoint = endpoint; _initMapsSDKServiceProxy(); } private void _initMapsSDKServiceProxy() { try { it.eng.spagobi.sdk.maps.stub.MapsSDKServiceServiceLocator locator = new it.eng.spagobi.sdk.maps.stub.MapsSDKServiceServiceLocator(); Remote remote = locator.getPort(it.eng.spagobi.sdk.maps.stub.MapsSDKService.class); Stub axisPort = (Stub) remote; axisPort._setProperty(WSHandlerConstants.USER, cch.getUsername()); axisPort._setProperty(WSHandlerConstants.PW_CALLBACK_REF, cch); //axisPort.setTimeout(30000); //used in SpagoBIStudio mapsSDKService = (it.eng.spagobi.sdk.maps.stub.MapsSDKService) axisPort; //mapsSDKService = (new MapsSDKServiceServiceLocator()).getMapsSDKService(); if (mapsSDKService != null) { if (_endpoint != null) ((javax.xml.rpc.Stub)mapsSDKService)._setProperty("javax.xml.rpc.service.endpoint.address", _endpoint); else _endpoint = (String)((javax.xml.rpc.Stub)mapsSDKService)._getProperty("javax.xml.rpc.service.endpoint.address"); } } catch (javax.xml.rpc.ServiceException serviceException) {} } public String getEndpoint() { return _endpoint; } public void setEndpoint(String endpoint) { _endpoint = endpoint; if (mapsSDKService != null) ((javax.xml.rpc.Stub)mapsSDKService)._setProperty("javax.xml.rpc.service.endpoint.address", _endpoint); } public MapsSDKService getMapsSDKService() { if (mapsSDKService == null) _initMapsSDKServiceProxy(); return mapsSDKService; } public it.eng.spagobi.sdk.maps.bo.SDKMap[] getMaps() throws java.rmi.RemoteException, it.eng.spagobi.sdk.exceptions.NotAllowedOperationException{ if (mapsSDKService == null) _initMapsSDKServiceProxy(); return mapsSDKService.getMaps(); } public it.eng.spagobi.sdk.maps.bo.SDKMap getMapById(java.lang.Integer in0) throws java.rmi.RemoteException, it.eng.spagobi.sdk.exceptions.NotAllowedOperationException{ if (mapsSDKService == null) _initMapsSDKServiceProxy(); return mapsSDKService.getMapById(in0); } public it.eng.spagobi.sdk.maps.bo.SDKFeature[] getMapFeatures(java.lang.Integer in0) throws java.rmi.RemoteException, it.eng.spagobi.sdk.exceptions.NotAllowedOperationException{ if (mapsSDKService == null) _initMapsSDKServiceProxy(); return mapsSDKService.getMapFeatures(in0); } public it.eng.spagobi.sdk.maps.bo.SDKFeature[] getFeatures() throws java.rmi.RemoteException, it.eng.spagobi.sdk.exceptions.NotAllowedOperationException{ if (mapsSDKService == null) _initMapsSDKServiceProxy(); return mapsSDKService.getFeatures(); } public it.eng.spagobi.sdk.maps.bo.SDKFeature getFeatureById(java.lang.Integer in0) throws java.rmi.RemoteException, it.eng.spagobi.sdk.exceptions.NotAllowedOperationException{ if (mapsSDKService == null) _initMapsSDKServiceProxy(); return mapsSDKService.getFeatureById(in0); } }
{ "pile_set_name": "Github" }
/* Copyright (c) 2017 The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/kref.h> #include "msm_gpu.h" void msm_submitqueue_destroy(struct kref *kref) { struct msm_gpu_submitqueue *queue = container_of(kref, struct msm_gpu_submitqueue, ref); kfree(queue); } struct msm_gpu_submitqueue *msm_submitqueue_get(struct msm_file_private *ctx, u32 id) { struct msm_gpu_submitqueue *entry; if (!ctx) return NULL; read_lock(&ctx->queuelock); list_for_each_entry(entry, &ctx->submitqueues, node) { if (entry->id == id) { kref_get(&entry->ref); read_unlock(&ctx->queuelock); return entry; } } read_unlock(&ctx->queuelock); return NULL; } void msm_submitqueue_close(struct msm_file_private *ctx) { struct msm_gpu_submitqueue *entry, *tmp; if (!ctx) return; /* * No lock needed in close and there won't * be any more user ioctls coming our way */ list_for_each_entry_safe(entry, tmp, &ctx->submitqueues, node) msm_submitqueue_put(entry); } int msm_submitqueue_create(struct drm_device *drm, struct msm_file_private *ctx, u32 prio, u32 flags, u32 *id) { struct msm_drm_private *priv = drm->dev_private; struct msm_gpu_submitqueue *queue; if (!ctx) return -ENODEV; queue = kzalloc(sizeof(*queue), GFP_KERNEL); if (!queue) return -ENOMEM; kref_init(&queue->ref); queue->flags = flags; if (priv->gpu) { if (prio >= priv->gpu->nr_rings) return -EINVAL; queue->prio = prio; } write_lock(&ctx->queuelock); queue->id = ctx->queueid++; if (id) *id = queue->id; list_add_tail(&queue->node, &ctx->submitqueues); write_unlock(&ctx->queuelock); return 0; } int msm_submitqueue_init(struct drm_device *drm, struct msm_file_private *ctx) { struct msm_drm_private *priv = drm->dev_private; int default_prio; if (!ctx) return 0; /* * Select priority 2 as the "default priority" unless nr_rings is less * than 2 and then pick the lowest pirority */ default_prio = priv->gpu ? clamp_t(uint32_t, 2, 0, priv->gpu->nr_rings - 1) : 0; INIT_LIST_HEAD(&ctx->submitqueues); rwlock_init(&ctx->queuelock); return msm_submitqueue_create(drm, ctx, default_prio, 0, NULL); } int msm_submitqueue_remove(struct msm_file_private *ctx, u32 id) { struct msm_gpu_submitqueue *entry; if (!ctx) return 0; /* * id 0 is the "default" queue and can't be destroyed * by the user */ if (!id) return -ENOENT; write_lock(&ctx->queuelock); list_for_each_entry(entry, &ctx->submitqueues, node) { if (entry->id == id) { list_del(&entry->node); write_unlock(&ctx->queuelock); msm_submitqueue_put(entry); return 0; } } write_unlock(&ctx->queuelock); return -ENOENT; }
{ "pile_set_name": "Github" }
{ "accessors" : [ { "bufferView" : 0, "componentType" : 5123, "count" : 612, "max" : [ 335 ], "min" : [ 0 ], "type" : "SCALAR" }, { "bufferView" : 1, "componentType" : 5126, "count" : 336, "max" : [ 1.132531762123108, 0.9043031930923462, 0.2850000262260437 ], "min" : [ -1.132531762123108, -0.9043031930923462, -0.2850000262260437 ], "type" : "VEC3" }, { "bufferView" : 2, "componentType" : 5126, "count" : 336, "max" : [ 1.0, 1.0, 1.0 ], "min" : [ -1.0, -1.0, -1.0 ], "type" : "VEC3" } ], "asset" : { "generator" : "Khronos Blender glTF 2.0 exporter", "version" : "2.0" }, "bufferViews" : [ { "buffer" : 0, "byteLength" : 1224, "byteOffset" : 0, "target" : 34963 }, { "buffer" : 0, "byteLength" : 4032, "byteOffset" : 1224, "target" : 34962 }, { "buffer" : 0, "byteLength" : 4032, "byteOffset" : 5256, "target" : 34962 } ], "buffers" : [ { "byteLength" : 9288, "uri" : "honeycomb.bin" } ], "meshes" : [ { "name" : "honeycomb", "primitives" : [ { "attributes" : { "NORMAL" : 2, "POSITION" : 1 }, "indices" : 0 } ] } ], "nodes" : [ { "name" : "camera", "rotation" : [ 0.466261088848114, 0.3226812779903412, -0.1875857561826706, 0.8020530343055725 ], "translation" : [ 7.333371162414551, 6.029646873474121, 7.63869571685791 ] }, { "name" : "camera_target" }, { "mesh" : 0, "name" : "honeycomb", "scale" : [ 1.0, 0.9995182752609253, 1.0 ] }, { "name" : "light_target" }, { "name" : "sun", "rotation" : [ 0.18757343292236328, 0.749933123588562, -0.23946259915828705, 0.5874302387237549 ], "scale" : [ 1.0, 1.0, 0.9999998211860657 ], "translation" : [ 4.076245307922363, 5.903861999511719, -1.0054539442062378 ] } ], "scene" : 0, "scenes" : [ { "name" : "Scene", "nodes" : [ 2, 3, 4, 1, 0 ] } ] }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 2afedbe6e25844649ae7ac632544ef63 NativeFormatImporter: externalObjects: {} mainObjectFileID: 2100000 userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
/* * @Author: ecitlm * @Date: 2017-11-30 21:16:16 * @Last Modified by: ecitlm * @Last Modified time: 2018-04-14 23:16:11 */ const MYSQL = require('mysql') // 调用MySQL模块 // 创建一个connection const connection = MYSQL.createConnection({ host: '127.0.0.1', // 主机 user: 'root', // MySQL认证用户名 password: '', port: '3306', database: 'blog_cms', charset: 'UTF8_GENERAL_CI' }) module.exports = connection
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; namespace Microsoft.VisualStudio.LanguageServices.Implementation.RQName.Nodes { internal class RQProperty : RQPropertyBase { public RQProperty( RQUnconstructedType containingType, RQMethodPropertyOrEventName memberName, int typeParameterCount, IList<RQParameter> parameters) : base(containingType, memberName, typeParameterCount, parameters) { } } }
{ "pile_set_name": "Github" }
package main import ( "fmt" "runtime" "time" ) func main() { go func() { for { time.Sleep(time.Microsecond) go func() { n := 0 for i := 0; i < 100000000; i++ { n += i } }() } }() i := 0 t := time.Now() for { time.Sleep(100 * time.Millisecond) i++ n := time.Now() fmt.Println(i, runtime.NumGoroutine(), n, (n.UnixNano()-t.UnixNano())/1000000) t = n if i == 100 { break } } }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <style> body { margin: 0; width:100%%; height:100%%; background-color:#000; } html { width:100%%; height:100%%; background-color:#000; } .container iframe, .container object, .container embed { position: absolute;top: 0; left: 0; width: 100%% !important; height: 100%% !important; } </style> </head> <body> <div class="container"> <iframe id="player" src="https://player.vimeo.com/video/%@?api=1&badge=0&byline=0&portrait=0&title=0&player_id=player" width="100%" height="100%" frameborder="0"></iframe> </div> <script> var Froogaloop=function(){function e(a){return new e.fn.init(a)}function g(a,c,b){if(!b.contentWindow.postMessage)return!1;a=JSON.stringify({method:a,value:c});b.contentWindow.postMessage(a,h)}function l(a){var c,b;try{c=JSON.parse(a.data),b=c.event||c.method}catch(e){}"ready"!=b||k||(k=!0);if(!/^https?:\/\/player.vimeo.com/.test(a.origin))return!1;"*"===h&&(h=a.origin);a=c.value;var m=c.data,f=""===f?null:c.player_id;c=f?d[f][b]:d[b];b=[];if(!c)return!1;void 0!==a&&b.push(a);m&&b.push(m);f&&b.push(f); return 0<b.length?c.apply(null,b):c.call()}function n(a,c,b){b?(d[b]||(d[b]={}),d[b][a]=c):d[a]=c}var d={},k=!1,h="*";e.fn=e.prototype={element:null,init:function(a){"string"===typeof a&&(a=document.getElementById(a));this.element=a;return this},api:function(a,c){if(!this.element||!a)return!1;var b=this.element,d=""!==b.id?b.id:null,e=c&&c.constructor&&c.call&&c.apply?null:c,f=c&&c.constructor&&c.call&&c.apply?c:null;f&&n(a,f,d);g(a,e,b);return this},addEvent:function(a,c){if(!this.element)return!1; var b=this.element,d=""!==b.id?b.id:null;n(a,c,d);"ready"!=a?g("addEventListener",a,b):"ready"==a&&k&&c.call(null,d);return this},removeEvent:function(a){if(!this.element)return!1;var c=this.element,b=""!==c.id?c.id:null;a:{if(b&&d[b]){if(!d[b][a]){b=!1;break a}d[b][a]=null}else{if(!d[a]){b=!1;break a}d[a]=null}b=!0}"ready"!=a&&b&&g("removeEventListener",a,c)}};e.fn.init.prototype=e.fn;window.addEventListener?window.addEventListener("message",l,!1):window.attachEvent("onmessage",l);return window.Froogaloop= window.$f=e}(); var iframe; var player; function invoke(command) { iframe.contentWindow.postMessage(JSON.stringify({ "event": "inject", "command": command }), "*"); } var played = false; function play() { if (played) { player.api("play"); } else { invoke("autoplay"); played = true; } } function pause() { player.api("pause"); } function seek(timestamp) { player.api("seekTo", timestamp); } (function() { var playbackState = 0; var duration = 0.0; var position = 0.0; var downloadProgress = 0.0; iframe = document.querySelectorAll("iframe")[0]; player = $f(iframe); function updateState() { window.location.href = "embed://onState?playback=" + playbackState + "&position=" + position + "&duration=" + duration + "&download=" + downloadProgress; } player.addEvent("ready", function(player_id) { window.location.href = "embed://onReady?data=" + player_id; player.addEvent("play", onPlay); player.addEvent("pause", onPause); player.addEvent("finish", onFinish); player.addEvent("playProgress", onPlayProgress); player.addEvent("loadProgress", onLoadProgress); window.setInterval(updateState, 500); invoke("initialize"); if (%@) { invoke("autoplay"); } }); function onPlay(data) { playbackState = 1; updateState(); } function onPause(data) { playbackState = 0; updateState(); } function onFinish(data) { playbackState = 2; updateState(); } function onPlayProgress(data) { position = data.seconds; duration = data.duration; } function onLoadProgress(data) { downloadProgress = data.percent; } })(); </script> </body> </html>
{ "pile_set_name": "Github" }
# Test Folder ## Sub Folder 1 ### F1 Project 1 Note line 1. Note line 2. - parent task F1 P1 1 - sub task with a colon: - task F1 P1 2 ### F1 Project 2 - task F1 P2 1 Note line 1. Note line 2. - task F1 P2 2 ## Sub Folder 2 ### F2 Project 1 - task F2 P1 1 - task F2 P1 2 - I'm done! done:**2013-04-21** ### F2 Project 2 - task F2 P2 1 - task F2 P2 2 - task with no context
{ "pile_set_name": "Github" }
///////////////////////////////////////////////////////////////////////// // $Id$ ///////////////////////////////////////////////////////////////////////// // // Copyright (c) 2003-2014 Stanislav Shwartsman // Written by Stanislav Shwartsman [sshwarts at sourceforge net] // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA B 02110-1301 USA // ///////////////////////////////////////////////////////////////////////// #define NEED_CPU_REG_SHORTCUTS 1 #include "bochs.h" #include "cpu.h" #define LOG_THIS BX_CPU_THIS_PTR #if BX_CPU_LEVEL >= 6 #include "fpu/softfloat-compare.h" #include "simd_pfp.h" #include "simd_int.h" void BX_CPU_C::check_exceptionsSSE(int exceptions_flags) { exceptions_flags &= MXCSR_EXCEPTIONS; int unmasked = ~(MXCSR.get_exceptions_masks()) & exceptions_flags; // unmasked pre-computational exception detected (#IA, #DE or #DZ) if (unmasked & 0x7) exceptions_flags &= 0x7; MXCSR.set_exceptions(exceptions_flags); if (unmasked) { if(BX_CPU_THIS_PTR cr4.get_OSXMMEXCPT()) exception(BX_XM_EXCEPTION, 0); else exception(BX_UD_EXCEPTION, 0); } } void mxcsr_to_softfloat_status_word(float_status_t &status, bx_mxcsr_t mxcsr) { status.float_exception_flags = 0; // clear exceptions before execution status.float_nan_handling_mode = float_first_operand_nan; status.float_rounding_mode = mxcsr.get_rounding_mode(); // if underflow is masked and FUZ is 1, set it to 1, else to 0 status.flush_underflow_to_zero = (mxcsr.get_flush_masked_underflow() && mxcsr.get_UM()) ? 1 : 0; status.float_exception_masks = mxcsr.get_exceptions_masks(); status.float_suppress_exception = 0; status.denormals_are_zeros = mxcsr.get_DAZ(); } /* Comparison predicate for CMPSS/CMPPS instructions */ static float32_compare_method compare32[8] = { float32_eq_ordered_quiet, float32_lt_ordered_signalling, float32_le_ordered_signalling, float32_unordered_quiet, float32_neq_unordered_quiet, float32_nlt_unordered_signalling, float32_nle_unordered_signalling, float32_ordered_quiet }; /* Comparison predicate for CMPSD/CMPPD instructions */ static float64_compare_method compare64[8] = { float64_eq_ordered_quiet, float64_lt_ordered_signalling, float64_le_ordered_signalling, float64_unordered_quiet, float64_neq_unordered_quiet, float64_nlt_unordered_signalling, float64_nle_unordered_signalling, float64_ordered_quiet }; #endif // BX_CPU_LEVEL >= 6 /* * Opcode: 0F 2A * Convert two 32bit signed integers from MMX/MEM to two single precision FP * When a conversion is inexact, the value returned is rounded according * to rounding control bits in MXCSR register. * Possible floating point exceptions: #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTPI2PS_VpsQqR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 /* check floating point status word for a pending FPU exceptions */ FPU_check_pending_exceptions(); BxPackedMmxRegister op = BX_READ_MMX_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); MMXUD0(op) = int32_to_float32(MMXSD0(op), status); MMXUD1(op) = int32_to_float32(MMXSD1(op), status); prepareFPU2MMX(); /* cause FPU2MMX state transition */ check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), MMXUQ(op)); #endif BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTPI2PS_VpsQqM(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedMmxRegister op; // do not cause transition to MMX state because no MMX register touched bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); MMXUQ(op) = read_virtual_qword(i->seg(), eaddr); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); MMXUD0(op) = int32_to_float32(MMXSD0(op), status); MMXUD1(op) = int32_to_float32(MMXSD1(op), status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), MMXUQ(op)); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F 2A * Convert two 32bit signed integers from MMX/MEM to two double precision FP * Possible floating point exceptions: - */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTPI2PD_VpdQqR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister result; /* check floating point status word for a pending FPU exceptions */ FPU_check_pending_exceptions(); prepareFPU2MMX(); /* cause FPU2MMX state transition */ BxPackedMmxRegister op = BX_READ_MMX_REG(i->src()); result.xmm64u(0) = int32_to_float64(MMXSD0(op)); result.xmm64u(1) = int32_to_float64(MMXSD1(op)); BX_WRITE_XMM_REG(i->dst(), result); #endif BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTPI2PD_VpdQqM(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedMmxRegister op; BxPackedXmmRegister result; // do not cause transition to MMX state because no MMX register touched bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); MMXUQ(op) = read_virtual_qword(i->seg(), eaddr); result.xmm64u(0) = int32_to_float64(MMXSD0(op)); result.xmm64u(1) = int32_to_float64(MMXSD1(op)); BX_WRITE_XMM_REG(i->dst(), result); #endif BX_NEXT_INSTR(i); } /* * Opcode: F2 0F 2A * Convert one 32bit signed integer to one double precision FP * Possible floating point exceptions: - */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTSI2SD_VsdEdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float64 result = int32_to_float64(BX_READ_32BIT_REG(i->src())); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), result); #endif BX_NEXT_INSTR(i); } #if BX_SUPPORT_X86_64 BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTSI2SD_VsdEqR(bxInstruction_c *i) { float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); float64 result = int64_to_float64(BX_READ_64BIT_REG(i->src()), status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), result); BX_NEXT_INSTR(i); } #endif /* * Opcode: F3 0F 2A * Convert one 32bit signed integer to one single precision FP * When a conversion is inexact, the value returned is rounded according * to rounding control bits in MXCSR register. * Possible floating point exceptions: #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTSI2SS_VssEdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); float32 result = int32_to_float32(BX_READ_32BIT_REG(i->src()), status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_DWORD(i->dst(), result); #endif BX_NEXT_INSTR(i); } #if BX_SUPPORT_X86_64 BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTSI2SS_VssEqR(bxInstruction_c *i) { float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); float32 result = int64_to_float32(BX_READ_64BIT_REG(i->src()), status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_DWORD(i->dst(), result); BX_NEXT_INSTR(i); } #endif /* * Opcode: 0F 2C * Convert two single precision FP numbers to two signed doubleword integers * in MMX using truncation if the conversion is inexact * Possible floating point exceptions: #I, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTTPS2PI_PqWps(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 /* check floating point status word for a pending FPU exceptions */ FPU_check_pending_exceptions(); BxPackedMmxRegister op; /* op is a register or memory reference */ if (i->modC0()) { MMXUQ(op) = BX_READ_XMM_REG_LO_QWORD(i->src()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ MMXUQ(op) = read_virtual_qword(i->seg(), eaddr); } float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); MMXSD0(op) = float32_to_int32_round_to_zero(MMXUD0(op), status); MMXSD1(op) = float32_to_int32_round_to_zero(MMXUD1(op), status); prepareFPU2MMX(); /* cause FPU2MMX state transition */ check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_MMX_REG(i->dst(), op); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F 2C * Convert two double precision FP numbers to two signed doubleword integers * in MMX using truncation if the conversion is inexact * Possible floating point exceptions: #I, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTTPD2PI_PqWpd(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 /* check floating point status word for a pending FPU exceptions */ FPU_check_pending_exceptions(); BxPackedXmmRegister op; BxPackedMmxRegister result; /* op is a register or memory reference */ if (i->modC0()) { op = BX_READ_XMM_REG(i->src()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); if (BX_CPU_THIS_PTR mxcsr.get_MM()) read_virtual_xmmword(i->seg(), eaddr, &op); else read_virtual_xmmword_aligned(i->seg(), eaddr, &op); } float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); MMXSD0(result) = float64_to_int32_round_to_zero(op.xmm64u(0), status); MMXSD1(result) = float64_to_int32_round_to_zero(op.xmm64u(1), status); prepareFPU2MMX(); /* cause FPU2MMX state transition */ check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_MMX_REG(i->dst(), result); #endif BX_NEXT_INSTR(i); } /* * Opcode: F2 0F 2C * Convert one double precision FP number to doubleword integer using * truncation if the conversion is inexact * Possible floating point exceptions: #I, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTTSD2SI_GdWsdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float64 op = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); softfloat_status_word_rc_override(status, i); Bit32s result = float64_to_int32_round_to_zero(op, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_32BIT_REGZ(i->dst(), (Bit32u) result); #endif BX_NEXT_INSTR(i); } #if BX_SUPPORT_X86_64 BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTTSD2SI_GqWsdR(bxInstruction_c *i) { float64 op = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); softfloat_status_word_rc_override(status, i); Bit64s result = float64_to_int64_round_to_zero(op, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_64BIT_REG(i->dst(), (Bit64u) result); BX_NEXT_INSTR(i); } #endif /* * Opcode: F3 0F 2C * Convert one single precision FP number to doubleword integer using * truncation if the conversion is inexact * Possible floating point exceptions: #I, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTTSS2SI_GdWssR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float32 op = BX_READ_XMM_REG_LO_DWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); softfloat_status_word_rc_override(status, i); Bit32s result = float32_to_int32_round_to_zero(op, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_32BIT_REGZ(i->dst(), (Bit32u) result); #endif BX_NEXT_INSTR(i); } #if BX_SUPPORT_X86_64 BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTTSS2SI_GqWssR(bxInstruction_c *i) { float32 op = BX_READ_XMM_REG_LO_DWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); softfloat_status_word_rc_override(status, i); Bit64s result = float32_to_int64_round_to_zero(op, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_64BIT_REG(i->dst(), (Bit64u) result); BX_NEXT_INSTR(i); } #endif /* * Opcode: 0F 2D * Convert two single precision FP numbers to two signed doubleword integers * in MMX register. When a conversion is inexact, the value returned is * rounded according to rounding control bits in MXCSR register. * Possible floating point exceptions: #I, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTPS2PI_PqWps(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 /* check floating point status word for a pending FPU exceptions */ FPU_check_pending_exceptions(); BxPackedMmxRegister op; /* op is a register or memory reference */ if (i->modC0()) { MMXUQ(op) = BX_READ_XMM_REG_LO_QWORD(i->src()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); /* pointer, segment address pair */ MMXUQ(op) = read_virtual_qword(i->seg(), eaddr); } float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); MMXSD0(op) = float32_to_int32(MMXUD0(op), status); MMXSD1(op) = float32_to_int32(MMXUD1(op), status); prepareFPU2MMX(); /* cause FPU2MMX state transition */ check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_MMX_REG(i->dst(), op); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F 2D * Convert two double precision FP numbers to two signed doubleword integers * in MMX register. When a conversion is inexact, the value returned is * rounded according to rounding control bits in MXCSR register. * Possible floating point exceptions: #I, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTPD2PI_PqWpd(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 /* check floating point status word for a pending FPU exceptions */ FPU_check_pending_exceptions(); BxPackedXmmRegister op; BxPackedMmxRegister result; /* op is a register or memory reference */ if (i->modC0()) { op = BX_READ_XMM_REG(i->src()); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); #if BX_SUPPORT_MISALIGNED_SSE if (BX_CPU_THIS_PTR mxcsr.get_MM()) read_virtual_xmmword(i->seg(), eaddr, &op); else #endif read_virtual_xmmword_aligned(i->seg(), eaddr, &op); } float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); MMXSD0(result) = float64_to_int32(op.xmm64u(0), status); MMXSD1(result) = float64_to_int32(op.xmm64u(1), status); prepareFPU2MMX(); /* cause FPU2MMX state transition */ check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_MMX_REG(i->dst(), result); #endif BX_NEXT_INSTR(i); } /* * Opcode: F2 0F 2D * Convert one double precision FP number to doubleword integer * When a conversion is inexact, the value returned is rounded according * to rounding control bits in MXCSR register. * Possible floating point exceptions: #I, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTSD2SI_GdWsdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float64 op = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); softfloat_status_word_rc_override(status, i); Bit32s result = float64_to_int32(op, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_32BIT_REGZ(i->dst(), (Bit32u) result); #endif BX_NEXT_INSTR(i); } #if BX_SUPPORT_X86_64 BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTSD2SI_GqWsdR(bxInstruction_c *i) { float64 op = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); softfloat_status_word_rc_override(status, i); Bit64s result = float64_to_int64(op, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_64BIT_REG(i->dst(), (Bit64u) result); BX_NEXT_INSTR(i); } #endif /* * Opcode: F3 0F 2D * Convert one single precision FP number to doubleword integer. * When a conversion is inexact, the value returned is rounded according * to rounding control bits in MXCSR register. * Possible floating point exceptions: #I, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTSS2SI_GdWssR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float32 op = BX_READ_XMM_REG_LO_DWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); softfloat_status_word_rc_override(status, i); Bit32s result = float32_to_int32(op, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_32BIT_REGZ(i->dst(), (Bit32u) result); #endif BX_NEXT_INSTR(i); } #if BX_SUPPORT_X86_64 BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTSS2SI_GqWssR(bxInstruction_c *i) { float32 op = BX_READ_XMM_REG_LO_DWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); softfloat_status_word_rc_override(status, i); Bit64s result = float32_to_int64(op, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_64BIT_REG(i->dst(), (Bit64u) result); BX_NEXT_INSTR(i); } #endif /* * Opcode: 0F 5A * Convert two single precision FP numbers to two double precision FP numbers * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTPS2PD_VpdWpsR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister result; BxPackedMmxRegister op; // use MMX register as 64-bit value with convinient accessors MMXUQ(op) = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); result.xmm64u(0) = float32_to_float64(MMXUD0(op), status); result.xmm64u(1) = float32_to_float64(MMXUD1(op), status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), result); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F 5A * Convert two double precision FP numbers to two single precision FP. * When a conversion is inexact, the value returned is rounded according * to rounding control bits in MXCSR register. * Possible floating point exceptions: #I, #D, #O, #I, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTPD2PS_VpsWpdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op.xmm32u(0) = float64_to_float32(op.xmm64u(0), status); op.xmm32u(1) = float64_to_float32(op.xmm64u(1), status); op.xmm64u(1) = 0; check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op); #endif BX_NEXT_INSTR(i); } /* * Opcode: F2 0F 5A * Convert one double precision FP number to one single precision FP. * When a conversion is inexact, the value returned is rounded according * to rounding control bits in MXCSR register. * Possible floating point exceptions: #I, #D, #O, #I, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTSD2SS_VssWsdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float64 op = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); float32 result = float64_to_float32(op, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_DWORD(i->dst(), result); #endif BX_NEXT_INSTR(i); } /* * Opcode: F3 0F 5A * Convert one single precision FP number to one double precision FP. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTSS2SD_VsdWssR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float32 op = BX_READ_XMM_REG_LO_DWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); float64 result = float32_to_float64(op, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), result); #endif BX_NEXT_INSTR(i); } /* * Opcode: 0F 5B * Convert four signed integers to four single precision FP numbers. * When a conversion is inexact, the value returned is rounded according * to rounding control bits in MXCSR register. * Possible floating point exceptions: #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTDQ2PS_VpsWdqR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op.xmm32u(0) = int32_to_float32(op.xmm32s(0), status); op.xmm32u(1) = int32_to_float32(op.xmm32s(1), status); op.xmm32u(2) = int32_to_float32(op.xmm32s(2), status); op.xmm32u(3) = int32_to_float32(op.xmm32s(3), status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F 5B * Convert four single precision FP to four doubleword integers. * When a conversion is inexact, the value returned is rounded according * to rounding control bits in MXCSR register. * Possible floating point exceptions: #I, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTPS2DQ_VdqWpsR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op.xmm32s(0) = float32_to_int32(op.xmm32u(0), status); op.xmm32s(1) = float32_to_int32(op.xmm32u(1), status); op.xmm32s(2) = float32_to_int32(op.xmm32u(2), status); op.xmm32s(3) = float32_to_int32(op.xmm32u(3), status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op); #endif BX_NEXT_INSTR(i); } /* * Opcode: F3 0F 5B * Convert four single precision FP to four doubleword integers using * truncation if the conversion is inexact. * Possible floating point exceptions: #I, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTTPS2DQ_VdqWpsR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op.xmm32s(0) = float32_to_int32_round_to_zero(op.xmm32u(0), status); op.xmm32s(1) = float32_to_int32_round_to_zero(op.xmm32u(1), status); op.xmm32s(2) = float32_to_int32_round_to_zero(op.xmm32u(2), status); op.xmm32s(3) = float32_to_int32_round_to_zero(op.xmm32u(3), status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F E6 * Convert two double precision FP to two signed doubleword integers using * truncation if the conversion is inexact. * Possible floating point exceptions: #I, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTTPD2DQ_VqWpdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op.xmm32s(0) = float64_to_int32_round_to_zero(op.xmm64u(0), status); op.xmm32s(1) = float64_to_int32_round_to_zero(op.xmm64u(1), status); op.xmm64u(1) = 0; check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op); #endif BX_NEXT_INSTR(i); } /* * Opcode: F2 0F E6 * Convert two double precision FP to two signed doubleword integers. * When a conversion is inexact, the value returned is rounded according * to rounding control bits in MXCSR register. * Possible floating point exceptions: #I, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTPD2DQ_VqWpdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op.xmm32s(0) = float64_to_int32(op.xmm64u(0), status); op.xmm32s(1) = float64_to_int32(op.xmm64u(1), status); op.xmm64u(1) = 0; check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op); #endif BX_NEXT_INSTR(i); } /* * Opcode: F3 0F E6 * Convert two 32bit signed integers from XMM/MEM to two double precision FP * Possible floating point exceptions: - */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CVTDQ2PD_VpdWqR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister result; BxPackedMmxRegister op; // use MMX register as 64-bit value with convinient accessors MMXUQ(op) = BX_READ_XMM_REG_LO_QWORD(i->src()); result.xmm64u(0) = int32_to_float64(MMXSD0(op)); result.xmm64u(1) = int32_to_float64(MMXSD1(op)); BX_WRITE_XMM_REG(i->dst(), result); #endif BX_NEXT_INSTR(i); } /* * Opcode: 0F 2E * Compare two single precision FP numbers and set EFLAGS accordintly. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::UCOMISS_VssWssR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float32 op1 = BX_READ_XMM_REG_LO_DWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_DWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); softfloat_status_word_rc_override(status, i); int rc = float32_compare_quiet(op1, op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_CPU_THIS_PTR write_eflags_fpu_compare(rc); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F 2E * Compare two double precision FP numbers and set EFLAGS accordintly. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::UCOMISD_VsdWsdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float64 op1 = BX_READ_XMM_REG_LO_QWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); softfloat_status_word_rc_override(status, i); int rc = float64_compare_quiet(op1, op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_CPU_THIS_PTR write_eflags_fpu_compare(rc); #endif BX_NEXT_INSTR(i); } /* * Opcode: 0F 2F * Compare two single precision FP numbers and set EFLAGS accordintly. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::COMISS_VssWssR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float32 op1 = BX_READ_XMM_REG_LO_DWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_DWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); softfloat_status_word_rc_override(status, i); int rc = float32_compare(op1, op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_CPU_THIS_PTR write_eflags_fpu_compare(rc); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F 2F * Compare two double precision FP numbers and set EFLAGS accordintly. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::COMISD_VsdWsdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float64 op1 = BX_READ_XMM_REG_LO_QWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); softfloat_status_word_rc_override(status, i); int rc = float64_compare(op1, op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_CPU_THIS_PTR write_eflags_fpu_compare(rc); #endif BX_NEXT_INSTR(i); } /* * Opcode: 0F 51 * Square Root packed single precision. * Possible floating point exceptions: #I, #D, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::SQRTPS_VpsWpsR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op.xmm32u(0) = float32_sqrt(op.xmm32u(0), status); op.xmm32u(1) = float32_sqrt(op.xmm32u(1), status); op.xmm32u(2) = float32_sqrt(op.xmm32u(2), status); op.xmm32u(3) = float32_sqrt(op.xmm32u(3), status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F 51 * Square Root packed double precision. * Possible floating point exceptions: #I, #D, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::SQRTPD_VpdWpdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op.xmm64u(0) = float64_sqrt(op.xmm64u(0), status); op.xmm64u(1) = float64_sqrt(op.xmm64u(1), status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op); #endif BX_NEXT_INSTR(i); } /* * Opcode: F2 0F 51 * Square Root scalar double precision. * Possible floating point exceptions: #I, #D, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::SQRTSD_VsdWsdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float64 op = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op = float64_sqrt(op, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), op); #endif BX_NEXT_INSTR(i); } /* * Opcode: F3 0F 51 * Square Root scalar single precision. * Possible floating point exceptions: #I, #D, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::SQRTSS_VssWssR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float32 op = BX_READ_XMM_REG_LO_DWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op = float32_sqrt(op, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_DWORD(i->dst(), op); #endif BX_NEXT_INSTR(i); } /* * Opcode: 0F 58 * Add packed single precision FP numbers from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::ADDPS_VpsWpsR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_addps(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F 58 * Add packed double precision FP numbers from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::ADDPD_VpdWpdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_addpd(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F2 0F 58 * Add the lower double precision FP number from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::ADDSD_VsdWsdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float64 op1 = BX_READ_XMM_REG_LO_QWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op1 = float64_add(op1, op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F3 0F 58 * Add the lower single precision FP number from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::ADDSS_VssWssR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float32 op1 = BX_READ_XMM_REG_LO_DWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_DWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op1 = float32_add(op1, op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_DWORD(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: 0F 59 * Multiply packed single precision FP numbers from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::MULPS_VpsWpsR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_mulps(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F 59 * Multiply packed double precision FP numbers from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::MULPD_VpdWpdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_mulpd(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F2 0F 59 * Multiply the lower double precision FP number from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::MULSD_VsdWsdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float64 op1 = BX_READ_XMM_REG_LO_QWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op1 = float64_mul(op1, op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F3 0F 59 * Multiply the lower single precision FP number from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::MULSS_VssWssR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float32 op1 = BX_READ_XMM_REG_LO_DWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_DWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op1 = float32_mul(op1, op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_DWORD(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: 0F 5C * Subtract packed single precision FP numbers from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::SUBPS_VpsWpsR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_subps(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F 5C * Subtract packed double precision FP numbers from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::SUBPD_VpdWpdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_subpd(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F2 0F 5C * Subtract the lower double precision FP number from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::SUBSD_VsdWsdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float64 op1 = BX_READ_XMM_REG_LO_QWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op1 = float64_sub(op1, op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F3 0F 5C * Subtract the lower single precision FP number from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::SUBSS_VssWssR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float32 op1 = BX_READ_XMM_REG_LO_DWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_DWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op1 = float32_sub(op1, op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_DWORD(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: 0F 5D * Calculate the minimum single precision FP between XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::MINPS_VpsWpsR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_minps(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F 5D * Calculate the minimum double precision FP between XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::MINPD_VpdWpdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_minpd(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F2 0F 5D * Calculate the minimum scalar double precision FP between XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::MINSD_VsdWsdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float64 op1 = BX_READ_XMM_REG_LO_QWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op1 = float64_min(op1, op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F3 0F 5D * Calculate the minimum scalar single precision FP between XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::MINSS_VssWssR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float32 op1 = BX_READ_XMM_REG_LO_DWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_DWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op1 = float32_min(op1, op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_DWORD(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: 0F 5E * Divide packed single precision FP numbers from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #Z, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::DIVPS_VpsWpsR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_divps(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F 5E * Divide packed double precision FP numbers from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #Z, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::DIVPD_VpdWpdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_divpd(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F2 0F 5E * Divide the lower double precision FP number from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #Z, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::DIVSD_VsdWsdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float64 op1 = BX_READ_XMM_REG_LO_QWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op1 = float64_div(op1, op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F3 0F 5E * Divide the lower single precision FP number from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #Z, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::DIVSS_VssWssR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float32 op1 = BX_READ_XMM_REG_LO_DWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_DWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op1 = float32_div(op1, op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_DWORD(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: 0F 5F * Calculate the maximum single precision FP between XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::MAXPS_VpsWpsR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_maxps(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F 5F * Calculate the maximum double precision FP between XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::MAXPD_VpdWpdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_maxpd(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F2 0F 5F * Calculate the maximum scalar double precision FP between XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::MAXSD_VsdWsdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float64 op1 = BX_READ_XMM_REG_LO_QWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op1 = float64_max(op1, op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F3 0F 5F * Calculate the maxumim scalar single precision FP between XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::MAXSS_VssWssR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float32 op1 = BX_READ_XMM_REG_LO_DWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_DWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); op1 = float32_max(op1, op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_DWORD(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F 7C * Add horizontally packed double precision FP in XMM2/MEM from XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::HADDPD_VpdWpdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_haddpd(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F2 0F 7C * Add horizontally packed single precision FP in XMM2/MEM from XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::HADDPS_VpsWpsR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_haddps(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F 7D * Subtract horizontally packed double precision FP in XMM2/MEM from XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::HSUBPD_VpdWpdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_hsubpd(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F2 0F 7D * Subtract horizontally packed single precision FP in XMM2/MEM from XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::HSUBPS_VpsWpsR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_hsubps(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: 0F C2 * Compare packed single precision FP values using Ib as comparison predicate. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CMPPS_VpsWpsIbR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); int ib = i->Ib() & 7; op1.xmm32u(0) = compare32[ib](op1.xmm32u(0), op2.xmm32u(0), status) ? 0xFFFFFFFF : 0; op1.xmm32u(1) = compare32[ib](op1.xmm32u(1), op2.xmm32u(1), status) ? 0xFFFFFFFF : 0; op1.xmm32u(2) = compare32[ib](op1.xmm32u(2), op2.xmm32u(2), status) ? 0xFFFFFFFF : 0; op1.xmm32u(3) = compare32[ib](op1.xmm32u(3), op2.xmm32u(3), status) ? 0xFFFFFFFF : 0; check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F C2 * Compare packed double precision FP values using Ib as comparison predicate. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CMPPD_VpdWpdIbR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); int ib = i->Ib() & 7; op1.xmm64u(0) = compare64[ib](op1.xmm64u(0), op2.xmm64u(0), status) ? BX_CONST64(0xFFFFFFFFFFFFFFFF) : 0; op1.xmm64u(1) = compare64[ib](op1.xmm64u(1), op2.xmm64u(1), status) ? BX_CONST64(0xFFFFFFFFFFFFFFFF) : 0; check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F2 0F C2 * Compare double precision FP values using Ib as comparison predicate. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CMPSD_VsdWsdIbR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float64 op1 = BX_READ_XMM_REG_LO_QWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); int ib = i->Ib() & 7; if(compare64[ib](op1, op2, status)) { op1 = BX_CONST64(0xFFFFFFFFFFFFFFFF); } else { op1 = 0; } check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F3 0F C2 * Compare single precision FP values using Ib as comparison predicate. * Possible floating point exceptions: #I, #D */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::CMPSS_VssWssIbR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 float32 op1 = BX_READ_XMM_REG_LO_DWORD(i->dst()), op2 = BX_READ_XMM_REG_LO_DWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); int ib = i->Ib() & 7; op1 = compare32[ib](op1, op2, status) ? 0xFFFFFFFF : 0; check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_DWORD(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: 66 0F D0 * Add/Subtract packed double precision FP numbers from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::ADDSUBPD_VpdWpdR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_addsubpd(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } /* * Opcode: F2 0F D0 * Add/Substract packed single precision FP numbers from XMM2/MEM to XMM1. * Possible floating point exceptions: #I, #D, #O, #U, #P */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::ADDSUBPS_VpsWpsR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); xmm_addsubps(&op1, &op2, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op1); #endif BX_NEXT_INSTR(i); } #if BX_CPU_LEVEL >= 6 /* 66 0F 3A 08 */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::ROUNDPS_VpsWpsIbR(bxInstruction_c *i) { BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); Bit8u control = i->Ib(); // override MXCSR rounding mode with control coming from imm8 if ((control & 0x4) == 0) status.float_rounding_mode = control & 0x3; // ignore precision exception result if (control & 0x8) status.float_suppress_exception |= float_flag_inexact; op.xmm32u(0) = float32_round_to_int(op.xmm32u(0), status); op.xmm32u(1) = float32_round_to_int(op.xmm32u(1), status); op.xmm32u(2) = float32_round_to_int(op.xmm32u(2), status); op.xmm32u(3) = float32_round_to_int(op.xmm32u(3), status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op); BX_NEXT_INSTR(i); } /* 66 0F 3A 09 */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::ROUNDPD_VpdWpdIbR(bxInstruction_c *i) { BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); Bit8u control = i->Ib(); // override MXCSR rounding mode with control coming from imm8 if ((control & 0x4) == 0) status.float_rounding_mode = control & 0x3; // ignore precision exception result if (control & 0x8) status.float_suppress_exception |= float_flag_inexact; op.xmm64u(0) = float64_round_to_int(op.xmm64u(0), status); op.xmm64u(1) = float64_round_to_int(op.xmm64u(1), status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op); BX_NEXT_INSTR(i); } /* 66 0F 3A 0A */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::ROUNDSS_VssWssIbR(bxInstruction_c *i) { float32 op = BX_READ_XMM_REG_LO_DWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); Bit8u control = i->Ib(); // override MXCSR rounding mode with control coming from imm8 if ((control & 0x4) == 0) status.float_rounding_mode = control & 0x3; // ignore precision exception result if (control & 0x8) status.float_suppress_exception |= float_flag_inexact; op = float32_round_to_int(op, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_DWORD(i->dst(), op); BX_NEXT_INSTR(i); } /* 66 0F 3A 0B */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::ROUNDSD_VsdWsdIbR(bxInstruction_c *i) { float64 op = BX_READ_XMM_REG_LO_QWORD(i->src()); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); Bit8u control = i->Ib(); // override MXCSR rounding mode with control coming from imm8 if ((control & 0x4) == 0) status.float_rounding_mode = control & 0x3; // ignore precision exception result if (control & 0x8) status.float_suppress_exception |= float_flag_inexact; op = float64_round_to_int(op, status); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), op); BX_NEXT_INSTR(i); } /* Opcode: 66 0F 3A 40 * Selectively multiply packed SP floating-point values from xmm1 with * packed SP floating-point values from xmm2, add and selectively * store the packed SP floating-point values or zero values to xmm1 */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::DPPS_VpsWpsIbR(bxInstruction_c *i) { BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()); BxPackedXmmRegister op2 = BX_READ_XMM_REG(i->src()); Bit8u mask = i->Ib(); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); // op1: [A, B, C, D] // op2: [E, F, G, H] // after multiplication: op1 = [EA, BF, CG, DH] xmm_mulps_mask(&op1, &op2, status, mask >> 4); check_exceptionsSSE(get_exception_flags(status)); // shuffle op2 = [BF, AE, DH, CG] xmm_shufps(&op2, &op1, &op1, 0xb1); // op2 = [(BF+AE), (AE+BF), (DH+CG), (CG+DH)] xmm_addps(&op2, &op1, status); check_exceptionsSSE(get_exception_flags(status)); // shuffle op1 = [(DH+CG), (CG+DH), (BF+AE), (AE+BF)] xmm_shufpd(&op1, &op2, &op2, 0x1); // op2 = [(BF+AE)+(DH+CG), (AE+BF)+(CG+DH), (DH+CG)+(BF+AE), (CG+DH)+(AE+BF)] xmm_addps_mask(&op2, &op1, status, mask); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REG(i->dst(), op2); BX_NEXT_INSTR(i); } /* Opcode: 66 0F 3A 41 * Selectively multiply packed DP floating-point values from xmm1 with * packed DP floating-point values from xmm2, add and selectively * store the packed DP floating-point values or zero values to xmm1 */ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::DPPD_VpdHpdWpdIbR(bxInstruction_c *i) { BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->src1()); BxPackedXmmRegister op2 = BX_READ_XMM_REG(i->src2()); Bit8u mask = i->Ib(); float_status_t status; mxcsr_to_softfloat_status_word(status, MXCSR); // op1: [A, B] // op2: [C, D] // after multiplication: op1 = [AC, BD] xmm_mulpd_mask(&op1, &op2, status, mask >> 4); check_exceptionsSSE(get_exception_flags(status)); // shuffle op2 = [BD, AC] xmm_shufpd(&op2, &op1, &op1, 0x1); // op1 = [AC+BD, BD+AC] xmm_addpd_mask(&op1, &op2, status, mask); check_exceptionsSSE(get_exception_flags(status)); BX_WRITE_XMM_REGZ(i->dst(), op1, i->getVL()); BX_NEXT_INSTR(i); } #endif // BX_CPU_LEVEL >= 6
{ "pile_set_name": "Github" }
/* This is a compiled file, you should be editing the file in the templates directory */ .pace { -webkit-pointer-events: none; pointer-events: none; -webkit-user-select: none; -moz-user-select: none; user-select: none; } .pace-inactive { display: none; } .pace .pace-progress { background: #eb7a55; position: fixed; z-index: 2000; top: 0; right: 100%; width: 100%; height: 2px; }
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MOBA_CSharp_Server.Library.DataReader; using MOBA_CSharp_Server.Library.ECS; namespace MOBA_CSharp_Server.Game { public class Sight : Effect { readonly float Duration; public bool IsBuilding { get; private set; } Dictionary<Team, float> timers = new Dictionary<Team, float>(); public Sight(bool isBuilding, Unit unitRoot, Entity root) : base(CombatType.Sight, unitRoot, root) { AddInheritedType(typeof(Sight)); Duration = GetYAMLObject().GetData<float>("Duration"); IsBuilding = isBuilding; foreach (Team team in Enum.GetValues(typeof(Team))) { if(isBuilding || team == unitRoot.Team) { timers.Add(team, Duration); } else { if(unitRoot.UnitID != unitRoot.OwnerUnitID) { Unit ownerUnit = Root.GetChild<WorldEntity>().GetUnit(unitRoot.OwnerUnitID); if(ownerUnit != null) { Sight sight = ownerUnit.GetChild<Sight>(); if (sight != null && sight.GetSight(team)) { timers.Add(team, Duration); continue; } } } timers.Add(team, 0); } } } public override void Step(float deltaTime) { base.Step(deltaTime); List<Team> keys = new List<Team>(timers.Keys); foreach (var team in keys) { if (team != unitRoot.Team) { timers[team] -= IsBuilding ? 0 : deltaTime; } if (timers[team] > 0) { SetVisionParam(team, true, (int)VisionStatusPriority.Sight); } else { UnSetVisionParam(team); } } } public bool GetSight(Team team) { return timers[team] > 0; } public void SetSight(Team team) { timers[team] = Duration; } } }
{ "pile_set_name": "Github" }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data-major_survey.R \docType{data} \name{major_survey} \alias{major_survey} \alias{major.survey} \title{Survey of Duke students and the area of their major} \format{ A data frame with 218 observations on the following 2 variables. \describe{ \item{gpa}{Grade point average (GPA).} \item{major}{Area of academic major.} } } \usage{ major_survey } \description{ Survey of 218 students, collecting information on their GPAs and their academic major. } \examples{ library(ggplot2) ggplot(major_survey, aes(x = major, y = gpa)) + geom_boxplot() } \keyword{datasets}
{ "pile_set_name": "Github" }
/* * wrg.c * * Copyright (C) 2005 Mike Baker * Copyright (C) 2008 Felix Fietkau <[email protected]> * Copyright (C) 2011-2012 Gabor Juhos <[email protected]> * Copyright (C) 2016 Stijn Tintel <[email protected]> * Copyright (C) 2017 George Hopkins <[email protected]> * * 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 2 * 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, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <byteswap.h> #include <endian.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <string.h> #include <errno.h> #include <arpa/inet.h> #include <sys/ioctl.h> #include <mtd/mtd-user.h> #include "mtd.h" #include "md5.h" #if !defined(__BYTE_ORDER) #error "Unknown byte order" #endif #if __BYTE_ORDER == __BIG_ENDIAN #define cpu_to_le32(x) bswap_32(x) #define le32_to_cpu(x) bswap_32(x) #elif __BYTE_ORDER == __LITTLE_ENDIAN #define cpu_to_le32(x) (x) #define le32_to_cpu(x) (x) #else #error "Unsupported endianness" #endif #define WRG_MAGIC 0x20040220 struct wrg_header { char signature[32]; uint32_t magic1; uint32_t magic2; uint32_t size; uint32_t offset; char devname[32]; char digest[16]; } __attribute__ ((packed)); ssize_t pread(int fd, void *buf, size_t count, off_t offset); ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset); int wrg_fix_md5(struct wrg_header *shdr, int fd, size_t data_offset, size_t data_size) { char *buf; ssize_t res; MD5_CTX ctx; unsigned char digest[16]; int i; int err = 0; buf = malloc(data_size); if (!buf) { err = -ENOMEM; goto err_out; } res = pread(fd, buf, data_size, data_offset); if (res != data_size) { perror("pread"); err = -EIO; goto err_free; } MD5_Init(&ctx); MD5_Update(&ctx, (char *)&shdr->offset, sizeof(shdr->offset)); MD5_Update(&ctx, (char *)&shdr->devname, sizeof(shdr->devname)); MD5_Update(&ctx, buf, data_size); MD5_Final(digest, &ctx); if (!memcmp(digest, shdr->digest, sizeof(digest))) { if (quiet < 2) fprintf(stderr, "the header is fixed already\n"); return -1; } if (quiet < 2) { fprintf(stderr, "new size: %u, new MD5: ", data_size); for (i = 0; i < sizeof(digest); i++) fprintf(stderr, "%02x", digest[i]); fprintf(stderr, "\n"); } /* update the size in the image */ shdr->size = cpu_to_le32(data_size); /* update the checksum in the image */ memcpy(shdr->digest, digest, sizeof(digest)); err_free: free(buf); err_out: return err; } int mtd_fixwrg(const char *mtd, size_t offset, size_t data_size) { int fd; char *first_block; ssize_t res; size_t block_offset; size_t data_offset; struct wrg_header *shdr; if (quiet < 2) fprintf(stderr, "Trying to fix WRG header in %s at 0x%x...\n", mtd, offset); block_offset = offset & ~(erasesize - 1); offset -= block_offset; fd = mtd_check_open(mtd); if(fd < 0) { fprintf(stderr, "Could not open mtd device: %s\n", mtd); exit(1); } if (block_offset + erasesize > mtdsize) { fprintf(stderr, "Offset too large, device size 0x%x\n", mtdsize); exit(1); } first_block = malloc(erasesize); if (!first_block) { perror("malloc"); exit(1); } res = pread(fd, first_block, erasesize, block_offset); if (res != erasesize) { perror("pread"); exit(1); } shdr = (struct wrg_header *)(first_block + offset); if (le32_to_cpu(shdr->magic1) != WRG_MAGIC) { fprintf(stderr, "No WRG header found (%08x != %08x)\n", le32_to_cpu(shdr->magic1), WRG_MAGIC); exit(1); } else if (!le32_to_cpu(shdr->size)) { fprintf(stderr, "WRG entity with empty image\n"); exit(1); } data_offset = offset + sizeof(struct wrg_header); if (!data_size) data_size = mtdsize - data_offset; if (data_size > le32_to_cpu(shdr->size)) data_size = le32_to_cpu(shdr->size); if (wrg_fix_md5(shdr, fd, data_offset, data_size)) goto out; if (mtd_erase_block(fd, block_offset)) { fprintf(stderr, "Can't erease block at 0x%x (%s)\n", block_offset, strerror(errno)); exit(1); } if (quiet < 2) fprintf(stderr, "Rewriting block at 0x%x\n", block_offset); if (pwrite(fd, first_block, erasesize, block_offset) != erasesize) { fprintf(stderr, "Error writing block (%s)\n", strerror(errno)); exit(1); } if (quiet < 2) fprintf(stderr, "Done.\n"); out: close (fd); sync(); return 0; }
{ "pile_set_name": "Github" }
# Strfmt [![Build Status](https://travis-ci.org/go-openapi/strfmt.svg?branch=master)](https://travis-ci.org/go-openapi/strfmt) [![codecov](https://codecov.io/gh/go-openapi/strfmt/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/strfmt) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) [![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/strfmt/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/strfmt?status.svg)](http://godoc.org/github.com/go-openapi/strfmt) [![GolangCI](https://golangci.com/badges/github.com/go-openapi/strfmt.svg)](https://golangci.com) [![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/strfmt)](https://goreportcard.com/report/github.com/go-openapi/strfmt) This package exposes a registry of data types to support string formats in the go-openapi toolkit. strfmt represents a well known string format such as credit card or email. The go toolkit for OpenAPI specifications knows how to deal with those. ## Supported data formats go-openapi/strfmt follows the swagger 2.0 specification with the following formats defined [here](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types). It also provides convenient extensions to go-openapi users. - [x] JSON-schema draft 4 formats - date-time - email - hostname - ipv4 - ipv6 - uri - [x] swagger 2.0 format extensions - binary - byte (e.g. base64 encoded string) - date (e.g. "1970-01-01") - password - [x] go-openapi custom format extensions - bsonobjectid (BSON objectID) - creditcard - duration (e.g. "3 weeks", "1ms") - hexcolor (e.g. "#FFFFFF") - isbn, isbn10, isbn13 - mac (e.g "01:02:03:04:05:06") - rgbcolor (e.g. "rgb(100,100,100)") - ssn - uuid, uuid3, uuid4, uuid5 - cidr (e.g. "192.0.2.1/24", "2001:db8:a0b:12f0::1/32") > NOTE: as the name stands for, this package is intended to support string formatting only. > It does not provide validation for numerical values with swagger format extension for JSON types "number" or > "integer" (e.g. float, double, int32...). ## Format types Types defined in strfmt expose marshaling and validation capabilities. List of defined types: - Base64 - CreditCard - Date - DateTime - Duration - Email - HexColor - Hostname - IPv4 - IPv6 - CIDR - ISBN - ISBN10 - ISBN13 - MAC - ObjectId - Password - RGBColor - SSN - URI - UUID - UUID3 - UUID4 - UUID5
{ "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.14"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>FabGL: Member List</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="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(document).ready(initResizable); /* @license-end */</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="projectalign" style="padding-left: 0.5em;"> <div id="projectname">FabGL </div> <div id="projectbrief">ESP32 VGA Controller and Graphics Library</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.14 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(document).ready(function(){initNavTree('structfabgl_1_1_raw_data.html','');}); /* @license-end */ </script> <div id="doc-content"> <!-- 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 class="header"> <div class="headertitle"> <div class="title">fabgl::RawData Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="structfabgl_1_1_raw_data.html">fabgl::RawData</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="structfabgl_1_1_raw_data.html#ac09693623930e96f612d3a705c577595">data</a></td><td class="entry"><a class="el" href="structfabgl_1_1_raw_data.html">fabgl::RawData</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structfabgl_1_1_raw_data.html#a2e62ba37099f8b9213f57453834a71b2">height</a></td><td class="entry"><a class="el" href="structfabgl_1_1_raw_data.html">fabgl::RawData</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="structfabgl_1_1_raw_data.html#a0ee8ffeaa94d9078e853caddb916d107">width</a></td><td class="entry"><a class="el" href="structfabgl_1_1_raw_data.html">fabgl::RawData</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structfabgl_1_1_raw_data.html#ae14e8d663b0201d7b052bdba54b9c5a1">X</a></td><td class="entry"><a class="el" href="structfabgl_1_1_raw_data.html">fabgl::RawData</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="structfabgl_1_1_raw_data.html#abc511f378c9b5db899e4292f2ceb2682">Y</a></td><td class="entry"><a class="el" href="structfabgl_1_1_raw_data.html">fabgl::RawData</a></td><td class="entry"></td></tr> </table></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.14 </li> </ul> </div> </body> </html>
{ "pile_set_name": "Github" }
setlocal commentstring=#\ %s setlocal comments=:#
{ "pile_set_name": "Github" }
"" DialogScript DialogScript CreateScript CreateScript TypePropertiesOptions TypePropertiesOptions Help Help Tools.shelf Tools.shelf InternalFileOptions InternalFileOptions Contents.gz Contents.gz IconSVG IconSVG OnCreated OnCreated ExtraFileOptions ExtraFileOptions mops__TD__tools__05.svg mops_TD_tools_05.svg
{ "pile_set_name": "Github" }
using System; using NHapi.Base; using NHapi.Base.Parser; using NHapi.Base.Model; using NHapi.Model.V251.Datatype; using NHapi.Base.Log; namespace NHapi.Model.V251.Segment{ ///<summary> /// Represents an HL7 GOL message segment. /// This segment has the following fields:<ol> ///<li>GOL-1: Action Code (ID)</li> ///<li>GOL-2: Action Date/Time (TS)</li> ///<li>GOL-3: Goal ID (CE)</li> ///<li>GOL-4: Goal Instance ID (EI)</li> ///<li>GOL-5: Episode of Care ID (EI)</li> ///<li>GOL-6: Goal List Priority (NM)</li> ///<li>GOL-7: Goal Established Date/Time (TS)</li> ///<li>GOL-8: Expected Goal Achieve Date/Time (TS)</li> ///<li>GOL-9: Goal Classification (CE)</li> ///<li>GOL-10: Goal Management Discipline (CE)</li> ///<li>GOL-11: Current Goal Review Status (CE)</li> ///<li>GOL-12: Current Goal Review Date/Time (TS)</li> ///<li>GOL-13: Next Goal Review Date/Time (TS)</li> ///<li>GOL-14: Previous Goal Review Date/Time (TS)</li> ///<li>GOL-15: Goal Review Interval (TQ)</li> ///<li>GOL-16: Goal Evaluation (CE)</li> ///<li>GOL-17: Goal Evaluation Comment (ST)</li> ///<li>GOL-18: Goal Life Cycle Status (CE)</li> ///<li>GOL-19: Goal Life Cycle Status Date/Time (TS)</li> ///<li>GOL-20: Goal Target Type (CE)</li> ///<li>GOL-21: Goal Target Name (XPN)</li> ///</ol> /// The get...() methods return data from individual fields. These methods /// do not throw exceptions and may therefore have to handle exceptions internally. /// If an exception is handled internally, it is logged and null is returned. /// This is not expected to happen - if it does happen this indicates not so much /// an exceptional circumstance as a bug in the code for this class. ///</summary> [Serializable] public class GOL : AbstractSegment { /** * Creates a GOL (Goal Detail) segment object that belongs to the given * message. */ public GOL(IGroup parent, IModelClassFactory factory) : base(parent,factory) { IMessage message = Message; try { this.add(typeof(ID), true, 1, 2, new System.Object[]{message, 287}, "Action Code"); this.add(typeof(TS), true, 1, 26, new System.Object[]{message}, "Action Date/Time"); this.add(typeof(CE), true, 1, 250, new System.Object[]{message}, "Goal ID"); this.add(typeof(EI), true, 1, 60, new System.Object[]{message}, "Goal Instance ID"); this.add(typeof(EI), false, 1, 60, new System.Object[]{message}, "Episode of Care ID"); this.add(typeof(NM), false, 1, 60, new System.Object[]{message}, "Goal List Priority"); this.add(typeof(TS), false, 1, 26, new System.Object[]{message}, "Goal Established Date/Time"); this.add(typeof(TS), false, 1, 26, new System.Object[]{message}, "Expected Goal Achieve Date/Time"); this.add(typeof(CE), false, 1, 250, new System.Object[]{message}, "Goal Classification"); this.add(typeof(CE), false, 1, 250, new System.Object[]{message}, "Goal Management Discipline"); this.add(typeof(CE), false, 1, 250, new System.Object[]{message}, "Current Goal Review Status"); this.add(typeof(TS), false, 1, 26, new System.Object[]{message}, "Current Goal Review Date/Time"); this.add(typeof(TS), false, 1, 26, new System.Object[]{message}, "Next Goal Review Date/Time"); this.add(typeof(TS), false, 1, 26, new System.Object[]{message}, "Previous Goal Review Date/Time"); this.add(typeof(TQ), false, 1, 200, new System.Object[]{message}, "Goal Review Interval"); this.add(typeof(CE), false, 1, 250, new System.Object[]{message}, "Goal Evaluation"); this.add(typeof(ST), false, 0, 300, new System.Object[]{message}, "Goal Evaluation Comment"); this.add(typeof(CE), false, 1, 250, new System.Object[]{message}, "Goal Life Cycle Status"); this.add(typeof(TS), false, 1, 26, new System.Object[]{message}, "Goal Life Cycle Status Date/Time"); this.add(typeof(CE), false, 0, 250, new System.Object[]{message}, "Goal Target Type"); this.add(typeof(XPN), false, 0, 250, new System.Object[]{message}, "Goal Target Name"); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Can't instantiate " + GetType().Name, he); } } ///<summary> /// Returns Action Code(GOL-1). ///</summary> public ID ActionCode { get{ ID ret = null; try { IType t = this.GetField(1, 0); ret = (ID)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Action Date/Time(GOL-2). ///</summary> public TS ActionDateTime { get{ TS ret = null; try { IType t = this.GetField(2, 0); ret = (TS)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Goal ID(GOL-3). ///</summary> public CE GoalID { get{ CE ret = null; try { IType t = this.GetField(3, 0); ret = (CE)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Goal Instance ID(GOL-4). ///</summary> public EI GoalInstanceID { get{ EI ret = null; try { IType t = this.GetField(4, 0); ret = (EI)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Episode of Care ID(GOL-5). ///</summary> public EI EpisodeOfCareID { get{ EI ret = null; try { IType t = this.GetField(5, 0); ret = (EI)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Goal List Priority(GOL-6). ///</summary> public NM GoalListPriority { get{ NM ret = null; try { IType t = this.GetField(6, 0); ret = (NM)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Goal Established Date/Time(GOL-7). ///</summary> public TS GoalEstablishedDateTime { get{ TS ret = null; try { IType t = this.GetField(7, 0); ret = (TS)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Expected Goal Achieve Date/Time(GOL-8). ///</summary> public TS ExpectedGoalAchieveDateTime { get{ TS ret = null; try { IType t = this.GetField(8, 0); ret = (TS)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Goal Classification(GOL-9). ///</summary> public CE GoalClassification { get{ CE ret = null; try { IType t = this.GetField(9, 0); ret = (CE)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Goal Management Discipline(GOL-10). ///</summary> public CE GoalManagementDiscipline { get{ CE ret = null; try { IType t = this.GetField(10, 0); ret = (CE)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Current Goal Review Status(GOL-11). ///</summary> public CE CurrentGoalReviewStatus { get{ CE ret = null; try { IType t = this.GetField(11, 0); ret = (CE)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Current Goal Review Date/Time(GOL-12). ///</summary> public TS CurrentGoalReviewDateTime { get{ TS ret = null; try { IType t = this.GetField(12, 0); ret = (TS)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Next Goal Review Date/Time(GOL-13). ///</summary> public TS NextGoalReviewDateTime { get{ TS ret = null; try { IType t = this.GetField(13, 0); ret = (TS)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Previous Goal Review Date/Time(GOL-14). ///</summary> public TS PreviousGoalReviewDateTime { get{ TS ret = null; try { IType t = this.GetField(14, 0); ret = (TS)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Goal Review Interval(GOL-15). ///</summary> public TQ GoalReviewInterval { get{ TQ ret = null; try { IType t = this.GetField(15, 0); ret = (TQ)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Goal Evaluation(GOL-16). ///</summary> public CE GoalEvaluation { get{ CE ret = null; try { IType t = this.GetField(16, 0); ret = (CE)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns a single repetition of Goal Evaluation Comment(GOL-17). /// throws HL7Exception if the repetition number is invalid. /// <param name="rep">The repetition number (this is a repeating field)</param> ///</summary> public ST GetGoalEvaluationComment(int rep) { ST ret = null; try { IType t = this.GetField(17, rep); ret = (ST)t; } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } ///<summary> /// Returns all repetitions of Goal Evaluation Comment (GOL-17). ///</summary> public ST[] GetGoalEvaluationComment() { ST[] ret = null; try { IType[] t = this.GetField(17); ret = new ST[t.Length]; for (int i = 0; i < ret.Length; i++) { ret[i] = (ST)t[i]; } } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } return ret; } ///<summary> /// Returns the total repetitions of Goal Evaluation Comment (GOL-17). ///</summary> public int GoalEvaluationCommentRepetitionsUsed { get{ try { return GetTotalFieldRepetitionsUsed(17); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } } } ///<summary> /// Returns Goal Life Cycle Status(GOL-18). ///</summary> public CE GoalLifeCycleStatus { get{ CE ret = null; try { IType t = this.GetField(18, 0); ret = (CE)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Goal Life Cycle Status Date/Time(GOL-19). ///</summary> public TS GoalLifeCycleStatusDateTime { get{ TS ret = null; try { IType t = this.GetField(19, 0); ret = (TS)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns a single repetition of Goal Target Type(GOL-20). /// throws HL7Exception if the repetition number is invalid. /// <param name="rep">The repetition number (this is a repeating field)</param> ///</summary> public CE GetGoalTargetType(int rep) { CE ret = null; try { IType t = this.GetField(20, rep); ret = (CE)t; } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } ///<summary> /// Returns all repetitions of Goal Target Type (GOL-20). ///</summary> public CE[] GetGoalTargetType() { CE[] ret = null; try { IType[] t = this.GetField(20); ret = new CE[t.Length]; for (int i = 0; i < ret.Length; i++) { ret[i] = (CE)t[i]; } } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } return ret; } ///<summary> /// Returns the total repetitions of Goal Target Type (GOL-20). ///</summary> public int GoalTargetTypeRepetitionsUsed { get{ try { return GetTotalFieldRepetitionsUsed(20); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } } } ///<summary> /// Returns a single repetition of Goal Target Name(GOL-21). /// throws HL7Exception if the repetition number is invalid. /// <param name="rep">The repetition number (this is a repeating field)</param> ///</summary> public XPN GetGoalTargetName(int rep) { XPN ret = null; try { IType t = this.GetField(21, rep); ret = (XPN)t; } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } ///<summary> /// Returns all repetitions of Goal Target Name (GOL-21). ///</summary> public XPN[] GetGoalTargetName() { XPN[] ret = null; try { IType[] t = this.GetField(21); ret = new XPN[t.Length]; for (int i = 0; i < ret.Length; i++) { ret[i] = (XPN)t[i]; } } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } return ret; } ///<summary> /// Returns the total repetitions of Goal Target Name (GOL-21). ///</summary> public int GoalTargetNameRepetitionsUsed { get{ try { return GetTotalFieldRepetitionsUsed(21); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } } } }}
{ "pile_set_name": "Github" }
// Copyright 2018 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 aix // +build ppc package unix //sysnb Getrlimit(resource int, rlim *Rlimit) (err error) = getrlimit64 //sysnb Setrlimit(resource int, rlim *Rlimit) (err error) = setrlimit64 //sys Seek(fd int, offset int64, whence int) (off int64, err error) = lseek64 //sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) func setTimespec(sec, nsec int64) Timespec { return Timespec{Sec: int32(sec), Nsec: int32(nsec)} } func setTimeval(sec, usec int64) Timeval { return Timeval{Sec: int32(sec), Usec: int32(usec)} } func (iov *Iovec) SetLen(length int) { iov.Len = uint32(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (msghdr *Msghdr) SetIovlen(length int) { msghdr.Iovlen = int32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } func Fstat(fd int, stat *Stat_t) error { return fstat(fd, stat) } func Fstatat(dirfd int, path string, stat *Stat_t, flags int) error { return fstatat(dirfd, path, stat, flags) } func Lstat(path string, stat *Stat_t) error { return lstat(path, stat) } func Stat(path string, statptr *Stat_t) error { return stat(path, statptr) }
{ "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.stanbol.ontologymanager.servicesapi.scope; import java.io.File; import org.apache.stanbol.ontologymanager.ontonet.api.scope.OntologyScope; import org.apache.stanbol.ontologymanager.servicesapi.OfflineConfiguration; import org.apache.stanbol.ontologymanager.servicesapi.io.OntologyInputSource; /** * A Scope Manager holds all references and tools for creating, modifying and deleting the logical realms that * store Web Ontologies, as well as offer facilities for handling the ontologies contained therein.<br> * <br> * Note that since this object is both a {@link ScopeRegistry} and an {@link ScopeFactory}, the call to * {@link ScopeRegistry#registerScope(OntologyScope)} or its overloads after * {@link ScopeFactory#createOntologyScope(String, OntologyInputSource...)} is unnecessary, as the ONManager * automatically registers newly created scopes. * * @author alexdma, anuzzolese * */ public interface ScopeManager extends ScopeFactory, ScopeRegistry { /** * The key used to configure the path of the ontology network configuration. */ String CONFIG_ONTOLOGY_PATH = "org.apache.stanbol.ontologymanager.ontonet.onconfig"; /** * The key used to configure the connectivity policy. */ String CONNECTIVITY_POLICY = "org.apache.stanbol.ontologymanager.ontonet.connectivity"; /** * The key used to configure the simple identifier of the scope registry (which should also be * concatenated with the base namespace to obtain the registry's HTTP endpoint URI). */ String ID_SCOPE_REGISTRY = "org.apache.stanbol.ontologymanager.ontonet.scopeRegistry.id"; /** * Returns the offline configuration set for this ontology network manager, if any. * * @return the offline configuration, or null if none was set. */ OfflineConfiguration getOfflineConfiguration(); OntologySpaceFactory getOntologySpaceFactory(); /** * Implementations should be able to create a {@link File} object from this path. * * @return the local path of the ontology storing the ontology network configuration. */ String getOntologyNetworkConfigurationPath(); /** * Returns the base namespace to be used for the Stanbol ontology network (e.g. for the creation of new * scopes). For convenience, it is returned as a string so that it can be concatenated to form IRIs. * * @deprecated please use {@link OfflineConfiguration#getDefaultOntologyNetworkNamespace()} to obtain the * namespace * * @return the base namespace of the Stanbol ontology network. */ String getOntologyNetworkNamespace(); /** * Returns the unique ontology scope registry for this context. * * @deprecated This methods now returns the current object, which is also a {@link ScopeRegistry}. * @return the ontology scope registry. */ ScopeRegistry getScopeRegistry(); /** * Sets the IRI that will be the base namespace for all ontology scopes and collectors created by this * object. * * @deprecated {@link ScopeManager} should set its namespace to be the same as * {@link OfflineConfiguration#getDefaultOntologyNetworkNamespace()} whenever it changes on * the object obtained by calling {@link #getOfflineConfiguration()}. * * @param namespace * the base namespace. */ void setOntologyNetworkNamespace(String namespace); }
{ "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. --> <div id="partyNotes" class="screenlet"> <div class="screenlet-title-bar"> <ul> <li class="h3">${uiLabelMap.CommonNotes}</li> <#if security.hasEntityPermission("PARTYMGR", "_NOTE", session)> <li><a href="<@ofbizUrl>AddPartyNote?partyId=${partyId}</@ofbizUrl>">${uiLabelMap.CommonCreateNew}</a></li> </#if> </ul> <br class="clear" /> </div> <div class="screenlet-body"> <#if notes?has_content> <table width="100%" border="0" cellpadding="1"> <#list notes as noteRef> <tr> <td> <div><b>${uiLabelMap.FormFieldTitle_noteName}: </b>${noteRef.noteName!}</div> <#if noteRef.noteParty?has_content> <div><b>${uiLabelMap.CommonBy}: </b>${Static["org.apache.ofbiz.party.party.PartyHelper"].getPartyName(delegator, noteRef.noteParty, true)}</div> </#if> <div><b>${uiLabelMap.CommonAt}: </b>${noteRef.noteDateTime.toString()}</div> </td> <td> ${noteRef.noteInfo} </td> </tr> <#if noteRef_has_next> <tr><td colspan="2"><hr/></td></tr> </#if> </#list> </table> <#else> ${uiLabelMap.PartyNoNotesForParty} </#if> </div> </div>
{ "pile_set_name": "Github" }
#!/bin/bash set -eu DB=primarykey.sqlite rm -f $DB ( echo "CREATE TABLE words (word varchar NOT NULL PRIMARY KEY);" echo "BEGIN;" for w in $( cat words.txt ); do echo "INSERT INTO words VALUES (\"$w\");" done echo "COMMIT;" ) | sqlite3 --batch $DB
{ "pile_set_name": "Github" }
<!-- --- name: Sixfab XBee Shield V2 class: board type: com formfactor: pHAT manufacturer: Sixfab description: Use XBee modules with the Raspberry Pi url: http://sixfab.com/product/xbee-shield/ buy: http://sixfab.com/product/xbee-shield/ image: 'sixfab-xbee-shield-v2.png' pincount: 40 eeprom: no power: '2': ground: '6': '9': '14': '20': '25': '30': '34': '39': pin: '3': mode: i2c '5': mode: i2c '7': mode: 1-wire '8': mode: uart '10': mode: uart '11': mode: output name: RTS '13': mode: output name: XBee_Reset '18': mode: output name: XBee_IO1 '22': mode: output name: XBee_IO1 '32': mode: output name: IN1 '36': mode: output name: RSSI '38': mode: input name: User Button '40': mode: output name: User Led --> # Sixfab XBee Shield V2 The Sixfab XBee Shield is add-on board that allows you to use XBee modules easily with your Pi. Some features include: * Headers fit most XBee modules * Up to 28 miles range * Point to point communication * Communication LED * 1-Wire sensor breakout (bcm4) * Programable from Linux, Windows and Android
{ "pile_set_name": "Github" }
# aws_db_subnet_group <!-- BEGINNING OF PRE-COMMIT-TERRAFORM DOCS HOOK --> ## Requirements No requirements. ## Providers | Name | Version | |------|---------| | aws | n/a | ## Inputs | Name | Description | Type | Default | Required | |------|-------------|------|---------|:--------:| | create | Whether to create this resource or not? | `bool` | `true` | no | | identifier | The identifier of the resource | `string` | n/a | yes | | name\_prefix | Creates a unique name beginning with the specified prefix | `string` | n/a | yes | | subnet\_ids | A list of VPC subnet IDs | `list(string)` | `[]` | no | | tags | A mapping of tags to assign to the resource | `map(string)` | `{}` | no | ## Outputs | Name | Description | |------|-------------| | this\_db\_subnet\_group\_arn | The ARN of the db subnet group | | this\_db\_subnet\_group\_id | The db subnet group name | <!-- END OF PRE-COMMIT-TERRAFORM DOCS HOOK -->
{ "pile_set_name": "Github" }
/******************************************************* * Copyright (C) 2015 Haotian Wu * * This file is the solution to the question: * https://www.hackerrank.com/challenges/encryption * * Redistribution and use in source and binary forms are permitted. *******************************************************/ #include <cstdio> #include <cstring> #include <string> #include <cmath> #include <cstdlib> #include <map> #include <iostream> #include <vector> #include <algorithm> using namespace std; // Compute sqrt(L). Watch out float point error. int main() { char str[100]; scanf("%s",str); int l = strlen(str); int floorl = (int)(sqrt(l)+1e-9); int ceill = (l==floorl*floorl? floorl : floorl+1); char grid[10][10] = {0}; int x=0,y=0; for (int i=0;i<strlen(str);i++) { grid[x++][y] = str[i]; if (x==ceill) { x = 0; y++; } } for (int i=0;i<ceill;i++) printf("%s ",grid[i]); }
{ "pile_set_name": "Github" }
/* * This file is part of hipSYCL, a SYCL implementation based on CUDA/HIP * * Copyright (c) 2019 Aksel Alpay * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef HIPSYCL_DEVICE_ID_HPP #define HIPSYCL_DEVICE_ID_HPP #include <functional> #include <cassert> #include <ostream> namespace hipsycl { namespace rt { enum class hardware_platform { rocm, cuda, cpu }; enum class api_platform { cuda, hip, openmp_cpu }; enum class backend_id { cuda, hip, openmp_cpu }; struct backend_descriptor { backend_id id; api_platform sw_platform; hardware_platform hw_platform; backend_descriptor() = default; backend_descriptor(hardware_platform hw_plat, api_platform sw_plat) : hw_platform{hw_plat}, sw_platform{sw_plat} { if (hw_plat == hardware_platform::cpu && sw_plat == api_platform::openmp_cpu) id = backend_id::openmp_cpu; else if (sw_plat == api_platform::hip) id = backend_id::hip; else if (hw_plat == hardware_platform::cuda && sw_plat == api_platform::cuda) id = backend_id::cuda; else assert(false && "Invalid combination of hardware/software platform for " "backend descriptor."); } friend bool operator==(const backend_descriptor &a, const backend_descriptor &b) { return a.id == b.id; } }; class device_id { public: device_id() = default; device_id(const device_id&) = default; device_id(backend_descriptor b, int id); bool is_host() const; backend_id get_backend() const; backend_descriptor get_full_backend_descriptor() const; int get_id() const; void dump(std::ostream& ostr) const; friend bool operator==(const device_id& a, const device_id& b) { return a._backend == b._backend && a._device_id == b._device_id; } friend bool operator!=(const device_id& a, const device_id& b) { return !(a == b); } private: backend_descriptor _backend; int _device_id; }; class platform_id { public: platform_id(backend_id b, int platform) : _backend{b}, _platform_id{platform} {} platform_id() = default; platform_id(device_id dev) : _backend{dev.get_backend()}, _platform_id{0} {} backend_id get_backend() const { return _backend; } int get_platform() const { return _platform_id; } friend bool operator==(const platform_id &a, const platform_id &b) { return a._backend == b._backend && a._platform_id == b._platform_id; } friend bool operator!=(const platform_id &a, const platform_id &b) { return !(a == b); } private: backend_id _backend; int _platform_id; }; } } namespace std { template <> struct hash<hipsycl::rt::device_id> { std::size_t operator()(const hipsycl::rt::device_id& k) const { return hash<int>()(static_cast<int>(k.get_backend())) ^ (hash<int>()(k.get_id()) << 1); } }; } #endif
{ "pile_set_name": "Github" }
.class final Lcom/tencent/mm/plugin/freewifi/model/a$1; .super Ljava/lang/Object; .source "SourceFile" # interfaces .implements Lcom/tencent/mm/t/d; # annotations .annotation system Ldalvik/annotation/EnclosingMethod; value = Lcom/tencent/mm/plugin/freewifi/model/a;->aaC()V .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x0 name = null .end annotation # instance fields .field final synthetic ebA:Lcom/tencent/mm/plugin/freewifi/model/a; # direct methods .method constructor <init>(Lcom/tencent/mm/plugin/freewifi/model/a;)V .locals 0 .prologue .line 124 iput-object p1, p0, Lcom/tencent/mm/plugin/freewifi/model/a$1;->ebA:Lcom/tencent/mm/plugin/freewifi/model/a; invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method # virtual methods .method public final onSceneEnd(IILjava/lang/String;Lcom/tencent/mm/t/j;)V .locals 4 .prologue .line 129 check-cast p4, Lcom/tencent/mm/plugin/freewifi/d/b; .line 130 iget-object v0, p4, Lcom/tencent/mm/plugin/freewifi/d/b;->mac:Ljava/lang/String; .line 131 invoke-static {v0}, Lcom/tencent/mm/plugin/freewifi/m;->pQ(Ljava/lang/String;)Z move-result v1 if-eqz v1, :cond_0 .line 139 :goto_0 return-void .line 134 :cond_0 const/16 v1, -0x753b if-ne p2, v1, :cond_1 .line 135 iget-object v1, p0, Lcom/tencent/mm/plugin/freewifi/model/a$1;->ebA:Lcom/tencent/mm/plugin/freewifi/model/a; iget-object v1, v1, Lcom/tencent/mm/plugin/freewifi/model/a;->eby:Landroid/util/SparseArray; invoke-virtual {v0}, Ljava/lang/String;->hashCode()I move-result v0 invoke-static {}, Lcom/tencent/mm/sdk/platformtools/be;->Gp()J move-result-wide v2 invoke-static {v2, v3}, Ljava/lang/Long;->valueOf(J)Ljava/lang/Long; move-result-object v2 invoke-virtual {v1, v0, v2}, Landroid/util/SparseArray;->put(ILjava/lang/Object;)V goto :goto_0 .line 137 :cond_1 iget-object v1, p0, Lcom/tencent/mm/plugin/freewifi/model/a$1;->ebA:Lcom/tencent/mm/plugin/freewifi/model/a; iget-object v1, v1, Lcom/tencent/mm/plugin/freewifi/model/a;->eby:Landroid/util/SparseArray; invoke-virtual {v0}, Ljava/lang/String;->hashCode()I move-result v0 invoke-virtual {v1, v0}, Landroid/util/SparseArray;->remove(I)V goto :goto_0 .end method
{ "pile_set_name": "Github" }
c2bc09ae256c6e95cdc2bf4e508dd94ef2168296
{ "pile_set_name": "Github" }
package v02 import ( "encoding/json" "net/url" "reflect" "strings" "time" ) // Event implements the the CloudEvents specification version 0.2 // https://github.com/cloudevents/spec/blob/v0.2/spec.md type Event struct { // SpecVersion is a mandatory property // https://github.com/cloudevents/spec/blob/v0.2/spec.md#cloudeventsversion SpecVersion string `json:"specversion" cloudevents:"ce-specversion,required"` // EventType is a mandatory property // https://github.com/cloudevents/spec/blob/v0.2/spec.md#eventtype Type string `json:"type" cloudevents:"ce-type,required"` // Source is a mandatory property // https://github.com/cloudevents/spec/blob/v0.2/spec.md#source Source url.URL `json:"source" cloudevents:"ce-source,required"` // ID is a mandatory property // https://github.com/cloudevents/spec/blob/v0.2/spec.md#eventid ID string `json:"id" cloudevents:"ce-id,required"` // Time is an optional property // https://github.com/cloudevents/spec/blob/v0.2/spec.md#eventtime Time *time.Time `json:"time,omitempty" cloudevents:"ce-time"` // SchemaURL is an optional property // https://github.com/cloudevents/spec/blob/v0.2/spec.md#schemaurl SchemaURL url.URL `json:"schemaurl,omitempty" cloudevents:"ce-schemaurl"` // ContentType is an optional property // https://github.com/cloudevents/spec/blob/v0.2/spec.md#contenttype ContentType string `json:"contenttype,omitempty" cloudevents:"content-type"` // Data is an optional property // https://github.com/cloudevents/spec/blob/v0.2/spec.md#data-1 Data interface{} `json:"data,omitempty" cloudevents:",body"` // extension an internal map for extension properties not defined in the spec extension map[string]interface{} } // CloudEventVersion returns the CloudEvents specification version supported by this implementation func (e Event) CloudEventVersion() (version string) { return e.SpecVersion } // Get gets a CloudEvent property value func (e Event) Get(key string) (interface{}, bool) { t := reflect.TypeOf(e) for i := 0; i < t.NumField(); i++ { // Find a matching field by name, ignoring case if strings.EqualFold(t.Field(i).Name, key) { // return the value of that field return reflect.ValueOf(e).Field(i).Interface(), true } } v, ok := e.extension[strings.ToLower(key)] return v, ok } // GetInt is a convenience method that wraps Get to provide a type checked return value. Ok will be false // if the property does not exist or the value cannot be converted to an int32. func (e Event) GetInt(property string) (value int32, ok bool) { if val, ok := e.Get(property); ok { intVal, ok := val.(int32) return intVal, ok } return 0, false } // GetString is a convenience method that wraps Get to provide a type checked return value. Ok will be false // if the property does not exist or the value cannot be converted to a string. func (e Event) GetString(property string) (value string, ok bool) { if val, ok := e.Get(property); ok { stringVal, ok := val.(string) return stringVal, ok } return "", false } // GetBinary is a convenience method that wraps Get to provide a type checked return value. Ok will be false // if the property does not exist or the value cannot be converted to a binary array. func (e Event) GetBinary(property string) (value []byte, ok bool) { if val, ok := e.Get(property); ok { binaryArrVal, ok := val.([]byte) return binaryArrVal, ok } return []byte(nil), false } // GetMap is a convenience method that wraps Get to provide a type checked return value. Ok will be false // if the property does not exist or the value cannot be converted to a map. func (e Event) GetMap(property string) (value map[string]interface{}, ok bool) { if val, ok := e.Get(property); ok { mapVal, ok := val.(map[string]interface{}) return mapVal, ok } return map[string]interface{}(nil), false } // GetTime is a convenience method that wraps Get to provide a type checked return value. Ok will be false // if the property does not exist or the value cannot be converted or parsed into a time.Time. func (e Event) GetTime(property string) (value *time.Time, ok bool) { raw, ok := e.Get(property) if !ok { return &time.Time{}, false } switch val := raw.(type) { case *time.Time: return val, ok case time.Time: return &val, ok case string: timestamp, err := time.Parse(time.RFC3339, val) if err != nil { return &timestamp, false } return &timestamp, true default: return &time.Time{}, false } } // GetURL is a convenience method that wraps Get to provide a type checked return value. Ok will be false // if the property does not exist or the value cannot be converted or parsed into a url.URL. func (e Event) GetURL(property string) (value url.URL, ok bool) { raw, ok := e.Get(property) if !ok { return url.URL{}, false } switch val := raw.(type) { case url.URL: return val, ok case string: urlVal, err := url.ParseRequestURI(val) if err != nil { return url.URL{}, false } return *urlVal, true default: return url.URL{}, false } } // Set sets a CloudEvent property value. If setting a well known field the type of // value must be assignable to the type of the well known field. func (e *Event) Set(key string, value interface{}) { t := reflect.TypeOf(*e) for i := 0; i < t.NumField(); i++ { // Find a matching field by name, ignoring case if strings.EqualFold(t.Field(i).Name, key) { // set that field to the passed in value reflect.ValueOf(e).Elem().Field(i).Set(reflect.ValueOf(value)) return } } // If no matching field, add value to the extension map, creating the map if nil if e.extension == nil { e.extension = map[string]interface{}{} } e.extension[strings.ToLower(key)] = value } // Properties returns the map of all supported properties in version 0.1. // The map value says whether particular property is required. func (e Event) Properties() map[string]bool { t := reflect.TypeOf(e) props := make(map[string]bool) for i := 0; i < t.NumField(); i++ { field := t.Field(i) required := false if strings.Contains(field.Tag.Get("cloudevents"), "required") { required = true } props[strings.ToLower(field.Name)] = required } return props } type jsonEncodeOpts struct { name string omitempty bool encoded bool ignored bool } // MarshalJSON marshal an event into json func (e Event) MarshalJSON() ([]byte, error) { output := make(map[string]interface{}) t := reflect.TypeOf(e) eventValue := reflect.ValueOf(e) for i := 0; i < t.NumField(); i++ { field := eventValue.Field(i) if !field.CanInterface() { // if cannot access, i.e. extension continue // then ignore it } jsonOpts := parseJSONTag(t.Field(i)) // if tag says field is ignored or omitted when empty if jsonOpts.ignored || (jsonOpts.omitempty && isZero(field, t.Field(i).Type)) { continue // then ignore it } val := field.Interface() if url, ok := val.(url.URL); ok { val = url.String() } output[jsonOpts.name] = val } for k, v := range e.extension { output[k] = v } return json.Marshal(output) } // UnmarshalJSON override default json unmarshall func (e *Event) UnmarshalJSON(b []byte) error { // Unmarshal the raw data into an intermediate map var intermediate map[string]interface{} if err := json.Unmarshal(b, &intermediate); err != nil { return err } t := reflect.TypeOf(*e) target := reflect.New(t).Elem() for i := 0; i < t.NumField(); i++ { targetField := target.Field(i) // allows us to modify the target value if !targetField.CanSet() { // if cannot be set, i.e. extension continue // ignore it } structField := t.Field(i) // contains type info jsonOpts := parseJSONTag(structField) if jsonOpts.ignored { continue } // if prop exists in map convert it and set to the target's field. if mapVal, ok := intermediate[jsonOpts.name]; ok { assignToFieldByType(&targetField, mapVal) } // remove processed field delete(intermediate, jsonOpts.name) } *e = target.Interface().(Event) if len(intermediate) == 0 { return nil } // add any left over fields to the extensions map e.extension = make(map[string]interface{}, len(intermediate)) for k, v := range intermediate { e.extension[k] = v } return nil } func isZero(fieldValue reflect.Value, fieldType reflect.Type) bool { return reflect.DeepEqual(fieldValue.Interface(), reflect.Zero(fieldType).Interface()) } // assignToFieldByType assigns the value to the given field Value converting to the correct type if necessary func assignToFieldByType(field *reflect.Value, value interface{}) error { var val reflect.Value switch field.Type().Kind() { case reflect.TypeOf((*time.Time)(nil)).Kind(): timestamp, err := time.Parse(time.RFC3339, value.(string)) if err != nil { return err } val = reflect.ValueOf(&timestamp) case reflect.TypeOf((*url.URL)(nil)).Elem().Kind(): url, err := url.ParseRequestURI(value.(string)) if err != nil { return err } val = reflect.ValueOf(*url) default: val = reflect.ValueOf(value) } field.Set(val) return nil } func parseJSONTag(field reflect.StructField) jsonEncodeOpts { tag := field.Tag.Get("json") opts := jsonEncodeOpts{} if tag == "-" { opts.ignored = true return opts } options := strings.SplitN(tag, ",", 2) opts.name = options[0] if opts.name == "" { opts.name = field.Name } if len(options) == 1 { return opts } if strings.Contains(options[1], "omitempty") { opts.omitempty = true } if strings.Contains(options[1], "string") { opts.encoded = true } return opts }
{ "pile_set_name": "Github" }
msgid "" msgstr "" "Project-Id-Version: \n" "POT-Creation-Date: \n" "PO-Revision-Date: \n" "Last-Translator: Yann Mérignac <[email protected]>\n" "Language-Team: Vasseur Gilles <[email protected]>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: fr\n" "X-Generator: Poedit 1.8.11\n" #: todoliststrconsts.dlgfiltercsv msgid "CSV files" msgstr "Fichier CSV" #: todoliststrconsts.dlgunitdeprefresh msgid "Refresh" msgstr "Rafraîchir" #: todoliststrconsts.lisctinsertmacro msgid "Insert Macro" msgstr "Insérer une macro" #: todoliststrconsts.lisoptions msgid "Options" msgstr "Options" #: todoliststrconsts.lispackages msgid "Packages" msgstr "Paquets" #: todoliststrconsts.lispackageshint msgid "Extends \"%s\" and \"%s\" options by units from used packages" msgstr "Étendre \"%s\" et les options \"%s\" par unités à partir de paquets utilisés " #: todoliststrconsts.lispkgfiletypetext msgid "Text" msgstr "Texte" #: todoliststrconsts.lissourceeditor msgid "Editor" msgstr "Éditeur" #: todoliststrconsts.lissourceeditorhint msgctxt "todoliststrconsts.lissourceeditorhint" msgid "Add units in source editor" msgstr "Ajouter les unités de l'éditeur de source" #: todoliststrconsts.listddinserttodo msgid "Insert ToDo" msgstr "Insérer une note dans le pense-bête (\"ToDo\")" #: todoliststrconsts.listodoexport msgid "Export" msgstr "Exporter" #: todoliststrconsts.listodogoto msgid "Goto" msgstr "Aller" #: todoliststrconsts.listodoldescription msgid "Description" msgstr "Description" #: todoliststrconsts.listodoldone msgid "Done" msgstr "Fait" #: todoliststrconsts.listodolfile msgid "Module" msgstr "Module" #: todoliststrconsts.listodolist msgid "ToDo List" msgstr "Pense-bête" #: todoliststrconsts.listodolisted msgid "Listed" msgstr "Listé" #: todoliststrconsts.listodolistedhint msgid "Add units listed in project inspector/package editor" msgstr "Ajouter les unités listées dans l'inspecteur de projet/l'éditeur de paquet" #: todoliststrconsts.listodolistgotoline msgid "Goto selected source line" msgstr "Aller à la ligne du code source sélectionné" #: todoliststrconsts.listodolistrefresh msgid "Refresh todo items" msgstr "Rafraîchir le pense-bête" #: todoliststrconsts.listodolline msgid "Line" msgstr "Ligne" #: todoliststrconsts.listodolowner msgid "Owner" msgstr "Propriétaire" #: todoliststrconsts.listodolpriority msgid "Priority" msgstr "Priorité" #: todoliststrconsts.listodoused msgid "Used" msgstr "Utilisé" #: todoliststrconsts.listodousedhint msgid "Add units used by main source file" msgstr "Ajouter les unités utilisées dans le fichier source principal" #: todoliststrconsts.listtodolcategory msgid "Category" msgstr "Catégorie" #: todoliststrconsts.lisviewtodolist msgid "View ToDo List" msgstr "Afficher le pense-bête"
{ "pile_set_name": "Github" }
[Infinite Health] 10A483A4 00000190 [Max Health] 10A483A6 00000190 [Infinite Stamina] 20A4876A 00000074 20A4876B 00000074 [Infinite Suppressor] 2091F2B8 0000001E 2091F278 0000001E [Infinite Battery] 20A4876E 0000002C [Have/Infinite Fork] 1091C8B8 00000001 [Have/Infinite Cig Spray] 1091C8F8 000003E7 [Have/Infinite Handker] 1091C938 000003E7 [Have/Infinite Torch] 1091CCB8 00000001 [Have/Infinite Grenades] 1091CCF8 000003E7 [Have/Infinite White Phosphorous Grenades] 1091CD38 000003E7 [Have/Infinite Stun Grenades] 1091CD78 000003E7 [Have/Infinite Chaff Grenades] 1091CDB8 000003E7 [Have/Infinite Smoke Grenades] 1091CDF8 000003E7 [Have/Infinite Magazines] 1091CE38 000003E7 [Have/Infinite Books] 1091CF38 000003E7 [Have/Infinite Mouse Traps] 1091CF78 000003E7 [HAVE/INFINITE AMMO/NO RELOAD Mk22] 1091C978 000003E7 2091C97C 00000008 [HAVE/INFINITE AMMO/NO RELOAD M1911A1] 1091C9B8 000003E7 2091C9BC 00000008 [HAVE/INFINITE AMMO/NO RELOAD Ez Gun] 1091C9F8 00000001 [HAVE/INFINITE AMMO/NO RELOAD Single Action Army] 1091CA38 000003E7 2091CA3C 00000006 [HAVE/INFINITE AMMO/NO RELOAD Patriot] 1091CA78 00000001 [HAVE/INFINITE AMMO/NO RELOAD Scorpion] 1091CAB8 000003E7 2091CABC 0000001E [HAVE/INFINITE AMMO/NO RELOAD XM16E1] 1091CAF8 000003E7 2091CAFC 00000014 [HAVE/INFINITE AMMO/NO RELOAD AK47] 1091CB38 000003E7 2091CB3C 0000001E [HAVE/INFINITE AMMO/NO RELOAD M63] 1091CB78 000003E7 2091CB7C 00000064 [HAVE/INFINITE AMMO/NO RELOAD Shotgun] 1091CBB8 000003E7 2091CBBC 00000005 [HAVE/INFINITE AMMO/NO RELOAD SVD] 1091CBF8 000003E7 2091CBFC 0000000A [HAVE/INFINITE AMMO/NO RELOAD Mosin Nagant] 1091CC38 000003E7 2091CC3C 0000000A [HAVE/INFINITE AMMO/NO RELOAD RPG-7] 1091CC78 000003E7 2091CC7C 00000001 [HAVE/INFINITE AMMO/NO RELOAD TNT] 1091CE78 000003E7 [HAVE/INFINITE AMMO/NO RELOAD C3] 1091CEB8 000003E7 [HAVE/INFINITE AMMO/NO RELOAD Claymore] 1091CEF8 000003E7 [Have/Infinite Life Medicine] 1091E938 000003E7 [Have/Infinite Pentazemin] 1091E978 000003E7 [Have/Infinite Death Pill] 1091E9B8 000003E7 [Have/Infinite Bug Juice] 1091EEF8 000003E7 [Have Thermal Goggles] 1091EAB8 00000001 [Have Night Vision Goggles] 1091EAF8 00000001 [Have Camera] 1091EB38 00000001 [Have Mine Detector] 1091EBF8 00000001 [Have Cardboard Box A] 1091EC78 00000001 [Have Cardboard Box B] 1091ECB8 00000001 [Have Cardboard Box C] 1091ECF8 00000001 [Have Crocodile Cap] 1091ED78 00000001 [Have Stealth Camouflage] 1091EEB8 00000001 [Have Key A] 1091EDB8 00000001 [Have Key B] 1091EDF8 00000001 [Have Key C] 1091EE38 00000001 [Infinite Ointment] 2091F078 00000063 [Infinite Splint] 2091F0B8 00000063 [Infinite Disinfect] 2091F0F8 00000063 [Infinite Styptic] 2091F138 00000063 [Infinite Bandage] 2091F178 00000063 [Infinite Suture Kit] 2091F1B8 00000063 [Infinite Serum] 2091EF78 00000063 [Infinite Antidote] 2091EFB8 00000063 [Infinite C Med] 2091EFF8 00000063 [Infinite D Med] 2091F038 00000063 [Have Chocco Chip UNIFORM] 1091F438 00000001 [Have Splitter UNIFORM] 1091F478 00000001 [Have Raindrop UNIFORM] 1091F4B8 00000001 [Have Water UNIFORM] 1091f538 00000001 [Have Snow UNIFORM] 1091F5B8 00000001 [Have Sneaking Suite] 1091F638 00000001 [Have Scientist UNIFORM] 1091F678 00000001 [Have Officer UNIFORM] 1091F6B8 00000001 [Have Maintenance Crew Uniform] 1091F6F8 00000001 [Have Tuxedo] 1091F738 00000001 [Have Hornet Stripe UNIFORM] 1091F778 00000001 [Have Spider UNIFORM] 1091F7B8 00000001 [Have Moss UNIFORM] 1091f7f8 00000001 [Have Fire UNIFORM] 1091F838 00000001 [Have Spirit UNIFORM] 1091F878 00000001 [Have Cold War UNIFORM] 1091F8B8 00000001 [Have Snake UNIFORM] 1091F8F8 00000001 [Have Fruit UNIFORM] 1091F938 00000001 [Have Desert Tiger UNIFORM] 1091f978 00000001 [Have DPM UNIFORM] 1091F9B8 00000001 [Have Flecktarn UNIFORM] 1091F9F8 00000001 [Have Auscam Desert UNIFORM] 1091FA38 00000001 [Have Animals UNIFORM] 1091FA78 00000001 [Have Fly UNIFORM] 1091fab8 00000001 [Have Banana UNIFORM] 1091FAF8 00000001 [Have Grenade UNIFORM] 1091FB78 00000001 [Have Water FACE] 1091FCB8 00000001 [Have Desert FACE] 1091FCF8 00000001 [Have Snow FACE] 1091FD78 00000001 [Have Kabuki FACE] 1091FDB8 00000001 [Have Zombie FACE] 1091FDF8 00000001 [Have Oyama FACE] 1091FE38 00000001 [Have Green FACE] 1091FEB8 00000001 [Have Brown FACE] 1091FEF8 00000001 [Have Infinity FACE] 1091FF38 00000001 [Have Soviet FACE] 1091FF78 00000001 [Have UK FACE] 1091FFB8 00000001 [Have France FACE] 1091FFF8 00000001 [Have Germany FACE] 10920038 00000001 [Have Italia FACE] 10920078 00000001 [Have Spain FACE] 109200B8 00000001 [Have Sweden FACE] 109200F8 00000001 [Have Japan FACE] 10920138 00000001 [Have USA FACE] 10920178 00000001 [0 Saves] 20A47D2E 00000000 20A47514 00000000 [0 Playtime] 20A47D45 00000000 20A47511 00000000 [0 Continues] 20A47D2C 00000000 20A47516 00000000 [0 Alerts] 20A47D30 00000000 20A47518 00000000 [0 People Killed] 20A47D32 00000000 20A4751A 00000000 [0 Serious Injuries] 20A47D38 00000000 20A4751C 00000000 [0 Damage Taken] 20A47D3C 00000000 20A47520 00000000 [0 Medicines Used] 20A47522 00000000 [Max Plants/Animals Captured] 10A47D37 000000E7 180039D8 0000270F [0 Meals Eaten] 20A47D3E 00000000 20A4752C 00000000
{ "pile_set_name": "Github" }
{ "name": "@curi-example/data-loading-react", "private": true, "description": "Prefetch data before navigating", "main": "index.js", "keywords": [ "curi", "prefetch", "data", "loading" ], "author": "Paul Sherman", "license": "MIT", "dependencies": { "@curi/react-dom": "2.0.3", "@curi/router": "2.1.1", "@hickory/browser": "^2.1.0", "react": "^16.12.0", "react-dom": "^16.12.0" } }
{ "pile_set_name": "Github" }
// Code generated by smithy-go-codegen DO NOT EDIT. package health import ( "context" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/retry" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" smithy "github.com/awslabs/smithy-go" "github.com/awslabs/smithy-go/middleware" smithyhttp "github.com/awslabs/smithy-go/transport/http" ) // This operation provides status information on enabling or disabling AWS Health // to work with your organization. To call this operation, you must sign in as an // IAM user, assume an IAM role, or sign in as the root user (not recommended) in // the organization's master account. func (c *Client) DescribeHealthServiceStatusForOrganization(ctx context.Context, params *DescribeHealthServiceStatusForOrganizationInput, optFns ...func(*Options)) (*DescribeHealthServiceStatusForOrganizationOutput, error) { stack := middleware.NewStack("DescribeHealthServiceStatusForOrganization", smithyhttp.NewStackRequest) options := c.options.Copy() for _, fn := range optFns { fn(&options) } addawsAwsjson11_serdeOpDescribeHealthServiceStatusForOrganizationMiddlewares(stack) awsmiddleware.AddRequestInvocationIDMiddleware(stack) smithyhttp.AddContentLengthMiddleware(stack) AddResolveEndpointMiddleware(stack, options) v4.AddComputePayloadSHA256Middleware(stack) retry.AddRetryMiddlewares(stack, options) addHTTPSignerV4Middleware(stack, options) awsmiddleware.AddAttemptClockSkewMiddleware(stack) addClientUserAgent(stack) smithyhttp.AddErrorCloseResponseBodyMiddleware(stack) smithyhttp.AddCloseResponseBodyMiddleware(stack) stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeHealthServiceStatusForOrganization(options.Region), middleware.Before) addRequestIDRetrieverMiddleware(stack) addResponseErrorMiddleware(stack) for _, fn := range options.APIOptions { if err := fn(stack); err != nil { return nil, err } } handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) result, metadata, err := handler.Handle(ctx, params) if err != nil { return nil, &smithy.OperationError{ ServiceID: ServiceID, OperationName: "DescribeHealthServiceStatusForOrganization", Err: err, } } out := result.(*DescribeHealthServiceStatusForOrganizationOutput) out.ResultMetadata = metadata return out, nil } type DescribeHealthServiceStatusForOrganizationInput struct { } type DescribeHealthServiceStatusForOrganizationOutput struct { // Information about the status of enabling or disabling AWS Health Organizational // View in your organization. Valid values are ENABLED | DISABLED | PENDING. HealthServiceAccessStatusForOrganization *string // Metadata pertaining to the operation's result. ResultMetadata middleware.Metadata } func addawsAwsjson11_serdeOpDescribeHealthServiceStatusForOrganizationMiddlewares(stack *middleware.Stack) { stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeHealthServiceStatusForOrganization{}, middleware.After) stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeHealthServiceStatusForOrganization{}, middleware.After) } func newServiceMetadataMiddleware_opDescribeHealthServiceStatusForOrganization(region string) awsmiddleware.RegisterServiceMetadata { return awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "health", OperationName: "DescribeHealthServiceStatusForOrganization", } }
{ "pile_set_name": "Github" }
import makeColourObject from './convert' import convert from '../helpers/convert-to-type' export default function shade (shift, colourRef) { var colour = convert('hsv', colourRef) colour.v += shift if (colour.v < 0) { colour.v = 0 } else if (colour.v > 100) { colour.v = 100 } return makeColourObject(colour) }
{ "pile_set_name": "Github" }
// Copyright 2013 The go-github AUTHORS. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package github import ( "encoding/json" "fmt" "net/http" "reflect" "testing" ) func TestRepositoriesService_List_authenticatedUser(t *testing.T) { setup() defer teardown() mux.HandleFunc("/user/repos", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") fmt.Fprint(w, `[{"id":1},{"id":2}]`) }) repos, _, err := client.Repositories.List("", nil) if err != nil { t.Errorf("Repositories.List returned error: %v", err) } want := []Repository{{ID: Int(1)}, {ID: Int(2)}} if !reflect.DeepEqual(repos, want) { t.Errorf("Repositories.List returned %+v, want %+v", repos, want) } } func TestRepositoriesService_List_specifiedUser(t *testing.T) { setup() defer teardown() mux.HandleFunc("/users/u/repos", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") testFormValues(t, r, values{ "type": "owner", "sort": "created", "direction": "asc", "page": "2", }) fmt.Fprint(w, `[{"id":1}]`) }) opt := &RepositoryListOptions{"owner", "created", "asc", ListOptions{Page: 2}} repos, _, err := client.Repositories.List("u", opt) if err != nil { t.Errorf("Repositories.List returned error: %v", err) } want := []Repository{{ID: Int(1)}} if !reflect.DeepEqual(repos, want) { t.Errorf("Repositories.List returned %+v, want %+v", repos, want) } } func TestRepositoriesService_List_invalidUser(t *testing.T) { _, _, err := client.Repositories.List("%", nil) testURLParseError(t, err) } func TestRepositoriesService_ListByOrg(t *testing.T) { setup() defer teardown() mux.HandleFunc("/orgs/o/repos", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") testFormValues(t, r, values{ "type": "forks", "page": "2", }) fmt.Fprint(w, `[{"id":1}]`) }) opt := &RepositoryListByOrgOptions{"forks", ListOptions{Page: 2}} repos, _, err := client.Repositories.ListByOrg("o", opt) if err != nil { t.Errorf("Repositories.ListByOrg returned error: %v", err) } want := []Repository{{ID: Int(1)}} if !reflect.DeepEqual(repos, want) { t.Errorf("Repositories.ListByOrg returned %+v, want %+v", repos, want) } } func TestRepositoriesService_ListByOrg_invalidOrg(t *testing.T) { _, _, err := client.Repositories.ListByOrg("%", nil) testURLParseError(t, err) } func TestRepositoriesService_ListAll(t *testing.T) { setup() defer teardown() mux.HandleFunc("/repositories", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") testFormValues(t, r, values{ "since": "1", "page": "2", "per_page": "3", }) fmt.Fprint(w, `[{"id":1}]`) }) opt := &RepositoryListAllOptions{1, ListOptions{2, 3}} repos, _, err := client.Repositories.ListAll(opt) if err != nil { t.Errorf("Repositories.ListAll returned error: %v", err) } want := []Repository{{ID: Int(1)}} if !reflect.DeepEqual(repos, want) { t.Errorf("Repositories.ListAll returned %+v, want %+v", repos, want) } } func TestRepositoriesService_Create_user(t *testing.T) { setup() defer teardown() input := &Repository{Name: String("n")} mux.HandleFunc("/user/repos", func(w http.ResponseWriter, r *http.Request) { v := new(Repository) json.NewDecoder(r.Body).Decode(v) testMethod(t, r, "POST") if !reflect.DeepEqual(v, input) { t.Errorf("Request body = %+v, want %+v", v, input) } fmt.Fprint(w, `{"id":1}`) }) repo, _, err := client.Repositories.Create("", input) if err != nil { t.Errorf("Repositories.Create returned error: %v", err) } want := &Repository{ID: Int(1)} if !reflect.DeepEqual(repo, want) { t.Errorf("Repositories.Create returned %+v, want %+v", repo, want) } } func TestRepositoriesService_Create_org(t *testing.T) { setup() defer teardown() input := &Repository{Name: String("n")} mux.HandleFunc("/orgs/o/repos", func(w http.ResponseWriter, r *http.Request) { v := new(Repository) json.NewDecoder(r.Body).Decode(v) testMethod(t, r, "POST") if !reflect.DeepEqual(v, input) { t.Errorf("Request body = %+v, want %+v", v, input) } fmt.Fprint(w, `{"id":1}`) }) repo, _, err := client.Repositories.Create("o", input) if err != nil { t.Errorf("Repositories.Create returned error: %v", err) } want := &Repository{ID: Int(1)} if !reflect.DeepEqual(repo, want) { t.Errorf("Repositories.Create returned %+v, want %+v", repo, want) } } func TestRepositoriesService_Create_invalidOrg(t *testing.T) { _, _, err := client.Repositories.Create("%", nil) testURLParseError(t, err) } func TestRepositoriesService_Get(t *testing.T) { setup() defer teardown() mux.HandleFunc("/repos/o/r", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") fmt.Fprint(w, `{"id":1,"name":"n","description":"d","owner":{"login":"l"}}`) }) repo, _, err := client.Repositories.Get("o", "r") if err != nil { t.Errorf("Repositories.Get returned error: %v", err) } want := &Repository{ID: Int(1), Name: String("n"), Description: String("d"), Owner: &User{Login: String("l")}} if !reflect.DeepEqual(repo, want) { t.Errorf("Repositories.Get returned %+v, want %+v", repo, want) } } func TestRepositoriesService_Edit(t *testing.T) { setup() defer teardown() i := true input := &Repository{HasIssues: &i} mux.HandleFunc("/repos/o/r", func(w http.ResponseWriter, r *http.Request) { v := new(Repository) json.NewDecoder(r.Body).Decode(v) testMethod(t, r, "PATCH") if !reflect.DeepEqual(v, input) { t.Errorf("Request body = %+v, want %+v", v, input) } fmt.Fprint(w, `{"id":1}`) }) repo, _, err := client.Repositories.Edit("o", "r", input) if err != nil { t.Errorf("Repositories.Edit returned error: %v", err) } want := &Repository{ID: Int(1)} if !reflect.DeepEqual(repo, want) { t.Errorf("Repositories.Edit returned %+v, want %+v", repo, want) } } func TestRepositoriesService_Delete(t *testing.T) { setup() defer teardown() mux.HandleFunc("/repos/o/r", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") }) _, err := client.Repositories.Delete("o", "r") if err != nil { t.Errorf("Repositories.Delete returned error: %v", err) } } func TestRepositoriesService_Get_invalidOwner(t *testing.T) { _, _, err := client.Repositories.Get("%", "r") testURLParseError(t, err) } func TestRepositoriesService_Edit_invalidOwner(t *testing.T) { _, _, err := client.Repositories.Edit("%", "r", nil) testURLParseError(t, err) } func TestRepositoriesService_ListContributors(t *testing.T) { setup() defer teardown() mux.HandleFunc("/repos/o/r/contributors", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") testFormValues(t, r, values{ "anon": "true", "page": "2", }) fmt.Fprint(w, `[{"contributions":42}]`) }) opts := &ListContributorsOptions{Anon: "true", ListOptions: ListOptions{Page: 2}} contributors, _, err := client.Repositories.ListContributors("o", "r", opts) if err != nil { t.Errorf("Repositories.ListContributors returned error: %v", err) } want := []Contributor{{Contributions: Int(42)}} if !reflect.DeepEqual(contributors, want) { t.Errorf("Repositories.ListContributors returned %+v, want %+v", contributors, want) } } func TestRepositoriesService_ListLanguages(t *testing.T) { setup() defer teardown() mux.HandleFunc("/repos/o/r/languages", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") fmt.Fprint(w, `{"go":1}`) }) languages, _, err := client.Repositories.ListLanguages("o", "r") if err != nil { t.Errorf("Repositories.ListLanguages returned error: %v", err) } want := map[string]int{"go": 1} if !reflect.DeepEqual(languages, want) { t.Errorf("Repositories.ListLanguages returned %+v, want %+v", languages, want) } } func TestRepositoriesService_ListTeams(t *testing.T) { setup() defer teardown() mux.HandleFunc("/repos/o/r/teams", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") testFormValues(t, r, values{"page": "2"}) fmt.Fprint(w, `[{"id":1}]`) }) opt := &ListOptions{Page: 2} teams, _, err := client.Repositories.ListTeams("o", "r", opt) if err != nil { t.Errorf("Repositories.ListTeams returned error: %v", err) } want := []Team{{ID: Int(1)}} if !reflect.DeepEqual(teams, want) { t.Errorf("Repositories.ListTeams returned %+v, want %+v", teams, want) } } func TestRepositoriesService_ListTags(t *testing.T) { setup() defer teardown() mux.HandleFunc("/repos/o/r/tags", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") testFormValues(t, r, values{"page": "2"}) fmt.Fprint(w, `[{"name":"n", "commit" : {"sha" : "s", "url" : "u"}, "zipball_url": "z", "tarball_url": "t"}]`) }) opt := &ListOptions{Page: 2} tags, _, err := client.Repositories.ListTags("o", "r", opt) if err != nil { t.Errorf("Repositories.ListTags returned error: %v", err) } want := []RepositoryTag{ { Name: String("n"), Commit: &Commit{ SHA: String("s"), URL: String("u"), }, ZipballURL: String("z"), TarballURL: String("t"), }, } if !reflect.DeepEqual(tags, want) { t.Errorf("Repositories.ListTags returned %+v, want %+v", tags, want) } } func TestRepositoriesService_ListBranches(t *testing.T) { setup() defer teardown() mux.HandleFunc("/repos/o/r/branches", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") testFormValues(t, r, values{"page": "2"}) fmt.Fprint(w, `[{"name":"master", "commit" : {"sha" : "a57781", "url" : "https://api.github.com/repos/o/r/commits/a57781"}}]`) }) opt := &ListOptions{Page: 2} branches, _, err := client.Repositories.ListBranches("o", "r", opt) if err != nil { t.Errorf("Repositories.ListBranches returned error: %v", err) } want := []Branch{{Name: String("master"), Commit: &Commit{SHA: String("a57781"), URL: String("https://api.github.com/repos/o/r/commits/a57781")}}} if !reflect.DeepEqual(branches, want) { t.Errorf("Repositories.ListBranches returned %+v, want %+v", branches, want) } } func TestRepositoriesService_GetBranch(t *testing.T) { setup() defer teardown() mux.HandleFunc("/repos/o/r/branches/b", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") fmt.Fprint(w, `{"name":"n", "commit":{"sha":"s"}}`) }) branch, _, err := client.Repositories.GetBranch("o", "r", "b") if err != nil { t.Errorf("Repositories.GetBranch returned error: %v", err) } want := &Branch{Name: String("n"), Commit: &Commit{SHA: String("s")}} if !reflect.DeepEqual(branch, want) { t.Errorf("Repositories.GetBranch returned %+v, want %+v", branch, want) } } func TestRepositoriesService_ListLanguages_invalidOwner(t *testing.T) { _, _, err := client.Repositories.ListLanguages("%", "%") testURLParseError(t, err) }
{ "pile_set_name": "Github" }
10 predictions NOM: 0.0 0.0 1.0 0.9999995409941143 4.5900588572256467E-7 NOM: 1.0 1.0 1.0 0.1699828189660011 0.8300171810339988 NOM: 1.0 1.0 1.0 6.768172301029505E-12 0.9999999999932319 NOM: 0.0 0.0 1.0 0.9999997310642107 2.68935789348773E-7 NOM: 1.0 1.0 1.0 0.1699828189660011 0.8300171810339988 NOM: 0.0 0.0 1.0 0.7074431173096629 0.29255688269033703 NOM: 1.0 1.0 1.0 0.1699828189660011 0.8300171810339988 NOM: 0.0 0.0 1.0 0.9999997965277552 2.034722448440416E-7 NOM: 0.0 0.0 1.0 0.6408909507563209 0.35910904924367926 NOM: 1.0 1.0 1.0 1.0346935709664646E-7 0.9999998965306429
{ "pile_set_name": "Github" }
#pragma once #include <eosio/testing/tester.hpp> namespace eosio { namespace testing { struct contracts { static std::vector<uint8_t> system_wasm() { return read_wasm("${CMAKE_BINARY_DIR}/../eosio.system/eosio.system.wasm"); } static std::string system_wast() { return read_wast("${CMAKE_BINARY_DIR}/../eosio.system/eosio.system.wast"); } static std::vector<char> system_abi() { return read_abi("${CMAKE_BINARY_DIR}/../eosio.system/eosio.system.abi"); } static std::vector<uint8_t> token_wasm() { return read_wasm("${CMAKE_BINARY_DIR}/../eosio.token/eosio.token.wasm"); } static std::string token_wast() { return read_wast("${CMAKE_BINARY_DIR}/../eosio.token/eosio.token.wast"); } static std::vector<char> token_abi() { return read_abi("${CMAKE_BINARY_DIR}/../eosio.token/eosio.token.abi"); } static std::vector<uint8_t> msig_wasm() { return read_wasm("${CMAKE_BINARY_DIR}/../eosio.msig/eosio.msig.wasm"); } static std::string msig_wast() { return read_wast("${CMAKE_BINARY_DIR}/../eosio.msig/eosio.msig.wast"); } static std::vector<char> msig_abi() { return read_abi("${CMAKE_BINARY_DIR}/../eosio.msig/eosio.msig.abi"); } static std::vector<uint8_t> wrap_wasm() { return read_wasm("${CMAKE_BINARY_DIR}/../eosio.wrap/eosio.wrap.wasm"); } static std::string wrap_wast() { return read_wast("${CMAKE_BINARY_DIR}/../eosio.wrap/eosio.wrap.wast"); } static std::vector<char> wrap_abi() { return read_abi("${CMAKE_BINARY_DIR}/../eosio.wrap/eosio.wrap.abi"); } static std::vector<uint8_t> bios_wasm() { return read_wasm("${CMAKE_BINARY_DIR}/../eosio.bios/eosio.bios.wasm"); } static std::string bios_wast() { return read_wast("${CMAKE_BINARY_DIR}/../eosio.bios/eosio.bios.wast"); } static std::vector<char> bios_abi() { return read_abi("${CMAKE_BINARY_DIR}/../eosio.bios/eosio.bios.abi"); } static std::vector<uint8_t> nft_wasm() { return read_wasm("${CMAKE_BINARY_DIR}/../eosio.nft/eosio.nft.wasm"); } static std::string nft_wast() { return read_wast("${CMAKE_BINARY_DIR}/../eosio.nft/eosio.nft.wast"); } static std::vector<char> nft_abi() { return read_abi("${CMAKE_BINARY_DIR}/../eosio.nft/eosio.nft.abi"); } struct util { static std::vector<uint8_t> test_api_wasm() { return read_wasm("${CMAKE_SOURCE_DIR}/test_contracts/test_api.wasm"); } static std::vector<uint8_t> exchange_wasm() { return read_wasm("${CMAKE_SOURCE_DIR}/test_contracts/exchange.wasm"); } static std::vector<uint8_t> system_wasm_old() { return read_wasm("${CMAKE_SOURCE_DIR}/test_contracts/eosio.system.old/eosio.system.wasm"); } static std::vector<char> system_abi_old() { return read_abi("${CMAKE_SOURCE_DIR}/test_contracts/eosio.system.old/eosio.system.abi"); } static std::vector<uint8_t> msig_wasm_old() { return read_wasm("${CMAKE_SOURCE_DIR}/test_contracts/eosio.msig.old/eosio.msig.wasm"); } static std::vector<char> msig_abi_old() { return read_abi("${CMAKE_SOURCE_DIR}/test_contracts/eosio.msig.old/eosio.msig.abi"); } }; }; }} //ns eosio::testing
{ "pile_set_name": "Github" }
echo T.getline: test getline function awk=${awk-../a.out} who >foo1 cat foo1 | $awk ' BEGIN { while (getline) print exit } ' >foo cmp -s foo1 foo || echo 'BAD: T.getline (bare getline)' who >foo1 cat foo1 | $awk ' BEGIN { while (getline xxx) print xxx exit } ' >foo cmp -s foo1 foo || echo 'BAD: T.getline (getline xxx)' $awk ' BEGIN { while (getline <"/etc/passwd") print exit } ' >foo cmp -s /etc/passwd foo || echo 'BAD: T.getline (getline <file)' cat /etc/passwd | $awk ' BEGIN { while (getline <"-") # stdin print exit } ' >foo cmp -s /etc/passwd foo || echo 'BAD: T.getline (getline <"-")' $awk ' BEGIN { while (getline <ARGV[1]) print exit } ' /etc/passwd >foo cmp -s /etc/passwd foo || echo 'BAD: T.getline (getline <arg)' $awk ' BEGIN { while (getline x <ARGV[1]) print x exit } ' /etc/passwd >foo cmp -s /etc/passwd foo || echo 'BAD: T.getline (getline x <arg)' $awk ' BEGIN { while (("cat " ARGV[1]) | getline) print exit } ' /etc/passwd >foo cmp -s /etc/passwd foo || echo 'BAD: T.getline (cat arg | getline)' $awk ' BEGIN { while (("cat " ARGV[1]) | getline x) print x exit } ' /etc/passwd >foo cmp -s /etc/passwd foo || echo 'BAD: T.getline (cat arg | getline x)' $awk ' BEGIN { print getline <"/glop/glop/glop" } ' >foo echo '-1' >foo1 cmp -s foo foo1 || echo 'BAD: T.getline (non-existent file)' echo 'false false equal' >foo1 $awk 'BEGIN { "echo 0" | getline if ($0) printf "true " else printf "false " if ($1) printf "true " else printf "false " if ($0==$1) printf "equal\n" else printf "not equal\n" }' >foo2 cmp -s foo1 foo2 || echo 1>&2 'BAD: T.getline bad $0 type in cmd|getline' echo 'L1 L2' | $awk 'BEGIN { $0="old stuff"; $1="new"; getline x; print}' >foo1 echo 'new stuff' >foo2 cmp -s foo1 foo2 || echo 1>&2 'BAD: T.getline bad update $0'
{ "pile_set_name": "Github" }
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved #pragma once class SoundFileReader { public: SoundFileReader(_In_ Platform::String^ soundFileName); Platform::Array<byte>^ GetSoundData() const; WAVEFORMATEX* GetSoundFormat() const; private: Platform::Array<byte>^ m_soundData; Platform::Array<byte>^ m_soundFormat; };
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- """ pygments.styles.fruity ~~~~~~~~~~~~~~~~~~~~~~ pygments version of my "fruity" vim theme. :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Token, Comment, Name, Keyword, \ Generic, Number, String, Whitespace class FruityStyle(Style): """ Pygments version of the "native" vim theme. """ background_color = '#111111' highlight_color = '#333333' styles = { Whitespace: '#888888', Token: '#ffffff', Generic.Output: '#444444 bg:#222222', Keyword: '#fb660a bold', Keyword.Pseudo: 'nobold', Number: '#0086f7 bold', Name.Tag: '#fb660a bold', Name.Variable: '#fb660a', Comment: '#008800 bg:#0f140f italic', Name.Attribute: '#ff0086 bold', String: '#0086d2', Name.Function: '#ff0086 bold', Generic.Heading: '#ffffff bold', Keyword.Type: '#cdcaa9 bold', Generic.Subheading: '#ffffff bold', Name.Constant: '#0086d2', Comment.Preproc: '#ff0007 bold' }
{ "pile_set_name": "Github" }
RTOS Task Review ======================= Task name: KePFg8-arm-trampoline Version reviewed: d3bfd0a5864cb6f621c69561f55611eb2726b685 Reviewer: stg Date: 2013-01-21 Conclusion: Accepted
{ "pile_set_name": "Github" }
package com.github.kfcfans.powerjob.worker.core.tracker.task; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.util.List; import java.util.Map; import java.util.function.Function; /** * 持有 TaskTracker 对象 * * @author tjq * @since 2020/3/24 */ public class TaskTrackerPool { private static final Map<Long, TaskTracker> instanceId2TaskTracker = Maps.newConcurrentMap(); /** * 获取 TaskTracker */ public static TaskTracker getTaskTrackerPool(Long instanceId) { return instanceId2TaskTracker.get(instanceId); } public static TaskTracker remove(Long instanceId) { return instanceId2TaskTracker.remove(instanceId); } public static void atomicCreateTaskTracker(Long instanceId, Function<Long, TaskTracker> creator) { instanceId2TaskTracker.computeIfAbsent(instanceId, creator); } public static List<Long> getAllFrequentTaskTrackerKeys() { List<Long> keys = Lists.newLinkedList(); instanceId2TaskTracker.forEach((key, tk) -> { if (tk instanceof FrequentTaskTracker) { keys.add(key); } }); return keys; } }
{ "pile_set_name": "Github" }
# ST Microelectronics STM32 all MCU lines # Copyright (c) 2017, I-SENSE group of ICCS # SPDX-License-Identifier: Apache-2.0 # Here are set all the Kconfig symbols common to the whole STM32 family if SOC_FAMILY_STM32 config CORTEX_M_SYSTICK bool default n if STM32_LPTIM_TIMER default y if !STM32_LPTIM_TIMER config CLOCK_CONTROL_STM32_CUBE default y depends on CLOCK_CONTROL config UART_STM32 default y depends on SERIAL if GPIO config GPIO_STM32 default y endif # GPIO config PINMUX_STM32 default y depends on PINMUX if WATCHDOG config IWDG_STM32 default y config WWDG_STM32 default n endif # WATCHDOG config PWM_STM32 default y depends on PWM config SPI_STM32 default y depends on SPI config USB_DC_STM32 default y depends on USB config COUNTER_RTC_STM32 default y depends on COUNTER config CAN_STM32 default y depends on CAN config ADC_STM32 default y depends on ADC if DMA config DMA_STM32 default y config HEAP_MEM_POOL_SIZE default 1024 endif # DMA endif # SOC_FAMILY_STM32
{ "pile_set_name": "Github" }
{ "images" : [ { "idiom" : "universal", "scale" : "1x" }, { "idiom" : "universal", "filename" : "[email protected]", "scale" : "2x" }, { "idiom" : "universal", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } }
{ "pile_set_name": "Github" }
/** * Random Password * @description Base64 随机密码串 * * @param {Number} size 密码长度 * @return {String} * */ export const randomPassword = (size) => { const seed = new Array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z', 'a','b','c','d','e','f','g','h','i','j','k','m','n','p','Q','r','s','t','u','v','w','x','y','z', '2','3','4','5','6','7','8','9' ) let seedlength = seed.length let createPassword = '' let j for (let i=0; i < size; i++) { j = Math.floor(Math.random() * seedlength) createPassword += seed[j] } return createPassword } import moment from 'moment' /** * Date Parse */ export const dateParse = (str, format) => { if (typeof str != 'string') { return str } return moment(str, format).toString() } /** * Date Format */ export const dateFormat = (str, format) => { str = str || new Date() return moment(str).format(format) }
{ "pile_set_name": "Github" }
/* * Copyright 2000-2020 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.flow.server.communication; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.vaadin.flow.server.BootstrapHandler; import com.vaadin.flow.server.PwaIcon; import com.vaadin.flow.server.PwaRegistry; import com.vaadin.flow.server.RequestHandler; import com.vaadin.flow.server.VaadinRequest; import com.vaadin.flow.server.VaadinResponse; import com.vaadin.flow.server.VaadinSession; /** * Handles serving of PWA resources. * * Resources include: * <ul> * <li>manifest * <li>service worker * <li>offline fallback page * <li>icons * </ul> * * @since 1.2 */ public class PwaHandler implements RequestHandler { private final Map<String, RequestHandler> requestHandlerMap = new HashMap<>(); private final PwaRegistry pwaRegistry; /** * Creates PwaHandler from {@link PwaRegistry}. * * Sets up handling for icons, manifest, service worker and offline page. * * @param pwaRegistry * registry for PWA */ public PwaHandler(PwaRegistry pwaRegistry) { this.pwaRegistry = pwaRegistry; init(); } private void init() { // Don't init handlers, if not enabled if (!pwaRegistry.getPwaConfiguration().isEnabled()) { return; } // Icon handling for (PwaIcon icon : pwaRegistry.getIcons()) { requestHandlerMap.put(icon.getRelHref(), (session, request, response) -> { response.setContentType(icon.getType()); // Icon is cached with service worker, deny browser // caching if (icon.shouldBeCached()) { response.setHeader("Cache-Control", "no-cache, must-revalidate"); } try (OutputStream out = response.getOutputStream()) { icon.write(out); } return true; }); } // Offline page handling requestHandlerMap.put( pwaRegistry.getPwaConfiguration().relOfflinePath(), (session, request, response) -> { response.setContentType("text/html"); try (PrintWriter writer = response.getWriter()) { writer.write(pwaRegistry.getOfflineHtml()); } return true; }); // manifest.webmanifest handling requestHandlerMap.put( pwaRegistry.getPwaConfiguration().relManifestPath(), (session, request, response) -> { response.setContentType("application/manifest+json"); try (PrintWriter writer = response.getWriter()) { writer.write(pwaRegistry.getManifestJson()); } return true; }); // serviceworker.js handling requestHandlerMap.put( pwaRegistry.getPwaConfiguration().relServiceWorkerPath(), (session, request, response) -> { response.setContentType("application/javascript"); try (PrintWriter writer = response.getWriter()) { writer.write(pwaRegistry.getServiceWorkerJs()); } return true; }); } @Override public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException { String requestUri = request.getPathInfo(); if (pwaRegistry.getPwaConfiguration().isEnabled()) { if (requestHandlerMap.containsKey(requestUri)) { return requestHandlerMap.get(requestUri).handleRequest(session, request, response); } else if (requestUri != null && requestUri .startsWith("/" + PwaRegistry.WORKBOX_FOLDER)) { // allow only files under workbox_folder String resourceName = PwaRegistry.WORKBOX_FOLDER + requestUri // remove the extra '/' .substring(PwaRegistry.WORKBOX_FOLDER.length() + 1) .replaceAll("/", ""); return handleWorkboxResource(resourceName, response); } } return false; } private boolean handleWorkboxResource(String fileName, VaadinResponse response) { try (InputStream stream = BootstrapHandler.class .getResourceAsStream(fileName); InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);) { PrintWriter writer = response.getWriter(); if (fileName.endsWith(".js")) { response.setContentType("application/javascript"); } else { response.setContentType("text/plain"); } final char[] buffer = new char[1024]; int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } return true; } catch (NullPointerException e) { getLogger().debug("Workbox file '{}' does not exist", fileName, e); return false; } catch (IOException e) { getLogger().warn("Error while reading workbox file '{}'", fileName, e); return false; } } private static Logger getLogger() { return LoggerFactory.getLogger(PwaHandler.class); } }
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace MVCTaxonomyPickerWeb { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
{ "pile_set_name": "Github" }
describe("module:ng.directive:ngChecked", function() { var rootEl; beforeEach(function() { rootEl = browser.rootEl; browser.get("./examples/example-example7/index-jquery.html"); }); it('should check both checkBoxes', function() { expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy(); element(by.model('master')).click(); expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy(); }); });
{ "pile_set_name": "Github" }
// // AnonymousObserver.swift // Rx // // Created by Krunoslav Zaher on 2/8/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class AnonymousObserver<ElementType> : ObserverBase<ElementType> { typealias Element = ElementType typealias EventHandler = Event<Element> -> Void private let _eventHandler : EventHandler init(_ eventHandler: EventHandler) { #if TRACE_RESOURCES AtomicIncrement(&resourceCount) #endif _eventHandler = eventHandler } override func onCore(event: Event<Element>) { return _eventHandler(event) } #if TRACE_RESOURCES deinit { AtomicDecrement(&resourceCount) } #endif }
{ "pile_set_name": "Github" }
# This file is distributed under the same license as the Django package. # # Translators: # Jannis Leidel <[email protected]>, 2011. # Tran Van <[email protected]>, 2011. msgid "" msgstr "" "Project-Id-Version: Django\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2012-10-15 10:57+0200\n" "PO-Revision-Date: 2012-02-14 13:40+0000\n" "Last-Translator: Tran Van <[email protected]>\n" "Language-Team: Vietnamese (http://www.transifex.com/projects/p/django/" "language/vi/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: vi\n" "Plural-Forms: nplurals=1; plural=0;\n" #: models.py:38 msgid "session key" msgstr "Mã phiên" #: models.py:40 msgid "session data" msgstr "Dữ liệu phiên" #: models.py:41 msgid "expire date" msgstr "Ngày hết hạn" #: models.py:46 msgid "session" msgstr "Phiên" #: models.py:47 msgid "sessions" msgstr "Phiên"
{ "pile_set_name": "Github" }
// underlying_type.hpp ---------------------------------------------------------// // Copyright Beman Dawes, 2009 // Copyright (C) 2011-2012 Vicente J. Botet Escriba // Copyright (C) 2012 Anthony Williams // Copyright (C) 2014 Andrey Semashev // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt #ifndef BOOST_CORE_UNDERLYING_TYPE_HPP #define BOOST_CORE_UNDERLYING_TYPE_HPP #include <boost/config.hpp> // GCC 4.7 and later seem to provide std::underlying_type #if !defined(BOOST_NO_CXX11_HDR_TYPE_TRAITS) || (defined(BOOST_GCC) && BOOST_GCC >= 40700 && defined(__GXX_EXPERIMENTAL_CXX0X__)) #include <type_traits> #define BOOST_DETAIL_HAS_STD_UNDERLYING_TYPE #endif #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif namespace boost { namespace detail { template< typename EnumType, typename Void = void > struct underlying_type_impl; #if defined(BOOST_NO_CXX11_SCOPED_ENUMS) // Support for boost/core/scoped_enum.hpp template< typename EnumType > struct underlying_type_impl< EnumType, typename EnumType::is_boost_scoped_enum_tag > { /** * The member typedef type names the underlying type of EnumType. It is EnumType::underlying_type when the EnumType is an emulated scoped enum, */ typedef typename EnumType::underlying_type type; }; #endif #if defined(BOOST_DETAIL_HAS_STD_UNDERLYING_TYPE) template< typename EnumType, typename Void > struct underlying_type_impl { typedef typename std::underlying_type< EnumType >::type type; }; #endif } // namespace detail #if !defined(BOOST_NO_CXX11_SCOPED_ENUMS) && !defined(BOOST_DETAIL_HAS_STD_UNDERLYING_TYPE) #define BOOST_NO_UNDERLYING_TYPE #endif /** * Meta-function to get the underlying type of a scoped enum. * * Requires EnumType must be an enum type or the emulation of a scoped enum. * If BOOST_NO_UNDERLYING_TYPE is defined, the implementation will not be able * to deduce the underlying type of enums. The user is expected to specialize * this trait in this case. */ template< typename EnumType > struct underlying_type : public detail::underlying_type_impl< EnumType > { }; } // namespace boost #endif // BOOST_CORE_UNDERLYING_TYPE_HPP
{ "pile_set_name": "Github" }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../javascript/javascript"), require("../css/css"), require("../htmlmixed/htmlmixed")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../javascript/javascript", "../css/css", "../htmlmixed/htmlmixed"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode('jade', function (config) { // token types var KEYWORD = 'keyword'; var DOCTYPE = 'meta'; var ID = 'builtin'; var CLASS = 'qualifier'; var ATTRS_NEST = { '{': '}', '(': ')', '[': ']' }; var jsMode = CodeMirror.getMode(config, 'javascript'); function State() { this.javaScriptLine = false; this.javaScriptLineExcludesColon = false; this.javaScriptArguments = false; this.javaScriptArgumentsDepth = 0; this.isInterpolating = false; this.interpolationNesting = 0; this.jsState = jsMode.startState(); this.restOfLine = ''; this.isIncludeFiltered = false; this.isEach = false; this.lastTag = ''; this.scriptType = ''; // Attributes Mode this.isAttrs = false; this.attrsNest = []; this.inAttributeName = true; this.attributeIsType = false; this.attrValue = ''; // Indented Mode this.indentOf = Infinity; this.indentToken = ''; this.innerMode = null; this.innerState = null; this.innerModeForLine = false; } /** * Safely copy a state * * @return {State} */ State.prototype.copy = function () { var res = new State(); res.javaScriptLine = this.javaScriptLine; res.javaScriptLineExcludesColon = this.javaScriptLineExcludesColon; res.javaScriptArguments = this.javaScriptArguments; res.javaScriptArgumentsDepth = this.javaScriptArgumentsDepth; res.isInterpolating = this.isInterpolating; res.interpolationNesting = this.intpolationNesting; res.jsState = CodeMirror.copyState(jsMode, this.jsState); res.innerMode = this.innerMode; if (this.innerMode && this.innerState) { res.innerState = CodeMirror.copyState(this.innerMode, this.innerState); } res.restOfLine = this.restOfLine; res.isIncludeFiltered = this.isIncludeFiltered; res.isEach = this.isEach; res.lastTag = this.lastTag; res.scriptType = this.scriptType; res.isAttrs = this.isAttrs; res.attrsNest = this.attrsNest.slice(); res.inAttributeName = this.inAttributeName; res.attributeIsType = this.attributeIsType; res.attrValue = this.attrValue; res.indentOf = this.indentOf; res.indentToken = this.indentToken; res.innerModeForLine = this.innerModeForLine; return res; }; function javaScript(stream, state) { if (stream.sol()) { // if javaScriptLine was set at end of line, ignore it state.javaScriptLine = false; state.javaScriptLineExcludesColon = false; } if (state.javaScriptLine) { if (state.javaScriptLineExcludesColon && stream.peek() === ':') { state.javaScriptLine = false; state.javaScriptLineExcludesColon = false; return; } var tok = jsMode.token(stream, state.jsState); if (stream.eol()) state.javaScriptLine = false; return tok || true; } } function javaScriptArguments(stream, state) { if (state.javaScriptArguments) { if (state.javaScriptArgumentsDepth === 0 && stream.peek() !== '(') { state.javaScriptArguments = false; return; } if (stream.peek() === '(') { state.javaScriptArgumentsDepth++; } else if (stream.peek() === ')') { state.javaScriptArgumentsDepth--; } if (state.javaScriptArgumentsDepth === 0) { state.javaScriptArguments = false; return; } var tok = jsMode.token(stream, state.jsState); return tok || true; } } function yieldStatement(stream) { if (stream.match(/^yield\b/)) { return 'keyword'; } } function doctype(stream) { if (stream.match(/^(?:doctype) *([^\n]+)?/)) { return DOCTYPE; } } function interpolation(stream, state) { if (stream.match('#{')) { state.isInterpolating = true; state.interpolationNesting = 0; return 'punctuation'; } } function interpolationContinued(stream, state) { if (state.isInterpolating) { if (stream.peek() === '}') { state.interpolationNesting--; if (state.interpolationNesting < 0) { stream.next(); state.isInterpolating = false; return 'puncutation'; } } else if (stream.peek() === '{') { state.interpolationNesting++; } return jsMode.token(stream, state.jsState) || true; } } function caseStatement(stream, state) { if (stream.match(/^case\b/)) { state.javaScriptLine = true; return KEYWORD; } } function when(stream, state) { if (stream.match(/^when\b/)) { state.javaScriptLine = true; state.javaScriptLineExcludesColon = true; return KEYWORD; } } function defaultStatement(stream) { if (stream.match(/^default\b/)) { return KEYWORD; } } function extendsStatement(stream, state) { if (stream.match(/^extends?\b/)) { state.restOfLine = 'string'; return KEYWORD; } } function append(stream, state) { if (stream.match(/^append\b/)) { state.restOfLine = 'variable'; return KEYWORD; } } function prepend(stream, state) { if (stream.match(/^prepend\b/)) { state.restOfLine = 'variable'; return KEYWORD; } } function block(stream, state) { if (stream.match(/^block\b *(?:(prepend|append)\b)?/)) { state.restOfLine = 'variable'; return KEYWORD; } } function include(stream, state) { if (stream.match(/^include\b/)) { state.restOfLine = 'string'; return KEYWORD; } } function includeFiltered(stream, state) { if (stream.match(/^include:([a-zA-Z0-9\-]+)/, false) && stream.match('include')) { state.isIncludeFiltered = true; return KEYWORD; } } function includeFilteredContinued(stream, state) { if (state.isIncludeFiltered) { var tok = filter(stream, state); state.isIncludeFiltered = false; state.restOfLine = 'string'; return tok; } } function mixin(stream, state) { if (stream.match(/^mixin\b/)) { state.javaScriptLine = true; return KEYWORD; } } function call(stream, state) { if (stream.match(/^\+([-\w]+)/)) { if (!stream.match(/^\( *[-\w]+ *=/, false)) { state.javaScriptArguments = true; state.javaScriptArgumentsDepth = 0; } return 'variable'; } if (stream.match(/^\+#{/, false)) { stream.next(); state.mixinCallAfter = true; return interpolation(stream, state); } } function callArguments(stream, state) { if (state.mixinCallAfter) { state.mixinCallAfter = false; if (!stream.match(/^\( *[-\w]+ *=/, false)) { state.javaScriptArguments = true; state.javaScriptArgumentsDepth = 0; } return true; } } function conditional(stream, state) { if (stream.match(/^(if|unless|else if|else)\b/)) { state.javaScriptLine = true; return KEYWORD; } } function each(stream, state) { if (stream.match(/^(- *)?(each|for)\b/)) { state.isEach = true; return KEYWORD; } } function eachContinued(stream, state) { if (state.isEach) { if (stream.match(/^ in\b/)) { state.javaScriptLine = true; state.isEach = false; return KEYWORD; } else if (stream.sol() || stream.eol()) { state.isEach = false; } else if (stream.next()) { while (!stream.match(/^ in\b/, false) && stream.next()); return 'variable'; } } } function whileStatement(stream, state) { if (stream.match(/^while\b/)) { state.javaScriptLine = true; return KEYWORD; } } function tag(stream, state) { var captures; if (captures = stream.match(/^(\w(?:[-:\w]*\w)?)\/?/)) { state.lastTag = captures[1].toLowerCase(); if (state.lastTag === 'script') { state.scriptType = 'application/javascript'; } return 'tag'; } } function filter(stream, state) { if (stream.match(/^:([\w\-]+)/)) { var innerMode; if (config && config.innerModes) { innerMode = config.innerModes(stream.current().substring(1)); } if (!innerMode) { innerMode = stream.current().substring(1); } if (typeof innerMode === 'string') { innerMode = CodeMirror.getMode(config, innerMode); } setInnerMode(stream, state, innerMode); return 'atom'; } } function code(stream, state) { if (stream.match(/^(!?=|-)/)) { state.javaScriptLine = true; return 'punctuation'; } } function id(stream) { if (stream.match(/^#([\w-]+)/)) { return ID; } } function className(stream) { if (stream.match(/^\.([\w-]+)/)) { return CLASS; } } function attrs(stream, state) { if (stream.peek() == '(') { stream.next(); state.isAttrs = true; state.attrsNest = []; state.inAttributeName = true; state.attrValue = ''; state.attributeIsType = false; return 'punctuation'; } } function attrsContinued(stream, state) { if (state.isAttrs) { if (ATTRS_NEST[stream.peek()]) { state.attrsNest.push(ATTRS_NEST[stream.peek()]); } if (state.attrsNest[state.attrsNest.length - 1] === stream.peek()) { state.attrsNest.pop(); } else if (stream.eat(')')) { state.isAttrs = false; return 'punctuation'; } if (state.inAttributeName && stream.match(/^[^=,\)!]+/)) { if (stream.peek() === '=' || stream.peek() === '!') { state.inAttributeName = false; state.jsState = jsMode.startState(); if (state.lastTag === 'script' && stream.current().trim().toLowerCase() === 'type') { state.attributeIsType = true; } else { state.attributeIsType = false; } } return 'attribute'; } var tok = jsMode.token(stream, state.jsState); if (state.attributeIsType && tok === 'string') { state.scriptType = stream.current().toString(); } if (state.attrsNest.length === 0 && (tok === 'string' || tok === 'variable' || tok === 'keyword')) { try { Function('', 'var x ' + state.attrValue.replace(/,\s*$/, '').replace(/^!/, '')); state.inAttributeName = true; state.attrValue = ''; stream.backUp(stream.current().length); return attrsContinued(stream, state); } catch (ex) { //not the end of an attribute } } state.attrValue += stream.current(); return tok || true; } } function attributesBlock(stream, state) { if (stream.match(/^&attributes\b/)) { state.javaScriptArguments = true; state.javaScriptArgumentsDepth = 0; return 'keyword'; } } function indent(stream) { if (stream.sol() && stream.eatSpace()) { return 'indent'; } } function comment(stream, state) { if (stream.match(/^ *\/\/(-)?([^\n]*)/)) { state.indentOf = stream.indentation(); state.indentToken = 'comment'; return 'comment'; } } function colon(stream) { if (stream.match(/^: */)) { return 'colon'; } } function text(stream, state) { if (stream.match(/^(?:\| ?| )([^\n]+)/)) { return 'string'; } if (stream.match(/^(<[^\n]*)/, false)) { // html string setInnerMode(stream, state, 'htmlmixed'); state.innerModeForLine = true; return innerMode(stream, state, true); } } function dot(stream, state) { if (stream.eat('.')) { var innerMode = null; if (state.lastTag === 'script' && state.scriptType.toLowerCase().indexOf('javascript') != -1) { innerMode = state.scriptType.toLowerCase().replace(/"|'/g, ''); } else if (state.lastTag === 'style') { innerMode = 'css'; } setInnerMode(stream, state, innerMode); return 'dot'; } } function fail(stream) { stream.next(); return null; } function setInnerMode(stream, state, mode) { mode = CodeMirror.mimeModes[mode] || mode; mode = config.innerModes ? config.innerModes(mode) || mode : mode; mode = CodeMirror.mimeModes[mode] || mode; mode = CodeMirror.getMode(config, mode); state.indentOf = stream.indentation(); if (mode && mode.name !== 'null') { state.innerMode = mode; } else { state.indentToken = 'string'; } } function innerMode(stream, state, force) { if (stream.indentation() > state.indentOf || (state.innerModeForLine && !stream.sol()) || force) { if (state.innerMode) { if (!state.innerState) { state.innerState = state.innerMode.startState ? state.innerMode.startState(stream.indentation()) : {}; } return stream.hideFirstChars(state.indentOf + 2, function () { return state.innerMode.token(stream, state.innerState) || true; }); } else { stream.skipToEnd(); return state.indentToken; } } else if (stream.sol()) { state.indentOf = Infinity; state.indentToken = null; state.innerMode = null; state.innerState = null; } } function restOfLine(stream, state) { if (stream.sol()) { // if restOfLine was set at end of line, ignore it state.restOfLine = ''; } if (state.restOfLine) { stream.skipToEnd(); var tok = state.restOfLine; state.restOfLine = ''; return tok; } } function startState() { return new State(); } function copyState(state) { return state.copy(); } /** * Get the next token in the stream * * @param {Stream} stream * @param {State} state */ function nextToken(stream, state) { var tok = innerMode(stream, state) || restOfLine(stream, state) || interpolationContinued(stream, state) || includeFilteredContinued(stream, state) || eachContinued(stream, state) || attrsContinued(stream, state) || javaScript(stream, state) || javaScriptArguments(stream, state) || callArguments(stream, state) || yieldStatement(stream, state) || doctype(stream, state) || interpolation(stream, state) || caseStatement(stream, state) || when(stream, state) || defaultStatement(stream, state) || extendsStatement(stream, state) || append(stream, state) || prepend(stream, state) || block(stream, state) || include(stream, state) || includeFiltered(stream, state) || mixin(stream, state) || call(stream, state) || conditional(stream, state) || each(stream, state) || whileStatement(stream, state) || tag(stream, state) || filter(stream, state) || code(stream, state) || id(stream, state) || className(stream, state) || attrs(stream, state) || attributesBlock(stream, state) || indent(stream, state) || text(stream, state) || comment(stream, state) || colon(stream, state) || dot(stream, state) || fail(stream, state); return tok === true ? null : tok; } return { startState: startState, copyState: copyState, token: nextToken }; }); CodeMirror.defineMIME('text/x-jade', 'jade'); });
{ "pile_set_name": "Github" }
var Minimatch = require("../minimatch.js").Minimatch var tap = require("tap") tap.test("cache test", function (t) { var mm1 = new Minimatch("a?b") var mm2 = new Minimatch("a?b") t.equal(mm1, mm2, "should get the same object") // the lru should drop it after 100 entries for (var i = 0; i < 100; i ++) { new Minimatch("a"+i) } mm2 = new Minimatch("a?b") t.notEqual(mm1, mm2, "cache should have dropped") t.end() })
{ "pile_set_name": "Github" }
/* * Copyright (c) 2017, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package com.acme; import jakarta.ejb.*; import jakarta.interceptor.*; import jakarta.annotation.*; @Stateless public class SlessEJB extends BaseBean { @EJB SlessEJB2 s2; @EJB SlessEJB3 s3; public SlessEJB() {} public String sayHello() { verifyA_AC("SlessEJB"); //verifyB_AC("SlessEJB"); verifyA_PC("SlessEJB"); return (s2.sayHello() + s3.sayHello()); } @PostConstruct private void init() { System.out.println("**SlessEJB PostConstruct"); verifyMethod("init"); } }
{ "pile_set_name": "Github" }
[TRAINER FORMAT] Name|Stewart TrainerClass|Psychic Money|0 IntroMessage|... OutroMessage|I focused my mind in silence... DefeatMessage|I focused my mind in silence... TextureID|battletower\39 Region|Johto IniMusic|Johto_trainer_intro DefeatMusic|trainer_defeat BattleMusic|johto_trainer Pokemon1|<system.random(0,251)>,<pokemon.maxpartylevel> Pokemon2|<system.random(0,251)>,<pokemon.maxpartylevel> Pokemon3|<system.random(0,251)>,<pokemon.maxpartylevel> Pokemon4| Pokemon5| Pokemon6| Items| Gender|0 AI|0 IntroSequence|battlefrontier,lightblue
{ "pile_set_name": "Github" }
{ "Press Resources": "", "We love working with press—both within the Linux world and the greater tech and culture beats—to share our story and what we are working on.": "", "Join Our Press List": "", "Be the first to know about new releases and significant developments. We send early access to press releases and press kits, including high resolution screenshots. This is a <strong>very low volume</strong> list; we send you the biggest news around once a year.": "", "Email": "", "First Name": "", "Last Name": "", "Publication": "", "Subscribe": "", "elementary OS 5.1 Hera": "", "Hera is a major update on a solid foundation. Featuring a completely redesigned login and lockscreen greeter, a new onboarding experience, new ways to sideload and install apps, major System Settings updates, improved core apps, and desktop refinements.": "", "Read Announcement": "", "Download Press Kit": "", "News &amp; Announcements": "", "We share frequent updates on development, major announcements, tips for developers, featured apps, and other new content via our official blog.": "", "Visit Our Blog": "", "Brand Resources": "", "View the elementary logos, brand usage guidelines, color palette, and community logo. Plus download the official high-resolution and vector elementary logo assets.": "", "View Brand Resources": "", "Get in Touch": "", "Talk directly with the team by emailing us at <a href=\"mailto:[email protected]\">[email protected]</a>. We welcome requests for interviews, podcast appearances, or just general press inquiries.": "", "Send an Email": "", "Press &sdot; elementary": "" }
{ "pile_set_name": "Github" }
{ "name": "@datafire/azure_servicebus", "version": "4.0.0", "main": "index.js", "description": "DataFire integration for ServiceBusManagementClient", "repository": { "type": "git", "url": "git+https://github.com/DataFire/integrations.git" }, "author": "DataFire", "license": "MIT", "bugs": { "url": "https://github.com/DataFire/integrations/issues" }, "homepage": "https://github.com/DataFire/integrations#readme", "datafire": { "origin": "https://api.apis.guru/v2/specs/azure.com/servicebus/2017-04-01/swagger.json", "type": "openapi" }, "peerDependencies": { "datafire": "^2.0.0" }, "dependencies": { "datafire": "^2.0.0" } }
{ "pile_set_name": "Github" }
package config import ( "net" "testing" "github.com/stretchr/testify/assert" ) func TestGetTrafficEncapModeFromStr(t *testing.T) { tests := []struct { name string mode string expBool bool expMode TrafficEncapModeType }{ {"encap-mode-valid", "enCap", true, 0}, {"no-encap-mode-valid", "Noencap", true, 1}, {"hybrid-mode-valid", "Hybrid", true, 2}, {"policy-only-mode-valid", "NetworkPolicyOnly", true, 3}, {"invalid-str", "en cap", false, -1}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { actualBool, actualMode := GetTrafficEncapModeFromStr(tt.mode) assert.Equal(t, tt.expBool, actualBool, "GetTrafficEncapModeFromStr did not return correct boolean") assert.Equal(t, tt.expMode, actualMode, "GetTrafficEncapModeFromStr did not return correct traffic type") }) } } func TestGetTrafficEncapModes(t *testing.T) { modes := GetTrafficEncapModes() expModes := []TrafficEncapModeType{0, 1, 2, 3} assert.Equal(t, expModes, modes, "GetTrafficEncapModes received unexpected encap modes") } func TestTrafficEncapModeTypeString(t *testing.T) { tests := []struct { name string modeType TrafficEncapModeType expMode string }{ {"encap-mode", 0, "Encap"}, {"no-encap-mode", 1, "NoEncap"}, {"hybrid-mode", 2, "Hybrid"}, {"policy-only-mode-valid", 3, "NetworkPolicyOnly"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { actualMode := tt.modeType.String() assert.Equal(t, tt.expMode, actualMode, "String did not return correct traffic type in string format") }) } } func TestTrafficEncapModeTypeSupports(t *testing.T) { tests := []struct { name string mode TrafficEncapModeType expNoEncap bool expEncap bool }{ {"encap-mode", 0, false, true}, {"no-encap-mode", 1, true, false}, {"hybrid-mode", 2, true, true}, {"policy-only-mode-valid", 3, true, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { actualNoEncap := tt.mode.SupportsNoEncap() actualEncap := tt.mode.SupportsEncap() assert.Equal(t, tt.expNoEncap, actualNoEncap, "SupportsNoEncap did not return correct result") assert.Equal(t, tt.expEncap, actualEncap, "SupportsEncap did not return correct result") }) } } func TestTrafficEncapModeTypeNeedsEncapToPeer(t *testing.T) { tests := []struct { name string mode TrafficEncapModeType peerIP net.IP localIP *net.IPNet expBool bool }{ { name: "encap-mode", mode: 0, peerIP: net.ParseIP("192.168.0.5"), localIP: &net.IPNet{ IP: net.IPv4(192, 168, 0, 1), Mask: net.IPv4Mask(255, 255, 255, 0), }, expBool: true, }, { name: "no-encap-mode", mode: 1, peerIP: net.ParseIP("192.168.0.5"), localIP: &net.IPNet{ IP: net.IPv4(192, 168, 0, 1), Mask: net.IPv4Mask(255, 255, 255, 0), }, expBool: false, }, { name: "hybrid-mode-need-encapsulated", mode: 2, peerIP: net.ParseIP("10.0.0.0"), localIP: &net.IPNet{ IP: net.IPv4(192, 168, 0, 1), Mask: net.IPv4Mask(255, 255, 255, 0), }, expBool: true, }, { name: "hybrid-mode-no-need-encapsulated", mode: 2, peerIP: net.ParseIP("192.168.0.5"), localIP: &net.IPNet{ IP: net.IPv4(192, 168, 0, 1), Mask: net.IPv4Mask(255, 255, 255, 0), }, expBool: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { actualBool := tt.mode.NeedsEncapToPeer(tt.peerIP, tt.localIP) assert.Equal(t, tt.expBool, actualBool, "NeedsEncapToPeer did not return correct result") }) } } func TestTrafficEncapModeTypeNeedsRoutingToPeer(t *testing.T) { tests := []struct { name string mode TrafficEncapModeType peerIP net.IP localIP *net.IPNet expBool bool }{ { name: "encap-mode", mode: 0, peerIP: net.ParseIP("192.168.0.5"), localIP: &net.IPNet{ IP: net.IPv4(192, 168, 0, 1), Mask: net.IPv4Mask(255, 255, 255, 0), }, expBool: false, }, { name: "no-encap-mode-no-need-support", mode: 1, peerIP: net.ParseIP("192.168.0.5"), localIP: &net.IPNet{ IP: net.IPv4(192, 168, 0, 1), Mask: net.IPv4Mask(255, 255, 255, 0), }, expBool: false, }, { name: "no-encap-mode-need-support", mode: 1, peerIP: net.ParseIP("192.168.1.5"), localIP: &net.IPNet{ IP: net.IPv4(192, 168, 0, 1), Mask: net.IPv4Mask(255, 255, 255, 0), }, expBool: true, }, { name: "hybrid-mode", mode: 2, peerIP: net.ParseIP("192.168.0.5"), localIP: &net.IPNet{ IP: net.IPv4(192, 168, 0, 1), Mask: net.IPv4Mask(255, 255, 255, 0), }, expBool: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { actualBool := tt.mode.NeedsRoutingToPeer(tt.peerIP, tt.localIP) assert.Equal(t, tt.expBool, actualBool, "NeedsRoutingToPeer did not return correct result") }) } }
{ "pile_set_name": "Github" }
[package] name = "completion" version = "0.1.0" authors = ["Nick Cameron <[email protected]>"] [dependencies]
{ "pile_set_name": "Github" }
<refentry xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:src="http://nwalsh.com/xmlns/litprog/fragment" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="5.0" xml:id="filename-prefix"> <refmeta> <refentrytitle>filename-prefix</refentrytitle> <refmiscinfo class="other" otherclass="datatype">string</refmiscinfo> </refmeta> <refnamediv> <refname>filename-prefix</refname> <refpurpose>Prefix added to all filenames</refpurpose> </refnamediv> <refsynopsisdiv> <src:fragment xml:id="filename-prefix.frag"> <xsl:param name="filename-prefix"></xsl:param> </src:fragment> </refsynopsisdiv> <refsection><info><title>Description</title></info> <para>To produce the <quote>text-only</quote> (that is, non-tabular) layout of a website simultaneously with the tabular layout, the filenames have to be distinguished. That's accomplished by adding the <varname>filename-prefix</varname> to the front of each filename.</para> </refsection> </refentry>
{ "pile_set_name": "Github" }
[![Build Status](https://drone.our.buildo.io/api/badges/buildo/react-cookie-banner/status.svg)](https://drone.our.buildo.io/buildo/react-cookie-banner) ![](https://img.shields.io/npm/v/react-cookie-banner.svg) # React Cookie Banner A cookie banner for React that can be dismissed with a simple scroll. Because [fuck the Cookie Law](http://nocookielaw.com/) that's why. (If you *really* want to annoy your users you can disable this feature but this is strongly discouraged!). ```jsx import CookieBanner from 'react-cookie-banner'; React.renderComponent( <div> <CookieBanner message="Yes, we use cookies. If you don't like it change website, we won't miss you!" onAccept={() => {}} cookie="user-has-accepted-cookies" /> </div>, document.body ); ``` [Live Examples](http://react-components.buildo.io/#cookiebanner) ## Install ``` npm install --save react-cookie-banner ``` or using `yarn`: ``` yarn add react-cookie-banner ``` ## API You can see `CookieBanner`'s props in its own [README.md](https://github.com/buildo/react-cookie-banner/blob/master/src/README.md) ## Style `react-cookie-banner` comes with a nice default style made using inline-style. Of course, you can customize it as you like in several ways. Based on how many changes you want to apply, you can style `react-cookie-banner` as follows: ### You like the original style and you wish to make only a few modifications Why spending hours on the CSS when you have such a nice default style? :) In this case you can: #### 1) Override the predefined inline-styles In this example we change the message font-size and make the banner slightly transparent with the `styles` prop: ```jsx <CookieBanner styles={{ banner: { backgroundColor: 'rgba(60, 60, 60, 0.8)' }, message: { fontWeight: 400 } }} message='...' /> ``` See [`src/styleUtils.ts`](https://github.com/buildo/react-cookie-banner/blob/master/src/styleUtils.ts) for a complete list of overridable style objects. #### 2) Beat it with good old CSS (or SASS) The banner is structured as follows: ```jsx <div className={this.props.className + ' react-cookie-banner'} <span className='cookie-message'> {this.props.message} <a className='cookie-link'> Learn more </a> </span> <button className='button-close'> Got it </button> </div> ``` You can style every part of it using the appropriate `className`: ```sass .your-class-name.react-cookie-banner { background-color: rgba(60, 60, 60, 0.8); .cookie-message { font-weight: 400; } } ``` ### You need to heavily adapt the style to your application Your creative designer wants to change the style of the cookie banner completely? Don't worry, we got your covered! If you need to re-style it, you can: #### 1) Disable the default style and use your CSS You may disable the default style by simply setting the prop `disableStyle` to `true`: ```jsx <CookieBanner disableStyle={true} /> ``` Now you can re-style the cookie banner completely using your own CSS. #### 2) Use your own cookie banner! Don't like the layout either? You can use your own custom cookie banner component by passing it as `children` and still let `react-cookie-banner` handle the hassle of managing `cookies` for you :) ```jsx <CookieBanner> {(onAccept) => ( <MyCustomCookieBanner {...myCustomProps} onAccept={onAccept} /> {/* rendered directly without any <div> wrapper */} )} </CookieBanner> ``` ## Cookies manipulation `react-cookie-banner` uses **`universal-cookie`** to manipulate cookies. You can import the `Cookies` class and use it as follows: ```js import { Cookies } from 'react-cookie-banner' const cookies = new Cookies(/* Your cookie header, on browsers defaults to document.cookie */) // simple set cookie.set('test', 'a') // complex set - cookie(name, value, ttl, path, domain, secure) cookie.set('test', 'a', { expires: new Date(2020-05-04) path: '/api', domain: '*.example.com', secure: true }) // get cookies.get('test') // destroy cookies.remove('test', '', -1) ``` Please refer to [universal-cookie](https://github.com/reactivestack/cookies/tree/master/packages/universal-cookie#api---cookies-class) repo for more documentation. ## Server side rendering (aka Universal) `react-cookie-banner` supports SSR thanks to `react-cookie`. If you want to support SSR, you should use the `CookieProvider` from `react-cookie` and the `CookieBannerUniversal` wrapper: ```jsx import { Cookies, CookiesProvider, CookieBannerUniversal } from 'react-cookie-banner' const cookies = new Cookies(/* Your cookie header, on browsers defaults to document.cookie */) <CookiesProvider cookies={cookies}> <CookieBannerUniversal /> </CookiesProvider> ```
{ "pile_set_name": "Github" }
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Local File Inclusion Test Case</title> </head> <body> <%@ include file="include.jsp"%> <% //*** Re-define Default Exposure Variables - Per Page *** //CONTEXT_STREAM, FILE_CLASS, URL_CLASS, FTP_CLASS, INCLUDE, REDIRECT, FORWARD fileAccessMethod = FileAccessMethod.CONTEXT_STREAM; //NONE, WHITE_LIST, LOCAL_FOLDER_ONLY, PERMISSIONS, //UNIX_TRAVESAL_INPUT_VALIDATION, UNIX_TRAVESAL_INPUT_REMOVAL, //WINDOWS_TRAVESAL_INPUT_VALIDATION, WINDOWS_TRAVESAL_INPUT_REMOVAL, //SLASH_INPUT_VALIDATION, SLASH_INPUT_REMOVAL, //BACKSLASH_INPUT_VALIDATION, BACKSLASH_INPUT_REMOVAL, accessRestriction = FileAccessRestriction.NONE; //FULL_PATH_INPUT, RELATIVE_INPUT, INVALID_INPUT , EMPTY_INPUT defaultInputType = DefaultInputType.EMPTY_INPUT; //FULL_FILENAME, FILENAME_ONLY, DIRECTORY, EXTENSION injectionContext = FileInjectionContext.FULL_FILENAME; //ANY, NONE, SLASH_PREFIX, BACKSLASH_PREFIX, //FTP_DIRECTIVE, HTTP_DIRECTIVE, prefixRequired = PrefixRequirement.NONE; //WINDOWS, UNIX //osSimulated = OsType.WINDOWS; //Use the default defined in include.jsp //ERROR_500, ERROR_404, REDIRECT_302, ERROR_200, VALID_200, Identical_200 //invalidResponseType = ResponseType.ERROR_200; //Use the default defined in include.jsp //CONTENT_TYPE_TEXT_HTML ("text/html"), CONTENT_TYPE_STREAM ("application/octet-stream") //validResposeStream = ContentConstants.CONTENT_TYPE_TEXT_HTML; //OS_PATH, FILE_DIRECTIVE_URL, FTP_URL, HTTP_URL pathType = PathType.OS_PATH; //LFI, RFI, DIRECTORY_TRAVERSAL, CODE_LFI, CODE_RFI, FALSE_POSITIVE vulnerability = VulnerabilityType.LFI; %> <%@ include file="inclusion-logic.jsp"%>
{ "pile_set_name": "Github" }
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true end
{ "pile_set_name": "Github" }
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // Regression test for http://dartbug.com/11637 class _C {} class _E { throwIt() => throw "it"; } class _F { throwIt() => throw "IT"; } class _D extends _C with _E, _F {} main() { var d = new _D(); try { d.throwIt(); } catch (e, s) { print("Exception: $e"); print("Stacktrace:\n$s"); } }
{ "pile_set_name": "Github" }
package org.dddjava.jig.domain.model.jigmodel.lowmodel.declaration.field; /** * フィールドの名称 */ public class FieldIdentifier { String value; public FieldIdentifier(String value) { this.value = value; } public String text() { return value; } }
{ "pile_set_name": "Github" }
/* Package to provides helpers to ease working with pointer values of marshalled structures. */ package to // Copyright 2017 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // String returns a string value for the passed string pointer. It returns the empty string if the // pointer is nil. func String(s *string) string { if s != nil { return *s } return "" } // StringPtr returns a pointer to the passed string. func StringPtr(s string) *string { return &s } // StringSlice returns a string slice value for the passed string slice pointer. It returns a nil // slice if the pointer is nil. func StringSlice(s *[]string) []string { if s != nil { return *s } return nil } // StringSlicePtr returns a pointer to the passed string slice. func StringSlicePtr(s []string) *[]string { return &s } // StringMap returns a map of strings built from the map of string pointers. The empty string is // used for nil pointers. func StringMap(msp map[string]*string) map[string]string { ms := make(map[string]string, len(msp)) for k, sp := range msp { if sp != nil { ms[k] = *sp } else { ms[k] = "" } } return ms } // StringMapPtr returns a pointer to a map of string pointers built from the passed map of strings. func StringMapPtr(ms map[string]string) *map[string]*string { msp := make(map[string]*string, len(ms)) for k, s := range ms { msp[k] = StringPtr(s) } return &msp } // Bool returns a bool value for the passed bool pointer. It returns false if the pointer is nil. func Bool(b *bool) bool { if b != nil { return *b } return false } // BoolPtr returns a pointer to the passed bool. func BoolPtr(b bool) *bool { return &b } // Int returns an int value for the passed int pointer. It returns 0 if the pointer is nil. func Int(i *int) int { if i != nil { return *i } return 0 } // IntPtr returns a pointer to the passed int. func IntPtr(i int) *int { return &i } // Int32 returns an int value for the passed int pointer. It returns 0 if the pointer is nil. func Int32(i *int32) int32 { if i != nil { return *i } return 0 } // Int32Ptr returns a pointer to the passed int32. func Int32Ptr(i int32) *int32 { return &i } // Int64 returns an int value for the passed int pointer. It returns 0 if the pointer is nil. func Int64(i *int64) int64 { if i != nil { return *i } return 0 } // Int64Ptr returns a pointer to the passed int64. func Int64Ptr(i int64) *int64 { return &i } // Float32 returns an int value for the passed int pointer. It returns 0.0 if the pointer is nil. func Float32(i *float32) float32 { if i != nil { return *i } return 0.0 } // Float32Ptr returns a pointer to the passed float32. func Float32Ptr(i float32) *float32 { return &i } // Float64 returns an int value for the passed int pointer. It returns 0.0 if the pointer is nil. func Float64(i *float64) float64 { if i != nil { return *i } return 0.0 } // Float64Ptr returns a pointer to the passed float64. func Float64Ptr(i float64) *float64 { return &i } // ByteSlicePtr returns a pointer to the passed byte slice. func ByteSlicePtr(b []byte) *[]byte { return &b }
{ "pile_set_name": "Github" }
/* * searchtools.js_t * ~~~~~~~~~~~~~~~~ * * Sphinx JavaScript utilties for the full-text search. * * :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ /** * Porter Stemmer */ var Stemmer = function() { var step2list = { ational: 'ate', tional: 'tion', enci: 'ence', anci: 'ance', izer: 'ize', bli: 'ble', alli: 'al', entli: 'ent', eli: 'e', ousli: 'ous', ization: 'ize', ation: 'ate', ator: 'ate', alism: 'al', iveness: 'ive', fulness: 'ful', ousness: 'ous', aliti: 'al', iviti: 'ive', biliti: 'ble', logi: 'log' }; var step3list = { icate: 'ic', ative: '', alize: 'al', iciti: 'ic', ical: 'ic', ful: '', ness: '' }; var c = "[^aeiou]"; // consonant var v = "[aeiouy]"; // vowel var C = c + "[^aeiouy]*"; // consonant sequence var V = v + "[aeiou]*"; // vowel sequence var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0 var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1 var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1 var s_v = "^(" + C + ")?" + v; // vowel in stem this.stemWord = function (w) { var stem; var suffix; var firstch; var origword = w; if (w.length < 3) return w; var re; var re2; var re3; var re4; firstch = w.substr(0,1); if (firstch == "y") w = firstch.toUpperCase() + w.substr(1); // Step 1a re = /^(.+?)(ss|i)es$/; re2 = /^(.+?)([^s])s$/; if (re.test(w)) w = w.replace(re,"$1$2"); else if (re2.test(w)) w = w.replace(re2,"$1$2"); // Step 1b re = /^(.+?)eed$/; re2 = /^(.+?)(ed|ing)$/; if (re.test(w)) { var fp = re.exec(w); re = new RegExp(mgr0); if (re.test(fp[1])) { re = /.$/; w = w.replace(re,""); } } else if (re2.test(w)) { var fp = re2.exec(w); stem = fp[1]; re2 = new RegExp(s_v); if (re2.test(stem)) { w = stem; re2 = /(at|bl|iz)$/; re3 = new RegExp("([^aeiouylsz])\\1$"); re4 = new RegExp("^" + C + v + "[^aeiouwxy]$"); if (re2.test(w)) w = w + "e"; else if (re3.test(w)) { re = /.$/; w = w.replace(re,""); } else if (re4.test(w)) w = w + "e"; } } // Step 1c re = /^(.+?)y$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; re = new RegExp(s_v); if (re.test(stem)) w = stem + "i"; } // Step 2 re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; suffix = fp[2]; re = new RegExp(mgr0); if (re.test(stem)) w = stem + step2list[suffix]; } // Step 3 re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; suffix = fp[2]; re = new RegExp(mgr0); if (re.test(stem)) w = stem + step3list[suffix]; } // Step 4 re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/; re2 = /^(.+?)(s|t)(ion)$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; re = new RegExp(mgr1); if (re.test(stem)) w = stem; } else if (re2.test(w)) { var fp = re2.exec(w); stem = fp[1] + fp[2]; re2 = new RegExp(mgr1); if (re2.test(stem)) w = stem; } // Step 5 re = /^(.+?)e$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; re = new RegExp(mgr1); re2 = new RegExp(meq1); re3 = new RegExp("^" + C + v + "[^aeiouwxy]$"); if (re.test(stem) || (re2.test(stem) && !(re3.test(stem)))) w = stem; } re = /ll$/; re2 = new RegExp(mgr1); if (re.test(w) && re2.test(w)) { re = /.$/; w = w.replace(re,""); } // and turn initial Y back to y if (firstch == "y") w = firstch.toLowerCase() + w.substr(1); return w; } } /** * Simple result scoring code. */ var Scorer = { // Implement the following function to further tweak the score for each result // The function takes a result array [filename, title, anchor, descr, score] // and returns the new score. /* score: function(result) { return result[4]; }, */ // query matches the full name of an object objNameMatch: 11, // or matches in the last dotted part of the object name objPartialMatch: 6, // Additive scores depending on the priority of the object objPrio: {0: 15, // used to be importantResults 1: 5, // used to be objectResults 2: -5}, // used to be unimportantResults // Used when the priority is not in the mapping. objPrioDefault: 0, // query found in title title: 15, // query found in terms term: 5 }; /** * Search Module */ var Search = { _index : null, _queued_query : null, _pulse_status : -1, init : function() { var params = $.getQueryParameters(); if (params.q) { var query = params.q[0]; $('input[name="q"]')[0].value = query; this.performSearch(query); } }, loadIndex : function(url) { $.ajax({type: "GET", url: url, data: null, dataType: "script", cache: true, complete: function(jqxhr, textstatus) { if (textstatus != "success") { document.getElementById("searchindexloader").src = url; } }}); }, setIndex : function(index) { var q; this._index = index; if ((q = this._queued_query) !== null) { this._queued_query = null; Search.query(q); } }, hasIndex : function() { return this._index !== null; }, deferQuery : function(query) { this._queued_query = query; }, stopPulse : function() { this._pulse_status = 0; }, startPulse : function() { if (this._pulse_status >= 0) return; function pulse() { var i; Search._pulse_status = (Search._pulse_status + 1) % 4; var dotString = ''; for (i = 0; i < Search._pulse_status; i++) dotString += '.'; Search.dots.text(dotString); if (Search._pulse_status > -1) window.setTimeout(pulse, 500); } pulse(); }, /** * perform a search for something (or wait until index is loaded) */ performSearch : function(query) { // create the required interface elements this.out = $('#search-results'); this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out); this.dots = $('<span></span>').appendTo(this.title); this.status = $('<p style="display: none"></p>').appendTo(this.out); this.output = $('<ul class="search"/>').appendTo(this.out); $('#search-progress').text(_('Preparing search...')); this.startPulse(); // index already loaded, the browser was quick! if (this.hasIndex()) this.query(query); else this.deferQuery(query); }, /** * execute search (requires search index to be loaded) */ query : function(query) { var i; var stopwords = ["a","and","are","as","at","be","but","by","for","if","in","into","is","it","near","no","not","of","on","or","such","that","the","their","then","there","these","they","this","to","was","will","with"]; // stem the searchterms and add them to the correct list var stemmer = new Stemmer(); var searchterms = []; var excluded = []; var hlterms = []; var tmp = query.split(/\s+/); var objectterms = []; for (i = 0; i < tmp.length; i++) { if (tmp[i] !== "") { objectterms.push(tmp[i].toLowerCase()); } if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i].match(/^\d+$/) || tmp[i] === "") { // skip this "word" continue; } // stem the word var word = stemmer.stemWord(tmp[i].toLowerCase()); var toAppend; // select the correct list if (word[0] == '-') { toAppend = excluded; word = word.substr(1); } else { toAppend = searchterms; hlterms.push(tmp[i].toLowerCase()); } // only add if not already in the list if (!$u.contains(toAppend, word)) toAppend.push(word); } var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" ")); // console.debug('SEARCH: searching for:'); // console.info('required: ', searchterms); // console.info('excluded: ', excluded); // prepare search var terms = this._index.terms; var titleterms = this._index.titleterms; // array of [filename, title, anchor, descr, score] var results = []; $('#search-progress').empty(); // lookup as object for (i = 0; i < objectterms.length; i++) { var others = [].concat(objectterms.slice(0, i), objectterms.slice(i+1, objectterms.length)); results = results.concat(this.performObjectSearch(objectterms[i], others)); } // lookup as search terms in fulltext results = results.concat(this.performTermsSearch(searchterms, excluded, terms, Scorer.term)) .concat(this.performTermsSearch(searchterms, excluded, titleterms, Scorer.title)); // let the scorer override scores with a custom scoring function if (Scorer.score) { for (i = 0; i < results.length; i++) results[i][4] = Scorer.score(results[i]); } // now sort the results by score (in opposite order of appearance, since the // display function below uses pop() to retrieve items) and then // alphabetically results.sort(function(a, b) { var left = a[4]; var right = b[4]; if (left > right) { return 1; } else if (left < right) { return -1; } else { // same score: sort alphabetically left = a[1].toLowerCase(); right = b[1].toLowerCase(); return (left > right) ? -1 : ((left < right) ? 1 : 0); } }); // for debugging //Search.lastresults = results.slice(); // a copy //console.info('search results:', Search.lastresults); // print the results var resultCount = results.length; function displayNextItem() { // results left, load the summary and display it if (results.length) { var item = results.pop(); var listItem = $('<li style="display:none"></li>'); if (DOCUMENTATION_OPTIONS.FILE_SUFFIX === '') { // dirhtml builder var dirname = item[0] + '/'; if (dirname.match(/\/index\/$/)) { dirname = dirname.substring(0, dirname.length-6); } else if (dirname == 'index/') { dirname = ''; } listItem.append($('<a/>').attr('href', DOCUMENTATION_OPTIONS.URL_ROOT + dirname + highlightstring + item[2]).html(item[1])); } else { // normal html builders listItem.append($('<a/>').attr('href', item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX + highlightstring + item[2]).html(item[1])); } if (item[3]) { listItem.append($('<span> (' + item[3] + ')</span>')); Search.output.append(listItem); listItem.slideDown(5, function() { displayNextItem(); }); } else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) { $.ajax({url: DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + item[0] + '.txt', dataType: "text", complete: function(jqxhr, textstatus) { var data = jqxhr.responseText; if (data !== '') { listItem.append(Search.makeSearchSummary(data, searchterms, hlterms)); } Search.output.append(listItem); listItem.slideDown(5, function() { displayNextItem(); }); }}); } else { // no source available, just display title Search.output.append(listItem); listItem.slideDown(5, function() { displayNextItem(); }); } } // search finished, update title and status message else { Search.stopPulse(); Search.title.text(_('Search Results')); if (!resultCount) Search.status.text(_('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.')); else Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount)); Search.status.fadeIn(500); } } displayNextItem(); }, /** * search for object names */ performObjectSearch : function(object, otherterms) { var filenames = this._index.filenames; var objects = this._index.objects; var objnames = this._index.objnames; var titles = this._index.titles; var i; var results = []; for (var prefix in objects) { for (var name in objects[prefix]) { var fullname = (prefix ? prefix + '.' : '') + name; if (fullname.toLowerCase().indexOf(object) > -1) { var score = 0; var parts = fullname.split('.'); // check for different match types: exact matches of full name or // "last name" (i.e. last dotted part) if (fullname == object || parts[parts.length - 1] == object) { score += Scorer.objNameMatch; // matches in last name } else if (parts[parts.length - 1].indexOf(object) > -1) { score += Scorer.objPartialMatch; } var match = objects[prefix][name]; var objname = objnames[match[1]][2]; var title = titles[match[0]]; // If more than one term searched for, we require other words to be // found in the name/title/description if (otherterms.length > 0) { var haystack = (prefix + ' ' + name + ' ' + objname + ' ' + title).toLowerCase(); var allfound = true; for (i = 0; i < otherterms.length; i++) { if (haystack.indexOf(otherterms[i]) == -1) { allfound = false; break; } } if (!allfound) { continue; } } var descr = objname + _(', in ') + title; var anchor = match[3]; if (anchor === '') anchor = fullname; else if (anchor == '-') anchor = objnames[match[1]][1] + '-' + fullname; // add custom score for some objects according to scorer if (Scorer.objPrio.hasOwnProperty(match[2])) { score += Scorer.objPrio[match[2]]; } else { score += Scorer.objPrioDefault; } results.push([filenames[match[0]], fullname, '#'+anchor, descr, score]); } } } return results; }, /** * search for full-text terms in the index */ performTermsSearch : function(searchterms, excluded, terms, score) { var filenames = this._index.filenames; var titles = this._index.titles; var i, j, file, files; var fileMap = {}; var results = []; // perform the search on the required terms for (i = 0; i < searchterms.length; i++) { var word = searchterms[i]; // no match but word was a required one if ((files = terms[word]) === undefined) break; if (files.length === undefined) { files = [files]; } // create the mapping for (j = 0; j < files.length; j++) { file = files[j]; if (file in fileMap) fileMap[file].push(word); else fileMap[file] = [word]; } } // now check if the files don't contain excluded terms for (file in fileMap) { var valid = true; // check if all requirements are matched if (fileMap[file].length != searchterms.length) continue; // ensure that none of the excluded terms is in the search result for (i = 0; i < excluded.length; i++) { if (terms[excluded[i]] == file || $u.contains(terms[excluded[i]] || [], file)) { valid = false; break; } } // if we have still a valid result we can add it to the result list if (valid) { results.push([filenames[file], titles[file], '', null, score]); } } return results; }, /** * helper function to return a node containing the * search summary for a given text. keywords is a list * of stemmed words, hlwords is the list of normal, unstemmed * words. the first one is used to find the occurance, the * latter for highlighting it. */ makeSearchSummary : function(text, keywords, hlwords) { var textLower = text.toLowerCase(); var start = 0; $.each(keywords, function() { var i = textLower.indexOf(this.toLowerCase()); if (i > -1) start = i; }); start = Math.max(start - 120, 0); var excerpt = ((start > 0) ? '...' : '') + $.trim(text.substr(start, 240)) + ((start + 240 - text.length) ? '...' : ''); var rv = $('<div class="context"></div>').text(excerpt); $.each(hlwords, function() { rv = rv.highlightText(this, 'highlighted'); }); return rv; } }; $(document).ready(function() { Search.init(); });
{ "pile_set_name": "Github" }
The HDR images in this directory are provided from sIBL Archive under the Creative Commons license (CC BY-NC-SA 3.0 US). Please see the page below for further details. http://www.hdrlabs.com/sibl/archive.html
{ "pile_set_name": "Github" }
/*! Special comment */@charset "UTF-8";@import"foo.css";.bar{display:block}.qux{display:block}
{ "pile_set_name": "Github" }
RSpec.describe Hanami::Controller::Configuration do before do module CustomAction end end let(:configuration) { Hanami::Controller::Configuration.new } after do Object.send(:remove_const, :CustomAction) end describe 'handle exceptions' do it 'returns true by default' do expect(configuration.handle_exceptions).to be(true) end it 'allows to set the value with a writer' do configuration.handle_exceptions = false expect(configuration.handle_exceptions).to be(false) end it 'allows to set the value with a dsl' do configuration.handle_exceptions(false) expect(configuration.handle_exceptions).to be(false) end it 'ignores nil' do configuration.handle_exceptions(nil) expect(configuration.handle_exceptions).to be(true) end end describe 'handled exceptions' do it 'returns an empty hash by default' do expect(configuration.handled_exceptions).to eq({}) end it 'allows to set an exception' do configuration.handle_exception ArgumentError => 400 expect(configuration.handled_exceptions).to include(ArgumentError) end end describe 'exception_handler' do describe 'when the given error is unknown' do it 'returns the default value' do expect(configuration.exception_handler(Exception)).to be(500) end end describe 'when the given error was registered' do before do configuration.handle_exception NotImplementedError => 400 end it 'returns configured value when an exception instance is given' do expect(configuration.exception_handler(NotImplementedError.new)).to be(400) end end end describe 'action_module' do describe 'when not previously configured' do it 'returns the default value' do expect(configuration.action_module).to eq(::Hanami::Action) end end describe 'when previously configured' do before do configuration.action_module(CustomAction) end it 'returns the value' do expect(configuration.action_module).to eq(CustomAction) end end end describe 'modules' do before do unless defined?(FakeAction) class FakeAction end end unless defined?(FakeCallable) module FakeCallable def call(_) [status, {}, ['Callable']] end def status 200 end end end unless defined?(FakeStatus) module FakeStatus def status 318 end end end end after do Object.send(:remove_const, :FakeAction) Object.send(:remove_const, :FakeCallable) Object.send(:remove_const, :FakeStatus) end describe 'when not previously configured' do it 'is empty' do expect(configuration.modules).to be_empty end end describe 'when prepare with no block' do it 'raises error' do expect { configuration.prepare }.to raise_error(ArgumentError, 'Please provide a block') end end describe 'when previously configured' do before do configuration.prepare do include FakeCallable end end it 'allows to configure additional modules to include' do configuration.prepare do include FakeStatus end configuration.modules.each do |mod| FakeAction.class_eval(&mod) end code, _, body = FakeAction.new.call({}) expect(code).to be(318) expect(body).to eq(['Callable']) end end it 'allows to configure modules to include' do configuration.prepare do include FakeCallable end configuration.modules.each do |mod| FakeAction.class_eval(&mod) end code, _, body = FakeAction.new.call({}) expect(code).to be(200) expect(body).to eq(['Callable']) end end describe '#format' do before do configuration.format custom: 'custom/format' BaseObject = Class.new(BasicObject) do def hash 23 end end end after do Object.send(:remove_const, :BaseObject) end it 'registers the given format' do expect(configuration.format_for('custom/format')).to eq(:custom) end it 'raises an error if the given format cannot be coerced into symbol' do expect { configuration.format(23 => 'boom') }.to raise_error(TypeError) end it 'raises an error if the given mime type cannot be coerced into string' do expect { configuration.format(boom: BaseObject.new) }.to raise_error(TypeError) end end describe '#mime_types' do before do configuration.format custom: 'custom/format' end it 'returns all known MIME types' do all = ["custom/format"] expect(configuration.mime_types).to eq(all + Hanami::Action::Mime::MIME_TYPES.values) end it 'returns correct values even after the value is cached' do configuration.mime_types configuration.format electroneering: 'custom/electroneering' all = ["custom/format", "custom/electroneering"] expect(configuration.mime_types).to eq(all + Hanami::Action::Mime::MIME_TYPES.values) end end describe '#default_request_format' do describe "when not previously set" do it 'returns nil' do expect(configuration.default_request_format).to be(nil) end end describe "when set" do before do configuration.default_request_format :html end it 'returns the value' do expect(configuration.default_request_format).to eq(:html) end end it 'raises an error if the given format cannot be coerced into symbol' do expect { configuration.default_request_format(23) }.to raise_error(TypeError) end end describe '#default_response_format' do describe "when not previously set" do it 'returns nil' do expect(configuration.default_response_format).to be(nil) end end describe "when set" do before do configuration.default_response_format :json end it 'returns the value' do expect(configuration.default_response_format).to eq(:json) end end it 'raises an error if the given format cannot be coerced into symbol' do expect { configuration.default_response_format(23) }.to raise_error(TypeError) end end describe '#default_charset' do describe "when not previously set" do it 'returns nil' do expect(configuration.default_charset).to be(nil) end end describe "when set" do before do configuration.default_charset 'latin1' end it 'returns the value' do expect(configuration.default_charset).to eq('latin1') end end end describe '#format_for' do it 'returns a symbol from the given mime type' do expect(configuration.format_for('*/*')).to eq(:all) expect(configuration.format_for('application/octet-stream')).to eq(:all) expect(configuration.format_for('text/html')).to eq(:html) end describe 'with custom defined formats' do before do configuration.format htm: 'text/html' end after do configuration.reset! end it 'returns the custom defined mime type, which takes the precedence over the builtin value' do expect(configuration.format_for('text/html')).to eq(:htm) end end end describe '#mime_type_for' do it 'returns a mime type from the given symbol' do expect(configuration.mime_type_for(:all)).to eq('application/octet-stream') expect(configuration.mime_type_for(:html)).to eq('text/html') end describe 'with custom defined formats' do before do configuration.format htm: 'text/html' end after do configuration.reset! end it 'returns the custom defined format, which takes the precedence over the builtin value' do expect(configuration.mime_type_for(:htm)).to eq('text/html') end end end describe '#default_headers' do after do configuration.reset! end describe "when not previously set" do it 'returns default value' do expect(configuration.default_headers).to eq({}) end end describe "when set" do let(:headers) { { 'X-Frame-Options' => 'DENY' } } before do configuration.default_headers(headers) end it 'returns the value' do expect(configuration.default_headers).to eq(headers) end describe "multiple times" do before do configuration.default_headers(headers) configuration.default_headers('X-Foo' => 'BAR') end it 'returns the value' do expect(configuration.default_headers).to eq( 'X-Frame-Options' => 'DENY', 'X-Foo' => 'BAR' ) end end describe "with nil values" do before do configuration.default_headers(headers) configuration.default_headers('X-NIL' => nil) end it 'rejects those' do expect(configuration.default_headers).to eq(headers) end end end end describe "#public_directory" do describe "when not previously set" do it "returns default value" do expected = ::File.join(Dir.pwd, 'public') actual = configuration.public_directory # NOTE: For Rack compatibility it's important to have a string as public directory expect(actual).to be_kind_of(String) expect(actual).to eq(expected) end end describe "when set with relative path" do before do configuration.public_directory 'static' end it "returns the value" do expected = ::File.join(Dir.pwd, 'static') actual = configuration.public_directory # NOTE: For Rack compatibility it's important to have a string as public directory expect(actual).to be_kind_of(String) expect(actual).to eq(expected) end end describe "when set with absolute path" do before do configuration.public_directory ::File.join(Dir.pwd, 'absolute') end it "returns the value" do expected = ::File.join(Dir.pwd, 'absolute') actual = configuration.public_directory # NOTE: For Rack compatibility it's important to have a string as public directory expect(actual).to be_kind_of(String) expect(actual).to eq(expected) end end end describe 'duplicate' do before do configuration.reset! configuration.prepare { include Kernel } configuration.format custom: 'custom/format' configuration.default_request_format :html configuration.default_response_format :html configuration.default_charset 'latin1' configuration.default_headers({ 'X-Frame-Options' => 'DENY' }) configuration.public_directory 'static' end let(:config) { configuration.duplicate } it 'returns a copy of the configuration' do expect(config.handle_exceptions).to eq(configuration.handle_exceptions) expect(config.handled_exceptions).to eq(configuration.handled_exceptions) expect(config.action_module).to eq(configuration.action_module) expect(config.modules).to eq(configuration.modules) expect(config.send(:formats)).to eq(configuration.send(:formats)) expect(config.mime_types).to eq(configuration.mime_types) expect(config.default_request_format).to eq(configuration.default_request_format) expect(config.default_response_format).to eq(configuration.default_response_format) expect(config.default_charset).to eq(configuration.default_charset) expect(config.default_headers).to eq(configuration.default_headers) expect(config.public_directory).to eq(configuration.public_directory) end it "doesn't affect the original configuration" do config.handle_exceptions = false config.handle_exception ArgumentError => 400 config.action_module CustomAction config.prepare { include Comparable } config.format another: 'another/format' config.default_request_format :json config.default_response_format :json config.default_charset 'utf-8' config.default_headers({ 'X-Frame-Options' => 'ALLOW ALL' }) config.public_directory 'pub' expect(config.handle_exceptions).to be(false) expect(config.handled_exceptions).to eq(ArgumentError => 400) expect(config.action_module).to eq(CustomAction) expect(config.modules.size).to be(2) expect(config.format_for('another/format')).to eq(:another) expect(config.mime_types).to include('another/format') expect(config.default_request_format).to eq(:json) expect(config.default_response_format).to eq(:json) expect(config.default_charset).to eq('utf-8') expect(config.default_headers).to eq('X-Frame-Options' => 'ALLOW ALL') expect(config.public_directory).to eq(::File.join(Dir.pwd, 'pub')) expect(configuration.handle_exceptions).to be(true) expect(configuration.handled_exceptions).to eq({}) expect(configuration.action_module).to eq(::Hanami::Action) expect(configuration.modules.size).to be(1) expect(configuration.format_for('another/format')).to be(nil) expect(configuration.mime_types).to_not include('another/format') expect(configuration.default_request_format).to eq(:html) expect(configuration.default_response_format).to eq(:html) expect(configuration.default_charset).to eq('latin1') expect(configuration.default_headers).to eq('X-Frame-Options' => 'DENY') expect(configuration.public_directory).to eq(::File.join(Dir.pwd, 'static')) end end describe 'reset!' do before do configuration.handle_exceptions = false configuration.handle_exception ArgumentError => 400 configuration.action_module CustomAction configuration.modules { include Kernel } configuration.format another: 'another/format' configuration.default_request_format :another configuration.default_response_format :another configuration.default_charset 'kor-1' configuration.default_headers({ 'X-Frame-Options' => 'ALLOW DENY' }) configuration.public_directory 'files' configuration.reset! end it 'resets to the defaults' do expect(configuration.handle_exceptions).to be(true) expect(configuration.handled_exceptions).to eq({}) expect(configuration.action_module).to eq(::Hanami::Action) expect(configuration.modules).to eq([]) expect(configuration.send(:formats)).to eq(Hanami::Controller::Configuration::DEFAULT_FORMATS) expect(configuration.mime_types).to eq(Hanami::Action::Mime::MIME_TYPES.values) expect(configuration.default_request_format).to be(nil) expect(configuration.default_response_format).to be(nil) expect(configuration.default_charset).to be(nil) expect(configuration.default_headers).to eq({}) expect(configuration.public_directory).to eq(::File.join(Dir.pwd, 'public')) end end end
{ "pile_set_name": "Github" }
from rl_coach.agents.td3_agent import TD3AgentParameters from rl_coach.architectures.layers import Dense from rl_coach.base_parameters import VisualizationParameters, PresetValidationParameters, EmbedderScheme from rl_coach.core_types import EnvironmentEpisodes, EnvironmentSteps from rl_coach.environments.environment import SingleLevelSelection from rl_coach.environments.gym_environment import GymVectorEnvironment, mujoco_v2 from rl_coach.graph_managers.basic_rl_graph_manager import BasicRLGraphManager from rl_coach.graph_managers.graph_manager import ScheduleParameters #################### # Graph Scheduling # #################### schedule_params = ScheduleParameters() schedule_params.improve_steps = EnvironmentSteps(1000000) schedule_params.steps_between_evaluation_periods = EnvironmentSteps(5000) schedule_params.evaluation_steps = EnvironmentEpisodes(10) schedule_params.heatup_steps = EnvironmentSteps(10000) ######### # Agent # ######### agent_params = TD3AgentParameters() agent_params.network_wrappers['actor'].input_embedders_parameters['observation'].scheme = [Dense(400)] agent_params.network_wrappers['actor'].middleware_parameters.scheme = [Dense(300)] agent_params.network_wrappers['critic'].input_embedders_parameters['observation'].scheme = EmbedderScheme.Empty agent_params.network_wrappers['critic'].input_embedders_parameters['action'].scheme = EmbedderScheme.Empty agent_params.network_wrappers['critic'].middleware_parameters.scheme = [Dense(400), Dense(300)] ############### # Environment # ############### env_params = GymVectorEnvironment(level=SingleLevelSelection(mujoco_v2)) ######## # Test # ######## preset_validation_params = PresetValidationParameters() preset_validation_params.test = True preset_validation_params.min_reward_threshold = 500 preset_validation_params.max_episodes_to_achieve_reward = 1100 preset_validation_params.reward_test_level = 'hopper' preset_validation_params.trace_test_levels = ['inverted_pendulum', 'hopper'] graph_manager = BasicRLGraphManager(agent_params=agent_params, env_params=env_params, schedule_params=schedule_params, vis_params=VisualizationParameters(), preset_validation_params=preset_validation_params)
{ "pile_set_name": "Github" }
<?php return [ 'recurring' => 'განმეორებადი', 'every' => 'ყოველი', 'period' => 'პერიოდი', 'times' => 'დრო', 'daily' => 'ყოველდღე', 'weekly' => 'ყოველკვირა', 'monthly' => 'ყოველთვე', 'yearly' => 'ყოველწლიურად', 'custom' => 'მომხმარებელი', 'days' => 'დღე(ები)', 'weeks' => 'კვირა(კვირები)', 'months' => 'თვე(ები)', 'years' => 'წელი(წლები)', 'message' => 'ეს არის განმეორებადი :ტიპი და შემდეგი :ტიპი ავტომატურად დაგენერირდება :თარიღი', ];
{ "pile_set_name": "Github" }
// // BluetoothKit // // Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public func == (lhs: BKDiscoveriesChange, rhs: BKDiscoveriesChange) -> Bool { switch (lhs, rhs) { case (.insert(let lhsDiscovery), .insert(let rhsDiscovery)): return lhsDiscovery == rhsDiscovery || lhsDiscovery == nil || rhsDiscovery == nil case (.remove(let lhsDiscovery), .remove(let rhsDiscovery)): return lhsDiscovery == rhsDiscovery || lhsDiscovery == nil || rhsDiscovery == nil default: return false } } /** Change in available discoveries. - Insert: A new discovery. - Remove: A discovery has become unavailable. Cases without associated discoveries can be used to validate whether or not a change is and insert or a remove. */ public enum BKDiscoveriesChange: Equatable { case insert(discovery: BKDiscovery?) case remove(discovery: BKDiscovery?) /// The discovery associated with the change. public var discovery: BKDiscovery! { switch self { case .insert(let discovery): return discovery case .remove(let discovery): return discovery } } }
{ "pile_set_name": "Github" }
reviewers: - lavalamp - smarterclayton - wojtek-t - deads2k - derekwaynecarr - caesarxuchao - vishh - mikedanese - liggitt - nikhiljindal - erictune - pmorie - dchen1107 - saad-ali - luxas - yifan-gu - eparis - mwielgus - timothysc - jsafrane - dims - krousey - a-robinson - aveshagarwal - resouer - cjcullen
{ "pile_set_name": "Github" }
console.log('b');
{ "pile_set_name": "Github" }
context("Checking car") test_that("car ...",{ })
{ "pile_set_name": "Github" }
/* Copyright (C) 2007 Thomas Jahns <[email protected]> Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef EIS_SEQUENCEMULTIREAD_H #define EIS_SEQUENCEMULTIREAD_H /** * \file eis-sequencemultiread.h * Keeps information about multiple synchronous reads of sequence * data, where only one source and multiple consumers exist. */ #include "core/assert_api.h" #include "core/minmax_api.h" #include "match/eis-seqdatasrc.h" /** every reader is identified by a unique scalar */ typedef unsigned consumerID; /* moves data that can no longer be regenerated to the backlog */ typedef void (*move2BacklogFunc)(void *backlogState, const void *seqData, GtUword requestStart, size_t requestLen); /** * basic idea: let this function write the required data to output * and also call the move2Backlog callback if any data will be * invalidated after this call and is still required by other consumers * @return number of elements actually generated (might be short on eof etc.) */ typedef size_t (*generatorFunc)(void *generatorState, void *backlogState, move2BacklogFunc move2Backlog, void *output, GtUword generateStart, size_t len, SeqDataTranslator xltor); typedef struct seqReaderSet SeqReaderSet; struct seqReaderSet { int numConsumers, numAutoConsumers; int tagSuperSet; struct seqReaderState *consumerList; struct seqSinkState *autoConsumerList; GtUword backlogStartPos; bool fromSuffixsortspace; size_t backlogSize, backlogLen, backlogElemSize; void *seqDataBacklog, *generatorState; generatorFunc generator; }; /** * @return numReaders if all consumers registered otherwise */ /* int gt_initSeqReaderSet(SeqReaderSet *readerSet, int initialSuperSet, int numConsumers, int *tags, SeqDataTranslator xltors[], SeqDataReader *generatedReaders, size_t seqElemSize, generatorFunc generator, void *generatorState); */ void gt_initEmptySeqReaderSet(SeqReaderSet *readerSet, int initialSuperSet, bool fromSuffixsortspace, size_t seqElemSize, generatorFunc generator, void *generatorState); /** * @return readData field will be NULL on error -> test with * SDRIsValid */ SeqDataReader gt_seqReaderSetRegisterConsumer(SeqReaderSet *readerSet, int tag, SeqDataTranslator xltor); /** * @brief The registered writer will be called automatically for any * data that is to be invalidated. * * @return false on error, true if successfully registered */ bool gt_seqReaderSetRegisterAutoConsumer(SeqReaderSet *readerSet, int tag, SeqDataWriter writer); void gt_destructSeqReaderSet(SeqReaderSet *readerSet); #endif
{ "pile_set_name": "Github" }
/** * @license AngularJS v1.2.13 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) { 'use strict'; /** * @ngdoc overview * @name angular.mock * @description * * Namespace from 'angular-mocks.js' which contains testing related code. */ angular.mock = {}; /** * ! This is a private undocumented service ! * * @name ngMock.$browser * * @description * This service is a mock implementation of {@link ng.$browser}. It provides fake * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr, * cookies, etc... * * The api of this service is the same as that of the real {@link ng.$browser $browser}, except * that there are several helper methods available which can be used in tests. */ angular.mock.$BrowserProvider = function() { this.$get = function() { return new angular.mock.$Browser(); }; }; angular.mock.$Browser = function() { var self = this; this.isMock = true; self.$$url = "http://server/"; self.$$lastUrl = self.$$url; // used by url polling fn self.pollFns = []; // TODO(vojta): remove this temporary api self.$$completeOutstandingRequest = angular.noop; self.$$incOutstandingRequestCount = angular.noop; // register url polling fn self.onUrlChange = function(listener) { self.pollFns.push( function() { if (self.$$lastUrl != self.$$url) { self.$$lastUrl = self.$$url; listener(self.$$url); } } ); return listener; }; self.cookieHash = {}; self.lastCookieHash = {}; self.deferredFns = []; self.deferredNextId = 0; self.defer = function(fn, delay) { delay = delay || 0; self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId}); self.deferredFns.sort(function(a,b){ return a.time - b.time;}); return self.deferredNextId++; }; /** * @name ngMock.$browser#defer.now * @propertyOf ngMock.$browser * * @description * Current milliseconds mock time. */ self.defer.now = 0; self.defer.cancel = function(deferId) { var fnIndex; angular.forEach(self.deferredFns, function(fn, index) { if (fn.id === deferId) fnIndex = index; }); if (fnIndex !== undefined) { self.deferredFns.splice(fnIndex, 1); return true; } return false; }; /** * @name ngMock.$browser#defer.flush * @methodOf ngMock.$browser * * @description * Flushes all pending requests and executes the defer callbacks. * * @param {number=} number of milliseconds to flush. See {@link #defer.now} */ self.defer.flush = function(delay) { if (angular.isDefined(delay)) { self.defer.now += delay; } else { if (self.deferredFns.length) { self.defer.now = self.deferredFns[self.deferredFns.length-1].time; } else { throw new Error('No deferred tasks to be flushed'); } } while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) { self.deferredFns.shift().fn(); } }; self.$$baseHref = ''; self.baseHref = function() { return this.$$baseHref; }; }; angular.mock.$Browser.prototype = { /** * @name ngMock.$browser#poll * @methodOf ngMock.$browser * * @description * run all fns in pollFns */ poll: function poll() { angular.forEach(this.pollFns, function(pollFn){ pollFn(); }); }, addPollFn: function(pollFn) { this.pollFns.push(pollFn); return pollFn; }, url: function(url, replace) { if (url) { this.$$url = url; return this; } return this.$$url; }, cookies: function(name, value) { if (name) { if (angular.isUndefined(value)) { delete this.cookieHash[name]; } else { if (angular.isString(value) && //strings only value.length <= 4096) { //strict cookie storage limits this.cookieHash[name] = value; } } } else { if (!angular.equals(this.cookieHash, this.lastCookieHash)) { this.lastCookieHash = angular.copy(this.cookieHash); this.cookieHash = angular.copy(this.cookieHash); } return this.cookieHash; } }, notifyWhenNoOutstandingRequests: function(fn) { fn(); } }; /** * @ngdoc object * @name ngMock.$exceptionHandlerProvider * * @description * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors * passed into the `$exceptionHandler`. */ /** * @ngdoc object * @name ngMock.$exceptionHandler * * @description * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed * into it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration * information. * * * <pre> * describe('$exceptionHandlerProvider', function() { * * it('should capture log messages and exceptions', function() { * * module(function($exceptionHandlerProvider) { * $exceptionHandlerProvider.mode('log'); * }); * * inject(function($log, $exceptionHandler, $timeout) { * $timeout(function() { $log.log(1); }); * $timeout(function() { $log.log(2); throw 'banana peel'; }); * $timeout(function() { $log.log(3); }); * expect($exceptionHandler.errors).toEqual([]); * expect($log.assertEmpty()); * $timeout.flush(); * expect($exceptionHandler.errors).toEqual(['banana peel']); * expect($log.log.logs).toEqual([[1], [2], [3]]); * }); * }); * }); * </pre> */ angular.mock.$ExceptionHandlerProvider = function() { var handler; /** * @ngdoc method * @name ngMock.$exceptionHandlerProvider#mode * @methodOf ngMock.$exceptionHandlerProvider * * @description * Sets the logging mode. * * @param {string} mode Mode of operation, defaults to `rethrow`. * * - `rethrow`: If any errors are passed into the handler in tests, it typically * means that there is a bug in the application or test, so this mock will * make these tests fail. * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log` * mode stores an array of errors in `$exceptionHandler.errors`, to allow later * assertion of them. See {@link ngMock.$log#assertEmpty assertEmpty()} and * {@link ngMock.$log#reset reset()} */ this.mode = function(mode) { switch(mode) { case 'rethrow': handler = function(e) { throw e; }; break; case 'log': var errors = []; handler = function(e) { if (arguments.length == 1) { errors.push(e); } else { errors.push([].slice.call(arguments, 0)); } }; handler.errors = errors; break; default: throw new Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!"); } }; this.$get = function() { return handler; }; this.mode('rethrow'); }; /** * @ngdoc service * @name ngMock.$log * * @description * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays * (one array per logging level). These arrays are exposed as `logs` property of each of the * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`. * */ angular.mock.$LogProvider = function() { var debug = true; function concat(array1, array2, index) { return array1.concat(Array.prototype.slice.call(array2, index)); } this.debugEnabled = function(flag) { if (angular.isDefined(flag)) { debug = flag; return this; } else { return debug; } }; this.$get = function () { var $log = { log: function() { $log.log.logs.push(concat([], arguments, 0)); }, warn: function() { $log.warn.logs.push(concat([], arguments, 0)); }, info: function() { $log.info.logs.push(concat([], arguments, 0)); }, error: function() { $log.error.logs.push(concat([], arguments, 0)); }, debug: function() { if (debug) { $log.debug.logs.push(concat([], arguments, 0)); } } }; /** * @ngdoc method * @name ngMock.$log#reset * @methodOf ngMock.$log * * @description * Reset all of the logging arrays to empty. */ $log.reset = function () { /** * @ngdoc property * @name ngMock.$log#log.logs * @propertyOf ngMock.$log * * @description * Array of messages logged using {@link ngMock.$log#log}. * * @example * <pre> * $log.log('Some Log'); * var first = $log.log.logs.unshift(); * </pre> */ $log.log.logs = []; /** * @ngdoc property * @name ngMock.$log#info.logs * @propertyOf ngMock.$log * * @description * Array of messages logged using {@link ngMock.$log#info}. * * @example * <pre> * $log.info('Some Info'); * var first = $log.info.logs.unshift(); * </pre> */ $log.info.logs = []; /** * @ngdoc property * @name ngMock.$log#warn.logs * @propertyOf ngMock.$log * * @description * Array of messages logged using {@link ngMock.$log#warn}. * * @example * <pre> * $log.warn('Some Warning'); * var first = $log.warn.logs.unshift(); * </pre> */ $log.warn.logs = []; /** * @ngdoc property * @name ngMock.$log#error.logs * @propertyOf ngMock.$log * * @description * Array of messages logged using {@link ngMock.$log#error}. * * @example * <pre> * $log.error('Some Error'); * var first = $log.error.logs.unshift(); * </pre> */ $log.error.logs = []; /** * @ngdoc property * @name ngMock.$log#debug.logs * @propertyOf ngMock.$log * * @description * Array of messages logged using {@link ngMock.$log#debug}. * * @example * <pre> * $log.debug('Some Error'); * var first = $log.debug.logs.unshift(); * </pre> */ $log.debug.logs = []; }; /** * @ngdoc method * @name ngMock.$log#assertEmpty * @methodOf ngMock.$log * * @description * Assert that the all of the logging methods have no logged messages. If messages present, an * exception is thrown. */ $log.assertEmpty = function() { var errors = []; angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) { angular.forEach($log[logLevel].logs, function(log) { angular.forEach(log, function (logItem) { errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || '')); }); }); }); if (errors.length) { errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or "+ "an expected log message was not checked and removed:"); errors.push(''); throw new Error(errors.join('\n---------\n')); } }; $log.reset(); return $log; }; }; /** * @ngdoc service * @name ngMock.$interval * * @description * Mock implementation of the $interval service. * * Use {@link ngMock.$interval#methods_flush `$interval.flush(millis)`} to * move forward by `millis` milliseconds and trigger any functions scheduled to run in that * time. * * @param {function()} fn A function that should be called repeatedly. * @param {number} delay Number of milliseconds between each function call. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat * indefinitely. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#methods_$apply $apply} block. * @returns {promise} A promise which will be notified on each iteration. */ angular.mock.$IntervalProvider = function() { this.$get = ['$rootScope', '$q', function($rootScope, $q) { var repeatFns = [], nextRepeatId = 0, now = 0; var $interval = function(fn, delay, count, invokeApply) { var deferred = $q.defer(), promise = deferred.promise, iteration = 0, skipApply = (angular.isDefined(invokeApply) && !invokeApply); count = (angular.isDefined(count)) ? count : 0, promise.then(null, null, fn); promise.$$intervalId = nextRepeatId; function tick() { deferred.notify(iteration++); if (count > 0 && iteration >= count) { var fnIndex; deferred.resolve(iteration); angular.forEach(repeatFns, function(fn, index) { if (fn.id === promise.$$intervalId) fnIndex = index; }); if (fnIndex !== undefined) { repeatFns.splice(fnIndex, 1); } } if (!skipApply) $rootScope.$apply(); } repeatFns.push({ nextTime:(now + delay), delay: delay, fn: tick, id: nextRepeatId, deferred: deferred }); repeatFns.sort(function(a,b){ return a.nextTime - b.nextTime;}); nextRepeatId++; return promise; }; $interval.cancel = function(promise) { if(!promise) return false; var fnIndex; angular.forEach(repeatFns, function(fn, index) { if (fn.id === promise.$$intervalId) fnIndex = index; }); if (fnIndex !== undefined) { repeatFns[fnIndex].deferred.reject('canceled'); repeatFns.splice(fnIndex, 1); return true; } return false; }; /** * @ngdoc method * @name ngMock.$interval#flush * @methodOf ngMock.$interval * @description * * Runs interval tasks scheduled to be run in the next `millis` milliseconds. * * @param {number=} millis maximum timeout amount to flush up until. * * @return {number} The amount of time moved forward. */ $interval.flush = function(millis) { now += millis; while (repeatFns.length && repeatFns[0].nextTime <= now) { var task = repeatFns[0]; task.fn(); task.nextTime += task.delay; repeatFns.sort(function(a,b){ return a.nextTime - b.nextTime;}); } return millis; }; return $interval; }]; }; /* jshint -W101 */ /* The R_ISO8061_STR regex is never going to fit into the 100 char limit! * This directive should go inside the anonymous function but a bug in JSHint means that it would * not be enacted early enough to prevent the warning. */ var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; function jsonStringToDate(string) { var match; if (match = string.match(R_ISO8061_STR)) { var date = new Date(0), tzHour = 0, tzMin = 0; if (match[9]) { tzHour = int(match[9] + match[10]); tzMin = int(match[9] + match[11]); } date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3])); date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0)); return date; } return string; } function int(str) { return parseInt(str, 10); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while(num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } /** * @ngdoc object * @name angular.mock.TzDate * @description * * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`. * * Mock of the Date type which has its timezone specified via constructor arg. * * The main purpose is to create Date-like instances with timezone fixed to the specified timezone * offset, so that we can test code that depends on local timezone settings without dependency on * the time zone settings of the machine where the code is running. * * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored) * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC* * * @example * !!!! WARNING !!!!! * This is not a complete Date object so only methods that were implemented can be called safely. * To make matters worse, TzDate instances inherit stuff from Date via a prototype. * * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is * incomplete we might be missing some non-standard methods. This can result in errors like: * "Date.prototype.foo called on incompatible Object". * * <pre> * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z'); * newYearInBratislava.getTimezoneOffset() => -60; * newYearInBratislava.getFullYear() => 2010; * newYearInBratislava.getMonth() => 0; * newYearInBratislava.getDate() => 1; * newYearInBratislava.getHours() => 0; * newYearInBratislava.getMinutes() => 0; * newYearInBratislava.getSeconds() => 0; * </pre> * */ angular.mock.TzDate = function (offset, timestamp) { var self = new Date(0); if (angular.isString(timestamp)) { var tsStr = timestamp; self.origDate = jsonStringToDate(timestamp); timestamp = self.origDate.getTime(); if (isNaN(timestamp)) throw { name: "Illegal Argument", message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string" }; } else { self.origDate = new Date(timestamp); } var localOffset = new Date(timestamp).getTimezoneOffset(); self.offsetDiff = localOffset*60*1000 - offset*1000*60*60; self.date = new Date(timestamp + self.offsetDiff); self.getTime = function() { return self.date.getTime() - self.offsetDiff; }; self.toLocaleDateString = function() { return self.date.toLocaleDateString(); }; self.getFullYear = function() { return self.date.getFullYear(); }; self.getMonth = function() { return self.date.getMonth(); }; self.getDate = function() { return self.date.getDate(); }; self.getHours = function() { return self.date.getHours(); }; self.getMinutes = function() { return self.date.getMinutes(); }; self.getSeconds = function() { return self.date.getSeconds(); }; self.getMilliseconds = function() { return self.date.getMilliseconds(); }; self.getTimezoneOffset = function() { return offset * 60; }; self.getUTCFullYear = function() { return self.origDate.getUTCFullYear(); }; self.getUTCMonth = function() { return self.origDate.getUTCMonth(); }; self.getUTCDate = function() { return self.origDate.getUTCDate(); }; self.getUTCHours = function() { return self.origDate.getUTCHours(); }; self.getUTCMinutes = function() { return self.origDate.getUTCMinutes(); }; self.getUTCSeconds = function() { return self.origDate.getUTCSeconds(); }; self.getUTCMilliseconds = function() { return self.origDate.getUTCMilliseconds(); }; self.getDay = function() { return self.date.getDay(); }; // provide this method only on browsers that already have it if (self.toISOString) { self.toISOString = function() { return padNumber(self.origDate.getUTCFullYear(), 4) + '-' + padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' + padNumber(self.origDate.getUTCDate(), 2) + 'T' + padNumber(self.origDate.getUTCHours(), 2) + ':' + padNumber(self.origDate.getUTCMinutes(), 2) + ':' + padNumber(self.origDate.getUTCSeconds(), 2) + '.' + padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z'; }; } //hide all methods not implemented in this mock that the Date prototype exposes var unimplementedMethods = ['getUTCDay', 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString', 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf']; angular.forEach(unimplementedMethods, function(methodName) { self[methodName] = function() { throw new Error("Method '" + methodName + "' is not implemented in the TzDate mock"); }; }); return self; }; //make "tzDateInstance instanceof Date" return true angular.mock.TzDate.prototype = Date.prototype; /* jshint +W101 */ angular.mock.animate = angular.module('ngAnimateMock', ['ng']) .config(['$provide', function($provide) { var reflowQueue = []; $provide.value('$$animateReflow', function(fn) { reflowQueue.push(fn); return angular.noop; }); $provide.decorator('$animate', function($delegate) { var animate = { queue : [], enabled : $delegate.enabled, triggerReflow : function() { if(reflowQueue.length === 0) { throw new Error('No animation reflows present'); } angular.forEach(reflowQueue, function(fn) { fn(); }); reflowQueue = []; } }; angular.forEach( ['enter','leave','move','addClass','removeClass','setClass'], function(method) { animate[method] = function() { animate.queue.push({ event : method, element : arguments[0], args : arguments }); $delegate[method].apply($delegate, arguments); }; }); return animate; }); }]); /** * @ngdoc function * @name angular.mock.dump * @description * * *NOTE*: this is not an injectable instance, just a globally available function. * * Method for serializing util angular objects (scope, elements, etc..) into strings, useful for * debugging. * * This method is also available on window, where it can be used to display objects on debug * console. * * @param {*} object - any object to turn into string. * @return {string} a serialized string of the argument */ angular.mock.dump = function(object) { return serialize(object); function serialize(object) { var out; if (angular.isElement(object)) { object = angular.element(object); out = angular.element('<div></div>'); angular.forEach(object, function(element) { out.append(angular.element(element).clone()); }); out = out.html(); } else if (angular.isArray(object)) { out = []; angular.forEach(object, function(o) { out.push(serialize(o)); }); out = '[ ' + out.join(', ') + ' ]'; } else if (angular.isObject(object)) { if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) { out = serializeScope(object); } else if (object instanceof Error) { out = object.stack || ('' + object.name + ': ' + object.message); } else { // TODO(i): this prevents methods being logged, // we should have a better way to serialize objects out = angular.toJson(object, true); } } else { out = String(object); } return out; } function serializeScope(scope, offset) { offset = offset || ' '; var log = [offset + 'Scope(' + scope.$id + '): {']; for ( var key in scope ) { if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) { log.push(' ' + key + ': ' + angular.toJson(scope[key])); } } var child = scope.$$childHead; while(child) { log.push(serializeScope(child, offset + ' ')); child = child.$$nextSibling; } log.push('}'); return log.join('\n' + offset); } }; /** * @ngdoc object * @name ngMock.$httpBackend * @description * Fake HTTP backend implementation suitable for unit testing applications that use the * {@link ng.$http $http service}. * * *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}. * * During unit testing, we want our unit tests to run quickly and have no external dependencies so * we don’t want to send {@link https://developer.mozilla.org/en/xmlhttprequest XHR} or * {@link http://en.wikipedia.org/wiki/JSONP JSONP} requests to a real server. All we really need is * to verify whether a certain request has been sent or not, or alternatively just let the * application make requests, respond with pre-trained responses and assert that the end result is * what we expect it to be. * * This mock implementation can be used to respond with static or dynamic responses via the * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc). * * When an Angular application needs some data from a server, it calls the $http service, which * sends the request to a real server using $httpBackend service. With dependency injection, it is * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify * the requests and respond with some testing data without sending a request to real server. * * There are two ways to specify what test data should be returned as http responses by the mock * backend when the code under test makes http requests: * * - `$httpBackend.expect` - specifies a request expectation * - `$httpBackend.when` - specifies a backend definition * * * # Request Expectations vs Backend Definitions * * Request expectations provide a way to make assertions about requests made by the application and * to define responses for those requests. The test will fail if the expected requests are not made * or they are made in the wrong order. * * Backend definitions allow you to define a fake backend for your application which doesn't assert * if a particular request was made or not, it just returns a trained response if a request is made. * The test will pass whether or not the request gets made during testing. * * * <table class="table"> * <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr> * <tr> * <th>Syntax</th> * <td>.expect(...).respond(...)</td> * <td>.when(...).respond(...)</td> * </tr> * <tr> * <th>Typical usage</th> * <td>strict unit tests</td> * <td>loose (black-box) unit testing</td> * </tr> * <tr> * <th>Fulfills multiple requests</th> * <td>NO</td> * <td>YES</td> * </tr> * <tr> * <th>Order of requests matters</th> * <td>YES</td> * <td>NO</td> * </tr> * <tr> * <th>Request required</th> * <td>YES</td> * <td>NO</td> * </tr> * <tr> * <th>Response required</th> * <td>optional (see below)</td> * <td>YES</td> * </tr> * </table> * * In cases where both backend definitions and request expectations are specified during unit * testing, the request expectations are evaluated first. * * If a request expectation has no response specified, the algorithm will search your backend * definitions for an appropriate response. * * If a request didn't match any expectation or if the expectation doesn't have the response * defined, the backend definitions are evaluated in sequential order to see if any of them match * the request. The response from the first matched definition is returned. * * * # Flushing HTTP requests * * The $httpBackend used in production always responds to requests with responses asynchronously. * If we preserved this behavior in unit testing we'd have to create async unit tests, which are * hard to write, understand, and maintain. However, the testing mock can't respond * synchronously because that would change the execution of the code under test. For this reason the * mock $httpBackend has a `flush()` method, which allows the test to explicitly flush pending * requests and thus preserve the async api of the backend while allowing the test to execute * synchronously. * * * # Unit testing with mock $httpBackend * The following code shows how to setup and use the mock backend when unit testing a controller. * First we create the controller under test: * <pre> // The controller code function MyController($scope, $http) { var authToken; $http.get('/auth.py').success(function(data, status, headers) { authToken = headers('A-Token'); $scope.user = data; }); $scope.saveMessage = function(message) { var headers = { 'Authorization': authToken }; $scope.status = 'Saving...'; $http.post('/add-msg.py', message, { headers: headers } ).success(function(response) { $scope.status = ''; }).error(function() { $scope.status = 'ERROR!'; }); }; } </pre> * * Now we setup the mock backend and create the test specs: * <pre> // testing controller describe('MyController', function() { var $httpBackend, $rootScope, createController; beforeEach(inject(function($injector) { // Set up the mock http service responses $httpBackend = $injector.get('$httpBackend'); // backend definition util for all tests $httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'}); // Get hold of a scope (i.e. the root scope) $rootScope = $injector.get('$rootScope'); // The $controller service is used to create instances of controllers var $controller = $injector.get('$controller'); createController = function() { return $controller('MyController', {'$scope' : $rootScope }); }; })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it('should fetch authentication token', function() { $httpBackend.expectGET('/auth.py'); var controller = createController(); $httpBackend.flush(); }); it('should send msg to server', function() { var controller = createController(); $httpBackend.flush(); // now you don’t care about the authentication, but // the controller will still send the request and // $httpBackend will respond without you having to // specify the expectation and response for this request $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, ''); $rootScope.saveMessage('message content'); expect($rootScope.status).toBe('Saving...'); $httpBackend.flush(); expect($rootScope.status).toBe(''); }); it('should send auth header', function() { var controller = createController(); $httpBackend.flush(); $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) { // check if the header was send, if it wasn't the expectation won't // match the request and the test will fail return headers['Authorization'] == 'xxx'; }).respond(201, ''); $rootScope.saveMessage('whatever'); $httpBackend.flush(); }); }); </pre> */ angular.mock.$HttpBackendProvider = function() { this.$get = ['$rootScope', createHttpBackendMock]; }; /** * General factory function for $httpBackend mock. * Returns instance for unit testing (when no arguments specified): * - passing through is disabled * - auto flushing is disabled * * Returns instance for e2e testing (when `$delegate` and `$browser` specified): * - passing through (delegating request to real backend) is enabled * - auto flushing is enabled * * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified) * @param {Object=} $browser Auto-flushing enabled if specified * @return {Object} Instance of $httpBackend mock */ function createHttpBackendMock($rootScope, $delegate, $browser) { var definitions = [], expectations = [], responses = [], responsesPush = angular.bind(responses, responses.push), copy = angular.copy; function createResponse(status, data, headers) { if (angular.isFunction(status)) return status; return function() { return angular.isNumber(status) ? [status, data, headers] : [200, status, data]; }; } // TODO(vojta): change params to: method, url, data, headers, callback function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) { var xhr = new MockXhr(), expectation = expectations[0], wasExpected = false; function prettyPrint(data) { return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp) ? data : angular.toJson(data); } function wrapResponse(wrapped) { if (!$browser && timeout && timeout.then) timeout.then(handleTimeout); return handleResponse; function handleResponse() { var response = wrapped.response(method, url, data, headers); xhr.$$respHeaders = response[2]; callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders()); } function handleTimeout() { for (var i = 0, ii = responses.length; i < ii; i++) { if (responses[i] === handleResponse) { responses.splice(i, 1); callback(-1, undefined, ''); break; } } } } if (expectation && expectation.match(method, url)) { if (!expectation.matchData(data)) throw new Error('Expected ' + expectation + ' with different data\n' + 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data); if (!expectation.matchHeaders(headers)) throw new Error('Expected ' + expectation + ' with different headers\n' + 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' + prettyPrint(headers)); expectations.shift(); if (expectation.response) { responses.push(wrapResponse(expectation)); return; } wasExpected = true; } var i = -1, definition; while ((definition = definitions[++i])) { if (definition.match(method, url, data, headers || {})) { if (definition.response) { // if $browser specified, we do auto flush all requests ($browser ? $browser.defer : responsesPush)(wrapResponse(definition)); } else if (definition.passThrough) { $delegate(method, url, data, callback, headers, timeout, withCredentials); } else throw new Error('No response defined !'); return; } } throw wasExpected ? new Error('No response defined !') : new Error('Unexpected request: ' + method + ' ' + url + '\n' + (expectation ? 'Expected ' + expectation : 'No more request expected')); } /** * @ngdoc method * @name ngMock.$httpBackend#when * @methodOf ngMock.$httpBackend * @description * Creates a new backend definition. * * @param {string} method HTTP method. * @param {string|RegExp} url HTTP url. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. * * - respond – * `{function([status,] data[, headers])|function(function(method, url, data, headers)}` * – The respond method takes a set of static data to be returned or a function that can return * an array containing response status (number), response data (string) and response headers * (Object). */ $httpBackend.when = function(method, url, data, headers) { var definition = new MockHttpExpectation(method, url, data, headers), chain = { respond: function(status, data, headers) { definition.response = createResponse(status, data, headers); } }; if ($browser) { chain.passThrough = function() { definition.passThrough = true; }; } definitions.push(definition); return chain; }; /** * @ngdoc method * @name ngMock.$httpBackend#whenGET * @methodOf ngMock.$httpBackend * @description * Creates a new backend definition for GET requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ /** * @ngdoc method * @name ngMock.$httpBackend#whenHEAD * @methodOf ngMock.$httpBackend * @description * Creates a new backend definition for HEAD requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ /** * @ngdoc method * @name ngMock.$httpBackend#whenDELETE * @methodOf ngMock.$httpBackend * @description * Creates a new backend definition for DELETE requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ /** * @ngdoc method * @name ngMock.$httpBackend#whenPOST * @methodOf ngMock.$httpBackend * @description * Creates a new backend definition for POST requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ /** * @ngdoc method * @name ngMock.$httpBackend#whenPUT * @methodOf ngMock.$httpBackend * @description * Creates a new backend definition for PUT requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ /** * @ngdoc method * @name ngMock.$httpBackend#whenJSONP * @methodOf ngMock.$httpBackend * @description * Creates a new backend definition for JSONP requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ createShortMethods('when'); /** * @ngdoc method * @name ngMock.$httpBackend#expect * @methodOf ngMock.$httpBackend * @description * Creates a new request expectation. * * @param {string} method HTTP method. * @param {string|RegExp} url HTTP url. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current expectation. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. * * - respond – * `{function([status,] data[, headers])|function(function(method, url, data, headers)}` * – The respond method takes a set of static data to be returned or a function that can return * an array containing response status (number), response data (string) and response headers * (Object). */ $httpBackend.expect = function(method, url, data, headers) { var expectation = new MockHttpExpectation(method, url, data, headers); expectations.push(expectation); return { respond: function(status, data, headers) { expectation.response = createResponse(status, data, headers); } }; }; /** * @ngdoc method * @name ngMock.$httpBackend#expectGET * @methodOf ngMock.$httpBackend * @description * Creates a new request expectation for GET requests. For more info see `expect()`. * * @param {string|RegExp} url HTTP url. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. See #expect for more info. */ /** * @ngdoc method * @name ngMock.$httpBackend#expectHEAD * @methodOf ngMock.$httpBackend * @description * Creates a new request expectation for HEAD requests. For more info see `expect()`. * * @param {string|RegExp} url HTTP url. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ /** * @ngdoc method * @name ngMock.$httpBackend#expectDELETE * @methodOf ngMock.$httpBackend * @description * Creates a new request expectation for DELETE requests. For more info see `expect()`. * * @param {string|RegExp} url HTTP url. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ /** * @ngdoc method * @name ngMock.$httpBackend#expectPOST * @methodOf ngMock.$httpBackend * @description * Creates a new request expectation for POST requests. For more info see `expect()`. * * @param {string|RegExp} url HTTP url. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ /** * @ngdoc method * @name ngMock.$httpBackend#expectPUT * @methodOf ngMock.$httpBackend * @description * Creates a new request expectation for PUT requests. For more info see `expect()`. * * @param {string|RegExp} url HTTP url. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ /** * @ngdoc method * @name ngMock.$httpBackend#expectPATCH * @methodOf ngMock.$httpBackend * @description * Creates a new request expectation for PATCH requests. For more info see `expect()`. * * @param {string|RegExp} url HTTP url. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ /** * @ngdoc method * @name ngMock.$httpBackend#expectJSONP * @methodOf ngMock.$httpBackend * @description * Creates a new request expectation for JSONP requests. For more info see `expect()`. * * @param {string|RegExp} url HTTP url. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ createShortMethods('expect'); /** * @ngdoc method * @name ngMock.$httpBackend#flush * @methodOf ngMock.$httpBackend * @description * Flushes all pending requests using the trained responses. * * @param {number=} count Number of responses to flush (in the order they arrived). If undefined, * all pending requests will be flushed. If there are no pending requests when the flush method * is called an exception is thrown (as this typically a sign of programming error). */ $httpBackend.flush = function(count) { $rootScope.$digest(); if (!responses.length) throw new Error('No pending request to flush !'); if (angular.isDefined(count)) { while (count--) { if (!responses.length) throw new Error('No more pending request to flush !'); responses.shift()(); } } else { while (responses.length) { responses.shift()(); } } $httpBackend.verifyNoOutstandingExpectation(); }; /** * @ngdoc method * @name ngMock.$httpBackend#verifyNoOutstandingExpectation * @methodOf ngMock.$httpBackend * @description * Verifies that all of the requests defined via the `expect` api were made. If any of the * requests were not made, verifyNoOutstandingExpectation throws an exception. * * Typically, you would call this method following each test case that asserts requests using an * "afterEach" clause. * * <pre> * afterEach($httpBackend.verifyNoOutstandingExpectation); * </pre> */ $httpBackend.verifyNoOutstandingExpectation = function() { $rootScope.$digest(); if (expectations.length) { throw new Error('Unsatisfied requests: ' + expectations.join(', ')); } }; /** * @ngdoc method * @name ngMock.$httpBackend#verifyNoOutstandingRequest * @methodOf ngMock.$httpBackend * @description * Verifies that there are no outstanding requests that need to be flushed. * * Typically, you would call this method following each test case that asserts requests using an * "afterEach" clause. * * <pre> * afterEach($httpBackend.verifyNoOutstandingRequest); * </pre> */ $httpBackend.verifyNoOutstandingRequest = function() { if (responses.length) { throw new Error('Unflushed requests: ' + responses.length); } }; /** * @ngdoc method * @name ngMock.$httpBackend#resetExpectations * @methodOf ngMock.$httpBackend * @description * Resets all request expectations, but preserves all backend definitions. Typically, you would * call resetExpectations during a multiple-phase test when you want to reuse the same instance of * $httpBackend mock. */ $httpBackend.resetExpectations = function() { expectations.length = 0; responses.length = 0; }; return $httpBackend; function createShortMethods(prefix) { angular.forEach(['GET', 'DELETE', 'JSONP'], function(method) { $httpBackend[prefix + method] = function(url, headers) { return $httpBackend[prefix](method, url, undefined, headers); }; }); angular.forEach(['PUT', 'POST', 'PATCH'], function(method) { $httpBackend[prefix + method] = function(url, data, headers) { return $httpBackend[prefix](method, url, data, headers); }; }); } } function MockHttpExpectation(method, url, data, headers) { this.data = data; this.headers = headers; this.match = function(m, u, d, h) { if (method != m) return false; if (!this.matchUrl(u)) return false; if (angular.isDefined(d) && !this.matchData(d)) return false; if (angular.isDefined(h) && !this.matchHeaders(h)) return false; return true; }; this.matchUrl = function(u) { if (!url) return true; if (angular.isFunction(url.test)) return url.test(u); return url == u; }; this.matchHeaders = function(h) { if (angular.isUndefined(headers)) return true; if (angular.isFunction(headers)) return headers(h); return angular.equals(headers, h); }; this.matchData = function(d) { if (angular.isUndefined(data)) return true; if (data && angular.isFunction(data.test)) return data.test(d); if (data && angular.isFunction(data)) return data(d); if (data && !angular.isString(data)) return angular.equals(data, angular.fromJson(d)); return data == d; }; this.toString = function() { return method + ' ' + url; }; } function createMockXhr() { return new MockXhr(); } function MockXhr() { // hack for testing $http, $httpBackend MockXhr.$$lastInstance = this; this.open = function(method, url, async) { this.$$method = method; this.$$url = url; this.$$async = async; this.$$reqHeaders = {}; this.$$respHeaders = {}; }; this.send = function(data) { this.$$data = data; }; this.setRequestHeader = function(key, value) { this.$$reqHeaders[key] = value; }; this.getResponseHeader = function(name) { // the lookup must be case insensitive, // that's why we try two quick lookups first and full scan last var header = this.$$respHeaders[name]; if (header) return header; name = angular.lowercase(name); header = this.$$respHeaders[name]; if (header) return header; header = undefined; angular.forEach(this.$$respHeaders, function(headerVal, headerName) { if (!header && angular.lowercase(headerName) == name) header = headerVal; }); return header; }; this.getAllResponseHeaders = function() { var lines = []; angular.forEach(this.$$respHeaders, function(value, key) { lines.push(key + ': ' + value); }); return lines.join('\n'); }; this.abort = angular.noop; } /** * @ngdoc function * @name ngMock.$timeout * @description * * This service is just a simple decorator for {@link ng.$timeout $timeout} service * that adds a "flush" and "verifyNoPendingTasks" methods. */ angular.mock.$TimeoutDecorator = function($delegate, $browser) { /** * @ngdoc method * @name ngMock.$timeout#flush * @methodOf ngMock.$timeout * @description * * Flushes the queue of pending tasks. * * @param {number=} delay maximum timeout amount to flush up until */ $delegate.flush = function(delay) { $browser.defer.flush(delay); }; /** * @ngdoc method * @name ngMock.$timeout#verifyNoPendingTasks * @methodOf ngMock.$timeout * @description * * Verifies that there are no pending tasks that need to be flushed. */ $delegate.verifyNoPendingTasks = function() { if ($browser.deferredFns.length) { throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' + formatPendingTasksAsString($browser.deferredFns)); } }; function formatPendingTasksAsString(tasks) { var result = []; angular.forEach(tasks, function(task) { result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}'); }); return result.join(', '); } return $delegate; }; /** * */ angular.mock.$RootElementProvider = function() { this.$get = function() { return angular.element('<div ng-app></div>'); }; }; /** * @ngdoc overview * @name ngMock * @description * * # ngMock * * The `ngMock` module providers support to inject and mock Angular services into unit tests. * In addition, ngMock also extends various core ng services such that they can be * inspected and controlled in a synchronous manner within test code. * * {@installModule mock} * * <div doc-module-components="ngMock"></div> * */ angular.module('ngMock', ['ng']).provider({ $browser: angular.mock.$BrowserProvider, $exceptionHandler: angular.mock.$ExceptionHandlerProvider, $log: angular.mock.$LogProvider, $interval: angular.mock.$IntervalProvider, $httpBackend: angular.mock.$HttpBackendProvider, $rootElement: angular.mock.$RootElementProvider }).config(['$provide', function($provide) { $provide.decorator('$timeout', angular.mock.$TimeoutDecorator); }]); /** * @ngdoc overview * @name ngMockE2E * @description * * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing. * Currently there is only one mock present in this module - * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock. */ angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) { $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator); }]); /** * @ngdoc object * @name ngMockE2E.$httpBackend * @description * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of * applications that use the {@link ng.$http $http service}. * * *Note*: For fake http backend implementation suitable for unit testing please see * {@link ngMock.$httpBackend unit-testing $httpBackend mock}. * * This implementation can be used to respond with static or dynamic responses via the `when` api * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch * templates from a webserver). * * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application * is being developed with the real backend api replaced with a mock, it is often desirable for * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch * templates or static files from the webserver). To configure the backend with this behavior * use the `passThrough` request handler of `when` instead of `respond`. * * Additionally, we don't want to manually have to flush mocked out requests like we do during unit * testing. For this reason the e2e $httpBackend automatically flushes mocked out requests * automatically, closely simulating the behavior of the XMLHttpRequest object. * * To setup the application to run with this http backend, you have to create a module that depends * on the `ngMockE2E` and your application modules and defines the fake backend: * * <pre> * myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']); * myAppDev.run(function($httpBackend) { * phones = [{name: 'phone1'}, {name: 'phone2'}]; * * // returns the current list of phones * $httpBackend.whenGET('/phones').respond(phones); * * // adds a new phone to the phones array * $httpBackend.whenPOST('/phones').respond(function(method, url, data) { * phones.push(angular.fromJson(data)); * }); * $httpBackend.whenGET(/^\/templates\//).passThrough(); * //... * }); * </pre> * * Afterwards, bootstrap your app with this new module. */ /** * @ngdoc method * @name ngMockE2E.$httpBackend#when * @methodOf ngMockE2E.$httpBackend * @description * Creates a new backend definition. * * @param {string} method HTTP method. * @param {string|RegExp} url HTTP url. * @param {(string|RegExp)=} data HTTP request body. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. * * - respond – * `{function([status,] data[, headers])|function(function(method, url, data, headers)}` * – The respond method takes a set of static data to be returned or a function that can return * an array containing response status (number), response data (string) and response headers * (Object). * - passThrough – `{function()}` – Any request matching a backend definition with `passThrough` * handler, will be pass through to the real backend (an XHR request will be made to the * server. */ /** * @ngdoc method * @name ngMockE2E.$httpBackend#whenGET * @methodOf ngMockE2E.$httpBackend * @description * Creates a new backend definition for GET requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. */ /** * @ngdoc method * @name ngMockE2E.$httpBackend#whenHEAD * @methodOf ngMockE2E.$httpBackend * @description * Creates a new backend definition for HEAD requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. */ /** * @ngdoc method * @name ngMockE2E.$httpBackend#whenDELETE * @methodOf ngMockE2E.$httpBackend * @description * Creates a new backend definition for DELETE requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. */ /** * @ngdoc method * @name ngMockE2E.$httpBackend#whenPOST * @methodOf ngMockE2E.$httpBackend * @description * Creates a new backend definition for POST requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. * @param {(string|RegExp)=} data HTTP request body. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. */ /** * @ngdoc method * @name ngMockE2E.$httpBackend#whenPUT * @methodOf ngMockE2E.$httpBackend * @description * Creates a new backend definition for PUT requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. * @param {(string|RegExp)=} data HTTP request body. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. */ /** * @ngdoc method * @name ngMockE2E.$httpBackend#whenPATCH * @methodOf ngMockE2E.$httpBackend * @description * Creates a new backend definition for PATCH requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. * @param {(string|RegExp)=} data HTTP request body. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. */ /** * @ngdoc method * @name ngMockE2E.$httpBackend#whenJSONP * @methodOf ngMockE2E.$httpBackend * @description * Creates a new backend definition for JSONP requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. */ angular.mock.e2e = {}; angular.mock.e2e.$httpBackendDecorator = ['$rootScope', '$delegate', '$browser', createHttpBackendMock]; angular.mock.clearDataCache = function() { var key, cache = angular.element.cache; for(key in cache) { if (Object.prototype.hasOwnProperty.call(cache,key)) { var handle = cache[key].handle; handle && angular.element(handle.elem).off(); delete cache[key]; } } }; if(window.jasmine || window.mocha) { var currentSpec = null, isSpecRunning = function() { return !!currentSpec; }; beforeEach(function() { currentSpec = this; }); afterEach(function() { var injector = currentSpec.$injector; currentSpec.$injector = null; currentSpec.$modules = null; currentSpec = null; if (injector) { injector.get('$rootElement').off(); injector.get('$browser').pollFns.length = 0; } angular.mock.clearDataCache(); // clean up jquery's fragment cache angular.forEach(angular.element.fragments, function(val, key) { delete angular.element.fragments[key]; }); MockXhr.$$lastInstance = null; angular.forEach(angular.callbacks, function(val, key) { delete angular.callbacks[key]; }); angular.callbacks.counter = 0; }); /** * @ngdoc function * @name angular.mock.module * @description * * *NOTE*: This function is also published on window for easy access.<br> * * This function registers a module configuration code. It collects the configuration information * which will be used when the injector is created by {@link angular.mock.inject inject}. * * See {@link angular.mock.inject inject} for usage example * * @param {...(string|Function|Object)} fns any number of modules which are represented as string * aliases or as anonymous module initialization functions. The modules are used to * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an * object literal is passed they will be register as values in the module, the key being * the module name and the value being what is returned. */ window.module = angular.mock.module = function() { var moduleFns = Array.prototype.slice.call(arguments, 0); return isSpecRunning() ? workFn() : workFn; ///////////////////// function workFn() { if (currentSpec.$injector) { throw new Error('Injector already created, can not register a module!'); } else { var modules = currentSpec.$modules || (currentSpec.$modules = []); angular.forEach(moduleFns, function(module) { if (angular.isObject(module) && !angular.isArray(module)) { modules.push(function($provide) { angular.forEach(module, function(value, key) { $provide.value(key, value); }); }); } else { modules.push(module); } }); } } }; /** * @ngdoc function * @name angular.mock.inject * @description * * *NOTE*: This function is also published on window for easy access.<br> * * The inject function wraps a function into an injectable function. The inject() creates new * instance of {@link AUTO.$injector $injector} per test, which is then used for * resolving references. * * * ## Resolving References (Underscore Wrapping) * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable * that is declared in the scope of the `describe()` block. Since we would, most likely, want * the variable to have the same name of the reference we have a problem, since the parameter * to the `inject()` function would hide the outer variable. * * To help with this, the injected parameters can, optionally, be enclosed with underscores. * These are ignored by the injector when the reference name is resolved. * * For example, the parameter `_myService_` would be resolved as the reference `myService`. * Since it is available in the function body as _myService_, we can then assign it to a variable * defined in an outer scope. * * ``` * // Defined out reference variable outside * var myService; * * // Wrap the parameter in underscores * beforeEach( inject( function(_myService_){ * myService = _myService_; * })); * * // Use myService in a series of tests. * it('makes use of myService', function() { * myService.doStuff(); * }); * * ``` * * See also {@link angular.mock.module angular.mock.module} * * ## Example * Example of what a typical jasmine tests looks like with the inject method. * <pre> * * angular.module('myApplicationModule', []) * .value('mode', 'app') * .value('version', 'v1.0.1'); * * * describe('MyApp', function() { * * // You need to load modules that you want to test, * // it loads only the "ng" module by default. * beforeEach(module('myApplicationModule')); * * * // inject() is used to inject arguments of all given functions * it('should provide a version', inject(function(mode, version) { * expect(version).toEqual('v1.0.1'); * expect(mode).toEqual('app'); * })); * * * // The inject and module method can also be used inside of the it or beforeEach * it('should override a version and test the new version is injected', function() { * // module() takes functions or strings (module aliases) * module(function($provide) { * $provide.value('version', 'overridden'); // override version here * }); * * inject(function(version) { * expect(version).toEqual('overridden'); * }); * }); * }); * * </pre> * * @param {...Function} fns any number of functions which will be injected using the injector. */ var ErrorAddingDeclarationLocationStack = function(e, errorForStack) { this.message = e.message; this.name = e.name; if (e.line) this.line = e.line; if (e.sourceId) this.sourceId = e.sourceId; if (e.stack && errorForStack) this.stack = e.stack + '\n' + errorForStack.stack; if (e.stackArray) this.stackArray = e.stackArray; }; ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString; window.inject = angular.mock.inject = function() { var blockFns = Array.prototype.slice.call(arguments, 0); var errorForStack = new Error('Declaration Location'); return isSpecRunning() ? workFn.call(currentSpec) : workFn; ///////////////////// function workFn() { var modules = currentSpec.$modules || []; modules.unshift('ngMock'); modules.unshift('ng'); var injector = currentSpec.$injector; if (!injector) { injector = currentSpec.$injector = angular.injector(modules); } for(var i = 0, ii = blockFns.length; i < ii; i++) { try { /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */ injector.invoke(blockFns[i] || angular.noop, this); /* jshint +W040 */ } catch (e) { if (e.stack && errorForStack) { throw new ErrorAddingDeclarationLocationStack(e, errorForStack); } throw e; } finally { errorForStack = null; } } } }; } })(window, window.angular);
{ "pile_set_name": "Github" }
import _ from 'lodash-es'; import { KubernetesServiceHeadlessPrefix } from 'Kubernetes/models/service/models'; class KubernetesServiceHelper { static generateHeadlessServiceName(name) { return KubernetesServiceHeadlessPrefix + name; } static findApplicationBoundService(services, rawApp) { return _.find(services, (item) => item.spec.selector && _.isMatch(rawApp.spec.template.metadata.labels, item.spec.selector)); } } export default KubernetesServiceHelper;
{ "pile_set_name": "Github" }
[00:00] [music] [00:03] Wes: Now we're going to learn about destructuring. Along with arrow functions, let, and const, it's probably something you're going to be using every single day. I find them to be extremely useful in the code that I'm writing. [00:11] What does destructuring mean? It's a JavaScript expression that allows us to extract data from arrays, objects, and something called maps and sets, which we're going to learn about it in a feature video, into their own variable. It allows us to extract properties from an object or items from an array, multiple at a time. [00:33] Let's take a look at what this problem really solves. Sometimes you need to have top level variables like const = name or first = person.first, constlast = person.last. You get the point. You do this over and over, and over again. [00:49] You've got this pretty much repetitive code over and over again, where you need to make a variable from something that is inside of an object or inside of an array. What we could do instead of doing two variables, or six, you could say const and you open up a curly bracket. That is not a block. That is not an object. It's the destructuring syntax. [01:13] We say first last = what? Person. Now what does that do? That says, give me a variable called first, a variable called last, and take it from the person. It's weird because we're not setting the entire object, but we're taking the first property and the last property and putting them into two top level variables. [01:38] If I save that now and I say first and last, you'll see that we get Wes and Bos, because I've created two top level variables. Similarly, if I also wanted twitter, I would just add twitter into that, and I would get a third top level variable inside of my actual scope. [01:56] That's really handy in many use cases. This is just one nested level, but for example, in react often you want to use destructuring because the data is so deeply nested. [02:08] Let's take a look at some nested data here. I'm going to make another variable down here called Wes, and we've got a first, last. Now this data is something you might get back from an API where it's really deeply nested. [02:23] I want to be able to pull out Twitter and Facebook URLs here. I could do this, constTwitter=wes.links.social.twitter. Then we also want facebook, so I will just add facebook and I'm off and running. But again, that's really annoying. [02:43] We can use destructuring to do it one better. We just say const, open and close your curly brackets there, to open and close the destructuring syntax. Then we'll say twitter and facebook are going to be equal to... [02:56] We don't just say Wes here. We say wes.links.social, and that will then reach into the social object and pull out two variables called twitter and facebook. [03:08] Now, I just consted twitter and I did that up here as well. You can see my editor is getting all red and mad at me because I used that variable already, so I'm just going to comment that out and it's good. Now if I look at twitter, you see the link to my actual Twitter. [03:23] That is how you do it with nested data. Let's take a look at another use case which would be renaming your variables. Sometimes data comes back in some odd names, and you might not necessarily want to use a property key. [03:36] For example here, I already used twitter as a variable. I can't use it again, but I'm stuck, because this object gives me twitter as a key and this object gives me twitter as a key. What you can do is you can rename them as you destructure them. [03:51] You can say, I want the twitter property, but I want to call it tweet. I want the facebook property, but I want to call it fb. [laughs] That's my snippet text expander, I want to call it fb. [04:10] Let's see here. [laughs] Now I've got my tweet variable and I have my fb variable, and they are being destructured as wes.links.social.facebook, but then stored in a variable called fb and stored in an actual variable called tweet. [04:26] There's one last thing we need to know about destructuring objects, and that is the ability to set defaults. This one's a little bit confusing, so bear with me here and we're going to circle back for another example later on in a couple of videos with a function. [04:40] Let's say we have a function that's going to do some animation on our page, and it's going to create an element and style it for us. We have things like width, height, color, and font size that we want to set on this actual element. [04:56] We have that settings object. Now I'm going to create my own settings, so settings equals...and we want the width to be 300, and we want the color to be black. Those are our settings. [05:13] However, the thing that we're building also requires a height and a font size. Those are the four properties that the thing that we're building requires. How do we actually deal with them when they're not in there? [05:28] Previously what you'd do is you'd have a default settings object, then you would fold this one in, you would merge it on in. But with ES6 what we can do is, we change that to const, and we can create our variables here. I'm going to say const, width, height, color, font size equals, then in here we are going to say settings because that's this variable. [05:55] What that's going to do is, it's going to pick out the width, and it's going to pick out the color from our settings. But what about height and front size? They haven't been set in settings so they're going to be undefined and that's going to be a bit of a problem for us. [06:07] What you can do is, when you do your destructuring you can also set a fallback or a default value. Maybe width is default to 100, height is default to 100 as well, color is default to blue, and font size is default to 25. [06:27] What's going to happen is, this destructuring works like this. Width, is it being destructured from the settings object? Yes, so width is going to be 300. Height, is that being destructured from the settings object? No, it's not in there, so it's going to roll back to the default, 100. [06:44] Color, is that in there? Yes, so blue will not be used. Black will win over. Font size, that's not in there, so we will use the default. [06:53] If I open this up in my browser here, we should be able to see the width. It's 300, good. The settings took over. But let's look at height, which is not in the settings object. It's 100 because the default has fallen in. [07:09] Where this is going to be real useful is when we pass a settings object to a function in just a couple of videos. I know what you're asking right now is, "Wes, I just learned all the stuff about destructuring, but can we put it all together into one major thing?" [07:23] I actually wondered at that as well, so I came up with this, which is...[laughs] Take a look at this. Maybe pause it for a second, and try to ask yourself, what is going on here and what are the variables that are being created? [07:37] I'm going to go open my DevTools here. What are the variables being created? Well, the variables being created are width and height. Why, because it's destructuring W and H. But it's renaming them to width and height, so that I should be able to say width. I guess I've got to save first. Width and height, good, so it's 800 and 500. [08:01] What's happening here is that it's destructuring width from this object here. It's going to take 800, then it's immediately renaming it to width, so it's going to be 800. [08:12] Then height, what are these equals right here? Those are default values. Height, there is no H being passed at all, so H tries to destructure from the object here. It can't, so it falls back to 500 default, and then it renamed itself to height. [08:29] I'm not sure if you would use that every day or it maybe even every year, but it's fun to look at it and to wrap your head around. It's something that you can maybe write and put it on a t-shirt and be cool. [laughs] [08:42] Enjoy that one.
{ "pile_set_name": "Github" }
from __future__ import unicode_literals
{ "pile_set_name": "Github" }
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/mozilla-1.9.1-win32-xulrunner/build/dom/public/idl/events/nsIDOMKeyEvent.idl */ #ifndef __gen_nsIDOMKeyEvent_h__ #define __gen_nsIDOMKeyEvent_h__ #ifndef __gen_nsIDOMUIEvent_h__ #include "nsIDOMUIEvent.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIDOMKeyEvent */ #define NS_IDOMKEYEVENT_IID_STR "028e0e6e-8b01-11d3-aae7-0010838a3123" #define NS_IDOMKEYEVENT_IID \ {0x028e0e6e, 0x8b01, 0x11d3, \ { 0xaa, 0xe7, 0x00, 0x10, 0x83, 0x8a, 0x31, 0x23 }} class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMKeyEvent : public nsIDOMUIEvent { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMKEYEVENT_IID) enum { DOM_VK_CANCEL = 3U }; enum { DOM_VK_HELP = 6U }; enum { DOM_VK_BACK_SPACE = 8U }; enum { DOM_VK_TAB = 9U }; enum { DOM_VK_CLEAR = 12U }; enum { DOM_VK_RETURN = 13U }; enum { DOM_VK_ENTER = 14U }; enum { DOM_VK_SHIFT = 16U }; enum { DOM_VK_CONTROL = 17U }; enum { DOM_VK_ALT = 18U }; enum { DOM_VK_PAUSE = 19U }; enum { DOM_VK_CAPS_LOCK = 20U }; enum { DOM_VK_ESCAPE = 27U }; enum { DOM_VK_SPACE = 32U }; enum { DOM_VK_PAGE_UP = 33U }; enum { DOM_VK_PAGE_DOWN = 34U }; enum { DOM_VK_END = 35U }; enum { DOM_VK_HOME = 36U }; enum { DOM_VK_LEFT = 37U }; enum { DOM_VK_UP = 38U }; enum { DOM_VK_RIGHT = 39U }; enum { DOM_VK_DOWN = 40U }; enum { DOM_VK_PRINTSCREEN = 44U }; enum { DOM_VK_INSERT = 45U }; enum { DOM_VK_DELETE = 46U }; enum { DOM_VK_0 = 48U }; enum { DOM_VK_1 = 49U }; enum { DOM_VK_2 = 50U }; enum { DOM_VK_3 = 51U }; enum { DOM_VK_4 = 52U }; enum { DOM_VK_5 = 53U }; enum { DOM_VK_6 = 54U }; enum { DOM_VK_7 = 55U }; enum { DOM_VK_8 = 56U }; enum { DOM_VK_9 = 57U }; enum { DOM_VK_SEMICOLON = 59U }; enum { DOM_VK_EQUALS = 61U }; enum { DOM_VK_A = 65U }; enum { DOM_VK_B = 66U }; enum { DOM_VK_C = 67U }; enum { DOM_VK_D = 68U }; enum { DOM_VK_E = 69U }; enum { DOM_VK_F = 70U }; enum { DOM_VK_G = 71U }; enum { DOM_VK_H = 72U }; enum { DOM_VK_I = 73U }; enum { DOM_VK_J = 74U }; enum { DOM_VK_K = 75U }; enum { DOM_VK_L = 76U }; enum { DOM_VK_M = 77U }; enum { DOM_VK_N = 78U }; enum { DOM_VK_O = 79U }; enum { DOM_VK_P = 80U }; enum { DOM_VK_Q = 81U }; enum { DOM_VK_R = 82U }; enum { DOM_VK_S = 83U }; enum { DOM_VK_T = 84U }; enum { DOM_VK_U = 85U }; enum { DOM_VK_V = 86U }; enum { DOM_VK_W = 87U }; enum { DOM_VK_X = 88U }; enum { DOM_VK_Y = 89U }; enum { DOM_VK_Z = 90U }; enum { DOM_VK_CONTEXT_MENU = 93U }; enum { DOM_VK_NUMPAD0 = 96U }; enum { DOM_VK_NUMPAD1 = 97U }; enum { DOM_VK_NUMPAD2 = 98U }; enum { DOM_VK_NUMPAD3 = 99U }; enum { DOM_VK_NUMPAD4 = 100U }; enum { DOM_VK_NUMPAD5 = 101U }; enum { DOM_VK_NUMPAD6 = 102U }; enum { DOM_VK_NUMPAD7 = 103U }; enum { DOM_VK_NUMPAD8 = 104U }; enum { DOM_VK_NUMPAD9 = 105U }; enum { DOM_VK_MULTIPLY = 106U }; enum { DOM_VK_ADD = 107U }; enum { DOM_VK_SEPARATOR = 108U }; enum { DOM_VK_SUBTRACT = 109U }; enum { DOM_VK_DECIMAL = 110U }; enum { DOM_VK_DIVIDE = 111U }; enum { DOM_VK_F1 = 112U }; enum { DOM_VK_F2 = 113U }; enum { DOM_VK_F3 = 114U }; enum { DOM_VK_F4 = 115U }; enum { DOM_VK_F5 = 116U }; enum { DOM_VK_F6 = 117U }; enum { DOM_VK_F7 = 118U }; enum { DOM_VK_F8 = 119U }; enum { DOM_VK_F9 = 120U }; enum { DOM_VK_F10 = 121U }; enum { DOM_VK_F11 = 122U }; enum { DOM_VK_F12 = 123U }; enum { DOM_VK_F13 = 124U }; enum { DOM_VK_F14 = 125U }; enum { DOM_VK_F15 = 126U }; enum { DOM_VK_F16 = 127U }; enum { DOM_VK_F17 = 128U }; enum { DOM_VK_F18 = 129U }; enum { DOM_VK_F19 = 130U }; enum { DOM_VK_F20 = 131U }; enum { DOM_VK_F21 = 132U }; enum { DOM_VK_F22 = 133U }; enum { DOM_VK_F23 = 134U }; enum { DOM_VK_F24 = 135U }; enum { DOM_VK_NUM_LOCK = 144U }; enum { DOM_VK_SCROLL_LOCK = 145U }; enum { DOM_VK_COMMA = 188U }; enum { DOM_VK_PERIOD = 190U }; enum { DOM_VK_SLASH = 191U }; enum { DOM_VK_BACK_QUOTE = 192U }; enum { DOM_VK_OPEN_BRACKET = 219U }; enum { DOM_VK_BACK_SLASH = 220U }; enum { DOM_VK_CLOSE_BRACKET = 221U }; enum { DOM_VK_QUOTE = 222U }; enum { DOM_VK_META = 224U }; /* readonly attribute unsigned long charCode; */ NS_SCRIPTABLE NS_IMETHOD GetCharCode(PRUint32 *aCharCode) = 0; /* readonly attribute unsigned long keyCode; */ NS_SCRIPTABLE NS_IMETHOD GetKeyCode(PRUint32 *aKeyCode) = 0; /* readonly attribute boolean altKey; */ NS_SCRIPTABLE NS_IMETHOD GetAltKey(PRBool *aAltKey) = 0; /* readonly attribute boolean ctrlKey; */ NS_SCRIPTABLE NS_IMETHOD GetCtrlKey(PRBool *aCtrlKey) = 0; /* readonly attribute boolean shiftKey; */ NS_SCRIPTABLE NS_IMETHOD GetShiftKey(PRBool *aShiftKey) = 0; /* readonly attribute boolean metaKey; */ NS_SCRIPTABLE NS_IMETHOD GetMetaKey(PRBool *aMetaKey) = 0; /* void initKeyEvent (in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in nsIDOMAbstractView viewArg, in boolean ctrlKeyArg, in boolean altKeyArg, in boolean shiftKeyArg, in boolean metaKeyArg, in unsigned long keyCodeArg, in unsigned long charCodeArg); */ NS_SCRIPTABLE NS_IMETHOD InitKeyEvent(const nsAString & typeArg, PRBool canBubbleArg, PRBool cancelableArg, nsIDOMAbstractView *viewArg, PRBool ctrlKeyArg, PRBool altKeyArg, PRBool shiftKeyArg, PRBool metaKeyArg, PRUint32 keyCodeArg, PRUint32 charCodeArg) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMKeyEvent, NS_IDOMKEYEVENT_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDOMKEYEVENT \ NS_SCRIPTABLE NS_IMETHOD GetCharCode(PRUint32 *aCharCode); \ NS_SCRIPTABLE NS_IMETHOD GetKeyCode(PRUint32 *aKeyCode); \ NS_SCRIPTABLE NS_IMETHOD GetAltKey(PRBool *aAltKey); \ NS_SCRIPTABLE NS_IMETHOD GetCtrlKey(PRBool *aCtrlKey); \ NS_SCRIPTABLE NS_IMETHOD GetShiftKey(PRBool *aShiftKey); \ NS_SCRIPTABLE NS_IMETHOD GetMetaKey(PRBool *aMetaKey); \ NS_SCRIPTABLE NS_IMETHOD InitKeyEvent(const nsAString & typeArg, PRBool canBubbleArg, PRBool cancelableArg, nsIDOMAbstractView *viewArg, PRBool ctrlKeyArg, PRBool altKeyArg, PRBool shiftKeyArg, PRBool metaKeyArg, PRUint32 keyCodeArg, PRUint32 charCodeArg); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDOMKEYEVENT(_to) \ NS_SCRIPTABLE NS_IMETHOD GetCharCode(PRUint32 *aCharCode) { return _to GetCharCode(aCharCode); } \ NS_SCRIPTABLE NS_IMETHOD GetKeyCode(PRUint32 *aKeyCode) { return _to GetKeyCode(aKeyCode); } \ NS_SCRIPTABLE NS_IMETHOD GetAltKey(PRBool *aAltKey) { return _to GetAltKey(aAltKey); } \ NS_SCRIPTABLE NS_IMETHOD GetCtrlKey(PRBool *aCtrlKey) { return _to GetCtrlKey(aCtrlKey); } \ NS_SCRIPTABLE NS_IMETHOD GetShiftKey(PRBool *aShiftKey) { return _to GetShiftKey(aShiftKey); } \ NS_SCRIPTABLE NS_IMETHOD GetMetaKey(PRBool *aMetaKey) { return _to GetMetaKey(aMetaKey); } \ NS_SCRIPTABLE NS_IMETHOD InitKeyEvent(const nsAString & typeArg, PRBool canBubbleArg, PRBool cancelableArg, nsIDOMAbstractView *viewArg, PRBool ctrlKeyArg, PRBool altKeyArg, PRBool shiftKeyArg, PRBool metaKeyArg, PRUint32 keyCodeArg, PRUint32 charCodeArg) { return _to InitKeyEvent(typeArg, canBubbleArg, cancelableArg, viewArg, ctrlKeyArg, altKeyArg, shiftKeyArg, metaKeyArg, keyCodeArg, charCodeArg); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDOMKEYEVENT(_to) \ NS_SCRIPTABLE NS_IMETHOD GetCharCode(PRUint32 *aCharCode) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCharCode(aCharCode); } \ NS_SCRIPTABLE NS_IMETHOD GetKeyCode(PRUint32 *aKeyCode) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetKeyCode(aKeyCode); } \ NS_SCRIPTABLE NS_IMETHOD GetAltKey(PRBool *aAltKey) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAltKey(aAltKey); } \ NS_SCRIPTABLE NS_IMETHOD GetCtrlKey(PRBool *aCtrlKey) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCtrlKey(aCtrlKey); } \ NS_SCRIPTABLE NS_IMETHOD GetShiftKey(PRBool *aShiftKey) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetShiftKey(aShiftKey); } \ NS_SCRIPTABLE NS_IMETHOD GetMetaKey(PRBool *aMetaKey) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetMetaKey(aMetaKey); } \ NS_SCRIPTABLE NS_IMETHOD InitKeyEvent(const nsAString & typeArg, PRBool canBubbleArg, PRBool cancelableArg, nsIDOMAbstractView *viewArg, PRBool ctrlKeyArg, PRBool altKeyArg, PRBool shiftKeyArg, PRBool metaKeyArg, PRUint32 keyCodeArg, PRUint32 charCodeArg) { return !_to ? NS_ERROR_NULL_POINTER : _to->InitKeyEvent(typeArg, canBubbleArg, cancelableArg, viewArg, ctrlKeyArg, altKeyArg, shiftKeyArg, metaKeyArg, keyCodeArg, charCodeArg); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDOMKeyEvent : public nsIDOMKeyEvent { public: NS_DECL_ISUPPORTS NS_DECL_NSIDOMKEYEVENT nsDOMKeyEvent(); private: ~nsDOMKeyEvent(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsDOMKeyEvent, nsIDOMKeyEvent) nsDOMKeyEvent::nsDOMKeyEvent() { /* member initializers and constructor code */ } nsDOMKeyEvent::~nsDOMKeyEvent() { /* destructor code */ } /* readonly attribute unsigned long charCode; */ NS_IMETHODIMP nsDOMKeyEvent::GetCharCode(PRUint32 *aCharCode) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute unsigned long keyCode; */ NS_IMETHODIMP nsDOMKeyEvent::GetKeyCode(PRUint32 *aKeyCode) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute boolean altKey; */ NS_IMETHODIMP nsDOMKeyEvent::GetAltKey(PRBool *aAltKey) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute boolean ctrlKey; */ NS_IMETHODIMP nsDOMKeyEvent::GetCtrlKey(PRBool *aCtrlKey) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute boolean shiftKey; */ NS_IMETHODIMP nsDOMKeyEvent::GetShiftKey(PRBool *aShiftKey) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute boolean metaKey; */ NS_IMETHODIMP nsDOMKeyEvent::GetMetaKey(PRBool *aMetaKey) { return NS_ERROR_NOT_IMPLEMENTED; } /* void initKeyEvent (in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in nsIDOMAbstractView viewArg, in boolean ctrlKeyArg, in boolean altKeyArg, in boolean shiftKeyArg, in boolean metaKeyArg, in unsigned long keyCodeArg, in unsigned long charCodeArg); */ NS_IMETHODIMP nsDOMKeyEvent::InitKeyEvent(const nsAString & typeArg, PRBool canBubbleArg, PRBool cancelableArg, nsIDOMAbstractView *viewArg, PRBool ctrlKeyArg, PRBool altKeyArg, PRBool shiftKeyArg, PRBool metaKeyArg, PRUint32 keyCodeArg, PRUint32 charCodeArg) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIDOMKeyEvent_h__ */
{ "pile_set_name": "Github" }
# SPDX-License-Identifier: GPL-2.0+ # Copyright (c) 2012 The Chromium OS Authors. import ConfigParser import os import StringIO def Setup(fname=''): """Set up the buildman settings module by reading config files Args: config_fname: Config filename to read ('' for default) """ global settings global config_fname settings = ConfigParser.SafeConfigParser() if fname is not None: config_fname = fname if config_fname == '': config_fname = '%s/.buildman' % os.getenv('HOME') if not os.path.exists(config_fname): print 'No config file found ~/.buildman\nCreating one...\n' CreateBuildmanConfigFile(config_fname) print 'To install tool chains, please use the --fetch-arch option' if config_fname: settings.read(config_fname) def AddFile(data): settings.readfp(StringIO.StringIO(data)) def GetItems(section): """Get the items from a section of the config. Args: section: name of section to retrieve Returns: List of (name, value) tuples for the section """ try: return settings.items(section) except ConfigParser.NoSectionError as e: return [] except: raise def SetItem(section, tag, value): """Set an item and write it back to the settings file""" global settings global config_fname settings.set(section, tag, value) if config_fname is not None: with open(config_fname, 'w') as fd: settings.write(fd) def CreateBuildmanConfigFile(config_fname): """Creates a new config file with no tool chain information. Args: config_fname: Config filename to create Returns: None """ try: f = open(config_fname, 'w') except IOError: print "Couldn't create buildman config file '%s'\n" % config_fname raise print >>f, '''[toolchain] # name = path # e.g. x86 = /opt/gcc-4.6.3-nolibc/x86_64-linux [toolchain-prefix] # name = path to prefix # e.g. x86 = /opt/gcc-4.6.3-nolibc/x86_64-linux/bin/x86_64-linux- [toolchain-alias] # arch = alias # Indicates which toolchain should be used to build for that arch x86 = i386 blackfin = bfin nds32 = nds32le openrisc = or1k [make-flags] # Special flags to pass to 'make' for certain boards, e.g. to pass a test # flag and build tag to snapper boards: # snapper-boards=ENABLE_AT91_TEST=1 # snapper9260=${snapper-boards} BUILD_TAG=442 # snapper9g45=${snapper-boards} BUILD_TAG=443 ''' f.close();
{ "pile_set_name": "Github" }
/** * Copyright 2016 Red Hat, Inc. * * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.fabric8.maven.enricher.api.util; import java.io.StringReader; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.apache.maven.model.Plugin; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class MavenConfigurationExtractorTest { @Test public void should_parse_simple_types() { // Given final Plugin fakePlugin = createFakePlugin("<a>a</a><b>b</b>"); // When final Map<String, Object> config = MavenConfigurationExtractor.extract((Xpp3Dom) fakePlugin.getConfiguration()); // Then assertThat(config) .containsEntry("a", "a") .containsEntry("b", "b"); } @Test public void should_parse_inner_objects() { // Given final Plugin fakePlugin = createFakePlugin("<a>" + "<b>b</b>" + "</a>"); // When final Map<String, Object> config = MavenConfigurationExtractor.extract((Xpp3Dom) fakePlugin.getConfiguration()); // Then final Map<String, Object> expected = new HashMap<>(); expected.put("b", "b"); assertThat(config) .containsEntry("a", expected); } @Test public void should_parse_deep_inner_objects() { // Given final Plugin fakePlugin = createFakePlugin("<a>" + "<b>" + "<c>" + "<d>" + "<e>e1</e>" + "</d>" + "</c>" + "</b>" + "</a>"); // When final Map<String, Object> config = MavenConfigurationExtractor.extract((Xpp3Dom) fakePlugin.getConfiguration()); // Then final Map<String, Object> e = new HashMap<>(); e.put("e", "e1"); final Map<String, Object> d = new HashMap<>(); d.put("d", e); final Map<String, Object> c = new HashMap<>(); c.put("c", d); final Map<String, Object> expected = new HashMap<>(); expected.put("b", c); assertThat(config) .containsEntry("a", expected); } @Test public void should_parse_list_of_elements() { // Given final Plugin fakePlugin = createFakePlugin("<a>" + "<b>" + "<c>c1</c><c>c2</c>" + "</b>" + "</a>"); // When final Map<String, Object> config = MavenConfigurationExtractor.extract((Xpp3Dom) fakePlugin.getConfiguration()); // Then final Map<String, Object> expectedC = new HashMap<>(); expectedC.put("c", Arrays.asList("c1", "c2")); final Map<String, Object> expected = new HashMap<>(); expected.put("b", expectedC); assertThat(config) .containsEntry("a",expected); } @Test public void should_parse_list_of_mixed_elements() { // Given final Plugin fakePlugin = createFakePlugin("<a>" + "<b>" + "<c>c1</c><d>d1</d><c>c2</c>" + "</b>" + "</a>"); // When final Map<String, Object> config = MavenConfigurationExtractor.extract((Xpp3Dom) fakePlugin.getConfiguration()); // Then final Map<String, Object> expectedC = new HashMap<>(); expectedC.put("c", Arrays.asList("c1", "c2")); expectedC.put("d", "d1"); final Map<String, Object> expected = new HashMap<>(); expected.put("b", expectedC); assertThat(config) .containsEntry("a",expected); } private Plugin createFakePlugin(String config) { Plugin plugin = new Plugin(); plugin.setArtifactId("fabric8-maven-plugin"); plugin.setGroupId("io.fabric8"); String content = "<configuration>" + config + "</configuration>"; Xpp3Dom dom; try { dom = Xpp3DomBuilder.build(new StringReader(content)); } catch (Exception e) { throw new RuntimeException(e); } plugin.setConfiguration(dom); return plugin; } }
{ "pile_set_name": "Github" }
#ifndef __SOCKETS_H #define __SOCKETS_H #include <windows.h> #include <winsock.h> #include "buffer.h" class cSocket { private: SOCKET Socket; public: cSocket(void); cSocket(SOCKET InitSocket); ~cSocket(void); const SOCKET GetSocket(void) { return Socket; } void Free(void); // straight winsock commands bool socket(int af = PF_INET, int type = SOCK_STREAM, int protocol = IPPROTO_TCP); bool bind(const struct sockaddr FAR *name, int namelen); bool listen(int backlog = 5); SOCKET accept(struct sockaddr FAR *addr = NULL, int FAR *addrlen = 0); bool connect(struct sockaddr FAR *addr, int FAR addrlen); int recv(char FAR *buf, int len, int flags = 0); int send(const char FAR *buf, int len, int flags = 0); bool ioctlsocket(long cmd, u_long FAR *argp); bool setsockopt(int level, int optname, const char FAR *optval, int optlen); int getsockopt(int level, int optname, char FAR *optval, int FAR *optlen); bool getpeername(struct sockaddr FAR *name, int FAR *namelen); bool getpeername(struct sockaddr_in FAR *name, int FAR *namelen) { return getpeername((struct sockaddr FAR *)name, namelen); } // convience functions bool Create(u_short Port); bool Connect(unsigned char u1, unsigned char u2, unsigned char u3, unsigned char u4, unsigned short port); cSocket *GetConnection(void); bool SetBlocking(bool Enabled = false); bool SetKeepAlive(bool Enabled = false); bool SetLinger(bool Enabled = true, u_short TimeLimit = 0); bool SetSendBufferSize(int Size); }; class cConnection; typedef void (*Connect_Callback)(cConnection *); class cConnection { protected: cSocket *Socket; bool Reading; bool BufferReset; cBuffer Buffer; Connect_Callback Callback; public: cConnection(cSocket *Init_Socket, Connect_Callback InitCallback = NULL, bool InitReading = true); ~cConnection(void); cBuffer &GetBuffer(void) { return Buffer; } void Print(char *Format, ...); bool Write(void); bool Read(void); bool Handle(void); virtual bool ReadCallback(void) { return true; } virtual bool WriteCallback(void) { return true; } }; class cWinsock { private: bool WinsockStarted; public: cWinsock(void); ~cWinsock(void); void Init(void); void Shutdown(void); struct servent FAR *getservbyname(const char FAR *name, const char FAR *proto = "tcp"); u_short htons(u_short hostshort); struct hostent FAR *gethostbyaddr(const char FAR *addr, int len, int type = PF_INET); }; #endif // __SOCKETS_H
{ "pile_set_name": "Github" }
; RUN: opt < %s -pgo-instr-gen -S | FileCheck %s --check-prefix=GEN ; RUN: opt < %s -passes=pgo-instr-gen -S | FileCheck %s --check-prefix=GEN ; RUN: llvm-profdata merge %S/Inputs/criticaledge.proftext -o %t.profdata ; RUN: opt < %s -pgo-instr-use -pgo-test-profile-file=%t.profdata -S | FileCheck %s --check-prefix=USE ; RUN: opt < %s -passes=pgo-instr-use -pgo-test-profile-file=%t.profdata -S | FileCheck %s --check-prefix=USE target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128" target triple = "x86_64-unknown-linux-gnu" ; GEN: $__llvm_profile_raw_version = comdat any ; GEN: @__llvm_profile_raw_version = constant i64 {{[0-9]+}}, comdat ; GEN: @__profn_test_criticalEdge = private constant [17 x i8] c"test_criticalEdge" ; GEN: @__profn__stdin__bar = private constant [11 x i8] c"<stdin>:bar" define i32 @test_criticalEdge(i32 %i, i32 %j) { entry: ; CHECK: entry: ; GEN-NOT: call void @llvm.instrprof.increment switch i32 %i, label %sw.default [ i32 1, label %sw.bb i32 2, label %sw.bb1 i32 3, label %sw.bb2 i32 4, label %sw.bb2 ; CHECK: i32 3, label %entry.sw.bb2_crit_edge ; CHECK: i32 4, label %entry.sw.bb2_crit_edge1 i32 5, label %sw.bb2 ] ; USE: ] ; USE-SAME: !prof ![[BW_SWITCH:[0-9]+]] ; CHECK: entry.sw.bb2_crit_edge1: ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @__profn_test_criticalEdge, i32 0, i32 0), i64 82323253069, i32 8, i32 1) ; CHECK: br label %sw.bb2 ; CHECK: entry.sw.bb2_crit_edge: ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @__profn_test_criticalEdge, i32 0, i32 0), i64 82323253069, i32 8, i32 0) ; CHECK: br label %sw.bb2 sw.bb: ; GEN: sw.bb: ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @__profn_test_criticalEdge, i32 0, i32 0), i64 82323253069, i32 8, i32 5) %call = call i32 @bar(i32 2) br label %sw.epilog sw.bb1: ; GEN: sw.bb1: ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @__profn_test_criticalEdge, i32 0, i32 0), i64 82323253069, i32 8, i32 4) %call2 = call i32 @bar(i32 1024) br label %sw.epilog sw.bb2: ; GEN: sw.bb2: ; GEN-NOT: call void @llvm.instrprof.increment %cmp = icmp eq i32 %j, 2 br i1 %cmp, label %if.then, label %if.end ; USE: br i1 %cmp, label %if.then, label %if.end ; USE-SAME: !prof ![[BW_SW_BB2:[0-9]+]] if.then: ; GEN: if.then: ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @__profn_test_criticalEdge, i32 0, i32 0), i64 82323253069, i32 8, i32 2) %call4 = call i32 @bar(i32 4) br label %return if.end: ; GEN: if.end: ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @__profn_test_criticalEdge, i32 0, i32 0), i64 82323253069, i32 8, i32 3) %call5 = call i32 @bar(i32 8) br label %sw.epilog sw.default: ; GEN: sw.default: ; GEN-NOT: call void @llvm.instrprof.increment %call6 = call i32 @bar(i32 32) %cmp7 = icmp sgt i32 %j, 10 br i1 %cmp7, label %if.then8, label %if.end9 ; USE: br i1 %cmp7, label %if.then8, label %if.end9 ; USE-SAME: !prof ![[BW_SW_DEFAULT:[0-9]+]] if.then8: ; GEN: if.then8: ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @__profn_test_criticalEdge, i32 0, i32 0), i64 82323253069, i32 8, i32 7) %add = add nsw i32 %call6, 10 br label %if.end9 if.end9: ; GEN: if.end9: ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @__profn_test_criticalEdge, i32 0, i32 0), i64 82323253069, i32 8, i32 6) %res.0 = phi i32 [ %add, %if.then8 ], [ %call6, %sw.default ] br label %sw.epilog sw.epilog: ; GEN: sw.epilog: ; GEN-NOT: call void @llvm.instrprof.increment %res.1 = phi i32 [ %res.0, %if.end9 ], [ %call5, %if.end ], [ %call2, %sw.bb1 ], [ %call, %sw.bb ] br label %return return: ; GEN: return: ; GEN-NOT: call void @llvm.instrprof.increment %retval = phi i32 [ %res.1, %sw.epilog ], [ %call4, %if.then ] ret i32 %retval } define internal i32 @bar(i32 %i) { entry: ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([11 x i8], [11 x i8]* @__profn__stdin__bar, i32 0, i32 0), i64 12884901887, i32 1, i32 0) ret i32 %i } ; USE: ![[BW_SWITCH]] = !{!"branch_weights", i32 2, i32 1, i32 0, i32 2, i32 1, i32 1} ; USE: ![[BW_SW_BB2]] = !{!"branch_weights", i32 2, i32 2} ; USE: ![[BW_SW_DEFAULT]] = !{!"branch_weights", i32 1, i32 1}
{ "pile_set_name": "Github" }
# Latvian translations for gettext package. # Copyright (C) 2013 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the gettext package. # Kouhei Sutou <[email protected]>, 2013. # msgid "" msgstr "" "Project-Id-Version: gettext 3.0.1\n" "Report-Msgid-Bugs-To: \n" "PO-Revision-Date: 2013-09-03 21:34+0900\n" "Last-Translator: Kouhei Sutou <[email protected]>\n" "Language-Team: Latvian\n" "Language: lv\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n != 0 ? 1 : 2;\n" "\n"
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // @class NSArray, PLLibraryServicesManager; @protocol PLLibraryServicesDelegate - (void)handleCompletedAllOperationsForLibraryState:(long long)arg1; - (NSArray *)operationsForLibraryStateTransition:(long long)arg1; - (id)initWithLibraryServicesManager:(PLLibraryServicesManager *)arg1; @end
{ "pile_set_name": "Github" }