text
stringlengths 2
100k
| meta
dict |
---|---|
var convert = require('./convert'),
func = convert('xorWith', require('../xorWith'));
func.placeholder = require('./placeholder');
module.exports = func;
| {
"pile_set_name": "Github"
} |
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package deltablue {
public class BinaryConstraint {
protected var v1;
protected var v2;
protected var direction;
public function BinaryConstraint(var1, var2, strength) {
this.v1 = var1;
this.v2 = var2;
this.chooseMethod("var");
}
public function returnTrue() {
return true;
}
public function chooseMethod(mark) {
this.direction = (returnTrue()) ? "NORTH" : "south";
}
public function printDirection() {
print(this.direction);
}
}
function deltaBlue() {
var x = new BinaryConstraint("hello", "world", 3);
x.printDirection();
}
deltaBlue();
} // package
| {
"pile_set_name": "Github"
} |
DROP FUNCTION IF EXISTS report.Docs_Sales_Dunning_Report_details ( IN Record_ID numeric, IN AD_Language Character Varying (6)) ;
CREATE FUNCTION report.Docs_Sales_Dunning_Report_details ( IN Record_ID numeric, IN AD_Language Character Varying (6))
RETURNS TABLE (
printname character varying,
documentno character varying,
documentdate timestamp,
currency character,
grandtotal numeric,
paidamt numeric,
openamt numeric,
feeamt numeric,
totalamt numeric,
duedate timestamp with time zone,
daysdue numeric
) AS
$$
SELECT
COALESCE(dt_trl.printname, dt.PrintName) AS PrintName,
COALESCE(doc.DocumentNo, 'ERROR') AS DocumentNo,
doc.DocumentDate,
c.iso_code AS currency,
doc.GrandTotal,
doc.PaidAmt AS paidamt,
doc.GrandTotal - doc.PaidAmt AS openamt,
dl.amt AS FeeAmt,
invoiceopen(dc.Record_ID, 0::numeric) + dl.amt as totalamt,
paymenttermduedate(doc.C_PaymentTerm_ID, doc.DocumentDate::timestamp with time zone) AS DueDate,
dc.DaysDue
FROM
C_DunningDoc dd
LEFT JOIN C_DunningDoc_line dl ON dd.C_DunningDoc_ID = dl.C_DunningDoc_ID AND dl.isActive = 'Y'
LEFT JOIN C_DunningDoc_Line_Source dls ON dl.C_DunningDoc_Line_ID = dls.C_DunningDoc_Line_ID AND dls.isActive = 'Y'
LEFT JOIN C_Dunning_Candidate dc ON dls.C_Dunning_Candidate_ID = dc.C_Dunning_Candidate_ID AND dc.isActive = 'Y'
LEFT JOIN C_Currency c ON dc.C_Currency_ID = c.C_Currency_ID AND c.isActive = 'Y'
LEFT JOIN
(
SELECT sub_dc.C_Dunning_Candidate_ID,
Documentpaid(sub_dc.Record_ID, sub_dc.AD_Table_ID, sub_dc.C_Currency_ID, i.MultiplierAP) AS PaidAmt,
COALESCE(i.DocumentNo, o.DocumentNo) AS DocumentNo,
COALESCE(i.DateInvoiced, o.DateOrdered) AS DocumentDate,
COALESCE(i.C_Doctype_ID, o.C_Doctype_ID) AS C_Doctype_ID,
COALESCE(i.C_PaymentTerm_ID, o.C_PaymentTerm_ID) AS C_PaymentTerm_ID,
COALESCE(i.GrandTotal, o.GrandTotal) AS GrandTotal
FROM C_Dunning_Candidate sub_dc
LEFT JOIN C_Invoice_v i ON sub_dc.Record_ID = i.C_Invoice_ID AND sub_dc.AD_Table_ID = (SELECT AD_Table_ID FROM AD_Table WHERE TableName = 'C_Invoice' AND isActive = 'Y') AND i.isActive = 'Y'
LEFT JOIN C_Order o ON sub_dc.Record_ID = o.C_Order_ID AND sub_dc.AD_Table_ID = (SELECT AD_Table_ID FROM AD_Table WHERE TableName = 'C_Order' AND isActive = 'Y') AND o.isActive = 'Y'
WHERE sub_dc.isActive = 'Y'
) doc ON dc.C_Dunning_Candidate_ID = doc.C_Dunning_Candidate_ID
LEFT JOIN c_doctype dt ON doc.c_doctype_id = dt.c_doctype_id AND dt.isActive = 'Y'
LEFT JOIN C_DocType_Trl dt_trl ON doc.c_doctype_id = dt_trl.c_doctype_id AND dt_trl.AD_Language = $2 AND dt_trl.isActive = 'Y'
WHERE
dd.C_DunningDoc_ID = $1 AND dd.isActive = 'Y'
;
$$
LANGUAGE sql STABLE;
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1000"
version = "2.0">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "9C3799A9181838FD00488101"
BuildableName = "AnalyticsKit.app"
BlueprintName = "AnalyticsKit"
ReferencedContainer = "container:AnalyticsKit.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
codeCoverageEnabled = "YES"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "9C3799CA181838FD00488101"
BuildableName = "AnalyticsKitTests.xctest"
BlueprintName = "AnalyticsKitTests"
ReferencedContainer = "container:AnalyticsKit.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "9C3799A9181838FD00488101"
BuildableName = "AnalyticsKit.app"
BlueprintName = "AnalyticsKit"
ReferencedContainer = "container:AnalyticsKit.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugXPCServices = "NO"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "9C3799A9181838FD00488101"
BuildableName = "AnalyticsKit.app"
BlueprintName = "AnalyticsKit"
ReferencedContainer = "container:AnalyticsKit.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "9C3799A9181838FD00488101"
BuildableName = "AnalyticsKit.app"
BlueprintName = "AnalyticsKit"
ReferencedContainer = "container:AnalyticsKit.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2019_02_01.implementation;
import com.microsoft.azure.management.network.v2019_02_01.PublicIPPrefixSku;
import com.microsoft.azure.management.network.v2019_02_01.IPVersion;
import java.util.List;
import com.microsoft.azure.management.network.v2019_02_01.IpTag;
import com.microsoft.azure.management.network.v2019_02_01.ReferencedPublicIpAddress;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.rest.SkipParentValidation;
import com.microsoft.azure.Resource;
/**
* Public IP prefix resource.
*/
@JsonFlatten
@SkipParentValidation
public class PublicIPPrefixInner extends Resource {
/**
* The public IP prefix SKU.
*/
@JsonProperty(value = "sku")
private PublicIPPrefixSku sku;
/**
* The public IP address version. Possible values include: 'IPv4', 'IPv6'.
*/
@JsonProperty(value = "properties.publicIPAddressVersion")
private IPVersion publicIPAddressVersion;
/**
* The list of tags associated with the public IP prefix.
*/
@JsonProperty(value = "properties.ipTags")
private List<IpTag> ipTags;
/**
* The Length of the Public IP Prefix.
*/
@JsonProperty(value = "properties.prefixLength")
private Integer prefixLength;
/**
* The allocated Prefix.
*/
@JsonProperty(value = "properties.ipPrefix")
private String ipPrefix;
/**
* The list of all referenced PublicIPAddresses.
*/
@JsonProperty(value = "properties.publicIPAddresses")
private List<ReferencedPublicIpAddress> publicIPAddresses;
/**
* The resource GUID property of the public IP prefix resource.
*/
@JsonProperty(value = "properties.resourceGuid")
private String resourceGuid;
/**
* The provisioning state of the Public IP prefix resource. Possible values
* are: 'Updating', 'Deleting', and 'Failed'.
*/
@JsonProperty(value = "properties.provisioningState")
private String provisioningState;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
@JsonProperty(value = "etag")
private String etag;
/**
* A list of availability zones denoting the IP allocated for the resource
* needs to come from.
*/
@JsonProperty(value = "zones")
private List<String> zones;
/**
* Resource ID.
*/
@JsonProperty(value = "id")
private String id;
/**
* Get the public IP prefix SKU.
*
* @return the sku value
*/
public PublicIPPrefixSku sku() {
return this.sku;
}
/**
* Set the public IP prefix SKU.
*
* @param sku the sku value to set
* @return the PublicIPPrefixInner object itself.
*/
public PublicIPPrefixInner withSku(PublicIPPrefixSku sku) {
this.sku = sku;
return this;
}
/**
* Get the public IP address version. Possible values include: 'IPv4', 'IPv6'.
*
* @return the publicIPAddressVersion value
*/
public IPVersion publicIPAddressVersion() {
return this.publicIPAddressVersion;
}
/**
* Set the public IP address version. Possible values include: 'IPv4', 'IPv6'.
*
* @param publicIPAddressVersion the publicIPAddressVersion value to set
* @return the PublicIPPrefixInner object itself.
*/
public PublicIPPrefixInner withPublicIPAddressVersion(IPVersion publicIPAddressVersion) {
this.publicIPAddressVersion = publicIPAddressVersion;
return this;
}
/**
* Get the list of tags associated with the public IP prefix.
*
* @return the ipTags value
*/
public List<IpTag> ipTags() {
return this.ipTags;
}
/**
* Set the list of tags associated with the public IP prefix.
*
* @param ipTags the ipTags value to set
* @return the PublicIPPrefixInner object itself.
*/
public PublicIPPrefixInner withIpTags(List<IpTag> ipTags) {
this.ipTags = ipTags;
return this;
}
/**
* Get the Length of the Public IP Prefix.
*
* @return the prefixLength value
*/
public Integer prefixLength() {
return this.prefixLength;
}
/**
* Set the Length of the Public IP Prefix.
*
* @param prefixLength the prefixLength value to set
* @return the PublicIPPrefixInner object itself.
*/
public PublicIPPrefixInner withPrefixLength(Integer prefixLength) {
this.prefixLength = prefixLength;
return this;
}
/**
* Get the allocated Prefix.
*
* @return the ipPrefix value
*/
public String ipPrefix() {
return this.ipPrefix;
}
/**
* Set the allocated Prefix.
*
* @param ipPrefix the ipPrefix value to set
* @return the PublicIPPrefixInner object itself.
*/
public PublicIPPrefixInner withIpPrefix(String ipPrefix) {
this.ipPrefix = ipPrefix;
return this;
}
/**
* Get the list of all referenced PublicIPAddresses.
*
* @return the publicIPAddresses value
*/
public List<ReferencedPublicIpAddress> publicIPAddresses() {
return this.publicIPAddresses;
}
/**
* Set the list of all referenced PublicIPAddresses.
*
* @param publicIPAddresses the publicIPAddresses value to set
* @return the PublicIPPrefixInner object itself.
*/
public PublicIPPrefixInner withPublicIPAddresses(List<ReferencedPublicIpAddress> publicIPAddresses) {
this.publicIPAddresses = publicIPAddresses;
return this;
}
/**
* Get the resource GUID property of the public IP prefix resource.
*
* @return the resourceGuid value
*/
public String resourceGuid() {
return this.resourceGuid;
}
/**
* Set the resource GUID property of the public IP prefix resource.
*
* @param resourceGuid the resourceGuid value to set
* @return the PublicIPPrefixInner object itself.
*/
public PublicIPPrefixInner withResourceGuid(String resourceGuid) {
this.resourceGuid = resourceGuid;
return this;
}
/**
* Get the provisioning state of the Public IP prefix resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
*
* @return the provisioningState value
*/
public String provisioningState() {
return this.provisioningState;
}
/**
* Set the provisioning state of the Public IP prefix resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
*
* @param provisioningState the provisioningState value to set
* @return the PublicIPPrefixInner object itself.
*/
public PublicIPPrefixInner withProvisioningState(String provisioningState) {
this.provisioningState = provisioningState;
return this;
}
/**
* Get a unique read-only string that changes whenever the resource is updated.
*
* @return the etag value
*/
public String etag() {
return this.etag;
}
/**
* Set a unique read-only string that changes whenever the resource is updated.
*
* @param etag the etag value to set
* @return the PublicIPPrefixInner object itself.
*/
public PublicIPPrefixInner withEtag(String etag) {
this.etag = etag;
return this;
}
/**
* Get a list of availability zones denoting the IP allocated for the resource needs to come from.
*
* @return the zones value
*/
public List<String> zones() {
return this.zones;
}
/**
* Set a list of availability zones denoting the IP allocated for the resource needs to come from.
*
* @param zones the zones value to set
* @return the PublicIPPrefixInner object itself.
*/
public PublicIPPrefixInner withZones(List<String> zones) {
this.zones = zones;
return this;
}
/**
* Get resource ID.
*
* @return the id value
*/
public String id() {
return this.id;
}
/**
* Set resource ID.
*
* @param id the id value to set
* @return the PublicIPPrefixInner object itself.
*/
public PublicIPPrefixInner withId(String id) {
this.id = id;
return this;
}
}
| {
"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.lucene.search.vectorhighlight;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.highlight.Encoder;
/**
* Another highlighter implementation.
*
*/
public class FastVectorHighlighter {
public static final boolean DEFAULT_PHRASE_HIGHLIGHT = true;
public static final boolean DEFAULT_FIELD_MATCH = true;
protected final boolean phraseHighlight;
protected final boolean fieldMatch;
private final FragListBuilder fragListBuilder;
private final FragmentsBuilder fragmentsBuilder;
private int phraseLimit = Integer.MAX_VALUE;
/**
* the default constructor.
*/
public FastVectorHighlighter(){
this( DEFAULT_PHRASE_HIGHLIGHT, DEFAULT_FIELD_MATCH );
}
/**
* a constructor. Using {@link SimpleFragListBuilder} and {@link ScoreOrderFragmentsBuilder}.
*
* @param phraseHighlight true or false for phrase highlighting
* @param fieldMatch true of false for field matching
*/
public FastVectorHighlighter( boolean phraseHighlight, boolean fieldMatch ){
this( phraseHighlight, fieldMatch, new SimpleFragListBuilder(), new ScoreOrderFragmentsBuilder() );
}
/**
* a constructor. A {@link FragListBuilder} and a {@link FragmentsBuilder} can be specified (plugins).
*
* @param phraseHighlight true of false for phrase highlighting
* @param fieldMatch true of false for field matching
* @param fragListBuilder an instance of {@link FragListBuilder}
* @param fragmentsBuilder an instance of {@link FragmentsBuilder}
*/
public FastVectorHighlighter( boolean phraseHighlight, boolean fieldMatch,
FragListBuilder fragListBuilder, FragmentsBuilder fragmentsBuilder ){
this.phraseHighlight = phraseHighlight;
this.fieldMatch = fieldMatch;
this.fragListBuilder = fragListBuilder;
this.fragmentsBuilder = fragmentsBuilder;
}
/**
* create a {@link FieldQuery} object.
*
* @param query a query
* @return the created {@link FieldQuery} object
*/
public FieldQuery getFieldQuery( Query query ) {
// TODO: should we deprecate this?
// because if there is no reader, then we cannot rewrite MTQ.
try {
return getFieldQuery(query, null);
} catch (IOException e) {
// should never be thrown when reader is null
throw new RuntimeException (e);
}
}
/**
* create a {@link FieldQuery} object.
*
* @param query a query
* @return the created {@link FieldQuery} object
*/
public FieldQuery getFieldQuery( Query query, IndexReader reader ) throws IOException {
return new FieldQuery( query, reader, phraseHighlight, fieldMatch );
}
/**
* return the best fragment.
*
* @param fieldQuery {@link FieldQuery} object
* @param reader {@link IndexReader} of the index
* @param docId document id to be highlighted
* @param fieldName field of the document to be highlighted
* @param fragCharSize the length (number of chars) of a fragment
* @return the best fragment (snippet) string
* @throws IOException If there is a low-level I/O error
*/
public final String getBestFragment( final FieldQuery fieldQuery, IndexReader reader, int docId,
String fieldName, int fragCharSize ) throws IOException {
FieldFragList fieldFragList =
getFieldFragList( fragListBuilder, fieldQuery, reader, docId, fieldName, fragCharSize );
return fragmentsBuilder.createFragment( reader, docId, fieldName, fieldFragList );
}
/**
* return the best fragments.
*
* @param fieldQuery {@link FieldQuery} object
* @param reader {@link IndexReader} of the index
* @param docId document id to be highlighted
* @param fieldName field of the document to be highlighted
* @param fragCharSize the length (number of chars) of a fragment
* @param maxNumFragments maximum number of fragments
* @return created fragments or null when no fragments created.
* size of the array can be less than maxNumFragments
* @throws IOException If there is a low-level I/O error
*/
public final String[] getBestFragments( final FieldQuery fieldQuery, IndexReader reader, int docId,
String fieldName, int fragCharSize, int maxNumFragments ) throws IOException {
FieldFragList fieldFragList =
getFieldFragList( fragListBuilder, fieldQuery, reader, docId, fieldName, fragCharSize );
return fragmentsBuilder.createFragments( reader, docId, fieldName, fieldFragList, maxNumFragments );
}
/**
* return the best fragment.
*
* @param fieldQuery {@link FieldQuery} object
* @param reader {@link IndexReader} of the index
* @param docId document id to be highlighted
* @param fieldName field of the document to be highlighted
* @param fragCharSize the length (number of chars) of a fragment
* @param fragListBuilder {@link FragListBuilder} object
* @param fragmentsBuilder {@link FragmentsBuilder} object
* @param preTags pre-tags to be used to highlight terms
* @param postTags post-tags to be used to highlight terms
* @param encoder an encoder that generates encoded text
* @return the best fragment (snippet) string
* @throws IOException If there is a low-level I/O error
*/
public final String getBestFragment( final FieldQuery fieldQuery, IndexReader reader, int docId,
String fieldName, int fragCharSize,
FragListBuilder fragListBuilder, FragmentsBuilder fragmentsBuilder,
String[] preTags, String[] postTags, Encoder encoder ) throws IOException {
FieldFragList fieldFragList = getFieldFragList( fragListBuilder, fieldQuery, reader, docId, fieldName, fragCharSize );
return fragmentsBuilder.createFragment( reader, docId, fieldName, fieldFragList, preTags, postTags, encoder );
}
/**
* return the best fragments.
*
* @param fieldQuery {@link FieldQuery} object
* @param reader {@link IndexReader} of the index
* @param docId document id to be highlighted
* @param fieldName field of the document to be highlighted
* @param fragCharSize the length (number of chars) of a fragment
* @param maxNumFragments maximum number of fragments
* @param fragListBuilder {@link FragListBuilder} object
* @param fragmentsBuilder {@link FragmentsBuilder} object
* @param preTags pre-tags to be used to highlight terms
* @param postTags post-tags to be used to highlight terms
* @param encoder an encoder that generates encoded text
* @return created fragments or null when no fragments created.
* size of the array can be less than maxNumFragments
* @throws IOException If there is a low-level I/O error
*/
public final String[] getBestFragments( final FieldQuery fieldQuery, IndexReader reader, int docId,
String fieldName, int fragCharSize, int maxNumFragments,
FragListBuilder fragListBuilder, FragmentsBuilder fragmentsBuilder,
String[] preTags, String[] postTags, Encoder encoder ) throws IOException {
FieldFragList fieldFragList =
getFieldFragList( fragListBuilder, fieldQuery, reader, docId, fieldName, fragCharSize );
return fragmentsBuilder.createFragments( reader, docId, fieldName, fieldFragList, maxNumFragments,
preTags, postTags, encoder );
}
/**
* Return the best fragments. Matches are scanned from matchedFields and turned into fragments against
* storedField. The highlighting may not make sense if matchedFields has matches with offsets that don't
* correspond features in storedField. It will outright throw a {@code StringIndexOutOfBoundsException}
* if matchedFields produces offsets outside of storedField. As such it is advisable that all
* matchedFields share the same source as storedField or are at least a prefix of it.
*
* @param fieldQuery {@link FieldQuery} object
* @param reader {@link IndexReader} of the index
* @param docId document id to be highlighted
* @param storedField field of the document that stores the text
* @param matchedFields fields of the document to scan for matches
* @param fragCharSize the length (number of chars) of a fragment
* @param maxNumFragments maximum number of fragments
* @param fragListBuilder {@link FragListBuilder} object
* @param fragmentsBuilder {@link FragmentsBuilder} object
* @param preTags pre-tags to be used to highlight terms
* @param postTags post-tags to be used to highlight terms
* @param encoder an encoder that generates encoded text
* @return created fragments or null when no fragments created.
* size of the array can be less than maxNumFragments
* @throws IOException If there is a low-level I/O error
*/
public final String[] getBestFragments( final FieldQuery fieldQuery, IndexReader reader, int docId,
String storedField, Set< String > matchedFields, int fragCharSize, int maxNumFragments,
FragListBuilder fragListBuilder, FragmentsBuilder fragmentsBuilder,
String[] preTags, String[] postTags, Encoder encoder ) throws IOException {
FieldFragList fieldFragList =
getFieldFragList( fragListBuilder, fieldQuery, reader, docId, matchedFields, fragCharSize );
return fragmentsBuilder.createFragments( reader, docId, storedField, fieldFragList, maxNumFragments,
preTags, postTags, encoder );
}
/**
* Build a FieldFragList for one field.
*/
private FieldFragList getFieldFragList( FragListBuilder fragListBuilder,
final FieldQuery fieldQuery, IndexReader reader, int docId,
String matchedField, int fragCharSize ) throws IOException {
FieldTermStack fieldTermStack = new FieldTermStack( reader, docId, matchedField, fieldQuery );
FieldPhraseList fieldPhraseList = new FieldPhraseList( fieldTermStack, fieldQuery, phraseLimit );
return fragListBuilder.createFieldFragList( fieldPhraseList, fragCharSize );
}
/**
* Build a FieldFragList for more than one field.
*/
private FieldFragList getFieldFragList( FragListBuilder fragListBuilder,
final FieldQuery fieldQuery, IndexReader reader, int docId,
Set< String > matchedFields, int fragCharSize ) throws IOException {
Iterator< String > matchedFieldsItr = matchedFields.iterator();
if ( !matchedFieldsItr.hasNext() ) {
throw new IllegalArgumentException( "matchedFields must contain at least on field name." );
}
FieldPhraseList[] toMerge = new FieldPhraseList[ matchedFields.size() ];
int i = 0;
while ( matchedFieldsItr.hasNext() ) {
FieldTermStack stack = new FieldTermStack( reader, docId, matchedFieldsItr.next(), fieldQuery );
toMerge[ i++ ] = new FieldPhraseList( stack, fieldQuery, phraseLimit );
}
return fragListBuilder.createFieldFragList( new FieldPhraseList( toMerge ), fragCharSize );
}
/**
* return whether phraseHighlight or not.
*
* @return whether phraseHighlight or not
*/
public boolean isPhraseHighlight(){ return phraseHighlight; }
/**
* return whether fieldMatch or not.
*
* @return whether fieldMatch or not
*/
public boolean isFieldMatch(){ return fieldMatch; }
/**
* @return the maximum number of phrases to analyze when searching for the highest-scoring phrase.
*/
public int getPhraseLimit () { return phraseLimit; }
/**
* set the maximum number of phrases to analyze when searching for the highest-scoring phrase.
* The default is unlimited (Integer.MAX_VALUE).
*/
public void setPhraseLimit (int phraseLimit) { this.phraseLimit = phraseLimit; }
}
| {
"pile_set_name": "Github"
} |
//
// Copyright 2011 Ettus Research LLC
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
module buffer_pool_tb();
wire wb_clk_i;
wire wb_rst_i;
wire wb_we_i;
wire wb_stb_i;
wire [15:0] wb_adr_i;
wire [31:0] wb_dat_i;
wire [31:0] wb_dat_o;
wire wb_ack_o;
wire wb_err_o;
wire wb_rty_o;
wire stream_clk, stream_rst;
wire set_stb;
wire [7:0] set_addr;
wire [31:0] set_data;
wire [31:0] wr0_data, wr1_data, wr2_data, wr3_data;
wire [31:0] rd0_data, rd1_data, rd2_data, rd3_data;
wire [3:0] wr0_flags, wr1_flags, wr2_flags, wr3_flags;
wire [3:0] rd0_flags, rd1_flags, rd2_flags, rd3_flags;
wire wr0_ready, wr1_ready, wr2_ready, wr3_ready;
wire rd0_ready, rd1_ready, rd2_ready, rd3_ready;
wire wr0_write, wr1_write, wr2_write, wr3_write;
wire rd0_read, rd1_read, rd2_read, rd3_read;
buffer_pool dut
(.wb_clk_i(wb_clk_i),
.wb_rst_i(wb_rst_i),
.wb_we_i(wb_we_i),
.wb_stb_i(wb_stb_i),
.wb_adr_i(wb_adr_i),
.wb_dat_i(wb_dat_i),
.wb_dat_o(wb_dat_o),
.wb_ack_o(wb_ack_o),
.wb_err_o(wb_err_o),
.wb_rty_o(wb_rty_o),
.stream_clk(stream_clk),
.stream_rst(stream_rst),
.set_stb(set_stb),.set_addr(set_addr),.set_data(set_data),
.wr0_data_i(wr0_data), .wr0_write_i(wr0_write), .wr0_flags_i(wr0_flags), .wr0_ready_o(wr0_ready),
.wr1_data_i(wr1_data), .wr1_write_i(wr1_write), .wr1_flags_i(wr1_flags), .wr1_ready_o(wr1_ready),
.wr2_data_i(wr2_data), .wr2_write_i(wr2_write), .wr2_flags_i(wr2_flags), .wr2_ready_o(wr2_ready),
.wr3_data_i(wr3_data), .wr3_write_i(wr3_write), .wr3_flags_i(wr3_flags), .wr3_ready_o(wr3_ready),
.rd0_data_o(rd0_data), .rd0_read_i(rd0_read), .rd0_flags_o(rd0_flags), .rd0_ready_o(rd0_ready),
.rd1_data_o(rd1_data), .rd1_read_i(rd1_read), .rd1_flags_o(rd1_flags), .rd1_ready_o(rd1_ready),
.rd2_data_o(rd2_data), .rd2_read_i(rd2_read), .rd2_flags_o(rd2_flags), .rd2_ready_o(rd2_ready),
.rd3_data_o(rd3_data), .rd3_read_i(rd3_read), .rd3_flags_o(rd3_flags), .rd3_ready_o(rd3_ready)
);
endmodule // buffer_pool_tb
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#import <Foundation/Foundation.h>
#import "RTCLogging.h"
#import "RTCMacros.h"
NS_ASSUME_NONNULL_BEGIN
typedef void (^RTCCallbackLoggerMessageHandler)(NSString *message);
typedef void (^RTCCallbackLoggerMessageAndSeverityHandler)(NSString *message,
RTCLoggingSeverity severity);
// This class intercepts WebRTC logs and forwards them to a registered block.
// This class is not threadsafe.
RTC_OBJC_EXPORT
@interface RTCCallbackLogger : NSObject
// The severity level to capture. The default is kRTCLoggingSeverityInfo.
@property(nonatomic, assign) RTCLoggingSeverity severity;
// The callback handler will be called on the same thread that does the
// logging, so if the logging callback can be slow it may be a good idea
// to implement dispatching to some other queue.
- (void)start:(nullable RTCCallbackLoggerMessageHandler)handler;
- (void)startWithMessageAndSeverityHandler:
(nullable RTCCallbackLoggerMessageAndSeverityHandler)handler;
- (void)stop;
@end
NS_ASSUME_NONNULL_END
| {
"pile_set_name": "Github"
} |
#' Convert to an HTML document
#'
#' Format for converting from R Markdown to an HTML document.
#'
#' @details
#' CSS adapted from the readtheorg theme of the org-html-themes project :
#' \url{https://github.com/fniessen/org-html-themes}, which is itself inspired by
#' the Read the docs theme : \url{https://readthedocs.org/}.
#'
#' @param fig_width Default width (in inches) for figures
#' @param fig_height Default width (in inches) for figures
#' @param fig_caption \code{TRUE} to render figures with captions
#' @param highlight Syntax highlighting style. Supported styles include
#' "default", "tango", "pygments", "kate", "monochrome", "espresso",
#' "zenburn", "haddock", and "textmate". Pass \code{NULL} to prevent syntax
#' highlighting.
#' @param lightbox if TRUE, add lightbox effect to content images
#' @param thumbnails if TRUE display content images as thumbnails
#' @param gallery if TRUE and lightbox is TRUE, add a gallery navigation between images in lightbox display
#' @param pandoc_args arguments passed to the pandoc_args argument of rmarkdown \code{\link[rmarkdown]{html_document}}
#' @param md_extensions arguments passed to the md_extensions argument of rmarkdown \code{\link[rmarkdown]{html_document}}
#' @param toc_depth adjust table of contents depth
#' @param embed_fonts if TRUE, use local files for Lato and Roboto Slab fonts used in the template. This leads to bigger files but ensures that these fonts are available.
#' @param use_bookdown if TRUE, uses \code{\link[bookdown]{html_document2}} instead of \code{\link[rmarkdown]{html_document}}, thus providing numbered sections and cross references
#' @param mathjax set to NULL to disable Mathjax insertion
#' @param ... Additional function arguments passed to R Markdown \code{\link[rmarkdown]{html_document}}
#' @return R Markdown output format to pass to \code{\link[rmarkdown]{render}}
#' @import rmarkdown
#' @import bookdown
#' @importFrom htmltools htmlDependency
#' @export
readthedown <- function(fig_width = 8,
fig_height = 5,
fig_caption = TRUE,
highlight = "kate",
lightbox = FALSE,
thumbnails = FALSE,
gallery = FALSE,
toc_depth = 2,
embed_fonts = TRUE,
use_bookdown = FALSE,
pandoc_args = NULL,
md_extensions = NULL,
mathjax = "rmdformats",
...) {
html_template(
template_name = "readthedown",
template_path = "templates/template.html",
template_dependencies = list(
html_dependency_readthedown(embed_fonts)
),
pandoc_args = pandoc_args,
fig_width = fig_width,
fig_height = fig_height,
fig_caption = fig_caption,
highlight = highlight,
lightbox = lightbox,
thumbnails = thumbnails,
gallery = gallery,
toc = TRUE,
toc_depth = toc_depth,
use_bookdown = use_bookdown,
md_extensions = md_extensions,
mathjax = mathjax,
...
)
}
# readthedown js and css
html_dependency_readthedown <- function(embed_fonts = TRUE) {
stylesheets <- "readthedown.css"
if (embed_fonts) stylesheets <- c(stylesheets, "readthedown_fonts.css")
htmltools::htmlDependency(name = "readthedown",
version = "0.1",
src = system.file("templates/readthedown", package = "rmdformats"),
script = "readthedown.js",
stylesheet = stylesheets)
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML>
<html>
<body>
<fieldset id="f" style="position:relative; overflow:hidden; width:500px; height:500px;">
<legend>Legend</legend>
<div style="height:1000px;">
<div style="position:absolute; padding:2px; left:20px; top:50px; background:yellow;">Abs-pos</div>
</div>
</fieldset>
<script>
f.scrollTop = 30;
</script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2016 - 2018 Syncleus, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aparapi.codegen.test;
import org.junit.Test;
public class IfElseNot__OrOr_And_Test extends com.aparapi.codegen.CodeGenJUnitBase {
private static final String[] expectedOpenCL = {
"typedef struct This_s{\n"
+ "\n"
+ " int passid;\n"
+ " }This;\n"
+ " int get_pass_id(This *this){\n"
+ " return this->passid;\n"
+ " }\n"
+ "\n"
+ " __kernel void run(\n"
+ " int passid\n"
+ " ){\n"
+ " This thisStruct;\n"
+ " This* this=&thisStruct;\n"
+ " this->passid = passid;\n"
+ " {\n"
+ " int testValue = 10;\n"
+ " char pass = 0;\n"
+ " if ((testValue % 2)!=0 && testValue>0 && testValue<100 || (testValue % 4)!=0){\n"
+ " pass = 1;\n"
+ " } else {\n"
+ " pass = 0;\n"
+ " }\n"
+ " return;\n"
+ " }\n"
+ " }\n"
+ " "};
private static final Class<? extends com.aparapi.internal.exception.AparapiException> expectedException = null;
@Test
public void IfElseNot__OrOr_And_Test() {
test(com.aparapi.codegen.test.IfElseNot__OrOr_And_.class, expectedException, expectedOpenCL);
}
@Test
public void IfElseNot__OrOr_And_TestWorksWithCaching() {
test(com.aparapi.codegen.test.IfElseNot__OrOr_And_.class, expectedException, expectedOpenCL);
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2016 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "flatbuffers/code_generators.h"
#include <assert.h>
#include <cmath>
#include "flatbuffers/base.h"
#include "flatbuffers/util.h"
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4127) // C4127: conditional expression is constant
#endif
namespace flatbuffers {
void CodeWriter::operator+=(std::string text) {
if (!ignore_ident_ && !text.empty()) AppendIdent(stream_);
while (true) {
auto begin = text.find("{{");
if (begin == std::string::npos) { break; }
auto end = text.find("}}");
if (end == std::string::npos || end < begin) { break; }
// Write all the text before the first {{ into the stream.
stream_.write(text.c_str(), begin);
// The key is between the {{ and }}.
const std::string key = text.substr(begin + 2, end - begin - 2);
// Find the value associated with the key. If it exists, write the
// value into the stream, otherwise write the key itself into the stream.
auto iter = value_map_.find(key);
if (iter != value_map_.end()) {
const std::string &value = iter->second;
stream_ << value;
} else {
FLATBUFFERS_ASSERT(false && "could not find key");
stream_ << key;
}
// Update the text to everything after the }}.
text = text.substr(end + 2);
}
if (!text.empty() && string_back(text) == '\\') {
text.pop_back();
ignore_ident_ = true;
stream_ << text;
} else {
ignore_ident_ = false;
stream_ << text << std::endl;
}
}
void CodeWriter::AppendIdent(std::stringstream &stream) {
int lvl = cur_ident_lvl_;
while (lvl--) {
stream.write(pad_.c_str(), static_cast<std::streamsize>(pad_.size()));
}
}
const char *BaseGenerator::FlatBuffersGeneratedWarning() {
return "automatically generated by the FlatBuffers compiler,"
" do not modify";
}
std::string BaseGenerator::NamespaceDir(const Parser &parser,
const std::string &path,
const Namespace &ns) {
EnsureDirExists(path);
if (parser.opts.one_file) return path;
std::string namespace_dir = path; // Either empty or ends in separator.
auto &namespaces = ns.components;
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
namespace_dir += *it + kPathSeparator;
EnsureDirExists(namespace_dir);
}
return namespace_dir;
}
std::string BaseGenerator::NamespaceDir(const Namespace &ns) const {
return BaseGenerator::NamespaceDir(parser_, path_, ns);
}
std::string BaseGenerator::FullNamespace(const char *separator,
const Namespace &ns) {
std::string namespace_name;
auto &namespaces = ns.components;
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
if (namespace_name.length()) namespace_name += separator;
namespace_name += *it;
}
return namespace_name;
}
std::string BaseGenerator::LastNamespacePart(const Namespace &ns) {
if (!ns.components.empty())
return ns.components.back();
else
return std::string("");
}
// Ensure that a type is prefixed with its namespace.
std::string BaseGenerator::WrapInNameSpace(const Namespace *ns,
const std::string &name) const {
std::string qualified_name = qualifying_start_;
for (auto it = ns->components.begin(); it != ns->components.end(); ++it)
qualified_name += *it + qualifying_separator_;
return qualified_name + name;
}
std::string BaseGenerator::WrapInNameSpace(const Definition &def) const {
return WrapInNameSpace(def.defined_namespace, def.name);
}
std::string BaseGenerator::GetNameSpace(const Definition &def) const {
const Namespace *ns = def.defined_namespace;
if (CurrentNameSpace() == ns) return "";
std::string qualified_name = qualifying_start_;
for (auto it = ns->components.begin(); it != ns->components.end(); ++it) {
qualified_name += *it;
if ((it + 1) != ns->components.end()) {
qualified_name += qualifying_separator_;
}
}
return qualified_name;
}
std::string BaseGenerator::GeneratedFileName(const std::string &path,
const std::string &file_name,
const IDLOptions &options) const {
return path + file_name + options.filename_suffix + "." +
(options.filename_extension.empty() ? default_extension_
: options.filename_extension);
}
// Generate a documentation comment, if available.
void GenComment(const std::vector<std::string> &dc, std::string *code_ptr,
const CommentConfig *config, const char *prefix) {
if (dc.begin() == dc.end()) {
// Don't output empty comment blocks with 0 lines of comment content.
return;
}
std::string &code = *code_ptr;
if (config != nullptr && config->first_line != nullptr) {
code += std::string(prefix) + std::string(config->first_line) + "\n";
}
std::string line_prefix =
std::string(prefix) +
((config != nullptr && config->content_line_prefix != nullptr)
? config->content_line_prefix
: "///");
for (auto it = dc.begin(); it != dc.end(); ++it) {
code += line_prefix + *it + "\n";
}
if (config != nullptr && config->last_line != nullptr) {
code += std::string(prefix) + std::string(config->last_line) + "\n";
}
}
template<typename T>
std::string FloatConstantGenerator::GenFloatConstantImpl(
const FieldDef &field) const {
const auto &constant = field.value.constant;
T v;
auto done = StringToNumber(constant.c_str(), &v);
FLATBUFFERS_ASSERT(done);
if (done) {
#if (!defined(_MSC_VER) || (_MSC_VER >= 1800))
if (std::isnan(v)) return NaN(v);
if (std::isinf(v)) return Inf(v);
#endif
return Value(v, constant);
}
return "#"; // compile time error
}
std::string FloatConstantGenerator::GenFloatConstant(
const FieldDef &field) const {
switch (field.value.type.base_type) {
case BASE_TYPE_FLOAT: return GenFloatConstantImpl<float>(field);
case BASE_TYPE_DOUBLE: return GenFloatConstantImpl<double>(field);
default: {
FLATBUFFERS_ASSERT(false);
return "INVALID_BASE_TYPE";
}
};
}
TypedFloatConstantGenerator::TypedFloatConstantGenerator(
const char *double_prefix, const char *single_prefix,
const char *nan_number, const char *pos_inf_number,
const char *neg_inf_number)
: double_prefix_(double_prefix),
single_prefix_(single_prefix),
nan_number_(nan_number),
pos_inf_number_(pos_inf_number),
neg_inf_number_(neg_inf_number) {}
std::string TypedFloatConstantGenerator::MakeNaN(
const std::string &prefix) const {
return prefix + nan_number_;
}
std::string TypedFloatConstantGenerator::MakeInf(
bool neg, const std::string &prefix) const {
if (neg)
return !neg_inf_number_.empty() ? (prefix + neg_inf_number_)
: ("-" + prefix + pos_inf_number_);
else
return prefix + pos_inf_number_;
}
std::string TypedFloatConstantGenerator::Value(double v,
const std::string &src) const {
(void)v;
return src;
}
std::string TypedFloatConstantGenerator::Inf(double v) const {
return MakeInf(v < 0, double_prefix_);
}
std::string TypedFloatConstantGenerator::NaN(double v) const {
(void)v;
return MakeNaN(double_prefix_);
}
std::string TypedFloatConstantGenerator::Value(float v,
const std::string &src) const {
(void)v;
return src + "f";
}
std::string TypedFloatConstantGenerator::Inf(float v) const {
return MakeInf(v < 0, single_prefix_);
}
std::string TypedFloatConstantGenerator::NaN(float v) const {
(void)v;
return MakeNaN(single_prefix_);
}
SimpleFloatConstantGenerator::SimpleFloatConstantGenerator(
const char *nan_number, const char *pos_inf_number,
const char *neg_inf_number)
: nan_number_(nan_number),
pos_inf_number_(pos_inf_number),
neg_inf_number_(neg_inf_number) {}
std::string SimpleFloatConstantGenerator::Value(double v,
const std::string &src) const {
(void)v;
return src;
}
std::string SimpleFloatConstantGenerator::Inf(double v) const {
return (v < 0) ? neg_inf_number_ : pos_inf_number_;
}
std::string SimpleFloatConstantGenerator::NaN(double v) const {
(void)v;
return nan_number_;
}
std::string SimpleFloatConstantGenerator::Value(float v,
const std::string &src) const {
return this->Value(static_cast<double>(v), src);
}
std::string SimpleFloatConstantGenerator::Inf(float v) const {
return this->Inf(static_cast<double>(v));
}
std::string SimpleFloatConstantGenerator::NaN(float v) const {
return this->NaN(static_cast<double>(v));
}
std::string JavaCSharpMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
FLATBUFFERS_ASSERT(parser.opts.lang == IDLOptions::kJava ||
parser.opts.lang == IDLOptions::kCSharp);
std::string file_extension =
(parser.opts.lang == IDLOptions::kJava) ? ".java" : ".cs";
std::string make_rule;
for (auto it = parser.enums_.vec.begin(); it != parser.enums_.vec.end();
++it) {
auto &enum_def = **it;
if (!make_rule.empty()) make_rule += " ";
std::string directory =
BaseGenerator::NamespaceDir(parser, path, *enum_def.defined_namespace);
make_rule += directory + enum_def.name + file_extension;
}
for (auto it = parser.structs_.vec.begin(); it != parser.structs_.vec.end();
++it) {
auto &struct_def = **it;
if (!make_rule.empty()) make_rule += " ";
std::string directory = BaseGenerator::NamespaceDir(
parser, path, *struct_def.defined_namespace);
make_rule += directory + struct_def.name + file_extension;
}
make_rule += ": ";
auto included_files = parser.GetIncludedFilesRecursive(file_name);
for (auto it = included_files.begin(); it != included_files.end(); ++it) {
make_rule += " " + *it;
}
return make_rule;
}
std::string BinaryFileName(const Parser &parser, const std::string &path,
const std::string &file_name) {
auto ext = parser.file_extension_.length() ? parser.file_extension_ : "bin";
return path + file_name + "." + ext;
}
bool GenerateBinary(const Parser &parser, const std::string &path,
const std::string &file_name) {
if (parser.opts.use_flexbuffers) {
auto data_vec = parser.flex_builder_.GetBuffer();
auto data_ptr = reinterpret_cast<char *>(data(data_vec));
return !parser.flex_builder_.GetSize() ||
flatbuffers::SaveFile(
BinaryFileName(parser, path, file_name).c_str(), data_ptr,
parser.flex_builder_.GetSize(), true);
}
return !parser.builder_.GetSize() ||
flatbuffers::SaveFile(
BinaryFileName(parser, path, file_name).c_str(),
reinterpret_cast<char *>(parser.builder_.GetBufferPointer()),
parser.builder_.GetSize(), true);
}
std::string BinaryMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
if (!parser.builder_.GetSize()) return "";
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
std::string make_rule =
BinaryFileName(parser, path, filebase) + ": " + file_name;
auto included_files =
parser.GetIncludedFilesRecursive(parser.root_struct_def_->file);
for (auto it = included_files.begin(); it != included_files.end(); ++it) {
make_rule += " " + *it;
}
return make_rule;
}
} // namespace flatbuffers
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
| {
"pile_set_name": "Github"
} |
"Moono" Skin
====================
This skin has been chosen for the **default skin** of CKEditor 4.x, elected from the CKEditor
[skin contest](http://ckeditor.com/blog/new_ckeditor_4_skin) and further shaped by
the CKEditor team. "Moono" is maintained by the core developers.
For more information about skins, please check the [CKEditor Skin SDK](http://docs.cksource.com/CKEditor_4.x/Skin_SDK)
documentation.
Features
-------------------
"Moono" is a monochromatic skin, which offers a modern look coupled with gradients and transparency.
It comes with the following features:
- Chameleon feature with brightness,
- high-contrast compatibility,
- graphics source provided in SVG.
Directory Structure
-------------------
CSS parts:
- **editor.css**: the main CSS file. It's simply loading several other files, for easier maintenance,
- **mainui.css**: the file contains styles of entire editor outline structures,
- **toolbar.css**: the file contains styles of the editor toolbar space (top),
- **richcombo.css**: the file contains styles of the rich combo ui elements on toolbar,
- **panel.css**: the file contains styles of the rich combo drop-down, it's not loaded
until the first panel open up,
- **elementspath.css**: the file contains styles of the editor elements path bar (bottom),
- **menu.css**: the file contains styles of all editor menus including context menu and button drop-down,
it's not loaded until the first menu open up,
- **dialog.css**: the CSS files for the dialog UI, it's not loaded until the first dialog open,
- **reset.css**: the file defines the basis of style resets among all editor UI spaces,
- **preset.css**: the file defines the default styles of some UI elements reflecting the skin preference,
- **editor_XYZ.css** and **dialog_XYZ.css**: browser specific CSS hacks.
Other parts:
- **skin.js**: the only JavaScript part of the skin that registers the skin, its browser specific files and its icons and defines the Chameleon feature,
- **icons/**: contains all skin defined icons,
- **images/**: contains a fill general used images,
- **dev/**: contains SVG source of the skin icons.
License
-------
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
Licensed under the terms of any of the following licenses at your choice: [GPL](http://www.gnu.org/licenses/gpl.html), [LGPL](http://www.gnu.org/licenses/lgpl.html) and [MPL](http://www.mozilla.org/MPL/MPL-1.1.html).
See LICENSE.md for more information.
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2016 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <limits>
#include <memory>
#include <string>
#include "rtc_base/file.h"
#include "rtc_base/gunit.h"
#include "test/testsupport/fileutils.h"
#if defined(WEBRTC_WIN)
#include "rtc_base/win32.h"
#else // if defined(WEBRTC_WIN)
#include <errno.h>
#endif
namespace rtc {
int LastError() {
#if defined(WEBRTC_WIN)
return ::GetLastError();
#else
return errno;
#endif
}
bool VerifyBuffer(uint8_t* buffer, size_t length, uint8_t start_value) {
for (size_t i = 0; i < length; ++i) {
uint8_t val = start_value++;
EXPECT_EQ(val, buffer[i]);
if (buffer[i] != val)
return false;
}
// Prevent the same buffer from being verified multiple times simply
// because some operation that should have written to it failed
memset(buffer, 0, length);
return true;
}
class FileTest : public ::testing::Test {
protected:
std::string path_;
void SetUp() override {
path_ = webrtc::test::TempFilename(webrtc::test::OutputPath(), "test_file");
ASSERT_FALSE(path_.empty());
}
void TearDown() override { RemoveFile(path_); }
};
TEST_F(FileTest, DefaultConstructor) {
File file;
uint8_t buffer[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
EXPECT_FALSE(file.IsOpen());
EXPECT_EQ(0u, file.Write(buffer, 10));
EXPECT_FALSE(file.Seek(0));
EXPECT_EQ(0u, file.Read(buffer, 10));
EXPECT_EQ(0u, file.WriteAt(buffer, 10, 0));
EXPECT_EQ(0u, file.ReadAt(buffer, 10, 0));
EXPECT_FALSE(file.Close());
}
TEST_F(FileTest, DoubleClose) {
File file = File::Open(path_);
ASSERT_TRUE(file.IsOpen()) << "Error: " << LastError();
EXPECT_TRUE(file.Close());
EXPECT_FALSE(file.Close());
}
TEST_F(FileTest, SimpleReadWrite) {
File file = File::Open(path_);
ASSERT_TRUE(file.IsOpen()) << "Error: " << LastError();
uint8_t data[100] = {0};
uint8_t out[100] = {0};
for (int i = 0; i < 100; ++i) {
data[i] = i;
}
EXPECT_EQ(10u, file.Write(data, 10));
EXPECT_TRUE(file.Seek(0));
EXPECT_EQ(10u, file.Read(out, 10));
EXPECT_TRUE(VerifyBuffer(out, 10, 0));
EXPECT_TRUE(file.Seek(0));
EXPECT_EQ(100u, file.Write(data, 100));
EXPECT_TRUE(file.Seek(0));
EXPECT_EQ(100u, file.Read(out, 100));
EXPECT_TRUE(VerifyBuffer(out, 100, 0));
EXPECT_TRUE(file.Seek(1));
EXPECT_EQ(50u, file.Write(data, 50));
EXPECT_EQ(50u, file.Write(data + 50, 50));
EXPECT_TRUE(file.Seek(1));
EXPECT_EQ(100u, file.Read(out, 100));
EXPECT_TRUE(VerifyBuffer(out, 100, 0));
}
TEST_F(FileTest, ReadWriteClose) {
File file = File::Open(path_);
ASSERT_TRUE(file.IsOpen()) << "Error: " << LastError();
uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
uint8_t out[10] = {0};
EXPECT_EQ(10u, file.Write(data, 10));
EXPECT_TRUE(file.Close());
File file2 = File::Open(path_);
ASSERT_TRUE(file2.IsOpen()) << "Error: " << LastError();
EXPECT_EQ(10u, file2.Read(out, 10));
EXPECT_TRUE(VerifyBuffer(out, 10, 0));
}
TEST_F(FileTest, RandomAccessRead) {
File file = File::Open(path_);
ASSERT_TRUE(file.IsOpen()) << "Error: " << LastError();
uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
uint8_t out[10] = {0};
EXPECT_EQ(10u, file.Write(data, 10));
EXPECT_EQ(4u, file.ReadAt(out, 4, 0));
EXPECT_TRUE(VerifyBuffer(out, 4, 0));
EXPECT_EQ(4u, file.ReadAt(out, 4, 4));
EXPECT_TRUE(VerifyBuffer(out, 4, 4));
EXPECT_EQ(5u, file.ReadAt(out, 5, 5));
EXPECT_TRUE(VerifyBuffer(out, 5, 5));
}
TEST_F(FileTest, RandomAccessReadWrite) {
File file = File::Open(path_);
ASSERT_TRUE(file.IsOpen()) << "Error: " << LastError();
uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
uint8_t out[10] = {0};
EXPECT_EQ(10u, file.Write(data, 10));
EXPECT_TRUE(file.Seek(4));
EXPECT_EQ(4u, file.WriteAt(data, 4, 4));
EXPECT_EQ(4u, file.ReadAt(out, 4, 4));
EXPECT_TRUE(VerifyBuffer(out, 4, 0));
EXPECT_EQ(2u, file.WriteAt(data, 2, 8));
EXPECT_EQ(2u, file.ReadAt(out, 2, 8));
EXPECT_TRUE(VerifyBuffer(out, 2, 0));
}
TEST_F(FileTest, ShouldBeAbleToRemoveFile) {
{
File file = File::Open(path_);
ASSERT_TRUE(file.IsOpen()) << "Error: " << LastError();
}
ASSERT_TRUE(File::Remove(path_)) << "Error: " << LastError();
}
} // namespace rtc
| {
"pile_set_name": "Github"
} |
package org.stjs.generator.writer;
import org.stjs.generator.GenerationContext;
import org.stjs.generator.visitor.TreePathScannerContributors;
/**
* This class visits the Java AST and calls the corresponding writers to generate JavaScript.
*
* @author acraciun
*/
public class WriterVisitor<R> extends TreePathScannerContributors<R, GenerationContext<R>, WriterVisitor<R>> {
public WriterVisitor() {
super();
// setting another contributor for a node would replace the existing one
setOnlyOneFinalContributor(true);
}
public WriterVisitor(WriterVisitor<R> writerVisitor) {
super(writerVisitor);
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="gb2312"?>
<VisualStudioUserFile
ProjectType="Visual C++"
Version="9.00"
ShowAllFiles="false"
>
<Configurations>
<Configuration
Name="Debug|Win32"
>
<DebugSettings
Command="$(TargetPath)"
WorkingDirectory="..\demo"
CommandArguments="-p skin -i skin\index.xml -r duires\winres.rc2"
Attach="false"
DebuggerType="3"
Remote="1"
RemoteMachine="HUANGJX-PC"
RemoteCommand=""
HttpUrl=""
PDBPath=""
SQLDebugging=""
Environment=""
EnvironmentMerge="true"
DebuggerFlavor="0"
MPIRunCommand=""
MPIRunArguments=""
MPIRunWorkingDirectory=""
ApplicationCommand=""
ApplicationArguments=""
ShimCommand=""
MPIAcceptMode=""
MPIAcceptFilter=""
/>
</Configuration>
<Configuration
Name="Release|Win32"
>
<DebugSettings
Command="$(TargetPath)"
WorkingDirectory=""
CommandArguments=""
Attach="false"
DebuggerType="3"
Remote="1"
RemoteMachine="HUANGJX-PC"
RemoteCommand=""
HttpUrl=""
PDBPath=""
SQLDebugging=""
Environment=""
EnvironmentMerge="true"
DebuggerFlavor=""
MPIRunCommand=""
MPIRunArguments=""
MPIRunWorkingDirectory=""
ApplicationCommand=""
ApplicationArguments=""
ShimCommand=""
MPIAcceptMode=""
MPIAcceptFilter=""
/>
</Configuration>
</Configurations>
</VisualStudioUserFile>
| {
"pile_set_name": "Github"
} |
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
#
# Copyright (c) 2013-2017 Oracle and/or its affiliates. All rights reserved.
#
# The contents of this file are subject to the terms of either the GNU
# General Public License Version 2 only ("GPL") or the Common Development
# and Distribution License("CDDL") (collectively, the "License"). You
# may not use this file except in compliance with the License. You can
# obtain a copy of the License at
# https://oss.oracle.com/licenses/CDDL+GPL-1.1
# or LICENSE.txt. See the License for the specific
# language governing permissions and limitations under the License.
#
# When distributing the software, include this License Header Notice in each
# file and include the License file at LICENSE.txt.
#
# GPL Classpath Exception:
# Oracle designates this particular file as subject to the "Classpath"
# exception as provided by Oracle in the GPL Version 2 section of the License
# file that accompanied this code.
#
# Modifications:
# If applicable, add the following below the License Header, with the fields
# enclosed by brackets [] replaced by your own identifying information:
# "Portions Copyright [year] [name of copyright owner]"
#
# Contributor(s):
# If you wish your version of this file to be governed by only the CDDL or
# only the GPL Version 2, indicate your decision by adding "[Contributor]
# elects to include this software in this distribution under the [CDDL or GPL
# Version 2] license." If you don't indicate a single choice of license, a
# recipient has the option to distribute your version of this file under
# either the CDDL, the GPL Version 2 or to extend the choice of license to
# its licensees as provided above. However, if you add GPL Version 2 code
# and therefore, elected the GPL Version 2 license, then the option applies
# only if the new code is made subject to such option by the copyright
# holder.
#
# Options to wscompile target for this test suite.
debug=false
keep=false
verbose=false
genWsdl=false
package=fromjava.mbyte.client
# the name of the generated war file:
warfilename=fromjava_mbyte
wsdlname=${build.temp}/WEB-INF/wsdl/Hello\u00eeService.wsdl
endpointimplementationclass=fromjava.mbyte.server.TestService
client.binding=custom-client.xml
server.binding=
| {
"pile_set_name": "Github"
} |
GL_EXT_depth_bounds_test
http://www.nvidia.com/dev_content/nvopenglspecs/GL_EXT_depth_bounds_test.txt
GL_EXT_depth_bounds_test
GL_DEPTH_BOUNDS_TEST_EXT 0x8890
GL_DEPTH_BOUNDS_EXT 0x8891
void glDepthBoundsEXT (GLclampd zmin, GLclampd zmax)
| {
"pile_set_name": "Github"
} |
.class final Lcom/lifx/app/controller/effects/EffectsControlScreen$handleMessage$$inlined$let$lambda$1;
.super Lkotlin/jvm/internal/Lambda;
.source "SourceFile"
# interfaces
.implements Lkotlin/jvm/functions/Function0;
# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
value = Lcom/lifx/app/controller/effects/EffectsControlScreen;->handleMessage(Landroid/os/Message;)Z
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x18
name = null
.end annotation
.annotation system Ldalvik/annotation/Signature;
value = {
"Lkotlin/jvm/internal/Lambda;",
"Lkotlin/jvm/functions/Function0",
"<",
"Lkotlin/Unit;",
">;"
}
.end annotation
# instance fields
.field final synthetic a:Lcom/lifx/lifx/effects/Effect;
.field final synthetic b:Lcom/lifx/core/entity/LightTarget;
.field final synthetic c:Lcom/lifx/app/controller/effects/EffectsControlScreen;
# direct methods
.method constructor <init>(Lcom/lifx/lifx/effects/Effect;Lcom/lifx/core/entity/LightTarget;Lcom/lifx/app/controller/effects/EffectsControlScreen;)V
.locals 1
iput-object p1, p0, Lcom/lifx/app/controller/effects/EffectsControlScreen$handleMessage$$inlined$let$lambda$1;->a:Lcom/lifx/lifx/effects/Effect;
iput-object p2, p0, Lcom/lifx/app/controller/effects/EffectsControlScreen$handleMessage$$inlined$let$lambda$1;->b:Lcom/lifx/core/entity/LightTarget;
iput-object p3, p0, Lcom/lifx/app/controller/effects/EffectsControlScreen$handleMessage$$inlined$let$lambda$1;->c:Lcom/lifx/app/controller/effects/EffectsControlScreen;
const/4 v0, 0x0
invoke-direct {p0, v0}, Lkotlin/jvm/internal/Lambda;-><init>(I)V
return-void
.end method
# virtual methods
.method public final a()V
.locals 3
.prologue
.line 239
iget-object v0, p0, Lcom/lifx/app/controller/effects/EffectsControlScreen$handleMessage$$inlined$let$lambda$1;->c:Lcom/lifx/app/controller/effects/EffectsControlScreen;
invoke-static {v0}, Lcom/lifx/app/controller/effects/EffectsControlScreen;->d(Lcom/lifx/app/controller/effects/EffectsControlScreen;)Lcom/lifx/lifx/effects/IEffectService;
move-result-object v0
if-eqz v0, :cond_0
iget-object v1, p0, Lcom/lifx/app/controller/effects/EffectsControlScreen$handleMessage$$inlined$let$lambda$1;->b:Lcom/lifx/core/entity/LightTarget;
iget-object v2, p0, Lcom/lifx/app/controller/effects/EffectsControlScreen$handleMessage$$inlined$let$lambda$1;->a:Lcom/lifx/lifx/effects/Effect;
invoke-interface {v0, v1, v2}, Lcom/lifx/lifx/effects/IEffectService;->a(Lcom/lifx/core/entity/LightTarget;Lcom/lifx/lifx/effects/Effect;)V
:cond_0
return-void
.end method
.method public synthetic invoke()Ljava/lang/Object;
.locals 1
.prologue
.line 66
invoke-virtual {p0}, Lcom/lifx/app/controller/effects/EffectsControlScreen$handleMessage$$inlined$let$lambda$1;->a()V
sget-object v0, Lkotlin/Unit;->a:Lkotlin/Unit;
return-object v0
.end method
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!-- generated on Wed Sep 19 12:37:26 2018 by Eclipse SUMO Version v1_0_1+0023-9f2cdf8
This data file and the accompanying materials
are made available under the terms of the Eclipse Public License v2.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v20.html
SPDX-License-Identifier: EPL-2.0
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/sumoConfiguration.xsd">
<input>
<net-file value="net2.net.xml"/>
<additional-files value="input_additional.add.xml"/>
</input>
<output>
<write-license value="true"/>
</output>
<time>
<end value="300"/>
</time>
<processing>
<default.speeddev value="0"/>
</processing>
<report>
<xml-validation value="never"/>
<duration-log.disable value="true"/>
<no-step-log value="true"/>
</report>
</configuration>
-->
<tlsStates xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/tlsstates_file.xsd">
<tlsState time="0.00" id="C" programID="custom" phase="0" state="GGGggrrrrrGGGggrrrrr"/>
<tlsState time="33.00" id="C" programID="custom" phase="1" state="yyyggrrrrryyyggrrrrr"/>
<tlsState time="36.00" id="C" programID="custom" phase="2" state="rrrGGrrrrrrrrGGrrrrr"/>
<tlsState time="42.00" id="C" programID="custom" phase="3" state="rrryyrrrrrrrryyrrrrr"/>
<tlsState time="45.00" id="C" programID="custom" phase="4" state="rrrrrGGGggrrrrrGGGgg"/>
<tlsState time="78.00" id="C" programID="custom" phase="5" state="rrrrryyyggrrrrryyygg"/>
<tlsState time="81.00" id="C" programID="custom" phase="6" state="rrrrrrrrGGrrrrrrrrGG"/>
<tlsState time="87.00" id="C" programID="custom" phase="7" state="rrrrrrrryyrrrrrrrryy"/>
<tlsState time="90.00" id="C" programID="custom" phase="0" state="GGGggrrrrrGGGggrrrrr"/>
<tlsState time="123.00" id="C" programID="custom" phase="1" state="yyyggrrrrryyyggrrrrr"/>
<tlsState time="126.00" id="C" programID="custom" phase="2" state="rrrGGrrrrrrrrGGrrrrr"/>
<tlsState time="132.00" id="C" programID="custom" phase="3" state="rrryyrrrrrrrryyrrrrr"/>
<tlsState time="135.00" id="C" programID="custom" phase="4" state="rrrrrGGGggrrrrrGGGgg"/>
<tlsState time="168.00" id="C" programID="custom" phase="5" state="rrrrryyyggrrrrryyygg"/>
<tlsState time="171.00" id="C" programID="custom" phase="6" state="rrrrrrrrGGrrrrrrrrGG"/>
<tlsState time="177.00" id="C" programID="custom" phase="7" state="rrrrrrrryyrrrrrrrryy"/>
<tlsState time="180.00" id="C" programID="custom" phase="0" state="GGGggrrrrrGGGggrrrrr"/>
<tlsState time="213.00" id="C" programID="custom" phase="1" state="yyyggrrrrryyyggrrrrr"/>
<tlsState time="216.00" id="C" programID="custom" phase="2" state="rrrGGrrrrrrrrGGrrrrr"/>
<tlsState time="222.00" id="C" programID="custom" phase="3" state="rrryyrrrrrrrryyrrrrr"/>
<tlsState time="225.00" id="C" programID="custom" phase="4" state="rrrrrGGGggrrrrrGGGgg"/>
<tlsState time="258.00" id="C" programID="custom" phase="5" state="rrrrryyyggrrrrryyygg"/>
<tlsState time="261.00" id="C" programID="custom" phase="6" state="rrrrrrrrGGrrrrrrrrGG"/>
<tlsState time="267.00" id="C" programID="custom" phase="7" state="rrrrrrrryyrrrrrrrryy"/>
<tlsState time="270.00" id="C" programID="custom" phase="0" state="GGGggrrrrrGGGggrrrrr"/>
</tlsStates>
| {
"pile_set_name": "Github"
} |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\MethodRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type WorkbookFunctionsCscRequestBuilder.
/// </summary>
public partial class WorkbookFunctionsCscRequestBuilder : BaseActionMethodRequestBuilder<IWorkbookFunctionsCscRequest>, IWorkbookFunctionsCscRequestBuilder
{
/// <summary>
/// Constructs a new <see cref="WorkbookFunctionsCscRequestBuilder"/>.
/// </summary>
/// <param name="requestUrl">The URL for the request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="number">A number parameter for the OData method call.</param>
public WorkbookFunctionsCscRequestBuilder(
string requestUrl,
IBaseClient client,
Newtonsoft.Json.Linq.JToken number)
: base(requestUrl, client)
{
this.SetParameter("number", number, true);
}
/// <summary>
/// A method used by the base class to construct a request class instance.
/// </summary>
/// <param name="functionUrl">The request URL to </param>
/// <param name="options">The query and header options for the request.</param>
/// <returns>An instance of a specific request class.</returns>
protected override IWorkbookFunctionsCscRequest CreateRequest(string functionUrl, IEnumerable<Option> options)
{
var request = new WorkbookFunctionsCscRequest(functionUrl, this.Client, options);
if (this.HasParameter("number"))
{
request.RequestBody.Number = this.GetParameter<Newtonsoft.Json.Linq.JToken>("number");
}
return request;
}
}
}
| {
"pile_set_name": "Github"
} |
{
"word": "Unsold",
"definitions": [
"(of an item) not sold."
],
"parts-of-speech": "Adjective"
} | {
"pile_set_name": "Github"
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using Windows.Foundation.Collections;
namespace ModernWpf.Tests.MUXControls.ApiTests.RepeaterTests.Common
{
public class WinRTCollection : IObservableVector<object>
{
private IList<object> m_data;
public WinRTCollection(IEnumerable<object> collection)
{
m_data = new List<object>(collection);
}
public object this[int index]
{
get { return m_data[index]; }
set
{
m_data[index] = value;
if (VectorChanged != null) { VectorChanged(this, new VectorChangedEventArgs(CollectionChange.ItemChanged, (uint)index)); }
}
}
public int Count { get { return m_data.Count; } }
public bool IsReadOnly { get { return false; } }
public event VectorChangedEventHandler<object> VectorChanged;
public void Add(object item)
{
m_data.Add(item);
if (VectorChanged != null) { VectorChanged(this, new VectorChangedEventArgs(CollectionChange.ItemInserted, (uint)m_data.Count - 1u)); }
}
public void Clear()
{
m_data.Clear();
if (VectorChanged != null) { VectorChanged(this, new VectorChangedEventArgs(CollectionChange.Reset, 0u)); }
}
public bool Contains(object item)
{
return m_data.Contains(item);
}
public void CopyTo(object[] array, int arrayIndex)
{
m_data.CopyTo(array, arrayIndex);
}
public IEnumerator<object> GetEnumerator()
{
return m_data.GetEnumerator();
}
public int IndexOf(object item)
{
return m_data.IndexOf(item);
}
public void Insert(int index, object item)
{
m_data.Insert(index, item);
if (VectorChanged != null) { VectorChanged(this, new VectorChangedEventArgs(CollectionChange.ItemInserted, (uint)index)); }
}
public bool Remove(object item)
{
var index = (uint)m_data.IndexOf(item);
if (m_data.Remove(item))
{
if (VectorChanged != null) { VectorChanged(this, new VectorChangedEventArgs(CollectionChange.ItemRemoved, index)); }
return true;
}
return false;
}
public void RemoveAt(int index)
{
m_data.RemoveAt(index);
if (VectorChanged != null) { VectorChanged(this, new VectorChangedEventArgs(CollectionChange.ItemRemoved, (uint)index)); }
}
IEnumerator IEnumerable.GetEnumerator()
{
return m_data.GetEnumerator();
}
public void Reset()
{
if (VectorChanged != null) { VectorChanged(this, new VectorChangedEventArgs(CollectionChange.Reset, 0)); }
}
public void ResetWith(IEnumerable<object> enumerable)
{
m_data = new List<object>(enumerable);
Reset();
}
private class VectorChangedEventArgs : IVectorChangedEventArgs
{
public CollectionChange CollectionChange { get; private set; }
public uint Index { get; private set; }
public VectorChangedEventArgs(CollectionChange change, uint index)
{
CollectionChange = change;
Index = index;
}
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2008 Apple Inc. 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 APPLE INC. ``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 APPLE INC. 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.
*/
#include "config.h"
#if ENABLE(JIT)
#if USE(JSVALUE64)
#include "JIT.h"
#include "CodeBlock.h"
#include "JITInlineMethods.h"
#include "JITStubCall.h"
#include "JSArray.h"
#include "JSFunction.h"
#include "Interpreter.h"
#include "ResultType.h"
#include "SamplingTool.h"
#ifndef NDEBUG
#include <stdio.h>
#endif
using namespace std;
namespace JSC {
void JIT::compileOpCallInitializeCallFrame()
{
// regT0 holds callee, regT1 holds argCount
loadPtr(Address(regT0, OBJECT_OFFSETOF(JSFunction, m_scopeChain)), regT3); // scopeChain
emitPutIntToCallFrameHeader(regT1, RegisterFile::ArgumentCount);
emitPutCellToCallFrameHeader(regT0, RegisterFile::Callee);
emitPutCellToCallFrameHeader(regT3, RegisterFile::ScopeChain);
}
void JIT::emit_op_call_put_result(Instruction* instruction)
{
int dst = instruction[1].u.operand;
emitPutVirtualRegister(dst);
}
void JIT::compileOpCallVarargs(Instruction* instruction)
{
int callee = instruction[1].u.operand;
int argCountRegister = instruction[2].u.operand;
int registerOffset = instruction[3].u.operand;
emitGetVirtualRegister(argCountRegister, regT1);
emitFastArithImmToInt(regT1);
emitGetVirtualRegister(callee, regT0);
addPtr(Imm32(registerOffset), regT1, regT2);
// Check for JSFunctions.
emitJumpSlowCaseIfNotJSCell(regT0);
addSlowCase(branchPtr(NotEqual, Address(regT0), TrustedImmPtr(m_globalData->jsFunctionVPtr)));
// Speculatively roll the callframe, assuming argCount will match the arity.
mul32(TrustedImm32(sizeof(Register)), regT2, regT2);
intptr_t offset = (intptr_t)sizeof(Register) * (intptr_t)RegisterFile::CallerFrame;
addPtr(Imm32((int32_t)offset), regT2, regT3);
addPtr(callFrameRegister, regT3);
storePtr(callFrameRegister, regT3);
addPtr(regT2, callFrameRegister);
emitNakedCall(m_globalData->jitStubs->ctiVirtualCall());
sampleCodeBlock(m_codeBlock);
}
void JIT::compileOpCallVarargsSlowCase(Instruction*, Vector<SlowCaseEntry>::iterator& iter)
{
linkSlowCase(iter);
linkSlowCase(iter);
JITStubCall stubCall(this, cti_op_call_NotJSFunction);
stubCall.addArgument(regT0);
stubCall.addArgument(regT2);
stubCall.addArgument(regT1);
stubCall.call();
sampleCodeBlock(m_codeBlock);
}
#if !ENABLE(JIT_OPTIMIZE_CALL)
/* ------------------------------ BEGIN: !ENABLE(JIT_OPTIMIZE_CALL) ------------------------------ */
void JIT::compileOpCall(OpcodeID opcodeID, Instruction* instruction, unsigned)
{
int callee = instruction[1].u.operand;
int argCount = instruction[2].u.operand;
int registerOffset = instruction[3].u.operand;
// Handle eval
Jump wasEval;
if (opcodeID == op_call_eval) {
JITStubCall stubCall(this, cti_op_call_eval);
stubCall.addArgument(callee, regT0);
stubCall.addArgument(JIT::Imm32(registerOffset));
stubCall.addArgument(JIT::Imm32(argCount));
stubCall.call();
wasEval = branchPtr(NotEqual, regT0, TrustedImmPtr(JSValue::encode(JSValue())));
}
emitGetVirtualRegister(callee, regT0);
// Check for JSFunctions.
emitJumpSlowCaseIfNotJSCell(regT0);
addSlowCase(branchPtr(NotEqual, Address(regT0), TrustedImmPtr(m_globalData->jsFunctionVPtr)));
// Speculatively roll the callframe, assuming argCount will match the arity.
storePtr(callFrameRegister, Address(callFrameRegister, (RegisterFile::CallerFrame + registerOffset) * static_cast<int>(sizeof(Register))));
addPtr(Imm32(registerOffset * static_cast<int>(sizeof(Register))), callFrameRegister);
move(Imm32(argCount), regT1);
emitNakedCall(opcodeID == op_construct ? m_globalData->jitStubs->ctiVirtualConstruct() : m_globalData->jitStubs->ctiVirtualCall());
if (opcodeID == op_call_eval)
wasEval.link(this);
sampleCodeBlock(m_codeBlock);
}
void JIT::compileOpCallSlowCase(Instruction* instruction, Vector<SlowCaseEntry>::iterator& iter, unsigned, OpcodeID opcodeID)
{
int argCount = instruction[2].u.operand;
int registerOffset = instruction[3].u.operand;
linkSlowCase(iter);
linkSlowCase(iter);
JITStubCall stubCall(this, opcodeID == op_construct ? cti_op_construct_NotJSConstruct : cti_op_call_NotJSFunction);
stubCall.addArgument(regT0);
stubCall.addArgument(JIT::Imm32(registerOffset));
stubCall.addArgument(JIT::Imm32(argCount));
stubCall.call();
sampleCodeBlock(m_codeBlock);
}
#else // !ENABLE(JIT_OPTIMIZE_CALL)
/* ------------------------------ BEGIN: ENABLE(JIT_OPTIMIZE_CALL) ------------------------------ */
void JIT::compileOpCall(OpcodeID opcodeID, Instruction* instruction, unsigned callLinkInfoIndex)
{
int callee = instruction[1].u.operand;
int argCount = instruction[2].u.operand;
int registerOffset = instruction[3].u.operand;
// Handle eval
Jump wasEval;
if (opcodeID == op_call_eval) {
JITStubCall stubCall(this, cti_op_call_eval);
stubCall.addArgument(callee, regT0);
stubCall.addArgument(JIT::Imm32(registerOffset));
stubCall.addArgument(JIT::Imm32(argCount));
stubCall.call();
wasEval = branchPtr(NotEqual, regT0, TrustedImmPtr(JSValue::encode(JSValue())));
}
// This plants a check for a cached JSFunction value, so we can plant a fast link to the callee.
// This deliberately leaves the callee in ecx, used when setting up the stack frame below
emitGetVirtualRegister(callee, regT0);
DataLabelPtr addressOfLinkedFunctionCheck;
BEGIN_UNINTERRUPTED_SEQUENCE(sequenceOpCall);
Jump jumpToSlow = branchPtrWithPatch(NotEqual, regT0, addressOfLinkedFunctionCheck, TrustedImmPtr(JSValue::encode(JSValue())));
END_UNINTERRUPTED_SEQUENCE(sequenceOpCall);
addSlowCase(jumpToSlow);
ASSERT_JIT_OFFSET(differenceBetween(addressOfLinkedFunctionCheck, jumpToSlow), patchOffsetOpCallCompareToJump);
m_callStructureStubCompilationInfo[callLinkInfoIndex].hotPathBegin = addressOfLinkedFunctionCheck;
// The following is the fast case, only used whan a callee can be linked.
// Fast version of stack frame initialization, directly relative to edi.
// Note that this omits to set up RegisterFile::CodeBlock, which is set in the callee
loadPtr(Address(regT0, OBJECT_OFFSETOF(JSFunction, m_scopeChain)), regT1); // newScopeChain
store32(TrustedImm32(Int32Tag), intTagFor(registerOffset + RegisterFile::ArgumentCount));
store32(Imm32(argCount), intPayloadFor(registerOffset + RegisterFile::ArgumentCount));
storePtr(callFrameRegister, Address(callFrameRegister, (registerOffset + RegisterFile::CallerFrame) * static_cast<int>(sizeof(Register))));
storePtr(regT0, Address(callFrameRegister, (registerOffset + RegisterFile::Callee) * static_cast<int>(sizeof(Register))));
storePtr(regT1, Address(callFrameRegister, (registerOffset + RegisterFile::ScopeChain) * static_cast<int>(sizeof(Register))));
addPtr(Imm32(registerOffset * sizeof(Register)), callFrameRegister);
// Call to the callee
m_callStructureStubCompilationInfo[callLinkInfoIndex].hotPathOther = emitNakedCall();
if (opcodeID == op_call_eval)
wasEval.link(this);
sampleCodeBlock(m_codeBlock);
}
void JIT::compileOpCallSlowCase(Instruction* instruction, Vector<SlowCaseEntry>::iterator& iter, unsigned callLinkInfoIndex, OpcodeID opcodeID)
{
int argCount = instruction[2].u.operand;
int registerOffset = instruction[3].u.operand;
linkSlowCase(iter);
// Fast check for JS function.
Jump callLinkFailNotObject = emitJumpIfNotJSCell(regT0);
Jump callLinkFailNotJSFunction = branchPtr(NotEqual, Address(regT0), TrustedImmPtr(m_globalData->jsFunctionVPtr));
// Speculatively roll the callframe, assuming argCount will match the arity.
storePtr(callFrameRegister, Address(callFrameRegister, (RegisterFile::CallerFrame + registerOffset) * static_cast<int>(sizeof(Register))));
addPtr(Imm32(registerOffset * static_cast<int>(sizeof(Register))), callFrameRegister);
move(Imm32(argCount), regT1);
m_callStructureStubCompilationInfo[callLinkInfoIndex].callReturnLocation = emitNakedCall(opcodeID == op_construct ? m_globalData->jitStubs->ctiVirtualConstructLink() : m_globalData->jitStubs->ctiVirtualCallLink());
// Done! - return back to the hot path.
ASSERT(OPCODE_LENGTH(op_call) == OPCODE_LENGTH(op_call_eval));
ASSERT(OPCODE_LENGTH(op_call) == OPCODE_LENGTH(op_construct));
emitJumpSlowToHot(jump(), OPCODE_LENGTH(op_call));
// This handles host functions
callLinkFailNotObject.link(this);
callLinkFailNotJSFunction.link(this);
JITStubCall stubCall(this, opcodeID == op_construct ? cti_op_construct_NotJSConstruct : cti_op_call_NotJSFunction);
stubCall.addArgument(regT0);
stubCall.addArgument(JIT::Imm32(registerOffset));
stubCall.addArgument(JIT::Imm32(argCount));
stubCall.call();
sampleCodeBlock(m_codeBlock);
}
/* ------------------------------ END: !ENABLE / ENABLE(JIT_OPTIMIZE_CALL) ------------------------------ */
#endif // !ENABLE(JIT_OPTIMIZE_CALL)
} // namespace JSC
#endif // USE(JSVALUE64)
#endif // ENABLE(JIT)
| {
"pile_set_name": "Github"
} |
// ---------------------------------------------------------------------
//
// Copyright (C) 2015 - 2020 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE.md at
// the top level directory of deal.II.
//
// ---------------------------------------------------------------------
// Test for composite operations
#include <deal.II/lac/dynamic_sparsity_pattern.h>
#include <deal.II/lac/linear_operator.h>
#include <deal.II/lac/packaged_operation.h>
#include <deal.II/lac/precondition.h>
#include <deal.II/lac/solver_cg.h>
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/vector.h>
#include "../tests.h"
#define PRINTME(name, var) \
deallog << "Solution vector: " << name << ": " << var;
int
main()
{
initlog();
deallog << std::setprecision(10);
// SparseMatrix:
{
const unsigned int rc = 2;
SparsityPattern sparsity_pattern(rc, rc, 0);
sparsity_pattern.compress();
SparseMatrix<double> A(sparsity_pattern);
Vector<double> b(rc);
for (unsigned int i = 0; i < rc; ++i)
{
A.diag_element(i) = 5.0;
b(i) = 1.0;
}
const auto lo_A = linear_operator(A);
const auto lo_A_t = transpose_operator(lo_A);
// build transpose of inverse
SolverControl solver_control_A_1(100, 1.0e-10);
SolverCG<Vector<double>> solver_A_1(solver_control_A_1);
PreconditionJacobi<SparseMatrix<double>> preconditioner_A_1;
preconditioner_A_1.initialize(A);
const auto lo_A_inv =
inverse_operator(lo_A, solver_A_1, preconditioner_A_1);
const auto lo_A_inv_t = transpose_operator(lo_A_inv);
// build inverse of transpose
SolverControl solver_control_A_2(100, 1.0e-10);
SolverCG<Vector<double>> solver_A_2(solver_control_A_2);
PreconditionJacobi<SparseMatrix<double>> preconditioner_A_2;
preconditioner_A_2.initialize(A);
const auto lo_A_t_inv =
inverse_operator(lo_A_t, solver_A_2, preconditioner_A_2);
deallog << "Normal and inverse multiplication operations" << std::endl;
const Vector<double> x1 = lo_A * b;
const Vector<double> x2 = lo_A_t * b;
const Vector<double> x3 = lo_A_inv * b;
const Vector<double> x4a = lo_A_inv_t * b;
const Vector<double> x4b = lo_A_t_inv * b;
// PRINTME("x1", x1);
// PRINTME("x2", x2);
// PRINTME("x3", x3);
// PRINTME("x4a", x4a);
// PRINTME("x4b", x4b);
deallog << "x4a==x4b : " << (x4a == x4b) << std::endl;
// Schur-type composition
SparseMatrix<double> B(sparsity_pattern);
SparseMatrix<double> C(sparsity_pattern);
SparseMatrix<double> D(sparsity_pattern);
for (unsigned int i = 0; i < rc; ++i)
{
B.diag_element(i) = 4.0;
C.diag_element(i) = 4.0; // K = [A,B ; C,D] is symmetric
D.diag_element(i) = 3.0;
}
const auto lo_B = linear_operator(B);
const auto lo_C = linear_operator(C);
const auto lo_D = linear_operator(D);
const auto lo_B_t = transpose_operator(lo_B);
const auto lo_C_t = transpose_operator(lo_C);
const auto lo_D_t = transpose_operator(lo_D);
deallog << "Single packaged operation" << std::endl;
{
const auto S = lo_D - lo_C * lo_A_inv * lo_B;
const auto S_t_1 =
lo_D_t - lo_B_t * lo_A_inv_t * lo_C_t; // using transpose of inverse
const auto S_t_2 =
lo_D_t - lo_B_t * lo_A_t_inv * lo_C_t; // using inverse of transpose
const Vector<double> x5 = S * b;
const Vector<double> x6a = S_t_1 * b;
const Vector<double> x6b = S_t_2 * b;
deallog << "x5==x6a : " << (x5 == x6a)
<< std::endl; // using transpose of inverse
deallog << "x5==x6b : " << (x5 == x6b)
<< std::endl; // using inverse of transpose
// PRINTME("x5", x5);
// PRINTME("x6a", x6a);
// PRINTME("x6b", x6b);
}
deallog << "Manual operations" << std::endl;
{
const Vector<double> x5a = lo_B * b;
const Vector<double> x5b = lo_A_inv * x5a;
const Vector<double> x5c = lo_C * x5b;
const Vector<double> x5d = lo_D * b - x5c;
const Vector<double> x6a = lo_C_t * b;
const Vector<double> x6b_1 =
lo_A_inv_t * x6a; // using transpose of inverse
const Vector<double> x6c_1 = lo_B_t * x6b_1;
const Vector<double> x6d_1 = lo_D_t * b - x6c_1;
const Vector<double> x6b_2 =
lo_A_t_inv * x6a; // using inverse of transpose
const Vector<double> x6c_2 = lo_B_t * x6b_2;
const Vector<double> x6d_2 = lo_D_t * b - x6c_2;
deallog << "x5a==x6a : " << (x5a == x6a) << std::endl;
deallog << "x5b==x6b_1 : " << (x5b == x6b_1)
<< std::endl; // using transpose of inverse
deallog << "x5c==x6c_1 : " << (x5c == x6c_1) << std::endl;
deallog << "x5d==x6d_1 : " << (x5d == x6d_1) << std::endl;
deallog << "x5b==x6b_2 : " << (x5b == x6b_2)
<< std::endl; // using inverse of transpose
deallog << "x5c==x6c_2 : " << (x5c == x6c_2) << std::endl;
deallog << "x5d==x6d_2 : " << (x5d == x6d_2) << std::endl;
// PRINTME("x5a", x5a);
// PRINTME("x6a", x6a);
// PRINTME("x5b", x5b);
// PRINTME("x6b_1", x6b_1);
// PRINTME("x6b_2", x6b_2);
// PRINTME("x5c", x5c);
// PRINTME("x6c_1", x6c_1);
// PRINTME("x6c_2", x6c_2);
// PRINTME("x5d", x5d);
// PRINTME("x6d_1", x6d_1);
// PRINTME("x6d_2", x6d_2);
}
deallog << "OK" << std::endl;
}
}
| {
"pile_set_name": "Github"
} |
<?php
namespace SMW\Elastic\QueryEngine;
use Psr\Log\LoggerAwareTrait;
use SMW\ApplicationFactory;
use SMW\DIProperty;
use SMW\DIWikiPage;
use SMW\Options;
use SMW\HierarchyLookup;
use SMW\Services\ServicesContainer;
use SMW\Query\Language\ClassDescription;
use SMW\Query\Language\ConceptDescription;
use SMW\Query\Language\Conjunction;
use SMW\Query\Language\Description;
use SMW\Query\Language\Disjunction;
use SMW\Query\Language\NamespaceDescription;
use SMW\Query\Language\SomeProperty;
use SMW\Query\Language\ValueDescription;
use SMW\Store;
use SMWDataItem as DataItem;
/**
* Build an internal representation for a SPARQL condition from individual query
* descriptions.
*
* @license GNU GPL v2+
* @since 3.0
*
* @author mwjames
*/
class ConditionBuilder {
use LoggerAwareTrait;
/**
* @var Store
*/
private $store;
/**
* @var Options
*/
private $options;
/**
* @var TermsLookup
*/
private $termsLookup;
/**
* @var HierarchyLookup
*/
private $hierarchyLookup;
/**
* @var ServicesContainer
*/
private $servicesContainer;
/**
* @var FieldMapper
*/
private $fieldMapper;
/**
* @var ConceptDescriptionInterpreter
*/
private $conceptDescriptionInterpreter;
/**
* @var ClassDescriptionInterpreter
*/
private $classDescriptionInterpreter;
/**
* @var ValueDescriptionInterpreter
*/
private $valueDescriptionInterpreter;
/**
* @var SomePropertyInterpreter
*/
private $somePropertyInterpreter;
/**
* @var ConjunctionInterpreter
*/
private $conjunctionInterpreter;
/**
* @var DisjunctionInterpreter
*/
private $disjunctionInterpreter;
/**
* @var NamespaceDescriptionInterpreter
*/
private $namespaceDescriptionInterpreter;
/**
* @var SomeValueInterpreter
*/
private $someValueInterpreter;
/**
* @var array
*/
private $sortFields = [];
/**
* @var array
*/
private $errors = [];
/**
* @var array
*/
private $queryInfo = [];
/**
* @var array
*/
private $descriptionLog = [];
/**
* @var boolean
*/
protected $isConstantScore = true;
/**
* @var boolean
*/
private $initServices = false;
/**
* @since 3.0
*
* @param Store $store
* @param TermsLookup $termsLookup
* @param HierarchyLookup $hierarchyLookup
* @param ServicesContainer $servicesContainer
*/
public function __construct( Store $store, TermsLookup $termsLookup, HierarchyLookup $hierarchyLookup, ServicesContainer $servicesContainer ) {
$this->store = $store;
$this->termsLookup = $termsLookup;
$this->hierarchyLookup = $hierarchyLookup;
$this->servicesContainer = $servicesContainer;
}
/**
* @since 3.0
*
* @param Options $options
*/
public function setOptions( Options $options ) {
$this->options = $options;
}
/**
* @since 3.0
*
* @param string $key
*
* @return mixed
*/
public function getOption( $key, $default = false ) {
if ( $this->options === null ) {
$this->options = new Options();
}
return $this->options->safeGet( $key, $default );
}
/**
* @since 3.0
*
* @param array $sortFields
*/
public function setSortFields( array $sortFields ) {
$this->sortFields = $sortFields;
}
/**
* @since 3.0
*
* @return Store
*/
public function getStore() {
return $this->store;
}
/**
* @since 3.0
*
* @return TermsLookup
*/
public function getTermsLookup() {
return $this->termsLookup;
}
/**
* @since 3.0
*
* @return FieldMapper
*/
public function getFieldMapper() {
if ( $this->fieldMapper === null ) {
$this->fieldMapper = new FieldMapper();
}
return $this->fieldMapper;
}
/**
* @since 3.0
*
* @param []
*/
public function getQueryInfo() {
return $this->queryInfo;
}
/**
* @since 3.0
*
* @param array $queryInfo
*/
public function addQueryInfo( array $queryInfo ) {
$this->queryInfo[] = $queryInfo;
}
/**
* @since 3.0
*
* @param []
*/
public function getDescriptionLog() {
return $this->descriptionLog;
}
/**
* @since 3.0
*
* @return array
*/
public function getErrors() {
return $this->errors;
}
/**
* @since 3.0
*
* @param array $error
*/
public function addError( array $error ) {
$this->errors[] = $error;
}
/**
* @since 3.2
*
* @param array $dataItems
*/
public function prepareCache( array $dataItems ) {
$this->store->getObjectIds()->warmUpCache( $dataItems );
}
/**
* @since 3.0
*
* @return integer
*/
public function getID( $dataItem ) {
if ( $dataItem instanceof DIProperty ) {
return (int)$this->store->getObjectIds()->getSMWPropertyID(
$dataItem
);
}
if ( $dataItem instanceof DIWikiPage ) {
return (int)$this->store->getObjectIds()->getSMWPageID(
$dataItem->getDBKey(),
$dataItem->getNamespace(),
$dataItem->getInterWiki(),
$dataItem->getSubobjectName()
);
}
return 0;
}
/**
* @since 3.0
*
* @param Condition|array $params
*
* @return Condition
*/
public function newCondition( $params ) {
return new Condition( $params );
}
/**
* @since 3.0
*
* @param Description $description
* @param boolean $isConstantScore
*
* @return array
*/
public function makeFromDescription( Description $description, $isConstantScore = true ) {
$this->errors = [];
$this->queryInfo = [];
$this->descriptionLog = [];
$this->termsLookup->clear();
if ( $this->fieldMapper === null ) {
$this->fieldMapper = new FieldMapper();
}
$this->fieldMapper->isCompatMode(
$this->options->safeGet( 'compat.mode', true )
);
// Some notes on the difference between term, match, and query
// string:
//
// - match, term or range queries: look for a particular value in a
// particular field
// - bool: wrap other leaf or compound queries and are used to combine
// multiple queries
// - constant_score: simply returns a constant score equal to the query
// boost for every document in the filter
$condition = $this->interpretDescription( $description );
if ( $condition instanceof Condition ) {
$query = $condition->toArray();
$this->descriptionLog = $condition->getLogs();
} else {
$query = $condition;
}
if ( $this->options->safeGet( 'sort.property.must.exists' ) && $this->sortFields !== [] ) {
$params = [];
foreach ( $this->sortFields as $field ) {
$params[] = $this->fieldMapper->exists( "$field" );
}
$query = $this->fieldMapper->bool( 'must', [ $query, $params ] );
}
// If we know we don't need any score we turn this into a `constant_score`
// query
// @see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-constant-score-query.html
if ( $isConstantScore ) {
$query = $this->fieldMapper->constant_score( $query );
}
return $query;
}
/**
* @since 3.0
*
* @param DataItem|null $dataItem
* @param integer $hierarchyDepth
*
* @return array
*/
public function findHierarchyMembers( DataItem $dataItem = null, $hierarchyDepth ) {
$ids = [];
if ( $dataItem !== null && ( $members = $this->hierarchyLookup->getConsecutiveHierarchyList( $dataItem ) ) !== [] ) {
if ( $hierarchyDepth !== null ) {
$members = $hierarchyDepth == 0 ? [] : array_slice( $members, 0, $hierarchyDepth );
}
$this->prepareCache( $members );
foreach ( $members as $member ) {
$ids[] = $this->getID( $member );
}
}
return $ids;
}
/**
* @since 3.0
*
* @param Description $description
*
* @return array
*/
public function interpretDescription( Description $description, $isConjunction = false ) {
$params = [];
if ( $this->initServices === false ) {
$this->initServices();
}
if ( $description instanceof SomeProperty ) {
$params = $this->somePropertyInterpreter->interpretDescription( $description, $isConjunction );
}
if ( $description instanceof ConceptDescription ) {
$params = $this->conceptDescriptionInterpreter->interpretDescription( $description, $isConjunction );
}
if ( $description instanceof ClassDescription ) {
$params = $this->classDescriptionInterpreter->interpretDescription( $description, $isConjunction );
}
if ( $description instanceof NamespaceDescription ) {
$params = $this->namespaceDescriptionInterpreter->interpretDescription( $description, $isConjunction );
}
if ( $description instanceof ValueDescription ) {
$params = $this->valueDescriptionInterpreter->interpretDescription( $description, $isConjunction );
}
if ( $description instanceof Conjunction ) {
$params = $this->conjunctionInterpreter->interpretDescription( $description, $isConjunction );
}
if ( $description instanceof Disjunction ) {
$params = $this->disjunctionInterpreter->interpretDescription( $description, $isConjunction );
}
return $params;
}
/**
* @since 3.0
*
* @param ValueDescription $description
* @param array &$options
*
* @return Condition
*/
public function interpretSomeValue( ValueDescription $description, array &$options ) {
if ( $this->initServices === false ) {
$this->initServices();
}
return $this->someValueInterpreter->interpretDescription( $description, $options );
}
private function initServices() {
$this->somePropertyInterpreter = $this->servicesContainer->get( 'SomePropertyInterpreter', $this );
$this->conceptDescriptionInterpreter = $this->servicesContainer->get( 'ConceptDescriptionInterpreter', $this );
$this->classDescriptionInterpreter = $this->servicesContainer->get( 'ClassDescriptionInterpreter', $this );
$this->namespaceDescriptionInterpreter = $this->servicesContainer->get( 'NamespaceDescriptionInterpreter', $this );
$this->valueDescriptionInterpreter = $this->servicesContainer->get( 'ValueDescriptionInterpreter', $this );
$this->conjunctionInterpreter = $this->servicesContainer->get( 'ConjunctionInterpreter', $this );
$this->disjunctionInterpreter = $this->servicesContainer->get( 'DisjunctionInterpreter', $this );
$this->someValueInterpreter = $this->servicesContainer->get( 'SomeValueInterpreter', $this );
$this->initServices = true;
}
}
| {
"pile_set_name": "Github"
} |
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
A45E0AD91616B6F200E23C6D /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A45E0AD81616B6F200E23C6D /* UIKit.framework */; };
A45E0ADB1616B6F200E23C6D /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A45E0ADA1616B6F200E23C6D /* Foundation.framework */; };
A45E0ADD1616B6F200E23C6D /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A45E0ADC1616B6F200E23C6D /* CoreGraphics.framework */; };
A45E0AE31616B6F200E23C6D /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = A45E0AE11616B6F200E23C6D /* InfoPlist.strings */; };
A45E0AE51616B6F200E23C6D /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = A45E0AE41616B6F200E23C6D /* main.m */; };
A45E0AE91616B6F200E23C6D /* JJAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = A45E0AE81616B6F200E23C6D /* JJAppDelegate.m */; };
A45E0AEB1616B6F200E23C6D /* Default.png in Resources */ = {isa = PBXBuildFile; fileRef = A45E0AEA1616B6F200E23C6D /* Default.png */; };
A45E0AED1616B6F200E23C6D /* [email protected] in Resources */ = {isa = PBXBuildFile; fileRef = A45E0AEC1616B6F200E23C6D /* [email protected] */; };
A45E0AEF1616B6F200E23C6D /* [email protected] in Resources */ = {isa = PBXBuildFile; fileRef = A45E0AEE1616B6F200E23C6D /* [email protected] */; };
A45E0B341616BA9E00E23C6D /* AFHTTPClient.m in Sources */ = {isa = PBXBuildFile; fileRef = A45E0B221616BA9E00E23C6D /* AFHTTPClient.m */; };
A45E0B351616BA9E00E23C6D /* AFHTTPRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = A45E0B241616BA9E00E23C6D /* AFHTTPRequestOperation.m */; };
A45E0B361616BA9E00E23C6D /* AFImageRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = A45E0B261616BA9E00E23C6D /* AFImageRequestOperation.m */; };
A45E0B371616BA9E00E23C6D /* AFJSONRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = A45E0B281616BA9E00E23C6D /* AFJSONRequestOperation.m */; };
A45E0B381616BA9E00E23C6D /* AFNetworkActivityIndicatorManager.m in Sources */ = {isa = PBXBuildFile; fileRef = A45E0B2A1616BA9E00E23C6D /* AFNetworkActivityIndicatorManager.m */; };
A45E0B391616BA9E00E23C6D /* AFPropertyListRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = A45E0B2D1616BA9E00E23C6D /* AFPropertyListRequestOperation.m */; };
A45E0B3A1616BA9E00E23C6D /* AFURLConnectionOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = A45E0B2F1616BA9E00E23C6D /* AFURLConnectionOperation.m */; };
A45E0B3B1616BA9E00E23C6D /* AFXMLRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = A45E0B311616BA9E00E23C6D /* AFXMLRequestOperation.m */; };
A45E0B3C1616BA9E00E23C6D /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = A45E0B331616BA9E00E23C6D /* UIImageView+AFNetworking.m */; };
A45E0B3F1617EEDE00E23C6D /* JJViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = A45E0B3E1617EEDE00E23C6D /* JJViewController.m */; };
A477FE88164635A200407DFE /* JJViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = A477FE87164635A200407DFE /* JJViewController.xib */; };
A477FE971646DBDF00407DFE /* JJChunkedProgressView.m in Sources */ = {isa = PBXBuildFile; fileRef = A477FE961646DBDF00407DFE /* JJChunkedProgressView.m */; };
A4E79BBF169BCA4E00941CF4 /* JJAFAcceleratedDownloadRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = A4E79BBE169BCA4E00941CF4 /* JJAFAcceleratedDownloadRequestOperation.m */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
A45E0AD41616B6F200E23C6D /* JJAFAcceleratedDownloadRequestOperation-Sample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "JJAFAcceleratedDownloadRequestOperation-Sample.app"; sourceTree = BUILT_PRODUCTS_DIR; };
A45E0AD81616B6F200E23C6D /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
A45E0ADA1616B6F200E23C6D /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
A45E0ADC1616B6F200E23C6D /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; };
A45E0AE01616B6F200E23C6D /* JJAFAcceleratedDownloadRequestOperation-Sample-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "JJAFAcceleratedDownloadRequestOperation-Sample-Info.plist"; sourceTree = "<group>"; };
A45E0AE21616B6F200E23C6D /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = "<group>"; };
A45E0AE41616B6F200E23C6D /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
A45E0AE61616B6F200E23C6D /* JJAFAcceleratedDownloadRequestOperation-Sample-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "JJAFAcceleratedDownloadRequestOperation-Sample-Prefix.pch"; sourceTree = "<group>"; };
A45E0AE71616B6F200E23C6D /* JJAppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = JJAppDelegate.h; sourceTree = "<group>"; };
A45E0AE81616B6F200E23C6D /* JJAppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = JJAppDelegate.m; sourceTree = "<group>"; };
A45E0AEA1616B6F200E23C6D /* Default.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Default.png; sourceTree = "<group>"; };
A45E0AEC1616B6F200E23C6D /* [email protected] */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "[email protected]"; sourceTree = "<group>"; };
A45E0AEE1616B6F200E23C6D /* [email protected] */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "[email protected]"; sourceTree = "<group>"; };
A45E0AFB1616B74F00E23C6D /* JJAFAcceleratedDownloadRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = JJAFAcceleratedDownloadRequestOperation.h; path = ../JJAFAcceleratedDownloadRequestOperation.h; sourceTree = "<group>"; };
A45E0B211616BA9E00E23C6D /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPClient.h; path = Libraries/AFNetworking/AFNetworking/AFHTTPClient.h; sourceTree = "<group>"; };
A45E0B221616BA9E00E23C6D /* AFHTTPClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPClient.m; path = Libraries/AFNetworking/AFNetworking/AFHTTPClient.m; sourceTree = "<group>"; };
A45E0B231616BA9E00E23C6D /* AFHTTPRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPRequestOperation.h; path = Libraries/AFNetworking/AFNetworking/AFHTTPRequestOperation.h; sourceTree = "<group>"; };
A45E0B241616BA9E00E23C6D /* AFHTTPRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPRequestOperation.m; path = Libraries/AFNetworking/AFNetworking/AFHTTPRequestOperation.m; sourceTree = "<group>"; };
A45E0B251616BA9E00E23C6D /* AFImageRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFImageRequestOperation.h; path = Libraries/AFNetworking/AFNetworking/AFImageRequestOperation.h; sourceTree = "<group>"; };
A45E0B261616BA9E00E23C6D /* AFImageRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageRequestOperation.m; path = Libraries/AFNetworking/AFNetworking/AFImageRequestOperation.m; sourceTree = "<group>"; };
A45E0B271616BA9E00E23C6D /* AFJSONRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFJSONRequestOperation.h; path = Libraries/AFNetworking/AFNetworking/AFJSONRequestOperation.h; sourceTree = "<group>"; };
A45E0B281616BA9E00E23C6D /* AFJSONRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFJSONRequestOperation.m; path = Libraries/AFNetworking/AFNetworking/AFJSONRequestOperation.m; sourceTree = "<group>"; };
A45E0B291616BA9E00E23C6D /* AFNetworkActivityIndicatorManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFNetworkActivityIndicatorManager.h; path = Libraries/AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.h; sourceTree = "<group>"; };
A45E0B2A1616BA9E00E23C6D /* AFNetworkActivityIndicatorManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFNetworkActivityIndicatorManager.m; path = Libraries/AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.m; sourceTree = "<group>"; };
A45E0B2B1616BA9E00E23C6D /* AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFNetworking.h; path = Libraries/AFNetworking/AFNetworking/AFNetworking.h; sourceTree = "<group>"; };
A45E0B2C1616BA9E00E23C6D /* AFPropertyListRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFPropertyListRequestOperation.h; path = Libraries/AFNetworking/AFNetworking/AFPropertyListRequestOperation.h; sourceTree = "<group>"; };
A45E0B2D1616BA9E00E23C6D /* AFPropertyListRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFPropertyListRequestOperation.m; path = Libraries/AFNetworking/AFNetworking/AFPropertyListRequestOperation.m; sourceTree = "<group>"; };
A45E0B2E1616BA9E00E23C6D /* AFURLConnectionOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFURLConnectionOperation.h; path = Libraries/AFNetworking/AFNetworking/AFURLConnectionOperation.h; sourceTree = "<group>"; };
A45E0B2F1616BA9E00E23C6D /* AFURLConnectionOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFURLConnectionOperation.m; path = Libraries/AFNetworking/AFNetworking/AFURLConnectionOperation.m; sourceTree = "<group>"; };
A45E0B301616BA9E00E23C6D /* AFXMLRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFXMLRequestOperation.h; path = Libraries/AFNetworking/AFNetworking/AFXMLRequestOperation.h; sourceTree = "<group>"; };
A45E0B311616BA9E00E23C6D /* AFXMLRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFXMLRequestOperation.m; path = Libraries/AFNetworking/AFNetworking/AFXMLRequestOperation.m; sourceTree = "<group>"; };
A45E0B321616BA9E00E23C6D /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "UIImageView+AFNetworking.h"; path = "Libraries/AFNetworking/AFNetworking/UIImageView+AFNetworking.h"; sourceTree = "<group>"; };
A45E0B331616BA9E00E23C6D /* UIImageView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "UIImageView+AFNetworking.m"; path = "Libraries/AFNetworking/AFNetworking/UIImageView+AFNetworking.m"; sourceTree = "<group>"; };
A45E0B3D1617EEDE00E23C6D /* JJViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JJViewController.h; sourceTree = "<group>"; };
A45E0B3E1617EEDE00E23C6D /* JJViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JJViewController.m; sourceTree = "<group>"; };
A477FE87164635A200407DFE /* JJViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = JJViewController.xib; sourceTree = "<group>"; };
A477FE951646DBDF00407DFE /* JJChunkedProgressView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = JJChunkedProgressView.h; path = ../JJChunkedProgressView.h; sourceTree = "<group>"; };
A477FE961646DBDF00407DFE /* JJChunkedProgressView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = JJChunkedProgressView.m; path = ../JJChunkedProgressView.m; sourceTree = "<group>"; };
A4E79BBE169BCA4E00941CF4 /* JJAFAcceleratedDownloadRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = JJAFAcceleratedDownloadRequestOperation.m; path = ../JJAFAcceleratedDownloadRequestOperation.m; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
A45E0AD11616B6F200E23C6D /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
A45E0AD91616B6F200E23C6D /* UIKit.framework in Frameworks */,
A45E0ADB1616B6F200E23C6D /* Foundation.framework in Frameworks */,
A45E0ADD1616B6F200E23C6D /* CoreGraphics.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
A45E0AC91616B6F200E23C6D = {
isa = PBXGroup;
children = (
A45E0B021616BA1B00E23C6D /* Libraries */,
A45E0AF91616B73B00E23C6D /* JJAFAcceleratedDownloadRequestOperation */,
A45E0ADE1616B6F200E23C6D /* JJAFAcceleratedDownloadRequestOperation-Sample */,
A45E0AD71616B6F200E23C6D /* Frameworks */,
A45E0AD51616B6F200E23C6D /* Products */,
);
sourceTree = "<group>";
};
A45E0AD51616B6F200E23C6D /* Products */ = {
isa = PBXGroup;
children = (
A45E0AD41616B6F200E23C6D /* JJAFAcceleratedDownloadRequestOperation-Sample.app */,
);
name = Products;
sourceTree = "<group>";
};
A45E0AD71616B6F200E23C6D /* Frameworks */ = {
isa = PBXGroup;
children = (
A45E0AD81616B6F200E23C6D /* UIKit.framework */,
A45E0ADA1616B6F200E23C6D /* Foundation.framework */,
A45E0ADC1616B6F200E23C6D /* CoreGraphics.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
A45E0ADE1616B6F200E23C6D /* JJAFAcceleratedDownloadRequestOperation-Sample */ = {
isa = PBXGroup;
children = (
A45E0AE71616B6F200E23C6D /* JJAppDelegate.h */,
A45E0AE81616B6F200E23C6D /* JJAppDelegate.m */,
A45E0B3D1617EEDE00E23C6D /* JJViewController.h */,
A45E0B3E1617EEDE00E23C6D /* JJViewController.m */,
A477FE87164635A200407DFE /* JJViewController.xib */,
A45E0ADF1616B6F200E23C6D /* Supporting Files */,
);
path = "JJAFAcceleratedDownloadRequestOperation-Sample";
sourceTree = "<group>";
};
A45E0ADF1616B6F200E23C6D /* Supporting Files */ = {
isa = PBXGroup;
children = (
A45E0AE01616B6F200E23C6D /* JJAFAcceleratedDownloadRequestOperation-Sample-Info.plist */,
A45E0AE11616B6F200E23C6D /* InfoPlist.strings */,
A45E0AE41616B6F200E23C6D /* main.m */,
A45E0AE61616B6F200E23C6D /* JJAFAcceleratedDownloadRequestOperation-Sample-Prefix.pch */,
A45E0AEA1616B6F200E23C6D /* Default.png */,
A45E0AEC1616B6F200E23C6D /* [email protected] */,
A45E0AEE1616B6F200E23C6D /* [email protected] */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
A45E0AF91616B73B00E23C6D /* JJAFAcceleratedDownloadRequestOperation */ = {
isa = PBXGroup;
children = (
A45E0AFB1616B74F00E23C6D /* JJAFAcceleratedDownloadRequestOperation.h */,
A4E79BBE169BCA4E00941CF4 /* JJAFAcceleratedDownloadRequestOperation.m */,
A477FE951646DBDF00407DFE /* JJChunkedProgressView.h */,
A477FE961646DBDF00407DFE /* JJChunkedProgressView.m */,
);
name = JJAFAcceleratedDownloadRequestOperation;
sourceTree = "<group>";
};
A45E0B021616BA1B00E23C6D /* Libraries */ = {
isa = PBXGroup;
children = (
A45E0B041616BA2500E23C6D /* AFNetworking */,
);
name = Libraries;
sourceTree = "<group>";
};
A45E0B041616BA2500E23C6D /* AFNetworking */ = {
isa = PBXGroup;
children = (
A45E0B211616BA9E00E23C6D /* AFHTTPClient.h */,
A45E0B221616BA9E00E23C6D /* AFHTTPClient.m */,
A45E0B231616BA9E00E23C6D /* AFHTTPRequestOperation.h */,
A45E0B241616BA9E00E23C6D /* AFHTTPRequestOperation.m */,
A45E0B251616BA9E00E23C6D /* AFImageRequestOperation.h */,
A45E0B261616BA9E00E23C6D /* AFImageRequestOperation.m */,
A45E0B271616BA9E00E23C6D /* AFJSONRequestOperation.h */,
A45E0B281616BA9E00E23C6D /* AFJSONRequestOperation.m */,
A45E0B291616BA9E00E23C6D /* AFNetworkActivityIndicatorManager.h */,
A45E0B2A1616BA9E00E23C6D /* AFNetworkActivityIndicatorManager.m */,
A45E0B2B1616BA9E00E23C6D /* AFNetworking.h */,
A45E0B2C1616BA9E00E23C6D /* AFPropertyListRequestOperation.h */,
A45E0B2D1616BA9E00E23C6D /* AFPropertyListRequestOperation.m */,
A45E0B2E1616BA9E00E23C6D /* AFURLConnectionOperation.h */,
A45E0B2F1616BA9E00E23C6D /* AFURLConnectionOperation.m */,
A45E0B301616BA9E00E23C6D /* AFXMLRequestOperation.h */,
A45E0B311616BA9E00E23C6D /* AFXMLRequestOperation.m */,
A45E0B321616BA9E00E23C6D /* UIImageView+AFNetworking.h */,
A45E0B331616BA9E00E23C6D /* UIImageView+AFNetworking.m */,
);
name = AFNetworking;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
A45E0AD31616B6F200E23C6D /* JJAFAcceleratedDownloadRequestOperation-Sample */ = {
isa = PBXNativeTarget;
buildConfigurationList = A45E0AF21616B6F200E23C6D /* Build configuration list for PBXNativeTarget "JJAFAcceleratedDownloadRequestOperation-Sample" */;
buildPhases = (
A45E0AD01616B6F200E23C6D /* Sources */,
A45E0AD11616B6F200E23C6D /* Frameworks */,
A45E0AD21616B6F200E23C6D /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = "JJAFAcceleratedDownloadRequestOperation-Sample";
productName = "AFAcceleratedDownloadRequestOperation-Sample";
productReference = A45E0AD41616B6F200E23C6D /* JJAFAcceleratedDownloadRequestOperation-Sample.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
A45E0ACB1616B6F200E23C6D /* Project object */ = {
isa = PBXProject;
attributes = {
CLASSPREFIX = JJ;
LastUpgradeCheck = 0450;
ORGANIZATIONNAME = jnjosh.com;
};
buildConfigurationList = A45E0ACE1616B6F200E23C6D /* Build configuration list for PBXProject "JJAFAcceleratedDownloadRequestOperation-Sample" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
en,
);
mainGroup = A45E0AC91616B6F200E23C6D;
productRefGroup = A45E0AD51616B6F200E23C6D /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
A45E0AD31616B6F200E23C6D /* JJAFAcceleratedDownloadRequestOperation-Sample */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
A45E0AD21616B6F200E23C6D /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A45E0AE31616B6F200E23C6D /* InfoPlist.strings in Resources */,
A45E0AEB1616B6F200E23C6D /* Default.png in Resources */,
A45E0AED1616B6F200E23C6D /* [email protected] in Resources */,
A45E0AEF1616B6F200E23C6D /* [email protected] in Resources */,
A477FE88164635A200407DFE /* JJViewController.xib in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
A45E0AD01616B6F200E23C6D /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A45E0AE51616B6F200E23C6D /* main.m in Sources */,
A45E0AE91616B6F200E23C6D /* JJAppDelegate.m in Sources */,
A45E0B341616BA9E00E23C6D /* AFHTTPClient.m in Sources */,
A45E0B351616BA9E00E23C6D /* AFHTTPRequestOperation.m in Sources */,
A45E0B361616BA9E00E23C6D /* AFImageRequestOperation.m in Sources */,
A45E0B371616BA9E00E23C6D /* AFJSONRequestOperation.m in Sources */,
A45E0B381616BA9E00E23C6D /* AFNetworkActivityIndicatorManager.m in Sources */,
A45E0B391616BA9E00E23C6D /* AFPropertyListRequestOperation.m in Sources */,
A45E0B3A1616BA9E00E23C6D /* AFURLConnectionOperation.m in Sources */,
A45E0B3B1616BA9E00E23C6D /* AFXMLRequestOperation.m in Sources */,
A45E0B3C1616BA9E00E23C6D /* UIImageView+AFNetworking.m in Sources */,
A45E0B3F1617EEDE00E23C6D /* JJViewController.m in Sources */,
A477FE971646DBDF00407DFE /* JJChunkedProgressView.m in Sources */,
A4E79BBF169BCA4E00941CF4 /* JJAFAcceleratedDownloadRequestOperation.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXVariantGroup section */
A45E0AE11616B6F200E23C6D /* InfoPlist.strings */ = {
isa = PBXVariantGroup;
children = (
A45E0AE21616B6F200E23C6D /* en */,
);
name = InfoPlist.strings;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
A45E0AF01616B6F200E23C6D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 6.0;
SDKROOT = iphoneos;
};
name = Debug;
};
A45E0AF11616B6F200E23C6D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 6.0;
OTHER_CFLAGS = "-DNS_BLOCK_ASSERTIONS=1";
SDKROOT = iphoneos;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
A45E0AF31616B6F200E23C6D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "JJAFAcceleratedDownloadRequestOperation-Sample/JJAFAcceleratedDownloadRequestOperation-Sample-Prefix.pch";
INFOPLIST_FILE = "$(SRCROOT)/JJAFAcceleratedDownloadRequestOperation-Sample/JJAFAcceleratedDownloadRequestOperation-Sample-Info.plist";
PRODUCT_NAME = "JJAFAcceleratedDownloadRequestOperation-Sample";
WRAPPER_EXTENSION = app;
};
name = Debug;
};
A45E0AF41616B6F200E23C6D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "JJAFAcceleratedDownloadRequestOperation-Sample/JJAFAcceleratedDownloadRequestOperation-Sample-Prefix.pch";
INFOPLIST_FILE = "$(SRCROOT)/JJAFAcceleratedDownloadRequestOperation-Sample/JJAFAcceleratedDownloadRequestOperation-Sample-Info.plist";
PRODUCT_NAME = "JJAFAcceleratedDownloadRequestOperation-Sample";
WRAPPER_EXTENSION = app;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
A45E0ACE1616B6F200E23C6D /* Build configuration list for PBXProject "JJAFAcceleratedDownloadRequestOperation-Sample" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A45E0AF01616B6F200E23C6D /* Debug */,
A45E0AF11616B6F200E23C6D /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A45E0AF21616B6F200E23C6D /* Build configuration list for PBXNativeTarget "JJAFAcceleratedDownloadRequestOperation-Sample" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A45E0AF31616B6F200E23C6D /* Debug */,
A45E0AF41616B6F200E23C6D /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = A45E0ACB1616B6F200E23C6D /* Project object */;
}
| {
"pile_set_name": "Github"
} |
//
// main.m
// SimpleHTTPClient
//
// Created by Robbie Hanson on 7/5/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **)argv);
}
| {
"pile_set_name": "Github"
} |
StartChar: udieresis
Encoding: 252 252 133
Width: 566
Flags: W
LayerCount: 2
Fore
SplineSet
381 86 m 1,0,1
330.591836735 -9 330.591836735 -9 240 -9 c 0,2,3
122.642857143 -9 122.642857143 -9 95.5 91 c 0,4,5
86 126 86 126 91 177 c 2,6,-1
121 488 l 1,7,-1
230 488 l 1,8,-1
201 190 l 2,9,10
197 143 197 143 215.5 120 c 128,-1,11
234 97 234 97 274.5 97 c 128,-1,12
315 97 315 97 352 136.5 c 128,-1,13
389 176 389 176 397 256 c 2,14,-1
419 488 l 1,15,-1
529 488 l 1,16,-1
484 0 l 1,17,-1
373 0 l 1,18,-1
381 86 l 1,0,1
205.5 632.5 m 128,-1,20
189 651 189 651 191.5 680.5 c 128,-1,21
194 710 194 710 214 729.5 c 128,-1,22
234 749 234 749 263 749 c 256,23,24
292 749 292 749 308.5 729.5 c 128,-1,25
325 710 325 710 323 680 c 1,26,27
319 651 319 651 299 632.5 c 128,-1,28
279 614 279 614 250.5 614 c 128,-1,19
222 614 222 614 205.5 632.5 c 128,-1,20
369 681 m 0,29,30
371 710 371 710 391.5 730 c 128,-1,31
412 750 412 750 440.5 750 c 128,-1,32
469 750 469 750 485 730 c 128,-1,33
501 710 501 710 498.5 681 c 128,-1,34
496 652 496 652 476 633.5 c 128,-1,35
456 615 456 615 427.5 615 c 128,-1,36
399 615 399 615 382.5 633.5 c 128,-1,37
366 652 366 652 369 681 c 0,29,30
EndSplineSet
EndChar
| {
"pile_set_name": "Github"
} |
/*
* evm.c
*
* Board functions for TI814x EVM
*
* Copyright (C) 2011, Texas Instruments, Incorporated - http://www.ti.com/
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <common.h>
#include <cpsw.h>
#include <errno.h>
#include <spl.h>
#include <asm/arch/cpu.h>
#include <asm/arch/hardware.h>
#include <asm/arch/omap.h>
#include <asm/arch/ddr_defs.h>
#include <asm/arch/clock.h>
#include <asm/arch/gpio.h>
#include <asm/arch/mmc_host_def.h>
#include <asm/arch/sys_proto.h>
#include <asm/io.h>
#include <asm/emif.h>
#include <asm/gpio.h>
#include "evm.h"
DECLARE_GLOBAL_DATA_PTR;
static struct ctrl_dev *cdev = (struct ctrl_dev *)CTRL_DEVICE_BASE;
/* UART Defines */
#ifdef CONFIG_SPL_BUILD
static const struct cmd_control evm_ddr2_cctrl_data = {
.cmd0csratio = 0x80,
.cmd0iclkout = 0x00,
.cmd1csratio = 0x80,
.cmd1iclkout = 0x00,
.cmd2csratio = 0x80,
.cmd2iclkout = 0x00,
};
static const struct emif_regs evm_ddr2_emif0_regs = {
.sdram_config = 0x40801ab2,
.ref_ctrl = 0x10000c30,
.sdram_tim1 = 0x0aaaf552,
.sdram_tim2 = 0x043631d2,
.sdram_tim3 = 0x00000327,
.emif_ddr_phy_ctlr_1 = 0x00000007
};
static const struct emif_regs evm_ddr2_emif1_regs = {
.sdram_config = 0x40801ab2,
.ref_ctrl = 0x10000c30,
.sdram_tim1 = 0x0aaaf552,
.sdram_tim2 = 0x043631d2,
.sdram_tim3 = 0x00000327,
.emif_ddr_phy_ctlr_1 = 0x00000007
};
const struct dmm_lisa_map_regs evm_lisa_map_regs = {
.dmm_lisa_map_0 = 0x00000000,
.dmm_lisa_map_1 = 0x00000000,
.dmm_lisa_map_2 = 0x806c0300,
.dmm_lisa_map_3 = 0x806c0300,
};
static const struct ddr_data evm_ddr2_data = {
.datardsratio0 = ((0x35<<10) | (0x35<<0)),
.datawdsratio0 = ((0x20<<10) | (0x20<<0)),
.datawiratio0 = ((0<<10) | (0<<0)),
.datagiratio0 = ((0<<10) | (0<<0)),
.datafwsratio0 = ((0x90<<10) | (0x90<<0)),
.datawrsratio0 = ((0x50<<10) | (0x50<<0)),
};
void set_uart_mux_conf(void)
{
/* Set UART pins */
enable_uart0_pin_mux();
}
void set_mux_conf_regs(void)
{
/* Set MMC pins */
enable_mmc1_pin_mux();
/* Set Ethernet pins */
enable_enet_pin_mux();
}
void sdram_init(void)
{
config_dmm(&evm_lisa_map_regs);
config_ddr(0, NULL, &evm_ddr2_data, &evm_ddr2_cctrl_data,
&evm_ddr2_emif0_regs, 0);
config_ddr(0, NULL, &evm_ddr2_data, &evm_ddr2_cctrl_data,
&evm_ddr2_emif1_regs, 1);
}
#endif
/*
* Basic board specific setup. Pinmux has been handled already.
*/
int board_init(void)
{
gd->bd->bi_boot_params = CONFIG_SYS_SDRAM_BASE + 0x100;
return 0;
}
#if defined(CONFIG_MMC)
int board_mmc_init(bd_t *bis)
{
omap_mmc_init(1, 0, 0, -1, -1);
return 0;
}
#endif
#ifdef CONFIG_DRIVER_TI_CPSW
static void cpsw_control(int enabled)
{
/* VTP can be added here */
return;
}
static struct cpsw_slave_data cpsw_slaves[] = {
{
.slave_reg_ofs = 0x50,
.sliver_reg_ofs = 0x700,
.phy_addr = 1,
},
{
.slave_reg_ofs = 0x90,
.sliver_reg_ofs = 0x740,
.phy_addr = 0,
},
};
static struct cpsw_platform_data cpsw_data = {
.mdio_base = CPSW_MDIO_BASE,
.cpsw_base = CPSW_BASE,
.mdio_div = 0xff,
.channels = 8,
.cpdma_reg_ofs = 0x100,
.slaves = 1,
.slave_data = cpsw_slaves,
.ale_reg_ofs = 0x600,
.ale_entries = 1024,
.host_port_reg_ofs = 0x28,
.hw_stats_reg_ofs = 0x400,
.bd_ram_ofs = 0x2000,
.mac_control = (1 << 5),
.control = cpsw_control,
.host_port_num = 0,
.version = CPSW_CTRL_VERSION_1,
};
#endif
int board_eth_init(bd_t *bis)
{
uint8_t mac_addr[6];
uint32_t mac_hi, mac_lo;
if (!eth_getenv_enetaddr("ethaddr", mac_addr)) {
printf("<ethaddr> not set. Reading from E-fuse\n");
/* try reading mac address from efuse */
mac_lo = readl(&cdev->macid0l);
mac_hi = readl(&cdev->macid0h);
mac_addr[0] = mac_hi & 0xFF;
mac_addr[1] = (mac_hi & 0xFF00) >> 8;
mac_addr[2] = (mac_hi & 0xFF0000) >> 16;
mac_addr[3] = (mac_hi & 0xFF000000) >> 24;
mac_addr[4] = mac_lo & 0xFF;
mac_addr[5] = (mac_lo & 0xFF00) >> 8;
if (is_valid_ethaddr(mac_addr))
eth_setenv_enetaddr("ethaddr", mac_addr);
else
printf("Unable to read MAC address. Set <ethaddr>\n");
}
return cpsw_register(&cpsw_data);
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\time_type_switch2.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project> | {
"pile_set_name": "Github"
} |
import magnolia._, examples._
object Gen {
Eq.generic[adt.Alphabet]
Eq.generic[adt.Alphabet]
Eq.generic[adt.Alphabet]
Eq.generic[adt.Alphabet]
Eq.generic[adt.Alphabet]
Eq.generic[adt.Alphabet]
Eq.generic[adt.Alphabet]
Eq.generic[adt.Alphabet]
Eq.generic[adt.Alphabet]
Eq.generic[adt.Alphabet]
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!--
Auto-generated mapping file from
the hibernate.org cfg2hbm engine
-->
<class name="it.eng.spagobi.commons.metadata.SbiEventRole" table="SBI_EVENTS_ROLES">
<composite-id name="id" class="it.eng.spagobi.commons.metadata.SbiEventRoleId">
<key-many-to-one name="role" class="it.eng.spagobi.commons.metadata.SbiExtRoles">
<column name="ROLE_ID" />
</key-many-to-one>
<key-many-to-one name="event" class="it.eng.spagobi.events.metadata.SbiEventsLog">
<column name="EVENT_ID" />
</key-many-to-one>
</composite-id>
</class>
</hibernate-mapping>
| {
"pile_set_name": "Github"
} |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Review\Test\Constraint;
use Magento\Review\Test\Fixture\Review;
use Magento\Review\Test\Page\Adminhtml\ReviewIndex;
use Magento\Mtf\Constraint\AbstractConstraint;
/**
* Class AssertProductReviewMassActionSuccessDeleteMessage
* Assert success message appears after deletion via mass actions
*/
class AssertProductReviewMassActionSuccessDeleteMessage extends AbstractConstraint
{
/* tags */
const SEVERITY = 'high';
/* end tags */
/**
* Message that appears after deletion via mass actions
*/
const SUCCESS_DELETE_MESSAGE = 'A total of %d record(s) have been deleted.';
/**
* Assert that success message is displayed after deletion via mass actions
*
* @param Review|Review[] $review
* @param ReviewIndex $reviewIndex
* @return void
*/
public function processAssert(Review $review, ReviewIndex $reviewIndex)
{
$reviews = is_array($review) ? $review : [$review];
$deleteMessage = sprintf(self::SUCCESS_DELETE_MESSAGE, count($reviews));
\PHPUnit\Framework\Assert::assertEquals(
$deleteMessage,
$reviewIndex->getMessagesBlock()->getSuccessMessage(),
'Wrong success message is displayed.'
);
}
/**
* Text success save message is displayed
*
* @return string
*/
public function toString()
{
return 'Review success message appears after deletion via mass actions is present.';
}
}
| {
"pile_set_name": "Github"
} |
corePoolSize=10
maxPoolSize=20
idealTime=5
blockingQueueCap=100 | {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using ModestTree;
namespace Zenject
{
[NoReflectionBaking]
public class GetterProvider<TObj, TResult> : IProvider
{
readonly DiContainer _container;
readonly object _identifier;
readonly Func<TObj, TResult> _method;
readonly bool _matchAll;
readonly InjectSources _sourceType;
public GetterProvider(
object identifier, Func<TObj, TResult> method,
DiContainer container, InjectSources sourceType, bool matchAll)
{
_container = container;
_identifier = identifier;
_method = method;
_matchAll = matchAll;
_sourceType = sourceType;
}
public bool IsCached
{
get { return false; }
}
public bool TypeVariesBasedOnMemberType
{
get { return false; }
}
public Type GetInstanceType(InjectContext context)
{
return typeof(TResult);
}
InjectContext GetSubContext(InjectContext parent)
{
var subContext = parent.CreateSubContext(
typeof(TObj), _identifier);
subContext.Optional = false;
subContext.SourceType = _sourceType;
return subContext;
}
public void GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args, out Action injectAction, List<object> buffer)
{
Assert.IsEmpty(args);
Assert.IsNotNull(context);
Assert.That(typeof(TResult).DerivesFromOrEqual(context.MemberType));
injectAction = null;
if (_container.IsValidating)
{
// All we can do is validate that the getter object can be resolved
if (_matchAll)
{
_container.ResolveAll(GetSubContext(context));
}
else
{
_container.Resolve(GetSubContext(context));
}
buffer.Add(new ValidationMarker(typeof(TResult)));
return;
}
if (_matchAll)
{
Assert.That(buffer.Count == 0);
_container.ResolveAll(GetSubContext(context), buffer);
for (int i = 0; i < buffer.Count; i++)
{
buffer[i] = _method((TObj)buffer[i]);
}
}
else
{
buffer.Add(_method(
(TObj)_container.Resolve(GetSubContext(context))));
}
}
}
}
| {
"pile_set_name": "Github"
} |
import { ActionReducer } from '@ngrx/store';
import { NewsInitialState, NewsStateInterface, NewsStateKeys } from './news-state';
import { NewsActions } from './news-actions';
import { PayloadAction } from '../../../../shared/core/state/api-state';
const initialState: NewsStateInterface = new NewsInitialState() as NewsStateInterface;
export const newsReducer: ActionReducer<NewsStateInterface> =
(state: NewsStateInterface = initialState, {payload, type}: PayloadAction) => {
switch (type) {
case NewsActions.FETCH_FULFILLED:
return state.set(NewsStateKeys.Data, payload);
case NewsActions.FETCH_LOADER:
return state.set(NewsStateKeys.Loader, payload);
case NewsActions.FETCH_ERROR:
return state.set(NewsStateKeys.Error, payload);
default:
return state;
}
};
| {
"pile_set_name": "Github"
} |
{
"parent": "block/fence_gate_open",
"textures": {
"particle": "forestry:blocks/wood/planks.acacia",
"texture": "forestry:blocks/wood/planks.acacia"
}
} | {
"pile_set_name": "Github"
} |
import {
IAnimatable, Animation, Animatable, Scalar,
Color3, Tags, Scene, Vector2, Vector3, Vector4,
Mesh, IAnimationKey
} from 'babylonjs';
import * as Raphael from 'raphael';
import Editor, {
Tools,
UndoRedo,
SceneManager,
IStringDictionary,
EditorPlugin,
Layout,
Toolbar,
Dialog,
Window
} from 'babylonjs-editor';
import PropertyBrowser from './property-browser';
import Helpers from './helpers';
export interface DragData {
point: RaphaelElement;
line: RaphaelPath;
keyIndex: number;
maxFrame: number;
properties: string[];
property: string;
valueInterval: number;
middle: number;
}
export default class AnimationEditor extends EditorPlugin {
// Public members
public layout: Layout = null;
public toolbar: Toolbar = null;
public editToolbar: Toolbar = null;
public frameInput: JQuery = null;
public valueInput: JQuery = null;
public paper: RaphaelPaper = null;
public background: RaphaelElement = null;
public middleLine: RaphaelElement = null;
public noDataText: RaphaelElement = null;
public valueText: RaphaelElement = null;
public lines: RaphaelPath[] = [];
public points: RaphaelElement[] = [];
public timeline: RaphaelElement = null;
public timelineLines: RaphaelElement[] = [];
public timelineTexts: RaphaelElement[] = [];
public cursorRect: RaphaelElement = null;
public cursorLine: RaphaelElement = null;
public animatable: IAnimatable = null;
public animation: Animation = null;
public animationManager: Animatable = null;
public key: IAnimationKey = null;
public data: DragData = null;
public currentFrame: number = 0;
// Protected members
protected addingKeys: boolean = false;
protected removingKeys: boolean = false;
protected isPlaying: boolean = false;
protected forcedObject: IAnimatable;
protected mouseMoveHandler: (ev: MouseEvent) => void;
protected onObjectSelected = (node) => node && this.objectSelected(node);
protected onKeyDown: (ev: KeyboardEvent) => void = null;
protected onKeyUp: (ev: KeyboardEvent) => void = null;
// Private members
private _positionHelperMesh: Mesh = null;
private _positionHelperTimeout: number = -1;
private _xLocked: boolean = false;
private _viewBox: Vector4 = new Vector4(0, 0, 0, 0); // width height x y
private _viewScale: number = 1.0;
// Static members
public static PaperOffset: number = 30;
public static Colors: Color3[] = [
new Color3(255, 0, 0),
new Color3(0, 255, 0),
new Color3(0, 0, 255),
new Color3(0, 0, 0)
];
private static _Properties: IStringDictionary<string[]> = {
'number': [''],
'Number': [''],
'Vector2': ['x', 'y'],
'Vector3': ['x', 'y', 'z'],
'Vector4': ['x', 'y', 'z', 'w'],
'Quaternion': ['x', 'y', 'z', 'w'],
'Color3': ['r', 'g', 'b'],
'Color4': ['r', 'g', 'b', 'a']
};
/**
* Constructor
* @param name: the name of the plugin
*/
constructor(public editor: Editor, forcedObject: IAnimatable) {
super('Animation Editor');
// Misc.
this.forcedObject = forcedObject;
}
/**
* Creates the plugin
*/
public async create(): Promise<void> {
// Create layout
this.layout = new Layout('AnimationEditorLayout');
this.layout.panels = [
{ type: 'top', content: '<div id="ANIMATION-EDITOR-TOOLBAR" style="width: 100%; height: 100%;"></div>', size: AnimationEditor.PaperOffset, resizable: false },
{ type: 'preview', content: '<div id="ANIMATION-EDITOR-TOOLBAR-EDIT" style="width: 100%; height: 100%;"></div>', size: AnimationEditor.PaperOffset, resizable: false },
{ type: 'main', content: '<div id="ANIMATION-EDITOR-PAPER" style="width: 100%; height: 100%; overflow: hidden;"></div>', resizable: false }
]
this.layout.build('AnimationEditor');
// Create toolbar
this.toolbar = new Toolbar('AnimationEditorToolbar');
this.toolbar.items = [
{ type: 'button', id: 'play', text: 'Play', img: 'icon-play-game', checked: false },
{ type: 'break' },
{ type: 'button', id: 'add', text: 'Add', img: 'icon-add', checked: false },
{ type: 'button', id: 'remove-animation', text: 'Remove Animation', img: 'icon-error' },
{ type: 'break' },
{ type: 'menu', id: 'animations', text: 'Animations', img: 'icon-animated-mesh', items: [] },
{ type: 'break' },
{ type: 'menu', id: 'tools', text: 'Tools', img: 'icon-edit', items: [
{ type: 'button', id: 'tangents', img: 'icon-graph', text: 'Create Tangents...' }
] }
];
this.toolbar.right = 'No object selected';
this.toolbar.onClick = (id) => this.onToolbarClick(id);
this.toolbar.helpUrl = 'http://doc.babylonjs.com/resources/adding_animations';
this.toolbar.build('ANIMATION-EDITOR-TOOLBAR');
// Create edit toolbar
this.editToolbar = new Toolbar('AnimationEditorToolbarEdit');
this.editToolbar.items = [
{ type: 'button', id: 'add-key', text: 'Add Keys', img: 'icon-add', checked: false },
{ type: 'button', id: 'remove-key', text: 'Remove Keys', img: 'icon-error', checked: false },
{ type: 'break' },
{ type: 'button', id: 'add-key-current', text: 'Add Current Key', img: 'icon-add' }
];
this.editToolbar.right = `
<div style="padding: 3px 10px;">
Value: <input size="10" id="ANIMATION-EDITOR-VALUE" style="height: 20px; padding: 3px; border-radius: 2px; border: 1px solid silver;" value="0" />
Frame: <input size="10" id="ANIMATION-EDITOR-FRAME" style="height: 20px; padding: 3px; border-radius: 2px; border: 1px solid silver;" value="0" />
</div>`;
this.editToolbar.onClick = (id) => this.onEditorToolbarClick(id);
this.editToolbar.build('ANIMATION-EDITOR-TOOLBAR-EDIT');
// Create paper
this.paper = Raphael($('#ANIMATION-EDITOR-PAPER')[0], 0, 0);
this.paper.canvas.addEventListener('focus', () => {
if (this.animation)
this.editor.inspector.setObject(this.animation);
});
document.addEventListener('keydown', this.onKeyDown = (ev: KeyboardEvent) => {
this._xLocked = ev.key === 'x';
});
document.addEventListener('keyup', this.onKeyUp = (ev: KeyboardEvent) => {
if (ev.key === 'x')
this._xLocked = false;
})
this.paper.canvas.addEventListener('wheel', (ev: WheelEvent) => {
const delta = ev.deltaY;
if (delta < 0) {
this._viewBox.x *= 0.95;
this._viewBox.y *= 0.95;
} else {
this._viewBox.x *= 1.05;
this._viewBox.y *= 1.05;
}
this._viewScale = this.paper.width / this._viewBox.x;
if (this._viewScale < 1) {
this._viewScale = 1;
this._viewBox.set(this.paper.width, this.paper.height, 0, 0);
this.paper.setViewBox(0, 0, this.paper.width, this.paper.height, true);
return;
}
const moveX = (ev.offsetX - (ev.offsetX * this._viewScale));
const moveY = (ev.offsetY - (ev.offsetY * this._viewScale));
this._viewBox.z = 0 - moveX / this._viewScale;
this._viewBox.w = 0 - moveY / this._viewScale;
this.paper.setViewBox(this._viewBox.z, this._viewBox.w, this._viewBox.x, this._viewBox.y, true);
// Update points
this.points.forEach(p => p.transform(`S${1.0 / this._viewScale}`));
});
// Create background
this.background = this.paper.rect(0, 0, 0, 0);
this.background.attr('fill', '#ddd');
this.background.attr('stroke', '#ddd');
// Create middle line
this.middleLine = this.paper.rect(0, 0, 0, 1);
this.middleLine.attr('fill', '#eee');
this.middleLine.attr('stroke', '#eee');
// No data text
this.noDataText = this.paper.text(0, 0, 'No Animation Selected');
this.noDataText.node.style.pointerEvents = 'none';
this.noDataText.node.style.userSelect = 'none';
this.noDataText.attr('font-size', 64);
// Value text
this.valueText = this.paper.text(0, 0, '0.0');
this.valueText.node.style.pointerEvents = 'none';
this.valueText.node.style.userSelect = 'none';
this.valueText.attr('font-size', 10);
this.valueText.hide();
// Events / inputs
const frame = $('#ANIMATION-EDITOR-FRAME');
this.frameInput = (<any> frame).w2field('float', { autoFormat: true });
this.frameInput[0].addEventListener('change', (ev) => {
if (this.key) {
const fromFrame = this.key.frame;
const toFrame = parseFloat(<string> this.frameInput.val());
this.key.frame = toFrame;
this.updateGraph(this.animation);
// Undo / redo
const animation = this.animation;
const key = this.key;
UndoRedo.Push({ // Frame
scope: this.divElement.id,
object: key,
property: 'frame',
from: fromFrame,
to: toFrame,
fn: (type) => {
this.updateGraph(animation);
this.frameInput.val(type === 'from' ? fromFrame : toFrame);
}
});
}
});
const value = $('#ANIMATION-EDITOR-VALUE');
this.valueInput = (<any> value).w2field('float', { autoFormat: true });
this.valueInput[0].addEventListener('change', (ev) => {
if (this.key && this.data) {
const fromValue = this.data.property === '' ? this.key.value : this.key.value[this.data.property];
const toValue = parseFloat(<string> this.valueInput.val());
this.data.property === '' ? (this.key.value = toValue) : (this.key.value[this.data.property] = toValue);
this.updateGraph(this.animation);
// Undo / redo
UndoRedo.Push({ // Value
scope: this.divElement.id,
object: this.key,
property: this.data.property === '' ? 'value' : `value.${this.data.property}`,
from: fromValue,
to: toValue,
fn: (type) => {
this.updateGraph(this.animation);
this.frameInput.val(type === 'from' ? fromValue : toValue);
}
});
}
});
// On select object
this.objectSelected(this.forcedObject || this.editor.core.currentSelectedObject);
if (!this.forcedObject)
this.editor.core.onSelectObject.add(this.onObjectSelected);
}
/**
* Closes the plugin
*/
public async close(): Promise<void> {
super.close();
this.editor.core.onSelectObject.removeCallback(this.onObjectSelected);
document.removeEventListener('keydown', this.onKeyDown);
document.removeEventListener('keyup', this.onKeyUp);
this.paper.remove();
this.layout.element.destroy();
this.toolbar.element.destroy();
this.editToolbar.element.destroy();
Helpers.DisposePositionLineMesh();
UndoRedo.ClearScope(this.divElement.id);
await super.close();
}
/**
* On the user shows the plugin
*/
public onShow (forcedObject: IAnimatable): void {
// Forced object?
this.forcedObject = forcedObject;
this.editor.core.onSelectObject.removeCallback(this.onObjectSelected);
if (!forcedObject)
this.editor.core.onSelectObject.add(this.onObjectSelected);
else
this.objectSelected(forcedObject);
// Resize
this.onResize();
// Helpers
if (this._positionHelperMesh)
this._positionHelperMesh.setEnabled(true);
}
/**
* Called on the user hides the extension (by changing tab, etc.)
*/
public onHide (): void {
// Helpers
if (this._positionHelperMesh)
this._positionHelperMesh.setEnabled(false);
}
/**
* Called on the window, layout etc. is resized.
*/
public onResize(): void {
this.layout.element.resize();
// TODO: find why setTimeout needed
setTimeout(() => {
if (this.closed)
return;
const size = this.layout.getPanelSize('main');
this.paper.setSize(size.width, size.height);
this.background.attr('width', size.width);
this.background.attr('height', size.height);
this.middleLine.attr('width', size.width);
this.middleLine.attr('y', size.height / 2);
this.noDataText.attr('y', size.height / 2 - this.noDataText.attr('height') / 2);
this.noDataText.attr('x', size.width / 2 - this.noDataText.attr('width') / 2);
this.updateGraph(this.animation);
}, 250);
}
/**
* On the user clicked on the toolbar
* @param id the id of the element
*/
protected async onToolbarClick(id: string): Promise<void> {
const split = id.split(':');
if (split.length > 1 && split[0] === 'animations') {
this.onChangeAnimation(split[1]);
return;
}
// Switch id
switch (id) {
case 'play': this.playAnimation(); break;
case 'add': this.addAnimation(); break;
case 'remove-animation':
if (this.animation) {
const index = this.animatable.animations.indexOf(this.animation);
const animation = this.animation;
const animatable = this.animatable;
UndoRedo.Push({
scope: this.divElement.id,
fn: (type) => {
if (type === 'from')
this.animatable.animations.splice(index, 0, animation);
else
this.animatable.animations.splice(index, 1);
this.objectSelected(animatable);
}
});
this.animatable.animations.splice(index, 1);
this.objectSelected(this.animatable);
}
break;
case 'tools:tangents':
if (!this.animation)
return;
if (this.animation.dataType !== Animation.ANIMATIONTYPE_VECTOR3)
return Window.CreateAlert(`Tangents can be created only on animated 3D vectors.`, 'Informations');
const weight = parseFloat(await Dialog.CreateWithTextInput('Tangents Weight?')) || 0;
Helpers.ComputeTangents(this.animation, weight);
this.updateGraph(this.animation);
break;
default: break;
}
}
/**
* On the user clicked on the edit toolbar
* @param id the id of the element
*/
protected onEditorToolbarClick (id: string): void {
// Switch id
switch (id) {
case 'add-key':
case 'remove-key':
const active = this.editToolbar.isChecked(id, true);
this.editToolbar.setChecked('add-key', false);
this.editToolbar.setChecked('remove-key', false);
this.editToolbar.setChecked(id, active);
this.addingKeys = active && id === 'add-key';
this.removingKeys = active && id === 'remove-key';
break;
case 'add-key-current':
this.addCurrentValueToCurrentFrame();
break;
default: break;
}
}
/**
* Adds an animation
*/
protected addAnimation (): void {
if (!this.animatable)
return;
const browser = new PropertyBrowser(this.animatable);
browser.onSelect = (id) => {
// Property infos
const infos = browser.getPropertyInfos(this.animatable, id);
let defaultValue = infos.defaultValue;
// Get effective property
const split = id.split('.');
let effectiveValue = <any> this.animatable;
split.forEach(s => effectiveValue = effectiveValue[s]);
const ctor = Tools.GetConstructorName(effectiveValue);
switch (ctor) {
case 'Number': defaultValue = effectiveValue; break;
case 'Vector2':
case 'Vector3':
case 'Vector4':
case 'Color3':
case 'Color4':
case 'Quaternion':
defaultValue = effectiveValue.clone();
break;
default:
break;
}
// Create animation
const anim = new Animation(id, id, 60, infos.type, Animation.ANIMATIONLOOPMODE_CYCLE, false);
anim.setKeys([
{ frame: 0, value: defaultValue },
{ frame: 60, value: defaultValue }
]);
const length = this.animatable.animations.push(anim);
// Undo redo
UndoRedo.Push({
scope: this.divElement.id,
fn: (type) => {
if (type === 'from')
this.animatable.animations.splice(length - 1, 1);
else
this.animatable.animations.splice(length - 1, 0, anim);
this.objectSelected(this.animatable);
}
});
this.objectSelected(this.animatable);
// Tags
Tags.AddTagsTo(anim, 'added');
};
}
/**
* Plays the animation
*/
protected playAnimation (): void {
if (!this.animatable || !this.animation)
return;
if (this.isPlaying) {
this.cursorRect.stop();
this.cursorRect.attr('x', -this.cursorRect.attr('width') / 2);
this.cursorLine.stop();
this.cursorLine.attr('x', 0);
this.editor.core.scene.stopAnimation(this.animatable);
this.toolbar.element.uncheck('play');
this.isPlaying = false;
return;
}
const keys = this.animation.getKeys();
const min = this.currentFrame || keys[0].frame;
const max = keys[keys.length - 1].frame;
if (min === undefined || max === undefined)
return;
const time = ((max - min) * 1000) / this.animation.framePerSecond;
this.cursorRect.animate({ x: this.paper.width - this.cursorRect.attr('width') / 2 }, time);
this.cursorLine.animate({ x: this.paper.width }, time);
this.editor.core.scene.beginDirectAnimation(this.animatable, [this.animation], min, max, false, 1.0, () => {
this.isPlaying = false;
});
this.toolbar.element.check('play');
this.isPlaying = true;
}
/**
* On select an object
* @param object: the IAnimatable object
*/
protected objectSelected(object: IAnimatable): void {
this.toolbar.element.disable('remove-animation');
// Clean
this.animatable = null;
this.animation = null;
this.frameInput.val('');
this.valueInput.val('');
Helpers.DisposePositionLineMesh();
if (!object)
return;
// Refresh right text
this.toolbar.element.right = `Selected object: "${(object instanceof Scene ? 'Scene' : object['name'])}"`;
this.toolbar.element.render();
// Reset viewbox
this._viewScale = 1;
this._viewBox.set(this.paper.width, this.paper.height, 0, 0);
this.paper.setViewBox(0, 0, this.paper.width, this.paper.height, true);
// Check
if (!object.animations)
return;
// Misc.
this.editor.core.scene.stopAnimation(object);
// Update animations list
const animations = ['None'];
object.animations.forEach(a => {
animations.push(a.name);
});
const menu = <any>this.toolbar.element.get('animations');
menu.items = [];
animations.forEach(a => {
menu.items.push({
id: a,
caption: a,
text: a
});
});
this.toolbar.element.refresh();
// Misc.
this.animatable = object;
if (object.animations.length > 0) {
this.onChangeAnimation(object.animations[0].name);
} else {
this.updateGraph(null);
this.noDataText.show();
}
}
/**
* On the animation selection changed
* @param property: the animation property
*/
protected onChangeAnimation(property: string): void {
// Clean selected elements
this.key = null;
this.data = null;
// Reset viewbox
this._viewScale = 1;
this._viewBox.set(this.paper.width, this.paper.height, 0, 0);
this.paper.setViewBox(0, 0, this.paper.width, this.paper.height, true);
if (!this.animatable)
return;
// Show "no data" text
this.noDataText.show();
// Set up current animation
this.animation = this.animatable.animations.find(a => a.name === property);
// Return if no animation
if (!this.animation) {
this.toolbar.element.disable('remove-animation');
return this.updateGraph(this.animation);
}
// Hide "no data" text and configure toolbar
this.noDataText.hide();
this.toolbar.element.enable('remove-animation');
const keys = this.animation.getKeys();
const maxFrame = keys[keys.length - 1].frame;
if (this.animationManager)
this.animationManager.stop();
this.animationManager = new Animatable(this.editor.core.scene, this.animatable, keys[0].frame, maxFrame, false, 1.0);
this.animationManager.appendAnimations(this.animatable, this.animatable.animations);
this.animationManager.stop();
// Update graph
this.updateGraph(this.animation);
// Helpers
this._positionHelperMesh = Helpers.AddPositionLineMesh(this.editor.core.scene, this.animation);
}
/**
* Updates the graph
* @param anim: the animation reference
*/
protected updateGraph(anim: Animation): void {
// Remove all lines
this.lines.forEach(l => l.remove());
this.points.forEach(p => p.remove());
this.timelineLines.forEach(tl => tl.remove());
this.timelineTexts.forEach(t => t.remove());
this.lines = [];
this.points = [];
this.timelineLines = [];
this.timelineTexts = [];
if (this.cursorRect)
this.cursorRect.remove();
if (this.cursorLine)
this.cursorLine.remove();
if (this.timeline)
this.timeline.remove();
// Misc
this.currentFrame = 0;
// Return if no anim
if (!anim) {
// Reset viewbox
this._viewScale = 1;
this._viewBox.set(this.paper.width, this.paper.height, 0, 0);
this.paper.setViewBox(0, 0, this.paper.width, this.paper.height, true);
return;
}
// Keys
const keys = anim.getKeys();
if (keys.length === 0)
return;
// Values
const properties = AnimationEditor._Properties[Tools.GetConstructorName(keys[0].value)];
const maxFrame = keys[keys.length - 1].frame;
const middle = this.paper.height / 2;
let maxValue = 0;
let minValue = 0;
// Max value
properties.forEach((p, propertyIndex) => {
keys.forEach(k => {
if (p === '') {
if (k.value > maxValue)
maxValue = k.value;
else if (k.value < minValue)
minValue = k.value;
return;
}
if (k.value[p] > maxValue)
maxValue = k.value[p];
else if (k.value[p] < minValue)
minValue = k.value[p];
});
});
const valueInterval = Math.max(Math.abs(maxValue), Math.abs(minValue)) || 1;
// Add timeline lines
let linesCount = 100;
for (let i = 0; i < linesCount; i++) {
// Line
const x = (this.paper.width / linesCount) * i;
const line = this.paper.rect(x, 0, 1, 20);
line.attr('opacity', 0.05);
if (i % 5 === 0 && i > 0) {
line.attr('opacity', 1);
// Text
const text = this.paper.text(x, 30, (((x * maxFrame) / this.paper.width)).toFixed(2));
text.node.style.pointerEvents = 'none';
text.node.style.userSelect = 'none';
text.attr('opacity', 0.4);
this.timelineTexts.push(text);
}
// Add high lines
const highLine = this.paper.rect(x, 20, 1, this.paper.height - 20);
highLine.attr('opacity', 0.05);
this.timelineLines.push(line);
this.timelineLines.push(highLine);
}
// Add value lines
linesCount = 50;
let currentValue = maxValue * 2;
for (let i = 0; i < linesCount; i++) {
// Line
const y = (this.paper.height / linesCount) * i;
const line = this.paper.rect(0, y, 20, 1);
line.attr('opacity', 0.05);
if (i % 5 === 0) {
if (i > 0) {
const text = this.paper.text(30, y, currentValue.toFixed(2));
text.attr('opacity', 0.4);
text.node.style.pointerEvents = 'none';
text.node.style.userSelect = 'none';
this.timelineTexts.push(text);
}
currentValue -= (maxValue / (linesCount / 10)) * 2;
}
this.timelineLines.push(line);
}
// Add timeline clickable rect
this.timeline = this.paper.rect(0, 0, this.paper.width, 20);
this.timeline.attr('fill', Raphael.rgb(0, 0, 0));
this.timeline.attr('opacity', 0.2);
this.onClickTimeline(maxFrame);
// Add cursor
this.cursorLine = this.paper.rect(0, 0, 1, this.paper.height);
this.cursorLine.attr('opacity', 0.5);
this.cursorRect = this.paper.rect(-20, 0, 40, 20);
this.cursorRect.attr('fill', Raphael.rgb(0, 0, 0));
this.cursorRect.attr('opacity', 0.5);
this.onMoveCursor(maxFrame);
// Manage paper move
this.onPaperMove(properties, maxFrame, valueInterval, keys);
// Add all lines
properties.forEach((p, propertyIndex) => {
const color = AnimationEditor.Colors[propertyIndex];
const path: string[] = [];
// Build line and add it
const line = this.paper.path();
// For each key
keys.forEach((k, keyIndex) => {
const value = (p === '') ? k.value : k.value[p];
const position = Helpers.ProjectToGraph(k.frame, maxFrame, this.paper.width, middle, value, valueInterval);
if (isNaN(position.x)) position.x = 0;
if (isNaN(position.y)) position.y = 0;
if (keyIndex === 0) position.x = 6;
if (keyIndex === keys.length - 1) position.x -= 6;
const point = this.paper.circle(position.x, position.y, 6);
point.attr('fill', Raphael.rgb(color.r, color.g, color.b));
point.transform(`S${1.0 / this._viewScale}`);
point.attr('opacity', 0.3);
this.points.push(point);
this.onMovePoint({
point: point,
keyIndex: keyIndex,
line: line,
property: p,
properties: properties,
maxFrame: maxFrame,
valueInterval: valueInterval,
middle: middle
});
// Tangents?
const previousKey = keys[keyIndex - 1];
if (previousKey && previousKey.outTangent && k.inTangent) {
const frameDiff = k.frame - previousKey.frame;
const v1 = Vector3.Hermite(previousKey.value, Helpers.ScaleValue(previousKey.outTangent, frameDiff), k.value, Helpers.ScaleValue(k.inTangent, frameDiff), 0.33);
const v2 = Vector3.Hermite(previousKey.value, Helpers.ScaleValue(previousKey.outTangent, frameDiff), k.value, Helpers.ScaleValue(k.inTangent, frameDiff), 0.66);
const p1 = Helpers.ProjectToGraph(previousKey.frame + frameDiff * 0.33, maxFrame, this.paper.width, middle, v1[p], valueInterval);
const p2 = Helpers.ProjectToGraph(previousKey.frame + frameDiff * 0.66, maxFrame, this.paper.width, middle, v2[p], valueInterval);
path.push.apply(path, ['R', p1.x.toString(), p1.y.toString(), p2.x.toString(), p2.y.toString()]);
}
// Begin path?
if (keyIndex === 0)
path.push("M");
// End point
path.push(position.x.toString());
path.push(position.y.toString());
});
// Set line
line.attr('stroke', Raphael.rgb(color.r, color.g, color.b));
line.attr('path', path);
this.lines.push(line);
});
// Helpers
this._positionHelperMesh = Helpers.AddPositionLineMesh(this.editor.core.scene, this.animation);
}
/**
* Adds the current value to the current frame
*/
protected addCurrentValueToCurrentFrame (): void {
// Keys
const keys = this.animation.getKeys();
// Key
let keyIndex = 0;
let key = {
frame: this.currentFrame,
value: null
};
// Add key
for (let i = 0; i < keys.length; i++) {
if (keys[i].frame > this.currentFrame) {
keyIndex = i;
keys.splice(i, 0, key);
break;
}
}
// Clone effective value
const effectiveValue = Helpers.GetEffectiveProperty<any>(this.animatable, this.animation);
const ctor = Tools.GetConstructorName(effectiveValue);
switch (ctor) {
case 'Number': key.value = effectiveValue; break;
case 'Vector2':
case 'Vector3':
case 'Vector4':
case 'Color3':
case 'Color4':
case 'Quaternion':
key.value = effectiveValue.clone();
break;
default: return;
}
// Undo redo
const animation = this.animation;
UndoRedo.Push({
scope: this.divElement.id,
fn: type => {
if (type === 'from')
animation.getKeys().splice(keyIndex, 1);
else
animation.getKeys().splice(keyIndex, 0, key);
this.updateGraph(animation);
}
});
this.updateGraph(this.animation);
}
/**
* On the user moves a key
* @param key: the key to move
*/
protected onMovePoint(data: DragData): void {
let ox = 0;
let oy = 0;
let lx = 0;
let ly = 0;
let fromFrame = 0;
let toFrame = 0;
let fromValue = null;
let toValue = null;
const onStart = (x: number, y: number, ev) => {
if (this.removingKeys) {
const key = this.animation.getKeys()[data.keyIndex];
const animation = this.animation;
UndoRedo.Push({
scope: this.divElement.id,
fn: type => {
if (type === 'from')
animation.getKeys().splice(data.keyIndex, 0, key);
else
animation.getKeys().splice(data.keyIndex, 1);
this.updateGraph(animation);
}
});
this.animation.getKeys().splice(data.keyIndex, 1);
return this.updateGraph(this.animation);
}
data.point.attr('opacity', 1);
this.valueText.show();
// Set key and data as selected
this.key = this.animation.getKeys()[data.keyIndex];
this.data = data;
this.frameInput.val(this.key.frame);
if (data.property === '') {
this.valueInput.val(this.key.value);
fromValue = this.key.value;
}
else {
this.valueInput.val(this.key.value[data.property]);
fromValue = this.key.value[data.property];
}
fromFrame = this.key.frame;
};
const onMove = (dx, dy, x, y, ev) => {
lx = (dx + ox) / this._viewScale;
ly = (dy + oy) / this._viewScale;
data.point.transform(`t${this._xLocked ? 0 : lx},${ly}`);
// Update line path
const path: string[][] = data.line.attr('path');
let key = path[data.keyIndex];
if (key.length === 3) {
// Simple path
key[1] = data.point.attr('cx') + (this._xLocked ? 0 : lx);
key[2] = data.point.attr('cy') + ly;
} else {
// R path
key = path[data.keyIndex * 2];
key[5] = data.point.attr('cx') + (this._xLocked ? 0 : lx);
key[6] = data.point.attr('cy') + ly;
}
data.line.attr('path', path);
// Update current animation key (frame + value)
const frame = Scalar.Clamp(((ev.offsetX + this._viewBox.z * this._viewScale) / this._viewScale * data.maxFrame) / this.paper.width, 0, data.maxFrame - 1);
toValue = 0;
if (ev.offsetY > this.paper.height / 2)
toValue = -(((ev.offsetY + this._viewBox.w * this._viewScale) / this._viewScale - this.paper.height / 2) * data.valueInterval) / (this.paper.height / 2) * 2;
else
toValue = ((this.paper.height / 2 - (ev.offsetY + this._viewBox.w * this._viewScale) / this._viewScale) * data.valueInterval) / (this.paper.height / 2) * 2;
if (!this._xLocked)
this.key.frame = frame;
toFrame = frame;
if (data.property === '')
this.key.value = toValue;
else
this.key.value[data.property] = toValue;
// Update frame input
this.frameInput.val(frame);
this.valueInput.val(data.property === '' ? toValue : this.key.value[data.property]);
// Update value text
this.valueText.attr('x', (ev.offsetX + this._viewBox.z * this._viewScale) / this._viewScale);
this.valueText.attr('y', (ev.offsetY - (20 * this._viewScale) + this._viewBox.w * this._viewScale) / this._viewScale);
this.valueText.attr('text', toValue.toFixed(4));
// Update helper
clearTimeout(this._positionHelperTimeout);
this._positionHelperTimeout = setTimeout(() => {
this._positionHelperMesh = Helpers.AddPositionLineMesh(this.editor.core.scene, this.animation);
}, 5);
};
const onEnd = (ev) => {
data.point.attr('opacity', 0.3);
ox = lx;
oy = ly;
this.valueText.hide();
this.updateGraph(this.animation);
// Undo / redo
const key = this.key;
const animation = this.animation;
if (!this._xLocked) {
UndoRedo.Push({ // Frame
scope: this.divElement.id,
object: key,
property: 'frame',
from: fromFrame,
to: toFrame,
fn: (type) => {
this.updateGraph(animation);
this.frameInput.val(type === 'from' ? fromFrame : toFrame);
}
});
}
UndoRedo.Push({ // Value
scope: this.divElement.id,
object: key,
property: data.property === '' ? 'value' : `value.${data.property}`,
from: fromValue,
to: toValue,
fn: () => {
this.updateGraph(animation);
}
});
// Notify
this.editor.core.onModifiedObject.notifyObservers(this.animatable);
};
data.point.drag(<any>onMove, <any>onStart, <any>onEnd);
}
/**
* On moving cursor
*/
protected onMoveCursor(maxFrame: number): void {
const baseX = this.cursorLine.attr('x');
let ox = 0;
let lx = 0;
const doAnimatables = (animatables: (IAnimatable & { getAnimatables?: () => IAnimatable[] })[], frame: number) => {
animatables.forEach(a => {
if (!a || a === this.animatable)
return;
if (a.animations) {
let animatable = this.editor.core.scene.getAnimatableByTarget(a);
if (!animatable)
animatable = new Animatable(this.editor.core.scene, a, frame, maxFrame, false, 1.0);
animatable.appendAnimations(a, a.animations);
animatable.stop();
animatable.goToFrame(frame);
} else if (a.getAnimatables) {
a.getAnimatables().forEach(a => {
let animatable = this.editor.core.scene.getAnimatableByTarget(a);
if (!animatable)
animatable = new Animatable(this.editor.core.scene, a, frame, maxFrame, false, 1.0);
animatable.appendAnimations(a, a.animations);
animatable.stop();
animatable.goToFrame(frame);
});
}
});
};
const onStart = (x: number, y: number, ev: MouseEvent) => {
this.cursorRect.attr('opacity', 0.1);
};
const onMove = (dx: number, dy: number, x: number, y: number, ev: MouseEvent) => {
lx = dx + ox;
this.cursorRect.transform(`t${lx},0`);
this.cursorLine.transform(`t${lx},0`);
this.currentFrame = Scalar.Clamp(((lx + baseX) * maxFrame) / this.paper.width, 0, maxFrame - 1);
this.animationManager.stop();
this.animationManager.goToFrame(this.currentFrame);
doAnimatables(this.editor.core.scene.meshes, this.currentFrame);
doAnimatables(this.editor.core.scene.meshes.map(m => m.skeleton), this.currentFrame);
doAnimatables(this.editor.core.scene.cameras, this.currentFrame);
doAnimatables(this.editor.core.scene.lights, this.currentFrame);
doAnimatables(<any> this.editor.core.scene.particleSystems, this.currentFrame);
doAnimatables([SceneManager.StandardRenderingPipeline], this.currentFrame);
};
const onEnd = (ev: MouseEvent) => {
this.cursorRect.attr('opacity', 0.5);
ox = lx;
};
this.cursorRect.drag(<any>onMove, <any>onStart, <any>onEnd);
}
/**
* On click on the timeline
*/
protected onClickTimeline(maxFrame: number): void {
this.timeline.mousedown((ev: MouseEvent) => {
if (this.isPlaying)
return;
this.currentFrame = Scalar.Clamp((ev.offsetX * maxFrame) / this.paper.width, 0, maxFrame - 1);
this.animationManager.stop();
this.animationManager.goToFrame(this.currentFrame);
// Update cursor
this.cursorRect.undrag();
this.cursorRect.transform('t0,0');
this.cursorLine.transform('t0,0');
this.cursorRect.attr('x', ev.offsetX - 20);
this.cursorLine.attr('x', ev.offsetX);
this.onMoveCursor(maxFrame);
});
}
/**
* On paper mouse move
*/
protected onPaperMove(properties: string[], maxFrame: number, valueInterval: number, keys: any[]): void {
this.background.unmousemove(this.mouseMoveHandler);
const points: RaphaelElement[] = [];
this.mouseMoveHandler = (ev: MouseEvent) => {
this.lines.forEach((l, index) => {
if (!this.addingKeys) {
points[index].hide();
return;
}
points[index].show();
const length = l.getTotalLength();
const position = l.getPointAtLength((ev.offsetX * length) / this.paper.width);
const offset = length / this.paper.width;
const point = points[index];
point.transform(`t${position.x},${position.y}`);
});
};
properties.forEach((_, index) => {
const color = AnimationEditor.Colors[index];
const circle = this.paper.circle(0, 0, 6);
circle.attr('fill', Raphael.rgb(color.r, color.g, color.b));
circle.click((ev: MouseEvent) => {
const frame = Scalar.Clamp((ev.offsetX * maxFrame) / this.paper.width, 0, maxFrame - 1);
let value = 0;
if (ev.offsetY > this.paper.height / 2)
value = -((ev.offsetY - this.paper.height / 2) * valueInterval) / (this.paper.height / 2) * 2;
else
value = ((this.paper.height / 2 - ev.offsetY) * valueInterval) / (this.paper.height / 2) * 2;
// Key
let keyIndex = 0;
let key = {
frame: frame,
value: null
};
// Add key
for (let i = 0; i < keys.length; i++) {
if (keys[i].frame > frame) {
keyIndex = i;
keys.splice(i, 0, key);
break;
}
}
// Setup key
const lastKey = keys[keyIndex - 1];
switch (properties.length) {
case 1: key.value = value; break;
case 2: key.value = lastKey ? new Vector2().copyFrom(lastKey.value) : new Vector2(value, value + 1); break;
case 3:
switch (properties[0]) {
case 'x': key.value = lastKey ? new Vector3().copyFrom(lastKey.value) : new Vector3(value, value - 1, value + 1); break;
case 'r': key.value = lastKey ? new Color3().copyFrom(lastKey.value) : new Color3(value, value, value); break;
default: debugger; break;
}
break;
default: debugger; break;
}
// Undo redo
const animation = this.animation;
UndoRedo.Push({
scope: this.divElement.id,
fn: type => {
if (type === 'from')
animation.getKeys().splice(keyIndex, 1);
else
animation.getKeys().splice(keyIndex, 0, key);
this.updateGraph(animation);
}
});
this.updateGraph(this.animation);
});
points.push(circle);
this.points.push(circle);
})
this.background.mousemove(this.mouseMoveHandler);
}
}
| {
"pile_set_name": "Github"
} |
# 图标说明
在类别和源的右侧,都有一个图标,用来表示这个类别/源在同步时是否下载图片和下载全文。当你在类别/源的设置对话框中更改了相关设置,图标就会做相应的变化。
如下图所示,一共有四种类型。
<img src="https://github.com/seazon/FeedMe/blob/master/doc/en/imgs/subscription_sync_indicator.png" width="10%" height="10%" />
图标左半边代表是否下载图片,右半边代表是否下载全文。所以四个图标依次代表:
- 1:下载图片,不下载全文
- 2:不下载图片,不下载全文
- 3:下载图片,下载全文
- 4:不下载图片,下载全文
| {
"pile_set_name": "Github"
} |
/*
* Bolo - A stable and beautiful blogging system based in Solo.
* Copyright (c) 2020, https://github.com/adlered
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* preference for admin.
*
* @author <a href="http://vanessa.b3log.org">Liyuan Li</a>
* @author <a href="http://88250.b3log.org">Liang Ding (Solo Author)</a>
* @author <a href="https://github.com/adlered">adlered (Bolo Author)</a>
*/
/* preference 相关操作 */
admin.preference = {
locale: '',
editorMode: '',
/*
* 初始化
*/
init: function () {
$('#tabPreference').tabs()
$.ajax({
url: Label.servePath + '/console/preference/',
type: 'GET',
cache: false,
success: function (result, textStatus) {
$('#tipMsg').text(result.msg)
if (!result.sc) {
$('#loadMsg').text('')
return
}
var preference = result.preference
$.ajax({
url: Label.servePath + '/plugins/kanbanniang/assets/list',
type: 'GET',
async: false,
success: function(res) {
var kanbanniangList = res.msg.split(';');
for (var i = 0; i < kanbanniangList.length; i++) {
$('#kanbanniangSelector').append(
'<option value="' + kanbanniangList[i] + '">' + kanbanniangList[i] + '</option>'
);
}
}
});
if (preference.wafCurrentLimitTimes === "" || preference.wafCurrentLimitTimes === undefined) {
$("#wafCurrentLimitTimes").val("180")
} else {
$("#wafCurrentLimitTimes").val(preference.wafCurrentLimitTimes)
}
if (preference.wafCurrentLimitSecond === "" || preference.wafCurrentLimitSecond === undefined) {
$("#wafCurrentLimitSecond").val("180")
} else {
$("#wafCurrentLimitSecond").val(preference.wafCurrentLimitSecond)
}
if (preference.wafPower === "" || preference.wafPower === undefined) {
$("#wafPower").val("on")
} else {
$("#wafPower").val(preference.wafPower)
}
if (preference.interactive === "" || preference.interactive === undefined) {
$("#interactiveSwitch").val("on")
} else {
$("#interactiveSwitch").val(preference.interactive)
}
if(preference.adminActiveSentToMailbox === "" || preference.adminActiveSentToMailbox === undefined) {
$("#adminActiveSentToMailbox").val("on")
} else {
$("#adminActiveSentToMailbox").val(preference.adminActiveSentToMailbox)
}
$('#spam').val(preference.spam)
$('#kanbanniangSelector').val(preference.kanbanniangSelector)
$('#replyRemind').val(preference.replyRemind)
$('#sourceTC').text(preference.tuChuangConfig)
sltd = $('#sourceTC').text().split('<<>>')[0]
$('#tcS').val(sltd)
$('#hacpaiUser').val(preference.hacpaiUser)
$('#b3logKey').val(preference.b3logKey)
$('#mailBox').val(preference.mailBox)
$('#mailUsername').val(preference.mailUsername)
$('#mailPassword').val(preference.mailPassword)
$('#metaKeywords').val(preference.metaKeywords)
$('#metaDescription').val(preference.metaDescription)
$('#blogTitle').val(preference.blogTitle)
$('#blogSubtitle').val(preference.blogSubtitle)
$('#mostCommentArticleDisplayCount').
val(preference.mostCommentArticleDisplayCount)
$('#mostViewArticleDisplayCount').
val(preference.mostViewArticleDisplayCount)
$('#recentCommentDisplayCount').
val(preference.recentCommentDisplayCount)
$('#mostUsedTagDisplayCount').val(preference.mostUsedTagDisplayCount)
$('#articleListDisplayCount').val(preference.articleListDisplayCount)
$('#articleListPaginationWindowSize').
val(preference.articleListPaginationWindowSize)
$('#localeString').val(preference.localeString)
$('#timeZoneId').val(preference.timeZoneId)
$('#noticeBoard').val(preference.noticeBoard)
$('#footerContent').val(preference.footerContent)
$('#htmlHead').val(preference.htmlHead)
$('#externalRelevantArticlesDisplayCount').
val(preference.externalRelevantArticlesDisplayCount)
$('#relevantArticlesDisplayCount').
val(preference.relevantArticlesDisplayCount)
$('#randomArticlesDisplayCount').
val(preference.randomArticlesDisplayCount)
$('#customVars').val(preference.customVars)
$('#githubPAT').val(preference.githubPAT)
$('#maxArchive').val(preference.maxArchive)
'true' === preference.showCodeBlockLn ? $('#showCodeBlockLn').attr('checked', 'checked') : $('#showCodeBlockLn').removeAttr('checked')
'true' === preference.enableArticleUpdateHint ? $('#enableArticleUpdateHint').attr('checked', 'checked') : $('#enableArticleUpdateHint').removeAttr('checked')
'true' === preference.allowVisitDraftViaPermalink ? $('#allowVisitDraftViaPermalink').attr('checked', 'checked') : $('allowVisitDraftViaPermalink').removeAttr('checked')
'true' === preference.commentable ? $('#commentable').attr('checked', 'checked') : $('commentable').removeAttr('checked')
'true' === preference.syncGitHub ? $('#syncGitHub').attr('checked', 'checked') : $('syncGitHub').removeAttr('checked')
'true' === preference.pullGitHub ? $('#pullGitHub').attr('checked', 'checked') : $('pullGitHub').removeAttr('checked')
$("input:radio[value='" + preference.editorMode + "']").attr('checked','true');
admin.preference.editorMode = preference.editorMode
admin.preference.locale = preference.localeString
// sign
var signs = eval('(' + preference.signs + ')')
for (var j = 1; j < signs.length; j++) {
$('#preferenceSign' + j).val(signs[j].signHTML)
}
$('#articleListDisplay').val(preference.articleListStyle)
$('#hljsTheme').val(preference.hljsTheme)
$('#feedOutputMode').val(preference.feedOutputMode)
$('#feedOutputCnt').val(preference.feedOutputCnt)
$('#faviconURL').val(preference.faviconURL)
$('#loadMsg').text('')
},
})
},
/*
* @description 参数校验
*/
validate: function () {
if (!/^\d+$/.test($('#mostUsedTagDisplayCount').val())) {
$('#tipMsg').
text('[' + Label.paramSettingsLabel + ' - ' +
Label.indexTagDisplayCntLabel + '] ' +
Label.nonNegativeIntegerOnlyLabel)
$('#mostUsedTagDisplayCount').focus()
return false
} else if (!/^\d+$/.test($('#recentCommentDisplayCount').val())) {
$('#tipMsg').
text('[' + Label.paramSettingsLabel + ' - ' +
Label.indexRecentCommentDisplayCntLabel + '] ' +
Label.nonNegativeIntegerOnlyLabel)
$('#recentCommentDisplayCount').focus()
return false
} else if (!/^\d+$/.test($('#mostCommentArticleDisplayCount').val())) {
$('#tipMsg').
text('[' + Label.paramSettingsLabel + ' - ' +
Label.indexMostCommentArticleDisplayCntLabel + '] ' +
Label.nonNegativeIntegerOnlyLabel)
$('#mostCommentArticleDisplayCount').focus()
return false
} else if (!/^\d+$/.test($('#mostViewArticleDisplayCount').val())) {
$('#tipMsg').
text('[' + Label.paramSettingsLabel + ' - ' +
Label.indexMostViewArticleDisplayCntLabel + '] ' +
Label.nonNegativeIntegerOnlyLabel)
$('#mostViewArticleDisplayCount').focus()
return false
} else if (!/^\d+$/.test($('#articleListDisplayCount').val())) {
$('#tipMsg').
text('[' + Label.paramSettingsLabel + ' - ' + Label.pageSizeLabel +
'] ' + Label.nonNegativeIntegerOnlyLabel)
$('#articleListDisplayCount').focus()
return false
} else if (!/^\d+$/.test($('#articleListPaginationWindowSize').val())) {
$('#tipMsg').
text('[' + Label.paramSettingsLabel + ' - ' + Label.windowSizeLabel +
'] ' + Label.nonNegativeIntegerOnlyLabel)
$('#articleListPaginationWindowSize').focus()
return false
} else if (!/^\d+$/.test($('#randomArticlesDisplayCount').val())) {
$('#tipMsg').
text('[' + Label.paramSettingsLabel + ' - ' +
Label.randomArticlesDisplayCntLabel + '] ' +
Label.nonNegativeIntegerOnlyLabel)
$('#randomArticlesDisplayCount').focus()
return false
} else if (!/^\d+$/.test($('#relevantArticlesDisplayCount').val())) {
$('#tipMsg').
text('[' + Label.paramSettingsLabel + ' - ' +
Label.relevantArticlesDisplayCntLabel + '] ' +
Label.nonNegativeIntegerOnlyLabel)
$('#relevantArticlesDisplayCount').focus()
return false
} else if (!/^\d+$/.test(
$('#externalRelevantArticlesDisplayCount').val())) {
$('#tipMsg').
text('[' + Label.paramSettingsLabel + ' - ' +
Label.externalRelevantArticlesDisplayCntLabel + '] ' +
Label.nonNegativeIntegerOnlyLabel)
$('#externalRelevantArticlesDisplayCount').focus()
return false
} else if (
(!/^\d+$/.test($('#wafCurrentLimitTimes').val())) || $('#wafCurrentLimitTimes').val() < 2 || $('#wafCurrentLimitTimes').val() > 2147483647 ||
(!/^\d+$/.test($('#wafCurrentLimitSecond').val())) || $('#wafCurrentLimitSecond').val() < 2 || $('#wafCurrentLimitSecond').val() > 2147483647
) {
$('#tipMsg').text('访问频率次数与时间必须在 2-2147483647 之间!')
return false
}
return true
},
/*
* @description 更新
*/
update: function () {
if (!admin.preference.validate()) {
return
}
$('#tipMsg').text('')
$('#loadMsg').text(Label.loadingLabel)
var signs = [
{
'oId': 0,
'signHTML': '',
}, {
'oId': 1,
'signHTML': $('#preferenceSign1').val(),
}, {
'oId': 2,
'signHTML': $('#preferenceSign2').val(),
}, {
'oId': 3,
'signHTML': $('#preferenceSign3').val(),
}]
if ($("#interactiveSwitch").val() === null) {
$("#interactiveSwitch").val("on");
}
var requestJSONObject = {
'preference': {
'adminActiveSentToMailbox': $("#adminActiveSentToMailbox").val(),
'wafCurrentLimitTimes': $("#wafCurrentLimitTimes").val(),
'wafCurrentLimitSecond': $("#wafCurrentLimitSecond").val(),
'wafPower': $("#wafPower").val(),
'interactive': $("#interactiveSwitch").val(),
'spam': $('#spam').val(),
'kanbanniangSelector': $('#kanbanniangSelector').val(),
'replyRemind': $('#replyRemind').val(),
'tuChuangConfig': $('#sourceTC').text(),
'hacpaiUser': $('#hacpaiUser').val(),
'b3logKey': $('#b3logKey').val(),
'mailBox': $('#mailBox').val(),
'mailUsername': $('#mailUsername').val(),
'mailPassword': $('#mailPassword').val(),
'metaKeywords': $('#metaKeywords').val(),
'metaDescription': $('#metaDescription').val(),
'blogTitle': $('#blogTitle').val(),
'blogSubtitle': $('#blogSubtitle').val(),
'mostCommentArticleDisplayCount': $('#mostCommentArticleDisplayCount').
val(),
'mostViewArticleDisplayCount': $('#mostViewArticleDisplayCount').val(),
'recentCommentDisplayCount': $('#recentCommentDisplayCount').val(),
'mostUsedTagDisplayCount': $('#mostUsedTagDisplayCount').val(),
'articleListDisplayCount': $('#articleListDisplayCount').val(),
'articleListPaginationWindowSize': $(
'#articleListPaginationWindowSize').val(),
'localeString': $('#localeString').val(),
'timeZoneId': $('#timeZoneId').val(),
'noticeBoard': $('#noticeBoard').val(),
'footerContent': $('#footerContent').val(),
'htmlHead': $('#htmlHead').val(),
'externalRelevantArticlesDisplayCount': $(
'#externalRelevantArticlesDisplayCount').val(),
'relevantArticlesDisplayCount': $('#relevantArticlesDisplayCount').
val(),
'randomArticlesDisplayCount': $('#randomArticlesDisplayCount').val(),
'enableArticleUpdateHint': $('#enableArticleUpdateHint').
prop('checked'),
'signs': signs,
'allowVisitDraftViaPermalink': $('#allowVisitDraftViaPermalink').
prop('checked'),
'articleListStyle': $('#articleListDisplay').val(),
'hljsTheme': $('#hljsTheme').val(),
'feedOutputMode': $('#feedOutputMode').val(),
'feedOutputCnt': $('#feedOutputCnt').val(),
'faviconURL': $('#faviconURL').val(),
'syncGitHub': $('#syncGitHub').prop('checked'),
'showCodeBlockLn': $('#showCodeBlockLn').prop('checked'),
'pullGitHub': $('#pullGitHub').prop('checked'),
'commentable': $('#commentable').prop('checked'),
'customVars': $('#customVars').val(),
'githubPAT': $('#githubPAT').val(),
'maxArchive': $('#maxArchive').val(),
'editorMode': $("input[name='editorMode']:checked").val(),
},
}
$.ajax({
url: Label.servePath + '/console/preference/',
type: 'PUT',
cache: false,
data: JSON.stringify(requestJSONObject),
success: function (result, textStatus) {
$('#tipMsg').text(result.msg)
if (!result.sc) {
$('#loadMsg').text('')
return
}
if ($('#localeString').val() !== admin.preference.locale || $("input[name='editorMode']:checked").val() !== admin.preference.editorMode) {
window.location.reload()
}
$('#loadMsg').text('')
window.location.reload()
},
})
},
}
/*
* 注册到 admin 进行管理
*/
admin.register['preference'] = {
'obj': admin.preference,
'init': admin.preference.init,
'refresh': function () {
admin.clearTip()
},
}
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2012-2020 GEM Foundation
#
# OpenQuake 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.
#
# OpenQuake 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 OpenQuake. If not, see <http://www.gnu.org/licenses/>.
"""
Module
:mod:`openquake.hazardlib.gsim.gupta_2010`
defines :class:`Gupta2010SSlabTestCase`
for testing of :class:`openquake.hazardlib.gsim.gupta_2010.Gupta2010SSlab`.
"""
from openquake.hazardlib.tests.gsim.utils import BaseGSIMTestCase
from openquake.hazardlib.gsim.gupta_2010 import (
Gupta2010SSlab,
)
class Gupta2010SSlabTestCase(BaseGSIMTestCase):
"""
Mean value data obtained from author matched well at 1 s and below but
not at longer periods. As a temporary measure the reference test result
has been generated from the current implementation.
"""
GSIM_CLASS = Gupta2010SSlab
MEAN_FILES = ['GUPT10/GUPT10_MEAN_NEW.csv']
SIGMA_FILES = ['GUPT10/GUPT10_TOTAL_STDDEV.csv']
MEAN_TOL = 1e-4
SIGMA_TOL = 1e-4
def test_mean(self):
"""
Ensure that means match reference dataset.
"""
for mean_file in self.MEAN_FILES:
self.check(mean_file, max_discrep_percentage=self.MEAN_TOL)
def test_std_total(self):
"""
Ensure that standard deviations match reference dataset.
"""
for sigma_file in self.SIGMA_FILES:
self.check(sigma_file, max_discrep_percentage=self.SIGMA_TOL)
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2016 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <utility>
#include <type_traits>
namespace folly {
namespace dptr_detail {
/**
* Given a target type and a list of types, return the 1-based index of the
* type in the list of types. Fail to compile if the target type doesn't
* appear in the list.
*
* GetIndex<int, void, char, int>::value == 3
* GetIndex<int, void, char>::value -> fails to compile
*/
template <typename... Types> struct GetTypeIndex;
// When recursing, we never reach the 0- or 1- template argument base case
// unless the target type is not in the list. If the target type is in the
// list, we stop recursing when it is at the head of the remaining type
// list via the GetTypeIndex<T, T, Types...> partial specialization.
template <typename T, typename... Types>
struct GetTypeIndex<T, T, Types...> {
static const size_t value = 1;
};
template <typename T, typename U, typename... Types>
struct GetTypeIndex<T, U, Types...> {
static const size_t value = 1 + GetTypeIndex<T, Types...>::value;
};
// Generalize std::is_same for variable number of type arguments
template <typename... Types>
struct IsSameType;
template <>
struct IsSameType<> {
static const bool value = true;
};
template <typename T>
struct IsSameType<T> {
static const bool value = true;
};
template <typename T, typename U, typename... Types>
struct IsSameType<T, U, Types...> {
static const bool value =
std::is_same<T,U>::value && IsSameType<U, Types...>::value;
};
// Define type as the type of all T in (non-empty) Types..., asserting that
// all types in Types... are the same.
template <typename... Types>
struct SameType;
template <typename T, typename... Types>
struct SameType<T, Types...> {
typedef T type;
static_assert(IsSameType<T, Types...>::value,
"Not all types in pack are the same");
};
// Determine the result type of applying a visitor of type V on a pointer
// to type T.
template <typename V, typename T>
struct VisitorResult1 {
typedef typename std::result_of<V (T*)>::type type;
};
// Determine the result type of applying a visitor of type V on a const pointer
// to type T.
template <typename V, typename T>
struct ConstVisitorResult1 {
typedef typename std::result_of<V (const T*)>::type type;
};
// Determine the result type of applying a visitor of type V on pointers of
// all types in Types..., asserting that the type is the same for all types
// in Types...
template <typename V, typename... Types>
struct VisitorResult {
typedef typename SameType<
typename VisitorResult1<V,Types>::type...>::type type;
};
// Determine the result type of applying a visitor of type V on const pointers
// of all types in Types..., asserting that the type is the same for all types
// in Types...
template <typename V, typename... Types>
struct ConstVisitorResult {
typedef typename SameType<
typename ConstVisitorResult1<V,Types>::type...>::type type;
};
template <size_t index, typename V, typename R, typename... Types>
struct ApplyVisitor1;
template <typename V, typename R, typename T, typename... Types>
struct ApplyVisitor1<1, V, R, T, Types...> {
R operator()(size_t, V&& visitor, void* ptr) const {
return visitor(static_cast<T*>(ptr));
}
};
template <size_t index, typename V, typename R, typename T, typename... Types>
struct ApplyVisitor1<index, V, R, T, Types...> {
R operator()(size_t runtimeIndex, V&& visitor, void* ptr) const {
return runtimeIndex == 1
? visitor(static_cast<T*>(ptr))
: ApplyVisitor1<index - 1, V, R, Types...>()(
runtimeIndex - 1, std::forward<V>(visitor), ptr);
}
};
template <size_t index, typename V, typename R, typename... Types>
struct ApplyConstVisitor1;
template <typename V, typename R, typename T, typename... Types>
struct ApplyConstVisitor1<1, V, R, T, Types...> {
R operator()(size_t, V&& visitor, void* ptr) const {
return visitor(static_cast<const T*>(ptr));
}
};
template <size_t index, typename V, typename R, typename T, typename... Types>
struct ApplyConstVisitor1<index, V, R, T, Types...> {
R operator()(size_t runtimeIndex, V&& visitor, void* ptr) const {
return runtimeIndex == 1
? visitor(static_cast<const T*>(ptr))
: ApplyConstVisitor1<index - 1, V, R, Types...>()(
runtimeIndex - 1, std::forward<V>(visitor), ptr);
}
};
template <typename V, typename... Types>
using ApplyVisitor = ApplyVisitor1<
sizeof...(Types),
V,
typename VisitorResult<V, Types...>::type,
Types...>;
template <typename V, typename... Types>
using ApplyConstVisitor = ApplyConstVisitor1<
sizeof...(Types),
V,
typename ConstVisitorResult<V, Types...>::type,
Types...>;
} // namespace dptr_detail
} // namespace folly
| {
"pile_set_name": "Github"
} |
msgid "default.foo"
msgstr "Default Foo"
msgid "default.bar"
msgstr "Default Bar"
| {
"pile_set_name": "Github"
} |
simpleeval>=0.9.10
| {
"pile_set_name": "Github"
} |
#pragma unmanaged
// Defines the entry point for the console application.
#include "stdafx.h"
#include <stdlib.h>
#include <string.h>
#include <algorithm>
//#include <cstdlib>
#include "sort.h"
#include <vector>
#include <math.h>
static int d = 100;
static int hashBytes = 2;
int compare(void *context, const void * a, const void * b)
{
return memcmp(a, b, d);
}
bool compareb(void *context, const void * a, const void * b)
{
return memcmp(a, b, d) < 0;
}
bool comparec(const void * a, const void * b)
{
return memcmp(a, b, d) < 0;
}
#define swapcode(TYPE, parmi, parmj, n) { \
long i = (n) / sizeof (TYPE); \
TYPE *pi = (TYPE *) (parmi); \
TYPE *pj = (TYPE *) (parmj); \
do { \
TYPE t = *pi; \
*pi++ = *pj; \
*pj++ = t; \
} while (--i > 0); \
}
extern "C" __declspec(dllexport)
void stdquicksort(void* buf, int len, int dim)
{
dim = d;
qsort_s(buf, len, dim, compare, 0);
}
int comparefirst2(const void * a, const void * b)
{
return memcmp(a, b, 2);
}
#define getHash(data) \
(((int ((unsigned char)*(data))) << 8) + ((unsigned char)*((data)+1)) )
int hash(char * data)
{
int ret = ((unsigned char)*data);
for (int i = 1; i < hashBytes; i++)
{
ret = (ret << 8) + (unsigned char)*(data + i);
}
return ret;
}
static int * boundaryArr;
int GetIndex(int hashVal)
{
return boundaryArr[hashVal];
//return hashVal % 1024;
}
#define HASH(data) (((int ((unsigned char)*(data))) << 8) + ((unsigned char)*((data) + 1)))
extern "C" __declspec(dllexport)
void bin(char * buf, int len, int dim, int binNum, int * boundary, int * sPos, char * outBuf, size_t outBufSize)
{
//int hashBitSize = fmax(8, (int)(log2((float)(binNum - 1)) + 1));
//hashBytes = (hashBitSize - 1) / 8 + 1;
hashBytes = 2;
boundaryArr = boundary;
for (int i = 0; i < binNum; i++)
{
sPos[i] = 0;
}
for (int i = 0; i < len; i++)
{
int hashval = hash(buf + i*dim);
int index = GetIndex(hashval);
sPos[index] += dim;
}
int sum = 0;
for (int i = 0; i < binNum; i++)
{
int t = sum;
sum += sPos[i];
sPos[i] = t;
}
//0.84 seconds
//char * ttbuf = new char[len*dim];
for (int i = 0; i < len; i++)
{
int index = GetIndex(hash(buf + i * dim));
memcpy_s(outBuf + sPos[index], outBufSize - sPos[index], buf + i * dim, dim);
sPos[index] += dim;
}
//1.0 second
/*
int counter = 0;
int i = 0;
while (i < len)
{
int index = GetIndex(hash(buf + i * dim));
if (sPos[index] == i*dim)
{
i++;
sPos[index] += dim;
}
else if (sPos[index] >= sPos[index+binNum])
{
i++;
}
else if (sPos[index] < len * dim)
{
while (sPos[index] < len*dim && GetIndex(hash(buf + sPos[index])) == index)
{
sPos[index] += dim;
}
memcpy_s(tBuf, len*dim, buf + sPos[index], dim);
memcpy_s(buf + sPos[index], len*dim - sPos[index], buf + i * dim, dim);
memcpy_s(buf + i * dim, len*dim - i*dim, tBuf, dim);
sPos[index] += dim;
while (sPos[index] < len*dim && GetIndex(hash(buf + sPos[index])) == index)
{
sPos[index] += dim;
}
}
}
*/
//for (int i = 0; i < len; i++)
//{
// int index = boundary[hash(buf + i*dim, hashByteSize)];
// memcpy_s(tbuf + sPos[index], outBufSize - sPos[index], buf + i*dim, dim);
// sPos[index] += dim;
//}
//memcpy_s(buf, len*dim, tbuf, len*dim);
// delete tbuf;
}
extern "C" __declspec(dllexport)
void getBinSize(char * buf, int len, int dim, int binNum, int * boundary, int * binSize)
{
for (int i = 0; i < binNum; i++)
{
binSize[i] = 0;
}
for (int i = 0; i < len; i++)
{
int index = HASH(buf + i*dim);// % binNum;
binSize[boundary[index]] += dim;
}
}
extern "C" __declspec(dllexport)
void stdsort(void* buf, int len, int dim)
{
//char ** pointer = new char *[len];
std::vector<char*> pointer(len);
char * p = (char *)buf;
for (int i = 0; i < len; i++)
{
pointer[i] = p;
p = p + dim;
}
std::sort(pointer.begin(), pointer.end(), comparec);
char* tbuf = new char[len*dim];
for (int i = 0; i < len; i++)
{
//swapcode(char, pointer + i, tbuf + i*dim,dim);
memcpy_s(tbuf + i*dim, len*dim-i*dim, pointer[i], dim);
}
for (int i = 0; i < len; i++)
{
//swapcode(char, (char*)buf + (i*dim), tbuf + i*dim, dim);
memcpy_s((char*)buf + (i*dim), len*dim-i*dim, tbuf + i*dim, dim);
}
//delete pointer;
delete tbuf;
}
extern "C" __declspec(dllexport)
void MyMemoryCopy(char* srcBuf, int srcOff, char* dest, int destOff, int dstSize, int size)
{
memcpy_s(dest + destOff, dstSize, srcBuf + srcOff, size);
}
#pragma unmanaged
int __cdecl compare64(void *context, const void *a, const void *b)
{
int i;
int dim = *(int*)context;
unsigned __int64 *a64 = (unsigned __int64*)a;
unsigned __int64 *b64 = (unsigned __int64*)b;
#if 0
if (a64[0] > b64[0]) return 1;
if (a64[0] < b64[0]) return -1;
for (i=1; i < dim; i++)
{
if (a64[i] > b64[i]) return 1;
if (a64[i] < b64[i]) return -1;
}
#else
if (_byteswap_uint64(a64[0]) > _byteswap_uint64(b64[0])) return 1;
if (_byteswap_uint64(a64[0]) < _byteswap_uint64(b64[0])) return -1;
for (i = 1; i < dim; i++)
{
if (_byteswap_uint64(a64[i]) > _byteswap_uint64(b64[i])) return 1;
if (_byteswap_uint64(a64[i]) < _byteswap_uint64(b64[i])) return -1;
}
#endif
return 0;
}
// "buf" has "num" alignment units of size "align"
#pragma unmanaged
extern "C" __declspec(dllexport)
void __stdcall alignsort64(unsigned __int64 *buf, int align, int num)
{
qsort_s(buf, num, align*8, compare64, &align);
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2001-2016 Food and Agriculture Organization of the
* United Nations (FAO-UN), United Nations World Food Programme (WFP)
* and United Nations Environment Programme (UNEP)
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
* Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
* Rome - Italy. email: [email protected]
*/
package org.fao.geonet.api.csw;
import io.swagger.annotations.*;
import jeeves.server.JeevesEngine;
import org.fao.geonet.ApplicationContextHolder;
import org.fao.geonet.api.API;
import org.fao.geonet.api.exception.ResourceNotFoundException;
import org.fao.geonet.domain.Service;
import org.fao.geonet.repository.ServiceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RequestMapping(value = {
"/{portal}/api/csw/virtuals",
"/{portal}/api/" + API.VERSION_0_1 +
"/csw/virtuals"
})
@Api(value = "csw",
tags = "csw",
description = "Virtual CSW operations")
@Controller("cswVirtual")
public class VirtualCswApi {
public static final String API_PARAM_CSW_SERVICE_IDENTIFIER = "Service identifier";
public static final String API_PARAM_CSW_SERVICE_DETAILS = "Service details";
@Autowired
private ServiceRepository serviceRepository;
@ApiOperation(
value = "Get virtual CSW services",
notes = "Virtual CSWs are created to easily setup services " +
"providing access to records without the need to define filters. For example, " +
"in Europe, local, regional and national organizations define entry point " +
"for records in the scope of the INSPIRE directive. Those services can then be " +
"easily harvested to exchange information. " +
"Virtual CSWs do not support transaction. For this use the main " +
"catalog CSW service.",
nickname = "getAllVirtualCsw")
@RequestMapping(
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public List<Service> getAllVirtualCsw() throws Exception {
return serviceRepository.findAll();
}
@ApiOperation(
value = "Get a virtual CSW",
notes = "",
nickname = "getVirtualCsw")
@RequestMapping(
path = "/{identifier}",
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)
@ApiResponses(value = {
@ApiResponse(code = 404, message = "Resource not found.")
})
@ResponseBody
public Service getVirtualCsw(
@ApiParam(
value = API_PARAM_CSW_SERVICE_IDENTIFIER,
required = true
)
@PathVariable
int identifier
) throws Exception {
Service service = serviceRepository.findOne(identifier);
if (service == null) {
throw new ResourceNotFoundException(String.format(
"Virtual CSW with id '%d' does not exist.",
identifier
));
} else {
return service;
}
}
@ApiOperation(
value = "Add a virtual CSW",
notes = "The service name MUST be unique. " +
"An exception is returned if not the case.",
authorizations = {
@Authorization(value = "basicAuth")
},
nickname = "addVirtualCsw")
@RequestMapping(
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.PUT
)
@ResponseStatus(HttpStatus.CREATED)
@PreAuthorize("hasRole('Administrator')")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Return the identifier of the newly created service"),
@ApiResponse(code = 404, message = "A service already exist with this name") ,
@ApiResponse(code = 403, message = "Operation not allowed. Only Administrator can access it.")
})
@ResponseBody
public ResponseEntity<Integer> addVirtualCsw(
@ApiParam(
value = API_PARAM_CSW_SERVICE_DETAILS,
required = true
)
@RequestBody
Service service
) throws Exception {
Service existing = serviceRepository.findOneByName(service.getName());
if (existing != null) {
throw new IllegalArgumentException(String.format(
"A service already exist with this name '%s'. Choose another name.",
service.getName()));
}
service.getParameters().forEach(p -> {
p.setService(service);
});
serviceRepository.save(service);
ApplicationContext applicationContext = ApplicationContextHolder.get();
applicationContext.getBean(JeevesEngine.class)
.loadConfigDB(applicationContext, service.getId());
return new ResponseEntity<>(service.getId(), HttpStatus.CREATED);
}
@ApiOperation(
value = "Update a virtual CSW",
notes = "",
authorizations = {
@Authorization(value = "basicAuth")
},
nickname = "updateVirtualCsw")
@RequestMapping(
path = "/{identifier}",
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.PUT)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
@PreAuthorize("hasRole('Administrator')")
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Service updated.") ,
@ApiResponse(code = 404, message = "Resource not found.") ,
@ApiResponse(code = 403, message = "Operation not allowed. Only Administrator can access it.")
})
public void updateVirtualCsw(
@ApiParam(
value = API_PARAM_CSW_SERVICE_IDENTIFIER,
required = true
)
@PathVariable
int identifier,
@ApiParam(
value = API_PARAM_CSW_SERVICE_DETAILS,
required = true
)
@RequestBody
Service service
) throws Exception {
Service existing = serviceRepository.findOne(identifier);
if (existing != null) {
// Attach params to service in case not set by client.
service.getParameters().forEach(p -> {
p.setService(service);
});
serviceRepository.save(service);
} else {
throw new ResourceNotFoundException(String.format(
"Virtual CSW with id '%d' does not exist.",
identifier
));
}
ApplicationContext applicationContext = ApplicationContextHolder.get();
applicationContext.getBean(JeevesEngine.class)
.loadConfigDB(applicationContext, identifier);
}
@ApiOperation(
value = "Remove a virtual CSW",
notes = "After removal, all virtual CSW configuration is reloaded.",
authorizations = {
@Authorization(value = "basicAuth")
},
nickname = "deleteVirtualCsw")
@RequestMapping(
path = "/{identifier}",
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
@PreAuthorize("hasRole('Administrator')")
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Service removed.") ,
@ApiResponse(code = 404, message = "Resource not found.") ,
@ApiResponse(code = 403, message = "Operation not allowed. Only Administrator can access it.")
})
public void deleteVirtualCsw(
@ApiParam(
value = API_PARAM_CSW_SERVICE_IDENTIFIER,
required = true
)
@PathVariable
int identifier
) throws Exception {
Service existing = serviceRepository.findOne(identifier);
if (existing != null) {
serviceRepository.delete(identifier);
ApplicationContext applicationContext = ApplicationContextHolder.get();
applicationContext.getBean(JeevesEngine.class)
.loadConfigDB(applicationContext, Integer.valueOf(identifier));
} else {
throw new ResourceNotFoundException(String.format(
"Virtual CSW with id '%d' does not exist.",
identifier
));
}
}
}
| {
"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.
*/
/*!
* Copyright (c) 2017 by Contributors
* \file control_flow_op.cu
* \brief
*/
#include "./control_flow_op.h"
namespace mxnet {
namespace op {
NNVM_REGISTER_OP(where)
.set_attr<FCompute>("FCompute<gpu>", WhereOpForward<gpu>);
NNVM_REGISTER_OP(_backward_where)
.set_attr<FCompute>("FCompute<gpu>", WhereOpBackward<gpu>);
} // namespace op
} // namespace mxnet
| {
"pile_set_name": "Github"
} |
//
// GMSPath.h
// Google Maps SDK for iOS
//
// Copyright 2013 Google Inc.
//
// Usage of this SDK is subject to the Google Maps/Google Earth APIs Terms of
// Service: https://developers.google.com/maps/terms
//
#import <CoreLocation/CoreLocation.h>
#if __has_feature(modules)
@import GoogleMapsBase;
#else
#import <GoogleMapsBase/GoogleMapsBase.h>
#endif
GMS_ASSUME_NONNULL_BEGIN
/**
* GMSPath encapsulates an immutable array of CLLocationCooordinate2D. All the coordinates of a
* GMSPath must be valid. The mutable counterpart is GMSMutablePath.
*/
@interface GMSPath : NSObject<NSCopying, NSMutableCopying>
/** Convenience constructor for an empty path. */
+ (instancetype)path;
/** Initializes a newly allocated path with the contents of another GMSPath. */
- (id)initWithPath:(GMSPath *)path;
/** Get size of path. */
- (NSUInteger)count;
/** Returns kCLLocationCoordinate2DInvalid if |index| >= count. */
- (CLLocationCoordinate2D)coordinateAtIndex:(NSUInteger)index;
/**
* Initializes a newly allocated path from |encodedPath|. This format is described at:
* https://developers.google.com/maps/documentation/utilities/polylinealgorithm
*/
+ (GMS_NULLABLE_INSTANCETYPE)pathFromEncodedPath:(NSString *)encodedPath;
/** Returns an encoded string of the path in the format described above. */
- (NSString *)encodedPath;
/**
* Returns a new path obtained by adding |deltaLatitude| and |deltaLongitude| to each coordinate
* of the current path. Does not modify the current path.
*/
- (instancetype)pathOffsetByLatitude:(CLLocationDegrees)deltaLatitude
longitude:(CLLocationDegrees)deltaLongitude;
@end
/**
* kGMSEquatorProjectedMeter may be useful when specifying lengths for segment in "projected" units.
* The value of kGMSEquatorProjectedMeter, 1/(pi * EarthRadius), represents the length of one meter
* at the equator in projected units. For example to specify a projected length that corresponds
* to 100km at the equator use 100000 * kGMSEquatorProjectedMeter.
* See [GMSPath segmentsForLength:kind:], [GMSPath lengthOfKind:] and kGMSLengthProjected.
*/
extern const double kGMSEquatorProjectedMeter;
/**
* GMSLengthKind indicates the type of a length value, which can be geodesic (in meters), rhumb
* length (in meters) and projected length (in GMSMapPoint units).
*/
typedef enum {
/*
* Geodesic length, in meters, along geodesic segments. May be useful, for example, to specify
* lengths along the the trajectory of airplanes or ships.
*/
kGMSLengthGeodesic,
/*
* Rhumb length, in meters, along rhumb (straight line) segments. May be useful, for example, to
* draw a scale bar on a map. The visual size of a segment of a given length depens on the
* latitude.
*/
kGMSLengthRhumb,
/*
* Length in projected space, along rhumb segments. Projected length uses the same units as
* GMSMapPoint - the Earth equator circumference has length 2. It is possible to specify projected
* length in units corresponding to 1 meter at the equator by multiplying with
* kGMSEquatorProjectedMeter, equal to 1/(pi * EarthRadius).
*
* Projected length may be useful, for example, to specify segments with the same visual length
* regardless of latitude.
*/
kGMSLengthProjected
} GMSLengthKind;
@interface GMSPath (GMSPathLength)
/**
* Returns the fractional number of segments along the path that correspond to |length|,
* interpreted according to |kind|. See GMSLengthKind.
*/
- (double)segmentsForLength:(CLLocationDistance)length kind:(GMSLengthKind)kind;
/**
* Returns the length of the path, according to |kind|. See GMSLengthKind.
*/
- (CLLocationDistance)lengthOfKind:(GMSLengthKind)kind;
@end
GMS_ASSUME_NONNULL_END
| {
"pile_set_name": "Github"
} |
# Copyright (C) 2007-2012 Michael Foord & the mock team
# E-mail: fuzzyman AT voidspace DOT org DOT uk
# http://www.voidspace.org.uk/python/mock/
from tests.support import (
callable, unittest2, inPy3k, is_instance, next
)
import copy
import pickle
import sys
import mock
from mock import (
call, DEFAULT, patch, sentinel,
MagicMock, Mock, NonCallableMock,
NonCallableMagicMock, _CallList,
create_autospec
)
try:
unicode
except NameError:
unicode = str
class Iter(object):
def __init__(self):
self.thing = iter(['this', 'is', 'an', 'iter'])
def __iter__(self):
return self
def next(self):
return next(self.thing)
__next__ = next
class Subclass(MagicMock):
pass
class Thing(object):
attribute = 6
foo = 'bar'
class MockTest(unittest2.TestCase):
def test_all(self):
# if __all__ is badly defined then import * will raise an error
# We have to exec it because you can't import * inside a method
# in Python 3
exec("from mock import *")
def test_constructor(self):
mock = Mock()
self.assertFalse(mock.called, "called not initialised correctly")
self.assertEqual(mock.call_count, 0,
"call_count not initialised correctly")
self.assertTrue(is_instance(mock.return_value, Mock),
"return_value not initialised correctly")
self.assertEqual(mock.call_args, None,
"call_args not initialised correctly")
self.assertEqual(mock.call_args_list, [],
"call_args_list not initialised correctly")
self.assertEqual(mock.method_calls, [],
"method_calls not initialised correctly")
# Can't use hasattr for this test as it always returns True on a mock
self.assertFalse('_items' in mock.__dict__,
"default mock should not have '_items' attribute")
self.assertIsNone(mock._mock_parent,
"parent not initialised correctly")
self.assertIsNone(mock._mock_methods,
"methods not initialised correctly")
self.assertEqual(mock._mock_children, {},
"children not initialised incorrectly")
def test_unicode_not_broken(self):
# This used to raise an exception with Python 2.5 and Mock 0.4
unicode(Mock())
def test_return_value_in_constructor(self):
mock = Mock(return_value=None)
self.assertIsNone(mock.return_value,
"return value in constructor not honoured")
def test_repr(self):
mock = Mock(name='foo')
self.assertIn('foo', repr(mock))
self.assertIn("'%s'" % id(mock), repr(mock))
mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')]
for mock, name in mocks:
self.assertIn('%s.bar' % name, repr(mock.bar))
self.assertIn('%s.foo()' % name, repr(mock.foo()))
self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing))
self.assertIn('%s()' % name, repr(mock()))
self.assertIn('%s()()' % name, repr(mock()()))
self.assertIn('%s()().foo.bar.baz().bing' % name,
repr(mock()().foo.bar.baz().bing))
def test_repr_with_spec(self):
class X(object):
pass
mock = Mock(spec=X)
self.assertIn(" spec='X' ", repr(mock))
mock = Mock(spec=X())
self.assertIn(" spec='X' ", repr(mock))
mock = Mock(spec_set=X)
self.assertIn(" spec_set='X' ", repr(mock))
mock = Mock(spec_set=X())
self.assertIn(" spec_set='X' ", repr(mock))
mock = Mock(spec=X, name='foo')
self.assertIn(" spec='X' ", repr(mock))
self.assertIn(" name='foo' ", repr(mock))
mock = Mock(name='foo')
self.assertNotIn("spec", repr(mock))
mock = Mock()
self.assertNotIn("spec", repr(mock))
mock = Mock(spec=['foo'])
self.assertNotIn("spec", repr(mock))
def test_side_effect(self):
mock = Mock()
def effect(*args, **kwargs):
raise SystemError('kablooie')
mock.side_effect = effect
self.assertRaises(SystemError, mock, 1, 2, fish=3)
mock.assert_called_with(1, 2, fish=3)
results = [1, 2, 3]
def effect():
return results.pop()
mock.side_effect = effect
self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
"side effect not used correctly")
mock = Mock(side_effect=sentinel.SideEffect)
self.assertEqual(mock.side_effect, sentinel.SideEffect,
"side effect in constructor not used")
def side_effect():
return DEFAULT
mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
self.assertEqual(mock(), sentinel.RETURN)
@unittest2.skipUnless('java' in sys.platform,
'This test only applies to Jython')
def test_java_exception_side_effect(self):
import java
mock = Mock(side_effect=java.lang.RuntimeException("Boom!"))
# can't use assertRaises with java exceptions
try:
mock(1, 2, fish=3)
except java.lang.RuntimeException:
pass
else:
self.fail('java exception not raised')
mock.assert_called_with(1,2, fish=3)
def test_reset_mock(self):
parent = Mock()
spec = ["something"]
mock = Mock(name="child", parent=parent, spec=spec)
mock(sentinel.Something, something=sentinel.SomethingElse)
something = mock.something
mock.something()
mock.side_effect = sentinel.SideEffect
return_value = mock.return_value
return_value()
mock.reset_mock()
self.assertEqual(mock._mock_name, "child",
"name incorrectly reset")
self.assertEqual(mock._mock_parent, parent,
"parent incorrectly reset")
self.assertEqual(mock._mock_methods, spec,
"methods incorrectly reset")
self.assertFalse(mock.called, "called not reset")
self.assertEqual(mock.call_count, 0, "call_count not reset")
self.assertEqual(mock.call_args, None, "call_args not reset")
self.assertEqual(mock.call_args_list, [], "call_args_list not reset")
self.assertEqual(mock.method_calls, [],
"method_calls not initialised correctly: %r != %r" %
(mock.method_calls, []))
self.assertEqual(mock.mock_calls, [])
self.assertEqual(mock.side_effect, sentinel.SideEffect,
"side_effect incorrectly reset")
self.assertEqual(mock.return_value, return_value,
"return_value incorrectly reset")
self.assertFalse(return_value.called, "return value mock not reset")
self.assertEqual(mock._mock_children, {'something': something},
"children reset incorrectly")
self.assertEqual(mock.something, something,
"children incorrectly cleared")
self.assertFalse(mock.something.called, "child not reset")
def test_reset_mock_recursion(self):
mock = Mock()
mock.return_value = mock
# used to cause recursion
mock.reset_mock()
def test_call(self):
mock = Mock()
self.assertTrue(is_instance(mock.return_value, Mock),
"Default return_value should be a Mock")
result = mock()
self.assertEqual(mock(), result,
"different result from consecutive calls")
mock.reset_mock()
ret_val = mock(sentinel.Arg)
self.assertTrue(mock.called, "called not set")
self.assertEqual(mock.call_count, 1, "call_count incoreect")
self.assertEqual(mock.call_args, ((sentinel.Arg,), {}),
"call_args not set")
self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})],
"call_args_list not initialised correctly")
mock.return_value = sentinel.ReturnValue
ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
self.assertEqual(ret_val, sentinel.ReturnValue,
"incorrect return value")
self.assertEqual(mock.call_count, 2, "call_count incorrect")
self.assertEqual(mock.call_args,
((sentinel.Arg,), {'key': sentinel.KeyArg}),
"call_args not set")
self.assertEqual(mock.call_args_list, [
((sentinel.Arg,), {}),
((sentinel.Arg,), {'key': sentinel.KeyArg})
],
"call_args_list not set")
def test_call_args_comparison(self):
mock = Mock()
mock()
mock(sentinel.Arg)
mock(kw=sentinel.Kwarg)
mock(sentinel.Arg, kw=sentinel.Kwarg)
self.assertEqual(mock.call_args_list, [
(),
((sentinel.Arg,),),
({"kw": sentinel.Kwarg},),
((sentinel.Arg,), {"kw": sentinel.Kwarg})
])
self.assertEqual(mock.call_args,
((sentinel.Arg,), {"kw": sentinel.Kwarg}))
def test_assert_called_with(self):
mock = Mock()
mock()
# Will raise an exception if it fails
mock.assert_called_with()
self.assertRaises(AssertionError, mock.assert_called_with, 1)
mock.reset_mock()
self.assertRaises(AssertionError, mock.assert_called_with)
mock(1, 2, 3, a='fish', b='nothing')
mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
def test_assert_called_once_with(self):
mock = Mock()
mock()
# Will raise an exception if it fails
mock.assert_called_once_with()
mock()
self.assertRaises(AssertionError, mock.assert_called_once_with)
mock.reset_mock()
self.assertRaises(AssertionError, mock.assert_called_once_with)
mock('foo', 'bar', baz=2)
mock.assert_called_once_with('foo', 'bar', baz=2)
mock.reset_mock()
mock('foo', 'bar', baz=2)
self.assertRaises(
AssertionError,
lambda: mock.assert_called_once_with('bob', 'bar', baz=2)
)
def test_attribute_access_returns_mocks(self):
mock = Mock()
something = mock.something
self.assertTrue(is_instance(something, Mock), "attribute isn't a mock")
self.assertEqual(mock.something, something,
"different attributes returned for same name")
# Usage example
mock = Mock()
mock.something.return_value = 3
self.assertEqual(mock.something(), 3, "method returned wrong value")
self.assertTrue(mock.something.called,
"method didn't record being called")
def test_attributes_have_name_and_parent_set(self):
mock = Mock()
something = mock.something
self.assertEqual(something._mock_name, "something",
"attribute name not set correctly")
self.assertEqual(something._mock_parent, mock,
"attribute parent not set correctly")
def test_method_calls_recorded(self):
mock = Mock()
mock.something(3, fish=None)
mock.something_else.something(6, cake=sentinel.Cake)
self.assertEqual(mock.something_else.method_calls,
[("something", (6,), {'cake': sentinel.Cake})],
"method calls not recorded correctly")
self.assertEqual(mock.method_calls, [
("something", (3,), {'fish': None}),
("something_else.something", (6,), {'cake': sentinel.Cake})
],
"method calls not recorded correctly")
def test_method_calls_compare_easily(self):
mock = Mock()
mock.something()
self.assertEqual(mock.method_calls, [('something',)])
self.assertEqual(mock.method_calls, [('something', (), {})])
mock = Mock()
mock.something('different')
self.assertEqual(mock.method_calls, [('something', ('different',))])
self.assertEqual(mock.method_calls,
[('something', ('different',), {})])
mock = Mock()
mock.something(x=1)
self.assertEqual(mock.method_calls, [('something', {'x': 1})])
self.assertEqual(mock.method_calls, [('something', (), {'x': 1})])
mock = Mock()
mock.something('different', some='more')
self.assertEqual(mock.method_calls, [
('something', ('different',), {'some': 'more'})
])
def test_only_allowed_methods_exist(self):
for spec in ['something'], ('something',):
for arg in 'spec', 'spec_set':
mock = Mock(**{arg: spec})
# this should be allowed
mock.something
self.assertRaisesRegexp(
AttributeError,
"Mock object has no attribute 'something_else'",
getattr, mock, 'something_else'
)
def test_from_spec(self):
class Something(object):
x = 3
__something__ = None
def y(self):
pass
def test_attributes(mock):
# should work
mock.x
mock.y
mock.__something__
self.assertRaisesRegexp(
AttributeError,
"Mock object has no attribute 'z'",
getattr, mock, 'z'
)
self.assertRaisesRegexp(
AttributeError,
"Mock object has no attribute '__foobar__'",
getattr, mock, '__foobar__'
)
test_attributes(Mock(spec=Something))
test_attributes(Mock(spec=Something()))
def test_wraps_calls(self):
real = Mock()
mock = Mock(wraps=real)
self.assertEqual(mock(), real())
real.reset_mock()
mock(1, 2, fish=3)
real.assert_called_with(1, 2, fish=3)
def test_wraps_call_with_nondefault_return_value(self):
real = Mock()
mock = Mock(wraps=real)
mock.return_value = 3
self.assertEqual(mock(), 3)
self.assertFalse(real.called)
def test_wraps_attributes(self):
class Real(object):
attribute = Mock()
real = Real()
mock = Mock(wraps=real)
self.assertEqual(mock.attribute(), real.attribute())
self.assertRaises(AttributeError, lambda: mock.fish)
self.assertNotEqual(mock.attribute, real.attribute)
result = mock.attribute.frog(1, 2, fish=3)
Real.attribute.frog.assert_called_with(1, 2, fish=3)
self.assertEqual(result, Real.attribute.frog())
def test_exceptional_side_effect(self):
mock = Mock(side_effect=AttributeError)
self.assertRaises(AttributeError, mock)
mock = Mock(side_effect=AttributeError('foo'))
self.assertRaises(AttributeError, mock)
def test_baseexceptional_side_effect(self):
mock = Mock(side_effect=KeyboardInterrupt)
self.assertRaises(KeyboardInterrupt, mock)
mock = Mock(side_effect=KeyboardInterrupt('foo'))
self.assertRaises(KeyboardInterrupt, mock)
def test_assert_called_with_message(self):
mock = Mock()
self.assertRaisesRegexp(AssertionError, 'Not called',
mock.assert_called_with)
def test__name__(self):
mock = Mock()
self.assertRaises(AttributeError, lambda: mock.__name__)
mock.__name__ = 'foo'
self.assertEqual(mock.__name__, 'foo')
def test_spec_list_subclass(self):
class Sub(list):
pass
mock = Mock(spec=Sub(['foo']))
mock.append(3)
mock.append.assert_called_with(3)
self.assertRaises(AttributeError, getattr, mock, 'foo')
def test_spec_class(self):
class X(object):
pass
mock = Mock(spec=X)
self.assertTrue(isinstance(mock, X))
mock = Mock(spec=X())
self.assertTrue(isinstance(mock, X))
self.assertIs(mock.__class__, X)
self.assertEqual(Mock().__class__.__name__, 'Mock')
mock = Mock(spec_set=X)
self.assertTrue(isinstance(mock, X))
mock = Mock(spec_set=X())
self.assertTrue(isinstance(mock, X))
def test_setting_attribute_with_spec_set(self):
class X(object):
y = 3
mock = Mock(spec=X)
mock.x = 'foo'
mock = Mock(spec_set=X)
def set_attr():
mock.x = 'foo'
mock.y = 'foo'
self.assertRaises(AttributeError, set_attr)
def test_copy(self):
current = sys.getrecursionlimit()
self.addCleanup(sys.setrecursionlimit, current)
# can't use sys.maxint as this doesn't exist in Python 3
sys.setrecursionlimit(int(10e8))
# this segfaults without the fix in place
copy.copy(Mock())
@unittest2.skipIf(inPy3k, "no old style classes in Python 3")
def test_spec_old_style_classes(self):
class Foo:
bar = 7
mock = Mock(spec=Foo)
mock.bar = 6
self.assertRaises(AttributeError, lambda: mock.foo)
mock = Mock(spec=Foo())
mock.bar = 6
self.assertRaises(AttributeError, lambda: mock.foo)
@unittest2.skipIf(inPy3k, "no old style classes in Python 3")
def test_spec_set_old_style_classes(self):
class Foo:
bar = 7
mock = Mock(spec_set=Foo)
mock.bar = 6
self.assertRaises(AttributeError, lambda: mock.foo)
def _set():
mock.foo = 3
self.assertRaises(AttributeError, _set)
mock = Mock(spec_set=Foo())
mock.bar = 6
self.assertRaises(AttributeError, lambda: mock.foo)
def _set():
mock.foo = 3
self.assertRaises(AttributeError, _set)
def test_subclass_with_properties(self):
class SubClass(Mock):
def _get(self):
return 3
def _set(self, value):
raise NameError('strange error')
some_attribute = property(_get, _set)
s = SubClass(spec_set=SubClass)
self.assertEqual(s.some_attribute, 3)
def test():
s.some_attribute = 3
self.assertRaises(NameError, test)
def test():
s.foo = 'bar'
self.assertRaises(AttributeError, test)
def test_setting_call(self):
mock = Mock()
def __call__(self, a):
return self._mock_call(a)
type(mock).__call__ = __call__
mock('one')
mock.assert_called_with('one')
self.assertRaises(TypeError, mock, 'one', 'two')
@unittest2.skipUnless(sys.version_info[:2] >= (2, 6),
"__dir__ not available until Python 2.6 or later")
def test_dir(self):
mock = Mock()
attrs = set(dir(mock))
type_attrs = set([m for m in dir(Mock) if not m.startswith('_')])
# all public attributes from the type are included
self.assertEqual(set(), type_attrs - attrs)
# creates these attributes
mock.a, mock.b
self.assertIn('a', dir(mock))
self.assertIn('b', dir(mock))
# instance attributes
mock.c = mock.d = None
self.assertIn('c', dir(mock))
self.assertIn('d', dir(mock))
# magic methods
mock.__iter__ = lambda s: iter([])
self.assertIn('__iter__', dir(mock))
@unittest2.skipUnless(sys.version_info[:2] >= (2, 6),
"__dir__ not available until Python 2.6 or later")
def test_dir_from_spec(self):
mock = Mock(spec=unittest2.TestCase)
testcase_attrs = set(dir(unittest2.TestCase))
attrs = set(dir(mock))
# all attributes from the spec are included
self.assertEqual(set(), testcase_attrs - attrs)
# shadow a sys attribute
mock.version = 3
self.assertEqual(dir(mock).count('version'), 1)
@unittest2.skipUnless(sys.version_info[:2] >= (2, 6),
"__dir__ not available until Python 2.6 or later")
def test_filter_dir(self):
patcher = patch.object(mock, 'FILTER_DIR', False)
patcher.start()
try:
attrs = set(dir(Mock()))
type_attrs = set(dir(Mock))
# ALL attributes from the type are included
self.assertEqual(set(), type_attrs - attrs)
finally:
patcher.stop()
def test_configure_mock(self):
mock = Mock(foo='bar')
self.assertEqual(mock.foo, 'bar')
mock = MagicMock(foo='bar')
self.assertEqual(mock.foo, 'bar')
kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
'foo': MagicMock()}
mock = Mock(**kwargs)
self.assertRaises(KeyError, mock)
self.assertEqual(mock.foo.bar(), 33)
self.assertIsInstance(mock.foo, MagicMock)
mock = Mock()
mock.configure_mock(**kwargs)
self.assertRaises(KeyError, mock)
self.assertEqual(mock.foo.bar(), 33)
self.assertIsInstance(mock.foo, MagicMock)
def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs):
# needed because assertRaisesRegex doesn't work easily with newlines
try:
func(*args, **kwargs)
except:
instance = sys.exc_info()[1]
self.assertIsInstance(instance, exception)
else:
self.fail('Exception %r not raised' % (exception,))
msg = str(instance)
self.assertEqual(msg, message)
def test_assert_called_with_failure_message(self):
mock = NonCallableMock()
expected = "mock(1, '2', 3, bar='foo')"
message = 'Expected call: %s\nNot called'
self.assertRaisesWithMsg(
AssertionError, message % (expected,),
mock.assert_called_with, 1, '2', 3, bar='foo'
)
mock.foo(1, '2', 3, foo='foo')
asserters = [
mock.foo.assert_called_with, mock.foo.assert_called_once_with
]
for meth in asserters:
actual = "foo(1, '2', 3, foo='foo')"
expected = "foo(1, '2', 3, bar='foo')"
message = 'Expected call: %s\nActual call: %s'
self.assertRaisesWithMsg(
AssertionError, message % (expected, actual),
meth, 1, '2', 3, bar='foo'
)
# just kwargs
for meth in asserters:
actual = "foo(1, '2', 3, foo='foo')"
expected = "foo(bar='foo')"
message = 'Expected call: %s\nActual call: %s'
self.assertRaisesWithMsg(
AssertionError, message % (expected, actual),
meth, bar='foo'
)
# just args
for meth in asserters:
actual = "foo(1, '2', 3, foo='foo')"
expected = "foo(1, 2, 3)"
message = 'Expected call: %s\nActual call: %s'
self.assertRaisesWithMsg(
AssertionError, message % (expected, actual),
meth, 1, 2, 3
)
# empty
for meth in asserters:
actual = "foo(1, '2', 3, foo='foo')"
expected = "foo()"
message = 'Expected call: %s\nActual call: %s'
self.assertRaisesWithMsg(
AssertionError, message % (expected, actual), meth
)
def test_mock_calls(self):
mock = MagicMock()
# need to do this because MagicMock.mock_calls used to just return
# a MagicMock which also returned a MagicMock when __eq__ was called
self.assertIs(mock.mock_calls == [], True)
mock = MagicMock()
mock()
expected = [('', (), {})]
self.assertEqual(mock.mock_calls, expected)
mock.foo()
expected.append(call.foo())
self.assertEqual(mock.mock_calls, expected)
# intermediate mock_calls work too
self.assertEqual(mock.foo.mock_calls, [('', (), {})])
mock = MagicMock()
mock().foo(1, 2, 3, a=4, b=5)
expected = [
('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))
]
self.assertEqual(mock.mock_calls, expected)
self.assertEqual(mock.return_value.foo.mock_calls,
[('', (1, 2, 3), dict(a=4, b=5))])
self.assertEqual(mock.return_value.mock_calls,
[('foo', (1, 2, 3), dict(a=4, b=5))])
mock = MagicMock()
mock().foo.bar().baz()
expected = [
('', (), {}), ('().foo.bar', (), {}),
('().foo.bar().baz', (), {})
]
self.assertEqual(mock.mock_calls, expected)
self.assertEqual(mock().mock_calls,
call.foo.bar().baz().call_list())
for kwargs in dict(), dict(name='bar'):
mock = MagicMock(**kwargs)
int(mock.foo)
expected = [('foo.__int__', (), {})]
self.assertEqual(mock.mock_calls, expected)
mock = MagicMock(**kwargs)
mock.a()()
expected = [('a', (), {}), ('a()', (), {})]
self.assertEqual(mock.mock_calls, expected)
self.assertEqual(mock.a().mock_calls, [call()])
mock = MagicMock(**kwargs)
mock(1)(2)(3)
self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list())
self.assertEqual(mock().mock_calls, call(2)(3).call_list())
self.assertEqual(mock()().mock_calls, call(3).call_list())
mock = MagicMock(**kwargs)
mock(1)(2)(3).a.b.c(4)
self.assertEqual(mock.mock_calls,
call(1)(2)(3).a.b.c(4).call_list())
self.assertEqual(mock().mock_calls,
call(2)(3).a.b.c(4).call_list())
self.assertEqual(mock()().mock_calls,
call(3).a.b.c(4).call_list())
mock = MagicMock(**kwargs)
int(mock().foo.bar().baz())
last_call = ('().foo.bar().baz().__int__', (), {})
self.assertEqual(mock.mock_calls[-1], last_call)
self.assertEqual(mock().mock_calls,
call.foo.bar().baz().__int__().call_list())
self.assertEqual(mock().foo.bar().mock_calls,
call.baz().__int__().call_list())
self.assertEqual(mock().foo.bar().baz.mock_calls,
call().__int__().call_list())
def test_subclassing(self):
class Subclass(Mock):
pass
mock = Subclass()
self.assertIsInstance(mock.foo, Subclass)
self.assertIsInstance(mock(), Subclass)
class Subclass(Mock):
def _get_child_mock(self, **kwargs):
return Mock(**kwargs)
mock = Subclass()
self.assertNotIsInstance(mock.foo, Subclass)
self.assertNotIsInstance(mock(), Subclass)
def test_arg_lists(self):
mocks = [
Mock(),
MagicMock(),
NonCallableMock(),
NonCallableMagicMock()
]
def assert_attrs(mock):
names = 'call_args_list', 'method_calls', 'mock_calls'
for name in names:
attr = getattr(mock, name)
self.assertIsInstance(attr, _CallList)
self.assertIsInstance(attr, list)
self.assertEqual(attr, [])
for mock in mocks:
assert_attrs(mock)
if callable(mock):
mock()
mock(1, 2)
mock(a=3)
mock.reset_mock()
assert_attrs(mock)
mock.foo()
mock.foo.bar(1, a=3)
mock.foo(1).bar().baz(3)
mock.reset_mock()
assert_attrs(mock)
def test_call_args_two_tuple(self):
mock = Mock()
mock(1, a=3)
mock(2, b=4)
self.assertEqual(len(mock.call_args), 2)
args, kwargs = mock.call_args
self.assertEqual(args, (2,))
self.assertEqual(kwargs, dict(b=4))
expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
for expected, call_args in zip(expected_list, mock.call_args_list):
self.assertEqual(len(call_args), 2)
self.assertEqual(expected[0], call_args[0])
self.assertEqual(expected[1], call_args[1])
def test_side_effect_iterator(self):
mock = Mock(side_effect=iter([1, 2, 3]))
self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
self.assertRaises(StopIteration, mock)
mock = MagicMock(side_effect=['a', 'b', 'c'])
self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
self.assertRaises(StopIteration, mock)
mock = Mock(side_effect='ghi')
self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
self.assertRaises(StopIteration, mock)
class Foo(object):
pass
mock = MagicMock(side_effect=Foo)
self.assertIsInstance(mock(), Foo)
mock = Mock(side_effect=Iter())
self.assertEqual([mock(), mock(), mock(), mock()],
['this', 'is', 'an', 'iter'])
self.assertRaises(StopIteration, mock)
def test_side_effect_setting_iterator(self):
mock = Mock()
mock.side_effect = iter([1, 2, 3])
self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
self.assertRaises(StopIteration, mock)
side_effect = mock.side_effect
self.assertIsInstance(side_effect, type(iter([])))
mock.side_effect = ['a', 'b', 'c']
self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
self.assertRaises(StopIteration, mock)
side_effect = mock.side_effect
self.assertIsInstance(side_effect, type(iter([])))
this_iter = Iter()
mock.side_effect = this_iter
self.assertEqual([mock(), mock(), mock(), mock()],
['this', 'is', 'an', 'iter'])
self.assertRaises(StopIteration, mock)
self.assertIs(mock.side_effect, this_iter)
def test_side_effect_iterator_exceptions(self):
for Klass in Mock, MagicMock:
iterable = (ValueError, 3, KeyError, 6)
m = Klass(side_effect=iterable)
self.assertRaises(ValueError, m)
self.assertEqual(m(), 3)
self.assertRaises(KeyError, m)
self.assertEqual(m(), 6)
def test_assert_has_calls_any_order(self):
mock = Mock()
mock(1, 2)
mock(a=3)
mock(3, 4)
mock(b=6)
mock(b=6)
kalls = [
call(1, 2), ({'a': 3},),
((3, 4),), ((), {'a': 3}),
('', (1, 2)), ('', {'a': 3}),
('', (1, 2), {}), ('', (), {'a': 3})
]
for kall in kalls:
mock.assert_has_calls([kall], any_order=True)
for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
self.assertRaises(
AssertionError, mock.assert_has_calls,
[kall], any_order=True
)
kall_lists = [
[call(1, 2), call(b=6)],
[call(3, 4), call(1, 2)],
[call(b=6), call(b=6)],
]
for kall_list in kall_lists:
mock.assert_has_calls(kall_list, any_order=True)
kall_lists = [
[call(b=6), call(b=6), call(b=6)],
[call(1, 2), call(1, 2)],
[call(3, 4), call(1, 2), call(5, 7)],
[call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
]
for kall_list in kall_lists:
self.assertRaises(
AssertionError, mock.assert_has_calls,
kall_list, any_order=True
)
def test_assert_has_calls(self):
kalls1 = [
call(1, 2), ({'a': 3},),
((3, 4),), call(b=6),
('', (1,), {'b': 6}),
]
kalls2 = [call.foo(), call.bar(1)]
kalls2.extend(call.spam().baz(a=3).call_list())
kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
mocks = []
for mock in Mock(), MagicMock():
mock(1, 2)
mock(a=3)
mock(3, 4)
mock(b=6)
mock(1, b=6)
mocks.append((mock, kalls1))
mock = Mock()
mock.foo()
mock.bar(1)
mock.spam().baz(a=3)
mock.bam(set(), foo={}).fish([1])
mocks.append((mock, kalls2))
for mock, kalls in mocks:
for i in range(len(kalls)):
for step in 1, 2, 3:
these = kalls[i:i+step]
mock.assert_has_calls(these)
if len(these) > 1:
self.assertRaises(
AssertionError,
mock.assert_has_calls,
list(reversed(these))
)
def test_assert_any_call(self):
mock = Mock()
mock(1, 2)
mock(a=3)
mock(1, b=6)
mock.assert_any_call(1, 2)
mock.assert_any_call(a=3)
mock.assert_any_call(1, b=6)
self.assertRaises(
AssertionError,
mock.assert_any_call
)
self.assertRaises(
AssertionError,
mock.assert_any_call,
1, 3
)
self.assertRaises(
AssertionError,
mock.assert_any_call,
a=4
)
def test_mock_calls_create_autospec(self):
def f(a, b):
pass
obj = Iter()
obj.f = f
funcs = [
create_autospec(f),
create_autospec(obj).f
]
for func in funcs:
func(1, 2)
func(3, 4)
self.assertEqual(
func.mock_calls, [call(1, 2), call(3, 4)]
)
def test_mock_add_spec(self):
class _One(object):
one = 1
class _Two(object):
two = 2
class Anything(object):
one = two = three = 'four'
klasses = [
Mock, MagicMock, NonCallableMock, NonCallableMagicMock
]
for Klass in list(klasses):
klasses.append(lambda K=Klass: K(spec=Anything))
klasses.append(lambda K=Klass: K(spec_set=Anything))
for Klass in klasses:
for kwargs in dict(), dict(spec_set=True):
mock = Klass()
#no error
mock.one, mock.two, mock.three
for One, Two in [(_One, _Two), (['one'], ['two'])]:
for kwargs in dict(), dict(spec_set=True):
mock.mock_add_spec(One, **kwargs)
mock.one
self.assertRaises(
AttributeError, getattr, mock, 'two'
)
self.assertRaises(
AttributeError, getattr, mock, 'three'
)
if 'spec_set' in kwargs:
self.assertRaises(
AttributeError, setattr, mock, 'three', None
)
mock.mock_add_spec(Two, **kwargs)
self.assertRaises(
AttributeError, getattr, mock, 'one'
)
mock.two
self.assertRaises(
AttributeError, getattr, mock, 'three'
)
if 'spec_set' in kwargs:
self.assertRaises(
AttributeError, setattr, mock, 'three', None
)
# note that creating a mock, setting an instance attribute, and
# *then* setting a spec doesn't work. Not the intended use case
def test_mock_add_spec_magic_methods(self):
for Klass in MagicMock, NonCallableMagicMock:
mock = Klass()
int(mock)
mock.mock_add_spec(object)
self.assertRaises(TypeError, int, mock)
mock = Klass()
mock['foo']
mock.__int__.return_value =4
mock.mock_add_spec(int)
self.assertEqual(int(mock), 4)
self.assertRaises(TypeError, lambda: mock['foo'])
def test_adding_child_mock(self):
for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock:
mock = Klass()
mock.foo = Mock()
mock.foo()
self.assertEqual(mock.method_calls, [call.foo()])
self.assertEqual(mock.mock_calls, [call.foo()])
mock = Klass()
mock.bar = Mock(name='name')
mock.bar()
self.assertEqual(mock.method_calls, [])
self.assertEqual(mock.mock_calls, [])
# mock with an existing _new_parent but no name
mock = Klass()
mock.baz = MagicMock()()
mock.baz()
self.assertEqual(mock.method_calls, [])
self.assertEqual(mock.mock_calls, [])
def test_adding_return_value_mock(self):
for Klass in Mock, MagicMock:
mock = Klass()
mock.return_value = MagicMock()
mock()()
self.assertEqual(mock.mock_calls, [call(), call()()])
def test_manager_mock(self):
class Foo(object):
one = 'one'
two = 'two'
manager = Mock()
p1 = patch.object(Foo, 'one')
p2 = patch.object(Foo, 'two')
mock_one = p1.start()
self.addCleanup(p1.stop)
mock_two = p2.start()
self.addCleanup(p2.stop)
manager.attach_mock(mock_one, 'one')
manager.attach_mock(mock_two, 'two')
Foo.two()
Foo.one()
self.assertEqual(manager.mock_calls, [call.two(), call.one()])
def test_magic_methods_mock_calls(self):
for Klass in Mock, MagicMock:
m = Klass()
m.__int__ = Mock(return_value=3)
m.__float__ = MagicMock(return_value=3.0)
int(m)
float(m)
self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
self.assertEqual(m.method_calls, [])
def test_attribute_deletion(self):
# this behaviour isn't *useful*, but at least it's now tested...
for Klass in Mock, MagicMock, NonCallableMagicMock, NonCallableMock:
m = Klass()
original = m.foo
m.foo = 3
del m.foo
self.assertEqual(m.foo, original)
new = m.foo = Mock()
del m.foo
self.assertEqual(m.foo, new)
def test_mock_parents(self):
for Klass in Mock, MagicMock:
m = Klass()
original_repr = repr(m)
m.return_value = m
self.assertIs(m(), m)
self.assertEqual(repr(m), original_repr)
m.reset_mock()
self.assertIs(m(), m)
self.assertEqual(repr(m), original_repr)
m = Klass()
m.b = m.a
self.assertIn("name='mock.a'", repr(m.b))
self.assertIn("name='mock.a'", repr(m.a))
m.reset_mock()
self.assertIn("name='mock.a'", repr(m.b))
self.assertIn("name='mock.a'", repr(m.a))
m = Klass()
original_repr = repr(m)
m.a = m()
m.a.return_value = m
self.assertEqual(repr(m), original_repr)
self.assertEqual(repr(m.a()), original_repr)
def test_attach_mock(self):
classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
for Klass in classes:
for Klass2 in classes:
m = Klass()
m2 = Klass2(name='foo')
m.attach_mock(m2, 'bar')
self.assertIs(m.bar, m2)
self.assertIn("name='mock.bar'", repr(m2))
m.bar.baz(1)
self.assertEqual(m.mock_calls, [call.bar.baz(1)])
self.assertEqual(m.method_calls, [call.bar.baz(1)])
def test_attach_mock_return_value(self):
classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
for Klass in Mock, MagicMock:
for Klass2 in classes:
m = Klass()
m2 = Klass2(name='foo')
m.attach_mock(m2, 'return_value')
self.assertIs(m(), m2)
self.assertIn("name='mock()'", repr(m2))
m2.foo()
self.assertEqual(m.mock_calls, call().foo().call_list())
def test_attribute_deletion(self):
for mock in Mock(), MagicMock():
self.assertTrue(hasattr(mock, 'm'))
del mock.m
self.assertFalse(hasattr(mock, 'm'))
del mock.f
self.assertFalse(hasattr(mock, 'f'))
self.assertRaises(AttributeError, getattr, mock, 'f')
def test_class_assignable(self):
for mock in Mock(), MagicMock():
self.assertNotIsInstance(mock, int)
mock.__class__ = int
self.assertIsInstance(mock, int)
@unittest2.expectedFailure
def test_pickle(self):
for Klass in (MagicMock, Mock, Subclass, NonCallableMagicMock):
mock = Klass(name='foo', attribute=3)
mock.foo(1, 2, 3)
data = pickle.dumps(mock)
new = pickle.loads(data)
new.foo.assert_called_once_with(1, 2, 3)
self.assertFalse(new.called)
self.assertTrue(is_instance(new, Klass))
self.assertIsInstance(new, Thing)
self.assertIn('name="foo"', repr(new))
self.assertEqual(new.attribute, 3)
if __name__ == '__main__':
unittest2.main()
| {
"pile_set_name": "Github"
} |
// Copyright 2016 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.
package ipv6
import (
"net"
"syscall"
"unsafe"
"golang.org/x/net/internal/iana"
"golang.org/x/net/internal/socket"
)
var (
ctlOpts = [ctlMax]ctlOpt{
ctlTrafficClass: {sysIPV6_TCLASS, 4, marshalTrafficClass, parseTrafficClass},
ctlHopLimit: {sysIPV6_HOPLIMIT, 4, marshalHopLimit, parseHopLimit},
ctlPacketInfo: {sysIPV6_PKTINFO, sizeofInet6Pktinfo, marshalPacketInfo, parsePacketInfo},
ctlNextHop: {sysIPV6_NEXTHOP, sizeofSockaddrInet6, marshalNextHop, parseNextHop},
ctlPathMTU: {sysIPV6_PATHMTU, sizeofIPv6Mtuinfo, marshalPathMTU, parsePathMTU},
}
sockOpts = map[int]*sockOpt{
ssoTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_TCLASS, Len: 4}},
ssoHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_UNICAST_HOPS, Len: 4}},
ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_IF, Len: 4}},
ssoMulticastHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_HOPS, Len: 4}},
ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_LOOP, Len: 4}},
ssoReceiveTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVTCLASS, Len: 4}},
ssoReceiveHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVHOPLIMIT, Len: 4}},
ssoReceivePacketInfo: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPKTINFO, Len: 4}},
ssoReceivePathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPATHMTU, Len: 4}},
ssoPathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_PATHMTU, Len: sizeofIPv6Mtuinfo}},
ssoChecksum: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_CHECKSUM, Len: 4}},
ssoICMPFilter: {Option: socket.Option{Level: iana.ProtocolIPv6ICMP, Name: sysICMP6_FILTER, Len: sizeofICMPv6Filter}},
ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq},
ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq},
ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
}
)
func (sa *sockaddrInet6) setSockaddr(ip net.IP, i int) {
sa.Family = syscall.AF_INET6
copy(sa.Addr[:], ip)
sa.Scope_id = uint32(i)
}
func (pi *inet6Pktinfo) setIfindex(i int) {
pi.Ifindex = uint32(i)
}
func (mreq *ipv6Mreq) setIfindex(i int) {
mreq.Interface = uint32(i)
}
func (gr *groupReq) setGroup(grp net.IP) {
sa := (*sockaddrInet6)(unsafe.Pointer(uintptr(unsafe.Pointer(gr)) + 4))
sa.Family = syscall.AF_INET6
copy(sa.Addr[:], grp)
}
func (gsr *groupSourceReq) setSourceGroup(grp, src net.IP) {
sa := (*sockaddrInet6)(unsafe.Pointer(uintptr(unsafe.Pointer(gsr)) + 4))
sa.Family = syscall.AF_INET6
copy(sa.Addr[:], grp)
sa = (*sockaddrInet6)(unsafe.Pointer(uintptr(unsafe.Pointer(gsr)) + 260))
sa.Family = syscall.AF_INET6
copy(sa.Addr[:], src)
}
| {
"pile_set_name": "Github"
} |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * website_sale_product_configurator
#
# Translators:
# Mikel Lizarralde <[email protected]>, 2020
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server saas~12.4\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-08-12 11:33+0000\n"
"PO-Revision-Date: 2019-08-26 09:16+0000\n"
"Last-Translator: Mikel Lizarralde <[email protected]>, 2020\n"
"Language-Team: Basque (https://www.transifex.com/odoo/teams/41243/eu/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Language: eu\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#. module: website_sale_product_configurator
#. openerp-web
#: code:addons/website_sale_product_configurator/static/src/js/website_sale_options.js:26
#, python-format
msgid "Add to cart"
msgstr ""
#. module: website_sale_product_configurator
#. openerp-web
#: code:addons/website_sale_product_configurator/static/src/js/website_sale_options.js:25
#, python-format
msgid "Continue Shopping"
msgstr ""
#. module: website_sale_product_configurator
#. openerp-web
#: code:addons/website_sale_product_configurator/static/src/js/website_sale_options.js:24
#, python-format
msgid "Proceed to Checkout"
msgstr ""
#. module: website_sale_product_configurator
#: model:ir.model,name:website_sale_product_configurator.model_sale_order
msgid "Sales Order"
msgstr "Salmenta-eskaera"
| {
"pile_set_name": "Github"
} |
===================================
Example project for django-tagulous
===================================
This example project is configured for Django 2.2.
You can see a static demo version of this example app at http://radiac.net/projects/django-tagulous/demo/
To set it up and run the live version in a self-contained virtualenv::
virtualenv tagulous-example
cd tagulous-example
source bin/activate
pip install "Django>=2.2,<2.3"
pip install -e git+https://github.com/radiac/django-tagulous.git#egg=django-tagulous
cd src/django-tagulous/example
python manage.py migrate
python manage.py createsuperuser
python manage.py initial_tags
python manage.py runserver
You can then visit the example site at http://localhost:8000/
| {
"pile_set_name": "Github"
} |
// Copyright 2009 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 darwin dragonfly freebsd linux netbsd openbsd solaris
// Package unix contains an interface to the low-level operating system
// primitives. OS details vary depending on the underlying system, and
// by default, godoc will display OS-specific documentation for the current
// system. If you want godoc to display OS documentation for another
// system, set $GOOS and $GOARCH to the desired system. For example, if
// you want to view documentation for freebsd/arm on linux/amd64, set $GOOS
// to freebsd and $GOARCH to arm.
//
// The primary use of this package is inside other packages that provide a more
// portable interface to the system, such as "os", "time" and "net". Use
// those packages rather than this one if you can.
//
// For details of the functions and data types in this package consult
// the manuals for the appropriate operating system.
//
// These calls return err == nil to indicate success; otherwise
// err represents an operating system error describing the failure and
// holds a value of type syscall.Errno.
package unix // import "golang.org/x/sys/unix"
import "strings"
// ByteSliceFromString returns a NUL-terminated slice of bytes
// containing the text of s. If s contains a NUL byte at any
// location, it returns (nil, EINVAL).
func ByteSliceFromString(s string) ([]byte, error) {
if strings.IndexByte(s, 0) != -1 {
return nil, EINVAL
}
a := make([]byte, len(s)+1)
copy(a, s)
return a, nil
}
// BytePtrFromString returns a pointer to a NUL-terminated array of
// bytes containing the text of s. If s contains a NUL byte at any
// location, it returns (nil, EINVAL).
func BytePtrFromString(s string) (*byte, error) {
a, err := ByteSliceFromString(s)
if err != nil {
return nil, err
}
return &a[0], nil
}
// Single-word zero for use when we need a valid pointer to 0 bytes.
// See mkunix.pl.
var _zero uintptr
| {
"pile_set_name": "Github"
} |
/**
* @file hilbert_r_tree_split.hpp
* @author Mikhail Lozhnikov
*
* Definition of the HilbertRTreeSplit class, a class that splits the nodes of an R
* tree, starting at a leaf node and moving upwards if necessary.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_HILBERT_R_TREE_SPLIT_HPP
#define MLPACK_CORE_TREE_RECTANGLE_TREE_HILBERT_R_TREE_SPLIT_HPP
#include <mlpack/prereqs.hpp>
namespace mlpack {
namespace tree /** Trees and tree-building procedures. */ {
/**
* The splitting procedure for the Hilbert R tree. The template parameter
* splitOrder is the order of the splitting policy. The Hilbert R tree splits a
* node on overflow, turning splitOrder nodes into (splitOrder + 1) nodes.
*
* @tparam splitOrder Number of nodes to split.
*/
template<size_t splitOrder = 2>
class HilbertRTreeSplit
{
public:
/**
* Split a leaf node using the "default" algorithm. If necessary, this split
* will propagate upwards through the tree.
*
* @param node The node that is being split.
* @param relevels Not used.
*/
template<typename TreeType>
static void SplitLeafNode(TreeType* tree, std::vector<bool>& relevels);
/**
* Split a non-leaf node using the "default" algorithm. If this is a root
* node, the tree increases in depth.
*
* @param node The node that is being split.
* @param relevels Not used.
*/
template<typename TreeType>
static bool SplitNonLeafNode(TreeType* tree, std::vector<bool>& relevels);
private:
/**
* Try to find splitOrder cooperating siblings in order to redistribute their
* children evenly. Returns true on success.
*
* @param parent The parent of of the overflowing node.
* @param iTree The number of the overflowing node.
* @param firstSibling The first cooperating sibling.
* @param lastSibling The last cooperating sibling.
*/
template<typename TreeType>
static bool FindCooperatingSiblings(TreeType* parent,
const size_t iTree,
size_t& firstSibling,
size_t& lastSibling);
/**
* Redistribute the children of the cooperating siblings evenly among them.
*
* @param parent The parent of of the overflowing node.
* @param firstSibling The first cooperating sibling.
* @param lastSibling The last cooperating sibling.
*/
template<typename TreeType>
static void RedistributeNodesEvenly(const TreeType* parent,
const size_t firstSibling,
const size_t lastSibling);
/**
* Redistribute the points of the cooperating siblings evenly among them.
*
* @param parent The parent of of the overflowing node.
* @param firstSibling The first cooperating sibling.
* @param lastSibling The last cooperating sibling.
*/
template<typename TreeType>
static void RedistributePointsEvenly(TreeType* parent,
const size_t firstSibling,
const size_t lastSibling);
};
} // namespace tree
} // namespace mlpack
// Include implementation.
#include "hilbert_r_tree_split_impl.hpp"
#endif
| {
"pile_set_name": "Github"
} |
{
"author": {
"name": "Chad Brown",
"email": "[email protected]",
"url": "https://www.json2html.com"
},
"name": "node-json2html",
"description": "json2html - Pure Javascript HTML Templating",
"version": "1.4.1",
"homepage": "https://www.json2html.com",
"repository": {
"url": "git://github.com/moappi/json2html.git"
},
"keywords": [
"json2html",
"templating",
"html",
"web",
"templates",
"transforms",
"json"
],
"main": "node.json2html.js",
"dependencies": {},
"devDependencies": {},
"optionalDependencies": {},
"engines": {
"node": "*"
}
} | {
"pile_set_name": "Github"
} |
/* $Id: thread2-r0drv-solaris.c $ */
/** @file
* IPRT - Threads (Part 2), Ring-0 Driver, Solaris.
*/
/*
* Copyright (C) 2006-2007 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#include "the-solaris-kernel.h"
#include "internal/iprt.h"
#include <iprt/thread.h>
#include <iprt/process.h>
#include <iprt/assert.h>
#include <iprt/err.h>
#include "internal/thread.h"
DECLHIDDEN(int) rtThreadNativeInit(void)
{
return VINF_SUCCESS;
}
RTDECL(RTTHREAD) RTThreadSelf(void)
{
return rtThreadGetByNative(RTThreadNativeSelf());
}
DECLHIDDEN(int) rtThreadNativeSetPriority(PRTTHREADINT pThread, RTTHREADTYPE enmType)
{
int iPriority;
switch (enmType)
{
case RTTHREADTYPE_INFREQUENT_POLLER: iPriority = 60; break;
case RTTHREADTYPE_EMULATION: iPriority = 66; break;
case RTTHREADTYPE_DEFAULT: iPriority = 72; break;
case RTTHREADTYPE_MSG_PUMP: iPriority = 78; break;
case RTTHREADTYPE_IO: iPriority = 84; break;
case RTTHREADTYPE_TIMER: iPriority = 99; break;
default:
AssertMsgFailed(("enmType=%d\n", enmType));
return VERR_INVALID_PARAMETER;
}
kthread_t *pCurThread = curthread;
Assert(pCurThread);
thread_lock(pCurThread);
thread_change_pri(pCurThread, iPriority, 0);
thread_unlock(pCurThread);
return VINF_SUCCESS;
}
DECLHIDDEN(int) rtThreadNativeAdopt(PRTTHREADINT pThread)
{
NOREF(pThread);
/* There is nothing special that needs doing here, but the
user really better know what he's cooking. */
return VINF_SUCCESS;
}
DECLHIDDEN(void) rtThreadNativeDestroy(PRTTHREADINT pThread)
{
NOREF(pThread);
}
/**
* Native thread main function.
*
* @param pvThreadInt The thread structure.
*/
static void rtThreadNativeMain(void *pvThreadInt)
{
PRTTHREADINT pThreadInt = (PRTTHREADINT)pvThreadInt;
rtThreadMain(pThreadInt, RTThreadNativeSelf(), &pThreadInt->szName[0]);
thread_exit();
}
DECLHIDDEN(int) rtThreadNativeCreate(PRTTHREADINT pThreadInt, PRTNATIVETHREAD pNativeThread)
{
RT_ASSERT_PREEMPTIBLE();
kthread_t *pThread = thread_create(NULL, /* Stack, use base */
0, /* Stack size */
rtThreadNativeMain, /* Thread function */
pThreadInt, /* Function data */
sizeof(pThreadInt), /* Data size */
(proc_t *)RTR0ProcHandleSelf(), /* Process handle */
TS_RUN, /* Ready to run */
minclsyspri /* Priority */
);
if (RT_LIKELY(pThread))
{
*pNativeThread = (RTNATIVETHREAD)pThread;
return VINF_SUCCESS;
}
return VERR_OUT_OF_RESOURCES;
}
| {
"pile_set_name": "Github"
} |
**Are you the copyright holder or authorized to act on the copyright owner's behalf?**
Yes, I am the copyright holder.
**Please describe the nature of your copyright ownership or authorization to act on the owner's behalf.**
We, Lineto GmbH, are the copyright owner of the font LL Circular.
**Please provide a detailed description of the original copyrighted work that has allegedly been infringed. If possible, include a URL to where it is posted online.**
We are a Swiss Typefoundry and the owner and sole distributer of LL Circular:
https://lineto.com/typefaces/circular?font=S4DwQnOmyEZ&text=%0A&tab=about
The Font is available as a free download on Github: https://github.com/kindweb223/angular2-skillsnap/tree/2af393848d9f012bf412f2d0c42beeb458e7e70d/assets/fonts/circular-std
**What files should be taken down? Please provide URLs for each file, or if the entire repository, the repository’s URL.**
All font files need to be immediately removed:
https://github.com/kindweb223/angular2-skillsnap/blob/2af393848d9f012bf412f2d0c42beeb458e7e70d/assets/fonts/circular-std/circular-std-medium.woff
https://github.com/kindweb223/angular2-skillsnap/blob/2af393848d9f012bf412f2d0c42beeb458e7e70d/assets/fonts/circular-std/circular-std-medium.otf
https://github.com/kindweb223/angular2-skillsnap/blob/2af393848d9f012bf412f2d0c42beeb458e7e70d/assets/fonts/circular-std/circular-std-book.woff
https://github.com/kindweb223/angular2-skillsnap/blob/2af393848d9f012bf412f2d0c42beeb458e7e70d/assets/fonts/circular-std/circular-std-book.otf
https://github.com/kindweb223/angular2-skillsnap/blob/2af393848d9f012bf412f2d0c42beeb458e7e70d/assets/fonts/circular-std/circular-std-bold.woff
https://github.com/kindweb223/angular2-skillsnap/blob/2af393848d9f012bf412f2d0c42beeb458e7e70d/assets/fonts/circular-std/circular-std-bold.otf
**Have you searched for any forks of the allegedly infringing files or repositories? Each fork is a distinct repository and must be identified separately if you believe it is infringing and wish to have it taken down.**
I haven't found any additional forks.
**Is the work licensed under an open source license? If so, which open source license? Are the allegedly infringing files being used under the open source license, or are they in violation of the license?**
No
**What would be the best solution for the alleged infringement? Are there specific changes the other person can make other than removal? Can the repository be made private?**
No, this is copyrighted software and distribution for free is damaging and threatening our small business.
**Do you have the alleged infringer’s contact information? If so, please provide it.**
No
**I have a good faith belief that use of the copyrighted materials described above on the infringing web pages is not authorized by the copyright owner, or its agent, or the law.**
**I have taken <a href="https://www.lumendatabase.org/topics/22">fair use</a> into consideration.**
**I swear, under penalty of perjury, that the information in this notification is accurate and that I am the copyright owner, or am authorized to act on behalf of the owner, of an exclusive right that is allegedly infringed.**
**I have read and understand GitHub's <a href="https://help.github.com/articles/guide-to-submitting-a-dmca-takedown-notice/">Guide to Submitting a DMCA Takedown Notice</a>.**
**So that we can get back to you, please provide either your telephone number or physical address.**
[private]
**Please type your full legal name below to sign this request.**
[private]
| {
"pile_set_name": "Github"
} |
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/SAObjects.framework/SAObjects
*/
@interface SAUTSLiveStreamingViewingContext : SAUTSViewingContext
@property (nonatomic, copy) NSDate *eventStartTime;
@property (nonatomic) bool watchingLive;
+ (id)liveStreamingViewingContext;
+ (id)liveStreamingViewingContextWithDictionary:(id)arg1 context:(id)arg2;
- (id)encodedClassName;
- (id)eventStartTime;
- (id)groupIdentifier;
- (void)setEventStartTime:(id)arg1;
- (void)setWatchingLive:(bool)arg1;
- (bool)watchingLive;
@end
| {
"pile_set_name": "Github"
} |
/******************************************************************************
* Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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.
******************************************************************************/
#pragma once
#include <mi/mdl_sdk.h>
#include <string>
#include <vector>
namespace i18n
{
/// Command class
class Command
{
private:
Command(const Command &); // prevent copy ctor
public:
Command() {}
virtual ~Command() {}
virtual int execute()=0;
};
/// Help command
///
class Help : public Command
{
std::string m_command;
public:
Help(const std::string & command)
: m_command(command)
{}
/// \return
/// - SUCCESS: Success
/// - UNSPECIFIED_FAILURE: Unspecified failure.
int execute();
};
/// Command class
class Option_set;
class Command_factory
{
public:
static Command * build_command(const Option_set & option);
};
} // namespace i18n
| {
"pile_set_name": "Github"
} |
{% extends "base.html" %}
{% block title %}{{ dtype.name }} – {{ project }} {% endblock title %}
{% block body %}
{% import 'macros.html' as macros %}
<div class="row">
<h1>{{ dtype.name }}
<small>Derived Type</small>
{% if dtype.meta['deprecated'] and dtype.meta['deprecated'].lower() == 'true' %}
<span class="label label-danger depwarn">Deprecated</span>
{% endif %}
</h1>
{{ macros.info_bar(dtype.name,dtype.meta,incl_src,project_url,dtype.hierarchy,dtype.lines_description(project.type_lines,project.type_lines_all)) }}
</div>
<div class="row">
<div class="col-md-3 hidden-xs hidden-sm visible-md visible-lg">
{{ macros.sidebar(project,dtype) }}
</div>
<div class="col-md-9" id='text'>
<h2>type{% if dtype.parobj == 'module' %}, {{ dtype.permission }}{% endif %}{% for attr in dtype.attributes%}, {{ attr }}{% endfor %}{% if dtype.extends %}, extends({{ dtype.extends }}){% endif %} :: {{ dtype.name }}{% if dtype.sequence%}<br>sequence{% endif %}</h2>
{{ dtype.doc }}
{% if dtype.inherbygraph or dtype.inhergraph %}<br>{% endif %}
{% if dtype.inhergraph %}
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Inherits</h3>
</div>
<div class="panel-body">
{{ dtype.inhergraph }}
</div>
</div>
{% endif %}
{% if dtype.inherbygraph %}
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Inherited by</h3>
</div>
<div class="panel-body">
{{ dtype.inherbygraph }}
</div>
</div>
{% endif %}
<br>
<section class="visible-xs visible-sm hidden-md">
{{ macros.content_list(dtype,1) }}
</section>
<br class="visible-xs visible-sm hidden-md">
{% if dtype.variables|length > 0 %}
<section>
<h2>Components</h2>
{{ macros.var_list(dtype.variables,permission=True) }}
</section>
<br>
{% endif %}
{% if dtype.constructor %}
<section>
<h2>Constructor</h2>
{% if dtype.constructor.obj == "interface" %}
{{ macros.interface(dtype.constructor) }}
{% elif dtype.constructor.obj == "subroutine" or dtype.constructor.obj == "function" %}
{% set obj = dtype.constructor %}
<div class="panel panel-default">
<div class="panel-heading codesum"><span class="anchor" id="{{ obj.anchor }}"></span><h3>{{ macros.proc_line(obj) }}</h3></div>
<div class="panel-body">
{{ macros.proc_summary(obj,False) }}
</div>
</div>
{% endif %}
</section>
<br>
{% endif %}
{% if dtype.finalprocs|length > 0 %}
<section>
<h2>Finalization Procedures</h2>
{% for proc in dtype.finalprocs %}
{{ macros.final(proc) }}
{% endfor %}
</section>
<br>
{% endif %}
{% if dtype.boundprocs|length > 0 %}
<section>
<h2>Type-Bound Procedures</h2>
{% for bp in dtype.boundprocs %}
{{ macros.bound_info(bp) }}
{% endfor %}
</section>
{% endif %}
{% if dtype.src %}
<section>
<h3><span class="anchor" id="src"></span>Source Code</h3>
{{ dtype.src }}
</section>
{% endif %}
</div>
</div>
{% endblock body %}
| {
"pile_set_name": "Github"
} |
# Copyright 2015 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'includes': [
'../third_party/icu/icu.isolate',
# MSVS runtime libraries.
'../gypfiles/win/msvs_dependencies.isolate',
],
'conditions': [
['v8_use_snapshot=="true" and v8_use_external_startup_data==1', {
'variables': {
'files': [
'<(PRODUCT_DIR)/natives_blob.bin',
'<(PRODUCT_DIR)/snapshot_blob.bin',
],
},
}],
['tsan==1', {
'variables': {
'files': [
'../tools/sanitizers/tsan_suppressions.txt',
],
},
}],
['OS=="linux" and (asan==1 or cfi_vptr==1 or msan==1 or tsan==1)', {
'variables': {
'files': [
# For llvm-symbolizer.
'../third_party/llvm-build/Release+Asserts/lib/libstdc++.so.6',
],
},
}],
['asan==1 or cfi_vptr==1 or msan==1 or tsan==1', {
'variables': {
'files': [
'../third_party/llvm-build/Release+Asserts/bin/llvm-symbolizer<(EXECUTABLE_SUFFIX)',
],
},
}],
# Workaround for https://code.google.com/p/swarming/issues/detail?id=211
['asan==0 or cfi_vptr==0 or msan==0 or tsan==0', {
'variables': {},
}],
],
}
| {
"pile_set_name": "Github"
} |
/***************************************************************************
* ARPHeader.h -- The ARPHeader Class represents an ARP packet. It *
* contains methods to set any header field. In general, these methods do *
* error checkings and byte order conversion. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2019 Insecure.Com LLC ("The Nmap *
* Project"). Nmap is also a registered trademark of the Nmap Project. *
* This program is free software; you may redistribute and/or modify it *
* under the terms of the GNU General Public License as published by the *
* Free Software Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE *
* CLARIFICATIONS AND EXCEPTIONS DESCRIBED HEREIN. This guarantees your *
* right to use, modify, and redistribute this software under certain *
* conditions. If you wish to embed Nmap technology into proprietary *
* software, we sell alternative licenses (contact [email protected]). *
* Dozens of software vendors already license Nmap technology such as *
* host discovery, port scanning, OS detection, version detection, and *
* the Nmap Scripting Engine. *
* *
* Note that the GPL places important restrictions on "derivative works", *
* yet it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we interpret that term as broadly as copyright law *
* allows. For example, we consider an application to constitute a *
* derivative work for the purpose of this license if it does any of the *
* following with any software or content covered by this license *
* ("Covered Software"): *
* *
* o Integrates source code from Covered Software. *
* *
* o Reads or includes copyrighted data files, such as Nmap's nmap-os-db *
* or nmap-service-probes. *
* *
* o Is designed specifically to execute Covered Software and parse the *
* results (as opposed to typical shell or execution-menu apps, which will *
* execute anything you tell them to). *
* *
* o Includes Covered Software in a proprietary executable installer. The *
* installers produced by InstallShield are an example of this. Including *
* Nmap with other software in compressed or archival form does not *
* trigger this provision, provided appropriate open source decompression *
* or de-archiving software is widely available for no charge. For the *
* purposes of this license, an installer is considered to include Covered *
* Software even if it actually retrieves a copy of Covered Software from *
* another source during runtime (such as by downloading it from the *
* Internet). *
* *
* o Links (statically or dynamically) to a library which does any of the *
* above. *
* *
* o Executes a helper program, module, or script to do any of the above. *
* *
* This list is not exclusive, but is meant to clarify our interpretation *
* of derived works with some common examples. Other people may interpret *
* the plain GPL differently, so we consider this a special exception to *
* the GPL that we apply to Covered Software. Works which meet any of *
* these conditions must conform to all of the terms of this license, *
* particularly including the GPL Section 3 requirements of providing *
* source code and allowing free redistribution of the work as a whole. *
* *
* As another special exception to the GPL terms, the Nmap Project grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. *
* *
* The Nmap Project has permission to redistribute Npcap, a packet *
* capturing driver and library for the Microsoft Windows platform. *
* Npcap is a separate work with it's own license rather than this Nmap *
* license. Since the Npcap license does not permit redistribution *
* without special permission, our Nmap Windows binary packages which *
* contain Npcap may not be redistributed without special permission. *
* *
* Any redistribution of Covered Software, including any derived works, *
* must obey and carry forward all of the terms of this license, including *
* obeying all GPL rules and restrictions. For example, source code of *
* the whole work must be provided and free redistribution must be *
* allowed. All GPL references to "this License", are to be treated as *
* including the terms and conditions of this license text as well. *
* *
* Because this license imposes special exceptions to the GPL, Covered *
* Work may not be combined (even as part of a larger work) with plain GPL *
* software. The terms, conditions, and exceptions of this license must *
* be included as well. This license is incompatible with some other open *
* source licenses as well. In some cases we can relicense portions of *
* Nmap or grant special permissions to use it in other open source *
* software. Please contact [email protected] with any such requests. *
* Similarly, we don't incorporate incompatible open source software into *
* Covered Software without special permission from the copyright holders. *
* *
* If you have any questions about the licensing restrictions on using *
* Nmap in other works, we are happy to help. As mentioned above, we also *
* offer an alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing support and updates. They also fund the continued *
* development of Nmap. Please email [email protected] for further *
* information. *
* *
* If you have received a written license agreement or contract for *
* Covered Software stating terms other than these, you may choose to use *
* and redistribute Covered Software under those terms instead of these. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes. *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to the [email protected] mailing list for possible incorporation into the *
* main distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, or checking them into the Nmap *
* source code repository, it is understood (unless you specify *
* otherwise) that you are offering the Nmap Project the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because *
* the inability to relicense code has caused devastating problems for *
* other Free Software projects (such as KDE and NASM). We also *
* occasionally relicense the code to third parties as discussed above. *
* If you wish to specify special license conditions of your *
* contributions, just say so when you send them. *
* *
* 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 Nmap *
* license file for more details (it's in a COPYING file included with *
* Nmap, and also available from https://svn.nmap.org/nmap/COPYING) *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef __ARPHEADER_H__
#define __ARPHEADER_H__ 1
#include "NetworkLayerElement.h"
/* Lengths */
#define ARP_HEADER_LEN 28
#define IPv4_ADDRESS_LEN 4
#define ETH_ADDRESS_LEN 6
/* Hardware Types */
#define HDR_RESERVED 0 /* [RFC5494] */
#define HDR_ETH10MB 1 /* Ethernet (10Mb) */
#define HDR_ETH3MB 2 /* Experimental Ethernet (3Mb) */
#define HDR_AX25 3 /* Amateur Radio AX.25 */
#define HDR_PRONET_TR 4 /* Proteon ProNET Token Ring */
#define HDR_CHAOS 5 /* Chaos */
#define HDR_IEEE802 6 /* IEEE 802 Networks */
#define HDR_ARCNET 7 /* ARCNET [RFC1201] */
#define HDR_HYPERCHANNEL 8 /* Hyperchannel */
#define HDR_LANSTAR 9 /* Lanstar */
#define HDR_AUTONET 10 /* Autonet Short Address */
#define HDR_LOCALTALK 11 /* LocalTalk */
#define HDR_LOCALNET 12 /* LocalNet (IBM PCNet or SYTEK LocalNET) */
#define HDR_ULTRALINK 13 /* Ultra link */
#define HDR_SMDS 14 /* SMDS */
#define HDR_FRAMERELAY 15 /* Frame Relay */
#define HDR_ATM 16 /* Asynchronous Transmission Mode (ATM) */
#define HDR_HDLC 17 /* HDLC */
#define HDR_FIBRE 18 /* Fibre Channel [RFC4338] */
#define HDR_ATMb 19 /* Asynchronous Transmission Mode (ATM) */
#define HDR_SERIAL 20 /* Serial Line */
#define HDR_ATMc 21 /* Asynchronous Transmission Mode [RFC2225] */
#define HDR_MILSTD 22 /* MIL-STD-188-220 */
#define HDR_METRICOM 23 /* Metricom */
#define HDR_IEEE1394 24 /* IEEE 1394.199 */
#define HDR_MAPOS 25 /* MAPOS [RFC2176] */
#define HDR_TWINAXIAL 26 /* Twinaxial */
#define HDR_EUI64 27 /* EUI-64 */
#define HDR_HIPARP 28 /* HIPARP */
#define HDR_ISO7816 29 /* IP and ARP over ISO 7816-3 */
#define HDR_ARPSEC 30 /* ARPSec */
#define HDR_IPSEC 31 /* IPsec tunnel */
#define HDR_INFINIBAND 32 /* InfiniBand (TM) */
#define HDR_TIA102 33 /* TIA-102 Project 25 Common Air Interface */
#define HDR_WIEGAND 34 /* Wiegand Interface */
#define HDR_PUREIP 35 /* Pure IP */
#define HDR_HW_EXP1 36 /* HW_EXP1 [RFC5494] */
#define HDR_HW_EXP2 37 /* HW_EXP2 [RFC5494] */
/* Operation Codes */
#define OP_ARP_REQUEST 1 /* ARP Request */
#define OP_ARP_REPLY 2 /* ARP Reply */
#define OP_RARP_REQUEST 3 /* Reverse ARP Request */
#define OP_RARP_REPLY 4 /* Reverse ARP Reply */
#define OP_DRARP_REQUEST 5 /* DRARP-Request */
#define OP_DRARP_REPLY 6 /* DRARP-Reply */
#define OP_DRARP_ERROR 7 /* DRARP-Error */
#define OP_INARP_REQUEST 8 /* InARP-Request */
#define OP_INARP_REPLY 9 /* InARP-Reply */
#define OP_ARPNAK 10 /* ARP-NAK */
#define OP_MARS_REQUEST 11 /* MARS-Request */
#define OP_MARS_MULTI 12 /* MARS-Multi */
#define OP_MARS_MSERV 13 /* MARS-MServ */
#define OP_MARS_JOIN 14 /* MARS-Join */
#define OP_MARS_LEAVE 15 /* MARS-Leave */
#define OP_MARS_NAK 16 /* MARS-NAK */
#define OP_MARS_UNSERV 17 /* MARS-Unserv */
#define OP_MARS_SJOIN 18 /* MARS-SJoin */
#define OP_MARS_SLEAVE 19 /* MARS-SLeave */
#define OP_MARS_GL_REQ 20 /* MARS-Grouplist-Request */
#define OP_MARS_GL_REP 21 /* MARS-Grouplist-Reply */
#define OP_MARS_REDIR_MAP 22 /* MARS-Redirect-Map */
#define OP_MAPOS_UNARP 23 /* MAPOS-UNARP [RFC2176] */
#define OP_EXP1 24 /* OP_EXP1 [RFC5494] */
#define OP_EXP2 25 /* OP_EXP2 [RFC5494] */
#define OP_RESERVED 65535 /* Reserved [RFC5494] */
/* TODO @todo: getTargetIP() and getSenderIP() should either
* return struct in_addr or IPAddress but not u32. */
class ARPHeader : public NetworkLayerElement {
private:
struct nping_arp_hdr{
u16 ar_hrd; /* Hardware Type. */
u16 ar_pro; /* Protocol Type. */
u8 ar_hln; /* Hardware Address Length. */
u8 ar_pln; /* Protocol Address Length. */
u16 ar_op; /* Operation Code. */
u8 data[20];
// Cannot use these because the four-flushing alignment screws up
// everything. I miss ANSI C.
//u8 ar_sha[6]; /* Sender Hardware Address. */
//u32 ar_sip; /* Sender Protocol Address (IPv4 address). */
//u8 ar_tha[6]; /* Target Hardware Address. */
//u32 ar_tip; /* Target Protocol Address (IPv4 address). */
}__attribute__((__packed__));
typedef struct nping_arp_hdr nping_arp_hdr_t;
nping_arp_hdr_t h;
public:
/* Misc */
ARPHeader();
~ARPHeader();
void reset();
u8 *getBufferPointer();
int storeRecvData(const u8 *buf, size_t len);
int protocol_id() const;
int validate();
int print(FILE *output, int detail) const;
/* Hardware Type */
int setHardwareType(u16 t);
int setHardwareType();
u16 getHardwareType();
/* Protocol Type */
int setProtocolType(u16 t);
int setProtocolType();
u16 getProtocolType();
/* Hardware Address Length */
int setHwAddrLen(u8 v);
int setHwAddrLen();
u8 getHwAddrLen();
/* Hardware Address Length */
int setProtoAddrLen(u8 v);
int setProtoAddrLen();
u8 getProtoAddrLen();
/* Operation Code */
int setOpCode(u16 c);
u16 getOpCode();
/* Sender Hardware Address */
int setSenderMAC(const u8 *m);
u8 *getSenderMAC();
/* Sender Protocol address */
int setSenderIP(struct in_addr i);
u32 getSenderIP();
/* Target Hardware Address */
int setTargetMAC(u8 *m);
u8 *getTargetMAC();
/* Target Protocol Address */
int setTargetIP(struct in_addr i);
u32 getTargetIP();
}; /* End of class ARPHeader */
#endif /* __ARPHEADER_H__ */
| {
"pile_set_name": "Github"
} |
[subject:New message - {site}]
Hello, {nickname}.
The site «{site}» You received a new private message from <a href="{user_url}">{user_nickname}</a>.
--
Best regards, {site}
<small>This letter is sent automatically, please do not reply</small> | {
"pile_set_name": "Github"
} |
1.11 Fixed bug with -scripts_only switch. Changed generated simulation script - now simulation works differently in batch mode. Removed fixed simulation resolution.
1.10 Files grouped to speed up compilation. AXI-BFM settings updated. Pre/post tcl hooks added.
1.9 export_simulation procedure and support for -lib_map_path switch added
1.8 Fixed system file
1.7 Update 1.7: Add mappings for libraries from compiled library location.
1.6 Update 1.6: Coverage options.
| {
"pile_set_name": "Github"
} |
//! moment.js locale configuration
//! locale : thai (th)
//! author : Kridsada Thanabulpong : https://github.com/sirn
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['moment'], factory) :
factory(global.moment)
}(this, function (moment) { 'use strict';
var th = moment.defineLocale('th', {
months : 'มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม'.split('_'),
monthsShort : 'มกรา_กุมภา_มีนา_เมษา_พฤษภา_มิถุนา_กรกฎา_สิงหา_กันยา_ตุลา_พฤศจิกา_ธันวา'.split('_'),
weekdays : 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์'.split('_'),
weekdaysShort : 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์'.split('_'), // yes, three characters difference
weekdaysMin : 'อา._จ._อ._พ._พฤ._ศ._ส.'.split('_'),
longDateFormat : {
LT : 'H นาฬิกา m นาที',
LTS : 'H นาฬิกา m นาที s วินาที',
L : 'YYYY/MM/DD',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY เวลา H นาฬิกา m นาที',
LLLL : 'วันddddที่ D MMMM YYYY เวลา H นาฬิกา m นาที'
},
meridiemParse: /ก่อนเที่ยง|หลังเที่ยง/,
isPM: function (input) {
return input === 'หลังเที่ยง';
},
meridiem : function (hour, minute, isLower) {
if (hour < 12) {
return 'ก่อนเที่ยง';
} else {
return 'หลังเที่ยง';
}
},
calendar : {
sameDay : '[วันนี้ เวลา] LT',
nextDay : '[พรุ่งนี้ เวลา] LT',
nextWeek : 'dddd[หน้า เวลา] LT',
lastDay : '[เมื่อวานนี้ เวลา] LT',
lastWeek : '[วัน]dddd[ที่แล้ว เวลา] LT',
sameElse : 'L'
},
relativeTime : {
future : 'อีก %s',
past : '%sที่แล้ว',
s : 'ไม่กี่วินาที',
m : '1 นาที',
mm : '%d นาที',
h : '1 ชั่วโมง',
hh : '%d ชั่วโมง',
d : '1 วัน',
dd : '%d วัน',
M : '1 เดือน',
MM : '%d เดือน',
y : '1 ปี',
yy : '%d ปี'
}
});
return th;
})); | {
"pile_set_name": "Github"
} |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>receiveusingsequencenumber</groupId>
<version>1.0.0</version>
<artifactId>receiveusingsequencenumber</artifactId>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<debug>true</debug>
<debuglevel>lines,vars,source</debuglevel>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.microsoft.azure.eventhubs.samples.receiveusingsequencenumber.ReceiveUsingSequenceNumber</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-eventhubs</artifactId>
<version>3.0.2</version>
</dependency>
</dependencies>
</project>
| {
"pile_set_name": "Github"
} |
/**
* Copyright 2014 XCL-Charts
*
* 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.
*
* @Project XCL-Charts
* @Description Android图表基类库
* @author XiongChuanLiang<br/>([email protected])
* @license http://www.apache.org/licenses/ Apache v2 License
* @version 1.0
*/
package org.xclcharts.renderer;
import org.xclcharts.chart.PieData;
import org.xclcharts.common.MathHelper;
import org.xclcharts.renderer.info.PlotArcLabelInfo;
import org.xclcharts.renderer.plot.LabelBrokenLine;
import org.xclcharts.renderer.plot.LabelBrokenLineRender;
import org.xclcharts.renderer.plot.PlotLabel;
import org.xclcharts.renderer.plot.PlotLabelRender;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.PointF;
import android.util.Log;
/**
* @ClassName CirChart
* @Description 圆形类图表,如饼图,刻度盘...类的图表的基类
* @author XiongChuanLiang<br/>([email protected])
*
*/
public class CirChart extends EventChart{
private static final String TAG = "CirChart";
//半径
private float mRadius=0.0f;
//标签注释显示位置 [隐藏,Default,Inside,Ouside,Line]
private XEnum.SliceLabelStyle mLabelStyle = XEnum.SliceLabelStyle.INSIDE;
//开放标签画笔让用户设置
private Paint mPaintLabel = null;
//初始偏移角度
protected float mOffsetAngle = 0.0f;//180;
protected float mInitOffsetAngle = 0.0f;
//折线标签基类
private LabelBrokenLineRender mLabelLine = null;
//同步标签颜色
private boolean mIsLabelLineSyncColor = false;
private boolean mIsLabelPointSyncColor = false;
private boolean mIsLabelSyncColor = false;
//用于设置标签特性
private PlotLabelRender mPlotLabel = null;
public CirChart()
{
//初始化图例
if(null != plotLegend)
{
plotLegend.show();
plotLegend.setType(XEnum.LegendType.ROW);
plotLegend.setHorizontalAlign(XEnum.HorizontalAlign.CENTER);
plotLegend.setVerticalAlign(XEnum.VerticalAlign.BOTTOM);
plotLegend.showBox();
plotLegend.hideBackground();
}
}
@Override
protected void calcPlotRange()
{
super.calcPlotRange();
this.mRadius = Math.min( div(this.plotArea.getWidth() ,2f) ,
div(this.plotArea.getHeight(),2f) );
}
/**
* 返回半径
* @return 半径
*/
public float getRadius()
{
return mRadius;
}
/**
* 设置饼图(pie chart)起始偏移角度
* @param Angle 偏移角度
*/
public void setInitialAngle(float Angle)
{
mInitOffsetAngle = mOffsetAngle = Angle;
}
/**
* 返回图的起始偏移角度
* @return 偏移角度
*/
public float getInitialAngle()
{
return mInitOffsetAngle;
}
/**
* 返回图的当前偏移角度
* @return 偏移角度
*/
public float getOffsetAngle()
{
return mOffsetAngle;
}
/**
* 设置标签显示在扇区的哪个位置(里面,外面,隐藏)
* @param style 显示位置
*/
public void setLabelStyle(XEnum.SliceLabelStyle style)
{
mLabelStyle = style;
//INNER,OUTSIDE,HIDE
switch(style)
{
case INSIDE :
getLabelPaint().setTextAlign(Align.CENTER);
break;
case OUTSIDE :
break;
case HIDE :
break;
case BROKENLINE:
break;
default:
}
}
/**
* 返回标签风格设置
* @return 标签风格
*/
public XEnum.SliceLabelStyle getLabelStyle()
{
return mLabelStyle;
}
/**
* 开放标签画笔
* @return 画笔
*/
public Paint getLabelPaint()
{
if(null == mPaintLabel)
{
mPaintLabel = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaintLabel.setColor(Color.BLACK);
mPaintLabel.setAntiAlias(true);
mPaintLabel.setTextAlign(Align.CENTER);
mPaintLabel.setTextSize(18);
}
return mPaintLabel;
}
/**
* 开放折线标签绘制类(当标签为Line类型时有效)
* @return 折线标签绘制类
*/
public LabelBrokenLine getLabelBrokenLine()
{
if(null == mLabelLine)mLabelLine = new LabelBrokenLineRender();
return mLabelLine;
}
protected PointF renderLabelInside(Canvas canvas,String text,float itemAngle,
float cirX,float cirY,float radius,float calcAngle,
boolean showLabel)
{
//显示在扇形的中心
float calcRadius = MathHelper.getInstance().sub(radius , radius/2f);
//计算百分比标签
PointF point = MathHelper.getInstance().calcArcEndPointXY(
cirX, cirY, calcRadius, calcAngle);
//标识
if(showLabel)
{
//DrawHelper.getInstance().drawRotateText(text, point.x, point.y, itemAngle,
// canvas, getLabelPaint());
getPlotLabel().drawLabel(canvas, getLabelPaint(), text, point.x, point.y, itemAngle);
}
return (new PointF(point.x, point.y));
}
protected PointF renderLabelOutside(Canvas canvas,String text,float itemAngle,
float cirX,float cirY,float radius,float calcAngle,
boolean showLabel)
{
//显示在扇形的外部
float calcRadius = MathHelper.getInstance().add(radius , radius/10f);
//计算百分比标签
PointF point = MathHelper.getInstance().calcArcEndPointXY(
cirX, cirY, calcRadius, calcAngle);
//标识
if(showLabel)
{
//DrawHelper.getInstance().drawRotateText(text, point.x, point.y, itemAngle,
// canvas, getLabelPaint());
getPlotLabel().drawLabel(canvas, getLabelPaint(), text, point.x, point.y, itemAngle);
}
return (new PointF(point.x, point.y));
}
//折线标签
protected PointF renderLabelLine(Canvas canvas,PieData cData,
float cirX,float cirY,float radius,float calcAngle,
boolean showLabel)
{
if(null == mLabelLine)mLabelLine = new LabelBrokenLineRender();
if(mIsLabelLineSyncColor)
mLabelLine.getLabelLinePaint().setColor(cData.getSliceColor());
if(mIsLabelPointSyncColor)
mLabelLine.getPointPaint().setColor(cData.getSliceColor());
return ( mLabelLine.renderLabelLine(cData.getLabel(),cData.getItemLabelRotateAngle(),
cirX,cirY,radius,calcAngle,
canvas,getLabelPaint(),showLabel,mPlotLabel) );
}
/**
* 设置标签颜色与当地扇区颜色同步
*/
public void syncLabelLineColor()
{
mIsLabelLineSyncColor = true;
}
/**
* 设置折线标签点颜色与当地扇区颜色同步
*/
public void syncLabelPointColor()
{
mIsLabelPointSyncColor = true;
}
/**
* 设置折线标签颜色与当地扇区颜色同步
*/
public void syncLabelColor()
{
mIsLabelSyncColor = true;
}
/**
* 用于设置标签显示属性
* @return 标签属性类
*/
public PlotLabel getPlotLabel()
{
if(null == mPlotLabel)
{
mPlotLabel = new PlotLabelRender();
mPlotLabel.setLabelBoxStyle(XEnum.LabelBoxStyle.TEXT);
}
return mPlotLabel;
}
/**
* 绘制标签
* @param canvas 画布
* @param cData PieData类
* @param info 信息类
* @param savePosition 是否保存位置
* @param showLabel 是否显示标签
* @return 是否成功
*/
protected boolean renderLabel(Canvas canvas, PieData cData,
PlotArcLabelInfo info,
boolean savePosition,
boolean showLabel)
{
if(XEnum.SliceLabelStyle.HIDE == mLabelStyle) return true;
if(null == cData)return false;
String text = cData.getLabel();
if(""==text||text.length()==0)return true;
float cirX = info.getX();
float cirY = info.getY();
float radius = info.getRadius();
double offsetAngle = info.getOffsetAngle();
float calcAngle = (float) MathHelper.getInstance().add(offsetAngle , info.getCurrentAngle()/2);
if(Float.compare(calcAngle,0.0f) == 0
|| Float.compare(calcAngle,0.0f) == -1 )
{
Log.e(TAG,"计算出来的圆心角等于0.");
return false;
}
PointF position = null;
//标签颜色与当地扇区颜色同步
if(mIsLabelSyncColor) this.getLabelPaint().setColor(cData.getSliceColor());
int color = getLabelPaint().getColor();
//有定制需求
XEnum.SliceLabelStyle labelStyle = mLabelStyle;
if( cData.getCustLabelStyleStatus() )
{
labelStyle = cData.getLabelStyle();
if( XEnum.SliceLabelStyle.INSIDE == labelStyle)
getLabelPaint().setTextAlign(Align.CENTER);
getLabelPaint().setColor(cData.getCustLabelColor());
}
if(XEnum.SliceLabelStyle.INSIDE == labelStyle)
{
//canvas.save();
//canvas.save(1);
//canvas.translate(cirX,cirY);
//canvas.rotate(20); //cData.getItemLabelRotateAngle());
//显示在扇形的内部
position = renderLabelInside(canvas,text,0, //cData.getItemLabelRotateAngle(),
cirX,cirY,radius,calcAngle,showLabel);
//canvas.restore();
//canvas.restoreToCount(1);
}else if(XEnum.SliceLabelStyle.OUTSIDE == labelStyle){
//显示在扇形的外部
position = renderLabelOutside(canvas,text, cData.getItemLabelRotateAngle(),
cirX,cirY,radius,calcAngle,showLabel);
}else if(XEnum.SliceLabelStyle.BROKENLINE == labelStyle){
//显示在扇形的外部
//1/4处为起始点
position = renderLabelLine(canvas,cData,cirX,cirY,radius,calcAngle,showLabel);
}else{
Log.e(TAG,"未知的标签处理类型.");
return false;
}
getLabelPaint().setColor(color);
if(savePosition)
info.setLabelPointF(position); //保存标签坐标位置
return true;
}
@Override
protected boolean postRender(Canvas canvas) throws Exception
{
try {
super.postRender(canvas);
//计算主图表区范围
calcPlotRange();
//画Plot Area背景
plotArea.render(canvas);
//绘制标题
renderTitle(canvas);
} catch (Exception e) {
throw e;
}
return true;
}
@Override
public boolean render(Canvas canvas) throws Exception {
// TODO Auto-generated method stubcalcPlotRange
try {
if (null == canvas)
return false;
if(getPanModeStatus())
{
canvas.save();
//设置原点位置
switch(this.getPlotPanMode())
{
case HORIZONTAL:
canvas.translate(mTranslateXY[0],0);
break;
case VERTICAL:
canvas.translate(0,mTranslateXY[1]);
break;
default:
canvas.translate(mTranslateXY[0],mTranslateXY[1]);
break;
}
//绘制图表
super.render(canvas);
//还原
canvas.restore();
}else{
//绘制图表
super.render(canvas);
}
return true;
} catch (Exception e) {
throw e;
}
}
}
| {
"pile_set_name": "Github"
} |
package bl.test;
public class Claz {
// here
} | {
"pile_set_name": "Github"
} |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/privacy/dlp/v2/dlp.proto
namespace Google\Cloud\Dlp\V2;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* Represents a color in the RGB color space.
*
* Generated from protobuf message <code>google.privacy.dlp.v2.Color</code>
*/
class Color extends \Google\Protobuf\Internal\Message
{
/**
* The amount of red in the color as a value in the interval [0, 1].
*
* Generated from protobuf field <code>float red = 1;</code>
*/
private $red = 0.0;
/**
* The amount of green in the color as a value in the interval [0, 1].
*
* Generated from protobuf field <code>float green = 2;</code>
*/
private $green = 0.0;
/**
* The amount of blue in the color as a value in the interval [0, 1].
*
* Generated from protobuf field <code>float blue = 3;</code>
*/
private $blue = 0.0;
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* @type float $red
* The amount of red in the color as a value in the interval [0, 1].
* @type float $green
* The amount of green in the color as a value in the interval [0, 1].
* @type float $blue
* The amount of blue in the color as a value in the interval [0, 1].
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Google\Privacy\Dlp\V2\Dlp::initOnce();
parent::__construct($data);
}
/**
* The amount of red in the color as a value in the interval [0, 1].
*
* Generated from protobuf field <code>float red = 1;</code>
* @return float
*/
public function getRed()
{
return $this->red;
}
/**
* The amount of red in the color as a value in the interval [0, 1].
*
* Generated from protobuf field <code>float red = 1;</code>
* @param float $var
* @return $this
*/
public function setRed($var)
{
GPBUtil::checkFloat($var);
$this->red = $var;
return $this;
}
/**
* The amount of green in the color as a value in the interval [0, 1].
*
* Generated from protobuf field <code>float green = 2;</code>
* @return float
*/
public function getGreen()
{
return $this->green;
}
/**
* The amount of green in the color as a value in the interval [0, 1].
*
* Generated from protobuf field <code>float green = 2;</code>
* @param float $var
* @return $this
*/
public function setGreen($var)
{
GPBUtil::checkFloat($var);
$this->green = $var;
return $this;
}
/**
* The amount of blue in the color as a value in the interval [0, 1].
*
* Generated from protobuf field <code>float blue = 3;</code>
* @return float
*/
public function getBlue()
{
return $this->blue;
}
/**
* The amount of blue in the color as a value in the interval [0, 1].
*
* Generated from protobuf field <code>float blue = 3;</code>
* @param float $var
* @return $this
*/
public function setBlue($var)
{
GPBUtil::checkFloat($var);
$this->blue = $var;
return $this;
}
}
| {
"pile_set_name": "Github"
} |
opt imgin:OSAIMGAT.BIN
ovrcopy from:osask_qe.sys to:@:OSASK.SYS
copy from:OSASK0.PSF to:@:
opt imgout:osaimgqe.bin
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<shelfDocument>
<!-- This file contains definitions of shelves, toolbars, and tools.
It should not be hand-edited when it is being used by the application.
Note, that two definitions of the same element are not allowed in
a single file. -->
<tool name="$HDA_DEFAULT_TOOL" label="$HDA_LABEL" icon="$HDA_ICON">
<toolMenuContext name="viewer">
<contextNetType>SOP</contextNetType>
</toolMenuContext>
<toolMenuContext name="network">
<contextOpType>$HDA_TABLE_AND_NAME</contextOpType>
</toolMenuContext>
<toolSubmenu>GameDev/Import</toolSubmenu>
<script scriptType="python"><![CDATA[import soptoolutils
soptoolutils.genericTool(kwargs, '$HDA_NAME')]]></script>
</tool>
</shelfDocument>
| {
"pile_set_name": "Github"
} |
/**
* VERSION: 0.2 (beta)
* DATE: 2010-04-16
* ACTIONSCRIPT VERSION: 3.0
* UPDATES AND DOCUMENTATION AT: http://www.GreenSock.com
**/
package com.greensock.plugins {
import com.greensock.*;
import com.greensock.motionPaths.CirclePath2D;
import com.greensock.motionPaths.PathFollower;
import flash.geom.Matrix;
/**
* Tweens an object along a CirclePath2D motion path in any direction (clockwise, counter-clockwise, or shortest).
* The plugin recognizes the following properties:
* <ul>
* <li><b>path</b> : CirclePath2D - The CirclePath2D instance to follow (com.greensock.motionPaths.CirclePath2D)</li>
* <li><b>startAngle</b> : Number - The position at which the target should begin its rotation (described
* in degrees unless useRadians is true in which case it is described in radians).
* For example, to begin at the top of the circle, use 270 or -90 as the startAngle.</li>
* <li><b>endAngle</b> : Number - The position at which the target should end its rotation (described in
* degrees unless useRadians is true in which case it is described in radians).
* For example, to end at the bottom of the circle, use 90 as the endAngle</li>
* <li><b>autoRotate</b> : Boolean - When <code>autoRotate</code> is <code>true</code>, the target will automatically
* be rotated so that it is oriented to the angle of the path. To offset this value (like to always add
* 90 degrees for example), use the <code>rotationOffset</code> property.</li>
* <li><b>rotationOffset</b> : Number - When <code>autoRotate</code> is <code>true</code>, this value will always
* be added to the resulting <code>rotation</code> of the target.</li>
* <li><b>direction</b> : String - The direction in which the target should travel around the path. Options are
* <code>Direction.CLOCKWISE</code> ("clockwise"), <code>Direction.COUNTER_CLOCKWISE</code>
* ("counterClockwise"), or <code>Direction.SHORTEST</code> ("shortest").</li>
* <li><b>extraRevolutions</b> : uint - If instead of going directly to the endAngle, you want the target to
* travel one or more extra revolutions around the path before going to the endAngle,
* define that number of revolutions here. </li>
* <li><b>useRadians</b> : Boolean - If you prefer to define values in radians instead of degrees, set useRadians to true.</li>
* </ul>
*
* <br /><br />
*
* <b>USAGE:</b><br /><br />
* <code>
* import com.greensock.~~; <br />
* import com.greensock.plugins.~~; <br />
* import com.greensock.motionPaths.~~<br />
* TweenPlugin.activate([CirclePath2DPlugin]); //activation is permanent in the SWF, so this line only needs to be run once.<br /><br />
*
* var circle:CirclePath2D = new CirclePath2D(150, 150, 100);
* TweenLite.to(mc, 2, {circlePath2D:{path:circle, startAngle:90, endAngle:270, direction:Direction.CLOCKWISE, extraRevolutions:2}}); <br /><br />
* </code>
*
* <b>Copyright 2011, GreenSock. All rights reserved.</b> This work is subject to the terms in <a href="http://www.greensock.com/terms_of_use.html">http://www.greensock.com/terms_of_use.html</a> or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership.
*
* @author Jack Doyle, [email protected]
*/
public class CirclePath2DPlugin extends TweenPlugin {
/** @private **/
public static const API:Number = 1.0; //If the API/Framework for plugins changes in the future, this number helps determine compatibility
/** @private **/
private static const _2PI:Number = Math.PI * 2;
/** @private **/
private static const _RAD2DEG:Number = 180 / Math.PI;
/** @private **/
protected var _target:Object;
/** @private **/
protected var _autoRemove:Boolean;
/** @private **/
protected var _start:Number;
/** @private **/
protected var _change:Number;
/** @private **/
protected var _circle:CirclePath2D;
/** @private **/
protected var _autoRotate:Boolean;
/** @private **/
protected var _rotationOffset:Number;
/** @private **/
public function CirclePath2DPlugin() {
super();
this.propName = "circlePath2D";
this.overwriteProps = ["x","y"];
}
/** @private **/
override public function onInitTween(target:Object, value:*, tween:TweenLite):Boolean {
if (!("path" in value) || !(value.path is CirclePath2D)) {
trace("CirclePath2DPlugin error: invalid 'path' property. Please define a CirclePath2D instance.");
return false;
}
_target = target;
_circle = value.path as CirclePath2D;
_autoRotate = Boolean(value.autoRotate == true);
_rotationOffset = value.rotationOffset || 0;
var f:PathFollower = _circle.getFollower(target);
if (f != null && !("startAngle" in value)) {
_start = f.progress;
} else {
_start = _circle.angleToProgress(value.startAngle || 0, value.useRadians);
_circle.renderObjectAt(_target, _start);
}
_change = Number(_circle.anglesToProgressChange(_circle.progressToAngle(_start), value.endAngle || 0, value.direction || "clockwise", value.extraRevolutions || 0, Boolean(value.useRadians)));
return true;
}
/** @private **/
override public function killProps(lookup:Object):void {
super.killProps(lookup);
if (("x" in lookup) || ("y" in lookup)) {
this.overwriteProps = [];
}
}
/** @private **/
override public function set changeFactor(n:Number):void {
var angle:Number = (_start + (_change * n)) * _2PI;
var radius:Number = _circle.radius;
var m:Matrix = _circle.transform.matrix;
var px:Number = Math.cos(angle) * radius;
var py:Number = Math.sin(angle) * radius;
_target.x = px * m.a + py * m.c + m.tx;
_target.y = px * m.b + py * m.d + m.ty;
if (_autoRotate) {
angle += Math.PI / 2;
px = Math.cos(angle) * _circle.radius;
py = Math.sin(angle) * _circle.radius;
_target.rotation = Math.atan2(px * m.b + py * m.d, px * m.a + py * m.c) * _RAD2DEG + _rotationOffset;
}
}
}
} | {
"pile_set_name": "Github"
} |
<?php
/**
* Ustream.tv shortcode
*
* Example:
* [ustream id=1524 live=1]
* [ustreamsocial id=12980237 width="500"]
*
* Embed code example, from http://www.ustream.tv/leolaporte
* <iframe src="http://www.ustream.tv/embed/recorded/1524?v=3&wmode=direct" width="480" height="296" scrolling="no" frameborder="0" style="border: 0 none transparent;"></iframe>
*
* @package Jetpack
*/
add_shortcode( 'ustream', 'ustream_shortcode' );
add_shortcode( 'ustreamsocial', 'ustreamsocial_shortcode' );
/**
* Parse shortcode arguments and render output for ustream single video.
*
* @since 4.5.0
*
* @param array $atts array of user-supplied arguments.
*
* @return string HTML output.
*/
function ustream_shortcode( $atts ) {
if ( isset( $atts[0] ) ) {
return '<!-- ustream error: bad parameters -->';
}
$defaults = array(
'width' => 480,
'height' => 296,
'id' => 0,
'live' => 0,
'highlight' => 0,
'version' => 3,
'hwaccel' => 1,
);
$atts = array_map( 'intval', shortcode_atts( $defaults, $atts ) );
if ( 0 >= $atts['id'] ) {
return '<!-- ustream error: bad video ID -->';
}
if ( 0 >= $atts['height'] ) {
return '<!-- ustream error: height invalid -->';
}
if ( 0 >= $atts['width'] ) {
return '<!-- ustream error: width invalid -->';
}
if ( $atts['live'] ) {
$recorded = '';
} else {
$recorded = 'recorded/';
}
if ( ! $atts['live'] && ( 0 < $atts['highlight'] ) ) {
$highlight = sprintf( '/highlight/%d', esc_attr( $atts['highlight'] ) );
} else {
$highlight = '';
}
$url_base = sprintf(
'https://www.ustream.tv/embed/%s%d%s',
$recorded,
esc_attr( $atts['id'] ),
$highlight
);
$video_options = array(
'html5ui' => 1,
'v' => absint( $atts['version'] ),
);
if ( 0 < $atts['hwaccel'] ) {
$video_options['wmode'] = 'direct';
}
$url = add_query_arg(
$video_options,
$url_base
);
$output = sprintf(
'<iframe src="%1$s" width="%2$d" height="%3$d" scrolling="no" style="border: 0 none transparent;"></iframe>',
esc_url( $url ),
absint( $atts['width'] ),
absint( $atts['height'] )
);
return $output;
}
/**
* Parse shortcode arguments and render output for ustream's Social Stream.
*
* @since 4.5.0
*
* @param array $atts array of user-supplied arguments.
*
* @return string HTML output.
*/
function ustreamsocial_shortcode( $atts ) {
$defaults = array(
'id' => 0,
'height' => 420,
'width' => 320,
);
$atts = array_map( 'intval', shortcode_atts( $defaults, $atts ) );
if ( 0 >= $atts['id'] ) {
return '<!-- ustreamsocial error: bad social stream ID -->';
}
if ( 0 >= $atts['height'] ) {
return '<!-- ustreamsocial error: height invalid -->';
}
if ( 0 >= $atts['width'] ) {
return '<!-- ustreamsocial error: width invalid -->';
}
$url = 'https://www.ustream.tv/socialstream/' . esc_attr( $atts['id'] );
return sprintf(
'<iframe id="SocialStream" src="%1$s" class="" name="SocialStream" width="%2$d" height="%3$d" scrolling="no" allowtransparency="true" style="visibility: visible; margin-top: 0; margin-bottom: 0; border: 0;"></iframe>',
esc_url( $url ),
absint( $atts['width'] ),
absint( $atts['height'] )
);
}
| {
"pile_set_name": "Github"
} |
package PageObject::Setup::CreateUser;
use strict;
use warnings;
use Carp;
use Moose;
use namespace::autoclean;
use PageObject;
extends 'PageObject';
__PACKAGE__->self_register(
'setup-add-user',
'.//body[@id="setup-new-user"]',
tag_name => 'body',
attributes => {
id => 'setup-new-user',
});
my @fields = ("Username", "Password", "Create new user", "Import existing user",
"Salutation", "First Name", "Last name", "Employee Number",
"Date of Birth", "Tax ID/SSN", "Country", "Assign Permissions");
sub _verify {
my ($self) = @_;
$self->find('*labeled', text => $_) for @fields;
return $self;
}
sub create_user {
my $self = shift;
my %param = @_;
foreach my $field (@fields) {
next unless exists $param{$field};
my $elm =
$self->find('*labeled', text => $field);
if ($elm->can('find_option')) {
$elm->find_option($param{$field})->click;
}
else {
$elm->send_keys($param{$field});
}
}
my $btn = $self->find('*button', text => "Create User");
$btn->click;
$self->session->page->wait_for_body;
return $self->session->page->body;
}
__PACKAGE__->meta->make_immutable;
1;
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<product version="3" modelHash="-3bfho715sbrza1dacqy8kvt1siplb5x">
<files names="Language.java" />
</product>
| {
"pile_set_name": "Github"
} |
//========================================================================
// GLFW 3.3 GLX - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2016 Camilla Löwy <[email protected]>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include "internal.h"
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#ifndef GLXBadProfileARB
#define GLXBadProfileARB 13
#endif
// Returns the specified attribute of the specified GLXFBConfig
//
static int getGLXFBConfigAttrib(GLXFBConfig fbconfig, int attrib)
{
int value;
glXGetFBConfigAttrib(_glfw.x11.display, fbconfig, attrib, &value);
return value;
}
// Return the GLXFBConfig most closely matching the specified hints
//
static GLFWbool chooseGLXFBConfig(const _GLFWfbconfig* desired,
GLXFBConfig* result)
{
GLXFBConfig* nativeConfigs;
_GLFWfbconfig* usableConfigs;
const _GLFWfbconfig* closest;
int i, nativeCount, usableCount;
const char* vendor;
GLFWbool trustWindowBit = GLFW_TRUE;
// HACK: This is a (hopefully temporary) workaround for Chromium
// (VirtualBox GL) not setting the window bit on any GLXFBConfigs
vendor = glXGetClientString(_glfw.x11.display, GLX_VENDOR);
if (vendor && strcmp(vendor, "Chromium") == 0)
trustWindowBit = GLFW_FALSE;
nativeConfigs =
glXGetFBConfigs(_glfw.x11.display, _glfw.x11.screen, &nativeCount);
if (!nativeConfigs || !nativeCount)
{
_glfwInputError(GLFW_API_UNAVAILABLE, "GLX: No GLXFBConfigs returned");
return GLFW_FALSE;
}
usableConfigs = calloc(nativeCount, sizeof(_GLFWfbconfig));
usableCount = 0;
for (i = 0; i < nativeCount; i++)
{
const GLXFBConfig n = nativeConfigs[i];
_GLFWfbconfig* u = usableConfigs + usableCount;
// Only consider RGBA GLXFBConfigs
if (!(getGLXFBConfigAttrib(n, GLX_RENDER_TYPE) & GLX_RGBA_BIT))
continue;
// Only consider window GLXFBConfigs
if (!(getGLXFBConfigAttrib(n, GLX_DRAWABLE_TYPE) & GLX_WINDOW_BIT))
{
if (trustWindowBit)
continue;
}
if (desired->transparent)
{
XVisualInfo* vi = glXGetVisualFromFBConfig(_glfw.x11.display, n);
if (vi)
{
u->transparent = _glfwIsVisualTransparentX11(vi->visual);
XFree(vi);
}
}
u->redBits = getGLXFBConfigAttrib(n, GLX_RED_SIZE);
u->greenBits = getGLXFBConfigAttrib(n, GLX_GREEN_SIZE);
u->blueBits = getGLXFBConfigAttrib(n, GLX_BLUE_SIZE);
u->alphaBits = getGLXFBConfigAttrib(n, GLX_ALPHA_SIZE);
u->depthBits = getGLXFBConfigAttrib(n, GLX_DEPTH_SIZE);
u->stencilBits = getGLXFBConfigAttrib(n, GLX_STENCIL_SIZE);
u->accumRedBits = getGLXFBConfigAttrib(n, GLX_ACCUM_RED_SIZE);
u->accumGreenBits = getGLXFBConfigAttrib(n, GLX_ACCUM_GREEN_SIZE);
u->accumBlueBits = getGLXFBConfigAttrib(n, GLX_ACCUM_BLUE_SIZE);
u->accumAlphaBits = getGLXFBConfigAttrib(n, GLX_ACCUM_ALPHA_SIZE);
u->auxBuffers = getGLXFBConfigAttrib(n, GLX_AUX_BUFFERS);
if (getGLXFBConfigAttrib(n, GLX_STEREO))
u->stereo = GLFW_TRUE;
if (getGLXFBConfigAttrib(n, GLX_DOUBLEBUFFER))
u->doublebuffer = GLFW_TRUE;
if (_glfw.glx.ARB_multisample)
u->samples = getGLXFBConfigAttrib(n, GLX_SAMPLES);
if (_glfw.glx.ARB_framebuffer_sRGB || _glfw.glx.EXT_framebuffer_sRGB)
u->sRGB = getGLXFBConfigAttrib(n, GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB);
u->handle = (uintptr_t) n;
usableCount++;
}
closest = _glfwChooseFBConfig(desired, usableConfigs, usableCount);
if (closest)
*result = (GLXFBConfig) closest->handle;
XFree(nativeConfigs);
free(usableConfigs);
return closest != NULL;
}
// Create the OpenGL context using legacy API
//
static GLXContext createLegacyContextGLX(_GLFWwindow* window,
GLXFBConfig fbconfig,
GLXContext share)
{
return glXCreateNewContext(_glfw.x11.display,
fbconfig,
GLX_RGBA_TYPE,
share,
True);
}
static void makeContextCurrentGLX(_GLFWwindow* window)
{
if (window)
{
if (!glXMakeCurrent(_glfw.x11.display,
window->context.glx.window,
window->context.glx.handle))
{
_glfwInputError(GLFW_PLATFORM_ERROR,
"GLX: Failed to make context current");
return;
}
}
else
{
if (!glXMakeCurrent(_glfw.x11.display, None, NULL))
{
_glfwInputError(GLFW_PLATFORM_ERROR,
"GLX: Failed to clear current context");
return;
}
}
_glfwPlatformSetTls(&_glfw.contextSlot, window);
}
static void swapBuffersGLX(_GLFWwindow* window)
{
glXSwapBuffers(_glfw.x11.display, window->context.glx.window);
}
static void swapIntervalGLX(int interval)
{
_GLFWwindow* window = _glfwPlatformGetTls(&_glfw.contextSlot);
if (_glfw.glx.EXT_swap_control)
{
_glfw.glx.SwapIntervalEXT(_glfw.x11.display,
window->context.glx.window,
interval);
}
else if (_glfw.glx.MESA_swap_control)
_glfw.glx.SwapIntervalMESA(interval);
else if (_glfw.glx.SGI_swap_control)
{
if (interval > 0)
_glfw.glx.SwapIntervalSGI(interval);
}
}
static int extensionSupportedGLX(const char* extension)
{
const char* extensions =
glXQueryExtensionsString(_glfw.x11.display, _glfw.x11.screen);
if (extensions)
{
if (_glfwStringInExtensionString(extension, extensions))
return GLFW_TRUE;
}
return GLFW_FALSE;
}
static GLFWglproc getProcAddressGLX(const char* procname)
{
if (_glfw.glx.GetProcAddress)
return _glfw.glx.GetProcAddress((const GLubyte*) procname);
else if (_glfw.glx.GetProcAddressARB)
return _glfw.glx.GetProcAddressARB((const GLubyte*) procname);
else
return _glfw_dlsym(_glfw.glx.handle, procname);
}
// Destroy the OpenGL context
//
static void destroyContextGLX(_GLFWwindow* window)
{
if (window->context.glx.window)
{
glXDestroyWindow(_glfw.x11.display, window->context.glx.window);
window->context.glx.window = None;
}
if (window->context.glx.handle)
{
glXDestroyContext(_glfw.x11.display, window->context.glx.handle);
window->context.glx.handle = NULL;
}
}
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
// Initialize GLX
//
GLFWbool _glfwInitGLX(void)
{
int i;
const char* sonames[] =
{
#if defined(_GLFW_GLX_LIBRARY)
_GLFW_GLX_LIBRARY,
#elif defined(__CYGWIN__)
"libGL-1.so",
#else
"libGL.so.1",
"libGL.so",
#endif
NULL
};
if (_glfw.glx.handle)
return GLFW_TRUE;
for (i = 0; sonames[i]; i++)
{
_glfw.glx.handle = _glfw_dlopen(sonames[i]);
if (_glfw.glx.handle)
break;
}
if (!_glfw.glx.handle)
{
_glfwInputError(GLFW_API_UNAVAILABLE, "GLX: Failed to load GLX");
return GLFW_FALSE;
}
_glfw.glx.GetFBConfigs =
_glfw_dlsym(_glfw.glx.handle, "glXGetFBConfigs");
_glfw.glx.GetFBConfigAttrib =
_glfw_dlsym(_glfw.glx.handle, "glXGetFBConfigAttrib");
_glfw.glx.GetClientString =
_glfw_dlsym(_glfw.glx.handle, "glXGetClientString");
_glfw.glx.QueryExtension =
_glfw_dlsym(_glfw.glx.handle, "glXQueryExtension");
_glfw.glx.QueryVersion =
_glfw_dlsym(_glfw.glx.handle, "glXQueryVersion");
_glfw.glx.DestroyContext =
_glfw_dlsym(_glfw.glx.handle, "glXDestroyContext");
_glfw.glx.MakeCurrent =
_glfw_dlsym(_glfw.glx.handle, "glXMakeCurrent");
_glfw.glx.SwapBuffers =
_glfw_dlsym(_glfw.glx.handle, "glXSwapBuffers");
_glfw.glx.QueryExtensionsString =
_glfw_dlsym(_glfw.glx.handle, "glXQueryExtensionsString");
_glfw.glx.CreateNewContext =
_glfw_dlsym(_glfw.glx.handle, "glXCreateNewContext");
_glfw.glx.CreateWindow =
_glfw_dlsym(_glfw.glx.handle, "glXCreateWindow");
_glfw.glx.DestroyWindow =
_glfw_dlsym(_glfw.glx.handle, "glXDestroyWindow");
_glfw.glx.GetProcAddress =
_glfw_dlsym(_glfw.glx.handle, "glXGetProcAddress");
_glfw.glx.GetProcAddressARB =
_glfw_dlsym(_glfw.glx.handle, "glXGetProcAddressARB");
_glfw.glx.GetVisualFromFBConfig =
_glfw_dlsym(_glfw.glx.handle, "glXGetVisualFromFBConfig");
if (!_glfw.glx.GetFBConfigs ||
!_glfw.glx.GetFBConfigAttrib ||
!_glfw.glx.GetClientString ||
!_glfw.glx.QueryExtension ||
!_glfw.glx.QueryVersion ||
!_glfw.glx.DestroyContext ||
!_glfw.glx.MakeCurrent ||
!_glfw.glx.SwapBuffers ||
!_glfw.glx.QueryExtensionsString ||
!_glfw.glx.CreateNewContext ||
!_glfw.glx.CreateWindow ||
!_glfw.glx.DestroyWindow ||
!_glfw.glx.GetProcAddress ||
!_glfw.glx.GetProcAddressARB ||
!_glfw.glx.GetVisualFromFBConfig)
{
_glfwInputError(GLFW_PLATFORM_ERROR,
"GLX: Failed to load required entry points");
return GLFW_FALSE;
}
if (!glXQueryExtension(_glfw.x11.display,
&_glfw.glx.errorBase,
&_glfw.glx.eventBase))
{
_glfwInputError(GLFW_API_UNAVAILABLE, "GLX: GLX extension not found");
return GLFW_FALSE;
}
if (!glXQueryVersion(_glfw.x11.display, &_glfw.glx.major, &_glfw.glx.minor))
{
_glfwInputError(GLFW_API_UNAVAILABLE,
"GLX: Failed to query GLX version");
return GLFW_FALSE;
}
if (_glfw.glx.major == 1 && _glfw.glx.minor < 3)
{
_glfwInputError(GLFW_API_UNAVAILABLE,
"GLX: GLX version 1.3 is required");
return GLFW_FALSE;
}
if (extensionSupportedGLX("GLX_EXT_swap_control"))
{
_glfw.glx.SwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)
getProcAddressGLX("glXSwapIntervalEXT");
if (_glfw.glx.SwapIntervalEXT)
_glfw.glx.EXT_swap_control = GLFW_TRUE;
}
if (extensionSupportedGLX("GLX_SGI_swap_control"))
{
_glfw.glx.SwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)
getProcAddressGLX("glXSwapIntervalSGI");
if (_glfw.glx.SwapIntervalSGI)
_glfw.glx.SGI_swap_control = GLFW_TRUE;
}
if (extensionSupportedGLX("GLX_MESA_swap_control"))
{
_glfw.glx.SwapIntervalMESA = (PFNGLXSWAPINTERVALMESAPROC)
getProcAddressGLX("glXSwapIntervalMESA");
if (_glfw.glx.SwapIntervalMESA)
_glfw.glx.MESA_swap_control = GLFW_TRUE;
}
if (extensionSupportedGLX("GLX_ARB_multisample"))
_glfw.glx.ARB_multisample = GLFW_TRUE;
if (extensionSupportedGLX("GLX_ARB_framebuffer_sRGB"))
_glfw.glx.ARB_framebuffer_sRGB = GLFW_TRUE;
if (extensionSupportedGLX("GLX_EXT_framebuffer_sRGB"))
_glfw.glx.EXT_framebuffer_sRGB = GLFW_TRUE;
if (extensionSupportedGLX("GLX_ARB_create_context"))
{
_glfw.glx.CreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC)
getProcAddressGLX("glXCreateContextAttribsARB");
if (_glfw.glx.CreateContextAttribsARB)
_glfw.glx.ARB_create_context = GLFW_TRUE;
}
if (extensionSupportedGLX("GLX_ARB_create_context_robustness"))
_glfw.glx.ARB_create_context_robustness = GLFW_TRUE;
if (extensionSupportedGLX("GLX_ARB_create_context_profile"))
_glfw.glx.ARB_create_context_profile = GLFW_TRUE;
if (extensionSupportedGLX("GLX_EXT_create_context_es2_profile"))
_glfw.glx.EXT_create_context_es2_profile = GLFW_TRUE;
if (extensionSupportedGLX("GLX_ARB_create_context_no_error"))
_glfw.glx.ARB_create_context_no_error = GLFW_TRUE;
if (extensionSupportedGLX("GLX_ARB_context_flush_control"))
_glfw.glx.ARB_context_flush_control = GLFW_TRUE;
return GLFW_TRUE;
}
// Terminate GLX
//
void _glfwTerminateGLX(void)
{
// NOTE: This function must not call any X11 functions, as it is called
// after XCloseDisplay (see _glfwPlatformTerminate for details)
if (_glfw.glx.handle)
{
_glfw_dlclose(_glfw.glx.handle);
_glfw.glx.handle = NULL;
}
}
#define setAttrib(a, v) \
{ \
assert((size_t) (index + 1) < sizeof(attribs) / sizeof(attribs[0])); \
attribs[index++] = a; \
attribs[index++] = v; \
}
// Create the OpenGL or OpenGL ES context
//
GLFWbool _glfwCreateContextGLX(_GLFWwindow* window,
const _GLFWctxconfig* ctxconfig,
const _GLFWfbconfig* fbconfig)
{
int attribs[40];
GLXFBConfig native = NULL;
GLXContext share = NULL;
if (ctxconfig->share)
share = ctxconfig->share->context.glx.handle;
if (!chooseGLXFBConfig(fbconfig, &native))
{
_glfwInputError(GLFW_FORMAT_UNAVAILABLE,
"GLX: Failed to find a suitable GLXFBConfig");
return GLFW_FALSE;
}
if (ctxconfig->client == GLFW_OPENGL_ES_API)
{
if (!_glfw.glx.ARB_create_context ||
!_glfw.glx.ARB_create_context_profile ||
!_glfw.glx.EXT_create_context_es2_profile)
{
_glfwInputError(GLFW_API_UNAVAILABLE,
"GLX: OpenGL ES requested but GLX_EXT_create_context_es2_profile is unavailable");
return GLFW_FALSE;
}
}
if (ctxconfig->forward)
{
if (!_glfw.glx.ARB_create_context)
{
_glfwInputError(GLFW_VERSION_UNAVAILABLE,
"GLX: Forward compatibility requested but GLX_ARB_create_context_profile is unavailable");
return GLFW_FALSE;
}
}
if (ctxconfig->profile)
{
if (!_glfw.glx.ARB_create_context ||
!_glfw.glx.ARB_create_context_profile)
{
_glfwInputError(GLFW_VERSION_UNAVAILABLE,
"GLX: An OpenGL profile requested but GLX_ARB_create_context_profile is unavailable");
return GLFW_FALSE;
}
}
_glfwGrabErrorHandlerX11();
if (_glfw.glx.ARB_create_context)
{
int index = 0, mask = 0, flags = 0;
if (ctxconfig->client == GLFW_OPENGL_API)
{
if (ctxconfig->forward)
flags |= GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
if (ctxconfig->profile == GLFW_OPENGL_CORE_PROFILE)
mask |= GLX_CONTEXT_CORE_PROFILE_BIT_ARB;
else if (ctxconfig->profile == GLFW_OPENGL_COMPAT_PROFILE)
mask |= GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
}
else
mask |= GLX_CONTEXT_ES2_PROFILE_BIT_EXT;
if (ctxconfig->debug)
flags |= GLX_CONTEXT_DEBUG_BIT_ARB;
if (ctxconfig->robustness)
{
if (_glfw.glx.ARB_create_context_robustness)
{
if (ctxconfig->robustness == GLFW_NO_RESET_NOTIFICATION)
{
setAttrib(GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB,
GLX_NO_RESET_NOTIFICATION_ARB);
}
else if (ctxconfig->robustness == GLFW_LOSE_CONTEXT_ON_RESET)
{
setAttrib(GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB,
GLX_LOSE_CONTEXT_ON_RESET_ARB);
}
flags |= GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB;
}
}
if (ctxconfig->release)
{
if (_glfw.glx.ARB_context_flush_control)
{
if (ctxconfig->release == GLFW_RELEASE_BEHAVIOR_NONE)
{
setAttrib(GLX_CONTEXT_RELEASE_BEHAVIOR_ARB,
GLX_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB);
}
else if (ctxconfig->release == GLFW_RELEASE_BEHAVIOR_FLUSH)
{
setAttrib(GLX_CONTEXT_RELEASE_BEHAVIOR_ARB,
GLX_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB);
}
}
}
if (ctxconfig->noerror)
{
if (_glfw.glx.ARB_create_context_no_error)
setAttrib(GLX_CONTEXT_OPENGL_NO_ERROR_ARB, GLFW_TRUE);
}
// NOTE: Only request an explicitly versioned context when necessary, as
// explicitly requesting version 1.0 does not always return the
// highest version supported by the driver
if (ctxconfig->major != 1 || ctxconfig->minor != 0)
{
setAttrib(GLX_CONTEXT_MAJOR_VERSION_ARB, ctxconfig->major);
setAttrib(GLX_CONTEXT_MINOR_VERSION_ARB, ctxconfig->minor);
}
if (mask)
setAttrib(GLX_CONTEXT_PROFILE_MASK_ARB, mask);
if (flags)
setAttrib(GLX_CONTEXT_FLAGS_ARB, flags);
setAttrib(None, None);
window->context.glx.handle =
_glfw.glx.CreateContextAttribsARB(_glfw.x11.display,
native,
share,
True,
attribs);
// HACK: This is a fallback for broken versions of the Mesa
// implementation of GLX_ARB_create_context_profile that fail
// default 1.0 context creation with a GLXBadProfileARB error in
// violation of the extension spec
if (!window->context.glx.handle)
{
if (_glfw.x11.errorCode == _glfw.glx.errorBase + GLXBadProfileARB &&
ctxconfig->client == GLFW_OPENGL_API &&
ctxconfig->profile == GLFW_OPENGL_ANY_PROFILE &&
ctxconfig->forward == GLFW_FALSE)
{
window->context.glx.handle =
createLegacyContextGLX(window, native, share);
}
}
}
else
{
window->context.glx.handle =
createLegacyContextGLX(window, native, share);
}
_glfwReleaseErrorHandlerX11();
if (!window->context.glx.handle)
{
_glfwInputErrorX11(GLFW_VERSION_UNAVAILABLE, "GLX: Failed to create context");
return GLFW_FALSE;
}
window->context.glx.window =
glXCreateWindow(_glfw.x11.display, native, window->x11.handle, NULL);
if (!window->context.glx.window)
{
_glfwInputError(GLFW_PLATFORM_ERROR, "GLX: Failed to create window");
return GLFW_FALSE;
}
window->context.makeCurrent = makeContextCurrentGLX;
window->context.swapBuffers = swapBuffersGLX;
window->context.swapInterval = swapIntervalGLX;
window->context.extensionSupported = extensionSupportedGLX;
window->context.getProcAddress = getProcAddressGLX;
window->context.destroy = destroyContextGLX;
return GLFW_TRUE;
}
#undef setAttrib
// Returns the Visual and depth of the chosen GLXFBConfig
//
GLFWbool _glfwChooseVisualGLX(const _GLFWwndconfig* wndconfig,
const _GLFWctxconfig* ctxconfig,
const _GLFWfbconfig* fbconfig,
Visual** visual, int* depth)
{
GLXFBConfig native;
XVisualInfo* result;
if (!chooseGLXFBConfig(fbconfig, &native))
{
_glfwInputError(GLFW_FORMAT_UNAVAILABLE,
"GLX: Failed to find a suitable GLXFBConfig");
return GLFW_FALSE;
}
result = glXGetVisualFromFBConfig(_glfw.x11.display, native);
if (!result)
{
_glfwInputError(GLFW_PLATFORM_ERROR,
"GLX: Failed to retrieve Visual for GLXFBConfig");
return GLFW_FALSE;
}
*visual = result->visual;
*depth = result->depth;
XFree(result);
return GLFW_TRUE;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW native API //////
//////////////////////////////////////////////////////////////////////////
GLFWAPI GLXContext glfwGetGLXContext(GLFWwindow* handle)
{
_GLFWwindow* window = (_GLFWwindow*) handle;
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
if (window->context.client == GLFW_NO_API)
{
_glfwInputError(GLFW_NO_WINDOW_CONTEXT, NULL);
return NULL;
}
return window->context.glx.handle;
}
GLFWAPI GLXWindow glfwGetGLXWindow(GLFWwindow* handle)
{
_GLFWwindow* window = (_GLFWwindow*) handle;
_GLFW_REQUIRE_INIT_OR_RETURN(None);
if (window->context.client == GLFW_NO_API)
{
_glfwInputError(GLFW_NO_WINDOW_CONTEXT, NULL);
return None;
}
return window->context.glx.window;
}
| {
"pile_set_name": "Github"
} |
<?php
namespace App\Http\Controllers;
use App\Models\Comment;
use App\Repositories\ArticleRepositoryEloquent;
use App\Models\Article;
use App\Repositories\CommentRepositoryEloquent;
use Auth;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
protected $article;
protected $comment;
/**
* ArticleController constructor.
* @param ArticleTagRepositoryEloquent $article
*/
public function __construct(ArticleRepositoryEloquent $article,CommentRepositoryEloquent $comment)
{
$this->article = $article;
$this->comment = $comment;
}
/**
* 显示文章详情
* Display article.
* @param $id
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index(Request $request,$id)
{
$article = $this->article->find($id);
$article->read_count = $article->read_count + 1;
$article->save();
$comments= $article->comments()->where('parent_id', 0)->orderBy('created_at', 'desc')->get();
for ($i=0; $i < sizeof($comments); $i++) {
$comments[$i]->created_at_diff = $comments[$i]->created_at->diffForHumans();
$comments[$i]->avatar_text = mb_substr($comments[$i]->name,0,1,'utf-8');
$replys = $comments[$i]->replys;
for ($j=0; $j < sizeof($replys); $j++) {
$replys[$j]->created_at_diff = $replys[$j]->created_at->diffForHumans();
$replys[$j]->avatar_text = mb_substr($replys[$j]->name,0,1,'utf-8');
}
}
$inputs = new CommentInputs;
if(Auth::id()){
$inputs->name = Auth::user()->name;
$inputs->email = Auth::user()->email;
$inputs->website =env('APP_URL');
}else{
$comment = Comment::where('ip',$request->ip())->orderBy('created_at', 'desc')->first();
if($comment){
$inputs->name=$comment->name;
$inputs->email=$comment->email;
$inputs->website=$comment->website;
}
}
return view('default.show_article', compact('article','comments','inputs'));
}
/**
* 归档查询列表
* Select the articles by Date.
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function selectDate()
{
// $articles=[];
// $years=[];
// $archives = $this->article->selectDate();
// foreach ($archives as $key=>$value){
// $archives[$key]['articles'] = $this->article->selectByDate($value['year'],$value['month']);
// $years[]=$value['year'];
// }
// $years=array_unique($years);
$articles = $this->article->selectDate();
return view('default.date_article',compact('articles'));
}
}
class CommentInputs{
public $name='';
public $email='';
public $website='';
} | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BuildMachineOSBuild</key>
<string>15C50</string>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>GenericUSBXHCI</string>
<key>CFBundleIdentifier</key>
<string>net.osx86.kexts.GenericUSBXHCI</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>GenericUSBXHCI</string>
<key>CFBundlePackageType</key>
<string>KEXT</string>
<key>CFBundleShortVersionString</key>
<string>1.2.11</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>MacOSX</string>
</array>
<key>CFBundleVersion</key>
<string>1.2.11</string>
<key>DTCompiler</key>
<string>com.apple.compilers.llvm.clang.1_0</string>
<key>DTPlatformBuild</key>
<string>7C68</string>
<key>DTPlatformVersion</key>
<string>GM</string>
<key>DTSDKBuild</key>
<string>12D75</string>
<key>DTSDKName</key>
<string>macosx10.8</string>
<key>DTXcode</key>
<string>0720</string>
<key>DTXcodeBuild</key>
<string>7C68</string>
<key>IOKitPersonalities</key>
<dict>
<key>GenericUSBXHCI</key>
<dict>
<key>#IOPCIPrimaryMatch</key>
<string>0x01941033</string>
<key>ASMediaEDLTAFix</key>
<true/>
<key>CFBundleIdentifier</key>
<string>net.osx86.kexts.GenericUSBXHCI</string>
<key>DeviceBlacklist</key>
<dict>
<key>1b73</key>
<integer>0</integer>
<key>8086</key>
<integer>0</integer>
</dict>
<key>DeviceWhitelist</key>
<dict>
<key>1b73_1000</key>
<integer>0</integer>
</dict>
<key>IOClass</key>
<string>GenericUSBXHCI</string>
<key>IOPCIClassMatch</key>
<string>0x0c033000</string>
<key>IOPCIPauseCompatible</key>
<true/>
<key>IOPCITunnelCompatible</key>
<true/>
<key>IOProbeScore</key>
<integer>1</integer>
<key>IOProviderClass</key>
<string>IOPCIDevice</string>
<key>IOUserClientClass</key>
<string>IOUSBControllerUserClient</string>
<key>IntelDoze</key>
<false/>
<key>RM,Build</key>
<string>Universal-RehabMan</string>
<key>RM,Version</key>
<string>GenericUSBXHCI 1.2.11</string>
</dict>
</dict>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2012-2014 Zenith432. All rights reserved.</string>
<key>OSBundleCompatibleVersion</key>
<string>1.0.0</string>
<key>OSBundleLibraries</key>
<dict>
<key>com.apple.iokit.IOPCIFamily</key>
<string>2.6</string>
<key>com.apple.iokit.IOUSBFamily</key>
<string>5.0.0a1</string>
<key>com.apple.kpi.iokit</key>
<string>10.6</string>
<key>com.apple.kpi.libkern</key>
<string>10.6</string>
<key>com.apple.kpi.mach</key>
<string>10.6</string>
<key>com.apple.kpi.unsupported</key>
<string>10.6</string>
</dict>
<key>OSBundleRequired</key>
<string>Root</string>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
<article id="comment{{ include.index }}" class="js-comment comment">
<div class="comment__avatar-wrapper">
<img class="comment__avatar" src="https://www.gravatar.com/avatar/{{ include.email }}?d=mm&s=80">
</div>
<div class="comment__content-wrapper">
<h3 class="comment__author">
{% unless include.url == blank %}
<a rel="nofollow" href="{{ include.url }}">{{ include.name }}</a>
{% else %}
{{ include.name }}
{% endunless %}
</h3>
<p class="comment__date">
{% if include.date %}
{% if include.index %}<a href="#comment{{ include.index }}">{% endif %}
<time datetime="{{ include.date | date_to_xmlschema }}">{{ include.date | date: "%B %d, %Y at %I:%M %p" }}</time>
{% if include.index %}</a>{% endif %}
{% endif %}
</p>
{{ include.message | markdownify }}
</div>
</article> | {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<body>
<div style="display: table; margin-left: 100px">
<div style="display: table-cell">
<div style="float: right;">
<input type="text" value="This is a test">
</div>
</div>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Note: the example only works with the code within the same release/branch.
package main
import (
"fmt"
"time"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
func main() {
// creates the in-cluster config
config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
for {
pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
// Examples for error handling:
// - Use helper functions like e.g. errors.IsNotFound()
// - And/or cast to StatusError and use its properties like e.g. ErrStatus.Message
_, err = clientset.CoreV1().Pods("default").Get("example-xxxxx", metav1.GetOptions{})
if errors.IsNotFound(err) {
fmt.Printf("Pod not found\n")
} else if statusError, isStatus := err.(*errors.StatusError); isStatus {
fmt.Printf("Error getting pod %v\n", statusError.ErrStatus.Message)
} else if err != nil {
panic(err.Error())
} else {
fmt.Printf("Found pod\n")
}
time.Sleep(10 * time.Second)
}
}
| {
"pile_set_name": "Github"
} |
using System.Reflection;
using System.Threading;
namespace System
{
internal sealed class TypeNameParser
{
internal static Type GetType(
string typeName,
Func<AssemblyName, Assembly> assemblyResolver,
Func<Assembly, string, bool, Type> typeResolver,
bool throwOnError,
bool ignoreCase,
ref StackCrawlMark stackMark)
{
TypeSpec spec = TypeSpec.Parse (typeName);
return spec.Resolve (assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark);
}
}
} | {
"pile_set_name": "Github"
} |
goog.module('com.google.j2cl.transpiler.readable.implementsgenericinterface.GenericInterface$impl');
const $Util = goog.require('nativebootstrap.Util$impl');
/**
* @interface
* @template T
*/
class GenericInterface {
static $clinit() {
GenericInterface.$clinit = () => {};
GenericInterface.$loadModules();
}
static $markImplementor(/** Function */ ctor) {
ctor.prototype
.$implements__com_google_j2cl_transpiler_readable_implementsgenericinterface_GenericInterface =
true;
}
/** @return {boolean} */
static $isInstance(/** ? */ instance) {
return instance != null &&
!!instance
.$implements__com_google_j2cl_transpiler_readable_implementsgenericinterface_GenericInterface;
}
static $loadModules() {}
}
$Util.$setClassMetadataForInterface(
GenericInterface,
'com.google.j2cl.transpiler.readable.implementsgenericinterface.GenericInterface');
GenericInterface.$markImplementor(/**@type {Function}*/ (GenericInterface));
exports = GenericInterface;
//# sourceMappingURL=GenericInterface.js.map
| {
"pile_set_name": "Github"
} |
ECS_LOGFILE=/var/log/ecs/ecs-agent.log
ECS_LOGLEVEL="{{settings.ecs.loglevel}}"
| {
"pile_set_name": "Github"
} |
/*-----------------------------------------------------------------
* Programmer(s): Daniel R. Reynolds @ SMU
* Alan C. Hindmarsh and Radu Serban @ LLNL
*-----------------------------------------------------------------
* SUNDIALS Copyright Start
* Copyright (c) 2002-2020, Lawrence Livermore National Security
* and Southern Methodist University.
* All rights reserved.
*
* See the top-level LICENSE and NOTICE files for details.
*
* SPDX-License-Identifier: BSD-3-Clause
* SUNDIALS Copyright End
*-----------------------------------------------------------------
* Implementation header file for IDAS's linear solver interface.
*-----------------------------------------------------------------*/
#ifndef _IDASLS_IMPL_H
#define _IDASLS_IMPL_H
#include <idas/idas_ls.h>
#include "idas_impl.h"
#ifdef __cplusplus /* wrapper to enable C++ usage */
extern "C" {
#endif
/*-----------------------------------------------------------------
Types : struct IDALsMemRec, struct *IDALsMem
The type IDALsMem is a pointer to a IDALsMemRec, which is a
structure containing fields that must be accessible by LS module
routines.
-----------------------------------------------------------------*/
typedef struct IDALsMemRec {
/* Linear solver type information */
booleantype iterative; /* is the solver iterative? */
booleantype matrixbased; /* is a matrix structure used? */
/* Jacobian construction & storage */
booleantype jacDQ; /* SUNTRUE if using internal DQ Jacobian approx. */
IDALsJacFn jac; /* Jacobian routine to be called */
void *J_data; /* J_data is passed to jac */
/* Linear solver, matrix and vector objects/pointers */
SUNLinearSolver LS; /* generic linear solver object */
SUNMatrix J; /* J = dF/dy + cj*dF/dy' */
N_Vector ytemp; /* temp vector used by IDAAtimesDQ */
N_Vector yptemp; /* temp vector used by IDAAtimesDQ */
N_Vector x; /* temp vector used by the solve function */
N_Vector ycur; /* current y vector in Newton iteration */
N_Vector ypcur; /* current yp vector in Newton iteration */
N_Vector rcur; /* rcur = F(tn, ycur, ypcur) */
/* Matrix-based solver, scale solution to account for change in cj */
booleantype scalesol;
/* Iterative solver tolerance */
realtype eplifac; /* nonlinear -> linear tol scaling factor */
realtype nrmfac; /* integrator -> LS norm conversion factor */
/* Statistics and associated parameters */
realtype dqincfac; /* dqincfac = optional increment factor in Jv */
long int nje; /* nje = no. of calls to jac */
long int npe; /* npe = total number of precond calls */
long int nli; /* nli = total number of linear iterations */
long int nps; /* nps = total number of psolve calls */
long int ncfl; /* ncfl = total number of convergence failures */
long int nreDQ; /* nreDQ = total number of calls to res */
long int njtsetup; /* njtsetup = total number of calls to jtsetup */
long int njtimes; /* njtimes = total number of calls to jtimes */
long int nst0; /* nst0 = saved nst (for performance monitor) */
long int nni0; /* nni0 = saved nni (for performance monitor) */
long int ncfn0; /* ncfn0 = saved ncfn (for performance monitor) */
long int ncfl0; /* ncfl0 = saved ncfl (for performance monitor) */
long int nwarn; /* nwarn = no. of warnings (for perf. monitor) */
int last_flag; /* last error return flag */
/* Preconditioner computation
(a) user-provided:
- pdata == user_data
- pfree == NULL (the user dealocates memory)
(b) internal preconditioner module
- pdata == ida_mem
- pfree == set by the prec. module and called in idaLsFree */
IDALsPrecSetupFn pset;
IDALsPrecSolveFn psolve;
int (*pfree)(IDAMem IDA_mem);
void *pdata;
/* Jacobian times vector compuation
(a) jtimes function provided by the user:
- jt_data == user_data
- jtimesDQ == SUNFALSE
(b) internal jtimes
- jt_data == ida_mem
- jtimesDQ == SUNTRUE */
booleantype jtimesDQ;
IDALsJacTimesSetupFn jtsetup;
IDALsJacTimesVecFn jtimes;
IDAResFn jt_res;
void *jt_data;
} *IDALsMem;
/*-----------------------------------------------------------------
Prototypes of internal functions
-----------------------------------------------------------------*/
/* Interface routines called by system SUNLinearSolver */
int idaLsATimes(void *ida_mem, N_Vector v, N_Vector z);
int idaLsPSetup(void *ida_mem);
int idaLsPSolve(void *ida_mem, N_Vector r, N_Vector z,
realtype tol, int lr);
/* Difference quotient approximation for Jac times vector */
int idaLsDQJtimes(realtype tt, N_Vector yy, N_Vector yp,
N_Vector rr, N_Vector v, N_Vector Jv,
realtype c_j, void *data,
N_Vector work1, N_Vector work2);
/* Difference-quotient Jacobian approximation routines */
int idaLsDQJac(realtype tt, realtype c_j, N_Vector yy, N_Vector yp,
N_Vector rr, SUNMatrix Jac, void *data,
N_Vector tmp1, N_Vector tmp2, N_Vector tmp3);
int idaLsDenseDQJac(realtype tt, realtype c_j, N_Vector yy,
N_Vector yp, N_Vector rr, SUNMatrix Jac,
IDAMem IDA_mem, N_Vector tmp1);
int idaLsBandDQJac(realtype tt, realtype c_j, N_Vector yy,
N_Vector yp, N_Vector rr, SUNMatrix Jac,
IDAMem IDA_mem, N_Vector tmp1,
N_Vector tmp2, N_Vector tmp3);
/* Generic linit/lsetup/lsolve/lperf/lfree interface routines for IDA to call */
int idaLsInitialize(IDAMem IDA_mem);
int idaLsSetup(IDAMem IDA_mem, N_Vector y, N_Vector yp, N_Vector r,
N_Vector vt1, N_Vector vt2, N_Vector vt3);
int idaLsSolve(IDAMem IDA_mem, N_Vector b, N_Vector weight,
N_Vector ycur, N_Vector ypcur, N_Vector rescur);
int idaLsPerf(IDAMem IDA_mem, int perftask);
int idaLsFree(IDAMem IDA_mem);
/* Auxilliary functions */
int idaLsInitializeCounters(IDALsMem idals_mem);
int idaLs_AccessLMem(void* ida_mem, const char* fname,
IDAMem* IDA_mem, IDALsMem* idals_mem);
/*---------------------------------------------------------------
Error and Warning Messages
---------------------------------------------------------------*/
#if defined(SUNDIALS_EXTENDED_PRECISION)
#define MSG_LS_TIME "at t = %Lg, "
#define MSG_LS_FRMT "%Le."
#elif defined(SUNDIALS_DOUBLE_PRECISION)
#define MSG_LS_TIME "at t = %lg, "
#define MSG_LS_FRMT "%le."
#else
#define MSG_LS_TIME "at t = %g, "
#define MSG_LS_FRMT "%e."
#endif
/* Error Messages */
#define MSG_LS_IDAMEM_NULL "Integrator memory is NULL."
#define MSG_LS_MEM_FAIL "A memory request failed."
#define MSG_LS_BAD_NVECTOR "A required vector operation is not implemented."
#define MSG_LS_BAD_SIZES "Illegal bandwidth parameter(s). Must have 0 <= ml, mu <= N-1."
#define MSG_LS_BAD_LSTYPE "Incompatible linear solver type."
#define MSG_LS_LMEM_NULL "Linear solver memory is NULL."
#define MSG_LS_BAD_GSTYPE "gstype has an illegal value."
#define MSG_LS_NEG_MAXRS "maxrs < 0 illegal."
#define MSG_LS_NEG_EPLIFAC "eplifac < 0.0 illegal."
#define MSG_LS_NEG_DQINCFAC "dqincfac < 0.0 illegal."
#define MSG_LS_PSET_FAILED "The preconditioner setup routine failed in an unrecoverable manner."
#define MSG_LS_PSOLVE_FAILED "The preconditioner solve routine failed in an unrecoverable manner."
#define MSG_LS_JTSETUP_FAILED "The Jacobian x vector setup routine failed in an unrecoverable manner."
#define MSG_LS_JTIMES_FAILED "The Jacobian x vector routine failed in an unrecoverable manner."
#define MSG_LS_JACFUNC_FAILED "The Jacobian routine failed in an unrecoverable manner."
#define MSG_LS_MATZERO_FAILED "The SUNMatZero routine failed in an unrecoverable manner."
/* Warning Messages */
#define MSG_LS_WARN "Warning: " MSG_LS_TIME "poor iterative algorithm performance. "
#define MSG_LS_CFN_WARN MSG_LS_WARN "Nonlinear convergence failure rate is " MSG_LS_FRMT
#define MSG_LS_CFL_WARN MSG_LS_WARN "Linear convergence failure rate is " MSG_LS_FRMT
/*-----------------------------------------------------------------
PART II - backward problems
-----------------------------------------------------------------*/
/*-----------------------------------------------------------------
Types : IDALsMemRecB, IDALsMemB
IDASetLinearSolverB attaches such a structure to the lmemB
field of IDAadjMem
-----------------------------------------------------------------*/
typedef struct IDALsMemRecB {
IDALsJacFnB jacB;
IDALsJacFnBS jacBS;
IDALsJacTimesSetupFnB jtsetupB;
IDALsJacTimesSetupFnBS jtsetupBS;
IDALsJacTimesVecFnB jtimesB;
IDALsJacTimesVecFnBS jtimesBS;
IDALsPrecSetupFnB psetB;
IDALsPrecSetupFnBS psetBS;
IDALsPrecSolveFnB psolveB;
IDALsPrecSolveFnBS psolveBS;
void *P_dataB;
} *IDALsMemB;
/*-----------------------------------------------------------------
Prototypes of internal functions
-----------------------------------------------------------------*/
int idaLsFreeB(IDABMem IDAB_mem);
int idaLs_AccessLMemB(void *ida_mem, int which, const char *fname,
IDAMem *IDA_mem, IDAadjMem *IDAADJ_mem,
IDABMem *IDAB_mem, IDALsMemB *idalsB_mem);
int idaLs_AccessLMemBCur(void *ida_mem, const char *fname,
IDAMem *IDA_mem, IDAadjMem *IDAADJ_mem,
IDABMem *IDAB_mem, IDALsMemB *idalsB_mem);
/*-----------------------------------------------------------------
Error Messages
-----------------------------------------------------------------*/
#define MSG_LS_CAMEM_NULL "idaadj_mem = NULL illegal."
#define MSG_LS_LMEMB_NULL "Linear solver memory is NULL for the backward integration."
#define MSG_LS_BAD_T "Bad t for interpolation."
#define MSG_LS_BAD_WHICH "Illegal value for which."
#define MSG_LS_NO_ADJ "Illegal attempt to call before calling IDAAdjInit."
#ifdef __cplusplus
}
#endif
#endif
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
* Copyright (c) 1996,1999 by Internet Software Consortium.
*
* 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 ISC DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC 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.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static const char rcsid[] = "$Id: inet_pton.c,v 1.3.18.2 2005/07/28 07:38:07 marka Exp $";
#endif /* LIBC_SCCS and not lint */
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/systm.h>
#include <netinet/in.h>
#if __FreeBSD_version < 700000
#define strchr index
#endif
/*%
* WARNING: Don't even consider trying to compile this on a system where
* sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX.
*/
static int inet_pton4(const char *src, u_char *dst);
static int inet_pton6(const char *src, u_char *dst);
/* int
* inet_pton(af, src, dst)
* convert from presentation format (which usually means ASCII printable)
* to network format (which is usually some kind of binary format).
* return:
* 1 if the address was valid for the specified address family
* 0 if the address wasn't valid (`dst' is untouched in this case)
* -1 if some other error occurred (`dst' is untouched in this case, too)
* author:
* Paul Vixie, 1996.
*/
int
inet_pton(int af, const char *src, void *dst)
{
switch (af) {
case AF_INET:
return (inet_pton4(src, dst));
case AF_INET6:
return (inet_pton6(src, dst));
default:
return (-1);
}
/* NOTREACHED */
}
/* int
* inet_pton4(src, dst)
* like inet_aton() but without all the hexadecimal and shorthand.
* return:
* 1 if `src' is a valid dotted quad, else 0.
* notice:
* does not touch `dst' unless it's returning 1.
* author:
* Paul Vixie, 1996.
*/
static int
inet_pton4(const char *src, u_char *dst)
{
static const char digits[] = "0123456789";
int saw_digit, octets, ch;
#define NS_INADDRSZ 4
u_char tmp[NS_INADDRSZ], *tp;
saw_digit = 0;
octets = 0;
*(tp = tmp) = 0;
while ((ch = *src++) != '\0') {
const char *pch;
if ((pch = strchr(digits, ch)) != NULL) {
u_int new = *tp * 10 + (pch - digits);
if (saw_digit && *tp == 0)
return (0);
if (new > 255)
return (0);
*tp = new;
if (!saw_digit) {
if (++octets > 4)
return (0);
saw_digit = 1;
}
} else if (ch == '.' && saw_digit) {
if (octets == 4)
return (0);
*++tp = 0;
saw_digit = 0;
} else
return (0);
}
if (octets < 4)
return (0);
memcpy(dst, tmp, NS_INADDRSZ);
return (1);
}
/* int
* inet_pton6(src, dst)
* convert presentation level address to network order binary form.
* return:
* 1 if `src' is a valid [RFC1884 2.2] address, else 0.
* notice:
* (1) does not touch `dst' unless it's returning 1.
* (2) :: in a full address is silently ignored.
* credit:
* inspired by Mark Andrews.
* author:
* Paul Vixie, 1996.
*/
static int
inet_pton6(const char *src, u_char *dst)
{
static const char xdigits_l[] = "0123456789abcdef",
xdigits_u[] = "0123456789ABCDEF";
#define NS_IN6ADDRSZ 16
#define NS_INT16SZ 2
u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp;
const char *xdigits, *curtok;
int ch, seen_xdigits;
u_int val;
memset((tp = tmp), '\0', NS_IN6ADDRSZ);
endp = tp + NS_IN6ADDRSZ;
colonp = NULL;
/* Leading :: requires some special handling. */
if (*src == ':')
if (*++src != ':')
return (0);
curtok = src;
seen_xdigits = 0;
val = 0;
while ((ch = *src++) != '\0') {
const char *pch;
if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL)
pch = strchr((xdigits = xdigits_u), ch);
if (pch != NULL) {
val <<= 4;
val |= (pch - xdigits);
if (++seen_xdigits > 4)
return (0);
continue;
}
if (ch == ':') {
curtok = src;
if (!seen_xdigits) {
if (colonp)
return (0);
colonp = tp;
continue;
} else if (*src == '\0') {
return (0);
}
if (tp + NS_INT16SZ > endp)
return (0);
*tp++ = (u_char) (val >> 8) & 0xff;
*tp++ = (u_char) val & 0xff;
seen_xdigits = 0;
val = 0;
continue;
}
if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) &&
inet_pton4(curtok, tp) > 0) {
tp += NS_INADDRSZ;
seen_xdigits = 0;
break; /*%< '\\0' was seen by inet_pton4(). */
}
return (0);
}
if (seen_xdigits) {
if (tp + NS_INT16SZ > endp)
return (0);
*tp++ = (u_char) (val >> 8) & 0xff;
*tp++ = (u_char) val & 0xff;
}
if (colonp != NULL) {
/*
* Since some memmove()'s erroneously fail to handle
* overlapping regions, we'll do the shift by hand.
*/
const int n = tp - colonp;
int i;
if (tp == endp)
return (0);
for (i = 1; i <= n; i++) {
endp[- i] = colonp[n - i];
colonp[n - i] = 0;
}
tp = endp;
}
if (tp != endp)
return (0);
memcpy(dst, tmp, NS_IN6ADDRSZ);
return (1);
}
/*! \file */
| {
"pile_set_name": "Github"
} |
# Microsoft Developer Studio Project File - Name="MasterServer" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Console Application" 0x0103
CFG=MasterServer - Win32 Client Debug
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "Master.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "Master.mak" CFG="MasterServer - Win32 Client Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "MasterServer - Win32 Release" (based on "Win32 (x86) Console Application")
!MESSAGE "MasterServer - Win32 Debug" (based on "Win32 (x86) Console Application")
!MESSAGE "MasterServer - Win32 Client Debug" (based on "Win32 (x86) Console Application")
!MESSAGE "MasterServer - Win32 Client Release" (based on "Win32 (x86) Console Application")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
RSC=rc.exe
!IF "$(CFG)" == "MasterServer - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "../../bin/VC/Release/MasterServer"
# PROP Intermediate_Dir "../../objs/VC/Release/MasterServer"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
# ADD CPP /nologo /W4 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__STDC__" /D "_POSIX_" /FR /YX /FD /c
# ADD BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
# ADD LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /machine:I386 /out:"../../bin/VC/Release/MasterServer.exe"
!ELSEIF "$(CFG)" == "MasterServer - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "../../bin/VC/Debug/MasterServer"
# PROP Intermediate_Dir "../../objs/VC/Debug/MasterServer"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
# ADD CPP /nologo /W4 /Gm /GX /ZI /Od /D "_DEBUG" /D "_WIN32" /D "__DEBUG__" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__STDC__" /D "_POSIX_" /FR /YX /FD /GZ /c
# ADD BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
# ADD LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /debug /machine:I386 /out:"../../bin/VC/Debug/MasterServer.exe" /pdbtype:sept
!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "MasterServer___Win32_Client_Debug"
# PROP BASE Intermediate_Dir "MasterServer___Win32_Client_Debug"
# PROP BASE Ignore_Export_Lib 0
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "../../bin/VC/Debug/MasterClient"
# PROP Intermediate_Dir "../../objs/VC/Debug/MasterClient"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W4 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /D "__STDC__" /YX /FD /GZ /c
# ADD CPP /nologo /W4 /Gm /GX /ZI /Od /D "_DEBUG" /D "_WIN32" /D "__DEBUG__" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__STDC__" /D "_POSIX_" /FR /YX /FD /GZ /c
# ADD BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /debug /machine:I386 /out:"../../bin/VC/Debug/MasterServer.exe" /pdbtype:sept
# ADD LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /debug /machine:I386 /out:"../../bin/VC/Debug/MasterClient.exe" /pdbtype:sept
!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "MasterServer___Win32_Client_Release"
# PROP BASE Intermediate_Dir "MasterServer___Win32_Client_Release"
# PROP BASE Ignore_Export_Lib 0
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "../../bin/VC/Release/MasterClient"
# PROP Intermediate_Dir "../../objs/VC/Release/MasterClient"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W4 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
# ADD CPP /nologo /W4 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__STDC__" /D "_POSIX_" /FR /YX /FD /c
# ADD BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /machine:I386 /out:"../../bin/VC/Release/MasterServer.exe"
# ADD LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /machine:I386 /out:"../../bin/VC/Release/MasterClient.exe"
!ENDIF
# Begin Target
# Name "MasterServer - Win32 Release"
# Name "MasterServer - Win32 Debug"
# Name "MasterServer - Win32 Client Debug"
# Name "MasterServer - Win32 Client Release"
# Begin Group "Source Files"
# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
# Begin Source File
SOURCE=.\client.cpp
!IF "$(CFG)" == "MasterServer - Win32 Release"
# PROP Exclude_From_Build 1
!ELSEIF "$(CFG)" == "MasterServer - Win32 Debug"
# PROP Exclude_From_Build 1
!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Debug"
# PROP BASE Exclude_From_Build 1
!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Release"
# PROP BASE Exclude_From_Build 1
!ENDIF
# End Source File
# Begin Source File
SOURCE=.\common.cpp
# End Source File
# Begin Source File
SOURCE=.\crypt.cpp
# End Source File
# Begin Source File
SOURCE=.\ipcs.cpp
# End Source File
# Begin Source File
SOURCE=.\server.cpp
!IF "$(CFG)" == "MasterServer - Win32 Release"
!ELSEIF "$(CFG)" == "MasterServer - Win32 Debug"
!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Debug"
# PROP Exclude_From_Build 1
!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Release"
# PROP Exclude_From_Build 1
!ENDIF
# End Source File
# Begin Source File
SOURCE=.\srvlist.cpp
# End Source File
# Begin Source File
SOURCE=.\stats.cpp
# End Source File
# End Group
# Begin Group "Header Files"
# PROP Default_Filter "h;hpp;hxx;hm;inl"
# Begin Source File
SOURCE=.\common.h
# End Source File
# Begin Source File
SOURCE=.\ipcs.h
# End Source File
# Begin Source File
SOURCE=.\srvlist.h
# End Source File
# Begin Source File
SOURCE=.\stats.h
# End Source File
# End Group
# Begin Group "Resource Files"
# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
# End Group
# End Target
# End Project
| {
"pile_set_name": "Github"
} |
/*************************************************************
*
* MathJax/localization/it/FontWarnings.js
*
* Copyright (c) 2009-2016 The MathJax Consortium
*
* 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.
*
*/
MathJax.Localization.addTranslation("it","FontWarnings",{
version: "2.7.2",
isLoaded: true,
strings: {
webFont: "MathJax sta usando dei web font per visualizzare le formule di questa pagina. Tali font richiedono tempo per essere scaricati, perci\u00F2 la pagina sarebbe resa pi\u00F9 velocemente se tu installassi dei font matematici direttamente nella cartella dei font di sistema.",
imageFonts: "MathJax sta usando dei font immagine invece di quelli locali o dei web font. Questo rallenta la resa oltremodo e le formule potrebbero non essere stampate alla massima risoluzione dalla tua stampante.",
noFonts: "MathJax non \u00E8 in grado di trovare un font adatto a visualizzare le formule e i font immagini non sono disponibili; perci\u00F2 utilizzer\u00E1 dei generici caratteri unicode sperando che il tuo browser sia in grado di visualizzarli. Alcuni caratteri potrebbero non essere mostrati correttamente o mancare del tutto.",
webFonts: "I browser attuali permettono di scaricare i font dal web. Aggiornando il tuo browser a una versione pi\u00F9 recente (o cambiando del tutto browser) la qualit\u00E1 delle formule di questa pagina potrebbe migliorare.",
fonts: "MathJax pu\u00F2 usare sia gli [STIX font](%1) che i [MathJax TeX font](%2). Scarica e installa uno di questi font per avere una resa migliore da MathJax.",
STIXPage: "Questa pagina richiede l'uso degli [STIX font](%1). Scarica e installa i suddetti font per avere una resa migliore da MathJax.",
TeXPage: "Questa pagina richiede l'uso dei [MathJax TeX font](%1). Scarica e installa i suddetti font per avere una resa migliore da MathJax."
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/it/FontWarnings.js");
| {
"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.commons.math.stat.descriptive;
/**
* Test cases for the {@link SynchronizedDescriptiveStatisticsTest} class.
* @version $Revision$ $Date: 2007-08-16 15:36:33 -0500 (Thu, 16 Aug
* 2007) $
*/
public final class SynchronizedDescriptiveStatisticsTest extends DescriptiveStatisticsTest {
public SynchronizedDescriptiveStatisticsTest(String name) {
super(name);
}
@Override
protected DescriptiveStatistics createDescriptiveStatistics() {
return new SynchronizedDescriptiveStatistics();
}
}
| {
"pile_set_name": "Github"
} |
using Chutzpah.Exceptions;
using Chutzpah.Models;
using Chutzpah.Server.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Internal.Networking;
using Microsoft.AspNetCore.StaticFiles;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
namespace Chutzpah.Server
{
public class ChutzpahWebServerFactory : IChutzpahWebServerFactory
{
readonly IFileProbe fileProbe;
public ChutzpahWebServerFactory(IFileProbe fileProbe)
{
this.fileProbe = fileProbe;
}
public IChutzpahWebServerHost CreateServer(ChutzpahWebServerConfiguration configuration, IChutzpahWebServerHost activeWebServerHost)
{
if (activeWebServerHost != null
&& activeWebServerHost.IsRunning
&& activeWebServerHost.RootPath.Equals(configuration.RootPath, StringComparison.OrdinalIgnoreCase))
{
// If the requested server is already running just re-use it
return activeWebServerHost;
}
var builtInDependencyFolder = fileProbe.BuiltInDependencyDirectory;
return BuildHost(configuration.RootPath, configuration.DefaultPort.Value, builtInDependencyFolder);
}
private void AddFileCacheHeaders(StaticFileResponseContext context)
{
// If we see you have sha on the url we send aggresive cache values
// otherwise we tell to not cache ever
if(context.Context.Request.Query.ContainsKey(Constants.FileUrlShaKey))
{
// Cache for a year
context.Context.Response.Headers["Cache-Control"] = "public, max-age=31536000";
}
else
{
context.Context.Response.Headers["Cache-Control"] = "no-cache";
context.Context.Response.Headers["Pragma"] = "no-cache";
context.Context.Response.Headers["Expires"] = "Thu, 01 Jan 1970 00:00:00 GMT";
}
}
private ChutzpahWebServerHost BuildHost(string rootPath, int defaultPort, string builtInDependencyFolder)
{
var attemptLimit = Constants.WebServerCreationAttemptLimit;
var success = false;
do
{
// We can try multiple times to build the webserver. The reason is there is a possible race condition where
// between when we find a free port and when we start the server that port may have been taken. To mitigate this we
// can retry to hopefully avoid this issue.
attemptLimit--;
var port = FindFreePort(defaultPort);
try
{
ChutzpahTracer.TraceInformation("Creating Web Server Host at path {0} and port {1}", rootPath, port);
var host = new WebHostBuilder()
.UseUrls($"http://localhost:{port}")
.UseContentRoot(rootPath)
.UseWebRoot("")
.UseKestrel()
.Configure((app) =>
{
var env = (IHostingEnvironment)app.ApplicationServices.GetService(typeof(IHostingEnvironment));
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = AddFileCacheHeaders,
ServeUnknownFileTypes = true,
FileProvider = new ChutzpahServerFileProvider(env.ContentRootPath, builtInDependencyFolder)
});
app.Run(async (context) =>
{
if (context.Request.Path == "/")
{
await context.Response.WriteAsync($"Chutzpah Web Server (Version { Assembly.GetEntryAssembly().GetName().Version})");
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
}
});
})
.Build();
host.Start();
success = true;
return ChutzpahWebServerHost.Create(host, rootPath, port);
}
catch (Exception ex) when (attemptLimit > 0)
{
ChutzpahTracer.TraceError(ex, "Unable to create web server host at path {0} and port {1}. Trying again...", rootPath, port);
}
}
while (!success && attemptLimit > 0);
throw new ChutzpahException("Failed to create web server. This should never be hit!");
}
public static int FindFreePort(int initialPort)
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
try
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, initialPort));
}
catch (SocketException)
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
}
return ((IPEndPoint)socket.LocalEndPoint).Port;
}
}
}
}
| {
"pile_set_name": "Github"
} |
# Usage
`amp [dir | file1 file2 ...]`
!!! abstract "Key Reference"
What follows is only an overview of Amp. If you'd like to see an exhaustive
list of its functionality, you can run `application::display_default_keymap` from [command mode](usage.md#running-commands), which will show you _all_ of the default key bindings
and the commands they invoke.
## Exiting
Before launching Amp, it's always a good idea to know how to quit. Type `Q (Shift+q)` to quit when in normal mode.
!!! note
**Amp will happily close modified buffers without warning when quitting**.
_Sharp tools_, folks. Given that, you'll more often opt to close buffers
beforehand using `q` (which _will_ prompt if the buffer is modified) until
the workspace is empty.
## Working with Files
Unless you've specified file paths when running Amp, you'll be greeted with a splash screen. You can find and edit files in open mode, by hitting `Space`.
!!! warning
This will **recursively index the current directory and all subdirectories.**
It's meant to be used in project directories; don't use it from paths like `/` or `~`.
### Using the File Finder
Amp's file finder is a little different than most. Rather than using a string fuzzing algorithm to match file paths against the query, it uses string fragments. Instead of typing full words, use fragments of the path name, separated by spaces:
`mod app op` --> src/__mod__els/__app__lications/__mod__es/__op__en.rs
Search terms _must_ occur in the path, which in practice tends to produce fewer, more accurate results than fuzzy matching. Order of tokens doesn't matter; you can add fragments from parent directory names after file name fragments.
!!! note
Hitting `backspace` will delete the entire last token, instead of the last character. The reasoning is, given the typical size of tokens, it's almost always easier to re-enter the last entry than to correct it.
#### Selecting/Opening Matches
Once the file you're searching for is shown, you can select it using the `up` and `down` arrows, followed by `Enter`. The file finder also has its own insert/normal modes. Hitting `esc` will grey out the input area and expose the following key bindings:
Key | Action
------------- | ------
`Space/Enter` | Open the selected file
`j` | Select the next result
`k` | Select the previous result
`i` | Edit the search query
`esc` | Leave open mode
!!! tip
The search/select UI pattern used in open mode is re-used elsewhere, with the same fragment matching and insert/normal sub-mode behaviour. Take the time to get familiar with it; it'll pay dividends when using other features in Amp.
#### Exclusions
By default, Amp's open mode doesn't index `.git` directories. If you'd like to change that behaviour, [you can redefine the exclusion patterns](configuration.md#excluding-filesdirectories) in the application preferences.
### Closing
From normal mode press `q` to close the current buffer. If the file has
modifications and hasn't been saved, you will be asked to confirm.
### Saving
Press `s` to save the current buffer. The UI will indicate when a buffer has
unsaved modifications: their path will be rendered in bold, with an asterisk,
and the normal mode indicator will be orange. These are cleared on save (or if
the buffer is rolled back to an unmodified state with `undo` or `reload`).
### Creating
If you'd like to create a new file, start by opening a new, empty buffer by
pressing `B`. When you're ready, press `s` to save it; Amp will realize it has
no path, and you'll be prompted to enter one, after which the buffer will be
written to disk.
## Movement
Scrolling up/down in normal mode uses the `,` and `m` keys, respectively.
For cursor movement, the usual `h,j,k,l` movement commands are there, along with `w,b` word equivalents. Anything more than that and you'll want to use jump mode.
### Jump Mode
Press `f` to switch to jump mode. Elements on-screen will be prefixed with a two character jump token. Type the characters to jump to the associated element.

!!! tip
Jump mode won't target one-character elements. You can use `'` to switch to a single-character version instead. The scope is much more restricted; it's ideally suited for jumping to smaller, nearby elements.
### Jumping to Symbols
For files with syntax support, you can jump to class, method, and function definitions using symbol mode. Hit `Enter` in normal mode to use the symbol finder, which works identically to [open mode](#open-mode).
### Jumping to a specific line
You can also move the cursor to a specific line using `g`, which will prompt for a target line.
## Working with Text
### Inserting Text
Use `i` to enter insert mode. When you're done adding text, hit `esc` to return to normal mode.
### Editing Text
From normal mode, there are a few ways to interact with text:
Key | Action
----------- | ------
`Backspace` | Delete the character to the left of the cursor
`x` | Delete the character to the right of the cursor
`d` | Delete from the cursor to the end of the word
`c` | Change the text from the cursor to the end of the word
`y` | Copy the current line
### Selecting Text
To start a text selection range, use `v`. Move the cursor using [movement keys](#movement), and then delete, change, or copy the selected text. To select entire lines of text, use `V` instead.
!!! tip
Although a matter of personal preference, configuring your terminal to use a vertical bar cursor, rather than a block, can make edit operations and text selection more intuitive.
## Using the Clipboard
Amp has built-in support for using the system clipboard; there is no additional
configuration nor external dependencies required. Use can use the following keys
to interact with it:
Key | Action
--- | ------
`y` | Copy the current selection (if present) or line
`p` | Paste at the cursor
`P` | Paste on the line above
!!! note
Like in Vim, whenever data is removed or changed in the buffer (e.g.
changing a word, deleting the current line), it's copied to the clipboard.
## Running Commands
Under the hood, _all of Amp's functionality is exposed through a set of
**commands**_; the UI is driven entirely by a simple `key` --> `command` map.
You can run any of these directly by switching to command mode (`0` from normal
mode), which will bring up a search prompt. If you'd rather browse the full list
of commands, you can run the `application::display_available_commands` command
to open the complete set in a new buffer.
!!! tip
Command mode itself isn't really about discovery; it's a handy means of
triggering infrequently-used functionality that doesn't merit a dedicated
key binding (think converting tabs to spaces).
## Search
You can search using `/` to enter a query. If matches are found, the cursor will be moved ahead to the first match (relative to its current position). You can navigate to the next/previous match using `n` and `N`, respectively. Searches will wrap once the EOF is reached.
Most of the keybindings you'd expect will work: `c` to change the selected content, `d` to delete it, `p` to paste the buffer contents.
### Replace
Amp doesn't have a proper search and replace workflow _yet_; you can't specify a replacement value after searching. That being said, you can accomplish this with a little workaround:
1. Replace the first occurrence manually (`c` to replace the current result)
2. Copy the updated content (`v` to enter select mode, `y` to copy selected content)
3. Start the search again (`n` to find the next result)
4. Paste to replace the content (`p`)
!!! warning
Amp doesn't currently support advanced search options (regular expressions, case sensitivity, recursive file search, etc.). This isn't intentional; these features will eventually be added.
## Suspend
It can be handy to temporarily leave Amp, interact with your shell, and then
resume editing. Hit `z` in normal mode to suspend Amp and return to your shell,
and run `fg` to resume it when you're ready to edit again.
## Git
Amp provides basic [Git](https://git-scm.com) integration. The lower-right
portion of the status bar displays the current buffer's status. The options are:
* `[untracked]`: the file has never been added to the repository
* `[ok]`: the file is unmodified (matches the repository version)
* `[modified]`: the file has local modifications
* `[staged]`: the file has local modifications, all of which are staged for commit
* `[partially staged]`: the file has local modifications, _some_ of which are staged for commit
### Staging changes
You can use the `=` key to stage the current file. This _doesn't_ support staging
line ranges, _yet_.
### Copying a GitHub URL
When collaborating with others, it can be handy to share a link to a file you're
working on. The `R` key can be used to copy the current file's GitHub URL. If in
select-line mode, the selected line range will also be included in the URL.
!!! note
This feature makes one assumption: that the GitHub remote is configured as
`origin`.
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<phpunit printerFile="CustomPrinter.php" printerClass="CustomPrinter" /> | {
"pile_set_name": "Github"
} |
#include <sys/file.h>
#include "syscall.h"
int flock(int fd, int op)
{
return syscall(SYS_flock, fd, op);
}
| {
"pile_set_name": "Github"
} |
export interface OptionsSchema {
// Whether to skip package.json install.
skipPackageJson: boolean;
// Used to specify required module names
modules: string;
// Used to specify custom module path
modulePath: string;
// Used to specify theme name
theme: 'material' | 'fabric' | 'bootstrap' | 'highcontrast';
// Name of the project to target.
project?: string;
}
export interface LibOptionsSchema {
// Package name
pkgName: string;
// Package version
pkgVer: string;
// Library base module name
moduleName: string;
// Theme version
themeVer: string;
}
| {
"pile_set_name": "Github"
} |
{
"extends": "../tslint.json",
"rules": {
"directive-selector": [
true,
"attribute",
"app",
"camelCase"
],
"component-selector": [
true,
"element",
"app",
"kebab-case"
]
}
}
| {
"pile_set_name": "Github"
} |
// errorcheck
// Copyright 2010 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.
package main
var x map[string]string{"a":"b"} // ERROR "unexpected { at end of statement|unexpected { after top level declaration|expected ';' or newline after top level declaration"
| {
"pile_set_name": "Github"
} |
package mock
import (
"context"
"github.com/influxdata/platform"
)
var _ platform.OrganizationService = &OrganizationService{}
// OrganizationService is a mock organization server.
type OrganizationService struct {
FindOrganizationByIDF func(ctx context.Context, id platform.ID) (*platform.Organization, error)
FindOrganizationF func(ctx context.Context, filter platform.OrganizationFilter) (*platform.Organization, error)
FindOrganizationsF func(ctx context.Context, filter platform.OrganizationFilter, opt ...platform.FindOptions) ([]*platform.Organization, int, error)
CreateOrganizationF func(ctx context.Context, b *platform.Organization) error
UpdateOrganizationF func(ctx context.Context, id platform.ID, upd platform.OrganizationUpdate) (*platform.Organization, error)
DeleteOrganizationF func(ctx context.Context, id platform.ID) error
}
//FindOrganizationByID calls FindOrganizationByIDF.
func (s *OrganizationService) FindOrganizationByID(ctx context.Context, id platform.ID) (*platform.Organization, error) {
return s.FindOrganizationByIDF(ctx, id)
}
//FindOrganization calls FindOrganizationF.
func (s *OrganizationService) FindOrganization(ctx context.Context, filter platform.OrganizationFilter) (*platform.Organization, error) {
return s.FindOrganizationF(ctx, filter)
}
//FindOrganizations calls FindOrganizationsF.
func (s *OrganizationService) FindOrganizations(ctx context.Context, filter platform.OrganizationFilter, opt ...platform.FindOptions) ([]*platform.Organization, int, error) {
return s.FindOrganizationsF(ctx, filter, opt...)
}
// CreateOrganization calls CreateOrganizationF.
func (s *OrganizationService) CreateOrganization(ctx context.Context, b *platform.Organization) error {
return s.CreateOrganizationF(ctx, b)
}
// UpdateOrganization calls UpdateOrganizationF.
func (s *OrganizationService) UpdateOrganization(ctx context.Context, id platform.ID, upd platform.OrganizationUpdate) (*platform.Organization, error) {
return s.UpdateOrganizationF(ctx, id, upd)
}
// DeleteOrganization calls DeleteOrganizationF.
func (s *OrganizationService) DeleteOrganization(ctx context.Context, id platform.ID) error {
return s.DeleteOrganizationF(ctx, id)
}
| {
"pile_set_name": "Github"
} |
<blockquote>
<p>In today’s society, we have an epidemic where millions of people have no fucks to give. With our ERC-20 FUCK token we have solved the “lack of FUCKs” problem. Tip your friends 0.001 FUCKs, or 1 FUCK, it doesn’t matter how many FUCKs you give. All that matters is you are contributing something to society.</p>
<footer><a href="http://www.fucktoken.io/" target="_blank">http://www.fucktoken.io/</a></footer>
</blockquote>
| {
"pile_set_name": "Github"
} |
' TEST_MODE : COMPILE_ONLY_FAIL
type TheBase
i as integer
end type
type Derived extends TheBase
i1 as integer
end type
type Pod
i as integer
end type
dim as Derived ptr pderived
dim as integer ptr pint
pint = pderived
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.