hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
6f1c77d6d5b552654970ef97e022e0dee974bef9
966
sh
Shell
user.sh
omkantmant54/omkantmani
23b7aa91c278868384eabaee62046633be9b2d01
[ "Apache-2.0" ]
null
null
null
user.sh
omkantmant54/omkantmani
23b7aa91c278868384eabaee62046633be9b2d01
[ "Apache-2.0" ]
null
null
null
user.sh
omkantmant54/omkantmani
23b7aa91c278868384eabaee62046633be9b2d01
[ "Apache-2.0" ]
null
null
null
#!/data/data/com.termux/files/usr/bin/bash clear echo " " echo " " echo -e "\e[33mEnter Your Terminal Name(e.g. @thedumpedone) \e[32m \n\n" read varterm echo " " echo "cowsay -f kiss ' $varterm' |lolcat" > t-ban.txt echo -e "\e[33mEnter Your Banner Name(e.g. DUMPED ONE) \e[32m \n\n" read varbanner echo " " echo "toilet -f slant ' $varbanner' -F gay |lolcat" > t-ban.txt echo -e "\e[33mEnter Your Dollar Name(e.g. dumped) \e[32m \n\n" read vardollar echo " " echo "PS1='\[\e[1;34m \a┌──\a─T─I─M─E─\a──┐\033[1;34m\a┌──\a─D─A─T─E─\a───>\033[1;34m \a┌─[\033[1;93m \@\033[1;34m ]──[\033[1;93m \d\033[1;34m ]\033[1;34m \a├─[\033[1;32m\w\033[1;34m]\033[1;34m \[\e[34m\]└─>$vardollar[~]:#\[\e[1;92m\] ' " > ash.txt cat "t-ban.txt" >> /data/data/com.termux/files/usr/etc/bash.bashrc cat "user.txt" >> /data/data/com.termux/files/usr/etc/bash.bashrc cat "ash.txt" >> /data/data/com.termux/files/usr/etc/bash.bashrc sleep 3
26.833333
73
0.601449
72950d63eefd8135336436688cf8f7326a01a701
7,232
cs
C#
DTQA/Form1.cs
ISDHN/DTQA
d6a2525dd4ec48b1216f0cd027b459fa298574ec
[ "MIT" ]
null
null
null
DTQA/Form1.cs
ISDHN/DTQA
d6a2525dd4ec48b1216f0cd027b459fa298574ec
[ "MIT" ]
null
null
null
DTQA/Form1.cs
ISDHN/DTQA
d6a2525dd4ec48b1216f0cd027b459fa298574ec
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; namespace DTQA { public partial class Form1 : Form { private int questionNumber; private readonly List<Question> questionLibrary= new List<Question>(); private readonly int[] questions = new int[10]; private readonly int[] answers = new int[10]; private string school=""; private string grade=""; private int classnum=1; private string username=""; public Form1() { InitializeComponent(); string xmlquestion = Properties.Resources.questions; XmlDocument xml = new XmlDocument(); xml.LoadXml(xmlquestion); XmlNode root = xml.SelectSingleNode("Library"); foreach(var cn in root.ChildNodes) { XmlElement ce = (XmlElement)cn; string txt = ce.GetAttribute("text"); string exp = ce.GetAttribute("explanation"); int ans = int.Parse(ce.GetAttribute("answer")); string a = ce.GetAttribute("A"); string b = ce.GetAttribute("B"); string c = ce.GetAttribute("C"); string d = ce.GetAttribute("D"); questionLibrary.Add(new Question(txt,ans,a,b,c,d,exp)); } WelcomePanel.Location = new Point(46, 46); QAPanel.Location = new Point(46, 46); FinalPanel.Location = new Point(46, 46); InfPanel.Location = new Point(46, 46); } private void Start_Click(object sender, EventArgs e) { WelcomePanel.Hide(); FinalPanel.Hide(); InfPanel.Show(); QAPanel.Hide(); } private void Exit_Click(object sender, EventArgs e) { this.Close(); Application.Exit(); } private void ChangeQuestion(int number) { Previous.Enabled = !(number == 1); Next.Enabled = !(number == 10); if (number > 10 | number < 1) return; ((ToolStripButton)QuestionList.Items[questionNumber]).Checked = false; this.questionNumber = number-1; Question current = this.questionLibrary[questions[questionNumber]]; QuestionText.Text = current.question; AnswerA.Text = current.options[0]; AnswerB.Text = current.options[1]; AnswerC.Text = current.options[2]; AnswerD.Text = current.options[3]; ((ToolStripButton)QuestionList.Items[questionNumber]).Checked = true; switch (answers[questionNumber]) { case -1: AnswerA.Checked = false; AnswerB.Checked = false; AnswerC.Checked = false; AnswerD.Checked = false; break; case 0: AnswerA.Checked = true; break; case 1: AnswerB.Checked = true; break; case 2: AnswerC.Checked = true; break; case 3: AnswerD.Checked = true; break; } } private void Question2_Click(object sender, EventArgs e) { ChangeQuestion(2); } private void Question1_Click(object sender, EventArgs e) { ChangeQuestion(1); } private void Question3_Click(object sender, EventArgs e) { ChangeQuestion(3); } private void Question4_Click(object sender, EventArgs e) { ChangeQuestion(4); } private void Question5_Click(object sender, EventArgs e) { ChangeQuestion(5); } private void Question6_Click(object sender, EventArgs e) { ChangeQuestion(6); } private void Question7_Click(object sender, EventArgs e) { ChangeQuestion(7); } private void Question8_Click(object sender, EventArgs e) { ChangeQuestion(8); } private void Question9_Click(object sender, EventArgs e) { ChangeQuestion(9); } private void Question10_Click(object sender, EventArgs e) { ChangeQuestion(10); } private void Previous_Click(object sender, EventArgs e) { ChangeQuestion(questionNumber);//questionnumber与传入的参数有1的差距 } private void Next_Click(object sender, EventArgs e) { ChangeQuestion(questionNumber + 2); } private void StartChanllenge() { Random r = new Random(); for (int i = 0; i < 10; i++) { answers[i] = -1; questions[i] = -1; } for (int i = 0; i < 10; i++) { int j; do { j = r.Next(questionLibrary.Count); } while (questions.Contains(j)); questions[i] = j; } WelcomePanel.Hide(); FinalPanel.Hide(); InfPanel.Hide(); QAPanel.Show(); ChangeQuestion(1); } private void JudgeChallenge() { int score=0; string s = ""; for(int i = 0; i < 10; i++) { if (answers[i] == questionLibrary[questions[i]].answer) score += 10; else { string wrong; if (answers[i] == -1) wrong = "你没选"; else wrong = "你选了\""+ questionLibrary[questions[i]].options[answers[i]]+"\""; s += $"错了第{i+1}题,题目为\"{questionLibrary[questions[i]].question}\",答案为\"{questionLibrary[questions[i]].options[questionLibrary[questions[i]].answer]}\",{wrong}.\r\n"; } } Summary.Text=s.Insert(0,$"{school}校区{grade}{classnum}班的{username}同学,你的得分是{score}分.\r\n"); WelcomePanel.Hide(); FinalPanel.Show(); QAPanel.Hide(); } private void Again_Click(object sender, EventArgs e) { StartChanllenge(); } private void AnswerA_Click(object sender, EventArgs e) { answers[questionNumber] = 0; } private void AnswerB_Click(object sender, EventArgs e) { answers[questionNumber] = 1; } private void AnswerC_Click(object sender, EventArgs e) { answers[questionNumber] = 2; } private void AnswerD_Click(object sender, EventArgs e) { answers[questionNumber] = 3; } private void Submit_Click(object sender, EventArgs e) { JudgeChallenge(); } private void School_SelectedIndexChanged(object sender, EventArgs e) { Grade.Items.Clear(); Grade.Text = ""; switch (school=School.SelectedItem.ToString()) { case "枋湖": Grade.Items.Add("高一"); Grade.Items.Add("高二"); Grade.Items.Add("高三"); Class.Maximum = 20; break; case "镇海": Grade.Items.Add("初一"); Grade.Items.Add("初二"); Grade.Items.Add("初三"); Class.Maximum = 20; break; case "翔安": Grade.Items.Add("高一"); Grade.Items.Add("初一"); Class.Maximum = 8; break; } } private void Grade_SelectedIndexChanged(object sender, EventArgs e) { grade = Grade.SelectedItem.ToString(); } private void Class_ValueChanged(object sender, EventArgs e) { classnum = (int)Class.Value; } private void UserName_TextChanged(object sender, EventArgs e) { username = UserName.Text; } private void SaveInformation_Click(object sender, EventArgs e) { if (grade == "" | school == "" | username == "") { MessageBox.Show("信息不完整,请完善后再继续哦!"); return; } else StartChanllenge(); } } public class Question { public string question; public int answer; public string explanation; public string[] options = new string[4]; public Question(string ques, int ans, string a,string b,string c,string d,string reason = "") { answer = ans; question = ques; options[0] = a; options[1] = b; options[2] = c; options[3] = d; explanation = reason; } } }
23.633987
169
0.633296
11ddb216339f0be3c8952948d30cfa6497ec25ed
2,176
go
Go
service/worker/scanner/executions/invariants/test_util.go
backwardn/cadence
6fcee79ea3a6be7e33dff3ab15cfe3f31eef4b89
[ "MIT" ]
1
2020-06-13T21:03:53.000Z
2020-06-13T21:03:53.000Z
service/worker/scanner/executions/invariants/test_util.go
backwardn/cadence
6fcee79ea3a6be7e33dff3ab15cfe3f31eef4b89
[ "MIT" ]
null
null
null
service/worker/scanner/executions/invariants/test_util.go
backwardn/cadence
6fcee79ea3a6be7e33dff3ab15cfe3f31eef4b89
[ "MIT" ]
null
null
null
// The MIT License (MIT) // // Copyright (c) 2017-2020 Uber Technologies Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package invariants import ( "github.com/uber/cadence/common/persistence" "github.com/uber/cadence/service/worker/scanner/executions/common" ) const ( domainID = "test-domain-id" workflowID = "test-workflow-id" runID = "test-run-id" shardID = 0 treeID = "test-tree-id" branchID = "test-branch-id" openState = persistence.WorkflowStateCreated closedState = persistence.WorkflowStateCompleted ) var ( branchToken = []byte{1, 2, 3} ) func getOpenExecution() common.Execution { return common.Execution{ ShardID: shardID, DomainID: domainID, WorkflowID: workflowID, RunID: runID, BranchToken: branchToken, TreeID: treeID, BranchID: branchID, State: openState, } } func getClosedExecution() common.Execution { return common.Execution{ ShardID: shardID, DomainID: domainID, WorkflowID: workflowID, RunID: runID, BranchToken: branchToken, TreeID: treeID, BranchID: branchID, State: closedState, } }
31.085714
81
0.721967
e231e928df62fe1d218c56b3a09788c7da0e4643
42
js
JavaScript
src/page/LendingPage/LendingPage.js
ShengminQuan/GleichWeb
0b1be649b22b9033754bc80bb71c7c9010c25820
[ "MIT" ]
null
null
null
src/page/LendingPage/LendingPage.js
ShengminQuan/GleichWeb
0b1be649b22b9033754bc80bb71c7c9010c25820
[ "MIT" ]
null
null
null
src/page/LendingPage/LendingPage.js
ShengminQuan/GleichWeb
0b1be649b22b9033754bc80bb71c7c9010c25820
[ "MIT" ]
null
null
null
export default { name: 'LendingPage', };
10.5
21
0.666667
9fbd1720b346ab2e070b69e39fe0124605b4a8b9
393
lua
Lua
lovr-api/data/TextureData/getBlob.lua
jmiskovic/aquadeck
d9f1efa31cd9ac445ee5aa39339a5671ee80ff8b
[ "Unlicense" ]
1
2022-02-20T19:11:59.000Z
2022-02-20T19:11:59.000Z
lovr-api/data/TextureData/getBlob.lua
jmiskovic/aquadeck
d9f1efa31cd9ac445ee5aa39339a5671ee80ff8b
[ "Unlicense" ]
8
2022-01-15T03:19:30.000Z
2022-01-15T04:20:30.000Z
lovr-api/data/TextureData/getBlob.lua
jmiskovic/aquadeck
d9f1efa31cd9ac445ee5aa39339a5671ee80ff8b
[ "Unlicense" ]
null
null
null
return { summary = 'Get the bytes backing this TextureData as a `Blob`.', description = 'Returns a Blob containing the raw bytes of the TextureData.', arguments = {}, returns = { { name = 'blob', type = 'Blob', description = 'The Blob instance containing the bytes for the `TextureData`.' } }, related = { 'Blob:getPointer', 'Sound:getBlob' } }
23.117647
83
0.608142
2fee5f742d887b7d519294f80a61d2209321bb48
4,100
py
Python
tests/test_circuit/test_new_style_syntax.py
leonardt/magma
d3e8c9500ec3b167df8ed067e0c0305781c94ab6
[ "MIT" ]
167
2017-10-08T00:59:22.000Z
2022-02-08T00:14:39.000Z
tests/test_circuit/test_new_style_syntax.py
leonardt/magma
d3e8c9500ec3b167df8ed067e0c0305781c94ab6
[ "MIT" ]
719
2017-08-29T17:58:28.000Z
2022-03-31T23:39:18.000Z
tests/test_circuit/test_new_style_syntax.py
leonardt/magma
d3e8c9500ec3b167df8ed067e0c0305781c94ab6
[ "MIT" ]
14
2017-09-01T03:25:16.000Z
2021-11-05T13:30:24.000Z
import magma as m from magma.testing.utils import has_warning, has_error def _check_foo_interface(Foo): assert list(Foo.interface.ports.keys()) == ["I", "O"] assert isinstance(Foo.interface.ports["I"], m.Bit) assert Foo.interface.ports["I"].is_output() assert isinstance(Foo.interface.ports["O"], m.Bit) assert Foo.interface.ports["O"].is_input() def test_new_style_basic(): class _Foo(m.Circuit): io = m.IO(I=m.In(m.Bit), O=m.Out(m.Bit)) m.wire(io.I, io.O) assert _Foo.name == "_Foo" assert m.isdefinition(_Foo) _check_foo_interface(_Foo) def test_new_style_name(): class _Foo(m.Circuit): io = m.IO(I=m.In(m.Bit), O=m.Out(m.Bit)) name = "new_name" assert _Foo.name == "new_name" def test_new_style_with_instance(): instances = [] class _Bar(m.Circuit): io = m.IO(I=m.In(m.Bit), O=m.Out(m.Bit)) m.wire(io.I, io.O) class _Foo(m.Circuit): io = m.IO(I=m.In(m.Bit), O=m.Out(m.Bit)) bar = _Bar() m.wire(io.I, bar.I) m.wire(bar.O, io.O) instances.append(bar) assert _Foo.instances == instances assert _Foo.O.value() is instances[0].O assert instances[0].I.value() is _Foo.I def test_old_style_override(caplog): class _Foo(m.Circuit): IO = ["I", m.In(m.Bit), "O", m.Out(m.Bit)] io = None # doesn't matter what the value of io is. _check_foo_interface(_Foo) expected = "'IO' and 'io' should not both be specified, ignoring 'io'" assert has_warning(caplog, expected) def test_new_style_not_isdefinition(): class _Foo(m.Circuit): io = m.IO(I=m.In(m.Bit), O=m.Out(m.Bit)) assert not m.isdefinition(_Foo) def test_new_style_unconnected(caplog): class _Foo(m.Circuit): io = m.IO(I=m.In(m.Bit), O=m.Out(m.Bits[2])) m.wire(io.I, io.O[0]) assert m.isdefinition(_Foo) assert has_error(caplog, "Output port _Foo.O not driven") def test_new_style_with_definition_method(caplog): class _Foo(m.Circuit): io = m.IO(I=m.In(m.Bit), O=m.Out(m.Bit)) m.wire(io.I, io.O) @classmethod def definition(io): raise Exception() assert m.isdefinition(_Foo) expected = ("Supplying method 'definition' with new inline definition " "syntax is not supported, ignoring 'definition'") assert has_warning(caplog, expected) def test_defn_wiring_error(caplog): class _Foo(m.Circuit): io = m.IO(I=m.In(m.Bit), O=m.In(m.Bit), O1=m.Out(m.Bits[1])) m.wire(io.I, io.O) m.wire(io.I, io.O1) assert not m.isdefinition(_Foo) assert has_error(caplog, "Cannot wire _Foo.I (Out(Bit)) to _Foo.O (Out(Bit))") assert has_error(caplog, "Cannot wire _Foo.I (Out(Bit)) to _Foo.O1 (In(Bits[1]))") def test_inst_wiring_error(caplog): class _Bar(m.Circuit): io = m.IO(I=m.In(m.Bits[1]), O=m.Out(m.Bits[1])) class _Foo(m.Circuit): io = m.IO(I=m.In(m.Bit), O=m.Out(m.Bit)) bar = _Bar() m.wire(io.I, bar.I) m.wire(bar.O, io.O) assert has_error( caplog, "Cannot wire _Foo.I (Out(Bit)) to _Foo._Bar_inst0.I (In(Bits[1]))") assert has_error( caplog, "Cannot wire _Foo._Bar_inst0.O (Out(Bits[1])) to _Foo.O (In(Bit))") assert has_error(caplog, "Output port _Foo.O not driven") assert has_error(caplog, "Input port _Bar_inst0.I not driven") def test_nested_definition(): class _Foo(m.Circuit): io = m.IO(I=m.In(m.Bit), O=m.Out(m.Bit)) class _Bar(m.Circuit): io = m.IO(I=m.In(m.Bit), O=m.Out(m.Bit)) m.wire(io.I, io.O) bar = _Bar() m.wire(io.I, bar.I) m.wire(bar.O, io.O) assert repr(_Foo) == """_Foo = DefineCircuit("_Foo", "I", In(Bit), "O", Out(Bit)) _Bar_inst0 = _Bar() wire(_Foo.I, _Bar_inst0.I) wire(_Bar_inst0.O, _Foo.O) EndCircuit()""" assert repr(_Foo._Bar) == """_Bar = DefineCircuit("_Bar", "I", In(Bit), "O", Out(Bit)) wire(_Bar.I, _Bar.O) EndCircuit()"""
27.516779
90
0.597805
f4945fcd79ca0f16adbdf8e3c10bd6db51de7c88
162
ts
TypeScript
src/decorators/index.ts
UserOfficeProject/user-office-backend
dc69dfd7332d96b28cd28134478b0a7c1abff932
[ "BSD-3-Clause" ]
4
2020-08-27T15:25:12.000Z
2021-12-13T16:12:28.000Z
src/decorators/index.ts
UserOfficeProject/user-office-backend
dc69dfd7332d96b28cd28134478b0a7c1abff932
[ "BSD-3-Clause" ]
60
2020-09-17T06:37:33.000Z
2022-03-29T05:30:31.000Z
src/decorators/index.ts
UserOfficeProject/user-office-backend
dc69dfd7332d96b28cd28134478b0a7c1abff932
[ "BSD-3-Clause" ]
1
2021-04-07T12:19:36.000Z
2021-04-07T12:19:36.000Z
export { default as ValidateArgs } from './ValidateArgs'; export { default as EventBus } from './EventBus'; export { default as Authorized } from './Authorized';
40.5
57
0.722222
662f90b16d97cf62514584fe720421996bf9a56a
4,749
py
Python
open_cli/completer.py
dennislwm/open-cli
dad66ee6a0b494c7a7f983ff43a030ea8ffc291d
[ "MIT" ]
55
2018-05-11T20:14:51.000Z
2022-02-16T18:08:19.000Z
open_cli/completer.py
dennislwm/open-cli
dad66ee6a0b494c7a7f983ff43a030ea8ffc291d
[ "MIT" ]
3
2018-05-17T14:44:03.000Z
2018-08-29T07:44:49.000Z
open_cli/completer.py
dennislwm/open-cli
dad66ee6a0b494c7a7f983ff43a030ea8ffc291d
[ "MIT" ]
5
2019-10-26T00:16:09.000Z
2021-07-22T15:13:44.000Z
import shlex from prompt_toolkit.completion import Completer, Completion class CommandCompleter(Completer): """Manage completion suggestions to the CLI.""" def __init__(self, client): """Create a CLI commands completer based on the client object.""" self.client = client self.definitions = client.swagger_spec.definitions def get_completions(self, document, complete_event): """Yields CLI completion based on the input text and the client object.""" for completion, position in self._text_to_completions(document.text): yield Completion(completion, start_position=-position) def _text_to_completions(self, text): """Convert raw text into completion suggestions.""" try: words = shlex.split(text) except ValueError: words = text.split(" ") operation, remaining_text = self._extract_operation(words=words) if callable(operation): return self._get_operation_params_completions( original_text=text, remaining_text=remaining_text, operation=operation, ) return self._get_completion( original_text=text, remaining_text=remaining_text, options=dir(operation) ) def _extract_operation(self, words): """Get the required client operation and separate it from the remaining text.""" operation = self.client for word in words: attr = getattr(operation, word, None) if attr is None: return operation, words[-1] operation = attr return operation, "" def _get_operation_params_completions(self, original_text, remaining_text, operation): """Get suggestions based on operation and remaining text.""" completion_offset = 0 # Strip argument prefix if remaining_text.startswith("--"): if len(remaining_text.split("=")) == 2: # Already a valid param remaining_text = "" else: remaining_text = remaining_text[2:] completion_offset = 2 # Handel definition type argument completions if "." in remaining_text: return self._get_definition_completions( original_text=original_text, remaining_text=remaining_text, operation=operation ) if self.should_hide_completions(original_text=original_text, remaining_text=remaining_text, allowed_suffixes=(" ", "-")): return [] return [("--" + attribute, len(remaining_text) + completion_offset) for attribute in operation.operation.params if attribute.startswith(remaining_text) and not attribute.startswith("_")] def _get_definition_completions(self, original_text, remaining_text, operation): """Get suggestions based on definition and remaining text.""" param_words = remaining_text.split(".") # Only two words parameter completion are supported if len(param_words) != 2: return [] param_name, sub_name = param_words if param_name not in operation.operation.params: return [] param_object = operation.operation.params[param_name] param_schema = param_object.param_spec.get("schema") if not param_schema: return [] param_ref = param_schema.get("$ref") if not param_ref: return [] definition_name = param_ref.split('/')[-1] definition = self.definitions.get(definition_name) if not definition: return [] return self._get_completion( original_text=original_text, remaining_text=sub_name, options=dir(definition()) ) def _get_completion(self, original_text, remaining_text, options): """Get completion properties based on text and possible options.""" if self.should_hide_completions(original_text=original_text, remaining_text=remaining_text, allowed_suffixes=(" ", ".")): return [] return [(option, len(remaining_text)) for option in options if option.startswith(remaining_text) and not option.startswith("_")] @staticmethod def should_hide_completions(original_text, remaining_text, allowed_suffixes): return (original_text and not remaining_text and original_text[-1] not in allowed_suffixes)
35.440299
90
0.608549
afa008fa3636a4fda9344f5f425591dcd3ce2b35
2,250
py
Python
robobet/bet_placer/site_routers.py
Toffooo/robobet
e3522be66b963bec1439a0e06dde3ae2edbcf22c
[ "MIT" ]
null
null
null
robobet/bet_placer/site_routers.py
Toffooo/robobet
e3522be66b963bec1439a0e06dde3ae2edbcf22c
[ "MIT" ]
null
null
null
robobet/bet_placer/site_routers.py
Toffooo/robobet
e3522be66b963bec1439a0e06dde3ae2edbcf22c
[ "MIT" ]
null
null
null
import time from abc import ABC, abstractmethod from contextlib import contextmanager from selenium import webdriver from settings import Bet1X from .schemas import RouterResponse, create_router_response class AbstractRouter(ABC): def __init__(self, username: int, password: str) -> None: self.username = username self.password = password @abstractmethod def get_balance(self) -> RouterResponse: pass class Bet1XRouter(AbstractRouter): def __init__(self, username: int, password: str) -> None: super().__init__(username, password) @contextmanager def login(self): driver = webdriver.Firefox() try: driver.get(Bet1X.base_url) drop_login_btn = driver.find_element_by_id("curLoginForm") drop_login_btn.click() auth_id_email = driver.find_element_by_id("auth_id_email") auth_id_email.send_keys(self.username) auth_form_password = driver.find_element_by_id("auth-form-password") auth_form_password.send_keys(self.password) login_btn = driver.find_element_by_class_name("auth-button") login_btn.click() time.sleep(3) # TODO: replace this block to `.wait_until` yield driver finally: exit_btn = driver.find_element_by_class_name("exitLink") exit_btn.click() driver.close() def get_balance(self) -> RouterResponse: response = create_router_response( path=Bet1X.get_balance, linter={ "type": "ELEMENT", "tag": "p", "attrs": {"class": "top-b-acc__amount"}, }, ) return response def get_live_matches(self) -> RouterResponse: response = create_router_response( path=Bet1X.base_url, linter={ "type": "LIST", "tag": "div", "attrs": {"data-name": "dashboard-champ-content"}, "children": { "type": "LIST", "tag": "div", "attrs": {"class": "c-events__item"}, }, }, ) return response
28.125
80
0.572889
2c64be6c48e872ca2725e3d2f655ea8319d5bdcb
10,090
py
Python
cooler/cli/load.py
mimakaev/cooler
84b0d510dc3baf0b9ef3592f9d27ba795e1802ee
[ "BSD-3-Clause" ]
106
2016-01-15T21:24:41.000Z
2020-09-24T12:15:13.000Z
cooler/cli/load.py
mimakaev/cooler
84b0d510dc3baf0b9ef3592f9d27ba795e1802ee
[ "BSD-3-Clause" ]
190
2016-02-16T03:35:30.000Z
2020-09-25T19:16:28.000Z
cooler/cli/load.py
mimakaev/cooler
84b0d510dc3baf0b9ef3592f9d27ba795e1802ee
[ "BSD-3-Clause" ]
43
2016-08-26T18:51:21.000Z
2020-09-08T13:38:50.000Z
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import simplejson as json import sys import numpy as np import pandas as pd from ._util import parse_bins, parse_field_param, parse_kv_list_param from . import cli, get_logger import click from ..create import ( create_from_unordered, sanitize_records, sanitize_pixels, BIN_DTYPE, COUNT_DTYPE, ) @cli.command() @click.argument( "bins_path", metavar="BINS_PATH" ) @click.argument( "pixels_path", type=click.Path(exists=True, allow_dash=True), metavar="PIXELS_PATH" ) @click.argument( "cool_path", metavar="COOL_PATH" ) @click.option( "--format", "-f", help="'coo' refers to a tab-delimited sparse triplet file " "(bin1, bin2, count). " "'bg2' refers to a 2D bedGraph-like file " "(chrom1, start1, end1, chrom2, start2, end2, count).", type=click.Choice(["coo", "bg2"]), required=True, ) @click.option( "--metadata", help="Path to JSON file containing user metadata." ) @click.option( "--assembly", help="Name of genome assembly (e.g. hg19, mm10)" ) @click.option( "--field", help="Add supplemental value fields or override default field numbers for " "the specified format. " "Specify quantitative input fields to aggregate into value columns " "using the syntax ``--field <field-name>=<field-number>``. " "Optionally, append ``:`` followed by ``dtype=<dtype>`` to specify " "the data type (e.g. float). Field numbers are 1-based. " "Repeat the ``--field`` option for each additional field.", type=str, multiple=True, ) @click.option( "--chunksize", "-c", help="Size (in number of lines/records) of data chunks to read and process " "from the input file at a time. These chunks will be saved as " "temporary partial Coolers and merged at the end. Also specifies the " "size of the buffer during the merge step.", type=int, default=int(20e6), ) @click.option( "--count-as-float", is_flag=True, default=False, help="Store the 'count' column as floating point values instead of as " "integers. Can also be specified using the `--field` option.", ) @click.option( "--one-based", is_flag=True, default=False, help="Pass this flag if the bin IDs listed in a COO file are one-based " "instead of zero-based.", ) @click.option( "--comment-char", type=str, default="#", show_default=True, help="Comment character that indicates lines to ignore.", ) @click.option( "--no-symmetric-upper", "-N", help="Create a complete square matrix without implicit symmetry. " "This allows for distinct upper- and lower-triangle values", is_flag=True, default=False, ) @click.option( "--input-copy-status", type=click.Choice(["unique", "duplex"]), default="unique", help="Copy status of input data when using symmetric-upper storage. | " "`unique`: Incoming data comes from a unique half of a symmetric " "matrix, regardless of how element coordinates are ordered. " "Execution will be aborted if duplicates are detected. " "`duplex`: Incoming data contains upper- and lower-triangle duplicates. " "All lower-triangle input elements will be discarded! | " "If you wish to treat lower- and upper-triangle input data as " "distinct, use the ``--no-symmetric-upper`` option instead. ", show_default=True, ) @click.option( "--storage-options", help="Options to modify the data filter pipeline. Provide as a " "comma-separated list of key-value pairs of the form 'k1=v1,k2=v2,...'. " "See http://docs.h5py.org/en/stable/high/dataset.html#filter-pipeline " "for more details.", ) def load( bins_path, pixels_path, cool_path, format, metadata, assembly, chunksize, field, count_as_float, one_based, comment_char, input_copy_status, no_symmetric_upper, storage_options, **kwargs ): """ Create a cooler from a pre-binned matrix. BINS_PATH : One of the following <TEXT:INTEGER> : 1. Path to a chromsizes file, 2. Bin size in bp <TEXT> : Path to BED file defining the genomic bin segmentation. PIXELS_PATH : Text file containing nonzero pixel values. May be gzipped. Pass '-' to use stdin. COOL_PATH : Output COOL file path or URI. **Notes** Two input format options (tab-delimited). Input pixel file may be compressed. COO: COO-rdinate sparse matrix format (a.k.a. ijv triple). 3 columns: "bin1_id, bin2_id, count", BG2: 2D version of the bedGraph format. 7 columns: "chrom1, start1, end1, chrom2, start2, end2, count" **Examples** cooler load -f bg2 <chrom.sizes>:<binsize> in.bg2.gz out.cool """ logger = get_logger(__name__) chromsizes, bins = parse_bins(bins_path) symmetric_upper = not no_symmetric_upper tril_action = None if symmetric_upper: if input_copy_status == "unique": tril_action = "reflect" elif input_copy_status == "duplex": tril_action = "drop" # User-supplied JSON file if metadata is not None: with open(metadata, "r") as f: metadata = json.load(f) # Initialize the output schema. We don't include 'count' yet. output_field_names = ["bin1_id", "bin2_id"] output_field_dtypes = { "bin1_id": BIN_DTYPE, "bin2_id": BIN_DTYPE, "count": COUNT_DTYPE, } # Initialize the input schema and create the input santizer. if format == "bg2": input_field_names = [ "chrom1", "start1", "end1", "chrom2", "start2", "end2", # We don't include 'count' yet. ] input_field_dtypes = { "chrom1": str, "start1": int, "end1": int, "chrom2": str, "start2": int, "end2": int, "count": output_field_dtypes["count"], } input_field_numbers = { "chrom1": kwargs.get("chrom1", 0), "start1": kwargs.get("start1", 1), "end1": kwargs.get("end1", 2), "chrom2": kwargs.get("chrom2", 3), "start2": kwargs.get("start2", 4), "end2": kwargs.get("end2", 5), "count": 6, } pipeline = sanitize_records( bins, schema="bg2", is_one_based=one_based, tril_action=tril_action, sort=True, ) elif format == "coo": input_field_names = [ "bin1_id", "bin2_id", # We don't include 'count' yet. ] input_field_dtypes = { "bin1_id": int, "bin2_id": int, "count": output_field_dtypes["count"], } input_field_numbers = {"bin1_id": 0, "bin2_id": 1, "count": 2} pipeline = sanitize_pixels( bins, is_one_based=one_based, tril_action=tril_action, sort=True ) # Include input value columns if len(field): for arg in field: name, colnum, dtype, _ = parse_field_param(arg, includes_agg=False) # Special cases: omit field number to change standard dtypes. if colnum is None: if name in {"bin1_id", "bin2_id"} and dtype is not None: # No input field output_field_dtypes[name] = dtype continue elif name == "count" and dtype is not None: input_field_names.append("count") output_field_names.append("count") input_field_dtypes[name] = dtype output_field_dtypes[name] = dtype continue else: raise click.BadParameter( "A field number is required.", param_hint=arg ) if name not in input_field_names: input_field_names.append(name) if name not in output_field_names: output_field_names.append(name) input_field_numbers[name] = colnum if dtype is not None: input_field_dtypes[name] = dtype output_field_dtypes[name] = dtype else: # If no other fields are given, 'count' is implicitly included. # Default dtype and field number are assumed. input_field_names.append("count") output_field_names.append("count") if "count" in input_field_names and count_as_float: input_field_dtypes["count"] = np.float64 output_field_dtypes["count"] = np.float64 # Customize the HDF5 filters if storage_options is not None: h5opts = parse_kv_list_param(storage_options) for key in h5opts: if isinstance(h5opts[key], list): h5opts[key] = tuple(h5opts[key]) else: h5opts = None # Initialize the input stream if pixels_path == "-": f_in = sys.stdin else: f_in = pixels_path reader = pd.read_csv( f_in, sep="\t", usecols=[input_field_numbers[name] for name in input_field_names], names=input_field_names, dtype=input_field_dtypes, comment=comment_char, iterator=True, chunksize=chunksize, ) logger.info("fields: {}".format(input_field_numbers)) logger.info("dtypes: {}".format(input_field_dtypes)) logger.info("symmetric-upper: {}".format(symmetric_upper)) create_from_unordered( cool_path, bins, map(pipeline, reader), columns=output_field_names, dtypes=output_field_dtypes, metadata=metadata, assembly=assembly, mergebuf=chunksize, ensure_sorted=False, # boundscheck=True, # dupcheck=True, triucheck=True if symmetric_upper else False, symmetric_upper=symmetric_upper, h5opts=h5opts, )
30.029762
80
0.603072
4d9b3d8204168da6ff885d41b9a5f9bcea9cd42f
2,947
cs
C#
AsyncTwitch2/Models/ChatUser.cs
lolPants/AsyncTwitch2
c887a3ea15f29313eb217c607fdd5d0c098e628d
[ "0BSD" ]
1
2020-06-20T08:40:05.000Z
2020-06-20T08:40:05.000Z
AsyncTwitch2/Models/ChatUser.cs
lolPants/AsyncTwitch2
c887a3ea15f29313eb217c607fdd5d0c098e628d
[ "0BSD" ]
null
null
null
AsyncTwitch2/Models/ChatUser.cs
lolPants/AsyncTwitch2
c887a3ea15f29313eb217c607fdd5d0c098e628d
[ "0BSD" ]
null
null
null
using System.Text; namespace AsyncTwitch.Models { public struct ChatUser { /// <summary> /// Twitch Username. /// </summary> public string Username; /// <summary> /// Twitch Username as displayed in chat. /// </summary> public string DisplayName; /// <summary> /// Unique identifer for this user. /// </summary> public string ID; /// <summary> /// User's chat color in RGB hex format. EG: #bf67ff /// </summary> public string Color; /// <summary> /// Whether this user has moderator status in the current room. /// </summary> public bool Moderator; /// <summary> /// Whether this user has broadcaster status in the current room. /// </summary> public bool Broadcaster; /// <summary> /// Whether this user is a subscriber in the current room. /// </summary> public bool Subscriber; /// <summary> /// Whether this user is a VIP in the current room. /// </summary> public bool VIP; /// <summary> /// All badges this user has in the current room. /// </summary> public ChatBadge[] Badges; public ChatUser(string _username, string _displayName, string _id, string _color, bool _moderator, bool _broadcaster, bool _subscriber, bool _vip) { Username = _username; DisplayName = _displayName; ID = _id; Color = _color; Moderator = _moderator; Broadcaster = _broadcaster; Subscriber = _subscriber; VIP = _vip; Badges = new ChatBadge[0]; } public ChatUser(string _username, string _displayName, string _id, string _color, bool _moderator, bool _broadcaster, bool _subscriber, bool _vip, ChatBadge[] _badges) { Username = _username; DisplayName = _displayName; ID = _id; Color = _color; Moderator = _moderator; Broadcaster = _broadcaster; Subscriber = _subscriber; VIP = _vip; Badges = _badges; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendLine("-- Chat User --"); sb.AppendLine($"Username: {Username}"); sb.AppendLine($"Display Name: {DisplayName}"); sb.AppendLine($"User ID: {ID}"); sb.AppendLine($"Chat Color: {Color}"); sb.AppendLine($"Is Moderator: {Moderator}"); sb.AppendLine($"Is Broadcaster: {Broadcaster}"); sb.AppendLine($"Is Subscriber: {Subscriber}"); sb.AppendLine($"Is VIP: {VIP}"); sb.Append($"# of Badges: {Badges.Length}"); return sb.ToString(); } } }
30.381443
175
0.534102
004edcc84acf226a31f955d90d4e92d8648f56f7
1,347
swift
Swift
Ribbon/Extensions/NSToolbar.swift
chriszielinski/Ribbon
e4a93bdcf945839f48d61a27045d1e53a86f3a30
[ "MIT" ]
297
2019-08-11T07:33:09.000Z
2022-03-26T02:41:03.000Z
Ribbon/Extensions/NSToolbar.swift
mohsinalimat/Ribbon
a69fbd14dbe05dfdd92128c1de7d53501bfba270
[ "MIT" ]
null
null
null
Ribbon/Extensions/NSToolbar.swift
mohsinalimat/Ribbon
a69fbd14dbe05dfdd92128c1de7d53501bfba270
[ "MIT" ]
21
2019-08-13T13:47:32.000Z
2022-01-29T16:11:43.000Z
// // NSToolbar.swift // Ribbon 🎀 // // Created by Chris Zielinski on 7/26/19. // Copyright © 2019 Big Z Labs. All rights reserved. // #if canImport(AppKit) import AppKit extension NSToolbar { // MARK: - Initializers // MARK: Convenience convenience init(ribbon: Ribbon) { self.init(identifier: ribbon.configuration?.toolbar?.identifier ?? "Ribbon") if UserDefaults.standard.dictionary(forKey: "NSToolbar Configuration \(identifier)") == nil { if let configuration = ribbon.configuration?.toolbar { displayMode = configuration.displayMode?.bridge ?? .iconOnly isVisible = configuration.isVisible ?? true sizeMode = configuration.sizeMode?.bridge ?? .default } else { displayMode = .iconOnly isVisible = true sizeMode = .default } } allowsExtensionItems = ribbon.configuration?.toolbar?.allowsExtensionItems ?? false allowsUserCustomization = ribbon.configuration?.toolbar?.allowsUserCustomization ?? true showsBaselineSeparator = ribbon.configuration?.toolbar?.showsBaselineSeparator ?? false autosavesConfiguration = true delegate = ribbon ribbon.items.forEach({ $0.initializeToolbarItemIfNeeded() }) } } #endif
29.933333
101
0.639941
37858200586dbcdec25a789fae40f6ec357ab102
1,260
kts
Kotlin
build.gradle.kts
AndrewReitz/zwift-workout-creator
302c2e2b2b5e0c42651d9cc456609ee15a007372
[ "MIT" ]
null
null
null
build.gradle.kts
AndrewReitz/zwift-workout-creator
302c2e2b2b5e0c42651d9cc456609ee15a007372
[ "MIT" ]
null
null
null
build.gradle.kts
AndrewReitz/zwift-workout-creator
302c2e2b2b5e0c42651d9cc456609ee15a007372
[ "MIT" ]
null
null
null
plugins { application kotlin("jvm") version "1.3.71" id("com.palantir.graal") version "0.6.0" id("com.github.ben-manes.versions") version "0.28.0" } repositories { jcenter() } dependencies { implementation(kotlin("stdlib")) implementation(kotlin("main-kts")) implementation(kotlin("reflect")) implementation("com.github.ajalt:clikt:2.6.0") implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.11.0.rc1") implementation("com.fasterxml.jackson.core:jackson-annotations:2.11.0.rc1") testImplementation(kotlin("test")) testImplementation("org.spekframework.spek2:spek-dsl-jvm:2.0.10") testRuntimeOnly("org.spekframework.spek2:spek-runner-junit5:2.0.10") testImplementation("ch.tutteli.spek:tutteli-spek-extensions:1.1.0") testImplementation("com.google.truth:truth:1.0.1") } application { mainClassName = "andrew.cash.zwift.AppKt" } tasks.withType<Test> { useJUnitPlatform { includeEngines("spek2") } } tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> { sourceCompatibility = "1.8" targetCompatibility = "1.8" kotlinOptions.jvmTarget = "1.8" } graal { mainClass("andrew.cash.zwift.AppKt") outputName("zwocreate") }
25.714286
88
0.702381
6d8836946e1791a8561d51a5408991bdc678da22
15,242
h
C
bsp/imx6sx/iMX6_Platform_SDK/sdk/common/usb_stack/Device/source/class/usb_msc.h
Davidfind/rt-thread
56f1a8af4f9e8bad0a0fdc5cea7112767267b243
[ "Apache-2.0" ]
7,482
2015-01-01T09:23:08.000Z
2022-03-31T19:34:05.000Z
platform/mcu/imx6/imx6_platform_sdk/sdk/common/usb_stack/Device/source/class/usb_msc.h
IamBaoMouMou/AliOS-Things
195a9160b871b3d78de6f8cf6c2ab09a71977527
[ "Apache-2.0" ]
2,543
2015-01-09T02:01:34.000Z
2022-03-31T23:10:14.000Z
platform/mcu/imx6/imx6_platform_sdk/sdk/common/usb_stack/Device/source/class/usb_msc.h
IamBaoMouMou/AliOS-Things
195a9160b871b3d78de6f8cf6c2ab09a71977527
[ "Apache-2.0" ]
4,645
2015-01-06T07:05:31.000Z
2022-03-31T18:21:50.000Z
/****************************************************************************** * * Freescale Semiconductor Inc. * (c) Copyright 2004-2009 Freescale Semiconductor, Inc. * ALL RIGHTS RESERVED. * ****************************************************************************** * * THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESSED OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL FREESCALE OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * **************************************************************************//*! * * @file usb_msc.h * * @author * * @version * * @date May-08-2009 * * @brief The file contains USB stack MSC class layer api header function. * *****************************************************************************/ #ifndef _USB_MSC_H #define _USB_MSC_H 1 /****************************************************************************** * Includes *****************************************************************************/ #include "usb_devapi.h" #include "usb_descriptor.h" #include "usb_class.h" #include "usb_framework.h" #ifdef COMPOSITE_DEV #include "usb_composite.h" #endif /****************************************************************************** * Constants - None *****************************************************************************/ /****************************************************************************** * Macro's *****************************************************************************/ #define COMPONENT_PREPARE_SHIFT (0x07) #define USB_MSC_DEVICE_READ_REQUEST (0x81) #define USB_MSC_DEVICE_WRITE_REQUEST (0x82) #define USB_MSC_DEVICE_FORMAT_COMPLETE (0x83) #define USB_MSC_DEVICE_REMOVAL_REQUEST (0x84) #define USB_MSC_DEVICE_GET_INFO (0x85) #define USB_MSC_START_STOP_EJECT_MEDIA (0x86) /* Class specific request Codes */ #define BULK_ONLY_MASS_STORAGE_RESET (0xFF) #define GET_MAX_LUN (0xFE) #define PUT_REQUESTS (0xFD) #define GET_REQUESTS (0xFC) /* Events to the Application */ /* 0 to 4 are reserved for class events */ /* other macros */ #if (defined LITTLE_ENDIAN) #define USB_DCBWSIGNATURE (0x43425355) /*little endian : 0x43425355 */ #define USB_DCSWSIGNATURE (0x53425355) /*little endian : 0x53425355 */ #else #define USB_DCBWSIGNATURE (0x55534243) /*big endian : 0x55534243 */ #define USB_DCSWSIGNATURE (0x55534253) /*big endian : 0x55534253 */ #endif #define USB_CBW_DIRECTION_BIT (0x80) #define USB_CBW_DIRECTION_SHIFT (7) #define MSC_CBW_LENGTH (31) #define MSC_CSW_LENGTH (13) #define MSC_RECV_DATA_BUFF_SIZE (MSD_RECEIVE_BUFFER_SIZE) #define MSC_SEND_DATA_BUFF_SIZE (MSD_SEND_BUFFER_SIZE) #define COMMAND_PASSED (0x00) #define COMMAND_FAILED (0x01) #define PHASE_ERROR (0x02) /* macros for queuing */ #define MAX_QUEUE_ELEMS (4) /* MACROS FOR COMMANDS SUPPORTED */ #define INQUIRY_COMMAND (0x12) #define READ_10_COMMAND (0x28) #define READ_12_COMMAND (0xA8) #define REQUEST_SENSE_COMMAND (0x03) #define TEST_UNIT_READY_COMMAND (0x00) #define WRITE_10_COMMAND (0x2A) #define WRITE_12_COMMAND (0xAA) #define PREVENT_ALLOW_MEDIUM_REM_COMMAND (0x1E) #define FORMAT_UNIT_COMMAND (0x04) #define READ_CAPACITY_10_COMMAND (0x25) #define READ_FORMAT_CAPACITIES_COMMAND (0x23) #define MODE_SENSE_10_COMMAND (0x5A) #define MODE_SENSE_6_COMMAND (0x1A) #define MODE_SELECT_10_COMMAND (0x55) #define MODE_SELECT_6_COMMAND (0x15) #define SEND_DIAGNOSTIC_COMMAND (0x1D) #define VERIFY_COMMAND (0x2F) #define START_STOP_UNIT_COMMAND (0x1B) /***************************************************************************** * Local Functions *****************************************************************************/ void USB_Service_Bulk_In(PTR_USB_DEV_EVENT_STRUCT event); void USB_Service_Bulk_Out(PTR_USB_DEV_EVENT_STRUCT event); void USB_Class_MSC_Event(uint_8 controller_ID, uint_8 event, void* val); /****************************************************************************** * Types *****************************************************************************/ #ifndef __HIWARE__ #pragma pack(1) #endif /* structure to hold a request in the endpoint queue */ typedef struct _usb_class_msc_queue { uint_8 controller_ID; uint_8 channel; APP_DATA_STRUCT app_data; }USB_CLASS_MSC_QUEUE, *PTR_USB_CLASS_MSC_QUEUE; /* USB class msc endpoint data */ typedef struct _usb_class_msc_endpoint { uint_8 endpoint; /* endpoint num */ uint_8 type; /* type of endpoint (interrupt, bulk or isochronous) */ uint_8 bin_consumer;/* the num of queued elements */ uint_8 bin_producer;/* the num of de-queued elements */ USB_CLASS_MSC_QUEUE queue[MAX_QUEUE_ELEMS]; /* queue data */ }USB_CLASS_MSC_ENDPOINT; typedef struct _usb_msc_cbw /* Command Block Wrapper -- 31 bytes */ { uint_32 signature; /*0-3 : dCBWSignature*/ uint_32 tag; /*4-7 : dCBWTag*/ uint_32 data_length; /*8-11 : dCBWDataTransferLength*/ uint_8 flag; /*12 : bmCBWFlags*/ uint_8 lun; /*13 : bCBWLUN(bits 3 to 0)*/ uint_8 cb_length; /*14 : bCBWCBLength*/ uint_8 command_block[16];/*15-30 : CBWCB*/ }CBW, *PTR_CBW ; typedef struct _usb_msc_csw /* Command Status Wrapper -- 13 bytes */ { uint_32 signature; /*0-3 : dCSWSignature*/ uint_32 tag; /*4-7 : dCSWTag*/ uint_32 residue; /*8-11 : dCSWDataResidue*/ uint_8 csw_status; /*12 : bCSWStatus*/ }CSW, *PTR_CSW; typedef struct _lba_info_struct { uint_32 starting_lba;/* LBA to start transfering with */ uint_32 lba_transfer_num;/* number of LBAs to transfer */ }LBA_INFO_STRUCT, * PTR_LBA_INFO_STRUCT; typedef struct _lba_app_struct { uint_32 offset; uint_32 size; uint_8_ptr buff_ptr; }LBA_APP_STRUCT, * PTR_LBA_APP_STRUCT; typedef struct _device_lba_info_struct { uint_32 total_lba_device_supports;/* lba : LOGICAL BLOCK ADDRESS */ uint_32 length_of_each_lba_of_device; uint_8 num_lun_supported; }DEVICE_LBA_INFO_STRUCT, * PTR_DEVICE_LBA_INFO_STRUCT; typedef struct _msc_thirteen_case_check { uint_8 controller_ID; uint_32 host_expected_data_len; uint_8 host_expected_direction; uint_32 device_expected_data_len; uint_8 device_expected_direction; uint_8_ptr csw_status_ptr; uint_32_ptr csw_residue_ptr; uint_8_ptr buffer_ptr; boolean lba_txrx_select; LBA_INFO_STRUCT lba_info; }MSC_THIRTEEN_CASE_STRUCT, *PTR_MSC_THIRTEEN_CASE_STRUCT; typedef struct _msc_variable_struct { USB_CLASS_CALLBACK msc_callback; USB_REQ_FUNC vendor_callback; USB_CLASS_CALLBACK param_callback; uint_8 msc_lba_send_buff[MSC_SEND_DATA_BUFF_SIZE]; uint_8 msc_lba_recv_buff[MSC_RECV_DATA_BUFF_SIZE]; /* contains the endpoint info */ #ifndef COMPOSITE_DEV USB_CLASS_MSC_ENDPOINT ep[MSC_DESC_ENDPOINT_COUNT]; #else USB_CLASS_MSC_ENDPOINT ep[COMPOSITE_DESC_ENDPOINT_COUNT]; #endif /* macro configuired by user*/ /* LUN can have value only from 0 to 15 decimal */ uint_8 lun; /* flag to track bulk out data processing after CBW if needed*/ boolean out_flag; /* flag to track bulk in data processing before CSW if needed*/ boolean in_flag; /* flag to track if there is need to stall BULK IN ENDPOINT because of BULK COMMAND*/ boolean in_stall_flag; /* flag to track if there is need to stall BULK OUT ENDPOINT because of BULK COMMAND */ boolean out_stall_flag; /* flag to validate CBW */ boolean cbw_valid_flag; boolean re_stall_flag; DEVICE_LBA_INFO_STRUCT device_info; /* global structure for command block wrapper */ CBW cbw_struct; /* global structure for command status wrapper */ CSW csw_struct; }MSC_GLOBAL_VARIABLE_STRUCT, * PTR_MSC_GLOBAL_VARIABLE_STRUCT; #if defined(__CWCC__) #pragma options align=reset #elif defined(__IAR_SYSTEMS_ICC__) #pragma pack() #endif /****************************************************************************** * Global Functions *****************************************************************************/ extern uint_8 USB_Class_MSC_Init ( uint_8 controller_ID, USB_CLASS_CALLBACK msc_class_callback, USB_REQ_FUNC vendor_req_callback, USB_CLASS_CALLBACK param_callback ); extern void USB_Class_MSC_Event ( uint_8 controller_ID, /* [IN] Controller ID */ uint_8 event, /* [IN] Event Type */ void* val /* [IN] Pointer to configuration Value */ ); #ifdef COMPOSITE_DEV extern uint_8 USB_MSC_Other_Requests(uint_8 controller_ID, USB_SETUP_STRUCT * setup_packet, uint_8_ptr *data, uint_32 *size); #endif extern uint_8 USB_Class_MSC_DeInit ( uint_8 controller_ID ); extern uint_8 USB_MSC_SCSI_Init ( uint_8 controller_ID, USB_CLASS_CALLBACK callback ); extern uint_8 USB_MSC_LBA_Transfer ( uint_8 controller_ID, boolean direction, PTR_LBA_INFO_STRUCT lba_info_ptr ); extern uint_8 USB_Class_MSC_Send_Data ( uint_8 controller_ID, uint_8 ep_num, uint_8_ptr buff_ptr, /* [IN] buffer to send */ uint_32 size /* [IN] length of the transfer */ ); #define USB_MSC_Bulk_Send_Data(a,b,c) USB_Class_MSC_Send_Data(a,BULK_IN_ENDPOINT,b,c) #define USB_MSC_Bulk_Recv_Data(a,b,c) _usb_device_recv_data(a,BULK_OUT_ENDPOINT,b,c) #define USB_MSC_Periodic_Task USB_Class_Periodic_Task /* Sub Class Functions */ extern uint_8 msc_inquiry_command (uint_8 controller_ID, PTR_CBW cbw_ptr, uint_32* csw_residue_ptr, uint_8* csw_status_ptr); extern uint_8 msc_read_command (uint_8 controller_ID, PTR_CBW cbw_ptr, uint_32* csw_residue_ptr, uint_8* csw_status_ptr); extern uint_8 msc_request_sense_command(uint_8 controller_ID, PTR_CBW cbw_ptr, uint_32* csw_residue_ptr, uint_8* csw_status_ptr); extern uint_8 msc_test_unit_ready_command(uint_8 controller_ID, PTR_CBW cbw_ptr, uint_32* csw_residue_ptr, uint_8* csw_status_ptr); extern uint_8 msc_verify_command(uint_8 controller_ID, PTR_CBW cbw_ptr, uint_32* csw_residue_ptr, uint_8* csw_status_ptr); extern uint_8 msc_mode_sense_command(uint_8 controller_ID, PTR_CBW cbw_ptr, uint_32* csw_residue_ptr, uint_8* csw_status_ptr); extern uint_8 msc_mode_select_command(uint_8 controller_ID, PTR_CBW cbw_ptr, uint_32* csw_residue_ptr, uint_8* csw_status_ptr); extern uint_8 msc_read_capacity_command(uint_8 controller_ID, PTR_CBW cbw_ptr, uint_32* csw_residue_ptr, uint_8* csw_status_ptr); extern uint_8 msc_format_unit_command(uint_8 controller_ID, PTR_CBW cbw_ptr, uint_32* csw_residue_ptr, uint_8* csw_status_ptr); extern uint_8 msc_write_command (uint_8 controller_ID, PTR_CBW cbw_ptr, uint_32* csw_residue_ptr, uint_8* csw_status_ptr); extern uint_8 msc_prevent_allow_medium_removal(uint_8 controller_ID, PTR_CBW cbw_ptr, uint_32* csw_residue_ptr, uint_8* csw_status_ptr); extern uint_8 msc_read_format_capacity_command(uint_8 controller_ID, PTR_CBW cbw_ptr, uint_32* csw_residue_ptr, uint_8* csw_status_ptr); extern uint_8 msc_send_diagnostic_command(uint_8 controller_ID, PTR_CBW cbw_ptr, uint_32* csw_residue_ptr, uint_8* csw_status_ptr); extern uint_8 msc_start_stop_unit_command(uint_8 controller_ID, PTR_CBW cbw_ptr, uint_32* csw_residue_ptr, uint_8* csw_status_ptr); extern uint_8 msc_unsupported_command(uint_8 controller_ID, PTR_CBW cbw_ptr, uint_32* csw_residue_ptr, uint_8* csw_status_ptr); extern void USB_BYTE_SWAP4(uint_32 a, uint_32* b); extern void USB_memzero(void* ptr, uint_32 size); extern void USB_memcopy(void* src, void* dst, uint_32 size); #endif /* EOF */
40.322751
134
0.542186
3f9152a0549f5c150230ffa4aad69453d9cc63b8
5,724
asm
Assembly
Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0xca.log_21829_246.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0xca.log_21829_246.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0xca.log_21829_246.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r14 push %r9 push %rcx push %rdi push %rdx push %rsi lea addresses_normal_ht+0x14142, %rsi lea addresses_D_ht+0x7db6, %rdi nop nop nop nop nop and %r14, %r14 mov $92, %rcx rep movsq nop nop nop nop xor %rsi, %rsi lea addresses_WT_ht+0x67c2, %rsi lea addresses_WC_ht+0x1da02, %rdi nop nop nop nop nop and $28404, %r9 mov $35, %rcx rep movsb nop nop sub %rsi, %rsi lea addresses_WC_ht+0xf24a, %rsi lea addresses_UC_ht+0x19d42, %rdi nop cmp %rdx, %rdx mov $14, %rcx rep movsl nop nop nop nop nop and $16617, %r14 pop %rsi pop %rdx pop %rdi pop %rcx pop %r9 pop %r14 ret .global s_faulty_load s_faulty_load: push %r11 push %r8 push %r9 push %rax push %rbp push %rbx push %rdx // Load mov $0x5abf200000000866, %r8 nop nop nop nop nop xor $48153, %r9 mov (%r8), %rdx nop nop nop nop add $9944, %r8 // Store lea addresses_normal+0x8142, %rbx nop nop nop inc %rbp mov $0x5152535455565758, %r9 movq %r9, (%rbx) nop nop and $26673, %r9 // Load lea addresses_WT+0x11cf2, %r9 sub %r11, %r11 mov (%r9), %rbp nop nop add %r9, %r9 // Store mov $0x4c4af0000000a42, %r8 clflush (%r8) nop xor $9251, %rax movl $0x51525354, (%r8) nop sub $51074, %rdx // Faulty Load lea addresses_PSE+0x17542, %r9 nop nop nop nop nop xor $36047, %r11 movups (%r9), %xmm2 vpextrq $1, %xmm2, %rax lea oracles, %r9 and $0xff, %rax shlq $12, %rax mov (%r9,%rax,1), %rax pop %rdx pop %rbx pop %rbp pop %rax pop %r9 pop %r8 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': True, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'} {'src': {'congruent': 2, 'AVXalign': True, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_NC'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_normal'}} {'src': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_WT'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_NC'}} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 8, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_D_ht'}} {'src': {'congruent': 5, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_WC_ht'}} {'src': {'congruent': 3, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_UC_ht'}} {'33': 21829} 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 */
37.907285
2,999
0.657757
0d5d3f5ab01e892a45f4154a217332c9b5b8f371
1,280
h
C
panda/src/physx/physxRaycastReport.h
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/physx/physxRaycastReport.h
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/physx/physxRaycastReport.h
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file physxRaycastReport.h * @author enn0x * @date 2009-10-21 */ #ifndef PHYSXRAYCASTREPORT_H #define PHYSXRAYCASTREPORT_H #include "pandabase.h" #include "pvector.h" #include "config_physx.h" class PhysxRaycastHit; /** * Objects of this class are returned by the 'raycast all' methods. They * contain an iterable list of all hits that the raycast query produced. */ class EXPCL_PANDAPHYSX PhysxRaycastReport : public NxUserRaycastReport { PUBLISHED: unsigned int get_num_hits() const; PhysxRaycastHit get_first_hit(); PhysxRaycastHit get_next_hit(); PhysxRaycastHit get_hit(unsigned int idx); MAKE_SEQ(get_hits, get_num_hits, get_hit); public: INLINE PhysxRaycastReport(); INLINE ~PhysxRaycastReport(); virtual bool onHit(const NxRaycastHit& hit); private: typedef pvector<PhysxRaycastHit> Hits; Hits _hits; typedef Hits::const_iterator const_iterator; const_iterator _iterator; }; #include "physxRaycastReport.I" #endif // PHYSXRAYCASTREPORT_H
23.703704
73
0.757031
d01cb6e182d81c9a1b8ecedc5d95be9a285351d3
3,751
rb
Ruby
spec/spec_helper.rb
zph/buff
d07c9febe2d4d901fcb6728f41f66206c53e33c2
[ "MIT" ]
1
2016-01-06T10:57:43.000Z
2016-01-06T10:57:43.000Z
spec/spec_helper.rb
zph/buff
d07c9febe2d4d901fcb6728f41f66206c53e33c2
[ "MIT" ]
1
2015-04-05T04:32:06.000Z
2015-04-05T04:32:06.000Z
spec/spec_helper.rb
zph/buff
d07c9febe2d4d901fcb6728f41f66206c53e33c2
[ "MIT" ]
null
null
null
require 'buff' require 'rspec' require 'webmock/rspec' require 'json' require 'coveralls' Coveralls.wear! def travis? ENV['TRAVIS_CI'] end def fixture_path File.expand_path(File.join("..", "fixtures"), __FILE__) end def fixture(file) File.new(File.join(fixture_path, file)) end def post_data <<EOF schedules[0][days][]=mon&schedules[0][days][]=tue&schedules[0][days][]=wed&schedules[0][times][]=12:00&schedules[0][times][]=17:00&schedules[0][times][]=18:00& EOF end def modify_update_response response =<<EOF { "success" : true, "buffer_count" : 10, "buffer_percentage" : 20, "update" : { "id" : "4ecda256512f7ee521000004", "client_id" : "4f850cc93733aa9301000002", "created_at" : 1320703582, "day" : "Saturday 26th November", "due_at" : 1320742680, "due_time" : "11:05 am", "media" : { "link" : "http://google.com", "title" : "Google", "description" : "The google homepage" }, "profile_id" : "4eb854340acb04e870000010", "profile_service" : "twitter", "status" : "buffer", "text" : "This is an edited update", "text_formatted" : "This is an edited update", "user_id" : "4eb9276e0acb04bb81000067", "via" : "api" } } EOF end def create_update_return_body create_update_return_body =<<EOF { "success" : true, "buffer_count" : 10, "buffer_percentage" : 20, "updates" : [{ "id" : "4ecda256512f7ee521000004", "created_at" : 1320703582, "day" : "Saturday 26th November", "due_at" : 1320742680, "due_time" : "11:05 am", "media" : { "link" : "http://google.com", "title" : "Google", "description" : "The google homepage" }, "profile_id" : "4eb854340acb04e870000010", "profile_service" : "twitter", "status" : "buffer", "text" : "This is an example update", "text_formatted" : "This is an example update", "user_id" : "4eb9276e0acb04bb81000067", "via" : "api" } ] } EOF end def reorder_updates_body_response return_body =<<EOF { "success" : true, "updates" : [{ "id" : "4eb854340acb04e870000010", "created_at" : 1320703582, "day" : "Saturday 5th November", "due_at" : 1320742680, "due_time" : "08:01 am", "profile_id" : "4eb854340acb04e870000010", "profile_service" : "twitter", "status" : "buffer", "text" : "3 Incredible Stories Made Possible Through Twitter j.mp/u...", "text_formatted" : "3 Incredible Stories Made Possible Through Twit...", "user_id" : "4eb9276e0acb04bb81000067", "via" : "safari" } ] } EOF end def sample_schedules2 [{ days: %w[mon tue wed], times: %w[12:00 17:00 18:00]}, {days: %w[mon tue wed], times: %w[12:00 17:00 18:00]}, ] end def base_path "https://api.bufferapp.com/1" end def access_token_param "access_token=some_token" end def stub_with_to_return(request_type, url, fixture_name, query_hash={}) query = access_hash.merge(query_hash) stub_request(request_type, url). with(query: query). to_return(fixture(fixture_name)) end def access_hash { 'access_token' => 'some_token'} end def sample_schedules [{ days: %w[mon tue wed], times: %w[12:00 17:00 18:00]}] # @sample_schedules = JSON.parse <<EOF # [{ # "days" : [ # "mon", # "tue", # "wed", # "thu", # "fri" # ], # "times" : [ # "12:00", # "17:00", # "18:00" # ] # }, # { # "days" : [ # "mon", # "tue", # "wed", # "thu", # "fri" # ], # "times" : [ # "12:00", # "17:00", # "18:00" # ] # }] # EOF end
21.80814
159
0.569448
a3decf6ef96903a8d48b94a8e67064daa0b067e8
1,934
java
Java
simulator/src/test/java/com/hazelcast/simulator/protocol/handler/ResponseHandlerTest.java
hasancelik/hazelcast-stabilizer
2e3016ef6bdeeb39069ddcb6be6ff16ec97c1fb8
[ "Apache-2.0" ]
null
null
null
simulator/src/test/java/com/hazelcast/simulator/protocol/handler/ResponseHandlerTest.java
hasancelik/hazelcast-stabilizer
2e3016ef6bdeeb39069ddcb6be6ff16ec97c1fb8
[ "Apache-2.0" ]
null
null
null
simulator/src/test/java/com/hazelcast/simulator/protocol/handler/ResponseHandlerTest.java
hasancelik/hazelcast-stabilizer
2e3016ef6bdeeb39069ddcb6be6ff16ec97c1fb8
[ "Apache-2.0" ]
null
null
null
package com.hazelcast.simulator.protocol.handler; import com.hazelcast.simulator.protocol.core.AddressLevel; import com.hazelcast.simulator.protocol.core.Response; import com.hazelcast.simulator.protocol.core.ResponseFuture; import com.hazelcast.simulator.protocol.core.SimulatorAddress; import org.junit.Before; import org.junit.Test; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import static com.hazelcast.simulator.protocol.core.ResponseFuture.createFutureKey; import static com.hazelcast.simulator.protocol.core.ResponseFuture.createInstance; import static org.junit.Assert.assertEquals; public class ResponseHandlerTest { private final SimulatorAddress localAddress = SimulatorAddress.COORDINATOR; private final SimulatorAddress remoteAddress = new SimulatorAddress(AddressLevel.WORKER, 1, 1, 0); private ConcurrentMap<String, ResponseFuture> futureMap; private ResponseHandler responseHandler; @Before public void setUp() { futureMap = new ConcurrentHashMap<String, ResponseFuture>(); responseHandler = new ResponseHandler(localAddress, remoteAddress, futureMap); } @Test public void testChannelRead0() throws Exception { long messageId = 2948; Response response = new Response(messageId, remoteAddress); String futureKey = createFutureKey(response.getDestination(), messageId, remoteAddress.getAddressIndex()); ResponseFuture responseFuture = createInstance(futureMap, futureKey); responseHandler.channelRead0(null, response); assertEquals(response, responseFuture.get(1, TimeUnit.SECONDS)); } @Test(expected = IllegalArgumentException.class) public void testChannelRead0_futureNotFound() { Response response = new Response(1234, remoteAddress); responseHandler.channelRead0(null, response); } }
35.814815
114
0.775595
83589b04b3f9bc7f463ff1534ce878e9603fc4f6
1,829
tsx
TypeScript
src/Slices/DesiredStateResourceDetails/UI/DetailsProvider.test.tsx
inmanta/web-console
0cab0e3a6c65ea578b3ab29f0c0998762946ae44
[ "Apache-2.0" ]
null
null
null
src/Slices/DesiredStateResourceDetails/UI/DetailsProvider.test.tsx
inmanta/web-console
0cab0e3a6c65ea578b3ab29f0c0998762946ae44
[ "Apache-2.0" ]
1,201
2021-11-24T14:50:56.000Z
2022-03-31T17:56:51.000Z
src/Slices/DesiredStateResourceDetails/UI/DetailsProvider.test.tsx
inmanta/web-console
0cab0e3a6c65ea578b3ab29f0c0998762946ae44
[ "Apache-2.0" ]
null
null
null
import React from "react"; import { MemoryRouter } from "react-router-dom"; import { render, screen } from "@testing-library/react"; import { StoreProvider } from "easy-peasy"; import { act } from "react-dom/test-utils"; import { Either } from "@/Core"; import { getStoreInstance, QueryManagerResolver, QueryResolverImpl, } from "@/Data"; import { DeferredApiHelper, dependencies, StaticScheduler } from "@/Test"; import { DependencyProvider } from "@/UI/Dependency"; import * as VersionedResourceDetails from "@S/DesiredStateResourceDetails/Data/Mock"; import { DetailsProvider } from "./DetailsProvider"; function setup() { const store = getStoreInstance(); const scheduler = new StaticScheduler(); const apiHelper = new DeferredApiHelper(); const queryResolver = new QueryResolverImpl( new QueryManagerResolver(store, apiHelper, scheduler, scheduler) ); const component = ( <MemoryRouter> <DependencyProvider dependencies={{ ...dependencies, queryResolver }}> <StoreProvider store={store}> <DetailsProvider version="123" resourceId="abc" /> </StoreProvider> </DependencyProvider> </MemoryRouter> ); return { component, apiHelper, scheduler }; } test("GIVEN DesiredStateResourceDetails page WHEN api returns details THEN shows details", async () => { const { component, apiHelper } = setup(); render(component); expect(apiHelper.pendingRequests).toEqual([ { method: "GET", url: `/api/v2/desiredstate/123/resource/abc`, environment: "env", }, ]); await act(async () => { await apiHelper.resolve(Either.right({ data: VersionedResourceDetails.a })); }); expect( screen.getByRole("generic", { name: "ResourceDetails-Success" }) ).toBeVisible(); expect(screen.getByText("requires")).toBeVisible(); });
31.534483
104
0.694369
ddbbee37fe851629088ccfb06c73a0bf315ceedb
447
java
Java
LACCPlus/Hadoop/2644_1.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
LACCPlus/Hadoop/2644_1.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
LACCPlus/Hadoop/2644_1.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
//,temp,HistoryServerFileSystemStateStoreService.java,201,211,temp,ZKRMStateStore.java,1140,1152 //,3 public class xxx { @Override public void removeTokenMasterKey(DelegationKey key) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Removing master key " + key.getKeyId()); } Path keyPath = new Path(tokenKeysStatePath, TOKEN_MASTER_KEY_FILE_PREFIX + key.getKeyId()); deleteFile(keyPath); } };
27.9375
96
0.709172
ff931001fd3276c447a35be0ad2c4ac9072f8ef2
477
py
Python
persons/models.py
jrosczyk/addressbook
fab640a3398b99fd1a2fe376b21707fb3457a731
[ "MIT" ]
null
null
null
persons/models.py
jrosczyk/addressbook
fab640a3398b99fd1a2fe376b21707fb3457a731
[ "MIT" ]
2
2021-04-08T21:56:11.000Z
2021-09-22T19:41:23.000Z
persons/models.py
jrosczyk/addressbook
fab640a3398b99fd1a2fe376b21707fb3457a731
[ "MIT" ]
null
null
null
from django.db import models from phone_field import PhoneField # Create your models here. class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=254) phone = PhoneField(help_text='Contact phone number') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.first_name + ' ' + self.last_name
31.8
53
0.786164
84bb7f50be52c95fe4362698a4fcb538a2f5113c
6,113
cs
C#
Lazurite/LazuriteUI.Windows.Main/Statistics/StatisticsMainView.xaml.cs
noant/Pyrite2
f8575b9de67a86cb28040c8db34052900a726641
[ "Apache-2.0" ]
55
2018-09-27T09:49:32.000Z
2021-09-30T06:32:14.000Z
Lazurite/LazuriteUI.Windows.Main/Statistics/StatisticsMainView.xaml.cs
noant/Pyrite2
f8575b9de67a86cb28040c8db34052900a726641
[ "Apache-2.0" ]
6
2018-03-05T12:28:37.000Z
2019-05-12T15:44:37.000Z
Lazurite/LazuriteUI.Windows.Main/Statistics/StatisticsMainView.xaml.cs
noant/Pyrite2
f8575b9de67a86cb28040c8db34052900a726641
[ "Apache-2.0" ]
4
2018-09-27T17:34:09.000Z
2019-09-09T22:06:45.000Z
using Lazurite.IOC; using Lazurite.Logging; using Lazurite.MainDomain; using Lazurite.MainDomain.Statistics; using Lazurite.Scenarios.ScenarioTypes; using LazuriteUI.Icons; using LazuriteUI.Windows.Controls; using LazuriteUI.Windows.Main.Common; using LazuriteUI.Windows.Main.Statistics.Settings; using LazuriteUI.Windows.Main.Statistics.Views; using System; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace LazuriteUI.Windows.Main.Statistics { /// <summary> /// Логика взаимодействия для StatisticsMainView.xaml /// </summary> [LazuriteIcon(Icon.GraphLine)] [DisplayName("Статистика")] public partial class StatisticsMainView : Grid { private static readonly IStatisticsManager StatisticsManager = Singleton.Resolve<IStatisticsManager>(); private static readonly ScenariosRepositoryBase ScenariosRepository = Singleton.Resolve<ScenariosRepositoryBase>(); private static readonly UsersRepositoryBase UsersRepository = Singleton.Resolve<UsersRepositoryBase>(); private static readonly ScenarioActionSource SystemActionSource = new ScenarioActionSource(UsersRepository.SystemUser, ScenarioStartupSource.System, ScenarioAction.ViewValue); private static readonly ILogger Log = Singleton.Resolve<ILogger>(); private IStatisticsView _currentView; private StatisticsFilter _filter = StatisticsFilter.Empty; public StatisticsMainView() { InitializeComponent(); listItems.SelectionChanged += ListItemsView_SelectionChanged; datesRangeView.SelectionChanged += async (o, e) => await Refresh(); Loaded += async (o, args) => { using (MessageView.ShowLoad("Загрузка информации о статистике...")) { try { var registrationInfo = await StatisticsManager.GetRegistrationInfo(ScenariosRepository.Scenarios); var registered = await Task.WhenAll( ScenariosRepository.Scenarios .Where(x => (x.GetIsAvailable() || !(x is RemoteScenario)) && registrationInfo.IsRegistered(x.Id)) .Select(x => StatisticsManager.GetStatisticsInfoForScenario(x, SystemActionSource))); datesRangeView.Min = registered.Any() ? registered.Min(x => x.Since) : DateTime.Now; datesRangeView.Max = DateTime.Now; datesRangeView.DateSelectionItem = new Common.DateSelectionItem(DateSelection.Last24Hours); } catch (Exception e) { Log.Error("Ошибка во время загрузки статистики", e); } } }; Unloaded += (o, e) => (_currentView as IDisposable)?.Dispose(); } private void BtSettings_Click(object sender, RoutedEventArgs e) { StatisticsScenariosView.Show(); } private void AppendView(IStatisticsView view) { if (_currentView?.GetType() != view.GetType()) { _currentView = view; view.NeedItems = async (filter) => { _filter = filter; await Refresh(); }; viewHostControl.Content = view; } } private async Task Refresh() { if (_currentView == null) { AppendView(new DiagramView()); } else { var dateSince = datesRangeView.DateSelectionItem.Start; var dateTo = datesRangeView.DateSelectionItem.End; using (MessageView.ShowLoad("Загрузка информации о статистике...")) { try { var registrationInfo = await StatisticsManager .GetRegistrationInfo( ScenariosRepository .Scenarios .Where(z => _filter.All || (_filter.ScenariosIds?.Contains(z.Id) ?? false)) .ToArray()); var statisticScenariosInfos = await Task.WhenAll( ScenariosRepository .Scenarios .Where(x => (x.GetIsAvailable() || !(x is RemoteScenario)) && registrationInfo.IsRegistered(x.Id)) .Select(x => StatisticsManager.GetStatisticsInfoForScenario(x, SystemActionSource))); var items = await Task.WhenAll( statisticScenariosInfos .Select(x => StatisticsManager.GetItems(x, dateSince, dateTo, SystemActionSource))); _currentView.RefreshItems(items, dateSince, dateTo); } catch (Exception e) { Log.Error("Ошибка во время загрузки статистики", e); } } } } private void ListItemsView_SelectionChanged(object sender, RoutedEventArgs e) { if (listItems.SelectedItem == btTableView) { AppendView(new StatisticsTableView()); } else if (listItems.SelectedItem == btPieView) { AppendView(new PieDiagramView()); } else if (listItems.SelectedItem == btGeolocationView) { AppendView(new GeolocationView()); } else { AppendView(new DiagramView()); } } } }
39.694805
183
0.535743
8c4406d816e98354ed5f91a58171894d799ef60c
115
sql
SQL
src/test/resources/sql/insert/8e1cc98e.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
66
2018-06-15T11:34:03.000Z
2022-03-16T09:24:49.000Z
src/test/resources/sql/insert/8e1cc98e.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
13
2019-03-19T11:56:28.000Z
2020-08-05T04:20:50.000Z
src/test/resources/sql/insert/8e1cc98e.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
28
2019-01-05T19:59:02.000Z
2022-03-24T11:55:50.000Z
-- file:subselect.sql ln:308 expect:true insert into numeric_table values (1), (1.000000000000000000001), (2), (3)
38.333333
73
0.73913
e0065b42ce270fdd12509ac3cc9eb29538330d14
2,683
php
PHP
resources/views/notes/index.blade.php
maksenajeit33/Notes_app
5fadce0759c2a3c54ead6de6767907bb16b39b34
[ "MIT" ]
null
null
null
resources/views/notes/index.blade.php
maksenajeit33/Notes_app
5fadce0759c2a3c54ead6de6767907bb16b39b34
[ "MIT" ]
null
null
null
resources/views/notes/index.blade.php
maksenajeit33/Notes_app
5fadce0759c2a3c54ead6de6767907bb16b39b34
[ "MIT" ]
null
null
null
@extends('layouts.app') @section('content') <div class="container"> <div class="jumbotron container"> <h1>All Notes!</h1> <hr> <a class="btn btn-primary btn-lg" href="{{route('notes.create')}}" role="button">Create note</a> </div> @if ($message = Session::get('success')) <div class="alert alert-info" role="alert"> {{$message}} </div> @endif @if (count($notes)) <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Title</th> <th scope="col">Created at</th> <th scope="col">Actions</th> </tr> </thead> <tbody> @php $i = 0; @endphp @foreach ($notes as $item) <tr> <th scope="row">{{++$i}}</th> <td>{{$item->title}}</td> <td>{{$item->created_at->diffForhumans()}}</td> <td> <a href="{{route('notes.edit', $item->id)}}" class="btn btn-info">Edit</a> <a href="{{route('notes.show', $item->id)}}" class="btn btn-success">Show</a> <form action="{{route('notes.destroy', $item->id)}}" method="POST" style="display:inline"> @csrf @method('DELETE') <button type="submit" class="btn btn-danger">Delete</button> </form> </td> </tr> @endforeach </tbody> </table> {{-- PAGINATION --}} @if ($notes->hasPages()) <nav aria-label="Page navigation example"> <ul class="pagination justify-content-center"> @if ($notes->onFirstPage()) <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1" aria-disabled="true">Previous</a> </li> @else <li class="page-item"> <a class="page-link" href="{{ $notes->previousPageUrl() }}">Previous</a> </li> @endif @if ($notes->hasMorePages()) <li class="page-item"><a class="page-link" href="{{ $notes->nextPageUrl() }}">Next</a></li> @else <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1" aria-disabled="true">Next</a> </li> @endif </ul> </nav> @endif @else <div class="alert alert-warning container" role="alert"> There is no note! </div> @endif </div> @endsection
32.325301
110
0.447633
852345c7d33a2967b6f1b8324fe7ab3b20b9e032
1,002
cs
C#
Amazon.ApplicationLoadBalancer.Identity.AspNetCore.Tests/TestStartup.cs
rwarr627/aws-alb-identity-aspnetcore
9e8cf7839edbd6d83aa25f1fb69b6448062708a1
[ "Apache-2.0" ]
6
2019-12-19T13:12:46.000Z
2021-02-17T12:41:26.000Z
Amazon.ApplicationLoadBalancer.Identity.AspNetCore.Tests/TestStartup.cs
rwarr627/aws-alb-identity-aspnetcore
9e8cf7839edbd6d83aa25f1fb69b6448062708a1
[ "Apache-2.0" ]
1
2020-03-20T15:00:14.000Z
2020-03-20T15:00:14.000Z
Amazon.ApplicationLoadBalancer.Identity.AspNetCore.Tests/TestStartup.cs
rwarr627/aws-alb-identity-aspnetcore
9e8cf7839edbd6d83aa25f1fb69b6448062708a1
[ "Apache-2.0" ]
6
2019-12-08T20:19:30.000Z
2021-09-02T17:56:55.000Z
namespace Amazon.ApplicationLoadBalancer.Identity.AspNetCore.Tests { using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; public class TestStartup { public void ConfigureServices(IServiceCollection services) { services .AddLogging() .AddSingleton(new ALBIdentityMiddlewareOptions { MaxCacheSizeMB = 10, MaxCacheLifetime = TimeSpan.FromHours(1), ValidateTokenSignature = true, ValidateTokenLifetime = false }); } public void Configure(IApplicationBuilder app, IHostingEnvironment host) { app .UseMiddleware<ALBIdentityMiddleware>() .Run(async _ => await _.Response.WriteAsync(_.User.Identity.Name)); } } }
31.3125
83
0.592814
3372e0775975711dc816f044e24f83a2c01f1ac3
9,268
asm
Assembly
Transynther/x86/_processed/AVXALIGN/_ht_zr_/i7-7700_9_0xca_notsx.log_21829_1315.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/AVXALIGN/_ht_zr_/i7-7700_9_0xca_notsx.log_21829_1315.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/AVXALIGN/_ht_zr_/i7-7700_9_0xca_notsx.log_21829_1315.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r13 push %r8 push %rcx push %rdi push %rdx push %rsi lea addresses_UC_ht+0x99a7, %rsi xor %r10, %r10 movb $0x61, (%rsi) nop nop nop nop add $60807, %rsi lea addresses_A_ht+0x166a7, %r10 cmp %r11, %r11 mov (%r10), %esi sub $23505, %rsi lea addresses_normal_ht+0x6537, %r11 clflush (%r11) nop nop inc %r8 mov (%r11), %dx nop lfence lea addresses_WC_ht+0x73a7, %rsi lea addresses_normal_ht+0x21a7, %rdi nop nop lfence mov $93, %rcx rep movsq nop nop nop nop dec %rcx lea addresses_D_ht+0x12ba7, %rsi lea addresses_A_ht+0x1039b, %rdi clflush (%rsi) nop nop nop add $17297, %rdx mov $8, %rcx rep movsw nop nop nop nop nop lfence lea addresses_WT_ht+0x1ebe7, %rsi lea addresses_UC_ht+0x4ba7, %rdi nop nop nop add $37498, %r13 mov $9, %rcx rep movsq nop sub $26417, %rdx lea addresses_WT_ht+0x1454b, %rsi lea addresses_A_ht+0x18d27, %rdi nop nop nop nop cmp $32207, %r8 mov $104, %rcx rep movsb nop nop nop nop nop cmp $53445, %rsi lea addresses_A_ht+0x1eaf0, %rsi lea addresses_UC_ht+0x1d88f, %rdi nop nop nop and %r11, %r11 mov $11, %rcx rep movsl nop nop cmp %rcx, %rcx lea addresses_normal_ht+0xb7a7, %rsi lea addresses_WC_ht+0xf90f, %rdi nop nop add %rdx, %rdx mov $32, %rcx rep movsw nop cmp %r8, %r8 lea addresses_UC_ht+0x187d3, %r13 xor $10577, %rsi movw $0x6162, (%r13) nop nop nop nop nop sub %rcx, %rcx lea addresses_D_ht+0x17faf, %rdi nop nop nop nop cmp %r11, %r11 movl $0x61626364, (%rdi) nop nop add %rdx, %rdx lea addresses_D_ht+0xdfa7, %r10 nop nop cmp %r8, %r8 mov (%r10), %esi cmp %rcx, %rcx lea addresses_D_ht+0x1b5a7, %rsi nop nop nop nop xor %r13, %r13 movl $0x61626364, (%rsi) nop nop nop nop nop xor $61733, %r8 lea addresses_UC_ht+0xdfa7, %rsi nop nop nop add $31684, %rcx and $0xffffffffffffffc0, %rsi movaps (%rsi), %xmm4 vpextrq $0, %xmm4, %r10 nop nop nop nop sub %r10, %r10 pop %rsi pop %rdx pop %rdi pop %rcx pop %r8 pop %r13 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r15 push %r8 push %rax push %rbx push %rdi // Store lea addresses_D+0xc4d4, %r12 nop nop nop nop xor %rdi, %rdi mov $0x5152535455565758, %rax movq %rax, %xmm6 movups %xmm6, (%r12) nop xor $37534, %rdi // Store lea addresses_RW+0x661f, %r15 clflush (%r15) nop inc %r12 movb $0x51, (%r15) and %rax, %rax // Load lea addresses_normal+0x1ab27, %r15 nop and %rbx, %rbx mov (%r15), %rax nop and $9517, %r8 // Store mov $0x3a7, %r15 nop nop nop nop sub %rbx, %rbx movw $0x5152, (%r15) nop nop nop nop nop xor $11092, %r15 // Store lea addresses_RW+0x77a7, %r8 clflush (%r8) nop nop cmp %r12, %r12 mov $0x5152535455565758, %r10 movq %r10, (%r8) nop and $32219, %r12 // Store mov $0x3a7, %r8 nop nop nop xor $12525, %rdi movw $0x5152, (%r8) nop nop nop nop nop cmp $48309, %rbx // Store mov $0x1d3abf00000003b3, %r10 nop nop nop nop and $20279, %rbx mov $0x5152535455565758, %rax movq %rax, (%r10) nop nop dec %rax // Faulty Load mov $0x3a7, %rbx nop nop nop dec %rdi vmovaps (%rbx), %ymm6 vextracti128 $0, %ymm6, %xmm6 vpextrq $1, %xmm6, %r8 lea oracles, %rbx and $0xff, %r8 shlq $12, %r8 mov (%rbx,%r8,1), %r8 pop %rdi pop %rbx pop %rax pop %r8 pop %r15 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0, 'same': False, 'type': 'addresses_P'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0, 'same': False, 'type': 'addresses_D'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 1, 'same': False, 'type': 'addresses_RW'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 4, 'same': False, 'type': 'addresses_normal'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0, 'same': True, 'type': 'addresses_P'}, 'OP': 'STOR'} {'dst': {'NT': True, 'AVXalign': False, 'size': 8, 'congruent': 7, 'same': False, 'type': 'addresses_RW'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0, 'same': True, 'type': 'addresses_P'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 1, 'same': False, 'type': 'addresses_NC'}, 'OP': 'STOR'} [Faulty Load] {'src': {'NT': True, 'AVXalign': True, 'size': 32, 'congruent': 0, 'same': True, 'type': 'addresses_P'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'NT': False, 'AVXalign': True, 'size': 1, 'congruent': 7, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 6, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 4, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 8, 'same': True, 'type': 'addresses_WC_ht'}, 'dst': {'congruent': 8, 'same': True, 'type': 'addresses_normal_ht'}, 'OP': 'REPM'} {'src': {'congruent': 11, 'same': False, 'type': 'addresses_D_ht'}, 'dst': {'congruent': 2, 'same': True, 'type': 'addresses_A_ht'}, 'OP': 'REPM'} {'src': {'congruent': 5, 'same': False, 'type': 'addresses_WT_ht'}, 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM'} {'src': {'congruent': 2, 'same': False, 'type': 'addresses_WT_ht'}, 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM'} {'src': {'congruent': 0, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM'} {'src': {'congruent': 10, 'same': False, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 3, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 1, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 3, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 9, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 9, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'STOR'} {'src': {'NT': True, 'AVXalign': True, 'size': 16, 'congruent': 10, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'00': 21823, '48': 6} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
29.993528
2,999
0.651165
14ca315f68109ba57e9c41f0d097b3ac04362e25
306,482
ts
TypeScript
packages/stentor-handler/src/HandlerGraph/__test__/assets/handlers.ts
stentorium/stentor
f49b51e8b4f82012d1ac8ddd15af279bd4619229
[ "Apache-2.0" ]
2
2019-12-30T19:23:17.000Z
2021-07-06T02:47:39.000Z
packages/stentor-handler/src/HandlerGraph/__test__/assets/handlers.ts
stentorium/stentor
f49b51e8b4f82012d1ac8ddd15af279bd4619229
[ "Apache-2.0" ]
74
2020-01-07T00:25:16.000Z
2022-02-23T04:06:56.000Z
packages/stentor-handler/src/HandlerGraph/__test__/assets/handlers.ts
stentorium/stentor
f49b51e8b4f82012d1ac8ddd15af279bd4619229
[ "Apache-2.0" ]
1
2021-01-01T08:57:23.000Z
2021-01-01T08:57:23.000Z
/*! Copyright (c) 2019, XAPPmedia */ /* tslint:disable:no-magic-numbers */ export const handlers: any = [ { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T17:58:07.293Z", name: "Al Is Telling The Truth", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "AlIsTellingTheTruthIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.929001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["Al {is telling the truth|}", "Al truth"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T18:50:53.742Z", name: "Blue Card", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "BlueCardIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.931001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{I choose|I want|} {the|} blue {card|}"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T18:35:36.174Z", name: "BlueDoor", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "BlueDoorIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.930001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{Pick|} {the|} blue {door|}"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T19:02:33.001Z", name: "Boat Trip To Nowhere", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "BoatTripToNowhereIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.930001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["Boat trip {to nowhere|} {first|}"] }, { content: { CancelIntent: [ { name: "Saved your spot", outputSpeech: { displayText: "Ok. I’ve saved your spot in the adventure for next time. There are plenty more Goosebumps left!", ssml: "Ok. I’ve saved your spot in the adventure for next time. There are plenty more Goosebumps left!" } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T15:03:12.726Z", name: "Global Cancel", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "CancelIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.935001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T15:18:15.225Z", name: "Cannon", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "CannonIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.932001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{I choose|} {the|} cannon"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T19:29:18.608Z", name: "CheckoutMidwayIntent", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "CheckoutMidwayIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.942001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["Midway {please|}", "Checkout {the|} Midway {please|}", "The midway"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T15:32:00.382Z", name: "Choo Choo", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "ChooChooIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.934001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{I choose|} {the|} choo choo", "{I choose|} {the|} chew chew"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T15:32:43.284Z", name: "Choose Blue ", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "ChooseBlueIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.941001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{I choose|} blue {please|thanks|}"] }, { action: [], helpData: [], responseData: [], slots: [ { name: "number", type: "STENTOR.NUMBER", isNew: true } ], createdAt: "2018-07-17T13:04:05.692Z", name: "Claps Number Intent", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "ClapsNumberIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.946001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["i got {-|number} claps", "{-|number} claps", "i only got {-|number} claps"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T15:59:48.303Z", name: "Climb The Fence Intent", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "ClimbTheFenceIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.962001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["Climb the fence", "fence", "climb", "climb the fence please"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T19:31:10.528Z", name: "Decide To Be Rescued", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "DecideToBeRescuedIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.937001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: [ "Keep yelling", "yell", "I keep yelling", "yell out", "call out", "keep", "i call out", "calling out" ] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T19:31:19.512Z", name: "Decide To Swim For It", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "DecideToSwimForItIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.971001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["Swim for it", "Swim to it", "safety", "{i|} swim {to|for|} safety", "swim", "swimming"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T20:12:51.360Z", name: "EscapeThroughTheDoor", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "EscapeThroughTheDoorIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.945001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["escape {through|} {the|} {door|} {down|} {the|} {hall|}"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T18:31:26.813Z", name: "FindYourOwnWayOut", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "FindYourOwnWayOutIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.945001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["Find your own way {out|}", "Own way"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T18:17:24.143Z", name: "Flap Your Arms", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "FlapYourArmsIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.964001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["Flap your arms", "Try to fly", "Fly", "Flap your arms to try and fly", "flap"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T17:26:43.930Z", name: "FollowPatty", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "FollowPattyIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.946001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["Follow {Patty|}"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T18:30:37.082Z", name: "FollowTheDwarf", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "FollowTheDwarfIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.948001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{Follow|} the dwarf", "Follow"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T16:00:54.303Z", name: "Go Home Intent", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "GoHomeIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.948001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["go home", "home", "go home please", "home please"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T17:56:49.883Z", name: "Grab the side of the bridge", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "GrabTheSideOfTheBridgeIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.948001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{make a|} grab for {the|} side of the bridge", "bridge", "grab", "grab bridge"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T14:36:52.316Z", name: "HalloweenExpress", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "HalloweenExpressIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.949001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["Halloween {Express|} {way|}", "Halloween"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T17:51:47.780Z", name: "Haunted House", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "HauntedHouseIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.951001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{the|} haunted house", "house"] }, { content: { HelpMidStoryHandler: [ { name: "Help Mid Story", outputSpeech: { displayText: "It looks like you need some help. Carnival of Horror is a choose your own adventure tale. Each decision you make will determine your scare. Throughout the carnival you can say repeat to hear the previous passage or game options again. You can say stop to end your session and pick it back up later. To start a new adventure from the beginning, just say start over. When it’s time to make a decision, you’ll hear this sound. Are you ready to get back to the Carnival?", ssml: "It looks like you need some help. Throughout the carnival you can say repeat to hear the previous passage or game options again. You can say stop to end your session and pick it back up later. To start a new adventure from the beginning, just say start over. Are you ready to get back to the Carnival?\n" }, reprompt: { ssml: "Are you ready to get back to the Carnival?", displayText: "Are you ready to get back to the Carnival?" } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T15:05:59.711Z", name: "Help Mid Story", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "HelpMidStoryHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.952001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { HelpNewStoryHandler: [ { name: "Help New Story", outputSpeech: { displayText: "It looks like you need some help. Carnival of Horror is a choose your own adventure tale. Each decision you make will determine your scare. Throughout the carnival you can say repeat to hear the previous passage or game options again. You can say stop to end your session and pick it back up later. To start a new adventure from the beginning, just say start over. When it’s time to make a decision, you’ll hear this sound. Are you ready to get started?", ssml: "It looks like you need some help. Throughout the carnival you can say repeat to hear the previous passage or game options again. You can say stop to end your session and pick it back up later. To start a new adventure from the beginning, just say start over. Are you ready to get started?" }, reprompt: { ssml: "Are you ready to get started?" } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T14:43:15.717Z", name: "Help New Story", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "HelpNewStoryHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.955001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T18:15:03.489Z", name: "Hop Out oF the Car", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "HopOutOFTheCarIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.969001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["hop out", "hop out of the car", "out of the car", "get out", "hop", "car"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T18:24:36.063Z", name: "House of Horrors", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "HouseOfHorrorsIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.950001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{ready for the|} house of horrors {first|}"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T16:09:19.083Z", name: "JumpOut", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "JumpOutIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.956001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["jump {out|}"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T20:45:10.542Z", name: "Kick The Doctor", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "KickTheDoctorIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.957001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{try to|} Kick {the doctor|}"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T14:07:54.828Z", name: "Knock all of the ships down", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "KnockAllOfTheShipsDownIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.969001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{i|we|he|she|} knocked all {of the|} ships {down|off|}"] }, { content: { LaunchRequest: [ { name: "New User - Success", outputSpeech: { displayText: "Welcome to Goosebump’s Carnival of Horrors. This is no ordinary carnival. Here you’ll find awesome rides. Exciting games of chance. And the weirdest Freak Show ever. This scary adventure is all about you. You decide what will happen. And you decide how terrifying the scares will be. You make the choices. If you make the right choices, you’ll escape from the spine-tingling Carnival of Horrors in time. If you make the wrong choice … BEWARE! So take a long, deep breath, cross your fingers. Are you ready to give yourself Goosebumps?", ssml: 'Welcome to Goosebump’s Carnival of Horrors. This is no ordinary carnival. Here you’ll find awesome rides. Exciting games of chance. And the weirdest Freak Show ever.\nThis scary adventure is all about you. You decide what will happen. And you decide how terrifying the scares will be. You make the choices. If you make the right choices, you’ll escape from the spine-tingling Carnival of Horrors in time. If you make the wrong choice … BEWARE!\nSo take a long,<break time="500ms"/> deep breath, cross your fingers. Are you ready to give yourself Goosebumps?\n' }, reprompt: { ssml: "Are you ready to give yourself Goosebumps?", displayText: "Are you ready to give yourself Goosebumps?" } } ] }, forward: { NoIntent: [ { type: "START", intentId: "NotReadyForGoosebumpsHandler" } ], YesIntent: [ { type: "START", intentId: "NewUserPageOnePageTwoHandler" }, { type: "START", intentId: "PageOneAndPageTwoHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T14:19:26.520Z", name: "Launch Request", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "LaunchRequest", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.969001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T14:06:21.586Z", name: "Missed", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "MissIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.957001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{I|we|he|she|} {miss|missed} {it|the ship}"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-10T13:28:10.223Z", name: "Mission to Mars", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "MissionToMarsIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.965001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["mission to mars", "i choose mission to mars"] }, { content: { MissionToMarsPageSeventyTwoHandler: [ { outputSpeech: { ssml: "<!-- Page 72-->\n \nYou step up to the Mission to Mars booth. A woman in a space suit motions you inside a gate. You pass through and find yourself in the middle of a courtyard that looks just like a miniature launching site — complete with its own rocket!\n \n“Security check,” the lady says as she presses your hand onto a screen.\n \n“So how does this game work?” you ask.\n \nThe space lady points to a pyramid of five stacked bottles that look like rocket ships. Then she hands you a ball. “Take this meteor and knock all of the rockets off the platform.”\n \nThis shouldn’t be too hard, you think.\n \n“If you get them all, you can go,” she says.\n \n<!-- Page 18 -->\n \nThe space lady slowly circles you as she sizes you up from head to toe. “Hmmmm, I’ve never seen anyone win this before.”\n \nShe snaps her fingers and two enormous guards appear. They stand on each side of you while you get ready to throw. Something tells you that what Big Al said about having to survive might be true.\n \n<!-- Page 134 -->\n \nYou stretch your arm to loosen it up. If you want to escape, you know you need to do this. No pressure!\n \nYou go into your windup. Take aim. And throw.\n\nDid you knock all of the ships down or did you miss?" }, reprompt: { ssml: "Did you knock all of the ships down or did you miss?" } } ] }, forward: { KnockAllOfTheShipsDownIntent: [ { intentId: "PageFiftyThreeAndFourtyHandler" } ], MissIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageTwentytwoHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T19:44:56.032Z", name: "Page 72 and 18 and 134 - Mission to Mars", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "MissionToMarsPageSeventyTwoHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.970001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T16:59:58.606Z", name: "MondayWednesdsayFridaySaturday", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "MondayWednesdsayFridaySaturdayIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.963001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["Monday", "Wednesday", "Friday", "Saturday"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T15:06:48.665Z", name: "More Than 8", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "MoreThanEightIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.966001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: [ "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty" ] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T14:36:59.290Z", name: "MountainKing", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "MountainKingIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.964001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["Mountain {King|} {way|}"] }, { content: { NewUserPageOnePageTwoHandler: [ { name: "New User + Page 1 + Page 2", outputSpeech: { ssml: "Great! Here's how to play. You'll be part of a story where you'll need to make decisions to find out what happens next. I'll ask you a question when it's time for you to decide. You can ask me to repeat something if you need to hear it again, or you can ask for help and I'll tell you about your options. Let's get started.\n \n<!-- Page 1 -->\n \n“What do you want to do?”\n \n“I don’t know, Patty. What do you want to do?”\n \n“Not fair, Brad. I asked you first.”\n \nPatty and Brad. Your two best friends. Arguing. As usual.\n \nIt’s the last week of August. And Patty and Brad haven’t stopped fighting since your summer vacation started.\n \nPatty likes being bossy. You don’t mind, though. It’s no big deal.\n \nIt’s hard to win a fight with her anyway. You don’t know why Brad even tries. You guess it’s because he doesn’t want to look like a wimp.\n \n“There’s nothing to do. I guess I’ll just go home,” Brad says. He shoves his hands in his pockets. Then his shoulders slump and he sort of shrivels up. You guess Brad is kind of a wimp — even if he is your best friend.\n \n“You’re so boring, Brad,” Patty complains. Whenever Patty complains, her freckles really pop out. Now there are about a million of them spread across her face.\n \n“Hey! I know what we should do!” Patty suddenly bursts out.\n \n<!-- Page 2 -->\n \n“Let’s bike over to Bennet’s Field and watch them set up the carnival!”\n \n“I don’t know,” you answer. “It’s getting dark, and Mom said I have to be in by nine.”\n \n“It’s only a quick bike ride,” Brad says. “Are you some kind of wimp?”\n \nBrad calling you a wimp? You can’t believe it!\n \n“Okay. Okay,” you agree. “But if it’s as bad as last year, there won’t be much to see. Don’t you remember the main attraction?” you remind them. “The ride they called Terror Track? It turned out to be a baby choo-choo train that circled around and around and around.”\n \nIt doesn’t matter what you say. Patty’s made up her mind. You’re going to ride over to the carnival.\n \nA hot, humid breeze blows in your face as you pedal along. Patty’s in the lead. No surprise. And Brad’s puffing behind you.\n \nIt’s dark by the time you reach Bennet’s Field.\n \nYou and your friends drop your bikes in the grass and race across the moonlit field, toward the huge wooden fence that surrounds the carnival.\n \n<!-- Insert carnival sound Fx -->\n \nWhat is your favorite carnival ride? " }, reprompt: { displayText: "What is your favorite carnival ride? " } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", intentId: "PageThreeHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-11T21:13:25.743Z", name: "New User and Page 1 and 2", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "NewUserPageOnePageTwoHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.964001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T14:28:12.163Z", name: "NoIntent", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "NoIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.965001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["no", "no thanks"] }, { content: { NotReadyForGoosebumpsHandler: [ { name: "Not Ready For Goosebumps", outputSpeech: { displayText: "No problem, sounds you like aren't ready yet. Come back any time.", ssml: "No problem, sounds you like aren't ready yet. Come back any time." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T14:46:53.258Z", name: "Not Ready For Goosebumps", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "NotReadyForGoosebumpsHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.969001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { action: [], helpData: [], responseData: [], slots: [ { name: "number", type: "STENTOR.NUMBER" } ], createdAt: "2018-07-15T18:28:41.711Z", name: "NumberIntent", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "NumberIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.969001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{-|number}"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-10T14:42:29.083Z", name: "One - Three - Two", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "OneThreeTwoIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.965001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["one three two", "one hundred {and|} thirty two"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T17:17:05.995Z", name: "Option A", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "OptionAIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.966001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["A", "Option A", "karru marri odonna loma molonu karrano", "first choice", "choice a"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T17:17:12.519Z", name: "Option B", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "OptionBIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.964001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["B", "option b", "choice b", "second choice", "oopah lupah dummie dupah"] }, { content: { PageEightyEightAndThirtyTwoHandler: [ { name: "Page 88 and 32", outputSpeech: { ssml: "<!-- Page 88 -->\n \nYou head toward the Boat Trip to Nowhere. At the dock, you spot a stubby guy with long arms slouching against one of the mooring posts. In the strange light of the swamp, his skin shines with an oily, green glow. And his ears and nose are as craggy as tree bark.\n \n“Step right up,” he calls in a gravelly voice.\n \n<!-- Insert motorboat sound Fx -->]\n\nHe pulls one of the motorboats over. It’s red with a silver racing stripe! “You can do fifteen knots in these babies,” he says. “But stay away from the tree stumps.”\n \nYou watch the little man’s sharp green fingernails tearing the mooring rope apart. As soon as the boat is free, you jump in, step on the gas, and roar away from the dock.\n \n<!-- Insert boating sound Fx -->]\n\nThe wind blows hard against your face. You’re flying over the water. This is totally cool! You head for a channel that you see up ahead. Too bad you didn’t notice that sign that reads: TO BOOGER BOG.\n \n<!-- Page 32 -->\n \nYour boat glides through the channel at high speed to Booger Bog. Water sprays up into your face. But soon you have to slow down. Trees have suddenly sprung up all around you. You’re completely surrounded now by their towering trunks.\n \nIn the dark light, their limbs take on the shape of gnarled arms with blackened, bony fingers at the ends. You stare hard at the tree trunks. Could it be? Are they reaching out for you?\n \n<!-- Insert boating sound Fx -->]\n\nYou slowly weave the boat through the twisted trunks and branches. They’ve grown so thick here that you can barely pilot your boat through them.\n \n<!-- Insert tree sound Fx -->]\n\nThe trees rustle as if they’re whispering to each other. Their limbs begin to sway. As you glide carefully through the water, the leaves slap against your face. Slap. Slap. Slap.\n \nYour heart starts hammering away in your chest. This is really scary. Just how far is nowhere? you begin to wonder. \n\n<!-- Insert swipe sound Fx -->]\n\nSomething swipes at your hair!\n \nWhat was that?" }, reprompt: { ssml: "What was that?" } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneOhFiveAndNinetyHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T19:08:07.552Z", name: "Page 88 and 32 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageEightyEightAndThirtyTwoHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.970001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageEightyFiveHandler: [ { name: "Page 85", outputSpeech: { ssml: "<!-- Page 85 -->\n \nThe giant hangs over you, flexing his muscles. He squints at you as if you are a bug — ready to be squashed.\n \n“Did you call me a wimp?” he thunders.\n \nYou are much too scared to answer.\n \nThe giant answers for you. “You’re right. I am a wimp!”\n \nAnd with that, he bends the bars, and you, Patty, and Brad scramble through.\n \n“Follow me,” the giant says. “I know a way out of here.”\n \n“What about the others?” you ask, pointing to the freaks in the cells that line the wall.\n \n“No problem!” Patty yells, grabbing the keys from a hook on the wall. “Here — catch!”\n \nYou quickly unlock all the doors — setting the freaks free!\n \n<!-- Page 126 -->\n \n“Yay! Our hero!” the freaks cheer as they bolt out of their cells.\n \nYou follow the giant through a side exit. And in no time, you’re leading all your new friends to your house.\n \nYou’re sure your parents won’t mind taking them in. After all, how much can an eight foot giant, a snake lady, and a three-headed man eat? Hmmmm. Better not answer that question.\n \nJust be happy that you’ve come to …\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T18:23:48.624Z", name: "Page 85 and 126 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageEightyFiveHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.966001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageEightyFourHandler: [ { name: "Page 84", outputSpeech: { ssml: "<!-- Page 84 -->\n \nBig Al shoves you and your friends into a huge red tent. It seems to be set up for some kind of show. Red carpeted steps lead up to a platform, which sits under a golden arch. The arch twinkles with a thousand colored lights that spell out: FINAL CHALLENGE.\n \nTrumpets blast as people flood into the viewing area. As they march in, they clap their hands and yell, “FI-NAL. FI-NAL.”\n \nBig Al leads you up the carpeted steps. You are standing on the platform now — in front of a shimmering curtain that hangs down from the arch.\n \nThe crowd begins to chant, “SUD-DEN DEATH. SUD-DEN DEATH.”\n \n<!-- Read in prompt voice -->]\n\n What do you think that means?" }, reprompt: { ssml: " What do you think that means?" } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneTwentyThreeAndTwentyFiveHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T17:52:00.831Z", name: "Page 84 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageEightyFourHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.968001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageEightyOneHandler: [ { name: "Page 81 Handler", outputSpeech: { ssml: "<!-- Page 81 -->\n \n“You’re lying!” you yell. “You are a robot.”\n \nYou quickly reach up with both hands and tug at his head. His sharp jaws slash at you. But you’re fast. You hold on firmly and pull!\n \nOh, no! He really is a monster. And he’s not happy.\n \nYou know you’re dead meat, but you have to try one more time. Just to make sure. You give his head one more tug. He laughs. Then he gives your head a tug.\n \nSorry. You were doing so well. But now you’ve gone and lost your head. The only way you’ll be able to face the challenge of the Carnival of Horrors now is to begin another day. At least then — you’ll have a head start.\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T13:31:23.940Z", name: "Page 81 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageEightyOneHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.978001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageEightySevenHandler: [ { name: "Page 87 Handler", outputSpeech: { ssml: "<!-- Page 87 -->\n \nThe man doesn't move. \"We wanted to look around. That’s all. But we’ll leave. Right now.”\n \nHis eyes stare into yours. He clamps both hands down on your shoulders and says, “You’re not going anywhere!”\n \n<!-- Page 4 -->\n \n“Wh-what do you mean?” Brad asks, trembling all over.\n \n“I just had an idea. A great idea,” the man replies. “I want you kids to stay and try out the rides before the grand opening tomorrow.”\n \nPatty’s eyes open wide. “Cool!” she says.\n \n“Are you sure it’s all right with the owner?” you ask.\n \n“I’m Big Al, the manager. And what I say around here goes.”\n \nBig Al digs around in his checkered jacket and pulls out three maps. He hands one to each of you.\n \n“Study them carefully,” he says. “If you have any questions, ask them now.”\n\nAsk Al a question. " }, reprompt: { ssml: "Ask Al a question. " } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageFourHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T19:18:09.563Z", name: "Page 87 & 4 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageEightySevenHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714152.972001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageEightySixHandler: [ { name: "Page 86", outputSpeech: { ssml: "<!-- Page 86 -->\n \n“I don’t know,” you say. “I don’t think we should take any more risks. Especially not in this crazy carnival.”\n \n“Don’t you trust me?” Patty demands. Her eyes flash angrily.\n \nYou glance at Brad. He stares at the ground.\n \n“I just have a bad feeling about this, Patty. Okay?”\n \nBut Patty doesn’t answer. She throws her shoulders back and stands up taller. And taller. And taller.\n \nYou gasp! Patty is growing! She’s nearly ten feet tall!\n \nShe reaches out a long arm and grabs you by the wrist. Her nails dig deep into your skin.\n \nYou can’t move.\n \n<!-- Insert scream sound Fx -->]\n\nYou scream as Patty continues to change. Her skin turns green and lumpy. Horns sprout from her head. And her teeth grow into sharp fangs.\n \nYou remember the horrible monsters on the walls of the slide. Patty has turned into one of them!\n \n“Let me go. Please!” you plead.\n \n“Too bad you didn’t trust me,” she growls. “I can’t have you ruining my plans.” Her nails sink deeper into your flesh.\n \n“Ha-ha-ha!” she cackles. Then she wraps her slimy mouth around your arm and bites down. Hard!\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T17:45:59.392Z", name: "Page 86 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageEightySixHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.915001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageEightyTwoHandler: [ { name: "Page 82", outputSpeech: { ssml: "<!-- Page 82 -->\n \n“Oooopah lupah dummie dupah.” You say the magic words and wait for the dummy to spring to life.\n \nAnd you wait.\n \nAnd you wait.\n \nThe dummy remains the same.\n \nBut something strange is happening to you. What are those feathers sprouting out of your skin? And what’s happening to your feet? Are those claws you see growing out of them?\n \nIs it possible that the magic words are turning you — \n\n<!-- Insert chicken sound Fx -->]\n\nCLUCK — into a — CLUCK — chicken?\n \nThat’s eggs-actly what’s happening.\n\nBrad was wrong. Very wrong!\n \nWell, you laid an egg this time. Let’s hope you won’t be too chicken to open this again and try once more to escape from the Carnival of Horrors.\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T17:19:57.939Z", name: "Page 82 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageEightyTwoHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.918001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageElevenAndThirtyFiveAndThirteenHandler: [ { name: "Page 11 and 35 and 13", outputSpeech: { ssml: "<!-- Page 11 -->\n \nYou’ve decided to help the freaks. As you race down the midway, you spot Brad and Patty.\n \n“Listen, guys,” you tell them, lowering your voice. “We’ve got a problem. A big problem.”\n \nYou take a deep breath and tell them all about Madame Zeno and the blue card.\n \n“So,” you finish saying, “somebody might need our help in the back of the Freak Show.”\n \n“What’s a freak show?” Brad asks nervously.\n \n“Remember the poster we saw when we came in? The one with the three-headed man and the lady with the snake body?” you remind him.\n \nBrad bites down on his lip. “Are they really real?”\n \n“Sure they’re real,” Patty chimes in.\n \n“I don’t know,” Brad says. “It sounds kind of creepy.”\n \n“Well, Madame Zeno said this was my fate. I’m going to help them — whatever they are. Are you guys in?”\n \n“You bet,” Patty answers, her eyes shining with excitement.\n \n“Okay, okay. I’ll go,” Brad mumbles.\n \n“Then let’s hurry!” you exclaim.\n \n<!--Page 35 -->\n \nFive minutes later, the three of you are sneaking down a dark alley. Brad is so frightened, he’s practically walking on top of you.\n \nThe alley is littered with large cardboard boxes and overflowing trash cans. And it smells like dead fish.\n \n“Hey! Quit stepping on my shoe,” you say to Brad.\n \n“I’m not stepping on your shoe,” he shoots back. “I’m not anywhere near your shoe.”\n \nYou glance down. And nearly scream.\n \nBrad’s right. He’s not stepping on you. But about a dozen rats are.\n \n<!--Insert rat sound fx -->\n \nYou shake your foot wildly. The rats scurry off.\n \nBrad catches sight of the rats and tries to bolt.\n \nYou and Patty quickly pull him back.\n \n“Hey! Look!” Patty says, pointing up ahead. “A door!”\n \nOn the door you see a big sign that reads KEEP OUT, so … you go in.\n \n<!--Page 13 -->\n \nThe room is dark, but all around you, you hear hushed moans. “Help us! Help us!”\n \n“We’re in a prison,” Patty says. “And look at the prisoners! They’re weird!”\n \nPatty is right. As your eyes grow accustomed to the darkness, you see cell after cell. Each one holds a strange-looking prisoner. There’s a lady with a snake’s body, and a monster with three heads. A giant nearly bursting out of his cage. And a man who looks like he’s part plant.\n \n“We’re the freakssss,” the Snake Lady says. “Every night when the sssshow endssss, the masssster lockssss ussss up.”\n \n“The master? You mean Big Al is —” you start to say.\n \n“You must help us!” the giant interrupts.\n \n“Sssssssh,” the Snake Lady says. “The master’sssss coming — you musssstn’t be here! Go! That way!” She points to a door down the hall.\n \nDo you escape through the door down the hall or stay and talk to Big Al?" }, reprompt: { ssml: "Do you escape through the door down the hall or stay and talk to Big Al?" } } ] }, forward: { TalkToBigAlIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageSixtyTwoHandler" } ], EscapeThroughTheDoorIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageFourtyEightAndSixtyHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T19:17:36.496Z", name: "Page 11 and 35 and 13", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageElevenAndThirtyFiveAndThirteenHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.915001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageFifteenHandler: [ { name: "Page 15", outputSpeech: { ssml: "<!-- Page 15 -->\n \n<!-- Insert spinning wheel sound Fx --> \n\nRound and round the wheel spins. It finally lands on number 15. NO CHANCE.\n \nNo chance. Does that mean what you think it means?\n \nNo chance at all.\n \nZip.\n \nZero.\n \nNothing.\n \nNada.\n \nNegatory.\n \nYes. That’s exactly what it means. You have met …\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-09T19:46:11.216Z", name: "Page 15 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFifteenHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.916001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageFiftyFourAndEightyThreeHandler: [ { name: "Page 54 and 83 Handler", outputSpeech: { ssml: "<!-- Page 54 -->\n \nYour heart begins to race as the car speeds out of control. You tear through an eerie forest, speed past more cottages — but still you don’t see a way out.\n \nAnd then it comes into view — a service exit!\n \nAll you have to do is stop the car, jump out, and scramble through the fence, and you’ll be free.\n \nFive minutes to midnight!\n \n“Oh, no!” Patty screams. “Quick, turn left! Don’t stop!”\n \n<!-- Page 83 -->\n \nYou squint hard at the road ahead of you — and see why Patty wants you to turn. There they are — the people in the old-fashioned clothes. Only they don’t look the same.\n \nSome have green flesh. Some are deathly white. Their rotting skin hangs from their bones.\n \nAnd they’re all reaching out. Reaching out for you!\n \n“Turn! Turn!” Patty yells.\n \nYou spin the wheel sharply to the left to avoid them. But you can’t dodge the ghostly creature that’s rising above you. He’s ten feet tall — with arms so long that they scrape the ground. His mouth gapes open to reveal hundreds of blackened, rotting teeth.\n \nHe swoops down at you. You turn the steering wheel hard to the right. Too hard — it comes off in your hands!\n \n“Jump!” you cry. “Jump and run! Run!”\n \nThe three of you leap out of the moving car. But are you fast enough? That depends on how good your reflexes are.\n \nWhen I say go, count how many claps you can get before I say stop. Go. Stop.\n \nHow many claps did you get?" }, reprompt: { ssml: "How many claps did you get?" } } ] }, forward: { "ClapsNumberIntent|NumberIntent": [ { type: "START", intentId: "PageOneTwentySevenHandler", slotMatch: { name: "number", value: 8, operation: "<" } }, { type: "START", intentId: "PageSeventyThreeHandler", slotMatch: { name: "number", value: 8, operation: ">=" } } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T14:48:57.641Z", name: "Page 54 and 83 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFiftyFourAndEightyThreeHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.917001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageFiftyNineHandler: [ { outputSpeech: { ssml: "<!-- Page 59 -->\n \nBlue is your favorite color. You turn the blue card over.\n \nThere is a message: Help us! You are our only hope. Hurry to the back door of the freak show. Signed, The Freaks.\n \n“What does this mean?” you ask Madame Zeno. She stares deep into your eyes. Her lips tremble. She leans forward. She’s about to speak.\n \nAnd then the lights go out — \n\n<!-- Insert scream sound fx --> \n\nand a blood-curdling scream rips through the dark!\n \nYou start to bolt for the door when a dim light suddenly flickers. You stare across the table. Madame Zeno is gone!\n \nYou reach out to take the card. And it bursts into red-hot flames! In seconds, the entire tent fills with thick smoke. Flames shoot across the floor. You run for the door.\n \nOutside, you gulp the fresh air. Whew! You made it.\n \nYou glance back. No smoke. No fire. No tent! Everything has disappeared!\n \nDo you help the freaks?" }, reprompt: { ssml: "What should you do now, do you help the freaks??", displayText: "What should you do now, do you help the freaks??" } } ] }, forward: { NoIntent: [ { type: "START", intentId: "PageOneThirteenAndSixteenHandler" } ], YesIntent: [ { type: "START", intentId: "PageElevenAndThirtyFiveAndThirteenHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T18:53:02.993Z", name: "Page 59", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFiftyNineHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.916001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageFiftyOneHandler: [ { name: "Page 51", outputSpeech: { ssml: "<!-- Page 51 -->\n \nYou can’t take on both monsters, so you decide to wait until one of them leaves the room.\n \n<!-- Insert struggle sound fx -->\n\nYou grab hold of Dr. Stone’s hand. He’s a lot stronger than he looks. With one small tug, he pulls you free of the web.\n \nThen he turns to the monsters. “Okay,” he barks. “Adjust the net. It’s time to practice spiking.”\n \nSpiking? What does he mean by that?\n \nThe monsters leap up. They rub their hands together in evil delight. Then they untie the net and head to the back of the room, where two huge poles rest on the floor.\n \nYou close your eyes — and hope that when you open them, you’ll see that this was all a dream. A really bad dream.\n\n<!-- Insert volleyball sound fx -->\n \nBut when you open your eyes, you know it’s not a dream. No — it’s a volleyball game. The net has been tied to the poles — and guess what position you play? That’s right. You’re the ball! Watch out for those two-handed spikes! They can be pretty painful!\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T18:53:30.246Z", name: "Page 51 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFiftyOneHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.916001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageFiftySevenAndOneThirtyFiveHandler: [ { name: "Page 57 and 135", outputSpeech: { ssml: "<!-- Page 57 -->\n \nYou open the blue door and peer through. You’re staring down a long dark passageway. At least you think it’s long. It’s difficult to tell. It’s pitch-black. You don’t know what to do.\n \n“Maybe I should have picked the other door,” you say to yourself. “I’m getting out of here!”\n \nBut the blue door has locked behind you! Now you’re sure you made the wrong choice. But there’s nowhere to go but forward.\n \nYour knees begin to tremble as you inch your way down the dark hallway.\n \nThe passage ends in a bright burst of light. And in front of you, a tall purple mountain rises hundreds of feet into the air.\n \nYou breathe out a long sigh of relief. You’re out of the dark!\n \nYou study the mountain. It looks so real! But cut into its side, you spot a doorway. Above it a brightly painted sign reads: DOOM SLIDE. WILL YOU BE THE ONE TO SLIDE FOREVER?\n \n<!-- Page 135 -->\n \n<!-- Insert door open sound fx --> \n\nYou open the door and climb a steep ramp that curves around and around. It’s cold and dark inside. Halfway up the ramp, you stop. There’s another sign: WARNING! — YOU MAY BE THE ONE TO SLIDE TO YOUR DOOM!\n \nYou continue up the ramp. You finally make it to the top, and find yourself standing on a wide, dimly lit platform. A row of long, curving slides stretches out before you. The slides are numbered from one to ten.\n \nYou think hard. The Doom Slide. You know you’ve heard about it before. But where? Where was it?\n \nAnd then you remember! It was in a GOOSEBUMPS book you read! One Day at HorrorLand.\n \nNow you know you’re in big trouble. Because you remember all about the Doom Slide from the book. You remember that if you pick the wrong slide, you’ll spend the rest of your life sliding and sliding — forever!\n \nPick one and hope it’s not the Doom Slide!\n \nWhich number between 1 and 10 do you choose?" }, reprompt: { ssml: "Which number between 1 and 10 do you choose?" } } ] }, forward: { "SlideNumberIntent|NumberIntent": [ { type: "START", intentId: "PageOneTwentyOneAndSixtyThreeHandler", slotMatch: { name: "number", value: [1, 4, 5], operation: "==" } }, { type: "START", intentId: "PageNinetyFiveHandler", slotMatch: { name: "number", value: [2, 7, 9], operation: "==" } }, { type: "START", intentId: "PageSixtyEightHandler", slotMatch: { name: "number", value: [3, 6, 8, 10], operation: "==" } } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T20:00:57.475Z", name: "Page 57 and 135 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFiftySevenAndOneThirtyFiveHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.921001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: ["shortcut doom slide"] }, { content: { PageFiftySixHandler: [ { name: "Page 56", outputSpeech: { ssml: "<!-- Insert water sound fx -->\n\nYou leap out of the boat. The putrid brown water splashes into your mouth. Gross!\n \nYou swim a few strokes and suddenly find your knees scraping the bottom of the bog. The water here is less than a foot deep. Unbelievable! You were practically inches away from safety the entire time!\n \nSlogging through the brown foam, you wade to shore. Your clothes are dripping wet and smell like a sewer. Well, look at the bright side, you remind yourself. At least you didn’t go down with your boat.\n \nBut your troubles aren’t over yet. You’re standing in a dank, eerie forest that surrounds the lake. \n\n<!-- Insert echo sound fx --> \n\nCreepy screeches echo through the night mist. And you’re totally lost.\n \nThe wind starts to blow. Shivering, you wrap your arms around your shoulders and wonder where your friends are and what they are doing.\n \n<!-- Insert bat sound fx --> \n\nThen — POW! Something black and furry swoops down at you! You duck your head, but it comes at you again and again.\n \nWhat could it be!?" }, reprompt: { ssml: "What could it be!?" } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageThirtySevenAndNinetyThreeHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T19:37:32.746Z", name: "Page 56 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFiftySixHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.920001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageFiftyThreeAndFourtyHandler: [ { outputSpeech: { ssml: '<!-- Page 53 -->\n\n<!-- Insert battle sound fx -->\n\nYou hit them all off the platform! Boy, oh, boy! What a relief.\n \nYou jump up and down. “I won! I won!"\n \nThe two guards grab you and shove you into the space chamber. The door slams shut behind you.\n \n“What are you doing?” you yell. “I won!”\n \nIt’s a clear, narrow tube that rises farther up than you can see.\n \nYou press the chamber-door release, but it’s stuck.\n \nYou try again. It doesn’t budge.\n \nMaybe it’s locked from the outside.\n \n“Hey! I can’t get out!” you yell to the guards. But they simply wave.\n \n“Hey, let me out!” Now you’re mad. “Let me out!”\n \nAll at once the room starts to shake and rattle.\n\n<!-- Insert rocket sound fx --> \n\n RRRRRRRR. The thrust of powerful rocket engines echoes in your ears. It sounds as if you’re being launched into space. But that’s impossible, isn’t it?\n \n<!-- Page 40 -->\n \n<!-- Insert launch sound fx --> \n \n“Five, four, three, two, one. We have liftoff,” a mechanical voice announces.\n \nTo your horror, the rocket blasts off! You’re slammed against the side of the capsule with hurricane force. Seconds later, you’ve left Earth’s atmosphere.\n \nA recorded message comes on: “Congratulations. You won Mission to Mars! Your prize is you get to go—to Mars. We’ll be monitoring your trip and will bring you back in approximately twenty years — with a plus or minus ten-year margin of error in case something goes wrong. But do not worry. Nothing can go wrong … go wrong … go wrong.”\n \nThe end.' } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T14:03:59.443Z", name: "Page 53 and 40", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFiftyThreeAndFourtyHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.916001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageFiftyTwoAndTwentyFourHandler: [ { name: "Page 52 and 24", outputSpeech: { ssml: "<!-_ Page 52 -->\n \n<!-- Insert clock strike sound fx --> \n\nJust as the clock strikes twelve, the train enters a tunnel.\n \nYou hold your breath, wondering what you’ll see when you reach the other end.\n\n<!-- Insert chug sound fx --> \n \nChug. Chug. Chug.\n \nThe choo-choo slowly pulls out of the tunnel — and you are surrounded by carnival workers — everywhere!\n \n<!-- Page 24 -->\n \nCarnival workers. The carnival workers who set up the same rinky-dink carnival you go to every summer.\n \nYou can’t believe your eyes. You must be seeing things!\n \nPatty tries to say something smart, but the only thing she manages is “Huh?”\n \n“Hey, kids!” a worker yells at you. “Get away from that ride. The carnival doesn’t start till tomorrow night.”\n \nYou gaze around in wonder at the faded games, the baby rides, the tacky food stands. For the first time in your life, it all looks great!\n \n“We’ll be there!” you shout as you head for your bikes. “This is the greatest carnival I’ve ever seen!”\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T15:36:29.249Z", name: "Page 52 and 24 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFiftyTwoAndTwentyFourHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.917001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageFiveAndOneTwentySevenHandlerIntent: [ { name: "Page 5 and 127", outputSpeech: { ssml: "<!-- Page 5 -->\n \n“Come on, run!” you yell to Patty and Brad as you spin around. “There’s got to be another way out!”\n \n<!-- Insert whistle sound fx --> \n\nBig Al blows a whistle. Its shrill blast hurts your ears.\n\n<!-- Insert whistle sound fx --> \n\n He blows it again and, suddenly, dozens and dozens of carnival people appear out of nowhere. But they don’t look the way they did before.\n \nSome have green flesh. Some are deathly white. Their rotting skin hangs from their bones. Above their sunken cheekbones, their eyes glow an eerie yellow.\n \nYou watch in horror as more and more of them appear.\n \nWhat should you do? Your legs won’t budge. You can’t think clearly. You’re terrified! You stand there — frozen — in a trance.\n \nBut Brad breaks the spell when he screams out, “They’re ghosts! That’s why they’re wearing those old-fashioned clothes. They’re dead!”\n \n“Watch out! Over there!” Patty yells. “That — that ghost … It’s coming right at us. Run!”\n \n<!-- Page 127 -->\n \n<!-- Insert chase sound fx -->\n\nYou’re not fast enough to get away from the ghost. You’re running now, but the ghost swoops down in front of you. You plow into him — and pass right through him!\n \nThe carnival people are swarming after you. They don’t want you to leave the carnival.\n \n“Hurry!” you yell to your friends — only three minutes to midnight! You dash off in one direction, then another. The carnival people are approaching from every which way. They carry torches with flames that leap high in the air.\n \nYou steal a glance at your watch — 11:58.\n \n“We can’t let them catch us!” you scream. “Let’s hide!”\n \nBut where can you hide? Up ahead you see a gigantic cannon. All three of you could fit easily in there.\n \nYou also spot a baby ride — the baby choo-choo train — maybe you could squeeze into that. Quick! Pick one — and hope for the best.\n \nDo you choose the cannon or the choo-choo?" }, reprompt: { ssml: "The cannon or the choo-choo. Which do you choose?" } } ] }, forward: { ChooChooIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneTwentyEightAndSeventyHandler" } ], CannonIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneThirtyAndOneOhOneHandlerI" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T17:10:32.084Z", name: "Page 5 and 127 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFiveAndOneTwentySevenHandlerIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.929001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageFortyFiveAndNinetyEightHandler: [ { name: "Page 45 and 98 ", outputSpeech: { ssml: "<!-- Page 45 -->\n \nThe giant looms over you. He’s as tall as the tree outside your house — and a lot meaner. His huge lips part and he says, “You hurt my feelings.”\n \nThen he begins to cry.\n\n<!-- insert crying sound fx -->\n \n“I am not a wimp. I am not,” he says between huge sobs.\n \nHe sure looks like a wimp.\n \n<!-- Page 98 -->\n \nWell, looks can fool you. He is not a wimp.\n \nAnd he’s mad — at you.\n \nIn the next moment, he scoops you up and hurls you at the cell wall. His throw is so forceful, you smash right through the wall and soar out of the carnival grounds.\n \nCongratulations! You escaped the Carnival of Horrors — but not in one piece.\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T18:34:45.420Z", name: "Page 45 and 98 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFortyFiveAndNinetyEightHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.917001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageFortyNineAndFiftyHandler: [ { name: "Page 49 and 50", outputSpeech: { ssml: "<!-- Page 49 -->\n\n<!-- Insert wheel spin sound fx --> \n\nThe wheel stops on FREE SPIN. You are ready to try again. But the dumb parrot flies over and latches onto your shoulder.\n \n“Ouch! That hurts,” you cry.\n \n“Free spin, free spin, you’re going on a free spin.”\n \n“Turn me loose,” you command. When you swivel your head to glare at the bird, a scream freezes in your throat. The parrot has ballooned into an enormous vulture. His black, beady eyes pierce right through you. He digs his razor-sharp claws deeper into your shoulder.\n \nRun! — your every survival instinct shouts. But the bird of prey has other ideas. One of them is dinner — with you as the main course.\n \n<!-- Insert struggle sound fx --> \n\nThe big bird snatches you by the back of your shirt as if you were a rag doll. Kicking and screaming and using every defensive move you learned from karate class, you struggle for your life. But it’s no use. With a jerk he lifts you off the ground.\n \nAnd suddenly you have a frightening view of the carnival from twenty feet … thirty feet … fifty feet up.\n \n<!-- Page 50 -->\n \n<!-- Insert heartbeat sound fx --> \n\nThummp, thump, thump. Your heart bangs loudly inside your chest. What kind of carnival is this, you wonder, where a free spin is more like a death sentence?\n \nYou circle a green clump of treetops. You’re really dizzy now. You want to close your eyes. But you know it’s not a good idea — since you’re flying fifty feet high without a plane or a parachute.\n \nAs you circle closer to the treetops, you are met with a horrifying view. Five baby vultures in a nest, five very hungry babies, with mouths gaping wide open.\n \nThe end is near. You are going to wind up as a take-home dinner. Unless you can somehow force the vulture to let you go. Frantically, you reach into your pockets!\n \nYou remember something from earlier that might help, what is it?" }, reprompt: { ssml: "You remember something from earlier that might help, what is it?" } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageSeventySixHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T18:49:00.869Z", name: "Page 49 and 50 WITH BAR Handler ", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFortyNineAndFiftyHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.924001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageFortyNineAndFiftyWITHOUTBARHandler: [ { name: "Page 49 and 50", outputSpeech: { ssml: "<!-- Page 49 -->\n\n<!-- Insert wheel spin sound fx --> \n \nThe wheel stops on FREE SPIN. You are ready to try again. But the dumb parrot flies over and latches onto your shoulder.\n \n“Ouch! That hurts,” you cry.\n \n“Free spin, free spin, you’re going on a free spin.”\n \n“Turn me loose,” you command. When you swivel your head to glare at the bird, a scream freezes in your throat. The parrot has ballooned into an enormous vulture. His black, beady eyes pierce right through you. He digs his razor-sharp claws deeper into your shoulder.\n \nRun! — your every survival instinct shouts. But the bird of prey has other ideas. One of them is dinner — with you as the main course.\n \n<!-- Insert struggle sound fx --> \n\nThe big bird snatches you by the back of your shirt as if you were a rag doll. Kicking and screaming and using every defensive move you learned from karate class, you struggle for your life. But it’s no use. With a jerk he lifts you off the ground.\n \nAnd suddenly you have a frightening view of the carnival from twenty feet … thirty feet … fifty feet up.\n \n<!-- Page 50 -->\n \n<!-- Insert heartbeat sound fx --> \n\nThummp, thump, thump. Your heart bangs loudly inside your chest. What kind of carnival is this, you wonder, where a free spin is more like a death sentence?\n \nYou circle a green clump of treetops. You’re really dizzy now. You want to close your eyes. But you know it’s not a good idea — since you’re flying fifty feet high without a plane or a parachute.\n \nAs you circle closer to the treetops, you are met with a horrifying view. Five baby vultures in a nest, five very hungry babies, with mouths gaping wide open.\n \nThe end is near. You are going to wind up as a take-home dinner. Unless you can somehow force the vulture to let you go. Tell the vulture why it should let you go." }, reprompt: { ssml: " Tell the vulture why it should let you go." } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneFifteenHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-09T19:20:50.297Z", name: "Page 49 and 50 WITHOUT BAR Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFortyNineAndFiftyWITHOUTBARHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.925001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageFortySixHandler: [ { name: "Page 46", outputSpeech: { ssml: "<!-- Page 46 -->\nYou’re falling … falling … everything passes as if you’re dropping in slow motion. Is this …\nthe end?\nYes.\n" } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T18:02:34.627Z", name: "Page 46 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFortySixHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.925001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageFourHandler: [ { name: "Page 4 Handler", outputSpeech: { ssml: "<!-- Page 4 -->\n\nYour eyes fall upon the map but when you gaze up, Big Al is gone. He’s vanished!\n \n“A whole carnival to ourselves!” Patty exclaims. “Where should we start?”\n \nYou stare down at your map once again. You notice that the carnival is split in half. On one side are the rides. Tons of them. On the other side is the midway, packed with games of chance and the Freak Show.\n \nYou can go to the midway or the rides. Which do you checkout first?" }, reprompt: { ssml: "The midway or the rides. Which do you check out first?" } } ] }, forward: { TheRidesIntent: [ { type: "START", intentId: "PagethirtyfourAndfourtysevenHandler" } ], CheckoutMidwayIntent: [ { type: "START", intentId: "PageseventysevenAndseventyeightHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T19:21:28.002Z", name: "Page 4 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFourHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.926001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageFourteenAndFortyOneHandler: [ { outputSpeech: { ssml: "<!-- Page 14 -->\n \nYou reach out slowly and touch the red card.\n \nTo your amazement, a 3-D heart magically appears and rises from the flat surface. Then it starts to beat! \n\n<!-- Insert beat sound Fx --> \n\nTha-dump, tha-dump. It must be some fancy optical illusion. You lean closer to figure out the trick.\n \n“Yowwwww!” you screech and jerk back to avoid the warm red liquid that nearly squirts in your eye. Is it blood? It looks like blood. “Wow! Cool effect,” you say. “How did you do it?”\n \n“Turn over the card,” Madame Zeno orders. “Do it now!”\n \nMadame Zeno really gets into her act. Doesn’t she know this is just a game? you think. But you do as you’re told.\n \nBig deal. No weird pictures. No hidden fortunes. All you see are the numbers 1, 3, 2 shimmering in gold script against a midnight background. “What does it mean?” you ask.\n \n“You will know when the time is right,” the fortune-teller whispers. Her voice is so low, you can barely hear her. “It could save your life!”\n \n<!-- Page 41 -->\n \n“What do you mean the magic number could save my life?” you ask Madame Zeno. But the fortune-teller doesn’t answer. She stares off into space. She seems to have fallen into a deep trance.\n \nYou don’t really believe her — these fortune-tellers are all fakes, but you memorize the number anyway. 1–3–2, 1–3–2. I picked red instead of blue, you chant to help you remember.\n \nMadame Zeno puts the card back in the deck. She closes her eyes and waves you away with her jeweled hand.\n \nYou guess the fortune-telling is over, so you leave the tent to search for Patty and Brad.\n \nYou squint under the bright lights of the midway, scanning all the game booths. But you can’t find them.\n \nYou’re trying to figure out which way to go when you spot Big Al coming toward you. He’s not alone. He’s leading a large group of people. As they come closer, you hear that they are chanting something. What is it?\n \n“PLAY OR PAY. PLAY OR PAY.”\n \n<!-- Page 16 -->\n \nHi!” you say to Big Al. “Who are all those people?”\n \nHe doesn’t really answer your question.\n \n“Welcome to the Carnival of Horrors,” he says. “You must play or pay. We have many games on our midway. You must play two.” He practically spits the word must out. “If you succeed, you can win prizes. But if you lose, you pay with your life!”\n \nBoy, he’s really laying it on thick, you think. But it’s a pretty cool gimmick. “Okay, I’ll play a game. Then I’ve got to go home.”\n \n“No one goes home,” Big Al says, “until they play. You must play two games. And survive.”\n \n“Okay. Okay,” you mutter to yourself.\n \nYou glance around the midway at the two closest games. Mission to Mars and the Wheel of Chance. You have to pick one to start, or you’ll never get out of here.\n \nMission to Mars or the Wheel of Chance?" }, reprompt: { ssml: "Mission to Mars or the Wheel of Chance, Which do you choose?" } } ] }, forward: { MissionToMarsIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "MissionToMarsPageSeventyTwoHandler" } ], WheelOfChanceIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "WheelOfChancePageEightHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T18:52:37.745Z", name: "Page 14 and 41 and 16", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFourteenAndFortyOneHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.923001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageFourtyEightAndSixtyHandler: [ { name: "Page 48 and 60", outputSpeech: { ssml: "<!-- Page 48 -->\n \n“Come on!” Patty cries. “Come on!”\n \nThen, without another word, she races off. You and Brad dash after her.\n \nI hope Patty knows what she’s doing, you think as you try to catch up. Because right now, it doesn’t look that way.\n \nPatty leads you through a maze of underground passageways. Then, just as you’re about to yell, “Stop!” — she does. And you find yourself standing outside, in front of a barbed-wire fence!\n \nUp ahead, you spot an opening.\n \n“Let’s go in!” Patty says.\n\n<!-- Insert fence sound fx -->\n \nThe three of you creep through the fence and trudge through some tall, wet grass. You gaze around. It’s way too dark to see.\n \nBut you can hear perfectly. And the sounds that reach your ears make your skin crawl.\n \n<!-- insert sliterhing sound fx -->\n\nSlithering. You definitely hear slithering.\n \nAnd hissing.\n \nYou want to leave. You spin around, but you can’t find the opening in the fence! You do see something else. A sign!\n \n<!-- Page 60 -->\n \n“There’s a sign!” you call out to Patty and Brad. “Let’s see what it says.”\n \nThe three of you race through the wet grass. Your socks are drenched. And your sneakers squeak as you run. But that’s not the sound that’s sending chills down your spine.\n \n<!-- insert squeaks and hiss sound fx -->\n\nIt’s the hissing. It’s growing louder.\n \n“I’m not sure I want to read that sign,” you call out to Patty and Brad.\n \n“I know what you mean!” Patty shouts back. “I have a feeling we’re not going to like what it says.”\n \nAnd you don’t. You reach the sign and read it aloud. “Reptile Petting Zoo! Whoever heard of a Reptile Petting Zoo! What kind of carnival is this anyway?”\n \n“This carnival is e-evil,” Brad stammers.\n \nYou’re about to agree when you notice the grass in front of you is swaying. Something is slithering through it. Something big. And then it comes into view.\n \n“Snake!” Brad cries.\n \nWhich way do you run - left or right?" }, reprompt: { ssml: "Do you run left or right?" } } ] }, forward: { TurnRightIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageTwelveHandler" } ], TurnLeftIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneTwentyFiveAndFourtyThreeHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T17:28:16.202Z", name: "Page 48 and 60 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFourtyEightAndSixtyHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.924001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageFourtyFourHandler: [ { name: "Page 44", outputSpeech: { ssml: "<!-- Page 44 -->\n \n<!-- insert wheel spin sound fx -->\n\nYou’re spinning round and round. Everything is a blur. You can’t see, but you hear the crowd chanting, “FI-NAL! FI-NAL! FI-NAL!”\n \nAnd then the wheel stops.\n \nA huge gasp escapes from the audience.\n \nDid you win or lose?\n \nNeither. You stopped on SPIN AGAIN.\n \nBig Al approaches the wheel.\n \nHe gives the wheel — with you on it — a hard turn. Where will it stop?\n \nGuess a number between 1 and 3!" }, reprompt: { ssml: "Guess a number between 1 and 3!" } } ] }, forward: { "SlideNumberIntent|NumberIntent": [ { type: "START", intentId: "PageFourtyFourHandler", slotMatch: { name: "number", value: 1, operation: "==" } }, { type: "START", intentId: "PageSeventyFourAndOneThirtyOneAndOneSixteenHandler", slotMatch: { name: "number", value: 2, operation: "==" } }, { type: "START", intentId: "PageSeventyThreeAndOneThirtyOneAndOneSixteenWITHOUTBLOODHandler", slotMatch: { name: "number", value: 2, operation: "==" } }, { type: "START", intentId: "PageOneTwentyFourAndOneTwelveHandler", slotMatch: { name: "number", value: 3, operation: "==" } } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T16:59:04.107Z", name: "Page 44 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageFourtyFourHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.926001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageNineteenHandler: [ { name: "Page 19", outputSpeech: { ssml: "<!-- Page 19 -->\n \n<!-- Insert spinning wheel sound Fx --> \n\nYou land on number 19.\n \n“Double or nothing. Double or nothing,” two voices behind you echo.\n \nYou whirl around — and gasp! It’s a man with two heads.\n \n“Congratulations. You win ten points,” one head says to you. “Quit while you’re ahead!”\n \n“Ahead, get it? A head!” the other head adds, laughing hysterically.\n \n“Shut up,” head number one says.\n \n“You shut up,” head number two shoots back. “Ten points is nothing. You better spin again. And this time it’s double or nothing. You get double the points wherever you land.”\n \nYou’re not sure which head to listen to, do you want to spin again or quit while you are ahead?" }, reprompt: { ssml: "do you want to spin again or quit while you are ahead?" } } ] }, forward: { QuitWhileAheadIntent: [ { type: "START", intentId: "MissionToMarsPageSeventyTwoHandler" }, { type: "START", intentId: "PageSeventeenAndEightyFourAndOneTwentyThreeAndTwentyFiveHandler" } ], SpinAgainIntent: [ { type: "START", intentId: "WheelOfChancePageEightHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-09T19:47:48.789Z", name: "Page 19 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageNineteenHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.925001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageNinetyFiveHandler: [ { name: "Page 95 Handler", outputSpeech: { ssml: "<!-- Page 95 -->\n \nYou sit down on the slide and push off. The world tilts as you plunge down. Down, down, down.\n \nYou’re scared. But you can’t help feeling that this is kind of cool! Sliding and swirling in the darkness.\n \n<!-- Insert scream sound Fx -->]\n\nUntil you hear the screams. The eerie screams that follow you as you twist and turn.\n \nYour heart starts pounding wildly. Oh, no! You must have picked the Doom Slide. You’re going to slide forever!\n \nAnd then --\n\n<!-- Insert bump/chute sound Fx -->]\n\nBump. A chute opens up. You hit the ground hard. You tumble over and over and finally stop.\n \nYou lie on the ground. Panting.\n \nYou’re outside!\n \nYou scramble to your feet and gaze around.\n\n<!-- Insert laughter sound Fx -->]\n \nYou hear laughter. It seems to be coming from the bright pink building a few feet in front of you.\n \nYou walk over to its big pink door and press your ear against it.\n \nYes. The laughter is definitely coming from inside.\n \n<!-- Page 117 -->\n \nYou open the door and enter a room bursting with people who seem to be waiting for you. You think that’s weird until you study them — and realize something even stranger. They’re all dressed up in old-fashioned costumes.\n \n“Welcome to the Carnival of Horrors,” a tall woman with a red parasol says, smiling. “Nice of you to join us.”\n \nThe Carnival of Horrors. The words send shivers down your spine.\n \nThe woman with the parasol whispers in your ear, Do you want to know the secret?" }, reprompt: { ssml: 'Yes or no, do you want to know the secret?"' } } ] }, forward: { NoIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneSeventeenAndOneOhSixAndFortyTwoNOHandler" } ], YesIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneOhSixAndFourtyTwoHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T14:18:20.121Z", name: "Page 95 and 117 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageNinetyFiveHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.925001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageNinetyNineHandler: [ { name: "Page 99", outputSpeech: { ssml: "<!-- Page 99 -->\n \n“Okay, get me out of here,” you say to the goblin. “Did you help my friends, too?”\n \nThe goblin does not answer. He sprints off and you have to race to keep up with him. Through a confusing maze of twisting tunnels. You’re sure glad you have a guide.\n \nThe goblin suddenly stops. “That way,” he says gruffly, pointing straight ahead.\n \nBefore you can blink, he vanishes in a puff of smoke! And you’re left standing in front of two doors. One red. One blue. The red one has a sign that reads: DANGER. The blue one has a sign that reads: BIG DANGER.\n \nDo you pick the red door or the blue door?" }, reprompt: { ssml: "Do you pick the red door or the blue door?" } } ] }, forward: { BlueDoorIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageFiftySevenAndOneThirtyFiveHandler" } ], RedDoorIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneOhFourAndSixtyOneHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T18:32:47.329Z", name: "Page 99 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageNinetyNineHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.924001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageNinetySevenAndOneTwentyNineHandler: [ { name: "Page 97 and 129", outputSpeech: { ssml: "<!-- Page 97 -->\n \nYour hand clamps around the can of Monster Blood in your pocket. Quickly, you snap off the lid and the green gunk pours out.\n \n“Look! It’s alive!” Brad shouts.\n \n<!-- Insert sucking sound fx-->\n\nHe’s right. The Monster Blood oozes from the can, quivers, and appears to stretch and pull itself up! Then it starts to roll and bounce, making horrible sucking sounds.\n \nGreat! It’s rolling into the crowd, sucking up everything in its path!\n \n“Run!” Big Al screams as the huge green ball rolls over the people in the crowd — sucking them up with a loud plop.\n \nThen the Monster Blood hits the side of the tent. It changes direction.\n \nIt’s coming after you!\n \n<!-- Page 129 -->\n \nThe Monster Blood has grown so big — now you can’t see over it or around it.\n \n“Run for your lives!” Patty screams. But reaching the door is impossible.\n \nThe mound of green slime is bearing down on you. Fast! You stand frozen to the spot. Terrified. And then — just in time — you, Patty, and Brad leap to the side. \n\n<!-- Insert crushing sound fx-->\n\nAnd the Monster Blood slams into the wall with a crushing force — and plows right through it.\n \nYou stare at the giant gaping hole in the wall. Quickly, the three of you jump through the opening. You are standing outside the main gate — where you came in!\n \nThere’s a wide path of destruction across the field and the forest beyond. From somewhere, a clock chimes twelve times, sending a chill down your spine. And when you peer back at the carnival, it has disappeared. All that’s left is a spooky silver mist.\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T17:09:10.805Z", name: "Page 97 and 129 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageNinetySevenAndOneTwentyNineHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.929001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageNinetySixAndTwentyThreeHandler: [ { name: "Page 96 and 23", outputSpeech: { ssml: "<!-- Page 96 -->\n \n<!-- Insert swinging axe/horse sound Fx -->]\n\nthey’re swinging axes.\n \nYour heart leaps into your throat. The elves move to the roadside now — and they’re chopping down the horse-drawn carts ahead of you! One cart splinters into a million pieces before your horrified eyes.\n \nThe elves continue on to the next cart. Their sharp blades slice right through it!\n \nYour horse keeps trotting up the steep path. You’re headed right for the wildly chopping elves!\n \n“Do something!” Patty cries.\n \n<!-- Page 23 -->\n\n<!-- Insert swinging axe/horse sound Fx -->]\n \nYou yank on the reins. But your horse plows ahead, pulling you forward — closer and closer to the chopping, chopping, chopping blades. Brad squinches down in the cart and buries his head in his lap.\n \nPatty jumps into the front seat with you. Together you pull on the reins and scream, “Whoa, fellow! Whoa!”\n \nBut your horse trots onward. “It’s no use,” you cry. “We’d better jump!”\n \nYou stare over the side. You’re riding along a narrow ridge and there’s a deep drop that makes your blood run cold! If you jump, you’ll plunge to your death!\n \nThen you glance up ahead — and spot a safer place to leap. Great!\n \nYou are about to show it to your friends when Brad cries out, “Look at the elves! They chop at set times. If we can get the horse to move faster, we can miss the axes!”\n \n“That’s dumb, we should jump!” argues Patty.\n \nWhat do you think you should do, jump out or get the horse to sneak by the axes?" }, reprompt: { ssml: "You can jump out our speed up the horses. Which would you like to do?" } } ] }, forward: { SneakByTheAxesIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneNineteenHandler" } ], JumpOutIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneOhThreeAndOneOhNineHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T16:04:15.003Z", name: "Page 96 and 23 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageNinetySixAndTwentyThreeHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.923001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageNinetyTwoHandler: [ { outputSpeech: { ssml: "<!-- Page 92 -->\n \nYou decide to wait. Someone should be here soon, you think. But after waiting in the space shuttle for at least fifteen minutes, you’re not so sure. No one has shown up to rescue you.\n \nA chill runs down your back. You feel as if a thousand pairs of eyes are watching you from the shadows.\n \n<!-- Insert rustling sound Fx -->]\n\nNow that you’re accustomed to the darkness, you can see dozens of tracks leading in and out of the tunnel.\n \nAnd then you hear a rustling sound. You freeze. You listen hard. Could it be rats — or something worse?\n \nYou draw up your knees and wrap your arms around them tightly. \n\n<!-- Insert hissing sound Fx -->]\n\nThen you hear a hissing sound — and you smell something odd. It’s kind of a sweet smell — like heavy perfume. You hold your nose because the smell is making you feel strange. Dizzy. Sick.\n \n<!--Page 20 -->\n \nIt seems as if hours have passed. Or maybe it’s only minutes.\n \nYou try to unclasp your hands. But they won’t budge. It’s as if your arms are glued around your knees.\n \nYou try to move something. Anything.\n \nBut you can’t blink an eyelid. Your body is paralyzed. You can’t even scream.\n \nA door opens and two men dressed in overalls and wearing gas masks amble in. Finally. They’re here to rescue you!\n \n“Looks like the perfume worked,” you hear one of them say.\n \n“Yeah. And just in time. We needed a new dummy for the Real-Life Space Display,” the other adds.\n \nThey pick up your rigid body and carry you out. No wonder those astronauts in the silver tunnel looked so real!\n \nSorry. You can’t scream. You can’t escape.\n \nNext time, you promise yourself, you’ll stick with the baby rides. But then you remember — there isn’t going to be a next time … because this is … The end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T18:16:17.833Z", name: "Page 92 and 20 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageNinetyTwoHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.924001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneAndPageTwoHandler: [ { name: "Page 1 + Page 2", outputSpeech: { ssml: "<!-- Page 1 -->\n \n“What do you want to do?”\n \n“I don’t know, Patty. What do you want to do?”\n \n“Not fair, Brad. I asked you first.”\n \nPatty and Brad. Your two best friends. Arguing. As usual.\n \nIt’s the last week of August. And Patty and Brad haven’t stopped fighting since your summer vacation started.\n \nPatty likes being bossy. You don’t mind, though. It’s no big deal.\n \nIt’s hard to win a fight with her anyway. You don’t know why Brad even tries. You guess it’s because he doesn’t want to look like a wimp.\n \n“There’s nothing to do. I guess I’ll just go home,” Brad says. He shoves his hands in his pockets. Then his shoulders slump and he sort of shrivels up. You guess Brad is kind of a wimp — even if he is your best friend.\n \n“You’re so boring, Brad,” Patty complains. Whenever Patty complains, her freckles really pop out. Now there are about a million of them spread across her face.\n \n“Hey! I know what we should do!” Patty suddenly bursts out.\n \n<!-- Page 2 -->\n \n“Let’s bike over to Bennet’s Field and watch them set up the carnival!”\n \n“I don’t know,” you answer. “It’s getting dark, and Mom said I have to be in by nine.”\n \n“It’s only a quick bike ride,” Brad says. “Are you some kind of wimp?”\n \nBrad calling you a wimp? You can’t believe it!\n \n“Okay. Okay,” you agree. “But if it’s as bad as last year, there won’t be much to see. Don’t you remember the main attraction?” you remind them. “The ride they called Terror Track? It turned out to be a baby choo-choo train that circled around and around and around.”\n \nIt doesn’t matter what you say. Patty’s made up her mind. You’re going to ride over to the carnival.\n \nA hot, humid breeze blows in your face as you pedal along. Patty’s in the lead. No surprise. And Brad’s puffing behind you.\n \nIt’s dark by the time you reach Bennet’s Field.\n \nYou and your friends drop your bikes in the grass and race across the moonlit field, toward the huge wooden fence that surrounds the carnival.\n \n<!-- Insert carnival sound Fx -->\n \nWhat is your favorite carnival ride?" }, reprompt: { ssml: "What is your favorite carnival ride?" } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", intentId: "PageThreeHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T15:09:39.942Z", name: "Page 1 and 2", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneAndPageTwoHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.925001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneEighteenHandler: [ { name: "Page 118", outputSpeech: { ssml: "<!-- Page 118 -->\n\n<!-- Insert laughter sound Fx -->\n\nYou turn left. Somewhere ahead of you, you hear laughter. \n\n“Is somebody there?” you call out.\n \nSilence.\n \nYou stare at your reflections in the mirrored hall.\n \nAm I trapped? you wonder. Am I in real danger? Or is this all a big, scary joke? Your heart begins to race.\n \nYou inch forward a few more steps — moving toward the laughter. Slowly.\n \n“Over here,” a voice calls again. But now the voice seems to be coming from behind you!\n \n<!-- Page 36 -->\n \nYou turn back and head in the other direction. Your reflections bounce off the walls at crazy angles. Are you walking straight, or have you rounded a corner? There’s no way to tell. Yet this time you’re sure you’re going the right way!\n \n“Over here!” a voice calls. “Turn left again!”\n \nTurn left again? Now you are really confused.\n \nIf you turn left again, will you finally escape?\n\n<!-- Page 36B -->\n\nYou turn left. \n\n<!-- Insert laughter sound Fx -->\n\nSomewhere ahead of you, you hear laughter…again. You think, this seems familiar. It should because you were just here. I hope you like you’re reflection because you’re stuck in this loop…forever. \n\n<!-- Insert panic sound Fx -->\n\nYou turn left. You turn left. You turn left. You turn left. \n\nThe end. " } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T18:56:14.793Z", name: "Page 118 and 36 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneEighteenHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.928001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneElevenHandlerIntent: [ { name: "Page 111", outputSpeech: { ssml: "<!-- Page 111 -->\n \nYour pulse pounds in your ears as you carefully lift yourself out of the car. The tunnel is dark and musty and really creepy. Anything could be lurking in the shadows.\n \nThis must be part of the ride, you reason. And the more you think about it, the more convinced you are. You’re scared. But you have to admit, this is pretty cool.\n \nIn the distance, you spot several red lights that seem to lead to other dimly lit tunnels. You cautiously head toward one of them. Overhead something dark and slimy drips. Splattering on the top of your head. Stinging your forehead.\n \nAs you desperately try to wipe the burning slime away, something grabs you by the knees!\n \nAaaah! You look down. A pair of red-rimmed eyes meet yours. It’s a goblin with scraggly red hair and a toothless smile.\n \n“Want me to lead you out of here, kid?” he asks. You’re about to follow the goblin, but then you stop. Is he part of the ride? He looks really evil.\n \nDo you follow the goblin or find your own way out?" }, reprompt: { ssml: "Do you follow the goblin or find your own way out?" } } ] }, forward: { FindYourOwnWayOutIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageThirtyThreeHandler" } ], FollowTheDwarfIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageNinetyNineHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T18:28:09.108Z", name: "Page 111 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneElevenHandlerIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.926001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneFifteenHandler: [ { name: "Page 115", outputSpeech: { ssml: "<!-- Page 115 -->\n \n\n“Help! Save me!” you cry.\n \n<!--Insert swooping sound Fx --> The vulture swoops down and drops you in the nest.\n \nThe baby vultures approach.\n \nMouths open — ready to peck you to death …\n \nBut — good news! They don’t eat you. You fall out of the nest instead.\n \n<!-- Insert thud sound -->\n\nTHUD!\n \nDon’t go to pieces. Pull yourself together and prepare to visit the Carnival of Horrors again — the next time you’re brave enough!\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T19:20:53.873Z", name: "Page 115 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneFifteenHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.927001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneFourteenHandler: [ { name: "Page 114", outputSpeech: { ssml: "<!-- Page 114 -->\n \nThis is your lucky day.\n \nYou duck as the crane swings over your head.\n \n“Run!” you shout to your friends.\n \nYou glance at your watch — 11:55. If you’re really lucky, you can still make it out of the carnival by midnight.\n \nYou can see the exit up ahead. As you charge through the gate, you feel really hopeful — until you run into Big Al.\n \nHe blocks the exit with his huge body. His massive hands are planted on his hips. “No one escapes from the Carnival of Horrors!” he roars.\n \nYou’ve got to find a way out. Now!\n \nTo your right is the entrance to Halloween Express — you could try that.\n \nOr maybe you should run down a different path. There’s got to be more exits around here somewhere.\n \nChoose fast!\n \nWant to try the Halloween Express or run down a different path?" }, reprompt: { ssml: "Do you want to try the Halloween Express or run down a different path?" } } ] }, forward: { RunDownADifferentPathIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageFiveAndOneTwentySevenHandlerIntent" } ], HalloweenExpressIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneOhEightAndFiftyFourHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T17:01:39.563Z", name: "Page 114 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneFourteenHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.066001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneHundredHandler: [ { name: "Page 100", outputSpeech: { ssml: "<!-- Page 100 -->\n \n“Help! Help! Over here!” you scream, waving your arms wildly in the air.\n \n“Hold on!” a deep voice answers through the heavy mist.\n \n<!--Insert boat sound Fx -->\n \nThe boat turns and speeds toward you. As it nears, the voice calls out again. “Jump! Jump over!”\n \nJump? Is he crazy? Can you really jump onto a moving boat?\n \n<!--Insert boat sound Fx -->\n \nThe boat is coming closer now. Closer. Closer. You stand up. You bend your knees. You’re about to jump — and the boat speeds right past you.\n \nBut wait! It is circling back now in a nice, slow approach. It glides up to you, and gigantic hands pull you onto the boat.\n \n“You saved me!” you cry.\n \nYou gaze up and gasp in surprise. The man in the other boat isn’t a man — it’s a monster with a drooling snout and rows of jagged teeth.\n \n“Save you? Save you?” the monster repeats.\n \nHis red eyes light up. “Save you … good idea,” he says. “I won’t eat you now. I’ll save you for a midnight snack!”\n \nThe end.\n\nThe Carnival of Horrors never stops. Do you want to try your luck again and start from the beginning?" }, reprompt: { ssml: "Do you want to try your luck again and start from the beginning?" } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T19:34:45.128Z", name: "Page 100 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneHundredHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714153.927001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneNineteenHandler: [ { name: "Page 119", outputSpeech: { ssml: "<!-- Page 119 -->\n \n<!-- Insert horse sound fx --> \n\nYou take charge of the reins to urge the horse on.\n \n“Giddyap, boy,” you and Patty shout. But your horse won’t move any faster.\n \nYou shoot a glance up ahead. The elves are chopping … and a shiny blade … is now … right over … your head!\n \n“No,” you scream. “NO! Let me out of here.”\n \nYou feel a sharp pain. And you realize you’ve just had the shortest haircut of your life. Unfortunately, they took a little too much off the top.\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T16:11:07.942Z", name: "Page 119 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneNineteenHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.056001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneOhEightAndFiftyFourHandler: [ { name: "Page 108 and 54", outputSpeech: { ssml: "<!--Page 108 -->\n \n“We’ve got to get out of here, it’s almost midnight,” you say as you run toward the Halloween Express ride.\n \n“Hey, maybe we should try one of these cars,” Brad says, pointing to the red and orange cars that run on a track.\n \nThe three of you crowd into a little car that’s really meant for two. You jam your foot on the gas pedal, and you’re flying!\n \n“All right!” Brad cheers. “We’re on our way home! Hey, I wonder why they call this Halloween Express?” he asks.\n \nYou turn the wheel sharply to the left, and then you know why….\n \n<!-- Page 54 -->\n \nYour Halloween Express car pulls up in front of a cottage and the cottage door opens with a creak.\n \n<!-- Insert creak sound Fx -->\n \nYou all jerk your heads up to peer at the door. You see a skeleton wearing an evil smile. And he lunges right for you!\n \n“Trick or treat!” he screeches. Then he stretches out his bony hands to snatch you!\n \nYou pound on the gas pedal, and the car shoots forward — out of the skeleton’s grasp!\n \n<!-- Insert car sound Fx -->\n \nYell something at the skeleton as you drive away." }, reprompt: { ssml: "Yell something at the skeleton as you drive away." } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageFiftyFourAndEightyThreeHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T14:42:41.567Z", name: "Page 108 and 54 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneOhEightAndFiftyFourHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.057001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneOhFiveAndNinetyHandler: [ { name: "Page 105 and 90", outputSpeech: { ssml: "<!-- Page 105 -->\n \nIt’s a tree branch! Grabbing at you. Tugging, tugging at your hair. You can’t break free. Its gnarly stubs dig in deeper as you struggle.\n \nSuddenly, you feel something wrap itself around your arms. Then your legs. Closing in tighter. Tighter.\n \nYou gaze down and see them — black knobby tree limbs twisting around you. Strangling you.\n \nYou drop hold of the steering wheel and begin to claw at the branches, ripping them away.\n \nAnd then you peer up — and see a terrifying sight. It’s a huge tree. And you’re headed straight for it! You grasp the steering wheel to regain control of the boat. The tree is just inches away.\n \nAre you going to CRASH?!\n \n<!-- Page 90 -->\n \nNO!\n\n<!-- Insert boat sound Fx -->\n \nAt the last minute, you wrench the steering wheel hard to the left. The side of your boat clears the tree with a sickening scrape.\n \nYou breathe a sigh of relief, but it ends in a groan. A huge, sharp root below the water has just ripped into the bottom of your boat.\n \n<!-- Insert tearing and water sound Fx -->.\n \nYou hear a tearing sound, then gurgling as the cockpit starts to fill with water.\n \n“Now what?” you mutter.\n \nThen through the mist you spot another boat. But it’s some distance away.\n \n“Hey, over here!” you cry out.\n \nDid they hear you? You cry out again. Then you glance behind you. More than half your boat is underwater — and you’re going down fast.\n \nQuick - do you keep yelling or swim to safety?" }, reprompt: { ssml: "Do you keep yelling or swim to safety?" } } ] }, forward: { DecideToBeRescuedIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneHundredHandler" } ], DecideToSwimForItIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageFiftySixHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T19:15:47.703Z", name: "Page 105 and 90 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneOhFiveAndNinetyHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.056001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneOhFourAndSixtyOneHandler: [ { name: "Page 104 and 61", outputSpeech: { ssml: "<!-- Page 104 -->\n \nYou push open the red door. Another tunnel lies beyond it. You follow its twists and turns, and you realize that you’re sloshing through cold muddy water. It grows deeper and chillier as you go.\n \nWith a cold shudder, you decide to head back — until you hear a slurping noise behind you.\n \n<!--Insert slurping sound Fx -->\n \nWhirling around, you watch in horrible fascination as giant earthworms crawl out of the mud. Gross!\n \nNo way you’re heading back there. You clench your teeth and slog onward. Up ahead, you see a dim green light. Great! An exit.\n \nAs you reach the end of the tunnel, you hear a low growl behind you.\n \n<!--Insert low growl with footsteps sound Fx-->\n \nAt first you try to pretend it’s your imagination. But there’s no mistaking the sound of thudding footsteps. Getting closer. And closer. And now it’s breathing down your neck!\n \n<!-- Page 61 -->\n \nYou’re too scared to turn around. And too scared not to. Risking a glance over your shoulder, you see a large, dark shape behind you. It’s a big man. No. You squint hard. It’s dark and hairy with muddy leaves and green vines trailing from its body. It’s some sort of swamp monster!\n \nYou run as fast as you can. Your chest is on fire. The swamp monster is gaining on you.\n \nYou know you should keep running, but your heart feels as if it’s about to explode. You have to stop.\n \nYou turn and stare right into the swamp monster’s bloody eyes. “Neat costume,” you say hopefully.\n \nGood try — but the swamp monster isn’t wearing a costume. He’s real and this, unfortunately, is really … the end.\n\nThe Carnival of Horrors never stops. Do you want to try your luck again and start from the beginning?" }, reprompt: { ssml: "The Carnival of Horrors never stops. Do you want to try your luck again and start from the beginning?" } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T18:54:21.101Z", name: "Page 104 and 61 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneOhFourAndSixtyOneHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.049001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneOhSevenAndSeventyFiveHandler: [ { name: "Page 107 and 75", outputSpeech: { ssml: "<!-- Page 107 -->\n \n“Sorry, Brad. I think Patty’s right,” you tell him as you turn toward the Hall of the Mountain King. “I think I spotted an exit there when we first came in.”\n \nPatty runs ahead. “Look!” she cries out. “There’s the path. It leads past the Hall of the Mountain King to the exit.”\n \n“Yeah, but who are those people up there?” Brad asks. “They’re blocking the way.”\n \nYou peer up ahead and see them — the people in the old-fashioned clothes. And they’re still chanting — “Only one right way, only one right way.”\n \n“They’re not going to let us out!” Brad panics.\n \n“Okay. Okay. I have an idea,” you say calmly. “Let’s go into the Mountain King ride — maybe we can jump off at the end and sneak past them.”\n \nDo you have another choice? No.\n \n<!-- Page 75 -->\n \nThe three of you duck inside the Hall of the Mountain King!\n \nA painted backdrop of rounded, snowcapped mountains rises on your left. Up in the mountains, a big stone castle rests in the sunshine.\n \n<!-- Insert cheerful/garden sound Fx -->.\n\nA group of cheerful elves picks flowers in the castle’s garden. \n\nTo your right, you spot the ride — wooden carts pulled by real horses. “Come on!” you call to your friends. “Jump in a cart. This is great. We’ll be out of here in no time.” No time — that reminds you. You glance at your watch. 11:45!\n \nYou all scramble into one of the carts and grab the reins. Your horse plods forward, and you pass through a painted stone archway.\n \nYou gasp. Everything in the painted backdrop is now in front of you. And it has suddenly become real. But different!\n \nThe snowcapped mountains rise to black, jagged peaks that pierce the sky. The big stone castle huddles on a scary, dark hill. And the elves — they aren’t picking flowers.\n \nThey’re …\n \n<!-- Read in prompt voice -->\n \nWhat do you think the elves are doing?" }, reprompt: { ssml: "What do you think the elves are doing?" } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageNinetySixAndTwentyThreeHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T15:43:38.482Z", name: "Page 107 and 75 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneOhSevenAndSeventyFiveHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.056001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneOhSixAndFourtyTwoHandler: [ { name: "Page 117 and 106 and 42", outputSpeech: { ssml: "<!-- Page 117 -->\n \n“The Carnival of Horrors comes alive in a different place and a different time each night. Tonight we’re in your town. Tomorrow we could be in another country! But every place we stop, we invite kids like you to join us….”\n \n“Thanks for the invitation,” you say, “but I gotta go.”\n \n“I’m sorry.” The lady chuckles. “You can never escape from the Carnival of Horrors,” she says solemnly. “Unless …”\n \n<!-- Page 106 -->\n \n“Unless what?” you scream. “Tell me!”\n \n“You can escape the Carnival of Horrors if you leave before closing time.”\n \n“When is closing time?” you shoot back.\n \n“When the last ride stops….” the lady whispers. “At midnight.”\n \nYou glance at your watch — 11:40. Twenty minutes — that’s not so bad. But how do you get out of here?\n \nAs if the lady can read your mind, she says, “There’s only one right way.”\n\n <!-- Insert chanting sound Fx -->\n\nThen all around you, the crowd begins to chant. \n \n“ONLY ONE RIGHT WAY, ONLY ONE RIGHT WAY.” They repeat it over and over again.\n \n“What is it?” you scream. “Which way?”\n \nIt’s useless. They’re not going to tell you.\n \nBut it’s not midnight yet. There’s still time to figure it out.\n\n<!-- Insert tremble sound Fx -->\n \nUntil the floor begins to tremble. And the walls begin to shake. \n \nEarthquake!\n \n<!-- Page 42 -->\n \n<!-- Insert tremble sound Fx --> \n\nA wave of panic washes over you as the walls crumble around you. You throw your arms over your head and close your eyes.\n \nThen silence. The shaking stops.\n \nWhen you open your eyes, the room and all the costumed people have vanished. And you are outside — in the rides area! But the biggest surprise of all is that you spot Patty and Brad!\n \n“Boy, am I glad to see you,” you say, racing over to them. “Where have you guys been?”\n \nBrad shakes his head. “You wouldn’t believe the rides we were on!”\n \n“We’ve got to get out of here before midnight,” you say. Quickly, you tell your friends about the warning from the lady with the red parasol.\n \n“No problem,” Patty says. “Look. I’m sure the exit is right over there past that ride called the Hall of the Mountain King.”\n \n“No, it’s that way — near the sign that says ‘Halloween Express,’” Brad insists.\n \nDo you think the exit is near Halloween Express or Mountain King?" }, reprompt: { ssml: "Is the exit near the Halloween Express or Mountain King?" } } ] }, forward: { HalloweenExpressIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneOhEightAndFiftyFourHandler" } ], MountainKingIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneOhSevenAndSeventyFiveHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T14:34:17.805Z", name: "Page 117 and 106 and 42 YES Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneOhSixAndFourtyTwoHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.064001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneOhThreeAndOneOhNineHandler: [ { name: "Page 103 and 109", outputSpeech: { ssml: "<!-- Page 103 -->\n \n“We’ve got to jump,” you tell Patty and Brad. “It’s our only chance.”\n \n“Okay,” Brad agrees as your cart inches up to the chopping elves.\n \n“Come on,” you cry. “Now!” But Brad is too paralyzed with fear to move. You and Patty grab him and haul him toward the side of the cart.\n \nYour cart has reached the elves! One of them smirks as he lifts his ax.\n \nIt’s right above your neck.\n \nYou picture your head tumbling down the side of the mountain.\n \nWith a loud cry, all three of you jump. You land with a thud on a rocky ledge. It breaks your fall. But the rock is too weak to hold all of you.\n \nYou scream again as the edge tears loose and the world drops from under your feet.\n \n<!-- Insert rock breaking and tumble sound Fx -->\n \nYou tumble over and over, down the side of the mountain.\n \n<!-- Page 109 -->\n \nYou squeeze your eyes shut and wait for the crash. Finally, you land. You glance up. You’re at the foot of the Log Flume ride.\n \nYou, Patty, and Brad have lots of cuts and bruises, but you’re okay! Terrific! you think — until you spot the army of elves with their axes. They’re rushing down the mountain toward you! The only escape is to enter the flume ride, so you dash inside.\n \nThe Log Flume reminds you of a western logging camp, complete with log cabins, trees, trucks, and a sparkling blue lake.\n \n<!-- Insert chain saw sound Fx -->\n \nIn the distance, you can hear the buzz of chain saws. And down by the lake, giant cranes pick up logs and plop them in the water. Some of the logs are hollowed out in the middle with seats for passengers. As you watch, the current catches one. It glides to the edge of a waterfall, plunges over, and shoots down.\n \nAs you glance around, you spot an EXIT sign.\n \nThen to your horror, you see a giant crane swinging your way. “Duck!” you scream.\n \nWill you make it to the exit?\n \nTo find out, tell me what day of the week it is." }, reprompt: { ssml: "What day of the week is it right now?" } } ] }, forward: { MondayWednesdsayFridaySaturdayIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneFourteenHandler" } ], TuesdayThursdaySundayIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageSeventyOneHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T16:56:42.223Z", name: "Page 103 and 109 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneOhThreeAndOneOhNineHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.050001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneOhTwoAndOneTwentyHandler: [ { name: "Page 102 and 120", outputSpeech: { ssml: "<!-- Page 102 -->\n \n“I’m not going anywhere with you, Big Al. I believe the Snake Lady!”\n \n“So do I,” says Patty.\n \n“Me, too!” Brad echoes.\n \n“That’s too bad,” Big Al says. Then he turns to the Snake Lady.\n \n“And as for you, Miss Reptilia — I told you, you’ve been overacting. If these kids believe you, we won’t be able to torture them with our real horrors.”\n \n“Ssssssorry, bosssssss,” she says. “Sssssso what do you want me to do with them?”\n \nYou can hardly believe it! Real horrors?\n \n“What kind of carnival is this?” you shout.\n \n“The Carnival of Horrorssssss,” the Snake Lady answers — and that’s the good news.\n \n<!-- Page 120 -->\n \nThe bad news is the Snake Lady fooled you.\n \n“Throw them into the large cell with Harold and all the other prisoners,” Big Al commands.\n \n<!--Insert click sound Fx -->\n \nYou are shoved into a dark cell. You hear a click. You’re locked in.\n \n<!--Insert laughter sound Fx -->\n \nAs the Snake Lady leaves with Big Al, you can hear their laughter echo down the hall.\n \nYou glance into the other cells and think, the freaks are prisoners. They do need our help. Then you peer into the darkness of your cell — to find out who Harold is.\n \nThere’s no way you could miss him. Harold is a giant. He’s huge — twice as big as a football player. His hands are, in fact, the size of two footballs. His arms look like tree trunks.\n \nAt first you are afraid of him, but then you think, Hey! He’s trapped, too. Maybe we can convince him to help us.\n \nTo get Harold to help you, give him a compliment to get on his good side." }, reprompt: { ssml: "Give Harold a compliment to get on his good side." } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageTwentyEightHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T18:03:06.138Z", name: "Page 102 and 120 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneOhTwoAndOneTwentyHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.051001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneSeventeenAndOneOhSixAndFortyTwoNOHandler: [ { name: "Page 117 and 106 and 42", outputSpeech: { ssml: "<!-- Page 117 -->\n \nToo bad.\n \n“The Carnival of Horrors comes alive in a different place and a different time each night. Tonight we’re in your town. Tomorrow we could be in another country! But every place we stop, we invite kids like you to join us….”\n \n“Thanks for the invitation,” you say, “but I gotta go.”\n \n“I’m sorry.” The lady chuckles. “You can never escape from the Carnival of Horrors,” she says solemnly. “Unless …”\n \n<!-- Page 106 -->\n \n“Unless what?” you scream. “Tell me!”\n \n“You can escape the Carnival of Horrors if you leave before closing time.”\n \n“When is closing time?” you shoot back.\n \n“When the last ride stops….” the lady whispers. “At midnight.”\n \nYou glance at your watch — 11:40. Twenty minutes — that’s not so bad. But how do you get out of here?\n \nAs if the lady can read your mind, she says, “There’s only one right way.”\n \n<!-- Insert chanting sound Fx -->\n \nThen all around you, the crowd begins to chant. \n\n“ONLY ONE RIGHT WAY, ONLY ONE RIGHT WAY.” They repeat it over and over again.\n \n“What is it?” you scream. “Which way?”\n \nIt’s useless. They’re not going to tell you.\n \nBut it’s not midnight yet. There’s still time to figure it out.\n\n<!-- Insert tremble sound Fx -->\n \nUntil the floor begins to tremble. And the walls begin to shake. \n \nEarthquake!\n \n<!-- Page 42 -->\n \n<!-- Insert tremble sound Fx --> \n\nA wave of panic washes over you as the walls crumble around you. You throw your arms over your head and close your eyes.\n \nThen silence. The shaking stops.\n \nWhen you open your eyes, the room and all the costumed people have vanished. And you are outside — in the rides area! But the biggest surprise of all is that you spot Patty and Brad!\n \n“Boy, am I glad to see you,” you say, racing over to them. “Where have you guys been?”\n \nBrad shakes his head. “You wouldn’t believe the rides we were on!”\n \n“We’ve got to get out of here before midnight,” you say. Quickly, you tell your friends about the warning from the lady with the red parasol.\n \n“No problem,” Patty says. “Look. I’m sure the exit is right over there past that ride called the Hall of the Mountain King.”\n \n“No, it’s that way — near the sign that says ‘Halloween Express,’” Brad insists.\n \nDo you think the exit is near Halloween Express or Mountain King?" }, reprompt: { ssml: "Is the exit is near Halloween Express or Mountain King?" } } ] }, forward: { HalloweenExpressIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneOhEightAndFiftyFourHandler" } ], MountainKingIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneOhSevenAndSeventyFiveHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-11T15:08:27.422Z", name: "Page 117 and 106 and 42 NO Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneSeventeenAndOneOhSixAndFortyTwoNOHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.062001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneTenHandler: [ { name: "Page 110", outputSpeech: { ssml: "<!-- Page 110 -->\n \nThis one is for real. Maybe it’s the way he stares into your eyes. Or maybe it’s the rows and rows of razor-sharp teeth jutting from his mouth.\n \nYou take a step back. He takes a step closer. A drop of his drool drips on your hand.\n \n<!--Insert sizzle sound fx -->\n \nIt sizzles and burns.\n \nThis is the end, you figure. You’ll never escape the Carnival of Horrors. Never see your family or Patty and Brad again.\n \nThe monster lifts his gigantic, clawed hand. He waves it over your head. And you wait for the searing pain as it plunges down to strike you.\n \nBut that’s not what happens.\n \nThe monster slowly lowers his hand and clutches at his own neck, and then — pulls his own head off! And when you discover what’s underneath, you know you’re still in big trouble!\n \nWhat do you think is underneath the robot head?" }, reprompt: { ssml: "What do you think is underneath?" } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneThirtyThreeAndOneSeventeedHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T13:41:17.972Z", name: "Page 110 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneTenHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.071001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneThirteenAndSixteenHandler: [ { outputSpeech: { ssml: "<!--Page 113 -->\n \nHelp some freaks? That’s a good one! You laugh.\n \nYou think about Madame Zeno, the fire, and the disappearing tent. Totally cool! You wonder who thought up such awesome special effects.\n \nYou can’t wait to tell Brad and Patty all about it.\n \nYou search for your friends in the big wooden booths that line the midway. Instead, you find incredible games of chance. Some test your eye-hand coordination. Others require pure luck. But they all offer the most amazing prizes you’ve ever seen — phones, video games, fifteen-speed mountain bikes. You can’t wait to play!\n \nYou spot a booth across the midway with a crowd gathered in front. That’s odd, you think. Didn’t Big Al say we were the only people at the carnival tonight? You wonder if your friends are in the crowd. You move closer.\n \n“Oh. I get it,” you say aloud. “These people must work at the carnival.”\n \nYou’re about to call out to them. Until you see their eyes. Strange, haunted eyes.\n \n<!--Page 16 -->\n \n“Hi!” you say to Big Al. “Who are all those people?”\n \nHe doesn’t really answer your question.\n \n“Welcome to the Carnival of Horrors,” he says. “You must play or pay. We have many games on our midway. You must play two.” He practically spits the word must out. “If you succeed, you can win prizes. But if you lose, you pay with your life!”\n \nBoy, he’s really laying it on thick, you think. But it’s a pretty cool gimmick. “Okay, I’ll play a game. Then I’ve got to go home.”\n \n“No one goes home,” Big Al says, “until they play. You must play two games. And survive.”\n \n“Okay. Okay,” you mutter to yourself.\n \nYou glance around the midway at the two closest games. Mission to Mars and the Wheel of Chance. You have to pick one to start, or you’ll never get out of here.\n\nMission to Mars or the Wheel of Chance, which do you choose? " }, reprompt: { ssml: "Mission to Mars or the Wheel of Chance, which do you choose? " } } ] }, forward: { MissionToMarsIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "MissionToMarsPageSeventyTwoHandler" } ], WheelOfChanceIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "WheelOfChancePageEightHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T19:37:02.189Z", name: "Page 113 and 16", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneThirteenAndSixteenHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.082001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneThirtyAndOneOhOneHandlerI: [ { name: "Page 130 and 101", outputSpeech: { ssml: "<!-- Page 130 -->\n \nYou and your friends squeeze into the cannon.\n \n“Ouch! You’re sitting on my hand,” Brad whines.\n \nBut you don’t have time to apologize.\n \n“Do you smell something … burning?” you ask.\n \n<!-- Insert explosion sound Fx --> \n\nBOOM! \n\nThere’s a tremendous explosion. You fly through space. You are headed for a fence that encloses the carnival, and the field beyond.\n \nWill you make it out of the park?\n \n<!-- Page 101 -->\n \nYou make it! You make it out of the park!\n \nYou also make it out of the state!\n \nIn fact, the last time anyone saw you, Patty, and Brad, you were all a tiny blip on NASA’s radar screen.\n \nCongratulations! You escaped from the Carnival of Horrors.\n \nHappy landings!\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T15:22:41.765Z", name: "Page 130 and 101 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneThirtyAndOneOhOneHandlerI", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.050001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneThirtyThreeAndOneSeventeedHandler: [ { name: "Page 133 and 117 and 106", outputSpeech: { ssml: '<!-- Page 133 -->\n \nThose eyes behind the alligator snout — those beady eyes. You should have recognized them before. It’s Big Al.\n \n“Hey! You did a great job here,” he says warmly. “You’ve really got the stuff for the Carnival of Horrors.”\n \n“Uh, thanks,” you mumble. “But I really have to go home now.”\n \n“What’s the rush?” he asks, patting you on the shoulder. “Aren’t you having fun?”\n \nFun? you think. Crushed between solid walls. Then attacked by a bulging-eyed monster. Fun? No. This isn’t fun. This is weird.\n \n“Uh, yeah. It’s been really great. But, um, I really do have to get home,” you stammer. “So if you’ll just take me to wherever Patty and Brad are — and show us the way out — we’ll be going.”\n \n“I’m afraid that isn’t possible,” Big Al says. “Just open the door and you’ll understand.”\n \n<!-- Page 117 -->\n\n<!-- Insert open door sound fx -->\n \nYou open the door and enter a room bursting with people who seem to be waiting for you. You think that’s weird until you study them — and realize something even stranger. They’re all dressed up in old-fashioned costumes.\n \n“Welcome to the Carnival of Horrors,” a tall woman with a red parasol says, smiling. “Nice of you to join us.”\n \nThe Carnival of Horrors. The words send shivers down your spine.\n \nThe woman with the parasol whispers in your ear, “Do you want to know the secret?"' }, reprompt: { ssml: "Yes or no, do you want to know the secret?" } } ] }, forward: { NoIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneSeventeenAndOneOhSixAndFortyTwoNOHandler" } ], YesIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneOhSixAndFourtyTwoHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T14:15:21.732Z", name: "Page 133 and 117 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneThirtyThreeAndOneSeventeedHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.055001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneThirtyTwoAndTwentyOneHandler: [ { name: "Page 132 and 21", outputSpeech: { ssml: "<!-- Page 132 -->\n \nThe fortune-teller said this number might save your life. But how?\n \nThen you see it. In the corner. A tall silver locker with the number 132 painted in red.\n \n“In here,” you say, opening the door to the locker. You push Patty and Brad inside.\n\n<!-- Insert locker rattle and shake sound fx -->\n \nAs soon as you close the door, the locker begins to rattle and shake. You’re nearly blinded by a bright, white light. You hear a loud whooshing sound. And then all is silent. The door pops open — and you’re amazed at what you see.\n \n<!-- Page 21 -->\n \nYou’re outside — standing in Bennet’s Field — gazing at the fence that surrounds the carnival.\n \n“I guess we’ll have to wait until tomorrow night when the carnival opens,” Brad says.\n \n“No way,” Patty says. “Let’s climb the fence.”\n \nWhat’s going on here?\n \nYou guessed it. The silver locker was a time machine. You’ve gone back in time to the first moment you spotted the carnival. Now it appears as if you have to start all over again — fighting horror after horror, right up to …\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T19:13:52.983Z", name: "Page 132 and 21 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneThirtyTwoAndTwentyOneHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.074001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneTwentyEightAndSeventyHandler: [ { name: "Page 128 and 70 ", outputSpeech: { ssml: "<!-- Page 128 -->\n \nYou squeeze into the choo-choo and scrunch down. 11:59.\n \nLights from the carnival people’s torches sweep over you. Their foul smell fills your lungs.\n \nThe blood pounds in your temples.\n \nYou’re sure they’re going to find you. But you’re trapped now.\n \nThere’s no way out.\n \nYou hear someone shout in the distance. “Closing time!” \n\n<!--Insert chime sound Fx --> \n\nAnd then you hear a bell start to chime …\n \n… Midnight!\n \n“One, two, three,” Brad counts the chimes.\n \nYou want to strangle him!\n \n“Four, five …”\n \nSuddenly, the kiddie train starts to move.\n \n“Six … seven … eight …”\n \nYou sit up and what you see is the biggest shock of this whole horrible night….\n \n<!-- Page 70 -->\n \n“Nine … ten …”\n \n“Brad, shut up. Look at this!”\n \nYou point to the letters on the front of the train car.\n \nYou’ve been staring at them the entire time. Why didn’t you notice them before?\n \n“What about the letters?” Patty says sharply.\n \n“Eleven …”\n \n“Don’t you see what they say?” you shoot back.\n \n“ ‘Right-Way Railroad,’ ” Patty reads. “So what?”\n \nThe chants of the merry-go-round people echo in your head. There’s only one right way. There’s only one right way.\n \nCould it be?\n \n“Twelve!”\n \nWhat is the latest time you’ve ever stayed up until?" }, reprompt: { ssml: "What is the latest time you’ve ever stayed up until?" } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageFiftyTwoAndTwentyFourHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T15:33:39.384Z", name: "Page 128 and 70 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneTwentyEightAndSeventyHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.053001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneTwentyFiveAndFourtyThreeHandler: [ { name: "Page 125 and 43", outputSpeech: { ssml: "<!-- Page 125 -->\n \n“This way!” You wave to Patty and Brad.\n \nThe three of you turn to the left and keep running — \n\n<!-- Insert water sound Fx --> \n\nstraight into a pond!\n \n“Why didn’t you tell us to stop?” Patty whines.\n \n“Don’t complain to me!” you shout back. “We followed you through the fence!”\n \nYou turn around and slog your way back to shore. Patty and Brad make it there first. You are a few feet away — when you see it.\n \nAn alligator.\n \nWith its mouth gaping open — revealing two rows of razor-sharp teeth.\n \nYou freeze.\n \nPatty spots the alligator and yells, “Quick! There’s a log! Jump on it!”\n \nYou scramble up on the log, but it’s no use. You’re still an easy target.\n \nThe alligator opens its huge mouth even wider. He slithers right up to the log. And you can tell he’s ready. Ready to crunch down on you!\n \n<!-- Page 43 -->\n \nYou are about to scream. It seems like the only sensible thing to do.\n \nAnd then you remember the sign.\n \nReptile Petting Zoo.\n \nYou have an idea. It’s a dangerous idea, you know. But everything in this carnival is dangerous.\n \nYou can feel the alligator’s hot breath on your arm. But instead of pulling your arm back, you stretch it out!\n \n“What are you doing?” Patty screams.\n \nYour fingers reach out. Out over the alligator’s open snout to the top of his head.\n \nAnd you pet him.\n \n“Nice alligator,” you purr as you stroke his scaly head.\n \nYour arm trembles, but you don’t stop. And slowly — very slowly — the creature’s mouth begins to shut.\n \nThen he rolls over and falls asleep!\n \nYou slip quietly off the log, charge for the shore — and plow right into Big Al!\n \n“Well, well, well. Look who we have here,” Big Al sings out. “Come with me. It’s time for The Final Challenge.”\n \nYou have no choice, you follow Big Al. Tell Al what you think of his carnival." }, reprompt: { ssml: " Tell Al what you think of his carnival." } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageEightyFourHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T17:45:22.180Z", name: "Page 125 and 43 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneTwentyFiveAndFourtyThreeHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.051001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneTwentyFourAndOneTwelveHandler: [ { name: "Page 124 and 112", outputSpeech: { ssml: "<!-- Page 124 -->\n\n<!-- Insert wheel spin sound Fx -->\n \n“FI-NAL! FI-NAL! FI-NAL!” you hear the crowd yelling as you spin round and round. \n\nYou’re getting dizzy. Really dizzy. So dizzy that you faint.\n \n<!-- Page 112 -->\n \n<!-- Insert splash sound Fx --> \n\nYeoow! Someone splashes cold water in your face. Your eyes open.\n \n“Come on! Wake up! It’s almost show time,” a raspy voice says.\n \n“Show time?” you say, gazing into the eyes of a goblin. “What show?”\n \n“The Freak Show. You are the Amazing Three-Headed Monster.”\n \nYou glance around and see Patty on one side of you and Brad on the other. You try to pull away from them, but you can’t.\n \n“We’re stuck together with some kind of glue,” Patty says.\n \n“It isn’t glue,” Brad argues.\n \n“Is too!”\n \n“Is not!”\n \nWell, whatever it is — you are stuck. Stuck between your arguing friends for a long, long time — like forever. And here’s something you can’t argue about. This really is …\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T18:08:10.808Z", name: "Page 124 and 112 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneTwentyFourAndOneTwelveHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.067001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneTwentyOneAndSixtyThreeHandler: [ { name: "Page 121 and 63", outputSpeech: { ssml: "<!-- Page 121 -->\n \nYou grab the sides of the slide and lower yourself down. The second you sit, the slide’s floor tilts up beneath you and propels you forward.\n\n\nYou shriek!\n \nYou raise your arms and scream louder. You slide faster and faster. In total darkness. Darkness so black, you can’t even see your own feet in front of you.\n \nYour eyes dart frantically from side to side. Faces suddenly appear in the darkness in bright flashes of light. Faces of hideous monsters with deformed heads and oozing flesh.\n \nBut you’re moving too fast to focus on them. You slide and slide — until the faces stop flashing and you’re covered in the thick, heavy blackness again.\n\n<!--Insert scream sound Fx -->\n \nYou scream as you round a sharp curve. Your head is spinning. You pick up speed.\n \nWhen will it end?\n\n<!--Insert scream sound Fx -->\n \nThen you hear the screams. Chilling screams that echo through the darkness. \n\nOh, no! You must have picked the Doom Slide!\n \n<!-- Page 63 -->\n \n<!--Insert bump sound Fx -->\n\nBump.\n\n<!-- Insert chute and langing sound Fx -->\n\nA chute opens up. You land headfirst on soft grass.\n \nYou blink several times. A long sigh escapes from your lips. It wasn’t the Doom Slide after all.\n \nAs you climb to your feet you hear someone call your name.\n \nYou glance up and shout for joy. It’s Brad! And Patty’s there, too!\n \nYou tell them about your scary ride on the slide — about how you thought you’d slide forever.\n \n“Cool!” Patty exclaims. “Let’s all ride it this time!”\n \n“No!” you tell her. “This carnival is too weird. And dangerous. Something’s not right. We have to get out of here. Now!”\n \n“Yeah,” Brad agrees. “The faster, the better.”\n \n“I have an idea,” Patty announces. You and Brad huddle around her. “I spotted a back way out of here. But it’s a little risky. We have to squeeze through a barbed-wire fence — and it’s guarded by the carnival’s security. But we should try!”\n \nDo you follow Patty or take the back way out?" }, reprompt: { ssml: "Do you follow Patty or take the back way out?" } } ] }, forward: { TakeTheBackWayOutIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageEightySixHandler" } ], FollowPattyIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageFourtyEightAndSixtyHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T17:23:24.762Z", name: "Page 121 and 63 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneTwentyOneAndSixtyThreeHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.062001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneTwentySevenHandler: [ { name: "Page 127 Handler", outputSpeech: { ssml: " \n<!-- Page 127 -->\n \nYou’re not fast enough to get away from the ghost. You’re running now, but the ghost swoops down in front of you. You plow into him — and pass right through him!\n \nThe carnival people are swarming after you. They don’t want you to leave the carnival.\n \n“Hurry!” you yell to your friends — only three minutes to midnight! You dash off in one direction, then another. The carnival people are approaching from every which way. They carry torches with flames that leap high in the air.\n \nYou steal a glance at your watch — 11:58.\n \n“We can’t let them catch us!” you scream. “Let’s hide!”\n \nBut where can you hide? Up ahead you see a gigantic cannon. All three of you could fit easily in there.\n \nYou also spot a baby ride — the baby choo-choo train — maybe you could squeeze into that. Quick! Pick one — and hope for the best.\n \nDo you choose the cannon or the choo-choo?" }, reprompt: { ssml: "Cannon or the choo-choo. Which one will it be?" } } ] }, forward: { ChooChooIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneTwentyEightAndSeventyHandler" } ], CannonIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneThirtyAndOneOhOneHandlerI" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T15:12:11.915Z", name: "Page 127 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneTwentySevenHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.061001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageOneTwentyThreeAndTwentyFiveHandler: [ { name: "Page 123 and 25", outputSpeech: { ssml: "<!-- Page 123 -->\n \n“The Final Challenge,” Big Al announces. And the crowd goes wild.\n \nThen he turns to you and says, “Remember — the fun games are over. Now you are playing for your life.”\n \n“You go first,” Big Al says to you. You see Brad and Patty taken off to the side by a huge man in a black hood.\n \nTwo red-haired goblins in clown costumes scurry up the steps. To your surprise, they fit you with new high-top sneakers — sneakers with metal studs running up the backs. This is going to be some kind of race, you think. But then you change your mind — when they snap a heavy, metal helmet on your head.\n \nThe crowd’s cheers grow louder. Big Al throws a switch. The curtain behind you parts and — \n\n<!--Insert zing sound Fx -->\n\nWhammo! \n\nThe wall behind the curtain turns into a super magnet. You go zinging to the wall like a dart to a bull’s-eye.\n \n<!-- Page 25 -->\n \nSeconds later your head and the back of your feet slam into the wall. You’re hanging upside down — in the middle of a gigantic magnetic wheel with 3 numbers around the edge with “spin again” mixed in around them!\n \n“Are you ready for The Final Challenge?” Big Al asks.\n \n“Of course not!” you say. “LET ME DOWN!”\n \n“We’ll let you down — but not until you face The Final Challenge. One spin will decide your fate. If you win, you go. If you lose, you stay here forever.”\n \nWill that be your fate?\n \nBig Al approaches the wheel.\n \nBrad and Patty are holding on to each other.\n \nYour heart is pounding.\n \nYour hands are sweating.\n \nThis is it. One spin. <!-- Insert wheel spin sound Fx -->\n \nHe gives the wheel — with you on it — a hard turn. Where will it stop? Guess a number between 1 and 3!" }, reprompt: { ssml: "Guess a number between 1 and 3!" } } ] }, forward: { "SlideNumberIntent|NumberIntent": [ { type: "START", intentId: "PageFourtyFourHandler", slotMatch: { name: "number", value: 1, operation: "==" } }, { type: "START", intentId: "PageSeventyFourAndOneThirtyOneAndOneSixteenHandler", slotMatch: { name: "number", value: 2, operation: "==" } }, { type: "START", intentId: "PageSeventyThreeAndOneThirtyOneAndOneSixteenWITHOUTBLOODHandler", slotMatch: { name: "number", value: 2, operation: "==" } }, { type: "START", intentId: "PageOneTwentyFourAndOneTwelveHandler", slotMatch: { name: "number", value: 3, operation: "==" } } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T17:54:55.301Z", name: "Page 123 and 25 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageOneTwentyThreeAndTwentyFiveHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.091001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageSeventeenAndEightyFourAndOneTwentyThreeAndTwentyFiveHandler: [ { outputSpeech: { ssml: "<!--Page 17 -->\n \nYou take a few steps along the midway hoping you’ve won enough prizes and points. You notice the crowd of people surrounding Big Al. They’re still chanting, “PAY OR PLAY. PAY OR PLAY.”\n \nYou break through the crowd and grab Big Al’s arm. “Hey! Do you know where my friends are?”\n \n“Certainly,” Big Al says, pointing up ahead. “They’re right over there!”\n \n“Patty! Brad!” you shout as you rush up to them. “Come on! We’ve got to go! This carnival is evil!”\n \nBut before they can say a word, Big Al’s voice booms from behind you. “Not before The Final Challenge!”\n \n<!--Page 84 -->\n \nBig Al shoves you and your friends into a huge red tent. It seems to be set up for some kind of show. Red carpeted steps lead up to a platform, which sits under a golden arch. The arch twinkles with a thousand colored lights that spell out: FINAL CHALLENGE.\n \nTrumpets blast as people flood into the viewing area. As they march in, they clap their hands and yell, “FI-NAL. FI-NAL.”\n \nBig Al leads you up the carpeted steps. You are standing on the platform now — in front of a shimmering curtain that hangs down from the arch.\n \nThe crowd begins to chant, “SUD-DEN DEATH. SUD-DEN DEATH.”\n \n<!-- In prompt voice -->\n\nWhat do you think that means?" }, reprompt: { ssml: " What do you think that means?" } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { intentId: "PageOneTwentyThreeAndTwentyFiveHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T14:48:02.884Z", name: "Page 17 and 84", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageSeventeenAndEightyFourAndOneTwentyThreeAndTwentyFiveHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.072001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageSeventyFourAndOneThirtyOneAndOneSixteenHandler: [ { name: "Page 74, 131, 116", outputSpeech: { ssml: "<!-- Page 74 -->\n \n<!-- Insert wheel spin sound Fx -->]\n\nRound and round you go. The world is a blur of colors. You can hear the crowd screaming. “FI-NAL! FI-NAL!”\n \nAnd the wheel stops.\n \n“Ahhhhhh,” the crowd gasps.\n \nWhat does it mean?\n \n“YOU WIN,” Big Al says. “Now come this way to collect your prize and go home.”\n \n<!-- Page 131 -->\n \nSUCKER!\n \nYou didn’t really think you could get out this easily, did you?\n \nIt’s called the Carnival of Horrors.\n \nHorrors! You need to face a lot more horrors — and then maybe you’ll escape.\n \n<!-- Page 116 -->\n \n<!-- Insert zap sound Fx -->]\n\nZAP!\n \nBig Al throws a switch and the magnet shuts off. You come flying down to earth — right where Brad and Patty are waiting.\n \n“I played your dumb game. Now, let us go!” you tell Big Al.\n \nBig Al doesn’t answer. But the crowd does. “SUD-DEN DEATH! SUD-DEN DEATH! SUD-DEN DEATH!”\n \nThe crowd surges toward you. They are not friendly. They back you up against a wall. You’re trapped.\n \nTrapped by a mob!\n \nYou reach into your pocket, hoping to find something that might help you. Something to save you …\n \nyou remember something from earlier that might help, what is it?" }, reprompt: { ssml: "You reach into your pocket, hoping to find something that might help you. Something to save you …\n \nyou remember something from earlier that might help, what is it?" } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageNinetySevenAndOneTwentyNineHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T18:37:07.775Z", name: "Page 74 and 131 and 116 WITH BLOOD Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageSeventyFourAndOneThirtyOneAndOneSixteenHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.066001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageSeventyNineAndSixtySevenHandler: [ { name: "Page 79 and 67", outputSpeech: { ssml: "<!-- Page 79 -->\n \nThe doctor leans over. He’s so close now, his sour breath fills your nostrils. Then his fingertips brush your hand and — \n\n<!-- Insert foot strike sound Fx -->]\n\nPOW! Your foot flies into his stomach! A direct hit!\n \nBut nothing happens.\n \nHe doesn’t scream. He doesn’t even moan. In fact, he doesn’t seem to notice at all.\n \nHe simply smiles at you.\n \nNow you’re scared. Really scared. But you know you have to do whatever it takes to get out of there. You have to find your friends and escape from this Carnival of Horrors.\n \nYou gather up every ounce of courage and strength you have — and kick him once more. Harder!\n \nAnd this time something does happen — BIG TIME!\n \n<!-- Page 67 -->\n \n<!-- Insert thump sound Fx -->]\n\nThrumpff! Your foot plows into the doctor’s stomach again. But this time, it smashes right through it. And hits … solid steel!\n \nThe crunch of metal echoes in the room — along with the doctor’s screams. “Aiiii!” he wails like a siren.\n \nYou gaze into the gaping hole your sneaker made. Thousands of circuits and wires burn and crackle inside it. The doctor is a robot! Well, an ex-robot now. Your kick totally destroyed him.\n \nThat’s the good news.\n \nThe bad news is headed for you. It’s the monster with the blue horns and red, bulging eyes.\n \nYou scramble out of the net and dash toward the door. But the monster is too quick for you.\n \nDo you try to dodge or fight back?" }, reprompt: { ssml: "Do you try to dodge or fight back? " } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageSixtySevenAndNinetyOneAndOneTwentyTwoHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T20:48:35.963Z", name: "Page 79 and 67 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageSeventyNineAndSixtySevenHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.070001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageSeventyOneHandler: [ { name: "Page 71 Handler", outputSpeech: { ssml: "<!-- Page 71 -->\n \nSorry. It’s not your lucky day. As you dash toward the sign, the giant crane scoops the three of you up and drops you off into a hollowed-out log. You barely have time to sit up straight before the craft reaches the waterfall!\n \n<!-- Insert water/scream sound Fx -->]\n\nYou hold your breath as the log teeters on the fall’s edge. As it plunges over, you scream.\n \n<!-- Insert water/scream sound Fx -->]\n\nA hard spray smacks you in the face and drenches your clothing as you race down the long slide. At the bottom, the log hits a pool of water and sinks.\n \nYou’re still holding your breath as you wait to bob to the surface again. But it never happens. You keep going down.\n \nYour last thought is that you’re going to set a world’s record for holding your breath underwater. Maybe next time you dive in you’ll have better luck.\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T17:18:39.782Z", name: "Page 71 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageSeventyOneHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.056001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageSeventySixHandler: [ { name: "PAge 76", outputSpeech: { ssml: "<!-- Page 76 -->\n \nYou dig deep into the side pocket of your jeans — and find it! The chocolate bar you won.\n \nIt’s a good thing you didn’t eat it all — but will the vulture go for it?\n \nWithout warning, the big bird starts his final approach, diving straight for the nest. You pull out the candy and wave it frantically in front of him. “Treat! Treat!” you holler. These words make your dog at home go wild. But will it work on the vulture?\n \nYes! He cracks open his claws — just enough for you to wiggle loose. Then you’re falling, falling.\n \nYou’ve landed on a giant trampoline.\n \n<!-- Insert trampoline sound Fx -->]\n\nFwanggg!\n \nNow you’re going up again. Higher this time. Now you’re falling again.\n \n<!-- Insert trampoline sound Fx -->]\n\nFwanggg — you’ve bounced up even higher this time.\n \nEvery life has its ups and downs, but it looks as if you’ll be bouncing up and down forever — and boy, is it fun!\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-09T19:24:23.536Z", name: "Page 76 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageSeventySixHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.062001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageSeventyThreeAndOneThirtyOneAndOneSixteenWITHOUTBLOODHandler: [ { name: "Page 74 and 131 and 116 ", outputSpeech: { ssml: "<!-- Page 74 -->\n \n<!-- Insert weel spin sound Fx -->]\n\nRound and round you go. The world is a blur of colors. You can hear the crowd screaming. “FI-NAL! FI-NAL!”\n \nAnd the wheel stops.\n \n“Ahhhhhh,” the crowd gasps.\n \nWhat does it mean?\n \n“YOU WIN,” Big Al says. “Now come this way to collect your prize and go home.”\n \n<!-- Page 131 -->\n \nSUCKER!\n \nYou didn’t really think you could get out this easily, did you?\n \nIt’s called the Carnival of Horrors.\n \nHorrors! You need to face a lot more horrors — and then maybe you’ll escape.\n \n<!-- Page 116 -->\n \n<!-- Insert zap sound Fx -->]\n\nZAP!\n \nBig Al throws a switch and the magnet shuts off. You come flying down to earth — right where Brad and Patty are waiting.\n \n“I played your dumb game. Now, let us go!” you tell Big Al.\n \nBig Al doesn’t answer. But the crowd does. “SUD-DEN DEATH! SUD-DEN DEATH! SUD-DEN DEATH!”\n \nThe crowd surges toward you. They are not friendly. They back you up against a wall. You’re trapped.\n \nTrapped by a mob!\n \nSing a line from your favorite song to get the mob to leave you alone." }, reprompt: { ssml: "Sing a line from your favorite song to get the mob to leave you alone." } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageTwentySevenAndFiftyFiveHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-09T16:33:23.335Z", name: "Page 74 and 131 and 116 WITHOUT BLOOD Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageSeventyThreeAndOneThirtyOneAndOneSixteenWITHOUTBLOODHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.073001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageSeventyThreeHandler: [ { name: "Page 73", outputSpeech: { ssml: "<!-- Page 73 -->\n \nYour reflexes are great. You jumped out fast enough and escaped the ghost — that ghost. But you didn’t see the other one behind the car — waiting for you.\n \nYour heart hammers away in your chest as it circles you. Around and around and around.\n \n“It’s all right,” you tell yourself over and over. “It’s not real. This is just a ride in an amusement park.”\n \nYou’re still telling yourself that as the ghost plucks you off your feet.\n \nHis black lips part.\n \nHe opens his mouth — wider and wider. Until it’s as wide as an entrance to a cave.\n \nThen he stuffs you inside.\n \nInstantly, you feel lightheaded, then light all over. You peek down at your hands.\n \nYou can see straight through them. You’ve been turned into a ghost! And as your senses fade, you hear a distant bell chime twelve times. Too bad. The Carnival of Horrors will be one of your favorite haunts — forever!\n \nTHE END." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T15:08:18.764Z", name: "Page 73 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageSeventyThreeHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.072001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageSixHandler: [ { name: "Page 6-7", outputSpeech: { ssml: "<!--Page 6 -->\n \n“Let’s do it!” you say to your friends. “Let’s climb the fence!”\n \nPatty is halfway up before you finish speaking. You let Brad go next. You’re last.\n \n<!-- Insert climbing sound Fx -->]\n\nIt’s a hard climb up. There’s really no place on the fence to get a good grip. But you make it to the top, swing your legs over, and tumble down. You land on the grass. You’re inside!\n \n<!-- Insert carnival sound Fx -->]\n\nYou and your friends gaze around. It’s pretty dark — the only light comes from torches. At first the carnival looks the same as it always does. Dinky rides. Hot dog wagons. Then the lights start to flicker on in every corner of the field — the rides start to move. It’s as if the whole place is magically coming to life.\n \n“Hey! Look at that giant roller coaster!” you exclaim, pointing up ahead. “They never had a roller coaster before!”\n \n“Yeah,” Brad agrees. “And the whole place is a lot bigger than last year!”\n \n“This is awesome!” Patty says as she sprints toward the rides.\n \n<!-- Page 7 -->\n \nYou and Brad take off after Patty. You all stop in front of the roller coaster.\n \n<!-- Insert carnival sound fx -->\n\n“Wow!” Patty says as she gazes up at it. “It’s like a rocket to outer space!”\n \nBeyond the roller coaster, you spy a castle surrounded by a moat. And a spooky-looking haunted house sitting high atop a hill.\n \n“These are the coolest rides I’ve ever seen!” you say. “They still have that dumb choo-choo train over there,” you point out, “but we could ride this stuff all night and never go near it!”\n \nPatty grabs your arm and tugs you over to the other side of the carnival — to the midway. Brad races after you.\n \n“Hey! Where are all those dinky wooden booths from last year?” you ask as you gawk at the amazing games of chance.\n \nThey’re gone. And in their place are giant video games and huge spinning wheels studded with hundreds of blinking colored lights!\n \n“Get a load of that!” Brad suddenly cries out.\n \nYou and Patty spin around.\n \nYou can’t believe what you see!\n \n<!-- Page 87 -->\n \nYou’re staring at a sign that reads: WORLD’S FREAKIEST FREAK SHOW! The three of you gape at the pictures.\n \nThere’s the Three-Headed Man with the ugliest collection of faces you’ve ever seen. And the Snake Lady — a young blond girl with a beautiful face and the body of a slithering snake.\n \n“This is, uh — uh —” you start to say. But you don’t finish. Because a large hand has come down on your shoulder. Hard.\n \nYou slowly turn and gaze up at a huge man with shoulders wider than a refrigerator. He has coal-black eyes with a thick mustache to match. He looks strong enough — and mean enough — to pitch you over the fence with one hand.\n \n“What are you doing?” his deep voice booms. “You’re not allowed in here,” he says, pointing directly at you.\n \nYou’re sorry. Give your best apology and hope they accept it.\n" }, reprompt: { ssml: "You’re sorry. Give your best apology and hope they accept it." } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageFourHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T16:56:08.358Z", name: "Page 6 and 7 and 87 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageSixHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.074001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageSixtyEightHandler: [ { outputSpeech: { ssml: "<!-- Page 68 -->\n \nYou slowly lower yourself onto the slide. You start to stretch out your legs when the bottom tilts underneath you and throws you forward. \n\n<!-- Insert slide sound Fx -->]\n\nYou’re sliding! Fast!\n \nThe surface must be made of some kind of special material because you’re zooming down at top speed.\n \nYou hold your breath as you fly through the blackness. A bump sends you bouncing into the air. \n\n<!-- Insert scream sound Fx -->]\n\nYou scream. And scream.\n \nWhen is it going to end?\n \nOh, no! Could this be the Doom Slide?\n \n<!-- Insert scream sound Fx -->]\n\nYou hear screams echo in the darkness. You twist around. But you don’t see anyone.\n \nThe ghostly screams grow louder — in front of you, next to you, behind you. Screaming and sliding. And sliding. Never stopping.\n \nYou gasp for breath. And then you hear it.\n \nA voice cuts through the blackness. Through the screams. A voice that cries, “Welcome to the rest of your life. Welcome to the Doom Slide!”\n \nThe End." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T20:07:18.692Z", name: "Page 68 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageSixtyEightHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.070001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageSixtyFourHandler: [ { name: "Page 64", outputSpeech: { ssml: "The House of Horrors! You have to see it. You just have to!\n \n“I’ll catch up with you guys later,” you call to Patty and Brad. “I’m going to check out the haunted house.”\n \nYou glance down at your map for directions. The rickety wooden bridge over to your left appears to lead straight there.\n \n<!-- Insert plank sound Fx -->]\n\nAs you start across the bridge, the wooden planks creak under your feet. Then the bridge begins to sway. You look down. Way down. The bridge spans a deep, rocky gorge. Gulping, you grab the handrail. You move slowly. A strong wind blows up from the canyon below. The bridge is swaying wildly now, tossing from side to side.\n \n<!-- Insert lightning sound Fx -->]\n\nA massive spear of lightning splits the sky. Thunder rumbles so loudly you jump and lose your balance. “Help!” you scream as you tumble right over the side — and plunge toward the jagged rocks below!\n \nDo you grab for the side of the bridge or flap your arms to try to fly?" }, reprompt: { ssml: "Do you grab for the side of the bridge or flap your arms to try to fly?" } } ] }, forward: { FlapYourArmsIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageThirtyHandler" } ], GrabTheSideOfTheBridgeIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageFortySixHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T17:53:41.738Z", name: "Page 64 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageSixtyFourHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.099001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageSixtyNineFortuneTellerHandler: [ { name: "Page 68", outputSpeech: { ssml: "<!-- Page 69 -->\n \n“Karru marri odonna loma molonu karrano.” You say the magic words and — the dummy comes to life!\n \nHe opens his mouth and speaks. “Hey, you. Your face reminds me of a wart I once had removed.”\n \n“Come on,” you plead. “We’re the ones who brought you back to life. Aren’t you going to be nice to us? We need your help.”\n \n“I’m sorry,” the dummy says. “I’m sorry you’re so ugly….” Then he laughs at his own lame joke.\n \nYou stare at him and his face grows serious. “You brought me to life,” he says slowly, “but now you are mine.\n \n“Forever — until …\n \nWait! This isn’t the way this is supposed to end. Quick – you have one last chance. What was the number the fortune-teller told you?" }, reprompt: { ssml: "What was the number the fortune-teller told you?" } } ] }, forward: { OneThreeTwoIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneThirtyTwoAndTwentyOneHandler" } ], "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageSixtyNineTheEndIntent" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-09T16:40:07.011Z", name: "Page 69 Seen the Fortune Teller Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageSixtyNineFortuneTellerHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.075001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageSixtyNineHandler: [ { name: "Page 69", outputSpeech: { ssml: "<!-- Page 69 -->\n \n“Karru marri odonna loma molonu karrano.” You say the magic words and — the dummy comes to life!\n \nHe opens his mouth and speaks. “Hey, you. Your face reminds me of a wart I once had removed.”\n \n“Come on,” you plead. “We’re the ones who brought you back to life. Aren’t you going to be nice to us? We need your help.”\n \n“I’m sorry,” the dummy says. “I’m sorry you’re so ugly….” Then he laughs at his own lame joke.\n \nYou stare at him and his face grows serious. “You brought me to life,” he says slowly, “but now you are mine.\n \n“Forever — until …\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T17:35:53.145Z", name: "Page 69 No Fortune Teller Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageSixtyNineHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.090001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageSixtyNineTheEndIntent: [ { name: "Page 69 Actual End", outputSpeech: { ssml: "<!-- Page 69 -->\n\nThe Fortune Teller told you to remember that number. It’s almost like they could see the future. Too bad you couldn’t. All you’re going to see is…\n \nTHE END" } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-11T15:26:35.773Z", name: "Page 69 The End", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageSixtyNineTheEndIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.095001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageSixtySevenAndNinetyOneAndOneTwentyTwoHandler: [ { name: "Page 67, 91 and 122", outputSpeech: { ssml: "<!-- Page 67 -->\n \n<!-- Insert struggle sound fx -->\n\n His tentacle arms shoot out and snatch you. Giant suckers at the ends of his wrists circle your throat.\n \nYou gasp for air as the monster pins you against the wall. Can you free yourself from his oozing grasp?\n \n<!-- Page 91 -->\n \nThe red-eyed beast leans against you now, pressing you hard against the wall. The monster moves his face close to yours. The jagged horns at the top of his head nick your cheeks.\n \n<!-- Insert struggle sound fx -->\n\nYou can’t bear it anymore. You bring your hand up with all your might and shove his head away from yours.\n \nAs you watch in horror, the monster’s head rolls off its neck. The head tumbles to the floor and lands at your feet.\n \nThe eyes glance up at you, and you notice his hideous lips moving. “That hurt,” the head says. “That really h-h- …”\n \nHe never finishes. You’ve destroyed another robot!\n \n“Almost out of here,” you whisper to yourself. Now all you have to do is slip by the crusty, alligator-snout creature guarding the door.\n \n“You robots aren’t so tough,” you say to him with fake bravery.\n \n“Oh, really?” the scaly beast croaks. “Well, maybe not. But what makes you think that I am a robot?”\n \n<!-- Page 122 -->\n \nThe creature slides one step toward you, and with a burning stare says, “I am not a robot. I am not going to shut down. So don’t bother with any of your silly, human tricks!”\n \nYou stare at him. You study him hard. Is he lying? Is he a robot like the other two? Or could he be a lot more dangerous?\n \nYour knees begin to tremble when you think about never going home — never seeing your family and friends ever again. Tears start to sting your eyes. Angry tears! No carnival — not even a Carnival of Horrors — is going to defeat you!\n \nYou stare deeply into the evil eyes of the creature hovering before you.\n \nDo you think the creature is a robot or a real monster?" }, reprompt: { ssml: "Do you think the creature is a robot or a real monster?" } } ] }, forward: { RobotIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageEightyOneHandler" } ], RealMonsterIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneTenHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T20:53:41.842Z", name: "Page 67 and 91 and 122 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageSixtySevenAndNinetyOneAndOneTwentyTwoHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.071001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageSixtySixAndEightyHandlerIntent: [ { name: "Page 66 and 80", outputSpeech: { ssml: "<!-- Page 66 -->\n \nYou start up the brick path to the House of Horrors. Suddenly, someone sneaks up behind you and taps you on the shoulder. You spin around and jump back.\n \nStanding in front of you is a bony skeleton.\n \nAnd it talks.\n \n“Don’t go in there,” the skeleton says. “Or you’ll end up like me….”\n \nYou stare in terror at the hideous creature. Then you burst out laughing.\n \n“Wow! You guys really want to make the haunted house totally creepy. This is going to be great!” you say.\n \nYou’re still chuckling as you push open the giant oak door of the House of Horrors. \n\n<!-- Insert creaking sound Fx -->]\n\nIt swings back with a long, loud creak.\n \nYou step inside and find yourself in a narrow hallway. The door slams shut behind you and the hall turns darker than a starless night. “I can’t even see my hands!” you exclaim.\n \nYou stumble ahead slowly, pressing your palms against the walls to guide you.\n \nWhen will this tunnel end?\n \n<!-- Page 80 -->\n \nYou turn a corner and are instantly blinded by glaring lights.\n \nYou are standing in a room of mirrors. Walls. Floor. Ceiling. All mirrors!\n \nEverywhere you gaze, you are met with reflections of yourself! You take a few steps forward and — \n\n<!-- Insert bonk sound Fx -->]\n\nBONK! You hit your head on solid glass.\n \nYou move one step to the left, and a dozen copies of you move in that direction.\n \nTotally dizzy, you close your eyes. Maybe you can find the exit with your hands. Keeping your eyes shut, you walk until your palms hit against another glass wall. Then you hear a voice. “Come this way. Over here,” it calls.\n \nYou walk toward the voice — \n\n<!-- Insert bonk sound Fx -->]\n\nBONK — a solid wall again.\n \nFinally, your hands find an open doorway! It leads to a mirrored hallway that goes left and right.\n \nDo you go left or right?" }, reprompt: { ssml: "Do you go left or right?" } } ] }, forward: { TurnRightIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageTwentyNineAndSixtyFiveAndThirtyOneHandler" } ], TurnLeftIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneEighteenHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T18:36:15.163Z", name: "Page 66 and 80 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageSixtySixAndEightyHandlerIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.101001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageSixtyTwoHandler: [ { outputSpeech: { ssml: "<!-- Page 62 -->\n \n“Big Al has to free the freaks,” you say to Patty and Brad. “If he doesn’t, we’ll tell him we’re calling the police!”\n \n“Free the freaks?” Big Al says, bursting into the room. “The freaks are free to go any time. This prison is just part of the show. Did you pull that ‘free us’ joke on him?” Big Al laughs heartily.\n \n“He’ssss lying,” the Snake Lady says. “We’re prisonersssss.”\n \n“Oh, come now,” Big Al says. “You’re not prisoners.” And with that he unlocks all the cell doors. Then he turns to you and your friends.\n \n“As you can see, the freaks are free. Now, come with me. You haven’t even tried one game on the midway.”\n \n“Don’t go with him. It’sssss a trick!” the Snake Lady cries.\n\n Do you believe Big Al or the Snake Lady?" }, reprompt: { ssml: "Do you believe Big Al or the Snake Lady?" } } ] }, forward: { AlIsTellingTheTruthIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageEightyFourHandler" } ], SnakeLadyIsTellingTheTruthIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneOhTwoAndOneTwentyHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T20:10:37.346Z", name: "Page 62", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageSixtyTwoHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.074001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageTenHandler: [ { name: "Page 10 and 6 and 7", outputSpeech: { ssml: "<!-- Page 10 -->\n \nYou’ve decided not to sneak into the carnival? You’re going home instead? Well, it’s a good thing Patty usually makes all the decisions. Otherwise, you’d never have any fun! And this adventure would be over before it began!\n \nGo ahead. Take a deep breath. Then go climb the fence. You’re not scared — are you?\n \n<!-- Page 6 -->\n \nYou finally muster up the courage:\n \n“Let’s do it!” you say to your friends. “Let’s climb the fence!”\n \nPatty is halfway up before you finish speaking. You let Brad go next. You’re last.\n \n<!-- Insert climbing sound Fx -->\n \nIt’s a hard climb up. There’s really no place on the fence to get a good grip. But you make it to the top, swing your legs over, and tumble down. You land on the grass. You’re inside!\n \nYou and your friends gaze around. It’s pretty dark — the only light comes from torches. At first the carnival looks the same as it always does. Dinky rides. Hot dog wagons. Then the lights start to flicker on in every corner of the field — the rides start to move. It’s as if the whole place is magically coming to life.\n \n“Hey! Look at that giant roller coaster!” you exclaim, pointing up ahead. “They never had a roller coaster before!”\n \n“Yeah,” Brad agrees. “And the whole place is a lot bigger than last year!”\n \n“This is awesome!” Patty says as she sprints toward the rides.\n \n<!--Page 7-->\n \nYou and Brad take off after Patty. You all stop in front of the roller coaster.\n \n“Wow!” Patty says as she gazes up at it. “It’s like a rocket to outer space!”\n \nBeyond the roller coaster, you spy a castle surrounded by a moat. And a spooky-looking haunted house sitting high atop a hill.\n \n“These are the coolest rides I’ve ever seen!” you say. “They still have that dumb choo-choo train over there,” you point out, “but we could ride this stuff all night and never go near it!”\n \nPatty grabs your arm and tugs you over to the other side of the carnival — to the midway. Brad races after you.\n \n“Hey! Where are all those dinky wooden booths from last year?” you ask as you gawk at the amazing games of chance.\n \nThey’re gone. And in their place are giant video games and huge spinning wheels studded with hundreds of blinking colored lights!\n \n“Get a load of that!” Brad suddenly cries out.\n \nYou and Patty spin around.\n \nYou can’t believe what you see!\n \n<!-- Page 87-->\n \nYou’re staring at a sign that reads: WORLD’S FREAKIEST FREAK SHOW! The three of you gape at the pictures.\n \nThere’s the Three-Headed Man with the ugliest collection of faces you’ve ever seen. And the Snake Lady — a young blond girl with a beautiful face and the body of a slithering snake.\n \n“This is, uh — uh —” you start to say. But you don’t finish. Because a large hand has come down on your shoulder. Hard.\n \nYou slowly turn and gaze up at a huge man with shoulders wider than a refrigerator. He has coal-black eyes with a thick mustache to match. He looks strong enough — and mean enough — to pitch you over the fence with one hand.\n \n“What are you doing?” his deep voice booms. “You’re not allowed in here,” he says, pointing directly at you.\n \nYou’re sorry. Give your best apology and hope he accepts it." }, reprompt: { ssml: "You’re sorry. Give your best apology and hope they accept it." } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageFourHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T19:03:37.330Z", name: "Page 10 and 6 and 7 and 87", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageTenHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.089001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageThirthyNineAndNinetyFourHandlerIntent: [ { name: "Page 39 and 94", outputSpeech: { ssml: "<!-- Page 39 -->\n \n<!-- insert coaster sound fx -->\n\nIt’s a loop-the-loop. Your mouth drops open to scream, but no sound comes out.\n \nNow your car starts to plunge downward — like an elevator out of control. Your heart pounds in your chest. This is the fastest and best roller coaster you’ve ever been on! As you near the bottom, you slow down. You begin to catch your breath. And then you see what’s up ahead. A huge black hole — a tunnel!\n \nAs you shoot toward the open mouth of the tunnel, you begin to scream again. The door of the tunnel is about to close!\n \n<!-- insert door sound fx -->\n\nSnap! The door comes crashing down — behind your car. You breathe out a long sigh. But now you’re in a tunnel so dark that you can’t see a thing.\n \nScary! But not nearly as scary as what happens next.\n \n<!--Page 94 -->\n \nThe ride stops.\n \nDead.\n \nYou are sitting in the dark.\n \nNothing is moving.\n \n“Patty! Brad!” you call.\n \nSilence.\n \nWhy don’t they answer? They have to be there.\n \nYou try to twist around. But you’re locked in your harness and clamped in your headrest.\n \nBlinking in the dim light, your eyes dart to the left. Then to the right. You spot dozens of empty space rockets lining the walls. They seem to come in sections, making longer and shorter space rockets.\n \nYour mind starts working feverishly. Did your section detach from Patty and Brad’s section?\n \nSuddenly, the silence is shattered. Your seat lock grinds open, and you are released from your harness. You quickly spin around. Patty’s and Brad’s cars have disappeared! If this is all part of the ride, maybe you should hop out. But if the ride is broken, maybe you should wait for help.\n \nDo you wait for help to come or hop out of the car?" }, reprompt: { ssml: "Do you wait or hop out of the car?" } } ] }, forward: { WaitForHelpToComeIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageNinetyTwoHandler" } ], HopOutOFTheCarIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneElevenHandlerIntent" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T18:06:25.835Z", name: "Page 39 and 94 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageThirthyNineAndNinetyFourHandlerIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.098001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageThirtyEightHandler: [ { name: "Page 38", outputSpeech: { ssml: "<!-- Page 38 -->\n \n<!-- insert wheel spin sound fx -->\n \n“Got a winner, got a winner,” the parrot squawks. “You’ve won twenty-five points, plus anything you want in the prize room. Step this way.”\n \nEagerly, you follow the bird into a storeroom behind the booth. It’s packed with the weirdest assortment of junk you’ve ever seen. Dusty old catalogs, stuffed rats, a collection of axes, and portraits of headless people holding their own heads!\n \n“So pick something. It’s getting late,” the parrot says.\n \nNot this garbage, you think. Then you spot a shelf of small cans with bright labels: PLAY AND GLOW, CLAY SLIME, and MONSTER BLOOD. Monster Blood? Hey, isn’t that the magic stuff you read about in GOOSEBUMPS?\n \n“I’ll take the Monster Blood,” you decide.\n \n“Excellent choice,” the parrot remarks.\n \nAs you quickly leave the room with your prize, you wonder, is twenty-five points enough?\n \nDo you want to spin again?" }, reprompt: { ssml: "Do you want to spin again?" } } ] }, forward: { NoIntent: [ { type: "START", intentId: "MissionToMarsPageSeventyTwoHandler" }, { type: "START", intentId: "PageSeventeenAndEightyFourAndOneTwentyThreeAndTwentyFiveHandler" } ], YesIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "WheelOfChancePageEightHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-09T19:55:46.261Z", name: "Page 38 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageThirtyEightHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.086001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageThirtyHandler: [ { name: "Page 30", outputSpeech: { ssml: "<!-- Page 30 -->\n \nYou’re falling … falling … You can’t think of anything else to do, so you start flapping your arms like a bird.\n \n<!-- Insert sound Fx --> \n\nAt that moment a huge gust of air shoots up from under you and blows you back onto the bridge.\n \nBreathing hard, you run the rest of the way across the rickety span. When you reach the safety of the other side, you glance back. And gasp! The bridge and the midway beyond it have vanished! Only a black void remains!\n \n“Wow! Awesome special effects!” you cry out loud. But was your fall part of the special effects, too? It didn’t feel like it.\n \nYou spin around to face the House of Horrors. Up close it appears really, really creepy. Cobwebs drip down from its roof and an eerie yellow light glows inside. Cool! Next to the house you spot a sign that reads BOAT TRIP TO NOWHERE. There are amazing speedboats that you can drive yourself.\n \nDo you go to the boat trip to nowhere or to the house of horrors?" }, reprompt: { ssml: "Boat trip to nowhere or house of horrors, which do you try first?" } } ] }, forward: { HouseOfHorrorsIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageSixtySixAndEightyHandlerIntent" } ], BoatTripToNowhereIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageEightyEightAndThirtyTwoHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T18:19:53.754Z", name: "Page 30 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageThirtyHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.094001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageThirtyOneAndEightyNineHandler: [ { name: "Page 31 and 89", outputSpeech: { ssml: "<!-- Page 31 -->\n \nYou are facing a short man with wrinkly skin and bloodshot eyes. His bushy black hair resembles a scouring pad — and from the looks of it, it probably feels like one, too. His evil expression makes you cringe.\n \nBut he’s nothing compared to the “things” in back of him — two seven-foot-tall monsters. One has blue horns and bulging red eyes. The other has scaly skin and an alligator snout that snaps open and closed as he eyes you.\n \nThe trio all wear lab coats. And from the eager way they’re looking at you, you realize that you are the lab rat.\n\n<!-- Insert struggle sound fx -->\n \nYou struggle to escape from the net. But you’re trapped in the webbing. Like a fly in a spider’s web.\n \n“Welcome to my humble laboratory,” the short man says. “I am Dr. Frank N. Stone, the mastermind who created the Carnival of Horrors.”\n \nThe Carnival of Horrors! You don’t like the sound of that!\n \n<!-- Page 89 -->\n \nDr. Stone extends a long bony hand to pull you from the net. When you peer into his face, his eyes roll up into his head.\n \n“Pleased to meet you,” he rumbles.\n \nDid he say, “Pleased to meet you” or “Pleased to eat you”? You’re not sure, and you don’t want to hang around to find out.\n \nI’ve got to get out of here, you think.\n \nAs the doctor lowers his hand a bit more, you wriggle your right foot free of the netting. If you give him one hard kick in the stomach, maybe you can make a run for the door.\n \nBut what about the monsters? Can you dodge them?\n \nYou change your mind. “I’ll wait — play it cool until at least one of the beasts leaves the room,” you say to yourself.\n \nThen you change your mind again. “No. I’d better make my escape now!”\n \nThe doctor looms inches away. And you’re still not sure what to do. You’d better decide fast!\n \nDo you try to kick the doctor or wait until one of the monsters leaves to better your odds?" }, reprompt: { ssml: "Do you try to kick the doctor or wait until one of the monsters leaves to better your odds?" } } ] }, forward: { WaitUntilMonsterLeavesIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageFiftyOneHandler" } ], KickTheDoctorIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageSeventyNineAndSixtySevenHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T18:47:01.722Z", name: "Page 31 and 89 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageThirtyOneAndEightyNineHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.091001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageThirtySevenAndNinetyThreeHandler: [ { name: "Page 37 and 93 and 26 and 58", outputSpeech: { ssml: "<!-- Page 56 -->\n \n<!-- Insert bat sound fx --> \n\nA huge bat!\n \n<!-- Page 37 -->\n \n<!-- Insert bat sound fx --> \n\nYou cover your head with your hands and try to run into a thick grove of trees. But the bat circles in front of you and dives again.\n \n“Stop it! Stop it!” you scream.\n \nAs you turn and race toward some low bushes, you remember the stories — the horrible stories about bats making nests in people’s hair. And the only way to get them out was to shave your head….\n \nThose stories weren’t true — were they?\n \nYou spot a big stick in the wet dirt and scoop it up.\n \n<!-- insert swoosh sound fx -->\n\nThe bat swoops down at you once more and — FWAP! You hit it.\n \nThe bat falls to the ground.\n \nAnd you see it’s on a wire.\n \nIt’s a mechanical bat.\n \nAll part of the ride, you think. You think about the boat ride. Boy, they really make things seem real at this carnival, you think. You feel much better when you gaze up ahead. There’s a clearing.\n \nBut when you see what’s there — you scream!\n \n<!-- Page 93 -->\n \nWhat a sight!\n \nYou can hardly believe your eyes!\n \nYou scream again.\n \nIt’s Patty and Brad!\n \n<!-- Page 26 -->\n \n“Hey, wait up!” you yell to Brad and Patty as you sprint through the Space Coaster gate.\n \nThey both ignore you and charge straight ahead. You follow them into a narrow tunnel that leads to the boarding area.\n \nYou gaze down at the floor. Black rubber. It makes you walk with a strange bounce.\n \nEvery few feet there is a round porthole window. When you glance out one, you see astronauts planting flags on the moon. You peer out another. Now they’re seated in their capsule. This is amazing, you think. The figures look real. Totally real.\n \nAfter a long climb, you and Patty and Brad finally arrive at the loading area.\n \nA sleek bullet-shaped capsule whooshes up and stops right beside you. It has three sections. Brad climbs defiantly into the last section. You leap into the front. Patty’s left with the middle section.\n \nAnd suddenly you’re trapped!\n \n<!-- Page 58 -->\n \n<!-- insert steel bars sound fx --> \n\nSteel bars plunge down from above and drop across your lap and chest, pinning you in place. You can’t move at all. Even your head is held by superstrong headphones that clamp over your ears. A voice comes through them announcing: “Five, four, three, two, one, BLAST OFF!”\n \n<!-- insert bang sound fx --> \n\nYou hear a huge bang. Smoke and fireworks fill the air as your car starts up the first big hill. Your head presses back against the seat as you climb higher and higher. That first hill is endless, but the view is awesome. From the top, you can see the midway, the haunted house, and a shadowy swamp. You can’t believe how big the carnival is!\n \n“Neat!” Patty yells. “There’s AHHHH —”\n \nWhatever she was going to say turns into a wild scream as the rocket plunges down the other side of the hill. The wind whips at your face. You are pressed back so hard, you feel like a pancake. Everything passes in a fantastic blur.\n \nAs your car shoots up to the top of the next hill, you’re laughing and screaming at the same time. This is great, you think! But then you make a big mistake.\n \n<!-- Page 39 -->\n \nYou close your eyes. When you open them, your car lunges forward with a burst of speed.\n \nwhat are you most scared of?" }, reprompt: { ssml: "What are you most scared of?" } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageThirthyNineAndNinetyFourHandlerIntent" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T19:40:07.144Z", name: "Page 37 and 93 and 26 and 58 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageThirtySevenAndNinetyThreeHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.101001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageThirtyThreeHandler: [ { name: "Page 33", outputSpeech: { ssml: "<!-- Page 33 -->\n \nYou glance once more at the goblin. He lets out an evil cackle. That’s it — there’s no way you can trust him. \n\n<!--Insert music sound Fx --> \n\nBesides, you can hear music up ahead. You’re sure you must be near an exit.\n \n“No, thanks. I don’t need any help,” you mumble again.\n \nHe shrugs. “Oh, yes, you do,” he says. But then he sprints off.\n\n<!--Insert music sound Fx --> \n \nYou walk in the direction of the music. But after five minutes, you realize that you’re not getting anywhere.\n \nMaybe you should have followed the goblin. You start to think about Patty and Brad. Are they okay? you wonder.\n \nJust when you think you’ll be wandering these tunnels for the rest of your life, the passageway ends! Now you’re facing two doors — one red and one blue.\n \nDo you try the blue door or the red door?" }, reprompt: { ssml: "Do you try the blue door or the red door?" } } ] }, forward: { BlueDoorIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageFiftySevenAndOneThirtyFiveHandler" } ], RedDoorIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneOhFourAndSixtyOneHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T20:21:01.742Z", name: "Page 33 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageThirtyThreeHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.092001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageThreeHandler: [ { name: "Page Three Handler", outputSpeech: { ssml: "<!-- Page 3 -->\n \n<!--insert carnival sound fx --> \n\nAs you reach the carnival entrance, you hear music coming from inside. Not the usual corny organ stuff they always play. But some really strange music. It sounds familiar and totally new at the same time.\n \nBrad stretches his neck to try to peer over the fence. But no luck. The fence is way too high.\n \nPatty jiggles the padlock on the gate. It’s sealed shut.\n \n“I guess we’ll have to wait until tomorrow night when the carnival opens,” Brad says.\n \n“No way,” Patty says. “Let’s climb the fence. Now!”\n \n“Are you crazy?” Brad says. “We’ll get caught!”\n \n“Come on. There’s probably no one in there,” Patty replies.\n \nYour friends turn to you to cast the deciding vote. You glance at your watch. It’s almost 9:00 P.M. If you’re going to get home in time, you should start back now.\n \nDo you go home or climb the fence?" }, reprompt: { ssml: "Do you go home or climb the fence?\n" } } ] }, forward: { GoHomeIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageTenHandler" } ], ClimbTheFenceIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageSixHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T15:22:15.468Z", name: "Page 3 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageThreeHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.879001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageTwelveHandler: [ { name: "Page 12", outputSpeech: { ssml: "<!-- Page 12 -->\n \nYou run to the right. “Follow me!” you cry out to Patty and Brad.\n\n<!-- Insert running footsteps sound fx --> \n \nYou run faster than you’ve ever run in your life. Your sides ache, but you keep on going.\n \nWhen your chest feels as if it’s about to burst, you finally stop. And hear a crash behind you. Then at both sides of you. Then in front of you. Trapping you.\n \n“Welcome to the Reptile’s Petting Zoo,” a deep voice echoes through the darkness.\n \nReptile’s Petting Zoo? You thought the sign said Reptile Petting Zoo.\n \n“Our alligator has been so lonely,” the deep voice continues. “Waiting and waiting — for his new pets to arrive. And here you are — finally.”\n \nThe end." } } ] }, forward: {}, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T17:42:55.960Z", name: "Page 12 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageTwelveHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.878001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageTwentyEightHandler: [ { name: "Page 28", outputSpeech: { ssml: "<!-- Page 120 -->\n \nAnd then you get a big idea!\n \n<!-- Page 28 -->\n \nYou’re going to embarrass the giant into helping you.\n \n“Hey, you. You know, you’re a real wimp,” you say to the giant.\n \nHe looks at you as if he can’t believe what he hears.\n \nPatty and Brad look at you as if you’re crazy.\n \nMaybe you are.\n \n“You wimp,” you continue. “You sit here all day, taking orders from that creep, Big Al. And you live in these horrible conditions. Why? Because you’re a wimp and you refuse to fight back. You could bend those bars and escape — but you won’t. Because you are a wimp — W-I-M-P — wimp.”\n \nThe giant stands. You gaze up. He’s over fifteen feet tall. He lumbers over to you. He isn’t smiling.\n \nIs your plan going to work? Is he going to bend the bars to prove you wrong? Or is he going to bend you?\n \nIt’s out of your control now.\n \nLook out of your window. Is the sun shining?" }, reprompt: { ssml: "Look out of your window. Is the sun shining?" } } ] }, forward: { NoIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageEightyFiveHandler" } ], YesIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageFortyFiveAndNinetyEightHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T18:21:16.670Z", name: "Page 28 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageTwentyEightHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.878001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageTwentyNineAndSixtyFiveAndThirtyOneHandler: [ { name: "page 29 and 65 and 31", outputSpeech: { ssml: "<!-- Page 29 -->\n \nYou stumble down the corridor to your right. As you peer from side to side, you are met with hundreds of images of — you! And you look pretty baffled. And scared.\n \n“Hey, I could use some help,” you call out.\n \nSilence.\n \n<!--Insert pound sound fx --> \n\nYou pound your fist against the wall.\n \nThe wall starts to move.\n \nJust an inch or two — an inch or two closer to you!\n \nYou take a step back — but the wall behind you is moving, too.\n\n<!--Insert wall moving sound fx --> \n \nThe walls are moving together. They’re closing in on you.\n \nYou’re going to be crushed!\n \n<!-- Page 65 -->\n \nThe walls are closing in faster now.\n \nYou throw your arms out and try to push them away. But it’s hopeless. You’re going to be crushed like a bug.\n \nYou suck in a deep breath — it could be the last breath you take.\n \nThe floor opens beneath your feet!\n \nYou drop down. Down. Down. Down. A long, agonizing scream escapes from your throat as you tumble through space.\n \nWill you ever hit bottom?\n \n“Incoming player,” you hear a commanding voice shout. “Stations, everybody.”\n \nA layer of webbing catches you like one of those nets trapeze artists use. Gasping, unable to understand what’s happening, you bounce up and down.\n \n<!-- Page 31 -->\n \nYou snap your head around to the right --\n\n<!-- Insert footstep sound Fx --> \n\nWhere you hear footsteps coming toward you.\n \nWho do you think the footsteps belong to?" }, reprompt: { ssml: "Who do you think the footsteps belong to? " } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageThirtyOneAndEightyNineHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T18:40:44.002Z", name: "Page 29 and 65 and 31 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageTwentyNineAndSixtyFiveAndThirtyOneHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.877001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageTwentySevenAndFiftyFiveHandler: [ { name: "Page 27 and 55 ", outputSpeech: { ssml: "<!-- Page 27 -->\n \nIt didn’t work—they hate music! The crowd is closing in. You have nothing to defend yourself with. So you run!\n \nYou spot a crack in the wall, next to the wheel. It’s small — too small for an adult to squeeze through — but you can probably make it.\n \n“Follow me!” you yell out to Patty and Brad as you squeeze through the opening. It leads to a backstage area — and then to the flap of another tent.\n \n<!--Insert crowd sound fx -->\n\nYou can hear the crowd behind you, trying to follow you through the crack.\n \n“Come on! We can slip under this tent,” you say. For once, no one argues with you.\n \nThe three of you duck in and find yourself surrounded by another crowd. They are all seated in chairs. And they don’t move. They just stare at you with glassy eyes.\n \n<!-- Page 55 -->\n \nThey’re dummies. That’s why they don’t move!\n \n“They’ve got to be here somewhere,” you hear Big Al’s voice boom outside the tent.\n \n“Hey! This dummy looks just like the one in that GOOSEBUMPS book,” Patty says.\n \n“You mean Slappy?” Brad asks.\n \nGreat! you think. Your friends are chatting about books minutes before you’re about to be attacked by a mob. Then you get an idea.\n \n“Remember those magic words that brought the dummy to life in that book?” you ask your friends. “Maybe we can bring this guy to life and he’ll help us — he was pretty tough.”\n \nYour friends agree — it’s worth a try.\n \n“I think the words are karru marri odonna loma molonu karrano,” Patty says. \n\n“No way. They’re oopah lupah dummie dupah, Brad says.” Who is right, Patty or Brad?" }, reprompt: { ssml: "Who is right, Patty or Brad?" } } ] }, forward: { OptionAIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageSixtyNineHandler" } ], OptionBIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageEightyTwoHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T17:12:52.863Z", name: "Page 27 and 55 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageTwentySevenAndFiftyFiveHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.881001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageTwentysixHandlerIntent: [ { name: "Page 26 & 58 & 39", outputSpeech: { ssml: "<!-- Page 26 -->\n \n“Hey, wait up!” you yell to Brad and Patty as you sprint through the Space Coaster gate.\n \nThey both ignore you and charge straight ahead. You follow them into a narrow tunnel that leads to the boarding area.\n \nYou gaze down at the floor. Black rubber. It makes you walk with a strange bounce.\n \nEvery few feet there is a round porthole window. When you glance out one, you see astronauts planting flags on the moon. You peer out another. Now they’re seated in their capsule. This is amazing, you think. The figures look real. Totally real.\n \nAfter a long climb, you and Patty and Brad finally arrive at the loading area.\n\n<!-- Insert whoosh sound fx -->\n \nA sleek bullet-shaped capsule whooshes up and stops right beside you. It has three sections. Brad climbs defiantly into the last section. You leap into the front. Patty’s left with the middle section.\n \nAnd suddenly you’re trapped!\n \n<!-- Page 58 -->\n \n<!--Insert steel bar sound Fx --> \n\nSteel bars plunge down from above and drop across your lap and chest, pinning you in place. You can’t move at all. Even your head is held by superstrong headphones that clamp over your ears. A voice comes through them announcing: “Five, four, three, two, one, BLAST OFF!”\n \n<!--Insert bang sound Fx --> \n\nYou hear a huge bang. Smoke and fireworks fill the air as your car starts up the first big hill. Your head presses back against the seat as you climb higher and higher. That first hill is endless, but the view is awesome. From the top, you can see the midway, the haunted house, and a shadowy swamp. You can’t believe how big the carnival is!\n \n“Neat!” Patty yells. “There’s AHHHH —”\n \nWhatever she was going to say turns into a wild scream as the rocket plunges down the other side of the hill. The wind whips at your face. You are pressed back so hard, you feel like a pancake. Everything passes in a fantastic blur.\n \nAs your car shoots up to the top of the next hill, you’re laughing and screaming at the same time. This is great, you think! But then you make a big mistake.\n \n<!-- Page 39 -->\n \nYou close your eyes. When you open them, your car lunges forward with a burst of speed.\n \nWhat is the scariest thing you can think of?" }, reprompt: { ssml: "What is the scariest thing you can think of?" } } ] }, forward: { "^((?!(StopIntent|HelpIntent|CancelIntent)).)*$": [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageThirthyNineAndNinetyFourHandlerIntent" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-09T19:49:38.401Z", name: "Page 26 & 58", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageTwentysixHandlerIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.877001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageTwentytwoHandler: [ { name: "Page 22", outputSpeech: { ssml: "<!-- Page 22 -->\n \nYou missed! How will you ever escape now?\n \nYou look at the huge guards standing over you. They don’t move.\n \nThe space lady looks at you sadly. “I’m sorry but you lost Mission to Mars. Unfortunately, you won’t be getting to go to Mars. Take this to sweeten up being a loser and be on your way.”\n \nShe hands you a huge chocolate bar.\n \nYou take a big bite out of it and stuff the rest in your pocket. None of this makes sense.\n \nYou gaze around. The coast is clear. Maybe you can find Patty and Brad and get out of here.\n \nYou walk a few steps forward. But a heavy hand clamps down on your shoulder from behind.\n \nIt’s Big Al.\n \n“It’s time to play another game,” he says, grinning.\n \nAre you ready for the wheel of chance now?" }, reprompt: { ssml: "Are you ready for the wheel of chance now?" } } ] }, forward: { NoIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageSeventeenAndEightyFourAndOneTwentyThreeAndTwentyFiveHandler" } ], YesIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "WheelOfChancePageEightHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-09T20:19:52.053Z", name: "Page 22", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageTwentytwoHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.879001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PagefiftynineHandler: [ { outputSpeech: { ssml: "Blue is your favorite color. You turn the blue card over.\n \nThere is a message: Help us! You are our only hope. Hurry to the back door of the freak show. Signed, The Freaks.\n \n“What does this mean?” you ask Madame Zeno. She stares deep into your eyes. Her lips tremble. She leans forward. She’s about to speak.\n \nAnd then the lights go out —\n\n<!-- Insert scream sound fx --> \n\n and a blood-curdling scream rips through the dark!\n \nYou start to bolt for the door when a dim light suddenly flickers. You stare across the table. Madame Zeno is gone!\n \nYou reach out to take the card. And it bursts into red-hot flames! In seconds, the entire tent fills with thick smoke. Flames shoot across the floor. You run for the door.\n \nOutside, you gulp the fresh air. Whew! You made it.\n \nYou glance back. No smoke. No fire. No tent! Everything has disappeared!\n \nWhat should you do now, do you help the freaks?" }, reprompt: { ssml: "What should you do now, do you help the freaks?" } } ] }, forward: { NoIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageOneThirteenAndSixteenHandler" } ], YesIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageElevenAndThirtyFiveAndThirteenHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T15:33:41.875Z", name: "Page 59 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PagefiftynineHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.877001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PageseventysevenAndseventyeightHandler: [ { name: "Page 77 and 78", outputSpeech: { ssml: "<!-- Page 77 -->\n \n“Let’s head for the midway and play some games!” you say.\n \nYou, Patty, and Brad jog down a wide avenue. Tents of every color line the street. \n\n<!-- Insert carinval music sound Fx -->]\n\nCarnival music blares from loudspeakers.\n \nYou spot a green neon sign flashing above a yellow-striped tent. The sign reads: MADAME ZENO — FORTUNE-TELLER.\n \n“Excellent!” you exclaim. “I’m going in!”\n \nYou tell your friends you’ll catch up with them in a minute.\n \nYou lift the tent flap. Inside, one small candle flickers in the dark. You hear a low voice call out, “Enter my chamber.”\n \nThere is Madame Zeno, sitting in the shadows. She wears a long red dress dotted with brightly colored gems. They shimmer in the candlelight. Her black hair tumbles to her shoulders as she bends over a large crystal ball.\n \n“Welcome,” she whispers. Then she reaches out and gently lifts your hand. “Let me tell you your future.”\n \n<!-- Page 78 -->\n \nMadame Zeno studies your hand closely. She traces the lines in your hand with her soft fingers.\n \n“I see horror in your future. In your immediate future,” she warns.\n \n“Wh-what kind of horror?” you stammer. “What do you mean?”\n \nMadame Zeno releases your hand. She picks up a strange deck of cards. She spreads them out on the table. You notice the cards have pictures — a headless man, a bloody sword, a large, evil eye.\n \nShe gathers up all the cards and flips the deck over. Then she deals out a red card and a blue card.\n \n“Turn one over,” she commands. “Learn your fate.”\n \nDo you choose red or blue?" }, reprompt: { ssml: "Do you choose red or blue?" } } ] }, forward: { BlueCardIntent: [ { type: "START", intentId: "PageFiftyNineHandler" } ], RedCardIntent: [ { type: "START", intentId: "PageFourteenAndFortyOneHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T19:37:10.719Z", name: "Page 77 and 78 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PageseventysevenAndseventyeightHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.879001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { content: { PagethirtyfourAndfourtysevenHandler: [ { name: "Page 34 and 47 Handler", outputSpeech: { ssml: "<!-- Page 34 -->\n \n“Let’s go on the rides first!” you say. “That roller coaster looked awesome!”\n \n“Okay,” Patty agrees. “Over this way!” she yells as she charges over to it.\n\n<!-- Insert carnival sound fx -->\n \nWhen you reach the rides, you can only stare in amazement. These are the most fantastic rides you’ve ever seen. The towering roller coaster … the soaring speedboats … the twisty slides! Every one is in motion. Whizzing, whirling, doing loop-the-loops. And they’re all empty! No riders. No people in line!\n \n“Cool!” Patty exclaims. “We have the whole place to ourselves.”\n \nBrad’s face turns a little green as his gaze swings from the Supersonic Space Coaster to the Doom Slide. “Do you think they have rides that don’t go upside down?” he asks.\n \n“Come on! Let’s check out the coaster!” Patty calls to you and Brad. Then they run off to its starting gate.\n \nYou stop and crane your neck to gaze up at the coaster’s first hill. And you gasp!\n \n<!-- Page 47 -->\n \nThe tracks stretch up so high that they seem to touch the clouds. Your gaze follows one of the cars speeding around a sharp curve. It looks like the space shuttle. You notice that it has a safety harness that locks over your body — you’ve seen those before. They keep you in when the ride turns upside down. You didn’t want to admit it before, but, like Brad, riding upside down is not your favorite thing.\n \nStill, the coaster does look amazing — one part enters a tunnel — and you can see that the cars go fast. Really Fast!\n \n<!-- Insert organ sound Fx --> \n\nYou’re just about to walk through the Space Coaster gate when you hear spooky organ music coming from behind you. You turn around. Looming in the distance is a dark and creepy haunted house.\n \nYou gaze down at your map. It’s called the House of Horrors. Hmmm. You love haunted houses. And this one really looks scary.\n \nNow you’re not sure what to do. You won’t have time for everything. Patty and Brad are going to the Space Coaster and you would be going alone to the House of Horrors.\n \nDo you pick the coaster or the haunted house?" }, reprompt: { ssml: "The coaster or the haunted house, which do you choose?" } } ] }, forward: { SpaceCoasterIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageTwentysixHandlerIntent" } ], HauntedHouseIntent: [ { type: "START", actions: [ { type: "SET", store: "SESSION" } ], intentId: "PageSixtyFourHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T19:33:09.170Z", name: "Page 34 and 47 Handler", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "PagethirtyfourAndfourtysevenHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.882001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: ["shortcut rides"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-17T16:52:19.622Z", name: "QuitWhileAhead", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "QuitWhileAheadIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.878001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["quit while i'm ahead", "quit while ahead"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T13:33:50.190Z", name: "Real Monster", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "RealMonsterIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.882001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{it's a|} {real|} monster", "{i think it's a|} {real|} monster"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T18:50:46.147Z", name: "Red Card", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "RedCardIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.881001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{I choose|I want|} {the|} red {card|}"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T18:36:31.282Z", name: "RedDoor", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "RedDoorIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.882001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{pick|} {the|} red {door|}"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T14:22:01.376Z", name: "RepeatIntent", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "RepeatIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.883001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["repeat", "repeat that please", "say that again"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T13:28:15.594Z", name: "Robot", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "RobotIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.878001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{it's a|} robot", "{I think it's a|} robot"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T17:07:41.237Z", name: "RunDownADifferentPath", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "RunDownADifferentPathIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.885001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["run down {a different path|}", "{a|} different path"] }, { action: [], helpData: [], responseData: [], slots: [ { name: "number", type: "STENTOR.NUMBER" } ], createdAt: "2018-07-15T17:58:02.156Z", name: "SlideNumberIntent", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "SlideNumberIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.883001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["i choose slide {-|number}", "slide {-|number}", "let's go with slide {-|number}"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-06T17:58:24.208Z", name: "Snake Lady Is Telling The Truth", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "SnakeLadyIsTellingTheTruthIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.883001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["snake lady {is telling the truth|}", "snake lady truth"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-11T14:58:24.349Z", name: "Sneak by the Axes", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "SneakByTheAxesIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.880001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["sneak by the axes", "try to sneak by the axes"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T15:54:59.585Z", name: "Space Coaster", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "SpaceCoasterIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.882001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: [ "Space Coaster", "Join Patty and Brad on the space coaster", "Patty and Brad", "Go to space coaster" ] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-17T16:47:29.572Z", name: "Spin Again", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "SpinAgainIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.880001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["spin again", "i want to spin again", "spin", "spin again please"] }, { action: [], helpData: [], responseData: [], slots: [ { name: "speed", type: "SPEED" } ], createdAt: "2018-07-17T17:08:24.492Z", name: "SpinSpeed", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "SpinSpeedIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.880001, langCode: "en-US", slotTypes: { SPEED: { name: "SPEED", values: [ { name: "fast", data: {} }, { name: "slow", data: {} } ] } }, exitData: [], utterancePatterns: ["spin {-|speed} ", "i want to spin {-|speed}"] }, { content: { StartOverIntent: [ { name: "Start Over Prompt", outputSpeech: { ssml: "Too scared? Are you sure you want to start over?" }, reprompt: { ssml: "Too scared? Are you sure you want to start over?" } } ] }, forward: { YesIntent: [ { type: "START", intentId: "PageOneAndPageTwoHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T19:52:01.397Z", name: "StartOver", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "StartOverIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.884001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: ["Start over", "start from {the|} beginning", "restart"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T14:59:08.654Z", name: "Stop", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "StopIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.883001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["stop please"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T17:44:57.252Z", name: "Take The Back Way Out", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "TakeTheBackWayOutIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.883001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{Take the|} back way out", "Back out", "Way out"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T20:16:55.220Z", name: "Talk to Big Al", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "TalkToBigAlIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.884001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{stay|} {and|} talk to {big|} Al"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T19:28:29.069Z", name: "TheRidesIntent", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "TheRidesIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.884001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["The rides", "rides", "go on rides", "rides please", "the rides please"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T17:00:06.571Z", name: "TuesdayThursdaySunday", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "TuesdayThursdaySundayIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.885001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["Tuesday", "Thursday", "Sunday"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T17:36:14.585Z", name: "Turn Left", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "TurnLeftIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.884001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{turn|} Left"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-03T17:36:19.494Z", name: "Turn Right", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "TurnRightIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.885001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{turn|} right"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T20:05:26.048Z", name: "Two, Seven or Nine", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "TwoSevenOrNineIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.885001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["Two", "Seven", "Nine"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-02T18:13:21.073Z", name: "Wait For Help To Come", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "WaitForHelpToComeIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.900001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["{|Wait} for help {to come|}", "Help", "Wait"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T20:45:19.685Z", name: "Wait Until Monster Leaves", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "WaitUntilMonsterLeavesIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.898001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: [ "{wait until one of the|wait for the|} monster {leaves| to leave|}", "wait", "better your odds", "wait for the monster to leave " ] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T14:21:52.168Z", name: "WhatIntent", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "WhatIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.913001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["what", "what was that", "what are my options"] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-10T13:29:16.786Z", name: "Wheel of Chance", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "WheelOfChanceIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.898001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["wheel of chance", "i choose wheel of chance"] }, { content: { WheelOfChancePageEightHandler: [ { name: "Page 8 and 9", outputSpeech: { ssml: "<!-- Page 8 -->\n \nYou wander over to the Wheel of Chance and immediately notice two strange things.\n \nFirst, you read the sign on the booth. It says “Wheel of No Chance.” Then you hear the barker’s voice calling, “Step right up!” But there’s no one there.\n \nNo one but a green-and-yellow parrot.\n \n“Excuse me,” you say, hoping someone will answer. “Is this game open?”\n \n“No, I’m standing by this wheel for my health,” the parrot cracks. “Now, do you want to spin or what?”\n \nThe parrot is obviously annoyed. “Mammals,” he mutters. “Can’t live with them, can’t live without them.”\n \nYou steal a glance around. Maybe you should skip this game. But Big Al sneaks up behind you.\n \n“Spin,” he says. “You must earn enough points to win.”\n \n“But how will I know if I have enough points?” you ask.\n \n“Spin!” It’s his final word.\n \n<!-- Page 9 -->\n \nYou stand in front of the wheel examining the options: free spin, no chance, double or nothing, and prize. You close your eyes and get ready to spin the wheel.\n \nDo you spin the wheel slow or fast?" }, reprompt: { ssml: "Do you spin the wheel slow or fast?" } } ] }, forward: { SpinSpeedIntent: [ { type: "START", intentId: "PageThirtyEightHandler" }, { type: "START", intentId: "PageNineteenHandler" }, { type: "START", intentId: "PageFifteenHandler" }, { type: "START", intentId: "PageFortyNineAndFiftyHandler" } ] }, action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-07-05T19:45:33.873Z", name: "Page 8 and 9 Wheel of Chance", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "WheelOfChancePageEightHandler", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.900001, langCode: "en-US", slotTypes: {}, exitData: [], type: "InSessionIntent", utterancePatterns: [] }, { action: [], helpData: [], responseData: [], slots: [], createdAt: "2018-06-28T14:28:03.203Z", name: "YesIntent", "aws:rep:deleting": false, data: {}, organizationId: "Scholastic-Inc", intentId: "YesIntent", appId: "goosebumps-tts", "aws:rep:updateregion": "us-east-1", "aws:rep:updatetime": 1532714154.909001, langCode: "en-US", slotTypes: {}, exitData: [], utterancePatterns: ["yes", "yes please"] } ];
51.182699
3,386
0.537399
8e6eea5ec8ae986adfdac5a6fbb760ffe244e6ab
4,838
rb
Ruby
modules/health_quest/spec/services/lighthouse/token_spec.rb
darkbushido/vets-api
b436ad3cbcb35821995a3fd2499b8e0859179842
[ "CC0-1.0" ]
150
2016-07-01T18:52:26.000Z
2022-03-30T11:30:31.000Z
modules/health_quest/spec/services/lighthouse/token_spec.rb
darkbushido/vets-api
b436ad3cbcb35821995a3fd2499b8e0859179842
[ "CC0-1.0" ]
3,372
2016-07-15T14:28:16.000Z
2022-03-31T17:18:40.000Z
modules/health_quest/spec/services/lighthouse/token_spec.rb
darkbushido/vets-api
b436ad3cbcb35821995a3fd2499b8e0859179842
[ "CC0-1.0" ]
63
2016-09-14T14:29:27.000Z
2022-03-30T20:48:10.000Z
# frozen_string_literal: true require 'rails_helper' describe HealthQuest::Lighthouse::Token do subject { described_class } let(:user) { double('User', account_uuid: 'abc123', icn: '1008596379V859838') } let(:token) { subject.build(user: user, api: 'pgd_api') } describe 'constants' do it 'has an ACCESS_TOKEN' do expect(subject::ACCESS_TOKEN).to eq('access_token') end it 'has an EXPIRATION' do expect(subject::EXPIRATION).to eq('exp') end it 'has a SCOPES_DELIMITER' do expect(subject::SCOPES_DELIMITER).to eq(' ') end end describe 'attributes' do it 'responds to api' do expect(token.respond_to?(:api)).to be(true) end it 'responds to user' do expect(token.respond_to?(:user)).to be(true) end it 'responds to request' do expect(token.respond_to?(:request)).to be(true) end it 'responds to claims_token' do expect(token.respond_to?(:claims_token)).to be(true) end it 'responds to access_token' do expect(token.respond_to?(:access_token)).to be(true) end it 'responds to decoded_token' do expect(token.respond_to?(:decoded_token)).to be(true) end end describe '.build' do it 'returns an instance of Token' do expect(token).to be_an_instance_of(HealthQuest::Lighthouse::Token) end end describe '#fetch' do let(:sample_access_token) do 'eyJraWQiOiJRMFZKbEt0TU9rYUxXTEtxdXhsTllHQzFRLWMtblQzYjRWVlJLaXB4TThzIiwiYWxnIj' \ 'oiUlMyNTYifQ.eyJ2ZXIiOjEsImp0aSI6IkFULjVTcDV4QnNZQzdXQU1MU2ZOR3JETlFmS0JQaHpWaW' \ 'VwQ1NYbHhPODBKV1kiLCJpc3MiOiJodHRwczovL2RlcHR2YS1ldmFsLm9rdGEuY29tL29hdXRoMi9hdX' \ 'M4eDI3bnY0ZzRCUzAxdjJwNyIsImF1ZCI6Imh0dHBzOi8vc2FuZGJveC1hcGkudmEuZ292L3NlcnZpY2V' \ 'zL3BnZCIsImlhdCI6MTYxMDExODk3NywiZXhwIjoxNjEwMTE5Mjc3LCJjaWQiOiIwb2E5Z3Z3ZjVtdnhj' \ 'WDN6SDJwNyIsInNjcCI6WyJwYXRpZW50L1BhdGllbnQucmVhZCIsImxhdW5jaC9wYXRpZW50Il0sInN1Yi' \ 'I6IjBvYTlndndmNW12eGNYM3pIMnA3In0.Z_1xLenmVFZwqkboOGB8xdRvoiWmn1kFaPDBklOz2vRncuKX' \ 'HFuiHqsULMM9Jr4IimSyhhSX26A0AQZj5F1LcS4I1N_CeJEiCzCr4ZuihUd6HFeP5g3wbtLekrPWL697vVX' \ 'itUytDpcaWlUTTtW1pzfNKFVyb-m5Z3votzqLPp9tV_DdhnkbwnEuAFKp-lIkOfBfZtB7_Orv55xunvNeY6R' \ '-j-DjMgjNn7Xmn3-h_PXi9doVwp5KOdoTD3fX9t4EZy0zRFgN3zz5DahVmBEq65Sy9KLzmu_CL9wF2CEqgQz' \ '4rOGK0j6RcoezpJwuABi61a3WOGMJx6kT3eytuzA-UA' end let(:faraday_response) { double('Faraday::Response', body: { 'access_token' => sample_access_token }.to_json) } it 'returns an instance of Token' do allow_any_instance_of(HealthQuest::Lighthouse::Request).to receive(:post) .with(anything, anything).and_return(faraday_response) expect(token.fetch).to be_an_instance_of(subject) end end describe '#created_at' do it 'is an Integer' do expect(token.created_at).to be_a(Integer) end end describe '#ttl_duration' do it 'is an Integer' do token.decoded_token = { 'exp' => 5.minutes.from_now.utc.to_i } expect(token.ttl_duration).to be_a(Integer) end end describe '#api_paths' do context 'when pgd_api' do it 'returns the pgd token path' do pgd_token_path = '/oauth2/pgd/v1/token' expect(token.api_paths['pgd_api']).to eq(pgd_token_path) end end context 'when health_api' do it 'returns the health token path' do health_token_path = '/oauth2/health/system/v1/token' expect(token.api_paths['health_api']).to eq(health_token_path) end end end describe '#scopes' do context 'when pgd_api' do it 'returns the pgd api scopes' do expect(token.scopes['pgd_api']).to eq(Settings.hqva_mobile.lighthouse.pgd_api_scopes) end end context 'when health_api' do it 'returns the health api scopes' do expect(token.scopes['health_api']).to eq(Settings.hqva_mobile.lighthouse.health_api_scopes) end end end describe '#base64_encoded_launch' do it 'base64 encodes the launch object' do expect(token.base64_encoded_launch).to eq('eyI6cGF0aWVudCI6IjEwMDg1OTYzNzlWODU5ODM4In0=') end end describe '#post_params' do context 'when pgd_api' do it 'sets the pgd scopes' do scopes = Settings.hqva_mobile.lighthouse.pgd_api_scopes.join(' ') matched_scope = URI.encode_www_form(scope: scopes) expect(token.post_params).to include(matched_scope) end end context 'when health_api' do let(:token) { subject.build(user: user, api: 'health_api') } it 'sets the health scopes' do scopes = Settings.hqva_mobile.lighthouse.health_api_scopes.join(' ') matched_scope = URI.encode_www_form(scope: scopes) expect(token.post_params).to include(matched_scope) end end end end
31.212903
115
0.708351
b34eadf4d81579fb600a710e3a3db935cbce1a41
1,862
py
Python
bot_modules/py/help_mgr.py
cumdata/irc_bot
6593215acb7850f435389ae64652d831279f3332
[ "WTFPL" ]
2
2021-09-30T03:19:15.000Z
2021-12-30T04:18:46.000Z
bot_modules/py/help_mgr.py
deacon-ralph/irc_bot
62c8a6d0f9890b3fbfd356f533e9d58c38bbc176
[ "WTFPL" ]
7
2021-10-01T02:38:39.000Z
2022-02-17T04:58:48.000Z
bot_modules/py/help_mgr.py
cumdata/irc_bot
6593215acb7850f435389ae64652d831279f3332
[ "WTFPL" ]
null
null
null
"""Help module, which displays help info for plugins""" import colors import plugin_api class Plugin(plugin_api.LocalPlugin): """Help plugin""" @property def enabled(self): """ALWAYS ENABLED!""" return True def help_msg(self): return { 'usage': '.help <module> <detail>', 'example_detail': 'this is an example help detail' } async def on_message(self, target, by, message): if message.startswith('.help '): parts = message.split(' ') if len(parts) == 2: plugin = self.client.plugins.get(parts[1]) if plugin: await self.client.message( target, colors.colorize(plugin.showhelp(), fg=colors.LIGHT_BLUE) ) else: await self.client.message( target, colors.colorize( f'plugin {parts[1]} not found', colors.WHITE, colors.RED ) ) if len(parts) == 3: plugin = self.client.plugins.get(parts[1]) if plugin: await self.client.message( target, colors.colorize( plugin.showhelp(parts[2]), fg=colors.LIGHT_BLUE) ) else: await self.client.message( target, colors.colorize( f'plugin {parts[1]} not found', colors.WHITE, colors.RED ) )
32.666667
80
0.39957
a517f4770a7ef0abd61d18957b1c5a97ce6e4cc4
4,946
asm
Assembly
asm/giepy/load.asm
boldowa/GIEPY
5aa326b264ef19f71d2e0ab5513b08fac7bca941
[ "MIT" ]
8
2018-03-15T22:01:35.000Z
2019-07-13T18:04:41.000Z
asm/giepy/load.asm
telinc1/GIEPY
9c87ad1070e519637fc4b11b6bef01f998961678
[ "MIT" ]
21
2018-02-18T06:25:40.000Z
2018-07-13T17:54:40.000Z
asm/giepy/load.asm
telinc1/GIEPY
9c87ad1070e519637fc4b11b6bef01f998961678
[ "MIT" ]
2
2018-07-25T21:04:23.000Z
2022-01-01T08:40:13.000Z
@include ;------------------------------------------------------------------------------- ; GIEPY Sprite load code hijacks ;------------------------------------------------------------------------------- ; Sprite type bit mask !SprTypeMask := $07 pushpc %org_assert_long2($02a837, 0285,1029) autoclean jsl SeparateExBits %org_assert_long2($02a861, 0585,ceb7) jml SprLoadHijack if !true == !EXTRA_BYTES_EXT %org_assert_long2($02a846, 80e8,c8c8) jml LoadNextSprHijack endif pullpc ;------------------------------------------------- ; Separate Extra Bits ;------------------------------------------------- SeparateExBits: %putdebug("SeparateExBits") and.b #$10 ; original proc sta.b $02 ; original proc ;--- get sprite type lda.b [$ce],y and.b #$0c sta.b $07 ; extra bits lsr lsr sta.b $06 ; sprite type rtl ;------------------------------------------------- ; Sprite Load Hijack ;------------------------------------------------- SprLoadHijack: %putdebug("SprLoadHijack") lda.b [$ce],y ; a = sprite num. sta.b $05 dey phx php xba lda.b $06 ; sprite type xba ; a = sprite type/num rep #$30 tax sep #$20 ;--- check type lda.l SprTypeTable,x sep #$30 and.b #!SprTypeMask bne .isCustom .nonCustom plp plx lda.b $05 %jml_assert_long(jml, $02a866, 90e7c9) ; return to orig smw routine .isCustom %putdebug("isCustom") dec bne + ;--- normal custom sprite lda.b $07 ; exita bits ora.b #$80 ; set bit7(custom sprite) : C---EE-- sta.b $07 plp plx %jml_assert_long(jml, $02a8dd, 8501a9) ; jump to normal sprite routine + dec bne + jmp LoadShooter + dec beq LoadGenerator dec beq LoadInitializer dec bne .nonCustom LoadScroller: %putdebug("LoadScroller") ;--- check layer1 and layer2 scroll lda.w !scroll_num_l1 ora.w !scroll_num_l2 beq + ; scroller is already working. return. plp plx %jml_assert_long(jml, $02a846, e8c8c8) ; jmp to LoadNextSprite ;--- Execute scroller if any scroller isn't working + plp plx ;\ swap stack phy ; | for smw routine phx ;/ ;--- read extra_bytes if !true == !EXTRA_BYTES_EXT iny jsr LoadExBytesSub beq + ;\ Load extra bytes. - lda.b [$ce],y ; | if extra bytes size greater than 4, sta.l !extra_byte_scr ; | extra byte will overwrite by iny ; | latest extra byte value. dec $04 ; | bne - ;/ + endif lda.b $07 ; extra bits ora.b #$80 sta.l !extra_bits_l1scr ; C---EE-- sta.l !extra_bits_l2scr ; C---EE-- lda.b $05 inc sta.w !scroll_num_l1 sta.w !scroll_num_l2 %jml_assert_long(jml, $02a87c, ceb788) ; jmp to LoadScrollSprite LoadGenerator: %putdebug("LoadGenerator") plp plx lda.b $07 ; extra bits ora.b #$80 sta.l !extra_bits_gen lda.b $05 inc a sta.w !18b9 stz.w !1938,x if !true == !EXTRA_BYTES_EXT iny jsr LoadExBytesSub beq .return - lda.b [$ce],y ;\ Load extra bytes. sta.l !extra_byte_gen ; | if extra bytes size greater than 4, iny ; | extra byte will overwrite by dec $04 ; | latest extra byte value. bne - ;/ .return inx %jml_assert_long(jml, $02a82e, c9ceb7) ; jmp to LoadSpriteLoopStart else %jml_assert_long(jml, $02a846, e8c8c8) ; jmp to LoadNextSprite endif LoadInitializer: %putdebug("LoadInitializer") phy if !true == !EXTRA_BYTES_EXT phy iny iny php rep #$20 lda.b $ce sta.b $98 lda.b $cf sta.b $99 sep #$20 tya clc adc.b $98 sta.b $98 bcc .notCarry inc $99 .notCarry plp ply endif dey sty.b $03 ;--- backup $05-$06 for LoadNextSprite routine. rep #$10 lda.b $05 pha php ;--- call initializer sep #$30 jsl CallInitializer ;--- restore $05-06 plp pla sta.b $05 sep #$10 ply plp plx %jml_assert_long(jml, $02a846, e8c8c8) ; jmp to LoadNextSprite LoadShooter: %putdebug("LoadShooter") plp plx stx.b $02 dey sty.b $03 ;--- search empty slot ldx.b #$07 - lda.w !1783,x beq + dex bne - + dec.w $18ff|!base2 bpl + lda.b #$07 sta.w $18ff|!base2 + ldx.w $18ff|!base2 ldy.w $17b3|!base2,x lda.b $07 ; extra bits ora.b #$80 sta.l !extra_bits_sh,x stz.w !1938,x ldy.b $03 lda.b $05 inc sta.w !1783,x jml $02aba8|!bankB %jml_assert_long(jml, $02aba8, 4a5ba5) ;------------------------------------------------- ; Load Next Sprite Hijack ;------------------------------------------------- if !true == !EXTRA_BYTES_EXT LoadNextSprHijack: %putdebug("LoadNextSprHijack") ; Skip extra bytes iny lda.b [$ce],y sta.b $05 dey dey phx php rep #$10 tya ldx.b $05 ; load table inx clc adc.l EBLengthTable,x sep #$10 tay plp plx inx %jml_assert_long(jml, $02a82e, c9ceb7) ; jmp to LoadSpriteLoopStart endif
17.855596
81
0.558431
0822338dcfc0203ec52707d3753b51f37f534ebd
103
swift
Swift
TestProject/RequiredInitializerClassMock.swift
vlondon/SwiftMockGeneratorForXcode
cf07c748e41b057fa2e1854d90c05323c7881c06
[ "MIT" ]
1
2018-11-07T10:14:05.000Z
2018-11-07T10:14:05.000Z
TestProject/RequiredInitializerClassMock.swift
vlondon/SwiftMockGeneratorForXcode
cf07c748e41b057fa2e1854d90c05323c7881c06
[ "MIT" ]
null
null
null
TestProject/RequiredInitializerClassMock.swift
vlondon/SwiftMockGeneratorForXcode
cf07c748e41b057fa2e1854d90c05323c7881c06
[ "MIT" ]
null
null
null
@testable import TestProject class RequiredInitializerClassMock: RequiredInitializerClass { <caret> }
17.166667
62
0.84466
2c8ab7b83bee2c78b41b84b226e641253abbe4ed
7,356
py
Python
pyscf/lo/iao.py
BoothGroup/pyscf
32b632eb5ceae907eb537e0a728a0f2e73244bbb
[ "Apache-2.0" ]
null
null
null
pyscf/lo/iao.py
BoothGroup/pyscf
32b632eb5ceae907eb537e0a728a0f2e73244bbb
[ "Apache-2.0" ]
1
2021-05-02T16:10:10.000Z
2021-05-02T16:10:10.000Z
pyscf/lo/iao.py
BoothGroup/pyscf
32b632eb5ceae907eb537e0a728a0f2e73244bbb
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Author: Qiming Sun <osirpt.sun@gmail.com> # Paul J. Robinson <pjrobinson@ucla.edu> # Zhi-Hao Cui <zhcui0408@gmail.com> ''' Intrinsic Atomic Orbitals ref. JCTC, 9, 4834 ''' from functools import reduce import numpy import scipy.linalg from pyscf.lib import logger, c_null_ptr from pyscf import gto from pyscf import scf from pyscf import __config__ from pyscf.lo.orth import vec_lowdin from pyscf.data.elements import is_ghost_atom # Alternately, use ANO for minao # orthogonalize iao with coefficients obtained by # vec_lowdin(iao_coeff, mol.intor('int1e_ovlp')) MINAO = getattr(__config__, 'lo_iao_minao', 'minao') def iao(mol, orbocc, minao=MINAO, kpts=None, lindep_threshold=1e-10): '''Intrinsic Atomic Orbitals (IAO). [Ref. JCTC, 9, 4834] Args: mol : pyscf.gto.Mole or pyscf.pbc.gto.Cell The molecule or cell object. orbocc : (N, M) or (K, N, M) array Occupied molecular orbitals. N= number of AOs, M= number of occupied MOs, K= number of k-points (only if mol is Cell object). minao : str, optional Minimal basis set used for IAOs. kpts : ndarray(K), optional k-points, only used for Cell objects. lindep_threshold : float, optional For almost linearly dependent basis sets, the Cholesky decomposition can fail. In this case the eigendecomposition of the overlap matrix is used with eigenvectors corresponding to eigenvalues below `lindep_threshold` removed. Returns: a : (N, L) or (K, N, L) array Non-orthogonal IAOs. Orthogonalize them as C (C^T S C)^{-1/2}, eg. using :func:`orth.lowdin` >>> orbocc = mf.mo_coeff[:,mf.mo_occ>0] >>> c = iao(mol, orbocc) >>> numpy.dot(c, orth.lowdin(reduce(numpy.dot, (c.T,s,c)))) ''' if mol.has_ecp() and minao == "minao": logger.warn(mol, 'ECP/PP is used. MINAO is not a good reference AO basis for IAOs.') def kernel(s1, s2, s12, orbocc): """Make IAOs for a molecule or single k-point.""" s21 = s12.conj().T # Minimal basis CD is not expected to fail s2cd = scipy.linalg.cho_factor(s2) ctild = scipy.linalg.cho_solve(s2cd, numpy.dot(s21, orbocc)) # Try Cholesky of computational basis first try: s1cd = scipy.linalg.cho_factor(s1) p12 = scipy.linalg.cho_solve(s1cd, s12) ctild = scipy.linalg.cho_solve(s1cd, numpy.dot(s12, ctild)) # For overcomplete basis sets, use eigendecomposition + canonical orthogonalization instead except numpy.linalg.LinAlgError: se, sv = numpy.linalg.eigh(s1) logger.debug(mol, "Cholesky decomp. of overlap S failed; removing %d eigenvectors of S with eigenvalues below %.2e", numpy.count_nonzero(se < lindep_threshold), lindep_threshold) keep = (se >= lindep_threshold) invS = numpy.einsum("ai,i,bi->ab", sv[:,keep], 1/se[keep], sv[:,keep]) p12 = numpy.dot(invS, s12) ctild = numpy.dot(p12, ctild) ctild = vec_lowdin(ctild, s1) ccs1 = reduce(numpy.dot, (orbocc, orbocc.conj().T, s1)) ccs2 = reduce(numpy.dot, (ctild, ctild.conj().T, s1)) #a is the set of IAOs in the original basis a = (p12 + reduce(numpy.dot, (ccs1, ccs2, p12)) * 2 - numpy.dot(ccs1, p12) - numpy.dot(ccs2, p12)) return a pmol = reference_mol(mol, minao) # For PBC, we must use the pbc code for evaluating the integrals lest the # pbc conditions be ignored. # DO NOT import pbcgto early and check whether mol is a cell object. # "from pyscf.pbc import gto as pbcgto and isinstance(mol, pbcgto.Cell)" # The code should work even pbc module is not availabe. # # s1 is the one electron overlap integrals (coulomb integrals) # s2 is the same as s1 except in minao # s12 are the overlap integrals of the two molecules #if getattr(mol, 'pbc_intor', None): # cell object has pbc_intor method if hasattr(mol, 'a') and mol.a is not None: from pyscf.pbc import gto as pbcgto s1 = numpy.asarray(mol.pbc_intor('int1e_ovlp', hermi=1, kpts=kpts, pbcopt=c_null_ptr())) s2 = numpy.asarray(pmol.pbc_intor('int1e_ovlp', hermi=1, kpts=kpts, pbcopt=c_null_ptr())) s12 = numpy.asarray(pbcgto.cell.intor_cross('int1e_ovlp', mol, pmol, kpts=kpts, pbcopt=c_null_ptr())) else: s1 = mol.intor_symmetric('int1e_ovlp') s2 = pmol.intor_symmetric('int1e_ovlp') s12 = gto.mole.intor_cross('int1e_ovlp', mol, pmol) # Molecule if len(s1.shape) == 2: a = kernel(s1, s2, s12, orbocc) # k-point sampling else: a = [] for k in range(len(kpts)): ak = kernel(s1[k], s2[k], s12[k], orbocc[k]) a.append(ak) a = numpy.asarray(a) return a def reference_mol(mol, minao=MINAO): '''Create a molecule which uses reference minimal basis''' pmol = mol.copy() atoms = [atom for atom in gto.format_atom(pmol.atom, unit=1)] # remove ghost atoms pmol.atom = [atom for atom in atoms if not is_ghost_atom(atom[0])] if len(pmol.atom) != len(atoms): logger.info(mol, 'Ghost atoms found in system. ' 'Current IAO does not support ghost atoms. ' 'They are removed from IAO reference basis.') if getattr(pmol, 'rcut', None) is not None: pmol.rcut = None pmol.build(False, False, basis=minao) return pmol def fast_iao_mullikan_pop(mol, dm, iaos, verbose=logger.DEBUG): ''' Args: mol : the molecule or cell object iaos : 2D array (orthogonal or non-orthogonal) IAO orbitals Returns: mullikan population analysis in the basis IAO ''' pmol = reference_mol(mol) if getattr(mol, 'pbc_intor', None): # whether mol object is a cell ovlpS = mol.pbc_intor('int1e_ovlp') else: ovlpS = mol.intor_symmetric('int1e_ovlp') # Transform DM in big basis to IAO basis # |IAO> = |big> C # DM_{IAO} = C^{-1} DM (C^{-1})^T = S_{IAO}^{-1} C^T S DM S C S_{IAO}^{-1} cs = numpy.dot(iaos.T.conj(), ovlpS) s_iao = numpy.dot(cs, iaos) iao_inv = numpy.linalg.solve(s_iao, cs) if isinstance(dm, numpy.ndarray) and dm.ndim == 2: dm = reduce(numpy.dot, (iao_inv, dm, iao_inv.conj().T)) return scf.hf.mulliken_pop(pmol, dm, s_iao, verbose) else: dm = [reduce(numpy.dot, (iao_inv, dm[0], iao_inv.conj().T)), reduce(numpy.dot, (iao_inv, dm[1], iao_inv.conj().T))] return scf.uhf.mulliken_pop(pmol, dm, s_iao, verbose) del(MINAO)
41.094972
128
0.637711
9bdc6ce2d8d2441cc418ede593bb0c200103e262
3,038
swift
Swift
passKitTests/Models/PasswordStoreTest.swift
sysbot/passforios
78d6e6013361cc762a98271b54fbf88301240140
[ "MIT" ]
null
null
null
passKitTests/Models/PasswordStoreTest.swift
sysbot/passforios
78d6e6013361cc762a98271b54fbf88301240140
[ "MIT" ]
null
null
null
passKitTests/Models/PasswordStoreTest.swift
sysbot/passforios
78d6e6013361cc762a98271b54fbf88301240140
[ "MIT" ]
null
null
null
// // PasswordStoreTest.swift // passKitTests // // Copyright © 2020 Bob Sun. All rights reserved. // import Foundation import XCTest import ObjectiveGit @testable import passKit class PasswordStoreTest: XCTestCase { let cloneOptions: [String : GTCredentialProvider] = { let credentialProvider = GTCredentialProvider { (_, _, _) -> (GTCredential?) in try? GTCredential(userName: "", password: "") } return [GTRepositoryCloneOptionsCredentialProvider: credentialProvider] }() let remoteRepoURL = URL(string: "https://github.com/mssun/passforios-password-store.git")! func testCloneAndDecryptMultiKeys() throws { let url = URL(fileURLWithPath: "\(Globals.repositoryPath)-test") let passwordStore = PasswordStore(url: url) let expectation = self.expectation(description: "clone") try passwordStore.cloneRepository( remoteRepoURL: remoteRepoURL, options: cloneOptions, branchName: "master", transferProgressBlock: { _, _ in }, checkoutProgressBlock: { _, _, _ in } ) { expectation.fulfill() } waitForExpectations(timeout: 3, handler: nil) [ ("work/github.com", "4712286271220DB299883EA7062E678DA1024DAE"), ("personal/github.com", "787EAE1A5FA3E749AA34CC6AA0645EBED862027E") ].forEach {(path, id) in let keyID = findGPGID(from: url.appendingPathComponent(path)) XCTAssertEqual(keyID, id) } let keychain = AppKeychain.shared try KeyFileManager(keyType: PgpKey.PUBLIC, keyPath: "", keyHandler: keychain.add).importKey(from: RSA2048_RSA4096.publicKeys) try KeyFileManager(keyType: PgpKey.PRIVATE, keyPath: "", keyHandler: keychain.add).importKey(from: RSA2048_RSA4096.privateKeys) try PGPAgent.shared.initKeys() let personal = try decrypt(passwordStore: passwordStore, path: "personal/github.com.gpg", passphrase: "passforios") XCTAssertEqual(personal.plainText, "passwordforpersonal\n") let work = try decrypt(passwordStore: passwordStore, path: "work/github.com.gpg", passphrase: "passforios") XCTAssertEqual(work.plainText, "passwordforwork\n") let testPassword = Password(name: "test", url: URL(string: "test.gpg")!, plainText: "testpassword") let testPasswordEntity = try passwordStore.add(password: testPassword)! let testPasswordPlain = try passwordStore.decrypt(passwordEntity: testPasswordEntity, requestPGPKeyPassphrase: requestPGPKeyPassphrase ) XCTAssertEqual(testPasswordPlain.plainText, "testpassword") passwordStore.erase() } private func decrypt(passwordStore: PasswordStore, path: String, passphrase: String) throws -> Password { let entity = passwordStore.getPasswordEntity(by: path, isDir: false)! return try passwordStore.decrypt(passwordEntity: entity, requestPGPKeyPassphrase: requestPGPKeyPassphrase ) } }
41.054054
144
0.684332
96f4895b4bc56a450347701e1a1599ebf43b0d2c
3,927
cs
C#
dotnet/src/extensions/Azure/Handlers/Helpers/FunctionMetadata.cs
genexuslabs/DotNetClasses
cffe3676981248bf77964cf0483a9e61a1146351
[ "Apache-2.0" ]
9
2020-04-25T01:30:35.000Z
2021-12-24T00:28:18.000Z
dotnet/src/extensions/Azure/Handlers/Helpers/FunctionMetadata.cs
genexuslabs/DotNetClasses
cffe3676981248bf77964cf0483a9e61a1146351
[ "Apache-2.0" ]
444
2020-04-21T21:10:35.000Z
2022-03-31T22:24:22.000Z
dotnet/src/extensions/Azure/Handlers/Helpers/FunctionMetadata.cs
genexuslabs/DotNetClasses
cffe3676981248bf77964cf0483a9e61a1146351
[ "Apache-2.0" ]
5
2020-04-30T15:12:08.000Z
2022-02-06T17:40:32.000Z
using System.Collections.Generic; using System.Text.Json.Serialization; namespace GeneXus.Deploy.AzureFunctions.Handlers.Helpers { public class FunctionMetadata { public const string directionIn = "In"; public const string directionOut = "Out"; public class TriggerTypes { public const string TimerTrigger = "timerTrigger"; public const string QueueTrigger = "queueTrigger"; public const string ServiceBusTrigger = "serviceBusTrigger"; public const string HttpTrigger = "HttpTrigger"; public const string Http = "http"; } public string name { get; set; } public string scriptFile { get; set; } public string entryPoint { get; set; } public string language { get; set; } public PropertyList properties; [JsonIgnore] public Binding binding; public List<Binding> bindings; public class PropertyList { public PropertyList(bool isCodeless, string confSource) { IsCodeless = isCodeless; configurationSource = confSource; } public bool IsCodeless { get; set; } public string configurationSource { get; set; } } public class Binding { public Binding(string trigger) { type = trigger; } public string type { get; set; } } public class TimerBinding : Binding { public TimerBinding(string trigger, string scheduleTime, bool monitor, bool runStartUp, string nameVariable) : base(trigger) { schedule = scheduleTime; useMonitor = monitor; runOnStartup = runStartUp; name = nameVariable; } public TimerBinding(string trigger) : base(trigger) { } public string schedule { get; set; } public bool useMonitor { get; set; } public bool runOnStartup { get; set; } public string name { get; set; } } public class QueueBinding : Binding { public QueueBinding(string trigger, string connectionQueue, string queue, string nameVariable) : base(trigger) { connection = connectionQueue; queueName = queue; name = nameVariable; } public QueueBinding(string trigger) : base(trigger) { } public string connection { get; set; } public string queueName { get; set; } public string name { get; set; } } public class ServiceBusQueueBinding : QueueBinding { public ServiceBusQueueBinding(string trigger, string connectionQueue, string queue, string nameVariable) : base(trigger, connectionQueue, queue, nameVariable) { } public ServiceBusQueueBinding(string trigger) : base(trigger) { } public bool isSessionsEnabled { get; set; } public bool autoComplete { get; set; } } public class ServiceBusTopicBinding : Binding { public ServiceBusTopicBinding(string trigger) : base(trigger) { } public string connection { get; set; } public string topicName { get; set; } public string subscriptionName { get; set; } public string name { get; set; } public bool isSessionsEnabled { get; set; } public bool autoComplete { get; set; } } public class HttpInBinding : Binding { public HttpInBinding(string nameFunc, string trigger, string authLevelFunc, List<string> methodsSupported, string routeFunc) : base(trigger) { name = nameFunc; direction = directionIn; authLevel = authLevelFunc; methods = methodsSupported; route = routeFunc; } public HttpInBinding(string trigger) : base(trigger) { } public string name { get; set; } public string direction { get; set; } public string authLevel { get; set; } public string route { get; set; } public List<string> methods { get; set; } } public class HttpOutBinding : Binding { public HttpOutBinding(string trigger) : base(trigger) { name = "$return"; direction = directionOut; } public string name { get; set; } public string direction { get; set; } } } }
29.088889
162
0.67176
6b0312d95c3cae9b4484c473828d7adacf9ebf4e
1,432
cpp
C++
src/ConsoleReader.cpp
mjiricka/gongfu-tea-timer
f4bec066d7c5955a7338603ecf10079ccf5a661e
[ "MIT" ]
null
null
null
src/ConsoleReader.cpp
mjiricka/gongfu-tea-timer
f4bec066d7c5955a7338603ecf10079ccf5a661e
[ "MIT" ]
null
null
null
src/ConsoleReader.cpp
mjiricka/gongfu-tea-timer
f4bec066d7c5955a7338603ecf10079ccf5a661e
[ "MIT" ]
null
null
null
#include "ConsoleReader.h" #include <termios.h> #include <unistd.h> #include <stdio.h> #include <cassert> // Inspiration: https://gist.github.com/whyrusleeping/3983293 static void setKeyboardNonBlock(termios *initialSettings) { struct termios new_settings; tcgetattr(STDIN_FILENO, initialSettings); new_settings = *initialSettings; new_settings.c_lflag &= ~(ICANON | ECHO | ISIG); new_settings.c_cc[VMIN] = 0; new_settings.c_cc[VTIME] = 0; tcsetattr(STDIN_FILENO, TCSANOW, &new_settings); } static void restoreKeyboardBlocking(termios *initialSettings) { tcsetattr(STDIN_FILENO, TCSANOW, initialSettings); } void ConsoleReader::startSession() { assert(_sessionIsRunning == false); setKeyboardNonBlock(&termSettings); userInput = 0; _sessionIsRunning = true; } void ConsoleReader::stopSession() { assert(_sessionIsRunning == true); while (getchar() > 0); // Clear CIN buffer. restoreKeyboardBlocking(&termSettings); _sessionIsRunning = false; } bool ConsoleReader::isInput() { assert(_sessionIsRunning == true); if (userInput > 0) { return true; } else { userInput = getchar(); return userInput > 0; } } char ConsoleReader::getInput() { assert(_sessionIsRunning == true); char ui = userInput; userInput = 0; return ui; } bool ConsoleReader::sessionIsRunning() { return _sessionIsRunning; }
20.753623
61
0.689246
457e4d13ac801ec0309ee076530ee1df2010d1f6
1,159
py
Python
problems/617.Merge_Two_Binary_Trees/li.py
subramp-prep/leetcode
d125201d9021ab9b1eea5e5393c2db4edd84e740
[ "Unlicense" ]
null
null
null
problems/617.Merge_Two_Binary_Trees/li.py
subramp-prep/leetcode
d125201d9021ab9b1eea5e5393c2db4edd84e740
[ "Unlicense" ]
null
null
null
problems/617.Merge_Two_Binary_Trees/li.py
subramp-prep/leetcode
d125201d9021ab9b1eea5e5393c2db4edd84e740
[ "Unlicense" ]
null
null
null
# coding=utf-8 # Author: Jianghan LI # Question: 617.Merge_Two_Binary_Trees # Complexity: O(N) # Date: 2017-06-12 10:52 - 10:54, 0 wrong try # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): # merge t2 into t1 if t1 exists. oterwise return t2 def mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ if not t1: return t2 if not t2: return t1 t1.val += t2.val t1.left = self.mergeTrees(t1.left, t2.left) t1.right = self.mergeTrees(t1.right, t2.right) return t1 # return a new tree. better and shorter def mergeTrees(self, t1, t2): if not t1 and not t2: return None res = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0)) res.left = self.mergeTrees(t1.left if t1 else None, t2.left if t2 else None) res.right = self.mergeTrees(t1.right if t1 else None, t2.right if t2 else None) return res
28.268293
87
0.57981
6e5c8d5e5490f9fc0e74a4b1cec1cb3687b989b3
1,844
swift
Swift
test/PCMacro/func_decls.swift
francisvm/swift
15e209ea2fde679ee78438d4ba949144acb7fee4
[ "Apache-2.0" ]
427
2018-05-29T14:21:02.000Z
2022-03-16T03:17:54.000Z
test/PCMacro/func_decls.swift
francisvm/swift
15e209ea2fde679ee78438d4ba949144acb7fee4
[ "Apache-2.0" ]
153
2018-01-21T15:24:47.000Z
2018-09-13T12:46:16.000Z
test/PCMacro/func_decls.swift
francisvm/swift
15e209ea2fde679ee78438d4ba949144acb7fee4
[ "Apache-2.0" ]
52
2018-07-19T19:57:32.000Z
2022-03-11T16:05:38.000Z
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: cp %s %t/main.swift // RUN: %target-build-swift -Xfrontend -pc-macro -o %t/main %S/Inputs/PCMacroRuntime.swift %t/main.swift // RUN: %target-run %t/main | %FileCheck %s // RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PCMacroRuntime.swift %t/main.swift %S/Inputs/SilentPlaygroundsRuntime.swift // RUN: %target-run %t/main | %FileCheck %s // REQUIRES: executable_test // FIXME: rdar://problem/30234450 PCMacro tests fail on linux in optimized mode // UNSUPPORTED: OS=linux-gnu // Lets check that the source ranges are correct on all different kinds of func // decls. #sourceLocation(file: "main.swift", line: 8) func function1(_ x: Int) -> Bool { return x == 1 } _ = function1(0) // CHECK: [12:1-12:17] pc before // CHECK-NEXT: [8:1-8:33] pc before // CHECK-NEXT: [8:1-8:33] pc after // CHECK-NEXT: [9:3-9:16] pc before // CHECK-NEXT: [9:3-9:16] pc after // CHECK-NEXT: [12:1-12:17] pc after func function2(_ x: Int) { } _ = function2(0) // CHECK-NEXT: [24:1-24:17] pc before // CHECK-NEXT: [21:1-21:25] pc before // CHECK-NEXT: [21:1-21:25] pc after // CHECK-NEXT: [24:1-24:17] pc after func function3(_ x: Int) throws { } _ = try! function3(0) // this test is XFAIL-ed in func_throw_notype and should be updated to 31:32 instead of 31:25 once fixed. // CHECK-NEXT: [34:1-34:22] pc before // CHECK-NEXT: [31:1-31:25] pc before // CHECK-NEXT: [31:1-31:25] pc after // CHECK-NEXT: [34:1-34:22] pc after func function4(_ x: Int) throws -> Bool { return x == 1 } _ = try! function4(0) // CHECK-NEXT: [44:1-44:22] pc before // CHECK-NEXT: [41:1-41:40] pc before // CHECK-NEXT: [41:1-41:40] pc after // CHECK-NEXT: [42:3-42:16] pc before // CHECK-NEXT: [42:3-42:16] pc after // CHECK-NEXT: [44:1-44:22] pc after
30.733333
197
0.664317
3f7ed57e442aed7bc9f49bd4d18b64e2cabd0ff6
1,877
rb
Ruby
spec/features/store_admin/authentication/admin_can_visit_dashboard_spec.rb
kelleyjenkins/le-pivot
1306412666966a0b344d99f9dbf6c551fc45ac1a
[ "MIT" ]
1
2021-01-06T00:03:44.000Z
2021-01-06T00:03:44.000Z
spec/features/store_admin/authentication/admin_can_visit_dashboard_spec.rb
kelleyjenkins/le-pivot
1306412666966a0b344d99f9dbf6c551fc45ac1a
[ "MIT" ]
null
null
null
spec/features/store_admin/authentication/admin_can_visit_dashboard_spec.rb
kelleyjenkins/le-pivot
1306412666966a0b344d99f9dbf6c551fc45ac1a
[ "MIT" ]
null
null
null
#need to update paths to be store/admin/dashboard, etc! require 'rails_helper' feature "admin dashboard" do describe "admin can visit the admin dashboard" do it "I will see a heading on the page that says Store Dashboard" do store = create(:store) admin_user = create(:store_admin, store: store) role = Role.create(title: "store_admin") create(:user_role, user: admin_user, role: role) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin_user) visit admin_store_dashboard_index_path(store) expect(page).to have_content("Store Dashboard") end end end describe "as a logged in user when I visit /admin/dashboard" do it "I see a 404 error" do default_user = create(:user) allow_any_instance_of(ApplicationController).to receive(:current_user). and_return(default_user) expect { visit admin_dashboard_index_path }.to raise_error(ActionController::RoutingError) end end describe "as a visitor when I visit /admin/dashboard" do it "I see a 404 error" do expect { visit admin_dashboard_index_path }.to raise_error(ActionController::RoutingError) end end feature "as an Admin" do describe "when I log into my account" do it "I am redirected to the Admin Dashboard" do store = create(:store) admin = create(:store_admin, store: store) role = Role.create(title: "store_admin") create(:user_role, user: admin, role: role) visit login_path fill_in "session[email]", with: admin.email fill_in "session[password]", with: admin.password click_button("Login") expect(page).to have_content("You're logged in as an Administrator") expect(current_path).to eq(admin_store_dashboard_index_path(store)) end end end
27.602941
102
0.6878
7fc1825b5ba08b0933fb987a5fb7069b0b0a20e0
4,705
php
PHP
app/Controllers/VentasController.php
Chelsea9803/api-toycenter
e0b1ad8c15869cc35a2babd22f9e3f90d4d269fe
[ "MIT" ]
null
null
null
app/Controllers/VentasController.php
Chelsea9803/api-toycenter
e0b1ad8c15869cc35a2babd22f9e3f90d4d269fe
[ "MIT" ]
null
null
null
app/Controllers/VentasController.php
Chelsea9803/api-toycenter
e0b1ad8c15869cc35a2babd22f9e3f90d4d269fe
[ "MIT" ]
null
null
null
<?php namespace App\Controllers; use App\Models\VentasModel; use CodeIgniter\API\ResponseTrait; use CodeIgniter\RESTful\ResourceController; class VentasController extends ResourceController { use ResponseTrait; public function getHome() { $model = new VentasModel(); $data = [ 'status' => 200, 'error' => false, 'messages' => [ 'success' => 'Lista de ventas' ] ]; $data['Ventas'] = $model->getHome(); return $this->respond($data); } public function index() { $model = new VentasModel(); $data = [ 'status' => 200, 'error' => false, 'messages' => [ 'success' => 'Lista de ventas' ] ]; $data['Ventas'] = $model->orderBy('ven_id', 'DESC')->findAll(); return $this->respond($data); } public function getVentas($id = null) { $model = new VentasModel(); $response = $model->where('ven_id', $id)->first(); if ($response) { $data = [ 'status' => 200, 'error' => false, 'messages' => [ 'success' => 'Venta Encontrada' ], 'Venta' => $response ]; return $this->respond($data); } else { $data = [ 'status' => 404, 'error' => true, 'messages' => [ 'success' => 'Venta No Existe' ] ]; return $this->respond($data); } } public function getVentasName($name = null) { $model = new VentasModel(); $response = $model->where('ven_factura', $name)->first(); if ($response) { $data = [ 'status' => 200, 'error' => false, 'messages' => [ 'success' => 'Venta Encontrado' ], 'Venta' => $response ]; return $this->respond($data); } else { $data = [ 'status' => 404, 'error' => true, 'messages' => [ 'success' => 'Venta No Existe' ] ]; return $this->respond($data); } } public function create() { $model = new VentasModel(); $data = [ 'ven_factura' => $this->request->getVar('ven_factura'), 'ven_valor' => $this->request->getVar('ven_valor'), 'ven_cant' => $this->request->getVar('ven_cant'), 'cli_id' => $this->request->getVar('cli_id'), 'ven_tipo' => $this->request->getVar('ven_tipo'), 'id_user' => $this->request->getVar('id_user') ]; $model->insert($data); $response = [ 'status' => 201, 'error' => false, 'messages' => [ 'success' => 'Venta Creada' ] ]; return $this->respondCreated($response); } public function updateVentas() { $model = new VentasModel(); $ven_id = $this->request->getVar('ven_id'); $data = [ 'ven_factura' => $this->request->getVar('ven_factura'), 'ven_valor' => $this->request->getVar('ven_valor'), 'ven_cant' => $this->request->getVar('ven_cant'), 'cli_id' => $this->request->getVar('cli_id'), 'ven_tipo' => $this->request->getVar('ven_tipo'), 'id_user' => $this->request->getVar('id_user') ]; //$dt = $this->request->getRawInput(); // print_r($dt); $model->update($ven_id, $data); $response = [ 'status' => 200, 'error' => null, 'messages' => [ 'success' => 'Venta Actualizada' ] ]; return $this->respond($response); } public function delete($ven_id = null) { $model = new VentasModel(); $data = $model->where('ven_id', $ven_id)->delete($ven_id); if ($data) { $model->delete($ven_id); $response = [ 'status' => 200, 'error' => false, 'messages' => [ 'success' => 'Venta Eliminado' ] ]; return $this->respondDeleted($response); } else { return $this->failNotFound('Venta No Existe'); } } }
26.138889
73
0.419129
c58147c59c65593b7d0e664e4247f2e8eee4dfa2
6,782
css
CSS
fire/css/styles.css
luvuong-le/css-illustrations
e9b60969f394d7233ed47f8db6220d0dfc392019
[ "MIT" ]
4
2020-05-31T08:23:35.000Z
2021-07-03T03:25:15.000Z
fire/css/styles.css
luvuong-le/css-illustrations
e9b60969f394d7233ed47f8db6220d0dfc392019
[ "MIT" ]
null
null
null
fire/css/styles.css
luvuong-le/css-illustrations
e9b60969f394d7233ed47f8db6220d0dfc392019
[ "MIT" ]
null
null
null
/* Bonfire */ .bonfire { position: relative; top: 50%; left: 50%; width: 200px; height: 200px; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } /* Fire */ .fire { background: #ED2D22; -webkit-box-shadow: 0 0 10px #ED2D22; box-shadow: 0 0 10px #ED2D22; width: 100%; height: 100%; border-radius: 50% 0 50% 50%; -webkit-transform: rotate(-45deg); transform: rotate(-45deg); -webkit-animation: fire .5s linear infinite; animation: fire .5s linear infinite; z-index: 2; } .fire::before { border-radius: 50% 0 50% 50%; bottom: 0; height: 85%; width: 85%; background: #F68A1A; -webkit-box-shadow: 0 0 10px #F68A1A; box-shadow: 0 0 10px #F68A1A; } .fire::after { border-radius: 50% 0 50% 50%; bottom: 0; height: 70%; width: 70%; background: #FDCB0A; -webkit-box-shadow: 0 0 10px #FDCB0A; box-shadow: 0 0 10px #FDCB0A; } /* Fire Sparks */ .sparks { width: 100%; height: 100%; } .sparks__fire { background: #ED2D22; width: 40px; height: 15px; opacity: 0; border-radius: 10px; -webkit-transform: rotate(90deg); transform: rotate(90deg); } .sparks__fire:after { background: #F68A1A; width: 70%; height: 70%; left: 50%; top: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); border-radius: 10px; } .sparks__fire:nth-of-type(1) { left: 34px; -webkit-animation: fire-spark 2s ease infinite; animation: fire-spark 2s ease infinite; -webkit-animation-delay: 4s; animation-delay: 4s; } .sparks__fire:nth-of-type(2) { left: 164px; -webkit-animation: fire-spark 2s ease infinite; animation: fire-spark 2s ease infinite; -webkit-animation-delay: 6s; animation-delay: 6s; } .sparks__fire:nth-of-type(3) { left: 102px; -webkit-animation: fire-spark 2s ease infinite; animation: fire-spark 2s ease infinite; -webkit-animation-delay: 2s; animation-delay: 2s; } .sparks__fire:nth-of-type(4) { left: 174px; -webkit-animation: fire-spark 3s ease infinite; animation: fire-spark 3s ease infinite; -webkit-animation-delay: 2s; animation-delay: 2s; } .sparks__fire:nth-of-type(5) { left: 4px; -webkit-animation: fire-spark 2s ease infinite; animation: fire-spark 2s ease infinite; -webkit-animation-delay: 3s; animation-delay: 3s; } .sparks__fire:nth-of-type(6) { left: 122px; -webkit-animation: fire-spark 3s ease infinite; animation: fire-spark 3s ease infinite; -webkit-animation-delay: 5s; animation-delay: 5s; } .sparks__fire:nth-of-type(7) { left: 5px; -webkit-animation: fire-spark 2s ease infinite; animation: fire-spark 2s ease infinite; -webkit-animation-delay: 6s; animation-delay: 6s; } .sparks__fire:nth-of-type(8) { left: 79px; -webkit-animation: fire-spark 3s ease infinite; animation: fire-spark 3s ease infinite; -webkit-animation-delay: 6s; animation-delay: 6s; } .sparks__fire:nth-of-type(9) { left: 28px; -webkit-animation: fire-spark 2s ease infinite; animation: fire-spark 2s ease infinite; -webkit-animation-delay: 3s; animation-delay: 3s; } /* Pieces of wood */ .wood { width: 100%; height: 100%; } .wood::before { width: 250px; height: 50px; background: brown; -webkit-box-shadow: 0 0 10px brown, inset 0 0 5px black; box-shadow: 0 0 10px brown, inset 0 0 5px black; border-radius: 10px; bottom: -25px; left: -25px; z-index: 1; -webkit-transform: rotate(-15deg); transform: rotate(-15deg); } .wood::after { width: 250px; height: 50px; background: brown; -webkit-box-shadow: 0 0 10px brown, inset 0 0 5px black; box-shadow: 0 0 10px brown, inset 0 0 5px black; border-radius: 10px; bottom: -25px; left: -25px; z-index: 1; -webkit-transform: rotate(15deg); transform: rotate(15deg); } /* Keyframes */ @-webkit-keyframes fire { 0% { -webkit-transform: rotate(-45deg) scale(1); transform: rotate(-45deg) scale(1); border-radius: 50% 0 50% 50%; } 50% { -webkit-transform: rotate(-45deg) scale(1.05); transform: rotate(-45deg) scale(1.05); border-radius: 50% 0 50% 50%; } 100% { -webkit-transform: rotate(-45deg) scale(1); transform: rotate(-45deg) scale(1); border-radius: 50% 0 50% 50%; } } @keyframes fire { 0% { -webkit-transform: rotate(-45deg) scale(1); transform: rotate(-45deg) scale(1); border-radius: 50% 0 50% 50%; } 50% { -webkit-transform: rotate(-45deg) scale(1.05); transform: rotate(-45deg) scale(1.05); border-radius: 50% 0 50% 50%; } 100% { -webkit-transform: rotate(-45deg) scale(1); transform: rotate(-45deg) scale(1); border-radius: 50% 0 50% 50%; } } @-webkit-keyframes fire-shadow { 0% { -webkit-box-shadow: 0 0 10px #FDCB0A; box-shadow: 0 0 10px #FDCB0A; } 50% { -webkit-box-shadow: 0 0 50px #FDCB0A; box-shadow: 0 0 50px #FDCB0A; } 100% { -webkit-box-shadow: 0 0 10px #FDCB0A; box-shadow: 0 0 10px #FDCB0A; } } @keyframes fire-shadow { 0% { -webkit-box-shadow: 0 0 10px #FDCB0A; box-shadow: 0 0 10px #FDCB0A; } 50% { -webkit-box-shadow: 0 0 50px #FDCB0A; box-shadow: 0 0 50px #FDCB0A; } 100% { -webkit-box-shadow: 0 0 10px #FDCB0A; box-shadow: 0 0 10px #FDCB0A; } } @-webkit-keyframes fire-spark { 0% { -webkit-transform: rotate(90deg) translateX(70px); transform: rotate(90deg) translateX(70px); opacity: 1; } 50% { -webkit-transform: rotate(90deg) translateX(-140px); transform: rotate(90deg) translateX(-140px); opacity: 0; } 70% { -webkit-transform: rotate(90deg) translateX(-140px); transform: rotate(90deg) translateX(-140px); opacity: 0; } 100% { -webkit-transform: rotate(90deg) translateX(70px); transform: rotate(90deg) translateX(70px); opacity: 0; } } @keyframes fire-spark { 0% { -webkit-transform: rotate(90deg) translateX(70px); transform: rotate(90deg) translateX(70px); opacity: 1; } 50% { -webkit-transform: rotate(90deg) translateX(-140px); transform: rotate(90deg) translateX(-140px); opacity: 0; } 70% { -webkit-transform: rotate(90deg) translateX(-140px); transform: rotate(90deg) translateX(-140px); opacity: 0; } 100% { -webkit-transform: rotate(90deg) translateX(70px); transform: rotate(90deg) translateX(70px); opacity: 0; } }
23.305842
58
0.607785
5d184b089a0766b1185c34f8932657fda107ae31
12,451
cpp
C++
dali/internal/event/actors/layer-impl.cpp
vcebollada/dali-core
1f880695d4f6cb871db7f946538721e882ba1633
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali/internal/event/actors/layer-impl.cpp
vcebollada/dali-core
1f880695d4f6cb871db7f946538721e882ba1633
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-03-22T10:19:17.000Z
2020-03-22T10:19:17.000Z
dali/internal/event/actors/layer-impl.cpp
fayhot/dali-core
a69ea317f30961164520664a645ac36c387055ef
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2019 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali/internal/event/actors/layer-impl.h> // EXTERNAL INCLUDES // INTERNAL INCLUDES #include <dali/public-api/actors/layer.h> #include <dali/public-api/common/dali-common.h> #include <dali/public-api/object/type-registry.h> #include <dali/internal/event/actors/layer-list.h> #include <dali/internal/event/common/property-helper.h> #include <dali/internal/event/common/scene-impl.h> #include <dali/internal/event/common/event-thread-services.h> using Dali::Internal::SceneGraph::UpdateManager; namespace Dali { namespace { typedef Layer::Behavior Behavior; DALI_ENUM_TO_STRING_TABLE_BEGIN( BEHAVIOR ) DALI_ENUM_TO_STRING_WITH_SCOPE( Layer, LAYER_UI ) DALI_ENUM_TO_STRING_WITH_SCOPE( Layer, LAYER_3D ) DALI_ENUM_TO_STRING_TABLE_END( BEHAVIOR ) } // namespace namespace Internal { namespace { // Properties // Name Type writable animatable constraint-input enum for index-checking DALI_PROPERTY_TABLE_BEGIN DALI_PROPERTY( "clippingEnable", BOOLEAN, true, false, true, Dali::Layer::Property::CLIPPING_ENABLE ) DALI_PROPERTY( "clippingBox", RECTANGLE, true, false, true, Dali::Layer::Property::CLIPPING_BOX ) DALI_PROPERTY( "behavior", STRING, true, false, false, Dali::Layer::Property::BEHAVIOR ) DALI_PROPERTY_TABLE_END( DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX, LayerDefaultProperties ) // Actions const char* const ACTION_RAISE = "raise"; const char* const ACTION_LOWER = "lower"; const char* const ACTION_RAISE_TO_TOP = "raiseToTop"; const char* const ACTION_LOWER_TO_BOTTOM = "lowerToBottom"; BaseHandle Create() { return Dali::Layer::New(); } TypeRegistration mType( typeid( Dali::Layer ), typeid( Dali::Actor ), Create, LayerDefaultProperties ); TypeAction a1( mType, ACTION_RAISE, &Layer::DoAction ); TypeAction a2( mType, ACTION_LOWER, &Layer::DoAction ); TypeAction a3( mType, ACTION_RAISE_TO_TOP, &Layer::DoAction ); TypeAction a4( mType, ACTION_LOWER_TO_BOTTOM, &Layer::DoAction ); } // unnamed namespace LayerPtr Layer::New() { // create node, nodes are owned by UpdateManager SceneGraph::Layer* layerNode = SceneGraph::Layer::New(); OwnerPointer< SceneGraph::Node > transferOwnership( layerNode ); AddNodeMessage( EventThreadServices::Get().GetUpdateManager(), transferOwnership ); LayerPtr layer( new Layer( Actor::LAYER, *layerNode ) ); // Second-phase construction layer->Initialize(); return layer; } LayerPtr Layer::NewRoot( LayerList& layerList ) { // create node, nodes are owned by UpdateManager SceneGraph::Layer* rootLayer = SceneGraph::Layer::New(); OwnerPointer< SceneGraph::Layer > transferOwnership( rootLayer ); InstallRootMessage( EventThreadServices::Get().GetUpdateManager(), transferOwnership ); LayerPtr root( new Layer( Actor::ROOT_LAYER, *rootLayer ) ); // root actor is immediately considered to be on-stage root->mIsOnStage = true; // The root actor will not emit a stage connection signal so set the signalled flag here as well root->mOnStageSignalled = true; // layer-list must be set for the root layer root->mLayerList = &layerList; layerList.SetRootLayer( &(*root) ); layerList.RegisterLayer( *root ); return root; } Layer::Layer( Actor::DerivedType type, const SceneGraph::Layer& layer ) : Actor( type, layer ), mLayerList( NULL ), mClippingBox( 0, 0, 0, 0 ), mSortFunction( Layer::ZValue ), mBehavior( Dali::Layer::LAYER_UI ), mIsClipping( false ), mDepthTestDisabled( true ), mTouchConsumed( false ), mHoverConsumed( false ) { } void Layer::OnInitialize() { } Layer::~Layer() { if ( mIsRoot ) { // Guard to allow handle destruction after Core has been destroyed if( EventThreadServices::IsCoreRunning() ) { UninstallRootMessage( GetEventThreadServices().GetUpdateManager(), &GetSceneLayerOnStage() ); GetEventThreadServices().UnregisterObject( this ); } } } unsigned int Layer::GetDepth() const { return mLayerList ? mLayerList->GetDepth( this ) : 0u; } void Layer::Raise() { if ( mLayerList ) { mLayerList->RaiseLayer(*this); } } void Layer::Lower() { if ( mLayerList ) { mLayerList->LowerLayer(*this); } } void Layer::RaiseAbove( const Internal::Layer& target ) { // cannot raise above ourself, both have to be on stage if( ( this != &target ) && OnStage() && target.OnStage() ) { // get parameters depth const uint32_t targetDepth = target.GetDepth(); if( GetDepth() < targetDepth ) { MoveAbove( target ); } } } void Layer::LowerBelow( const Internal::Layer& target ) { // cannot lower below ourself, both have to be on stage if( ( this != &target ) && OnStage() && target.OnStage() ) { // get parameters depth const uint32_t targetDepth = target.GetDepth(); if( GetDepth() > targetDepth ) { MoveBelow( target ); } } } void Layer::RaiseToTop() { if ( mLayerList ) { mLayerList->RaiseLayerToTop(*this); } } void Layer::LowerToBottom() { if ( mLayerList ) { mLayerList->LowerLayerToBottom(*this); } } void Layer::MoveAbove( const Internal::Layer& target ) { // cannot raise above ourself, both have to be on stage if( ( this != &target ) && mLayerList && target.OnStage() ) { mLayerList->MoveLayerAbove(*this, target ); } } void Layer::MoveBelow( const Internal::Layer& target ) { // cannot lower below ourself, both have to be on stage if( ( this != &target ) && mLayerList && target.OnStage() ) { mLayerList->MoveLayerBelow(*this, target ); } } void Layer::SetBehavior( Dali::Layer::Behavior behavior ) { mBehavior = behavior; // Notify update side object. SetBehaviorMessage( GetEventThreadServices(), GetSceneLayerOnStage(), behavior ); // By default, disable depth test for LAYER_UI, and enable for LAYER_3D. SetDepthTestDisabled( mBehavior == Dali::Layer::LAYER_UI ); } void Layer::SetClipping(bool enabled) { if (enabled != mIsClipping) { mIsClipping = enabled; // layerNode is being used in a separate thread; queue a message to set the value SetClippingMessage( GetEventThreadServices(), GetSceneLayerOnStage(), mIsClipping ); } } void Layer::SetClippingBox(int x, int y, int width, int height) { if( ( x != mClippingBox.x ) || ( y != mClippingBox.y ) || ( width != mClippingBox.width ) || ( height != mClippingBox.height ) ) { // Clipping box is not animatable; this is the most up-to-date value mClippingBox.Set(x, y, width, height); // Convert mClippingBox to GL based coordinates (from bottom-left) ClippingBox clippingBox( mClippingBox ); if( mScene ) { clippingBox.y = static_cast<int32_t>( mScene->GetSize().height ) - clippingBox.y - clippingBox.height; // layerNode is being used in a separate thread; queue a message to set the value SetClippingBoxMessage( GetEventThreadServices(), GetSceneLayerOnStage(), clippingBox ); } } } void Layer::SetDepthTestDisabled( bool disable ) { if( disable != mDepthTestDisabled ) { mDepthTestDisabled = disable; // Send message. // layerNode is being used in a separate thread; queue a message to set the value SetDepthTestDisabledMessage( GetEventThreadServices(), GetSceneLayerOnStage(), mDepthTestDisabled ); } } bool Layer::IsDepthTestDisabled() const { return mDepthTestDisabled; } void Layer::SetSortFunction(Dali::Layer::SortFunctionType function) { if( function != mSortFunction ) { mSortFunction = function; // layerNode is being used in a separate thread; queue a message to set the value SetSortFunctionMessage( GetEventThreadServices(), GetSceneLayerOnStage(), mSortFunction ); } } void Layer::SetTouchConsumed( bool consume ) { mTouchConsumed = consume; } bool Layer::IsTouchConsumed() const { return mTouchConsumed; } void Layer::SetHoverConsumed( bool consume ) { mHoverConsumed = consume; } bool Layer::IsHoverConsumed() const { return mHoverConsumed; } void Layer::OnStageConnectionInternal() { if ( !mIsRoot ) { DALI_ASSERT_DEBUG( NULL == mLayerList ); // Find the ordered layer-list for ( Actor* parent = mParent; parent != NULL; parent = parent->GetParent() ) { if( parent->IsLayer() ) { Layer* parentLayer = static_cast< Layer* >( parent ); // cheaper than dynamic_cast mLayerList = parentLayer->mLayerList; } } } DALI_ASSERT_DEBUG( NULL != mLayerList ); mLayerList->RegisterLayer( *this ); } void Layer::OnStageDisconnectionInternal() { mLayerList->UnregisterLayer(*this); // mLayerList is only valid when on-stage mLayerList = NULL; } const SceneGraph::Layer& Layer::GetSceneLayerOnStage() const { return static_cast< const SceneGraph::Layer& >( GetNode() ); // we know our node is a layer node } void Layer::SetDefaultProperty( Property::Index index, const Property::Value& propertyValue ) { if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT ) { Actor::SetDefaultProperty( index, propertyValue ); } else { switch( index ) { case Dali::Layer::Property::CLIPPING_ENABLE: { SetClipping( propertyValue.Get<bool>() ); break; } case Dali::Layer::Property::CLIPPING_BOX: { Rect<int32_t> clippingBox( propertyValue.Get<Rect<int32_t> >() ); SetClippingBox( clippingBox.x, clippingBox.y, clippingBox.width, clippingBox.height ); break; } case Dali::Layer::Property::BEHAVIOR: { Behavior behavior(Dali::Layer::LAYER_UI); if( Scripting::GetEnumeration< Behavior >( propertyValue.Get< std::string >().c_str(), BEHAVIOR_TABLE, BEHAVIOR_TABLE_COUNT, behavior ) ) { SetBehavior( behavior ); } break; } default: { DALI_LOG_WARNING( "Unknown property (%d)\n", index ); break; } } // switch(index) } // else } Property::Value Layer::GetDefaultProperty( Property::Index index ) const { Property::Value ret; if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT ) { ret = Actor::GetDefaultProperty( index ); } else { switch( index ) { case Dali::Layer::Property::CLIPPING_ENABLE: { ret = mIsClipping; break; } case Dali::Layer::Property::CLIPPING_BOX: { ret = mClippingBox; break; } case Dali::Layer::Property::BEHAVIOR: { ret = Scripting::GetLinearEnumerationName< Behavior >( GetBehavior(), BEHAVIOR_TABLE, BEHAVIOR_TABLE_COUNT ); break; } default: { DALI_LOG_WARNING( "Unknown property (%d)\n", index ); break; } } // switch(index) } return ret; } Property::Value Layer::GetDefaultPropertyCurrentValue( Property::Index index ) const { Property::Value ret; if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT ) { ret = Actor::GetDefaultPropertyCurrentValue( index ); } else { ret = GetDefaultProperty( index ); // Layer only has event-side properties } return ret; } bool Layer::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& /*attributes*/ ) { bool done = false; Layer* layer = dynamic_cast<Layer*>( object ); if( layer ) { if( 0 == actionName.compare( ACTION_RAISE ) ) { layer->Raise(); done = true; } else if( 0 == actionName.compare( ACTION_LOWER ) ) { layer->Lower(); done = true; } else if( 0 == actionName.compare( ACTION_RAISE_TO_TOP ) ) { layer->RaiseToTop(); done = true; } else if( 0 == actionName.compare( ACTION_LOWER_TO_BOTTOM ) ) { layer->LowerToBottom(); done = true; } } return done; } } // namespace Internal } // namespace Dali
25.410204
145
0.674886
e252d2e263e9d49542db4ad58d8a2790aa10a1f2
185
rs
Rust
hesoyam_core/src/query_builder/clause/mod.rs
andrew528i/hesoyam
3ecb77e7457db9b97255758d655d17322f9448cb
[ "MIT" ]
13
2020-07-17T04:46:30.000Z
2021-12-21T06:47:10.000Z
hesoyam_core/src/query_builder/clause/mod.rs
mashuai/hesoyam
ab8ad716a289469ea254e4683433a9764129de8c
[ "MIT" ]
null
null
null
hesoyam_core/src/query_builder/clause/mod.rs
mashuai/hesoyam
ab8ad716a289469ea254e4683433a9764129de8c
[ "MIT" ]
2
2020-08-04T14:10:41.000Z
2020-08-06T01:03:13.000Z
pub use delete::*; pub use insert::*; pub use select::*; pub use update::*; pub use where_::*; pub use limit::*; mod select; mod update; mod where_; mod delete; mod insert; mod limit;
13.214286
18
0.67027
52119cdbeee6141aaa06bb86dde67771ba707795
435
lua
Lua
game/scripts/vscripts/units/undead/abomination.lua
PetarTilevRusev/EndlessWar
77a02ff64263c331ddfcbbef21fa41f1b3920a3c
[ "MIT" ]
null
null
null
game/scripts/vscripts/units/undead/abomination.lua
PetarTilevRusev/EndlessWar
77a02ff64263c331ddfcbbef21fa41f1b3920a3c
[ "MIT" ]
null
null
null
game/scripts/vscripts/units/undead/abomination.lua
PetarTilevRusev/EndlessWar
77a02ff64263c331ddfcbbef21fa41f1b3920a3c
[ "MIT" ]
null
null
null
function DiseaseCloudStartSound( keys ) local caster = keys.caster local sound = "Hero_Pudge.Rot" StartSoundEvent(sound, caster) Timers:CreateTimer( function() if not caster:HasModifier("abomination_disease_cloud_debuff_modifier") then DiseaseCloudStopSound(sound, caster) else return 1 end end) end function DiseaseCloudStopSound( sound, caster ) StopSoundEvent(sound, caster) end
24.166667
80
0.726437
0d2dfe29e3910a766846aecfeac36aed5afe5219
460
cs
C#
Squalr.Engine.Debugger/CodeTraceInfo.cs
Xen0byte/Squalr
be300f2bf9d4129751b6c2f21f62c7bfe7e3f852
[ "MIT" ]
null
null
null
Squalr.Engine.Debugger/CodeTraceInfo.cs
Xen0byte/Squalr
be300f2bf9d4129751b6c2f21f62c7bfe7e3f852
[ "MIT" ]
null
null
null
Squalr.Engine.Debugger/CodeTraceInfo.cs
Xen0byte/Squalr
be300f2bf9d4129751b6c2f21f62c7bfe7e3f852
[ "MIT" ]
null
null
null
namespace Squalr.Engine.Debuggers { using Squalr.Engine.Architecture; using System; using System.Collections.Generic; public class CodeTraceInfo { public CodeTraceInfo() { this.IntRegisters = new Dictionary<String, UInt64>(); } public Instruction Instruction { get; set; } public Dictionary<String, UInt64> IntRegisters { get; set; } } //// End interface } //// End namespace
21.904762
68
0.623913
db985aa25c37fa8f2f39f00aa12a4b8d2b31f7f2
24,627
php
PHP
bitrix/modules/forum/install/components/bitrix/forum.rss/component.php
votanko/Bitrix_tutorial
2fcc045ec827ac08d9dcdbefa1f6ff822730c2b2
[ "MIT" ]
1
2020-10-05T04:28:40.000Z
2020-10-05T04:28:40.000Z
bitrix/modules/forum/install/components/bitrix/forum.rss/component.php
votanko/Bitrix_tutorial
2fcc045ec827ac08d9dcdbefa1f6ff822730c2b2
[ "MIT" ]
null
null
null
bitrix/modules/forum/install/components/bitrix/forum.rss/component.php
votanko/Bitrix_tutorial
2fcc045ec827ac08d9dcdbefa1f6ff822730c2b2
[ "MIT" ]
null
null
null
<?if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die(); if (!CModule::IncludeModule("forum")): ShowError(GetMessage("F_NO_MODULE")); return 0; elseif (is_set($arParams, "USE_RSS") && $arParams["USE_RSS"] == "N"): // out-of-date params return 0; endif; if (!function_exists("__create_uuid")) { function __create_uuid($params) { $uuid = md5($params); return substr($uuid, 0, 8).'-'. substr($uuid, 8, 4).'-'. substr($uuid, 12, 4).'-'. substr($uuid, 16, 4).'-'. substr($uuid, 20); } } $arResult["TYPE_RSS"] = array("RSS1" => "RSS .92", "RSS2" => "RSS 2.0", "ATOM" => "Atom .3"); $arResult["FORUMS"] = array(); $arResult["TOPIC"] = array(); $arResult["SERVER_NAME"] = (defined("SITE_SERVER_NAME") && strLen(SITE_SERVER_NAME) > 0) ? SITE_SERVER_NAME : COption::GetOptionString("main", "server_name"); /******************************************************************** Input params ********************************************************************/ /***************** BASE ********************************************/ $arParams["TYPE_RANGE"] = (is_array($arParams["TYPE_RANGE"]) ? $arParams["TYPE_RANGE"] : array("RSS1", "RSS2", "ATOM")); $arParams["TYPE_RANGE"] = array_intersect($arParams["TYPE_RANGE"], array_keys($arResult["TYPE_RSS"])); $arParams["TYPE_DEFAULT"] = (in_array($arParams["TYPE_DEFAULT"], $arParams["TYPE_RANGE"]) ? $arParams["TYPE_DEFAULT"] : $arParams["TYPE_RANGE"][0]); $arParams["TYPE"] = (strToUpper($arParams["TYPE"]) == "DEFAULT" ? $arParams["TYPE_DEFAULT"] : $arParams["TYPE"]); $arParams["TYPE"] = strToUpper(!empty($arResult["TYPE_RSS"][strToUpper($arParams["TYPE"])]) ? $arParams["TYPE"] : false); $arParams["FID_RANGE"] = (is_array($arParams["FID_RANGE"]) ? $arParams["FID_RANGE"] : array()); $arParams["MODE"] = (in_array(strToLower($arParams["MODE"]), array("forum", "topic", "link")) ? strToLower($arParams["MODE"]) : "link"); $arParams["MODE_DATA"] = trim($arParams["MODE_DATA"]); if (empty($arParams["MODE_DATA"])) $arParams["MODE_DATA"] = ($arParams["MODE"] == "topic" ? "topic" : "forum"); else $arParams["MODE_DATA"] = ($arParams["MODE_DATA"] == "topic" ? "topic" : "forum"); $arParams["MODE"] = ($arParams["MODE"] == "link" || $arParams["TYPE"] == false ? "link" : "rss"); $arParams["IID"] = intVal(intVal($arParams["IID"]) <= 0 ? $_REQUEST["IID"] : $arParams["IID"]); $arParams["FID"] = ($arParams["MODE_DATA"] == "forum" ? $arParams["IID"] : 0); $arParams["TID"] = ($arParams["MODE_DATA"] == "topic" ? $arParams["IID"] : 0); /***************** URL *********************************************/ $URL_NAME_DEFAULT = array( "list" => "PAGE_NAME=list&FID=#FID#", "read" => "PAGE_NAME=read&FID=#FID#&TID=#TID#", "message" => "PAGE_NAME=message&FID=#FID#&TID=#TID#&MID=#MID#", "profile_view" => "PAGE_NAME=profile_view&UID=#UID#", "rss" => "PAGE_NAME=rss&TYPE=#TYPE#&MODE=#MODE#&IID=#IID#"); if (empty($arParams["URL_TEMPLATES_MESSAGE"]) && !empty($arParams["URL_TEMPLATES_READ"])) { $arParams["URL_TEMPLATES_MESSAGE"] = $arParams["URL_TEMPLATES_READ"]; } foreach ($URL_NAME_DEFAULT as $URL => $URL_VALUE) { if (strLen(trim($arParams["URL_TEMPLATES_".strToUpper($URL)])) <= 0) $arParams["URL_TEMPLATES_".strToUpper($URL)] = $APPLICATION->GetCurPage()."?".$URL_VALUE; $arParams["~URL_TEMPLATES_".strToUpper($URL)] = $arParams["URL_TEMPLATES_".strToUpper($URL)]; $arParams["URL_TEMPLATES_".strToUpper($URL)] = htmlspecialcharsbx($arParams["~URL_TEMPLATES_".strToUpper($URL)]); } /***************** ADDITIONAL **************************************/ $arParams["COUNT"] = intVal(intVal($arParams["COUNT"]) > 0 ? $arParams["COUNT"] : ($arParams["MODE_DATA"] == "forum" ? COption::GetOptionString("forum", "TOPICS_PER_PAGE", "10") : COption::GetOptionString("forum", "MESSAGES_PER_PAGE", "10"))); $arParams["COUNT"] = ($arParams["COUNT"] > 0 ? $arParams["COUNT"] : 10); $arParams["MAX_FILE_SIZE"] = (intVal($arParams["MAX_FILE_SIZE"]) <= 0 ? 10*1024*1024 : intVal($arParams["MAX_FILE_SIZE"])*1024*1024); $arParams["DATE_TIME_FORMAT"] = trim(empty($arParams["DATE_TIME_FORMAT"]) ? $DB->DateFormatToPHP(CSite::GetDateFormat("FULL")) : $arParams["DATE_TIME_FORMAT"]); $arParams["NAME_TEMPLATE"] = (!empty($arParams["NAME_TEMPLATE"]) ? $arParams["NAME_TEMPLATE"] : false); $arParams["DESIGN_MODE"] = ($GLOBALS["APPLICATION"]->GetShowIncludeAreas() && CForumUser::IsAdmin() ? "Y" : "N"); $arParams["TEMPLATES_TITLE_FORUMS"] = ($arParams["TEMPLATES_TITLE_FORUMS"] ? $arParams["TEMPLATES_TITLE_FORUMS"] : GetMessage("F_TEMPLATES_TITLE_FORUMS")); $arParams["TEMPLATES_TITLE_FORUM"] = ($arParams["TEMPLATES_TITLE_FORUM"] ? $arParams["TEMPLATES_TITLE_FORUM"] : GetMessage("F_TEMPLATES_TITLE_FORUM")); $arParams["TEMPLATES_TITLE_TOPIC"] = ($arParams["TEMPLATES_TITLE_TOPIC"] ? $arParams["TEMPLATES_TITLE_TOPIC"] : GetMessage("F_TEMPLATES_TITLE_TOPIC")); $arParams["TEMPLATES_DESCRIPTION_FORUMS"] = ($arParams["TEMPLATES_DESCRIPTION_FORUMS"] ? $arParams["TEMPLATES_DESCRIPTION_FORUMS"] : GetMessage("F_TEMPLATES_DESCRIPTION_FORUMS")); $arParams["TEMPLATES_DESCRIPTION_FORUM"] = ($arParams["TEMPLATES_DESCRIPTION_FORUM"] ? $arParams["TEMPLATES_DESCRIPTION_FORUM"] : GetMessage("F_TEMPLATES_DESCRIPTION_FORUM")); $arParams["TEMPLATES_DESCRIPTION_TOPIC"] = ($arParams["TEMPLATES_DESCRIPTION_TOPIC"] ? $arParams["TEMPLATES_DESCRIPTION_TOPIC"] : GetMessage("F_TEMPLATES_DESCRIPTION_TOPIC")); /***************** CACHE *******************************************/ if ($arParams["CACHE_TYPE"] == "Y" || ($arParams["CACHE_TYPE"] == "A" && COption::GetOptionString("main", "component_cache_on", "Y") == "Y")) $arParams["CACHE_TIME"] = intval($arParams["CACHE_TIME"]); else $arParams["CACHE_TIME"] = 0; $arParams["CACHE_TIME"] = 0; /******************************************************************** /Input params ********************************************************************/ if (empty($arParams["TYPE_RANGE"])): ShowError(GetMessage("F_EMPTY_TYPE")); return 0; else: $arFilter = (!empty($arParams["FID_RANGE"]) ? array("@ID" => $arParams["FID_RANGE"]) : array()) + array( "LID" => SITE_ID, "PERMS" => array($USER->GetGroups(), 'A'), "ACTIVE" => "Y"); $db_res = CForumNew::GetListEx( array("FORUM_GROUP_SORT"=>"ASC", "FORUM_GROUP_ID"=>"ASC", "SORT"=>"ASC", "NAME"=>"ASC"), $arFilter, false, 0, array("sNameTemplate" => $arParams["NAME_TEMPLATE"]) ); if ($db_res && ($res = $db_res->Fetch())) { do { foreach ($res as $key => $val): $res["~".$key] = $val; $res[$key] = htmlspecialcharsbx($val); endforeach; $res["ALLOW"] = forumTextParser::GetFeatures($res); $res["~FORUM_DESCRIPTION"] = $res["~DESCRIPTION"]; $res["FORUM_DESCRIPTION"] = $res["DESCRIPTION"]; $res["~FORUM_LINK"] = CComponentEngine::MakePathFromTemplate($arParams["~URL_TEMPLATES_LIST"], array("FID" => $res["ID"])); $res["FORUM_LINK"] = CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_LIST"], array("FID" => $res["ID"])); $res["~URL"] = "http://".$arResult["SERVER_NAME"].$res["~FORUM_LINK"]; $res["URL"] = "http://".htmlspecialcharsbx($arResult["SERVER_NAME"]).$res["FORUM_LINK"]; $arResult["FORUMS"][$res["ID"]] = $res; }while ($res = $db_res->Fetch()); } if (empty($arResult["FORUMS"])): ShowError(GetMessage("F_EMPTY_FORUMS")); CHTTP::SetStatus("404 Not Found"); return false; elseif ($arParams["MODE_DATA"] == "topic" && $arParams["TID"] <= 0): ShowError(GetMessage("F_EMPTY_TOPIC_ID")); CHTTP::SetStatus("404 Not Found"); return false; elseif ($arParams["MODE_DATA"] == "topic"): if (!($res = CForumTopic::GetList(array(), array("ID" => $arParams["TID"]))->fetch())): ShowError(GetMessage("F_EMPTY_TOPIC")); CHTTP::SetStatus("404 Not Found"); return false; elseif (!array_key_exists($res["FORUM_ID"], $arResult["FORUMS"])): ShowError(GetMessage("F_EMPTY_TOPIC")); CHTTP::SetStatus("404 Not Found"); return false; endif; foreach ($res as $key => $val): $res["~".$key] = $val; $res[$key] = htmlspecialcharsbx($val); endforeach; $arResult["TOPIC"] = $res; endif; endif; if (empty($arResult["FORUMS"]) || ($_SESSION["SESS_SEARCHER_ID"] > 0 && CModule::IncludeModule("statistic"))): return false; elseif ($arParams["MODE_DATA"] == "forum" && $arParams["FID"] > 0 && empty($arResult["FORUMS"][$arParams["FID"]])): if ($arParams["MODE"] != "link"): ShowError(GetMessage("F_ERR_BAD_FORUM")); CHTTP::SetStatus("404 Not Found"); endif; return false; elseif ($arParams["MODE_DATA"] == "topic" && $arParams["TID"] > 0 && empty($arResult["FORUMS"][$arResult["TOPIC"]["FORUM_ID"]])): if ($arParams["MODE"] != "link"): ShowError(GetMessage("F_ERR_BAD_FORUM")); CHTTP::SetStatus("404 Not Found"); endif; return false; endif; /******************************************************************** Data 1 ********************************************************************/ if ($arParams["MODE"] == "link"): $arResult["rss_link"] = array(); foreach ($arParams["TYPE_RANGE"] as $key) { $rss = strToLower($key); $arResult["rss_link"][$rss] = array( "type" => $rss, "name" => $arResult["TYPE_RSS"][$key], "link" => CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_RSS"], array("TYPE" => $rss, "MODE" => $arParams["MODE_DATA"], "IID" => $arParams["IID"]))); } $this->IncludeComponentTemplate(); return false; endif; /******************************************************************** /Data 1 ********************************************************************/ /******************************************************************** Default values ********************************************************************/ $arFilter = array(); $arItems = array(); $arParams["FID"] = (!empty($arResult["FORUMS"][$arParams["FID"]]) ? $arParams["FID"] : 0); $arResult["LANGUAGE_ID"] = LANGUAGE_ID; $arResult["CHARSET"] = (defined("SITE_CHARSET") && strLen(SITE_CHARSET) > 0) ? SITE_CHARSET : "windows-1251"; $arResult["NOW"] = ($arParams["TYPE"] != "ATOM") ? date("r") : date("Y-m-d H:i:s").substr(date("O"), 0, 3).":".substr(date("O"), -2, 2); $arResult["TEMPLATE_ELEMENTS"] = array("AUTHOR_NAME", "AUTHOR_LINK", "SIGNATURE", "DATE_REG", "AVATAR", "POST_MESSAGE", "POST_LINK", "POST_DATE", "ATTACH_IMG", "TITLE", "TOPIC_LINK", "TOPIC_DATE", "TOPIC_DESCRIPTION", "NAME", "FORUM_LINK", "FORUM_DESCRIPTION"); $parser = new forumTextParser(LANGUAGE_ID); $parser->MaxStringLen = 0; $parser->userPath = $arParams["URL_TEMPLATES_PROFILE_VIEW"]; $parser->userNameTemplate = $arParams["NAME_TEMPLATE"]; $arResult["SITE"] = array(); $db_res = CSite::GetByID(SITE_ID); if ($db_res && $res = $db_res->GetNext()) $arResult["SITE"] = $res; $arResult["~TITLE"] = $arParams["TEMPLATES_TITLE_FORUMS"]; $arResult["~DESCRIPTION"] = $arParams["TEMPLATES_DESCRIPTION_FORUMS"]; if ($arParams["MODE_DATA"] == "forum" && $arParams["IID"] > 0) { $arResult["~TITLE"] = $arParams["TEMPLATES_TITLE_FORUM"]; $arResult["~DESCRIPTION"] = $arParams["TEMPLATES_DESCRIPTION_FORUM"]; } elseif ($arParams["MODE_DATA"] == "topic") { $arResult["~TITLE"] = $arParams["TEMPLATES_TITLE_TOPIC"]; $arResult["~DESCRIPTION"] = $arParams["TEMPLATES_DESCRIPTION_TOPIC"]; } $arResult["~TITLE"] = str_replace( array("#FORUM_TITLE#", "#FORUM_DESCRIPTION#", "#TOPIC_TITLE#", "#TOPIC_DESCRIPTION#", "#SITE_NAME#", "#SERVER_NAME#"), array($arResult["FORUMS"][$arParams["IID"]]["~NAME"], $arResult["FORUMS"][$arParams["IID"]]["~DESCRIPTION"], $arResult["TOPIC"]["~TITLE"], $arResult["TOPIC"]["~DESCRIPTION"], $arResult["SITE"]["SITE_NAME"], $arResult["SERVER_NAME"]), $arResult["~TITLE"]); $arResult["~DESCRIPTION"] = str_replace( array("#FORUM_TITLE#", "#FORUM_DESCRIPTION#", "#TOPIC_TITLE#", "#TOPIC_DESCRIPTION#", "#SITE_NAME#", "#SERVER_NAME#"), array($arResult["FORUMS"][$arParams["IID"]]["~NAME"], $arResult["FORUMS"][$arParams["IID"]]["~DESCRIPTION"], $arResult["TOPIC"]["~TITLE"], $arResult["TOPIC"]["~DESCRIPTION"], $arResult["SITE"]["SITE_NAME"], $arResult["SERVER_NAME"]), $arResult["~DESCRIPTION"]); $arResult["TITLE"] = htmlspecialcharsbx($arResult["~TITLE"]); $arResult["DESCRIPTION"] = htmlspecialcharsbx($arResult["~DESCRIPTION"]); $arResult["URL"] = array( "~ALTERNATE" => "http://".$arResult["SERVER_NAME"], "ALTERNATE" => htmlspecialcharsbx("http://".$arResult["SERVER_NAME"]), "~REAL" => "http://".$arResult["SERVER_NAME"].$APPLICATION->GetCurPageParam(), "REAL" => htmlspecialcharsbx("http://".$arResult["SERVER_NAME"].$APPLICATION->GetCurPageParam())); $arResult["MESSAGE_LIST"] = $arResult["FILES"] = array(); /******************************************************************** /Default values ********************************************************************/ /******************************************************************** Data 2 ********************************************************************/ $cache_id_array = array("MODE" => $arParams["MODE_DATA"], "IID" => $arParams["IID"], "TYPE" => $arParams["TYPE"], "COUNT" => $arParams["COUNT"], "FID_RANGE" => $arParams["FID_RANGE"], "USER_GROUP" => $GLOBALS["USER"]->GetUserGroupArray(), "LANGUAGE" => $arResult["LANGUAGE_ID"], "SERVER_NAME" => $arResult["SERVER_NAME"], "CHARSET" => $arResult["CHARSET"]); if ($arParams["DESIGN_MODE"] != "Y") { $APPLICATION->RestartBuffer(); header("Content-Type: text/xml"); header("Pragma: no-cache"); } if($this->StartResultCache($arParams["CACHE_TIME"], array($cache_id_array, $arParams["DESIGN_MODE"]), "/".SITE_ID."/forum/rss/".$arParams["TYPE"]."/".$arParams["MODE_DATA"]."/")) { $arFilter = array( "TOPIC_ID" => $arParams["TID"], "APPROVED" => "Y", "@FORUM_ID" => implode(",", array_keys($arResult["FORUMS"])), "TOPIC" => "GET_TOPIC_INFO"); if ($arParams["MODE_DATA"] != "topic") { $arFilter = array(); if (intVal($arParams["FID"]) > 0) { $arFilter["FORUM_ID"] = $arParams["FID"]; } else { $arFilter["@FORUM_ID"] = implode(",", array_keys($arResult["FORUMS"])); } $arFilter["APPROVED"] = "Y"; $arFilter["NEW_TOPIC"] = "Y"; $arFilter["TOPIC"] = "GET_TOPIC_INFO"; } CTimeZone::Disable(); $db_res = CForumMessage::GetListEx( array("ID" => "DESC"), $arFilter, 0, $arParams["COUNT"], array("sNameTemplate" => $arParams["NAME_TEMPLATE"])); CTimeZone::Enable(); if ($db_res && ($res = $db_res->Fetch())) { do { foreach ($res as $key => $val) { $res["~".$key] = $val; $res[$key] = htmlspecialcharsbx($val); } /************** Message info ***************************************/ // data $arDate = ParseDateTime($res["POST_DATE"], false); $date = date("r", mktime($arDate["HH"], $arDate["MI"], $arDate["SS"], $arDate["MM"], $arDate["DD"], $arDate["YYYY"])); if ($arParams["TYPE"] == "ATOM") { $timeISO = mktime($arDate["HH"], $arDate["MI"], $arDate["SS"], $arDate["MM"], $arDate["DD"], $arDate["YYYY"]); $date = date("Y-m-d\TH:i:s", $timeISO).substr(date("O", $timeISO), 0, 3).":".substr(date("O", $timeISO), -2, 2); } $res["POST_DATE"] = $date; $res["POST_DATE_FORMATED"] = CForumFormat::DateFormat($arParams["DATE_TIME_FORMAT"], MakeTimeStamp($res["~POST_DATE"], CSite::GetDateFormat())+CTimeZone::GetOffset()); // text $arAllow = $arResult["FORUMS"][$res["FORUM_ID"]]["ALLOW"]; $res["ALLOW"] = array_merge($arAllow, array("SMILES" => ($res["USE_SMILES"] == "Y" ? $arAllow["SMILES"] : "N"))); $res["~POST_MESSAGE"] = (COption::GetOptionString("forum", "FILTER", "Y")=="Y" ? $res["~POST_MESSAGE_FILTER"] : $res["~POST_MESSAGE"]); // attach $res["ATTACH_IMG"] = ""; $res["FILES"] = $res["~ATTACH_FILE"] = $res["ATTACH_FILE"] = array(); /************** Message info/***************************************/ /************** Author info ****************************************/ // Avatar if (strLen($res["AVATAR"]) > 0): $res["~AVATAR"] = array("ID" => $res["AVATAR"]); $res["~AVATAR"]["FILE"] = CFile::GetFileArray($res["~AVATAR"]["ID"]); $res["AVATAR"] = CFile::ShowImage($res["~AVATAR"]["FILE"], COption::GetOptionString("forum", "avatar_max_width", 100), COption::GetOptionString("forum", "avatar_max_height", 100), "border=\"0\"", "", true); endif; // data $res["DATE_REG"] = CForumFormat::DateFormat($arParams["DATE_FORMAT"], MakeTimeStamp($res["DATE_REG"], CSite::GetDateFormat())); // Another data $res["SIGNATURE"] = ""; if ($arResult["FORUMS"][$res["FORUM_ID"]]["ALLOW_SIGNATURE"] == "Y" && strlen($res["~SIGNATURE"]) > 0) { $res["SIGNATURE"] = $parser->convert_to_rss($res["~SIGNATURE"], array_merge($arAllow, array("SMILES" => "N"))); } /************** Author info/****************************************/ $res["~AUTHOR_LINK"] = CComponentEngine::MakePathFromTemplate($arParams["~URL_TEMPLATES_PROFILE_VIEW"], array("UID" => intVal($res["AUTHOR_ID"]))); $res["AUTHOR_LINK"] = CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_PROFILE_VIEW"], array("UID" => intVal($res["AUTHOR_ID"]))); $res["~POST_LINK"] = CComponentEngine::MakePathFromTemplate($arParams["~URL_TEMPLATES_MESSAGE"], array("FID" => $res["FORUM_ID"], "TID" => $res["TOPIC_ID"], "TITLE_SEO" => $res["TITLE_SEO"], "MID" => $res["ID"])); $res["POST_LINK"] = CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_MESSAGE"], array("FID" => $res["FORUM_ID"], "TID" => $res["TOPIC_ID"], "TITLE_SEO" => $res["TITLE_SEO"], "MID" => $res["ID"])); $res["~AUTHOR_URL"] = "http://".$arResult["SERVER_NAME"].$res["~AUTHOR_LINK"]; $res["AUTHOR_URL"] = "http://".htmlspecialcharsbx($arResult["SERVER_NAME"]).$res["AUTHOR_LINK"]; $res["~URL"] = "http://".$arResult["SERVER_NAME"].$res["~POST_LINK"]; $res["URL"] = "http://".htmlspecialcharsbx($arResult["SERVER_NAME"]).$res["POST_LINK"]; $res["~URL_RSS"] = "http://".$arResult["SERVER_NAME"].CComponentEngine::MakePathFromTemplate($arParams["~URL_TEMPLATES_RSS"], array("TYPE" => strToLower($arParams["TYPE"]), "MODE" => "topic", "IID" => $res["TOPIC_ID"])); $res["URL_RSS"] = "http://".htmlspecialcharsbx($arResult["SERVER_NAME"]). CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_RSS"], array("TYPE" => strToLower($arParams["TYPE"]), "MODE" => "topic", "IID" => $res["TOPIC_ID"])); $res["UUID"] = __create_uuid($res["~URL"]); // TOPIC DATA $arDate = ParseDateTime($res["START_DATE"], false); $date = date("r", mktime($arDate["HH"], $arDate["MI"], $arDate["SS"], $arDate["MM"], $arDate["DD"], $arDate["YYYY"])); if ($arParams["TYPE"] == "ATOM") { $timeISO = mktime($arDate["HH"], $arDate["MI"], $arDate["SS"], $arDate["MM"], $arDate["DD"], $arDate["YYYY"]); $date = date("Y-m-d\TH:i:s", $timeISO).substr(date("O", $timeISO), 0, 3).":".substr(date("O", $timeISO), -2, 2); } $topic = array( "ID" => $res["TOPIC_ID"], "TITLE" => $res["TITLE"], "~TITLE" => $res["~TITLE"], "DESCRIPTION" => $res["TOPIC_DESCRIPTION"], "~DESCRIPTION" => $res["~TOPIC_DESCRIPTION"], "TOPIC_DESCRIPTION" => $res["TOPIC_DESCRIPTION"], "~TOPIC_DESCRIPTION" => $res["~TOPIC_DESCRIPTION"], "START_DATE" => $date, "~START_DATE" => $res["~START_DATE"], "START_DATE_FORMATED" => CForumFormat::DateFormat($arParams["DATE_TIME_FORMAT"], MakeTimeStamp($res["~START_DATE"], CSite::GetDateFormat())), "AUTHOR_NAME" => $res["USER_START_NAME"], "~AUTHOR_NAME" => $res["~USER_START_NAME"], "AUTHOR_ID" => $res["USER_START_ID"], "~AUTHOR_ID" => $res["~USER_START_ID"], "~AUTHOR_LINK" => CComponentEngine::MakePathFromTemplate($arParams["~URL_TEMPLATES_PROFILE_VIEW"], array("UID" => intVal($res["~USER_START_ID"]))), "AUTHOR_LINK" => CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_PROFILE_VIEW"], array("UID" => intVal($res["~USER_START_ID"]))), "~TOPIC_LINK" => CComponentEngine::MakePathFromTemplate($arParams["~URL_TEMPLATES_READ"], array("FID" => $res["FORUM_ID"], "TID" => $res["TOPIC_ID"], "TITLE_SEO" => $res["TITLE_SEO"], "MID" => "s")), "TOPIC_LINK" => CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_READ"], array("FID" => $res["FORUM_ID"], "TID" => $res["TOPIC_ID"], "TITLE_SEO" => $res["TITLE_SEO"], "MID" => "s")), "MESSAGES" => array() ); $topic["~AUTHOR_URL"] = "http://".$arResult["SERVER_NAME"].$topic["~AUTHOR_LINK"]; $topic["AUTHOR_URL"] = "http://".htmlspecialcharsbx($arResult["SERVER_NAME"]).$topic["AUTHOR_LINK"]; $topic["~URL"] = "http://".$arResult["SERVER_NAME"].$topic["~TOPIC_LINK"]; $topic["URL"] = "http://".htmlspecialcharsbx($arResult["SERVER_NAME"]).$topic["TOPIC_LINK"]; if (empty($arItems[$res["FORUM_ID"]]["TOPICS"][$res["TOPIC_ID"]])) $arItems[$res["FORUM_ID"]]["TOPICS"][$res["TOPIC_ID"]] = $topic; unset($res["TITLE"]); unset($res["DESCRIPTION"]); if (!empty($arParams["TEMPLATE"])) { $text = $arParams["TEMPLATE"]; foreach ($arParams["TEMPLATE_ELEMENTS"] as $element) { $replace = array($arItems[$res["FORUM_ID"]]["TOPICS"][$res["TOPIC_ID"]][$element], $arItems[$res["FORUM_ID"]]["TOPICS"][$res["TOPIC_ID"]]["~".$element]); if (strLen($res[$element]) > 0) $replace = array($res[$element], $res["~".$element]); $text = str_replace(array("#".$res."#", "#~".$res."#"), $replace, $text); } $res["TEMPLATE"] = $text; } $arResult["MESSAGE_LIST"][$res["ID"]] = $res; $arItems[$res["FORUM_ID"]]["TOPICS"][$res["TOPIC_ID"]]["MESSAGES"][$res["ID"]] = $res; } while ($res = $db_res->Fetch()); } if (is_array($arItems) && (count($arItems) > 0)) { foreach ($arItems as $key => $val) $arItems[$key] = array_merge($arResult["FORUMS"][$key], $val); } /************** Attach files ***************************************/ if (!empty($arResult["MESSAGE_LIST"])) { $arFilter = array("@FILE_MESSAGE_ID" => array_keys($arResult["MESSAGE_LIST"])); $db_files = CForumFiles::GetList(array("MESSAGE_ID" => "ASC"), $arFilter); if ($db_files && $res = $db_files->Fetch()) { do { $arResult["FILES"][$res["FILE_ID"]] = $res; $res["SRC"] = str_replace("#FILE_ID#", $res["FILE_ID"], $src); $arItems[$res["FORUM_ID"]]["TOPICS"][$res["TOPIC_ID"]]["MESSAGES"][$res["MESSAGE_ID"]]["FILES"][$res["FILE_ID"]] = $res; }while ($res = $db_files->Fetch()); } $parser->arFiles = $arResult["FILES"]; foreach ($arResult["MESSAGE_LIST"] as $iID => $res) { $arItems[$res["FORUM_ID"]]["TOPICS"][$res["TOPIC_ID"]]["MESSAGES"][$res["ID"]]["POST_MESSAGE"] = $parser->convert_to_rss($res["~POST_MESSAGE"], array(), $res["ALLOW"]); $arItems[$res["FORUM_ID"]]["TOPICS"][$res["TOPIC_ID"]]["MESSAGES"][$res["ID"]]["FILES_PARSED"] = $parser->arFilesIDParsed; $arFiles = $arItems[$res["FORUM_ID"]]["TOPICS"][$res["TOPIC_ID"]]["MESSAGES"][$res["ID"]]["FILES"]; foreach ($arFiles as $key => $val) { if (in_array($key, $arItems[$res["FORUM_ID"]]["TOPICS"][$res["TOPIC_ID"]]["MESSAGES"][$res["ID"]]["FILES_PARSED"])): unset ($arItems[$res["FORUM_ID"]]["TOPICS"][$res["TOPIC_ID"]]["MESSAGES"][$res["ID"]]["FILES"][$val["FILE_ID"]]); continue; endif; $val["HTML"] = $GLOBALS["APPLICATION"]->IncludeComponent( "bitrix:forum.interface", "show_file", Array( "FILE" => $val, "SHOW_MODE" => "RSS", "WIDTH" => $parser->image_params["width"], "HEIGHT" => $parser->image_params["height"], "CONVERT" => "N", "FAMILY" => "FORUM", "SINGLE" => "Y", "RETURN" => "Y"), null, array("HIDE_ICONS" => "Y")); $arItems[$res["FORUM_ID"]]["TOPICS"][$res["TOPIC_ID"]]["MESSAGES"][$res["ID"]]["FILES"][$val["FILE_ID"]]["HTML"] = $val["HTML"]; if ($arItems[$res["FORUM_ID"]]["TOPICS"][$res["TOPIC_ID"]]["MESSAGES"][$res["ID"]]["~ATTACH_IMG"] == $val["FILE_ID"]) // attach for custom { $arItems[$res["FORUM_ID"]]["TOPICS"][$res["TOPIC_ID"]]["MESSAGES"][$res["ID"]]["ATTACH_IMG"] = $val["HTML"]; $arItems[$res["FORUM_ID"]]["TOPICS"][$res["TOPIC_ID"]]["MESSAGES"][$res["ID"]]["~ATTACH_IMG"] = array_merge($val, array("ID" => $val["FILE_ID"])); } } } } /************** Message List/***************************************/ $arResult["DATA"] = $arItems; $arParams["TYPE"] = strToLower($arParams["TYPE"]); if ($arParams["DESIGN_MODE"] != "Y") { $this->IncludeComponentTemplate(); } else { ob_start(); $this->IncludeComponentTemplate(); $contents = ob_get_clean(); echo "<pre>",htmlspecialcharsbx($contents),"</pre>"; } } if ($arParams["DESIGN_MODE"] != "Y") die(); /******************************************************************** /Data 2 ********************************************************************/ ?>
49.751515
180
0.5885
b0ac85e0fa01cbadc612fb96cbc40f40d316c1ff
8,934
py
Python
sh_coding_challenge/sh_server/itertools_ext_lib.py
Plumbob/PythonDemos
fb008651ad72e5f07ded5da44a04ab996571fb4d
[ "Unlicense" ]
null
null
null
sh_coding_challenge/sh_server/itertools_ext_lib.py
Plumbob/PythonDemos
fb008651ad72e5f07ded5da44a04ab996571fb4d
[ "Unlicense" ]
null
null
null
sh_coding_challenge/sh_server/itertools_ext_lib.py
Plumbob/PythonDemos
fb008651ad72e5f07ded5da44a04ab996571fb4d
[ "Unlicense" ]
null
null
null
# Provides itertools-related functions not available in the Python3 intertools library # Requires Python3 import itertools def grouper(items, n): """ Collect data into fixed-length chunks or blocks. @param itr $items - List to be split into M N-length chunks If len('items') is not evenly divisible by 'n', the last chunk will be padded with 'fillvalue'. @param int $n - Desired length of each chunk/block returned @returns - A single tuple, composed of ceil(len(items)/n) sub-tuples Note: This function will return an empty tuple if 'items' is empty. Example usage: grouper([1,2,3,4,5,6,7], 3) --> ((1,2,3), (4,5,6), (7, None, None)) """ # Dev.Note: This function is adapted from the Python 3.3 itertools doc examples at: # https://docs.python.org/3.3/library/itertools.html#itertools.zip_longest args = [iter(items)] * n generator = itertools.zip_longest(*args, fillvalue=None) return tuple(generator) def div_mod(items, n): """ Equivalent of divmod(), but for lists. Spit list 'items' into M tuples of N items each. "Remainder" elements are returned in a second tuple. @param itr $items - List to be split into M N-length tuples. @param int $n - Desired length of each sub-tuple @returns - A two item tuple (quotient, remainder) The quotient contains M N-length tuples. The remainder contains the "remainder" items when len(items)/n is a non-integer value. Either or both tuples can be empty Example usage: grouper([1,2,3,4,5,6,7], 3) --> ((1,2,3), (4,5,6)), (7,) """ # Pre-process arguments to handle corner cases: if (not items) or (n == 0): quotient_tuple = () remainder_tuple = () return quotient_tuple, remainder_tuple # Split 'items' into M N-element tuples. If 'items' doesn't split evenly # into 'n' chunks, the last typle will be padded with None values groups = grouper(items, n) # Split result into "quotient" and "remainder" tuples. # The "quotient" tuple will contain M sub-tuples contain of N elements each. # The "remainder" typle will contain all "leftover" values, if any # Either or both tuples can be empty num_items = len(items) quotient, remainder = divmod(num_items, n) # No quotient values, just remainders if quotient == 0: quotient_tuple = () remainder_tuple = groups[0] # Even split, no remainders elif remainder == 0: quotient_tuple = groups remainder_tuple = () # Both quotients and remainders else: quotient_tuple = groups[:-1] remainder_tuple = groups[-1] # Remove any None entries from remainder tuple if remainder_tuple: remainder_tuple = tuple(filter(lambda x: x is not None, remainder_tuple)) return quotient_tuple, remainder_tuple if __name__ == '__main__': import math print("\n") print("Running self-tests") print("==================") print("\n") # ========================================================================== # Test grouper() # ========================================================================== print("Testing grouper()") print("-----------------") # # Given an empty list, verify grouper() will return an empty tuple # print("Verify grouper([],x) returns empty tuple...", end="") return_val = grouper([], 3) if return_val != (): print("\n") print("FAIL: returned %r" % (return_val,)) print("FAIL: expected: ()") else: print("PASS") # # Verify grouper splits into correct number of sub-tuples # test_list = [1,2,3,4,5,6,7] test_modulus = 3 expected_number_of_subtuples = math.ceil(len(test_list) / test_modulus) print("Verify grouper(%r, %d) returns correct number of sub-tuples..." % (test_list, test_modulus), end="") return_val = grouper(test_list, test_modulus) if len(return_val) != expected_number_of_subtuples: print("\n") print("FAIL: grouper(%r, %r) returned %r" % (test_list, test_modulus, return_val)) print("FAIL: expected %d sub-tuples, not %d" % (expected_number_of_subtuples, len(return_val))) else: print("PASS") # # Verify grouper doesn't re-arrange items in the original list # test_list = [1,2,3,4,5,6,7] test_modulus = 3 print("Verify grouper(%r, %d) does not rearrange items when splitting into " "sub-tuples..." % (test_list, test_modulus), end="") return_val = grouper(test_list, test_modulus) # Unsplit back into a single tuple unsplit_tuple = itertools.chain(*return_val) # Remove any Nones that might have been inserted by grouper() unsplit_list = list(filter(lambda x : x is not None, unsplit_tuple)) if unsplit_list != test_list: print("\n") print("FAIL: grouper(%r, %r) rearranged list items" % (test_list, test_modulus)) print("FAIL: received: %r" % unsplit_list) print("FAIL: expected: %r" % test_list) else: print("PASS") # ========================================================================== # Test div_mod() # ========================================================================== print("\n") print("Testing div_mod()") print("-----------------") # # Given an empty list, verify div_mod() will return two empty # tuples # print("Verify div_mod([],x) returns (), ()...", end="") quot, rem = div_mod([], 3) if not quot and not rem: print("PASS") else: print("\n") print("FAIL: returned %r" % (quotient, remainder)) print("FAIL: expected: (), ()") # # Verify div_mod when quotient is zero, remainder is non-zero # test_list = [1] test_modulus = 3 expected_quot = () expected_rem = (1,) print("Verify div_mod(%r, %d) returns %r, %r..." % (test_list, test_modulus, expected_quot, expected_rem), end="") quot, rem = div_mod(test_list, test_modulus) if ((quot != expected_quot) or (rem != expected_rem)): print("\n") print("FAIL: div_mod(%r, %r) returned %r, %r" % (test_list, test_modulus, quot, rem)) print("FAIL: expected %r %r" % (expected_quot, expected_rem)) else: print("PASS") # # Verify div_mod when quotient non-zero, remainder is zero # test_list = [1,2,3,4,5,6] test_modulus = 3 expected_quot = ((1,2,3),(4,5,6)) expected_rem = () print("Verify div_mod(%r, %d) returns %r, %r..." % (test_list, test_modulus, expected_quot, expected_rem), end="") quot, rem = div_mod(test_list, test_modulus) if ((quot != expected_quot) or (rem != expected_rem)): print("\n") print("FAIL: div_mod(%r, %r) returned %r, %r" % (test_list, test_modulus, quot, rem)) print("FAIL: expected %r %r" % (expected_quot, expected_rem)) else: print("PASS") # # Verify div_mod when both quotient and remainder are non-zero # test_list = [1,2,3,4,5,6,7] test_modulus = 3 expected_quot = ((1,2,3),(4,5,6)) expected_rem = (7,) print("Verify div_mod(%r, %d) returns %r, %r..." % (test_list, test_modulus, expected_quot, expected_rem), end="") quot, rem = div_mod(test_list, test_modulus) if ((quot != expected_quot) or (rem != expected_rem)): print("\n") print("FAIL: div_mod(%r, %r) returned %r, %r" % (test_list, test_modulus, quot, rem)) print("FAIL: expected %r %r" % (expected_quot, expected_rem)) else: print("PASS") # # Verify grouper doesn't re-arrange items in the original list # # # test_list = [1,2,3,4,5,6,7] # test_modulus = 3 # # print("Testing grouper(%r, %d) does not rearrange items when splitting into " # "sub-lists..." % (test_list, test_modulus), end="") # # return_val = grouper(test_list, test_modulus) # # # Unsplit back into a single list # unsplit_list = itertools.chain(*return_val) # # # Remove any Nones that might have been inserted by grouper() # unsplit_list = list(filter(lambda x : x is not None, unsplit_list)) # # if unsplit_list != test_list: # print("\n") # print("FAIL: grouper(%r, %r) rearranged list items" % (test_list, test_modulus)) # print("FAIL: received: %r" % unsplit_list) # print("FAIL: expected: %r" % test_list) # # else: # print("PASS")
28.912621
90
0.563465
0da1dfd97186dcaaaadd5feb64b4b378ed18d637
1,391
cs
C#
samples/ri/Storage.IntegrationTests/LocalMachineFileRepositorySpec .cs
jezzsantos/queryany
1c5baf79f13fe4d6719bb1565f1189275dcfe6e2
[ "Apache-2.0" ]
1
2020-06-29T04:30:45.000Z
2020-06-29T04:30:45.000Z
samples/ri/Storage.IntegrationTests/LocalMachineFileRepositorySpec .cs
jezzsantos/queryany
1c5baf79f13fe4d6719bb1565f1189275dcfe6e2
[ "Apache-2.0" ]
9
2020-07-19T20:03:00.000Z
2021-05-15T22:52:08.000Z
samples/ri/Storage.IntegrationTests/LocalMachineFileRepositorySpec .cs
jezzsantos/queryany
1c5baf79f13fe4d6719bb1565f1189275dcfe6e2
[ "Apache-2.0" ]
null
null
null
using System; using Microsoft.Extensions.Configuration; using ServiceStack; using Xunit; namespace Storage.IntegrationTests { public class LocalMachineFileRepositorySpecSetup : IDisposable { public LocalMachineFileRepositorySpecSetup() { var config = new ConfigurationBuilder().AddJsonFile(@"appsettings.json").Build(); var settings = new NetCoreAppSettings(config); Repository = LocalMachineFileRepository.FromSettings(settings); Blobository = LocalMachineFileRepository.FromSettings(settings); } public IRepository Repository { get; } public IBlobository Blobository { get; } public void Dispose() { } } [Trait("Category", "Integration.Storage")] public class LocalMachineFileRepositorySpec : AnyRepositoryBaseSpec, IClassFixture<LocalMachineFileRepositorySpecSetup> { public LocalMachineFileRepositorySpec(LocalMachineFileRepositorySpecSetup setup) : base(setup.Repository) { } } [Trait("Category", "Integration.Storage")] public class LocalMachineFileBlobositorySpec : AnyBlobositoryBaseSpec, IClassFixture<LocalMachineFileRepositorySpecSetup> { public LocalMachineFileBlobositorySpec(LocalMachineFileRepositorySpecSetup setup) : base(setup.Blobository) { } } }
31.613636
115
0.700216
98b821323d0bd2fc5c5dad64dbba3cbda5b99511
9,151
kt
Kotlin
src/test/kotlin/net/lfn3/leth/LogTest.kt
lfn3/leth
4c123098b1fccea9e3cea7220ea449df94a5703b
[ "Apache-2.0" ]
null
null
null
src/test/kotlin/net/lfn3/leth/LogTest.kt
lfn3/leth
4c123098b1fccea9e3cea7220ea449df94a5703b
[ "Apache-2.0" ]
null
null
null
src/test/kotlin/net/lfn3/leth/LogTest.kt
lfn3/leth
4c123098b1fccea9e3cea7220ea449df94a5703b
[ "Apache-2.0" ]
null
null
null
package net.lfn3.leth import net.lfn3.leth.unsafe.InMemoryPartitionedLog import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Nested import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicLong import java.util.stream.Collectors import java.util.stream.IntStream import java.util.stream.LongStream import kotlin.test.* abstract class LogTest(private val ctor: () -> Log<Pair<Long, Long>>) { @Test fun `The log returns a single recorded entry`() { val log = ctor.invoke() val entry = Pair(6L, 7L) val seq = log.record(entry) val (queriedSeq, queriedVal) = log.headWithSeq()!! assertEquals(entry, queriedVal) assertEquals(seq, queriedSeq) assertEquals(1, log.size) } @Test fun `Can iterate everything added to a log`() { val log = ctor.invoke() val first = Pair(6L, 7L) val second = Pair(7L, 7L) val third = Pair(9L, 7L) log.batchRecord(arrayListOf(first, second, third)) assertEquals(3, log.size) val iter = log.iterator() assertEquals(first, iter.next()) assertEquals(second, iter.next()) assertEquals(third, iter.next()) } @Test fun `Iterator should not see newly added items`() { val log = ctor.invoke() val first = Pair(6L, 7L) log.record(first) val iter = log.iterator() assertEquals(first, iter.next()) log.record(Pair(6L, 7L)) assertFalse(iter.hasNext()) } @Test fun `Should be able to partition log`() { val log = ctor.invoke() val first: Pair<Long, Long> = Pair(1, 2) log.record(first) val indexed = InMemoryPartitionedLog(log) { it.first } assertEquals(first, indexed.head(1)) } @Test fun `Should see new entries in partitioned log`() { val log = ctor.invoke() val indexed = InMemoryPartitionedLog(log) { it.first } val entry: Pair<Long, Long> = Pair(5, 6) log.record(entry) assertEquals(entry, log.head()) assertEquals(entry, indexed.head(5)) } @Test fun `Can map over log`() { val log = ctor.invoke() val mapped = LogReader.map(log) { it.first + it.second } val counter = AtomicLong() assertNull(mapped.head()) log.record(Pair(3, 4)) mapped.tail { counter.addAndGet(it) } assertEquals(7, counter.get()) assertEquals(7, mapped.head()) log.record(Pair(2, 1)) assertEquals(10, counter.get()) assertEquals(3, mapped.head()) } @Nested inner class Batch { @Test fun `Should be able to batch insert`() { val log = ctor.invoke() val toInsert: Collection<Pair<Long, Long>> = LongStream.range(1, 100).mapToObj { Pair(1.toLong(), it) }.collect(Collectors.toList()) log.batchRecord(toInsert) val iter = toInsert.iterator() log.tail { assertEquals(iter.next(), it) } } @Test fun `Batch insert should fire observers`() { val log = ctor.invoke() val counter = AtomicInteger(0) val toInsert = 100 val entries = IntStream.range(0, toInsert).mapToObj { Pair(1.toLong(), it.toLong()) }.collect(Collectors.toSet()) log.tail { counter.incrementAndGet() assert(entries.contains(it)) } log.batchRecord(entries) assertEquals(toInsert, counter.get()) } } @Nested inner class Tailing { @Test fun `Can tail log`() { val log = ctor.invoke() val counter = AtomicInteger(0) log.tail { counter.incrementAndGet() } log.record(Pair(5L, 12L)) assertEquals(1, counter.get()) } @Test fun `Should see updates in tail`() { val log = ctor.invoke() val counter = AtomicInteger(0) log.tail { counter.incrementAndGet() } val entry = Pair(12L, 3L) val seq = log.record(entry) assertEquals(1, counter.get()) log.update({ seq }, { Pair(it.first, it.second + 1) }) assertEquals(2, counter.get()) } @Test fun `Should see existing values in tail`() { val log = ctor.invoke() val counter = AtomicInteger(0) log.record(Pair(5L, 12L)) log.tail { counter.incrementAndGet() } log.record(Pair(5L, 13L)) assertEquals(2, counter.get()) } @Test fun `Can tail from a position in the log`() { val log = ctor.invoke() val counter = AtomicInteger(0) log.record(Pair(5L, 12L)) val seq2 = log.record(Pair(5L, 12L)) log.tail(seq2) { counter.incrementAndGet() } log.record(Pair(5L, 12L)) assertEquals(2, counter.get()) } @Test fun `Can tail only updates using seq + 1`() { val log = ctor.invoke() val counter = AtomicInteger(0) val entry = Pair(12L, 3L) val seq = log.record(entry) log.tail(seq + 1) { counter.incrementAndGet() } assertEquals(0, counter.get()) log.update({ seq }, { Pair(it.first, it.second + 1) }) assertEquals(1, counter.get()) } @Test fun `Observer that throws should not effect other observers`() { val log = ctor.invoke() val counter = AtomicInteger(0) log.tail { throw IllegalStateException() } log.tail { counter.incrementAndGet() } log.record(Pair(5L, 12L)) assertEquals(1, counter.get()) } @Test fun `Observer that throws should not effect other observers when batch inserting`() { val log = ctor.invoke() val counter = AtomicInteger(0) val toInsert = 100 val entries = IntStream.range(0, toInsert).mapToObj { Pair(1.toLong(), it.toLong()) }.collect(Collectors.toSet()) log.tail { throw IllegalStateException() } log.tail { counter.incrementAndGet() } log.batchRecord(entries) assertEquals(toInsert, counter.get()) } } @Nested inner class Updates { @Test fun `The log allows updates`() { val log = ctor.invoke() val entry = Pair(12L, 3L) val seq = log.record(entry) log.update({ seq }, { Pair(it.first, it.second + 1) }) val updatedEntry = Pair(12L, 4L) assertEquals(updatedEntry, log.head()) assertEquals(2, log.size) val iter = log.iterator() assertEquals(entry, iter.next()) assertEquals(updatedEntry, iter.next()) assertFalse(iter.hasNext()) } @Test fun `The log should throw on updates for unknown sequences`() { val log = ctor.invoke() val entry = Pair(12L, 3L) val seq = log.record(entry) //Should fail since we don't have this sequence, yet. assertThrows(Exception::class.java) { log.update({ seq + 1 }, { Pair(it.first, it.second + 1) }) } assertEquals(1, log.size) assertEquals(entry, log.get(seq)) } @Test fun `Log should ignore updates to same value`() { val log = ctor.invoke() val entry = Pair(12L, 3L) val seq = log.record(entry) log.tail(seq + 1) { fail("Should not have written back identical value") } log.update({ seq }, { Pair(it.first, it.second) }) assertEquals(1, log.size) } @Test fun `Should only apply a single conflicting update`() { val log = ctor.invoke() val seq = log.record(Pair(5, 1)) log.update({ seq }, { Pair(it.first, it.second + 1) }) assertThrows(java.lang.Exception::class.java, { log.update({ seq }, { Pair(it.first, it.second + 1) }) }) assertEquals(2, log.head()!!.second) } @Test fun `Should only retry updates 5 times`() { val log = ctor.invoke() val counter = AtomicLong(0) log.record(Pair(0, 0)) LongStream.range(0, 6).forEach { log.update({ log.headWithSeq()!!.first }, { Pair(it.first, it.second + 1) }) } assertThrows(java.lang.Exception::class.java) { log.update({ val nextSeq = counter.incrementAndGet() if (5 < nextSeq) { fail("More than 5 attempts to get sequence") } nextSeq }, { Pair(it.first, it.second + 1) }) } assertEquals(5, counter.get()) } } }
27.89939
117
0.535242
ca998185591068122e57601d0d09395b33fb4903
747
cs
C#
Assets/UnityExtensions.DependencyInjection/InstantiationInjector.cs
KuraiAndras/UnityExtensions.DependencyInjection
d25099adb1076c8b5680b294aa07e04e2be83432
[ "MIT" ]
5
2020-03-31T12:26:29.000Z
2020-03-31T16:37:16.000Z
Assets/UnityExtensions.DependencyInjection/InstantiationInjector.cs
KuraiAndras/UnityExtensions.DependencyInjection
d25099adb1076c8b5680b294aa07e04e2be83432
[ "MIT" ]
3
2020-04-01T08:20:51.000Z
2020-04-02T19:30:56.000Z
Assets/UnityExtensions.DependencyInjection/InstantiationInjector.cs
KuraiAndras/UnityExtensions.DependencyInjection
d25099adb1076c8b5680b294aa07e04e2be83432
[ "MIT" ]
null
null
null
using Injecter; using Microsoft.Extensions.DependencyInjection; using System; using Object = UnityEngine.Object; namespace UnityExtensions.DependencyInjection { public static class InstantiationInjector { public static IServiceCollection AddInjectorServices(this IServiceCollection services, Action<InjecterOptions> optionsBuilder = null) { if (services is null) throw new ArgumentNullException(nameof(services)); services.AddSingleton<IGameObjectFactory, DefaultGameObjectFactory>(); services.AddSingleton<ISceneInjector, SceneInjector>(_ => Object.FindObjectOfType<SceneInjector>()); services.AddInjecter(optionsBuilder); return services; } } }
33.954545
141
0.729585
24c05297b2ed9046caf888c8f404abe4aa9bebeb
260
php
PHP
application/helpers/new_helper.php
Abdullah1404111/cicrud
a189094307088ef5a12349b33c89e88a55853f9d
[ "MIT" ]
null
null
null
application/helpers/new_helper.php
Abdullah1404111/cicrud
a189094307088ef5a12349b33c89e88a55853f9d
[ "MIT" ]
null
null
null
application/helpers/new_helper.php
Abdullah1404111/cicrud
a189094307088ef5a12349b33c89e88a55853f9d
[ "MIT" ]
null
null
null
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); if ( ! function_exists('standard_time')){ function standard_time($time){ $dateTime = gmdate("F d, Y - H:i", strtotime($time)); return $dateTime; } }
26
74
0.584615
df0a041e214cfb200eaae6816756ee6e948bf74f
1,039
cs
C#
1. Base/Workflow.Basic.Presentation/BasicModel/SessionUser.cs
kamilRepo/Workflow-App-Based-On-DDD
42dd8a507795af794c9e752416931fb30347f2e0
[ "MIT" ]
null
null
null
1. Base/Workflow.Basic.Presentation/BasicModel/SessionUser.cs
kamilRepo/Workflow-App-Based-On-DDD
42dd8a507795af794c9e752416931fb30347f2e0
[ "MIT" ]
null
null
null
1. Base/Workflow.Basic.Presentation/BasicModel/SessionUser.cs
kamilRepo/Workflow-App-Based-On-DDD
42dd8a507795af794c9e752416931fb30347f2e0
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Workflow.Basic.Presentation.BasicModels { [Serializable] public class SessionUser { public int Id { get; private set; } public string Name { get; private set; } public string Surname { get; private set; } public string Email { get; private set; } public bool All { get; set; } public bool AuthorizedPersons { get; set; } public bool EditingCapabilities { get; set; } public bool OwnData { get; set; } public SessionUser(int id, string name, string surname, string email, bool all, bool authorizedPersons, bool editingCapabilities, bool ownData) { Id = id; Name = name; Surname = surname; Email = email; All = all; AuthorizedPersons = authorizedPersons; EditingCapabilities = editingCapabilities; OwnData = ownData; } } }
24.738095
87
0.595765
28777b5d4dd9f28e1ac724598fec0fa4820a5f57
5,832
swift
Swift
AtalasDream/ShowTipController.swift
DarmBeene/GuoAltas
456d6cabb5d75a256a5a4905a80897e6cf16f1c7
[ "MIT" ]
null
null
null
AtalasDream/ShowTipController.swift
DarmBeene/GuoAltas
456d6cabb5d75a256a5a4905a80897e6cf16f1c7
[ "MIT" ]
null
null
null
AtalasDream/ShowTipController.swift
DarmBeene/GuoAltas
456d6cabb5d75a256a5a4905a80897e6cf16f1c7
[ "MIT" ]
null
null
null
// // ShowTipController.swift // AtalasDream // // Created by GuoGongbin on 7/8/17. // Copyright © 2017 GuoGongbin. All rights reserved. // import UIKit private let cellId = "cellId" class ShowTipController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UITabBarDelegate { var course: Course? let toolBarHeight: CGFloat = 49 lazy var toolBar: UIToolbar = { let toolbar = UIToolbar() toolbar.translatesAutoresizingMaskIntoConstraints = false return toolbar }() lazy var favoriteButton: UIButton = { let button = UIButton(type: .system) button.setTitle("收藏", for: .normal) button.setImage(UIImage(named: "favorite")?.withRenderingMode(.alwaysOriginal), for: .normal) button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10) return button }() lazy var commentButton: UIButton = { let button = UIButton(type: .system) button.setTitle("评论", for: .normal) button.setImage(UIImage(named: "comments_icon")?.withRenderingMode(.alwaysOriginal), for: .normal) button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10) return button }() override func viewDidLoad() { super.viewDidLoad() setupViews() setupRightBarButton() } func setupViews() { navigationItem.title = course?.name self.collectionView?.register(TipCell.self, forCellWithReuseIdentifier: cellId) collectionView?.alwaysBounceVertical = true collectionView?.backgroundColor = UIColor.white setupToolBar() } func setupRightBarButton() { } func setupToolBar() { self.view.insertSubview(toolBar, aboveSubview: self.collectionView!) toolBar.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true toolBar.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true toolBar.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor).isActive = true toolBar.heightAnchor.constraint(equalToConstant: toolBarHeight).isActive = true let width = self.view.frame.width / 2 - 20 let favoriteView = UIView() favoriteView.frame = CGRect(x: 0, y: 0, width: width, height: toolBarHeight) favoriteButton.frame = CGRect(x: 0, y: 0, width: 120, height: 35) favoriteView.addSubview(favoriteButton) favoriteButton.center = favoriteView.center let commentView = UIView() commentView.frame = CGRect(x: 0, y: 0, width: width, height: toolBarHeight) commentButton.frame = CGRect(x: 0, y: 0, width: 120, height: 35) commentView.addSubview(commentButton) commentButton.center = commentView.center favoriteButton.addTarget(self, action: #selector(handleFavorite), for: .touchUpInside) commentButton.addTarget(self, action: #selector(handleComment), for: .touchUpInside) let item1 = UIBarButtonItem(customView: favoriteView) let item2 = UIBarButtonItem(customView: commentView) toolBar.items = [item1, item2] } func handleFavorite() { guard let uid = FIRAuth.auth()?.currentUser?.uid, let coursekey = course?.courseKey, let university = course?.university, let department = course?.department else { self.showAlertPrompt(message: "请先登录,登陆后方可收藏") return } let ref = FirDatabasePath.UserReference.child(uid).child(SettingsConstants.favoriteCourseTip) let values = [coursekey: [university, department]] ref.updateChildValues(values) { (error, reference) in if let error = error { self.showAlertPrompt(message: error.localizedDescription) return } self.view.prompt(message: "收藏成功") } } func handleComment() { let vc = TipCommentController(collectionViewLayout: UICollectionViewFlowLayout()) vc.courseKey = course?.courseKey navigationController?.pushViewController(vc, animated: true) } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! TipCell cell.course = course if let content = course?.courseDescription { let height = estimatedHeight(text: content) cell.contentHeightAnchor?.isActive = false cell.contentHeightAnchor?.constant = height cell.contentHeightAnchor?.isActive = true } return cell } // helper method func estimatedHeight(text: String) -> CGFloat { let width = self.view.frame.width - 40 let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 16)] let height = text.height(withWidth: width, attributes: attributes) return height + 20 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if let content = course?.courseDescription { let height = estimatedHeight(text: content) return CGSize(width: self.view.frame.width, height: 95 + height + toolBarHeight + 5) } return CGSize(width: self.view.frame.width, height: 95 + 10) } }
39.14094
160
0.655178
fa7dba3908b35bf14a87cfe638101b39a1dd2dce
6,743
cpp
C++
src/make_detect.cpp
cschreib/qdeblend
dceee75f3ff475995dbbb8660a6665ece205494f
[ "MIT" ]
null
null
null
src/make_detect.cpp
cschreib/qdeblend
dceee75f3ff475995dbbb8660a6665ece205494f
[ "MIT" ]
null
null
null
src/make_detect.cpp
cschreib/qdeblend
dceee75f3ff475995dbbb8660a6665ece205494f
[ "MIT" ]
null
null
null
#include <vif.hpp> #include <vif/astro/ds9.hpp> using namespace vif; using namespace vif::astro; int vif_main(int argc, char* argv[]) { vec1s files = {"acs-f435w", "acs-f606w", "acs-f775w", "acs-f814w", "acs-f850lp", "wfc3-f105w", "wfc3-f125w", "wfc3-f140w", "wfc3-f160w"}; files += ".fits"; std::string flux_image = "wfc3-f160w.fits"; double deblend_threshold = 0.4; double detect_threshold = 1.0; double conv_fwhm = 0.2; double min_snr = 10.0; uint_t min_area = 10; read_args(argc, argv, arg_list(files, flux_image, deblend_threshold, detect_threshold, conv_fwhm, min_area, min_snr )); vec3f imgs; vec1f rms; double stack_rms = 0; vec2f stack; vec2f wstack; fits::header ghdr; double aspix = 0.06; for (std::string& f : files) { if (!file::exists(f)) continue; vec2d img; fits::header hdr; fits::read(f, img, hdr); astro::wcs w(hdr); if (ghdr.empty()) ghdr = hdr; // From DS9 region files std::string base = file::remove_extension(f); std::string bad_file = base+"-bad.reg"; if (!file::exists(bad_file)) { bad_file = base+"_bad.reg"; } if (!file::exists(bad_file)) { bad_file = ""; } if (!bad_file.empty()) { vec2b bad_mask(img.dims); ds9::mask_regions(bad_file, w, bad_mask); img[where(bad_mask)] = dnan; } if (fraction_of(is_finite(img) || abs(img) > 0) < 0.6) continue; rms.push_back(1.48*mad(img)); vec2d wei = replicate(1.0/sqr(rms.back()), img.dims); vec1u idb = where(!is_finite(img)); img[idb] = 0; wei[idb] = 0; if (stack.empty()) { stack = img*wei; wstack = wei; } else { stack += img*wei; wstack += wei; } stack_rms += sqr(rms.back()/sqr(rms.back())); append<0>(imgs, reform(img/rms.back(), 1, img.dims)); } astro::wcs gw(ghdr); double tw = total(1/sqr(rms)); stack_rms = sqrt(stack_rms)/tw; stack /= wstack; fits::write("det_stack.fits", stack, ghdr); append<0>(imgs, reform(stack/stack_rms, 1, stack.dims)); // Build detection image vec2f det = partial_max(0, imgs); double conv = conv_fwhm/aspix/2.335; { vec1u idb = where(!is_finite(det)); det[idb] = 0; uint_t hpix = 5*conv; vec2d kernel = gaussian_profile({{2*hpix+1, 2*hpix+1}}, conv, hpix, hpix); det = convolve2d(det, kernel); det[idb] = fnan; } fits::write("det_snr.fits", det, ghdr); // Perform segmentation segment_deblend_params sdp; sdp.detect_threshold = detect_threshold + median(det); sdp.deblend_threshold = deblend_threshold/aspix; sdp.min_area = min_area; segment_deblend_output segments; vec2u seg = segment_deblend(det, segments, sdp); // Read fluxes on image vec2d himg; fits::read(flux_image, himg); vec1u idbg = where(seg == 0); himg -= median(himg[idbg]); double hrms = 1.48*mad(himg[idbg]); vec1f hflx(segments.id.size()); vec1f hflx_err(segments.id.size()); foreach_segment(seg, segments.origin, [&](uint_t s, vec1u ids) { hflx[s] = total(himg[ids]); hflx_err[s] = sqrt(ids.size())*hrms; }); // Remove too low S/N objects. vec1u idls = where(hflx/hflx_err < min_snr); foreach_segment(seg, segments.origin[idls], [&](uint_t s, vec1u ids) { seg[ids] = 0; }); inplace_remove(segments.id, idls); inplace_remove(segments.area, idls); inplace_remove(segments.px, idls); inplace_remove(segments.py, idls); inplace_remove(hflx, idls); inplace_remove(hflx_err, idls); // Merge segments (if any). std::string manual_file = "merged_segments.reg"; if (file::exists(manual_file)) { vec<1,ds9::region> reg; ds9::read_regions_physical(manual_file, gw, reg); for (uint_t i : range(reg)) { vec2b mask(seg.dims); ds9::mask_region(reg[i], mask); vec1u idm = where(mask); vec1u idu = unique_values(seg[idm]); idu = idu[where(idu != 0)]; if (idu.size() > 1) { print("merged ", idu.size(), " segments"); for (uint_t u : range(1, idu.size())) { vec1u ids = where(seg == idu[u]); seg[ids] = idu[0]; idu[u] = where_first(segments.id == idu[u]); } uint_t im = where_first(segments.id == idu[0]); idu[0] = im; segments.px[im] = total(segments.px[idu]*segments.area[idu])/total(segments.area[idu]); segments.py[im] = total(segments.py[idu]*segments.area[idu])/total(segments.area[idu]); segments.area[im] = total(segments.area[idu]); hflx[im] = total(hflx[idu]); hflx_err[im] = sqrt(total(sqr(hflx_err[idu]))); idu = idu[1-_]; inplace_remove(segments.id, idu); inplace_remove(segments.px, idu); inplace_remove(segments.py, idu); inplace_remove(segments.area, idu); inplace_remove(hflx, idu); inplace_remove(hflx_err, idu); } } } // Add manual detections (if any). manual_file = "det_manual.reg"; if (file::exists(manual_file)) { vec<1,ds9::region> reg; ds9::read_regions_physical(manual_file, gw, reg); vec1s sid(reg.size()); for (uint_t i : range(reg)) sid[i] = reg[i].text; vec1s uid = unique_values(sid); for (std::string s : uid) { vec1u idl = where(sid == s); vec2b mask(seg.dims); for (uint_t i : idl) { ds9::mask_region(reg[i], mask); } vec1u ids = where(mask); uint_t seg_id = max(segments.id)+1; seg[ids] = seg_id; segments.id.push_back(seg_id); segments.px.push_back(reg[idl[0]].params[0]); segments.py.push_back(reg[idl[0]].params[1]); segments.area.push_back(ids.size()); hflx.push_back(total(himg[ids])); hflx_err.push_back(sqrt(ids.size())*hrms); } } fits::write("det_seg.fits", seg, ghdr); vec1d ra, dec; astro::xy2ad(gw, segments.px+1, segments.py+1, ra, dec); fits::write_table("det_cat.fits", "id", segments.id, "area", segments.area, "x", segments.px, "y", segments.py, "ra", ra, "dec", dec, "flux", hflx, "flux_err", hflx_err ); return 0; }
30.102679
103
0.547976
7b0b6f6dde03cc77373bfd8ca76a96a50bcf619c
890
lua
Lua
server/server.lua
Guccirp2/Redline-Fuel
208afcaa6d9f36f9aed0d6b667615a2616d09d09
[ "MIT" ]
null
null
null
server/server.lua
Guccirp2/Redline-Fuel
208afcaa6d9f36f9aed0d6b667615a2616d09d09
[ "MIT" ]
null
null
null
server/server.lua
Guccirp2/Redline-Fuel
208afcaa6d9f36f9aed0d6b667615a2616d09d09
[ "MIT" ]
null
null
null
ESX = nil TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) ESX.RegisterServerCallback('gucci:cmoney', function(source, callback) local xPlayer = ESX.GetPlayerFromID(source) local money = xPlayer.getInventoryItem('money').count if money >= 60 then callback(true) else callback(false) end end) RegisterServerEvent('gucci:tmoney') AddEventHandler('gucci:tmoney', function() local xPlayer = ESX.GetPlayerFromID(source) xPlayer.removeInventoryItem('money', 60) end) ESX.RegisterServerCallback('gucci:cjerrymoney', function(source, callback) local xPlayer = ESX.GetPlayerFromId(source) local money = xPlayer.getInventoryItem('money').count if money >= 60 then callback(true) xPlayer.addInventoryitem('WEAPON_PETROLCAN', 1) else callback(false) end end)
27.8125
75
0.682022
daaa983bb22e95f07ca68466de91f2bcb35d5b66
19,029
php
PHP
http-api-page/src/ModuleConfigZrcms.php
reliv/rcms
b4f6b993e4e1ece730ffea6329de872706e6007f
[ "0BSD" ]
null
null
null
http-api-page/src/ModuleConfigZrcms.php
reliv/rcms
b4f6b993e4e1ece730ffea6329de872706e6007f
[ "0BSD" ]
null
null
null
http-api-page/src/ModuleConfigZrcms.php
reliv/rcms
b4f6b993e4e1ece730ffea6329de872706e6007f
[ "0BSD" ]
3
2017-09-28T22:15:19.000Z
2018-06-27T23:00:00.000Z
<?php namespace Zrcms\HttpApiPage; use Zrcms\Acl\Api\IsAllowedRcmUserSitesAdmin; use Zrcms\Core\Api\CmsResource\CmsResourcesToArray; use Zrcms\Core\Api\CmsResource\CmsResourceToArray; use Zrcms\Core\Api\Content\ContentVersionsToArray; use Zrcms\Core\Api\Content\ContentVersionToArray; use Zrcms\CorePage\Api\CmsResource\CreatePageDraftCmsResource; use Zrcms\CorePage\Api\CmsResource\FindPageCmsResource; use Zrcms\CorePage\Api\CmsResource\FindPageCmsResourcesBy; use Zrcms\CorePage\Api\CmsResource\FindPageCmsResourcesPublished; use Zrcms\CorePage\Api\CmsResource\FindPageDraftCmsResource; use Zrcms\CorePage\Api\CmsResource\FindPageDraftCmsResourcesBy; use Zrcms\CorePage\Api\CmsResource\FindPageTemplateCmsResource; use Zrcms\CorePage\Api\CmsResource\FindPageTemplateCmsResourcesBy; use Zrcms\CorePage\Api\CmsResource\UpdatePageCmsResource; use Zrcms\CorePage\Api\CmsResource\UpdatePageDraftCmsResource; use Zrcms\CorePage\Api\CmsResource\UpdatePageTemplateCmsResource; use Zrcms\CorePage\Api\CmsResourceHistory\FindPageCmsResourceHistory; use Zrcms\CorePage\Api\CmsResourceHistory\FindPageCmsResourceHistoryBy; use Zrcms\CorePage\Api\Content\FindPageVersion; use Zrcms\CorePage\Api\Content\FindPageVersionsBy; use Zrcms\CorePage\Api\Content\InsertPageVersion; use Zrcms\CorePage\Fields\FieldsPageVersion; use Zrcms\ValidationRatZrcms\Api\FieldValidator\ValidateFieldsCreateCmsResourceData; use Zrcms\ValidationRatZrcms\Api\FieldValidator\ValidateFieldsInsertContentVersionData; use Zrcms\ValidationRatZrcms\Api\FieldValidator\ValidateFieldsUpdateCmsResourceData; /** * @author James Jervis - https://github.com/jerv13 */ class ModuleConfigZrcms { public function __invoke() { return [ /** * ===== ZRCMS HTTP API by request ===== */ 'zrcms-http-api-dynamic' => [ 'page' => [ /** * CmsResource */ 'find-cms-resource' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageCmsResource::class, 'to-array' => CmsResourceToArray::class, 'not-found-status' => 404, ], ], 'find-cms-resources-by' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageCmsResourcesBy::class, 'to-array' => CmsResourcesToArray::class, 'not-found-status' => 404, ], ], 'find-cms-resources-published' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageCmsResourcesPublished::class, 'to-array' => CmsResourcesToArray::class, 'not-found-status' => 404, ], ], 'update-cms-resource' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'fields-validator' => [ 'fields-validator' => ValidateFieldsUpdateCmsResourceData::class, 'fields-validator-options' => [ 'validator-options-content-version-id' => [ 'api-service-find-content-version' => FindPageVersion::class, ], ], 'not-valid-status' => 400, ], 'api' => [ 'api-service-find-content-version' => FindPageVersion::class, 'api-service' => UpdatePageCmsResource::class, 'to-array' => CmsResourceToArray::class, 'not-found-status' => 404, ], ], /** * CmsResourceHistory */ 'find-cms-resource-history' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageCmsResourceHistory::class, 'to-array' => CmsResourceToArray::class, 'not-found-status' => 404, ], ], 'find-cms-resource-histories-by' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageCmsResourceHistoryBy::class, 'to-array' => CmsResourcesToArray::class, 'not-found-status' => 404, ], ], /** * ContentVersion */ 'find-content-version' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageVersion::class, 'to-array' => ContentVersionToArray::class, 'not-found-status' => 404, ], ], 'find-content-versions-by' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageVersionsBy::class, 'to-array' => ContentVersionsToArray::class, 'not-found-status' => 404, ], ], 'insert-content-version' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'fields-validator' => [ 'fields-validator' => ValidateFieldsInsertContentVersionData::class, 'fields-validator-options' => [ 'fields-validator-options-properties' => [ 'fields-model-name' => FieldsPageVersion::FIELD_MODEL_NAME ], ], 'not-valid-status' => 400, ], 'api' => [ 'api-service' => InsertPageVersion::class, 'to-array' => ContentVersionToArray::class, 'not-found-status' => 404, ], ], ], 'page-draft' => [ /** * CmsResource */ 'create-cms-resource' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'fields-validator' => [ 'fields-validator' => ValidateFieldsCreateCmsResourceData::class, 'fields-validator-options' => [ 'validator-options-content-version-id' => [ 'api-service-find-content-version' => FindPageVersion::class, ], ], 'not-valid-status' => 400, ], 'api' => [ 'api-service' => CreatePageDraftCmsResource::class, 'to-array' => CmsResourceToArray::class, ], ], 'find-cms-resource' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageDraftCmsResource::class, 'to-array' => CmsResourceToArray::class, 'not-found-status' => 404, ], ], 'find-cms-resources-by' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageDraftCmsResourcesBy::class, 'to-array' => CmsResourcesToArray::class, 'not-found-status' => 404, ], ], /* @todo NOT IMPLEMENTED * 'find-cms-resources-published' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageCmsResourcesPublished::class, 'to-array' => CmsResourcesToArray::class, 'not-found-status' => 404, ], ], /* */ 'update-cms-resource' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'fields-validator' => [ 'fields-validator' => ValidateFieldsUpdateCmsResourceData::class, 'fields-validator-options' => [ 'validator-options-content-version-id' => [ 'api-service-find-content-version' => FindPageVersion::class, ], ], 'not-valid-status' => 400, ], 'api' => [ 'api-service-find-content-version' => FindPageVersion::class, 'api-service' => UpdatePageDraftCmsResource::class, 'to-array' => CmsResourceToArray::class, 'not-found-status' => 404, ], ], /** * CmsResourceHistory */ /* @todo NOT IMPLEMENTED * 'find-cms-resource-history' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageDraftCmsResourceHistory::class, 'to-array' => CmsResourceToArray::class, 'not-found-status' => 404, ], ], /* */ /* @todo NOT IMPLEMENTED * 'find-cms-resource-histories-by' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageDraftCmsResourceHistoryBy::class, 'to-array' => CmsResourcesToArray::class, 'not-found-status' => 404, ], ], * /* */ /* NOTE: we can use the PageVersion APIs for versions as they are shared */ ], 'page-template' => [ /** * CmsResource */ 'find-cms-resource' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageTemplateCmsResource::class, 'to-array' => CmsResourceToArray::class, 'not-found-status' => 404, ], ], 'find-cms-resources-by' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageTemplateCmsResourcesBy::class, 'to-array' => CmsResourcesToArray::class, 'not-found-status' => 404, ], ], /* @todo NOT IMPLEMENTED * 'find-cms-resources-published' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageTemplateCmsResourcesPublished::class, 'to-array' => CmsResourcesToArray::class, 'not-found-status' => 404, ], ], /* */ 'update-cms-resource' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'fields-validator' => [ 'fields-validator' => ValidateFieldsUpdateCmsResourceData::class, 'fields-validator-options' => [ 'validator-options-content-version-id' => [ 'api-service-find-content-version' => FindPageVersion::class, ], ], 'not-valid-status' => 400, ], 'api' => [ 'api-service-find-content-version' => FindPageVersion::class, 'api-service' => UpdatePageTemplateCmsResource::class, 'to-array' => CmsResourceToArray::class, 'not-found-status' => 404, ], ], /** * CmsResourceHistory */ /* @todo NOT IMPLEMENTED * 'find-cms-resource-history' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageTemplateCmsResourceHistory::class, 'to-array' => CmsResourceToArray::class, 'not-found-status' => 404, ], ], /* */ /* @todo NOT IMPLEMENTED * 'find-cms-resource-histories-by' => [ 'acl' => [ 'is-allowed' => IsAllowedRcmUserSitesAdmin::class, 'is-allowed-options' => [], 'not-allowed-status' => 401, ], 'api' => [ 'api-service' => FindPageTemplateCmsResourceHistoryBy::class, 'to-array' => CmsResourcesToArray::class, 'not-found-status' => 404, ], ], * /* */ /* NOTE: we can use the PageVersion APIs for versions as they are shared */ ], ], ]; } }
45.199525
97
0.374586
4b7ede277a45c884ce5e14d1107c6e531948d4ab
371
cpp
C++
C++ Contribution/Possible Combination Problem.cpp
katsuNakajima/Hacktoberfest
ecd09627c5ca2defd08d048d11b5660a78df481c
[ "MIT" ]
1
2021-10-31T11:28:29.000Z
2021-10-31T11:28:29.000Z
C++ Contribution/Possible Combination Problem.cpp
katsuNakajima/Hacktoberfest
ecd09627c5ca2defd08d048d11b5660a78df481c
[ "MIT" ]
1
2021-11-13T18:27:21.000Z
2021-11-13T18:27:21.000Z
C++ Contribution/Possible Combination Problem.cpp
katsuNakajima/Hacktoberfest
ecd09627c5ca2defd08d048d11b5660a78df481c
[ "MIT" ]
1
2021-10-31T11:28:31.000Z
2021-10-31T11:28:31.000Z
#include <iostream> using namespace std; int main() { int factorial = 1; int num1,num2,arrangements,i; cout<<"Enter Number of Guests: "; cin>>num1; cout<<"Enter Number of Chairs: "; cin>>num2; for (i = 1; i<=num1; i++) { factorial = factorial*i; } arrangements = factorial/(num1-num2); cout<<"Possible Arrangments : "<<arrangements; return 0; }
19.526316
51
0.638814
62144a8808cb111722dc9e1418945de5f0712f93
1,730
lua
Lua
lua/includes/sdkgen/enums.lua
McSimp/Borderlands2SDK
89a6cecfa9c17293a8ebea45b7016fbc56c64fb1
[ "MIT" ]
4
2016-01-15T11:07:49.000Z
2020-07-04T16:24:59.000Z
lua/includes/sdkgen/enums.lua
McSimp/Borderlands2SDK
89a6cecfa9c17293a8ebea45b7016fbc56c64fb1
[ "MIT" ]
null
null
null
lua/includes/sdkgen/enums.lua
McSimp/Borderlands2SDK
89a6cecfa9c17293a8ebea45b7016fbc56c64fb1
[ "MIT" ]
2
2018-05-29T23:34:25.000Z
2020-07-04T16:50:52.000Z
local ffi = require("ffi") local engine = engine local Package = SDKGen.Package local DefaultEnum = engine.FindObject("Enum Core.Default__Enum", engine.Classes.UEnum) function Package:ProcessEnum(enum) if enum == DefaultEnum then return end SDKGen.DebugPrint("[SDKGen] Enum " .. enum:GetFullName()) local enumText = string.format("enum.MakeEnum(\"%s\", {\n", enum:GetName()) local processedNames = {} local names = enum.UEnum.Names for i=0,(names.Count-1) do local name = names.Data[i]:GetName() enumText = enumText .. "\t\"" .. name if processedNames[name] ~= nil then enumText = enumText .. tostring(processedNames[name]) SDKGen.AddError("Duplicate enum identifier " .. name .. " in " .. enum:GetFullName()) processedNames[name] = processedNames[name] + 1 else processedNames[name] = 1 end enumText = enumText .. "\"" if i ~= (names.Count-1) then -- It's not the last one, so put a comma on the end enumText = enumText .. "," end enumText = enumText .. "\n" end enumText = enumText .. "})\n\n" self.File:write(enumText) end function Package:ProcessEnums() self:CreateFile("enums") self:WriteFileHeader("Enums") -- Foreach object, check if it's an enum, then check if it's in the package. -- If it is, then process the enum for i=0,(engine.Objects.Count-1) do local obj = engine.Objects[i] if IsNull(obj) then goto continue end local package_object = obj:GetPackageObject() if IsNull(package_object) then goto continue end if package_object ~= self.PackageObj then goto continue end if not obj:IsA(engine.Classes.UEnum) then goto continue end obj = ffi.cast("struct UEnum*", obj) self:ProcessEnum(obj) ::continue:: end self:CloseFile() end
24.714286
88
0.694798
43a1b192c5802969bcb3083a2d559f544fec7c45
326
ts
TypeScript
sdk/core/core-http/src/util/typeguards.ts
yifan-zhou922/azure-sdk-for-js
48ecf32b6029d4eb4ef397bbe5f15d35a539007e
[ "MIT" ]
1,273
2018-09-12T22:17:39.000Z
2022-03-30T00:46:27.000Z
sdk/core/core-http/src/util/typeguards.ts
yifan-zhou922/azure-sdk-for-js
48ecf32b6029d4eb4ef397bbe5f15d35a539007e
[ "MIT" ]
12,787
2018-08-27T22:28:48.000Z
2022-03-31T22:23:19.000Z
sdk/core/core-http/src/util/typeguards.ts
yifan-zhou922/azure-sdk-for-js
48ecf32b6029d4eb4ef397bbe5f15d35a539007e
[ "MIT" ]
832
2018-08-30T21:18:03.000Z
2022-03-31T11:57:53.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Helper TypeGuard that checks if the value is not null or undefined. * @param thing - Anything * @internal */ export function isDefined<T>(thing: T | undefined | null): thing is T { return typeof thing !== "undefined" && thing !== null; }
27.166667
71
0.684049
afea4b536e618cb520246e81772f2873c30233cf
1,605
py
Python
examples/tensorflow/inference/tf-serving/inception/inference.py
FinchZHU/uai-sdk
78e06bebba2d18233ce6dcb5be619e940f7a7ef3
[ "Apache-2.0" ]
38
2017-04-26T04:00:09.000Z
2022-02-10T02:51:05.000Z
examples/tensorflow/inference/tf-serving/inception/inference.py
FinchZHU/uai-sdk
78e06bebba2d18233ce6dcb5be619e940f7a7ef3
[ "Apache-2.0" ]
17
2017-11-20T20:47:09.000Z
2022-02-09T23:48:46.000Z
examples/tensorflow/inference/tf-serving/inception/inference.py
FinchZHU/uai-sdk
78e06bebba2d18233ce6dcb5be619e940f7a7ef3
[ "Apache-2.0" ]
28
2017-07-08T05:23:13.000Z
2020-08-18T03:12:27.000Z
# Copyright 2017 The UAI-SDK Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """ A very simple Inception-v3 inferencer. The model that loaded was saved by SavedModelBuilder. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from PIL import Image import json from uai.arch.tf_serving import TFServingAiUcloudModel class InceptionModel(TFServingAiUcloudModel): """ Inception-v3 example model """ def __init__(self, conf): super(InceptionModel, self).__init__(conf) def load_model(self): super(InceptionModel, self).load_model() def execute(self, data, batch_size): output_tensor = super(InceptionModel, self).execute(data, batch_size) ret = [] for i in range(batch_size): classes_arr = output_tensor[0] ret.append(classes_arr[i][0]) return ret
34.891304
81
0.67352
c9cefee8a168803352c655d4e233de9b1175ff23
3,054
ts
TypeScript
src/pudeuko-service.ts
Deseteral/pudeuko
6010d65d36f03ece99df7b416b76e48bb3b55f0b
[ "MIT" ]
4
2019-02-21T19:19:43.000Z
2021-01-22T14:23:27.000Z
src/pudeuko-service.ts
Deseteral/pudeuko
6010d65d36f03ece99df7b416b76e48bb3b55f0b
[ "MIT" ]
6
2019-02-23T21:15:11.000Z
2021-11-02T23:25:14.000Z
src/pudeuko-service.ts
Deseteral/pudeuko
6010d65d36f03ece99df7b416b76e48bb3b55f0b
[ "MIT" ]
1
2019-02-27T18:41:20.000Z
2019-02-27T18:41:20.000Z
import cheerio from 'cheerio'; import getUrls from 'get-urls'; import { nanoid } from 'nanoid'; import fetch from 'node-fetch'; import { URL } from 'url'; import DropboxStorage from './dropbox-storage'; import Logger from './logger'; import { PudeukoItem, PudeukoLink, PudeukoObject } from './model'; class PudeukoItemNotFoundError extends Error { constructor(itemId: string) { super(`Pudeuko does not contain item with id: ${itemId}`); this.name = 'PudeukoItemNotFoundError'; } } class PudeukoService { private static logger = new Logger('PudeukoService'); static async getPudeuko(): Promise<PudeukoObject> { return DropboxStorage.read(); } static async getItem(itemId: string): Promise<PudeukoItem> { const pudeuko = await DropboxStorage.read(); const item = pudeuko.items.find((it) => it.id === itemId); if (!item) throw new PudeukoItemNotFoundError(itemId); return item; } static async addItemFromText(text: string): Promise<void> { const item = this.simpleItemFromText(text); const pudeuko = await DropboxStorage.read(); pudeuko.items.unshift(item); await DropboxStorage.write(pudeuko); PudeukoService.logger.info(`Added new pudeuko item with id ${item.id}`); try { this.enrichItem(item.id); } catch (e) { PudeukoService.logger.withError(e); } } static async archiveItem(itemId: string): Promise<void> { const pudeuko = await DropboxStorage.read(); const index = pudeuko.items.findIndex((item) => item.id === itemId); if (index === -1) throw new PudeukoItemNotFoundError(itemId); const item = pudeuko.items[index]; pudeuko.items.splice(index, 1); pudeuko.archive.unshift(item); await DropboxStorage.write(pudeuko); PudeukoService.logger.info(`Archived pudeuko item with id ${itemId}`); } private static simpleItemFromText(text: string): PudeukoItem { const url: (string | undefined) = getUrls(text).values().next().value; const link: (PudeukoLink | undefined) = url ? { url } : undefined; const icon = url ? { src: `${new URL(url).origin}/favicon.ico` } : undefined; return { id: nanoid(), text, link, icon, createdAt: new Date(), }; } private static async enrichItem(itemId: string): Promise<void> { const pudeuko = await this.getPudeuko(); const index = pudeuko.items.findIndex((it) => it.id === itemId); if (index === -1) return; const item = pudeuko.items[index]; if (!item.link) return; if (!item.text.startsWith('http') || item.text.split(' ').length > 1) return; const response = await fetch(item.link.url); if (!response.ok) return; const html = await response.text(); const $ = cheerio.load(html); item.text = $('title') .text() .split('\n') .join(''); pudeuko.items[index] = item; DropboxStorage.write(pudeuko); PudeukoService.logger.info(`Enriched data for pudeuko item with id ${itemId}`); } } export { PudeukoService, PudeukoItemNotFoundError, };
27.513514
83
0.662083
79d78188d3e628a5ad7cc87d233c2bec6892c224
2,284
php
PHP
resources/views/admin/auth/register.blade.php
BrianRuchiadi/resep_bangsa
f014b9bfc0983fa66c415057ba670d0c5d447aaf
[ "MIT" ]
null
null
null
resources/views/admin/auth/register.blade.php
BrianRuchiadi/resep_bangsa
f014b9bfc0983fa66c415057ba670d0c5d447aaf
[ "MIT" ]
null
null
null
resources/views/admin/auth/register.blade.php
BrianRuchiadi/resep_bangsa
f014b9bfc0983fa66c415057ba670d0c5d447aaf
[ "MIT" ]
null
null
null
@extends('layouts.admin.app') @section('content') <div class="header"> <div class="logo"></div> </div> <div class="login-body"> <div class="login-box"> <div class="login-box-title">Admin Register</div> <form method="post" action="{{ url('/admin/register') }}"> {{ csrf_field() }} <table> <tr> <td> Username </td> <td> <input type="text" name="name" value="{{ old('name') }}" required > </td> </tr> <tr> <td> Email </td> <td> <input type="email" name="email" value="{{ old('email') }}" required> </td> @if ($errors->has('email')) <span> <strong>{{ $errors->first('email') }}</strong> </span> @endif </tr> <tr> <td> Password </td> <td> <input type="password" name="password" required> </td> @if ($errors->has('password')) <span> <strong>{{ $errors->first('password') }}</strong> </span> @endif </tr> <tr> <td> Password Confirmation</td> <td> <input type="password" name="password_confirmation" required> </td> </tr> <tr> <td> Admin Pin </td> <td> <input type="number" name="admin_pin" required> </td> </tr> <tr> <td colspan="2"><span class="errors">{{ $errors->first() }}</span></td> </tr> <tr> <td></td> <td> <input type="submit" value="Register"> </td> </tr> </table> </form> </div> </div> @endsection
38.711864
104
0.32268
b7919637242c503f2e2d26342b5b56d84824bc24
14,642
cpp
C++
depricated/acyclic_graph_nodes.cpp
imikejackson/bingocpp
6ba00a490c8cb46edebfd78f56b1604a76d668e9
[ "Apache-2.0" ]
13
2019-03-14T09:54:02.000Z
2021-09-26T14:01:30.000Z
depricated/acyclic_graph_nodes.cpp
imikejackson/bingocpp
6ba00a490c8cb46edebfd78f56b1604a76d668e9
[ "Apache-2.0" ]
35
2019-08-29T19:12:05.000Z
2021-07-15T22:17:53.000Z
depricated/acyclic_graph_nodes.cpp
imikejackson/bingocpp
6ba00a490c8cb46edebfd78f56b1604a76d668e9
[ "Apache-2.0" ]
9
2018-10-18T02:43:03.000Z
2021-09-02T22:08:39.000Z
/*! * \file acyclic_graph_nodes.cc * * \author Ethan Adams * \date 2/6/2018 * * This file contains the functions associated with each class * implementation of Operation. */ #include "BingoCpp/acyclic_graph_nodes.h" namespace agraphnodes{ namespace { void x_load_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = x.col(stack(result_location, 1)); } void x_load_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { } void c_load_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { if (stack(result_location, 1) != -1) { buffer[result_location] = Eigen::ArrayXXd::Constant(x.rows(), 1, constants[stack(result_location, 1)]); } else { buffer[result_location] = Eigen::ArrayXXd::Zero(x.rows(), 1); } } void c_load_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { } void addition_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = buffer[stack(result_location, 1)] + buffer[stack(result_location, 2)]; } void addition_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { if (stack(dependency, 1) == command_index) { reverse_buffer[command_index] += reverse_buffer[dependency]; } if (stack(dependency, 2) == command_index) { reverse_buffer[command_index] += reverse_buffer[dependency]; } } void subtraction_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = buffer[stack(result_location, 1)] - buffer[stack(result_location, 2)]; } void subtraction_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { if (stack(dependency, 1) == command_index) { reverse_buffer[command_index] += reverse_buffer[dependency]; } if (stack(dependency, 2) == command_index) { reverse_buffer[command_index] -= reverse_buffer[dependency]; } } void multiplication_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = buffer[stack(result_location, 1)] * buffer[stack(result_location, 2)]; } void multiplication_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { if (stack(dependency, 1) == command_index) { reverse_buffer[command_index] += reverse_buffer[dependency] * forward_buffer[stack(dependency, 2)]; } if (stack(dependency, 2) == command_index) { reverse_buffer[command_index] += reverse_buffer[dependency] * forward_buffer[stack(dependency, 1)]; } } void division_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = buffer[stack(result_location, 1)] / buffer[stack(result_location, 2)]; } void division_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { if (stack(dependency, 1) == command_index) { reverse_buffer[command_index] += reverse_buffer[dependency] / forward_buffer[stack(dependency, 2)]; } if (stack(dependency, 2) == command_index) { reverse_buffer[command_index] += reverse_buffer[dependency] * (-forward_buffer[dependency] / forward_buffer[stack(dependency, 2)]); } } void sin_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = buffer[stack(result_location, 1)].sin(); } void sin_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { reverse_buffer[command_index] += reverse_buffer[dependency] * forward_buffer[stack(dependency, 1)].cos(); } void cos_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = buffer[stack(result_location, 1)].cos(); } void cos_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { reverse_buffer[command_index] -= reverse_buffer[dependency] * forward_buffer[stack(dependency, 1)].sin(); } void exp_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = buffer[stack(result_location, 1)].exp(); } void exp_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { reverse_buffer[command_index] += reverse_buffer[dependency] * forward_buffer[dependency]; } void log_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = (buffer[stack(result_location, 1)].abs()).log(); } void log_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { reverse_buffer[command_index] += reverse_buffer[dependency] / forward_buffer[stack(dependency, 1)]; } void power_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = (buffer[stack(result_location, 1)].abs()).pow( buffer[stack(result_location, 2)]); } void power_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { if (stack(dependency, 1) == command_index) { reverse_buffer[command_index] += forward_buffer[dependency] * reverse_buffer[dependency] * forward_buffer[stack(dependency, 2)] / forward_buffer[stack(dependency, 1)]; } if (stack(dependency, 2) == command_index) { reverse_buffer[command_index] += forward_buffer[dependency] * reverse_buffer[dependency] * (forward_buffer[stack(dependency, 1)].abs()).log(); } } void absolute_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = buffer[stack(result_location, 1)].abs(); } void absolute_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { reverse_buffer[command_index] += reverse_buffer[dependency] * forward_buffer[stack(dependency, 1)].sign(); } void sqrt_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = (buffer[stack(result_location, 1)].abs()).sqrt(); } void sqrt_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { reverse_buffer[command_index] += 0.5 * reverse_buffer[dependency] / forward_buffer[dependency] * forward_buffer[stack(dependency, 1)].sign(); } } //namespace const std::vector<forward_operator_function> forward_eval_map { x_load_evaluate, c_load_evaluate, addition_evaluate, subtraction_evaluate, multiplication_evaluate, division_evaluate, sin_evaluate, cos_evaluate, exp_evaluate, log_evaluate, power_evaluate, absolute_evaluate, sqrt_evaluate }; const std::vector<derivative_operator_function> derivative_eval_map { x_load_deriv_evaluate, c_load_deriv_evaluate, addition_deriv_evaluate, subtraction_deriv_evaluate, multiplication_deriv_evaluate, division_deriv_evaluate, sin_deriv_evaluate, cos_deriv_evaluate, exp_deriv_evaluate, log_deriv_evaluate, power_deriv_evaluate, absolute_deriv_evaluate, sqrt_deriv_evaluate }; void forward_eval_function(int node, const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { forward_eval_map.at(node)(stack, x, constants, buffer, result_location); } void derivative_eval_function(int node, const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { derivative_eval_map.at(node)(stack, command_index, forward_buffer, reverse_buffer, dependency); } }
46.044025
99
0.523562
bf4eea16f74715eeb9afd178ee99ce7707ba5a23
227
rb
Ruby
db/migrate/20160511001608_add_activation_to_users.rb
kissaah1/345
a370339116d522f44fa07c2a55863bafb6daa3d1
[ "FSFAP" ]
null
null
null
db/migrate/20160511001608_add_activation_to_users.rb
kissaah1/345
a370339116d522f44fa07c2a55863bafb6daa3d1
[ "FSFAP" ]
null
null
null
db/migrate/20160511001608_add_activation_to_users.rb
kissaah1/345
a370339116d522f44fa07c2a55863bafb6daa3d1
[ "FSFAP" ]
null
null
null
class AddActivationToUsers < ActiveRecord::Migration def change add_column :users, :activation_digest, :string add_column :users, :activated, :boolean, default: false add_column :users, :activated_at, :datetime end end
28.375
57
0.779736
a014b26110881a2342def7a7e9fc678fb096e270
9,828
tsx
TypeScript
src/RenderController.tsx
alexseitsinger/data-controller
37fa4333ae0b1f0df7ec0e8e68a038be12002505
[ "BSD-2-Clause" ]
null
null
null
src/RenderController.tsx
alexseitsinger/data-controller
37fa4333ae0b1f0df7ec0e8e68a038be12002505
[ "BSD-2-Clause" ]
2
2021-05-09T00:26:18.000Z
2021-09-01T05:59:57.000Z
src/RenderController.tsx
alexseitsinger/react-render-controller
37fa4333ae0b1f0df7ec0e8e68a038be12002505
[ "BSD-2-Clause" ]
null
null
null
import React, { ReactNode } from "react" //import PropTypes from "prop-types" import { debounce, isEqual, isFunction } from "underscore" import { RenderControllerRenderProps } from "./RenderControllerContext" import { RenderControllerWithContextInitialProps } from "./RenderControllerWithContext" //import { resetAttempted } from "../utils/attempted" import { FunctionType } from "./types" import { hasCompleted, setCompleted, setUncompleted } from "./utils/completing" import { assertFirstLoad } from "./utils/counting" import { controllerMessage } from "./utils/debug" import { createChecker, isDefined } from "./utils/general" import { assertTargetsHaveData, startLoading } from "./utils/loading" import { hasMounted, setMounted, setUnmounted } from "./utils/mounting" import { clearSkippedPathnames, FinalSkippedPathname } from "./utils/pathnames" import { startUnloading } from "./utils/unloading" export type RenderControllerTargetData = any[] | { [key: string]: any } export interface RenderControllerTarget { name: string; data: RenderControllerTargetData; getter: FunctionType; setter: FunctionType; empty: {} | []; excluded?: string[]; forced?: boolean; cached?: boolean; attempted?: boolean; } export interface RenderControllerPathnames { lastPathname: string; currentPathname: string; } export type RenderControllerProps = RenderControllerWithContextInitialProps & RenderControllerPathnames & RenderControllerRenderProps & { skippedPathnames: FinalSkippedPathname[], } export interface RenderControllerState { isControllerCompleted: boolean; } export class RenderController extends React.Component< RenderControllerProps, RenderControllerState > { // Control our setState method with a variable to prevent memroy leaking // from our debounced methods running after the components are removed. isMountedNow = false // Store a set of canceller functions to run when our debounced load // functions should not continue due to unmounting, etc. cancellers: FunctionType[] = [] // Once a component has been mounted, we toggle a local state variable to // change the rendered output from renderFirst() to either renderWith() or // renderWithout() setControllerCompleted: FunctionType // Each time one of these components is unmounted, it invokes a debounced // method to run functions following its unmounting. However, if the component // is remounted before the timeout completes, this handler method is // cancelled. handleUnmount: FunctionType // Prevents the handleUnmount method from actually running. This is invoked // during mounting each time the component is mounted. cancelHandleUnmount: FunctionType check: () => void constructor(props: RenderControllerProps) { super(props) const { controllerName, targets } = props // Require the delay to be at least 1100ms. // Limit the delay to 4400ms const failDelay = Math.max(1100, Math.min(4400, targets.length * 1100)) const realSetState = this.setState.bind(this) this.setState = (...args): void => { if (!this.isMountedNow) { return } realSetState(...args) } // If this component gets re-mounted and it already has empty data, the // default state for isControllerCompleted will be false, so the loading screen // will shopw. To avoid this, we track each mounted component and reset the // default state if its already been mounted once. const isCompleted = hasCompleted(controllerName) this.state = { isControllerCompleted: isCompleted, } this.check = createChecker({ controllerName, delay: 2200, check: () => !hasMounted(controllerName), complete: () => { if (this.isMountedNow) { controllerMessage({ text: `Controller is currently mounted, so cancelling unmount process for '${controllerName}'`, level: 3, }) return } // When its determined that this pathname combination isnt being used, // run some functions to clear our our local caches. const isPrefixMounted = hasMounted(controllerName) if (!isPrefixMounted) { clearSkippedPathnames(controllerName) } // If this component instance is currently mounted and has been mounted // previously, don't run the rest of this function. This prevents our // handler from removing itself while its about to be // re-used/re-rendered again. //const { isMountedNow } = this //const isMountedPreviously = hasMounted(controllerName) //if (!isMountedNow) { setUncompleted(controllerName) //} }, }) // Save an instance method that adds this controllers name to a list of // controllers seen. This prevents the renderFirst() method from displaying // again, after the data has already been loaded, but this cmponent gets // re-rendered. this.setControllerCompleted = debounce(() => { const { isControllerCompleted } = this.state if (isControllerCompleted) { controllerMessage({ text: `'${controllerName}' is already completed.`, level: 3, }) return } setCompleted(controllerName) // Toggle the components state to True so our renderFirst() method // finished, and is replaced with either renderWith() or renderWithout(). this.setState({ isControllerCompleted: true }) }, failDelay) } componentDidMount(): void { const { targets, lastPathname, currentPathname, skippedPathnames, controllerName, } = this.props controllerMessage({ text: `Mounting controller '${controllerName}'`, level: 1, }) /** * Make sure we set the local flag to true, so our setState method works. */ this.isMountedNow = true /** * First, unload any previous data from prior render controllers before we * attempt to load data for this currently mounted render controller. */ startUnloading({ targets, controllerName, lastPathname, currentPathname, skippedPathnames, }) /** * Then, start the loading process for this render controllers targets. */ startLoading({ controllerName, targets, addCanceller: this.addCanceller, setControllerCompleted: () => { const f = this.setControllerCompleted if (isDefined(f) && isFunction(f)) { f() } }, }) // Add this controller to the list of mounted controllers. setMounted(controllerName) } componentDidUpdate(prevProps: RenderControllerProps): void { const { targets, controllerName } = this.props controllerMessage({ text: `Updating controller '${controllerName}'`, level: 1, }) const f = this.setControllerCompleted if (isDefined(f) && isFunction(f)) { f() } // If we have pending loads, and then we navigate away from that controller // before the load completes, the data will clear, and then load again. // To avoid this, cancel any pending loads everytime our targets change. if (!isEqual(targets, prevProps.targets)) { this.runCancellers() } } componentWillUnmount(): void { const { controllerName } = this.props // Set our flag to false so setState doesn't work after this. this.isMountedNow = false // Remove this controllers name from the list of mounbted controllers so // check() can run for this controller (if its finally unmounted). setUnmounted(controllerName) const f = this.check if (isDefined(f) && isFunction(f)) { f() } // Before any unmounting, cancel any pending loads. this.runCancellers() } addCanceller = (f?: FunctionType): void => { if (isDefined(f) && isFunction(f)) { this.cancellers.push(f) } } runCancellers = (): void => { this.cancellers.forEach((f: FunctionType) => { if (isFunction(f)) { f() } }) } renderFirst = (): ReactNode | null => { const { renderFirst, onRenderFirst } = this.props if (isFunction(renderFirst)) { return renderFirst() } if (isDefined(onRenderFirst) && isFunction(onRenderFirst)) { return onRenderFirst() } return null } renderWithout = (): ReactNode | null => { const { renderBoth, renderWithout, onRenderWithout } = this.props if (isFunction(renderBoth)) { return renderBoth() } if (isFunction(renderWithout)) { return renderWithout() } if (isDefined(onRenderWithout) && isFunction(onRenderWithout)) { return onRenderWithout() } return null } renderWith = (): ReactNode => { const { renderBoth, renderWith, children } = this.props if (isFunction(renderBoth)) { return renderBoth() } if (isDefined(renderWith) && isFunction(renderWith)) { return renderWith() } return children } render(): ReactNode | null { const { controllerName, targets } = this.props const { isControllerCompleted } = this.state const isFirstLoad = assertFirstLoad(controllerName, targets) const isTargetsHaveData = assertTargetsHaveData(targets) if (isFirstLoad && !isControllerCompleted) { controllerMessage({ text: `First render for '${controllerName}'`, level: 1, }) return this.renderFirst() } if (isTargetsHaveData) { controllerMessage({ text: `Rendering '${controllerName}' with data`, level: 1, }) return this.renderWith() } controllerMessage({ text: `Rendering '${controllerName}' without data`, level: 1, }) return this.renderWithout() } }
29.337313
107
0.665344
21c3440089dcca962af41985939d3ee5e23cdba7
840
js
JavaScript
src/Components/Post/CardAvatar.js
snwolak/steemblr
004eb56c1497457833afbe586d3bc9821f7a0003
[ "MIT" ]
11
2018-09-04T11:58:55.000Z
2022-02-22T19:10:55.000Z
src/Components/Post/CardAvatar.js
snwolak/steemblr
004eb56c1497457833afbe586d3bc9821f7a0003
[ "MIT" ]
14
2019-02-21T07:58:07.000Z
2021-05-27T21:28:40.000Z
src/Components/Post/CardAvatar.js
snwolak/steemblr
004eb56c1497457833afbe586d3bc9821f7a0003
[ "MIT" ]
5
2018-06-25T23:40:12.000Z
2019-05-06T00:56:59.000Z
import React, { Component } from "react"; import styled from "styled-components"; import getAvatarURL from "../../Functions/getAvatarURL"; // Component to load profile picture accordingly to the platform export const Avatar = styled.div` background: url(${props => props.url}); width: 40px; height: 40px; background-size: cover; box-sizing: border-box; display: flex; justify-content: center; align-content: flex-start; `; export default class CardAvatar extends Component { constructor(props) { super(props); this.state = { url: "" }; } async componentWillMount() { const { platform, author } = this.props; const URL = await getAvatarURL(platform, author); this.setState({ url: URL }); } render() { const { url } = this.state; return <Avatar url={url} />; } }
22.702703
64
0.652381
6756577f51ee89ed72ddb77368797697dd18dd72
9,737
dart
Dart
packages/flutter/test/material/navigation_bar_theme_test.dart
KKimj/flutter
6755ba59f43644cfeb82116b9b5595a8ddf464be
[ "BSD-3-Clause" ]
3
2020-08-25T19:44:45.000Z
2020-09-17T17:27:47.000Z
packages/flutter/test/material/navigation_bar_theme_test.dart
KKimj/flutter
6755ba59f43644cfeb82116b9b5595a8ddf464be
[ "BSD-3-Clause" ]
15
2022-02-07T20:06:06.000Z
2022-03-30T16:30:03.000Z
packages/flutter/test/material/navigation_bar_theme_test.dart
KKimj/flutter
6755ba59f43644cfeb82116b9b5595a8ddf464be
[ "BSD-3-Clause" ]
1
2019-12-23T15:06:59.000Z
2019-12-23T15:06:59.000Z
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('copyWith, ==, hashCode basics', () { expect(const NavigationBarThemeData(), const NavigationBarThemeData().copyWith()); expect(const NavigationBarThemeData().hashCode, const NavigationBarThemeData().copyWith().hashCode); }); testWidgets('Default debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const NavigationBarThemeData().debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description, <String>[]); }); testWidgets('Custom debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); NavigationBarThemeData( height: 200.0, backgroundColor: const Color(0x00000099), elevation: 20.0, indicatorColor: const Color(0x00000098), indicatorShape: const CircleBorder(), labelTextStyle: MaterialStateProperty.all(const TextStyle(fontSize: 7.0)), iconTheme: MaterialStateProperty.all(const IconThemeData(color: Color(0x00000097))), labelBehavior: NavigationDestinationLabelBehavior.alwaysHide, ).debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description[0], 'height: 200.0'); expect(description[1], 'backgroundColor: Color(0x00000099)'); expect(description[2], 'elevation: 20.0'); expect(description[3], 'indicatorColor: Color(0x00000098)'); expect(description[4], 'indicatorShape: CircleBorder(BorderSide(Color(0xff000000), 0.0, BorderStyle.none))'); expect(description[5], 'labelTextStyle: MaterialStateProperty.all(TextStyle(inherit: true, size: 7.0))'); // Ignore instance address for IconThemeData. expect(description[6].contains('iconTheme: MaterialStateProperty.all(IconThemeData'), isTrue); expect(description[6].contains('(color: Color(0x00000097))'), isTrue); expect(description[7], 'labelBehavior: NavigationDestinationLabelBehavior.alwaysHide'); }); testWidgets('NavigationBarThemeData values are used when no NavigationBar properties are specified', (WidgetTester tester) async { const double height = 200.0; const Color backgroundColor = Color(0x00000001); const double elevation = 42.0; const Color indicatorColor = Color(0x00000002); const ShapeBorder indicatorShape = CircleBorder(); const double selectedIconSize = 25.0; const double unselectedIconSize = 23.0; const Color selectedIconColor = Color(0x00000003); const Color unselectedIconColor = Color(0x00000004); const double selectedIconOpacity = 0.99; const double unselectedIconOpacity = 0.98; const double selectedLabelFontSize = 13.0; const double unselectedLabelFontSize = 11.0; const NavigationDestinationLabelBehavior labelBehavior = NavigationDestinationLabelBehavior.alwaysShow; await tester.pumpWidget( MaterialApp( home: Scaffold( bottomNavigationBar: NavigationBarTheme( data: NavigationBarThemeData( height: height, backgroundColor: backgroundColor, elevation: elevation, indicatorColor: indicatorColor, indicatorShape: indicatorShape, iconTheme: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return const IconThemeData( size: selectedIconSize, color: selectedIconColor, opacity: selectedIconOpacity, ); } return const IconThemeData( size: unselectedIconSize, color: unselectedIconColor, opacity: unselectedIconOpacity, ); }), labelTextStyle: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return const TextStyle(fontSize: selectedLabelFontSize); } return const TextStyle(fontSize: unselectedLabelFontSize); }), labelBehavior: labelBehavior, ), child: NavigationBar( destinations: _destinations(), ), ), ), ), ); expect(_barHeight(tester), height); expect(_barMaterial(tester).color, backgroundColor); expect(_barMaterial(tester).elevation, elevation); expect(_indicator(tester)?.color, indicatorColor); expect(_indicator(tester)?.shape, indicatorShape); expect(_selectedIconTheme(tester).size, selectedIconSize); expect(_selectedIconTheme(tester).color, selectedIconColor); expect(_selectedIconTheme(tester).opacity, selectedIconOpacity); expect(_unselectedIconTheme(tester).size, unselectedIconSize); expect(_unselectedIconTheme(tester).color, unselectedIconColor); expect(_unselectedIconTheme(tester).opacity, unselectedIconOpacity); expect(_selectedLabelStyle(tester).fontSize, selectedLabelFontSize); expect(_unselectedLabelStyle(tester).fontSize, unselectedLabelFontSize); expect(_labelBehavior(tester), labelBehavior); }); testWidgets('NavigationBar values take priority over NavigationBarThemeData values when both properties are specified', (WidgetTester tester) async { const double height = 200.0; const Color backgroundColor = Color(0x00000001); const double elevation = 42.0; const NavigationDestinationLabelBehavior labelBehavior = NavigationDestinationLabelBehavior.alwaysShow; await tester.pumpWidget( MaterialApp( home: Scaffold( bottomNavigationBar: NavigationBarTheme( data: const NavigationBarThemeData( height: 100.0, elevation: 18.0, backgroundColor: Color(0x00000099), labelBehavior: NavigationDestinationLabelBehavior.alwaysHide, ), child: NavigationBar( height: height, elevation: elevation, backgroundColor: backgroundColor, labelBehavior: labelBehavior, destinations: _destinations(), ), ), ), ), ); expect(_barHeight(tester), height); expect(_barMaterial(tester).color, backgroundColor); expect(_barMaterial(tester).elevation, elevation); expect(_labelBehavior(tester), labelBehavior); }); } List<NavigationDestination> _destinations() { return const <NavigationDestination>[ NavigationDestination( icon: Icon(Icons.favorite_border), selectedIcon: Icon(Icons.favorite), label: 'Abc', ), NavigationDestination( icon: Icon(Icons.star_border), selectedIcon: Icon(Icons.star), label: 'Def', ), ]; } double _barHeight(WidgetTester tester) { return tester.getRect( find.byType(NavigationBar), ).height; } Material _barMaterial(WidgetTester tester) { return tester.firstWidget<Material>( find.descendant( of: find.byType(NavigationBar), matching: find.byType(Material), ), ); } ShapeDecoration? _indicator(WidgetTester tester) { return tester.firstWidget<Container>( find.descendant( of: find.byType(FadeTransition), matching: find.byType(Container), ), ).decoration as ShapeDecoration?; } IconThemeData _selectedIconTheme(WidgetTester tester) { return _iconTheme(tester, Icons.favorite); } IconThemeData _unselectedIconTheme(WidgetTester tester) { return _iconTheme(tester, Icons.star_border); } IconThemeData _iconTheme(WidgetTester tester, IconData icon) { return tester.firstWidget<IconTheme>( find.ancestor( of: find.byIcon(icon), matching: find.byType(IconTheme), ), ).data; } TextStyle _selectedLabelStyle(WidgetTester tester) { return tester.widget<RichText>( find.descendant( of: find.text('Abc'), matching: find.byType(RichText), ), ).text.style!; } TextStyle _unselectedLabelStyle(WidgetTester tester) { return tester.widget<RichText>( find.descendant( of: find.text('Def'), matching: find.byType(RichText), ), ).text.style!; } NavigationDestinationLabelBehavior _labelBehavior(WidgetTester tester) { if (_opacityAboveLabel('Abc').evaluate().isNotEmpty && _opacityAboveLabel('Def').evaluate().isNotEmpty) { return _labelOpacity(tester, 'Abc') == 1 ? NavigationDestinationLabelBehavior.onlyShowSelected : NavigationDestinationLabelBehavior.alwaysHide; } else { return NavigationDestinationLabelBehavior.alwaysShow; } } Finder _opacityAboveLabel(String text) { return find.ancestor( of: find.text(text), matching: find.byType(Opacity), ); } // Only valid when labelBehavior != alwaysShow. double _labelOpacity(WidgetTester tester, String text) { final Opacity opacityWidget = tester.widget<Opacity>( find.ancestor( of: find.text(text), matching: find.byType(Opacity), ), ); return opacityWidget.opacity; }
36.468165
151
0.689432
ce9788e66534b60df094ef6cdfd1f9135385bafa
265
swift
Swift
Sources/VDRegex/QuantifierType.swift
dankinsoid/VDRegex
1a35bf3b760d817c64c046a59be87e712a95534b
[ "MIT" ]
null
null
null
Sources/VDRegex/QuantifierType.swift
dankinsoid/VDRegex
1a35bf3b760d817c64c046a59be87e712a95534b
[ "MIT" ]
null
null
null
Sources/VDRegex/QuantifierType.swift
dankinsoid/VDRegex
1a35bf3b760d817c64c046a59be87e712a95534b
[ "MIT" ]
null
null
null
// // File.swift // // // Created by Данил Войдилов on 14.06.2021. // import Foundation extension Regex { public enum QuantifierType: String { case lazy = "?", possessive = "+", greedy = "" public static var `default`: QuantifierType { .greedy } } }
15.588235
57
0.630189
bb69936c6e85ce7cfb880515d0ac42c22593f60d
88,573
cs
C#
SMI/Interface/frmCharacter.cs
mustafakemalgilor/kol-administration-tool
40b5d997e1f9b921abafc6b8dd983f981dcab882
[ "MIT" ]
null
null
null
SMI/Interface/frmCharacter.cs
mustafakemalgilor/kol-administration-tool
40b5d997e1f9b921abafc6b8dd983f981dcab882
[ "MIT" ]
null
null
null
SMI/Interface/frmCharacter.cs
mustafakemalgilor/kol-administration-tool
40b5d997e1f9b921abafc6b8dd983f981dcab882
[ "MIT" ]
1
2021-05-16T14:45:05.000Z
2021-05-16T14:45:05.000Z
/** * ______________________________________________________ * This file is part of ko-administration-tool project. * * @author Mustafa Kemal Gılor <mustafagilor@gmail.com> (2017) * . * SPDX-License-Identifier: MIT * ______________________________________________________ */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Windows.Forms; using DevExpress.Utils; using DevExpress.XtraEditors; using DevExpress.XtraNavBar; using KAI.Common.Declarations; using KAI.Declarations; namespace KAI.Interface { public partial class frmCharacter : XtraForm { #region Definition private byte _currentBagIndex = 1; public bool FromMaster = false; private bool _isInventoryReadOnly = true; // private InventorySlot _cutSlot = null; private InventorySlot _copiedSlot = null; private readonly InventorySlot[] _inventoryCopy = new InventorySlot[72]; /* User status flags */ public readonly User CurrentUser = new User(); private readonly mainFrm _myParent; private readonly Color _clrIncomingMessage = Color.FromArgb(255, 255, 255, 0); private readonly Color _clrOutgoingMessage = Color.FromArgb(255, 0, 0xFF, 0xCE); readonly Font _countFont = new Font("Verdana", 8.00F); private readonly Dictionary<int, XtraPanel> _equipments = new Dictionary<int, XtraPanel>(); private readonly Dictionary<int, XtraPanel> _inventory = new Dictionary<int, XtraPanel>(); private readonly Dictionary<int, XtraPanel> _cosplay = new Dictionary<int, XtraPanel>(); private readonly Dictionary<int, XtraPanel> _magicBag = new Dictionary<int, XtraPanel>(); private readonly Button _enter = new Button(); private readonly Button _escape = new Button(); private Color _rtfColor; class CustomFormatter : IFormatProvider, ICustomFormatter { private ProgressBarControl ProgressBar { get; set; } public CustomFormatter(ProgressBarControl progressBarControl) { ProgressBar = progressBarControl; } // implementing the GetFormat method of the IFormatProvider interface public object GetFormat(System.Type type) { return this; } // implementing the Format method of the ICustomFormatter interface public string Format(string format, object arg, IFormatProvider formatProvider) { var pbControl = ((CustomFormatter)formatProvider).ProgressBar; return $"{pbControl.Position}/{pbControl.Properties.Maximum}"; } } #endregion #region Construction public frmCharacter(mainFrm parent) { _myParent = parent; InitializeComponent(); AllowDrop = true; CurrentUser.OnSlotChanged += CurrentUser_OnSlotChanged; Closing += frmCharacter_Closing; /* Initialize backup array */ for (var i = 0; i < 72; i++) { _inventoryCopy[i] = new InventorySlot(); } chbBag1.Parent = pbInventory; chbBag2.Parent = pbInventory; chbBag1.Location = pbInventory.PointToClient(chbBag1.Location); chbBag2.Location = pbInventory.PointToClient(chbBag2.Location); chbBag1.Location = new Point(chbBag1.Location.X + 8, chbBag1.Location.Y + 35); chbBag2.Location = new Point(chbBag2.Location.X + 8, chbBag2.Location.Y + 35); // StaticReference.DisableDropRecursive(this); CancelButton = _escape; AcceptButton = _enter; _escape.Click += Escape_Click; _enter.Click += Enter_Click; TopLevel = true; AddPrivateChatLine_Italic("You haven't started a private chat yet.\nTo do so, just type a message below.", Color.White); InitializeInventorySlots(); rtfItemData.Parent = pbInventory; rtfItemData.WordWrap = false; rtfItemData.ContentsResized += RtfItemData_ContentsResized; healthBar.Properties.DisplayFormat.FormatType = FormatType.Custom; healthBar.Properties.DisplayFormat.Format = new CustomFormatter(healthBar); manaBar.Properties.DisplayFormat.FormatType = FormatType.Custom; manaBar.Properties.DisplayFormat.Format = new CustomFormatter(manaBar); } private void frmCharacter_Load(object sender, EventArgs e) { foreach (var v in CommonReference.ZoneList) { cbZones.Properties.Items.Add(v.Value + ":" + v.Key); } } private void Escape_Click(object sender, EventArgs e) { WindowState = FormWindowState.Minimized; } private void frmCharacter_Closing(object sender, CancelEventArgs e) { if (FromMaster) return; StaticReference.RemoveCharacterForm(CurrentUser.SocketID); StaticReference.ClientCore.SendTrackingUserUnset(CurrentUser.SocketID); // Main form navbar element _myParent.Invoke(new Action(() => { foreach (Control c in _myParent.npTrackedCharacters.Controls) { if(c is HyperlinkLabelControl) { if (Convert.ToInt16(c.Tag) != CurrentUser.SocketID) continue; _myParent.npTrackedCharacters.Controls.Remove(c); } return; } })); } public void OnCharacterLogout() { CommonReference.ShowWarning(this, $"Traced character(AID :{CurrentUser.AccountID}, CID : {CurrentUser.CharacterID}) has just logout from the server.\nYou can no longer trace this character."); Close(); } #endregion #region Inventory related private void SetInventoryReadOnly(bool value) { _isInventoryReadOnly = nbOptions_EnableEdit.Enabled = value; if (!_isInventoryReadOnly) { /* Backup the inventory data */ for (var i = 0; i < 72; i++) { CurrentUser.Inventory[i].CopyTo(_inventoryCopy[i]); } } ngOptions_DisableEdit.Enabled = !value; ngOptions_ImportPlayerInventory.Enabled = !value; CommonReference.ShowInformation(this, !_isInventoryReadOnly ? "Edit mode enabled." : "Edit mode disabled."); } #region Inventory render internal void RenderBagSlots() { int start = 0,end = 0; if (_currentBagIndex == 1) { start = 48; end = 59; } else { start = 60; end = 71; } for (var i = start; i <= end; i++) { var slot = CurrentUser.Inventory[i]; Image img = null; if (!slot.isEmpty()) { img = slot.Info == null ? CommonReference.GetIconByIconID((uint)0) : CommonReference.GetIconByIconID((uint)slot.Info.IconID); } if (img != null) { switch ((ItemFlag) slot.Flag) { case ItemFlag.ITEM_FLAG_SEALED: img = ((Bitmap) img).ColorTint(32/100.0f, 0, 0); break; case ItemFlag.ITEM_FLAG_DUPLICATE: img = ((Bitmap) img).ColorTint(0/100.0f, 30/100.0f, 50/100.0f); break; } } _magicBag[i - start].Tag = slot; _magicBag[i - start].BackgroundImage = img; } } internal void RenderInventory() { /* Suspend layout temporarily */ pbInventory.SuspendLayout(); for (var i = 0; i < 72; i++) { var slot = CurrentUser.Inventory[i]; Image img = null; if (!slot.isEmpty()) { img = slot.Info == null ? CommonReference.GetIconByIconID((uint)0) : CommonReference.GetIconByIconID((uint)slot.Info.IconID); } if (img != null) { switch ((ItemFlag) slot.Flag) { case ItemFlag.ITEM_FLAG_SEALED: img = ((Bitmap) img).ColorTint(32/100.0f, 0, 0); break; case ItemFlag.ITEM_FLAG_DUPLICATE: img = ((Bitmap) img).ColorTint(0/100.0f, 30/100.0f, 50/100.0f); break; } } if (i < 14) { /* Equipment */ _equipments[i].Tag = slot; _equipments[i].BackgroundImage = img; } else if (i >= 14 && i < 42) { /* Inventory */ _inventory[i - 14].Tag = slot; _inventory[i - 14].BackgroundImage = img; } else if (i >= 42 && i <= 47) { /* Cosplay */ _cosplay[i - 42].Tag = slot; _cosplay[i - 42].BackgroundImage = img; } } chbBag1.Checked = true; pbInventory.Controls.SetChildIndex(rtfItemData, 0);pbInventory.ResumeLayout(); } private void OnInventoryPanelPaint(object sender, PaintEventArgs e) { var senderPanel = sender as XtraPanel; Trace.Assert(null != senderPanel); var slot = senderPanel.Tag as InventorySlot; Trace.Assert(null != slot); var stringAlign = new StringFormat { Alignment = StringAlignment.Far, LineAlignment = StringAlignment.Far }; if (slot.Count <= 1) goto skip_count_rendering; /* Draw item count */ using (Brush brush = new SolidBrush(Color.FromArgb(255, 255, 255, 255))) { e.Graphics.DrawString(slot.Count.ToString(), _countFont, brush, senderPanel.DisplayRectangle, stringAlign); } skip_count_rendering:/* Draw selection rectangle if hovered */ if (!slot.Hovered) return; /* Draw selection rectangle */ using (var pen = new Pen(Color.Aquamarine, 3)) e.Graphics.DrawLines(pen, CommonReference.PanelGetBorder(0, 0, senderPanel.Width - 1, senderPanel.Height - 1)); } #endregion #region Inventory slot initialization private XtraPanel CreateNewInventoryPanel(int x, int y) { var newPanel = new XtraPanel { Size = new Size(45, 45), Location = new Point(x, y), BackColor = Color.Transparent, AllowDrop = true, Name = $"InventoryPanel{x}{y}", ContextMenuStrip = cmsInventory, }; newPanel.MouseHover += OnInventoryPanelMouseHover; newPanel.Paint += OnInventoryPanelPaint; newPanel.MouseEnter += OnInventoryPanelMouseEnter; newPanel.MouseLeave += OnInventoryPanelMouseLeave; newPanel.MouseDown += OnInventoryPanelMouseDown; newPanel.DragOver += OnInventoryPanelDragOver; newPanel.DragEnter += OnInventoryPanelDragEnter; newPanel.DragLeave += OnInventoryPanelDragLeave; newPanel.DragDrop += OnInventoryPanelDragDrop; return newPanel; } private void InitializeInventorySlots() { const int equipmentStartX = 420, equipmentStartY = 96; const int inventoryStartX = 232, inventoryStartY = 369; const int magicBagStartX = 28, magicBagStartY = 335; for (var i = 0; i < 28; i++) { int plusValueX = 49 * (i % 7), plusValueY = 49 * (i / 7); var newPanel = CreateNewInventoryPanel(inventoryStartX + plusValueX, inventoryStartY + plusValueY); pbInventory.Controls.Add(newPanel); _inventory.Add(i, newPanel); } for (var i = 0; i < 14; i++) { int plusValueX = 52 * (i % 3), plusValueY = 52 * (i / 3); var newPanel = CreateNewInventoryPanel(equipmentStartX + plusValueX, equipmentStartY + plusValueY); pbInventory.Controls.Add(newPanel); _equipments.Add(i, newPanel); } // for(var i = 0) /* Cospre & Magic Bag Slots */ var cospreHelmetPanel = CreateNewInventoryPanel(80, 63); pbInventory.Controls.Add(cospreHelmetPanel); _cosplay.Add(0, cospreHelmetPanel); var cospreArmLeft = CreateNewInventoryPanel(28, 115); pbInventory.Controls.Add(cospreArmLeft); _cosplay.Add(1, cospreArmLeft); var cospreArmRight = CreateNewInventoryPanel(132, 115); pbInventory.Controls.Add(cospreArmRight); _cosplay.Add(2, cospreArmRight); var cospreArmorPanel = CreateNewInventoryPanel(80, 170); pbInventory.Controls.Add(cospreArmorPanel); _cosplay.Add(3, cospreArmorPanel); var cospreMagicBag1 = CreateNewInventoryPanel(56, 244); pbInventory.Controls.Add(cospreMagicBag1); _cosplay.Add(4, cospreMagicBag1); var cospreMagicBag2 = CreateNewInventoryPanel(110, 244); pbInventory.Controls.Add(cospreMagicBag2); _cosplay.Add(5, cospreMagicBag2); for (int i = 0; i < 12; i++) { int plusValueX = 52 * (i % 3), plusValueY = 52 * (i / 3); var newPanel = CreateNewInventoryPanel(magicBagStartX + plusValueX, magicBagStartY+ plusValueY); pbInventory.Controls.Add(newPanel); // newPanel.BackColor = Color.Blue; _magicBag.Add(i, newPanel); } } #endregion #region Inventory Drag & Drop private void OnInventoryPanelDragDrop(object sender, DragEventArgs e) { var me = sender as XtraPanel; if (e.Data.GetDataPresent(DataFormats.Bitmap)) e.Effect = e.AllowedEffect & DragDropEffects.Move; else e.Effect = DragDropEffects.None; DropTargetHelper.Drop(e.Data, new Point(e.X, e.Y), e.Effect); if (_isInventoryReadOnly) return; if (me == null) return; var mySlot = me.Tag as InventorySlot; if (mySlot == null) { Trace.Assert(false, "mySlot is null."); return; } string draggedPanel = (string) e.Data.GetData("dragged_panel"); var vayaq = pbInventory.Controls[draggedPanel] as XtraPanel; if (vayaq == null) // null { // if the "vayaq" is null, then source must be an outsider. // Copying from outside requires an empty slot. if (!mySlot.isEmpty()) return; // There must be item information inside drag & drop info. // Extract it InventorySlot dragged_slot = e.Data.GetData("dragged_slot") as InventorySlot; if (dragged_slot == null) { Trace.WriteLine( "OnInventoryPanelDragDrop() - Drag drop succeeded, but dragged slot information is null."); return; } /* Copy information */ dragged_slot.CopyTo(CurrentUser.Inventory[mySlot.Pos]); mySlot.Serial = CommonReference.GenerateItemSerial(); mySlot.Durability = mySlot.Info.Duration; mySlot.Count = 1; /* Re-render the slot */ CurrentUser_OnSlotChanged(mySlot.Pos); } else { var draggedSlot = vayaq.Tag as InventorySlot; // Internal copy, we should just exchange. if (draggedSlot != null) CurrentUser.DoSlotExchange(mySlot.Pos,draggedSlot.Pos); // That's it. } } private static void OnInventoryPanelDragLeave(object sender, EventArgs e) { var me = sender as XtraPanel; DropTargetHelper.DragLeave(me); } private static void OnInventoryPanelDragEnter(object sender, DragEventArgs e) { var me = sender as XtraPanel; if (e.Data.GetDataPresent(DataFormats.Bitmap)) e.Effect = e.AllowedEffect & DragDropEffects.Move; else e.Effect = DragDropEffects.None; DropTargetHelper.DragEnter(me, e.Data, new Point(e.X, e.Y), e.Effect); } private static void OnInventoryPanelDragOver(object sender, DragEventArgs e) { try { if (e.Data.GetDataPresent(DataFormats.Bitmap)) e.Effect = e.AllowedEffect & DragDropEffects.Move; else e.Effect = DragDropEffects.None; DropTargetHelper.DragOver(new Point(e.X, e.Y), e.Effect); } catch(Exception ex) { } } private void OnInventoryPanelMouseDown(object sender, MouseEventArgs e) { if (_isInventoryReadOnly) return; if (e.Button != MouseButtons.Left) return; var senderPanel = sender as XtraPanel; Trace.Assert(null != senderPanel); var slot = senderPanel.Tag as InventorySlot; Trace.Assert(null != slot); if (slot.isEmpty()) return; DragSourceHelper.DoDragDrop(senderPanel, (Bitmap)senderPanel.BackgroundImage, new Point(e.X, e.Y), DragDropEffects.Move, new KeyValuePair<string, object>(DataFormats.Bitmap, senderPanel.BackgroundImage), new KeyValuePair<string, object>("dragged_panel",senderPanel.Name), new KeyValuePair<string, object>("slot_data", slot)); } #endregion #region Panel click events private void OnInventoryPanelMouseEnter(object sender, EventArgs e) { var senderPanel = sender as XtraPanel; Trace.Assert(null != senderPanel); var slot = senderPanel.Tag as InventorySlot; Trace.Assert(null != slot); slot.Hovered = true; /* Re-render the panel */ senderPanel.Refresh(); if (slot.ItemID <= 0) return; rtfItemData.Tag = senderPanel; ShowItemDetails(slot); rtfItemData.Show(); } private void OnInventoryPanelMouseLeave(object sender, EventArgs e) { var senderPanel = sender as XtraPanel; Trace.Assert(null != senderPanel); var slot = senderPanel.Tag as InventorySlot; Trace.Assert(null != slot); slot.Hovered = false; senderPanel.Refresh(); /* Hide item details */ if (!slot.isEmpty()) rtfItemData.Hide(); } private void OnInventoryPanelMouseHover(object sender, EventArgs e) { XtraPanel senderPanel = sender as XtraPanel; Trace.Assert(null != senderPanel); InventorySlot slot = senderPanel.Tag as InventorySlot; Trace.Assert(null != slot); } #endregion #endregion #region Private chat related public void PrivateChatMsgRecv(string msg) { AddPrivateChatLine(msg, _clrIncomingMessage); } private void Enter_Click(object sender, EventArgs e) { if (!tePrivateChat.EditorContainsFocus) return; StaticReference.ClientCore.SendPrivateChat(CurrentUser.SocketID, tePrivateChat.Text); AddPrivateChatLine(tePrivateChat.Text, _clrOutgoingMessage); tePrivateChat.Text = ""; } private void AddPrivateChatLine_Italic(string text, Color color) { rtbPrivateMessages.SelectionFont = new Font("Verdana", 7.11f, FontStyle.Italic); rtbPrivateMessages.SelectionColor = color; rtbPrivateMessages.SelectedText = text + "\n"; rtbPrivateMessages.SelectionColor = Color.White; rtbPrivateMessages.ScrollToCaret(); } private void AddPrivateChatLine(string text, Color color) { rtbPrivateMessages.SelectionFont = new Font("Verdana", 8.11f, FontStyle.Regular); rtbPrivateMessages.SelectionColor = color; rtbPrivateMessages.SelectedText = $"{DateTime.Now.ToLongTimeString()} {text}{"\n"}"; rtbPrivateMessages.SelectionColor = Color.White; rtbPrivateMessages.ScrollToCaret(); } #endregion #region Packet handling internal void HandleTracedCharacterPremiumChange(Packet receivedPacket) { //throw new NotImplementedException(); Trace.TraceInformation("PREMIUM CHANGE"); CurrentUser.PremiumChange(receivedPacket); RefreshTracedUserPremiumInformation(); } public void HandleTracedCharacterItemMoveResult(Packet receivedPacket) { byte result = receivedPacket.Read<byte>(); if (result == 0x02) return; byte bSrcPos = receivedPacket.Read<byte>(); byte bDstPos = receivedPacket.Read<byte>(); CurrentUser.DoSlotExchange(bSrcPos, bDstPos); } public void HandleTracedCharacterSaveInventoryResponse(Packet receivedPacket) { byte result = receivedPacket.Read<byte>(); switch (result) { case 0x01: pbInventory.Enabled = true; CommonReference.ShowInformation(this, "Inventory is successfully saved."); break; case 0x02: /* Restore backup */ for (int i = 0; i < 72; i++) { _inventoryCopy[i].CopyTo(CurrentUser.Inventory[i]); } /* Render the inventory */ RenderInventory(); pbInventory.Enabled = true; CommonReference.ShowWarning(this, "Inventory save operation failed.\nPlayer does not exist!"); break; case 0x03: /* Restore backup */ for (int i = 0; i < 72; i++) { _inventoryCopy[i].CopyTo(CurrentUser.Inventory[i]); } /* Render the inventory */ RenderInventory(); pbInventory.Enabled = true; CommonReference.ShowWarning(this, "Inventory save operation failed.\nInternal inventory error!"); break; } } internal void HandleTracedCharacterWarp(Packet receivedPacket) { CurrentUser.Warp(receivedPacket); Invoke(new Action(RefreshTracedCharacterCoordinates)); } internal void HandleTracedCharacterTargetHP(Packet receivedPacket) { CurrentUser.TargetHP(receivedPacket); } internal void HandleTracedCharacterItemMove(Packet receivedPacket) { CurrentUser.ItemMove(receivedPacket); Invoke(new Action(RefreshTracedCharacterInfo)); } internal void HandleTracedCharacterLevelChange(Packet receivedPacket) { CurrentUser.LevelChange(receivedPacket); Invoke(new Action(RefreshTracedCharacterInfo)); } internal void HandleTracedCharacterLoyaltyChange(Packet receivedPacket) { CurrentUser.LoyaltyChange(receivedPacket); Invoke(new Action(RefreshTracedUserLoyalty)); } internal void HandleTracedCharacterMspChange(Packet receivedPacket) { CurrentUser.MpChange(receivedPacket); Invoke(new Action(RefreshTracedUserHealthAndMana)); } internal void HandleTracedCharacterHpChange(Packet receivedPacket) { CurrentUser.HpChange(receivedPacket); Invoke(new Action(RefreshTracedUserHealthAndMana)); } internal void HandleTracedCharacterGoldChange(Packet receivedPacket) { CurrentUser.GoldChange(receivedPacket); Invoke(new Action(RefreshTracedUserGold)); } internal void HandleTracedCharacterExpChange(Packet receivedPacket) { CurrentUser.ExpChange(receivedPacket); Invoke(new Action(RefreshTracedCharacterExperience)); } internal void HandleTracedCharacterMove(Packet receivedPacket) { CurrentUser.Move(receivedPacket); Invoke(new Action(RefreshTracedCharacterCoordinates)); } public void HandleTracedCharacterSkillPointChange(Packet receivedPacket) { switch (receivedPacket.Read<byte>()) { case 5: CurrentUser.Skills.Profession1 = receivedPacket.Read<byte>(); break; case 6: CurrentUser.Skills.Profession2 = receivedPacket.Read<byte>(); break; case 7: CurrentUser.Skills.Profession3 = receivedPacket.Read<byte>(); break; case 8: CurrentUser.Skills.Master = receivedPacket.Read<byte>(); break; } RefreshTracedUserSkills(); } public void HandleTracedCharacterStatPointChange(Packet receivedPacket) { switch (receivedPacket.Read<byte>() - 1) { case 0: CurrentUser.Stats.UpdateSTR(receivedPacket.Read<ushort>(), CurrentUser.Stats.STRB); break; case 1: CurrentUser.Stats.UpdateHP(receivedPacket.Read<ushort>(), CurrentUser.Stats.HPB); break; case 2: CurrentUser.Stats.UpdateDEX(receivedPacket.Read<ushort>(), CurrentUser.Stats.DEXB); break; case 3: CurrentUser.Stats.UpdateINT(receivedPacket.Read<ushort>(), CurrentUser.Stats.INTB); break; case 4: CurrentUser.Stats.UpdateMP(receivedPacket.Read<ushort>(), CurrentUser.Stats.MPB); break; } RefreshTracedUserStats(); // throw new NotImplementedException(); } public void HandleTracedCharacterItemCountChange(Packet receivedPacket) { CurrentUser.ItemCountChange(receivedPacket); } public void HandleTracedCharacterItemGet(Packet receivedPacket) { CurrentUser.ItemGet(receivedPacket); // throw new NotImplementedException(); } public void HandleTracedCharacterItemBuySell(Packet receivedPacket) { CurrentUser.ItemBuySell(receivedPacket); } #endregion #region Refresh UI private void CurrentUser_OnSlotChanged(byte pos) { pbInventory.SuspendLayout(); var slot = CurrentUser.Inventory[pos]; Image img = null; if (!slot.isEmpty()) { img = slot.Info == null ? CommonReference.GetIconByIconID((uint)0) : CommonReference.GetIconByIconID((uint)slot.Info.IconID); } if (img != null) { switch ((ItemFlag)slot.Flag) { case ItemFlag.ITEM_FLAG_SEALED: img = ((Bitmap)img).ColorTint(32 / 100.0f, 0, 0); break; case ItemFlag.ITEM_FLAG_DUPLICATE: img = ((Bitmap)img).ColorTint(0 / 100.0f, 30 / 100.0f, 50 / 100.0f); break; } } if (pos < 0) return; if (pos < 14) { _equipments[pos].Tag = slot; _equipments[pos].BackgroundImage = img; _equipments[pos].Refresh(); } else if (pos >= 14 && pos < 42) { _inventory[pos - 14].Tag = slot; _inventory[pos - 14].BackgroundImage = img; _inventory[pos - 14].Refresh(); } else if (pos >= 42 && pos <= 47) { /* Cosplay */ _cosplay[pos - 42].Tag = slot; _cosplay[pos - 42].BackgroundImage = img; _cosplay[pos - 42].Refresh(); } if (pos >= 48 && pos <= 59 && _currentBagIndex == 1) { _magicBag[pos - 48].Tag = slot; _magicBag[pos - 48].BackgroundImage = img; _magicBag[pos - 48].Refresh(); } else if (pos >= 60 && pos <= 71 && _currentBagIndex == 2) { _magicBag[pos - 60].Tag = slot; _magicBag[pos - 60].BackgroundImage = img; _magicBag[pos - 60].Refresh(); } /* Ankamall evriveyır avm. */ /* Only inventory supported */ pbInventory.ResumeLayout(); } private void RefreshTracedUserGold() { if (CurrentUser == null) return; tbGold.Text = $"{CurrentUser.Gold}"; } private void RefreshTracedUserLoyalty() { if (CurrentUser == null) return; tbNationalPoints.Text = $"{CurrentUser.NationalPoints}/{CurrentUser.LeaderPoints}"; } private void RefreshTracedCharacterExperience() { if (CurrentUser == null) return; tbExperience.Text = $"{CurrentUser.Experience.Current}/{CurrentUser.Experience.Maximum}"; UpdateExperienceBar((int)CurrentUser.Experience.Current, (int)CurrentUser.Experience.Maximum); } private void RefreshTracedCharacterCoordinates() { if (CurrentUser == null) return; tbPosX.Text = $"{CurrentUser.PosX}"; tbPosY.Text = $"{CurrentUser.PosY}"; tbPosZ.Text = $"{CurrentUser.PosZ}"; } internal void RefreshTracedCharacterInfo() { if (CurrentUser == null) return; tbAccountID.Text = $"{CurrentUser.AccountID}"; tbCharacterID.Text = $"{CurrentUser.CharacterID}"; tbZone.Text = $"{CommonReference.GetZone(CurrentUser.Zone).Value}"; tbPosX.Text = $"{CurrentUser.PosX}"; tbPosZ.Text = $"{CurrentUser.PosZ}"; tbNation.Text = $"{Nation.GetDescription(CurrentUser.Nation)}"; tbRace.Text = $"{Race.GetDescription(CurrentUser.Race)}"; tbClass.Text = $"{CharacterClass.GetDescription(CurrentUser.Class)}"; tbClanName.Text = $"{CurrentUser.ClanName}"; tbLevel.Text = "LV." + $"{CurrentUser.Level}"; tbExperience.Text = $"{CurrentUser.Experience.Current}/{CurrentUser.Experience.Maximum}"; tbNationalPoints.Text = $"{CurrentUser.NationalPoints}/{CurrentUser.LeaderPoints}"; tbGold.Text = $"{CurrentUser.Gold}"; tbAuthority.Text = $"{Authority.GetDescription(CurrentUser.Authority)}"; RefreshTracedUserStats(); RefreshTracedUserSkills(); RefreshTracedUserHealthAndMana(); RefreshTracedUserResistances(); UpdateTracedUserStatusValues(); RefreshTracedUserPremiumInformation(); // Main form navbar element _myParent.Invoke(new Action(() => { foreach (Control ni in _myParent.npTrackedCharacters.Controls) { if (ni is HyperlinkLabelControl) { if (Convert.ToInt16(ni.Tag) == CurrentUser.SocketID) return; } } HyperlinkLabelControl link = new HyperlinkLabelControl(); link.Text = $"{CurrentUser.AccountID}:{CurrentUser.CharacterID}"; link.Tag = CurrentUser.SocketID; link.HyperlinkClick += _myParent.trackedCharacterLink_HyperlinkClick; _myParent.npTrackedCharacters.Controls.Add(link); })); } public void RefreshZoneInformation() { tbZone.Text = $"{CommonReference.GetZone(CurrentUser.Zone).Value}"; } private void RefreshTracedUserHealthAndMana() { UpdateHealthBar((int)CurrentUser.Health.Current, (int)CurrentUser.Health.Maximum); UpdateManaBar((int)CurrentUser.Mana.Current, (int)CurrentUser.Mana.Maximum); } private void RefreshTracedUserPremiumInformation() { string premiumLabel = "NONE"; switch(CurrentUser.PremiumType) { case 0: premiumLabel = "NONE"; break; case 1: premiumLabel = "DISCOUNT PREMIUM"; break; case 2: premiumLabel = "EXP PREMIUM"; break; case 3: premiumLabel = "BRONZE PREMIUM"; break; case 4: premiumLabel = "SILVER PREMIUM"; break; case 5: premiumLabel = "GOLD PREMIUM"; break; case 6: premiumLabel = "WAR PREMIUM"; break; case 7: premiumLabel = "PLATINUM PREMIUM"; break; case 8: premiumLabel = "ROYAL PREMIUM"; break; } tbPremiumType.Text = premiumLabel; DateTime start = CommonReference.UnixTimeStampToDateTime(CurrentUser.PremiumStart); DateTime end = CommonReference.UnixTimeStampToDateTime(CurrentUser.PremiumEnd); var rmtime = end - start; tbPremiumStart.Text = start.ToShortDateString() + " " + start.ToShortTimeString(); tbPremiumEnd.Text = end.ToShortDateString() + " " + end.ToShortTimeString(); tbPremiumRem.Text = $"{rmtime.Days} day(s) {rmtime.Hours} hour(s) {rmtime.Minutes} minute(s)"; } private void RefreshTracedUserSkills() { if (CurrentUser == null) return; tbSkillPro1.Text = $"{CurrentUser.Skills.Profession1}"; tbSkillPro2.Text = $"{CurrentUser.Skills.Profession2}"; tbSkillPro3.Text = $"{CurrentUser.Skills.Profession3}"; tbSkillMaster.Text = $"{CurrentUser.Skills.Master}"; } private void RefreshTracedUserResistances() { if (CurrentUser == null) return; tbResFlame.Text = $"{CurrentUser.Resistances.Flame}"; tbResGlacier.Text = $"{CurrentUser.Resistances.Glacier}"; tbResLightning.Text = $"{CurrentUser.Resistances.Lightning}"; tbResMagic.Text = $"{CurrentUser.Resistances.Magic}"; tbResPoison.Text = $"{CurrentUser.Resistances.Poison}"; tbResCurse.Text = $"{CurrentUser.Resistances.Curse}"; } private void RefreshTracedUserStats() { if (CurrentUser == null) return; tbSTR.Text = $"{CurrentUser.Stats.STR} (+{CurrentUser.Stats.STRB})"; tbDEX.Text = $"{CurrentUser.Stats.DEX} (+{CurrentUser.Stats.DEXB})"; tbHP.Text = $"{CurrentUser.Stats.HP} (+{CurrentUser.Stats.HPB})"; tbMP.Text = $"{CurrentUser.Stats.MP} (+{CurrentUser.Stats.MPB})"; tbINT.Text = $"{CurrentUser.Stats.INT} (+{CurrentUser.Stats.INTB})"; } private void UpdateHealthBar(int current, int maxHP) { healthBar.Properties.Maximum = maxHP; healthBar.Properties.Minimum = 0; healthBar.Position = current; // healthBar.Properties.DisplayFormat.FormatString = $"{current} / {maxHP}"; } private void UpdateManaBar(int current, int maxMP) { manaBar.Properties.Maximum = maxMP; manaBar.Properties.Minimum = 0; manaBar.Position = current; // manaBar.Properties.DisplayFormat.FormatString = $"{current} / {maxMP}"; } private void UpdateExperienceBar(int current, int maxExp) { expBar.Properties.Maximum = maxExp; expBar.Properties.Minimum = 0; expBar.Position = current; } private void SetFlagLabel(LabelControl control, bool status) { if (status) { control.BackColor = Color.LimeGreen; control.ForeColor = Color.White; } else { control.BackColor = Color.IndianRed; control.ForeColor = Color.White; } } private void UpdateTracedUserStatusValues() { SetFlagLabel(lblAlive, CurrentUser.CheckFlagSet(StatusFlags.ALIVE)); SetFlagLabel(lblSitting, CurrentUser.CheckFlagSet(StatusFlags.SITTING)); SetFlagLabel(lblMerchanting, CurrentUser.CheckFlagSet(StatusFlags.MERCHANT)); SetFlagLabel(lblInvisible, CurrentUser.CheckFlagSet(StatusFlags.INVIS)); SetFlagLabel(lblMuted, CurrentUser.CheckFlagSet(StatusFlags.MUTED)); SetFlagLabel(lblTransformed, CurrentUser.CheckFlagSet(StatusFlags.TRANSFORM)); SetFlagLabel(lblMoving, CurrentUser.CheckFlagSet(StatusFlags.MOVE)); SetFlagLabel(lblBlinking, CurrentUser.CheckFlagSet(StatusFlags.BLINK)); SetFlagLabel(lblCanAttack, CurrentUser.CheckFlagSet(StatusFlags.ATTACK)); SetFlagLabel(lblTrading, CurrentUser.CheckFlagSet(StatusFlags.TRADE)); SetFlagLabel(lblReported, CurrentUser.CheckFlagSet(StatusFlags.REPORT)); SetFlagLabel(lblKing, CurrentUser.CheckFlagSet(StatusFlags.KING)); SetFlagLabel(lblIngame, CurrentUser.CheckFlagSet(StatusFlags.IN_GAME)); SetFlagLabel(lblUsingStore, CurrentUser.CheckFlagSet(StatusFlags.USING_STORE)); SetFlagLabel(lblGamemaster, CurrentUser.CheckFlagSet(StatusFlags.GAMEMASTER)); SetFlagLabel(lblStealthDetect, CurrentUser.CheckFlagSet(StatusFlags.STEALTH_DETECTION)); SetFlagLabel(lblPmBlocked, CurrentUser.CheckFlagSet(StatusFlags.PM_BLOCK)); SetFlagLabel(lblClanMember, CurrentUser.CheckFlagSet(StatusFlags.CLAN)); SetFlagLabel(lblClanLeader, CurrentUser.CheckFlagSet(StatusFlags.CLAN_LEADER)); SetFlagLabel(lblClanAssistant, CurrentUser.CheckFlagSet(StatusFlags.CLAN_ASSIST)); SetFlagLabel(lblPartyMember, CurrentUser.CheckFlagSet(StatusFlags.PARTY)); SetFlagLabel(lblPartyLeader, CurrentUser.CheckFlagSet(StatusFlags.PARTY_LEADER)); SetFlagLabel(lblSeekingParty, CurrentUser.CheckFlagSet(StatusFlags.PARTY_SEEKING)); /* UNUSED_1 = 16777216, UNUSED_2 = 33554432, UNUSED_3 = 67108864, UNUSED_4 = 134217728, UNUSED_5 = 268435456, UNUSED_6 = 536870912, UNUSED_7 = 1073741824,*/ } #endregion #region Control events private void navBarItem6_LinkPressed(object sender, NavBarLinkEventArgs e) { var result = CommonReference.ShowQuestion(this, "ATTENTION : \n" + "Caveat 1 : Edit mode copies the current state of inventory internally.\n" + "Caveat 2 : If you save changes you've made, changes made by user during the edit period will be discarded.\n" + "Caveat 3 : If you discard the changes, internal copy will be restored and no changes will be made.\n" + "Do you want to continue?"); /* Change inventory read only flag */ SetInventoryReadOnly(result == DialogResult.No); } private void ngOptions_DisableEdit_LinkPressed(object sender, NavBarLinkEventArgs e) { var result = CommonReference.ShowQuestion(this, "Do you want to commit the changes you've made?"); if (result == DialogResult.Yes) { // Send changes to the server StaticReference.ClientCore.SendCharacterSaveInventoryRequest(CurrentUser.SocketID, CurrentUser.Inventory); // Now, we wait.. :D pbInventory.Enabled = false; } else { /* Restore backup */ for (int i = 0; i < 72; i++) { _inventoryCopy[i].CopyTo(CurrentUser.Inventory[i]); } /* Render the inventory */ RenderInventory(); } /* Change inventory read only flag */ SetInventoryReadOnly(true); } private void chbBag1_CheckedChanged(object sender, EventArgs e) { if (chbBag1.Checked) { _currentBagIndex = 1; chbBag2.Checked = false; RenderBagSlots(); } } private void chbBag2_CheckedChanged(object sender, EventArgs e) { if (chbBag2.Checked) { _currentBagIndex = 2; chbBag1.Checked = false; RenderBagSlots(); } } private void rtfItemData_TextChanged(object sender, EventArgs e) { } private void ngAuthority_EnableAttack_LinkPressed(object sender, NavBarLinkEventArgs e) { var dr = CommonReference.ShowQuestion(this,"Are you sure you want to give this user's attack ability back?"); if (dr == DialogResult.Yes) { StaticReference.ClientCore.SendOperatorRequest(CurrentUser.SocketID, (byte)OperatorRequests.ATTACKENABLE); } } private void ngAuthority_DisableAttack_LinkPressed(object sender, NavBarLinkEventArgs e) { var dr = CommonReference.ShowQuestion(this, "Are you sure you want to take away attack ability of this user?"); if (dr == DialogResult.Yes) { StaticReference.ClientCore.SendOperatorRequest(CurrentUser.SocketID, (byte)OperatorRequests.ATTACKDISABLE); } } private void ngAuthority_Mute_LinkPressed(object sender, NavBarLinkEventArgs e) { var dr = CommonReference.ShowQuestion(this, "Are you sure you want to mute this character?"); if (dr == DialogResult.Yes) { StaticReference.ClientCore.SendOperatorRequest(CurrentUser.SocketID, (byte)OperatorRequests.MUTE); } } private void ngAuthority_Unmute_LinkPressed(object sender, NavBarLinkEventArgs e) { var dr = CommonReference.ShowQuestion(this, "Are you sure you want to unmute this character?"); if (dr == DialogResult.Yes) { StaticReference.ClientCore.SendOperatorRequest(CurrentUser.SocketID, (byte)OperatorRequests.UNMUTE); } } private void ngAuthority_Disconnect_LinkPressed(object sender, NavBarLinkEventArgs e) { var dr = CommonReference.ShowQuestion(this, "Are you sure you want to disconnect this character from the server?"); if (dr == DialogResult.Yes) { StaticReference.ClientCore.SendOperatorRequest(CurrentUser.SocketID, (byte)OperatorRequests.DISCONNECT); } } private void ngAuthority_Ban_LinkPressed(object sender, NavBarLinkEventArgs e) { var dr = CommonReference.ShowQuestion(this, "Are you sure you want to ban this character?"); if (dr == DialogResult.Yes) { StaticReference.ClientCore.SendOperatorRequest(CurrentUser.SocketID, (byte)OperatorRequests.BAN); } } private void btnGiveGold_Click(object sender, EventArgs e) { StaticReference.ClientCore.SendValueAlteration(CurrentUser.SocketID, 0x01, 0x01, (uint)seGoldAmount.Value); } private void btnTakeGold_Click(object sender, EventArgs e) { StaticReference.ClientCore.SendValueAlteration(CurrentUser.SocketID, 0x01, 0x02, (uint)seGoldAmount.Value); } private void btnGiveExperience_Click(object sender, EventArgs e) { StaticReference.ClientCore.SendValueAlteration(CurrentUser.SocketID, 0x02, 0x01, (uint)seExperienceAmount.Value); } private void btnTakeExperience_Click(object sender, EventArgs e) { StaticReference.ClientCore.SendValueAlteration(CurrentUser.SocketID, 0x02, 0x02, (uint)seExperienceAmount.Value); } private void btnGiveLoyalty_Click(object sender, EventArgs e) { StaticReference.ClientCore.SendValueAlteration(CurrentUser.SocketID, 0x03, 0x01, (uint)seLoyaltyAmount.Value); } private void btnTakeLoyalty_Click(object sender, EventArgs e) { StaticReference.ClientCore.SendValueAlteration(CurrentUser.SocketID, 0x03, 0x02, (uint)seLoyaltyAmount.Value); } private void OnButtonStatEditClick(object sender, EventArgs e) { var btnSender = sender as SimpleButton; Trace.Assert(btnSender != null); /* STAT_STR = 0, STAT_STA = 1, STAT_DEX = 2, STAT_INT = 3, STAT_CHA = 4, // MP*/ switch (btnSender.Name) { case "btnStrUp": StaticReference.ClientCore.SendStatAlteration(CurrentUser.SocketID, 0, 1); break; case "btnStrDown": StaticReference.ClientCore.SendStatAlteration(CurrentUser.SocketID, 0, 0); break; case "btnHpUp": StaticReference.ClientCore.SendStatAlteration(CurrentUser.SocketID, 1, 1); break; case "btnHpDown": StaticReference.ClientCore.SendStatAlteration(CurrentUser.SocketID, 1, 0); break; case "btnDexUp": StaticReference.ClientCore.SendStatAlteration(CurrentUser.SocketID, 2, 1); break; case "btnDexDown": StaticReference.ClientCore.SendStatAlteration(CurrentUser.SocketID, 2, 0); break; case "btnIntUp": StaticReference.ClientCore.SendStatAlteration(CurrentUser.SocketID, 3, 1); break; case "btnIntDown": StaticReference.ClientCore.SendStatAlteration(CurrentUser.SocketID, 3, 0); break; case "btnMpUp": StaticReference.ClientCore.SendStatAlteration(CurrentUser.SocketID, 4, 1); break; case "btnMpDown": StaticReference.ClientCore.SendStatAlteration(CurrentUser.SocketID, 4, 0); break; /*case "btnUnspentStatUp": break; case "btnUnspentStatDown": break;*/ } } private void OnButtonSkillEditClick(object sender, EventArgs e) { var btnSender = sender as SimpleButton; Trace.Assert(btnSender != null); switch (btnSender.Name) { case "btnSkill1Up": StaticReference.ClientCore.SendSkillAlteration(CurrentUser.SocketID, 5, 1); break; case "btnSkill1Down": StaticReference.ClientCore.SendSkillAlteration(CurrentUser.SocketID, 5, 0); break; case "btnSkill2Up": StaticReference.ClientCore.SendSkillAlteration(CurrentUser.SocketID, 6, 1); break; case "btnSkill2Down": StaticReference.ClientCore.SendSkillAlteration(CurrentUser.SocketID, 6, 0); break; case "btnSkill3Up": StaticReference.ClientCore.SendSkillAlteration(CurrentUser.SocketID, 7, 1); break; case "btnSkill3Down": StaticReference.ClientCore.SendSkillAlteration(CurrentUser.SocketID, 7, 0); break; case "btnMasterUp": StaticReference.ClientCore.SendSkillAlteration(CurrentUser.SocketID, 8, 1); break; case "btnMasterDown": StaticReference.ClientCore.SendSkillAlteration(CurrentUser.SocketID, 8, 0); break; case "btnUnspentSkillUp": break; case "btnUnspentSkillDown": break; } } private void btnZoneChangeUser_Click(object sender, EventArgs e) { if (cbZones.SelectedIndex == -1) { CommonReference.ShowWarning(this, "Select a zone first."); return; } var zone = Convert.ToUInt16(Convert.ToString(cbZones.SelectedItem).Split(':')[1]); StaticReference.ClientCore.SendZoneChange(CurrentUser.SocketID, 0x01, zone); } private void btnZoneChangeParty_Click(object sender, EventArgs e) { if (cbZones.SelectedIndex == -1) { CommonReference.ShowWarning(this, "Select a zone first."); return; } var zone = Convert.ToUInt16(Convert.ToString(cbZones.SelectedItem).Split(':')[1]); StaticReference.ClientCore.SendZoneChange(CurrentUser.SocketID, 0x02, zone); } private void btnZoneChangeClan_Click(object sender, EventArgs e) { if (cbZones.SelectedIndex == -1) { CommonReference.ShowWarning(this, "Select a zone first."); return; } var zone = Convert.ToUInt16(Convert.ToString(cbZones.SelectedItem).Split(':')[1]); StaticReference.ClientCore.SendZoneChange(CurrentUser.SocketID, 0x03, zone); } #endregion #region Show item details private void RtfItemData_ContentsResized(object sender, ContentsResizedEventArgs e) { var richTextBox = (RichTextBox)sender; var currentPanel = richTextBox.Tag as XtraPanel; if (currentPanel == null) return; richTextBox.Width = e.NewRectangle.Width + 10; richTextBox.Height = e.NewRectangle.Height + 10; int yPos = 0 , xPos = 0; if (currentPanel.Location.Y + richTextBox.Height > pbInventory.Bottom) { yPos = pbInventory.Bottom - richTextBox.Height; } else { yPos = currentPanel.Location.Y; } if (currentPanel.Left - richTextBox.Width < pbInventory.Left) { xPos = currentPanel.Right; } else { xPos = currentPanel.Left - richTextBox.Width; } // richTextBox.ClientRectangle richTextBox.Location = new Point(xPos, yPos); //Cursor.Position } /// <summary> /// Gets a normal color from hex color. /// </summary> /// <param name="hexColor"></param> /// <returns></returns> public Color HexStringToColour(string hexColor) { var regex = new Regex(@"[abcdefABCDEF\d]+", RegexOptions.Compiled); string str = hexColor.Where(ch => regex.IsMatch(ch.ToString())).Aggregate("", (current, ch) => current + ch); if (str.Length != 6) return Color.Empty; string s = str.Substring(0, 2); string str3 = str.Substring(2, 2); string str4 = str.Substring(4, 2); Color empty; try { int red = int.Parse(s, NumberStyles.HexNumber); int green = int.Parse(str3, NumberStyles.HexNumber); int blue = int.Parse(str4, NumberStyles.HexNumber); empty = Color.FromArgb(red, green, blue); } catch { return Color.Empty; } return empty; } /// <summary> /// Adds text to item detail (with title option) /// </summary> /// <param name="text"></param> /// <param name="isTitle"></param> private void AddText(string text, bool isTitle) { if (isTitle) rtfItemData.SelectionFont = new Font("Tahoma", 7.6f, FontStyle.Bold); rtfItemData.SelectionColor = _rtfColor; rtfItemData.SelectedText = text; rtfItemData.SelectionColor = Color.White; } /// <summary> /// Adds text to item detail. /// </summary> /// <param name="text"></param> private void AddText(string text) { rtfItemData.SelectionFont = new Font("Tahoma", 7.11f, FontStyle.Regular); rtfItemData.SelectionColor = _rtfColor; rtfItemData.SelectedText = text; rtfItemData.SelectionColor = Color.White; } string RemoveBetween(string s, char begin, char end) { Regex regex = new Regex(string.Format("\\{0}.*?\\{1}", begin, end)); return regex.Replace(s, string.Empty); } /// <summary> /// Shows an item's details on a rtf. /// </summary> /// <param name="num"></param> private void ShowItemDetails(InventorySlot slot) { rtfItemData.SuspendLayout(); ItemInformation currentItem = slot.Info; rtfItemData.Clear(); _rtfColor = Color.White; bool isTradeable = true; bool isUnique = false; #pragma warning disable 219 bool isSealed = false; #pragma warning restore 219 bool isReverse = false; rtfItemData.Clear(); rtfItemData.SelectionAlignment = HorizontalAlignment.Center; if (currentItem == null) { AddText($"Item ID : {slot.ItemID}\n not found in TBL!"); return; } #region Declare Color Color clrUpgrade = HexStringToColour("#c87cc7"); Color clrMagic = HexStringToColour("#8080ff"); Color clrRare = HexStringToColour("#ffff00"); Color clrCraft = HexStringToColour("#80ff00"); Color clrUnique = HexStringToColour("#DDC77C"); Color clrReverse = HexStringToColour("#FF84A8"); Color clrCospre = HexStringToColour("#06FCC9"); Color clrNonTradeable = HexStringToColour("#922221"); Color clrBonus = HexStringToColour("#80ff00"); #pragma warning disable 168 Color clrEvent = HexStringToColour("#00FFCE"); #pragma warning restore 168 Color clrReverseUnique = HexStringToColour("#FFA500"); Color clrWhite = Color.White; #endregion _rtfColor = clrWhite; byte type = currentItem.ItemType; switch (type) { #region Parse Type case 0: _rtfColor = clrWhite; AddText(currentItem.Name.Trim(), true); AddText("\n\n(Normal Item)\n"); break; case 1: _rtfColor = clrMagic; AddText(currentItem.Name.Trim(), true); AddText("\n\n(Magic Item)\n"); break; case 2: _rtfColor = clrRare; AddText(currentItem.Name.Trim(), true); AddText("\n\n(Rare Item)\n"); break; case 3: _rtfColor = clrCraft; AddText(currentItem.Name.Trim(), true); AddText("\n\n(Craft Item)\n"); break; case 4: _rtfColor = clrUnique; AddText(currentItem.Name.Trim(), true); AddText("\n\n(Unique Item)\n"); isUnique = true; break; case 5: _rtfColor = clrUpgrade; AddText(currentItem.Name.Trim(), true); AddText("\n\n(Upgrade Item)\n"); break; case 6: _rtfColor = clrUpgrade; AddText(currentItem.Name.Trim(), true); AddText("\n\n(Event Item)\n"); break; case 8: _rtfColor = clrCospre; AddText(currentItem.Name.Trim(), true); _rtfColor = clrWhite; AddText("\n\n(Cospre)\n"); isTradeable = false; break; case 11: _rtfColor = clrReverse; AddText(currentItem.Name.Trim(), true); AddText("\n\n(Reverse Item)\n"); isReverse = true; break; case 12: _rtfColor = clrReverseUnique; AddText(currentItem.Name.Trim(), true); AddText("\n\n(Reverse Unique Item)\n"); isUnique = true; isReverse = true; break; default: AddText(currentItem.Name.Trim() + "\n\n type = " + type); break; #endregion } if (slot.ItemID > 899999999) isTradeable = false; byte kind = currentItem.Kind; switch (kind) { #region Parse Kind case 0: _rtfColor = clrWhite; AddText("Reward"); break; case 11: _rtfColor = clrWhite; AddText("Dagger"); break; case 21: _rtfColor = clrWhite; AddText("One Handed Sword"); break; case 22: _rtfColor = clrWhite; AddText("Two Handed Sword"); break; case 31: _rtfColor = clrWhite; AddText("One Handed Axe"); break; case 32: _rtfColor = clrWhite; AddText("Two-Handed Axe"); break; case 41: _rtfColor = clrWhite; AddText("Club"); break; case 42: _rtfColor = clrWhite; AddText("Two Handed Club"); break; case 51: _rtfColor = clrWhite; AddText("Spear"); break; case 52: _rtfColor = clrWhite; AddText("Long Spear"); break; case 60: _rtfColor = clrWhite; AddText("Shield"); break; case 70: _rtfColor = clrWhite; AddText("Bow"); break; case 71: _rtfColor = clrWhite; AddText("Crossbow"); break; case 91: _rtfColor = clrWhite; AddText("Earring"); break; case 92: _rtfColor = clrWhite; AddText("Necklace"); break; case 93: _rtfColor = clrWhite; AddText("Ring"); break; case 94: _rtfColor = clrWhite; AddText("Belt"); break; case 95: _rtfColor = clrWhite; AddText("Quest Item"); break; case 97: _rtfColor = clrWhite; AddText("Lune Item"); break; case 98: _rtfColor = clrWhite; AddText("Upgrade Scroll"); break; case 101: _rtfColor = clrWhite; AddText("Monster's Stone"); break; case 110: _rtfColor = clrWhite; AddText("Staff"); break; case 120: _rtfColor = clrWhite; AddText("Arrow"); break; case 130: _rtfColor = clrWhite; AddText("Javelin"); break; case 150: _rtfColor = clrWhite; AddText("Familiar Egg"); break; case 151: case 152: _rtfColor = clrWhite; AddText("Familiar"); break; case 160: _rtfColor = clrWhite; AddText("Cypher Ring"); break; case 170: _rtfColor = clrWhite; AddText("Autoloot"); break; case 171: _rtfColor = clrWhite; AddText("Image Change Scroll"); break; case 172: _rtfColor = clrWhite; AddText("Familiar Attack"); break; case 173: _rtfColor = clrWhite; AddText("Familiar Defense"); break; case 174: _rtfColor = clrWhite; AddText("Familiar Loyalty"); break; case 175: _rtfColor = clrWhite; AddText("Familiar Speciality Food"); break; case 176: _rtfColor = clrWhite; AddText("Familiar Food"); break; case 181: _rtfColor = clrWhite; AddText("Priest Mace"); break; case 210: _rtfColor = clrWhite; AddText("Warrior Armor"); break; case 220: _rtfColor = clrWhite; AddText("Rogue Armor"); break; case 230: _rtfColor = clrWhite; AddText("Mage Armor"); break; case 240: _rtfColor = clrWhite; AddText("Priest Armor"); break; case 250: _rtfColor = clrWhite; AddText("Seal Scroll"); break; case 253: isSealed = true; break; case 254: _rtfColor = clrWhite; AddText("Chaos Skill Item"); break; case 255: _rtfColor = clrWhite; AddText("Power Up Item"); break; #endregion } byte cls = currentItem.Class; switch (cls) { case 6: _rtfColor = clrWhite; AddText("\nDefensive Warrior"); break; } #region Parse bonus(es) rtfItemData.SelectedText = "\n"; _rtfColor = clrWhite; rtfItemData.SelectionAlignment = HorizontalAlignment.Left; if ((((currentItem.Kind >= 11) && (currentItem.Kind <= 0x47)) && (currentItem.Kind != 60)) || (currentItem.Kind == 110)) { AddText("Attack Power : " + currentItem.Damage + "\n"); AddText("Attack Speed : " + ((currentItem.Delay < 110) ? "Fast" : ((currentItem.Delay > 150) ? "Very Slow" : "Slow")) + "\n"); AddText("Effective Range : " + string.Format("{0:0.00}", currentItem.Range) + "\n"); } if (currentItem.Weight > 0) AddText("Weight : " + string.Format("{0:0.00}", currentItem.Weight / 10) + "\n"); if ((short)currentItem.Duration > 1) AddText("Max Durability : " + currentItem.Duration + "\n"); if (currentItem.Hitrate != 0) AddText(string.Format("Increase Attack Power by {0}%\n", currentItem.Hitrate)); if (currentItem.EvasionRate != 0) AddText(string.Format("Increase Evasion by {0}%\n", currentItem.EvasionRate)); if (currentItem.DropRate != 0) AddText(string.Format("Increase Drop Rate by {0}%\n", currentItem.DropRate)); if (currentItem.Ac != 0) AddText("Defense Ability : " + currentItem.Ac + "\n"); if ((((((currentItem.FireDamage > 0) || (currentItem.IceDamage > 0)) || ((currentItem.LightningDamage > 0) || (currentItem.PoisonDamage > 0))) || (((currentItem.StrB > 0) || (currentItem.StaB > 0)) || ((currentItem.DexB > 0) || (currentItem.IntelB > 0)))) || ((((currentItem.ChaB > 0) || (currentItem.DaggerAc > 0)) || ((currentItem.SwordAc > 0) || (currentItem.MaceAc > 0))) || (((currentItem.AxeAc > 0) || (currentItem.SpearAc > 0)) || ((currentItem.BowAc > 0) || (currentItem.HpDrain > 0))))) || ((((currentItem.MpDamage > 0) || (currentItem.MpDrain > 0)) || ((currentItem.MaxHpB > 0) || (currentItem.MaxMpB > 0))) || ((((currentItem.FireR > 0) || (currentItem.ColdR > 0)) || ((currentItem.LightningR > 0) || (currentItem.MagicR > 0))) || ((currentItem.PoisonR > 0) || (currentItem.CurseR > 0))))) { _rtfColor = clrBonus; if (currentItem.FireDamage > 0) AddText("Fire Damage : " + currentItem.FireDamage + "\n"); if (currentItem.IceDamage > 0) AddText("Ice Damage : " + currentItem.IceDamage + "\n"); if (currentItem.LightningDamage > 0) AddText("Lightning Damage : " + currentItem.LightningDamage + "\n"); if (currentItem.PoisonDamage > 0) AddText("Poison Damage : " + currentItem.PoisonDamage + "\n"); if (currentItem.DaggerAc > 0) AddText("Defense Ability (Dagger) : " + currentItem.DaggerAc + "\n"); if (currentItem.SwordAc > 0) AddText("Defense Ability (Sword) : " + currentItem.SwordAc + "\n"); if (currentItem.MaceAc > 0) AddText("Defense Ability (Club) : " + currentItem.MaceAc + "\n"); if (currentItem.AxeAc > 0) AddText("Defense Ability (Ax): " + currentItem.AxeAc + "\n"); if (currentItem.SpearAc > 0) AddText("Defense Ability (Spear) : " + currentItem.SpearAc + "\n"); if (currentItem.BowAc > 0) AddText("Defense Ability (Bow) : " + currentItem.BowAc + "\n"); if (currentItem.HpDrain > 0) AddText("HP Absorbed : " + currentItem.HpDrain + "\n"); if (currentItem.MpDamage > 0) AddText("MP Damage : " + currentItem.MpDamage + "\n"); if (currentItem.MpDrain > 0) AddText("MP Absorbed : " + currentItem.MpDrain + "\n"); if (currentItem.MaxHpB > 0) AddText("HP Bonus : " + currentItem.MaxHpB + "\n"); if (currentItem.MaxMpB > 0) AddText("MP Bonus : " + currentItem.MaxMpB + "\n"); if (currentItem.StrB > 0) AddText("Strength Bonus : " + currentItem.StrB + "\n"); if (currentItem.StaB > 0) AddText("Health Bonus : " + currentItem.StaB + "\n"); if (currentItem.DexB > 0) AddText("Dexterity Bonus : " + currentItem.DexB + "\n"); if (currentItem.IntelB > 0) AddText("Intelligence Bonus : " + currentItem.IntelB + "\n"); if (currentItem.ChaB > 0) AddText("Magic Power Bonus : " + currentItem.ChaB + "\n"); if (currentItem.FireR > 0) AddText("Resistance to Flame : " + currentItem.FireR + "\n"); if (currentItem.ColdR > 0) AddText("Resistance to Glacier : " + currentItem.ColdR + "\n"); if (currentItem.LightningR > 0) AddText("Resistance to Lightning : " + currentItem.LightningR + "\n"); if (currentItem.MagicR > 0) AddText("Resistance to Magic : " + currentItem.MagicR + "\n"); if (currentItem.PoisonR > 0) AddText("Resistance to Poison : " + currentItem.PoisonR + "\n"); if (currentItem.CurseR > 0) AddText("Resistance to Curse : " + currentItem.CurseR + "\n"); _rtfColor = Color.White; } if ((((byte)currentItem.ReqStr > 0) || ((byte)currentItem.ReqSta > 0)) || ((((byte)currentItem.ReqDex > 0) || ((byte)currentItem.ReqIntel > 0)) || ((byte)currentItem.ReqCha > 0))) { if ((byte)currentItem.ReqStr > 0) AddText("Required Strength : " + currentItem.ReqStr + "\n"); if ((byte)currentItem.ReqSta > 0) AddText("Required Health : " + currentItem.ReqSta + "\n"); if ((byte)currentItem.ReqDex > 0) AddText("Required Dexterity : " + currentItem.ReqDex + "\n"); if ((byte)currentItem.ReqIntel > 0) AddText("Required Intelligence : " + currentItem.ReqIntel + "\n"); if ((byte)currentItem.ReqCha > 0) AddText("Required Magic Power : " + currentItem.ReqCha + "\n"); } #endregion _rtfColor = clrMagic; AddText($"Item ID : {slot.ItemID}\n"); /* if (slot.ExpirationTime > 0) { DateTime dt = DateTime.FromFileTime(slot.ExpirationTime); }*/ if (isUnique && isReverse) { _rtfColor = clrBonus; AddText("Reverse unique item"); goto skip; } if (isUnique) { _rtfColor = clrBonus; AddText("Unique"); } if (isReverse) { _rtfColor = clrBonus; AddText("Item rank : Reverse"); } skip: ; if (!isTradeable) { rtfItemData.SelectionAlignment = HorizontalAlignment.Center; _rtfColor = clrNonTradeable; AddText("\nCannot be traded or sold"); } switch ((ItemFlag)slot.Flag) { case ItemFlag.ITEM_FLAG_RENTED: rtfItemData.SelectionAlignment = HorizontalAlignment.Center; _rtfColor = clrRare; AddText("\nRented Item"); break; case ItemFlag.ITEM_FLAG_SEALED: rtfItemData.SelectionAlignment = HorizontalAlignment.Center; _rtfColor = clrRare; AddText("\nSealed Item"); break; case ItemFlag.ITEM_FLAG_DUPLICATE: rtfItemData.SelectionAlignment = HorizontalAlignment.Center; _rtfColor = clrRare; AddText("\nDuplicate Item"); break; } rtfItemData.SelectionAlignment = HorizontalAlignment.Center; _rtfColor = clrWhite; AddText($"\n*{RemoveBetween(slot.Info.Description.Replace('|', '\n'),'<','>')}*"); if (slot.Serial == 0) { _rtfColor = clrNonTradeable; AddText($"\nSerial is zero!\n"); } rtfItemData.ResumeLayout(true); } #endregion private void ctsChangeCount_Click(object sender, EventArgs e) { if (_isInventoryReadOnly) { CommonReference.ShowWarning(this, "Inventory is in read only mode.\nPlease enable edit mode first."); return; } var senderPanel = cmsInventory.SourceControl as XtraPanel; var senderSlot = senderPanel?.Tag as InventorySlot; if (senderSlot == null) return; if (senderSlot.Info.Countable == 0) { CommonReference.ShowInformation(this, "Selected item is not countable."); return; } var inpbx = new InputBox("Enter the new amount", senderSlot.Count); inpbx.OnDialogClosed += delegate(object o) { ushort newValue; if (ushort.TryParse(Convert.ToString(o), out newValue)) { senderSlot.Count = newValue; } else { CommonReference.ShowWarning(this, "Either input contains non-numerical characters or the value exceeds the min-max range."); } }; inpbx.Show(); CurrentUser_OnSlotChanged(senderSlot.Pos); } private void ctsChangeSerial_Click(object sender, EventArgs e) { if (_isInventoryReadOnly) { CommonReference.ShowWarning(this, "Inventory is in read only mode.\nPlease enable edit mode first."); return; } var senderPanel = cmsInventory.SourceControl as XtraPanel; var senderSlot = senderPanel?.Tag as InventorySlot; if (senderSlot == null) return; var inpbx = new InputBox("Enter the new serial", senderSlot.Serial); inpbx.OnDialogClosed += delegate (object o) { ulong newValue; if (ulong.TryParse(Convert.ToString(o), out newValue)) { senderSlot.Serial = newValue; } else { CommonReference.ShowWarning(this, "Either input contains non-numerical characters or the value exceeds the min-max range."); } }; inpbx.Show(); CurrentUser_OnSlotChanged(senderSlot.Pos); } private void ctsCopy_Click(object sender, EventArgs e) { if (_isInventoryReadOnly) { CommonReference.ShowWarning(this, "Inventory is in read only mode.\nPlease enable edit mode first."); return; } var senderPanel = cmsInventory.SourceControl as XtraPanel; var senderSlot = senderPanel?.Tag as InventorySlot; if (senderSlot == null) return; _copiedSlot = senderSlot; } private void ctsPaste_Click(object sender, EventArgs e) { if (_isInventoryReadOnly) { CommonReference.ShowWarning(this, "Inventory is in read only mode.\nPlease enable edit mode first."); return; } var senderPanel = cmsInventory.SourceControl as XtraPanel; var senderSlot = senderPanel?.Tag as InventorySlot; if (senderSlot == null) return; if (_copiedSlot == null) { CommonReference.ShowWarning(this, "There is no copied item.\nCopy an item from inventory first."); return; } if (!senderSlot.isEmpty()) { var result = CommonReference.ShowQuestion(this,"There is an item exist in this slot.\nIf you continue, the existing item will be overwriten.\nDo you want to continue?"); if (result == DialogResult.No) return; } _copiedSlot.CopyTo(senderSlot); CurrentUser_OnSlotChanged(senderSlot.Pos); } private void ctsDelete_Click(object sender, EventArgs e) { if (_isInventoryReadOnly) { CommonReference.ShowWarning(this, "Inventory is in read only mode.\nPlease enable edit mode first."); return; } var senderPanel = cmsInventory.SourceControl as XtraPanel; var senderSlot = senderPanel?.Tag as InventorySlot; if (senderSlot == null) return; var result = CommonReference.ShowQuestion(this, "This will remove the item permanently.\nDo you want to continue?"); if (result == DialogResult.No) return; /* Easy peasy.*/ new InventorySlot().CopyTo(senderSlot); CurrentUser_OnSlotChanged(senderSlot.Pos); } private void ctsCopyToClipboardPlain_Click(object sender, EventArgs e) { var senderPanel = cmsInventory.SourceControl as XtraPanel; var senderSlot = senderPanel?.Tag as InventorySlot; if (senderSlot == null) return; Clipboard.SetText(senderSlot.ItemID.ToString()); } private void ctsCopyToClipboardGiveItem_Click(object sender, EventArgs e) { var senderPanel = cmsInventory.SourceControl as XtraPanel; var senderSlot = senderPanel?.Tag as InventorySlot; if (senderSlot == null) return; Clipboard.SetText($"+give_item {senderSlot.ItemID}"); } private void ngAuthority_MakeGM_LinkPressed(object sender, NavBarLinkEventArgs e) { // TODO : Make it only available to administrators var dr = CommonReference.ShowQuestion(this, "Are you sure you want to make this user game master?"); if (dr == DialogResult.Yes) { StaticReference.ClientCore.SendOperatorRequest(CurrentUser.SocketID, (byte) OperatorRequests.MAKEGM); } } private void ngAuthority_Reset_LinkPressed(object sender, NavBarLinkEventArgs e) { var dr = CommonReference.ShowQuestion(this, "Are you sure you want to reset this user's authority?"); if (dr == DialogResult.Yes) { StaticReference.ClientCore.SendOperatorRequest(CurrentUser.SocketID, (byte)OperatorRequests.UNMUTE); } } private void dePremiumStart_EditValueChanged(object sender, EventArgs e) { //CurrentUser. var result = dePremiumEnd.DateTime - DateTime.Now; lblPremiumRem.Text = $"{result.Days} day(s) {result.Hours} hour(s) {result.Minutes} minute(s) from now on."; } public void OnPremiumChangeResult(byte result) { btnUpdatePremium.Text = "Confirm"; btnUpdatePremium.Enabled = true; if (result == 0x01) { CommonReference.ShowInformation(this, "Premium information successfully changed."); } else CommonReference.ShowWarning(this, "Premium information change failed!"); } private void btnUpdatePremium_Click(object sender, EventArgs e) { if (cbPremiumType.SelectedIndex == -1) { CommonReference.ShowWarning(this, "Select a premium type."); return; } byte type = (byte)cbPremiumType.SelectedIndex; ulong start = (ulong)CommonReference.DateTimeToUnixTime(dePremiumStart.DateTime); ulong end = (ulong)CommonReference.DateTimeToUnixTime(dePremiumEnd.DateTime); StaticReference.ClientCore.SendPremiumChangeReq(CurrentUser.AccountID, type, start, end); btnUpdatePremium.Text = "Processing.."; btnUpdatePremium.Enabled = false; } private void dePremiumEnd_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e) { if((DateTime)e.NewValue < dePremiumStart.DateTime) { CommonReference.ShowWarning(this, "Expiration date cannot be less than starting date."); e.Cancel = true; return; } } private void dePremiumStart_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e) { if (dePremiumEnd.DateTime < (DateTime)e.NewValue) { CommonReference.ShowWarning(this, "Starting date cannot be higher than expiration date."); e.Cancel = true; return; } } private void btnGiveManner_Click(object sender, EventArgs e) { StaticReference.ClientCore.SendValueAlteration(CurrentUser.SocketID, 0x04, 0x01, (uint)seMannerAmount.Value); } private void btnTakeManner_Click(object sender, EventArgs e) { StaticReference.ClientCore.SendValueAlteration(CurrentUser.SocketID, 0x04, 0x00, (uint)seMannerAmount.Value); } private void accordionControl1_Click(object sender, EventArgs e) { } private void ngAuthority_btnDisconnect_Click(object sender, EventArgs e) { } private void ngAuthority_btnSendPrison_Click(object sender, EventArgs e) { using (frmPunishPlayer fpp = new frmPunishPlayer(CurrentUser, AccountPenalty.AccountPenaltyType.ACCOUNT_PENALTY_PRISON)) fpp.ShowDialog(); } private void ngAuthority_btnBan_Click(object sender, EventArgs e) { using (frmPunishPlayer fpp = new frmPunishPlayer(CurrentUser, AccountPenalty.AccountPenaltyType.ACCOUNT_PENALTY_BAN)) fpp.ShowDialog(); } private void ngAuthority_btnMute_Click(object sender, EventArgs e) { using (frmPunishPlayer fpp = new frmPunishPlayer(CurrentUser, AccountPenalty.AccountPenaltyType.ACCOUNT_PENALTY_MUTE)) fpp.ShowDialog(); } private void ngAuthority_btnTradeBlock_Click(object sender, EventArgs e) { using (frmPunishPlayer fpp = new frmPunishPlayer(CurrentUser, AccountPenalty.AccountPenaltyType.ACCOUNT_PENALTY_TRADE)) fpp.ShowDialog(); } private void ngAuthority_btnMerchantBlock_Click(object sender, EventArgs e) { using (frmPunishPlayer fpp = new frmPunishPlayer(CurrentUser, AccountPenalty.AccountPenaltyType.ACCOUNT_PENALTY_MERCHANT)) fpp.ShowDialog(); } private void ngAuthority_btnAttackBlock_Click(object sender, EventArgs e) { using (frmPunishPlayer fpp = new frmPunishPlayer(CurrentUser, AccountPenalty.AccountPenaltyType.ACCOUNT_PENALTY_ATTACK)) fpp.ShowDialog(); } private void ngAuthority_btnLetterBlock_Click(object sender, EventArgs e) { using (frmPunishPlayer fpp = new frmPunishPlayer(CurrentUser, AccountPenalty.AccountPenaltyType.ACCOUNT_PENALTY_LETTER)) fpp.ShowDialog(); } private void ngAuthority_btnZoneChangeBlock_Click(object sender, EventArgs e) { using (frmPunishPlayer fpp = new frmPunishPlayer(CurrentUser, AccountPenalty.AccountPenaltyType.ACCOUNT_PENALTY_ZONE_CHANGE)) fpp.ShowDialog(); } } }
38.864853
184
0.520971
da5e914169bb436b8c31e10e999ad33ce17e47df
2,893
php
PHP
inc/sidebar.php
arman77262/blog1
dddcf4328a54880924c10941396b5bdf34bd58cc
[ "MIT" ]
null
null
null
inc/sidebar.php
arman77262/blog1
dddcf4328a54880924c10941396b5bdf34bd58cc
[ "MIT" ]
null
null
null
inc/sidebar.php
arman77262/blog1
dddcf4328a54880924c10941396b5bdf34bd58cc
[ "MIT" ]
null
null
null
<?php require_once 'config/config.php'; require_once 'lib/Database.php'; $db = new Database(); ?> <!-- Sidebar Widgets Column --> <div class="col-md-4"> <!-- Search Widget --> <div class="card my-4"> <h5 class="card-header">Search</h5> <div class="card-body"> <div class="input-group"> <div class="panel-content"> <div class="row"> <form class="form-inline" action="search.php" method="get"> <input class="form-control mr-sm-2" required name="search" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </div> </div> </div> </div> <!-- Categories Widget --> <div class="card my-4"> <h5 class="card-header">Categories</h5> <div class="card-body"> <div class="row"> <div class="col-lg-6"> <ul class="list-unstyled mb-0"> <?php $query = "SELECT * FROM tbl_category"; $result = $db->select($query); if ($result){ while ($row = mysqli_fetch_assoc($result)){ ?> <li> <a href="posts.php?category=<?=base64_encode($row['id'])?>"><?=$row['name']?></a> </li> <?php } } ?> </ul> </div> </div> </div> </div> <!-- Side Widget --> <div class="card my-4"> <h5 class="card-header">Side Widget</h5> <div class="card-body"> <div class="samesidebar clear"> <h2>Latest articles</h2> <?php $query = "SELECT * FROM `tbl_post` LIMIT 5"; $post = $db->select($query); if ($post){ while ($row = mysqli_fetch_assoc($post)){ ?> <div class="popular clear"> <h3><a href="post.php?id=<?=base64_encode($row['id'])?>"><?=$row['title']?></a></h3> <a href="#"><img src="admin/<?=$row['image']?>" alt="post image"/></a> <p><?php echo $fr->textShorten($row['body'],120)?></p> </div> <?php } }else{ echo '<h1>Post Not Found</h1>'; } ?> </div> </div> </div> </div>
35.716049
142
0.374006
e7746fa979c88accedf379f3d62ab0c089f0912c
222
php
PHP
src/LocalesResolvers/ResolverInterface.php
freiondrej/translation
27bc66c94043ed64c2dcd46a2ec680dc6bf502cb
[ "MIT" ]
null
null
null
src/LocalesResolvers/ResolverInterface.php
freiondrej/translation
27bc66c94043ed64c2dcd46a2ec680dc6bf502cb
[ "MIT" ]
1
2020-12-19T08:16:46.000Z
2020-12-19T08:16:46.000Z
src/LocalesResolvers/ResolverInterface.php
freiondrej/translation
27bc66c94043ed64c2dcd46a2ec680dc6bf502cb
[ "MIT" ]
null
null
null
<?php declare(strict_types = 1); namespace Contributte\Translation\LocalesResolvers; use Contributte; interface ResolverInterface { public function resolve(Contributte\Translation\Translator $translator): ?string; }
17.076923
82
0.806306
168ad0a3f54de27b6b08f55f2b84c53e7f52f891
1,528
dart
Dart
lib/src/transaction.dart
golfzimpligital/flutter_callkit
5d407c9330afb5ca4da4dbca79da1190e6352621
[ "MIT" ]
41
2020-03-23T17:35:32.000Z
2022-02-02T19:02:36.000Z
lib/src/transaction.dart
golfzimpligital/flutter_callkit
5d407c9330afb5ca4da4dbca79da1190e6352621
[ "MIT" ]
22
2020-03-28T08:50:21.000Z
2022-03-31T01:50:44.000Z
lib/src/transaction.dart
golfzimpligital/flutter_callkit
5d407c9330afb5ca4da4dbca79da1190e6352621
[ "MIT" ]
14
2020-08-28T18:20:30.000Z
2022-01-30T22:59:17.000Z
/// Copyright (c) 2011-2020, Zingaya, Inc. All rights reserved. part of flutter_callkit_voximplant; /// Dart representation of CXTransaction from iOS CallKit Framework. /// /// An object that contains zero or more action objects to be performed /// by a call controller. class FCXTransaction { /// The unique identifier of the transaction. final String uuid; /// Whether all actions have been completed. final bool complete; /// The list of actions contained by the transaction. Future<List<FCXAction>> getActions() async { try { String method = 'getActions'; var data = await _methodChannel.invokeListMethod<Map>( '$_TRANSACTION.$method', {'transactionUuid': uuid}, ); _FCXLog._i(runtimeType, method); List<FCXAction> actions = []; if (data == null) { _FCXLog._w(runtimeType, 'Empty data received, processing skipped'); } else { for (Map map in data) { FCXAction? action = _FCXActionMapDecodable._makeAction(map); if (action == null) { _FCXLog._w(runtimeType, 'failed to decode action: $map'); } else { actions.add(action); } } } return actions; } on PlatformException catch (e) { var exception = FCXException(e.code, e.message); _FCXLog._e(runtimeType, exception); throw exception; } } FCXTransaction._fromMap(Map<dynamic, dynamic> data) : this.uuid = data['uuid'], this.complete = data['complete']; }
30.56
75
0.63089
05d9cd5cedb26bcc0deeb7a804d1a0b3fa9ca67c
2,590
py
Python
integration/combination/test_intrinsic_function_support.py
hawflau/serverless-application-model
d2cf4b7e23d26cdf677c564d53bb58e6a5b6cac2
[ "Apache-2.0" ]
1,279
2020-08-25T03:33:15.000Z
2022-03-31T09:49:22.000Z
integration/combination/test_intrinsic_function_support.py
hawflau/serverless-application-model
d2cf4b7e23d26cdf677c564d53bb58e6a5b6cac2
[ "Apache-2.0" ]
797
2020-08-24T23:30:05.000Z
2022-03-31T22:28:29.000Z
integration/combination/test_intrinsic_function_support.py
hawflau/serverless-application-model
d2cf4b7e23d26cdf677c564d53bb58e6a5b6cac2
[ "Apache-2.0" ]
431
2020-08-27T20:47:26.000Z
2022-03-31T23:57:55.000Z
from parameterized import parameterized from integration.helpers.base_test import BaseTest class TestIntrinsicFunctionsSupport(BaseTest): # test code definition uri object and serverless function properties support @parameterized.expand( [ "combination/intrinsics_code_definition_uri", "combination/intrinsics_serverless_function", ] ) def test_common_support(self, file_name): # Just a simple deployment will validate that Code & Swagger files were accessible # Just a simple deployment will validate that all properties were resolved expected self.create_and_verify_stack(file_name, self.get_default_test_template_parameters()) def test_severless_api_properties_support(self): self.create_and_verify_stack( "combination/intrinsics_serverless_api", self.get_default_test_template_parameters() ) # Examine each resource policy and confirm that ARN contains correct APIGW stage lambda_function_name = self.get_physical_id_by_type("AWS::Lambda::Function") lambda_client = self.client_provider.lambda_client # This is a JSON string of resource policy policy = lambda_client.get_policy(FunctionName=lambda_function_name)["Policy"] # Instead of parsing the policy, we will verify that the policy contains certain strings # that we would expect based on the resource policy # This is the stage name specified in YAML template api_stage_name = "devstage" # Paths are specififed in the YAML template get_api_policy_expectation = "*/GET/pathget" post_api_policy_expectation = "*/POST/pathpost" self.assertTrue( get_api_policy_expectation in policy, "{} should be present in policy {}".format(get_api_policy_expectation, policy), ) self.assertTrue( post_api_policy_expectation in policy, "{} should be present in policy {}".format(post_api_policy_expectation, policy), ) # Test for tags function_result = lambda_client.get_function(FunctionName=lambda_function_name) tags = function_result["Tags"] self.assertIsNotNone(tags, "Expecting tags on function.") self.assertTrue("lambda:createdBy" in tags, "Expected 'lambda:CreatedBy' tag key, but not found.") self.assertEqual(tags["lambda:createdBy"], "SAM", "Expected 'SAM' tag value, but not found.") self.assertTrue("TagKey1" in tags) self.assertEqual(tags["TagKey1"], api_stage_name)
42.459016
106
0.705405
05d3c3dfc4ceb4fb3b5834e4d8509a7a271d59d6
3,285
py
Python
datasource/management/commands/import_tracks.py
nkalfa/argophonica
ef712fc97ecea139079d78aeb6253e017f946c88
[ "BSD-3-Clause" ]
null
null
null
datasource/management/commands/import_tracks.py
nkalfa/argophonica
ef712fc97ecea139079d78aeb6253e017f946c88
[ "BSD-3-Clause" ]
null
null
null
datasource/management/commands/import_tracks.py
nkalfa/argophonica
ef712fc97ecea139079d78aeb6253e017f946c88
[ "BSD-3-Clause" ]
null
null
null
from .import_albums import clean_artist_album_names, extract_track_name_number from datasource.models import Album, Artist, Track from django.conf import settings from django.core.management.base import BaseCommand import glob import os PATH = '/argophonica/argophonica/media' def construct_audio_link(path_string, track_number, track_name): # We construct the link like this because if we just pass in a path_string to process, each time a new track calls # this function it will always start at path_string[2][0] and store that track as audio_field instead of its true # file. Disaster! Avoid! os.chdir(path_string[0]) # Check if album dir contains any audio files. Specifying file type to ignore image files for _ in glob.glob('*.mp3'): # Split PATH on 'media/' relative_path = str(path_string[0]).split('media/') # Ignore 'media' by using 2nd path bc Django MEDIA ROOT handles adding 'media/' when sending image to browser # Else the URL path will be incorrect audio_file = os.path.join(relative_path[1], track_number + ' ' + track_name + '.mp3') return audio_file def get_track(audio_type='.mp3'): tracks_saved = 0 for e, path_string in enumerate(os.walk(PATH)): # Check that path_string[1] is empty to stay at consistent level of depth for album data extraction if len(path_string[1]) == 0: # Clean artist and album strings artist_name, album_name = clean_artist_album_names(path_string) # Get remainder of data for track in path_string[2]: # path_string[2] = files # Check for audio files via audio file extension if audio_type in track: # Extract track info from path string track_number, track_name = extract_track_name_number(track) # Extract audio file from path string audio_file = construct_audio_link(path_string, track_number, track_name) # If track exists then pass, else begin instantiation of tracks if Track.objects.filter(title=track_name, artist=artist_name).exists(): print(f'Passing, the track {track_name} already exists.') else: # Need to create instance with Album and Artist preloaded because foreign key t = Track(album=Album.objects.get(title=album_name), artist=Artist.objects.get(artist=artist_name)) t.title = track_name t.length = 'Not sure ... have a listen and time it' t.track_number = track_number t.audio_file = audio_file t.audio_link = audio_file t.save() print(f"Saved to database: {t.title} link {t.audio_file} by {t.artist} off the album {t.album}") tracks_saved += 1 print(f'{tracks_saved} tracks saved to database.') return class Command(BaseCommand): def handle(self, *args, **options): print(f'Importing data from {settings.DATA_IMPORT_LOCATION}') get_track() if __name__ == '__main__': get_track()
39.107143
123
0.629224
73c22163ca36b61f220c45a92babdd775b5edac8
1,102
swift
Swift
Sources/SwiftHtml/Tags/Picture.swift
robertschmid/swift-html
896e1bdd23432f9ca828f0c184c5bd636caeef73
[ "MIT" ]
null
null
null
Sources/SwiftHtml/Tags/Picture.swift
robertschmid/swift-html
896e1bdd23432f9ca828f0c184c5bd636caeef73
[ "MIT" ]
null
null
null
Sources/SwiftHtml/Tags/Picture.swift
robertschmid/swift-html
896e1bdd23432f9ca828f0c184c5bd636caeef73
[ "MIT" ]
null
null
null
// // Picture.swift // SwiftHtml // // Created` by Tibor Bodecs on 2021. 07. 19.. // /// The `<picture>` tag gives web developers more flexibility in specifying image resources. /// /// The most common use of the `<picture>` element will be for art direction in responsive designs. /// Instead of having one image that is scaled up or down based on the viewport width, multiple images can be designed to more nicely fill the browser viewport. /// /// The `<picture>` element contains two tags: one or more `<source>` tags and one `<img>` tag. /// /// The browser will look for the first <source> element where the media query matches the current viewport width, and then it will display the proper image (specified in the srcset attribute). /// The `<img>` element is required as the last child of the `<picture>` element, as a fallback option if none of the source tags matches. /// /// **Tip:** The `<picture>` element works "similar" to `<video>` and `<audio>`. You set up different sources, and the first source that fits the preferences is the one being used. open class Picture: Tag { }
50.090909
193
0.715064
0dcc51db5f6f705ebd483cb207dd56a2732453ed
865
cs
C#
Assets/Scripts/Terrain/NoiseMesh.cs
chrislugram/HuntRebels
c7ad4bb7f4f1a28a05477f7bce78fd6b22ba7617
[ "MIT" ]
null
null
null
Assets/Scripts/Terrain/NoiseMesh.cs
chrislugram/HuntRebels
c7ad4bb7f4f1a28a05477f7bce78fd6b22ba7617
[ "MIT" ]
null
null
null
Assets/Scripts/Terrain/NoiseMesh.cs
chrislugram/HuntRebels
c7ad4bb7f4f1a28a05477f7bce78fd6b22ba7617
[ "MIT" ]
null
null
null
using UnityEngine; using System; using System.Collections; [Serializable] public class NoiseMesh { #region STATIC_ENUM_CONSTANTS #endregion #region FIELDS public float power = 3.0f; public float scale = 1.0f; private Vector2 v2SampleStart = new Vector2(0f, 0f); #endregion #region METHODS_CUSTOM public Mesh ApplyNoise(Mesh mesh) { v2SampleStart = new Vector2(UnityEngine.Random.Range (0.0f, 100.0f), UnityEngine.Random.Range (0.0f, 100.0f)); Vector3[] vertices = mesh.vertices; for (int i = 0; i < vertices.Length; i++) { float xCoord = v2SampleStart.x + vertices[i].x * scale; float yCoord = v2SampleStart.y + vertices[i].z * scale; vertices[i].y = (Mathf.PerlinNoise (xCoord, yCoord) - 0.5f) * power; } mesh.vertices = vertices; mesh.RecalculateBounds(); mesh.RecalculateNormals(); return mesh; } #endregion }
24.714286
112
0.701734
ef2964f426c1223b004c8c49b5314cafda68b87f
351
h
C
PushAnimaDemo/ViewController.h
rickywbl/RSTransition
e20ff1af8a51dcc70f718ee214adf2cfadf0d6e4
[ "Apache-2.0" ]
null
null
null
PushAnimaDemo/ViewController.h
rickywbl/RSTransition
e20ff1af8a51dcc70f718ee214adf2cfadf0d6e4
[ "Apache-2.0" ]
null
null
null
PushAnimaDemo/ViewController.h
rickywbl/RSTransition
e20ff1af8a51dcc70f718ee214adf2cfadf0d6e4
[ "Apache-2.0" ]
null
null
null
// // ViewController.h // PushAnimaDemo // // Created by 王保霖 on 16/5/30. // Copyright © 2016年 Ricky. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController<UIViewControllerTransitioningDelegate> @property(nonatomic,strong)UIImageView *musicImageView; @property(nonatomic,strong)UIView *bottomView; @end
18.473684
83
0.757835
58fec8b596a8f9d0d4d8b6917d317b6e3b9aa629
7,321
lua
Lua
autorepair.lua
jrowles/Vendorer
b993223fff5a5405ab53ba9da7aecf7afc8eba33
[ "MIT" ]
1
2017-03-18T12:43:27.000Z
2017-03-18T12:43:27.000Z
autorepair.lua
jrowles/Vendorer
b993223fff5a5405ab53ba9da7aecf7afc8eba33
[ "MIT" ]
24
2016-07-26T07:46:19.000Z
2022-03-22T21:01:05.000Z
autorepair.lua
jrowles/Vendorer
b993223fff5a5405ab53ba9da7aecf7afc8eba33
[ "MIT" ]
4
2018-07-10T07:09:14.000Z
2021-03-13T06:13:06.000Z
------------------------------------------------------------ -- Vendorer by Sonaza (https://sonaza.com) -- Licensed under MIT License -- See attached license text in file LICENSE ------------------------------------------------------------ local ADDON_NAME, Addon = ...; local _; function Addon:GetGuildAllowance(triggeredByUser) if(not CanGuildBankRepair() or not GetGuildInfo("player")) then return 0; end if(not triggeredByUser and not Addon.db.global.SmartAutoRepair) then return 0; end local guildBankMoney = GetGuildBankMoney(); local withdrawMoney = GetGuildBankWithdrawMoney(); if(withdrawMoney == -1) then return guildBankMoney; end return math.min(guildBankMoney, withdrawMoney); end local repairableSlots = { 1, 3, 5, 6, 7, 8, 9, 10, 16, 17, } function Addon:GetItemRepairCost() local itemRepairs = {}; for index, slotID in ipairs(repairableSlots) do local hasItem, hasCooldown, repairCost = VendorerTooltip:SetInventoryItem("player", slotID); if(hasItem and repairCost and repairCost > 0) then tinsert(itemRepairs, {slot = slotID, cost = repairCost}); end end for containerID = 0, 4 do local containerSlots = GetContainerNumSlots(containerID); if(containerSlots > 0) then for containerSlotID = 1, containerSlots do local hasCooldown, repairCost = VendorerTooltip:SetBagItem(containerID, containerSlotID); if(repairCost and repairCost > 0) then tinsert(itemRepairs, {slot = containerID .. ":" .. containerSlotID, cost = repairCost}); end end end end table.sort(itemRepairs, function(a, b) if(a == nil and b == nil) then return false end if(a == nil) then return true end if(b == nil) then return false end return a.cost < b.cost; end); return itemRepairs; end function Addon:GetContainerRepairCost() local containerRepair = {}; for index, slotID in ipairs(repairableSlots) do local hasItem, hasCooldown, repairCost = VendorerTooltip:SetInventoryItem("player", slotID); if(hasItem and repairCost and repairCost > 0) then slotRepair[slotID] = repairCost; end end return slotRepair; end function Addon:RepairSlot(slot) if(not CanMerchantRepair() or not slot) then return end if(not InRepairMode()) then ClearCursor(); ShowRepairCursor(); end if(type(slot) == "string") then local container, slot = strsplit(":", slot); PickupContainerItem(container, slot) else PickupInventoryItem(slot); end HideRepairCursor(); end function Addon:DoAutoRepair(triggeredByUser) if(not CanMerchantRepair()) then return end local totalRepairCost, shouldRepair = GetRepairAllCost(); if(totalRepairCost == 0) then return end local playerMoney, guildMoney = Addon:GetAutoRepairCost(triggeredByUser) if(playerMoney > 0 or guildMoney > 0) then Addon:AddMessage("Smart Repair:"); if(guildMoney > 0) then Addon:AddMessage("Guild: %s", GetCoinTextureString(guildMoney)); end if(playerMoney > 0) then Addon:AddMessage("Player: %s", GetCoinTextureString(playerMoney)); end end local guildRepairMoney = Addon:GetGuildAllowance(triggeredByUser); if(guildRepairMoney > 0 and totalRepairCost > guildRepairMoney) then local itemRepairCosts = Addon:GetItemRepairCost(); for index, data in ipairs(itemRepairCosts) do -- Check if you can't repair even the cheapest item if(data.cost > guildRepairMoney) then break end if(totalRepairCost > guildRepairMoney) then if(GetMoney() >= data.cost) then Addon:RepairSlot(data.slot); totalRepairCost = totalRepairCost - data.cost; else return; end else RepairAllItems(true); totalRepairCost = 0; break; end end elseif(guildRepairMoney > 0 and totalRepairCost <= guildRepairMoney) then RepairAllItems(true); totalRepairCost = 0; end if(totalRepairCost > 0 and GetMoney() >= GetRepairAllCost()) then RepairAllItems(false); end end function Addon:GetAutoRepairCost(triggeredByUser) local playerMoney = 0; local guildMoney = 0; local totalRepairCost = GetRepairAllCost(); if(totalRepairCost > 0) then local guildRepairMoney = Addon:GetGuildAllowance(triggeredByUser); if(guildRepairMoney > 0 and totalRepairCost > guildRepairMoney) then local itemRepairCosts = Addon:GetItemRepairCost(); for index, data in ipairs(itemRepairCosts) do -- Check if you can't repair even the cheapest item if(data.cost > guildRepairMoney) then break end if(totalRepairCost > guildRepairMoney) then playerMoney = playerMoney + data.cost; totalRepairCost = totalRepairCost - data.cost; else guildMoney = guildMoney + totalRepairCost; totalRepairCost = 0; break; end end elseif(guildRepairMoney > 0 and totalRepairCost <= guildRepairMoney) then guildMoney = guildMoney + totalRepairCost; totalRepairCost = 0; end if(totalRepairCost > 0) then playerMoney = playerMoney + totalRepairCost; end end return playerMoney, guildMoney; end function Addon:UPDATE_INVENTORY_DURABILITY() local repairAllCost, canRepair = GetRepairAllCost(); if(not canRepair) then SetDesaturation(VendorerSmartRepairButtonIcon, true); VendorerSmartRepairButton:Disable(); else SetDesaturation(VendorerSmartRepairButtonIcon, false); VendorerSmartRepairButton:Enable(); end end hooksecurefunc("MerchantFrame_UpdateRepairButtons", function() Addon:UpdateRepairButtons() end); function Addon:UpdateRepairButtons() if(CanMerchantRepair() and CanGuildBankRepair()) then MerchantRepairAllButton:SetPoint("BOTTOMRIGHT", MerchantFrame, "BOTTOMLEFT", 83, 29) VendorerSmartRepairButton:Show(); local repairAllCost, canRepair = GetRepairAllCost(); if(not canRepair) then SetDesaturation(VendorerSmartRepairButtonIcon, true); VendorerSmartRepairButton:Disable(); else SetDesaturation(VendorerSmartRepairButtonIcon, false); VendorerSmartRepairButton:Enable(); end else VendorerSmartRepairButton:Hide(); end end function VendorerSmartRepairButton_OnEnter(self) local playerMoney, guildMoney = Addon:GetAutoRepairCost(true); GameTooltip:SetOwner(self, "ANCHOR_RIGHT"); GameTooltip:AddLine("Smart Repair Items"); GameTooltip:AddLine("Repair items by maximizing the guild bank repairs.", 1, 1, 1); GameTooltip:AddLine(" "); if(guildMoney > 0) then GameTooltip:AddLine("The Guild Bank Covers"); SetTooltipMoney(GameTooltip, guildMoney, "GUILD_REPAIR"); end if(playerMoney > 0) then GameTooltip:AddLine("You Cover"); SetTooltipMoney(GameTooltip, playerMoney, "GUILD_REPAIR"); end if(playerMoney == 0 and guildMoney == 0) then GameTooltip:AddLine(" "); GameTooltip:AddLine("All of your items have full durability."); end GameTooltip:AddLine(" "); local amount = GetGuildBankWithdrawMoney(); local guildBankMoney = GetGuildBankMoney(); if ( amount == -1 ) then -- Guild leader shows full guild bank amount amount = guildBankMoney; else amount = min(amount, guildBankMoney); end GameTooltip:AddLine(GUILDBANK_REPAIR, nil, nil, nil, true); SetTooltipMoney(GameTooltip, amount, "GUILD_REPAIR"); GameTooltip:Show(); end function VendorerSmartRepairButton_OnLeave(self) GameTooltip:Hide(); end function VendorerSmartRepairButton_OnClick(self) Addon:DoAutoRepair(true); GameTooltip:Hide(); VendorerSmartRepairButton_OnEnter(self); end
28.049808
96
0.73296
a11e7a9a500b5c14700a4d1cca4d8067f6b97e42
242
lua
Lua
Mods/LeaderLib_543d653f-446c-43d8-8916-54670ce24dd9/Story/RawFiles/Lua/Shared/Classes/_Init.lua
LaughingLeader-DOS2-Mods/LeaderLib
2a7ba51839eefe7bdc1dec15861fd33c1fdfafa1
[ "MIT" ]
5
2018-04-17T19:50:44.000Z
2020-08-31T05:49:01.000Z
Mods/LeaderLib_543d653f-446c-43d8-8916-54670ce24dd9/Story/RawFiles/Lua/Shared/Classes/_Init.lua
LaughingLeader-DOS2-Mods/LeaderLib
2a7ba51839eefe7bdc1dec15861fd33c1fdfafa1
[ "MIT" ]
2
2019-10-18T15:04:28.000Z
2020-04-26T14:59:00.000Z
Mods/LeaderLib_543d653f-446c-43d8-8916-54670ce24dd9/Story/RawFiles/Lua/Shared/Classes/_Init.lua
LaughingLeader-DOS2-Mods/LeaderLib
2a7ba51839eefe7bdc1dec15861fd33c1fdfafa1
[ "MIT" ]
6
2018-04-17T19:37:47.000Z
2021-11-17T18:02:10.000Z
Ext.Require("Shared/Classes/TranslatedString.lua") Ext.Require("Shared/Classes/MessageData.lua") Ext.Require("Shared/Classes/ClientData.lua") Ext.Require("Shared/Classes/DeltaModGroup.lua") Ext.Require("Shared/Classes/ModSettingsClasses.lua")
48.4
52
0.818182
23afb5e8ff5b9c9bc54712869b6295e57ceb63e8
316
js
JavaScript
frontend/src/js/components/UtilComponents/ProgressAnimation.js
guardian/giant
0db27dc28468e92574adfdb1d4089ce1cf25879e
[ "Apache-2.0" ]
22
2021-05-14T17:22:16.000Z
2022-03-29T07:27:02.000Z
frontend/src/js/components/UtilComponents/ProgressAnimation.js
guardian/giant
0db27dc28468e92574adfdb1d4089ce1cf25879e
[ "Apache-2.0" ]
15
2021-05-25T07:50:45.000Z
2022-03-28T15:57:18.000Z
frontend/src/js/components/UtilComponents/ProgressAnimation.js
guardian/giant
0db27dc28468e92574adfdb1d4089ce1cf25879e
[ "Apache-2.0" ]
null
null
null
import React from 'react'; export function ProgressAnimation() { return <div className='progress-animation'> <div className='progress-animation__cube cube1'></div> <div className='progress-animation__cube cube2'></div> <div className='progress-animation__cube cube3'></div> </div>; }
35.111111
62
0.689873
38d34ce9f5c25dc8b7bd8e6752479275f402fdd1
357
dart
Dart
lib/models/china_chart_model.dart
umaersharief/coronavirus_tracker
add7854e471e135df95f902ea7381a619b997cfa
[ "CC0-1.0" ]
null
null
null
lib/models/china_chart_model.dart
umaersharief/coronavirus_tracker
add7854e471e135df95f902ea7381a619b997cfa
[ "CC0-1.0" ]
null
null
null
lib/models/china_chart_model.dart
umaersharief/coronavirus_tracker
add7854e471e135df95f902ea7381a619b997cfa
[ "CC0-1.0" ]
null
null
null
import 'package:charts_flutter/flutter.dart' as charts; import 'package:flutter/foundation.dart'; //import 'model.dart'; class ChinaChartModel { final DateTime reportDate; final int mainlandChina; final charts.Color barColor; ChinaChartModel( {@required this.reportDate, @required this.mainlandChina, @required this.barColor}); }
25.5
55
0.742297
b867680b7aa463a442aa8de970fdb12a3d45c303
1,506
h
C
src/mxml/dom/DirectionType.h
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
18
2016-05-22T00:55:28.000Z
2021-03-29T08:44:23.000Z
src/mxml/dom/DirectionType.h
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
6
2017-05-17T13:20:09.000Z
2018-10-22T20:00:57.000Z
src/mxml/dom/DirectionType.h
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
14
2016-05-12T22:54:34.000Z
2021-10-19T12:43:16.000Z
// Copyright © 2016 Venture Media Labs. // // This file is part of mxml. The full mxml copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #pragma once #include "Node.h" #include "Optional.h" #include "Position.h" #include <string> namespace mxml { namespace dom { class DirectionType : public Node { public: DirectionType() = default; virtual ~DirectionType() = default; /** Return true if this direction type has start and stop elements. */ virtual bool span() const = 0; public: Position position; }; class Dynamics : public DirectionType { public: const std::string& string() const { return _string; } void setString(const std::string& string) { _string = string; } bool span() const { return false; } private: std::string _string; }; class Words : public DirectionType { public: const std::string& contents() const { return _contents; } void setContents(const std::string& contents) { _contents = contents; } bool span() const { return false; } private: std::string _contents; }; class Segno : public DirectionType { public: bool span() const { return false; } }; class Coda : public DirectionType { public: bool span() const { return false; } }; } // namespace dom } // namespace mxml
19.063291
77
0.634794
a424884a6bc27a4645cd1f9325a6291e71ed94d5
1,325
php
PHP
shtoDege.php
DionIslami1/UMAB-Moduli-Administratorit
34875d1210f3fefbc07e04b1d3a1a79f40b8a9de
[ "CC-BY-3.0" ]
null
null
null
shtoDege.php
DionIslami1/UMAB-Moduli-Administratorit
34875d1210f3fefbc07e04b1d3a1a79f40b8a9de
[ "CC-BY-3.0" ]
null
null
null
shtoDege.php
DionIslami1/UMAB-Moduli-Administratorit
34875d1210f3fefbc07e04b1d3a1a79f40b8a9de
[ "CC-BY-3.0" ]
null
null
null
<html> <head> <title>Moduli Administraotirt</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <link rel="stylesheet" href="assets/css/main.css" /> <noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript> </head> <body> <?php //including the database connection file include_once("konfig.php"); if(isset($_POST['shtoDege'])) { $dega = $_POST['dega']; // checking empty fields if(empty($dega)) { if(empty($dega)) { echo "<font color='red'>Fusha DEGA eshte jo e mbushur.</font><br/>"; } //link to the previous pMbiemri echo "<br/><a href='javascript:self.history.back();'>Kthehu Mbrapa</a>"; } else { // if all the fields are filled (not empty) //insert data to database $rezultat = mysqli_query($kon,"CALL shtoDega('$dega')"); //display success message echo "<script> setTimeout(function(){ window.location.href = 'ballina.php'; }, 5000); </script>"; echo"<p><b> E dhena eshte duke u regjistruar ne sistem. Ju lutem pritni 5 sekonda. <b></p>"; //echo "<font color='green'>Data added successfully."; //echo "<br/><a href='ballina.php'>View rezultat</a>"; } } ?> </body> </html>
27.604167
98
0.603774
45c52f54c79c285fdecfd0840c1c9b98b51d438b
17,067
py
Python
Lib/site-packages/qutebrowser/misc/crashsignal.py
fochoao/cpython
3dc84b260e5bced65ebc2c45c40c8fa65f9b5aa9
[ "bzip2-1.0.6", "0BSD" ]
null
null
null
Lib/site-packages/qutebrowser/misc/crashsignal.py
fochoao/cpython
3dc84b260e5bced65ebc2c45c40c8fa65f9b5aa9
[ "bzip2-1.0.6", "0BSD" ]
20
2021-05-03T18:02:23.000Z
2022-03-12T12:01:04.000Z
Lib/site-packages/qutebrowser/misc/crashsignal.py
fochoao/cpython
3dc84b260e5bced65ebc2c45c40c8fa65f9b5aa9
[ "bzip2-1.0.6", "0BSD" ]
null
null
null
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # qutebrowser is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see <https://www.gnu.org/licenses/>. """Handlers for crashes and OS signals.""" import os import os.path import sys import bdb import pdb # noqa: T002 import signal import argparse import functools import threading import faulthandler import dataclasses from typing import TYPE_CHECKING, Optional, MutableMapping, cast, List from PyQt5.QtCore import (pyqtSlot, qInstallMessageHandler, QObject, QSocketNotifier, QTimer, QUrl) from PyQt5.QtWidgets import QApplication from qutebrowser.api import cmdutils from qutebrowser.misc import earlyinit, crashdialog, ipc, objects from qutebrowser.utils import usertypes, standarddir, log, objreg, debug, utils from qutebrowser.qt import sip if TYPE_CHECKING: from qutebrowser.misc import quitter @dataclasses.dataclass class ExceptionInfo: """Information stored when there was an exception.""" pages: List[List[str]] cmd_history: List[str] objects: str crash_handler = cast('CrashHandler', None) class CrashHandler(QObject): """Handler for crashes, reports and exceptions. Attributes: _app: The QApplication instance. _quitter: The Quitter instance. _args: The argparse namespace. _crash_dialog: The CrashDialog currently being shown. _crash_log_file: The file handle for the faulthandler crash log. _crash_log_data: Crash data read from the previous crash log. is_crashing: Used by mainwindow.py to skip confirm questions on crashes. """ def __init__(self, *, app, quitter, args, parent=None): super().__init__(parent) self._app = app self._quitter = quitter self._args = args self._crash_log_file = None self._crash_log_data = None self._crash_dialog = None self.is_crashing = False def activate(self): """Activate the exception hook.""" sys.excepthook = self.exception_hook def init_faulthandler(self): """Handle a segfault from a previous run and set up faulthandler.""" logname = os.path.join(standarddir.data(), 'crash.log') try: # First check if an old logfile exists. if os.path.exists(logname): with open(logname, 'r', encoding='ascii') as f: self._crash_log_data = f.read() os.remove(logname) self._init_crashlogfile() else: # There's no log file, so we can use this to display crashes to # the user on the next start. self._init_crashlogfile() except OSError: log.init.exception("Error while handling crash log file!") self._init_crashlogfile() def display_faulthandler(self): """If there was data in the crash log file, display a dialog.""" assert not self._args.no_err_windows if self._crash_log_data: # Crashlog exists and has data in it, so something crashed # previously. self._crash_dialog = crashdialog.FatalCrashDialog( self._args.debug, self._crash_log_data) self._crash_dialog.show() self._crash_log_data = None def _recover_pages(self, forgiving=False): """Try to recover all open pages. Called from exception_hook, so as forgiving as possible. Args: forgiving: Whether to ignore exceptions. Return: A list containing a list for each window, which in turn contain the opened URLs. """ pages = [] for win_id in objreg.window_registry: win_pages = [] tabbed_browser = objreg.get('tabbed-browser', scope='window', window=win_id) for tab in tabbed_browser.widgets(): try: urlstr = tab.url().toString( QUrl.RemovePassword | QUrl.FullyEncoded) if urlstr: win_pages.append(urlstr) except Exception: if forgiving: log.destroy.exception("Error while recovering tab") else: raise pages.append(win_pages) return pages def _init_crashlogfile(self): """Start a new logfile and redirect faulthandler to it.""" logname = os.path.join(standarddir.data(), 'crash.log') try: self._crash_log_file = open(logname, 'w', encoding='ascii') except OSError: log.init.exception("Error while opening crash log file!") else: earlyinit.init_faulthandler(self._crash_log_file) @cmdutils.register(instance='crash-handler') def report(self, info=None, contact=None): """Report a bug in qutebrowser. Args: info: Information about the bug report. If given, no report dialog shows up. contact: Contact information for the report. """ pages = self._recover_pages() cmd_history = objreg.get('command-history')[-5:] all_objects = debug.get_all_objects() self._crash_dialog = crashdialog.ReportDialog(pages, cmd_history, all_objects) if info is None: self._crash_dialog.show() else: self._crash_dialog.report(info=info, contact=contact) @pyqtSlot() def shutdown(self): self.destroy_crashlogfile() def destroy_crashlogfile(self): """Clean up the crash log file and delete it.""" if self._crash_log_file is None: return # We use sys.__stderr__ instead of sys.stderr here so this will still # work when sys.stderr got replaced, e.g. by "Python Tools for Visual # Studio". if sys.__stderr__ is not None: faulthandler.enable(sys.__stderr__) else: faulthandler.disable() # type: ignore[unreachable] try: self._crash_log_file.close() os.remove(self._crash_log_file.name) except OSError: log.destroy.exception("Could not remove crash log!") def _get_exception_info(self): """Get info needed for the exception hook/dialog. Return: An ExceptionInfo object. """ try: pages = self._recover_pages(forgiving=True) except Exception as e: log.destroy.exception("Error while recovering pages: {}".format(e)) pages = [] try: cmd_history = objreg.get('command-history')[-5:] except Exception as e: log.destroy.exception("Error while getting history: {}".format(e)) cmd_history = [] try: all_objects = debug.get_all_objects() except Exception: log.destroy.exception("Error while getting objects") all_objects = "" return ExceptionInfo(pages, cmd_history, all_objects) def _handle_early_exits(self, exc): """Handle some special cases for the exception hook. Return value: True: Exception hook should be aborted. False: Continue handling exception. """ exctype, _excvalue, tb = exc if not self._quitter.quit_status['crash']: log.misc.error("ARGH, there was an exception while the crash " "dialog is already shown:", exc_info=exc) return True log.misc.error("Uncaught exception", exc_info=exc) is_ignored_exception = (exctype is bdb.BdbQuit or not issubclass(exctype, Exception)) if 'pdb-postmortem' in objects.debug_flags: if tb is None: pdb.set_trace() # noqa: T100 else: pdb.post_mortem(tb) if is_ignored_exception or 'pdb-postmortem' in objects.debug_flags: # pdb exit, KeyboardInterrupt, ... sys.exit(usertypes.Exit.exception) if threading.current_thread() != threading.main_thread(): log.misc.error("Ignoring exception outside of main thread... " "Please report this as a bug.") return True return False def exception_hook(self, exctype, excvalue, tb): """Handle uncaught python exceptions. It'll try very hard to write all open tabs to a file, and then exit gracefully. """ exc = (exctype, excvalue, tb) if self._handle_early_exits(exc): return self._quitter.quit_status['crash'] = False info = self._get_exception_info() if ipc.server is not None: try: ipc.server.ignored = True except Exception: log.destroy.exception("Error while ignoring ipc") try: self._app.lastWindowClosed.disconnect( self._quitter.on_last_window_closed) except TypeError: log.destroy.exception("Error while preventing shutdown") self.is_crashing = True self._app.closeAllWindows() if self._args.no_err_windows: crashdialog.dump_exception_info(exc, info.pages, info.cmd_history, info.objects) else: self._crash_dialog = crashdialog.ExceptionCrashDialog( self._args.debug, info.pages, info.cmd_history, exc, info.objects) ret = self._crash_dialog.exec() if ret == crashdialog.Result.restore: self._quitter.restart(info.pages) # We might risk a segfault here, but that's better than continuing to # run in some undefined state, so we only do the most needed shutdown # here. qInstallMessageHandler(None) self.destroy_crashlogfile() sys.exit(usertypes.Exit.exception) def raise_crashdlg(self): """Raise the crash dialog if one exists.""" if self._crash_dialog is not None: self._crash_dialog.raise_() class SignalHandler(QObject): """Handler responsible for handling OS signals (SIGINT, SIGTERM, etc.). Attributes: _app: The QApplication instance. _quitter: The Quitter instance. _activated: Whether activate() was called. _notifier: A QSocketNotifier used for signals on Unix. _timer: A QTimer used to poll for signals on Windows. _orig_handlers: A {signal: handler} dict of original signal handlers. _orig_wakeup_fd: The original wakeup filedescriptor. """ def __init__(self, *, app, quitter, parent=None): super().__init__(parent) self._app = app self._quitter = quitter self._notifier = None self._timer = usertypes.Timer(self, 'python_hacks') self._orig_handlers: MutableMapping[int, 'signal._HANDLER'] = {} self._activated = False self._orig_wakeup_fd: Optional[int] = None def activate(self): """Set up signal handlers. On Windows this uses a QTimer to periodically hand control over to Python so it can handle signals. On Unix, it uses a QSocketNotifier with os.set_wakeup_fd to get notified. """ self._orig_handlers[signal.SIGINT] = signal.signal( signal.SIGINT, self.interrupt) self._orig_handlers[signal.SIGTERM] = signal.signal( signal.SIGTERM, self.interrupt) if utils.is_posix and hasattr(signal, 'set_wakeup_fd'): # pylint: disable=import-error,no-member,useless-suppression import fcntl read_fd, write_fd = os.pipe() for fd in [read_fd, write_fd]: flags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) self._notifier = QSocketNotifier(cast(sip.voidptr, read_fd), QSocketNotifier.Read, self) self._notifier.activated.connect( # type: ignore[attr-defined] self.handle_signal_wakeup) self._orig_wakeup_fd = signal.set_wakeup_fd(write_fd) # pylint: enable=import-error,no-member,useless-suppression else: self._timer.start(1000) self._timer.timeout.connect(lambda: None) self._activated = True def deactivate(self): """Deactivate all signal handlers.""" if not self._activated: return if self._notifier is not None: assert self._orig_wakeup_fd is not None self._notifier.setEnabled(False) rfd = self._notifier.socket() wfd = signal.set_wakeup_fd(self._orig_wakeup_fd) os.close(int(rfd)) os.close(wfd) for sig, handler in self._orig_handlers.items(): signal.signal(sig, handler) self._timer.stop() self._activated = False @pyqtSlot() def handle_signal_wakeup(self): """Handle a newly arrived signal. This gets called via self._notifier when there's a signal. Python will get control here, so the signal will get handled. """ assert self._notifier is not None log.destroy.debug("Handling signal wakeup!") self._notifier.setEnabled(False) read_fd = self._notifier.socket() try: os.read(int(read_fd), 1) except OSError: log.destroy.exception("Failed to read wakeup fd.") self._notifier.setEnabled(True) def _log_later(self, *lines): """Log the given text line-wise with a QTimer.""" for line in lines: QTimer.singleShot(0, functools.partial(log.destroy.info, line)) def interrupt(self, signum, _frame): """Handler for signals to gracefully shutdown (SIGINT/SIGTERM). This calls shutdown and remaps the signal to call interrupt_forcefully the next time. """ signal.signal(signal.SIGINT, self.interrupt_forcefully) signal.signal(signal.SIGTERM, self.interrupt_forcefully) # Signals can arrive anywhere, so we do this in the main thread self._log_later("SIGINT/SIGTERM received, shutting down!", "Do the same again to forcefully quit.") QTimer.singleShot(0, functools.partial( self._quitter.shutdown, 128 + signum)) def interrupt_forcefully(self, signum, _frame): """Interrupt forcefully on the second SIGINT/SIGTERM request. This skips our shutdown routine and calls QApplication:exit instead. It then remaps the signals to call self.interrupt_really_forcefully the next time. """ signal.signal(signal.SIGINT, self.interrupt_really_forcefully) signal.signal(signal.SIGTERM, self.interrupt_really_forcefully) # Signals can arrive anywhere, so we do this in the main thread self._log_later("Forceful quit requested, goodbye cruel world!", "Do the same again to quit with even more force.") QTimer.singleShot(0, functools.partial(self._app.exit, 128 + signum)) def interrupt_really_forcefully(self, signum, _frame): """Interrupt with even more force on the third SIGINT/SIGTERM request. This doesn't run *any* Qt cleanup and simply exits via Python. It will most likely lead to a segfault. """ print("WHY ARE YOU DOING THIS TO ME? :(") sys.exit(128 + signum) def init(q_app: QApplication, args: argparse.Namespace, quitter: 'quitter.Quitter') -> None: """Initialize crash/signal handlers.""" global crash_handler crash_handler = CrashHandler( app=q_app, quitter=quitter, args=args, parent=q_app) objreg.register('crash-handler', crash_handler, command_only=True) crash_handler.activate() quitter.shutting_down.connect(crash_handler.shutdown) signal_handler = SignalHandler(app=q_app, quitter=quitter, parent=q_app) signal_handler.activate() quitter.shutting_down.connect(signal_handler.deactivate)
36.861771
79
0.619968
144b5eba995f2c2fdb6e83e81596566f1ba0e120
5,242
ts
TypeScript
libs/packages/components/src/lib/search/search.component.ts
GSA/sam-design-system
3da5561d8386b89c9562a556c6d9d5a9cc6fb705
[ "CC0-1.0" ]
7
2019-02-19T18:02:01.000Z
2021-07-28T15:45:55.000Z
libs/packages/components/src/lib/search/search.component.ts
GSA/sam-design-system
3da5561d8386b89c9562a556c6d9d5a9cc6fb705
[ "CC0-1.0" ]
198
2019-07-29T18:41:31.000Z
2022-03-31T17:15:46.000Z
libs/packages/components/src/lib/search/search.component.ts
GSA/sam-design-system
3da5561d8386b89c9562a556c6d9d5a9cc6fb705
[ "CC0-1.0" ]
15
2019-10-31T20:18:07.000Z
2021-12-16T17:59:55.000Z
import { Component, ViewChild, ElementRef, Input, AfterViewInit, forwardRef, ChangeDetectionStrategy, ChangeDetectorRef, Output, EventEmitter, } from '@angular/core'; import { FocusMonitor } from '@angular/cdk/a11y'; import { ViewportRuler } from '@angular/cdk/overlay'; import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms'; export class SearchSettings { public placeholder = 'Search'; public ariaLabel? = 'Search'; public size?: string; public inputClass?: string; public parentSelector?: string; public id?: string; public dropdown?: any = { id: 'searchOptions', placeholder: '-Select-', options: [], inverse: false, }; public isSuffixSearchIcon?: boolean = false; } @Component({ selector: 'sds-search', templateUrl: 'search.component.html', styleUrls: ['search.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => SdsSearchComponent), multi: true, }, ], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SdsSearchComponent implements AfterViewInit, ControlValueAccessor { @ViewChild('inputEl', { read: ElementRef, static: false }) inputEl: ElementRef; @ViewChild('selectEl', { read: ElementRef, static: false }) selectEl: ElementRef; @ViewChild('buttonEl', { read: ElementRef, static: false }) buttonEl: ElementRef; @Input() searchSettings: SearchSettings = new SearchSettings(); @Output() submit: EventEmitter<{ searchText: string }> = new EventEmitter( null ); model: any = {}; inputState = { initial: { visible: undefined }, visible: undefined, }; private _onChange = (_: any) => {}; private _onTouched = () => {}; constructor( private cd: ChangeDetectorRef, private focusMonitor: FocusMonitor, private viewportRuler: ViewportRuler ) {} ngAfterViewInit() { this.inputState.initial.visible = this.isInputVisible(); this.inputState.visible = this.inputState.initial.visible; this.viewportRuler.change(0).subscribe(() => { this.inputState.initial.visible = this.isInputVisible(); this.inputState.visible = this.inputState.initial.visible; }); } hasDropdown() { if ( this.searchSettings && this.searchSettings.dropdown && this.searchSettings.dropdown.options && this.searchSettings.dropdown.options.length ) { return true; } else { return false; } } handleClick(event) { event.preventDefault(); if (!this.inputState.visible) { this.setInputVisibleStyles(); this.focusMonitor.focusVia(this.inputEl, 'program'); } else if (this.inputEl || this.selectEl) { this.submit.emit(this.model); } } writeValueToModel() { this.model.searchText = this.inputEl ? this.inputEl.nativeElement.value : ''; if (this.selectEl && this.selectEl.nativeElement.value) { this.model.searchCategory = this.selectEl.nativeElement.value; } this._onChange(Object.assign({}, this.model)); } writeValue(value: any) { if (value && this.model !== value) { this.model = value; this.cd.markForCheck(); } else { this.model = {}; this.cd.markForCheck(); } } registerOnTouched(fn: any) { this._onTouched = fn; } registerOnChange(fn: any): void { this._onChange = fn; } isInputVisible(): boolean { return this.inputEl.nativeElement.getBoundingClientRect().width ? true : false; } setInputVisibleStyles() { const inputWidth = this.calculateInputWidth(); this.inputEl.nativeElement.style.setProperty( 'display', 'block', 'important' ); this.inputEl.nativeElement.style.position = 'absolute'; this.inputEl.nativeElement.style.left = `-${inputWidth}px`; this.inputEl.nativeElement.style.setProperty( 'width', `${inputWidth}px`, 'important' ); this.inputState.visible = true; } removeInputVisibleStyles() { this.inputEl.nativeElement.style.display = ''; this.inputEl.nativeElement.style.position = ''; this.inputEl.nativeElement.style.left = ''; this.inputEl.nativeElement.style.width = ''; this.inputState.visible = false; } focusChange() { if (!this.inputState.initial.visible) { this.removeInputVisibleStyles(); } } calculateInputWidth(): number { const leftPadding = 20; const buttonElement = this.buttonEl.nativeElement; const inputElement = this.inputEl.nativeElement; const rightPosition = buttonElement.getBoundingClientRect().left; const leftPosition = this.searchSettings.parentSelector ? inputElement .closest(this.searchSettings.parentSelector) .getBoundingClientRect().left : 0; return Math.floor(rightPosition - leftPosition - leftPadding); } getClass() { const cls = this.searchSettings && this.searchSettings.size === 'large' ? 'usa-search--big' : 'usa-search--small'; return this.searchSettings.dropdown && this.searchSettings.dropdown.inverse ? `${cls} sds-inverse` : cls; } clearInput(ev) { this.inputEl.nativeElement.value = ''; this.writeValueToModel(); } }
27.302083
80
0.663106
ef521ec333897d4a4cfd080026eb5c1dc0934aae
395
h
C
storage/source/net/message/storage/mirroring/StorageResyncStartedMsgEx.h
TomatoYoung/beegfs
edf287940175ecded493183209719d2d90d45374
[ "BSD-3-Clause" ]
null
null
null
storage/source/net/message/storage/mirroring/StorageResyncStartedMsgEx.h
TomatoYoung/beegfs
edf287940175ecded493183209719d2d90d45374
[ "BSD-3-Clause" ]
null
null
null
storage/source/net/message/storage/mirroring/StorageResyncStartedMsgEx.h
TomatoYoung/beegfs
edf287940175ecded493183209719d2d90d45374
[ "BSD-3-Clause" ]
null
null
null
#ifndef STORAGERESYNCSTARTEDMSGEX_H_ #define STORAGERESYNCSTARTEDMSGEX_H_ #include <common/net/message/storage/mirroring/StorageResyncStartedMsg.h> class StorageResyncStartedMsgEx : public StorageResyncStartedMsg { public: virtual bool processIncoming(ResponseContext& ctx); private: void deleteMirrorSessions(uint16_t targetID); }; #endif /*STORAGERESYNCSTARTEDMSGEX_H_*/
24.6875
73
0.810127
134bcea13f12f1d5e4cd4c44597dc75759cd8c23
3,411
h
C
parse/parse.h
mniip/nanohc
162660d7447b370a26b6ad79f816a41a00aa5bd9
[ "BSD-3-Clause" ]
null
null
null
parse/parse.h
mniip/nanohc
162660d7447b370a26b6ad79f816a41a00aa5bd9
[ "BSD-3-Clause" ]
null
null
null
parse/parse.h
mniip/nanohc
162660d7447b370a26b6ad79f816a41a00aa5bd9
[ "BSD-3-Clause" ]
null
null
null
#ifndef PARSER_H_ #define PARSER_H_ #include "lex.h" /* Tags for the AST (in parentheses the children values are listed) */ enum ast_tag { /* Expressions: */ /* Function application (function, arg) */ AST_APPLY, /* Not-yet-associated operator (operator, arg1, arg2) */ AST_UOPERATOR, /* Parenthesized expression (expr) */ AST_PARENS, /* Operator application (operator, arg1, arg2) */ AST_OPERATOR, /* Operator sections (operator, arg) */ AST_LSECTION, AST_RSECTION, /* Variable (qualname) */ AST_VAR, /* Constructor (qualname) */ AST_CON, /* Numeric literal (data is a pointer to an integer) */ AST_NUMLIT, /* Char literal (data is a pointer to an integer value of the char) */ AST_CHARLIT, /* String literal (data is a pointer to the string) */ AST_STRLIT, /* Type specification (expr, type) */ AST_CAST, /* Lambda (patlist, expr) */ AST_LAMBDA, /* If (cond, expr1, expr2) */ AST_IF, /* Case (scrutinee, branchlist) */ AST_CASE, /* Let (decllist, expr) */ AST_LET, /* Do (stmtlist) */ AST_DO, /* Patterns: */ /* Constructor pattern (qualname, patlist) */ AST_PAT_CON, /* As-pattern (name, pat) */ AST_PAT_AS, /* Variable pattern (name) */ AST_PAT_VAR, /* Numeric literal pattern (data is a pointer to an integer) */ AST_PAT_NUMLIT, /* Char literal pattern (data is a pointer to an integer value of the char) */ AST_PAT_CHARLIT, /* Sgtring literal pattern (data is a pointer to the string) */ AST_PAT_STRLIT, /* Ignored pattern */ AST_PAT_NONE, /* Guards: */ /* Pattern guard (pat, expr) */ AST_GUARD_PAT, /* Let-guard (decllist) */ AST_GUARD_LET, /* Boolean guard (expr) */ AST_GUARD_BOOL, /* Statements: */ /* Do-statement (expr) */ AST_STMT, /* Do-statement with bind (pat, expr) */ AST_STMT_BIND, /* Do-statement let (decllist) */ AST_STMT_LET, /* Declarations: */ /* A value binding (name, patlist, caselist) */ AST_BINDING, /* A type signature (name, type) */ AST_HAS_TYPE, /* A type synonym declaration (name, namelist, type) */ AST_TYPE, /* A datatype declaration (name, namelist, constrlist) */ AST_DATA, /* A class declaration (name, namelist, decllist) */ AST_CLASS, /* An instance declaration (qualname, typelist, decllist) */ AST_INSTANCE, /* A fixity declaration (qualname) (data is pointer to an integer) */ AST_INFIX, AST_INFIXL, AST_INFIXR, /* Types: */ /* Type application (fun, arg) */ AST_TYPE_APPLY, /* Arrow type () */ AST_TYPE_ARROW, /* Type constructor (qualname) */ AST_TYPE_CON, /* Type variable (name) */ AST_TYPE_VAR, /* Misc: */ /* An identifier name (data is a pointer to an interned pointer to a name */ AST_NAME, /* A possibly qualified name (data pointer is a pointer to a qualname) */ AST_QUALNAME, /* Tuple (data is pointer to integer which is arity) */ AST_TUPLE, /* Case branch (pat, caselist) */ AST_BRANCH, /* A guarded expression (guardlist, expr) */ AST_SWITCH, /* A datatype constructor declaration (name, typelist) */ AST_CONSTR, /* Lists: */ /* () */ AST_NIL, /* (head, tail) */ AST_CONS }; #define MAX_DEPTH 0x1000 typedef struct parser { lexer l; size_t depth; } parser; extern void parser_new(parser *, char const *data); extern void parser_eof(parser *); extern void parser_free(parser *); extern tree *parse_topdecls(parser *); extern tree *parse_type(parser *); extern tree *parse_exp(parser *); extern void dump_ast(tree *, size_t); #endif
23.524138
77
0.682205
ae8d195d2053bed2b7cc823965f7f2712c77b3ea
1,520
cs
C#
src/JsonKnownTypes/JsonDiscriminatorAttribute.cs
ibebbs/JsonKnownTypes
9e47bdd56d3232cf377888349495bd96f3d7b189
[ "MIT" ]
null
null
null
src/JsonKnownTypes/JsonDiscriminatorAttribute.cs
ibebbs/JsonKnownTypes
9e47bdd56d3232cf377888349495bd96f3d7b189
[ "MIT" ]
null
null
null
src/JsonKnownTypes/JsonDiscriminatorAttribute.cs
ibebbs/JsonKnownTypes
9e47bdd56d3232cf377888349495bd96f3d7b189
[ "MIT" ]
null
null
null
using System; namespace JsonKnownTypes { /// <summary> /// Manage discriminator settings /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] public class JsonDiscriminatorAttribute : Attribute { /// <summary> /// Discriminator field name in json representation /// </summary> public string Name { get; set; } /// <summary> /// If no descriminator for provided for a given type (i.e. through the <see cref="JsonKnownThisTypeAttribute"/> /// attribute then, if this setting is true then the <see cref="JsonKnownTypesConverter{T}"/> will look for /// a descriminator value from base types. /// </summary> /// <remarks> /// To use this setting effectively, <see cref="AddAutoDiscriminators"/> should be false and /// derived types should not be decorated with <see cref="JsonKnownThisTypeAttribute"/> /// </remarks> public bool UseBaseTypeDescriminators { get => UseBaseTypeDescriminatorsValue != false; set => UseBaseTypeDescriminatorsValue = value; } internal bool? UseBaseTypeDescriminatorsValue; /// <summary> /// Use class name as discriminator if JsonKnown attribute didn't add /// </summary> public bool AddAutoDiscriminators { get => AutoJson != false; set => AutoJson = value; } internal bool? AutoJson; } }
33.777778
120
0.6125
5878eef7669c057fcb6e9c2adf828e2cca4d70d6
862
swift
Swift
Example/Pods/Sluthware/Sluthware/Classes/Foundation/NSObjectProtocol+NSKeyValueObservation.swift
patsluth/KeyPath-Theme-Manager
43f232191f3d797610c2f2bd5f76d5156907c852
[ "MIT" ]
1
2020-03-17T08:04:14.000Z
2020-03-17T08:04:14.000Z
Example/Pods/Sluthware/Sluthware/Classes/Foundation/NSObjectProtocol+NSKeyValueObservation.swift
patsluth/KeyPath-Theme-Manager
43f232191f3d797610c2f2bd5f76d5156907c852
[ "MIT" ]
null
null
null
Example/Pods/Sluthware/Sluthware/Classes/Foundation/NSObjectProtocol+NSKeyValueObservation.swift
patsluth/KeyPath-Theme-Manager
43f232191f3d797610c2f2bd5f76d5156907c852
[ "MIT" ]
null
null
null
// // NSObjectProtocol+NSKeyValueObservation.swift // Sluthware // // Created by Pat Sluth on 2017-11-28. // Copyright © 2017 patsluth. All rights reserved. // import Foundation import ObjectiveC fileprivate var _keyValueObservations = Selector(("_keyValueObservations")) public extension NSObjectProtocol where Self: NSObject { var keyValueObservations: Set<NSKeyValueObservation> { get { if let keyValueObservations = objc_getAssociatedObject(self, &_keyValueObservations) as? Set<NSKeyValueObservation> { return keyValueObservations } else { self.keyValueObservations = Set<NSKeyValueObservation>() return self.keyValueObservations } } set { objc_setAssociatedObject(self, &_keyValueObservations, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } }
19.155556
91
0.734339
1a8c70801b227da912d563669e63a937d187d2eb
13,135
cs
C#
test/Cuemon.Runtime.Caching.Tests/SlimMemoryCacheTest.cs
gimlichael/cuemoncore
7750a3bd67200924b9cfa4dddccf54c765453c24
[ "MIT" ]
11
2018-05-30T05:46:59.000Z
2020-04-30T11:44:57.000Z
test/Cuemon.Runtime.Caching.Tests/SlimMemoryCacheTest.cs
gimlichael/cuemoncore
7750a3bd67200924b9cfa4dddccf54c765453c24
[ "MIT" ]
4
2021-02-28T00:24:26.000Z
2021-04-01T17:58:20.000Z
test/Cuemon.Runtime.Caching.Tests/SlimMemoryCacheTest.cs
gimlichael/cuemoncore
7750a3bd67200924b9cfa4dddccf54c765453c24
[ "MIT" ]
3
2018-08-29T15:19:47.000Z
2019-10-14T20:47:39.000Z
using System; using System.Collections.Concurrent; using System.Linq; using System.Threading; using System.Threading.Tasks; using Cuemon.Extensions.Xunit.Hosting; using Cuemon.Runtime.Caching.Assets; using Microsoft.Extensions.DependencyInjection; using Xunit; using Xunit.Abstractions; using Xunit.Priority; namespace Cuemon.Runtime.Caching { [TestCaseOrderer(PriorityOrderer.Name, PriorityOrderer.Assembly)] public class SlimMemoryCacheTest : HostTest<HostFixture> { private readonly SlimMemoryCache _cache; private readonly SlimMemoryCacheOptions _cacheOptions = new SlimMemoryCacheOptions(); private const string Sliding30Namespace = "Sliding30"; private const string Absolute30Namespace = "Absolute30"; private const string Dependency30Namespace = "Dependency30"; private const string Sliding60Namespace = "Sliding60"; private const string Absolute60Namespace = "Absolute60"; private const string Dependency60Namespace = "Dependency60"; private const int NumberOfItemsToCache = 1000; public SlimMemoryCacheTest(HostFixture hostFixture, ITestOutputHelper output = null) : base(hostFixture, output) { _cache = hostFixture.ServiceProvider.GetRequiredService<SlimMemoryCache>(); } [Fact] public void Add_ShouldBeThreadSafeWhenAddingSameKeyInParallel() { var items = NumberOfItemsToCache; var key = "cuemon"; Parallel.For(0, items, i => { var nw = Guid.NewGuid(); if (_cache.Add(key, nw, DateTime.MaxValue)) { Assert.Equal(nw, _cache[key]); } else { Assert.NotEqual(nw, _cache[key]); } }); Assert.Equal(1, _cache.Count()); Assert.Equal(1, _cache.ToList().Count); _cache.Remove(key); Assert.Equal(0, _cache.Count()); Assert.Equal(0, _cache.ToList().Count); } [Fact] public void Add_ShouldUpdateUsingPropertyIndexer() { var key = "cuemon"; var expectedPriorToVersionSix = "Cuemon .NET Standard"; var expectedFromVersionSix = "Cuemon for .NET"; _cache.Add(key, expectedPriorToVersionSix, DateTime.MaxValue); Assert.True(_cache.Contains(key)); Assert.Equal(expectedPriorToVersionSix, _cache[key]); _cache[key] = expectedFromVersionSix; Assert.Equal(expectedFromVersionSix, _cache[key]); _cache.Remove(key); Assert.False(_cache.Contains(key)); } [Fact, Priority(1)] public void Clear_ShouldRemoveAllCacheEntriesBothLogicalAndActual() { var values = Enumerable.Range(0, 10000).ToList(); foreach (var value in values) { _cache.Add(Guid.NewGuid().ToString("N"), value, DateTime.MaxValue); } Assert.Equal(values.Count, _cache.Count()); Assert.Equal(values.Count, _cache.ToList().Count); Assert.True(values.Count == _cache.Select(pair => pair.Value.CanExpire).Count(), "values.Count == _cache.Select(pair => pair.Value.CanExpire).Count()"); _cache.RemoveAll(); Assert.Equal(0, _cache.Count()); Assert.Equal(0, _cache.ToList().Count); } [Fact, Priority(2)] public void Add_ShouldHandleLargeLoadWithoutCollisionUsingSlidingExpirationOfOneMinute() { var items = NumberOfItemsToCache; var expires = TimeSpan.FromMinutes(1); var keys = Generate.RangeOf(items, i => Guid.NewGuid().ToString("N")).ToList(); var bag = new ConcurrentBag<long>(); // we use Parallel because we want to assure thread safety of the SlimMemoryCache Parallel.ForEach(keys, key => { bag.Add(_cacheOptions.KeyProvider(key, Sliding60Namespace)); _cache.Add(key, Generate.RandomString(5), expires, Sliding60Namespace); }); Assert.Equal(0, _cache.Count()); Assert.Equal(items, _cache.Count(Sliding60Namespace)); Assert.Equal(items, _cache.ToList().Count); Assert.True(bag.OrderBy(l => l).SequenceEqual(_cache.Where(pair => pair.Value.Namespace == Sliding60Namespace).Select(pair => pair.Key).OrderBy(l => l))); // insure thread safety validation } [Fact, Priority(3)] public void Add_ShouldHandleLargeLoadWithoutCollisionUsingSlidingExpirationOfThirtySecondsWithNamespaceSpecification() { var items = NumberOfItemsToCache; var expires = TimeSpan.FromSeconds(30); var keys = Generate.RangeOf(items, i => Guid.NewGuid().ToString("N")).ToList(); var bag = new ConcurrentBag<long>(); // we use Parallel because we want to assure thread safety of the SlimMemoryCache Parallel.ForEach(keys, key => { bag.Add(_cacheOptions.KeyProvider(key, Sliding30Namespace)); _cache.Add(key, Generate.RandomString(5), expires, Sliding30Namespace); }); Assert.Equal(0, _cache.Count()); Assert.Equal(keys.Count, _cache.Count(Sliding30Namespace)); Assert.Equal(items * 2, _cache.ToList().Count); Assert.True(bag.OrderBy(l => l).SequenceEqual(_cache.Where(pair => pair.Value.Namespace == Sliding30Namespace).Select(pair => pair.Key).OrderBy(l => l))); // insure thread safety validation } [Fact, Priority(4)] public void Add_ShouldHandleLargeLoadWithoutCollisionUsingAbsoluteExpirationOfOneMinute() { var items = NumberOfItemsToCache; var expires = DateTime.UtcNow.AddMinutes(1); var keys = Generate.RangeOf(items, i => Guid.NewGuid().ToString("N")).ToList(); var bag = new ConcurrentBag<long>(); // we use Parallel because we want to assure thread safety of the SlimMemoryCache Parallel.ForEach(keys, key => { bag.Add(_cacheOptions.KeyProvider(key, Absolute60Namespace)); _cache.Add(key, Generate.RandomString(5), expires, Absolute60Namespace); }); Assert.Equal(0, _cache.Count()); Assert.Equal(items, _cache.Count(Absolute60Namespace)); Assert.Equal(items * 3, _cache.ToList().Count); Assert.True(bag.OrderBy(l => l).SequenceEqual(_cache.Where(pair => pair.Value.Namespace == Absolute60Namespace).Select(pair => pair.Key).OrderBy(l => l))); // insure thread safety validation } [Fact, Priority(5)] public void Add_ShouldHandleLargeLoadWithoutCollisionUsingAbsoluteExpirationOfThirtySecondsWithNamespaceSpecification() { var items = NumberOfItemsToCache; var expires = DateTime.UtcNow.AddSeconds(30); var keys = Generate.RangeOf(items, i => Guid.NewGuid().ToString("N")).ToList(); var bag = new ConcurrentBag<long>(); // we use Parallel because we want to assure thread safety of the SlimMemoryCache Parallel.ForEach(keys, key => { bag.Add(_cacheOptions.KeyProvider(key, Absolute30Namespace)); _cache.Add(key, Generate.RandomString(5), expires, Absolute30Namespace); }); Assert.Equal(0, _cache.Count()); Assert.Equal(keys.Count, _cache.Count(Absolute30Namespace)); Assert.Equal(items * 4, _cache.ToList().Count); Assert.True(bag.OrderBy(l => l).SequenceEqual(_cache.Where(pair => pair.Value.Namespace == Absolute30Namespace).Select(pair => pair.Key).OrderBy(l => l))); // insure thread safety validation } [Fact, Priority(6)] public void Add_ShouldHandleLargeLoadWithoutCollisionUsingDependencyExpirationOfOneMinute() { var items = NumberOfItemsToCache; var expires = new Func<CountdownDependency>(() => new CountdownDependency(TimeSpan.FromMinutes(1))); var keys = Generate.RangeOf(items, i => Guid.NewGuid().ToString("N")).ToList(); var bag = new ConcurrentBag<long>(); // we use Parallel because we want to assure thread safety of the SlimMemoryCache Parallel.ForEach(keys, key => { bag.Add(_cacheOptions.KeyProvider(key, Dependency60Namespace)); _cache.Add(key, Generate.RandomString(5), expires(), Dependency60Namespace); }); Assert.Equal(0, _cache.Count()); Assert.Equal(items, _cache.Count(Dependency60Namespace)); Assert.Equal(items * 5, _cache.ToList().Count); Assert.True(bag.OrderBy(l => l).SequenceEqual(_cache.Where(pair => pair.Value.Namespace == Dependency60Namespace).Select(pair => pair.Key).OrderBy(l => l))); // insure thread safety validation } [Fact, Priority(7)] public void Add_ShouldHandleLargeLoadWithoutCollisionUsingDependencyExpirationOfThirtySecondsWithNamespaceSpecification() { var items = NumberOfItemsToCache; var expires = new Func<CountdownDependency>(() => new CountdownDependency(TimeSpan.FromSeconds(30))); var keys = Generate.RangeOf(items, i => Guid.NewGuid().ToString("N")).ToList(); var bag = new ConcurrentBag<long>(); // we use Parallel because we want to assure thread safety of the SlimMemoryCache Parallel.ForEach(keys, key => { bag.Add(_cacheOptions.KeyProvider(key, Dependency30Namespace)); _cache.Add(key, Generate.RandomString(5), expires(), Dependency30Namespace); }); Assert.Equal(0, _cache.Count()); Assert.Equal(items, _cache.Count(Dependency30Namespace)); Assert.Equal(items * 6, _cache.ToList().Count); Assert.True(bag.OrderBy(l => l).SequenceEqual(_cache.Where(pair => pair.Value.Namespace == Dependency30Namespace).Select(pair => pair.Key).OrderBy(l => l))); // insure thread safety validation } [Fact, Priority(8)] public void Add_VerifyBothLogicalAndActualCacheRemovalUponExpirationForThirtySecondsNamespaceSpecification() { Thread.Sleep(TimeSpan.FromSeconds(30)); Assert.Equal(0, _cache.Count(Dependency30Namespace)); Assert.Equal(0, _cache.Count(Sliding30Namespace)); Assert.Equal(0, _cache.Count(Absolute30Namespace)); Assert.Equal(NumberOfItemsToCache, _cache.Where(pair => pair.Value.Namespace == Dependency30Namespace).ToList().Count); Assert.Equal(NumberOfItemsToCache, _cache.Where(pair => pair.Value.Namespace == Sliding30Namespace).ToList().Count); Assert.Equal(NumberOfItemsToCache, _cache.Where(pair => pair.Value.Namespace == Absolute30Namespace).ToList().Count); Thread.Sleep(TimeSpan.FromSeconds(10)); Assert.Equal(0, _cache.Where(pair => pair.Value.Namespace == Dependency30Namespace).ToList().Count); Assert.Equal(0, _cache.Where(pair => pair.Value.Namespace == Sliding30Namespace).ToList().Count); Assert.Equal(0, _cache.Where(pair => pair.Value.Namespace == Absolute30Namespace).ToList().Count); } [Fact, Priority(9)] public void Add_VerifyBothLogicalAndActualCacheRemovalUponExpirationForSixtySecondsNamespaceSpecification() { Thread.Sleep(TimeSpan.FromSeconds(20)); Assert.Equal(0, _cache.Count(Dependency60Namespace)); Assert.Equal(0, _cache.Count(Sliding60Namespace)); Assert.Equal(0, _cache.Count(Absolute60Namespace)); Assert.Equal(NumberOfItemsToCache, _cache.Where(pair => pair.Value.Namespace == Dependency60Namespace).ToList().Count); Assert.Equal(NumberOfItemsToCache, _cache.Where(pair => pair.Value.Namespace == Sliding60Namespace).ToList().Count); Assert.Equal(NumberOfItemsToCache, _cache.Where(pair => pair.Value.Namespace == Absolute60Namespace).ToList().Count); Thread.Sleep(TimeSpan.FromSeconds(10)); Assert.Equal(0, _cache.Where(pair => pair.Value.Namespace == Dependency60Namespace).ToList().Count); Assert.Equal(0, _cache.Where(pair => pair.Value.Namespace == Sliding60Namespace).ToList().Count); Assert.Equal(0, _cache.Where(pair => pair.Value.Namespace == Absolute60Namespace).ToList().Count); } public override void ConfigureServices(IServiceCollection services) { services.AddSingleton<Action<SlimMemoryCacheOptions>>(o => { o.FirstSweep = TimeSpan.FromSeconds(35); o.SucceedingSweep = TimeSpan.FromSeconds(5); }); services.AddSingleton<SlimMemoryCache>(); } } }
47.078853
204
0.630758
e23947524a298e0ac78cea08c360d608c8162ab3
606
py
Python
src/convert_base.py
yxtay/data-structures-algorithms
a28f0b7a727192c121579ed51d44d00e09cc1b9a
[ "MIT" ]
1
2020-06-23T16:08:51.000Z
2020-06-23T16:08:51.000Z
src/convert_base.py
yxtay/data-structures-algorithms
a28f0b7a727192c121579ed51d44d00e09cc1b9a
[ "MIT" ]
null
null
null
src/convert_base.py
yxtay/data-structures-algorithms
a28f0b7a727192c121579ed51d44d00e09cc1b9a
[ "MIT" ]
null
null
null
DIGITS = "0123456789abcdef" def convert_base_stack(decimal_number, base): remainder_stack = [] while decimal_number > 0: remainder = decimal_number % base remainder_stack.append(remainder) decimal_number = decimal_number // base new_digits = [] while remainder_stack: new_digits.append(DIGITS[remainder_stack.pop()]) return "".join(new_digits) def convert_base_rec(decimal_number, base): if decimal_number < base: return DIGITS[decimal_number] return convert_base_rec(decimal_number // base, base) + DIGITS[decimal_number % base]
25.25
89
0.70297
bd7be98f54763716c2303917c354da7c5f71feb6
724
asm
Assembly
programs/oeis/109/A109235.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
1
2021-03-15T11:38:20.000Z
2021-03-15T11:38:20.000Z
programs/oeis/109/A109235.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
null
null
null
programs/oeis/109/A109235.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
null
null
null
; A109235: a(n) = floor(n*(e^2-1)/(e^2-2*e-1)). ; 6,13,20,26,33,40,46,53,60,67,73,80,87,93,100,107,114,120,127,134,140,147,154,160,167,174,181,187,194,201,207,214,221,228,234,241,248,254,261,268,275,281,288,295,301,308,315,321,328,335,342,348 mov $2,$0 add $2,1 mov $8,$0 lpb $2 mov $0,$8 sub $2,1 sub $0,$2 mov $9,$0 mov $11,2 lpb $11 mov $0,$9 sub $11,1 add $0,$11 sub $0,1 mov $7,$0 add $0,6 mov $6,$0 sub $0,$0 add $0,$7 div $0,2 mov $3,$11 sub $6,5 mul $6,8 mov $4,$6 add $4,$0 div $4,12 mov $5,$4 lpb $3 sub $3,1 mov $10,$5 lpe lpe lpb $9 mov $9,0 sub $10,$5 lpe mov $5,$10 add $5,6 add $1,$5 lpe
16.454545
194
0.498619
58592e6fceb6797def6c5cb95c2cfab2b20edb15
414
css
CSS
public/trevr/node_modules/grunt-rigger/node_modules/rigger/test/output/local-styl2css-withnib.css
msurguy/codepad
4efcc4fdd07236aa1b5651cf277d7b31cf681586
[ "MIT" ]
1
2021-01-02T04:12:24.000Z
2021-01-02T04:12:24.000Z
public/trevr/node_modules/grunt-rigger/node_modules/rigger/test/output/local-styl2css-withnib.css
msurguy/codepad
4efcc4fdd07236aa1b5651cf277d7b31cf681586
[ "MIT" ]
null
null
null
public/trevr/node_modules/grunt-rigger/node_modules/rigger/test/output/local-styl2css-withnib.css
msurguy/codepad
4efcc4fdd07236aa1b5651cf277d7b31cf681586
[ "MIT" ]
null
null
null
body { background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #fff), color-stop(1, #000)); background: -webkit-linear-gradient(top, #fff 0%, #000 100%); background: -moz-linear-gradient(top, #fff 0%, #000 100%); background: -o-linear-gradient(top, #fff 0%, #000 100%); background: -ms-linear-gradient(top, #fff 0%, #000 100%); background: linear-gradient(top, #fff 0%, #000 100%); }
46
104
0.661836
f4db7d185510952ddf0ca820ffd13d5091196371
2,401
ts
TypeScript
src/core/cache.ts
Okabe-Kurisu/kube-topo
078076491bd9be006ca3fabbb0ad685c916de5cb
[ "MIT" ]
null
null
null
src/core/cache.ts
Okabe-Kurisu/kube-topo
078076491bd9be006ca3fabbb0ad685c916de5cb
[ "MIT" ]
8
2020-05-15T01:46:11.000Z
2020-06-11T09:17:53.000Z
src/core/cache.ts
Okabe-Kurisu/kube-topo
078076491bd9be006ca3fabbb0ad685c916de5cb
[ "MIT" ]
1
2020-06-11T08:36:18.000Z
2020-06-11T08:36:18.000Z
import { intersectionSet } from "../utils"; import { TopologyNode, TopologyNodeTypes, TopologyNodeType } from "../type"; import { GroupConfig } from "@antv/g6/lib/types"; export let cache: { [key: string]: { [value: string]: Set<TopologyNode> } }, links: { [source: string]: { [target: string]: string } }, groups: GroupConfig[]; /** *clean all data in cache and init cache * */ export const initCache = () => { cache = { ObjType: {} }; Object.keys(TopologyNodeTypes).forEach((key) => { if (!cache.ObjType[key]) { cache.ObjType[key] = new Set(); } }); links = {}; groups = [{ id: "cluster", title: "Cluster" }]; }; export const resetLinks = () => { links = {}; }; /** *get toponodes from cache * * @param {string} name * @param {TopologyNodeType} type * @param {string} [namespace] * @returns {TopologyNode[]} */ export const getFromCache = ( name: string, type: TopologyNodeType, namespace?: string ): TopologyNode[] => { let result: TopologyNode[] = []; if (!name) { return result; } cache.ObjType[type.name].forEach((node) => { if (node.name === name) { if (namespace && node.namespace?.name !== namespace) { return; } result.push(node); } }); if ( result.length === 0 && (type === TopologyNodeTypes.Namespace || type === TopologyNodeTypes.PersistentVolumeClaim || type === TopologyNodeTypes.StorageClass) ) { const node = new TopologyNode(undefined, name, namespace, type); cache.ObjType[type.name].add(node); result.push(node); } return result; }; /** *search all node by labels * * @param {{ [keys: string]: string }} labels * @param {string} namespace * @returns {TopologyNode[]} */ export const matchLabel = ( labels: { [keys: string]: string }, namespace?: Set<string>, type?: TopologyNodeType ): TopologyNode[] => { let setList: Set<TopologyNode>[] = []; for (let key of Object.keys(labels)) { if (!cache[key]) { return []; } let tempSet: Set<TopologyNode> = cache[key][labels[key]]; if (!tempSet) { return []; } setList.push(tempSet); } return Array.from(intersectionSet(setList)) .filter((n) => !namespace || namespace.has(n.namespace!.name)) .filter((n) => !type || n.nodeType === type); };
25.542553
77
0.579342
1aacbd706dfb1e05d3e56149a68e9b937808e3cd
47,298
cs
C#
Programing EF DbContext/AfterCompletingChapter6/BreakAwayConsole/Program.cs
julielerman/ProgrammingEntityFrameworkBook
641fa5203925b0eaf1cce0791cc0d05043776ad4
[ "MIT" ]
3
2021-05-11T17:48:34.000Z
2021-09-08T19:41:21.000Z
Programing EF DbContext/AfterCompletingChapter6/BreakAwayConsole/Program.cs
julielerman/ProgrammingEntityFrameworkBook
641fa5203925b0eaf1cce0791cc0d05043776ad4
[ "MIT" ]
null
null
null
Programing EF DbContext/AfterCompletingChapter6/BreakAwayConsole/Program.cs
julielerman/ProgrammingEntityFrameworkBook
641fa5203925b0eaf1cce0791cc0d05043776ad4
[ "MIT" ]
1
2021-11-29T15:08:09.000Z
2021-11-29T15:08:09.000Z
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Text; using DataAccess; using Model; using System.Data.Objects.DataClasses; using System.Data; using System.Data.Entity.Validation; namespace BreakAwayConsole { class Program { static void Main(string[] args) { Database.SetInitializer(new InitializeBagaDatabaseWithSeedData()); ValidateEverything(); } private static void PrintAllDestinations() { using (var context = new BreakAwayContext()) { foreach (var destination in context.Destinations) { Console.WriteLine(destination.Name); } } } private static void PrintAllDestinationsTwice() { using (var context = new BreakAwayContext()) { var allDestinations = context.Destinations.ToList(); foreach (var destination in allDestinations) { Console.WriteLine(destination.Name); } foreach (var destination in allDestinations) { Console.WriteLine(destination.Name); } } } private static void PrintAllDestinationsSorted() { using (var context = new BreakAwayContext()) { var query = from d in context.Destinations orderby d.Name select d; foreach (var destination in query) { Console.WriteLine(destination.Name); } } } private static void PrintAustralianDestinations() { using (var context = new BreakAwayContext()) { var query = from d in context.Destinations where d.Country == "Australia" select d; foreach (var destination in query) { Console.WriteLine(destination.Name); } } } private static void PrintDestinationNameOnly() { using (var context = new BreakAwayContext()) { var query = from d in context.Destinations where d.Country == "Australia" orderby d.Name select d.Name; foreach (var name in query) { Console.WriteLine(name); } } } private static void FindDestination() { Console.Write("Enter id of Destination to find: "); var id = int.Parse(Console.ReadLine()); using (var context = new BreakAwayContext()) { var destination = context.Destinations.Find(id); if (destination == null) { Console.WriteLine("Destination not found!"); } else { Console.WriteLine(destination.Name); } } } private static void FindGreatBarrierReef() { using (var context = new BreakAwayContext()) { var query = from d in context.Destinations where d.Name == "Great Barrier Reef" select d; var reef = query.SingleOrDefault(); if (reef == null) { Console.WriteLine("Can't find the reef!"); } else { Console.WriteLine(reef.Description); } } } private static void GetLocalDestinationCount() { using (var context = new BreakAwayContext()) { foreach (var destination in context.Destinations) { Console.WriteLine(destination.Name); } var count = context.Destinations.Local.Count; Console.WriteLine("Destinations in memory: {0}", count); } } private static void GetLocalDestinationCountWithLoad() { using (var context = new BreakAwayContext()) { context.Destinations.Load(); var count = context.Destinations.Local.Count; Console.WriteLine("Destinations in memory: {0}", count); } } private static void LoadAustralianDestinations() { using (var context = new BreakAwayContext()) { var query = from d in context.Destinations where d.Country == "Australia" select d; query.Load(); var count = context.Destinations.Local.Count; Console.WriteLine("Aussie destinations in memory: {0}", count); } } private static void LocalLinqQueries() { using (var context = new BreakAwayContext()) { context.Destinations.Load(); var sortedDestinations = from d in context.Destinations.Local orderby d.Name select d; Console.WriteLine("All Destinations:"); foreach (var destination in sortedDestinations) { Console.WriteLine(destination.Name); } var aussieDestinations = from d in context.Destinations.Local where d.Country == "Australia" select d; Console.WriteLine(); Console.WriteLine("Australian Destinations:"); foreach (var destination in aussieDestinations) { Console.WriteLine(destination.Name); } } } private static void ListenToLocalChanges() { using (var context = new BreakAwayContext()) { context.Destinations.Local.CollectionChanged += (sender, args) => { if (args.NewItems != null) { foreach (Destination item in args.NewItems) { Console.WriteLine("Added: " + item.Name); } } if (args.OldItems != null) { foreach (Destination item in args.OldItems) { Console.WriteLine("Removed: " + item.Name); } } }; context.Destinations.Load(); } } private static void TestLazyLoading() { using (var context = new BreakAwayContext()) { var query = from d in context.Destinations where d.Name == "Grand Canyon" select d; var canyon = query.Single(); Console.WriteLine("Grand Canyon Lodging:"); if (canyon.Lodgings != null) { foreach (var lodging in canyon.Lodgings) { Console.WriteLine(lodging.Name); } } } } private static void TestEagerLoading() { using (var context = new BreakAwayContext()) { var allDestinations = context.Destinations.Include(d => d.Lodgings); foreach (var destination in allDestinations) { Console.WriteLine(destination.Name); foreach (var lodging in destination.Lodgings) { Console.WriteLine(" - " + lodging.Name); } } } } private static void TestExplicitLoading() { using (var context = new BreakAwayContext()) { var query = from d in context.Destinations where d.Name == "Grand Canyon" select d; var canyon = query.Single(); context.Entry(canyon) .Collection(d => d.Lodgings) .Load(); Console.WriteLine("Grand Canyon Lodging:"); foreach (var lodging in canyon.Lodgings) { Console.WriteLine(lodging.Name); } } } private static void TestIsLoaded() { using (var context = new BreakAwayContext()) { var canyon = (from d in context.Destinations where d.Name == "Grand Canyon" select d).Single(); var entry = context.Entry(canyon); Console.WriteLine("Before Load: {0}", entry.Collection(d => d.Lodgings).IsLoaded); entry.Collection(d => d.Lodgings).Load(); Console.WriteLine("After Load: {0}", entry.Collection(d => d.Lodgings).IsLoaded); } } private static void QueryLodgingDistance() { using (var context = new BreakAwayContext()) { var canyonQuery = from d in context.Destinations where d.Name == "Grand Canyon" select d; var canyon = canyonQuery.Single(); var lodgingQuery = context.Entry(canyon) .Collection(d => d.Lodgings) .Query(); var distanceQuery = from l in lodgingQuery where l.MilesFromNearestAirport <= 10 select l; foreach (var lodging in distanceQuery) { Console.WriteLine(lodging.Name); } } } private static void QueryLodgingCount() { using (var context = new BreakAwayContext()) { var canyonQuery = from d in context.Destinations where d.Name == "Grand Canyon" select d; var canyon = canyonQuery.Single(); var lodgingQuery = context.Entry(canyon) .Collection(d => d.Lodgings) .Query(); var lodgingCount = lodgingQuery.Count(); Console.WriteLine("Lodging at Grand Canyon: " + lodgingCount); } } private static void AddMachuPicchu() { using (var context = new BreakAwayContext()) { var machuPicchu = new Destination { Name = "Machu Picchu", Country = "Peru" }; context.Destinations.Add(machuPicchu); context.SaveChanges(); } } private static void ChangeGrandCanyon() { using (var context = new BreakAwayContext()) { var canyon = (from d in context.Destinations where d.Name == "Grand Canyon" select d).Single(); canyon.Description = "227 mile long canyon."; context.SaveChanges(); } } private static void DeleteWineGlassBay() { using (var context = new BreakAwayContext()) { var bay = (from d in context.Destinations where d.Name == "Wine Glass Bay" select d).Single(); context.Destinations.Remove(bay); context.SaveChanges(); } } private static void DeleteTrip() { using (var context = new BreakAwayContext()) { var trip = (from t in context.Trips where t.Description == "Trip from the database" select t).Single(); var res = (from r in context.Reservations where r.Trip.Description == "Trip from the database" select r).Single(); context.Trips.Remove(trip); context.SaveChanges(); } } private static void DeleteGrandCanyon() { using (var context = new BreakAwayContext()) { var canyon = (from d in context.Destinations where d.Name == "Grand Canyon" select d).Single(); context.Destinations.Remove(canyon); context.SaveChanges(); } } private static void MakeMultipleChanges() { using (var context = new BreakAwayContext()) { var niagaraFalls = new Destination { Name = "Niagara Falls", Country = "USA" }; context.Destinations.Add(niagaraFalls); var wineGlassBay = (from d in context.Destinations where d.Name == "Wine Glass Bay" select d).Single(); wineGlassBay.Description = "Picturesque bay with beaches."; context.SaveChanges(); } } private static void FindOrAddPerson() { using (var context = new BreakAwayContext()) { var ssn = 123456789; var person = context.People.Find(ssn) ?? context.People.Add(new Person { SocialSecurityNumber = ssn, FirstName = "<enter first name>", LastName = "<enter last name>" }); Console.WriteLine(person.FirstName); } } private static void NewGrandCanyonResort() { using (var context = new BreakAwayContext()) { var resort = new Resort { Name = "Pete's Luxury Resort" }; context.Lodgings.Add(resort); var canyon = (from d in context.Destinations where d.Name == "Grand Canyon" select d).Single(); canyon.Lodgings.Add(resort); context.SaveChanges(); } } private static void ChangeLodgingDestination() { using (var context = new BreakAwayContext()) { var hotel = (from l in context.Lodgings where l.Name == "Grand Hotel" select l).Single(); var reef = (from d in context.Destinations where d.Name == "Great Barrier Reef" select d).Single(); hotel.Destination = reef; context.SaveChanges(); } } private static void RemovePrimaryContact() { using (var context = new BreakAwayContext()) { var davesDump = (from l in context.Lodgings where l.Name == "Dave's Dump" select l).Single(); davesDump.PrimaryContactId = null; context.SaveChanges(); } } private static void ManualDetectChanges() { using (var context = new BreakAwayContext()) { context.Configuration.AutoDetectChangesEnabled = false; var reef = (from d in context.Destinations where d.Name == "Great Barrier Reef" select d).Single(); reef.Description = "The world's largest reef!"; Console.WriteLine("Before DetectChanges: {0}", context.Entry(reef).State); context.ChangeTracker.DetectChanges(); Console.WriteLine("After DetectChanges: {0}", context.Entry(reef).State); } } private static void AddMultipleDestinations() { using (var context = new BreakAwayContext()) { context.Configuration.AutoDetectChangesEnabled = false; context.Destinations.Add(new Destination { Name = "Paris", Country = "France" }); context.Destinations.Add(new Destination { Name = "Grindelwald", Country = "Switzerland" }); context.Destinations.Add(new Destination { Name = "Crete", Country = "Greece" }); context.SaveChanges(); } } private static void DetectRelationshipChanges() { using (var context = new BreakAwayContext()) { var hawaii = (from d in context.Destinations where d.Name == "Hawaii" select d).Single(); var davesDump = (from l in context.Lodgings where l.Name == "Dave's Dump" select l).Single(); context.Entry(davesDump) .Reference(l => l.Destination) .Load(); hawaii.Lodgings.Add(davesDump); Console.WriteLine("Before DetectChanges: {0}", davesDump.Destination.Name); context.ChangeTracker.DetectChanges(); Console.WriteLine("After DetectChanges: {0}", davesDump.Destination.Name); } } private static void TestForChangeTrackingProxy() { using (var context = new BreakAwayContext()) { var destination = context.Destinations.First(); var isProxy = destination is IEntityWithChangeTracker; Console.WriteLine("Destination is a proxy: {0}", isProxy); } } private static void CreatingNewProxies() { using (var context = new BreakAwayContext()) { var nonProxy = new Destination(); nonProxy.Name = "Non-proxy Destination"; nonProxy.Lodgings = new List<Lodging>(); var proxy = context.Destinations.Create(); proxy.Name = "Proxy Destination"; context.Destinations.Add(proxy); context.Destinations.Add(nonProxy); var davesDump = (from l in context.Lodgings where l.Name == "Dave's Dump" select l).Single(); context.Entry(davesDump) .Reference(l => l.Destination) .Load(); Console.WriteLine("Before changes: {0}", davesDump.Destination.Name); nonProxy.Lodgings.Add(davesDump); Console.WriteLine("Added to non-proxy destination: {0}", davesDump.Destination.Name); proxy.Lodgings.Add(davesDump); Console.WriteLine("Added to proxy destination: {0}", davesDump.Destination.Name); } } private static void PrintDestinationsWithoutChangeTracking() { using (var context = new BreakAwayContext()) { foreach (var destination in context.Destinations.AsNoTracking()) { Console.WriteLine(destination.Name); } } } private static void AddSimpleGraph() { var essex = new Destination { Name = "Essex, Vermont", Lodgings = new List<Lodging> { new Lodging { Name = "Big Essex Hotel" }, new Lodging { Name = "Essex Junction B&B" }, } }; using (var context = new BreakAwayContext()) { context.Destinations.Add(essex); Console.WriteLine("Essex Destination: {0}", context.Entry(essex).State); foreach (var lodging in essex.Lodgings) { Console.WriteLine("{0}: {1}", lodging.Name, context.Entry(lodging).State); } context.SaveChanges(); } } private static void TestAddDestination() { var jacksonHole = new Destination { Name = "Jackson Hole, Wyoming", Description = "Get your skis on!" }; AddDestination(jacksonHole); } private static void AddDestination(Destination destination) { using (var context = new BreakAwayContext()) { context.Entry(destination).State = EntityState.Added; context.SaveChanges(); } } private static void TestAttachDestination() { Destination canyon; using (var context = new BreakAwayContext()) { canyon = (from d in context.Destinations where d.Name == "Grand Canyon" select d).Single(); } AttachDestination(canyon); } private static void AttachDestination(Destination destination) { using (var context = new BreakAwayContext()) { context.Entry(destination).State = EntityState.Unchanged; context.SaveChanges(); } } private static void TestUpdateDestination() { Destination canyon; using (var context = new BreakAwayContext()) { canyon = (from d in context.Destinations where d.Name == "Grand Canyon" select d).Single(); } canyon.TravelWarnings = "Don't fall in!"; UpdateDestination(canyon); } private static void UpdateDestination(Destination destination) { using (var context = new BreakAwayContext()) { context.Entry(destination).State = EntityState.Modified; context.SaveChanges(); } } private static void TestDeleteDestination() { Destination canyon; using (var context = new BreakAwayContext()) { canyon = (from d in context.Destinations where d.Name == "Grand Canyon" select d).Single(); } DeleteDestination(canyon); } private static void DeleteDestination(Destination destination) { using (var context = new BreakAwayContext()) { context.Entry(destination).State = EntityState.Deleted; context.SaveChanges(); } } private static void DeleteDestination(int destinationId) { using (var context = new BreakAwayContext()) { var destination = new Destination { DestinationId = destinationId }; context.Entry(destination).State = EntityState.Deleted; context.SaveChanges(); } } private static void TestUpdateLodging() { int reefId; Lodging davesDump; using (var context = new BreakAwayContext()) { reefId = (from d in context.Destinations where d.Name == "Great Barrier Reef" select d.DestinationId).Single(); davesDump = (from l in context.Lodgings where l.Name == "Dave's Dump" select l).Single(); } davesDump.DestinationId = reefId; UpdateLodging(davesDump); } private static void UpdateLodging(Lodging lodging) { using (var context = new BreakAwayContext()) { context.Entry(lodging).State = EntityState.Modified; context.SaveChanges(); } } private static void SaveDestinationAndLodgings(Destination destination, List<Lodging> deletedLodgings) { // TODO: Ensure only Destinations & Lodgings are passed in using (var context = new BreakAwayContext()) { context.Destinations.Add(destination); if (destination.DestinationId > 0) { context.Entry(destination).State = EntityState.Modified; } foreach (var lodging in destination.Lodgings) { if (lodging.LodgingId > 0) { context.Entry(lodging).State = EntityState.Modified; } } foreach (var lodging in deletedLodgings) { context.Entry(lodging).State = EntityState.Deleted; } context.SaveChanges(); } } private static void TestSaveDestinationAndLodgings() { Destination canyon; using (var context = new BreakAwayContext()) { canyon = (from d in context.Destinations.Include(d => d.Lodgings) where d.Name == "Grand Canyon" select d).Single(); } canyon.TravelWarnings = "Carry enough water!"; canyon.Lodgings.Add(new Lodging { Name = "Big Canyon Lodge" }); var firstLodging = canyon.Lodgings.ElementAt(0); firstLodging.Name = "New Name Holiday Park"; var secondLodging = canyon.Lodgings.ElementAt(1); var deletedLodgings = new List<Lodging>(); canyon.Lodgings.Remove(secondLodging); deletedLodgings.Add(secondLodging); SaveDestinationAndLodgings(canyon, deletedLodgings); } public static void SaveDestinationGraph(Destination destination) { using (var context = new BreakAwayContext()) { context.Destinations.Add(destination); foreach (var entry in context.ChangeTracker.Entries<IObjectWithState>()) { IObjectWithState stateInfo = entry.Entity; entry.State = ConvertState(stateInfo.State); } context.SaveChanges(); } } public static EntityState ConvertState(State state) { switch (state) { case State.Added: return EntityState.Added; case State.Deleted: return EntityState.Deleted; default: return EntityState.Unchanged; } } private static void TestSaveDestinationGraph() { Destination canyon; using (var context = new BreakAwayContext()) { canyon = (from d in context.Destinations.Include(d => d.Lodgings) where d.Name == "Grand Canyon" select d).Single(); } canyon.TravelWarnings = "Carry enough water!"; var firstLodging = canyon.Lodgings.First(); firstLodging.Name = "New Name Holiday Park"; var secondLodging = canyon.Lodgings.Last(); secondLodging.State = State.Deleted; canyon.Lodgings.Add(new Lodging { Name = "Big Canyon Lodge", State = State.Added }); ApplyChanges(canyon); } private static void ApplyChanges<TEntity>(TEntity root) where TEntity : class, IObjectWithState { using (var context = new BreakAwayContext()) { context.Set<TEntity>().Add(root); CheckForEntitiesWithoutStateInterface(context); foreach (var entry in context.ChangeTracker.Entries<IObjectWithState>()) { IObjectWithState stateInfo = entry.Entity; entry.State = ConvertState(stateInfo.State); if (stateInfo.State == State.Unchanged) { var databaseValues = entry.GetDatabaseValues(); entry.OriginalValues.SetValues(databaseValues); } } context.SaveChanges(); } } private static void ApplyPropertyChanges(DbPropertyValues values, Dictionary<string, object> originalValues) { foreach (var originalValue in originalValues) { if (originalValue.Value is Dictionary<string, object>) { ApplyPropertyChanges( (DbPropertyValues)values[originalValue.Key], (Dictionary<string, object>)originalValue.Value); } else { values[originalValue.Key] = originalValue.Value; } } } private static void CheckForEntitiesWithoutStateInterface(BreakAwayContext context) { var entitiesWithoutState = from e in context.ChangeTracker.Entries() where !(e.Entity is IObjectWithState) select e; if (entitiesWithoutState.Any()) { throw new NotSupportedException("All entities must implement IObjectWithState"); } } private static void PrintState() { using (var context = new BreakAwayContext()) { var canyon = (from d in context.Destinations where d.Name == "Grand Canyon" select d).Single(); DbEntityEntry<Destination> entry = context.Entry(canyon); Console.WriteLine("Before Edit: {0}", entry.State); canyon.TravelWarnings = "Take lots of water."; Console.WriteLine("After Edit: {0}", entry.State); } } private static void PrintChangeTrackingInfo(BreakAwayContext context, object entity) { var entry = context.Entry(entity); Console.WriteLine("Type: {0}", entry.Entity.GetType()); Console.WriteLine("State: {0}", entry.State); if (entry.State != EntityState.Deleted) { Console.WriteLine("\nCurrent Values:"); PrintPropertyValues(entry.CurrentValues); } if (entry.State != EntityState.Added) { Console.WriteLine("\nOriginal Values:"); PrintPropertyValues(entry.OriginalValues); Console.WriteLine("\nDatabase Values:"); PrintPropertyValues(entry.GetDatabaseValues()); } } private static void PrintPropertyValues(DbPropertyValues values, int indent = 1) { foreach (var propertyName in values.PropertyNames) { var value = values[propertyName]; if (value is DbPropertyValues) { Console.WriteLine( "{0}- Complex Property: {1}", string.Empty.PadLeft(indent), propertyName); PrintPropertyValues( (DbPropertyValues)value, indent + 1); } else { Console.WriteLine( "{0}- {1}: {2}", string.Empty.PadLeft(indent), propertyName, values[propertyName]); } } } private static void PrintLodgingInfo() { using (var context = new BreakAwayContext()) { var hotel = (from d in context.Lodgings where d.Name == "Grand Hotel" select d).Single(); PrintChangeTrackingInfo(context, hotel); var davesDump = (from d in context.Lodgings where d.Name == "Dave's Dump" select d).Single(); context.Lodgings.Remove(davesDump); PrintChangeTrackingInfo(context, davesDump); var newMotel = new Lodging { Name = "New Motel" }; context.Lodgings.Add(newMotel); PrintChangeTrackingInfo(context, newMotel); } } private static void PrintOriginalName() { using (var context = new BreakAwayContext()) { var hotel = (from d in context.Lodgings where d.Name == "Grand Hotel" select d).Single(); hotel.Name = "Super Grand Hotel"; string originalName = context.Entry(hotel) .OriginalValues .GetValue<string>("Name"); Console.WriteLine("Current Name: {0}", hotel.Name); Console.WriteLine("Original Name: {0}", originalName); } } private static void PrintPersonInfo() { using (var context = new BreakAwayContext()) { var person = new Person { FirstName = "John", LastName = "Doe", Address = new Address { State = "VT" } }; context.People.Add(person); PrintChangeTrackingInfo(context, person); } } private static void PrintDestination(Destination destination) { Console.WriteLine( "-- {0}, {1} --", destination.Name, destination.Country); Console.WriteLine(destination.Description); if (destination.TravelWarnings != null) { Console.WriteLine("WARNINGS!: {0}", destination.TravelWarnings); } } private static void TestPrintDestination() { using (var context = new BreakAwayContext()) { var reef = (from d in context.Destinations where d.Name == "Great Barrier Reef" select d).Single(); reef.TravelWarnings = "Watch out for sharks!"; Console.WriteLine("Current Values"); PrintDestination(reef); Console.WriteLine("\nDatabase Values"); DbPropertyValues dbValues = context.Entry(reef).GetDatabaseValues(); PrintDestination((Destination)dbValues.ToObject()); } } private static void ChangeCurrentValue() { using (var context = new BreakAwayContext()) { context.Configuration.AutoDetectChangesEnabled = false; var hotel = (from d in context.Lodgings where d.Name == "Grand Hotel" select d).Single(); context.Entry(hotel).CurrentValues["Name"] = "Hotel Pretentious"; Console.WriteLine("Property Value: {0}", hotel.Name); Console.WriteLine("State: {0}", context.Entry(hotel).State); } } private static void CloneCurrentValues() { using (var context = new BreakAwayContext()) { var hotel = (from d in context.Lodgings where d.Name == "Grand Hotel" select d).Single(); var values = context.Entry(hotel).CurrentValues.Clone(); values["Name"] = "Simple Hotel"; Console.WriteLine("Property Value: {0}", hotel.Name); Console.WriteLine("State: {0}", context.Entry(hotel).State); } } private static void UndoEdits() { using (var context = new BreakAwayContext()) { var canyon = (from d in context.Destinations where d.Name == "Grand Canyon" select d).Single(); canyon.Name = "Bigger & Better Canyon"; var entry = context.Entry(canyon); entry.CurrentValues.SetValues(entry.OriginalValues); entry.State = EntityState.Unchanged; Console.WriteLine("Name: {0}", canyon.Name); } } private static void CreateDavesCampsite() { using (var context = new BreakAwayContext()) { var davesDump = (from d in context.Lodgings where d.Name == "Dave's Dump" select d).Single(); var clone = new Lodging(); context.Lodgings.Add(clone); context.Entry(clone) .CurrentValues .SetValues(davesDump); clone.Name = "Dave's Camp"; context.SaveChanges(); Console.WriteLine("Name: {0}", clone.Name); Console.WriteLine("Miles: {0}", clone.MilesFromNearestAirport); Console.WriteLine("Contact Id: {0}", clone.PrimaryContactId); } } private static void WorkingWithPropertyMethod() { using (var context = new BreakAwayContext()) { var davesDump = (from d in context.Lodgings where d.Name == "Dave's Dump" select d).Single(); var entry = context.Entry(davesDump); entry.Property(d => d.Name).CurrentValue = "Dave's Bargain Bungalows"; Console.WriteLine("Current Value: {0}", entry.Property(d => d.Name).CurrentValue); Console.WriteLine("Original Value: {0}", entry.Property(d => d.Name).OriginalValue); Console.WriteLine("Modified?: {0}", entry.Property(d => d.Name).IsModified); } } private static void FindModifiedProperties() { using (var context = new BreakAwayContext()) { var canyon = (from d in context.Destinations where d.Name == "Grand Canyon" select d).Single(); canyon.Name = "Super-Size Canyon"; canyon.TravelWarnings = "Bigger than your brain can handle!!!"; var entry = context.Entry(canyon); var propertyNames = entry.CurrentValues.PropertyNames; IEnumerable<string> modifiedProperties = from name in propertyNames where entry.Property(name).IsModified select name; foreach (var propertyName in modifiedProperties) { Console.WriteLine(propertyName); } } } private static void WorkingWithComplexMethod() { using (var context = new BreakAwayContext()) { var julie = (from p in context.People where p.FirstName == "Julie" select p).Single(); var entry = context.Entry(julie); entry.ComplexProperty(p => p.Address) .Property(a => a.State) .CurrentValue = "VT"; Console.WriteLine( "Address.State Modified?: {0}", entry.ComplexProperty(p => p.Address) .Property(a => a.State) .IsModified); Console.WriteLine( "Address Modified?: {0}", entry.ComplexProperty(p => p.Address).IsModified); Console.WriteLine( "Info.Height.Units Modified?: {0}", entry.ComplexProperty(p => p.Info) .ComplexProperty(i => i.Height) .Property(h => h.Units) .IsModified); } } private static void WorkingWithReferenceMethod() { using (var context = new BreakAwayContext()) { context.Configuration.AutoDetectChangesEnabled = false; context.Configuration.LazyLoadingEnabled = false; var davesDump = (from d in context.Lodgings where d.Name == "Dave's Dump" select d).Single(); var entry = context.Entry(davesDump); entry.Reference(l => l.Destination).Load(); var canyon = davesDump.Destination; Console.WriteLine( "Current Value After Load: {0}", entry.Reference(d => d.Destination) .CurrentValue .Name); var reef = (from d in context.Destinations where d.Name == "Great Barrier Reef" select d).Single(); entry.Reference(d => d.Destination) .CurrentValue = reef; Console.WriteLine( "Current Value After Change: {0}", davesDump.Destination.Name); Console.WriteLine( "State: {0}", entry.State); Console.WriteLine( "Referenced From Current Destination: {0}", reef.Lodgings.Contains(davesDump)); Console.WriteLine( "Referenced From Former Destination: {0}", canyon.Lodgings.Contains(davesDump)); } } private static void WorkingWithCollectionMethod() { using (var context = new BreakAwayContext()) { context.Configuration.AutoDetectChangesEnabled = false; var res = (from r in context.Reservations where r.Trip.Description == "Trip from the database" select r).Single(); var entry = context.Entry(res); entry.Collection(r => r.Payments).Load(); Console.WriteLine( "Payments Before Add: {0}", entry.Collection(r => r.Payments).CurrentValue.Count); var payment = new Payment { Amount = 245 }; context.Payments.Add(payment); entry.Collection(r => r.Payments) .CurrentValue .Add(payment); Console.WriteLine( "Payments After Add: {0}", entry.Collection(r => r.Payments).CurrentValue.Count); Console.WriteLine( "Foreign Key Before DetectChanges: {0}", payment.ReservationId); context.ChangeTracker.DetectChanges(); Console.WriteLine( "Foreign Key After DetectChanges: {0}", payment.ReservationId); } } private static void ReloadLodging() { using (var context = new BreakAwayContext()) { var hotel = (from d in context.Lodgings where d.Name == "Grand Hotel" select d).Single(); hotel.Name = "A New Name"; context.Database.ExecuteSqlCommand( @"UPDATE dbo.Lodgings SET Name = 'Le Grand Hotel' WHERE Name = 'Grand Hotel'"); Console.WriteLine( "Name Before Reload: {0}", hotel.Name); Console.WriteLine( "State Before Reload: {0}", context.Entry(hotel).State); context.Entry(hotel).Reload(); Console.WriteLine( "Name After Reload: {0}", hotel.Name); Console.WriteLine( "State After Reload: {0}", context.Entry(hotel).State); } } private static void PrintChangeTrackerEntries() { using (var context = new BreakAwayContext()) { var res = (from r in context.Reservations where r.Trip.Description == "Trip from the database" select r).Single(); context.Entry(res) .Collection(r => r.Payments) .Load(); res.Payments.Add(new Payment { Amount = 245 }); var entries = context.ChangeTracker.Entries<Payment>(); foreach (var entry in entries) { Console.WriteLine( "Amount: {0}", entry.Entity.Amount); Console.WriteLine( " - State: {0}", entry.State); } } } private static void ConcurrencyDemo() { using (var context = new BreakAwayContext()) { var trip = (from t in context.Trips.Include(t => t.Destination) where t.Description == "Trip from the database" select t).Single(); trip.Description = "Getaway in Vermont"; context.Database.ExecuteSqlCommand( @"UPDATE dbo.Trips SET CostUSD = 400 WHERE Description = 'Trip from the database'"); SaveWithConcurrencyResolution(context); } } private static void SaveWithConcurrencyResolution(BreakAwayContext context) { try { context.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { ResolveConcurrencyConflicts(ex); SaveWithConcurrencyResolution(context); } } private static void ResolveConcurrencyConflicts(DbUpdateConcurrencyException ex) { foreach (var entry in ex.Entries) { Console.WriteLine( "Concurrency conflict found for {0}", entry.Entity.GetType()); Console.WriteLine("\nYou are trying to save the following values:"); PrintPropertyValues(entry.CurrentValues); Console.WriteLine("\nThe values before you started editing were:"); PrintPropertyValues(entry.OriginalValues); var databaseValues = entry.GetDatabaseValues(); Console.WriteLine("\nAnother user has saved the following values:"); PrintPropertyValues(databaseValues); Console.Write("[S]ave your values, [D]iscard you changes or [M]erge?"); var action = Console.ReadKey().KeyChar.ToString().ToUpper(); switch (action) { case "S": entry.OriginalValues.SetValues(databaseValues); break; case "D": entry.Reload(); break; case "M": var mergedValues = MergeValues( entry.OriginalValues, entry.CurrentValues, databaseValues); entry.OriginalValues.SetValues(databaseValues); entry.CurrentValues.SetValues(mergedValues); break; default: throw new ArgumentException("Invalid option"); } } } private static DbPropertyValues MergeValues( DbPropertyValues original, DbPropertyValues current, DbPropertyValues database) { var result = original.Clone(); foreach (var propertyName in original.PropertyNames) { if (original[propertyName] is DbPropertyValues) { var mergedComplexValues = MergeValues( (DbPropertyValues)original[propertyName], (DbPropertyValues)current[propertyName], (DbPropertyValues)database[propertyName]); ((DbPropertyValues)result[propertyName]) .SetValues(mergedComplexValues); } else { if (!object.Equals(current[propertyName], original[propertyName])) { result[propertyName] = current[propertyName]; } else if (!object.Equals(database[propertyName], original[propertyName])) { result[propertyName] = database[propertyName]; } } } return result; } private static void TestSaveLogging() { using (var context = new BreakAwayContext()) { var canyon = (from d in context.Destinations where d.Name == "Grand Canyon" select d).Single(); context.Entry(canyon) .Collection(d => d.Lodgings) .Load(); canyon.TravelWarnings = "Take a hat!"; context.Lodgings.Remove(canyon.Lodgings.First()); context.Destinations.Add(new Destination { Name = "Seattle, WA" }); context.LogChangesDuringSave = true; context.SaveChanges(); } } private static void ValidateNewPerson() { var person = new Person { FirstName = "J", LastName = "Lerman-Flynn", Photo = new PersonPhoto { Photo = new Byte[] { 0 } } }; using (var context = new BreakAwayContext()) { if (context.Entry(person).GetValidationResult().IsValid) { Console.WriteLine("Person is Valid"); } else { Console.WriteLine("Person is Invalid"); var result = context.Entry(person).GetValidationResult(); foreach (DbValidationError error in result.ValidationErrors) { Console.WriteLine(error.ErrorMessage); } } } } private static void ConsoleValidationResults(object entity) { using (var context = new BreakAwayContext()) { var result = context.Entry(entity).GetValidationResult(); foreach (DbValidationError error in result.ValidationErrors) { Console.WriteLine(error.ErrorMessage); } } } public static void ValidateDestination() { ConsoleValidationResults( new Destination { Name = "New York City", Country = "U.S.A", Description = "Big city! :) " }); } private static void ValidatePropertyOnDemand() { var trip = new Trip { EndDate = DateTime.Now, StartDate = DateTime.Now, CostUSD = 500.00M, Description = "Hope you won't be freezing :)", }; using (var context = new BreakAwayContext()) { var errors = context.Entry(trip) .Property(t => t.Description) .GetValidationErrors(); Console.WriteLine("# Errors from Description validation: {0}", errors.Count()); } } private static void ValidateTrip() { ConsoleValidationResults(new Trip { EndDate = DateTime.Now, StartDate = DateTime.Now.AddDays(2), CostUSD = 500.00M, Description = "Hope you won't be freezing on this trip! :)", // Destination = new Destination { Name = "Somewhere Fun" } }); } private static void ValidateEverything() { using (var context = new BreakAwayContext()) { var station = new Destination { Name = "Antartica Research Station", Country = "Antartica", Description = "You will be freezing!" }; context.Destinations.Add(station); context.Trips.Add(new Trip { EndDate = new DateTime(2012, 4, 7), StartDate = new DateTime(2012, 4, 1), CostUSD = 500.00M, Description = "A valid trip.", Destination = station }); context.Trips.Add(new Trip { EndDate = new DateTime(2012, 4, 7), StartDate = new DateTime(2012, 4, 15), CostUSD = 500.00M, Description = "There were sad deaths last time.", Destination = station }); var dbTrip = context.Trips.First(); dbTrip.Destination = station; dbTrip.Description = "don't worry, this one's from the database"; try { context.SaveChanges(); Console.WriteLine("Save Succeeded."); } catch (DbEntityValidationException ex) { Console.WriteLine( "Validation failed for {0} objects", ex.EntityValidationErrors.Count()); } } } private static void DisplayErrors( IEnumerable<DbEntityValidationResult> results) { int counter = 0; foreach (DbEntityValidationResult result in results) { counter++; Console.WriteLine( "Failed Object #{0}: Type is {1}", counter, result.Entry.Entity.GetType().Name); Console.WriteLine( " Number of Problems: {0}", result.ValidationErrors.Count); foreach (DbValidationError error in result.ValidationErrors) { Console.WriteLine(" - {0}", error.ErrorMessage); } } } } }
27.789659
112
0.563174
144a077a184796e7356b1440c66fe441d7513ee0
1,387
dart
Dart
lib/icon_resizer.dart
thruthesky/icon_resizer
4224ff903ae364f3fc2346f9ca260daaa70e81d3
[ "MIT" ]
null
null
null
lib/icon_resizer.dart
thruthesky/icon_resizer
4224ff903ae364f3fc2346f9ca260daaa70e81d3
[ "MIT" ]
null
null
null
lib/icon_resizer.dart
thruthesky/icon_resizer
4224ff903ae364f3fc2346f9ca260daaa70e81d3
[ "MIT" ]
null
null
null
library icon_resizer; import 'dart:async'; import 'package:flutter/material.dart'; class IconResize { IconResize( {@required this.size, this.color, @required this.duration, this.icon}); final double size; final Color color; final int duration; final IconData icon; } class IconResizer extends StatefulWidget { IconResizer({@required this.icon, @required this.resizes, this.loop}); final IconData icon; final int loop; final List<IconResize> resizes; @override _IconResizerState createState() => _IconResizerState(); } class _IconResizerState extends State<IconResizer> { int frameCount = 0; int loopCount = 0; IconResize resize; @override void initState() { super.initState(); resizeLoop(); } resizeLoop() { setState(() { resize = widget.resizes[frameCount]; }); Timer( Duration(milliseconds: widget.resizes[frameCount].duration), () { frameCount++; if (frameCount >= widget.resizes.length) { if (widget.loop != null) { loopCount++; if (loopCount >= widget.loop) return; } frameCount = 0; } resizeLoop(); }, ); } @override Widget build(BuildContext context) { return Icon( resize.icon != null ? resize.icon : widget.icon, size: resize.size, color: resize.color, ); } }
21.338462
77
0.625811
34d7c2103f0bebc437b67ccc1012131123c18215
1,879
lua
Lua
projects/flower-extensions/flower-widget/src/flower/widget/ListViewLayout.lua
rammie/Hanappe
9e084c478e104ac5669cb33c73516f0606ab93f3
[ "Apache-2.0" ]
null
null
null
projects/flower-extensions/flower-widget/src/flower/widget/ListViewLayout.lua
rammie/Hanappe
9e084c478e104ac5669cb33c73516f0606ab93f3
[ "Apache-2.0" ]
null
null
null
projects/flower-extensions/flower-widget/src/flower/widget/ListViewLayout.lua
rammie/Hanappe
9e084c478e104ac5669cb33c73516f0606ab93f3
[ "Apache-2.0" ]
null
null
null
-------------------------------------------------------------------------------- -- Layout class for the ListView. -- -- <h4>Extends:</h4> -- <ul> -- <li><a href="flower.widget.UILayout.html">UILayout</a><l/i> -- </ul> -- -- @author Makoto -- @release V3.0.0 -------------------------------------------------------------------------------- -- import local class = require "flower.class" local table = require "flower.table" local UILayout = require "flower.widget.UILayout" -- class local ListViewLayout = class(UILayout) --- -- Initializes the internal variables. function ListViewLayout:_initInternal() self._columnCount = 1 self._rowHeight = 20 end --- -- Update the layout. -- @param parent parent function ListViewLayout:update(parent) local children = self:getLayoutChildren(parent.children) local columnCount = self._columnCount local rowHeight = self._rowHeight local rowCount = math.floor(#children / columnCount) local parentWidth = parent.parent:getWidth() local parentHeight = rowHeight * rowCount for i, child in ipairs(children) do local childWidth = math.floor((parentWidth) / columnCount) local childHeight = rowHeight local childX = childWidth * ((i - 1) % columnCount) local childY = childHeight * math.floor((i - 1) / columnCount) child:setSize(childWidth, childHeight) child:setPos(childX, childY) end end function ListViewLayout:getLayoutChildren(children) local targets = {} for i, child in ipairs(children) do if not child._excludeLayout then table.insert(targets, child) end end return targets end function ListViewLayout:setColumnCount(columnCount) self._columnCount = assert(columnCount) end function ListViewLayout:setRowHeight(rowHeight) self._rowHeight = assert(rowHeight) end return ListViewLayout
27.632353
80
0.641831
e6a3d0f96ef91fd255386f49e6ce250e1f4bbe4f
6,047
c
C
threads/stampa.c
hex7c0/university-projects
3b938f05c42870f43f92509145438fa37592254a
[ "MIT" ]
null
null
null
threads/stampa.c
hex7c0/university-projects
3b938f05c42870f43f92509145438fa37592254a
[ "MIT" ]
null
null
null
threads/stampa.c
hex7c0/university-projects
3b938f05c42870f43f92509145438fa37592254a
[ "MIT" ]
null
null
null
/********************* Punto 8 /********************/ #include "mylib.h" /* definizione mylib */ #include <string.h> /* stringhe */ #include <stdlib.h> /* exit */ #include <stdio.h> /* I/O */ #include <unistd.h> #include <pthread.h> struct arg { char file[25]; char file2[25]; msg *m; }; void *pr(void *data) { char turni[2000]; /* stringa di turni tmp */ char index; int i=0; /* tmp for */ int count=0; /* contatore utenti */ FILE *stream; /* file csv */ FILE *stream2; /* file csv */ struct arg *a; a = (struct arg *) data; if((stream = fopen(a->file2, "r"))==NULL){ printf("[8.] Errore nella apertura File Src\n");exit(1); } else { while (!feof(stream)) { fscanf(stream, "%c", &index); if (index==';' && i==1) { break; } if (index==';') { i++; } } if((stream2 = fopen(a->file, "w"))==NULL){ printf("[8.] Errore nella apertura File Dest\n");exit(1); } else { fscanf(stream, "%s", turni); fprintf(stream2,"%s", turni); fscanf(stream, "%c", &index); fprintf(stream2,"%c", index); fscanf(stream, "%c", &index); fscanf(stream, "%c", &index); fscanf(stream, "%s", turni); fprintf(stream2,"%s", turni); fflush(stream2);fclose(stream2); } fclose(stream); } if((stream = fopen("matrice_turni.csv", "r"))==NULL){ printf("[8.] Errore nella apertura File\n");exit(1); } while (!feof(stream)) { fscanf(stream, "%c", &index); if (index=='\n') { i=0;break; } } /* PWA read */ fscanf(stream, "%s", turni); fscanf(stream, "%s", turni); fscanf(stream, "%s", turni); fscanf(stream, "%c", &index); fscanf(stream, "%c", &index); while (!feof(stream)) { fscanf(stream, "%c", &index); if (index=='\n') { a->m->string_A[i++]='\0';i=0;break; } a->m->string_A[i++]=index; } /* PWD read */ fscanf(stream, "%s", turni); fscanf(stream, "%s", turni); fscanf(stream, "%s", turni); fscanf(stream, "%c", &index); fscanf(stream, "%c", &index); while (!feof(stream)) { fscanf(stream, "%c", &index); if (index=='\n') { a->m->string_D[i++]='\0';i=0;break; } a->m->string_D[i++]=index; } /* PWM read */ fscanf(stream, "%s", turni); fscanf(stream, "%s", turni); fscanf(stream, "%s", turni); fscanf(stream, "%c", &index); fscanf(stream, "%c", &index); while (!feof(stream)) { fscanf(stream, "%c", &index); if (index=='\n') { a->m->string_M[i++]='\0';i=0;break; } a->m->string_M[i++]=index; } fclose(stream); pthread_exit(NULL); exit(0); /* inutile, toglie warning eclipse */ } void *pwa(void *data) { FILE *stream; /* file csv */ struct arg *a; a = (struct arg *) data; if((stream = fopen(a->file, "a"))==NULL){ printf("[8.] Errore nella apertura File Dest A\n");exit(1); } fprintf(stream, "\n%s\n", a->m->string_A); fclose(stream); pthread_exit(NULL); exit(0); /* inutile, toglie warning eclipse */ } void *pwd(void *data) { FILE *stream; /* file csv */ struct arg *a; a = (struct arg *) data; if((stream = fopen(a->file, "a"))==NULL){ printf("[8.] Errore nella apertura File Dest D\n");exit(1); } fprintf(stream, "%s\n", a->m->string_D); fclose(stream); pthread_exit(NULL); exit(0); /* inutile, toglie warning eclipse */ } void *pwm(void *data) { FILE *stream; /* file csv */ struct arg *a; a = (struct arg *) data; if((stream = fopen(a->file, "a"))==NULL){ printf("[8.] Errore nella apertura File Dest M\n");exit(1); } fprintf(stream, "%s\n", a->m->string_M); fclose(stream); pthread_exit(NULL); exit(0); /* inutile, toglie warning eclipse */ } void *ppp(void *data) { FILE *stream; /* file csv */ struct arg *a; a = (struct arg *) data; if((stream = fopen("matrice_turni.csv", "r"))==NULL){ printf("[8.] Errore nella apertura File\n");exit(1); } char c; while (!feof(stream)) { fscanf(stream, "%c", &c); printf("%c", c); } fclose(stream); pthread_exit(NULL); exit(0); /* inutile, toglie warning eclipse */ } void stamp_C() { char mese[9]; /* input mese */ char file[25]; /* file estrapolato dai vari input */ int i; /* var temporanea */ int anno; /* input anno */ int days; /* set giorni del mese */ FILE *stream; /* file csv */ msg *m; m = (msg *) malloc (sizeof(msg)); pthread_t threads[5]; int rc; do{ printf("[8.] Inserisci Mese: "); scanf ("%s", mese); flush(); if (strcmp(mese,"Gennaio")==0) { days=31; break; } if (strcmp(mese,"Febbraio")==0) { days=28; break; } if (strcmp(mese,"Marzo")==0) { days=31; break; } if (strcmp(mese,"Aprile")==0) { days=30; break; } if (strcmp(mese,"Maggio")==0) { days=31; break; } if (strcmp(mese,"Giugno")==0) { days=30; break; } if (strcmp(mese,"Luglio")==0) { days=31; break; } if (strcmp(mese,"Agosto")==0) { days=31; break; } if (strcmp(mese,"Settembre")==0) { days=30; break; } if (strcmp(mese,"Ottobre")==0) { days=31; break; } if (strcmp(mese,"Novembre")==0) { days=30; break; } if (strcmp(mese,"Dicembre")==0) { days=31; break; } printf("[8-] Mese non valido\n"); }while (1); if (strcmp(mese,"Febbraio")==0) { anno=set_anno(days, 2, 8); } else { anno=set_anno(days, 1, 8); } struct arg a; sprintf(a.file2, "%s_%d.csv", mese, anno); sprintf(a.file, "turni_%s",a.file2); a.m=m; if((stream = fopen(a.file, "r"))==NULL){ printf("[8.] Errore nella apertura File\n");return; } fclose(stream); for(i=0; i<4; i++) { if (i==0) { rc= pthread_create(&threads[i], NULL, pr, (void *) &a); } if (i==1) { rc= pthread_create(&threads[i], NULL, pwa, (void *) &a); } if (i==2) { rc= pthread_create(&threads[i], NULL, pwd, (void *) &a); } if (i==3) { rc= pthread_create(&threads[i], NULL, pwm, (void *) &a); } if (rc) { printf("[8.] Errore nella creazione Thread\n");return; } pthread_join(threads[i], NULL); } rc= pthread_create(&threads[4], NULL, ppp, (void *) &a); if (rc) { printf("[8.] Errore nella creazione Thread\n");return; } pthread_join(threads[i], NULL); printf("[8.] Concluso\n\n"); return; }
20.638225
61
0.561766
dbe559fb8eea16d540addf40dbb2a52beb973f95
298
php
PHP
toitest/catalog/language/fr-Fr/extension/shipping/usps.php
pass-services/OToitPhaseTest
390aa1eb1ad417bc94b35b4cd06498cf399d042e
[ "MIT" ]
null
null
null
toitest/catalog/language/fr-Fr/extension/shipping/usps.php
pass-services/OToitPhaseTest
390aa1eb1ad417bc94b35b4cd06498cf399d042e
[ "MIT" ]
null
null
null
toitest/catalog/language/fr-Fr/extension/shipping/usps.php
pass-services/OToitPhaseTest
390aa1eb1ad417bc94b35b4cd06498cf399d042e
[ "MIT" ]
null
null
null
<?php // Text $_['text_title'] = 'Service Postal des Etats-Unis'; $_['text_weight'] = 'Poids:'; $_['text_eta'] = 'Temps estimé:'; /* Copyright (C) 2016-2017 Apptiko. Created by Apptiko - http://extension.apptiko.com. Time-stamp-code:Sat1117071304 */
18.625
57
0.57047
13ba5335b4bafa2bf49fbd7721e10bfc4b133933
9,188
lua
Lua
Recurrence.lua
petrjanda/rnn
5acdf20c02427088096cfb97d43487989987454a
[ "BSD-3-Clause" ]
1
2018-02-01T08:23:17.000Z
2018-02-01T08:23:17.000Z
Recurrence.lua
douwekiela/rnn
bec9fa9f76e91a3c7a80700f6ef722d2f710c0b2
[ "BSD-3-Clause" ]
null
null
null
Recurrence.lua
douwekiela/rnn
bec9fa9f76e91a3c7a80700f6ef722d2f710c0b2
[ "BSD-3-Clause" ]
null
null
null
------------------------------------------------------------------------ --[[ Recurrence ]]-- -- A general container for implementing a recurrence. -- Unlike Recurrent, this module doesn't manage a separate input layer, -- nor does it have a startModule. Instead for the first step, it -- just forwards a zero tensor through the recurrent layer (like LSTM). -- The recurrentModule should output Tensor or table : output(t) -- given input table : {input(t), output(t-1)} ------------------------------------------------------------------------ local Recurrence, parent = torch.class('nn.Recurrence', 'nn.AbstractRecurrent') function Recurrence:__init(recurrentModule, outputSize, nInputDim, rho) parent.__init(self, rho or 9999) assert(_.contains({'table','torch.LongStorage','number'}, torch.type(outputSize)), "Unsupported size type") self.outputSize = torch.type(outputSize) == 'number' and {outputSize} or outputSize -- for table outputs, this is the number of dimensions in the first (left) tensor (depth-first). assert(torch.type(nInputDim) == 'number', "Expecting nInputDim number for arg 2") self.nInputDim = nInputDim assert(torch.isTypeOf(recurrentModule, 'nn.Module'), "Expecting recurrenModule nn.Module for arg 3") self.recurrentModule = recurrentModule -- make it work with nn.Container and nn.Decorator self.module = self.recurrentModule self.modules[1] = self.recurrentModule self.sharedClones[1] = self.recurrentModule -- just so we can know the type of this module self.typeTensor = torch.Tensor() end -- recursively creates a zero tensor (or table thereof) (or table thereof). -- This zero Tensor is forwarded as output(t=0). function Recurrence:recursiveResizeZero(tensor, size, batchSize) local isTable = torch.type(size) == 'table' if isTable and torch.type(size[1]) == 'table' then tensor = (torch.type(tensor) == 'table') and tensor or {} for k,v in ipairs(size) do tensor[k] = self:recursiveResizeZero(tensor[k], v, batchSize) end elseif torch.type(size) == 'torch.LongStorage' then local size_ = torch.LongStorage():totable() tensor = torch.isTensor(tensor) and tensor or self.typeTensor.new() if batchSize then tensor:resize(batchSize, unpack(size_)) else tensor:resize(unpack(size)) end tensor:zero() elseif isTable and torch.type(size[1]) == 'number' then tensor = torch.isTensor(tensor) and tensor or self.typeTensor.new() if batchSize then tensor:resize(batchSize, unpack(size)) else tensor:resize(unpack(size)) end tensor:zero() else error("Unknown size type : "..torch.type(size)) end return tensor end -- get the batch size. -- When input is a table, we use the first tensor (depth first). function Recurrence:getBatchSize(input, nInputDim) local nInputDim = nInputDim or self.nInputDim if torch.type(input) == 'table' then return self:getBatchSize(input[1]) else assert(torch.isTensor(input)) if input:dim() == nInputDim then return il elseif input:dim() - 1 == nInputDim then return input:size(1) else error("inconsitent tensor dims "..input:dim()) end end end function Recurrence:updateOutput(input) local prevOutput if self.step == 1 then if self.userPrevOutput then -- user provided previous output prevOutput = self.userPrevOutput else -- first previous output is zeros local batchSize = self:getBatchSize(input) self.zeroTensor = self:recursiveResizeZero(self.zeroTensor, self.outputSize, batchSize) prevOutput = self.zeroTensor end else -- previous output of this module prevOutput = self.output end -- output(t) = recurrentModule{input(t), output(t-1)} local output if self.train ~= false then self:recycle() local recurrentModule = self:getStepModule(self.step) -- the actual forward propagation output = recurrentModule:updateOutput{input, prevOutput} else output = self.recurrentModule:updateOutput{input, prevOutput} end if self.train ~= false then local input_ = self.inputs[self.step] self.inputs[self.step] = self.copyInputs and nn.rnn.recursiveCopy(input_, input) or nn.rnn.recursiveSet(input_, input) end self.outputs[self.step] = output self.output = output self.step = self.step + 1 self.gradPrevOutput = nil self.updateGradInputStep = nil self.accGradParametersStep = nil self.gradParametersAccumulated = false return self.output end function Recurrence:backwardThroughTime(timeStep, rho) assert(self.step > 1, "expecting at least one updateOutput") self.gradInputs = {} -- used by Sequencer, Repeater timeStep = timeStep or self.step local rho = math.min(rho or self.rho, timeStep-1) local stop = timeStep - rho if self.fastBackward then for step=timeStep-1,math.max(stop,1),-1 do -- set the output/gradOutput states of current Module local recurrentModule = self:getStepModule(step) -- backward propagate through this step local gradOutput = self.gradOutputs[step] if self.gradPrevOutput then self._gradOutputs[step] = nn.rnn.recursiveCopy(self._gradOutputs[step], self.gradPrevOutput) nn.rnn.recursiveAdd(self._gradOutputs[step], gradOutput) gradOutput = self._gradOutputs[step] end local scale = self.scales[step] local output = (step == 1) and (self.userPrevOutput or self.zeroTensor) or self.outputs[step-1] local gradInputTable = recurrentModule:backward({self.inputs[step], output}, gradOutput, scale) gradInput, self.gradPrevOutput = unpack(gradInputTable) table.insert(self.gradInputs, 1, gradInput) if self.userPrevOutput then self.userGradPrevOutput = self.gradPrevOutput end end self.gradParametersAccumulated = true return gradInput else local gradInput = self:updateGradInputThroughTime() self:accGradParametersThroughTime() return gradInput end end function Recurrence:updateGradInputThroughTime(timeStep, rho) assert(self.step > 1, "expecting at least one updateOutput") self.gradInputs = {} local gradInput timeStep = timeStep or self.step local rho = math.min(rho or self.rho, timeStep-1) local stop = timeStep - rho for step=timeStep-1,math.max(stop,1),-1 do -- set the output/gradOutput states of current Module local recurrentModule = self:getStepModule(step) -- backward propagate through this step local gradOutput = self.gradOutputs[step] if self.gradPrevOutput then self._gradOutputs[step] = nn.rnn.recursiveCopy(self._gradOutputs[step], self.gradPrevOutput) nn.rnn.recursiveAdd(self._gradOutputs[step], gradOutput) gradOutput = self._gradOutputs[step] end local output = (step == 1) and (self.userPrevOutput or self.zeroTensor) or self.outputs[step-1] local gradInputTable = recurrentModule:updateGradInput({self.inputs[step], output}, gradOutput) gradInput, self.gradPrevOutput = unpack(gradInputTable) table.insert(self.gradInputs, 1, gradInput) if self.userPrevOutput then self.userGradPrevOutput = self.gradPrevOutput end end return gradInput end function Recurrence:accGradParametersThroughTime(timeStep, rho) timeStep = timeStep or self.step local rho = math.min(rho or self.rho, timeStep-1) local stop = timeStep - rho for step=timeStep-1,math.max(stop,1),-1 do -- set the output/gradOutput states of current Module local recurrentModule = self:getStepModule(step) -- backward propagate through this step local scale = self.scales[step] local output = (step == 1) and (self.userPrevOutput or self.zeroTensor) or self.outputs[step-1] local gradOutput = (step == self.step-1) and self.gradOutputs[step] or self._gradOutputs[step] recurrentModule:accGradParameters({self.inputs[step], output}, gradOutput, scale) end self.gradParametersAccumulated = true return gradInput end function Recurrence:accUpdateGradParametersThroughTime(lr, timeStep, rho) timeStep = timeStep or self.step local rho = math.min(rho or self.rho, timeStep-1) local stop = timeStep - rho for step=timeStep-1,math.max(stop,1),-1 do -- set the output/gradOutput states of current Module local recurrentModule = self:getStepModule(step) -- backward propagate through this step local scale = self.scales[step] local output = (step == 1) and (self.userPrevOutput or self.zeroTensor) or self.outputs[step-1] local gradOutput = (step == self.step-1) and self.gradOutputs[step] or self._gradOutputs[step] recurrentModule:accUpdateGradParameters({self.inputs[step], output}, gradOutput, lr*scale) end return gradInput end Recurrence.__tostring__ = nn.Decorator.__tostring__
38.932203
110
0.679909
d08e2e76cacbee170f9b2f433cc0de062fe28c14
271
lua
Lua
MMOCoreORB/bin/scripts/object/custom_content/tangible/item/beast/converted_thune_decoration.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/bin/scripts/object/custom_content/tangible/item/beast/converted_thune_decoration.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/bin/scripts/object/custom_content/tangible/item/beast/converted_thune_decoration.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
object_tangible_item_beast_converted_thune_decoration = object_tangible_item_beast_shared_converted_thune_decoration:new { } ObjectTemplates:addTemplate(object_tangible_item_beast_converted_thune_decoration, "object/tangible/item/beast/converted_thune_decoration.iff")
45.166667
143
0.911439