doc_id
stringlengths 36
36
| metadata
dict | input
stringlengths 28
4.3k
| output
stringlengths 11
5.45k
|
---|---|---|---|
8b4b2458-8f29-4f75-a014-9b639a13f942 | {
"language": "Ada"
} | ```ada
```
Refactor Buffered_Stream and Print_Stream - move the TR package instantiation in a separate file | ```ada
-----------------------------------------------------------------------
-- util-streams-texts-tr -- Text translation utilities on streams
-- Copyright (C) 2010, 2011, 2012, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
with Util.Texts.Transforms;
with Ada.Characters.Handling;
package Util.Streams.Texts.TR is
new Util.Texts.Transforms (Stream => Print_Stream'Class,
Char => Character,
Input => String,
Put => Write_Char,
To_Upper => Ada.Characters.Handling.To_Upper,
To_Lower => Ada.Characters.Handling.To_Lower);
``` |
503aa1d6-2ace-404a-ab95-f52ab7979019 | {
"language": "Ada"
} | ```ada
```
Implement operations to set the key and IV for AES-128/196/256 encryption and decryption streams | ```ada
-----------------------------------------------------------------------
-- util-streams-aes -- AES encoding and decoding streams
-- Copyright (C) 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Streams.AES is
-- -----------------------
-- Set the encryption key and mode to be used.
-- -----------------------
procedure Set_Key (Stream : in out Encoding_Stream;
Data : in Ada.Streams.Stream_Element_Array;
Mode : in Util.Encoders.AES.AES_Mode := Util.Encoders.AES.CBC) is
begin
Stream.Transform.Set_Key (Data, Mode);
end Set_Key;
-- -----------------------
-- Set the encryption initialization vector before starting the encryption.
-- -----------------------
procedure Set_IV (Stream : in out Encoding_Stream;
IV : in Util.Encoders.AES.Word_Block_Type) is
begin
Stream.Transform.Set_IV (IV);
end Set_IV;
-- -----------------------
-- Set the encryption key and mode to be used.
-- -----------------------
procedure Set_Key (Stream : in out Decoding_Stream;
Data : in Ada.Streams.Stream_Element_Array;
Mode : in Util.Encoders.AES.AES_Mode := Util.Encoders.AES.CBC) is
begin
Stream.Transform.Set_Key (Data, Mode);
end Set_Key;
-- -----------------------
-- Set the encryption initialization vector before starting the encryption.
-- -----------------------
procedure Set_IV (Stream : in out Decoding_Stream;
IV : in Util.Encoders.AES.Word_Block_Type) is
begin
Stream.Transform.Set_IV (IV);
end Set_IV;
end Util.Streams.AES;
``` |
8b9311e8-a7c1-4fd3-9f48-3c4fbc4f05fb | {
"language": "Ada"
} | ```ada
```
Implement the Print_Field procedure for addresses | ```ada
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Consoles is
-- ------------------------------
-- Format the address and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Addr : in MAT.Types.Target_Addr) is
Value : constant String := MAT.Types.Hex_Image (Addr);
begin
Console_Type'Class (Console).Print_Field (Field, Value);
end Print_Field;
end MAT.Consoles;
``` |
6fceae99-fc7a-4ce9-b862-820d7c86ebf3 | {
"language": "Ada"
} | ```ada
```
Add Split_Header (moved from Ada Server Faces) | ```ada
-----------------------------------------------------------------------
-- util-http-headers -- HTTP Headers
-- Copyright (C) 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with Util.Strings.Tokenizers;
package body Util.Http.Headers is
-- Split an accept like header into multiple tokens and a quality value.
-- Invoke the `Process` procedure for each token. Example:
--
-- Accept-Language: de, en;q=0.7, jp, fr;q=0.8, ru
--
-- The `Process` will be called for "de", "en" with quality 0.7,
-- and "jp", "fr" with quality 0.8 and then "ru" with quality 1.0.
procedure Split_Header (Header : in String;
Process : access procedure (Item : in String;
Quality : in Quality_Type)) is
use Util.Strings;
procedure Process_Token (Token : in String;
Done : out Boolean);
Quality : Quality_Type := 1.0;
procedure Process_Token (Token : in String;
Done : out Boolean) is
Name : constant String := Ada.Strings.Fixed.Trim (Token, Ada.Strings.Both);
begin
Process (Name, Quality);
Done := False;
end Process_Token;
Q, N, Pos : Natural;
Last : Natural := Header'First;
begin
while Last < Header'Last loop
Quality := 1.0;
Pos := Index (Header, ';', Last);
if Pos > 0 then
N := Index (Header, ',', Pos);
if N = 0 then
N := Header'Last + 1;
end if;
Q := Pos + 1;
while Q < N loop
if Header (Q .. Q + 1) = "q=" then
begin
Quality := Quality_Type'Value (Header (Q + 2 .. N - 1));
exception
when others =>
null;
end;
exit;
elsif Header (Q) /= ' ' then
exit;
end if;
Q := Q + 1;
end loop;
Util.Strings.Tokenizers.Iterate_Tokens (Content => Header (Last .. Pos - 1),
Pattern => ",",
Process => Process_Token'Access);
Last := N + 1;
else
Util.Strings.Tokenizers.Iterate_Tokens (Content => Header (Last .. Header'Last),
Pattern => ",",
Process => Process_Token'Access);
return;
end if;
end loop;
end Split_Header;
end Util.Http.Headers;
``` |
6e3d3871-5f65-4396-b468-bacd8aad4a6a | {
"language": "Ada"
} | ```ada
```
Test handling of record fields with negative offsets. | ```ada
-- RUN: %llvmgcc -c %s
with System;
procedure Negative_Field_Offset (N : Integer) is
type String_Pointer is access String;
-- Force use of a thin pointer.
for String_Pointer'Size use System.Word_Size;
P : String_Pointer;
begin
P := new String (1 .. N);
end;
``` |
c60c3f71-1c97-490c-83b7-3149fd420c62 | {
"language": "Ada"
} | ```ada
```
Test handling of ARRAY_REF when the component type is of unknown size. | ```ada
-- RUN: %llvmgcc -c %s -o /dev/null
procedure Array_Ref is
type A is array (Natural range <>, Natural range <>) of Boolean;
type A_Access is access A;
function Get (X : A_Access) return Boolean is
begin
return X (0, 0);
end;
begin
null;
end;
``` |
45f8fdc5-8442-496e-b403-583681e54223 | {
"language": "Ada"
} | ```ada
```
Add simple example for text transformations | ```ada
-----------------------------------------------------------------------
-- escape -- Text Transformations
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
with Util.Strings.Transforms;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
procedure Escape is
use Ada.Strings.Unbounded;
Count : constant Natural := Ada.Command_Line.Argument_Count;
begin
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: escape string...");
return;
end if;
for I in 1 .. Count loop
declare
S : constant String := Ada.Command_Line.Argument (I);
begin
Ada.Text_IO.Put_Line ("Escape javascript : "
& Util.Strings.Transforms.Escape_Javascript (S));
Ada.Text_IO.Put_Line ("Escape XML : "
& Util.Strings.Transforms.Escape_Xml (S));
end;
end loop;
end Escape;
``` |
c5735b02-d864-482f-8254-6ee4ed3600a5 | {
"language": "Ada"
} | ```ada
```
Implement the implicit object 'requestScope' | ```ada
-----------------------------------------------------------------------
-- asf-beans-requests -- Bean giving access to the request object
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
with ASF.Contexts.Faces;
with ASF.Requests;
package body ASF.Beans.Requests is
Bean : aliased Request_Bean;
-- ------------------------------
-- Get from the request object the value identified by the given name.
-- Returns Null_Object if the request does not define such name.
-- ------------------------------
overriding
function Get_Value (Bean : in Request_Bean;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (Bean);
use type ASF.Contexts.Faces.Faces_Context_Access;
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
if Ctx = null then
return Util.Beans.Objects.Null_Object;
end if;
declare
Req : constant ASF.Requests.Request_Access := Ctx.Get_Request;
begin
return Req.Get_Attribute (Name);
end;
end Get_Value;
-- ------------------------------
-- Return the Request_Bean instance.
-- ------------------------------
function Instance return Util.Beans.Objects.Object is
begin
return Util.Beans.Objects.To_Object (Bean'Access, Util.Beans.Objects.STATIC);
end Instance;
end ASF.Beans.Requests;
``` |
dc572036-e8b9-4bd8-b2ec-0f91235b7fd2 | {
"language": "Ada"
} | ```ada
```
Implement the Insert and Get_Event_Counter operations | ```ada
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Events.Targets is
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in MAT.Types.Uint16;
Frame : in MAT.Events.Frame_Info) is
begin
Target.Events.Insert (Event, Frame);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_EVent_Counter;
protected body Event_Collector is
-- ------------------------------
-- Add the event in the list of events.
-- ------------------------------
procedure Insert (Event : in MAT.Types.Uint16;
Frame : in MAT.Events.Frame_Info) is
begin
null;
end Insert;
end Event_Collector;
end MAT.Events.Targets;
``` |
56ed527a-360a-4892-bf74-4e22e0091a67 | {
"language": "Ada"
} | ```ada
```
Define a set of interface to send an email and have several possible implementations | ```ada
-----------------------------------------------------------------------
-- awa-mail-client -- Mail client interface
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
-- The <b>AWA.Mail.Clients</b> package defines a mail client API used by the mail module.
-- It defines two interfaces that must be implemented. This allows to have an implementation
-- based on an external application such as <tt>sendmail</tt> and other implementation that
-- use an SMTP connection.
package AWA.Mail.Clients is
type Recipient_Type is (TO, CC, BCC);
-- ------------------------------
-- Mail Message
-- ------------------------------
-- The <b>Mail_Message</b> represents an abstract mail message that can be initialized
-- before being sent.
type Mail_Message is limited interface;
type Mail_Message_Access is access all Mail_Message'Class;
-- Set the <tt>From</tt> part of the message.
procedure Set_From (Message : in out Mail_Message;
Name : in String;
Address : in String) is abstract;
-- Add a recipient for the message.
procedure Add_Recipient (Message : in out Mail_Message;
Kind : in Recipient_Type;
Name : in String;
Address : in String) is abstract;
-- Set the subject of the message.
procedure Set_Subject (Message : in out Mail_Message;
Subject : in String) is abstract;
-- Set the body of the message.
procedure Set_Body (Message : in out Mail_Message;
Content : in String) is abstract;
-- Send the email message.
procedure Send (Message : in out Mail_Message) is abstract;
-- ------------------------------
-- Mail Manager
-- ------------------------------
-- The <b>Mail_Manager</b> is the entry point to create a new mail message
-- and be able to send it.
type Mail_Manager is limited interface;
type Mail_Manager_Access is access all Mail_Manager'Class;
-- Create a new mail message.
function Create_Message (Manager : in Mail_Manager) return Mail_Message_Access is abstract;
end AWA.Mail.Clients;
``` |
f8379101-9fb0-4d1a-8adf-2834174d5b90 | {
"language": "Ada"
} | ```ada
```
Add unit test for Parse_Form procedure | ```ada
-----------------------------------------------------------------------
-- util-properties-form-tests -- Test reading form file into properties
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Properties.Form.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test loading a form file into a properties object.
procedure Test_Parse_Form (T : in out Test);
end Util.Properties.Form.Tests;
``` |
f0c64fb2-d9f0-413b-ac96-6c5e0ccbd638 | {
"language": "Ada"
} | ```ada
```
Add unit tests for local store and Read_File/Write_File operations | ```ada
-----------------------------------------------------------------------
-- babel-stores-local-tests - Unit tests for babel streams
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
with Util.Tests;
package Babel.Stores.Local.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test the Read_File and Write_File operations.
procedure Test_Read_File (T : in out Test);
end Babel.Stores.Local.Tests;
``` |
8fcb3b72-cc78-4318-8120-5a6c53365c1c | {
"language": "Ada"
} | ```ada
```
Add blog servlets definition with Image_Servlet type | ```ada
-----------------------------------------------------------------------
-- awa-blogs-servlets -- Serve files saved in the storage service
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with ADO;
with ASF.Requests;
with AWA.Storages.Servlets;
package AWA.Blogs.Servlets is
-- The <b>Storage_Servlet</b> represents the component that will handle
-- an HTTP request received by the server.
type Image_Servlet is new AWA.Storages.Servlets.Storage_Servlet with private;
-- Load the data content that correspond to the GET request and get the name as well
-- as mime-type and date.
procedure Load (Server : in Image_Servlet;
Request : in out ASF.Requests.Request'Class;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Data : out ADO.Blob_Ref);
private
type Image_Servlet is new AWA.Storages.Servlets.Storage_Servlet with null record;
end AWA.Blogs.Servlets;
``` |
a6428f80-49bb-4ece-8159-f5a6ce155cc2 | {
"language": "Ada"
} | ```ada
```
Define the factory for the creation of widget components | ```ada
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- 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.
-----------------------------------------------------------------------
with ASF.Factory;
package ASF.Components.Widgets.Factory is
-- Get the widget component factory.
function Definition return ASF.Factory.Factory_Bindings_Access;
end ASF.Components.Widgets.Factory;
``` |
95354469-d113-4871-86f3-2825c54771ab | {
"language": "Ada"
} | ```ada
```
Implement the REST API definition package | ```ada
-----------------------------------------------------------------------
-- asf-rest-operation -- REST API Operation Definition
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body ASF.Rest.Operation is
URI_Mapping : aliased String := URI;
Desc : aliased Static_Descriptor
:= (Next => null,
Method => Method,
Handler => Handler,
Pattern => URI_Mapping'Access,
Permission => Permission);
function Definition return Descriptor_Access is
begin
return Desc'Access;
end Definition;
end ASF.Rest.Operation;
``` |
05eca02f-3c31-47b5-aabe-eb81d52cd0c0 | {
"language": "Agda"
} | ```agda
module Base.Change.Context
{Type : Set}
(ΔType : Type → Type) where
-- Transform a context of values into a context of values and
-- changes.
open import Base.Syntax.Context Type
ΔContext : Context → Context
ΔContext ∅ = ∅
ΔContext (τ • Γ) = ΔType τ • τ • ΔContext Γ
-- like ΔContext, but ΔType τ and τ are swapped
ΔContext′ : Context → Context
ΔContext′ ∅ = ∅
ΔContext′ (τ • Γ) = τ • ΔType τ • ΔContext′ Γ
Γ≼ΔΓ : ∀ {Γ} → Γ ≼ ΔContext Γ
Γ≼ΔΓ {∅} = ∅
Γ≼ΔΓ {τ • Γ} = drop ΔType τ • keep τ • Γ≼ΔΓ
```
Move function-specific comment right before function | ```agda
module Base.Change.Context
{Type : Set}
(ΔType : Type → Type) where
open import Base.Syntax.Context Type
-- Transform a context of values into a context of values and
-- changes.
ΔContext : Context → Context
ΔContext ∅ = ∅
ΔContext (τ • Γ) = ΔType τ • τ • ΔContext Γ
-- like ΔContext, but ΔType τ and τ are swapped
ΔContext′ : Context → Context
ΔContext′ ∅ = ∅
ΔContext′ (τ • Γ) = τ • ΔType τ • ΔContext′ Γ
Γ≼ΔΓ : ∀ {Γ} → Γ ≼ ΔContext Γ
Γ≼ΔΓ {∅} = ∅
Γ≼ΔΓ {τ • Γ} = drop ΔType τ • keep τ • Γ≼ΔΓ
``` |
7732bace-5493-413b-a380-001ea089cd0f | {
"language": "Agda"
} | ```agda
module meaning where
open import Level
record Meaning (Syntax : Set) {ℓ : Level} : Set (suc ℓ) where
constructor
meaning
field
{Semantics} : Set ℓ
⟦_⟧ : Syntax → Semantics
open Meaning {{...}} public
```
Improve printing of resolved overloading. | ```agda
module meaning where
open import Level
record Meaning (Syntax : Set) {ℓ : Level} : Set (suc ℓ) where
constructor
meaning
field
{Semantics} : Set ℓ
⟨_⟩⟦_⟧ : Syntax → Semantics
open Meaning {{...}} public
renaming (⟨_⟩⟦_⟧ to ⟦_⟧)
open Meaning public
using (⟨_⟩⟦_⟧)
``` |
083fa2cc-e5fd-4250-8d6c-e742e1632584 | {
"language": "Agda"
} | ```agda
{-# OPTIONS --without-K #-}
open import Type hiding (★)
module Data.Tree.Binary where
data BinTree {a} (A : ★ a) : ★ a where
empty : BinTree A
leaf : A → BinTree A
fork : (ℓ r : BinTree A) → BinTree A
```
Add Any predicate for binary tree | ```agda
{-# OPTIONS --without-K #-}
open import Type hiding (★)
open import Level
open import Data.Zero
open import Data.Sum
module Data.Tree.Binary where
data BinTree {a} (A : ★ a) : ★ a where
empty : BinTree A
leaf : A → BinTree A
fork : (ℓ r : BinTree A) → BinTree A
Any : ∀ {a p}{A : ★ a}(P : A → ★ p) → BinTree A → ★ p
Any P empty = Lift 𝟘
Any P (leaf x) = P x
Any P (fork ts ts₁) = Any P ts ⊎ Any P ts₁
``` |
9381bc78-a5a3-4bea-ab70-29570a580d0f | {
"language": "Agda"
} | ```agda
```
Add alternative defintion for IND CPA | ```agda
{-# OPTIONS --without-K #-}
open import Type
open import Data.Product
open import Data.Bit
module Game.IND-CPA-alt
(PubKey : ★)
(SecKey : ★)
(Message : ★)
(CipherText : ★)
-- randomness supply for: encryption, key-generation, adversary, extensions
(Rₑ Rₖ Rₐ : ★)
(KeyGen : Rₖ → PubKey × SecKey)
(Enc : PubKey → Message → Rₑ → CipherText)
where
M² = Bit → Message
-- IND-CPA adversary in two parts
Adv : ★
Adv = Rₐ → PubKey → (M² × (CipherText → Bit))
-- IND-CPA randomness supply
R : ★
R = (Rₐ × Rₖ × Rₑ)
-- IND-CPA games:
-- * input: adversary and randomness supply
-- * output b: adversary claims we are in game ⅁ b
Game : ★
Game = Adv → R → Bit
-- The game step by step:
-- (pk) key-generation, only the public-key is needed
-- (mb) send randomness, public-key and bit
-- receive which message to encrypt
-- (c) encrypt the message
-- (b′) send randomness, public-key and ciphertext
-- receive the guess from the adversary
⅁ : Bit → Game
⅁ b m (rₐ , rₖ , rₑ) = b′
where
pk = proj₁ (KeyGen rₖ)
ad = m rₐ pk
mb = proj₁ ad b
c = Enc pk mb rₑ
b′ = proj₂ ad c
⅁₀ ⅁₁ : Game
⅁₀ = ⅁ 0b
⅁₁ = ⅁ 1b
``` |
6ccc942c-a998-499c-b1bb-761b979f074f | {
"language": "Agda"
} | ```agda
```
Add incomplete note on co-inductive natural numbers. | ```agda
------------------------------------------------------------------------------
-- Definition of FOTC Conat using Agda's co-inductive combinators
------------------------------------------------------------------------------
{-# OPTIONS --allow-unsolved-metas #-}
{-# OPTIONS --no-universe-polymorphism #-}
{-# OPTIONS --without-K #-}
module FOT.FOTC.Data.Conat.ConatSL where
open import FOTC.Base
open import Coinduction
------------------------------------------------------------------------------
data Conat : D → Set where
cozero : Conat zero
cosucc : ∀ {n} → (∞ (Conat n)) → Conat (succ₁ n)
Conat-unf : ∀ {n} → Conat n → n ≡ zero ∨ (∃[ n' ] Conat n' ∧ n ≡ succ₁ n')
Conat-unf cozero = inj₁ refl
Conat-unf (cosucc {n} Cn) = inj₂ (n , ♭ Cn , refl)
Conat-pre-fixed : ∀ {n} →
(n ≡ zero ∨ (∃[ n' ] Conat n' ∧ n ≡ succ₁ n')) →
Conat n
Conat-pre-fixed (inj₁ h) = subst Conat (sym h) cozero
Conat-pre-fixed (inj₂ (n , Cn , h)) = subst Conat (sym h) (cosucc (♯ Cn))
Conat-coind : ∀ (A : D → Set) {n} →
(A n → n ≡ zero ∨ (∃[ n' ] A n' ∧ n ≡ succ₁ n')) →
A n → Conat n
Conat-coind A h An = {!!}
``` |
6b265d43-a8db-4440-ba7d-f6b16e331811 | {
"language": "Agda"
} | ```agda
module Base.Change.Context
{Type : Set}
(ΔType : Type → Type) where
-- Transform a context of values into a context of values and
-- changes.
open import Base.Syntax.Context Type
ΔContext : Context → Context
ΔContext ∅ = ∅
ΔContext (τ • Γ) = ΔType τ • τ • ΔContext Γ
-- like ΔContext, but ΔType τ and τ are swapped
ΔContext′ : Context → Context
ΔContext′ ∅ = ∅
ΔContext′ (τ • Γ) = τ • ΔType τ • ΔContext′ Γ
Γ≼ΔΓ : ∀ {Γ} → Γ ≼ ΔContext Γ
Γ≼ΔΓ {∅} = ∅
Γ≼ΔΓ {τ • Γ} = drop ΔType τ • keep τ • Γ≼ΔΓ
```
Move function-specific comment right before function | ```agda
module Base.Change.Context
{Type : Set}
(ΔType : Type → Type) where
open import Base.Syntax.Context Type
-- Transform a context of values into a context of values and
-- changes.
ΔContext : Context → Context
ΔContext ∅ = ∅
ΔContext (τ • Γ) = ΔType τ • τ • ΔContext Γ
-- like ΔContext, but ΔType τ and τ are swapped
ΔContext′ : Context → Context
ΔContext′ ∅ = ∅
ΔContext′ (τ • Γ) = τ • ΔType τ • ΔContext′ Γ
Γ≼ΔΓ : ∀ {Γ} → Γ ≼ ΔContext Γ
Γ≼ΔΓ {∅} = ∅
Γ≼ΔΓ {τ • Γ} = drop ΔType τ • keep τ • Γ≼ΔΓ
``` |
ae2ec0cd-6b02-420f-8583-c52d7df0d3b8 | {
"language": "Agda"
} | ```agda
module meaning where
open import Level
record Meaning (Syntax : Set) {ℓ : Level} : Set (suc ℓ) where
constructor
meaning
field
{Semantics} : Set ℓ
⟦_⟧ : Syntax → Semantics
open Meaning {{...}} public
```
Improve printing of resolved overloading. | ```agda
module meaning where
open import Level
record Meaning (Syntax : Set) {ℓ : Level} : Set (suc ℓ) where
constructor
meaning
field
{Semantics} : Set ℓ
⟨_⟩⟦_⟧ : Syntax → Semantics
open Meaning {{...}} public
renaming (⟨_⟩⟦_⟧ to ⟦_⟧)
open Meaning public
using (⟨_⟩⟦_⟧)
``` |
e4d650c4-ec92-4c2e-88e8-bc57750fb927 | {
"language": "Agda"
} | ```agda
{-# OPTIONS --without-K #-}
open import Type hiding (★)
module Data.Tree.Binary where
data BinTree {a} (A : ★ a) : ★ a where
empty : BinTree A
leaf : A → BinTree A
fork : (ℓ r : BinTree A) → BinTree A
```
Add Any predicate for binary tree | ```agda
{-# OPTIONS --without-K #-}
open import Type hiding (★)
open import Level
open import Data.Zero
open import Data.Sum
module Data.Tree.Binary where
data BinTree {a} (A : ★ a) : ★ a where
empty : BinTree A
leaf : A → BinTree A
fork : (ℓ r : BinTree A) → BinTree A
Any : ∀ {a p}{A : ★ a}(P : A → ★ p) → BinTree A → ★ p
Any P empty = Lift 𝟘
Any P (leaf x) = P x
Any P (fork ts ts₁) = Any P ts ⊎ Any P ts₁
``` |
e7769b51-5846-46e0-8fbe-68c683e89b47 | {
"language": "Agda"
} | ```agda
```
Add alternative defintion for IND CPA | ```agda
{-# OPTIONS --without-K #-}
open import Type
open import Data.Product
open import Data.Bit
module Game.IND-CPA-alt
(PubKey : ★)
(SecKey : ★)
(Message : ★)
(CipherText : ★)
-- randomness supply for: encryption, key-generation, adversary, extensions
(Rₑ Rₖ Rₐ : ★)
(KeyGen : Rₖ → PubKey × SecKey)
(Enc : PubKey → Message → Rₑ → CipherText)
where
M² = Bit → Message
-- IND-CPA adversary in two parts
Adv : ★
Adv = Rₐ → PubKey → (M² × (CipherText → Bit))
-- IND-CPA randomness supply
R : ★
R = (Rₐ × Rₖ × Rₑ)
-- IND-CPA games:
-- * input: adversary and randomness supply
-- * output b: adversary claims we are in game ⅁ b
Game : ★
Game = Adv → R → Bit
-- The game step by step:
-- (pk) key-generation, only the public-key is needed
-- (mb) send randomness, public-key and bit
-- receive which message to encrypt
-- (c) encrypt the message
-- (b′) send randomness, public-key and ciphertext
-- receive the guess from the adversary
⅁ : Bit → Game
⅁ b m (rₐ , rₖ , rₑ) = b′
where
pk = proj₁ (KeyGen rₖ)
ad = m rₐ pk
mb = proj₁ ad b
c = Enc pk mb rₑ
b′ = proj₂ ad c
⅁₀ ⅁₁ : Game
⅁₀ = ⅁ 0b
⅁₁ = ⅁ 1b
``` |
9d32766a-de27-41c5-9c21-35f7d50c115d | {
"language": "Agda"
} | ```agda
```
Add incomplete note on co-inductive natural numbers. | ```agda
------------------------------------------------------------------------------
-- Definition of FOTC Conat using Agda's co-inductive combinators
------------------------------------------------------------------------------
{-# OPTIONS --allow-unsolved-metas #-}
{-# OPTIONS --no-universe-polymorphism #-}
{-# OPTIONS --without-K #-}
module FOT.FOTC.Data.Conat.ConatSL where
open import FOTC.Base
open import Coinduction
------------------------------------------------------------------------------
data Conat : D → Set where
cozero : Conat zero
cosucc : ∀ {n} → (∞ (Conat n)) → Conat (succ₁ n)
Conat-unf : ∀ {n} → Conat n → n ≡ zero ∨ (∃[ n' ] Conat n' ∧ n ≡ succ₁ n')
Conat-unf cozero = inj₁ refl
Conat-unf (cosucc {n} Cn) = inj₂ (n , ♭ Cn , refl)
Conat-pre-fixed : ∀ {n} →
(n ≡ zero ∨ (∃[ n' ] Conat n' ∧ n ≡ succ₁ n')) →
Conat n
Conat-pre-fixed (inj₁ h) = subst Conat (sym h) cozero
Conat-pre-fixed (inj₂ (n , Cn , h)) = subst Conat (sym h) (cosucc (♯ Cn))
Conat-coind : ∀ (A : D → Set) {n} →
(A n → n ≡ zero ∨ (∃[ n' ] A n' ∧ n ≡ succ₁ n')) →
A n → Conat n
Conat-coind A h An = {!!}
``` |
d39bb1c7-45cf-4867-ba4a-bc75f147422a | {
"language": "ANTLR"
} | ```antlr
grammar WorkflowCatalogQueryLanguage;
@header {
package org.ow2.proactive.workflow_catalog.rest.query;
}
clause: ATTRIBUTE OPERATOR VALUE ;
clauses: clause ( CONJUNCTION clause )* ;
statement: '(' clauses ')' | clauses ;
ATTRIBUTE: ([a-z] | [A-Z])+ ([_.]+ ([a-z] | [A-Z] | [0-9])*)* ;
CONJUNCTION: 'AND' | 'OR' ;
OPERATOR: '!=' | '=' ;
VALUE: '"' (~[\t\n])* '"' ;
WHITESPACE: [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines
```
Update grammar for our Workflow Catalog Query Language (WCQL) | ```antlr
grammar WorkflowCatalogQueryLanguage;
@header {
package org.ow2.proactive.workflow_catalog.rest.query;
}
// PARSER
expression
: and_expression
;
and_expression
: or_expression (AND or_expression)*
;
or_expression
: clause (OR clause)*
;
clause
: (AttributeLiteral COMPARE_OPERATOR StringLiteral)
| LPAREN and_expression RPAREN
;
// LEXER
AND : 'AND' | '&&' ;
OR : 'OR' | '||' ;
COMPARE_OPERATOR : '!=' | '=' ;
LPAREN : '(' ;
RPAREN : ')' ;
StringLiteral
: '"' (~["\\\r\n] | '\\' (. | EOF))* '"'
;
AttributeLiteral
: LETTER (LETTER | DIGIT | '_' | '.')*
;
WS
: [ \t\r\n]+ -> skip
;
fragment DIGIT: [0-9];
fragment LETTER: LOWERCASE | UPPERCASE;
fragment LOWERCASE: [a-z];
fragment UPPERCASE: [A-Z];
``` |
100a4c5c-daf3-4e9d-9c8e-228ba7872a10 | {
"language": "ANTLR"
} | ```antlr
grammar InvestmentSize;
import Tokens;
@header {
import com.github.robozonky.strategy.natural.*;
}
investmentSizeExpression returns [Collection<InvestmentSize> result]:
{ Collection<InvestmentSize> result = new LinkedHashSet<>(); }
(i=investmentSizeRatingExpression { result.add($i.result); })+
{ $result = result; }
;
investmentSizeRatingExpression returns [InvestmentSize result] :
'Do úvěrů v ratingu ' r=ratingExpression ' investovat' i=investmentSizeRatingSubExpression {
$result = new InvestmentSize($r.result, $i.result);
}
;
```
Make investment size spec optional | ```antlr
grammar InvestmentSize;
import Tokens;
@header {
import com.github.robozonky.strategy.natural.*;
}
investmentSizeExpression returns [Collection<InvestmentSize> result]:
{ Collection<InvestmentSize> result = new LinkedHashSet<>(); }
(i=investmentSizeRatingExpression { result.add($i.result); })*
{ $result = result; }
;
investmentSizeRatingExpression returns [InvestmentSize result] :
'Do úvěrů v ratingu ' r=ratingExpression ' investovat' i=investmentSizeRatingSubExpression {
$result = new InvestmentSize($r.result, $i.result);
}
;
``` |
cefb098a-0abf-4be8-ad9f-090b69ddb3c9 | {
"language": "ANTLR"
} | ```antlr
grammar Relational;
relationalExpression : unionExpression ;
unionExpression : 'union' '(' datasetExpression (',' datasetExpression )* ')' ;
datasetExpression : 'datasetExpr' NUM+;
NUM : '0'..'9' ;
WS : [ \t\n\t] -> skip ;
```
Add joinExpression to the relationalExpression | ```antlr
grammar Relational;
relationalExpression : unionExpression | joinExpression ;
unionExpression : 'union' '(' datasetExpression (',' datasetExpression )* ')' ;
datasetExpression : 'datasetExpr' NUM+;
joinExpression : '[' (INNER | OUTER | CROSS ) datasetExpression (',' datasetExpression )* ']' joinClause (',' joinClause)* ;
joinClause : joinCalc
| joinFilter
| joinKeep
| joinRename ;
// | joinDrop
// | joinUnfold
// | joinFold ;
joinCalc : 'TODO' ;
joinFilter : 'TODO' ;
joinKeep : 'TODO' ;
joinRename : 'TODO' ;
INNER : 'inner' ;
OUTER : 'outer' ;
CROSS : 'cross' ;
NUM : '0'..'9' ;
WS : [ \t\n\t] -> skip ;
``` |
afa37190-583c-4861-a781-5b9adf9a08ba | {
"language": "ANTLR"
} | ```antlr
grammar Type;
CT : [A-Z][a-z]+ ;
VT : [a-z]+ ;
WS : [ \t\r\n]+ -> skip ;
type : functionType | compoundType; // function type
functionType : compoundType ('->' type)+ ;
compoundType : concreteType | tupleType | listType | parenType ;
tupleType : '(' type (',' type)+ ')' ; // tuple type, k>=2
listType : '[' type ']' ; // list type
parenType : '(' type ')' ; // parenthesised constructor
concreteType : constantType | variableType ;
constantType : CT ;
variableType : VT ;
```
Change antler grammar to support new type API | ```antlr
grammar Type;
CT : [A-Z][a-z]+ ;
VT : [a-z]+ ;
WS : [ \t\r\n]+ -> skip ;
type : functionType | compoundType ; // function type
functionType : compoundType '->' type ;
compoundType : constantType | variableType | tupleType | listType | parenType ;
tupleType : '(' type (',' type)+ ')' ; // tuple type, k>=2
listType : '[' type ']' ; // list type
parenType : '(' type ')' ; // type with parentheses
constantType : CT ;
variableType : VT ;
``` |
0cfb16bb-4c47-4188-a3f2-8942d3092583 | {
"language": "ANTLR"
} | ```antlr
grammar Expression;
expression : sign = ('-' | '+') expression
| subExpresion
| left = expression op = POW right = expression
| left = expression op = ( MULT | DIV ) right = expression
| left = expression op = ( ADD | SUB ) right = expression
| function
| value = ( IDENT | CONST )
;
subExpresion : LPAREN expression RPAREN ;
function : name = IDENT LPAREN paramFirst = expression ( ',' paramRest += expression )* RPAREN ;
CONST : INTEGER | DECIMAL;
INTEGER : [0-9]+;
DECIMAL : [0-9]+'.'[0-9]+;
IDENT : [_A-Za-z#][_.A-Za-z#]*;
LPAREN : '(';
RPAREN : ')';
MULT : '*';
DIV : '/';
ADD : '+';
SUB : '-';
POW : '^';
WS : [ \r\t\u000C\n]+ -> skip ;```
Allow numeric digits also in the identifier names. | ```antlr
grammar Expression;
expression : sign = ('-' | '+') expression
| subExpresion
| left = expression op = POW right = expression
| left = expression op = ( MULT | DIV ) right = expression
| left = expression op = ( ADD | SUB ) right = expression
| function
| value = ( IDENT | CONST )
;
subExpresion : LPAREN expression RPAREN ;
function : name = IDENT LPAREN paramFirst = expression ( ',' paramRest += expression )* RPAREN ;
CONST : INTEGER | DECIMAL;
INTEGER : [0-9]+;
DECIMAL : [0-9]+'.'[0-9]+;
IDENT : [_#A-Za-z][_#.A-Za-z0-9]*;
LPAREN : '(';
RPAREN : ')';
MULT : '*';
DIV : '/';
ADD : '+';
SUB : '-';
POW : '^';
WS : [ \r\t\u000C\n]+ -> skip ;
``` |
b5f1122c-d417-4949-b0a0-4e311eed0590 | {
"language": "ANTLR"
} | ```antlr
/*-
* #%L
* Java VTL
* %%
* Copyright (C) 2016 Hadrien Kohl
* %%
* 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.
* #L%
*/
grammar VTL;
import Atoms, Clauses, Conditional, Relational;
start : statement+ EOF;
/* Assignment */
statement : variableRef ':=' datasetExpression;
exprMember : datasetExpression ('#' componentID)? ;
/* Expressions */
datasetExpression : <assoc=right>datasetExpression clauseExpression #withClause
| relationalExpression #withRelational
| getExpression #withGet
| putExpression #withPut
| exprAtom #withAtom
;
componentID : IDENTIFIER;
getExpression : 'get' '(' datasetId ')';
putExpression : 'put(todo)';
datasetId : STRING_CONSTANT ;
WS : [ \n\r\t\u000C] -> skip ;
```
Add comment to the parser grammar | ```antlr
/*-
* #%L
* Java VTL
* %%
* Copyright (C) 2016 Hadrien Kohl
* %%
* 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.
* #L%
*/
grammar VTL;
import Atoms, Clauses, Conditional, Relational;
start : statement+ EOF;
/* Assignment */
statement : variableRef ':=' datasetExpression;
exprMember : datasetExpression ('#' componentID)? ;
/* Expressions */
datasetExpression : <assoc=right>datasetExpression clauseExpression #withClause
| relationalExpression #withRelational
| getExpression #withGet
| putExpression #withPut
| exprAtom #withAtom
;
componentID : IDENTIFIER;
getExpression : 'get' '(' datasetId ')';
putExpression : 'put(todo)';
datasetId : STRING_CONSTANT ;
WS : [ \n\r\t\u000C] -> skip ;
COMMENT : '/*' .*? '*/' -> skip;
``` |
bfebdb41-281c-484a-9e3a-186e5d871e93 | {
"language": "ANTLR"
} | ```antlr
grammar Type;
CT : [A-Z][a-z]+ ;
VT : [a-z]+ ;
WS : [ \t\r\n]+ -> skip ;
type : typeClasses ? innerType ;
innerType : functionType | compoundType ; // function type
functionType : compoundType '->' innerType ;
compoundType : constantType | variableType | tupleType | listType | parenType ;
tupleType : '(' innerType (',' innerType)+ ')' ; // tuple type, k>=2
listType : '[' innerType ']' ; // list type
parenType : '(' innerType ')' ; // type with parentheses
constantType : typeConstructor (WS* innerType)* ;
typeConstructor : CT ;
variableType : VT ;
typeClasses : '(' typeWithClass (',' typeWithClass)* ')' '=>' | typeWithClass '=>' ;
typeWithClass : typeClass WS* classedType ;
classedType : VT ;
typeClass : CT ;
```
Fix issue with lexing type classes with an uppercase character after the first position | ```antlr
grammar Type;
CT : [A-Z][A-Za-z]+ ;
VT : [a-z]+ ;
WS : [ \t\r\n]+ -> skip ;
type : (typeClasses '=>')? innerType ;
innerType : functionType | compoundType ; // function type
functionType : compoundType '->' innerType ;
compoundType : constantType | variableType | tupleType | listType | parenType ;
tupleType : '(' innerType (',' innerType)+ ')' ; // tuple type, k>=2
listType : '[' innerType ']' ; // list type
parenType : '(' innerType ')' ; // type with parentheses
constantType : typeConstructor (innerType)* ;
typeConstructor : CT ;
variableType : VT ;
typeClasses : '(' typeWithClass (',' typeWithClass)* ')' | typeWithClass ;
typeWithClass : typeClass classedType ;
classedType : VT ;
typeClass : CT ;
``` |
89cc60c3-a24c-4447-8635-56962ac636d5 | {
"language": "ANTLR"
} | ```antlr
grammar WorkflowCatalogQueryLanguage;
@header {
package org.ow2.proactive.workflow_catalog.rest.query.parser;
}
// PARSER
expression
: and_expression
;
and_expression
: or_expression (AND or_expression)*
;
or_expression
: clause (OR clause)*
;
clause
: (AttributeLiteral COMPARE_OPERATOR StringLiteral)
| LPAREN and_expression RPAREN
;
// LEXER
AND : 'AND' | '&&' ;
OR : 'OR' | '||' ;
COMPARE_OPERATOR : '!=' | '=' ;
LPAREN : '(' ;
RPAREN : ')' ;
StringLiteral
: '"' (~["\\\r\n] | '\\' (. | EOF))* '"'
;
AttributeLiteral
: LETTER (LETTER | DIGIT | '_' | '.')*
;
WS
: [ \t\r\n]+ -> skip
;
fragment DIGIT: [0-9];
fragment LETTER: LOWERCASE | UPPERCASE;
fragment LOWERCASE: [a-z];
fragment UPPERCASE: [A-Z];
```
Add aliases to clauses subterms | ```antlr
grammar WorkflowCatalogQueryLanguage;
@header {
package org.ow2.proactive.workflow_catalog.rest.query.parser;
}
// PARSER
expression
: and_expression
;
and_expression
: or_expression (AND or_expression)*
;
or_expression
: clause (OR clause)*
;
clause
: (AttributeLiteral COMPARE_OPERATOR StringLiteral) #finalClause
| LPAREN and_expression RPAREN #parenthesedClause
;
// LEXER
AND : 'AND' | '&&' ;
OR : 'OR' | '||' ;
COMPARE_OPERATOR : '!=' | '=' ;
LPAREN : '(' ;
RPAREN : ')' ;
StringLiteral
: '"' (~["\\\r\n] | '\\' (. | EOF))* '"'
;
AttributeLiteral
: LETTER (LETTER | DIGIT | '_' | '.')*
;
WS
: [ \t\r\n]+ -> skip
;
fragment DIGIT: [0-9];
fragment LETTER: LOWERCASE | UPPERCASE;
fragment LOWERCASE: [a-z];
fragment UPPERCASE: [A-Z];
``` |
2daed35a-c019-4576-84b3-a2d6b39f6873 | {
"language": "ANTLR"
} | ```antlr
lexer grammar CcsLexer;
TERM: ';';
NIL: '0';
COMMA: ',';
DIV : '/' ;
DEF: '=';
PAR: '|';
PREFIX: '.';
CHOICE: '+';
TAU: 'tau';
LBRACE : '{' ;
RBRACE : '}' ;
MUL : '*' ;
SETDEF : 'set ' ;
LPAREN : '(' ;
RPAREN : ')' ;
LBRACK : '[' ;
RBRACK : ']' ;
T__1 : '\\' ;
COACTION: '\''[a-z][A-Za-z0-9]*;
ACTION: [a-z][A-Za-z0-9]*;
fragment InputCharacter: ~[\r\n\u0085\u2028\u2029];
COMMENT
: MUL InputCharacter+
| MUL
;
IDENTIFIER
: [A-Z][A-Za-z0-9]*
;
//RENAMINGS : RENAMING ',' RENAMINGS;
//RENAMING : ACTION ACTION;
// ignore whitespace
WHITESPACE : [ \r\n\t] + -> channel (HIDDEN);
```
Remove useless stuff from lever grammar | ```antlr
lexer grammar CcsLexer;
TERM: ';';
NIL: '0';
COMMA: ',';
DIV : '/' ;
DEF: '=';
PAR: '|';
PREFIX: '.';
CHOICE: '+';
TAU: 'tau';
LBRACE : '{' ;
RBRACE : '}' ;
MUL : '*' ;
SETDEF : 'set ' ;
LPAREN : '(' ;
RPAREN : ')' ;
LBRACK : '[' ;
RBRACK : ']' ;
T__1 : '\\' ;
COACTION: '\''[a-z][A-Za-z0-9]*;
ACTION: [a-z][A-Za-z0-9]*;
fragment InputCharacter: ~[\r\n\u0085\u2028\u2029];
COMMENT
: MUL InputCharacter+
| MUL
;
IDENTIFIER
: [A-Z][A-Za-z0-9]*
;
// ignore whitespace
WHITESPACE : [ \r\n\t] + -> channel (HIDDEN);
``` |
8ebb4c73-42df-4cb0-a62c-7142979482e1 | {
"language": "ANTLR"
} | ```antlr
grammar Type;
CT : [A-Z][a-z]+ ;
VT : [a-z]+ ;
WS : [ \t\r\n]+ -> skip ;
baseType : typeClasses ? type ;
type : functionType | compoundType ; // function type
functionType : compoundType '->' type ;
compoundType : constantType | variableType | tupleType | listType | parenType ;
tupleType : '(' type (',' type)+ ')' ; // tuple type, k>=2
listType : '[' type ']' ; // list type
parenType : '(' type ')' ; // type with parentheses
constantType : typeConstructor (WS* type)* ;
typeConstructor : CT ;
variableType : VT ;
typeClasses : '(' typeWithClass (',' typeWithClass)* ')' '=>' ;
typeWithClass : typeClass WS* classedType ;
classedType : VT ;
typeClass : CT ;
```
Fix bug in Antlr grammar | ```antlr
grammar Type;
CT : [A-Z][a-z]+ ;
VT : [a-z]+ ;
WS : [ \t\r\n]+ -> skip ;
type : typeClasses ? innerType ;
innerType : functionType | compoundType ; // function type
functionType : compoundType '->' innerType ;
compoundType : constantType | variableType | tupleType | listType | parenType ;
tupleType : '(' innerType (',' innerType)+ ')' ; // tuple type, k>=2
listType : '[' innerType ']' ; // list type
parenType : '(' innerType ')' ; // type with parentheses
constantType : typeConstructor (WS* innerType)* ;
typeConstructor : CT ;
variableType : VT ;
typeClasses : '(' typeWithClass (',' typeWithClass)* ')' '=>' ;
typeWithClass : typeClass WS* classedType ;
classedType : VT ;
typeClass : CT ;
``` |
e525eaa2-2cde-4847-9b33-7164a8881a4b | {
"language": "ANTLR"
} | ```antlr
grammar PTP;
@header {
package pt.up.fe.iart.proj1.parser;
}
map : stmt+ ;
stmt : node_stmt #node
| edge_stmt #edge
;
edge_stmt : 'Edge' '(' from=node_stmt ',' to=node_stmt ',' weight=(INT|REAL) ')';
node_stmt : 'GasStation' '(' position ')' #GasStation
| 'GenericLocation' '(' position ')' #GenericLocation
| 'PatientLocation' '(' position ')' #PatientLocation
| 'Filiation' '(' position ',' bool ')' #Filiation
;
position : '(' x=INT ',' y=INT ')' ;
bool : 'true' | 'false' ;
INT: [0-9]+ ;
REAL: [0-9]+ '.' [0-9]* ;
WS : [ \t\r\n]+ -> skip;```
Add comments to input grammar. | ```antlr
grammar PTP;
@header {
package pt.up.fe.iart.proj1.parser;
}
map : stmt+ ;
stmt : node_stmt #node
| edge_stmt #edge
;
edge_stmt : 'Edge' '(' from=node_stmt ',' to=node_stmt ',' weight=(INT|REAL) ')';
node_stmt : 'GasStation' '(' position ')' #GasStation
| 'GenericLocation' '(' position ')' #GenericLocation
| 'PatientLocation' '(' position ')' #PatientLocation
| 'Filiation' '(' position ',' bool ')' #Filiation
;
position : '(' x=INT ',' y=INT ')' ;
bool : 'true' | 'false' ;
INT: [0-9]+ ;
REAL: [0-9]+ '.' [0-9]* ;
WS : [ \t\r\n]+ -> skip;
COMMENT : '/*' .*? '*/' -> skip ;
LINE_COMMENT : '//' .*? '\r'? '\n' -> skip ;``` |
735241e6-dd86-43fc-9bb8-3d081386090e | {
"language": "ANTLR"
} | ```antlr
grammar Type;
CT : [A-Z][a-z]+ ;
VT : [a-z]+ ;
WS : [ \t\r\n]+ -> skip ;
type : typeClasses ? innerType ;
innerType : functionType | compoundType ; // function type
functionType : compoundType '->' innerType ;
compoundType : constantType | variableType | tupleType | listType | parenType ;
tupleType : '(' innerType (',' innerType)+ ')' ; // tuple type, k>=2
listType : '[' innerType ']' ; // list type
parenType : '(' innerType ')' ; // type with parentheses
constantType : typeConstructor (WS* innerType)* ;
typeConstructor : CT ;
variableType : VT ;
typeClasses : '(' typeWithClass (',' typeWithClass)* ')' '=>' ;
typeWithClass : typeClass WS* classedType ;
classedType : VT ;
typeClass : CT ;
```
Add single type class notation to type parser | ```antlr
grammar Type;
CT : [A-Z][a-z]+ ;
VT : [a-z]+ ;
WS : [ \t\r\n]+ -> skip ;
type : typeClasses ? innerType ;
innerType : functionType | compoundType ; // function type
functionType : compoundType '->' innerType ;
compoundType : constantType | variableType | tupleType | listType | parenType ;
tupleType : '(' innerType (',' innerType)+ ')' ; // tuple type, k>=2
listType : '[' innerType ']' ; // list type
parenType : '(' innerType ')' ; // type with parentheses
constantType : typeConstructor (WS* innerType)* ;
typeConstructor : CT ;
variableType : VT ;
typeClasses : '(' typeWithClass (',' typeWithClass)* ')' '=>' | typeWithClass '=>' ;
typeWithClass : typeClass WS* classedType ;
classedType : VT ;
typeClass : CT ;
``` |
e3a2cae9-5bb3-40e9-8602-c8c09c389f93 | {
"language": "ANTLR"
} | ```antlr
```
Add first attempt at track grammar | ```antlr
grammar Track;
track: track_decl decl* ;
track_decl: 'track' '{' IDENT+ '}' ;
decl: block_decl | channel_decl ;
block_decl: IDENT '::' 'block' '{' block_body '}' ;
block_body: (note)+ ;
note: NOTENAME OCTAVE? LENGTH? ;
channel_decl: IDENT '::' 'channel' WAVE '{' channel_body '}' ;
channel_body: (block_name)+ ;
block_name: IDENT ;
NOTENAME: 'Ab'
| 'A'
| 'A#'
| 'Bb'
| 'B'
| 'C'
| 'C#'
| 'Db'
| 'D'
| 'D#'
| 'Eb'
| 'E'
| 'F'
| 'F#'
| 'Gb'
| 'G'
| 'G#'
| 'R'
;
OCTAVE: [0-9] | '10' ;
LENGTH: [-+.]+ ;
WAVE: 'triangle' | 'square' | 'sawtooth' | 'noise' ;
IDENT: [a-zA-Z][a-zA-Z0-9_]+ ;
WS: [\t\r\n ]+ -> skip ;
``` |
b5d1082f-01b9-4884-a6a8-dfb611e414d8 | {
"language": "ANTLR"
} | ```antlr
```
Create prolog/scala based ANTLR 4 grammar to use to parse input files. | ```antlr
grammar PTP;
@header {
package pt.up.fe.iart.proj1.parser;
}
map : stmt+ ;
stmt : node_stmt #node
| edge_stmt #edge
;
edge_stmt : 'Edge' '(' from=node_stmt ',' to=node_stmt ',' weight=(INT|REAL) ')';
node_stmt : 'GasStation' '(' position ')' #GasStation
| 'GenericLocation' '(' position ')' #GenericLocation
| 'PatientLocation' '(' position ')' #PatientLocation
| 'Filiation' '(' position ',' bool ')' #Filiation
;
position : '(' x=INT ',' y=INT ')' ;
bool : 'true' | 'false' ;
INT: [0-9]+ ;
REAL: [0-9]+ '.' [0-9]* ;
WS : [ \t\r\n]+ -> skip;``` |
1d31128f-c589-4ef2-bf44-ea4c10d25a77 | {
"language": "ANTLR"
} | ```antlr
```
Add grammar in ANTLR 4 format | ```antlr
grammar Viper;
tokens { NAME
, NEWLINE
, INDENT
, DEDENT
, NUMBER
, STRING
}
func_def: 'def' func_name parameters '->' func_type ':' suite ;
func_name: NAME ;
func_type: type_expr ;
parameters: '(' params_list? ')' ;
params_list: argless_parameter parameter* ;
parameter: arg_label? argless_parameter ;
argless_parameter: param_name ':' param_type ;
arg_label: NAME ;
param_name: NAME ;
param_type: type_expr ;
type_expr: NAME ;
suite: ( simple_stmt
| NEWLINE INDENT stmt+ DEDENT
) ;
stmt: ( simple_stmt
| compound_stmt
) ;
simple_stmt: expr_stmt NEWLINE ;
expr_stmt: ( expr_list
| 'pass'
| 'return' expr_list?
) ;
expr_list: expr (',' expr)* ;
expr: atom_expr ;
atom_expr: atom trailer* ;
atom: ( '(' expr_list? ')'
| NAME
| NUMBER
| STRING
| '...'
| 'Zilch'
| 'True'
| 'False'
) ;
trailer: ( '(' arg_list? ')'
| '.' NAME
) ;
compound_stmt: ( func_def
| object_def
| data_def
) ;
object_def: ( class_def
| interface_def
| implementation_def
) ;
class_def: 'class' common_def ;
interface_def: 'interface' common_def ;
implementation_def: NAME common_def ;
data_def: 'data' common_def ;
common_def: NAME ('(' arg_list? ')')? ':' suite ;
arg_list: argument (',' argument)* ;
argument: expr ;
``` |
177c6d70-5877-4c03-99c9-2d3402ee3792 | {
"language": "ApacheConf"
} | ```apacheconf
server {
server_name default;
root /var/www/public;
index main.php;
client_max_body_size 100M;
fastcgi_read_timeout 1800;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location /status {
access_log off;
allow 172.17.0.0/16;
deny all;
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME /status;
fastcgi_pass unix:/var/run/php5-fpm.sock;
}
location /ping {
access_log off;
allow all;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /ping;
fastcgi_pass unix:/Var/run/php5-fpm.sock;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires max;
log_not_found off;
access_log off;
}
location ~ \.php$ {
try_files $uri =404;
include fastcgi_params;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/var/run/php5-fpm.sock;
}
}
```
Remove .php extensions from url | ```apacheconf
server {
server_name default;
root /var/www/public;
index main.php;
client_max_body_size 100M;
fastcgi_read_timeout 1800;
location / {
try_files $uri $uri.html $uri/ @extensionless-php;
}
location @extensionless-php {
rewrite ^(.*)$ $1.php last;
}
location /status {
access_log off;
allow 172.17.0.0/16;
deny all;
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME /status;
fastcgi_pass unix:/var/run/php5-fpm.sock;
}
location /ping {
access_log off;
allow all;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /ping;
fastcgi_pass unix:/Var/run/php5-fpm.sock;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires max;
log_not_found off;
access_log off;
}
location ~ \.php$ {
try_files $uri =404;
include fastcgi_params;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/var/run/php5-fpm.sock;
}
}
``` |
ee59be54-8e9b-4a5a-81d5-4925fa021744 | {
"language": "ApacheConf"
} | ```apacheconf
WSGIPythonPath /path/to/repo/FuzzManager/server
<VirtualHost *:80>
ServerName fuzzmanager.your.domain
Alias /static/ /path/to/repo/FuzzManager/server/crashmanager/static/
Alias /tests/ /path/to/repo/FuzzManager/server/tests/
WSGIScriptAlias / /path/to/repo/FuzzManager/server/server/wsgi.py
WSGIPassAuthorization On
<Location />
AuthType Basic
AuthName "LDAP Login"
AuthBasicProvider file ldap
AuthUserFile /path/to/.htpasswd
# Your LDAP configuration here, including Require directives
# This user is used by clients to download test cases and signatures
Require user fuzzmanager
</Location>
<Location /crashmanager/rest/>
Satisfy Any
Allow from all
</Location>
<Directory /path/to/repo/FuzzManager/server>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
</VirtualHost>
```
Update example vhost file for Apache2 | ```apacheconf
WSGIDaemonProcess fuzzmanager.your.domain python-path=/path/to/repo/FuzzManager/server
WSGIProcessGroup fuzzmanager.your.domain
WSGIApplicationGroup %{GLOBAL}
<VirtualHost *:80>
ServerName fuzzmanager.your.domain
Alias /static/ /path/to/repo/FuzzManager/server/crashmanager/static/
Alias /tests/ /path/to/repo/FuzzManager/server/tests/
WSGIScriptAlias / /path/to/repo/FuzzManager/server/server/wsgi.py process-group=fuzzmanager.your.domain
WSGIPassAuthorization On
<Location />
AuthType Basic
AuthName "LDAP Login"
AuthBasicProvider file ldap
AuthUserFile /path/to/.htpasswd
# Your LDAP configuration here, including Require directives
# This user is used by clients to download test cases and signatures
Require user fuzzmanager
</Location>
<Location /crashmanager/rest/>
Satisfy Any
Allow from all
</Location>
<Location /ec2spotmanager/rest/>
Satisfy Any
Allow from all
</Location>
<Directory /path/to/repo/FuzzManager/server>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
</VirtualHost>
``` |
7c5580fa-0b56-4324-94e7-8946d91618e8 | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
HOST: https://neighbor.ly/api/
# Neighbor.ly
Here you will find how to integrate an application with Neighbor.ly. Check our [Dashboard source code](https://github.com/neighborly/neighborly-dashboard) for a real use case.
# Sessions
Your first stop when integrating with Neighborly. For a lot of endpoints, you are expected to provide an `access_token`, managed by this section.
## Sessions [/sessions]
### Create a session [POST]
+ Request
{ "email": "[email protected]", "password": "your-really-strong-password" }
+ Header
Accept: application/vnd.api+json;revision=1
+ Response 201 (application/json)
{ "access_token": "Ndf6kxgLfr_KMhAg8wMpm7Yit2cvHkv9oI8qIXWiHmZdeqI1h0cmn8p4wCEhoZS-AQY", "user_id": 1 }
+ Response 400 (application/json)
{}
+ Response 401 (application/json)
{}
```
Add body section to create a new session | ```apiblueprint
FORMAT: 1A
HOST: https://neighbor.ly/api/
# Neighbor.ly
Here you will find how to integrate an application with Neighbor.ly. Check our [Dashboard source code](https://github.com/neighborly/neighborly-dashboard) for a real use case.
# Sessions
Your first stop when integrating with Neighborly. For a lot of endpoints, you are expected to provide an `access_token`, managed by this section.
## Sessions [/sessions]
### Create a session [POST]
+ Request
+ Header
Accept: application/vnd.api+json;revision=1
+ Body
{ "email": "[email protected]", "password": "your-really-strong-password" }
+ Response 201 (application/json)
{ "access_token": "Ndf6kxgLfr_KMhAg8wMpm7Yit2cvHkv9oI8qIXWiHmZdeqI1h0cmn8p4wCEhoZS-AQY", "user_id": 1 }
+ Response 400 (application/json)
{}
+ Response 401 (application/json)
{}
``` |
c161883e-46a7-45df-b15c-b3ed82e08e3c | {
"language": "API Blueprint"
} | ```apiblueprint
# Lion API
Lion is a basic localization service using `git` as the backend for storing translations.
## Request headers
All requests to Lion must include the following headers:
- `Lion-Api-Version`
# Group Projects
## Project collection [/projects]
### List projects [GET]
List all configured projects
+ Request (application/json)
+ Header
Lion-Api-Version: v1
+ Response 200 (application/json)
+ Header
Lion-Api-Version: v1
+ Body
{
"projects": [
"projectA": {
"name" "projectA" // All project details
}
]
}
## Project management [/project/{name}]
+ Parameters
+ name (required, string) ... Project name
### Get project [GET]
Fetch project details, given the projects' name.
+ Request (application/json)
+ Header
Lion-Api-Version: v1
+ Response 200 (application/json)
+ Header
Lion-Api-Version: v1
+ Body
{
"name": "Project name",
"resources": [
"resource1",
"..."
]
}
+ Response 404 (application/json)
+ Header
Lion-Api-Version: v1
```
Make the API version optional in the request | ```apiblueprint
# Lion API
Lion is a basic localization service using `git` as the backend for storing translations.
## Request headers
Requests should have the `Lion-Api-Version` header set. The current API version is `v1`. If the header is not set, it is assumed to be the latest version.
Example header:
- `Lion-Api-Version: v1`
# Group Projects
## Project collection [/projects]
### List projects [GET]
List all configured projects
+ Request (application/json)
+ Header
Lion-Api-Version: v1
+ Response 200 (application/json)
+ Header
Lion-Api-Version: v1
+ Body
{
"projects": [
"projectA": {
"name" "projectA" // All project details
}
]
}
## Project management [/project/{name}]
+ Parameters
+ name (required, string) ... Project name
### Get project [GET]
Fetch project details, given the projects' name.
+ Request (application/json)
+ Header
Lion-Api-Version: v1
+ Response 200 (application/json)
+ Header
Lion-Api-Version: v1
+ Body
{
"name": "Project name",
"resources": [
"resource1",
"..."
]
}
+ Response 404 (application/json)
+ Header
Lion-Api-Version: v1
``` |
a61d3f4d-6366-4c73-b0d7-940d25d30f21 | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
HOST: https://www.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt"
}
```
Add article body to API Blueprint | ```apiblueprint
FORMAT: 1A
HOST: https://www.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt",
"body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>"
}
``` |
c39ef5a3-dc97-4545-ad68-8861d00d4117 | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
HOST: https://orgmanager.miguelpiedrafita.com/api
# Orgmanager API
The Orgmanager API allows you to integrate Orgmanager with other applications and projects.
## Questions Collection [/questions]
### List All Questions [GET]
+ Response 200 (application/json)
[
{
"question": "Favourite programming language?",
"published_at": "2015-08-05T08:40:51.620Z",
"choices": [
{
"choice": "Swift",
"votes": 2048
}, {
"choice": "Python",
"votes": 1024
}, {
"choice": "Objective-C",
"votes": 512
}, {
"choice": "Ruby",
"votes": 256
}
]
}
]
### Create a New Question [POST]
You may create your own question using this action. It takes a JSON
object containing a question and a collection of answers in the
form of choices.
+ Request (application/json)
{
"question": "Favourite programming language?",
"choices": [
"Swift",
"Python",
"Objective-C",
"Ruby"
]
}
+ Response 201 (application/json)
+ Headers
Location: /questions/2
+ Body
{
"question": "Favourite programming language?",
"published_at": "2015-08-05T08:40:51.620Z",
"choices": [
{
"choice": "Swift",
"votes": 0
}, {
"choice": "Python",
"votes": 0
}, {
"choice": "Objective-C",
"votes": 0
}, {
"choice": "Ruby",
"votes": 0
}
]
}
```
Add /user and /user/orgs api endpoints to api docs | ```apiblueprint
FORMAT: 1A
HOST: https://orgmanager.miguelpiedrafita.com/api
# Orgmanager API
The Orgmanager API allows you to integrate Orgmanager with other applications and projects.
## User Data [/user]
### Get user info [GET]
+ Response 200 (application/json)
{
"id":1,
"name":"Miguel Piedrafita",
"email":"[email protected]",
"github_username":"m1guelpf",
"created_at":"2017-01-25 18:44:32",
"updated_at":"2017-02-16 19:40:50"
}
## User Organizations [/user/orgs]
### Get user organizations [GET]
+ Response 200 (application/json)
{
"id":1,
"name":"Test Organization",
"url":"https:\/\/api.github.com\/orgs\/test-org",
"description":null,
"avatar":"https:\/\/miguelpiedrafita.com\/logo.png",
"invitecount":100
}
``` |
3c30770f-f075-4c2e-acec-7321d67956da | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
HOST: https://www.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt",
"body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>"
}
```
Add locale to API Blueprint | ```apiblueprint
FORMAT: 1A
HOST: https://www.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/{locale}/articles/{id}]
A single Article object with all its details
+ Parameters
+ locale = `en` (optional, string, `cy`) ... Locale of the Article.
+ id (required, string, `foo-bar`) ... ID of the Article.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt",
"body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>"
}
``` |
0448eb27-e039-4dbd-ad69-95b3f6411339 | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
HOST: https://api.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"id": "where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt"
}
```
Add URLs to API Blueprint | ```apiblueprint
FORMAT: 1A
HOST: https://www.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt"
}
``` |
75f3b46d-73e9-46f2-a61c-86670e91d694 | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
HOST: https://www.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/{locale}/articles/{id}]
A single Article object with all its details
+ Parameters
+ locale = `en` (optional, string, `cy`) ... Locale of the Article.
+ id (required, string, `where-to-go-to-get-free-debt-advice`) ... ID of the Article.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt",
"body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>"
}
```
Fix locale example for API Blueprint | ```apiblueprint
FORMAT: 1A
HOST: https://www.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/{locale}/articles/{id}]
A single Article object with all its details
+ Parameters
+ locale = `en` (optional, string, `en`) ... Locale of the Article.
+ id (required, string, `where-to-go-to-get-free-debt-advice`) ... ID of the Article.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt",
"body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>"
}
``` |
5878ebe1-9efa-4114-bb5e-484dd228d679 | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
HOST: https://api.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service's API.
# Group Articles
Article related resources of the **Money Advice Service**
## Articles Collection [/articles]
### List all Articles [GET]
+ Response 200 (application/json)
[{
"id": 1, "content": "Jogging in park"
}, {
"id": 2, "content": "Pick-up posters from post-office"
}]
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ slug (required, string, `the-article`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
X-My-Header: The Value
+ Body
{ "slug": "the-article", "title": "Pick-up posters from post-office", content: "<p>La de da</p>" }
```
Remove articles collection from API blueprint | ```apiblueprint
FORMAT: 1A
HOST: https://api.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
X-My-Header: The Value
+ Body
{ "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice" }
``` |
9c057a54-83f0-481f-bea0-67e5bdbd2b00 | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
HOST: https://www.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt",
"body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>"
}
```
Add locale to API Blueprint | ```apiblueprint
FORMAT: 1A
HOST: https://www.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/{locale}/articles/{id}]
A single Article object with all its details
+ Parameters
+ locale = `en` (optional, string, `cy`) ... Locale of the Article.
+ id (required, string, `foo-bar`) ... ID of the Article.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt",
"body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>"
}
``` |
7a3e0062-7745-4261-8f2c-0389d15e170a | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
HOST: https://api.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
X-My-Header: The Value
+ Body
{ "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice" }
```
Add link header to API Blueprint | ```apiblueprint
FORMAT: 1A
HOST: https://api.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{ "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice" }
``` |
fd6bfff2-b5ec-4a0c-a3c4-a9d19eaadc5c | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
HOST: https://www.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt"
}
```
Add article body to API Blueprint | ```apiblueprint
FORMAT: 1A
HOST: https://www.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt",
"body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>"
}
``` |
e282a9fb-f61b-441a-a26c-d30bab76724d | {
"language": "API Blueprint"
} | ```apiblueprint
# Lion API
Lion is a basic localization service using `git` as the backend for storing translations.
## Request headers
Requests should have the `Lion-Api-Version` header set. The current API version is `v1`. If the header is not set, it is assumed to be the latest version.
Example header:
- `Lion-Api-Version: v1`
# Group Projects
## Project collection [/projects]
### List projects [GET]
List all configured projects
+ Request (application/json)
+ Header
Lion-Api-Version: v1
+ Response 200 (application/json)
+ Header
Lion-Api-Version: v1
+ Body
{
"projects": [
"projectA": {
"name" "projectA" // All project details
}
]
}
## Project management [/project/{name}]
+ Parameters
+ name (required, string) ... Project name
### Get project [GET]
Fetch project details, given the projects' name.
+ Request (application/json)
+ Header
Lion-Api-Version: v1
+ Response 200 (application/json)
+ Header
Lion-Api-Version: v1
+ Body
{
"name": "Project name",
"resources": [
"resource1",
"..."
]
}
+ Response 404 (application/json)
+ Header
Lion-Api-Version: v1
```
Substitute name with slug for fetching projects | ```apiblueprint
# Lion API
Lion is a basic localization service using `git` as the backend for storing translations.
## Request headers
Requests should have the `Lion-Api-Version` header set. The current API version is `v1`. If the header is not set, it is assumed to be the latest version.
Example header:
- `Lion-Api-Version: v1`
# Group Projects
## Project collection [/projects]
### List projects [GET]
List all configured projects
+ Request (application/json)
+ Header
Lion-Api-Version: v1
+ Response 200 (application/json)
+ Header
Lion-Api-Version: v1
+ Body
{
"projects": [
"projectA": {
"name" "projectA" // All project details
...
}
]
}
## Project management [/project/{slug}]
+ Parameters
+ slug (required, string) ... Project slug
### Get project [GET]
Fetch project details, given the projects' name.
+ Request (application/json)
+ Header
Lion-Api-Version: v1
+ Response 200 (application/json)
+ Header
Lion-Api-Version: v1
+ Body
{
"name": "Project name",
"slug": "project-name",
"resources": [
"resource1",
"..."
]
}
+ Response 404 (application/json)
+ Header
Lion-Api-Version: v1
``` |
909bdae0-ae6f-4da4-a045-29beead3590d | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
HOST: https://api.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{ "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice" }
```
Add article description to API Blueprint | ```apiblueprint
FORMAT: 1A
HOST: https://api.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"id": "where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt"
}
``` |
e13c4a44-ea7f-4606-95ff-156432c02d96 | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
HOST: https://awesome-bucketlist-api.herokuapp.com/
# awesome-bucketlist
Polls is a simple API allowing consumers to view polls and vote in them.
## Bucketlists [/bucketlists]
### Create New Bucketlist [POST]
Creates a new bucketlist under your account.
+ Request (application/json)
+ Headers
Authorization: "Your Token"
+ Response 201 (application/json)
[
{
"name": "Dare Devil",
"description": "Stunts I want to try out."
}
]
### Get All Bucketlists [GET]
You may create your own question using this action. It takes a JSON
object containing a question and a collection of answers in the
form of choices.
+ Request (application/json)
+ Headers
Authorization: "Your Token"
+ Response 200 (application/json)
+ Body
[
{
"name": "Dare Devil",
"description": "Stunts I want to try out."
}
]```
Update Introduction description for Apiary | ```apiblueprint
FORMAT: 1A
HOST: https://awesome-bucketlist-api.herokuapp.com/
# awesome-bucketlist
A Bucketlist is a list of items, activities or goals you want to achieve before you "kick the bucket"
this is an API to allow you create a new user account, login into your account, create, update, view or delete
bucketlists and bucketlist items.e
## Bucketlists [/bucketlists]
### Create New Bucketlist [POST]
Creates a new bucketlist under your account.
+ Request (application/json)
+ Headers
Authorization: "Your Token"
+ Response 201 (application/json)
[
{
"name": "Dare Devil",
"description": "Stunts I want to try out."
}
]
### Get All Bucketlists [GET]
You may create your own question using this action. It takes a JSON
object containing a question and a collection of answers in the
form of choices.
+ Request (application/json)
+ Headers
Authorization: "Your Token"
+ Response 200 (application/json)
+ Body
[
{
"name": "Dare Devil",
"description": "Stunts I want to try out."
}
]``` |
582d9221-dd75-44dd-a827-bb49d951f810 | {
"language": "API Blueprint"
} | ```apiblueprint
<!-- include(models.apib) -->
# Group Rescues
<!-- include(rescues/list.apib) -->
<!-- include(rescues/create.apib) -->
<!-- include(rescues/retrieve.apib) -->
<!-- include(rescues/update.apib) -->
```
Add missing rescue search documentation | ```apiblueprint
# Group Rescues
<!-- include(rescues/list.apib) -->
<!-- include(rescues/create.apib) -->
<!-- include(rescues/retrieve.apib) -->
<!-- include(rescues/search.apib) -->
<!-- include(rescues/update.apib) -->
``` |
20a7caa5-cea6-41f3-9198-5955a1c3bbe0 | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
HOST: https://www.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/{locale}/articles/{id}]
A single Article object with all its details
+ Parameters
+ locale = `en` (optional, string, `cy`) ... Locale of the Article.
+ id (required, string, `where-to-go-to-get-free-debt-advice`) ... ID of the Article.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt",
"body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>"
}
```
Fix locale example for API Blueprint | ```apiblueprint
FORMAT: 1A
HOST: https://www.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/{locale}/articles/{id}]
A single Article object with all its details
+ Parameters
+ locale = `en` (optional, string, `en`) ... Locale of the Article.
+ id (required, string, `where-to-go-to-get-free-debt-advice`) ... ID of the Article.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt",
"body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>"
}
``` |
072111ee-dc19-4ede-a3ad-d95357c5dd8f | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
HOST: https://api.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
X-My-Header: The Value
+ Body
{ "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice" }
```
Add link header to API Blueprint | ```apiblueprint
FORMAT: 1A
HOST: https://api.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{ "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice" }
``` |
b5318140-9819-47d6-8787-dd36c14f8a18 | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
HOST: https://api.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{ "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice" }
```
Add article description to API Blueprint | ```apiblueprint
FORMAT: 1A
HOST: https://api.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"id": "where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt"
}
``` |
2bb1ebe2-c0da-4951-88f4-1dbc78c4503e | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
HOST: https://api.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"id": "where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt"
}
```
Add URLs to API Blueprint | ```apiblueprint
FORMAT: 1A
HOST: https://www.moneyadviceservice.org.uk
# Money Advice Service
API for the Money Advice Service.
# Articles
Article related resources of the **Money Advice Service**.
## Article [/articles/{id}]
A single Article object with all its details
+ Parameters
+ id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value.
### Retrieve a Article [GET]
+ Response 200 (application/json)
+ Header
Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled"
+ Body
{
"url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice",
"title": "Where to go to get free debt advice",
"description": "Find out where you can get free, confidential help if you are struggling with debt"
}
``` |
bde2fdaa-1f8a-4e00-bfbc-4d418c075dc5 | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
# Machines API
# Group Machines
# Machines collection [/machines/{id}]
+ Parameters
- id (number, `1`)
## Get Machines [GET]
- Request (application/json)
+ Parameters
- id (number, `2`)
- Response 200 (application/json; charset=utf-8)
[
{
"type": "bulldozer",
"name": "willy"
}
]
- Request (application/json)
+ Parameters
- id (number, `3`)
- Response 200 (application/json; charset=utf-8)
[
{
"type": "bulldozer",
"name": "willy"
}
]
```
Use 4 spaces as indentation | ```apiblueprint
FORMAT: 1A
# Machines API
# Group Machines
# Machines collection [/machines/{id}]
+ Parameters
+ id (number, `1`)
## Get Machines [GET]
+ Request (application/json)
+ Parameters
+ id (number, `2`)
+ Response 200 (application/json; charset=utf-8)
[
{
"type": "bulldozer",
"name": "willy"
}
]
+ Request (application/json)
+ Parameters
+ id (number, `3`)
+ Response 200 (application/json; charset=utf-8)
[
{
"type": "bulldozer",
"name": "willy"
}
]
``` |
f0bda386-ff89-4f6b-a7e3-214fba6a59cf | {
"language": "API Blueprint"
} | ```apiblueprint
FORMAT: 1A
# Organising, Swiftly
_Organising_ is an outliner/todo list with strong search functionality.
## Node Collection [/nodes]
### Root node and all children [GET]
Returns the root node, with all of its children.
+ Response 200 (application/json)
{
"ID": 0,
"text": "Update repo",
"completed": false,
"children": [
{
"ID": 1,
"text": "Commit changes",
"completed": true
}, {
"ID": 2,
"text": "Push to origin",
"completed": false
}
]
}```
Correct API definition semantic issues. | ```apiblueprint
FORMAT: 1A
# Organising, Swiftly
_Organising_ is an outliner/todo list with strong search functionality.
## Node Collection [/nodes]
### Root node and all children [GET]
Returns the root node, with all of its children.
+ Response 200 (application/json)
{
"ID": 0,
"text": "Update repo",
"completed": false,
"children": [
{
"ID": 1,
"text": "Commit changes",
"completed": true
}, {
"ID": 2,
"text": "Push to origin",
"completed": false
}
]
}``` |
e37c57b4-5cbd-4cd4-9b13-c00dfc80d122 | {
"language": "API Blueprint"
} | ```apiblueprint
```
Add Apiary Documentation for the API | ```apiblueprint
FORMAT: 1A
HOST: https://awesome-bucketlist-api.herokuapp.com/
# awesome-bucketlist
Polls is a simple API allowing consumers to view polls and vote in them.
## Bucketlists [/bucketlists]
### Create New Bucketlist [POST]
Creates a new bucketlist under your account.
+ Request (application/json)
+ Headers
Authorization: "Your Token"
+ Response 201 (application/json)
[
{
"name": "Dare Devil",
"description": "Stunts I want to try out."
}
]
### Get All Bucketlists [GET]
You may create your own question using this action. It takes a JSON
object containing a question and a collection of answers in the
form of choices.
+ Request (application/json)
+ Headers
Authorization: "Your Token"
+ Response 200 (application/json)
+ Body
[
{
"name": "Dare Devil",
"description": "Stunts I want to try out."
}
]``` |
25b17d1f-2bf3-468f-a8b4-5287f49c0ad3 | {
"language": "API Blueprint"
} | ```apiblueprint
```
Add login and registration to blueprint | ```apiblueprint
FORMAT: 1A
# Admiral
Admiral is a deployment management system for Fleet and CoreOS. Unlike other deployment systems, Admiral also allows for automatic deployment and scaling of Fleet units.
# Admiral Root [/v1]
This resource simply represents the root of the Admiral API. It provides a basic JSON response as validation that the API server is running.
## Retrieve the API Information [GET]
+ Response 200 (application/json)
{
"name": "Admiral API",
"version": 1
}
## Group Authentication
Resources related to authenticating users.
## Login [/v1/login]
### Login [POST]
Authenticates a user and returns a token that the client should use for further interactions with the API server.
Requests should be made with a JSON object containing the following items:
+ Request (application/json)
{
"username": "johndoe",
"password": "password"
}
+ Response 200 (application/json)
{
"token": "API token"
}
+ Response 401 (application/json)
{
"error": 401,
"message": "The specified user was invalid."
}
## Registration [/v1/register]
### Register [POST]
Registers a user with the specified information, and returns a new token if the registration was successful. Registration must be enabled on the server or this endpoint will return an error.
+ Request (application/json)
{
"username": "johndoe",
"password": "password"
}
+ Response 200 (application/json)
{
"token": "API token"
}
+ Response 500 (application/json)
{
"error": 500,
"message": "The server is not accepting registration."
}
``` |
2982949c-26f6-4d8b-be34-fad9cb838380 | {
"language": "APL"
} | ```apl
msg←SelectAdvanced;result;output;sel;froot;prev
⍝ Test /Examples/DC/SelectAdvanced
⍝ Ensure 'multi' (the selection list) is there:
msg←'selection list not there'
:If 0≢sel←Find'multi'
⍝ Grab the 2 elements already chosen:
Click'PressMe'
output←Find'output'
{0≠⍴output.Text}Retry ⍬ ⍝ Wait to see if it gets populated
msg←'Expected output was not produced.'
:AndIf 'You picked: Bananas Pears'≡prev←output.Text
⍝ Make a single selection:
froot←'Grapes'
'multi'SelectByText'-'froot
Click'PressMe'
output←Find'output'
{prev≢output.Text}Retry ⍬ ⍝ Wait to see if it gets populated
:AndIf (prev←output.Text)≡'You picked: ',froot
⍝ Make another selection:
'multi'SelectByText'Pears'
Click'PressMe'
output←Find'output'
{prev≢output.Text}Retry ⍬ ⍝ Wait to see if it gets populated
:AndIf (prev←output.Text)≡'You picked: ',froot,' Pears'
msg←''
:EndIf```
Rename of SelectByText to SelectItemText | ```apl
msg←SelectAdvanced;result;output;sel;froot;prev
⍝ Test /Examples/DC/SelectAdvanced
⍝ Ensure 'multi' (the selection list) is there:
msg←'selection list not there'
:If 0≢sel←Find'multi'
⍝ Grab the 2 elements already chosen:
Click'PressMe'
output←Find'output'
{0≠⍴output.Text}Retry ⍬ ⍝ Wait to see if it gets populated
msg←'Expected output was not produced.'
:AndIf 'You picked: Bananas Pears'≡prev←output.Text
⍝ Make a single selection:
froot←'Grapes'
'multi'SelectItemText'~'froot
Click'PressMe'
output←Find'output'
{prev≢output.Text}Retry ⍬ ⍝ Wait to see if it gets populated
:AndIf (prev←output.Text)≡'You picked: ',froot
⍝ Make another selection:
'multi'SelectItemText'Pears'
Click'PressMe'
output←Find'output'
{prev≢output.Text}Retry ⍬ ⍝ Wait to see if it gets populated
:AndIf (prev←output.Text)≡'You picked: ',froot,' Pears'
msg←''
:EndIf``` |
4727b64b-c088-4819-80c6-5249f9ef0941 | {
"language": "APL"
} | ```apl
:Class EditFieldSimple : MiPageSample
⍝ Control:: _DC.EditField _DC.Button _html.label
⍝ Description:: Collect input and echo it on a button press
∇ Compose;btn;F1;label;name
:Access Public
F1←'myform'Add _.Form ⍝ Create a form
label←('for"name"')F1.Add _.label'Please enter your name'
name←'name'F1.Add _.EditField
done←'done'F1.Add _.Button'Done'
done.On'click' 'CallbackFn'
'result'F1.Add _.div ⍝ a div to contain output, updated by CallbackFn
∇
∇ r←CallbackFn
:Access Public
r←'#result'Replace _.p('Hello, ',(Get'name'),'!')
∇
:EndClass```
Add missing '=' in MS3/Examples/DC/EditFieldSample | ```apl
:Class EditFieldSimple : MiPageSample
⍝ Control:: _DC.EditField _DC.Button _html.label
⍝ Description:: Collect input and echo it on a button press
∇ Compose;btn;F1;label;name
:Access Public
F1←'myform'Add _.Form ⍝ Create a form
label←('for="name"')F1.Add _.label'Please enter your name'
name←'name'F1.Add _.EditField
done←'done'F1.Add _.Button'Done'
done.On'click' 'CallbackFn'
'result'F1.Add _.div ⍝ a div to contain output, updated by CallbackFn
∇
∇ r←CallbackFn
:Access Public
r←'#result'Replace _.p('Hello, ',(Get'name'),'!')
∇
:EndClass``` |
7cd2e625-0b30-4ca8-bd7b-8b3d70d3d365 | {
"language": "APL"
} | ```apl
:Class MS3Server : MiServer
⍝ This is an example of a customized MiServer
⍝ The MiServer class exposes several overridable methods that can be customized by the user
⍝ In this case we customize the onServerLoad method
⍝ The ClassName parameter in the Server.xml configuration file is used to specify the customized class
:Include #.MS3SiteUtils ⍝∇:require =/MS3SiteUtils
∇ Make config
:Access Public
:Implements Constructor :Base config
⍝ Version warning
:If 14>{⊃(//)⎕VFI ⍵/⍨2>+\'.'=⍵}2⊃'.'⎕WG'APLVersion'
⎕←''
⎕←'MiServer 3.0 itself will run under Dyalog APL versions 13.2 and later'
⎕←'However, the MS3 MiSite uses features found only in Dyalog APL versions beginning with 14.0'
⎕←''
⎕←'Please restart the MS3 MiSite using Dyalog APL version 14.0 or later...'
→
:EndIf
∇
∇ onServerLoad
:Access Public Override
⍝ Handle any server startup processing
{}C ⍝ initialize CACHE
∇
:EndClass```
Upgrade message inculdes note of 15.0+ being free. | ```apl
:Class MS3Server : MiServer
⍝ This is an example of a customized MiServer
⍝ The MiServer class exposes several overridable methods that can be customized by the user
⍝ In this case we customize the onServerLoad method
⍝ The ClassName parameter in the Server.xml configuration file is used to specify the customized class
:Include #.MS3SiteUtils ⍝∇:require =/MS3SiteUtils
∇ Make config
:Access Public
:Implements Constructor :Base config
⍝ Version warning
:If 14>{⊃(//)⎕VFI ⍵/⍨2>+\'.'=⍵}2⊃'.'⎕WG'APLVersion'
⎕←''
⎕←'MiServer 3.0 itself will run under Dyalog APL versions 13.2 and later'
⎕←'However, the MS3 MiSite uses features found only in Dyalog APL versions beginning with 14.0'
⎕←'From version 15.0, Dyalog APL is available free of charge at http://www.dyalog.com'
⎕←''
⎕←'Please restart the MS3 MiSite using Dyalog APL version 14.0 or later...'
→
:EndIf
∇
∇ onServerLoad
:Access Public Override
⍝ Handle any server startup processing
{}C ⍝ initialize CACHE
∇
:EndClass
``` |
5340748d-96d3-4f25-a17f-0314ad8a9e64 | {
"language": "APL"
} | ```apl
:class aSimple : MiPageSample
⍝ Control:: _html.a
⍝ Description:: Insert a hyperlink
∇ Compose
:Access public
Add 'Click '
'href' 'http://www.dyalog.com/meet-team-dyalog.htm'Add _.a'here'
Add ' to meet us.'
∇
:endclass
```
Fix to new ParseAttr syntax | ```apl
:class aSimple : MiPageSample
⍝ Control:: _html.a
⍝ Description:: Insert a hyperlink
∇ Compose
:Access public
Add'Click '
'href=http://www.dyalog.com/meet-team-dyalog.htm'Add _.a'here'
Add' to meet us.'
∇
:endclass
``` |
f25d0f72-adc5-4d90-9ae7-abb84825cdc1 | {
"language": "APL"
} | ```apl
#!/usr/local/bin/apl -s
'Day 3: Perfectly Spherical Houses in a Vacuum'
i ← (0 0)
cmds ← ('<' '>' '^' 'v')
dirs ← ((¯1 0) (1 0) (0 ¯1) (0 1))
houses ← ∪ (0 0) , i { ++\⍵ } { dirs[ti] ⊣ ti ← cmds ⍳ ⍵ } ⍞
⍴ houses ⍝ the amount of houses to visit
)OFF
```
Trim fat on apl nr 1 | ```apl
#!/usr/local/bin/apl -s
'Day 3: Perfectly Spherical Houses in a Vacuum'
cmds ← ('<' '>' '^' 'v')
dirs ← ((¯1 0) (1 0) (0 ¯1) (0 1))
houses ← ∪ (0 0) , { ++\⍵ } { dirs[ti] ⊣ ti ← cmds ⍳ ⍵ } ⍞
⍴ houses ⍝ the amount of houses to visit
)OFF
``` |
86100620-f9b0-4c90-9f27-2c017b3b2d38 | {
"language": "APL"
} | ```apl
:class abbrsample: MiPage
⍝ Control:: HTML.abbr
⍝ Description:: this is an example of use of abbr which allows you to display text when hovering over an area
⍝
⍝ This is an example of using the HTML 'abbr' element.
∇ Compose
:Access public
⍝ We simply display the text 'Hover over THIS to reveal.'
⍝ First we add the text 'Hover over', then
Add'Hover over '
⍝ Then we add the element 'abbr' containing the text 'THIS',
⍝ making sure the text to display when hovering over it
⍝ (the title) displays 'True Http Internet Scripts'
'title' 'True Http Internet Scripts'Add _.abbr'THIS'
⍝ then we add the final text.
Add' to reveal.'
∇
:endclass
```
Remove empty comment that messes up the index page | ```apl
:class abbrsample: MiPage
⍝ Control:: HTML.abbr
⍝ Description:: this is an example of use of abbr which allows you to display text when hovering over an area
⍝ This is an example of using the HTML 'abbr' element.
∇ Compose
:Access public
⍝ We simply display the text 'Hover over THIS to reveal.'
⍝ First we add the text 'Hover over', then
Add'Hover over '
⍝ Then we add the element 'abbr' containing the text 'THIS',
⍝ making sure the text to display when hovering over it
⍝ (the title) displays 'True Http Internet Scripts'
'title' 'True Http Internet Scripts'Add _.abbr'THIS'
⍝ then we add the final text.
Add' to reveal.'
∇
:endclass
``` |
90b419ec-4bec-46b4-8ca6-55c98167df1f | {
"language": "APL"
} | ```apl
```
Add boilerplate APL script to serve CGI webpages | ```apl
#!/usr/local/bin/apl --script
NEWLINE ← ⎕UCS 10
HEADERS ← 'Content-Type: text/plain', NEWLINE
HEADERS
⍝ ⎕←HEADERS
⍝ ⍕⎕TS
)OFF
⍝ testVars←'FUCKYEAH'
⍝ ≠\~(testVars ∊ 'AEIOU')
⍝ (124 × 4)≠(+/124 124 124)
⍝ testVars ∊ '<>'
``` |
ecea2d5d-e815-4621-938e-72ff99c1ce42 | {
"language": "AppleScript"
} | ```applescript
on run argv
tell application "iTunes"
set p to first item of argv
set a to (p as POSIX file)
add a to playlist (second item of argv)
end tell
end run
```
Add explanation of arguments in AppleScript scripts | ```applescript
on run argv
set posixFile to first item of argv
set playlistName to second item of argv
tell application "iTunes"
set p to posixFile
set a to (p as POSIX file)
add a to playlist playlistName
end tell
end run
``` |
bab87279-6eaf-4be8-94f0-8021c71022a9 | {
"language": "AppleScript"
} | ```applescript
-- execute_iterm.scpt
-- last change: 19 Jan 2013
---
-- this script require an argument that represent the command to execute
on run argv
set command to (item 1 of argv)
tell application "iTerm"
try
set mysession to current session of current terminal
on error
set myterm to (make new terminal)
tell myterm
launch session "Default"
set mysession to current session
end tell
end try
-- execute the command
tell mysession
write text command
end tell
end tell
end run
```
Change session name to 'rspec' | ```applescript
-- execute_iterm.scpt
-- last change: 19 Jan 2013
---
-- this script require an argument that represent the command to execute
on run argv
set command to (item 1 of argv)
tell application "iTerm"
try
set mysession to current session of current terminal
on error
set myterm to (make new terminal)
tell myterm
launch session "rspec"
set mysession to current session
end tell
end try
-- execute the command
tell mysession
write text command
end tell
end tell
end run
``` |
49b05acc-ec19-4cde-b5f5-505955d212f4 | {
"language": "AppleScript"
} | ```applescript
tell application "Spotify"
set cstate to "{"
set cstate to cstate & "\"track_id\": \"" & current track's id & "\""
set cstate to cstate & ",\"volume\": " & sound volume
set cstate to cstate & ",\"position\": " & player position
set cstate to cstate & ",\"state\": \"" & player state & "\""
set cstate to cstate & "}"
return cstate
end tell```
Fix get state for locales that have commas as decimal delimiters | ```applescript
on replace_chars(this_text, search_string, replacement_string)
set AppleScript's text item delimiters to the search_string
set the item_list to every text item of this_text
set AppleScript's text item delimiters to the replacement_string
set this_text to the item_list as string
set AppleScript's text item delimiters to ""
return this_text
end replace_chars
tell application "Spotify"
-- force string coercion and locale format
set position to "" & player position
set cstate to "{"
set cstate to cstate & "\"track_id\": \"" & current track's id & "\""
set cstate to cstate & ",\"volume\": " & sound volume
-- replace , with . when locale has , as decimal delimiter
set cstate to cstate & ",\"position\": " & my replace_chars(position, ",", ".")
set cstate to cstate & ",\"state\": \"" & player state & "\""
set cstate to cstate & "}"
return cstate
end tell
``` |
40cdd29e-d0c8-4740-bc7d-c059f334f116 | {
"language": "AppleScript"
} | ```applescript
on run
tell application "BibDesk"
try
set alertResult to display alert ("Really remove all linked files and private notes from " & name of first document as string) & "?" buttons {"Cancel", "OK"} default button "OK" cancel button "Cancel" as warning
if button returned of alertResult is "OK" then
save first document in "Filtered " & (name of first document as string) & ".bib"
repeat with thePub in first document's publications
set thePub's note to my splitNote(thePub's note)
repeat with theFile in thePub's linked files
remove theFile from thePub
end repeat
end repeat
save first document
end if
on error -128
display dialog "User cancelled."
end try
end tell
end run
to splitNote(theNoteText)
try
set oldDelims to AppleScript's text item delimiters
set AppleScript's text item delimiters to {"---"}
set theParts to every text item of theNoteText
if length of theParts is greater than 1 then
set outText to text 2 through end of last item of theParts
else
set outText to ""
end if
set AppleScript's text item delimiters to oldDelims
on error
set AppleScript's text item delimiters to oldDelims
end try
return outText
end splitNote```
Simplify filterer code so it actually works. | ```applescript
on run
tell application "BibDesk"
try
set alertResult to display alert ("Really remove all linked files and private notes from " & name of first document as string) & "?" buttons {"Cancel", "OK"} default button "OK" cancel button "Cancel" as warning
if button returned of alertResult is "OK" then
set theDocument to first document
save theDocument
set theFile to (theDocument's file) as alias
tell application "Finder"
set theContainer to (container of theFile) as alias
set newFile to make new file with properties {container:theFile, name:"Filtered " & ((name of theDocument) as string)}
end tell
return
save first document in (newFile as file)
repeat with thePub in first document's publications
set thePub's note to my splitNote(thePub's note)
repeat with theFile in thePub's linked files
remove theFile from thePub
end repeat
end repeat
save first document
end if
on error -128
display dialog "User cancelled."
end try
end tell
end run
to splitNote(theNoteText)
try
set oldDelims to AppleScript's text item delimiters
set AppleScript's text item delimiters to {"---"}
set theParts to every text item of theNoteText
if length of theParts is greater than 1 then
set outText to (text 2 through end) of last item of theParts
else
set outText to ""
end if
set AppleScript's text item delimiters to oldDelims
on error
set AppleScript's text item delimiters to oldDelims
end try
return outText
end splitNote``` |
3b5881cb-63f4-463f-b02d-9115e5684306 | {
"language": "AppleScript"
} | ```applescript
-- execute_iterm.scpt
-- last change: 19 Jan 2013
---
-- this script require an argument that represent the command to execute
on run argv
set command to (item 1 of argv)
tell application "iTerm"
try
set mysession to current session of current terminal
on error
set myterm to (make new terminal)
tell myterm
launch session "rspec"
set mysession to current session
end tell
end try
-- execute the command
tell mysession
write text command
end tell
end tell
end run
```
Change script for rspec command only | ```applescript
-- execute_iterm.scpt
-- last change: 19 Jan 2013
---
-- this script require an argument that represent the command to execute
on run argv
set command to (item 1 of argv)
tell application "iTerm"
repeat with _terminal in terminals
repeat with _session in (every session of _terminal whose name contains "rspec")
tell the _session
write text command
end tell
end repeat
end repeat
end tell
end run
``` |
4b529869-6c5b-44e1-934c-aa5199089403 | {
"language": "AppleScript"
} | ```applescript
# AppleScript folder action for the pdfmatch command
#
# Open with script editor, compile and save to
# ~/Library/Workflows/Applications/Folder\ Actions/
#
# Then open the "Folder Actions Setup" application and add the work folder
# where your pdfmatch.json config lives and attach this script.
#
on adding folder items to this_folder after receiving these_files
try
repeat with each_file in these_files
tell application "System Events"
if name extension of each_file is "pdf" or "tif" or "tiff" or "jpeg" or "jpg" then
# You might need to add your node binary to your $PATH. For example:
# export PATH=/usr/local/bin:/usr/local/opt/node@6/bin:$PATH
set output to (do shell script "export PATH=/usr/local/bin:/usr/local/opt/node@6/bin:$PATH && cd '" & POSIX path of this_folder & "' && pdfmatch '" & POSIX path of each_file & "' --delete 2>&1")
#display alert output
end if
end tell
end repeat
on error err_string number error_number
display alert "Error " & error_number & ": " & err_string
end try
end adding folder items to
```
Remove my $PATH setting from default apple script | ```applescript
# AppleScript folder action for the pdfmatch command
#
# Open with script editor, compile and save to
# ~/Library/Workflows/Applications/Folder\ Actions/
#
# Then open the "Folder Actions Setup" application and add the work folder
# where your pdfmatch.json config lives and attach this script.
#
on adding folder items to this_folder after receiving these_files
try
repeat with each_file in these_files
tell application "System Events"
if name extension of each_file is "pdf" or "tif" or "tiff" or "jpeg" or "jpg" then
# You might need to add your node binary to your $PATH. For example:
# export PATH=/usr/local/bin:/usr/local/opt/node@6/bin:$PATH
set output to (do shell script "cd '" & POSIX path of this_folder & "' && pdfmatch '" & POSIX path of each_file & "' --delete 2>&1")
#display alert output
end if
end tell
end repeat
on error err_string number error_number
display alert "Error " & error_number & ": " & err_string
end try
end adding folder items to
``` |
58224a6c-870a-467e-9d4f-cc9726aeb579 | {
"language": "AppleScript"
} | ```applescript
-- clears workflow cache, including album artwork and compiled scripts --
on loadConfig()
return (load script POSIX file (do shell script "./resources/compile-config.sh"))
end loadConfig
on run query
set config to loadConfig()
try
tell application "Finder"
delete folder (workflowCacheFolder of config)
end tell
end try
end run
```
Delete Alfred Play Song playlist when clearing cache | ```applescript
-- clears workflow cache, including album artwork and compiled scripts --
on loadConfig()
return (load script POSIX file (do shell script "./resources/compile-config.sh"))
end loadConfig
on run query
set config to loadConfig()
try
tell application "Finder"
delete folder (workflowCacheFolder of config)
end tell
tell application "Music"
delete user playlist (workflowPlaylistName of config)
end tell
end try
end run
``` |
211ec763-8bc6-4aeb-9c8c-1219e9fabbb8 | {
"language": "AppleScript"
} | ```applescript
set theFolder to POSIX path of ((the path to me as text) & "::")
set Controller to run script ("script s" & return & (read alias (POSIX file (theFolder & "/lib/controller.scpt")) as «class utf8») & return & "end script " & return & "return s")
set currentTrack to Controller's getCurrentSong()
set output to item 1 of currentTrack & " - " & item 2 of currentTrack
do shell script "echo " & quoted form of output
```
Set current song to empty string if nothing is playing | ```applescript
set theFolder to POSIX path of ((the path to me as text) & "::")
set Controller to run script ("script s" & return & (read alias (POSIX file (theFolder & "/lib/controller.scpt")) as «class utf8») & return & "end script " & return & "return s")
set currentTrack to Controller's getCurrentSong()
try
set output to quoted form of (item 1 of currentTrack & " - " & item 2 of currentTrack)
on error
set output to ""
end try
do shell script "echo " & output
``` |
429928b0-cea4-48e9-81d8-6dd2aec5d0e4 | {
"language": "AppleScript"
} | ```applescript
activate application "SystemUIServer"
tell application "System Events"
tell process "SystemUIServer"
set btMenu to (menu bar item 1 of menu bar 1 whose description contains "bluetooth")
tell btMenu
click
try
tell (menu item "Rosco's Headphones" of menu 1)
click
if exists menu item "Connect" of menu 1 then
click menu item "Connect" of menu 1
return "Connecting..."
else if exists menu item "Disconnect" of menu 1 then
click menu item "Disconnect" of menu 1
return "Disconnecting..."
end if
end tell
end try
end tell
end tell
key code 53
return "Device not found or Bluetooth turned off"
end tell
```
Update headphone connect script for Big Sur | ```applescript
-- Source: https://www.reddit.com/r/MacOS/comments/i4czgu/big_sur_airpods_script/gck3gz3
-- Works on macOS 11 Big Sur
use framework "IOBluetooth"
use scripting additions
set DeviceName to "Rosco's Headphones"
on getFirstMatchingDevice(deviceName)
repeat with device in (current application's IOBluetoothDevice's pairedDevices() as list)
if (device's nameOrAddress as string) contains deviceName then return device
end repeat
end getFirstMatchingDevice
on toggleDevice(device)
if not (device's isConnected as boolean) then
device's openConnection()
return "Connecting " & (device's nameOrAddress as string)
else
device's closeConnection()
return "Disconnecting " & (device's nameOrAddress as string)
end if
end toggleDevice
return toggleDevice(getFirstMatchingDevice(DeviceName))
``` |
4e50861f-d892-4aff-8cb6-eb1a2e2a95ee | {
"language": "AppleScript"
} | ```applescript
-- plays selected song or playlist directly (the Play Song v1 behavior)
-- for songs, this behavior continues playing music after the song finishes
on loadConfig()
return (load script POSIX file (do shell script "./resources/compile-config.sh"))
end loadConfig
on run query
set config to loadConfig()
set typeAndId to parseResultQuery(query as text) of config
set theType to type of typeAndId
set theId to id of typeAndId
tell application "iTunes"
if theType is "song" then
set theSong to getSong(theId) of config
play theSong
else if theType is "playlist" then
set thePlaylist to getPlaylist(theId) of config
play thePlaylist
else
log "Unknown type: " & theType
end if
end tell
end run
```
Fix bug where Apple Music playlists could not be played | ```applescript
-- plays selected song or playlist directly (the Play Song v1 behavior)
-- for songs, this behavior continues playing music after the song finishes
on loadConfig()
return (load script POSIX file (do shell script "./resources/compile-config.sh"))
end loadConfig
on run query
set config to loadConfig()
set typeAndId to parseResultQuery(query as text) of config
set theType to type of typeAndId
set theId to id of typeAndId
tell application "iTunes"
if theType is "song" then
set theSong to getSong(theId) of config
play theSong
else if theType ends with "playlist" then
set thePlaylist to getPlaylist(theId) of config
play thePlaylist
else
log "Unknown type: " & theType
end if
end tell
end run
``` |
82bde5f0-ed75-4a75-8f40-bb04166f8585 | {
"language": "AppleScript"
} | ```applescript
-- This Applescript changes all of the icon labels on the disk image to
-- a different color.
-- Usage: osascript set-labels.applescript <volume-name>
-- where <volume-name> is the volume name of the disk image.
on run argv
tell application "Finder"
set diskname to item 1 of argv
set file_list to every file in disk diskname
repeat with i in file_list
if the name of i is "Applications" then
set the position of i to {368, 135}
else if the name of i ends with ".app" then
set the position of i to {134, 135}
end if
-- The magic happens here: This will set the label color of
-- the file icon. Change the 7 to change the color: 0 is no
-- label, then red, orange, yellow, green, blue, purple, or gray.
set the label index of i to 7
end repeat
end tell
end run```
Make Mac disk image packager set application icon location more reliably. | ```applescript
-- This Applescript changes all of the icon labels on the disk image to
-- a different color.
-- Usage: osascript set-labels.applescript <volume-name>
-- where <volume-name> is the volume name of the disk image.
on run argv
tell application "Finder"
set diskname to item 1 of argv
tell disk diskname
set file_list to every file
repeat with i in file_list
if the name of i is "Applications" then
set the position of i to {368, 135}
else if the name of i ends with ".app" then
set the position of i to {134, 135}
end if
-- The magic happens here: This will set the label color of
-- the file icon. Change the 7 to change the color: 0 is no
-- label, then red, orange, yellow, green, blue, purple, or gray.
set the label index of i to 7
end repeat
update without registering applications
delay 4
end tell
end tell
end run
``` |
adcd9980-badf-4ea4-9b84-c9a10e9c731b | {
"language": "AppleScript"
} | ```applescript
on run {input}
try
do shell script "$HOME/Dropbox\\ \\(Personal\\)/projects/plover-tools/plover-dictionary-lookup/dictlook -x " & "\"" & input & "\""
display dialog result buttons {"OK"} default button 1
on error
display dialog "No such luck." buttons {"OK"} default button 1
beep
end try
end run
```
Add practice text area to lookup dialog | ```applescript
on run {input}
try
do shell script "$HOME/Dropbox\\ \\(Personal\\)/projects/plover-tools/plover-dictionary-lookup/dictlook -x " & "\"" & input & "\""
display dialog result default answer "" buttons {"OK"} default button 1
on error
display dialog "No such luck." buttons {"OK"} default button 1
beep
end try
end run
``` |
b6ac4568-ae91-4784-8e04-92d6b6e71e78 | {
"language": "AppleScript"
} | ```applescript
set close_vagrant to "z puppet; git pull; vagrant halt -f;"
-- close vagrant
tell application "iTerm"
activate
set myterm to (make new terminal)
tell myterm
launch session "Default"
set mysession to current session
end tell
tell mysession
write text close_vagrant
end tell
delay 5
end tell
-- quit iTerm
ignoring application responses
tell application "iTerm"
quit
end tell
end ignoring
delay 2
tell application "System Events" to keystroke return
```
Remove git pull from closing Vagrant | ```applescript
set close_vagrant to "z puppet; vagrant halt -f;"
-- close vagrant
tell application "iTerm"
activate
set myterm to (make new terminal)
tell myterm
launch session "Default"
set mysession to current session
end tell
tell mysession
write text close_vagrant
end tell
delay 5
end tell
-- quit iTerm
ignoring application responses
tell application "iTerm"
quit
end tell
end ignoring
delay 2
tell application "System Events" to keystroke return
``` |
1160ceac-cfa3-4659-8edd-fe8fff113410 | {
"language": "AppleScript"
} | ```applescript
set myTabs to {"http://app.getsentry.com/", "http://app.ubervu.com/", "http://github.com/uberVU/thehole/issues/assigned/palcu?direction=desc&labels=&milestone=&page=1&sort=updated&state=open/", "https://mail.google.com/mail/u/1/?shva=1#inbox", "https://drive.google.com/a/ubervu.com/#folders/0BzycGIkC5P50TXBlcTZoRXZ5VUE"}
tell application "Google Chrome"
activate
repeat with i in myTabs
open location i
end repeat
end tell
```
Change tabs to open at work | ```applescript
set myTabs to {"http://app.getsentry.com/", "http://github.com/uberVU/thehole/issues/assigned/palcu?direction=desc&labels=&milestone=&page=1&sort=updated&state=open/", "https://mail.google.com/mail/u/1/?shva=1#inbox", "https://drive.google.com/a/hootsuite.com/#folders/0BwuFsHJDxJWPYmxXQ1VQVlN6T2M"}
tell application "Google Chrome"
activate
repeat with i in myTabs
open location i
end repeat
end tell
``` |
d2f54b99-601c-4588-993b-e1a3fb43dc5d | {
"language": "AppleScript"
} | ```applescript
set broker to "h8.opera.com"
set workers to {"h6.opera.com", "h8.opera.com", "h9.opera.com", "h10.opera.com"}
tell application "iTerm"
activate
set myterm to (make new terminal)
tell myterm
set number of columns to 80
set number of rows to 50
repeat with workerhost in workers
set worker to (make new session at the end of sessions)
tell worker
set name to workerhost
set foreground color to "white"
set background color to "black"
set transparency to 0.1
exec command "/bin/sh -i"
write text "ssh root@" & workerhost & " 'tail -f /var/log/celeryd.log'"
end tell
end repeat
set rabbit to (make new session at the end of sessions)
tell rabbit
set name to "rabbit.log"
set foreground color to "white"
set background color to "black"
set transparency to 0.1
exec command "/bin/sh -i"
write text "ssh root@" & broker & " 'tail -f /var/log/rabbitmq/rabbit.log'"
end tell
tell the first session
activate
end tell
end tell
end tell
```
Update the watch workers applescript to watch the celerybeat log file. | ```applescript
set broker to "h8.opera.com"
set workers to {"h6.opera.com", "h8.opera.com", "h9.opera.com", "h10.opera.com"}
set clock to "h6.opera.com"
tell application "iTerm"
activate
set myterm to (make new terminal)
tell myterm
set number of columns to 80
set number of rows to 50
repeat with workerhost in workers
set worker to (make new session at the end of sessions)
tell worker
set name to workerhost
set foreground color to "white"
set background color to "black"
set transparency to 0.1
exec command "/bin/sh -i"
write text "ssh root@" & workerhost & " 'tail -f /var/log/celeryd.log'"
end tell
end repeat
set celerybeat to (make new session at the end of sessions)
tell celerybeat
set name to "celerybeat.log"
set foreground color to "white"
set background color to "black"
set transparency to 0.1
exec command "/bin/sh -i"
write text "ssh root@" & clock & " 'tail -f /var/log/celerybeat.log'"
end tell
set rabbit to (make new session at the end of sessions)
tell rabbit
set name to "rabbit.log"
set foreground color to "white"
set background color to "black"
set transparency to 0.1
exec command "/bin/sh -i"
write text "ssh root@" & broker & " 'tail -f /var/log/rabbitmq/rabbit.log'"
end tell
tell the first session
activate
end tell
end tell
end tell
``` |
bd7a265a-5ae0-4da2-ac42-5a8f1f635890 | {
"language": "AppleScript"
} | ```applescript
(*
Script object to make calling a defined function easier while in the
iTunes and System Events name space.
*)
script remoteSpeakerFinder
-- Given a list of buttons, find the remote speakers button
-- by finding the first button with a name that isn't in a
-- rejection list.
on findCorrectButton (in_buttons)
set buttons_to_skip to {"Burn Disc"}
repeat with a_button in in_buttons
try -- some buttons don't have names
set the_name to name of a_button
if buttons_to_skip does not contain {the_name} then
return the_name
end if
end try
end repeat
return 16 -- default response
end findCorrectButton
end script
(*
Tell iTunes to use the "Mobile" set of remote speakers.
*)
tell application "System Events"
tell process "iTunes"
set the_buttons to (get buttons of window 1)
set the_speaker_button to (remoteSpeakerFinder's findCorrectButton(the_buttons))
-- Switch to the speakers in my bedroom
set frontmost to true
click button the_speaker_button of window 1
key code 115 -- Home Key (first speaker in list)
key code 125 -- Down Arrow
key code 125 -- Down Arrow
key code 36 -- Return Key
end tell
end tell
```
Work around an issue with iTunes 9 that causes it to delay a connection to remote speakers | ```applescript
(*
Script object to make calling a defined function easier while in the
iTunes and System Events name space.
*)
script remoteSpeakerFinder
-- Given a list of buttons, find the remote speakers button
-- by finding the first button with a name that isn't in a
-- rejection list.
on findCorrectButton (in_buttons)
set buttons_to_skip to {"Burn Disc"}
repeat with a_button in in_buttons
try -- some buttons don't have names
set the_name to name of a_button
if buttons_to_skip does not contain {the_name} then
return the_name
end if
end try
end repeat
return 16 -- default response
end findCorrectButton
end script
(*
Tell iTunes to use the "Mobile" set of remote speakers.
*)
tell application "System Events"
tell process "iTunes"
set the_buttons to (get buttons of window 1)
set the_speaker_button to (remoteSpeakerFinder's findCorrectButton(the_buttons))
-- Switch to the speakers in my bedroom
set frontmost to true
click button the_speaker_button of window 1
key code 115 -- Home Key (first speaker in list)
key code 125 -- Down Arrow
key code 125 -- Down Arrow
key code 36 -- Return Key
-- Wait for iTunes to connect to the speakers
delay 5
end tell
end tell
``` |
2b395141-0660-4957-ab8b-0dfc508ab5ac | {
"language": "AppleScript"
} | ```applescript
set myTabs to {"http://app.getsentry.com/", "http://github.com/uberVU/thehole/issues/assigned/palcu?direction=desc&labels=&milestone=&page=1&sort=updated&state=open/", "https://mail.google.com/mail/u/1/?shva=1#inbox", "https://drive.google.com/a/hootsuite.com/#folders/0BwuFsHJDxJWPYmxXQ1VQVlN6T2M"}
tell application "Google Chrome"
activate
repeat with i in myTabs
open location i
end repeat
end tell
```
Update URLs that open at the office | ```applescript
set myTabs to {"https://github.com/search?utf8=%E2%9C%93&q=assignee%3Apalcu+state%3Aopen&type=Issues&ref=searchresults", "https://mail.google.com/mail/u/1/?shva=1#inbox", "https://drive.google.com/a/hootsuite.com/#folders/0BwuFsHJDxJWPYmxXQ1VQVlN6T2M"}
tell application "Google Chrome"
activate
repeat with i in myTabs
open location i
end repeat
end tell
``` |
cd413a4e-a07e-46ce-ae54-6c08225253c6 | {
"language": "AppleScript"
} | ```applescript
try
get application id "com.stairways.keyboardmaestro.engine"
on error err_msg number err_num
return "Keyboard Maestro not found. First install it and then use this workflow."
end try
tell application id "com.stairways.keyboardmaestro.engine"
gethotkeys with asstring
end tell
```
Update script to get ALL macros instead of just hotkeyed macros. | ```applescript
try
get application id "com.stairways.keyboardmaestro.engine"
on error err_msg number err_num
return "Keyboard Maestro not found. First install it and then use this workflow."
end try
tell application id "com.stairways.keyboardmaestro.engine"
gethotkeys with asstring and getall
end tell
``` |
b2e118ab-1119-47bb-83a6-66e5dfa51e27 | {
"language": "AppleScript"
} | ```applescript
set open_vagrant to "z puppet; vagrant up;"
tell application "iTerm"
activate
try
set mysession to current session of current terminal
on error
set myterm to (make new terminal)
tell myterm
launch session "Default"
set mysession to current session
end tell
end try
tell mysession
write text open_vagrant
end tell
end tell```
Add update script to open vagrant applescript | ```applescript
set open_vagrant to "z puppet; vagrant up;"
set update_master to "/Users/alex/.homesick/repos/palcu/dotfiles/scripts/update_master.sh;"
tell application "iTerm"
activate
try
set mysession to current session of current terminal
on error
set myterm to (make new terminal)
tell myterm
launch session "Default"
set mysession to current session
end tell
end try
tell mysession
write text update_master
write text open_vagrant
end tell
end tell
``` |
411e7e86-d37a-47eb-9931-ea55f6f9719c | {
"language": "Arc"
} | ```arc
(seval '(require file/glob))
(def glob (pat)
(each path (seval!glob pat #:capture-dotfiles? #t)
(let path (seval!path->string path)
(if (dir-exists path)
(out (+ path "/"))
(out path)))))
```
Update GLOB to remove the cwd from each result | ```arc
(seval '(require file/glob))
(seval '(xdef cwd cwd))
(def glob (pat (o root (cwd)))
(each path (seval!glob pat #:capture-dotfiles? #t)
(aand (seval!path->string path)
(if (dir-exists it) (+ it "/") it)
(if (seval!string-prefix? it root)
(cut it (len root))
it)
(out it))))
``` |
4a12c68f-cb98-457e-bdaa-a1929b8ed925 | {
"language": "Arc"
} | ```arc
(system "rm -rf html")
(ensure-dir "html")
(load "template.arc")
(runall)
;; fails with "Expected tests" error
;; (run "foundation-doc.tem")
(system "cp foundation-doc.html html/")
(system "rm -rf output")
(ensure-dir "output")
(system "cp docs/* html/* output/")
```
Disable atstrings when generating arcfn docs. | ```arc
(declare 'atstrings nil)
(system "rm -rf html")
(ensure-dir "html")
(load "template.arc")
(runall)
;; fails with "Expected tests" error
;; (run "foundation-doc.tem")
(system "cp foundation-doc.html html/")
(system "rm -rf output")
(ensure-dir "output")
(system "cp docs/* html/* output/")
``` |
df66c44c-cf75-43b7-bf2b-2fa9a4fd6661 | {
"language": "Arduino"
} | ```arduino
const int BUFFER_SIZE = 4;
int m_buffer[BUFFER_SIZE];
int m_bufIndex = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
int val = readValue();
//Serial.print("Voltage");
//Serial.print("\t");
Serial.println(val);
delay(5);
//we're interested in events that happen roughly within 15-20 ms
}
int readValue() {
m_buffer[m_bufIndex] = analogRead(A0);
m_bufIndex = (m_bufIndex + 1) % BUFFER_SIZE;
//test if median is better than avg
int sum = 0;
for (int n = 0; n < BUFFER_SIZE; ++n) {
sum += m_buffer[n];
}
return sum / BUFFER_SIZE;
}
```
Use interrupt for timing the sample read | ```arduino
const int BUFFER_SIZE = 8;
int m_buffer[BUFFER_SIZE];
int m_bufIndex = 0;
unsigned long m_timer = 0;
int m_counter = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
m_timer = millis();
// Timer0 is already used for millis() - we'll just interrupt somewhere
// in the middle and call the "Compare A" function below
OCR0A = 0xAF;
TIMSK0 |= _BV(OCIE0A);
}
// Interrupt is called once a millisecond (Timer0 frequency)
SIGNAL(TIMER0_COMPA_vect)
{
int val = readValue();
//we're interested in events that happen roughly within 15-20 ms
if (m_counter++ >= 4) {
Serial.println(val);
m_counter = 0;
}
}
void loop() {
}
int readSample() {
int value = m_buffer[m_bufIndex] = analogRead(A0);
m_bufIndex = (m_bufIndex + 1) % BUFFER_SIZE;
return value;
}
int readValue() {
int value = readSample();
//TODO: test if median is better than avg
int sum = 0;
for (int n = 0; n < BUFFER_SIZE; ++n) {
sum += m_buffer[n];
}
return sum / BUFFER_SIZE;
}
``` |
759bac8a-5c1a-48aa-bc67-b0efdf39709d | {
"language": "Arduino"
} | ```arduino
// Interduino is the physical manifestation of cigtee - an arduino sketch designed to take serial commands to make stuff happen IRL
void setup()
{
Serial.begin(9600);
pinMode(13, OUTPUT);
}
int pinState[6];
void loop()
{
if(Serial.available()){
int ledState = Serial.read();
if(ledState == 65){
digitalWrite(13, HIGH);
}
if(ledState == 90){
digitalWrite(13, LOW);
}
delay(2000);
}
}
```
Change logic for serial commands | ```arduino
// Interduino is the physical manifestation of cigtee - an arduino sketch designed to take serial commands to make stuff happen IRL
void setup()
{
Serial.begin(9600);
pinMode(13, OUTPUT);
}
int pinState[6];
void loop()
{
if(Serial.available()){
int ledState = Serial.read();
if(ledState == 65){
digitalWrite(13, HIGH);
}
// if(ledState == 90){
// digitalWrite(13, LOW);
// }
delay(2000);
digitalWrite(13, LOW);
}
}
``` |
77292e92-df8f-4252-8289-8e5604b20315 | {
"language": "Arduino"
} | ```arduino
#include <WaveHC.h>
#include <WaveUtil.h>
SdReader card; // This object holds the information for the card
FatVolume vol; // This holds the information for the partition on the card
FatReader root; // This holds the information for the volumes root directory
WaveHC wave; // This is the only wave (audio) object, since we will only play one at a time
void setupSdReader(SdReader &card) {
if (!card.init()) Serial.println("Card init failed");
card.partialBlockRead(true); // Optimization. Disable if having issues
}
void setupFatVolume(FatVolume &vol) {
uint8_t slot;
// There are 5 slots to look at.
for (slot = 0; slot < 5; slot++)
if (vol.init(card, slot)) break;
if (slot == 5) Serial.println("No valid FAT partition");
}
void setupFatReader(FatReader &root) {
if (!root.openRoot(vol)) Serial.println("Can't open root dir");
}
void setup() {
Serial.begin(9600);
setupSdReader(card);
setupFatVolume(vol);
setupFatReader(root);
}
void loop() {
}
```
Test out some wave files | ```arduino
#include <WaveHC.h>
#include <WaveUtil.h>
String fileNames[4] = {"BUGS2.WAV", "DAFFY1.WAV", "BUGS1.WAV", "DAFFY2.WAV"};
SdReader card; // This object holds the information for the card
FatVolume vol; // This holds the information for the partition on the card
FatReader root; // This holds the information for the volumes root directory
WaveHC wave; // This is the only wave (audio) object, since we will only play one at a time
void setupSdReader(SdReader &card) {
if (!card.init()) Serial.println("Card init failed");
card.partialBlockRead(true); // Optimization. Disable if having issues
}
void setupFatVolume(FatVolume &vol) {
uint8_t slot;
// There are 5 slots to look at.
for (slot = 0; slot < 5; slot++)
if (vol.init(card, slot)) break;
if (slot == 5) Serial.println("No valid FAT partition");
}
void setupFatReader(FatReader &root) {
if (!root.openRoot(vol)) Serial.println("Can't open root dir");
}
void setup() {
Serial.begin(9600);
setupSdReader(card);
setupFatVolume(vol);
setupFatReader(root);
}
void loop() {
root.rewind();
FatReader file;
for (int i = 0; i < 4; i++) {
char fileName[fileNames[i].length() + 1];
fileNames[i].toCharArray(fileName, fileNames[i].length() + 1);
file.open(root, fileName);
wave.create(file);
wave.play();
while (wave.isplaying) delay(100);
}
}
``` |
331989a2-4e55-45fd-a33b-3cc5e9d33d28 | {
"language": "Arduino"
} | ```arduino
#include "ConfigManager.h"
struct Config {
char name[20];
bool enabled;
int8 hour;
char password[20];
} config;
struct Metadata {
int8 version;
} meta;
ConfigManager configManager;
void createCustomRoute(ESP8266WebServer *server) {
server->on("/custom", HTTPMethod::HTTP_GET, [server](){
server->send(200, "text/plain", "Hello, World!");
});
}
void setup() {
meta.version = 3;
// Setup config manager
configManager.setAPName("Demo");
configManager.setAPFilename("/index.html");
configManager.addParameter("name", config.name, 20);
configManager.addParameter("enabled", &config.enabled);
configManager.addParameter("hour", &config.hour);
configManager.addParameter("password", config.password, 20, set);
configManager.addParameter("version", &meta.version, get);
configManager.begin(config);
configManager.setAPICallback(createCustomRoute);
//
}
void loop() {
configManager.loop();
// Add your loop code here
}
```
Move begin down in example | ```arduino
#include "ConfigManager.h"
struct Config {
char name[20];
bool enabled;
int8 hour;
char password[20];
} config;
struct Metadata {
int8 version;
} meta;
ConfigManager configManager;
void createCustomRoute(ESP8266WebServer *server) {
server->on("/custom", HTTPMethod::HTTP_GET, [server](){
server->send(200, "text/plain", "Hello, World!");
});
}
void setup() {
meta.version = 3;
// Setup config manager
configManager.setAPName("Demo");
configManager.setAPFilename("/index.html");
configManager.addParameter("name", config.name, 20);
configManager.addParameter("enabled", &config.enabled);
configManager.addParameter("hour", &config.hour);
configManager.addParameter("password", config.password, 20, set);
configManager.addParameter("version", &meta.version, get);
configManager.setAPICallback(createCustomRoute);
configManager.begin(config);
//
}
void loop() {
configManager.loop();
// Add your loop code here
}
``` |
72803cb1-5611-429e-9830-c8e0e01e4c88 | {
"language": "Arduino"
} | ```arduino
// Interduino is the physical manifestation of cigtee - an arduino sketch designed to take serial commands to make stuff happen IRL
void setup()
{
Serial.begin(9600);
pinMode(13, OUTPUT);
}
int pinState[6];
void loop()
{
if(Serial.available()){
int ledState = Serial.read();
if(ledState == 65){
digitalWrite(13, HIGH);
}
if(ledState == 90){
digitalWrite(13, LOW);
}
}
}
```
Add main func to stop build from breaking on akira | ```arduino
// Interduino is the physical manifestation of cigtee - an arduino sketch designed to take serial commands to make stuff happen IRL
void setup()
{
Serial.begin(9600);
pinMode(13, OUTPUT);
}
int pinState[6];
void loop()
{
if(Serial.available()){
int ledState = Serial.read();
if(ledState == 65){
digitalWrite(13, HIGH);
}
if(ledState == 90){
digitalWrite(13, LOW);
}
}
}
int main()
{
setup();
while(true) {
loop();
}
return 0;
}
``` |
d3b6af65-5d00-4ab2-8f8e-a16761dbf493 | {
"language": "Arduino"
} | ```arduino
const int outPinLed = 2;
const int inPinTrigger = 7;
const int inPinDetector = 4;
int triggerPressed = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(outPinLed, OUTPUT);
digitalWrite(outPinLed, LOW);
pinMode(inPinTrigger, INPUT);
pinMode(inPinDetector, INPUT);
}
void loop() {
int triggerPrev = triggerPressed;
triggerPressed = digitalRead(inPinTrigger);
if (triggerPressed != triggerPrev) {
Serial.print("Trigger state changed: ");
Serial.println(triggerPressed);
if (triggerPressed) {
int detectorValue = digitalRead(inPinDetector);
Serial.print("Detector: ");
Serial.println(detectorValue);
}
}
int ledState = triggerPressed ? HIGH : LOW;
digitalWrite(outPinLed, ledState);
}
```
Read detector value to A0 | ```arduino
const int outPinLed = 2;
const int inPinTrigger = 7;
const int inPinDetector = A0;
int triggerPressed = 0;
int detectorValue = 1023;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(outPinLed, OUTPUT);
digitalWrite(outPinLed, LOW);
pinMode(inPinTrigger, INPUT_PULLUP);
}
void loop() {
int triggerPrev = triggerPressed;
triggerPressed = digitalRead(inPinTrigger);
if (triggerPressed != triggerPrev) {
Serial.print("Trigger state changed: ");
Serial.println(triggerPressed);
/*if (triggerPressed) {
int detectorValue = analogRead(inPinDetector);
Serial.print("Detector: ");
Serial.println(detectorValue);
}*/
}
if (triggerPressed) {
int detectorPrev = detectorValue;
detectorValue = analogRead(inPinDetector);
Serial.print(" Detector: ");
Serial.print(detectorValue);
Serial.print(" diff=");
Serial.println(detectorValue - detectorPrev);
}
int ledState = triggerPressed ? HIGH : LOW;
digitalWrite(outPinLed, ledState);
}
``` |
7d5e6b08-3091-45cc-b7b0-f735368de4cd | {
"language": "Arduino"
} | ```arduino
```
Add first LDR sensor to sketch | ```arduino
/*
Arduino based self regulating kitchen garden
*/
// light related setup
int lightSensorPin = 3; // Set to whereever light sensor is connected
int lampRelay = 4; // Set to whereever relay for lamp is connected
// activity led setup
int ledPin = 13; // this is just for checking activity
// Initialize settings
void setup() {
// Initialize output pins.
pinMode(ledPin, OUTPUT);
// Initialize input pins.
pinMode(lightSensorPin, INPUT);
}
// Main loop
void loop() {
// Read sensor values
analogRead(lightSensorPin);
}
``` |