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
c681168a14ecbbc4686265ffe6e0f165f7f2d5ca
3,480
py
Python
tests/test_command_history.py
pmann84/PythonInteractiveInterpreter
ce1adcae35d9ee1a8cd2bb8402ff3a411f31fc4c
[ "MIT" ]
null
null
null
tests/test_command_history.py
pmann84/PythonInteractiveInterpreter
ce1adcae35d9ee1a8cd2bb8402ff3a411f31fc4c
[ "MIT" ]
null
null
null
tests/test_command_history.py
pmann84/PythonInteractiveInterpreter
ce1adcae35d9ee1a8cd2bb8402ff3a411f31fc4c
[ "MIT" ]
null
null
null
#!/usr/bin/env python import os import sys import unittest # Add the pii module to the path sys.path.insert(0, os.path.abspath("..")) # Import the pii module from pii import piilib # Setup class for history tests class PiiCommandHistoryTestSetup(unittest.TestCase): CMDS = ["foo", "blah", "test", "hello", "yes"] def setUp(self): # Instantiate a PiiCommandHistory object self.history = piilib.history.PiiCommandHistory() # Add 3 commands to history for cmd in self.CMDS: self.history.add_to_history(cmd) class PiiCommandHistoryTests(PiiCommandHistoryTestSetup): def test_add_command_to_history(self): # Check that the history is length 3 and equal to the cmds list self.assertEqual(len(self.history.command_list), len(self.CMDS)) self.assertEqual(self.history.command_list, self.CMDS) def test_get_previous_command(self): # run the prev command 3 times to get the commands for i in range(1, len(self.CMDS)): self.assertEqual(self.history.get_prev_command(), self.CMDS[-i]) def test_get_previous_command_clamp(self): # run the prev command 2*(3+1) times to get the commands for i in range(2*len(self.CMDS)): returned_cmd = self.history.get_prev_command() curr_pos = self.history.history_pos if i < len(self.CMDS): self.assertEqual(returned_cmd, self.CMDS[curr_pos]) self.assertEqual(curr_pos, len(self.CMDS)-i-1) else: self.assertEqual(returned_cmd, self.CMDS[0]) self.assertEqual(curr_pos, 0) def test_get_next_command_from_start(self): # run the next command 3 times from the start to get empty always for i in range(1, len(self.CMDS)): self.assertEqual(self.history.get_next_command(), "") def test_get_next_command_from_previous_position(self): offset = 2 num_left = len(self.CMDS)-offset # Go back a few commands for i in range(num_left): self.history.get_prev_command() # Now go forwards by the same amount for i in range(0, num_left): returned_cmd = self.history.get_next_command() if self.history.history_pos == len(self.CMDS)-1 and returned_cmd == "": self.assertEqual(returned_cmd, "") else: self.assertEqual(returned_cmd, self.CMDS[offset+i+1]) def test_get_next_command_from_previous_position_clamped(self): offset = 2 num_left = len(self.CMDS)-offset # Go back a few commands for i in range(num_left): self.history.get_prev_command() # Now go forwards by the same amount for i in range(0, num_left*4): returned_cmd = self.history.get_next_command() if self.history.history_pos >= len(self.CMDS)-1 and returned_cmd == "": self.assertEqual(returned_cmd, "") else: self.assertEqual(returned_cmd, self.CMDS[offset+i+1]) def test_clear_history(self): self.history.clear_history() self.assertEqual(self.history.command_list, []) self.assertEqual(self.history.history_pos, -1) # Run the tests with higher than default verbosity if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(PiiCommandHistoryTests) unittest.TextTestRunner(verbosity=10).run(suite)
36.631579
83
0.65
2ca54f8e96eb4fa755341211c9fb094048967794
140
py
Python
cherry/agents/algorithms.py
vishalbelsare/cherry-pytorch
7a05b488de1f4a5de52fe7d0f5e639b381da42d4
[ "MIT" ]
11
2020-01-28T15:40:25.000Z
2021-01-02T23:09:05.000Z
cherry/agents/algorithms.py
vishalbelsare/cherry-pytorch
7a05b488de1f4a5de52fe7d0f5e639b381da42d4
[ "MIT" ]
30
2019-12-14T12:11:07.000Z
2020-01-29T10:56:13.000Z
cherry/agents/algorithms.py
vishalbelsare/cherry-pytorch
7a05b488de1f4a5de52fe7d0f5e639b381da42d4
[ "MIT" ]
1
2020-01-29T13:15:46.000Z
2020-01-29T13:15:46.000Z
from cherry.agents.dqn import DQN from cherry.agents.ddqn import DDQN from cherry.agents.vpg import VPG from cherry.agents.ddpg import DDPG
28
35
0.828571
22ca36e02b6914326e85e58a1a38425507916754
5,575
sql
SQL
src/main/resources/db/2020-09-10.sql
wxclaude/jjzdpt
2a2cc1b9f2ff1671fe2f80f13fb3eb34941b2281
[ "Apache-2.0" ]
null
null
null
src/main/resources/db/2020-09-10.sql
wxclaude/jjzdpt
2a2cc1b9f2ff1671fe2f80f13fb3eb34941b2281
[ "Apache-2.0" ]
null
null
null
src/main/resources/db/2020-09-10.sql
wxclaude/jjzdpt
2a2cc1b9f2ff1671fe2f80f13fb3eb34941b2281
[ "Apache-2.0" ]
null
null
null
DROP TABLE IF EXISTS `df_sjfn`; CREATE TABLE `df_sjfn` ( `id` int(11) NOT NULL AUTO_INCREMENT, `type` varchar(50) DEFAULT NULL, `dept` varchar(50) DEFAULT NULL, `dept_id` varchar(50) DEFAULT NULL, `df_month` varchar(50) DEFAULT NULL, `create_by` varchar(50) DEFAULT NULL, `create_time` datetime DEFAULT CURRENT_TIMESTAMP, `isdel` int(11) DEFAULT '0', `s1` varchar(50) DEFAULT NULL, `s2` varchar(50) DEFAULT NULL, `s3` varchar(50) DEFAULT NULL, `s4` varchar(50) DEFAULT NULL, `s5` varchar(50) DEFAULT NULL, `s6` varchar(50) DEFAULT NULL, `s7` varchar(50) DEFAULT NULL, `s8` varchar(50) DEFAULT NULL, `s9` varchar(50) DEFAULT NULL, `s10` varchar(50) DEFAULT NULL, `s11` varchar(50) DEFAULT NULL, `s12` varchar(50) DEFAULT NULL, `s13` varchar(50) DEFAULT NULL, `s14` varchar(50) DEFAULT NULL, `s15` varchar(50) DEFAULT NULL, `s16` varchar(50) DEFAULT NULL, `s17` varchar(50) DEFAULT NULL, `s18` varchar(50) DEFAULT NULL, `s19` varchar(50) DEFAULT NULL, `s20` varchar(50) DEFAULT NULL, `s21` varchar(50) DEFAULT NULL, `s22` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=81 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of `df_sjfn` -- ---------------------------- BEGIN; INSERT INTO `df_sjfn` VALUES ('65', '1', '汊河', 'D0068', '2020-07', '', '2020-06-29 08:26:55', '0', '0', '0.00', '0', '0.00', '0', '0.00', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1.00', '2.00', '5.00', '2.29', '2.29', '2.00', '2.00'), ('66', '1', '方巷', 'D0112', '2020-07', '', '2020-06-29 08:26:55', '0', '0', '0.00', '0', '0.00', '0', '0.00', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1.00', '2.00', '4.41', '4.25', '4.25', '2.00', '2.00'), ('67', '1', '甘泉', 'D0245', '2020-07', '', '2020-06-29 08:26:55', '0', '0', '0.00', '0', '0.00', '0', '0.00', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1.00', '2.00', '2.08', '3.60', '3.60', '2.00', '2.00'), ('68', '1', '公道', 'D0122', '2020-07', '', '2020-06-29 08:26:55', '0', '0', '0.00', '0', '0.00', '0', '0.00', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1.00', '2.00', '5.00', '1.96', '1.96', '2.00', '2.00'), ('69', '1', '瓜洲', 'D0078', '2020-07', '', '2020-06-29 08:26:55', '0', '0', '0.00', '0', '0.00', '0', '0.00', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0.96', '2.00', '5.00', '2.59', '2.59', '2.00', '2.00'), ('70', '1', '邗上', 'D0059', '2020-07', '', '2020-06-29 08:26:55', '0', '0', '0.00', '0', '0.00', '0', '0.00', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0.92', '2.00', '5.00', '2.86', '2.86', '2.00', '1.98'), ('71', '1', '槐泗', 'D0102', '2020-07', '', '2020-06-29 08:26:55', '0', '0', '0.75', '0', '0.50', '0', '0.00', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0.96', '2.00', '3.51', '3.78', '3.78', '2.00', '2.00'), ('72', '1', '江阳', 'D0238', '2020-07', '', '2020-06-29 08:26:55', '0', '0', '0.00', '0', '0.00', '0', '0.00', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0.92', '2.00', '2.70', '3.20', '3.20', '2.00', '1.98'), ('73', '1', '蒋王', 'D0086', '2020-07', '', '2020-06-29 08:26:55', '0', '0', '0.00', '0', '0.00', '0', '0.00', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0.92', '2.00', '5.00', '4.87', '4.87', '2.00', '2.00'), ('74', '1', '念四桥', 'D0191', '2020-07', '', '2020-06-29 08:26:55', '0', '0', '0.00', '0', '0.00', '0', '0.00', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1.00', '2.00', '2.63', '3.00', '3.00', '1.98', '2.00'), ('75', '1', '四季园', 'D0181', '2020-07', '', '2020-06-29 08:26:55', '0', '0', '0.00', '0', '0.00', '0', '0.00', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1.00', '2.00', '5.00', '4.44', '4.44', '1.98', '2.00'), ('76', '1', '西湖', 'D0220', '2020-07', '', '2020-06-29 08:26:55', '0', '0', '0.00', '0', '0.00', '0', '0.00', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1.00', '2.00', '3.13', '2.28', '2.28', '1.98', '2.00'), ('77', '1', '新盛', 'D00003', '2020-07', '', '2020-06-29 08:26:55', '0', '0', '0.00', '0', '0.00', '0', '0.00', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1.00', '2.00', '4.92', '2.81', '2.81', '2.00', '2.00'), ('78', '1', '杨庙', 'D0095', '2020-07', '', '2020-06-29 08:26:55', '0', '0', '0.00', '0', '0.00', '0', '0.00', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1.00', '2.00', '5.00', '4.83', '4.83', '2.00', '2.00'), ('79', '1', '杨寿', 'D0173', '2020-07', '', '2020-06-29 08:26:55', '0', '0', '0.00', '0', '0.00', '0', '0.00', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1.00', '2.00', '5.00', '4.01', '4.01', '2.00', '2.00'), ('80', '1', '竹西', 'D0209', '2020-07', '', '2020-06-29 08:26:55', '0', '0', '0.00', '0', '0.00', '0', '0.00', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1.00', '2.00', '4.05', '1.80', '1.80', '2.00', '2.00'); COMMIT; DROP TABLE IF EXISTS `jq_cj_bhg`; CREATE TABLE `jq_cj_bhg` ( `id` int(11) NOT NULL AUTO_INCREMENT, `jjbh` varchar(50) DEFAULT NULL, `create_time` datetime DEFAULT CURRENT_TIMESTAMP, `create_by` varchar(50) DEFAULT NULL, `reason` varchar(50) DEFAULT NULL, `state` int(11) DEFAULT '0' COMMENT '0派出所未整改 1派出所已整改 2 703已确认合格 3 703已确认不合格 4无法整改', `update_time` datetime DEFAULT NULL, `update_by` varchar(50) DEFAULT NULL, `ip` varchar(50) DEFAULT NULL, `isdel` int(11) DEFAULT '0', `dept_code` varchar(50) DEFAULT NULL, `type` varchar(255) DEFAULT NULL, `remark` varchar(255) DEFAULT NULL COMMENT '-1 合格警情 自定义异常原因 type=99', `ip2` varchar(50) DEFAULT NULL, `jjsj` varchar(50) DEFAULT NULL, `dw` varchar(50) DEFAULT NULL, `frm` int(11) DEFAULT '0' COMMENT '来源 0指挥中心 1派出所', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=utf8;
85.769231
3,407
0.477848
c36acf9d55961a71c67a788f9d2bcf17e7685f2f
2,978
cs
C#
Data/FileSystemProvider.cs
Sagleft/FundTracking
2042c0554b21fd8f0fd96d25822ab55e4725ea48
[ "MIT" ]
null
null
null
Data/FileSystemProvider.cs
Sagleft/FundTracking
2042c0554b21fd8f0fd96d25822ab55e4725ea48
[ "MIT" ]
null
null
null
Data/FileSystemProvider.cs
Sagleft/FundTracking
2042c0554b21fd8f0fd96d25822ab55e4725ea48
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Text; using Newtonsoft.Json; namespace FundTracking.Data { /// <summary> /// File System Provider /// </summary> public class FileSystemProvider { private string dataPath = "finance.ftf"; //от bson выйгрыш всего 5% //private DataContainer dataContainer = null; public FileSystemProvider() { this.load(); } // public static string DecompressString(string input) // { // //thnx, Lasse Vågsæther Karlsen // byte[] compressed = Convert.FromBase64String(input); // byte[] decompressed = DecompressBytes(compressed); // return Encoding.UTF8.GetString(decompressed); // } // // public static string CompressString(string input) // { // byte[] encoded = Encoding.UTF8.GetBytes(input); // byte[] compressed = CompressBytes(encoded); // return Convert.ToBase64String(compressed); // } public static byte[] DecompressBytes(byte[] input) { using (var source = new MemoryStream(input)) { byte[] lengthBytes = new byte[4]; source.Read(lengthBytes, 0, 4); var length = BitConverter.ToInt32(lengthBytes, 0); using (var decompressionStream = new GZipStream(source, CompressionMode.Decompress)) { var result = new byte[length]; decompressionStream.Read(result, 0, length); return result; } } } public static byte[] CompressBytes(byte[] input) { using (var result = new MemoryStream()) { var lengthBytes = BitConverter.GetBytes(input.Length); result.Write(lengthBytes, 0, 4); using (var compressionStream = new GZipStream(result, CompressionMode.Compress)) { compressionStream.Write(input, 0, input.Length); compressionStream.Flush(); } return result.ToArray(); } } public DataContainer load() { DataContainer dataContainer = null; //пока так, не охота пока гору проверок писать if(File.Exists(dataPath)) { byte[] encoded = File.ReadAllBytes(dataPath); byte[] decoded = DecompressBytes(encoded); string json = Encoding.UTF8.GetString(decoded); //string json = Decompress(File.ReadAllText(dataPath)); dataContainer = JsonConvert.DeserializeObject<DataContainer>(json); } else { dataContainer = new DataContainer(); dataContainer.entrys_list = new List<FundEntry>(); //string json = JsonConvert.SerializeObject(dataContainer); //File.WriteAllText(dataPath, Compress(json)); save(dataContainer); } return dataContainer; } public void save(DataContainer container) { string json = JsonConvert.SerializeObject(container); byte[] encoded = Encoding.UTF8.GetBytes(json); //сохранение в бинарном виде File.WriteAllBytes(this.dataPath, CompressBytes(encoded)); } } }
29.485149
71
0.651444
b9400d5e2b897cb110995fb96c084c4c45fbbc77
372
css
CSS
betterbuttons/css/betterbuttons_nested_form.css
ByronMorley/silverstripe_master_template
84d721de82fd2039d0e48b346e34e54bda683175
[ "MIT" ]
null
null
null
betterbuttons/css/betterbuttons_nested_form.css
ByronMorley/silverstripe_master_template
84d721de82fd2039d0e48b346e34e54bda683175
[ "MIT" ]
null
null
null
betterbuttons/css/betterbuttons_nested_form.css
ByronMorley/silverstripe_master_template
84d721de82fd2039d0e48b346e34e54bda683175
[ "MIT" ]
null
null
null
.betterbuttons-nested-form form label.left {float:none;} .betterbuttons-nested-form form .middleColumn {margin-left:0;} .betterbuttons-nested-form form input.action { display: block; width: 50%; background: #15659C; border: 0; padding: 10px; color: #fff; margin: 0 auto; cursor:pointer; } .betterbuttons-nested-form form input.action:hover { background:#4080AC }
28.615385
73
0.744624
d8c737177c7a374d8262dab45270d056526d8b9d
1,360
sql
SQL
dfc-coursedirectory/Identity/Tables/AspNetUsers.sql
SkillsFundingAgency/dfc-providerportal-database
86bfec34eab07256d37a6e74452cacb4da9ac384
[ "MIT" ]
null
null
null
dfc-coursedirectory/Identity/Tables/AspNetUsers.sql
SkillsFundingAgency/dfc-providerportal-database
86bfec34eab07256d37a6e74452cacb4da9ac384
[ "MIT" ]
1
2019-10-10T07:15:35.000Z
2019-10-10T07:15:35.000Z
dfc-coursedirectory/Identity/Tables/AspNetUsers.sql
SkillsFundingAgency/dfc-providerportal-database
86bfec34eab07256d37a6e74452cacb4da9ac384
[ "MIT" ]
1
2021-04-11T08:45:46.000Z
2021-04-11T08:45:46.000Z
CREATE TABLE [Identity].[AspNetUsers]( [Id] [nvarchar](450) NOT NULL, [Email] [nvarchar](256) NULL, [EmailConfirmed] [bit] NOT NULL, [PasswordHash] [nvarchar](max) NULL, [SecurityStamp] [nvarchar](max) NULL, [PhoneNumber] [nvarchar](max) NULL, [PhoneNumberConfirmed] [bit] NOT NULL, [TwoFactorEnabled] [bit] NOT NULL, [LockoutEndDateUtc] [datetime] NULL, [LockoutEnabled] [bit] NOT NULL, [AccessFailedCount] [int] NOT NULL, [UserName] [nvarchar](256) NOT NULL, [Name] [nvarchar](max) NULL, [AddressId] [int] NULL, [PasswordResetRequired] [bit] NULL, [ProviderUserTypeId] [int] NULL, [CreatedByUserId] [nvarchar](128) NULL, [CreatedDateTimeUtc] [datetime] NULL, [ModifiedByUserId] [nvarchar](128) NULL, [ModifiedDateTimeUtc] [datetime] NULL, [IsDeleted] [bit] NULL, [LegacyUserId] [int] NULL, [LastLoginDateTimeUtc] [datetime] NULL, [IsSecureAccessUser] [bit] NULL, [SecureAccessUserId] [int] NULL, [ShowUserWizard] [bit] NULL, [NormalizedUserName] [nvarchar](256) NULL, [NormalizedEmail] [nvarchar](256) NULL, [ConcurrencyStamp] [nvarchar](max) NULL, [LockoutEnd] [datetimeoffset](7) NULL, CONSTRAINT [PK_AspNetUsers] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO
35.789474
133
0.726471
dbeb5b9393b08e896829088387c979fe041bbcef
245
cs
C#
API/DataAccess/Concrete/ClientDal.cs
jovasoft/JoEmpty.Api
0f7d7dfd27b7102b0c8408b671b54fdb1a6ad9ba
[ "MIT" ]
null
null
null
API/DataAccess/Concrete/ClientDal.cs
jovasoft/JoEmpty.Api
0f7d7dfd27b7102b0c8408b671b54fdb1a6ad9ba
[ "MIT" ]
null
null
null
API/DataAccess/Concrete/ClientDal.cs
jovasoft/JoEmpty.Api
0f7d7dfd27b7102b0c8408b671b54fdb1a6ad9ba
[ "MIT" ]
null
null
null
using DataAccess.Abstract; using Entities; using System; using System.Collections.Generic; using System.Text; namespace DataAccess.Concrete { public class ClientDal : EntityRepositoryBase<Client, PostgresContext>, IClientDal { } }
18.846154
86
0.771429
76f69b86fba92c4936224f3e65560b5f8416c45c
411
h
C
pred_code/fake_header.h
songjiguo/c3idl
a4b92a347618d66ad6295385412a9465550135f2
[ "BSD-3-Clause" ]
1
2016-03-16T05:57:40.000Z
2016-03-16T05:57:40.000Z
pred_code/fake_header.h
songjiguo/c3idl
a4b92a347618d66ad6295385412a9465550135f2
[ "BSD-3-Clause" ]
null
null
null
pred_code/fake_header.h
songjiguo/c3idl
a4b92a347618d66ad6295385412a9465550135f2
[ "BSD-3-Clause" ]
null
null
null
/* This file is temporarily used for gcc debug only. gcc can not * understand c3idl key words. It does not matter for parsing. Remove * this later. */ #ifndef _cos_fake_header_h #define _cos_fake_header_h #include <stdlib.h> #include <stdio.h> int fault; int uc; int ret; int param_sz; int IDL_desc_saved_params; // TODO: fix this #define assert(x) #define CSTUB_INVOKE #endif /* _cos_fake_header_h */
19.571429
69
0.744526
8a199d386244d4ba54887e20b1622459b373b70d
12,597
rs
Rust
src/core/index_meta.rs
ngi-nix/tantivy
f6cf6e889b1f8595dbd6b62f30c71562c1465d01
[ "MIT" ]
null
null
null
src/core/index_meta.rs
ngi-nix/tantivy
f6cf6e889b1f8595dbd6b62f30c71562c1465d01
[ "MIT" ]
9
2021-09-16T20:29:27.000Z
2022-03-01T20:29:19.000Z
src/core/index_meta.rs
ngi-nix/tantivy
f6cf6e889b1f8595dbd6b62f30c71562c1465d01
[ "MIT" ]
1
2021-08-13T15:11:02.000Z
2021-08-13T15:11:02.000Z
use super::SegmentComponent; use crate::schema::Schema; use crate::Opstamp; use crate::{core::SegmentId, store::Compressor}; use census::{Inventory, TrackedObject}; use serde::{Deserialize, Serialize}; use std::path::PathBuf; use std::{collections::HashSet, sync::atomic::AtomicBool}; use std::{fmt, sync::Arc}; #[derive(Clone, Debug, Serialize, Deserialize)] struct DeleteMeta { num_deleted_docs: u32, opstamp: Opstamp, } #[derive(Clone, Default)] pub struct SegmentMetaInventory { inventory: Inventory<InnerSegmentMeta>, } impl SegmentMetaInventory { /// Lists all living `SegmentMeta` object at the time of the call. pub fn all(&self) -> Vec<SegmentMeta> { self.inventory .list() .into_iter() .map(SegmentMeta::from) .collect::<Vec<_>>() } pub fn new_segment_meta(&self, segment_id: SegmentId, max_doc: u32) -> SegmentMeta { let inner = InnerSegmentMeta { segment_id, max_doc, include_temp_doc_store: Arc::new(AtomicBool::new(true)), deletes: None, }; SegmentMeta::from(self.inventory.track(inner)) } } /// `SegmentMeta` contains simple meta information about a segment. /// /// For instance the number of docs it contains, /// how many are deleted, etc. #[derive(Clone)] pub struct SegmentMeta { tracked: TrackedObject<InnerSegmentMeta>, } impl fmt::Debug for SegmentMeta { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { self.tracked.fmt(f) } } impl serde::Serialize for SegmentMeta { fn serialize<S>( &self, serializer: S, ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error> where S: serde::Serializer, { self.tracked.serialize(serializer) } } impl From<TrackedObject<InnerSegmentMeta>> for SegmentMeta { fn from(tracked: TrackedObject<InnerSegmentMeta>) -> SegmentMeta { SegmentMeta { tracked } } } impl SegmentMeta { // Creates a new `SegmentMeta` object. /// Returns the segment id. pub fn id(&self) -> SegmentId { self.tracked.segment_id } /// Removes the Component::TempStore from the alive list and /// therefore marks the temp docstore file to be deleted by /// the garbage collection. pub fn untrack_temp_docstore(&self) { self.tracked .include_temp_doc_store .store(false, std::sync::atomic::Ordering::Relaxed); } /// Returns the number of deleted documents. pub fn num_deleted_docs(&self) -> u32 { self.tracked .deletes .as_ref() .map(|delete_meta| delete_meta.num_deleted_docs) .unwrap_or(0u32) } /// Returns the list of files that /// are required for the segment meta. /// /// This is useful as the way tantivy removes files /// is by removing all files that have been created by tantivy /// and are not used by any segment anymore. pub fn list_files(&self) -> HashSet<PathBuf> { if self .tracked .include_temp_doc_store .load(std::sync::atomic::Ordering::Relaxed) { SegmentComponent::iterator() .map(|component| self.relative_path(*component)) .collect::<HashSet<PathBuf>>() } else { SegmentComponent::iterator() .filter(|comp| *comp != &SegmentComponent::TempStore) .map(|component| self.relative_path(*component)) .collect::<HashSet<PathBuf>>() } } /// Returns the relative path of a component of our segment. /// /// It just joins the segment id with the extension /// associated to a segment component. pub fn relative_path(&self, component: SegmentComponent) -> PathBuf { let mut path = self.id().uuid_string(); path.push_str(&*match component { SegmentComponent::Postings => ".idx".to_string(), SegmentComponent::Positions => ".pos".to_string(), SegmentComponent::Terms => ".term".to_string(), SegmentComponent::Store => ".store".to_string(), SegmentComponent::TempStore => ".store.temp".to_string(), SegmentComponent::FastFields => ".fast".to_string(), SegmentComponent::FieldNorms => ".fieldnorm".to_string(), SegmentComponent::Delete => format!(".{}.del", self.delete_opstamp().unwrap_or(0)), }); PathBuf::from(path) } /// Return the highest doc id + 1 /// /// If there are no deletes, then num_docs = max_docs /// and all the doc ids contains in this segment /// are exactly (0..max_doc). pub fn max_doc(&self) -> u32 { self.tracked.max_doc } /// Return the number of documents in the segment. pub fn num_docs(&self) -> u32 { self.max_doc() - self.num_deleted_docs() } /// Returns the `Opstamp` of the last delete operation /// taken in account in this segment. pub fn delete_opstamp(&self) -> Option<Opstamp> { self.tracked .deletes .as_ref() .map(|delete_meta| delete_meta.opstamp) } /// Returns true iff the segment meta contains /// delete information. pub fn has_deletes(&self) -> bool { self.num_deleted_docs() > 0 } /// Updates the max_doc value from the `SegmentMeta`. /// /// This method is only used when updating `max_doc` from 0 /// as we finalize a fresh new segment. pub(crate) fn with_max_doc(self, max_doc: u32) -> SegmentMeta { assert_eq!(self.tracked.max_doc, 0); assert!(self.tracked.deletes.is_none()); let tracked = self.tracked.map(move |inner_meta| InnerSegmentMeta { segment_id: inner_meta.segment_id, max_doc, deletes: None, include_temp_doc_store: Arc::new(AtomicBool::new(true)), }); SegmentMeta { tracked } } #[doc(hidden)] pub fn with_delete_meta(self, num_deleted_docs: u32, opstamp: Opstamp) -> SegmentMeta { let delete_meta = DeleteMeta { num_deleted_docs, opstamp, }; let tracked = self.tracked.map(move |inner_meta| InnerSegmentMeta { segment_id: inner_meta.segment_id, max_doc: inner_meta.max_doc, include_temp_doc_store: Arc::new(AtomicBool::new(true)), deletes: Some(delete_meta), }); SegmentMeta { tracked } } } #[derive(Debug, Clone, Serialize, Deserialize)] struct InnerSegmentMeta { segment_id: SegmentId, max_doc: u32, deletes: Option<DeleteMeta>, /// If you want to avoid the SegmentComponent::TempStore file to be covered by /// garbage collection and deleted, set this to true. This is used during merge. #[serde(skip)] #[serde(default = "default_temp_store")] pub(crate) include_temp_doc_store: Arc<AtomicBool>, } fn default_temp_store() -> Arc<AtomicBool> { Arc::new(AtomicBool::new(false)) } impl InnerSegmentMeta { pub fn track(self, inventory: &SegmentMetaInventory) -> SegmentMeta { SegmentMeta { tracked: inventory.inventory.track(self), } } } /// Search Index Settings. /// /// Contains settings which are applied on the whole /// index, like presort documents. #[derive(Clone, Default, Serialize, Deserialize, Eq, PartialEq)] pub struct IndexSettings { /// Sorts the documents by information /// provided in `IndexSortByField` #[serde(skip_serializing_if = "Option::is_none")] pub sort_by_field: Option<IndexSortByField>, /// The `Compressor` used to compress the doc store. #[serde(default)] pub docstore_compression: Compressor, } /// Settings to presort the documents in an index /// /// Presorting documents can greatly performance /// in some scenarios, by applying top n /// optimizations. #[derive(Clone, Serialize, Deserialize, Eq, PartialEq)] pub struct IndexSortByField { /// The field to sort the documents by pub field: String, /// The order to sort the documents by pub order: Order, } /// The order to sort by #[derive(Clone, Serialize, Deserialize, Eq, PartialEq)] pub enum Order { /// Ascending Order Asc, /// Descending Order Desc, } impl Order { /// return if the Order is ascending pub fn is_asc(&self) -> bool { self == &Order::Asc } /// return if the Order is descending pub fn is_desc(&self) -> bool { self == &Order::Desc } } /// Meta information about the `Index`. /// /// This object is serialized on disk in the `meta.json` file. /// It keeps information about /// * the searchable segments, /// * the index `docstamp` /// * the schema /// #[derive(Clone, Serialize)] pub struct IndexMeta { /// `IndexSettings` to configure index options. #[serde(default)] pub index_settings: IndexSettings, /// List of `SegmentMeta` informations associated to each finalized segment of the index. pub segments: Vec<SegmentMeta>, /// Index `Schema` pub schema: Schema, /// Opstamp associated to the last `commit` operation. pub opstamp: Opstamp, #[serde(skip_serializing_if = "Option::is_none")] /// Payload associated to the last commit. /// /// Upon commit, clients can optionally add a small `String` payload to their commit /// to help identify this commit. /// This payload is entirely unused by tantivy. pub payload: Option<String>, } #[derive(Deserialize)] struct UntrackedIndexMeta { pub segments: Vec<InnerSegmentMeta>, #[serde(default)] pub index_settings: IndexSettings, pub schema: Schema, pub opstamp: Opstamp, #[serde(skip_serializing_if = "Option::is_none")] pub payload: Option<String>, } impl UntrackedIndexMeta { pub fn track(self, inventory: &SegmentMetaInventory) -> IndexMeta { IndexMeta { index_settings: self.index_settings, segments: self .segments .into_iter() .map(|inner_seg_meta| inner_seg_meta.track(inventory)) .collect::<Vec<SegmentMeta>>(), schema: self.schema, opstamp: self.opstamp, payload: self.payload, } } } impl IndexMeta { /// Create an `IndexMeta` object representing a brand new `Index` /// with the given index. /// /// This new index does not contains any segments. /// Opstamp will the value `0u64`. pub fn with_schema(schema: Schema) -> IndexMeta { IndexMeta { index_settings: IndexSettings::default(), segments: vec![], schema, opstamp: 0u64, payload: None, } } pub(crate) fn deserialize( meta_json: &str, inventory: &SegmentMetaInventory, ) -> serde_json::Result<IndexMeta> { let untracked_meta_json: UntrackedIndexMeta = serde_json::from_str(meta_json)?; Ok(untracked_meta_json.track(inventory)) } } impl fmt::Debug for IndexMeta { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", serde_json::ser::to_string(self) .expect("JSON serialization for IndexMeta should never fail.") ) } } #[cfg(test)] mod tests { use super::IndexMeta; use crate::{ schema::{Schema, TEXT}, IndexSettings, IndexSortByField, Order, }; #[test] fn test_serialize_metas() { let schema = { let mut schema_builder = Schema::builder(); schema_builder.add_text_field("text", TEXT); schema_builder.build() }; let index_metas = IndexMeta { index_settings: IndexSettings { sort_by_field: Some(IndexSortByField { field: "text".to_string(), order: Order::Asc, }), ..Default::default() }, segments: Vec::new(), schema, opstamp: 0u64, payload: None, }; let json = serde_json::ser::to_string(&index_metas).expect("serialization failed"); assert_eq!( json, r#"{"index_settings":{"sort_by_field":{"field":"text","order":"Asc"},"docstore_compression":"lz4"},"segments":[],"schema":[{"name":"text","type":"text","options":{"indexing":{"record":"position","tokenizer":"default"},"stored":false}}],"opstamp":0}"# ); } }
31.4925
262
0.610145
459164f40f31987a93c7b77cb184b573ba599b70
1,510
py
Python
DockerFeed/Stores/FolderStore.py
DIPSAS/DockerFeed
64ad9e491112b70c2a50ad8c62cc3865d4908d2e
[ "MIT" ]
3
2019-11-18T14:23:42.000Z
2020-04-29T08:24:25.000Z
DockerFeed/Stores/FolderStore.py
DIPSAS/DockerFeed
64ad9e491112b70c2a50ad8c62cc3865d4908d2e
[ "MIT" ]
null
null
null
DockerFeed/Stores/FolderStore.py
DIPSAS/DockerFeed
64ad9e491112b70c2a50ad8c62cc3865d4908d2e
[ "MIT" ]
null
null
null
import os import glob import shutil from DockerFeed.Stores.AbstractStore import AbstractStore class FolderStore(AbstractStore): def __init__(self, \ sourceFolder ='stacks'): self.__sourceFolder = sourceFolder os.makedirs(self.__sourceFolder, exist_ok=True) def GetSource(self): return self.__sourceFolder def Pull(self, artifactName, outputFolder): sourcePath = self.__GetArtifactSourcePath(artifactName) destinationPath = os.path.join(outputFolder, artifactName) if not(os.path.isfile(sourcePath)): raise FileNotFoundError("Artifact {0} does not exist in source folder {1}".format(artifactName, self.__sourceFolder)) os.makedirs(outputFolder, exist_ok=True) shutil.copyfile(sourcePath, destinationPath) def Push(self, artifactFile): destinationPath = os.path.join(self.__sourceFolder, os.path.basename(artifactFile)) shutil.copyfile(artifactFile, destinationPath) def Exists(self, artifactName): sourcePath = self.__GetArtifactSourcePath(artifactName) return os.path.isfile(sourcePath) def Remove(self, artifactName): sourcePath = self.__GetArtifactSourcePath(artifactName) os.remove(sourcePath) def List(self, searchPattern = '*'): return glob.glob(os.path.join(self.__sourceFolder, searchPattern)) def __GetArtifactSourcePath(self, artifactName): return os.path.join(self.__sourceFolder, artifactName)
31.458333
129
0.711921
bdc1e67d43a55228f97aad70e212dffd8abee600
4,723
dart
Dart
lib/absinthe_socket.dart
anu788/absinthe_socket
055bc30c29c232acedefa2edddb27d639917e427
[ "MIT" ]
null
null
null
lib/absinthe_socket.dart
anu788/absinthe_socket
055bc30c29c232acedefa2edddb27d639917e427
[ "MIT" ]
null
null
null
lib/absinthe_socket.dart
anu788/absinthe_socket
055bc30c29c232acedefa2edddb27d639917e427
[ "MIT" ]
1
2022-03-01T21:14:03.000Z
2022-03-01T21:14:03.000Z
library absinthe_socket; import 'package:phoenix_wings/phoenix_wings.dart'; export 'package:phoenix_wings/phoenix_wings.dart'; import 'get_socket_by_platform/get_socket_by_platform_abstract.dart' if (dart.library.io) 'get_socket_by_platform/get_socket_by_mobile.dart' if (dart.library.js) 'get_socket_by_platform/get_socket_by_web.dart'; /// An Absinthe Socket class AbsintheSocket { String endpoint; PhoenixSocketOptions? socketOptions = PhoenixSocketOptions(); late PhoenixSocket _phoenixSocket; PhoenixChannel? _absintheChannel; List<Notifier> _notifiers = []; List<Notifier> _queuedPushes = []; late NotifierPushHandler subscriptionHandler; late NotifierPushHandler unsubscriptionHandler; static _onError(Map? response) { print("onError ${response?.toString()}"); } static _onSubscriptionSucceed(Map? response, Notifier notifier) { print("subscription response ${response?.toString()}"); notifier.subscriptionId = response?["subscriptionId"]; } _onUnsubscriptionSucceed(Map? response, Notifier notifier) { print("unsubscription response ${response?.toString()}"); notifier.cancel(); _notifiers.remove(notifier); } static _onTimeout(Map? response) { print("onTimeout ${response?.toString()}"); } AbsintheSocket(this.endpoint, {this.socketOptions}) { if (socketOptions == null) socketOptions = PhoenixSocketOptions(); subscriptionHandler = NotifierPushHandler( onError: _onError, onTimeout: _onTimeout, onSucceed: _onSubscriptionSucceed); unsubscriptionHandler = NotifierPushHandler( onError: _onError, onTimeout: _onTimeout, onSucceed: _onUnsubscriptionSucceed); _phoenixSocket = getPheonixSocket(endpoint, socketOptions!); _connect(); } _connect() async { await _phoenixSocket.connect(); _phoenixSocket.onMessage(_onMessage); _absintheChannel = _phoenixSocket.channel("__absinthe__:control", {}); _absintheChannel!.join()!.receive("ok", _sendQueuedPushes); } disconnect() { _phoenixSocket.disconnect(); } _sendQueuedPushes(_) { _queuedPushes.forEach((notifier) { _pushRequest(notifier); }); _queuedPushes = []; } void cancel(Notifier notifier) { unsubscribe(notifier); } void unsubscribe(Notifier notifier) { _handlePush( _absintheChannel!.push( event: "unsubscribe", payload: {"subscriptionId": notifier.subscriptionId})!, unsubscriptionHandler, notifier, ); } Notifier send(GqlRequest request) { Notifier notifier = Notifier(request: request); _notifiers.add(notifier); _pushRequest(notifier); return notifier; } _onMessage(PhoenixMessage message) { String? subscriptionId = message.topic; _notifiers .where((Notifier notifier) => notifier.subscriptionId == subscriptionId) .forEach( (Notifier notifier) => notifier.notify(message.payload!["result"])); } _pushRequest(Notifier notifier) { if (_absintheChannel == null) { _queuedPushes.add(notifier); } else { _handlePush( _absintheChannel!.push( event: "doc", payload: { "query": notifier.request.operation, "variables": notifier.request.params ?? {}, }, ), subscriptionHandler, notifier, ); } } _handlePush( PhoenixPush? push, NotifierPushHandler handler, Notifier notifier) { push ?.receive("ok", (response) => handler.onSucceed(response, notifier)) .receive("error", handler.onError) .receive("timeout", handler.onTimeout); } } class Notifier<Result> { GqlRequest request; List<Observer<Result>> observers = []; String? subscriptionId; Notifier({required this.request}); void observe(Observer observer) { observers.add(observer as Observer<Result>); } void notify(Map? result) { observers.forEach((Observer observer) => observer.onResult!(result)); } void cancel() { observers.forEach((Observer observer) => observer.onCancel!()); } } class Observer<Result> { Function? onAbort; Function? onCancel; Function? onError; Function? onStart; Function? onResult; Observer( {this.onAbort, this.onCancel, this.onError, this.onStart, this.onResult}); } class GqlRequest { String operation; Map<String, dynamic>? params; GqlRequest({required this.operation, this.params}); } class NotifierPushHandler<Response> { Function(Map?) onError; Function(Map?, Notifier) onSucceed; Function(Map?) onTimeout; NotifierPushHandler( {required this.onError, required this.onSucceed, required this.onTimeout}); }
26.835227
80
0.687275
7e49514a116b9962430ca3bd829dca32fd1ae1e8
9,740
rs
Rust
src/frontend/buttons.rs
jrmo14/Desktopper
1b7b42cffa8db573b3374a169fbc9816792121ac
[ "MIT" ]
null
null
null
src/frontend/buttons.rs
jrmo14/Desktopper
1b7b42cffa8db573b3374a169fbc9816792121ac
[ "MIT" ]
null
null
null
src/frontend/buttons.rs
jrmo14/Desktopper
1b7b42cffa8db573b3374a169fbc9816792121ac
[ "MIT" ]
null
null
null
use gpio_cdev::EventType::{FallingEdge, RisingEdge}; use gpio_cdev::{Chip, EventRequestFlags, EventType, LineEventHandle, LineRequestFlags}; use nix::poll::{poll, PollFd, PollFlags}; use parking_lot::Mutex; use serde::export::Formatter; use std::fmt::Display; use std::os::unix::io::AsRawFd; use std::sync::mpsc::Sender; use std::sync::Arc; use std::thread::{spawn, JoinHandle}; pub const RELEASED: Option<EventType> = Some(FallingEdge); pub const HELD: Option<EventType> = Some(RisingEdge); pub const OPEN: Option<EventType> = None; #[derive(Clone)] pub struct Buttons { pub mode: Button, pub cycle: Button, pub f0: Button, pub f1: Button, pub f2: Button, } impl Display for Buttons { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let extract = |state: &Option<EventType>| -> String { match state { Some(state) => match state { EventType::FallingEdge => String::from("Released"), EventType::RisingEdge => String::from("Held"), }, None => String::from("Open"), } }; write!( f, "Buttons:\n\tmode: ({}::{})\n\tcycle: ({}::{})\n\tf0: ({}::{})\n\tf1: ({}::{})\n\tf2: ({}::{})", self.mode.pin_num, extract(&self.mode.state), self.cycle.pin_num, extract(&self.cycle.state), self.f0.pin_num, extract(&self.f0.state), self.f1.pin_num, extract(&self.f1.state), self.f2.pin_num, extract(&self.f2.state) ) } } // There are 3 states, Held (Rising Edge), Just released (Falling Edge), Released (None) pub struct Button { pub pin_num: u32, pub state: Option<EventType>, } impl Button { pub fn new(pin_num: u32) -> Self { Button { pin_num, state: None, } } } impl Buttons { pub fn new(mode_pin: u32, cycle_pin: u32, f0_pin: u32, f1_pin: u32, f2_pin: u32) -> Self { Buttons { mode: Button::new(mode_pin), cycle: Button::new(cycle_pin), f0: Button::new(f0_pin), f1: Button::new(f1_pin), f2: Button::new(f2_pin), } } } impl Clone for Button { fn clone(&self) -> Self { Button { pin_num: self.pin_num, state: match &self.state { Some(evt_type) => match evt_type { EventType::FallingEdge => Some(EventType::FallingEdge), EventType::RisingEdge => Some(EventType::RisingEdge), }, None => None, }, } } } pub struct InputHandler { internal: Arc<Mutex<InputHandlerInternal>>, } struct InputHandlerInternal { buttons: Buttons, messenger: Sender<Buttons>, line_handles: Vec<LineEventHandle>, line_fds: Vec<PollFd>, } impl InputHandler { pub fn new( chip: &mut Chip, messenger: Sender<Buttons>, mode_pin: u32, cycle_pin: u32, f0_pin: u32, f1_pin: u32, f2_pin: u32, ) -> Self { let mut line_handles = Vec::new(); let mut line_fds = Vec::new(); // Build up the handles and fd's InputHandler::create_handle_fd(chip, mode_pin, &mut line_fds, &mut line_handles); InputHandler::create_handle_fd(chip, cycle_pin, &mut line_fds, &mut line_handles); InputHandler::create_handle_fd(chip, f0_pin, &mut line_fds, &mut line_handles); InputHandler::create_handle_fd(chip, f1_pin, &mut line_fds, &mut line_handles); InputHandler::create_handle_fd(chip, f2_pin, &mut line_fds, &mut line_handles); // Store everything in an internal struct so we can chuck it off into the worker thread ez pz let internal = Arc::from(Mutex::from(InputHandlerInternal { buttons: Buttons::new(mode_pin, cycle_pin, f0_pin, f1_pin, f2_pin), messenger, line_handles, line_fds, })); InputHandler { internal } } pub fn start(&mut self) -> JoinHandle<()> { // Get something we can move into the thread let internal_clone = self.internal.clone(); spawn(move || { // Just lock down the internal struct, nobody else is going to be using it let mut internal = internal_clone.lock(); loop { match poll(&mut internal.line_fds, -1) { Ok(timeout_status) => { if timeout_status == 0 { warn!("Input loop timeout!?!?!?") } else { for i in 0..internal.line_fds.len() { if let Some(evts) = internal.line_fds[i].revents() { let handle = internal.line_handles.get(i).unwrap(); let offset = handle.line().offset(); // We've got some kinda event if evts.contains(PollFlags::POLLIN) { match handle.get_event() { Ok(event) => { // Update the appropriate button's state if offset == internal.buttons.mode.pin_num { internal.buttons.mode.state = Some(event.event_type()); } else if offset == internal.buttons.cycle.pin_num { internal.buttons.cycle.state = Some(event.event_type()); } else if offset == internal.buttons.f0.pin_num { internal.buttons.f0.state = Some(event.event_type()); } else if offset == internal.buttons.f1.pin_num { internal.buttons.f1.state = Some(event.event_type()); } else if offset == internal.buttons.f2.pin_num { internal.buttons.f2.state = Some(event.event_type()); } // A button was released if event.event_type() == FallingEdge { info!("Sending buttons: {}", internal.buttons); // Send all the button states to the listener if let Err(e) = internal .messenger .send(internal.buttons.clone()) { error!("Failed to send buttons, {}", e) } // Reset the button states after one is released internal.buttons.mode.state = None; internal.buttons.cycle.state = None; internal.buttons.f0.state = None; internal.buttons.f1.state = None; internal.buttons.f2.state = None; } } Err(e) => error!( "Handle {} failed to unwrap event :: {}", offset, e ), } } else if evts.contains(PollFlags::POLLPRI) { // Don't really know how this would happen let's keep track though warn!("[{}] Got a POLLPRI", handle.line().offset()) } } } } } // Something is wrong Err(e) => error!("Poll failed to return: {}", e), } } }) } // Builds the necessary things and puts them in the right vector for each button fn create_handle_fd( chip: &mut Chip, line_offset: u32, button_fds: &mut Vec<PollFd>, event_handles: &mut Vec<LineEventHandle>, ) { let line_handle = chip .get_line(line_offset) .unwrap() .events( LineRequestFlags::INPUT, EventRequestFlags::BOTH_EDGES, "desktopper", ) .unwrap(); button_fds.push(PollFd::new( (&line_handle).as_raw_fd(), PollFlags::POLLIN | PollFlags::POLLPRI, )); event_handles.push(line_handle); } }
40.92437
108
0.429261
a324c230b2301c9e89ee42622da0e96404f394a6
1,921
java
Java
src/main/java/com/boundlessgeo/GeoHeatmapPlugin.java
o19s/elasticsearch-heatmap
d7e4f0a0edbeb2b96ae037f8f4d81e165a0c60da
[ "Apache-2.0" ]
2
2017-05-11T11:51:14.000Z
2018-01-15T09:08:42.000Z
src/main/java/com/boundlessgeo/GeoHeatmapPlugin.java
o19s/elasticsearch-heatmap
d7e4f0a0edbeb2b96ae037f8f4d81e165a0c60da
[ "Apache-2.0" ]
null
null
null
src/main/java/com/boundlessgeo/GeoHeatmapPlugin.java
o19s/elasticsearch-heatmap
d7e4f0a0edbeb2b96ae037f8f4d81e165a0c60da
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2015-2016 Boundless, http://boundlessgeo.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License * */ package com.boundlessgeo; import java.util.Collection; import com.boundlessgeo.module.GeoHeatmapModule; import com.boundlessgeo.rest.GeoHeatmapRestAction; import com.boundlessgeo.service.GeoHeatmapService; import org.elasticsearch.common.component.LifecycleComponent; import org.elasticsearch.common.inject.Module; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.rest.RestModule; import com.google.common.collect.Lists; public class GeoHeatmapPlugin extends Plugin { @Override public String name() { return "GeoHeatmapPlugin"; } @Override public String description() { return "This is a elasticsearch-heatmap plugin."; } public void onModule(final RestModule module) { module.addRestAction(GeoHeatmapRestAction.class); } @Override public Collection<Module> nodeModules() { final Collection<Module> modules = Lists.newArrayList(); modules.add(new GeoHeatmapModule()); return modules; } @SuppressWarnings("rawtypes") @Override public Collection<Class<? extends LifecycleComponent>> nodeServices() { final Collection<Class<? extends LifecycleComponent>> services = Lists.newArrayList(); services.add(GeoHeatmapService.class); return services; } }
31.491803
100
0.735554
6de39255bead752ef1b59e3536e483a2e850b422
906
ts
TypeScript
client/src/api/LocationService.ts
jmartinezgdev/quicargo-trucks-system
69eacc38a32fb049d0813586ab23b7fab2115ce4
[ "Xnet", "X11" ]
null
null
null
client/src/api/LocationService.ts
jmartinezgdev/quicargo-trucks-system
69eacc38a32fb049d0813586ab23b7fab2115ce4
[ "Xnet", "X11" ]
null
null
null
client/src/api/LocationService.ts
jmartinezgdev/quicargo-trucks-system
69eacc38a32fb049d0813586ab23b7fab2115ce4
[ "Xnet", "X11" ]
null
null
null
import httpClient from "./http"; import { Location } from "../interfaces"; const LOCATIONS_PATH = '/locations'; const getAll = (): Promise<Location[]> => { return httpClient.get(LOCATIONS_PATH); } const getById = (id: number): Promise<Location> => { return httpClient.get(`${LOCATIONS_PATH}/${id}`); } const getByTruckId = (truckId: number, limit?: number | null): Promise<Location[]> => { const partialUrl = limit ? `${truckId}?limit=${limit}` : `${truckId}`; return httpClient.get(`${LOCATIONS_PATH}/truck/${partialUrl}`); } const create = (newLocation: Location): Promise<Location> => { return httpClient.post(LOCATIONS_PATH, newLocation); } const remove = (id: number): Promise<void> => { return httpClient.delete(`${LOCATIONS_PATH}/${id}`); } const LocationService = { getAll, getById, getByTruckId, create, remove }; export default LocationService;
25.885714
87
0.666667
0d44bf560838c27f46d4f5e3b94d82a6d181aaad
80
rb
Ruby
spec/faraday/response/decode_tradevan_spec.rb
abookyun/einvoice
872b51a83e31231d36eba47f9c949da3aadecc21
[ "MIT" ]
12
2016-01-18T09:54:06.000Z
2021-03-02T16:56:44.000Z
spec/faraday/response/decode_tradevan_spec.rb
abookyun/einvoice
872b51a83e31231d36eba47f9c949da3aadecc21
[ "MIT" ]
13
2016-01-21T02:09:54.000Z
2021-02-17T04:32:32.000Z
spec/faraday/response/decode_tradevan_spec.rb
abookyun/einvoice
872b51a83e31231d36eba47f9c949da3aadecc21
[ "MIT" ]
2
2016-08-02T11:04:05.000Z
2018-06-11T09:50:55.000Z
require 'spec_helper' RSpec.describe Faraday::Response::DecodeTradevan do end
13.333333
51
0.8125
a32076093d2b4bcd039e05646cdab521d28a3b23
21,353
java
Java
src/main/java/com/hpb/bc/service/impl/TransactionServiceImpl.java
hpb-project/hpb-wallet-middleware
4a9eb3ebc6e8db3ba300908c6da829285a18983d
[ "Apache-2.0" ]
null
null
null
src/main/java/com/hpb/bc/service/impl/TransactionServiceImpl.java
hpb-project/hpb-wallet-middleware
4a9eb3ebc6e8db3ba300908c6da829285a18983d
[ "Apache-2.0" ]
null
null
null
src/main/java/com/hpb/bc/service/impl/TransactionServiceImpl.java
hpb-project/hpb-wallet-middleware
4a9eb3ebc6e8db3ba300908c6da829285a18983d
[ "Apache-2.0" ]
1
2020-09-15T06:33:56.000Z
2020-09-15T06:33:56.000Z
/* * Copyright 2020 HPB Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hpb.bc.service.impl; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import javax.annotation.Resource; import com.hpb.bc.constant.TokenConstant; import com.hpb.bc.entity.ContractErcStandardInfo; import com.hpb.bc.token.mapper.TxTransferRecordMapper; import com.hpb.bc.vo.TokenTypeInfoVo; import com.hpb.bc.example.ContractErcStandardInfoExample; import com.hpb.bc.service.TransactionService; import com.hpb.bc.token.mapper.ContractErcStandardInfoMapper; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.hpb.bc.chain.mapper.TransactionHistoryInfoMapper; import com.hpb.bc.constant.BcConstant; import com.hpb.bc.entity.TransactionHistoryInfo; import com.hpb.bc.entity.result.Result; import com.hpb.bc.entity.result.ResultCode; import com.hpb.bc.exception.ErrorException; import com.hpb.bc.util.NumericUtil; import io.hpb.web3.protocol.admin.Admin; import io.hpb.web3.protocol.core.DefaultBlockParameterName; import io.hpb.web3.protocol.core.Response.Error; import io.hpb.web3.protocol.core.methods.request.Transaction; import io.hpb.web3.protocol.core.methods.response.HpbBlock; import io.hpb.web3.protocol.core.methods.response.HpbBlock.Block; import io.hpb.web3.protocol.core.methods.response.HpbGetTransactionCount; import io.hpb.web3.protocol.core.methods.response.HpbGetTransactionReceipt; import io.hpb.web3.protocol.core.methods.response.HpbSendTransaction; import io.hpb.web3.protocol.core.methods.response.HpbTransaction; import io.hpb.web3.protocol.core.methods.response.TransactionReceipt; @Service public class TransactionServiceImpl extends AbstractBaseService implements TransactionService { @Resource(name = "hpbAdmin") private Admin admin; @Autowired private Token20ServiceImpl token20Service; @Autowired private Token721ServiceImpl token721Service; @Autowired private TransactionServiceImpl transactionService; @Autowired private TransactionHistoryInfoMapper transactionHistoryInfoMapper; @Autowired private ContractErcStandardInfoMapper contractErcStandardInfoMapper; @Autowired private TxTransferRecordMapper txTransferRecordMapper; @Override public Result<io.hpb.web3.protocol.core.methods.response.Transaction> hpbGetTransactionByHash(List<String> reqStrList) { Result<io.hpb.web3.protocol.core.methods.response.Transaction> result = new Result<>(ResultCode.SUCCESS); if (reqStrList == null || reqStrList.size() < 2) { result.result(ResultCode.FAIL.code(), ResultCode.PARAMETER_ERROR.code()); return result; } String transactionHash = reqStrList.get(1); if (!NumericUtil.isValidTxHash(transactionHash)) { result.result(ResultCode.FAIL.code(), ResultCode.INVALID_TXHASH.code()); return result; } try { HpbTransaction hpbTransaction = admin.hpbGetTransactionByHash(transactionHash).send(); Error error = hpbTransaction.getError(); if (null != error) { result.error(error); } else { result.setData(hpbTransaction.getResult()); } } catch (IOException e) { result.exception(e); log.error("processId:[" + reqStrList.get(0) + "]系统异常", e); } return result; } @Override public Result<BigInteger> hpbGetTransactionCount(List<String> reqStrList) { Result<BigInteger> result = new Result<>(ResultCode.SUCCESS); if (reqStrList == null || reqStrList.size() < 2) { result.result(ResultCode.FAIL.code(), ResultCode.PARAMETER_ERROR.code()); return result; } String from = reqStrList.get(1); if (!NumericUtil.isValidAddress(from)) { result.result(ResultCode.FAIL.code(), ResultCode.INVALID_ADDRESS.code()); return result; } try { result = getNonce(from, DefaultBlockParameterName.LATEST.name()); } catch (IOException | ErrorException e) { result.exception(e); log.error("processId:[" + reqStrList.get(0) + "]系统异常", e); } return result; } @Override public Result<String> hpbSendTransaction(List<String> reqStrList) { Result<String> result = new Result<>(ResultCode.SUCCESS); try { Transaction transaction = createTransaction(reqStrList); HpbSendTransaction hpbSendTransaction = admin.hpbSendTransaction(transaction).send(); Error error = hpbSendTransaction.getError(); if (null != error) { result.error(error); } else { result.setData(hpbSendTransaction.getResult()); } } catch (IOException e) { result.exception(e); log.error("processId:[" + reqStrList.get(0) + "]系统异常", e); } return result; } @Override public Result<String> hpbSendRawTransaction(List<String> reqStrList) { Result<String> result = new Result<>(ResultCode.SUCCESS); if (reqStrList == null || reqStrList.size() < 2) { result.result(ResultCode.FAIL.code(), ResultCode.PARAMETER_ERROR.code()); return result; } String input = reqStrList.get(1); if (!NumericUtil.isValidRawTransaction(input)) { result.result(ResultCode.FAIL.code(), ResultCode.INVALID_ADDRESS.code()); return result; } try { HpbSendTransaction hpbSendTransaction = admin.hpbSendRawTransaction(input).send(); Error error = hpbSendTransaction.getError(); if (null != error) { result.error(error); } else { result.setData(hpbSendTransaction.getResult()); } } catch (IOException e) { result.exception(e); log.error("processId:[" + reqStrList.get(0) + "]系统异常", e); } return result; } @Override public Result<TransactionReceipt> hpbGetTransactionReceipt(List<String> reqStrList) { Result<TransactionReceipt> result = new Result<>(ResultCode.SUCCESS); if (reqStrList == null || reqStrList.size() < 2) { result.result(ResultCode.FAIL.code(), ResultCode.PARAMETER_ERROR.code()); return result; } String transactionHash = reqStrList.get(1); if (!NumericUtil.isValidTxHash(transactionHash)) { result.result(ResultCode.FAIL.code(), ResultCode.INVALID_TXHASH.code()); return result; } try { HpbGetTransactionReceipt hpbGetTransactionReceipt = admin.hpbGetTransactionReceipt(transactionHash).send(); Error error = hpbGetTransactionReceipt.getError(); if (null != error) { result.error(error); } else { result.setData(hpbGetTransactionReceipt.getResult()); } } catch (IOException e) { result.exception(e); log.error("processId:[" + reqStrList.get(0) + "]系统异常", e); } return result; } private Transaction createTransaction(List<String> reqStrList) { if (reqStrList == null || reqStrList.size() < 7) { throw new ErrorException(new Error()); } else { String from = reqStrList.get(1); BigInteger nonce = new BigInteger(reqStrList.get(2)); BigInteger gasPrice = new BigInteger(reqStrList.get(3)); BigInteger gasLimit = new BigInteger(reqStrList.get(4)); String to = reqStrList.get(5); BigInteger value = new BigInteger(reqStrList.get(6)); String data = reqStrList.get(7); if (reqStrList.size() > 7) { value = new BigInteger(reqStrList.get(8)); } return Transaction.createFunctionCallTransaction(from, nonce, gasPrice, gasLimit, to, value, data); } } public Result<BigInteger> getNonce(String address, String name) throws IOException { Result<BigInteger> result = new Result<>(ResultCode.SUCCESS); HpbGetTransactionCount transactionCount = admin.hpbGetTransactionCount(address, DefaultBlockParameterName.fromString(name)).send(); Error error = transactionCount.getError(); if (error != null) { result.error(error); } else { result.setData(transactionCount.getTransactionCount()); } return result; } public static final String TX_TYPE_ALL = "0"; public static final String TX_TYPE_FROM = "1"; public static final String TX_TYPE_TO = "2"; @Override public Result<PageInfo<TransactionHistoryInfo>> getTransactionHistory(List<String> reqStrList) { Result<PageInfo<TransactionHistoryInfo>> result = new Result<>(ResultCode.SUCCESS); try { if(reqStrList.size()<2 || StringUtils.isBlank(reqStrList.get(1))) { result.result(ResultCode.FAIL.code(), ResultCode.PARAMETER_ERROR.code()); return result; } String address = reqStrList.get(1); if(!NumericUtil.isValidAddress(address)) { result.result(ResultCode.FAIL.code(), ResultCode.INVALID_ADDRESS.code()); return result; } String type = reqStrList.get(2); int pageNum = Integer.parseInt(reqStrList.get(3)); int pageSize = BcConstant.PAGESIZE_DEFAULT; if(TX_TYPE_ALL.equals(type)) { result.setData(selectTransactionHistoryInfoByAll(address,pageNum,pageSize)); }else if(TX_TYPE_FROM.equals(type)) { result.setData(selectTransactionHistoryInfoByPage(address,null,pageNum,pageSize)); }else if(TX_TYPE_TO.equals(type)) { result.setData(selectTransactionHistoryInfoByPage(null,address,pageNum,pageSize)); } } catch (IOException e) { result.exception(e); log.error("processId:["+reqStrList.get(0)+"]系统异常",e); } return result; } public Result<PageInfo<TransactionHistoryInfo>> getTransactionHistoryNew(List<String> reqStrList) { Result<PageInfo<TransactionHistoryInfo>> result = new Result<>(ResultCode.SUCCESS); try { if (reqStrList.size() < 2 || StringUtils.isBlank(reqStrList.get(1))) { result.result(ResultCode.FAIL.code(), ResultCode.PARAMETER_ERROR.code()); return result; } String address = reqStrList.get(1); if (!NumericUtil.isValidAddress(address)) { result.result(ResultCode.FAIL.code(), ResultCode.INVALID_ADDRESS.code()); return result; } String type = reqStrList.get(6); int pageNum = Integer.parseInt(reqStrList.get(5)); int pageSize = BcConstant.PAGESIZE_DEFAULT; if (TX_TYPE_ALL.equals(type)) { result.setData(selectTransactionHistoryInfoByAll(address, pageNum, pageSize)); } else if (TX_TYPE_FROM.equals(type)) { result.setData(selectTransactionHistoryInfoByPage(address, null, pageNum, pageSize)); } else if (TX_TYPE_TO.equals(type)) { result.setData(selectTransactionHistoryInfoByPage(null, address, pageNum, pageSize)); } } catch (IOException e) { result.exception(e); log.error("processId:[" + reqStrList.get(0) + "]系统异常", e); } return result; } private PageInfo<TransactionHistoryInfo> selectTransactionHistoryInfoByPage(String txFrom, String txTo, int pageNum, int pageSize) throws IOException { Map<String, Object> example = new HashMap<>(); example.put("txFrom", txFrom); example.put("txTo", txTo); PageHelper.startPage(pageNum, pageSize); List<TransactionHistoryInfo> transactionHistoryInfoByPage = transactionHistoryInfoMapper.selectTransactionHistoryInfoByPage(example); PageInfo<TransactionHistoryInfo> data = new PageInfo<>(transactionHistoryInfoByPage); if (data.getSize() > 0) { List<TransactionHistoryInfo> list = data.getList(); for (TransactionHistoryInfo transactionHistoryInfo : list) { String hash = transactionHistoryInfo.getTransactionHash(); HpbGetTransactionReceipt hpbGetTransactionReceipt = admin.hpbGetTransactionReceipt(hash).send(); if (!hpbGetTransactionReceipt.hasError()) { TransactionReceipt transactionReceipt = hpbGetTransactionReceipt.getResult(); transactionHistoryInfo.setStatus(transactionReceipt.getStatus()); transactionHistoryInfo.setGasUsed(transactionReceipt.getGasUsed().toString()); } String blockHash = transactionHistoryInfo.getBlockHash(); HpbBlock hpbBlock = admin.hpbGetBlockByHash(blockHash, false).send(); if (!hpbBlock.hasError()) { Block block = hpbBlock.getBlock(); transactionHistoryInfo.settTimestap(block.getTimestamp().longValue()); } } data.setList(list); } return data; } private PageInfo<TransactionHistoryInfo> selectTransactionHistoryInfoByAll(String address, int pageNum, int pageSize) throws IOException { Map<String, Object> example = new HashMap<>(); example.put("address", address); PageHelper.startPage(pageNum, pageSize); List<TransactionHistoryInfo> transactionHistoryInfoByPage = transactionHistoryInfoMapper.selectTransactionHistoryInfoByAll(example); PageInfo<TransactionHistoryInfo> data = new PageInfo<>(transactionHistoryInfoByPage); if (data.getSize() > 0) { List<TransactionHistoryInfo> list = data.getList(); for (TransactionHistoryInfo transactionHistoryInfo : list) { String hash = transactionHistoryInfo.getTransactionHash(); HpbGetTransactionReceipt hpbGetTransactionReceipt = admin.hpbGetTransactionReceipt(hash).send(); if (!hpbGetTransactionReceipt.hasError()) { TransactionReceipt transactionReceipt = hpbGetTransactionReceipt.getResult(); if (transactionReceipt!=null){ transactionHistoryInfo.setStatus(transactionReceipt.getStatus()); transactionHistoryInfo.setGasUsed(transactionReceipt.getGasUsed().toString()); String blockHash = transactionReceipt.getBlockHash(); HpbBlock hpbBlock = admin.hpbGetBlockByHash(blockHash, false).send(); if (!hpbBlock.hasError()) { Block block = hpbBlock.getBlock(); transactionHistoryInfo.settTimestap(block.getTimestamp().longValue()); } } } } data.setList(list); } return data; } @Override public Result<TransactionHistoryInfo> getTransactionDetail(List<String> reqStrList) { Result<TransactionHistoryInfo> result = new Result<>(ResultCode.SUCCESS); try { String hash = reqStrList.get(1); Map<String, Object> example = new HashMap<>(); example.put("hash", hash); TransactionHistoryInfo transactionHistoryInfo = transactionHistoryInfoMapper.selectTransactionHistoryInfoByHash(example); HpbGetTransactionReceipt hpbGetTransactionReceipt = admin.hpbGetTransactionReceipt(hash).send(); if (hpbGetTransactionReceipt.hasError()) { result.error(hpbGetTransactionReceipt.getError()); return result; } TransactionReceipt transactionReceipt = hpbGetTransactionReceipt.getResult(); transactionHistoryInfo.setStatus(transactionReceipt.getStatus()); transactionHistoryInfo.setGasUsed(transactionReceipt.getGasUsed().toString()); String blockHash = transactionHistoryInfo.getBlockHash(); HpbBlock hpbBlock = admin.hpbGetBlockByHash(blockHash, false).send(); if (hpbBlock.hasError()) { result.error(hpbBlock.getError()); return result; } Block block = hpbBlock.getBlock(); transactionHistoryInfo.settTimestap(block.getTimestamp().longValue()); result.setData(transactionHistoryInfo); } catch (IOException e) { result.exception(e); log.error("processId:[" + reqStrList.get(0) + "]系统异常", e); } return result; } @Override public Result<Map<String, Object>> historyList(List<String> reqStrList) { Result<Map<String, Object>> result = new Result<>(ResultCode.SUCCESS); try { String addr = reqStrList.get(1); String contractType = reqStrList.get(2); Map<String, Object> resMap = new HashMap<>(); if (null == reqStrList || reqStrList.size() != 7 || !NumericUtil.isValidAddress(addr)) { result.result(ResultCode.FAIL.code(), ResultCode.PARAMETER_ERROR.code()); return result; } PageInfo<TransactionHistoryInfo> pageInfo = null; if (contractType.equals(TokenConstant.HRC20)) { pageInfo = token20Service.list(reqStrList); } else if (contractType.equals(TokenConstant.HRC721)) { pageInfo = token721Service.get721transferRecord(reqStrList); } else if (contractType.equals(TokenConstant.HPB)) { Result<PageInfo<TransactionHistoryInfo>> transactionHistory = transactionService.getTransactionHistoryNew(reqStrList); pageInfo = transactionHistory.getData(); } resMap.put("total", pageInfo.getTotal()); resMap.put("pageNum", pageInfo.getPageNum()); resMap.put("pages", pageInfo.getPages()); resMap.put("list", pageInfo.getList()); result.setData(resMap); return result; } catch (Exception e) { log.error("【查询交易记录失败 reqParam:{} {} {} {} {}】", e.getMessage(), e); result.result(ResultCode.FAIL.code(), ResultCode.EXCEPTION.code()); return result; } } @Override public Result<Map<String, Object>> getTypeList(List<String> reqStrList) { Result<Map<String, Object>> result = new Result<>(ResultCode.SUCCESS); try { String address = reqStrList.get(1); String contractType = reqStrList.get(2); if (null == reqStrList || reqStrList.size() != 3 ) { result.result(ResultCode.FAIL.code(), ResultCode.PARAMETER_ERROR.code()); return result; } contractType = TokenConstant.HRC20.equalsIgnoreCase(contractType)? TokenConstant.ERC20:TokenConstant.ERC721; List<String> recordContrscts = txTransferRecordMapper.selectContractAddrsByAddr(address); List<TokenTypeInfoVo> infoVoList = new ArrayList<>(); if(null != recordContrscts && recordContrscts.size()>0){ ContractErcStandardInfoExample example = new ContractErcStandardInfoExample(); example.createCriteria().andContractTypeEqualTo(contractType).andContractAddressIn(recordContrscts); List<ContractErcStandardInfo> standardInfos = contractErcStandardInfoMapper.selectByExample(example); for(ContractErcStandardInfo info: standardInfos){ TokenTypeInfoVo tokenTypeInfo = new TokenTypeInfoVo(); tokenTypeInfo.setContractAddress(info.getContractAddress()); tokenTypeInfo.setTokenSymbol(info.getTokenSymbol()); infoVoList.add(tokenTypeInfo); } } Map<String, Object> map = new HashMap<>(); map.put("list", infoVoList); result.setData(map); return result; } catch (Exception e) { log.error("【代币管理查询失败 reqParam:{} {} 】", reqStrList.toArray(new String[reqStrList.size()]), e.getMessage(), e); result.result(ResultCode.FAIL.code(), ResultCode.EXCEPTION.code()); return result; } } }
46.218615
155
0.638458
afe027afc39b16290f240f40dc5b69f1bd0733e0
2,433
rs
Rust
src/builtins.rs
nonk123/bloodbath
7d5ca5e5bbe70a96dd6aa6f414860637a5fe552e
[ "MIT" ]
null
null
null
src/builtins.rs
nonk123/bloodbath
7d5ca5e5bbe70a96dd6aa6f414860637a5fe552e
[ "MIT" ]
null
null
null
src/builtins.rs
nonk123/bloodbath
7d5ca5e5bbe70a96dd6aa6f414860637a5fe552e
[ "MIT" ]
null
null
null
use crate::object::Object; pub fn add(args: Vec<Object>) -> Object { if let Some(a) = args[0].get_integer() { if let Some(b) = args[1].get_integer() { return Object::Integer(a + b); } else if let Some(b) = args[1].get_float() { return Object::Float(a as f64 + b); } } else if let Some(a) = args[0].get_float() { if let Some(b) = args[1].get_integer() { return Object::Float(a + b as f64); } else if let Some(b) = args[1].get_float() { return Object::Float(a + b); } } Object::Noop } pub fn sub(args: Vec<Object>) -> Object { if let Some(a) = args[0].get_integer() { if let Some(b) = args[1].get_integer() { return Object::Integer(a - b); } else if let Some(b) = args[1].get_float() { return Object::Float(a as f64 - b); } } else if let Some(a) = args[0].get_float() { if let Some(b) = args[1].get_integer() { return Object::Float(a - b as f64); } else if let Some(b) = args[1].get_float() { return Object::Float(a - b); } } Object::Noop } pub fn mul(args: Vec<Object>) -> Object { if let Some(a) = args[0].get_integer() { if let Some(b) = args[1].get_integer() { return Object::Integer(a * b); } else if let Some(b) = args[1].get_float() { return Object::Float(a as f64 * b); } } else if let Some(a) = args[0].get_float() { if let Some(b) = args[1].get_integer() { return Object::Float(a * b as f64); } else if let Some(b) = args[1].get_float() { return Object::Float(a * b); } } Object::Noop } pub fn div(args: Vec<Object>) -> Object { if let Some(a) = args[0].get_integer() { if let Some(b) = args[1].get_integer() { if a % b == 0 { return Object::Integer(a / b); } else { return Object::Float(a as f64 / b as f64); } } else if let Some(b) = args[1].get_float() { return Object::Float(a as f64 / b); } } else if let Some(a) = args[0].get_float() { if let Some(b) = args[1].get_integer() { return Object::Float(a / b as f64); } else if let Some(b) = args[1].get_float() { return Object::Float(a / b); } } Object::Noop }
31.192308
58
0.495684
b2f494dbc658ae0c5f3fa06881bc5c83d74ee99e
78
css
CSS
wp-content/themes/ElegantEstate3.6/includes/meta-box/css/checkbox.css
WebModerna/18._Inmobiliariadelassierras
86730cdafbdce35d1820b8b681cc777df0c919c0
[ "MIT" ]
null
null
null
wp-content/themes/ElegantEstate3.6/includes/meta-box/css/checkbox.css
WebModerna/18._Inmobiliariadelassierras
86730cdafbdce35d1820b8b681cc777df0c919c0
[ "MIT" ]
null
null
null
wp-content/themes/ElegantEstate3.6/includes/meta-box/css/checkbox.css
WebModerna/18._Inmobiliariadelassierras
86730cdafbdce35d1820b8b681cc777df0c919c0
[ "MIT" ]
null
null
null
.rwmb-checkbox-wrapper .description { display: inline; font-style: normal; }
19.5
37
0.74359
8c131a926ecddca45958dd35691aa8d1e8fdfd63
1,203
cs
C#
GroceryBagBlitzUnity/Assets/Scripts/TitleScreenSpawner.cs
AriTAF/Grocery-Bag-Blitz
0a4623d75cf073942ef3834180a0559c9d993731
[ "MIT" ]
null
null
null
GroceryBagBlitzUnity/Assets/Scripts/TitleScreenSpawner.cs
AriTAF/Grocery-Bag-Blitz
0a4623d75cf073942ef3834180a0559c9d993731
[ "MIT" ]
null
null
null
GroceryBagBlitzUnity/Assets/Scripts/TitleScreenSpawner.cs
AriTAF/Grocery-Bag-Blitz
0a4623d75cf073942ef3834180a0559c9d993731
[ "MIT" ]
null
null
null
/**** * Created by: Krieger * Date Created: Mar 7, 2022 * * Last Edited by: Krieger * Last Edited: March 7, 2022 * * Description: Script that spawns a rain of random items on the Title Screen ****/ using System.Collections; using System.Collections.Generic; using UnityEngine; public class TitleScreenSpawner : MonoBehaviour { public float itemSpawnChance = .2f; public float itemSpawnRangeX = 10; private GameManager gm; private List<GameObject> items; // Start is called before the first frame update void Start() { gm = GameManager.GM; items = gm.items; } // Update is called once per frame void FixedUpdate() { float itemSpawn = Random.Range(0f, 1f); if(itemSpawn < itemSpawnChance) { SpawnItem(); } } void SpawnItem() { int itemSelected = Random.Range(0, items.Count); GameObject newItem = Instantiate<GameObject>(items[itemSelected]); Vector3 itemPos = this.transform.position; float newX = Random.Range(-itemSpawnRangeX, itemSpawnRangeX); itemPos.x = newX; newItem.transform.position = itemPos; } }
23.134615
77
0.630091
ee9c6434dc87bdf3b45a02b1a5075db6b1fddbd4
2,176
go
Go
fmd_examples_test.go
biztos/frostedmd
321a9f4511c9173bf9552004db7927d39cc09af5
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
fmd_examples_test.go
biztos/frostedmd
321a9f4511c9173bf9552004db7927d39cc09af5
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
fmd_examples_test.go
biztos/frostedmd
321a9f4511c9173bf9552004db7927d39cc09af5
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
// frostedmd/fmd_examples_test.go -- examples for Frosted Markdown. // ------------------------------ package frostedmd_test import ( "fmt" "github.com/biztos/frostedmd" ) func Example() { // NOTE: due to a godoc bug, the following text may not appear correctly. // The "# Meta" line and the "Tags" line are both indented (four spaces). // https://github.com/golang/go/issues/18446 // The easiest way to get things done: input := `# My Markdown # Meta: Tags: ["fee","fi","foe"] Obscurantism threatens clean data. ` res, err := frostedmd.MarkdownCommon([]byte(input)) if err != nil { panic(err) } mm := res.Meta fmt.Println("Title:", mm["Title"]) fmt.Println("Tags:", mm["Tags"]) fmt.Println("HTML:", string(res.Content)) // Output: // Title: My Markdown // Tags: [fee fi foe] // HTML: <h1>My Markdown</h1> // // <p>Obscurantism threatens clean data.</p> } func ExampleNew() { input := `# Lots of Data Here we have a full dataset, which (for instance) a template engine will turn into something cool and dynamic. Thus we put it at the end so we can read our nice summary using the *head* command. { "datasets": { "numbers": [11,22,33,44,55,66], "letters": ["a","B","ß","í"] } } ` parser := frostedmd.New() parser.MetaAtEnd = true res, err := parser.Parse([]byte(input)) if err != nil { panic(err) } mm := res.Meta fmt.Println("Title:", mm["Title"]) fmt.Println("HTML:", string(res.Content)) // Order within a map is random in Go, so let's make it explicit. fmt.Println("Data sets:") if ds, ok := mm["datasets"].(map[string]interface{}); ok { fmt.Println(" numbers:", ds["numbers"]) fmt.Println(" letters:", ds["letters"]) } else { fmt.Printf("NOT A MAP: %T\n", mm["datasets"]) } // Output: // Title: Lots of Data // HTML: <h1>Lots of Data</h1> // // <p>Here we have a full dataset, which (for instance) a template engine // will turn into something cool and dynamic. Thus we put it at the end // so we can read our nice summary using the <em>head</em> command.</p> // // Data sets: // numbers: [11 22 33 44 55 66] // letters: [a B ß í] }
23.652174
74
0.616268
641913ee547c57a23701ac912d4cbe44560c4175
32,054
py
Python
RepCRec/TransactionManager.py
apsdehal/RepCRec
82f5d062752be5643ad6dbab10bf5d51cbdc9f97
[ "MIT" ]
null
null
null
RepCRec/TransactionManager.py
apsdehal/RepCRec
82f5d062752be5643ad6dbab10bf5d51cbdc9f97
[ "MIT" ]
null
null
null
RepCRec/TransactionManager.py
apsdehal/RepCRec
82f5d062752be5643ad6dbab10bf5d51cbdc9f97
[ "MIT" ]
null
null
null
""" Authors: Amanpreet Singh Sharan Agrawal """ import logging from collections import defaultdict from .Transaction import Transaction from .Lock import Lock from .LockTable import LockTable from .enums.LockAcquireStatus import LockAcquireStatus from .enums.LockType import LockType from .enums.TransactionStatus import TransactionStatus from .enums.InstructionType import InstructionType from .constants import BEGIN_FUNC, BEGIN_READ_ONLY_FUNC, WRITE_FUNC, \ READ_FUNC, END_FUNC log = logging.getLogger(__name__) class TransactionManager: """ Transaction manager class is reponsible for processing transactions and deadlock detection and resolution. It is also responsible for calling site manager to clear locks when a transaction commits. Attributes: num_vars (int): Number of variables num_sites (int): Number of sites lock_table (class object): Global instance of LockTable site_manager (class object): Global instance of SiteManager transaction_map (dict): Maps transaction name to Transaction class object blocked_transactions (dict): stores blocked transaction name mapped to blocking transaction tuple (transaction name, lock type, variable, .) waiting_transaction (dict): stores waiting transaction name mapped to a tuple containing relevant information """ def __init__(self, num_vars, num_sites, lock_table, site_manager): self.number_of_variables = num_vars self.number_of_sites = num_sites self.transaction_map = dict() self.lock_table = lock_table self.site_manager = site_manager self.current_time = 0 self.blocked_transactions = defaultdict(dict) self.waiting_transactions = defaultdict(dict) def tick(self, instruction): """ Method responsible for calling other methods based on instruction type. Also checks for deadlocks on every tick Args: instruction : object of class Instruction, contains the current instruction """ self.current_time += 1 self.clear_aborted() self.detect_and_clear_deadlocks() self.blocked_to_waiting() self.try_waiting() params = list(instruction.get_params()) # log.info(params, instruction.get_instruction_type()) if instruction.get_instruction_type() == BEGIN_FUNC: self.begin(params) elif instruction.get_instruction_type() == \ BEGIN_READ_ONLY_FUNC: self.begin_read_only(params) elif instruction.get_instruction_type() == READ_FUNC: self.read_request(params) elif instruction.get_instruction_type() == WRITE_FUNC: self.write_request(params) elif instruction.get_instruction_type() == END_FUNC: self.end(params) else: log.info("We have a problem") def begin(self, params): """ Method responsible for initializing a transaction and making a new instance of Transaction class Args: params : list of parameters of the parsed instruction, containing instruction name """ current_index = len(self.transaction_map) log.info("Starting " + params[0]) self.transaction_map[str(params[0])] = Transaction( current_index, params[0]) return def begin_read_only(self, params): """ Method responsible for initializing a read only transaction and making a new instance of Transaction class Args: params : list of parameters of the parsed instruction, containing instruction name """ current_index = len(self.transaction_map) log.info("Starting read only transaction " + params[0]) self.transaction_map[params[0]] = Transaction( current_index, params[0], True) self.transaction_map[ params[0]].variable_values = \ self.site_manager.get_current_variables() def write_request(self, params): """ Method responsible for processing a write request, gets write locks on the variable to be written, in case it is not able to get locks, changes status to blocked or waiting according to situation. Also inserts transactions in waiting or blocked transaction dicts as required. Args: params : list of parameters of the parsed instruction, containing instruction name """ transaction_name = params[0] variable = params[1] value = int(params[2]) if transaction_name not in self.transaction_map: return transaction = self.transaction_map[transaction_name] is_waiting = transaction.get_status() == TransactionStatus.WAITING is_running = transaction.get_status() == TransactionStatus.RUNNING if not (is_waiting or is_running): return if self.lock_table.is_locked_by_transaction(transaction, variable, LockType.WRITE): self.lock_table.set_lock(transaction, LockType.WRITE, variable) log.info(transaction.name + " already has a write lock on " + variable) transaction.uncommitted_variables[variable] = value transaction.set_status(TransactionStatus.RUNNING) return lock_acquire_status = self.site_manager.get_locks(transaction, LockType.WRITE, variable) if lock_acquire_status == LockAcquireStatus.GOT_LOCK: log.info(transaction.name + " got write lock on " + variable) self.lock_table.set_lock(transaction, LockType.WRITE, variable) transaction.uncommitted_variables[variable] = value squashed_waiting_transactions = \ self.get_squashed_waiting_transactions() if transaction.name in squashed_waiting_transactions: for waiting_tuple in squashed_waiting_transactions[ transaction.name]: if waiting_tuple[1] != variable: return transaction.set_status(TransactionStatus.RUNNING) elif lock_acquire_status == LockAcquireStatus.ALL_SITES_DOWN: waiting_txn_tuple = (InstructionType.WRITE, variable, value) squashed_waiting_transactions = \ self.get_squashed_waiting_transactions() if transaction.name in squashed_waiting_transactions: if waiting_txn_tuple in squashed_waiting_transactions[ transaction.name]: return log.info(transaction.name + " is waiting on " + variable) transaction.set_status(TransactionStatus.WAITING) self.waiting_transactions[self.current_time][ transaction.name] = waiting_txn_tuple else: for lock in self.site_manager.get_set_locks().lock_map[variable]: blocking_transaction = lock.transaction.name if lock.transaction == transaction: continue blocking_txn_tuple = (blocking_transaction, InstructionType.WRITE, variable, value) squashed_blocking_transactions = \ self.get_squashed_blocked_transactions() if transaction.name in squashed_blocking_transactions: if blocking_txn_tuple in squashed_blocking_transactions[ transaction.name]: return log.info(transaction.name + " is blocked for a write lock by " + blocking_transaction + " on " + variable) transaction.set_status(TransactionStatus.BLOCKED) self.current_time += 1 self.blocked_transactions[self.current_time][ transaction_name] = blocking_txn_tuple def read_request_read_only(self, transaction, variable, transaction_name, try_waiting): """ Method responsible for processing a read request from a read only transaction, if the site holding the variable is down, it waits for the site to be up and then reads the variable. Args: params : list of parameters of the parsed instruction, containing instruction name """ if try_waiting: val = self.site_manager.get_current_variables(variable) if val is None: transaction.variable_values[variable] = val else: return if variable in transaction.variable_values: if variable not in transaction.read_variables: transaction.read_variables[variable] = list() transaction.read_variables[ variable].append(transaction.variable_values[variable]) squashed_waiting_transactions = \ self.get_squashed_waiting_transactions() if transaction.name in squashed_waiting_transactions: for waiting_tuple in squashed_waiting_transactions[ transaction.name]: if waiting_tuple[1] != variable: return transaction.set_status(TransactionStatus.RUNNING) else: waiting_txn = (InstructionType.READ_ONLY, variable) squashed_waiting_transactions = \ self.get_squashed_waiting_transactions() if transaction_name in squashed_waiting_transactions: if waiting_txn_tuple in squashed_waiting_transactions[ transaction_name]: return transaction.set_status(TransactionStatus.WAITING) log.info(transaction.name + " is waiting on " + variable) self.waiting_transactions[self.current_time][ transaction_name] = waiting_txn return def read_request(self, params, try_waiting=False): """ Method responsible for processing a read request, gets read locks on the variable to be written, in case it is not able to get locks, changes status to blocked or waiting according to situation. Also inserts transactions in waiting or blocked transaction dicts as required. Args: params : list of parameters of the parsed instruction, containing instruction name """ transaction_name = params[0] variable = params[1] if transaction_name not in self.transaction_map: return transaction = self.transaction_map[transaction_name] is_waiting = transaction.get_status() == TransactionStatus.WAITING is_running = transaction.get_status() == TransactionStatus.RUNNING if not (is_waiting or is_running): return if transaction.is_read_only: self.read_request_read_only( transaction, variable, transaction_name, try_waiting) else: if self.lock_table.is_locked_by_transaction(transaction, variable, LockType.WRITE): val = transaction.uncommitted_variables[variable] log.info(transaction.name + " got read lock on " + variable + " having value " + str(val)) if variable not in transaction.read_variables: transaction.read_variables[variable] = list() transaction.read_variables[variable].append(val) return if self.lock_table.is_locked_by_transaction(transaction, variable, LockType.READ): self.lock_table.set_lock(transaction, LockType.READ, variable) log.info(transaction.name + " already has a read lock on " + variable) transaction.set_status(TransactionStatus.RUNNING) return for time in list(self.blocked_transactions): blocked_tuple_dict = self.blocked_transactions[time] for key in list(blocked_tuple_dict): blocked_tuple = blocked_tuple_dict[key] # print(len(blocked_tuple), variable) if len(blocked_tuple) == 4 and \ blocked_tuple[2] == variable: for lock in self.lock_table.lock_map[variable]: blocking_transaction = lock.transaction.name if lock.transaction == transaction: continue blocking_txn_tuple = (blocking_transaction, InstructionType.READ, variable) transaction.set_status(TransactionStatus.BLOCKED) self.blocked_transactions[self.current_time][ transaction_name] = blocking_txn_tuple log.info(transaction_name + " will not get a " + "read lock on " + variable + " because " + key + " is already waiting for a write lock") return lock_acquire_status = self.site_manager.get_locks( transaction, LockType.READ, variable) if lock_acquire_status == LockAcquireStatus.GOT_LOCK or \ lock_acquire_status == \ LockAcquireStatus.GOT_LOCK_RECOVERING: if lock_acquire_status == LockAcquireStatus.GOT_LOCK: log.info(transaction.name + " got read lock on " + variable + " having value " + str(self.site_manager.get_current_variables( variable))) else: log.info("Although, the site holding " + variable + " is recovering, " + transaction.name + " got read lock on " + variable + " having value " + str(self.site_manager.get_current_variables( variable)) + " since its the only copy") if variable not in transaction.read_variables: transaction.read_variables[variable] = list() curr_variable = self.site_manager.get_current_variables( variable) transaction.read_variables[ variable].append(curr_variable) self.lock_table.set_lock(transaction, LockType.READ, variable) squashed_waiting_transactions = \ self.get_squashed_waiting_transactions() if transaction.name in squashed_waiting_transactions: for waiting_tuple in squashed_waiting_transactions[ transaction.name]: if waiting_tuple[1] != variable: return transaction.set_status(TransactionStatus.RUNNING) elif lock_acquire_status == LockAcquireStatus.ALL_SITES_DOWN: waiting_txn_tuple = (InstructionType.READ, variable) squashed_waiting_transactions = \ self.get_squashed_waiting_transactions() if transaction.name in squashed_waiting_transactions: if waiting_txn_tuple in squashed_waiting_transactions[ transaction.name]: return log.info(transaction.name + " is waiting on " + variable) transaction.set_status(TransactionStatus.WAITING) self.waiting_transactions[self.current_time][ transaction.name] = waiting_txn_tuple else: for lock in self.site_manager.get_set_locks().lock_map[ variable]: blocking_transaction = lock.transaction.name if lock.transaction == transaction: continue blocking_txn_tuple = (blocking_transaction, InstructionType.READ, variable) squashed_blocking_transactions = \ self.get_squashed_blocked_transactions() if transaction.name in squashed_blocking_transactions: if blocking_txn_tuple in \ squashed_blocking_transactions[ transaction.name]: return log.info(transaction.name + " is blocked by " + blocking_transaction + " on " + variable) transaction.set_status(TransactionStatus.BLOCKED) self.blocked_transactions[self.current_time][ transaction_name] = blocking_txn_tuple self.current_time += 1 return def clear_aborted(self): """ Method responsible for clearing transactions aborted due to site failure. Excplicitely calls the abort function for them. """ to_pop = list() for trn_name in list(self.transaction_map): transaction = self.transaction_map[trn_name] if transaction.get_status() == TransactionStatus.ABORTED: to_pop.append(trn_name) self.abort(trn_name) def detect_and_clear_deadlocks(self): """ Method responsible for detecting and clearing deadlocks. Traverses through blocked transactions and tries to detect deadlock on each of them. """ squashed_blocked_transactions = \ self.get_squashed_blocked_transactions() for x in list(squashed_blocked_transactions): visited = dict() current = [] self.detect_deadlock( x, visited, current, squashed_blocked_transactions) def detect_deadlock(self, transaction, visited, current, blocked_dict): """ Method responsible for detecting deadlock and calling the clear_deadlock function when necessary. Args: transaction (str) : name of the blocked transaction visited (dict) : stores index of each transaction visited current (list) : list of all transactions which may be involved in a deadlock blocked_list (dict) : stores blocked transactions and the tuple containing information about the blocker """ is_aborted = self.transaction_map[transaction].get_status() \ == TransactionStatus.ABORTED is_committed = self.transaction_map[transaction].get_status() \ == TransactionStatus.COMMITTED if transaction in blocked_dict and not is_aborted and not is_committed: visited[transaction] = len(current) + 1 current.append(transaction) for block in blocked_dict[transaction]: block = block[0] if self.transaction_map[block].get_status() == \ TransactionStatus.ABORTED: continue if block in visited: self.clear_deadlock(current, visited[block] - 1) else: self.detect_deadlock(block, visited, current, blocked_dict) current.pop() visited.pop(transaction) def clear_deadlock(self, transaction_list, index): """ Method responsible for resolving deadlock after it has been detected by aborting the youngest transaction involved. Args: transaction_list (list) : list of all transactions visited index (int) : index of the first transaction involved in deadlock """ transaction_list = transaction_list[index:] max_id = -1 max_name = None for name in transaction_list: transaction = self.transaction_map[name] is_committed = transaction.get_status() == \ TransactionStatus.ABORTED is_aborted = transaction.get_status() == \ TransactionStatus.COMMITTED if is_committed or is_aborted: return if max_id < transaction.id: max_id = self.transaction_map[name].id max_name = name log.info(max_name + " aborted as it is youngest in a deadlock") self.abort(max_name) def get_squashed_blocked_transactions(self): """ Method responsible for squashing the default dict self.blocked_transactions (based on current time as key) into a default dict based on transaction name as key. """ squashed_blocked_transactions = defaultdict(list) for blocked_dicts in self.blocked_transactions.values(): for transaction_name in list(blocked_dicts): blocked_tuple = blocked_dicts[transaction_name] squashed_blocked_transactions[ transaction_name].append(blocked_tuple) return squashed_blocked_transactions def get_squashed_waiting_transactions(self): """ Method responsible for squashing the default dict self.waiting_transactions (based on current time as key) into a default dict based on transaction name as key. """ squashed_waiting_transactions = defaultdict(list) for waiting_dicts in self.waiting_transactions.values(): for transaction_name in list(waiting_dicts): waiting_tuple = waiting_dicts[transaction_name] squashed_waiting_transactions[ transaction_name].append(waiting_tuple) return squashed_waiting_transactions def blocked_to_waiting(self): """ Method responsible for trying to resolve blocked transactions by checking if the transaction blocking them has been committed or aborted. If so, it changes the status of the blocked transaction to waiting. """ to_pop = list() squashed_blocked_transactions = \ self.get_squashed_blocked_transactions() for blocked_dict_key in sorted(self.blocked_transactions.keys()): items = list(self.blocked_transactions[blocked_dict_key]) for key in items: blocked_tuple = self.blocked_transactions[ blocked_dict_key][key] is_clear = True # for blocking_transaction in block: block = self.transaction_map[blocked_tuple[0]] is_aborted = block.get_status() == TransactionStatus.ABORTED is_committed = block.get_status() == \ TransactionStatus.COMMITTED is_clear = is_clear & (is_aborted or is_committed) if is_clear: to_delete = None for blocker_tuple in squashed_blocked_transactions[key]: if blocker_tuple[0] == block.name: to_delete = blocker_tuple break squashed_blocked_transactions[key].remove(to_delete) to_pop.append((blocked_dict_key, key)) if len(squashed_blocked_transactions[key]) == 0: flag = 0 squashed_waiting_transactions = \ self.get_squashed_waiting_transactions() if key in squashed_waiting_transactions: for bl_tuple in squashed_waiting_transactions[key]: if bl_tuple == blocked_tuple[1:]: flag = 1 break if flag: continue self.waiting_transactions[self.current_time][ key] = blocked_tuple[1:] transaction = self.transaction_map[key] transaction.set_status(TransactionStatus.WAITING) for key in to_pop: self.blocked_transactions[key[0]].pop(key[1]) def abort(self, name): """ Method responsible for aborting transactions. It clears the transaction from blocked and waiting dicts. Args: name (str): name of the transaction to be aborted """ to_pop_blocked = list() to_pop_waiting = list() for time in sorted(self.blocked_transactions.keys()): if name in self.blocked_transactions[time]: to_pop_blocked.append((time, name)) for key in to_pop_blocked: self.blocked_transactions[key[0]].pop(key[1]) for time in self.waiting_transactions.keys(): if name in self.waiting_transactions[time]: to_pop_waiting.append((time, name)) for key in to_pop_waiting: self.waiting_transactions[key[0]].pop(key[1]) transaction = self.transaction_map[name] transaction.set_status(TransactionStatus.ABORTED) self.clear_locks(transaction) return def clear_locks(self, transaction): """ Method responsible for clearing locks of transactions. It clears the transaction locks in the global lock table as well as the lock tables controlled by site manager. Args: transaction (Object of class Transaction): transaction whose locks have to be cleared """ lock_map = self.site_manager.get_set_locks().get_lock_map() for var_name in sorted(list(lock_map)): locks = lock_map[var_name] for lock in locks: if lock.transaction == transaction: self.site_manager.clear_locks(lock, var_name) log.debug("Clearing site locks for " + transaction.name + " variable: " + var_name) if self.lock_table.clear_lock(lock, var_name): log.info("Clearing locks for " + transaction.name + " variable: " + var_name) def try_waiting(self): """ Method responsible for getting locks for waiting transaactions. Traverses through the waiting transactions and tries to get locks for them, to change their status to running. """ to_pop = list() for time in list(self.waiting_transactions): waiting_dicts = self.waiting_transactions[time] for transaction in list(waiting_dicts): params = waiting_dicts[transaction] transaction_obj = self.transaction_map[transaction] transaction_obj.set_status(TransactionStatus.WAITING) if params[0] == InstructionType.WRITE: self.write_request((transaction, params[1], params[2])) elif params[0] == InstructionType.READ: self.read_request((transaction, params[1])) elif params[0] == InstructionType.READ_ONLY: self.read_request((transaction, params[1]), True) if self.transaction_map[transaction].get_status() == \ TransactionStatus.RUNNING: to_pop.append((time, transaction)) for key in to_pop: self.waiting_transactions[key[0]].pop(key[1]) def commit_transaction(self, name): """ Method responsible for commiting transactions when we recieve an end instruction. It traverses through the list of uncommitted variables and writes the values on the respective sites. """ status = self.transaction_map[name].get_status() if status == TransactionStatus.COMMITTED or \ status == TransactionStatus.ABORTED: return transaction = self.transaction_map[name] read_variables = transaction.get_read_variables() for variable, values in read_variables.items(): for value in values: log.info(name + " read the value " + str(value) + " of variable " + variable) uncommited_variables = transaction.get_uncommitted_variables() for variable, value in uncommited_variables.items(): for i in range(1, self.number_of_sites + 1): var = int(variable[1:]) if var % 2 == 0 or ((var % 10) + 1) == i: site = self.site_manager.get_site(i) site.write_variable(transaction, variable, value) self.transaction_map[name].set_status(TransactionStatus.COMMITTED) def end(self, params): """ Method called when we recieve an end instruction. Calls commit_transaction and clears the transaction from blocked and waiting dicts. Also clears locks held by transaction. Args: params(list) : contains the transaction name to be committed """ status = self.transaction_map[params[0]].get_status() if status == TransactionStatus.COMMITTED or \ status == TransactionStatus.ABORTED: return self.commit_transaction(params[0]) log.info(params[0] + " committed") self.clear_locks(self.transaction_map[params[0]]) squashed_blocked_transactions = \ self.get_squashed_blocked_transactions() to_pop_blocked = list() to_pop_waiting = list() if params[0] in squashed_blocked_transactions: squashed_blocked_transactions.pop(params[0]) for blocked_dict_key in sorted(self.blocked_transactions.keys()): if params[0] in self.blocked_transactions[blocked_dict_key]: to_pop_blocked.append((blocked_dict_key, params[0])) for key in to_pop_blocked: self.blocked_transactions[key[0]].pop(key[1]) for time in self.waiting_transactions.keys(): if params[0] in self.waiting_transactions[time]: to_pop_waiting.append((time, params[0])) for key in to_pop_waiting: self.waiting_transactions[key[0]].pop(key[1]) self.detect_and_clear_deadlocks() self.blocked_to_waiting() self.try_waiting()
35.340684
79
0.574905
5d8b1ce3715d8e1a087ecdf5f9b21b0583e24786
514
cpp
C++
src/core/features/skyboxchanger.cpp
marius137/gamesneeze
00c03179bb5a7f171c20635b1b2db36edcdd77a3
[ "MIT" ]
1
2021-05-08T13:20:00.000Z
2021-05-08T13:20:00.000Z
src/core/features/skyboxchanger.cpp
cstles/gamesneeze
dcf6b70b69be8851479cf79cba00184291c86bc4
[ "MIT" ]
null
null
null
src/core/features/skyboxchanger.cpp
cstles/gamesneeze
dcf6b70b69be8851479cf79cba00184291c86bc4
[ "MIT" ]
null
null
null
#include "features.hpp" #include <cstring> void Features::SkyboxChanger::frameStageNotify(FrameStage frame) { if (frame == FRAME_NET_UPDATE_POSTDATAUPDATE_END && CONFIGINT("Visuals>World>World>Skybox")) { Offsets::setNamedSkybox((CONFIGINT("Visuals>World>World>Skybox") != 1) ? skyboxes[CONFIGINT("Visuals>World>World>Skybox")] : "sky_l4d_rural02_ldr"); static ConVar* r_3dsky = Interfaces::convar->FindVar("r_3dsky"); if (r_3dsky) { r_3dsky->SetValue(0); } } }
42.833333
156
0.678988
2d4a154ae6724ad582f679f5e9c0affea64842fa
1,205
css
CSS
Public/scene/static/css/index.css
zhaochong/wp_online
bc2bd519d5ab1fb330f71a6712add14270d65569
[ "Apache-2.0" ]
2
2016-02-24T11:04:15.000Z
2016-11-10T10:42:42.000Z
Public/scene/static/css/index.css
zhaochong/wp_online
bc2bd519d5ab1fb330f71a6712add14270d65569
[ "Apache-2.0" ]
null
null
null
Public/scene/static/css/index.css
zhaochong/wp_online
bc2bd519d5ab1fb330f71a6712add14270d65569
[ "Apache-2.0" ]
null
null
null
body{margin:auto;text-align:center;overflow:hidden;background-image:url("/static/img/3.jpg");background-size:100% 100%;} .topButton{width:100%;height:50px;background-color:rgba(255,255,255,0.4);position:absolute;top:0;left:0;z-index:2;box-shadow:0 0 15px black;} .toptable{width:1140px;height:50px;color:white;font-size:14px;} .tbutton{width:90px;cursor:pointer;text-align:center;} .tbutton:hover{background-image:url("../img/button_back.jpg");} .contant{ width:100%; height:2700px; background-image:url("../img/main-background.png"); background-position:top center; background-repeat:no-repeat; } .pages{ width:1140px; } .foot{ width:100%; height:20px; position:fixed; bottom:0px; left:0px; } .gotoBottom{ box-shadow:0 0 15px black; position:fixed; bottom:80px; right:20px; border-radius:20px; padding:12px; padding-left:8px; padding-right:8px; cursor:pointer; color:white; font-weight:bold; background-color:#B34948; font-size:14px; } .gotoTop{ box-shadow:0 0 15px black; position:fixed; bottom:30px; right:20px; border-radius:20px; padding:10px; cursor:pointer; color:white; font-weight:bold; background-color:#B34948; }
24.591837
142
0.713693
fdc925b96e324496de42bd75870c9d75f45bcfea
8,845
css
CSS
public/css/component/searchPan.css
kiavash25/koochitaTv
d7e9fe6078b0c54c7f6b81970f9260290bde81a6
[ "MIT" ]
null
null
null
public/css/component/searchPan.css
kiavash25/koochitaTv
d7e9fe6078b0c54c7f6b81970f9260290bde81a6
[ "MIT" ]
4
2021-02-02T19:07:29.000Z
2022-02-27T05:49:57.000Z
public/css/component/searchPan.css
kiavash25/kkTv
d7e9fe6078b0c54c7f6b81970f9260290bde81a6
[ "MIT" ]
null
null
null
.stateName { font-size: 12px; padding-right: 21px; } .mainDivSearchInputPhonePage > div { position: absolute; top: 44%; left: 50%; transform: translate(-50%, -50%); z-index: 100; } .mainDivSearchInputPhonePage > div:nth-child(1) { width: 45%; } .mainDivSearchInputPhonePage > div:not(:first-child) { width: 60%; } .mainDivSearchInputPhonePage > div:not(:first-child) > div:nth-child(1) { width: 70%; float: right; max-height: 300px; overflow: auto; border-radius: 0 25px 25px 0; } .mainDivSearchInputPhonePage > div:not(:first-child) > div:nth-child(2) { width: 30%; border-radius: 25px 0 0 25px; margin: 0 !important; } .mainDivSearchInputPhonePage > div:not(:first-child) > div:nth-child(1) > div { padding: 10px !important; } .searchDivForScroll-phoneButton > button { font-size: 30px; line-height: 54px; } .mainDivSearchInputPhonePage > div:not(:first-child) > div:nth-child(2) > button { font-size: 35px; line-height: 64px; } .mainDivSearchInputPhonePage > div:not(:first-child) > div input { width: 100%; font-size: 35px; line-height: 50px !important; float: right; border: none; margin-right: 5px } .searchPanes { position: fixed; left: 10%; right: 10%; top: 10%; bottom: auto; max-height: 80%; z-index: 10000001; padding: 48px 16px; direction: rtl; box-shadow: none; background-color: #232323; border-radius: 20px; overflow: hidden; } .searchPanes > div:nth-child(3) > select, .searchPanes > div:nth-child(3) > div { margin-top: 25px; } .searchPanes > div:nth-child(3) > div > button { color: #FFF; background-color: #4dc7bc; border-color: #4dc7bc; } .spSearchDivForScroll { position: relative; } input[type="text"].searchPaneInput::-webkit-input-placeholder { font-size: 1.3em; font-weight: 500; } div.prw_rup.prw_search_typeahead .typeahead_align { display: flex; align-items: center; } .spGoWhere { color: red; font-weight: 500; float: right; margin-left: 5px; font-size: 30px; } div.prw_rup.prw_search_typeahead .typeahead_align .typeahead_input { color: white; float: right; width: 90%; padding: 0; height: 40px; border: none; box-shadow: none !important; font-size: 20px; background-color: #232323; } .spBorderBottom { border-bottom: 2px solid red; margin: 10px 0 0; } .spIcons { float: right; margin: -3px 0 0 3px; padding-top: 3px; } .textsOfRecently { padding: 4px 0px 10px 0px; position: absolute; top: 0px; width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; background: #14151880; font-size: 17px; } .textsOfRecently:hover { background: #14151800; } .textsOfRecently_text { font-size: 1vw !important; line-height: 1.5vw; text-align: center; padding: 5px; white-space: normal; color: white !important; background-color: #000000d6; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; } .hotelIcon::before { font-family: Shazde_Regular2 !important; content: '\e000'; } .restaurantIcon::before { font-family: Shazde_Regular2 !important; content: '\e001'; } .touristAttractions::before { font-family: Shazde_Regular2 !important; content: '\e002'; } .souvenirIcon::before { font-family: Shazde_Regular2 !important; content: '\e005'; } .traditionalFood::before { font-family: Shazde_Regular2 !important; content: '\e006'; } .adventure::before { font-family: Shazde_Regular2 !important; content: '\e009'; } .pop-up-Panes { position: fixed; left: 30%; right: 30%; top: 19%; bottom: auto; overflow: auto; max-height: 500px; z-index: 10000001; } .pop-up-Panes > div:nth-child(3) > select, .pop-up-Panes > div:nth-child(3) > div { margin-top: 25px; } .pop-up-Panes > div:nth-child(3) > div > button { color: #FFF; background-color: #4dc7bc; border-color: #4dc7bc; } #searchDivForScroll { padding: 3px 4px 3px; } #searchDivForScroll > div:nth-child(1) { padding: 10px !important; } .searchPangResultSection { overflow-y: auto; border: 2px solid red; border-top: 0; width: 45%; padding: 10px 5px 6px; display: inline-block; max-height: 375px; } .searchPangResultSection > div { display: flex; flex-direction: column; margin-bottom: 4px; } .aSearchResult{ margin-bottom: 10px; transition: .3s; border-radius: 10px; padding: 10px; } .aSearchResult:hover{ background: red; } .visitSuggestionDiv { overflow-y: auto; max-height: 80vh; border: 2px solid red; border-top: 0; width: 50%; padding: 10px 5px 5px; float: left; border-radius: 0px 0px 10px 10px; } .visitSuggestion4Box { flex-wrap: wrap; display: flex; flex-direction: row; justify-content: right; } .visitSuggestionText { text-align: center; padding: 5px 0 10px; color: white; } .spBoxOfSuggestion { padding: 1px; width: 25%; border: solid red 1px; } .spImageWrapper { height: 100%; } .searchPaneCloseIcon { position: absolute; color: red; left: 15px; top: 0px; } .searchPaneCloseIcon:before { font-size: 50px; line-height: 70px; color: red; } .mainSearchpoi{ position: relative; padding-top: 100%; } .prw_rup.prw_shelves_rebrand_poi_shelf_item_widget.ui_column.is-6-mobile.ng-scope, .prw_rup.prw_shelves_rebrand_poi_shelf_item_widget.ui_column.is-6-mobile.ng-scope .poi { width: 100%; flex-basis: auto; } div.prw_rup.prw_shelves_rebrand_poi_shelf_item_widget .detail { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-height: 73%; } .prw_common_thumbnail_no_style_responsive22{ position: absolute; top: 0px; right: 0px; width: 100%; height: 100%; } .mainSearchImgTop{ height: 100%; display: flex; justify-content: center; align-items: center; overflow: hidden; } /*a:hover {*/ /* color: #4DC7BC;*/ /*}*/ .searchPanSuggest{ color: white; cursor: pointer; vertical-align: middle; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .searchPanSuggestName{ margin: 0px; font-size: 25px; } .searchPanSuggestCategory{ margin: 5px 20px 0px 0px; font-weight: bold; font-size: 14px } .searchPaneInput::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */ color: white; opacity: 1; /* Firefox */ } .searchPaneInput:-ms-input-placeholder { /* Internet Explorer 10-11 */ color: white; } .searchPaneInput::-ms-input-placeholder { /* Microsoft Edge */ color: white; } @media (max-width: 992px) { .searchPanes { left: 5%; right: 5%; } .spBoxOfSuggestion { width: 33.3333%; } .textsOfRecently_text { font-size: 1.5vw !important; line-height: 2vw; } } @media (max-width: 767px) { div.prw_rup.prw_search_typeahead .typeahead_align { margin-top: 20px; } div.ppr_rup.ppr_priv_homepage_shelves .homepage_shelves_widget:last-child { margin-bottom: 100px; } #searchDivForScroll { width: 100%; } .ui_modal.searchPanes { padding: 16px; } .mainContainerSearch { display: flex; flex-direction: column; justify-content: center; } .searchPangResultSection { display: block; width: auto; margin: 0 20px; } .visitSuggestionDiv { width: auto; border-top: 2px solid red; margin-top: 40px; } .textsOfRecently_text { font-size: 3vw !important; line-height: 3.5vw; } } @media (max-width: 630px) { .searchPanes { left: 2%; right: 2% } } @media (max-width: 500px) { .searchPanes { top: 1%; } .searchPanSuggestCategory{ font-size: 11px; } .searchPanSuggestName{ font-size: 17px; } } @media (max-width: 480px) { .spGoWhere{ font-size: 25px; } div.prw_rup.prw_search_typeahead .typeahead_align .typeahead_input { font-size: 20px; } .spBoxOfSuggestion { width: 50%; } } @media (max-width: 400px) { #searchDivForScroll > div:nth-child(1) { padding: 10px 0 !important; } #searchDivForScroll{ overflow-y: auto; height: 400px; } .searchPangResultSection { margin: 0; } } @media (max-width: 375px) { .spGoWhere{ font-size: 20px; } div.prw_rup.prw_search_typeahead .typeahead_align .typeahead_input { font-size: 15px; } }
18.660338
88
0.622046
1469ea7402920a73b3db2747d02cfb69bf4a742f
1,660
ts
TypeScript
@types/jdk/javax.print.PrintService.d.ts
wizawu/1c
b8b3c5d915de264347f42c438493e6a948de6d5c
[ "MIT" ]
126
2017-05-01T01:58:18.000Z
2020-09-14T01:17:51.000Z
@types/jdk/javax.print.PrintService.d.ts
wizawu/1c
b8b3c5d915de264347f42c438493e6a948de6d5c
[ "MIT" ]
17
2017-07-18T21:33:13.000Z
2020-09-01T15:00:57.000Z
@types/jdk/javax.print.PrintService.d.ts
wizawu/1c
b8b3c5d915de264347f42c438493e6a948de6d5c
[ "MIT" ]
6
2018-06-26T13:10:22.000Z
2020-05-14T21:34:19.000Z
declare namespace javax { namespace print { interface PrintService { getName(): java.lang.String createPrintJob(): javax.print.DocPrintJob addPrintServiceAttributeListener(arg0: javax.print.event.PrintServiceAttributeListener | javax.print.event.PrintServiceAttributeListener$$lambda): void removePrintServiceAttributeListener(arg0: javax.print.event.PrintServiceAttributeListener | javax.print.event.PrintServiceAttributeListener$$lambda): void getAttributes(): javax.print.attribute.PrintServiceAttributeSet getAttribute<T extends javax.print.attribute.PrintServiceAttribute>(arg0: java.lang.Class<T>): T getSupportedDocFlavors(): javax.print.DocFlavor[] isDocFlavorSupported(arg0: javax.print.DocFlavor): boolean getSupportedAttributeCategories(): java.lang.Class<unknown>[] isAttributeCategorySupported(arg0: java.lang.Class<javax.print.attribute.Attribute>): boolean getDefaultAttributeValue(arg0: java.lang.Class<javax.print.attribute.Attribute>): java.lang.Object getSupportedAttributeValues(arg0: java.lang.Class<javax.print.attribute.Attribute>, arg1: javax.print.DocFlavor, arg2: javax.print.attribute.AttributeSet): java.lang.Object isAttributeValueSupported(arg0: javax.print.attribute.Attribute, arg1: javax.print.DocFlavor, arg2: javax.print.attribute.AttributeSet): boolean getUnsupportedAttributes(arg0: javax.print.DocFlavor, arg1: javax.print.attribute.AttributeSet): javax.print.attribute.AttributeSet getServiceUIFactory(): javax.print.ServiceUIFactory equals(arg0: java.lang.Object | any): boolean hashCode(): number } } }
63.846154
178
0.78012
cc01753d839c13356180d7652288c28043049878
937
kt
Kotlin
src/commonMain/kotlin/data/itemsets/JusticarArmor.kt
borbrunpagle/tbcsim
7d75fd456632c357ce3bbee40013306e023bc59c
[ "MIT" ]
null
null
null
src/commonMain/kotlin/data/itemsets/JusticarArmor.kt
borbrunpagle/tbcsim
7d75fd456632c357ce3bbee40013306e023bc59c
[ "MIT" ]
12
2021-09-09T23:16:21.000Z
2021-09-26T20:56:39.000Z
src/commonMain/kotlin/data/itemsets/JusticarArmor.kt
CyberQuackGames/tbcsim
98a22924d4634ac4dc5358182cff1c90e88d7637
[ "MIT" ]
null
null
null
package data.itemsets import character.Buff import data.model.ItemSet class JusticarArmor : ItemSet() { companion object { const val TWO_SET_BUFF_NAME = "Justicar Armor (2 set)" const val FOUR_SET_BUFF_NAME = "Justicar Armor (4 set)" } override val id: Int = 625 // TODO: SoR, SoV, SoB, SoM should check this buff once it exists val twoBuff = object : Buff() { override val name: String = TWO_SET_BUFF_NAME override val durationMs: Int = -1 override val icon: String = "inv_helmet_15.jpg" } // TODO: Holy Shield should check this buff once it exists val fourBuff = object : Buff() { override val name: String = FOUR_SET_BUFF_NAME override val durationMs: Int = -1 override val icon: String = "inv_helmet_15.jpg" } override val bonuses: List<Bonus> = listOf( Bonus(id, 2, twoBuff), Bonus(id, 4, fourBuff) ) }
29.28125
69
0.642476
88e913fe4c8f47aaae773a9138aadff3bc9bca1e
19,244
cs
C#
src/unity/Assets/Scripts/Content.cs
SeokbinKang/PrototypAR
fa6ba2e15887b446d88a6196ff2d077681c132cb
[ "MIT" ]
null
null
null
src/unity/Assets/Scripts/Content.cs
SeokbinKang/PrototypAR
fa6ba2e15887b446d88a6196ff2d077681c132cb
[ "MIT" ]
null
null
null
src/unity/Assets/Scripts/Content.cs
SeokbinKang/PrototypAR
fa6ba2e15887b446d88a6196ff2d077681c132cb
[ "MIT" ]
null
null
null
using UnityEngine; using System.Collections; using OpenCvSharp; using OpenCvSharp.Blob; using OpenCvSharp.CPlusPlus; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System; public class Content { private static List<KeyValuePair<BehaviorCategory,string>> behaviorDefinitionList=null; private static List<KeyValuePair<BehaviorCategory, List<string>>> CategoricalBVDefs = null; public static string getOrganName(ModelCategory mc) { if (mc == ModelCategory.None) return "undefined"; if (mc == ModelCategory.Airways) return "airways"; if (mc == ModelCategory.Diaphragm) return "diaphragm"; if (mc == ModelCategory.Lung) return "lungs"; if (mc == ModelCategory.LungLeft) return "lungLeft"; if (mc == ModelCategory.LungRight) return "lungRight"; if (mc == ModelCategory.Stomach) return "stomach"; if (mc == ModelCategory.FrontChainring) return "FrontChainring"; if (mc == ModelCategory.RearSprocket) return "FreeWheel"; if (mc == ModelCategory.Chain) return "Chain"; if (mc == ModelCategory.UpperChain) return "UpperChain"; if (mc == ModelCategory.LowerChain) return "LowerChain"; if (mc == ModelCategory.PedalCrank) return "PedalCrank"; if (mc == ModelCategory.Fish) return "Fish"; if (mc == ModelCategory.Bacteria) return "Bacteria"; if (mc == ModelCategory.Plant) return "Plant"; if (mc == ModelCategory.AirPump) return "AirPump"; if (mc == ModelCategory.C4_lens) return "Lens"; if (mc == ModelCategory.C4_sensor) return "Sensor"; if (mc == ModelCategory.C4_shutter) return "Shutter"; return "undefined"; } public static string getBaviorLabelText(BehaviorCategory bc) { if (bc == BehaviorCategory.Empty) return ""; if (bc == BehaviorCategory.CONSUME) return "CONSUME"; if (bc == BehaviorCategory.CONTRACT) return "CONTRACT"; if (bc == BehaviorCategory.CONVERT) return "CONVERT"; if (bc == BehaviorCategory.DIFFUSE) return "DIFFUSE"; if (bc == BehaviorCategory.DRIVE) return "DRIVE"; if (bc == BehaviorCategory.EAT) return "EAT"; if (bc == BehaviorCategory.PEDAL) return "PEDAL"; if (bc == BehaviorCategory.PASS) return "PASS"; if (bc == BehaviorCategory.REDUCE) return "REDUCE"; if (bc == BehaviorCategory.ROTATE) return "ROTATE"; if (bc == BehaviorCategory.ENGAGE) return "ENGAGE"; if (bc == BehaviorCategory.PROPEL) return "PROPEL"; if (bc == BehaviorCategory.SUPPLY) return "SUPPLY"; if (bc == BehaviorCategory.TRANSFER) return "TRANSFER"; if (bc == BehaviorCategory.CLEAN) return "CLEAN"; if (bc == BehaviorCategory.C4_FOCUS) return "FOCUS"; if (bc == BehaviorCategory.C4_ALLOW) return "ALLOW"; if (bc == BehaviorCategory.C4_CAPTURE) return "CAPTURE"; return "undefined"; } public static int getBVHorizontalBorder(BehaviorCategory bc) { if (bc == BehaviorCategory.CONTRACT) return 69; if (bc == BehaviorCategory.PEDAL) return 58; if (bc == BehaviorCategory.REDUCE) return 73; return 0; } private static void CreateBehaviorDefinition() { behaviorDefinitionList = new List<KeyValuePair<BehaviorCategory, string>>(); foreach(BehaviorCategory behavior in System.Enum.GetValues(typeof(BehaviorCategory))) { behaviorDefinitionList.Add(new KeyValuePair<BehaviorCategory,string>(behavior, getBaviorLabelText(behavior))); } //create categorical behaviors CategoricalBVDefs = new List<KeyValuePair<BehaviorCategory, List<string>>>(); List<string> cameraSensorBVs = new List<string>(); cameraSensorBVs.Add("Black & White"); cameraSensorBVs.Add("GRAYSCALE"); cameraSensorBVs.Add("Red & Green"); cameraSensorBVs.Add("Full Color"); CategoricalBVDefs.Add(new KeyValuePair<BehaviorCategory, List<string>>(BehaviorCategory.C4_CAPTURE, cameraSensorBVs)); } public static List<string> getCategoricalBVdefinition(BehaviorCategory t) { if (behaviorDefinitionList == null) CreateBehaviorDefinition(); if (CategoricalBVDefs == null) return null; foreach (KeyValuePair<BehaviorCategory,List<string>> c in CategoricalBVDefs) { if (c.Key == t) { return c.Value; } } return null; } public static BehaviorCategory DetermineBehaviorType(string labelText, out int LDistance) { BehaviorCategory ret = BehaviorCategory.None; if (behaviorDefinitionList == null) CreateBehaviorDefinition(); Regex rgx = new Regex("[^a-zA-Z0-9 -]"); labelText = rgx.Replace(labelText, ""); labelText = labelText.ToUpper(); int[] Ldist = new int[behaviorDefinitionList.Count]; for (int i = 0; i < behaviorDefinitionList.Count; i++) { Ldist[i] = CalcLevenshteinDistance(labelText, behaviorDefinitionList[i].Value); } int maxIndex = Ldist.ToList().IndexOf(Ldist.Min()); //Debug.Log("[DEBUG]behavior recognized for text(" + labelText + ") as type(" + getBaviorLabelText(behaviorDefinitionList[maxIndex].Key)); LDistance = Ldist.Min(); ret = behaviorDefinitionList[maxIndex].Key; if (ret == BehaviorCategory.None || ret == BehaviorCategory.Empty) LDistance = int.MaxValue; return ret; } private static int CalcLevenshteinDistance(string a, string b) { if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b)) return int.MaxValue; int lengthA = a.Length; int lengthB = b.Length; var distances = new int[lengthA + 1, lengthB + 1]; for (int i = 0; i <= lengthA; distances[i, 0] = i++) ; for (int j = 0; j <= lengthB; distances[0, j] = j++) ; for (int i = 1; i <= lengthA; i++) for (int j = 1; j <= lengthB; j++) { int cost = b[j - 1] == a[i - 1] ? 0 : 1; distances[i, j] = Mathf.Min(Mathf.Min(distances[i - 1, j] + 1, distances[i, j - 1] + 1), distances[i - 1, j - 1] + cost); } return distances[lengthA, lengthB]; } public static ModelCategory[] loadColorObjectMap(out int NColors) { ModelCategory[] ret = new ModelCategory[5]; NColors = 0; if (FBSModel.ContentType== DesignContent.HumanRespiratorySystem) { ret[0] = ModelCategory.Diaphragm; ret[1] = ModelCategory.Lung; ret[2] = ModelCategory.Airways; ret[3] = ModelCategory.None; ret[4] = ModelCategory.None; NColors = 3; } if (FBSModel.ContentType == DesignContent.BicycleGearSystem) { ret[0] = ModelCategory.PedalCrank; ret[1] = ModelCategory.RearSprocket; ret[2] = ModelCategory.Chain; ret[3] = ModelCategory.FrontChainring; ret[4] = ModelCategory.None; NColors = 4; } if (FBSModel.ContentType == DesignContent.AquariumEcology) { ret[0] = ModelCategory.Bacteria; ret[1] = ModelCategory.Plant; ret[2] = ModelCategory.Fish; ret[3] = ModelCategory.AirPump; ret[4] = ModelCategory.None; NColors = 4; } if (FBSModel.ContentType == DesignContent.CameraSystem) { ret[0] = ModelCategory.C4_lens; ret[1] = ModelCategory.C4_shutter; ret[2] = ModelCategory.C4_sensor; ret[3] = ModelCategory.None; ret[4] = ModelCategory.None; NColors = 3; } return ret; } public static bool ForceConvexShape(ModelCategory mc) { // if (mc == ModelCategory.FrontChainring) return true; return false; } public static void ExtractSimulationParameters(prototypeDef proto, DesignContent cType, ref SimulationParam ret) { if(cType== DesignContent.HumanRespiratorySystem) { ret.C1_breathingRate = 0; ret.C1_breathingAmountLevel = 0; if (proto.mModels ==null || proto.mModels[ModelCategory.Diaphragm] == null || proto.mModels[ModelCategory.Diaphragm].Count == 0) return; //C1 foreach(var dia in proto.mModels[ModelCategory.Diaphragm]) { if (dia.behaviors == null) continue; foreach(var beh in dia.behaviors) { if (beh.marker == null) continue; ret.C1_breathingRate = (int) beh.marker.InfoNumericalBVValue; } } //C1 if (proto.mModels[ModelCategory.LungLeft] == null || proto.mModels[ModelCategory.LungRight] == null) return; float lungAreaPortion = 0; foreach (var dia in proto.mModels[ModelCategory.LungLeft]) { var geometry = dia.getShapeBuilder(); if (geometry == null) return; lungAreaPortion+=geometry.getAreaPortioninCanvas(); } foreach (var dia in proto.mModels[ModelCategory.LungRight]) { var geometry = dia.getShapeBuilder(); if (geometry == null) return; lungAreaPortion += geometry.getAreaPortioninCanvas(); } Debug.Log("Lung Area = " + lungAreaPortion); //range 0.01 to 0.20 ret.C1_breathingAmountLevel = (int)(lungAreaPortion * 100.0f/ 0.2f); } if (cType == DesignContent.BicycleGearSystem) { ret.C2_rearGearSize = -1; ret.C2_frontGearSize = -1; ret.C2_GearRatio = -1; ret.C2_pedallingRate = 30; //test ModelDef frontGearModel = proto.getModelDefbyType(ModelCategory.FrontChainring); ModelDef rearGearModel = proto.getModelDefbyType(ModelCategory.RearSprocket); ModelDef pedalModel = proto.getModelDefbyType(ModelCategory.PedalCrank); ModelDef ChainUpperModel = proto.getModelDefbyType(ModelCategory.UpperChain); ModelDef ChainLowerModel = proto.getModelDefbyType(ModelCategory.LowerChain); if (pedalModel == null) ret.C2_pedallingRate = 0; ret.C2_pedalAnimSpeed = ret.C2_pedallingRate / 12.0f; if (frontGearModel != null) { ret.C2_frontGearSize = Mathf.Sqrt((float)frontGearModel.AreaSize); ret.C2_frontGearAnimSpeed = ret.C2_pedalAnimSpeed; } else ret.C2_frontGearAnimSpeed = 0; if (ChainUpperModel != null && ChainLowerModel != null) ret.C2_chainAnimSpeed = ret.C2_frontGearAnimSpeed; else ret.C2_chainAnimSpeed = 0; if (rearGearModel != null) { ret.C2_rearGearSize = Mathf.Sqrt((float)rearGearModel.AreaSize); } else ret.C2_rearGearAnimSpeed = 0; if (frontGearModel != null && rearGearModel != null) { ret.C2_GearRatio = ret.C2_rearGearSize / ret.C2_frontGearSize; if (ret.C2_GearRatio > 0) ret.C2_rearGearAnimSpeed = ret.C2_chainAnimSpeed / ret.C2_GearRatio; else ret.C2_rearGearAnimSpeed = 0; } else ret.C2_rearGearAnimSpeed = 0; Debug.Log("Chain SPEED" + ret.C2_chainAnimSpeed+"READ SPEED"+ret.C2_rearGearAnimSpeed); } if (cType == DesignContent.CameraSystem) { //TODO ModelDef lensModel = proto.getModelDefbyType(ModelCategory.C4_lens); ModelDef shutterModel = proto.getModelDefbyType(ModelCategory.C4_shutter); ModelDef sensor = proto.getModelDefbyType(ModelCategory.C4_sensor); ret.C4_focalLength = -1; ret.C4_shutterSpeed = -1; ret.C4_sensorType = "none"; ret.C4_missingLens = false; ret.C4_missingSensor = false; ret.C4_missingShutter = false; BehaviorDef be = null; int ws = WorkSpaceUI.mInstance.GetCurrentStep(); if (lensModel != null) be = lensModel.getBehaviorDef(BehaviorCategory.C4_FOCUS); else if(ws ==-1 || ws == 0) ret.C4_missingLens = true; if (be != null) { ret.C4_focalLength = be.getNumericalBV(); if(be.marker!=null) ret.C4_focusLabelPos = be.marker.center; } if (shutterModel != null) be = shutterModel.getBehaviorDef(BehaviorCategory.C4_ALLOW); else { be = null; if (ws == -1 || ws == 1) ret.C4_missingShutter = true; } if (be != null) { // GlobalRepo.showDebugImage("mm",be.marker.BVImage); ret.C4_shutterSpeed = be.getNumericalBV(); if (be.marker != null) ret.C4_shutterspeedLabelPos = be.marker.center; } if (sensor != null) be = sensor.getBehaviorDef(BehaviorCategory.C4_CAPTURE); else { be = null; if (ws == -1 || ws == 2) ret.C4_missingSensor = true; } if (be != null) { ret.C4_sensorType = be.getCategoricalBV(); if (be.marker != null) ret.C4_sensortypeLabelPos = be.marker.center; } //check WS and compensate } } } public class SimulationParam : ICloneable { public int C1_breathingRate; public int C1_breathingAmountLevel; public int C2_pedallingRate; public float C2_GearRatio; public float C2_frontGearSize; public float C2_rearGearSize; public float C2_frontGearAnimSpeed; public float C2_rearGearAnimSpeed; public float C2_chainAnimSpeed; public float C2_pedalAnimSpeed; public float C4_focalLength; public float C4_shutterSpeed; public string C4_sensorType; public bool C4_missingLens; public bool C4_missingShutter; public bool C4_missingSensor; public CvPoint C4_focusLabelPos; public CvPoint C4_shutterspeedLabelPos; public CvPoint C4_sensortypeLabelPos; public int NumberOfFeedback; public object Clone() { return this.MemberwiseClone(); } public void DebugPrint() { Debug.Log("[DEBUG] Simulation Param C4: " + C4_focalLength + "\t" + C4_shutterSpeed + "\t" + C4_sensorType+"\t feedback N: " +NumberOfFeedback); } public int DistanceTo(SimulationParam sp) { int dist = 0; if (ApplicationControl.ActiveInstance.ContentType == DesignContent.BicycleGearSystem) { if (sp == null) return 3; if (Math.Abs(C2_GearRatio - sp.C2_GearRatio) >= 0.05) dist++; if (Math.Abs(C2_frontGearSize - sp.C2_frontGearSize) >= 30) dist++; if (Math.Abs(C2_rearGearSize - sp.C2_rearGearSize) >= 30) dist++; } if (ApplicationControl.ActiveInstance.ContentType == DesignContent.CameraSystem) { if (sp == null) return 3; if (Math.Abs(C4_focalLength - sp.C4_focalLength) >= 10) dist++; if (Math.Abs(this.C4_shutterSpeed - sp.C4_shutterSpeed) >= 50) dist++; if (this.C4_sensorType!=sp.C4_sensorType) dist++; } return dist; } public int DistanceTo(SimulationParam sp, ref List<string> parameterNames, out float diffLevel) { int dist = 0; parameterNames.Clear(); diffLevel = 0; if (ApplicationControl.ActiveInstance.ContentType == DesignContent.BicycleGearSystem) { if (sp == null) return 3; if (Math.Abs(C2_GearRatio - sp.C2_GearRatio) >= 0.05) dist++; if (Math.Abs(C2_frontGearSize - sp.C2_frontGearSize) >= 30) dist++; if (Math.Abs(C2_rearGearSize - sp.C2_rearGearSize) >= 30) dist++; } if (ApplicationControl.ActiveInstance.ContentType == DesignContent.CameraSystem) { if (sp == null) return 99; if (Math.Abs(C4_focalLength - sp.C4_focalLength) >= 10) { dist++; parameterNames.Add("focallength"); diffLevel = Math.Abs(C4_focalLength - sp.C4_focalLength); } if (Math.Abs(this.C4_shutterSpeed - sp.C4_shutterSpeed) >= 50) { dist++; parameterNames.Add("shutterspeed"); diffLevel = Math.Abs(this.C4_shutterSpeed - sp.C4_shutterSpeed); } if (this.C4_sensorType != sp.C4_sensorType) { dist++; parameterNames.Add("sensortype"); diffLevel = 1; } } return dist; } public bool HasAllParameters(DesignContent content) { if (content == DesignContent.BicycleGearSystem) { if (C2_frontGearSize > 0 && C2_rearGearSize > 0 && C2_GearRatio > 0) return true; } if (content == DesignContent.CameraSystem) { if (C4_focalLength>0 && C4_sensorType!="none" && C4_shutterSpeed>0) return true; } return false; } } public enum DesignContent { NONE, HumanRespiratorySystem, BicycleGearSystem, AquariumEcology, CameraSystem } public enum BehaviorVariableType { None, Numeric, Categorical, TotalNumberofTypes } public enum PosEvalType { None, CentralProximitytoPoint, ContourProximitytoPoint, HorizontalProximitytoPoint, VerticalProximitytoPoint } public enum ShapeEvalType { None, ActualShape, AspectRatio, DoNot, TotalNumberofShapeEvals } public enum StrEntityEvalType { None, OneonOne, atLeastOne, TotalNumberofStrEntityEvals } public enum EvaluationResultCategory { None, Shape_existence_missing, Shape_existence_redundant, Shape_suggestion, Position_direction, Connectivity_wrong, Connectivity_missing, Behavior_missing, Behavior_Unnecessary, Behavior_relocate, Behavior_variableUnchecked, TotalNumberofFeedbackTypes, } public enum ModelCategory { //this also defines the order of simulation None = 0x00, Diaphragm, Lung, Stomach, Airways, AirParticleLeft, AirParticleRight, LungLeft, LungRight, FrontChainring, RearSprocket, Chain, UpperChain, LowerChain, PedalCrank, Fish, Plant, AirPump, Bacteria, C4_lens, C4_shutter, C4_sensor, TotalNumberOfModels } public enum BehaviorCategory { None, Empty, PEDAL, EAT, CONSUME, SUPPLY, REDUCE, ROTATE, PROPEL, ENGAGE, DRIVE, TRANSFER, CONVERT, CONTRACT, PASS, DIFFUSE, PRODUCE, CLEAN, C4_FOCUS, C4_ALLOW, C4_CAPTURE, TotalNumberofBahaviors }
35.375
152
0.600811
cdf5056e9525316c9253dfcfa6ae7f8fe8545ab4
7,265
dart
Dart
lib/flutter_audio_as_service.dart
dmlzj/flutter_audio_as_service
d698577d5dd98db8307746bc96bbcd42722c743f
[ "BSD-3-Clause" ]
null
null
null
lib/flutter_audio_as_service.dart
dmlzj/flutter_audio_as_service
d698577d5dd98db8307746bc96bbcd42722c743f
[ "BSD-3-Clause" ]
null
null
null
lib/flutter_audio_as_service.dart
dmlzj/flutter_audio_as_service
d698577d5dd98db8307746bc96bbcd42722c743f
[ "BSD-3-Clause" ]
null
null
null
// // Flutter plugin for audio playback on Android // Created by Karol Wąsowski (wasowski02@gmail.com) on June 23rd 2019 // Licensed under the BSD License // import 'dart:async'; import 'package:flutter/services.dart'; import 'AudioInfoClass.dart'; /// A library to simply start an Android audio service with notification and control it const MethodChannel _nativeChannel = const MethodChannel("AudioService"); class FlutterAudioAsService { static AudioPlayerListener _audioListener; static StreamController<PlayerState> _playerStateController = new StreamController.broadcast(); static Stream<PlayerState> get onPlayerStateChanged => _playerStateController.stream; static StreamController<Duration> _positionController = new StreamController.broadcast(); static Stream<Duration> get onAudioPositionChanged => _positionController.stream; static void setSub() { _nativeChannel.setMethodCallHandler(_methodCallHandler); } // invoke Flutter from /// Lets the service send callbacks to Flutter ex. for interface updates. /// It's important to remove listeners in onDestroy() (not implemented) static void setListeners(AudioPlayerListener listener) { _audioListener = listener; _nativeChannel.setMethodCallHandler(_methodCallHandler); } static Future<dynamic> _methodCallHandler(MethodCall call) { switch (call.method) { case "onPlayerStateChanged": switch (call.arguments) { case "idle": _playerStateController?.add(PlayerState.idle); _audioListener?.onPlayerStateChanged(PlayerState.idle); break; case "buffering": _playerStateController?.add(PlayerState.loading); _audioListener?.onPlayerStateChanged(PlayerState.loading); break; case "playing": _playerStateController?.add(PlayerState.playing); _audioListener?.onPlayerStateChanged(PlayerState.playing); break; case "paused": _playerStateController?.add(PlayerState.paused); _audioListener?.onPlayerStateChanged(PlayerState.paused); break; } break; case "onPlayerPositionChanged": try { _positionController?.add(Duration(milliseconds: call.arguments)); _audioListener ?.onPlayerPositionChanged(Duration(milliseconds: call.arguments)); } catch (e) { // print('------------error----------'); // print(e.toString()); } break; case "onPlayerCompleted": _audioListener?.onPlayerCompleted(); break; // TODO: case launch app runApp() try this default: print("ERROR: method not implemented"); break; } return null; } // invoke native methods /// Starts the service, playback and sends a notification with given details /// This command has to be run before any other. The service will stop on itself when playback is done /// For more details about AudioInfo see the corresponding doc section static Future<void> init(AudioInfo details) async { String checkIfNull(String toCheck) { if (toCheck == null) { return "theGivenResourceIsNull"; } else { return toCheck; } } await _checkIfBound(); await _nativeChannel.invokeMethod("startService", { "title": details.title, "channel": details.artist, "url": details.url, "albumCoverFallback": checkIfNull(details.albumCoverFallback), "albumCoverUrl": checkIfNull(details.albumCoverUrl), "appIcon": checkIfNull(details.appIcon), }); } /// Stops and destroys the service. [init()] has to be run after this one, if you want to start playback again /// This also runs [AudioPlayerListener.onPlayerCompleted()] to free resources static Future<void> stop() async { await _checkIfBound(); await _nativeChannel.invokeMethod("stop"); } /// Will pause the player. If player already paused will do nothing static Future<void> pause() async { await _checkIfBound(); await _nativeChannel.invokeMethod("pause"); } /// Will resume playback (only if already loaded earlier and paused afterwards). If already playing will do nothing static Future<void> resume() async { await _checkIfBound(); await _nativeChannel.invokeMethod("resume"); } /// Seeks by the specified time. Seeks forward when a positive duration given and backwards if negative static Future<void> seekBy(Duration duration) async { await _checkIfBound(); await _nativeChannel.invokeMethod("seekBy", { "seekByInMs": duration.inMilliseconds, }); } /// Returns a Duration() with the current audio's length. Returns 0 if no audio is loaded static Future<Duration> getAudioLength() async { await _checkIfBound(); dynamic audioLength = await _nativeChannel.invokeMethod("getAudioLength"); return Duration(milliseconds: audioLength); // returns milliseconds } /// Seeks to a specified positions static Future<void> seekTo(Duration seekTo) async { await _checkIfBound(); await _nativeChannel.invokeMethod("seekTo", { "seekToInMs": seekTo.inMilliseconds, }); } static Future<void> unbind() async { await _checkIfBound(); await _nativeChannel.invokeMethod("unBind"); } static Future<void> _checkIfBound() async { await _nativeChannel.invokeMethod("checkIfBound"); } static Future<String> get platformVersion async { final String version = await _nativeChannel.invokeMethod('getPlatformVersion'); return version; } } /// Player states returned by the [AudioPlayerListener.onPlayerStateChanged()] callback enum PlayerState { idle, loading, playing, paused } /// A class to simplify the usage of callbacks. Specify the needed callbacks and pass the listener to /// [FlutterAudioAsService.setListeners()] class AudioPlayerListener { AudioPlayerListener({ Function onPlayerStateChanged, Function onPlayerPositionChanged, Function onPlayerCompleted, }) : _onPlayerStateChanged = onPlayerStateChanged, _onPlayerPositionChanged = onPlayerPositionChanged, _onPlayerCompleted = onPlayerCompleted; final Function _onPlayerStateChanged; final Function _onPlayerPositionChanged; final Function _onPlayerCompleted; /// Runs whenever PlayerState changes ex. audio paused, resumed, stopped, loading, idle. /// Useful for making dynamic play/pause buttons (example app will include later) or having different behaviour for certain /// UI elements in different player states onPlayerStateChanged(PlayerState state) { if (_onPlayerStateChanged != null) { _onPlayerStateChanged(state); } } /// Runs whenever there is progress on audio playback. Useful to update a progress bar onPlayerPositionChanged(Duration position) { if (_onPlayerPositionChanged != null) { _onPlayerPositionChanged(position); } } /// Runs when the given audio source finishes. Could be used to implement playlists (plugin may include /// playlist somewhere in the future) onPlayerCompleted() { if (_onPlayerCompleted != null) { _onPlayerCompleted(); } } }
33.022727
125
0.701032
39b3b920ce0164fb1f3b98ef70bb785a821c811b
4,856
swift
Swift
MyOmer/Classes/Models/OmerSettings.swift
darshanpanchal/MyOmer
c896b65cf8dd872336c11d702355fc48dde4ce0d
[ "MIT" ]
null
null
null
MyOmer/Classes/Models/OmerSettings.swift
darshanpanchal/MyOmer
c896b65cf8dd872336c11d702355fc48dde4ce0d
[ "MIT" ]
null
null
null
MyOmer/Classes/Models/OmerSettings.swift
darshanpanchal/MyOmer
c896b65cf8dd872336c11d702355fc48dde4ce0d
[ "MIT" ]
null
null
null
// // OmerSettings.swift // MyOmer // // Created by Aftab Akhtar on 3/16/18. // Copyright © 2018 Aftab Akhtar. All rights reserved. // import UIKit fileprivate struct Keys { internal struct Nightfall { static let hour = "nightfall.hour" static let minute = "nightfall.minute" } internal struct Nightly { static let enabled = "nightlyReminder.enabled" static let hour = "nightlyReminder.hour" static let minute = "nightlyReminder.minute" } internal struct Daily { static let enabled = "dailyReminder.enabled" static let hour = "dailyReminder.hour" static let minute = "dailyReminder.minute" } internal struct Notification { static let enabled = "notification" } } struct Notify { var enabled = true } struct Time { var hour = 0 var minute = 0 var date: Date { get { let formatter = DateFormatter() formatter.dateFormat = "H:m" return formatter.date(from: "\(hour):\(minute)")! } } func description() -> String { let formatter = DateFormatter() formatter.dateFormat = "hh:mm a" return formatter.string(from: date) } } struct Reminder { var time: Time var enabled = true } class OmerSettings: NSObject { var nightfallTime = Time(hour: 0, minute: 0) var nightlyReminder: Reminder = Reminder(time: Time(hour: 0, minute: 0), enabled: false) var dailyReminder: Reminder = Reminder(time: Time(hour: 0, minute: 0), enabled: false) var notificationEnable = Notify(enabled: true) fileprivate static var defaultNightfallTime = Time(hour: 20, minute: 0) fileprivate static var defaultNightlyReminderTime = Time(hour: 20, minute: 0) fileprivate static var defaultDailyReminderTime = Time(hour: 12, minute: 0) fileprivate static var defaultNotification = Notify(enabled: false) static var earlyReminderTime = Time(hour: 14, minute: 30) static var lateReminderTime = Time(hour: 22, minute: 30) class var current: OmerSettings { get { let defaults = UserDefaults.standard if defaults.object(forKey: Keys.Nightly.enabled) == nil { defaults.set(defaultNightfallTime.hour, forKey: Keys.Nightfall.hour) defaults.set(defaultNightfallTime.minute, forKey: Keys.Nightfall.minute) defaults.set(true, forKey: Keys.Nightly.enabled) defaults.set(false, forKey: Keys.Daily.enabled) defaults.set(defaultNightlyReminderTime.hour, forKey: Keys.Nightly.hour) defaults.set(defaultNightlyReminderTime.minute, forKey: Keys.Nightly.minute) defaults.set(defaultDailyReminderTime.hour, forKey: Keys.Daily.hour) defaults.set(defaultDailyReminderTime.minute, forKey: Keys.Daily.minute) defaults.set(false, forKey: Keys.Notification.enabled) defaults.synchronize() } let setting = OmerSettings() setting.nightfallTime = Time( hour: defaults.integer(forKey: Keys.Nightfall.hour), minute: defaults.integer(forKey: Keys.Nightfall.minute) ) setting.nightlyReminder = Reminder( time: Time( hour: defaults.integer(forKey: Keys.Nightly.hour), minute: defaults.integer(forKey: Keys.Nightly.minute) ), enabled: defaults.bool(forKey: Keys.Nightly.enabled) ) setting.dailyReminder = Reminder( time: Time( hour: defaults.integer(forKey: Keys.Daily.hour), minute: defaults.integer(forKey: Keys.Daily.minute) ), enabled: defaults.bool(forKey: Keys.Daily.enabled) ) setting.notificationEnable = Notify( enabled: defaults.bool(forKey: Keys.Notification.enabled) ) return setting } } func save() { let defaults = UserDefaults.standard defaults.set(nightfallTime.hour, forKey: Keys.Nightfall.hour) defaults.set(nightfallTime.minute, forKey: Keys.Nightfall.minute) defaults.set(nightlyReminder.enabled, forKey: Keys.Nightly.enabled) defaults.set(dailyReminder.enabled, forKey: Keys.Daily.enabled) defaults.set(nightlyReminder.time.hour, forKey: Keys.Nightly.hour) defaults.set(nightlyReminder.time.minute, forKey: Keys.Nightly.minute) defaults.set(dailyReminder.time.hour, forKey: Keys.Daily.hour) defaults.set(dailyReminder.time.minute, forKey: Keys.Daily.minute) defaults.set(notificationEnable.enabled, forKey: Keys.Notification.enabled) defaults.synchronize() } }
39.16129
92
0.62953
e850eacfb4510f98bbf2a270019df4b079439bb8
349
cs
C#
adminlte/Areas/Manager/Controllers/ManagerHomeController.cs
SergtoUn/GunSudexDoc
fef4e17672e19b483d44d86598a149ed00e6ba4a
[ "MIT" ]
null
null
null
adminlte/Areas/Manager/Controllers/ManagerHomeController.cs
SergtoUn/GunSudexDoc
fef4e17672e19b483d44d86598a149ed00e6ba4a
[ "MIT" ]
null
null
null
adminlte/Areas/Manager/Controllers/ManagerHomeController.cs
SergtoUn/GunSudexDoc
fef4e17672e19b483d44d86598a149ed00e6ba4a
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WeaponDoc.Areas.Manager.Controllers { public class ManagerHomeController : Controller { // GET: Manager/ManagerHome public ActionResult Index() { return View(); } } }
16.619048
51
0.638968
e41bcf9a5a1a863f80746c118e74cc8d86f0ac21
2,829
cshtml
C#
Views/Home/StartAPetition.cshtml
Goslenator7/Assessment2---Final
93bd4787fe03e79fdcd50726652d6a24d03e37bb
[ "Apache-2.0" ]
null
null
null
Views/Home/StartAPetition.cshtml
Goslenator7/Assessment2---Final
93bd4787fe03e79fdcd50726652d6a24d03e37bb
[ "Apache-2.0" ]
null
null
null
Views/Home/StartAPetition.cshtml
Goslenator7/Assessment2---Final
93bd4787fe03e79fdcd50726652d6a24d03e37bb
[ "Apache-2.0" ]
null
null
null
@model Assessment2___Final.Models.Cause @{ ViewBag.Title = "Start a Cause"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h1> Start a Cause</h1> <hr /> <div class="row"> <div class="col-lg-6"> <img src="~/Content/images/create.jpg" class="img-fluid" id="createImage" /> </div> <div class="col-lg-6"> @using (Html.BeginForm("StartAPetition", "Home", FormMethod.Post)) { @Html.AntiForgeryToken() <div class="form"> <h4> Your Cause</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label" }) <div class="col-lg-12"> @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label" }) <div class="col-lg-12"> @Html.EditorFor(model => model.Category, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label" }) <div class="col-lg-12"> @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Image, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-lg-12"> @Html.EditorFor(model => model.Image, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Image, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <button type="submit" class="btn btn-primary"> Submit </button> <button type="button" class="btn btn-danger"> Cancel </button> </div> </div> } </div> </div>
44.203125
125
0.485684
bd5d6cbf906007f8ab707655ef2c73cc74a05b0e
1,005
rb
Ruby
src/instrumentation/validators/instrument_only_once_validator.rb
sanderblue/demo-deployer
b17cfd9a0caef30fa4ac3641733d94d3ec0ce2a0
[ "Apache-2.0" ]
7
2020-08-25T19:08:36.000Z
2021-11-11T16:24:20.000Z
src/instrumentation/validators/instrument_only_once_validator.rb
sanderblue/demo-deployer
b17cfd9a0caef30fa4ac3641733d94d3ec0ce2a0
[ "Apache-2.0" ]
62
2020-08-19T23:36:34.000Z
2022-01-24T22:17:40.000Z
src/instrumentation/validators/instrument_only_once_validator.rb
sanderblue/demo-deployer
b17cfd9a0caef30fa4ac3641733d94d3ec0ce2a0
[ "Apache-2.0" ]
7
2020-08-20T13:38:28.000Z
2021-05-21T06:24:12.000Z
module Instrumentation module Validators class InstrumentOnlyOnceValidator def initialize(key_name, error_message = nil) @key_name = key_name @error_message = error_message || "Instrumentation defined more than once: " end def execute(parsed_instrumentors, ids) invalid = [] reference_count = Hash.new(0) (parsed_instrumentors || []).each do |instrumentor| instrumentor_ids = instrumentor[@key_name] (instrumentor_ids || []).each { |instrumentor_id| reference_count[instrumentor_id] += 1 } end (ids || []).each do |id| unless reference_count[id].nil?() if reference_count[id] > 1 invalid.push(id) end end end if invalid.compact().length() > 0 message = invalid.join(", ") return "#{@error_message}#{message}" end return nil end end end end
27.162162
101
0.558209
c93a7866ac9a1e999cf6dd8ed10854a9c4fb59c3
326
ts
TypeScript
src/modules/Invoice.ts
Rohan-Shakya/finance-logger
c11c0c19c7998c25746c94e7a80ed2644c90a41c
[ "MIT" ]
1
2021-09-09T16:10:09.000Z
2021-09-09T16:10:09.000Z
src/modules/Invoice.ts
Rohan-Shakya/finance-logger
c11c0c19c7998c25746c94e7a80ed2644c90a41c
[ "MIT" ]
null
null
null
src/modules/Invoice.ts
Rohan-Shakya/finance-logger
c11c0c19c7998c25746c94e7a80ed2644c90a41c
[ "MIT" ]
null
null
null
import { HasFormatter } from '../interfaces/HasFormatter'; export class Invoice implements HasFormatter { constructor( readonly type: string, public client: string, public details: string, public amount: number ) {} format() { return `${this.client} owes ${this.amount} for ${this.details}`; } }
21.733333
68
0.668712
df033812e828759ae1ba1f567d256e61640f668b
729
rb
Ruby
lib/vmdb/gettext/debug.rb
rvalente/manageiq
470e8b425d08432ddb785819c60e83815ac7954c
[ "Apache-2.0" ]
1,243
2015-01-13T12:29:36.000Z
2022-03-25T12:03:03.000Z
lib/vmdb/gettext/debug.rb
rvalente/manageiq
470e8b425d08432ddb785819c60e83815ac7954c
[ "Apache-2.0" ]
20,415
2015-01-01T10:37:18.000Z
2022-03-31T21:52:44.000Z
lib/vmdb/gettext/debug.rb
rvalente/manageiq
470e8b425d08432ddb785819c60e83815ac7954c
[ "Apache-2.0" ]
1,053
2015-01-07T17:54:15.000Z
2022-03-29T19:10:50.000Z
require 'fast_gettext' # include this module to see translations in the UI module Vmdb module Gettext module Debug DL = "\u00BB".encode("UTF-8") DR = "\u00AB".encode("UTF-8") # modified copy of fast_gettext _ method def _(key) "#{DL}#{FastGettext._(key)}#{DR}" end # modified copy of fast_gettext n_ method def n_(*keys) "#{DL}#{FastGettext.n_(*keys)}#{DR}" end # modified copy of fast_gettext s_ method def s_(key, separator = nil) "#{DL}#{FastGettext.s_(key, separator)}#{DR}" end # modified copy of fast_gettext ns_* method def ns_(*keys) "#{DL}#{FastGettext.ns_(*keys)}#{DR}" end end end end
22.78125
53
0.578875
ef2e8fdce2646f783bb2146523a3a86e5b9a1d97
2,868
c
C
plugins/fec/fec_scheme_protoops/rlc_fec_scheme_generate_gf256.c
ap300/pquic
55db7a8af2fa6057c2932188480b99ed7101873a
[ "MIT" ]
98
2019-06-27T11:54:39.000Z
2022-03-19T07:40:24.000Z
plugins/fec/fec_scheme_protoops/rlc_fec_scheme_generate_gf256.c
ap300/pquic
55db7a8af2fa6057c2932188480b99ed7101873a
[ "MIT" ]
31
2019-08-29T07:41:25.000Z
2022-01-04T17:11:39.000Z
plugins/fec/fec_scheme_protoops/rlc_fec_scheme_generate_gf256.c
ap300/pquic
55db7a8af2fa6057c2932188480b99ed7101873a
[ "MIT" ]
21
2019-08-05T08:40:49.000Z
2022-03-28T03:48:01.000Z
#include <picoquic.h> #include "../fec.h" #include "../gf256/swif_symbol.c" #include "../../helpers.h" #include "../prng/tinymt32.c" #include "rlc_fec_scheme_gf256.h" static inline void get_coefs(picoquic_cnx_t *cnx, tinymt32_t *prng, uint32_t seed, int n, uint8_t coefs[n]) { tinymt32_init(prng, seed); int i; for (i = 0 ; i < n ; i++) { coefs[i] = (uint8_t) tinymt32_generate_uint32(prng); if (coefs[i] == 0) coefs[i] = 1; } } /** * fec_block_t* fec_block = (fec_block_t *) cnx->protoop_inputv[0]; * * Output: return code (int) */ protoop_arg_t fec_generate_repair_symbols(picoquic_cnx_t *cnx) { tinymt32_t prng; prng.mat1 = 0x8f7011ee; prng.mat2 = 0xfc78ff1f; prng.tmat = 0x3793fdff; fec_block_t* fec_block = (fec_block_t *) get_cnx(cnx, AK_CNX_INPUT, 0); rlc_gf256_fec_scheme_t *fs = (rlc_gf256_fec_scheme_t *) get_cnx(cnx, AK_CNX_INPUT, 1); uint8_t **mul = fs->table_mul; PROTOOP_PRINTF(cnx, "GENERATING SYMBOLS WITH RLC GF256\n"); if (fec_block->total_repair_symbols == 0 || fec_block->total_source_symbols < 1 || fec_block->current_source_symbols != fec_block->total_source_symbols) { PROTOOP_PRINTF(cnx, "IMPOSSIBLE TO GENERATE\n"); return 1; } uint16_t max_length = 0; for_each_source_symbol(fec_block, source_symbol_t *source_symbol) { max_length = MAX(source_symbol->data_length, max_length); } uint8_t i, j; uint8_t *coefs = my_malloc(cnx, fec_block->total_source_symbols*sizeof(uint8_t)); uint8_t **knowns = my_malloc(cnx, fec_block->total_source_symbols*sizeof(uint8_t)); for (i = 0 ; i < fec_block->total_source_symbols ; i++) { knowns[i] = my_malloc(cnx, max_length); my_memset(knowns[i], 0, max_length); my_memcpy(knowns[i], fec_block->source_symbols[i]->data, fec_block->source_symbols[i]->data_length); } for (i = 0 ; i < fec_block->total_repair_symbols ; i++) { repair_fpid_t rfpid; rfpid.raw = 0; rfpid.fec_block_number = fec_block->fec_block_number; rfpid.symbol_number = i; get_coefs(cnx, &prng, rfpid.source_fpid.raw, fec_block->total_source_symbols, coefs); repair_symbol_t *rs = malloc_repair_symbol(cnx, rfpid, max_length); for (j = 0 ; j < fec_block->total_source_symbols ; j++) { // PROTOOP_PRINTF(cnx, "ADD coef = %d, data = %p, rs[8] = 0x%x, symbol2 = %p, tab = %p\n", coefs[j], (protoop_arg_t) rs->data, rs->data[8], (protoop_arg_t) knowns[j], (protoop_arg_t) mul); symbol_add_scaled(rs->data, coefs[j], knowns[j], max_length, mul); } fec_block->repair_symbols[i] = rs; } for (i = 0 ; i < fec_block->total_source_symbols ; i++) { my_free(cnx, knowns[i]); } my_free(cnx, coefs); my_free(cnx, knowns); return 0; }
36.769231
199
0.6447
24955ff19e9cb4e29a9d958e2c42885538aed297
1,372
php
PHP
resources/views/pages/location.blade.php
sudo-dev-urandom/briotest
e6751177d710c5d2ccf87cd126a8d1f643b15aa3
[ "MIT" ]
null
null
null
resources/views/pages/location.blade.php
sudo-dev-urandom/briotest
e6751177d710c5d2ccf87cd126a8d1f643b15aa3
[ "MIT" ]
null
null
null
resources/views/pages/location.blade.php
sudo-dev-urandom/briotest
e6751177d710c5d2ccf87cd126a8d1f643b15aa3
[ "MIT" ]
null
null
null
@extends('layout') @section('content') <div class="container-fluid" style="padding-top: 98px; background: #F7F8F9;"> <div class="row justify-content-center"> <div class="col-lg-12"> <iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d15868.113745055785!2d106.7453852!3d-6.1268757!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x6af8ff8423ea24b9!2sBriotest%20Lab!5e0!3m2!1sid!2sid!4v1622791626280!5m2!1sid!2sid" width="100%" class="p-lg-4" height="500" style="border:0;" allowfullscreen="" loading="lazy"></iframe> </div> </div> <div class="row pb-5"> <div class="col-lg-6 pl-lg-5"> <div class="column"> <div class="col"> <p class="contact-text-title1"> Briotest PIK </p> </div> <div class="col"> <p class="contact-text-title2"> Sentra Industri Tahap 1 & 2 Blok B No. 8 RT 03 / RW 3 Kamal Muara, Kec. Penjaringan Jakarta Utara </p> </div> </div> </div> </div> </div> @stop
42.875
248
0.452624
095ea2fda7e711a5fae6acbc18fa291363849705
876
swift
Swift
Sources/Enums/DateTimeInterval.swift
swaromik/ZamzamKit
3f2ccbcedb4868ee3b8c1e10f64332eff60a6bab
[ "MIT" ]
null
null
null
Sources/Enums/DateTimeInterval.swift
swaromik/ZamzamKit
3f2ccbcedb4868ee3b8c1e10f64332eff60a6bab
[ "MIT" ]
null
null
null
Sources/Enums/DateTimeInterval.swift
swaromik/ZamzamKit
3f2ccbcedb4868ee3b8c1e10f64332eff60a6bab
[ "MIT" ]
null
null
null
// // DateTimeInterval.swift // ZamzamKit // // Created by Basem Emara on 2018-11-22. // Copyright © 2018 Zamzam Inc. All rights reserved. // import Foundation /// Represents a specified number of a calendar component unit. You use `DateTimeInterval` values to do date calculations. public enum DateTimeInterval { case seconds(Int) case minutes(Int) case hours(Int) case days(Int) case weeks(Int) case months(Int) case years(Int) } /// Represents a specified number of a calendar component unit for a calendar. You use `DateTimeIntervalWithCalendar` values to do date calculations. public enum DateTimeIntervalWithCalendar { case seconds(Int, Calendar) case minutes(Int, Calendar) case hours(Int, Calendar) case days(Int, Calendar) case weeks(Int, Calendar) case months(Int, Calendar) case years(Int, Calendar) }
27.375
149
0.719178
b646463db774bef8b5888a46cfee4204d7c2351f
636
rb
Ruby
spec/feature/f00/f00_b02_spec.rb
utarsuno/ruuuby
affb51a30166067121799aed8aeea9cefa31c010
[ "MIT" ]
3
2020-01-01T00:14:20.000Z
2020-10-22T04:37:33.000Z
spec/feature/f00/f00_b02_spec.rb
utarsuno/ruuuby
affb51a30166067121799aed8aeea9cefa31c010
[ "MIT" ]
null
null
null
spec/feature/f00/f00_b02_spec.rb
utarsuno/ruuuby
affb51a30166067121799aed8aeea9cefa31c010
[ "MIT" ]
null
null
null
# encoding: UTF-8 RSpec.describe 'f00_b02' do context 'functionality' do end # end: {functionality} context 'audit', :audit do context 'funcs provided are defined in correct location' do it 'for ENV' do expect_∃⨍(:∃?, ENV) expect_∃⨍(:∄?, ENV) end it 'for IO classes' do expect(::Dir.respond_to?(:∃?)).to eq(true) expect(::File.respond_to?(:∃?)).to eq(true) expect(::Dir.respond_to?(:∄?)).to eq(true) expect(::File.respond_to?(:∄?)).to eq(true) end end end # end: {audit} context 'performance', :performance do end # end: {performance} end
23.555556
63
0.581761
b28b8b455b7b7f97d04584f2a3f8a93f5c4317a1
26,209
css
CSS
src/main/resources/css/light.css
fakegit/Subtitles-View
1a0bddadace8c25c6dbf00cb58a7ac2792f41270
[ "MIT" ]
331
2020-04-12T13:25:31.000Z
2021-08-22T18:59:31.000Z
src/main/resources/css/light.css
JunhaoHuang0615/subtitles-view
cd628806d237ede28f8781ebda7923678c1f3f26
[ "MIT" ]
9
2020-04-26T16:18:30.000Z
2021-08-14T03:20:24.000Z
src/main/resources/css/light.css
JunhaoHuang0615/subtitles-view
cd628806d237ede28f8781ebda7923678c1f3f26
[ "MIT" ]
44
2020-04-26T06:59:28.000Z
2021-08-19T14:13:20.000Z
.content, .bottom-round{ -fx-background-color: #dedede; } .titlesBar #closed { -fx-background-image: url("/images/public/close_light.png"); } .root_normal .titlesBar #maximize{ -fx-background-image: url("/images/public/max_light.png"); } .side{ -fx-background-color: #2D2D2D; } .root_full .titlesBar #maximize{ -fx-background-image: url("/images/public/standard_light.png"); } .titlesBar #minimize { -fx-background-image: url("/images/public/min_light.png"); } .titlesBar #minimize:hover, .titlesBar #mode_switch:hover, .titlesBar #maximize:hover { -fx-background-color: #bdc0c6; } .titlesBar #mode_switch { -fx-background-image: url("/images/public/light.png"); } .news { /*设置背景色*/ -fx-background-color: #DEDEDE; -fx-border-color: #262626; -fx-text-fill: #000; } .news:hover { -fx-background-color: #1b1b1b; -fx-text-fill: #FFF; } .contentBottom { -fx-background-color: #ffffff; } .nav_button:selected { -fx-background-color: #fff; -fx-effect: dropshadow(gaussian, #a8a5a5, 5, 0, 0, 0); } .nav_button:hover { -fx-background-color: #fff; -fx-effect: dropshadow(gaussian, #a8a5a5, 5, 0, 0, 0); } .nav_button { -fx-background-color: #DEDEDE; -fx-text-fill: #000; } .tips { -fx-text-fill: #929090; } .tips:hover { -fx-text-fill: #5B5BFA; } /*全局ChoiceBox*/ /*控件本身上的选定项目文本颜色*/ .choice-box > .label { -fx-text-fill: #000; } /*整个上下文菜单的背景色、字体大小、宽度*/ .choice-box .context-menu { -fx-background-color: #fff; } /*列表中的焦点项目背景颜色*/ .choice-box .menu-item:focused { -fx-background-color: #F4F4F4; } /*列表中非重点项目的文字颜色*/ .choice-box .menu-item > .label { -fx-text-fill: black; } /*列表中焦点项目的文本颜色*/ .choice-box .menu-item:focused > .label { -fx-text-fill: #5B5BFA; } /*控件主属性*/ .choice-box { -fx-background-color: #fff; /*控件本身的背景色*/ -fx-mark-color: black; /*箭头颜色*/ -fx-border-color: #bababe; } .choice-box:focused { -fx-border-color: #5B5BFA; } .button-shadow { -fx-effect: dropshadow( three-pass-box , #343434, 5, 0.0 , 0 , 0 ); } /*执行按钮*/ .execute-button { -fx-background-color: #5B5BFA, linear-gradient(#5B5BFA 50%, #363699 100%), radial-gradient(center 50% -40%, radius 200%, #5B5BFA 45%, #363699 50%); -fx-text-fill: #FFF; } .aux-button { -fx-background-color: #2ecc71; -fx-text-fill: #FFF; } .cancel-button { -fx-background-color: #ECECEC, linear-gradient(#ECECEC 50%, #D5D5D5 100%), radial-gradient(center 50% -40%, radius 200%, #ECECEC 45%, #D5D5D5 50%); -fx-text-fill: black; } /*输入框*/ .TextField { -fx-background-color: #fff; -fx-border-color: #bababe; -fx-text-fill: #000; } .TextField:focused { -fx-background-color: #fff; -fx-border-color: #5B5BFA; -fx-text-fill: #000; } /*全局提示框*/ .tooltip { -fx-background-color: #F4F5F7; -fx-text-fill: #000; } #TutorialsTips { -fx-text-fill: #6e6e6e; } #TutorialsTips:hover { -fx-text-fill: #5B5BFA; } /*输入框*/ #search_input { -fx-background-radius: 20; -fx-border-radius: 20; -fx-font-size: 18; } #search_input:focused { -fx-background-radius: 20; -fx-border-radius: 20; } #search_execute { -fx-background-image: url("/images/public/search_light.png"); -fx-background-color: rgba(38, 38, 38, 0); } #search_execute:hover { -fx-background-image: url("/images/public/search_hover.png"); } /*列表视图*/ .list-view { -fx-text-fill: #000; } .list-view .list-cell { -fx-text-fill: #FFF; } /*滚动条颜色*/ .list-view .thumb { -fx-background-color: rgb(226, 221, 221); } .news:hover { -fx-background-color: #1b1b1b; -fx-text-fill: #FFF; } #tips { -fx-text-fill: #929090; } #tips:hover { -fx-text-fill: #5B5BFA; } .titles_background_pure { -fx-background-color: #FFF; } .folder{ -fx-background-image: url("/images/application/start/folder_light.png"); } .folder:hover{ -fx-background-image: url("/images/application/start/folder_light_selected.png"); } .folder_success{ -fx-background-image: url("/images/application/start/folder_success.png"); } .folder_not_support{ -fx-background-image: url("/images/application/start/folder_not_support.png"); } /*搜索面板内容样式*/ .search_item .search_item_content{ -fx-fill: #000; } .search_item:hover .search_item_content{ -fx-fill: #5B5BFA; } .search_item_text{ -fx-font-size: 18; } .search_item_remark{ -fx-font-size: 14; } #home { -fx-background-image: url("/images/application/home.png"); } #sync { -fx-background-image: url("/images/application/sync.png"); } #translation { -fx-background-image: url("/images/application/translation.png"); } #build { -fx-background-image: url("/images/application/save.png"); } #about { -fx-background-image: url("/images/application/help.png"); } #setting { -fx-background-image: url("/images/application/setting.png"); } .sideButton:hover { -fx-background-color: rgb(74, 74, 74); } /*主页面板样式*/ .BasicEdit { -fx-background-image: url("/images/application/home/Edit_Light.png"); } .BasicEdit:selected { -fx-background-image: url("/images/application/home/Edit_Light_selected.png"); } .BasicEdit:hover { -fx-background-image: url("/images/application/home/Edit_Light_selected.png"); } .TimelineAdj { -fx-background-image: url("/images/application/home/timeline_Light.png"); } .TimelineAdj:selected { -fx-background-image: url("/images/application/home/timeline_Light_selected.png"); } .TimelineAdj:hover { -fx-background-image: url("/images/application/home/timeline_Light_selected.png"); } .FindR { -fx-background-image: url("/images/application/home/findR_Light.png"); } .FindR:hover { -fx-background-image: url("/images/application/home/findR_Light_selected.png"); } .FindR:selected { -fx-background-image: url("/images/application/home/findR_Light_selected.png"); } .Preview { -fx-background-image: url("/images/application/home/preview_Light.png"); } .Preview:hover { -fx-background-image: url("/images/application/home/preview_Light_selected.png"); } .Preview:selected { -fx-background-image: url("/images/application/home/preview_Light_selected.png"); } .edit_tool_button { -fx-text-fill: rgb(67, 67, 67); } .edit_tool_button:selected { -fx-background-color: rgba(234, 236, 240, 1); -fx-text-fill: #5B5BFA; } .edit_tool_button:hover { -fx-background-color: rgba(234, 236, 240, 1); -fx-text-fill: #5B5BFA; } .List_titles { -fx-text-fill: #000; } .listPanel { -fx-background-color: #F4F4F4; } /* 同步返听*/ .ManualSync { -fx-background-image: url("/images/application/sync/ManualSync_Light.png"); } .ManualSync:hover { -fx-background-image: url("/images/application/sync/ManualSync_Light_selected.png"); } .ManualSync:selected { -fx-background-image: url("/images/application/sync/ManualSync_Light_selected.png"); } .AutomaticSync { -fx-background-image: url("/images/application/sync/AutoSync_Light.png"); } .AutomaticSync:hover { -fx-background-image: url("/images/application/sync/AutoSync_Light_selected.png"); } .AutomaticSync:selected { -fx-background-image: url("/images/application/sync/AutoSync_Light_selected.png"); } /*文字翻译-在线翻译按钮样式*/ .Tran_Online { -fx-background-image: url("/images/application/tran/Tran_Online_Light.png"); } .Tran_Online:selected { -fx-background-image: url("/images/application/tran/Tran_Online_Light_selected.png"); } .Tran_Online:hover { -fx-background-image: url("/images/application/tran/Tran_Online_Light_selected.png"); } /*文字翻译-离线翻译按钮样式*/ .Tran_Offline { -fx-background-image: url("/images/application/tran/Tran_Offline_Light.png"); } .Tran_Offline:selected { -fx-background-image: url("/images/application/tran/Tran_Offline_Light_selected.png"); } .Tran_Offline:hover { -fx-background-image: url("/images/application/tran/Tran_Offline_Light_selected.png"); } /*翻译面板控件*/ #Tarn_image { -fx-background-image: url("/images/application/tran/Transformation.png"); } /*构建导出-导出选项样式*/ .Build_Manual { -fx-background-image: url("/images/application/build/Save_Manual_Light.png"); } .Build_Manual:selected { -fx-background-image: url("/images/application/build/Save_Manual_Light_selected.png"); } .Build_Manual:hover { -fx-background-image: url("/images/application/build/Save_Manual_Light_selected.png"); } /*构建导出-视频预览按钮样式*/ .Build_Preview { -fx-background-image: url("/images/application/build/Save_Preview_Light.png"); } .Build_Preview:selected { -fx-background-image: url("/images/application/build/Save_Preview_Light_selected.png"); } .Build_Preview:hover { -fx-background-image: url("/images/application/build/Save_Preview_Light_selected.png"); } /*设置窗格*/ .Base { -fx-background-image: url("/images/application/setting/Base_Light.png"); } .Base:selected { -fx-background-image: url("/images/application/setting/Base_Light_selected.png"); } .Base:hover { -fx-background-image: url("/images/application/setting/Base_Light_selected.png"); } .Advanced { -fx-background-image: url("/images/application/setting/Advanced_Light.png"); } .Advanced:selected { -fx-background-image: url("/images/application/setting/Advanced_Light_selected.png"); } .Advanced:hover { -fx-background-image: url("/images/application/setting/Advanced_Light_selected.png"); } .Lab { -fx-background-image: url("/images/application/setting/Lab_Light.png"); } .Lab:selected { -fx-background-image: url("/images/application/setting/Lab_Light_selected.png"); } .Lab:hover { -fx-background-image: url("/images/application/setting/Lab_Light_selected.png"); } /*关于软件*/ .Guide { -fx-background-image: url("/images/application/about/Guide_Light.png"); } .Guide:selected { -fx-background-image: url("/images/application/about/Guide_Light_selected.png"); } .Guide:hover { -fx-background-image: url("/images/application/about/Guide_Light_selected.png"); } .Pact { -fx-background-image: url("/images/application/about/Pact_Light.png"); } .Pact:selected { -fx-background-image: url("/images/application/about/Pact_Light_selected.png"); } .Pact:hover { -fx-background-image: url("/images/application/about/Pact_Light_selected.png"); } .UpdateLog { -fx-background-image: url("/images/application/about/UpdateLog_Light.png"); } .UpdateLog:selected { -fx-background-image: url("/images/application/about/UpdateLog_Light_selected.png"); } .UpdateLog:hover { -fx-background-image: url("/images/application/about/UpdateLog_Light_selected.png"); } /*主窗格底层*/ #bottomLayer { -fx-background-color: #FFFFFF; } /*全局TextArea*/ .editor { -fx-background-color: #FFFFFF; -fx-text-fill: #000000; -fx-highlight-fill: #9B9BFF; /* makes color of highlight region */ -fx-highlight-text-fill: #000; /* makes the color of highlighted text */ } .editor .scroll-pane .content { -fx-background-color: #FFFFFF; } .editor:focused { -fx-background-color: #FFFFFF; } /*滚动条颜色*/ .editor .thumb { -fx-background-color: rgb(226, 221, 221); } /*separator分界线*/ .separator *.line { -fx-background-color: #E6E6E6; -fx-border-color: #E6E6E6; } /*全局Label*/ .GlobalLabel { -fx-text-fill: #000000; } /*主页工具栏按钮*/ #edit_tool_find { -fx-background-image: url("/images/application/home/find_light.png"); } #edit_tool_find:hover { -fx-background-image: url("/images/application/home/find_hover.png"); } #edit_tool_find:selected { -fx-background-image: url("/images/application/home/find_hover.png"); } #edit_tool_replace { -fx-background-image: url("/images/application/home/replace_light.png"); } #edit_tool_replace:hover { -fx-background-image: url("/images/application/home/replace_hover.png"); } #edit_tool_replace:selected { -fx-background-image: url("/images/application/home/replace_hover.png"); } #edit_tool_hidden { -fx-background-image: url("/images/application/home/more_light.png"); } #edit_tool_hidden:hover { -fx-background-image: url("/images/application/home/more_hover.png"); } #edit_tool_hidden:selected { -fx-background-image: url("/images/application/home/more_hover.png"); } #edit_tool_jump { -fx-background-image: url("/images/application/home/jump_light.png"); } #edit_tool_jump:hover { -fx-background-image: url("/images/application/home/jump_hover.png"); } #edit_tool_jump:selected { -fx-background-image: url("/images/application/home/jump_hover.png"); } #edit_tool_code { -fx-background-image: url("/images/application/home/code_light.png"); } #edit_tool_code:hover { -fx-background-image: url("/images/application/home/code_hover.png"); } #edit_tool_code:selected { -fx-background-image: url("/images/application/home/code_hover.png"); } #edit_tool_style { -fx-background-image: url("/images/application/home/style_light.png"); } #edit_tool_style:hover { -fx-background-image: url("/images/application/home/style_hover.png"); } #edit_tool_style:selected { -fx-background-image: url("/images/application/home/style_hover.png"); } #edit_tool_time_line { -fx-background-image: url("/images/application/home/addTimeline_light.png"); } #edit_tool_time_line:hover { -fx-background-image: url("/images/application/home/addTimeline_hover.png"); } #edit_tool_time_line:selected { -fx-background-image: url("/images/application/home/addTimeline_hover.png"); } #edit_tool_regular_line { -fx-background-image: url("/images/application/home/newline_light.png"); } #edit_tool_regular_line:hover { -fx-background-image: url("/images/application/home/newline_hover.png"); } #edit_tool_regular_line:selected { -fx-background-image: url("/images/application/home/newline_hover.png"); } /*全局提示框*/ .tooltip { -fx-font-size: 17; } /*分界线*/ .splitPane *.split-pane-divider { -fx-background-color: #dbdbdb; } .modelPart { -fx-background-color: #FFF; -fx-effect: dropshadow(three-pass-box, #2D2D2D, 3.0, 0, 0, 0); } /*输入框*/ .input { -fx-background-color: #ffffff; -fx-border-color: #bababe; -fx-text-fill: #000; -fx-highlight-fill: #9B9BFF; /* makes color of highlight region */ -fx-highlight-text-fill: #000; /* makes the color of highlighted text */ } .input:focused { -fx-background-color: #fff; -fx-border-color: #bababe; -fx-text-fill: #000; } /*默认按钮*/ /*#cancel {*/ /* -fx-background-color:*/ /* #ECECEC,*/ /* linear-gradient(#ECECEC 50%, #D5D5D5 100%),*/ /* radial-gradient(center 50% -40%, radius 200%, #ECECEC 45%, #D5D5D5 50%);*/ /* -fx-background-radius: 10;*/ /* -fx-background-insets: 0,1,1;*/ /* -fx-text-fill: black;*/ /* -fx-effect: dropshadow( three-pass-box , rgba(0,0,0,0.6) , 3, 0.0 , 0 , 1 );*/ /*}*/ /*!*默认按钮*!*/ /*#cancel :hover {*/ /* -fx-background-color: #FFFFFF;*/ /* -fx-text-fill: #5B5BFA;*/ /* -fx-background-radius: 5;*/ /* -fx-effect: dropshadow(gaussian, #303030, 5.0,0, 0, 0);*/ /*}*/ /*全局单选按钮*/ .radio-button { -fx-text-fill: #000; } .radio-button .radio { -fx-border-color: #000; -fx-background-color: white; } /*全局ComboBox*/ .combo-box .list-cell { -fx-background: white; -fx-text-fill: #000; -fx-mark-color: black; /*箭头颜色*/ -fx-text-alignment: center; } .combo-box-popup .list-view { -fx-background-color: white, white; -fx-background-radius: 5; } .combo-box-popup .list-view .list-cell:filled:selected, .combo-box-popup .list-view .list-cell:filled:selected:hover { -fx-background-color: #FFF; -fx-text-fill: #5B5BFA; } .combo-box-popup .list-view .list-cell:filled:hover { -fx-background-color: #ececec; } .combo-box-base { -fx-border-color: #BFBFC2; } /*滚动条颜色*/ .combo-box .thumb { -fx-background-color: rgb(226, 221, 221); } /*工具面板组件样式*/ .editToolPanel { -fx-background-color: #FFF; -fx-effect: dropshadow(GAUSSIAN, #2d2d2d, 7, 0, 0, 0); /*<DropShadow blurType="GAUSSIAN" height="15.0" radius="7.0" width="15.0" />*/ } /*工具面板底层*/ #toolPanel { -fx-background-color: transparent; } /*工具面板文本框样式*/ .ToolPanel_TextField { -fx-background-color: #FFF; -fx-border-color: #FFF; -fx-text-fill: #000; } /*工具面板按钮样式*/ .ToolPanel_Button { -fx-background-color: #FFF; } /*工具栏按钮样式*/ #edit_tool_find_btn { -fx-background-image: url("/images/application/tool/search_light.png"); } #edit_tool_find_btn:hover { -fx-background-image: url("/images/application/tool/search_hover.png"); } #edit_tool_find_option { -fx-background-image: url("/images/application/tool/option_light.png"); } #edit_tool_find_option:hover { -fx-background-image: url("/images/application/tool/option_hover.png"); } #edit_tool_find_close { -fx-background-image: url("/images/application/tool/close_light.png"); } #edit_tool_find_close:hover { -fx-background-image: url("/images/application/tool/close_hover.png"); } #edit_tool_search_btn { -fx-background-image: url("/images/application/tool/search_light.png"); } #edit_tool_search_btn:hover { -fx-background-image: url("/images/application/tool/search_hover.png"); } #edit_tool_search_option { -fx-background-image: url("/images/application/tool/option_light.png"); } #edit_tool_search_option:hover { -fx-background-image: url("/images/application/tool/option_hover.png"); } #edit_tool_replace_close { -fx-background-image: url("/images/application/tool/close_light.png"); } #edit_tool_replace_close:hover { -fx-background-image: url("/images/application/tool/close_hover.png"); } #edit_tool_replace_next { -fx-background-image: url("/images/application/tool/replace_light.png"); } #edit_tool_replace_next:hover { -fx-background-image: url("/images/application/tool/replace_hover.png"); } #edit_tool_replace_all { -fx-background-image: url("/images/application/tool/replaceall_light.png"); } #edit_tool_replace_all:hover { -fx-background-image: url("/images/application/tool/replaceall_hover.png"); } #edit_tool_jump_btn { -fx-background-image: url("/images/application/tool/jump_light.png"); } #edit_tool_jump_btn:hover { -fx-background-image: url("/images/application/tool/jump_hover.png"); } #edit_tool_jump_close { -fx-background-image: url("/images/application/tool/close_light.png"); } #edit_tool_jump_close:hover { -fx-background-image: url("/images/application/tool/close_hover.png"); } #edit_tool_code_close { -fx-background-image: url("/images/application/tool/close_light.png"); } #edit_tool_code_close:hover { -fx-background-image: url("/images/application/tool/close_hover.png"); } #edit_tool_code_btn { -fx-background-image: url("/images/application/tool/refresh_light.png"); } #edit_tool_code_btn:hover { -fx-background-image: url("/images/application/tool/refresh_hover.png"); } #edit_tool_style_default { -fx-background-image: url("/images/application/tool/default_light.png"); } #edit_tool_style_default:hover { -fx-background-image: url("/images/application/tool/default_hover.png"); } #edit_tool_style_close { -fx-background-image: url("/images/application/tool/close_light.png"); } #edit_tool_style_close:hover { -fx-background-image: url("/images/application/tool/close_hover.png"); } #edit_tool_style_bold { -fx-background-image: url("/images/application/tool/bold_light.png"); } #edit_tool_style_bold:hover { -fx-background-image: url("/images/application/tool/bold_hover.png"); } #edit_tool_style_bold:selected { -fx-background-image: url("/images/application/tool/bold_hover.png"); } #edit_tool_style_italic { -fx-background-image: url("/images/application/tool/italic_light.png"); } #edit_tool_style_italic:hover { -fx-background-image: url("/images/application/tool/italic_hover.png"); } #edit_tool_style_italic:selected { -fx-background-image: url("/images/application/tool/italic_hover.png"); } #edit_tool_style_underline { -fx-background-image: url("/images/application/tool/underline_light.png"); } #edit_tool_style_underline:hover { -fx-background-image: url("/images/application/tool/underline_hover.png"); } #edit_tool_style_underline:selected { -fx-background-image: url("/images/application/tool/underline_hover.png"); } /*选项菜单样式*/ #edit_tool_find_option_menu > .label { -fx-text-fill: #000; } /*整个上下文菜单的背景色、字体大小、宽度*/ #edit_tool_find_option_menu .context-menu { -fx-background-color: #fff; } /*列表中的焦点项目背景颜色*/ #edit_tool_find_option_menu .menu-item:focused { -fx-background-color: #F4F4F4; } /*列表中非重点项目的文字颜色*/ #edit_tool_find_option_menu .menu-item > .label { -fx-text-fill: black; } /*列表中焦点项目的文本颜色*/ #edit_tool_find_option_menu .menu-item:focused > .label { -fx-text-fill: #5B5BFA; } #edit_tool_replace_search_menu > .label { -fx-text-fill: #000; } /*整个上下文菜单的背景色、字体大小、宽度*/ #edit_tool_replace_search_menu .context-menu { -fx-background-color: #fff; } /*列表中的焦点项目背景颜色*/ #edit_tool_replace_search_menu .menu-item:focused { -fx-background-color: #F4F4F4; } /*列表中非重点项目的文字颜色*/ #edit_tool_replace_search_menu .menu-item > .label { -fx-text-fill: black; } /*列表中焦点项目的文本颜色*/ #edit_tool_replace_search_menu .menu-item:focused > .label { -fx-text-fill: #5B5BFA; } .edit_mode_off { -fx-background-image: url("/images/application/tool/edit_mode_off.png"); } .edit_mode_off:hover{ -fx-background-image: url("/images/application/tool/edit_mode_off_hover.png"); } .edit_mode_no { -fx-background-image: url("/images/application/tool/edit_mode_no.png"); } .edit_mode_no:hover{ -fx-background-image: url("/images/application/tool/edit_mode_no_hover.png"); } /*同步返听字幕列表*/ .listView { -fx-text-fill: #fff; } .list-cell:even { -fx-text-fill: #000; } .list-cell:odd { -fx-text-fill: #000; } /*滚动条颜色*/ .listView .thumb { -fx-background-color: rgb(226, 221, 221); } /*待开发图片*/ #InDevelopment { -fx-background-image: url("/images/application/InDevelopment.png"); } #InDevelopment_Label { -fx-text-fill: #979292; } /*等待视频加载内容*/ #WaitingLoadingPanel_Content { -fx-border-color: #bebebe; } #WaitingLoadingPanel_Content_Image { -fx-background-image: url("/images/application/openVideo_Light.png"); } #WaitingLoadingPanel_Content_Image:hover { -fx-background-image: url("/images/application/openVideo_hover.png"); } .WaitingLoadingPanel_Content_Label { -fx-text-fill: #bebebe; } /*翻译面板控件*/ #tarn_online_image { -fx-background-image: url("/images/application/tran/TranOnline_Lable_Light.png"); } #LoadRoot { -fx-effect: dropshadow(gaussian, #000000, 10.0, 100, 0, 0); -fx-background-color: #DEDEDE; -fx-border-color: #000; } #Load_ChoiceBox { -fx-border-color: #2d2d2d; } #LoadTop { -fx-background-color: #fff; } /*构建导出样式*/ .Build_TextField { -fx-background-color: #fff; -fx-border-color: #bababe; -fx-text-fill: #000; } /*CheckBox默认样式*/ .check-box .box { -fx-background-color: white; -fx-border-color: grey; } .check-box:selected .mark { -fx-background-color: white; } /*选中颜色*/ .check-box:selected .box { -fx-background-color: #5B5BFA; } #Build_ChoosePath { -fx-background-color: #fff; -fx-border-color: #bababe; -fx-background-image: url("/images/application/build/Save_ChoosePath_Light.png"); } #Build_OutGraphicsQuality { -fx-font-size: 16; } .shadow { -fx-effect: dropshadow(three-pass-box, #2d2d2d, 7.0,0, 0, 0); } .buttonShadow { -fx-effect: dropshadow(three-pass-box, #383838, 3.0,0, 0, 0); } .buttonShadow :hover{ -fx-effect: dropshadow(three-pass-box, #2d2d2d, 3.0,0, 0, 0); } #Editor_Rec { -fx-background-image: url("/images/application/setting/Editor_Rec_Light.png"); } #Editor_Rec:hover { -fx-background-image: url("/images/application/setting/Editor_Rec_Light_Select.png"); } #translationLabel { -fx-background-image: url("/images/application/setting/translation_light.png"); } #translationLabel:hover { -fx-background-image: url("/images/application/setting/translation_hover.png"); } #voiceLabel { -fx-background-image: url("/images/application/setting/voice_light.png"); } #voiceLabel:hover { -fx-background-image: url("/images/application/setting/voice_hover.png"); } #appidLabel { -fx-background-image: url("/images/application/setting/appid_light.png"); } #appidLabel:hover { -fx-background-image: url("/images/application/setting/appid_hover.png"); } #keyLabel { -fx-background-image: url("/images/application/setting/key_light.png"); } #keyLabel:hover { -fx-background-image: url("/images/application/setting/key_hover.png"); } .trayMenu { -fx-background-color: transparent; -fx-border-color: transparent; } .trayMenu .trayMenu-bottom { -fx-background-color: #FFF; -fx-effect: dropshadow( three-pass-box , #000, 5, 0.0 , 0 , 0 ); } .trayMenu .row { -fx-background-color: #FFFFFF; } .trayMenu .row:hover { -fx-background-color: #C8C8C9; } .trayMenu .row:hover .item-exit { -fx-background-image: url("/images/application/system/exit-hover.png"); } .trayMenu .row:hover .item-open { -fx-background-image: url("/images/application/system/home-hover.png"); } .trayMenu .row:hover .item-setting { -fx-background-image: url("/images/application/system/setting-hover.png"); } .trayMenu .item-open { -fx-background-image: url("/images/application/system/home-light.png"); } .trayMenu .item-exit { -fx-background-image: url("/images/application/system/exit-light.png"); } .trayMenu .item-setting { -fx-background-image: url("/images/application/system/setting-light.png"); } #email { -fx-background-image: url("/images/application/about/email_light.png"); } #telegram { -fx-background-image: url("/images/application/about/telegram_light.png"); } .license_label { -fx-background-image: url("/images/application/about/license_light.png"); } .git_label { -fx-background-image: url("/images/application/about/github_light.png"); } .scroll_pane .thumb { -fx-background-color: rgb(226, 221, 221); } .group-line { -fx-background-color: #F4F4F4; }
21.482787
91
0.687283
05fa6682ff71f93d5deae4d3b1655f5650b8d8fe
1,753
rb
Ruby
test/controllers/iconly/projects_controller_test.rb
lugolabs/iconly
a3270926e13ecb501aacfeb97a633abaaa04341f
[ "MIT" ]
10
2017-02-22T19:06:22.000Z
2021-05-10T01:12:53.000Z
test/controllers/iconly/projects_controller_test.rb
lugolabs/iconly
a3270926e13ecb501aacfeb97a633abaaa04341f
[ "MIT" ]
null
null
null
test/controllers/iconly/projects_controller_test.rb
lugolabs/iconly
a3270926e13ecb501aacfeb97a633abaaa04341f
[ "MIT" ]
null
null
null
require 'test_helper' module Iconly class ProjectsControllerTest < ActionDispatch::IntegrationTest include Engine.routes.url_helpers setup do @project = iconly_projects(:one) ApplicationController.any_instance.stubs(:current_user).returns(@project.user) end test 'should get index' do get projects_url assert_response :success assert_select 'h1', 'Projects' end test 'should get new' do get new_project_url assert_response :success assert_select 'h1', 'New Project' end test 'should create project' do assert_difference('@project.user.projects.count') do post projects_url, params: { project: { name: 'New project' } } end assert_redirected_to project_url(Project.friendly.find('new-project')) end test 'should show project' do get project_url(id: @project) assert_response :success end test 'should get edit' do get edit_project_url(@project) assert_response :success end test 'should update project' do patch project_url(@project), params: { project: { name: 'New name' } } assert_redirected_to project_url(@project.reload) end test 'should destroy project' do assert_difference('Iconly::Project.count', -1) do delete project_url(@project) end assert_redirected_to projects_url end test 'should generate font' do downloader = stub(call: fixture_file_upload('iconly/files/facebook.svg')) Project::Downloader.expects(:new).with(@project).returns(downloader) post generate_font_project_url(@project) assert_response :success assert response.body.include?('</svg>') end end end
24.690141
84
0.675414
0376be0360c588a22dad478b90e2226d6b7239ce
13,183
dart
Dart
lib/tocheckndel/widget3.dart
Brain-up/mobile
6a5a6daf913d510b5ce833b6bec9638aa8484703
[ "CC0-1.0" ]
null
null
null
lib/tocheckndel/widget3.dart
Brain-up/mobile
6a5a6daf913d510b5ce833b6bec9638aa8484703
[ "CC0-1.0" ]
null
null
null
lib/tocheckndel/widget3.dart
Brain-up/mobile
6a5a6daf913d510b5ce833b6bec9638aa8484703
[ "CC0-1.0" ]
null
null
null
import 'package:flutter/material.dart'; class GroupSc1WidgetSTF extends StatefulWidget { @override _GroupSc1WidgetSTFState createState() => _GroupSc1WidgetSTFState(); } class _GroupSc1WidgetSTFState extends State<GroupSc1WidgetSTF> { @override Widget build(BuildContext context) { // Figma Flutter Generator Group577Widget - GROUP return Container( width: 1440, height: 888, child: Stack(children: <Widget>[ Positioned( top: 0, left: 0, child: Container( width: 1440, height: 888, child: Stack(children: <Widget>[ Positioned( top: 0, left: 0, child: Container( width: 1440, height: 888, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment( 0.8181040287017822, 0.18189597129821777), end: Alignment(-0.18189597129821777, 0.18189597129821777), colors: [ Color.fromRGBO( 66, 141, 252, 0.15000000596046448), Color.fromRGBO( 146, 119, 253, 0.10000000149011612) ]), ))), Positioned( top: 0, left: 0, child: Container( width: 1440, height: 232, decoration: BoxDecoration( color: Color.fromRGBO(255, 255, 255, 1), ), child: Stack(children: <Widget>[ Positioned( top: 60, left: 517, child: Text( 'Преимущества', textAlign: TextAlign.center, style: TextStyle( color: Color.fromRGBO(19, 18, 17, 1), fontFamily: 'Montserrat', fontSize: 40, letterSpacing: 0 /*percentages not used in flutter. defaulting to zero*/, fontWeight: FontWeight.normal, height: 1.5 /*PERCENT not supported*/ ), )), Positioned( top: 136, left: 239, child: Container( width: 961, height: 28, child: Stack(children: <Widget>[ Positioned( top: 0, left: 0, child: Text( 'Тренируйтесь всего от 30 минут в день для развития и получения результата', textAlign: TextAlign.center, style: TextStyle( color: Color.fromRGBO( 19, 18, 17, 1), fontFamily: 'Open Sans', fontSize: 18, letterSpacing: 0 /*percentages not used in flutter. defaulting to zero*/, fontWeight: FontWeight.normal, height: 1.5555555555555556), )), ]))), ]))), Positioned( top: 230, left: 64, child: Container( width: 411, height: 584, decoration: BoxDecoration( borderRadius: BorderRadius.only( topLeft: Radius.circular(8), topRight: Radius.circular(8), bottomLeft: Radius.circular(8), bottomRight: Radius.circular(8), ), color: Color.fromRGBO(255, 255, 255, 1), ), child: Stack(children: <Widget>[ Positioned( top: 109, left: 48, child: Text( 'Первая бесплатная онлайн программа для взрослых и детей с когнитивными проблемами восприятия речи. Все наши занятия рассчитаны на возраст детей от 7 лет и старше. Уже сейчас программа насчитывает более 20 разных тем по которым вы можете начать заниматься уже сейчас. А дальше будет еще больше - мы планируем постоянно расширять список наших тем.', textAlign: TextAlign.left, style: TextStyle( color: Color.fromRGBO(19, 18, 17, 1), fontFamily: 'Open Sans', fontSize: 18, letterSpacing: 0 /*percentages not used in flutter. defaulting to zero*/, fontWeight: FontWeight.normal, height: 1.5555555555555556), )), Positioned( top: 48, left: 48, child: Text( 'BRAINUP', textAlign: TextAlign.left, style: TextStyle( color: Color.fromRGBO(0, 0, 0, 1), fontFamily: 'Montserrat', fontSize: 24, letterSpacing: 0 /*percentages not used in flutter. defaulting to zero*/, fontWeight: FontWeight.normal, height: 1.875), )), ]))), Positioned( top: 230, left: 517, child: Container( width: 408, height: 584, decoration: BoxDecoration( borderRadius: BorderRadius.only( topLeft: Radius.circular(8), topRight: Radius.circular(8), bottomLeft: Radius.circular(8), bottomRight: Radius.circular(8), ), color: Color.fromRGBO(255, 255, 255, 1), ), child: Stack(children: <Widget>[ Positioned( top: 109, left: 48, child: Text( 'Мы хотели чтобы формат обучения был максимально удобным для каждого нашего пользователя. Именно поэтому наши уроки доступны в любое время. Вы ожете сами выбрать в какое время вам заниматься и сформировать собственное расписание занятий.', textAlign: TextAlign.left, style: TextStyle( color: Color.fromRGBO(19, 18, 17, 1), fontFamily: 'Open Sans', fontSize: 18, letterSpacing: 0 /*percentages not used in flutter. defaulting to zero*/, fontWeight: FontWeight.normal, height: 1.5555555555555556), )), Positioned( top: 48, left: 48, child: Text( 'ОНЛАЙН ЗАНЯТИЯ', textAlign: TextAlign.left, style: TextStyle( color: Color.fromRGBO(0, 0, 0, 1), fontFamily: 'Montserrat', fontSize: 24, letterSpacing: 0 /*percentages not used in flutter. defaulting to zero*/, fontWeight: FontWeight.normal, height: 1.875), )), ]))), Positioned( top: 230, left: 965, child: Container( width: 411, height: 584, decoration: BoxDecoration( borderRadius: BorderRadius.only( topLeft: Radius.circular(8), topRight: Radius.circular(8), bottomLeft: Radius.circular(8), bottomRight: Radius.circular(8), ), color: Color.fromRGBO(255, 255, 255, 1), ), child: Stack(children: <Widget>[ Positioned( top: 109, left: 48, child: Text( 'Занимаясь по нашей программе, вы сможете, развивать слух в различных акустических ситуациях; тренировать слуховую память, прослушивая упражнения столько раз, сколько необходимо именно вам.А также, расширить словарный запас в интересной игровой форме и в дальшейшем использовать новые слова в общении с друзьями и знакомыми.', textAlign: TextAlign.left, style: TextStyle( color: Color.fromRGBO(19, 18, 17, 1), fontFamily: 'Open Sans', fontSize: 18, letterSpacing: 0 /*percentages not used in flutter. defaulting to zero*/, fontWeight: FontWeight.normal, height: 1.5555555555555556), )), Positioned( top: 48, left: 48, child: Text( 'РАЗВИТИЕ', textAlign: TextAlign.left, style: TextStyle( color: Color.fromRGBO(0, 0, 0, 1), fontFamily: 'Montserrat', fontSize: 24, letterSpacing: 0 /*percentages not used in flutter. defaulting to zero*/, fontWeight: FontWeight.normal, height: 1.875), )), ]))), ]))), ])); } }
55.158996
386
0.324509
24bbda056a498ec0aa50e659a13dd1ce174102f1
2,041
php
PHP
Dbm v 1.0.0/staff_pro.php
raniatuh/DBM-v1.0.0
5e34a21b66a7cf3b1164cfe1d972261a86f8db70
[ "MIT" ]
null
null
null
Dbm v 1.0.0/staff_pro.php
raniatuh/DBM-v1.0.0
5e34a21b66a7cf3b1164cfe1d972261a86f8db70
[ "MIT" ]
null
null
null
Dbm v 1.0.0/staff_pro.php
raniatuh/DBM-v1.0.0
5e34a21b66a7cf3b1164cfe1d972261a86f8db70
[ "MIT" ]
null
null
null
<?php //include connection include 'conn.php'; // We don't have the password or email info stored in sessions so instead we can get the results from the database. $stmt = $con->prepare('SELECT phone, name, stafflevel FROM staff WHERE id = ?'); // In this case we can use the account ID to get the account info. $stmt->bind_param('i', $_SESSION['id']); $stmt->execute(); $stmt->bind_result($phone, $name, $level); $stmt->fetch(); $stmt->close(); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Staff Profile Page</title> <link href="style.css" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css"> <link rel="stylesheet" href="bootstrap3/css/bootstrap.min.css"> <script src="bootstrap3/jquery.js"></script> <script src="bootstrap3/js/bootstrap.min.js"></script> </head> <body class="loggedin"> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <ul class="nav navbar-nav"> <li><a href="staff_stock.php"><span class="glyphicon glyphicon-chevron-left"></span> Back</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#" data-toggle="tooltip" title="Logout"><span class="glyphicon glyphicon-option-vertical"></span> <span class="care"></span></a> <ul class="dropdown-menu"> <li><a href="logout.php"><span class="glyphicon glyphicon-log-out"></span> Logout</a></li> </ul> </li> </ul> </div> </nav> <div class="content"> <h2><?=$name?></h2> <div> <p>Your details are below:</p> <table> <tr> <td>Name:</td> <td><?=$name?></td> </tr> <tr> <td>Username:</td> <td><?=$_SESSION['name']?></td> </tr> <tr> <td>Userlevel:</td> <td><?=$level?></td> </tr> <tr> <td>Phone number:</td> <td><?=$phone?></td> </tr> </table> </div> </div> </body> </html>
29.57971
160
0.591377
b3299bc3bacf034ab8ee52995b3ef3e5b089f3f2
5,707
py
Python
fileprocessor.py
Akshay-Thakare/cctv
62bfaa23d8284527ed24ae038d68695a893b829a
[ "Apache-2.0" ]
null
null
null
fileprocessor.py
Akshay-Thakare/cctv
62bfaa23d8284527ed24ae038d68695a893b829a
[ "Apache-2.0" ]
null
null
null
fileprocessor.py
Akshay-Thakare/cctv
62bfaa23d8284527ed24ae038d68695a893b829a
[ "Apache-2.0" ]
null
null
null
import logging from googledrive import GoogleDrive import redisqueue as qm import logging import time from os import listdir, remove from os.path import isfile, join from threading import Thread # Constants FOLDER_PATH_MAC = "/Users/ast/Desktop/test_data" FOLDER_PATH_PI_OLD = "/home/pi/test_data" FOLDER_PATH_CCTV = "/home/pi/cctv_data" FOLDER_PATH_DEV = "/home/pi/cctv_test2" FOLDER_PATH = FOLDER_PATH_DEV TESTING_DEFAULT_BEFORE_DAYS = 15 class FileProcessor(object): def __init__(self): self.redis = qm.ConnectToRedis() self.DECAY_FLAG = False self.gd = GoogleDrive(self.redis) def start(self): # start all threads here t1 = Thread(target=self.process_jobs, args=()) t1.daemon = True t1.start() t2 = Thread(target=self.process_uploaded_files, args=()) t2.daemon = True t2.start() t3 = Thread(target=self.find_decayed_files, args=()) t3.daemon = True t3.start() return self def process_jobs(self): while True: logging.debug("ENTRY - processJobs") # Check if jobs are present in the queue if (qm.get_unprocessed_queue_size(self.redis) > 0): # get a job from top of the queue currentFileName = qm.print_unprocessed_queue(self.redis, 0, 0)[0].decode('ascii') logging.debug(currentFileName) # get file path currentFilePath = self.generate_file_path(currentFileName) logging.debug(currentFilePath) # add file to transient processing holder qm.transient_processing(self.redis, currentFileName) # check if file exists if(self.check_if_file_exists(currentFilePath)): # ask google drive to upload file if (self.gd.upload_file(currentFileName, currentFilePath)): logging.debug("File successfully uploaded : " + currentFileName) # remove element from unprocessed queue if (qm.pop_element_from_unprocessed_queue(self.redis) == currentFileName): # add element to uploaded queue qm.add_to_uploaded_queue(self.redis, currentFileName) logging.debug("Done processing file : " + currentFileName) else: # queue is corrupted logging.error("Queue corrupted. Needs to be looked into") logging.error("QUEUE DUMP") qm.printUnprocessedQueue(self.redis, 0, -1) else: logging.error("Error uploading file : " + currentFileName) else: qm.pop_element_from_unprocessed_queue(self.redis) logging.info("Fixed system corruption") else: self.fix_queue() # logging.info("wait for jobs to be added to unprocessed queue") time.sleep(10) logging.debug("EXIT - processJobs") def process_uploaded_files(self): while True: logging.debug("ENTRY - processUploadedFiles") # Check if files are present to be deleted if (qm.get_uploaded_queue_size(self.redis) > 0): # get a job from top of the queue currentFileName = qm.print_uploaded_queue(self.redis, 0, 0)[0].decode('ascii') # get file path currentFilePath = self.generate_file_path(currentFileName) logging.debug(currentFilePath) # add file to transient processing holder qm.transient_deleting(self.redis, currentFileName) # check if file exists if(self.check_if_file_exists(currentFilePath)): # delete from File System if (self.delete_file_locally(currentFilePath)): logging.debug("File deleted from fs : " + currentFileName) if (qm.pop_element_from_uploaded_queue(self.redis) == currentFileName): logging.debug("Successfully remove element from delete queue") else: logging.error("Error removing element from delete queue") else: logging.error("Failed to delete file : " + currentFileName) else: qm.pop_element_from_uploaded_queue(self.redis) logging.info("Fixed queue corruption") else: logging.debug("wait for jobs to be added to uploaded queue") time.sleep(10) logging.debug("EXIT - processUploadedFiles") def find_decayed_files(self): while True: logging.debug("ENTRY - processDecay") if (self.DECAY_FLAG): print("finding decay") logging.debug("ENTRY - Find decay") self.gd.find_decay(self.redis) self.DECAY_FLAG = False logging.debug("EXIT - Find decay") # check if files are present which need to be deleted while(qm.get_deleted_queue_size(self.redis)>0): if (qm.get_deleted_queue_size(self.redis)>0): # pop a job from top of the queue fileId = qm.pop_element_from_deleted_queue(self.redis) # ask google to delete file if (self.gd.delete_file(fileId)): # logging.info("File successfully deleted : "+fileId) logging.debug("File successfully deleted") print("file deleted") self.DECAY_FLAG = True else: # No need to handle this case, as the queue would be regenerated every 24hrs either ways print("unable to delete file") logging.error("Unable to delete file") else: logging.debug("No jobs to be processed. Sleeping for next 24 hours") self.DECAY_FLAG = True #time.sleep(60*60*24) time.sleep(120) logging.debug("EXIT - processDecay") def generate_file_path(self, fileName): return FOLDER_PATH + "/" + fileName def delete_file_locally(self, filePath): # logging.info("FilePath = " + filePath) try: remove(filePath) return True except OSError: return False def check_if_file_exists(self, filePath): try: return isfile(filePath) except Exception as err: return False def fix_queue(self): try: for file in listdir(FOLDER_PATH): if file.endswith(".avi"): # print(join(FOLDER_PATH+"/", file)) qm.add_to_unprocessed_queue(self.redis, file) except Exception as err: logging.error(err)
30.356383
94
0.701595
93e2d36aa91fd00861c56089fda6a6e044bb850a
14,519
sql
SQL
tp5.sql
lau1998/MyWorks
95e9b8cf91705c2d6c4c295d76cb83359c038d18
[ "Apache-2.0" ]
null
null
null
tp5.sql
lau1998/MyWorks
95e9b8cf91705c2d6c4c295d76cb83359c038d18
[ "Apache-2.0" ]
null
null
null
tp5.sql
lau1998/MyWorks
95e9b8cf91705c2d6c4c295d76cb83359c038d18
[ "Apache-2.0" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 4.7.9 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: 2018-08-15 15:11:26 -- 服务器版本: 10.1.31-MariaDB -- PHP Version: 7.2.3 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `tp5` -- -- -------------------------------------------------------- -- -- 表的结构 `lc_banner` -- CREATE TABLE `lc_banner` ( `id` int(11) NOT NULL, `status` tinyint(3) UNSIGNED NOT NULL DEFAULT '1' COMMENT '状态,1:显示,0不显示', `delete_time` int(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '删除时间', `name` varchar(50) CHARACTER SET utf8 NOT NULL DEFAULT '' COMMENT '幻灯片分类', `remark` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT '' COMMENT '分类备注' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='幻灯片表'; -- -- 转存表中的数据 `lc_banner` -- INSERT INTO `lc_banner` (`id`, `status`, `delete_time`, `name`, `remark`) VALUES (1, 1, 0, '默认幻灯片', 'laucher'); -- -------------------------------------------------------- -- -- 表的结构 `lc_banner_item` -- CREATE TABLE `lc_banner_item` ( `id` int(10) UNSIGNED NOT NULL, `slide_id` int(11) NOT NULL DEFAULT '0' COMMENT '幻灯片id', `status` tinyint(3) UNSIGNED NOT NULL DEFAULT '1' COMMENT '状态,1:显示;0:隐藏', `list_order` float NOT NULL DEFAULT '10000' COMMENT '排序', `title` varchar(50) NOT NULL DEFAULT '' COMMENT '幻灯片名称', `image` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT '' COMMENT '幻灯片图片', `url` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT '' COMMENT '幻灯片链接', `target` varchar(10) NOT NULL DEFAULT '' COMMENT '友情链接打开方式', `description` varchar(255) CHARACTER SET utf8 NOT NULL COMMENT '幻灯片描述', `content` text CHARACTER SET utf8 COMMENT '幻灯片内容', `more` text COMMENT '链接打开方式' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='幻灯片子项表'; -- -- 转存表中的数据 `lc_banner_item` -- INSERT INTO `lc_banner_item` (`id`, `slide_id`, `status`, `list_order`, `title`, `image`, `url`, `target`, `description`, `content`, `more`) VALUES (1, 1, 1, 10001, 'WELCOME', '20180807\\e81621ee5bafde562a63cb829a6072df.jpg', '/tp5/thinkphp_5.0.10/public/', '', '欢迎来到本网站', '这是一个dome测试,随时可以更改它', NULL), (2, 1, 1, 10002, 'LAUCHER-FASSS', '20180807\\7fe2b8f44d6b6f283a9befa5d27dc480.jpg', '/tp5/thinkphp_5.0.10/public/1', '', '这是dome幻灯片2', 'hello world!', NULL), (3, 1, 1, 10003, '多撒多', '20180807\\1843e2b1607a87aa3ad30af1a9f4b6ac.png', 'dd ', '', 'dd', 'dd', NULL); -- -------------------------------------------------------- -- -- 表的结构 `lc_link` -- CREATE TABLE `lc_link` ( `id` bigint(20) UNSIGNED NOT NULL, `status` tinyint(3) UNSIGNED NOT NULL DEFAULT '1' COMMENT '状态;1:显示;0:不显示', `rating` int(11) NOT NULL DEFAULT '0' COMMENT '友情链接评级', `list_order` float NOT NULL DEFAULT '10000' COMMENT '排序', `description` varchar(255) NOT NULL DEFAULT '' COMMENT '友情链接描述', `url` varchar(255) NOT NULL DEFAULT '' COMMENT '友情链接地址', `name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '友情链接名称', `image` varchar(100) NOT NULL DEFAULT '' COMMENT '友情链接图标', `target` varchar(10) NOT NULL DEFAULT '' COMMENT '友情链接打开方式', `rel` varchar(50) NOT NULL DEFAULT '' COMMENT '链接与网站的关系' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='友情链接表'; -- -- 转存表中的数据 `lc_link` -- INSERT INTO `lc_link` (`id`, `status`, `rating`, `list_order`, `description`, `url`, `name`, `image`, `target`, `rel`) VALUES (1, 1, 1, 1, 'thinkcmf官网', 'http://www.thinkcmf.com', 'ThinkCMF', '20180807\\b6ba97440eacc9261880ef1da1df5ee7.jpg', '_blank', ''), (2, 1, 0, 2, '大多撒多撒', 'czhlove.cn', '多撒多撒', '20180807\\0fc664e7bd5b74ca58384992e0e7996e.jpg', '', ''); -- -------------------------------------------------------- -- -- 表的结构 `lc_user` -- CREATE TABLE `lc_user` ( `id` bigint(20) UNSIGNED NOT NULL, `user_type` tinyint(3) UNSIGNED NOT NULL DEFAULT '1' COMMENT '用户类型;1:admin;2:普通用户;3:vip;4:svip', `sex` tinyint(2) NOT NULL DEFAULT '0' COMMENT '性别;0:保密,1:男,2:女', `birthday` int(11) NOT NULL DEFAULT '0' COMMENT '生日', `last_login_time` int(11) NOT NULL DEFAULT '0' COMMENT '最后登录时间', `score` int(11) NOT NULL DEFAULT '0' COMMENT '用户积分', `coin` int(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '金币', `balance` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '余额', `register_time` int(11) NOT NULL DEFAULT '0' COMMENT '注册时间', `user_status` tinyint(3) UNSIGNED NOT NULL DEFAULT '1' COMMENT '用户状态;0:禁用,1:正常,2:未验证', `user_login` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '用户名', `user_pass` varchar(64) NOT NULL DEFAULT '' COMMENT '登录密码;cmf_password加密', `user_nickname` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '用户昵称', `user_email` varchar(100) NOT NULL DEFAULT '' COMMENT '用户登录邮箱', `user_url` varchar(100) NOT NULL DEFAULT '' COMMENT '用户个人网址', `avatar` varchar(255) NOT NULL DEFAULT '' COMMENT '用户头像', `signature` varchar(255) NOT NULL DEFAULT '' COMMENT '个性签名', `last_login_ip` varchar(15) NOT NULL DEFAULT '' COMMENT '最后登录ip', `user_activation_key` varchar(60) NOT NULL DEFAULT '' COMMENT '激活码', `mobile` varchar(20) NOT NULL DEFAULT '' COMMENT '中国手机不带国家代码,国际手机号格式为:国家代码-手机号', `more` text COMMENT '扩展属性', `count` int(10) DEFAULT '1', `user_state` int(10) NOT NULL DEFAULT '1' COMMENT '默认为1,2为停用', `delete_time` int(11) DEFAULT NULL COMMENT '软删除' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表'; -- -- 转存表中的数据 `lc_user` -- INSERT INTO `lc_user` (`id`, `user_type`, `sex`, `birthday`, `last_login_time`, `score`, `coin`, `balance`, `register_time`, `user_status`, `user_login`, `user_pass`, `user_nickname`, `user_email`, `user_url`, `avatar`, `signature`, `last_login_ip`, `user_activation_key`, `mobile`, `more`, `count`, `user_state`, `delete_time`) VALUES (1, 0, 2, 0, 1533647990, 1, 1, '0.00', 1531636605, 1, 'admin', '21232f297a57a5a743894a0e4a801fc3', 'admin', '196663624@qq.com', '', '', '', '0.0.0.2', '', '1300000000000', NULL, 42, 1, NULL), (2, 1, 1, 0, 1532493392, 1, 1, '0.00', 1531636605, 1, '123', '202cb962ac59075b964b07152d234b70', 'laucher72811', '196663624@qq.com', '', '', '', '0.0.0.2', '', '1300000000000', NULL, 6, 1, NULL), (3, 1, 1, 0, 0, 0, 0, '0.00', 0, 1, '666', '21232f297a57a5a743894a0e4a801fc3', 'laucher', '196663624@qq.com', '', '', '', '', '', '1300000000000', NULL, 1, 2, NULL), (5, 1, 1, 0, 1532844446, 0, 0, '0.00', 1532586253, 1, 'test', '098f6bcd4621d373cade4e832627b4f6', 'test', 'test@qq.com', '', '', '', '', '', '11111111111', NULL, 2, 1, NULL), (6, 0, 1, 0, 0, 0, 0, '0.00', 1532586412, 1, 'czh', '623df13aa8e8874363281b85b42e9df0', '我是管理员', '1@qq.com', '', '', '', '', '', '11111222222', NULL, 1, 2, NULL), (9, 4, 1, 0, 1532840351, 0, 0, '0.00', 1532790803, 1, '196663624', 'f1d0b05363174752ac1a7829acde248b', '刘晨', '196663624@qq.com', '', '', '', '', '', '13206026299', NULL, 3, 1, NULL), (10, 2, 1, 0, 0, 0, 0, '0.00', 1532843706, 1, '111111', '96e79218965eb72c92a549dd5a330112', '111111', '196663624@qq.co', '', '', '', '', '', '13206029263', NULL, 1, 1, NULL), (11, 2, 1, 0, 0, 0, 0, '0.00', 1532843742, 1, '111111', '96e79218965eb72c92a549dd5a330112', '111111', '196663624@qq.co', '', '', '', '', '', '13206029263', NULL, 1, 1, 1532845128), (12, 2, 1, 0, 0, 0, 0, '0.00', 1532843747, 1, '111111', '96e79218965eb72c92a549dd5a330112', '111111', '196663624@qq.co', '', '', '', '', '', '13206029263', NULL, 1, 1, NULL), (13, 2, 1, 0, 0, 0, 0, '0.00', 1532843831, 1, '111111', '96e79218965eb72c92a549dd5a330112', '111111', '196663624@qq.co', '', '', '', '', '', '13206029263', NULL, 1, 1, NULL), (14, 2, 1, 0, 0, 0, 0, '0.00', 1532843833, 1, '111111', '96e79218965eb72c92a549dd5a330112', '111111', '196663624@qq.co', '', '', '', '', '', '13206029263', NULL, 1, 1, NULL), (15, 2, 1, 0, 0, 0, 0, '0.00', 1532843862, 1, '11111133', '96e79218965eb72c92a549dd5a330112', '111111', '196663624@qq.c', '', '', '', '', '', '13206029265', NULL, 1, 1, NULL), (16, 2, 1, 0, 0, 0, 0, '0.00', 1532843896, 1, 'user666', 'b59c67bf196a4758191e42f76670ceba', '1111', '196663624@qq.com', '', '', '', '', '', '13206026299', NULL, 1, 2, NULL), (17, 2, 1, 0, 0, 0, 0, '0.00', 1532843902, 1, 'user666', 'b59c67bf196a4758191e42f76670ceba', '1111', '196663624@qq.com', '', '', '', '', '', '13206026299', NULL, 1, 1, NULL), (18, 2, 1, 0, 0, 0, 0, '0.00', 1532843915, 1, 'user666', 'b59c67bf196a4758191e42f76670ceba', '1111', '196663624@qq.com', '', '', '', '', '', '13206026299', NULL, 1, 1, NULL), (19, 2, 1, 0, 0, 0, 0, '0.00', 1532844006, 1, 'chen', 'b59c67bf196a4758191e42f76670ceba', 'laucher6', '196663624@qq.co', '', '', '', '', '', '13206026299', NULL, 1, 2, NULL), (20, 2, 1, 0, 0, 0, 0, '0.00', 1532844008, 1, 'chen', 'b59c67bf196a4758191e42f76670ceba', 'laucher6', '196663624@qq.co', '', '', '', '', '', '13206026299', NULL, 1, 2, NULL), (21, 2, 1, 0, 0, 0, 0, '0.00', 1532844033, 1, 'user', 'b59c67bf196a4758191e42f76670ceba', 'laucher1', '196663624@qq.co', '', '', '', '', '', '13206026299', NULL, 1, 1, NULL), (22, 2, 1, 0, 0, 0, 0, '0.00', 1532844035, 1, 'user', 'b59c67bf196a4758191e42f76670ceba', 'laucher1', '196663624@qq.co', '', '', '', '', '', '13206026299', NULL, 1, 1, NULL), (23, 2, 1, 0, 0, 0, 0, '0.00', 1532844096, 1, 'user666', '698d51a19d8a121ce581499d7b701668', '333', '', '', '', '', '', '', '13206026299', NULL, 1, 1, NULL), (24, 2, 1, 0, 0, 0, 0, '0.00', 1532844098, 1, 'user666', '698d51a19d8a121ce581499d7b701668', '333', '', '', '', '', '', '', '13206026299', NULL, 1, 1, NULL), (25, 4, 1, 0, 0, 0, 0, '0.00', 1532844125, 1, 'user666', '1f2121f36f817bd18540e5fa7de06f59', 'laucher6', '111@qq.com', '', '', '', '', '', '13896422327', NULL, 1, 1, NULL), (26, 2, 1, 0, 0, 0, 0, '0.00', 1532844127, 1, 'user666', '1f2121f36f817bd18540e5fa7de06f59', 'laucher6', '111@qq.com', '', '', '', '', '', '13206026299', NULL, 1, 1, NULL), (27, 2, 1, 0, 0, 0, 0, '0.00', 1532844127, 1, 'user666', '1f2121f36f817bd18540e5fa7de06f59', 'laucher6', '111@qq.com', '', '', '', '', '', '13206026299', NULL, 1, 1, NULL), (28, 2, 1, 0, 0, 0, 0, '0.00', 1532844128, 1, 'user666', '1f2121f36f817bd18540e5fa7de06f59', 'laucher6', '111@qq.com', '', '', '', '', '', '13206026299', NULL, 1, 1, NULL), (29, 2, 1, 0, 0, 0, 0, '0.00', 1532844131, 1, 'user666', '1f2121f36f817bd18540e5fa7de06f59', 'laucher6', '111@qq.com', '', '', '', '', '', '13206026299', NULL, 1, 1, NULL), (30, 2, 1, 0, 0, 0, 0, '0.00', 1532844168, 1, 'user666', '3e920e34faed7875441e9c6a6d0911ff', 'dsad', '196663624@qq.com', '', '', '', '', '', '13206026299', NULL, 1, 1, NULL), (31, 2, 1, 0, 0, 0, 0, '0.00', 1532844169, 1, 'user666', '3e920e34faed7875441e9c6a6d0911ff', 'dsad', '196663624@qq.com', '', '', '', '', '', '13206026299', NULL, 1, 1, NULL), (32, 2, 1, 0, 0, 0, 0, '0.00', 1532844170, 1, 'user666', '3e920e34faed7875441e9c6a6d0911ff', 'dsad', '196663624@qq.com', '', '', '', '', '', '13206026299', NULL, 1, 1, NULL), (33, 2, 1, 0, 0, 0, 0, '0.00', 1532844170, 1, 'user666', '3e920e34faed7875441e9c6a6d0911ff', 'dsad', '196663624@qq.com', '', '', '', '', '', '13206026299', NULL, 1, 1, NULL); -- -------------------------------------------------------- -- -- 表的结构 `lc_video` -- CREATE TABLE `lc_video` ( `id` int(10) NOT NULL, `state` int(2) NOT NULL DEFAULT '0' COMMENT '视频状态,0::停用;1:启用', `url` varchar(100) NOT NULL COMMENT '视频路径', `delete_time` int(50) NOT NULL COMMENT 'tp5软删除' ) ENGINE=InnoDB DEFAULT CHARSET=gbk; -- -------------------------------------------------------- -- -- 表的结构 `lc_web_info` -- CREATE TABLE `lc_web_info` ( `id` bigint(20) UNSIGNED NOT NULL, `autoload` tinyint(3) UNSIGNED NOT NULL DEFAULT '1' COMMENT '是否自动加载;1:自动加载;0:不自动加载', `option_name` varchar(64) NOT NULL DEFAULT '' COMMENT '配置名', `option_value` mediumtext COMMENT '配置值' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='全站配置表' ROW_FORMAT=COMPACT; -- -- 转存表中的数据 `lc_web_info` -- INSERT INTO `lc_web_info` (`id`, `autoload`, `option_name`, `option_value`) VALUES (1, 1, 'site_info', '{\"site_name\":\"\\u6211\\u662f\\u7f51\\u7ad9info\",\"site_seo_keywords\":\"SEO\\u5173\\u952e\\u5b57\",\"site_seo_description\":\"SEO\\u63cf\\u8ff0\",\"site_email\":\"196663624@qq.com\",\"site_copyright\":\"\\u5e95\\u90e8\\u4fe1\\u606f\",\"site_icp\":\"icp\",\"site_analytics\":\"\\u7edf\\u8ba1\\u4ee3\\u7801\",\"from_name\":\"LAUCHER-FASSS666\",\"smtp_secure\":\"ssl\",\"host\":\"smtp.yeah.net\",\"port\":\"465\",\"username\":\"laucher@yeah.net\",\"password\":\"liuchen520\",\"from\":\"laucher@yeah.net\",\"site_closure\":\"1\",\"stop_time\":\"2018\\/09\\/03 23:11:32\"}'); -- -- Indexes for dumped tables -- -- -- Indexes for table `lc_banner` -- ALTER TABLE `lc_banner` ADD PRIMARY KEY (`id`); -- -- Indexes for table `lc_banner_item` -- ALTER TABLE `lc_banner_item` ADD PRIMARY KEY (`id`), ADD KEY `slide_id` (`slide_id`); -- -- Indexes for table `lc_link` -- ALTER TABLE `lc_link` ADD PRIMARY KEY (`id`), ADD KEY `status` (`status`); -- -- Indexes for table `lc_user` -- ALTER TABLE `lc_user` ADD PRIMARY KEY (`id`), ADD KEY `user_login` (`user_login`), ADD KEY `user_nickname` (`user_nickname`); -- -- Indexes for table `lc_video` -- ALTER TABLE `lc_video` ADD PRIMARY KEY (`id`); -- -- Indexes for table `lc_web_info` -- ALTER TABLE `lc_web_info` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `option_name` (`option_name`); -- -- 在导出的表使用AUTO_INCREMENT -- -- -- 使用表AUTO_INCREMENT `lc_banner` -- ALTER TABLE `lc_banner` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- 使用表AUTO_INCREMENT `lc_banner_item` -- ALTER TABLE `lc_banner_item` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- 使用表AUTO_INCREMENT `lc_link` -- ALTER TABLE `lc_link` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- 使用表AUTO_INCREMENT `lc_user` -- ALTER TABLE `lc_user` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=34; -- -- 使用表AUTO_INCREMENT `lc_video` -- ALTER TABLE `lc_video` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT; -- -- 使用表AUTO_INCREMENT `lc_web_info` -- ALTER TABLE `lc_web_info` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
49.552901
595
0.629382
459f1dc8944ded4218b69a3b14559e8899ca35f9
5,748
swift
Swift
TestFoundation/TestNSCharacterSet.swift
Bhaskers-Blu-Org2/swift-corelibs-foundation
4b7ee5a9a3f90b14b0fbca57758d05efdd66d049
[ "Apache-2.0" ]
3
2020-05-09T14:34:53.000Z
2021-11-11T19:43:39.000Z
TestFoundation/TestNSCharacterSet.swift
rajsesh-msft/swift-corelibs-foundation
4b7ee5a9a3f90b14b0fbca57758d05efdd66d049
[ "Apache-2.0" ]
null
null
null
TestFoundation/TestNSCharacterSet.swift
rajsesh-msft/swift-corelibs-foundation
4b7ee5a9a3f90b14b0fbca57758d05efdd66d049
[ "Apache-2.0" ]
5
2019-11-02T20:53:10.000Z
2021-11-10T10:14:18.000Z
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestNSCharacterSet : XCTestCase { static var allTests: [(String, TestNSCharacterSet -> () throws -> Void)] { return [ ("test_Predefines", test_Predefines), ("test_Range", test_Range), ("test_String", test_String), ("test_Bitmap", test_Bitmap), ("test_Mutables", test_Mutables), ("test_AnnexPlanes", test_AnnexPlanes), ("test_Planes", test_Planes), ("test_InlineBuffer", test_InlineBuffer), ] } func test_Predefines() { let cset = NSCharacterSet.controlCharacterSet() XCTAssertTrue(cset === NSCharacterSet.controlCharacterSet(), "predefined charactersets should be singletons") XCTAssertTrue(cset.characterIsMember(unichar(0xFEFF)), "Control set should contain UFEFF") XCTAssertTrue(NSCharacterSet.letterCharacterSet().characterIsMember("a"), "Letter set should contain 'a'") XCTAssertTrue(NSCharacterSet.lowercaseLetterCharacterSet().characterIsMember("a"), "Lowercase Letter set should contain 'a'") XCTAssertTrue(NSCharacterSet.uppercaseLetterCharacterSet().characterIsMember("A"), "Uppercase Letter set should contain 'A'") XCTAssertTrue(NSCharacterSet.uppercaseLetterCharacterSet().characterIsMember(unichar(0x01C5)), "Uppercase Letter set should contain U01C5") XCTAssertTrue(NSCharacterSet.capitalizedLetterCharacterSet().characterIsMember(unichar(0x01C5)), "Uppercase Letter set should contain U01C5") XCTAssertTrue(NSCharacterSet.symbolCharacterSet().characterIsMember(unichar(0x002B)), "Symbol set should contain U002B") XCTAssertTrue(NSCharacterSet.symbolCharacterSet().characterIsMember(unichar(0x20B1)), "Symbol set should contain U20B1") XCTAssertTrue(NSCharacterSet.newlineCharacterSet().characterIsMember(unichar(0x000A)), "Newline set should contain 0x000A") XCTAssertTrue(NSCharacterSet.newlineCharacterSet().characterIsMember(unichar(0x2029)), "Newline set should contain 0x2029") let mcset = NSMutableCharacterSet.whitespaceAndNewlineCharacterSet() let cset2 = NSCharacterSet.whitespaceAndNewlineCharacterSet() XCTAssert(mcset.isSupersetOfSet(cset2)) XCTAssert(cset2.isSupersetOfSet(mcset)) XCTAssertTrue(NSCharacterSet.whitespaceAndNewlineCharacterSet().isSupersetOfSet(NSCharacterSet.newlineCharacterSet()), "whitespace and newline should be a superset of newline") let data = NSCharacterSet.uppercaseLetterCharacterSet().bitmapRepresentation XCTAssertNotNil(data) } func test_Range() { let cset1 = NSCharacterSet(range: NSMakeRange(0x20, 40)) for idx: unichar in 0..<0xFFFF { XCTAssertEqual(cset1.characterIsMember(idx), (idx >= 0x20 && idx < 0x20 + 40 ? true : false)) } let cset2 = NSCharacterSet(range: NSMakeRange(0x0000, 0xFFFF)) for idx: unichar in 0..<0xFFFF { XCTAssertEqual(cset2.characterIsMember(idx), true) } let cset3 = NSCharacterSet(range: NSMakeRange(0x0000, 10)) for idx: unichar in 0..<0xFFFF { XCTAssertEqual(cset3.characterIsMember(idx), (idx < 10 ? true : false)) } let cset4 = NSCharacterSet(range: NSMakeRange(0x20, 0)) for idx: unichar in 0..<0xFFFF { XCTAssertEqual(cset4.characterIsMember(idx), false) } } func test_String() { let cset = NSCharacterSet(charactersInString: "abcABC") for idx: unichar in 0..<0xFFFF { XCTAssertEqual(cset.characterIsMember(idx), (idx >= unichar(unicodeScalarLiteral: "a") && idx <= unichar(unicodeScalarLiteral: "c")) || (idx >= unichar(unicodeScalarLiteral: "A") && idx <= unichar(unicodeScalarLiteral: "C")) ? true : false) } } func test_Bitmap() { } func test_Mutables() { let attachmentCharacterUnichar = unichar(0xFFFC) let attachmentCharacter = Character(UnicodeScalar(attachmentCharacterUnichar)) let attachmentCharacterRange = NSRange(Int(attachmentCharacterUnichar)..<Int(attachmentCharacterUnichar.successor())) let initialSetRange = NSRange(location: 0, length: 0) let string = String(attachmentCharacter) let mcset1 = NSMutableCharacterSet(range: initialSetRange) mcset1.addCharactersInRange(attachmentCharacterRange) XCTAssertTrue(mcset1.characterIsMember(attachmentCharacterUnichar), "attachmentCharacter should be member of mcset1 after being added") XCTAssertNotNil(string.rangeOfCharacterFromSet(mcset1), "Range of character from mcset1 set should not be nil") let mcset2 = NSMutableCharacterSet(range: initialSetRange) mcset2.addCharactersInString(string) XCTAssertTrue(mcset2.characterIsMember(attachmentCharacterUnichar), "attachmentCharacter should be member of mcset2 after being added") XCTAssertNotNil(string.rangeOfCharacterFromSet(mcset2), "Range of character from mcset2 should not be nil") } func test_AnnexPlanes() { } func test_Planes() { } func test_InlineBuffer() { } }
43.877863
252
0.693633
ab0aaef59d15fadc146ecdc991296c299a32302a
523
sql
SQL
l2j_datapack/dist/sql/game/updates/20090131update.sql
RollingSoftware/L2J_HighFive_Hardcore
a3c794c82c32b5afca49416119b4aafa8fb9b6d4
[ "MIT" ]
null
null
null
l2j_datapack/dist/sql/game/updates/20090131update.sql
RollingSoftware/L2J_HighFive_Hardcore
a3c794c82c32b5afca49416119b4aafa8fb9b6d4
[ "MIT" ]
38
2018-02-06T17:11:29.000Z
2018-06-05T20:47:59.000Z
l2j_datapack/dist/sql/game/updates/20090131update.sql
RollingSoftware/L2J_HighFive_Hardcore
a3c794c82c32b5afca49416119b4aafa8fb9b6d4
[ "MIT" ]
null
null
null
ALTER TABLE `fort` ADD COLUMN `fortType` int(1) NOT NULL DEFAULT 0; ALTER TABLE `fort` ADD COLUMN `state` int(1) NOT NULL DEFAULT 0; ALTER TABLE `fort` ADD COLUMN `castleId` int(1) NOT NULL DEFAULT 0; UPDATE `fort` SET `fortType` = '1' WHERE id IN (102,104,107,109,110,112,113,116,117,118); ALTER TABLE `fortsiege_clans` DROP `type`; ALTER TABLE `fortsiege_clans` DROP `fort_owner`; DROP TABLE IF EXISTS `fort_door`; UPDATE `fort` SET `name`='Swamp' WHERE id = 110; UPDATE `fort` SET `name`='Cloud Mountain' WHERE id = 113;
58.111111
89
0.722753
dbcf1f2c34b103b75e24db59799e12d5b21b0146
325
php
PHP
app/Model/AdditionalBenifits.php
116312/Nucleus-PHP-Code
3aea920baa3262b1935f3f909ea4540ea8c75caa
[ "MIT" ]
null
null
null
app/Model/AdditionalBenifits.php
116312/Nucleus-PHP-Code
3aea920baa3262b1935f3f909ea4540ea8c75caa
[ "MIT" ]
null
null
null
app/Model/AdditionalBenifits.php
116312/Nucleus-PHP-Code
3aea920baa3262b1935f3f909ea4540ea8c75caa
[ "MIT" ]
null
null
null
<?php namespace App\Model; use Illuminate\Database\Eloquent\Model; class AdditionalBenifits extends Model { protected $table ='additional_benifits'; public function subscriptionplandetails() { return $this->belongsTo('App\Model\SubscriptionPlanDetails','subscription_plan_details_id'); } }
18.055556
100
0.729231
12b05558faa42588d43417376df649dd6d71dd7a
1,410
lua
Lua
MMOCoreORB/bin/scripts/mobile/dungeon/warren/warren_stormtrooper.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/bin/scripts/mobile/dungeon/warren/warren_stormtrooper.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/bin/scripts/mobile/dungeon/warren/warren_stormtrooper.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
warren_stormtrooper = Creature:new { objectName = "@mob/creature_names:warren_stormtrooper", randomNameType = NAME_STORMTROOPER, randomNameTag = true, socialGroup = "warren_imperial", faction = "", level = 26, chanceHit = 0.360000, damageMin = 240, damageMax = 250, baseXp = 2730, baseHAM = 7200, baseHAMmax = 8800, armor = 0, resists = {20,20,40,0,0,0,0,-1,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0.000000, ferocity = 0, pvpBitmask = ATTACKABLE + AGGRESSIVE + ENEMY, creatureBitmask = PACK + KILLER, diet = HERBIVORE, templates = {"object/mobile/warren_stormtrooper.iff"}, lootGroups = { { groups = { {group = "color_crystals", chance = 100000}, {group = "junk", chance = 3400000}, {group = "rifles", chance = 1200000}, {group = "pistols", chance = 1200000}, {group = "melee_weapons", chance = 1200000}, {group = "carbines", chance = 1200000}, {group = "clothing_attachments", chance = 250000}, {group = "armor_attachments", chance = 250000}, {group = "stormtrooper_common", chance = 700000}, {group = "wearables_common", chance = 500000} } } }, weapons = {"stormtrooper_weapons"}, attacks = merge(brawlermaster,marksmanmaster,riflemanmaster,carbineermaster) } CreatureTemplates:addCreatureTemplate(warren_stormtrooper, "warren_stormtrooper")
27.647059
81
0.676596
39380a3e09015b90e86dbf884c4ce97d19e6ef4b
364
py
Python
all_index.py
michaelwinn/python
e811c654f949b020aee5e10c5e2740d564fbc407
[ "MIT" ]
null
null
null
all_index.py
michaelwinn/python
e811c654f949b020aee5e10c5e2740d564fbc407
[ "MIT" ]
null
null
null
all_index.py
michaelwinn/python
e811c654f949b020aee5e10c5e2740d564fbc407
[ "MIT" ]
null
null
null
def all_index(array, num): indx = [] for i in range(0,len(array)): for j in range(0,array[i].count(num)): if j == 0: indx.append([i, array[i].index(num)]) else: indx.append([i, array[i].index(num,indx[j-1][1]+1)]) return indx tic = [[1,1,0],[0,2,1],[1,2,2]] print(all_index(tic, 1))
21.411765
68
0.483516
dd6e94c5979c2c06d9d3fbe3472f705574ccbc39
2,555
java
Java
engine-jdk8-tests/src/test/java/org/hibernate/validator/test/internal/engine/valuehandling/JavaFXClassLoadingTest.java
fenrhil/hibernate-validator
ef9e0abdba01deb13a0013ef7254b54b4ad23159
[ "Apache-2.0" ]
null
null
null
engine-jdk8-tests/src/test/java/org/hibernate/validator/test/internal/engine/valuehandling/JavaFXClassLoadingTest.java
fenrhil/hibernate-validator
ef9e0abdba01deb13a0013ef7254b54b4ad23159
[ "Apache-2.0" ]
null
null
null
engine-jdk8-tests/src/test/java/org/hibernate/validator/test/internal/engine/valuehandling/JavaFXClassLoadingTest.java
fenrhil/hibernate-validator
ef9e0abdba01deb13a0013ef7254b54b4ad23159
[ "Apache-2.0" ]
null
null
null
/* * Hibernate Validator, declare and validate application constraints * * License: Apache License, Version 2.0 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>. */ package org.hibernate.validator.test.internal.engine.valuehandling; import java.security.AccessController; import java.security.PrivilegedAction; import javax.validation.ValidationException; import org.fest.assertions.Assertions; import org.hibernate.validator.internal.util.privilegedactions.LoadClass; import org.hibernate.validator.testutil.TestForIssue; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.classloader.ShrinkWrapClassLoader; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; /** * @author Davide D'Alto */ @TestForIssue( jiraKey = "HV-1017") public class JavaFXClassLoadingTest { /** * This class will be present in the TCCL because is part of JDK 8 */ private static final String JAVAFX_APPLICATION_CLASS = "javafx.application.Application"; @Test public void shouldBeAbleToFindTheClassInTCCL() throws Exception { JavaArchive archive = ShrinkWrap.create( JavaArchive.class ).addClass( JavaFXClassLoadingTest.class ); ShrinkWrapClassLoader classLoaderWithoutExpectedClass = new ShrinkWrapClassLoader( (ClassLoader) null, archive ); Assertions.assertThat( isClassPresent( JAVAFX_APPLICATION_CLASS, classLoaderWithoutExpectedClass, true ) ).isTrue(); } @Test public void shouldNotFindTheClass() throws Exception { JavaArchive archive = ShrinkWrap.create( JavaArchive.class ).addClass( JavaFXClassLoadingTest.class ); ShrinkWrapClassLoader classLoaderWithoutExpectedClass = new ShrinkWrapClassLoader( (ClassLoader) null, archive ); Assertions.assertThat( isClassPresent( JAVAFX_APPLICATION_CLASS, classLoaderWithoutExpectedClass, false ) ).isFalse(); } private static boolean isClassPresent(String className, ClassLoader classLoader, boolean fallbackOnTCCL) { try { run( LoadClass.action( className, classLoader, fallbackOnTCCL ) ); return true; } catch (ValidationException e) { return false; } } /** * Runs the given privileged action, using a privileged block if required. * <p> * <b>NOTE:</b> This must never be changed into a publicly available method to avoid execution of arbitrary * privileged actions within HV's protection domain. */ private static <T> T run(PrivilegedAction<T> action) { return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run(); } }
37.573529
120
0.783562
4ccaf094764b07b4d3672dc38961946e45b23350
1,859
swift
Swift
Domain/Domain/Cache/MemoryCache.swift
Pointwelve/Bitpal-iOS
ac1eff918db0b28ab8990b0f7de4dee49bfe0d17
[ "Apache-2.0" ]
1
2020-03-18T19:15:28.000Z
2020-03-18T19:15:28.000Z
Sources/Domain/Cache/MemoryCache.swift
Pointwelve/Bitpal-iOS
ac1eff918db0b28ab8990b0f7de4dee49bfe0d17
[ "Apache-2.0" ]
null
null
null
Sources/Domain/Cache/MemoryCache.swift
Pointwelve/Bitpal-iOS
ac1eff918db0b28ab8990b0f7de4dee49bfe0d17
[ "Apache-2.0" ]
1
2020-05-19T05:24:34.000Z
2020-05-19T05:24:34.000Z
// // MemoryCache.swift // Domain // // Created by Ryne Cheow on 17/4/17. // Copyright © 2017 Pointwelve. All rights reserved. // import Foundation import RxSwift public class MemoryCache<K, V>: Cache where K: Hashable { public typealias Key = K public typealias Value = V public init() {} let semaphore = DispatchSemaphore(value: 1) private var values = [Key: Value]() public func keyValues() -> Observable<[(K, V)]> { semaphore.wait() defer { semaphore.signal() } let keyValues = values.map { ($0, $1) } return Observable.just(keyValues) } private func debugCount() { debugPrint("\(Value.self) count in memory: \(values.count)") } public func get(_ key: Key) -> Observable<Value> { semaphore.wait() defer { semaphore.signal() } guard let value = values[key] else { return Observable.error(CacheError.notFound) } return Observable.just(value) } public func set(_ value: Value, for key: Key) -> Observable<Void> { semaphore.wait() defer { debugCount() semaphore.signal() } values[key] = value return Observable.just(()) } public func delete(_ key: K) -> Observable<Void> { semaphore.wait() defer { debugCount() semaphore.signal() } guard values.removeValue(forKey: key) != nil else { return Observable.error(CacheError.notFound) } return Observable.just(()) } public func clear() { semaphore.wait() defer { debugCount() semaphore.signal() } values.removeAll() } public func onMemoryWarning() { semaphore.wait() defer { debugCount() semaphore.signal() } values.removeAll() } }
20.88764
70
0.570737
ffb4e937b189889baf4ddf451c748b769601bea2
291
py
Python
mindhome_alpha/erpnext/patches/v12_0/rename_account_type_doctype.py
Mindhome/field_service
3aea428815147903eb9af1d0c1b4b9fc7faed057
[ "MIT" ]
1
2021-04-29T14:55:29.000Z
2021-04-29T14:55:29.000Z
mindhome_alpha/erpnext/patches/v12_0/rename_account_type_doctype.py
Mindhome/field_service
3aea428815147903eb9af1d0c1b4b9fc7faed057
[ "MIT" ]
null
null
null
mindhome_alpha/erpnext/patches/v12_0/rename_account_type_doctype.py
Mindhome/field_service
3aea428815147903eb9af1d0c1b4b9fc7faed057
[ "MIT" ]
1
2021-04-29T14:39:01.000Z
2021-04-29T14:39:01.000Z
from __future__ import unicode_literals import frappe def execute(): frappe.rename_doc('DocType', 'Account Type', 'Bank Account Type', force=True) frappe.rename_doc('DocType', 'Account Subtype', 'Bank Account Subtype', force=True) frappe.reload_doc('accounts', 'doctype', 'bank_account')
41.571429
84
0.766323
6daa1d33a6742895fe8652a84d3d9c980d45e97a
320
kt
Kotlin
src/main/kotlin/com/github/hotm/auranet/RenderedDependableAuraNode.kt
Heart-of-the-Machine/heart-of-the-machine
2e44dd9074df0dd91e8b7b92ed854dcd9a6f7963
[ "MIT" ]
4
2020-07-05T01:24:33.000Z
2020-09-14T13:46:33.000Z
src/main/kotlin/com/github/hotm/auranet/RenderedDependableAuraNode.kt
Heart-of-the-Machine/heart-of-the-machine
2e44dd9074df0dd91e8b7b92ed854dcd9a6f7963
[ "MIT" ]
41
2020-07-11T19:18:15.000Z
2021-08-09T04:33:42.000Z
src/main/kotlin/com/github/hotm/auranet/RenderedDependableAuraNode.kt
Heart-of-the-Machine/heart-of-the-machine
2e44dd9074df0dd91e8b7b92ed854dcd9a6f7963
[ "MIT" ]
null
null
null
package com.github.hotm.auranet import net.minecraft.util.math.BlockPos import java.util.stream.Stream interface RenderedDependableAuraNode : DependableAuraNode { fun getChildrenForRender(): Stream<BlockPos> fun getSuppliedAuraForRender(pos: BlockPos): Float fun getCrownRollSpeed(pos: BlockPos): Float }
26.666667
59
0.8
58bd42af770b7cc951d35f6c7a05a88fe084d341
8,680
css
CSS
css/about.css
Mathenge-Alex/Rent-A-Hand
1f987f815cc4158c9d1535e442dfcb7ba7be876a
[ "MIT" ]
null
null
null
css/about.css
Mathenge-Alex/Rent-A-Hand
1f987f815cc4158c9d1535e442dfcb7ba7be876a
[ "MIT" ]
null
null
null
css/about.css
Mathenge-Alex/Rent-A-Hand
1f987f815cc4158c9d1535e442dfcb7ba7be876a
[ "MIT" ]
null
null
null
@import url('https://fonts.googleapis.com/css?family=Open+Sans'); body{ background-color:#52ab98; background-image: linear-gradient(#52ab98 ,#ffffff); font-family: "Open Sans", sans-serif; } /* header styling - austin header{ background-color: #0F1010; height: 10vh; display: flex; color: white; justify-content: space-around; width: 100%; } header ul{ text-decoration: none; display: flex; justify-content: space-around; list-style: none; } header ul li a ,button{ text-decoration: none; color: white; margin-left: 2em; } header button{ background-color: #52ab98; width: 70px; height: 30px; font-weight: bolder; } header ul,p{ margin-top: 2em; font-size: bold; } header p{ font-weight: 100; font-family: "pacifico";} */ /* HEADER STYLING */ .bg-img { height: 8vh; width: 100% auto; background-repeat: no-repeat; background-size: cover; opacity: 0.9; background-position: center; } .navbar { display: flex; justify-content: space-between; } .navbar .icon { display: none; } .logo { font-family: pacifico; font-weight: 700; font-size: 3em; color: #AEEDF5; margin: 5px 40px; } .hw { overflow: hidden; } .navbar ul li { list-style-type: none; display: inline-block; padding: 1em; } .navbar ul li a{ text-decoration: none; font-size: 1em; text-transform: capitalize; font-style: italic; font-weight: 500; } .navbar .hw li a { color: #fff; } .navbar .rf li a { color: #002B2E; } .navbar .rf li a:hover { color: #246859; } .btn-login { background-color: #002B2E; border-radius: 5px; width: 100px; text-align: center; margin-right: 40px; border: none; height: 40px; color: #fff; font-style: italic; text-transform: capitalize; } .navbar ul li a:hover { color: #AEEDF5; overflow: hidden; } .btn-login:hover { background-color: #AEEDF5; color: #002B2E; } /* about us */ .aboutus{ margin-top: 3%; display: flex; width: 95%; margin-left: auto; margin-right: auto; height: 70vh; background-color: white; } .left{ flex-direction: left; width: 70%; height: 100%; padding-left: 5%; } h1{ text-decoration: underline; font-size: 50px; } .left > p{ font-size: x-large; } .right{ flex-direction: right; background-image: url(../images/hands.jpeg); background-repeat: no-repeat; width: 30%; height: 100%; } .cleaning{ height: 35%; width: 39%; background-image: url(../images/clean.jpg); background-repeat: no-repeat; background-size: contain; position: absolute; right: 20%; top: 30%;} .cleaning > img { position: absolute; bottom: 5%; left: 5%; } .button{ padding-top: 2%; display: flex; width: 50%; } .left > div > input{ color: black; background-color: #52ab98; padding: 5px 20px 5px 20px; border-radius:50px; } /* icon div styling */ .icons{ padding-top: 3%; width: 95%; margin: auto; display: flex; justify-content: space-around; text-align: center; } .icons > div > img { border-radius:50%; } /* meet the teams */ .h2{ width: 95%; margin: auto; text-align: center; font-size: x-large; text-decoration: underline; } /* team info */ .top{ padding-top: 2%; width: 95%; height:50vh; margin: auto; display: flex; justify-content: space-around; } .bottom{ width: 95%; height:50vh; margin: auto; display: flex; justify-content: space-evenly; } .team{ border-radius: 50%; } .team>img{ object-fit: cover; } .top > div > p{ text-align: center; } .bottom > div > p{ text-align: center; } /* footer section */ .footer{ width: 100%; height: 40vh; display: flex; justify-content: space-around; align-items: center; } footer hr{ border-bottom: #52AB98; } .f1{ font-size: larger; font-weight: bolder; width: 80px; } .f2 ul{ list-style: none; } .f2 li{ margin-top: 10px; } .first{ font-size: larger; font-weight: bolder; } .f3 ul{ list-style: none; } .f3 li{ margin-bottom: 10px; } .f3 li i{ margin-right: 10px; color: #52AB98; font-size: 20px; } #email{ padding: 15px; margin-top: 50px; border:transparent; border-radius: 10px 0 0 10px; } #email2{ padding: 15px; border-radius: 0 10px 10px 0; border: transparent; background-color: #52AB98; } .rights{ width: 100%; height: 50px; background-color: #0F1010; display: flex; justify-content: space-between; align-items: baseline; } .rights p{ color: #52AB98; font-weight: bold; margin-bottom: 20px; } #rights i{ font-size: 20px; margin-right: 20px; color: #52AB98; } /* mission/vision styling */ .changePage{ background-image: url(../images/hands.jpeg); background-repeat: no-repeat; background-size: cover; background-color: rgba(0, 0, 0, 0.5); width: 100%; height: 50vh; color: white; } .changePage > h2{ color:white ; font-weight: bolder; text-decoration: underline; text-align: center; font-size: xx-large; } .info{ display: flex; color:#52ab98; height: 100%; width: 100%; margin: auto; text-align: center; font-size: x-large; } .info1{ flex-direction: left; width: 50%; height: 100%; } .info2{ flex-direction: right; width: 50%; height: 100%; } /* RESPONSIVE DESIGN */ @media only screen and (max-width:1000px){ /* NAVBAR RESPONSIVE */ @media screen and (max-width: 1000px) { .navbar { display: flex; } .navbar .icon { display: none; } .logo { font-weight: 600; font-size: 2em; margin-right: 30px; padding: 2px; } .hw { overflow: hidden; } .navbar ul li { display: flex; padding: 0.5em; } .navbar ul li a{ font-weight: 400; } .btn-login { float: right; } .bg-img { height: 50vh; } .aboutus{ margin-top: 3%; display: flex; flex-direction: column; width: 95%; margin-left: auto; margin-right: auto; height: 70vh; background-image: url(../images/hands.jpeg); background-repeat: no-repeat; background-size: cover; } .left{ width:95%; height: 100%; padding-left: 5%; color: white; } h1{ text-decoration: underline; font-size: 30px; } .left > p{ font-size: large; } .right{ display: none; background-image: url(../images/hands.jpeg); background-repeat: no-repeat; background-size: contain; width: 80%; height: 100%; } .cleaning{ display: none; height: 35%; width: 39%; background-image: url(../images/clean.jpg); background-repeat: no-repeat; background-size: contain; position: absolute; right: 20%; top: 30%;} .cleaning > img { display: none; position: absolute; bottom: 5%; left: 5%; } .button{ display: flex; width: 20%; } .left > div > input{ color: black; background-color: #52ab98; padding: 5px 10px 5px 10px; border-radius:50px; } /* /* icon div styling */ .icons{ padding-top: 3%; width: 95%; height: 20vh; margin: auto; display: flex; justify-content: space-around; text-align: center; } .icons > div > img { border-radius:50%; } /* team info */ .top{ padding-top: 2%; width: 95%; height:50vh; margin: auto; display: flex; justify-content: space-around; } .bottom{ padding-top: 10%; padding-bottom: 10%; width: 95%; height:50vh; margin: auto; display: flex; justify-content: space-evenly; } /* /* mission/vision styling */ .changePage{ background-image: url(../images/hands.jpeg); background-repeat: no-repeat; background-size: cover; width: 100%; height: 80%; color: white; } .changePage > h2{ color:white ; text-align: center; font-size: xx-large; } .info{ display: flex; flex-direction: column; color:#52ab98; align-items: center; height: 100%; width: 100%; margin: auto; text-align: center; font-size: medium; } .info1{ width: 50%; height: 100%; margin-bottom: 5%; } .info2{ width: 50%; height: 100%; margin-bottom: 5%; } /* footer styling */ .footer{ height: 90vh; flex-direction: column; } .f1{ font-size: medium; } .f2 , .f3{ font-size: small; } footer form{ display: flex; } #email{ padding: 0%; height: 20px; } #email2{ padding: 0%; height: 20px; margin-top: 3.8em; } }
16.377358
65
0.590092
c4c5967a1fdc234c240577ee2dc274dfb50c5df2
9,922
cpp
C++
OcularCore/src/Scene/Routines/FreeFlyController.cpp
ssell/OcularEngine
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
[ "Apache-2.0" ]
8
2017-01-27T01:06:06.000Z
2020-11-05T20:23:19.000Z
OcularCore/src/Scene/Routines/FreeFlyController.cpp
ssell/OcularEngine
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
[ "Apache-2.0" ]
39
2016-06-03T02:00:36.000Z
2017-03-19T17:47:39.000Z
OcularCore/src/Scene/Routines/FreeFlyController.cpp
ssell/OcularEngine
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
[ "Apache-2.0" ]
4
2019-05-22T09:13:36.000Z
2020-12-01T03:17:45.000Z
/** * Copyright 2014-2017 Steven T Sell (ssell@vertexfragment.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Scene/Routines/FreeFlyController.hpp" #include "Scene/SceneObject.hpp" #include "Events/Events/KeyboardInputEvent.hpp" #include "Math/Matrix3x3.hpp" #include "OcularEngine.hpp" OCULAR_REGISTER_ROUTINE(Ocular::Core::FreeFlyController, "FreeFlyController") namespace { const float StaticSensitivityScale = 0.001f; ///< Default scaling applied to mouse looking, as even a sensitivity of 1.0 is extremely high. } //------------------------------------------------------------------------------------------ namespace Ocular { namespace Core { //---------------------------------------------------------------------------------- // CONSTRUCTORS //---------------------------------------------------------------------------------- FreeFlyController::FreeFlyController() : ARoutine("FreeFlyController", "FreeFlyController"), m_LookSensitivity(1.0f), m_MovementSpeed(1.0f), m_BurstModifier(5.0f), m_PreventRoll(true), m_IsInBurst(false) { OcularEvents->registerListener(this, Priority::Medium); OCULAR_EXPOSE(m_LookSensitivity); OCULAR_EXPOSE(m_MovementSpeed); OCULAR_EXPOSE(m_BurstModifier); OCULAR_EXPOSE(m_BurstModifier); OCULAR_EXPOSE(m_IsInBurst); } FreeFlyController::~FreeFlyController() { OcularEvents->unregisterListener(this); } //---------------------------------------------------------------------------------- // PUBLIC METHODS //---------------------------------------------------------------------------------- //---------------------------------------------------------------------------------- // Inherited Methods //---------------------------------------------------------------------------------- void FreeFlyController::onUpdate(float const delta) { ARoutine::onUpdate(delta); if(m_Parent) { handleMovement(delta); handleMouseRotation(); } } bool FreeFlyController::onEvent(std::shared_ptr<AEvent> event) { if(event->isType<KeyboardInputEvent>()) { KeyboardInputEvent* inputEvent = dynamic_cast<KeyboardInputEvent*>(event.get()); switch(inputEvent->key) { case KeyboardKeys::W: case KeyboardKeys::UpArrow: { if(inputEvent->state == KeyState::Pressed) { m_MovementVector.z = -1.0f; } else { m_MovementVector.z = 0.0f; } break; } case KeyboardKeys::A: case KeyboardKeys::LeftArrow: { if(inputEvent->state == KeyState::Pressed) { m_MovementVector.x = -1.0f; } else { m_MovementVector.x = 0.0f; } break; } case KeyboardKeys::S: case KeyboardKeys::DownArrow: { if(inputEvent->state == KeyState::Pressed) { m_MovementVector.z = 1.0f; } else { m_MovementVector.z = 0.0f; } break; } case KeyboardKeys::D: case KeyboardKeys::RightArrow: { if(inputEvent->state == KeyState::Pressed) { m_MovementVector.x = 1.0f; } else { m_MovementVector.x = 0.0f; } break; } case KeyboardKeys::Q: { if(inputEvent->state == KeyState::Pressed) { m_MovementVector.y = 1.0f; } else { m_MovementVector.y = 0.0f; } break; } case KeyboardKeys::Z: { if(inputEvent->state == KeyState::Pressed) { m_MovementVector.y = -1.0f; } else { m_MovementVector.y = 0.0f; } break; } case KeyboardKeys::ShiftLeft: { if(inputEvent->state == KeyState::Pressed) { m_IsInBurst = true; } else { m_IsInBurst = false; } break; } case KeyboardKeys::Space: { if(inputEvent->state == KeyState::Released) { if(m_Parent) { m_Euler.x = 0.0f; m_Euler.y = 0.0f; m_Parent->resetRotation(); } } break; } default: break; } } return true; } //---------------------------------------------------------------------------------- // Controller Specific Methods //---------------------------------------------------------------------------------- void FreeFlyController::setLookSensitivity(float sensitivity) { m_LookSensitivity = sensitivity; } float FreeFlyController::getLookSensitivity() const { return m_LookSensitivity; } void FreeFlyController::setMovementSpeed(float speed) { m_MovementSpeed = speed; } float FreeFlyController::getMovementSpeed() const { return m_MovementSpeed; } void FreeFlyController::setBurstSpeedModifier(float modifier) { m_BurstModifier = modifier; } float FreeFlyController::getBurstSpeedModifier() const { return m_BurstModifier; } void FreeFlyController::setPreventRoll(bool prevent) { m_PreventRoll = prevent; } bool FreeFlyController::getPreventRoll() const { return m_PreventRoll; } //---------------------------------------------------------------------------------- // PROTECTED METHODS //---------------------------------------------------------------------------------- void FreeFlyController::handleMovement(float delta) { float speed = m_MovementSpeed; if(m_IsInBurst) { speed *= m_BurstModifier; } m_Parent->translate(m_MovementVector * speed * delta); } void FreeFlyController::handleMouseRotation() { const Math::Vector2i currentMousePos = OcularInput->getMousePosition(); if(currentMousePos != m_LastMousePos) { const float dX = (static_cast<float>(currentMousePos.x) - static_cast<float>(m_LastMousePos.x)) * (StaticSensitivityScale * m_LookSensitivity); const float dY = (static_cast<float>(currentMousePos.y) - static_cast<float>(m_LastMousePos.y)) * (StaticSensitivityScale * m_LookSensitivity); if(m_PreventRoll) { m_Euler.x += -dY; m_Euler.y += -dX; m_Parent->setRotation(Math::Quaternion(m_Euler)); } else { Math::Quaternion rotation = Math::Quaternion(Math::Vector3f(-dX, dY, 0.0f)); m_Parent->rotate(rotation); Math::Quaternion rotX = Math::Quaternion(Math::Vector3f(-dX, 0.0f, 0.0f)); Math::Quaternion rotY = Math::Quaternion(Math::Vector3f(0.0f, dY, 0.0f)); m_Parent->rotate(rotY); m_Parent->rotate(rotX); } m_LastMousePos = currentMousePos; } } //---------------------------------------------------------------------------------- // PRIVATE METHODS //---------------------------------------------------------------------------------- } }
31.398734
159
0.395586
2f16f1fec55019324517489d756a558b37245e3f
390,010
js
JavaScript
index.js
halfnelson/svelte-component-parser
6d75dc48791c25825a0bf7e3fb44db1117320913
[ "MIT" ]
1
2019-03-19T06:38:31.000Z
2019-03-19T06:38:31.000Z
index.js
halfnelson/svelte-component-parser
6d75dc48791c25825a0bf7e3fb44db1117320913
[ "MIT" ]
null
null
null
index.js
halfnelson/svelte-component-parser
6d75dc48791c25825a0bf7e3fb44db1117320913
[ "MIT" ]
null
null
null
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); // Reserved word lists for various dialects of the language var reservedWords = { 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", 5: "class enum extends super const export import", 6: "enum", strict: "implements interface let package private protected public static yield", strictBind: "eval arguments" }; // And the keywords var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; var keywords = { 5: ecma5AndLessKeywords, 6: ecma5AndLessKeywords + " const class extends export import super" }; var keywordRelationalOperator = /^in(stanceof)?$/; // ## Character categories // Big ugly regular expressions that match characters in the // whitespace, identifier, and identifier-start categories. These // are only applied when a character is found to actually have a // code point above 128. // Generated by `bin/generate-identifier-regex.js`. var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7b9\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; // These are a run-length and offset encoded representation of the // >0xffff code points that are a valid part of identifiers. The // offset starts at 0x10000, and each pair of numbers represents an // offset to the next range, and then a size of the range. They were // generated by bin/generate-identifier-regex.js // eslint-disable-next-line comma-spacing var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,477,28,11,0,9,21,190,52,76,44,33,24,27,35,30,0,12,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,26,230,43,117,63,32,0,257,0,11,39,8,0,22,0,12,39,3,3,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,270,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,68,12,0,67,12,65,1,31,6129,15,754,9486,286,82,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,15,7472,3104,541]; // eslint-disable-next-line comma-spacing var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,525,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,4,9,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,280,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239]; // This has a complexity linear to the value of the code. The // assumption is that looking up astral identifier characters is // rare. function isInAstralSet(code, set) { var pos = 0x10000; for (var i = 0; i < set.length; i += 2) { pos += set[i]; if (pos > code) { return false } pos += set[i + 1]; if (pos >= code) { return true } } } // Test whether a given character code starts an identifier. function isIdentifierStart(code, astral) { if (code < 65) { return code === 36 } if (code < 91) { return true } if (code < 97) { return code === 95 } if (code < 123) { return true } if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet(code, astralIdentifierStartCodes) } // Test whether a given character is part of an identifier. function isIdentifierChar(code, astral) { if (code < 48) { return code === 36 } if (code < 58) { return true } if (code < 65) { return false } if (code < 91) { return true } if (code < 97) { return code === 95 } if (code < 123) { return true } if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) } // ## Token types // The assignment of fine-grained, information-carrying type objects // allows the tokenizer to store the information it has about a // token in a way that is very cheap for the parser to look up. // All token type variables start with an underscore, to make them // easy to recognize. // The `beforeExpr` property is used to disambiguate between regular // expressions and divisions. It is set on all token types that can // be followed by an expression (thus, a slash after them would be a // regular expression). // // The `startsExpr` property is used to check if the token ends a // `yield` expression. It is set on all token types that either can // directly start an expression (like a quotation mark) or can // continue an expression (like the body of a string). // // `isLoop` marks a keyword as starting a loop, which is important // to know when parsing a label, in order to allow or disallow // continue jumps to that label. var TokenType = function TokenType(label, conf) { if ( conf === void 0 ) conf = {}; this.label = label; this.keyword = conf.keyword; this.beforeExpr = !!conf.beforeExpr; this.startsExpr = !!conf.startsExpr; this.isLoop = !!conf.isLoop; this.isAssign = !!conf.isAssign; this.prefix = !!conf.prefix; this.postfix = !!conf.postfix; this.binop = conf.binop || null; this.updateContext = null; }; function binop(name, prec) { return new TokenType(name, {beforeExpr: true, binop: prec}) } var beforeExpr = {beforeExpr: true}; var startsExpr = {startsExpr: true}; // Map keyword names to token types. var keywords$1 = {}; // Succinct definitions of keyword token types function kw(name, options) { if ( options === void 0 ) options = {}; options.keyword = name; return keywords$1[name] = new TokenType(name, options) } var types = { num: new TokenType("num", startsExpr), regexp: new TokenType("regexp", startsExpr), string: new TokenType("string", startsExpr), name: new TokenType("name", startsExpr), eof: new TokenType("eof"), // Punctuation token types. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), bracketR: new TokenType("]"), braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), braceR: new TokenType("}"), parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), parenR: new TokenType(")"), comma: new TokenType(",", beforeExpr), semi: new TokenType(";", beforeExpr), colon: new TokenType(":", beforeExpr), dot: new TokenType("."), question: new TokenType("?", beforeExpr), arrow: new TokenType("=>", beforeExpr), template: new TokenType("template"), invalidTemplate: new TokenType("invalidTemplate"), ellipsis: new TokenType("...", beforeExpr), backQuote: new TokenType("`", startsExpr), dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), // Operators. These carry several kinds of properties to help the // parser use them properly (the presence of these properties is // what categorizes them as operators). // // `binop`, when present, specifies that this operator is a binary // operator, and will refer to its precedence. // // `prefix` and `postfix` mark the operator as a prefix or postfix // unary operator. // // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as // binary operators with a very low precedence, that should result // in AssignmentExpression nodes. eq: new TokenType("=", {beforeExpr: true, isAssign: true}), assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), logicalOR: binop("||", 1), logicalAND: binop("&&", 2), bitwiseOR: binop("|", 3), bitwiseXOR: binop("^", 4), bitwiseAND: binop("&", 5), equality: binop("==/!=/===/!==", 6), relational: binop("</>/<=/>=", 7), bitShift: binop("<</>>/>>>", 8), plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), modulo: binop("%", 10), star: binop("*", 10), slash: binop("/", 10), starstar: new TokenType("**", {beforeExpr: true}), // Keyword token types. _break: kw("break"), _case: kw("case", beforeExpr), _catch: kw("catch"), _continue: kw("continue"), _debugger: kw("debugger"), _default: kw("default", beforeExpr), _do: kw("do", {isLoop: true, beforeExpr: true}), _else: kw("else", beforeExpr), _finally: kw("finally"), _for: kw("for", {isLoop: true}), _function: kw("function", startsExpr), _if: kw("if"), _return: kw("return", beforeExpr), _switch: kw("switch"), _throw: kw("throw", beforeExpr), _try: kw("try"), _var: kw("var"), _const: kw("const"), _while: kw("while", {isLoop: true}), _with: kw("with"), _new: kw("new", {beforeExpr: true, startsExpr: true}), _this: kw("this", startsExpr), _super: kw("super", startsExpr), _class: kw("class", startsExpr), _extends: kw("extends", beforeExpr), _export: kw("export"), _import: kw("import"), _null: kw("null", startsExpr), _true: kw("true", startsExpr), _false: kw("false", startsExpr), _in: kw("in", {beforeExpr: true, binop: 7}), _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) }; // Matches a whole line break (where CRLF is considered a single // line break). Used to count lines. var lineBreak = /\r\n?|\n|\u2028|\u2029/; var lineBreakG = new RegExp(lineBreak.source, "g"); function isNewLine(code, ecma2019String) { return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029)) } var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; var ref = Object.prototype; var hasOwnProperty = ref.hasOwnProperty; var toString = ref.toString; // Checks if an object has a property. function has(obj, propName) { return hasOwnProperty.call(obj, propName) } var isArray = Array.isArray || (function (obj) { return ( toString.call(obj) === "[object Array]" ); }); function wordsRegexp(words) { return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") } // These are used when `options.locations` is on, for the // `startLoc` and `endLoc` properties. var Position = function Position(line, col) { this.line = line; this.column = col; }; Position.prototype.offset = function offset (n) { return new Position(this.line, this.column + n) }; var SourceLocation = function SourceLocation(p, start, end) { this.start = start; this.end = end; if (p.sourceFile !== null) { this.source = p.sourceFile; } }; // The `getLineInfo` function is mostly useful when the // `locations` option is off (for performance reasons) and you // want to find the line/column position for a given character // offset. `input` should be the code string that the offset refers // into. function getLineInfo(input, offset) { for (var line = 1, cur = 0;;) { lineBreakG.lastIndex = cur; var match = lineBreakG.exec(input); if (match && match.index < offset) { ++line; cur = match.index + match[0].length; } else { return new Position(line, offset - cur) } } } // A second optional argument can be given to further configure // the parser process. These options are recognized: var defaultOptions = { // `ecmaVersion` indicates the ECMAScript version to parse. Must be // either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), or 10 // (2019). This influences support for strict mode, the set of // reserved words, and support for new syntax features. The default // is 9. ecmaVersion: 9, // `sourceType` indicates the mode the code should be parsed in. // Can be either `"script"` or `"module"`. This influences global // strict mode and parsing of `import` and `export` declarations. sourceType: "script", // `onInsertedSemicolon` can be a callback that will be called // when a semicolon is automatically inserted. It will be passed // the position of the comma as an offset, and if `locations` is // enabled, it is given the location as a `{line, column}` object // as second argument. onInsertedSemicolon: null, // `onTrailingComma` is similar to `onInsertedSemicolon`, but for // trailing commas. onTrailingComma: null, // By default, reserved words are only enforced if ecmaVersion >= 5. // Set `allowReserved` to a boolean value to explicitly turn this on // an off. When this option has the value "never", reserved words // and keywords can also not be used as property names. allowReserved: null, // When enabled, a return at the top level is not considered an // error. allowReturnOutsideFunction: false, // When enabled, import/export statements are not constrained to // appearing at the top of the program. allowImportExportEverywhere: false, // When enabled, await identifiers are allowed to appear at the top-level scope, // but they are still not allowed in non-async functions. allowAwaitOutsideFunction: false, // When enabled, hashbang directive in the beginning of file // is allowed and treated as a line comment. allowHashBang: false, // When `locations` is on, `loc` properties holding objects with // `start` and `end` properties in `{line, column}` form (with // line being 1-based and column 0-based) will be attached to the // nodes. locations: false, // A function can be passed as `onToken` option, which will // cause Acorn to call that function with object in the same // format as tokens returned from `tokenizer().getToken()`. Note // that you are not allowed to call the parser from the // callback—that will corrupt its internal state. onToken: null, // A function can be passed as `onComment` option, which will // cause Acorn to call that function with `(block, text, start, // end)` parameters whenever a comment is skipped. `block` is a // boolean indicating whether this is a block (`/* */`) comment, // `text` is the content of the comment, and `start` and `end` are // character offsets that denote the start and end of the comment. // When the `locations` option is on, two more parameters are // passed, the full `{line, column}` locations of the start and // end of the comments. Note that you are not allowed to call the // parser from the callback—that will corrupt its internal state. onComment: null, // Nodes have their start and end characters offsets recorded in // `start` and `end` properties (directly on the node, rather than // the `loc` object, which holds line/column data. To also add a // [semi-standardized][range] `range` property holding a `[start, // end]` array with the same numbers, set the `ranges` option to // `true`. // // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 ranges: false, // It is possible to parse multiple files into a single AST by // passing the tree produced by parsing the first file as // `program` option in subsequent parses. This will add the // toplevel forms of the parsed file to the `Program` (top) node // of an existing parse tree. program: null, // When `locations` is on, you can pass this to record the source // file in every node's `loc` object. sourceFile: null, // This value, if given, is stored in every node, whether // `locations` is on or off. directSourceFile: null, // When enabled, parenthesized expressions are represented by // (non-standard) ParenthesizedExpression nodes preserveParens: false }; // Interpret and default an options object function getOptions(opts) { var options = {}; for (var opt in defaultOptions) { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; } if (options.ecmaVersion >= 2015) { options.ecmaVersion -= 2009; } if (options.allowReserved == null) { options.allowReserved = options.ecmaVersion < 5; } if (isArray(options.onToken)) { var tokens = options.onToken; options.onToken = function (token) { return tokens.push(token); }; } if (isArray(options.onComment)) { options.onComment = pushComment(options, options.onComment); } return options } function pushComment(options, array) { return function(block, text, start, end, startLoc, endLoc) { var comment = { type: block ? "Block" : "Line", value: text, start: start, end: end }; if (options.locations) { comment.loc = new SourceLocation(this, startLoc, endLoc); } if (options.ranges) { comment.range = [start, end]; } array.push(comment); } } // Each scope gets a bitset that may contain these flags var SCOPE_TOP = 1; var SCOPE_FUNCTION = 2; var SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION; var SCOPE_ASYNC = 4; var SCOPE_GENERATOR = 8; var SCOPE_ARROW = 16; var SCOPE_SIMPLE_CATCH = 32; var SCOPE_SUPER = 64; var SCOPE_DIRECT_SUPER = 128; function functionFlags(async, generator) { return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) } // Used in checkLVal and declareName to determine the type of a binding var BIND_NONE = 0; var BIND_VAR = 1; var BIND_LEXICAL = 2; var BIND_FUNCTION = 3; var BIND_SIMPLE_CATCH = 4; var BIND_OUTSIDE = 5; // Special case for function names as bound inside the function var Parser = function Parser(options, input, startPos) { this.options = options = getOptions(options); this.sourceFile = options.sourceFile; this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5]); var reserved = ""; if (!options.allowReserved) { for (var v = options.ecmaVersion;; v--) { if (reserved = reservedWords[v]) { break } } if (options.sourceType === "module") { reserved += " await"; } } this.reservedWords = wordsRegexp(reserved); var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; this.reservedWordsStrict = wordsRegexp(reservedStrict); this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); this.input = String(input); // Used to signal to callers of `readWord1` whether the word // contained any escape sequences. This is needed because words with // escape sequences must not be interpreted as keywords. this.containsEsc = false; // Set up token state // The current position of the tokenizer in the input. if (startPos) { this.pos = startPos; this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; } else { this.pos = this.lineStart = 0; this.curLine = 1; } // Properties of the current token: // Its type this.type = types.eof; // For tokens that include more information than their type, the value this.value = null; // Its start and end offset this.start = this.end = this.pos; // And, if locations are used, the {line, column} object // corresponding to those offsets this.startLoc = this.endLoc = this.curPosition(); // Position information for the previous token this.lastTokEndLoc = this.lastTokStartLoc = null; this.lastTokStart = this.lastTokEnd = this.pos; // The context stack is used to superficially track syntactic // context to predict whether a regular expression is allowed in a // given position. this.context = this.initialContext(); this.exprAllowed = true; // Figure out if it's a module code. this.inModule = options.sourceType === "module"; this.strict = this.inModule || this.strictDirective(this.pos); // Used to signify the start of a potential arrow function this.potentialArrowAt = -1; // Positions to delayed-check that yield/await does not exist in default parameters. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; // Labels in scope. this.labels = []; // Thus-far undefined exports. this.undefinedExports = {}; // If enabled, skip leading hashbang line. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") { this.skipLineComment(2); } // Scope tracking for duplicate variable names (see scope.js) this.scopeStack = []; this.enterScope(SCOPE_TOP); // For RegExp validation this.regexpState = null; }; var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true } }; Parser.prototype.parse = function parse () { var node = this.options.program || this.startNode(); this.nextToken(); return this.parseTopLevel(node) }; prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 }; prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 }; prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 }; prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; // Switch to a getter for 7.0.0. Parser.prototype.inNonArrowFunction = function inNonArrowFunction () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 }; Parser.extend = function extend () { var plugins = [], len = arguments.length; while ( len-- ) plugins[ len ] = arguments[ len ]; var cls = this; for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } return cls }; Parser.parse = function parse (input, options) { return new this(options, input).parse() }; Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { var parser = new this(options, input, pos); parser.nextToken(); return parser.parseExpression() }; Parser.tokenizer = function tokenizer (input, options) { return new this(options, input) }; Object.defineProperties( Parser.prototype, prototypeAccessors ); var pp = Parser.prototype; // ## Parser utilities var literal = /^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)")/; pp.strictDirective = function(start) { var this$1 = this; for (;;) { // Try to find string literal. skipWhiteSpace.lastIndex = start; start += skipWhiteSpace.exec(this$1.input)[0].length; var match = literal.exec(this$1.input.slice(start)); if (!match) { return false } if ((match[1] || match[2]) === "use strict") { return true } start += match[0].length; // Skip semicolon, if any. skipWhiteSpace.lastIndex = start; start += skipWhiteSpace.exec(this$1.input)[0].length; if (this$1.input[start] === ";") { start++; } } }; // Predicate that tests whether the next token is of the given // type, and if yes, consumes it as a side effect. pp.eat = function(type) { if (this.type === type) { this.next(); return true } else { return false } }; // Tests whether parsed token is a contextual keyword. pp.isContextual = function(name) { return this.type === types.name && this.value === name && !this.containsEsc }; // Consumes contextual keyword if possible. pp.eatContextual = function(name) { if (!this.isContextual(name)) { return false } this.next(); return true }; // Asserts that following token is given contextual keyword. pp.expectContextual = function(name) { if (!this.eatContextual(name)) { this.unexpected(); } }; // Test whether a semicolon can be inserted at the current position. pp.canInsertSemicolon = function() { return this.type === types.eof || this.type === types.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }; pp.insertSemicolon = function() { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon) { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } return true } }; // Consume a semicolon, or, failing that, see if we are allowed to // pretend that there is a semicolon at this position. pp.semicolon = function() { if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); } }; pp.afterTrailingComma = function(tokType, notNext) { if (this.type === tokType) { if (this.options.onTrailingComma) { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } if (!notNext) { this.next(); } return true } }; // Expect a token of a given type. If found, consume it, otherwise, // raise an unexpected token error. pp.expect = function(type) { this.eat(type) || this.unexpected(); }; // Raise an unexpected token error. pp.unexpected = function(pos) { this.raise(pos != null ? pos : this.start, "Unexpected token"); }; function DestructuringErrors() { this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1; } pp.checkPatternErrors = function(refDestructuringErrors, isAssign) { if (!refDestructuringErrors) { return } if (refDestructuringErrors.trailingComma > -1) { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); } }; pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { if (!refDestructuringErrors) { return false } var shorthandAssign = refDestructuringErrors.shorthandAssign; var doubleProto = refDestructuringErrors.doubleProto; if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } if (shorthandAssign >= 0) { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } if (doubleProto >= 0) { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } }; pp.checkYieldAwaitInDefaultParams = function() { if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } if (this.awaitPos) { this.raise(this.awaitPos, "Await expression cannot be a default value"); } }; pp.isSimpleAssignTarget = function(expr) { if (expr.type === "ParenthesizedExpression") { return this.isSimpleAssignTarget(expr.expression) } return expr.type === "Identifier" || expr.type === "MemberExpression" }; var pp$1 = Parser.prototype; // ### Statement parsing // Parse a program. Initializes the parser, reads any number of // statements, and wraps them in a Program node. Optionally takes a // `program` argument. If present, the statements will be appended // to its body instead of creating a new node. pp$1.parseTopLevel = function(node) { var this$1 = this; var exports = {}; if (!node.body) { node.body = []; } while (this.type !== types.eof) { var stmt = this$1.parseStatement(null, true, exports); node.body.push(stmt); } if (this.inModule) { for (var i = 0, list = Object.keys(this$1.undefinedExports); i < list.length; i += 1) { var name = list[i]; this$1.raiseRecoverable(this$1.undefinedExports[name].start, ("Export '" + name + "' is not defined")); } } this.adaptDirectivePrologue(node.body); this.next(); if (this.options.ecmaVersion >= 6) { node.sourceType = this.options.sourceType; } return this.finishNode(node, "Program") }; var loopLabel = {kind: "loop"}; var switchLabel = {kind: "switch"}; pp$1.isLet = function(context) { if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } skipWhiteSpace.lastIndex = this.pos; var skip = skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); // For ambiguous cases, determine if a LexicalDeclaration (or only a // Statement) is allowed here. If context is not empty then only a Statement // is allowed. However, `let [` is an explicit negative lookahead for // ExpressionStatement, so special-case it first. if (nextCh === 91) { return true } // '[' if (context) { return false } if (nextCh === 123) { return true } // '{' if (isIdentifierStart(nextCh, true)) { var pos = next + 1; while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; } var ident = this.input.slice(next, pos); if (!keywordRelationalOperator.test(ident)) { return true } } return false }; // check 'async [no LineTerminator here] function' // - 'async /*foo*/ function' is OK. // - 'async /*\n*/ function' is invalid. pp$1.isAsyncFunction = function() { if (this.options.ecmaVersion < 8 || !this.isContextual("async")) { return false } skipWhiteSpace.lastIndex = this.pos; var skip = skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length; return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8))) }; // Parse a single statement. // // If expecting a statement and finding a slash operator, parse a // regular expression literal. This is to handle cases like // `if (foo) /blah/.exec(foo)`, where looking at the previous token // does not help. pp$1.parseStatement = function(context, topLevel, exports) { var starttype = this.type, node = this.startNode(), kind; if (this.isLet(context)) { starttype = types._var; kind = "let"; } // Most types of statements are recognized by the keyword they // start with. Many are trivial to parse, some require a bit of // complexity. switch (starttype) { case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword) case types._debugger: return this.parseDebuggerStatement(node) case types._do: return this.parseDoStatement(node) case types._for: return this.parseForStatement(node) case types._function: // Function as sole body of either an if statement or a labeled statement // works, but not when it is part of a labeled statement that is the sole // body of an if statement. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } return this.parseFunctionStatement(node, false, !context) case types._class: if (context) { this.unexpected(); } return this.parseClass(node, true) case types._if: return this.parseIfStatement(node) case types._return: return this.parseReturnStatement(node) case types._switch: return this.parseSwitchStatement(node) case types._throw: return this.parseThrowStatement(node) case types._try: return this.parseTryStatement(node) case types._const: case types._var: kind = kind || this.value; if (context && kind !== "var") { this.unexpected(); } return this.parseVarStatement(node, kind) case types._while: return this.parseWhileStatement(node) case types._with: return this.parseWithStatement(node) case types.braceL: return this.parseBlock(true, node) case types.semi: return this.parseEmptyStatement(node) case types._export: case types._import: if (!this.options.allowImportExportEverywhere) { if (!topLevel) { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } if (!this.inModule) { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } } return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports) // If the statement does not start with a statement keyword or a // brace, it's an ExpressionStatement or LabeledStatement. We // simply start parsing an expression, and afterwards, if the // next token is a colon and the expression was a simple // Identifier node, we switch to interpreting it as a label. default: if (this.isAsyncFunction()) { if (context) { this.unexpected(); } this.next(); return this.parseFunctionStatement(node, true, !context) } var maybeName = this.value, expr = this.parseExpression(); if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) { return this.parseLabeledStatement(node, maybeName, expr, context) } else { return this.parseExpressionStatement(node, expr) } } }; pp$1.parseBreakContinueStatement = function(node, keyword) { var this$1 = this; var isBreak = keyword === "break"; this.next(); if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; } else if (this.type !== types.name) { this.unexpected(); } else { node.label = this.parseIdent(); this.semicolon(); } // Verify that there is an actual destination to break or // continue to. var i = 0; for (; i < this.labels.length; ++i) { var lab = this$1.labels[i]; if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } if (node.label && isBreak) { break } } } if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") }; pp$1.parseDebuggerStatement = function(node) { this.next(); this.semicolon(); return this.finishNode(node, "DebuggerStatement") }; pp$1.parseDoStatement = function(node) { this.next(); this.labels.push(loopLabel); node.body = this.parseStatement("do"); this.labels.pop(); this.expect(types._while); node.test = this.parseParenExpression(); if (this.options.ecmaVersion >= 6) { this.eat(types.semi); } else { this.semicolon(); } return this.finishNode(node, "DoWhileStatement") }; // Disambiguating between a `for` and a `for`/`in` or `for`/`of` // loop is non-trivial. Basically, we have to parse the init `var` // statement or expression, disallowing the `in` operator (see // the second parameter to `parseExpression`), and then check // whether the next token is `in` or `of`. When there is no init // part (semicolon immediately after the opening parenthesis), it // is a regular `for` loop. pp$1.parseForStatement = function(node) { this.next(); var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1; this.labels.push(loopLabel); this.enterScope(0); this.expect(types.parenL); if (this.type === types.semi) { if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, null) } var isLet = this.isLet(); if (this.type === types._var || this.type === types._const || isLet) { var init$1 = this.startNode(), kind = isLet ? "let" : this.value; this.next(); this.parseVar(init$1, true, kind); this.finishNode(init$1, "VariableDeclaration"); if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1 && !(kind !== "var" && init$1.declarations[0].init)) { if (this.options.ecmaVersion >= 9) { if (this.type === types._in) { if (awaitAt > -1) { this.unexpected(awaitAt); } } else { node.await = awaitAt > -1; } } return this.parseForIn(node, init$1) } if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, init$1) } var refDestructuringErrors = new DestructuringErrors; var init = this.parseExpression(true, refDestructuringErrors); if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) { if (this.options.ecmaVersion >= 9) { if (this.type === types._in) { if (awaitAt > -1) { this.unexpected(awaitAt); } } else { node.await = awaitAt > -1; } } this.toAssignable(init, false, refDestructuringErrors); this.checkLVal(init); return this.parseForIn(node, init) } else { this.checkExpressionErrors(refDestructuringErrors, true); } if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, init) }; pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) { this.next(); return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) }; pp$1.parseIfStatement = function(node) { this.next(); node.test = this.parseParenExpression(); // allow function declarations in branches, but only in non-strict mode node.consequent = this.parseStatement("if"); node.alternate = this.eat(types._else) ? this.parseStatement("if") : null; return this.finishNode(node, "IfStatement") }; pp$1.parseReturnStatement = function(node) { if (!this.inFunction && !this.options.allowReturnOutsideFunction) { this.raise(this.start, "'return' outside of function"); } this.next(); // In `return` (and `break`/`continue`), the keywords with // optional arguments, we eagerly look for a semicolon or the // possibility to insert one. if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; } else { node.argument = this.parseExpression(); this.semicolon(); } return this.finishNode(node, "ReturnStatement") }; pp$1.parseSwitchStatement = function(node) { var this$1 = this; this.next(); node.discriminant = this.parseParenExpression(); node.cases = []; this.expect(types.braceL); this.labels.push(switchLabel); this.enterScope(0); // Statements under must be grouped (by label) in SwitchCase // nodes. `cur` is used to keep the node that we are currently // adding statements to. var cur; for (var sawDefault = false; this.type !== types.braceR;) { if (this$1.type === types._case || this$1.type === types._default) { var isCase = this$1.type === types._case; if (cur) { this$1.finishNode(cur, "SwitchCase"); } node.cases.push(cur = this$1.startNode()); cur.consequent = []; this$1.next(); if (isCase) { cur.test = this$1.parseExpression(); } else { if (sawDefault) { this$1.raiseRecoverable(this$1.lastTokStart, "Multiple default clauses"); } sawDefault = true; cur.test = null; } this$1.expect(types.colon); } else { if (!cur) { this$1.unexpected(); } cur.consequent.push(this$1.parseStatement(null)); } } this.exitScope(); if (cur) { this.finishNode(cur, "SwitchCase"); } this.next(); // Closing brace this.labels.pop(); return this.finishNode(node, "SwitchStatement") }; pp$1.parseThrowStatement = function(node) { this.next(); if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) { this.raise(this.lastTokEnd, "Illegal newline after throw"); } node.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node, "ThrowStatement") }; // Reused empty array added for node fields that are always empty. var empty = []; pp$1.parseTryStatement = function(node) { this.next(); node.block = this.parseBlock(); node.handler = null; if (this.type === types._catch) { var clause = this.startNode(); this.next(); if (this.eat(types.parenL)) { clause.param = this.parseBindingAtom(); var simple = clause.param.type === "Identifier"; this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); this.checkLVal(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); this.expect(types.parenR); } else { if (this.options.ecmaVersion < 10) { this.unexpected(); } clause.param = null; this.enterScope(0); } clause.body = this.parseBlock(false); this.exitScope(); node.handler = this.finishNode(clause, "CatchClause"); } node.finalizer = this.eat(types._finally) ? this.parseBlock() : null; if (!node.handler && !node.finalizer) { this.raise(node.start, "Missing catch or finally clause"); } return this.finishNode(node, "TryStatement") }; pp$1.parseVarStatement = function(node, kind) { this.next(); this.parseVar(node, false, kind); this.semicolon(); return this.finishNode(node, "VariableDeclaration") }; pp$1.parseWhileStatement = function(node) { this.next(); node.test = this.parseParenExpression(); this.labels.push(loopLabel); node.body = this.parseStatement("while"); this.labels.pop(); return this.finishNode(node, "WhileStatement") }; pp$1.parseWithStatement = function(node) { if (this.strict) { this.raise(this.start, "'with' in strict mode"); } this.next(); node.object = this.parseParenExpression(); node.body = this.parseStatement("with"); return this.finishNode(node, "WithStatement") }; pp$1.parseEmptyStatement = function(node) { this.next(); return this.finishNode(node, "EmptyStatement") }; pp$1.parseLabeledStatement = function(node, maybeName, expr, context) { var this$1 = this; for (var i$1 = 0, list = this$1.labels; i$1 < list.length; i$1 += 1) { var label = list[i$1]; if (label.name === maybeName) { this$1.raise(expr.start, "Label '" + maybeName + "' is already declared"); } } var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null; for (var i = this.labels.length - 1; i >= 0; i--) { var label$1 = this$1.labels[i]; if (label$1.statementStart === node.start) { // Update information about previous labels on this node label$1.statementStart = this$1.start; label$1.kind = kind; } else { break } } this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); this.labels.pop(); node.label = expr; return this.finishNode(node, "LabeledStatement") }; pp$1.parseExpressionStatement = function(node, expr) { node.expression = expr; this.semicolon(); return this.finishNode(node, "ExpressionStatement") }; // Parse a semicolon-enclosed block of statements, handling `"use // strict"` declarations when `allowStrict` is true (used for // function bodies). pp$1.parseBlock = function(createNewLexicalScope, node) { var this$1 = this; if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; if ( node === void 0 ) node = this.startNode(); node.body = []; this.expect(types.braceL); if (createNewLexicalScope) { this.enterScope(0); } while (!this.eat(types.braceR)) { var stmt = this$1.parseStatement(null); node.body.push(stmt); } if (createNewLexicalScope) { this.exitScope(); } return this.finishNode(node, "BlockStatement") }; // Parse a regular `for` loop. The disambiguation code in // `parseStatement` will already have parsed the init statement or // expression. pp$1.parseFor = function(node, init) { node.init = init; this.expect(types.semi); node.test = this.type === types.semi ? null : this.parseExpression(); this.expect(types.semi); node.update = this.type === types.parenR ? null : this.parseExpression(); this.expect(types.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, "ForStatement") }; // Parse a `for`/`in` and `for`/`of` loop, which are almost // same from parser's perspective. pp$1.parseForIn = function(node, init) { var type = this.type === types._in ? "ForInStatement" : "ForOfStatement"; this.next(); if (type === "ForInStatement") { if (init.type === "AssignmentPattern" || (init.type === "VariableDeclaration" && init.declarations[0].init != null && (this.strict || init.declarations[0].id.type !== "Identifier"))) { this.raise(init.start, "Invalid assignment in for-in loop head"); } } node.left = init; node.right = type === "ForInStatement" ? this.parseExpression() : this.parseMaybeAssign(); this.expect(types.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, type) }; // Parse a list of variable declarations. pp$1.parseVar = function(node, isFor, kind) { var this$1 = this; node.declarations = []; node.kind = kind; for (;;) { var decl = this$1.startNode(); this$1.parseVarId(decl, kind); if (this$1.eat(types.eq)) { decl.init = this$1.parseMaybeAssign(isFor); } else if (kind === "const" && !(this$1.type === types._in || (this$1.options.ecmaVersion >= 6 && this$1.isContextual("of")))) { this$1.unexpected(); } else if (decl.id.type !== "Identifier" && !(isFor && (this$1.type === types._in || this$1.isContextual("of")))) { this$1.raise(this$1.lastTokEnd, "Complex binding patterns require an initialization value"); } else { decl.init = null; } node.declarations.push(this$1.finishNode(decl, "VariableDeclarator")); if (!this$1.eat(types.comma)) { break } } return node }; pp$1.parseVarId = function(decl, kind) { if ((kind === "const" || kind === "let") && this.isContextual("let")) { this.raiseRecoverable(this.start, "let is disallowed as a lexically bound name"); } decl.id = this.parseBindingAtom(); this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); }; var FUNC_STATEMENT = 1; var FUNC_HANGING_STATEMENT = 2; var FUNC_NULLABLE_ID = 4; // Parse a function declaration or literal (depending on the // `statement & FUNC_STATEMENT`). // Remove `allowExpressionBody` for 7.0.0, as it is only called with false pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) { this.initFunction(node); if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT)) { this.unexpected(); } node.generator = this.eat(types.star); } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } if (statement & FUNC_STATEMENT) { node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent(); if (node.id && !(statement & FUNC_HANGING_STATEMENT)) // If it is a regular function declaration in sloppy mode, then it is // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding // mode depends on properties of the current scope (see // treatFunctionsAsVar). { this.checkLVal(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } } var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope(functionFlags(node.async, node.generator)); if (!(statement & FUNC_STATEMENT)) { node.id = this.type === types.name ? this.parseIdent() : null; } this.parseFunctionParams(node); this.parseFunctionBody(node, allowExpressionBody, false); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") }; pp$1.parseFunctionParams = function(node) { this.expect(types.parenL); node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); }; // Parse a class declaration or literal (depending on the // `isStatement` parameter). pp$1.parseClass = function(node, isStatement) { var this$1 = this; this.next(); // ecma-262 14.6 Class Definitions // A class definition is always strict mode code. var oldStrict = this.strict; this.strict = true; this.parseClassId(node, isStatement); this.parseClassSuper(node); var classBody = this.startNode(); var hadConstructor = false; classBody.body = []; this.expect(types.braceL); while (!this.eat(types.braceR)) { var element = this$1.parseClassElement(node.superClass !== null); if (element) { classBody.body.push(element); if (element.type === "MethodDefinition" && element.kind === "constructor") { if (hadConstructor) { this$1.raise(element.start, "Duplicate constructor in the same class"); } hadConstructor = true; } } } node.body = this.finishNode(classBody, "ClassBody"); this.strict = oldStrict; return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") }; pp$1.parseClassElement = function(constructorAllowsSuper) { var this$1 = this; if (this.eat(types.semi)) { return null } var method = this.startNode(); var tryContextual = function (k, noLineBreak) { if ( noLineBreak === void 0 ) noLineBreak = false; var start = this$1.start, startLoc = this$1.startLoc; if (!this$1.eatContextual(k)) { return false } if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true } if (method.key) { this$1.unexpected(); } method.computed = false; method.key = this$1.startNodeAt(start, startLoc); method.key.name = k; this$1.finishNode(method.key, "Identifier"); return false }; method.kind = "method"; method.static = tryContextual("static"); var isGenerator = this.eat(types.star); var isAsync = false; if (!isGenerator) { if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) { isAsync = true; isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); } else if (tryContextual("get")) { method.kind = "get"; } else if (tryContextual("set")) { method.kind = "set"; } } if (!method.key) { this.parsePropertyName(method); } var key = method.key; var allowsDirectSuper = false; if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" || key.type === "Literal" && key.value === "constructor")) { if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); } if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } method.kind = "constructor"; allowsDirectSuper = constructorAllowsSuper; } else if (method.static && key.type === "Identifier" && key.name === "prototype") { this.raise(key.start, "Classes may not have a static property named prototype"); } this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper); if (method.kind === "get" && method.value.params.length !== 0) { this.raiseRecoverable(method.value.start, "getter should have no params"); } if (method.kind === "set" && method.value.params.length !== 1) { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); } if (method.kind === "set" && method.value.params[0].type === "RestElement") { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); } return method }; pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); return this.finishNode(method, "MethodDefinition") }; pp$1.parseClassId = function(node, isStatement) { if (this.type === types.name) { node.id = this.parseIdent(); if (isStatement) { this.checkLVal(node.id, BIND_LEXICAL, false); } } else { if (isStatement === true) { this.unexpected(); } node.id = null; } }; pp$1.parseClassSuper = function(node) { node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null; }; // Parses module export declaration. pp$1.parseExport = function(node, exports) { var this$1 = this; this.next(); // export * from '...' if (this.eat(types.star)) { this.expectContextual("from"); if (this.type !== types.string) { this.unexpected(); } node.source = this.parseExprAtom(); this.semicolon(); return this.finishNode(node, "ExportAllDeclaration") } if (this.eat(types._default)) { // export default ... this.checkExport(exports, "default", this.lastTokStart); var isAsync; if (this.type === types._function || (isAsync = this.isAsyncFunction())) { var fNode = this.startNode(); this.next(); if (isAsync) { this.next(); } node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); } else if (this.type === types._class) { var cNode = this.startNode(); node.declaration = this.parseClass(cNode, "nullableID"); } else { node.declaration = this.parseMaybeAssign(); this.semicolon(); } return this.finishNode(node, "ExportDefaultDeclaration") } // export var|const|let|function|class ... if (this.shouldParseExportStatement()) { node.declaration = this.parseStatement(null); if (node.declaration.type === "VariableDeclaration") { this.checkVariableExport(exports, node.declaration.declarations); } else { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); } node.specifiers = []; node.source = null; } else { // export { x, y as z } [from '...'] node.declaration = null; node.specifiers = this.parseExportSpecifiers(exports); if (this.eatContextual("from")) { if (this.type !== types.string) { this.unexpected(); } node.source = this.parseExprAtom(); } else { for (var i = 0, list = node.specifiers; i < list.length; i += 1) { // check for keywords used as local names var spec = list[i]; this$1.checkUnreserved(spec.local); // check if export is defined this$1.checkLocalExport(spec.local); } node.source = null; } this.semicolon(); } return this.finishNode(node, "ExportNamedDeclaration") }; pp$1.checkExport = function(exports, name, pos) { if (!exports) { return } if (has(exports, name)) { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } exports[name] = true; }; pp$1.checkPatternExport = function(exports, pat) { var this$1 = this; var type = pat.type; if (type === "Identifier") { this.checkExport(exports, pat.name, pat.start); } else if (type === "ObjectPattern") { for (var i = 0, list = pat.properties; i < list.length; i += 1) { var prop = list[i]; this$1.checkPatternExport(exports, prop); } } else if (type === "ArrayPattern") { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { var elt = list$1[i$1]; if (elt) { this$1.checkPatternExport(exports, elt); } } } else if (type === "Property") { this.checkPatternExport(exports, pat.value); } else if (type === "AssignmentPattern") { this.checkPatternExport(exports, pat.left); } else if (type === "RestElement") { this.checkPatternExport(exports, pat.argument); } else if (type === "ParenthesizedExpression") { this.checkPatternExport(exports, pat.expression); } }; pp$1.checkVariableExport = function(exports, decls) { var this$1 = this; if (!exports) { return } for (var i = 0, list = decls; i < list.length; i += 1) { var decl = list[i]; this$1.checkPatternExport(exports, decl.id); } }; pp$1.shouldParseExportStatement = function() { return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction() }; // Parses a comma-separated list of module exports. pp$1.parseExportSpecifiers = function(exports) { var this$1 = this; var nodes = [], first = true; // export { x, y as z } [from '...'] this.expect(types.braceL); while (!this.eat(types.braceR)) { if (!first) { this$1.expect(types.comma); if (this$1.afterTrailingComma(types.braceR)) { break } } else { first = false; } var node = this$1.startNode(); node.local = this$1.parseIdent(true); node.exported = this$1.eatContextual("as") ? this$1.parseIdent(true) : node.local; this$1.checkExport(exports, node.exported.name, node.exported.start); nodes.push(this$1.finishNode(node, "ExportSpecifier")); } return nodes }; // Parses import declaration. pp$1.parseImport = function(node) { this.next(); // import '...' if (this.type === types.string) { node.specifiers = empty; node.source = this.parseExprAtom(); } else { node.specifiers = this.parseImportSpecifiers(); this.expectContextual("from"); node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected(); } this.semicolon(); return this.finishNode(node, "ImportDeclaration") }; // Parses a comma-separated list of module imports. pp$1.parseImportSpecifiers = function() { var this$1 = this; var nodes = [], first = true; if (this.type === types.name) { // import defaultObj, { x, y as z } from '...' var node = this.startNode(); node.local = this.parseIdent(); this.checkLVal(node.local, BIND_LEXICAL); nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); if (!this.eat(types.comma)) { return nodes } } if (this.type === types.star) { var node$1 = this.startNode(); this.next(); this.expectContextual("as"); node$1.local = this.parseIdent(); this.checkLVal(node$1.local, BIND_LEXICAL); nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); return nodes } this.expect(types.braceL); while (!this.eat(types.braceR)) { if (!first) { this$1.expect(types.comma); if (this$1.afterTrailingComma(types.braceR)) { break } } else { first = false; } var node$2 = this$1.startNode(); node$2.imported = this$1.parseIdent(true); if (this$1.eatContextual("as")) { node$2.local = this$1.parseIdent(); } else { this$1.checkUnreserved(node$2.imported); node$2.local = node$2.imported; } this$1.checkLVal(node$2.local, BIND_LEXICAL); nodes.push(this$1.finishNode(node$2, "ImportSpecifier")); } return nodes }; // Set `ExpressionStatement#directive` property for directive prologues. pp$1.adaptDirectivePrologue = function(statements) { for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { statements[i].directive = statements[i].expression.raw.slice(1, -1); } }; pp$1.isDirectiveCandidate = function(statement) { return ( statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && // Reject parenthesized strings. (this.input[statement.start] === "\"" || this.input[statement.start] === "'") ) }; var pp$2 = Parser.prototype; // Convert existing expression atom to assignable pattern // if possible. pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) { var this$1 = this; if (this.options.ecmaVersion >= 6 && node) { switch (node.type) { case "Identifier": if (this.inAsync && node.name === "await") { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } break case "ObjectPattern": case "ArrayPattern": case "RestElement": break case "ObjectExpression": node.type = "ObjectPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } for (var i = 0, list = node.properties; i < list.length; i += 1) { var prop = list[i]; this$1.toAssignable(prop, isBinding); // Early error: // AssignmentRestProperty[Yield, Await] : // `...` DestructuringAssignmentTarget[Yield, Await] // // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. if ( prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") ) { this$1.raise(prop.argument.start, "Unexpected token"); } } break case "Property": // AssignmentProperty has type === "Property" if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } this.toAssignable(node.value, isBinding); break case "ArrayExpression": node.type = "ArrayPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } this.toAssignableList(node.elements, isBinding); break case "SpreadElement": node.type = "RestElement"; this.toAssignable(node.argument, isBinding); if (node.argument.type === "AssignmentPattern") { this.raise(node.argument.start, "Rest elements cannot have a default value"); } break case "AssignmentExpression": if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } node.type = "AssignmentPattern"; delete node.operator; this.toAssignable(node.left, isBinding); // falls through to AssignmentPattern case "AssignmentPattern": break case "ParenthesizedExpression": this.toAssignable(node.expression, isBinding, refDestructuringErrors); break case "MemberExpression": if (!isBinding) { break } default: this.raise(node.start, "Assigning to rvalue"); } } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } return node }; // Convert list of expression atoms to binding list. pp$2.toAssignableList = function(exprList, isBinding) { var this$1 = this; var end = exprList.length; for (var i = 0; i < end; i++) { var elt = exprList[i]; if (elt) { this$1.toAssignable(elt, isBinding); } } if (end) { var last = exprList[end - 1]; if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") { this.unexpected(last.argument.start); } } return exprList }; // Parses spread element. pp$2.parseSpread = function(refDestructuringErrors) { var node = this.startNode(); this.next(); node.argument = this.parseMaybeAssign(false, refDestructuringErrors); return this.finishNode(node, "SpreadElement") }; pp$2.parseRestBinding = function() { var node = this.startNode(); this.next(); // RestElement inside of a function parameter must be an identifier if (this.options.ecmaVersion === 6 && this.type !== types.name) { this.unexpected(); } node.argument = this.parseBindingAtom(); return this.finishNode(node, "RestElement") }; // Parses lvalue (assignable) atom. pp$2.parseBindingAtom = function() { if (this.options.ecmaVersion >= 6) { switch (this.type) { case types.bracketL: var node = this.startNode(); this.next(); node.elements = this.parseBindingList(types.bracketR, true, true); return this.finishNode(node, "ArrayPattern") case types.braceL: return this.parseObj(true) } } return this.parseIdent() }; pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) { var this$1 = this; var elts = [], first = true; while (!this.eat(close)) { if (first) { first = false; } else { this$1.expect(types.comma); } if (allowEmpty && this$1.type === types.comma) { elts.push(null); } else if (allowTrailingComma && this$1.afterTrailingComma(close)) { break } else if (this$1.type === types.ellipsis) { var rest = this$1.parseRestBinding(); this$1.parseBindingListItem(rest); elts.push(rest); if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element"); } this$1.expect(close); break } else { var elem = this$1.parseMaybeDefault(this$1.start, this$1.startLoc); this$1.parseBindingListItem(elem); elts.push(elem); } } return elts }; pp$2.parseBindingListItem = function(param) { return param }; // Parses assignment pattern around given atom if possible. pp$2.parseMaybeDefault = function(startPos, startLoc, left) { left = left || this.parseBindingAtom(); if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left } var node = this.startNodeAt(startPos, startLoc); node.left = left; node.right = this.parseMaybeAssign(); return this.finishNode(node, "AssignmentPattern") }; // Verify that a node is an lval — something that can be assigned // to. // bindingType can be either: // 'var' indicating that the lval creates a 'var' binding // 'let' indicating that the lval creates a lexical ('let' or 'const') binding // 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references pp$2.checkLVal = function(expr, bindingType, checkClashes) { var this$1 = this; if ( bindingType === void 0 ) bindingType = BIND_NONE; switch (expr.type) { case "Identifier": if (this.strict && this.reservedWordsStrictBind.test(expr.name)) { this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } if (checkClashes) { if (has(checkClashes, expr.name)) { this.raiseRecoverable(expr.start, "Argument name clash"); } checkClashes[expr.name] = true; } if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } break case "MemberExpression": if (bindingType) { this.raiseRecoverable(expr.start, "Binding member expression"); } break case "ObjectPattern": for (var i = 0, list = expr.properties; i < list.length; i += 1) { var prop = list[i]; this$1.checkLVal(prop, bindingType, checkClashes); } break case "Property": // AssignmentProperty has type === "Property" this.checkLVal(expr.value, bindingType, checkClashes); break case "ArrayPattern": for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { var elem = list$1[i$1]; if (elem) { this$1.checkLVal(elem, bindingType, checkClashes); } } break case "AssignmentPattern": this.checkLVal(expr.left, bindingType, checkClashes); break case "RestElement": this.checkLVal(expr.argument, bindingType, checkClashes); break case "ParenthesizedExpression": this.checkLVal(expr.expression, bindingType, checkClashes); break default: this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue"); } }; // A recursive descent parser operates by defining functions for all // syntactic elements, and recursively calling those, each function // advancing the input stream and returning an AST node. Precedence // of constructs (for example, the fact that `!x[1]` means `!(x[1])` // instead of `(!x)[1]` is handled by the fact that the parser // function that parses unary prefix operators is called first, and // in turn calls the function that parses `[]` subscripts — that // way, it'll receive the node for `x[1]` already parsed, and wraps // *that* in the unary operator node. // // Acorn uses an [operator precedence parser][opp] to handle binary // operator precedence, because it is much more compact than using // the technique outlined above, which uses different, nesting // functions to specify precedence, for all of the ten binary // precedence levels that JavaScript defines. // // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser var pp$3 = Parser.prototype; // Check if property name clashes with already added. // Object/class getters and setters are not allowed to clash — // either with each other or with an init property — and in // strict mode, init properties are also not allowed to be repeated. pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) { if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") { return } if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) { return } var key = prop.key; var name; switch (key.type) { case "Identifier": name = key.name; break case "Literal": name = String(key.value); break default: return } var kind = prop.kind; if (this.options.ecmaVersion >= 6) { if (name === "__proto__" && kind === "init") { if (propHash.proto) { if (refDestructuringErrors && refDestructuringErrors.doubleProto < 0) { refDestructuringErrors.doubleProto = key.start; } // Backwards-compat kludge. Can be removed in version 6.0 else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } } propHash.proto = true; } return } name = "$" + name; var other = propHash[name]; if (other) { var redefinition; if (kind === "init") { redefinition = this.strict && other.init || other.get || other.set; } else { redefinition = other.init || other[kind]; } if (redefinition) { this.raiseRecoverable(key.start, "Redefinition of property"); } } else { other = propHash[name] = { init: false, get: false, set: false }; } other[kind] = true; }; // ### Expression parsing // These nest, from the most general expression type at the top to // 'atomic', nondivisible expression types at the bottom. Most of // the functions will simply let the function(s) below them parse, // and, *if* the syntactic construct they handle is present, wrap // the AST node that the inner parser gave them in another node. // Parse a full expression. The optional arguments are used to // forbid the `in` operator (in for loops initalization expressions) // and provide reference for storing '=' operator inside shorthand // property assignment in contexts where both object expression // and object pattern might appear (so it's possible to raise // delayed syntax error at correct position). pp$3.parseExpression = function(noIn, refDestructuringErrors) { var this$1 = this; var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeAssign(noIn, refDestructuringErrors); if (this.type === types.comma) { var node = this.startNodeAt(startPos, startLoc); node.expressions = [expr]; while (this.eat(types.comma)) { node.expressions.push(this$1.parseMaybeAssign(noIn, refDestructuringErrors)); } return this.finishNode(node, "SequenceExpression") } return expr }; // Parse an assignment expression. This includes applications of // operators like `+=`. pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) { if (this.isContextual("yield")) { if (this.inGenerator) { return this.parseYield(noIn) } // The tokenizer will assume an expression is allowed after // `yield`, but this isn't that kind of yield else { this.exprAllowed = false; } } var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldShorthandAssign = -1; if (refDestructuringErrors) { oldParenAssign = refDestructuringErrors.parenthesizedAssign; oldTrailingComma = refDestructuringErrors.trailingComma; oldShorthandAssign = refDestructuringErrors.shorthandAssign; refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.shorthandAssign = -1; } else { refDestructuringErrors = new DestructuringErrors; ownDestructuringErrors = true; } var startPos = this.start, startLoc = this.startLoc; if (this.type === types.parenL || this.type === types.name) { this.potentialArrowAt = this.start; } var left = this.parseMaybeConditional(noIn, refDestructuringErrors); if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } if (this.type.isAssign) { var node = this.startNodeAt(startPos, startLoc); node.operator = this.value; node.left = this.type === types.eq ? this.toAssignable(left, false, refDestructuringErrors) : left; if (!ownDestructuringErrors) { DestructuringErrors.call(refDestructuringErrors); } refDestructuringErrors.shorthandAssign = -1; // reset because shorthand default was used correctly this.checkLVal(left); this.next(); node.right = this.parseMaybeAssign(noIn); return this.finishNode(node, "AssignmentExpression") } else { if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } } if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } if (oldShorthandAssign > -1) { refDestructuringErrors.shorthandAssign = oldShorthandAssign; } return left }; // Parse a ternary conditional (`?:`) operator. pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprOps(noIn, refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } if (this.eat(types.question)) { var node = this.startNodeAt(startPos, startLoc); node.test = expr; node.consequent = this.parseMaybeAssign(); this.expect(types.colon); node.alternate = this.parseMaybeAssign(noIn); return this.finishNode(node, "ConditionalExpression") } return expr }; // Start the precedence parser. pp$3.parseExprOps = function(noIn, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeUnary(refDestructuringErrors, false); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn) }; // Parse binary operators with the operator precedence parsing // algorithm. `left` is the left-hand side of the operator. // `minPrec` provides context that allows the function to stop and // defer further parser to one of its callers when it encounters an // operator that has a lower precedence than the set it is parsing. pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) { var prec = this.type.binop; if (prec != null && (!noIn || this.type !== types._in)) { if (prec > minPrec) { var logical = this.type === types.logicalOR || this.type === types.logicalAND; var op = this.value; this.next(); var startPos = this.start, startLoc = this.startLoc; var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn); var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical); return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn) } } return left }; pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) { var node = this.startNodeAt(startPos, startLoc); node.left = left; node.operator = op; node.right = right; return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") }; // Parse unary operators, both prefix and postfix. pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) { var this$1 = this; var startPos = this.start, startLoc = this.startLoc, expr; if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) { expr = this.parseAwait(); sawUnary = true; } else if (this.type.prefix) { var node = this.startNode(), update = this.type === types.incDec; node.operator = this.value; node.prefix = true; this.next(); node.argument = this.parseMaybeUnary(null, true); this.checkExpressionErrors(refDestructuringErrors, true); if (update) { this.checkLVal(node.argument); } else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } else { sawUnary = true; } expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); } else { expr = this.parseExprSubscripts(refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } while (this.type.postfix && !this.canInsertSemicolon()) { var node$1 = this$1.startNodeAt(startPos, startLoc); node$1.operator = this$1.value; node$1.prefix = false; node$1.argument = expr; this$1.checkLVal(expr); this$1.next(); expr = this$1.finishNode(node$1, "UpdateExpression"); } } if (!sawUnary && this.eat(types.starstar)) { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) } else { return expr } }; // Parse call, dot, and `[]`-subscript expressions. pp$3.parseExprSubscripts = function(refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprAtom(refDestructuringErrors); var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")"; if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) { return expr } var result = this.parseSubscripts(expr, startPos, startLoc); if (refDestructuringErrors && result.type === "MemberExpression") { if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } } return result }; pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { var this$1 = this; var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && this.input.slice(base.start, base.end) === "async"; while (true) { var element = this$1.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow); if (element === base || element.type === "ArrowFunctionExpression") { return element } base = element; } }; pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow) { var computed = this.eat(types.bracketL); if (computed || this.eat(types.dot)) { var node = this.startNodeAt(startPos, startLoc); node.object = base; node.property = computed ? this.parseExpression() : this.parseIdent(true); node.computed = !!computed; if (computed) { this.expect(types.bracketR); } base = this.finishNode(node, "MemberExpression"); } else if (!noCalls && this.eat(types.parenL)) { var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); if (maybeAsyncArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) { this.checkPatternErrors(refDestructuringErrors, false); this.checkYieldAwaitInDefaultParams(); if (this.awaitIdentPos > 0) { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true) } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; var node$1 = this.startNodeAt(startPos, startLoc); node$1.callee = base; node$1.arguments = exprList; base = this.finishNode(node$1, "CallExpression"); } else if (this.type === types.backQuote) { var node$2 = this.startNodeAt(startPos, startLoc); node$2.tag = base; node$2.quasi = this.parseTemplate({isTagged: true}); base = this.finishNode(node$2, "TaggedTemplateExpression"); } return base }; // Parse an atomic expression — either a single token that is an // expression, an expression started by a keyword like `function` or // `new`, or an expression wrapped in punctuation like `()`, `[]`, // or `{}`. pp$3.parseExprAtom = function(refDestructuringErrors) { // If a division operator appears in an expression position, the // tokenizer got confused, and we force it to read a regexp instead. if (this.type === types.slash) { this.readRegexp(); } var node, canBeArrow = this.potentialArrowAt === this.start; switch (this.type) { case types._super: if (!this.allowSuper) { this.raise(this.start, "'super' keyword outside a method"); } node = this.startNode(); this.next(); if (this.type === types.parenL && !this.allowDirectSuper) { this.raise(node.start, "super() call outside constructor of a subclass"); } // The `super` keyword can appear at below: // SuperProperty: // super [ Expression ] // super . IdentifierName // SuperCall: // super Arguments if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL) { this.unexpected(); } return this.finishNode(node, "Super") case types._this: node = this.startNode(); this.next(); return this.finishNode(node, "ThisExpression") case types.name: var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; var id = this.parseIdent(false); if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function)) { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) } if (canBeArrow && !this.canInsertSemicolon()) { if (this.eat(types.arrow)) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) } if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) { id = this.parseIdent(false); if (this.canInsertSemicolon() || !this.eat(types.arrow)) { this.unexpected(); } return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) } } return id case types.regexp: var value = this.value; node = this.parseLiteral(value.value); node.regex = {pattern: value.pattern, flags: value.flags}; return node case types.num: case types.string: return this.parseLiteral(this.value) case types._null: case types._true: case types._false: node = this.startNode(); node.value = this.type === types._null ? null : this.type === types._true; node.raw = this.type.keyword; this.next(); return this.finishNode(node, "Literal") case types.parenL: var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow); if (refDestructuringErrors) { if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) { refDestructuringErrors.parenthesizedAssign = start; } if (refDestructuringErrors.parenthesizedBind < 0) { refDestructuringErrors.parenthesizedBind = start; } } return expr case types.bracketL: node = this.startNode(); this.next(); node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors); return this.finishNode(node, "ArrayExpression") case types.braceL: return this.parseObj(false, refDestructuringErrors) case types._function: node = this.startNode(); this.next(); return this.parseFunction(node, 0) case types._class: return this.parseClass(this.startNode(), false) case types._new: return this.parseNew() case types.backQuote: return this.parseTemplate() default: this.unexpected(); } }; pp$3.parseLiteral = function(value) { var node = this.startNode(); node.value = value; node.raw = this.input.slice(this.start, this.end); this.next(); return this.finishNode(node, "Literal") }; pp$3.parseParenExpression = function() { this.expect(types.parenL); var val = this.parseExpression(); this.expect(types.parenR); return val }; pp$3.parseParenAndDistinguishExpression = function(canBeArrow) { var this$1 = this; var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; if (this.options.ecmaVersion >= 6) { this.next(); var innerStartPos = this.start, innerStartLoc = this.startLoc; var exprList = [], first = true, lastIsComma = false; var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; this.yieldPos = 0; this.awaitPos = 0; // Do not save awaitIdentPos to allow checking awaits nested in parameters while (this.type !== types.parenR) { first ? first = false : this$1.expect(types.comma); if (allowTrailingComma && this$1.afterTrailingComma(types.parenR, true)) { lastIsComma = true; break } else if (this$1.type === types.ellipsis) { spreadStart = this$1.start; exprList.push(this$1.parseParenItem(this$1.parseRestBinding())); if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element"); } break } else { exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem)); } } var innerEndPos = this.start, innerEndLoc = this.startLoc; this.expect(types.parenR); if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) { this.checkPatternErrors(refDestructuringErrors, false); this.checkYieldAwaitInDefaultParams(); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; return this.parseParenArrowList(startPos, startLoc, exprList) } if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } if (spreadStart) { this.unexpected(spreadStart); } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; if (exprList.length > 1) { val = this.startNodeAt(innerStartPos, innerStartLoc); val.expressions = exprList; this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); } else { val = exprList[0]; } } else { val = this.parseParenExpression(); } if (this.options.preserveParens) { var par = this.startNodeAt(startPos, startLoc); par.expression = val; return this.finishNode(par, "ParenthesizedExpression") } else { return val } }; pp$3.parseParenItem = function(item) { return item }; pp$3.parseParenArrowList = function(startPos, startLoc, exprList) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) }; // New's precedence is slightly tricky. It must allow its argument to // be a `[]` or dot subscript expression, but not a call — at least, // not without wrapping it in parentheses. Thus, it uses the noCalls // argument to parseSubscripts to prevent it from consuming the // argument list. var empty$1 = []; pp$3.parseNew = function() { var node = this.startNode(); var meta = this.parseIdent(true); if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) { node.meta = meta; var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "target" || containsEsc) { this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target"); } if (!this.inNonArrowFunction()) { this.raiseRecoverable(node.start, "new.target can only be used in functions"); } return this.finishNode(node, "MetaProperty") } var startPos = this.start, startLoc = this.startLoc; node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); } else { node.arguments = empty$1; } return this.finishNode(node, "NewExpression") }; // Parse template expression. pp$3.parseTemplateElement = function(ref) { var isTagged = ref.isTagged; var elem = this.startNode(); if (this.type === types.invalidTemplate) { if (!isTagged) { this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); } elem.value = { raw: this.value, cooked: null }; } else { elem.value = { raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), cooked: this.value }; } this.next(); elem.tail = this.type === types.backQuote; return this.finishNode(elem, "TemplateElement") }; pp$3.parseTemplate = function(ref) { var this$1 = this; if ( ref === void 0 ) ref = {}; var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; var node = this.startNode(); this.next(); node.expressions = []; var curElt = this.parseTemplateElement({isTagged: isTagged}); node.quasis = [curElt]; while (!curElt.tail) { if (this$1.type === types.eof) { this$1.raise(this$1.pos, "Unterminated template literal"); } this$1.expect(types.dollarBraceL); node.expressions.push(this$1.parseExpression()); this$1.expect(types.braceR); node.quasis.push(curElt = this$1.parseTemplateElement({isTagged: isTagged})); } this.next(); return this.finishNode(node, "TemplateLiteral") }; pp$3.isAsyncProp = function(prop) { return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }; // Parse an object literal or binding pattern. pp$3.parseObj = function(isPattern, refDestructuringErrors) { var this$1 = this; var node = this.startNode(), first = true, propHash = {}; node.properties = []; this.next(); while (!this.eat(types.braceR)) { if (!first) { this$1.expect(types.comma); if (this$1.afterTrailingComma(types.braceR)) { break } } else { first = false; } var prop = this$1.parseProperty(isPattern, refDestructuringErrors); if (!isPattern) { this$1.checkPropClash(prop, propHash, refDestructuringErrors); } node.properties.push(prop); } return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") }; pp$3.parseProperty = function(isPattern, refDestructuringErrors) { var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) { if (isPattern) { prop.argument = this.parseIdent(false); if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } return this.finishNode(prop, "RestElement") } // To disallow parenthesized identifier via `this.toAssignable()`. if (this.type === types.parenL && refDestructuringErrors) { if (refDestructuringErrors.parenthesizedAssign < 0) { refDestructuringErrors.parenthesizedAssign = this.start; } if (refDestructuringErrors.parenthesizedBind < 0) { refDestructuringErrors.parenthesizedBind = this.start; } } // Parse argument. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); // To disallow trailing comma via `this.toAssignable()`. if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { refDestructuringErrors.trailingComma = this.start; } // Finish return this.finishNode(prop, "SpreadElement") } if (this.options.ecmaVersion >= 6) { prop.method = false; prop.shorthand = false; if (isPattern || refDestructuringErrors) { startPos = this.start; startLoc = this.startLoc; } if (!isPattern) { isGenerator = this.eat(types.star); } } var containsEsc = this.containsEsc; this.parsePropertyName(prop); if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { isAsync = true; isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); this.parsePropertyName(prop, refDestructuringErrors); } else { isAsync = false; } this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); return this.finishNode(prop, "Property") }; pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { if ((isGenerator || isAsync) && this.type === types.colon) { this.unexpected(); } if (this.eat(types.colon)) { prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); prop.kind = "init"; } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) { if (isPattern) { this.unexpected(); } prop.kind = "init"; prop.method = true; prop.value = this.parseMethod(isGenerator, isAsync); } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type !== types.comma && this.type !== types.braceR)) { if (isGenerator || isAsync) { this.unexpected(); } prop.kind = prop.key.name; this.parsePropertyName(prop); prop.value = this.parseMethod(false); var paramCount = prop.kind === "get" ? 0 : 1; if (prop.value.params.length !== paramCount) { var start = prop.value.start; if (prop.kind === "get") { this.raiseRecoverable(start, "getter should have no params"); } else { this.raiseRecoverable(start, "setter should have exactly one param"); } } else { if (prop.kind === "set" && prop.value.params[0].type === "RestElement") { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } } } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { if (isGenerator || isAsync) { this.unexpected(); } this.checkUnreserved(prop.key); if (prop.key.name === "await" && !this.awaitIdentPos) { this.awaitIdentPos = startPos; } prop.kind = "init"; if (isPattern) { prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); } else if (this.type === types.eq && refDestructuringErrors) { if (refDestructuringErrors.shorthandAssign < 0) { refDestructuringErrors.shorthandAssign = this.start; } prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); } else { prop.value = prop.key; } prop.shorthand = true; } else { this.unexpected(); } }; pp$3.parsePropertyName = function(prop) { if (this.options.ecmaVersion >= 6) { if (this.eat(types.bracketL)) { prop.computed = true; prop.key = this.parseMaybeAssign(); this.expect(types.bracketR); return prop.key } else { prop.computed = false; } } return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(true) }; // Initialize empty function node. pp$3.initFunction = function(node) { node.id = null; if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } if (this.options.ecmaVersion >= 8) { node.async = false; } }; // Parse object or class method. pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.initFunction(node); if (this.options.ecmaVersion >= 6) { node.generator = isGenerator; } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); this.expect(types.parenL); node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); this.parseFunctionBody(node, false, true); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "FunctionExpression") }; // Parse arrow function expression with given parameters. pp$3.parseArrowExpression = function(node, params, isAsync) { var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); this.initFunction(node); if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; node.params = this.toAssignableList(params, true); this.parseFunctionBody(node, true, false); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "ArrowFunctionExpression") }; // Parse function body and check parameters. pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) { var isExpression = isArrowFunction && this.type !== types.braceL; var oldStrict = this.strict, useStrict = false; if (isExpression) { node.body = this.parseMaybeAssign(); node.expression = true; this.checkParams(node, false); } else { var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); if (!oldStrict || nonSimple) { useStrict = this.strictDirective(this.end); // If this is a strict mode function, verify that argument names // are not repeated, and it does not try to bind the words `eval` // or `arguments`. if (useStrict && nonSimple) { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } } // Start a new scope with regard to labels and the `inFunction` // flag (restore them to their old value afterwards). var oldLabels = this.labels; this.labels = []; if (useStrict) { this.strict = true; } // Add the params to varDeclaredNames to ensure that an error is thrown // if a let/const declaration in the function clashes with one of the params. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); node.body = this.parseBlock(false); node.expression = false; this.adaptDirectivePrologue(node.body.body); this.labels = oldLabels; } this.exitScope(); // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' if (this.strict && node.id) { this.checkLVal(node.id, BIND_OUTSIDE); } this.strict = oldStrict; }; pp$3.isSimpleParamList = function(params) { for (var i = 0, list = params; i < list.length; i += 1) { var param = list[i]; if (param.type !== "Identifier") { return false } } return true }; // Checks function params for various disallowed patterns such as using "eval" // or "arguments" and duplicate parameters. pp$3.checkParams = function(node, allowDuplicates) { var this$1 = this; var nameHash = {}; for (var i = 0, list = node.params; i < list.length; i += 1) { var param = list[i]; this$1.checkLVal(param, BIND_VAR, allowDuplicates ? null : nameHash); } }; // Parses a comma-separated list of expressions, and returns them as // an array. `close` is the token type that ends the list, and // `allowEmpty` can be turned on to allow subsequent commas with // nothing in between them to be parsed as `null` (which is needed // for array literals). pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { var this$1 = this; var elts = [], first = true; while (!this.eat(close)) { if (!first) { this$1.expect(types.comma); if (allowTrailingComma && this$1.afterTrailingComma(close)) { break } } else { first = false; } var elt = (void 0); if (allowEmpty && this$1.type === types.comma) { elt = null; } else if (this$1.type === types.ellipsis) { elt = this$1.parseSpread(refDestructuringErrors); if (refDestructuringErrors && this$1.type === types.comma && refDestructuringErrors.trailingComma < 0) { refDestructuringErrors.trailingComma = this$1.start; } } else { elt = this$1.parseMaybeAssign(false, refDestructuringErrors); } elts.push(elt); } return elts }; pp$3.checkUnreserved = function(ref) { var start = ref.start; var end = ref.end; var name = ref.name; if (this.inGenerator && name === "yield") { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } if (this.inAsync && name === "await") { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } if (this.keywords.test(name)) { this.raise(start, ("Unexpected keyword '" + name + "'")); } if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) { return } var re = this.strict ? this.reservedWordsStrict : this.reservedWords; if (re.test(name)) { if (!this.inAsync && name === "await") { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); } }; // Parse the next token as an identifier. If `liberal` is true (used // when parsing properties), it will also convert keywords into // identifiers. pp$3.parseIdent = function(liberal, isBinding) { var node = this.startNode(); if (liberal && this.options.allowReserved === "never") { liberal = false; } if (this.type === types.name) { node.name = this.value; } else if (this.type.keyword) { node.name = this.type.keyword; // To fix https://github.com/acornjs/acorn/issues/575 // `class` and `function` keywords push new context into this.context. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { this.context.pop(); } } else { this.unexpected(); } this.next(); this.finishNode(node, "Identifier"); if (!liberal) { this.checkUnreserved(node); if (node.name === "await" && !this.awaitIdentPos) { this.awaitIdentPos = node.start; } } return node }; // Parses yield expression inside generator. pp$3.parseYield = function(noIn) { if (!this.yieldPos) { this.yieldPos = this.start; } var node = this.startNode(); this.next(); if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) { node.delegate = false; node.argument = null; } else { node.delegate = this.eat(types.star); node.argument = this.parseMaybeAssign(noIn); } return this.finishNode(node, "YieldExpression") }; pp$3.parseAwait = function() { if (!this.awaitPos) { this.awaitPos = this.start; } var node = this.startNode(); this.next(); node.argument = this.parseMaybeUnary(null, true); return this.finishNode(node, "AwaitExpression") }; var pp$4 = Parser.prototype; // This function is used to raise exceptions on parse errors. It // takes an offset integer (into the current `input`) to indicate // the location of the error, attaches the position to the end // of the error message, and then raises a `SyntaxError` with that // message. pp$4.raise = function(pos, message) { var loc = getLineInfo(this.input, pos); message += " (" + loc.line + ":" + loc.column + ")"; var err = new SyntaxError(message); err.pos = pos; err.loc = loc; err.raisedAt = this.pos; throw err }; pp$4.raiseRecoverable = pp$4.raise; pp$4.curPosition = function() { if (this.options.locations) { return new Position(this.curLine, this.pos - this.lineStart) } }; var pp$5 = Parser.prototype; var Scope = function Scope(flags) { this.flags = flags; // A list of var-declared names in the current lexical scope this.var = []; // A list of lexically-declared names in the current lexical scope this.lexical = []; // A list of lexically-declared FunctionDeclaration names in the current lexical scope this.functions = []; }; // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. pp$5.enterScope = function(flags) { this.scopeStack.push(new Scope(flags)); }; pp$5.exitScope = function() { this.scopeStack.pop(); }; // The spec says: // > At the top level of a function, or script, function declarations are // > treated like var declarations rather than like lexical declarations. pp$5.treatFunctionsAsVarInScope = function(scope) { return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) }; pp$5.declareName = function(name, bindingType, pos) { var this$1 = this; var redeclared = false; if (bindingType === BIND_LEXICAL) { var scope = this.currentScope(); redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; scope.lexical.push(name); if (this.inModule && (scope.flags & SCOPE_TOP)) { delete this.undefinedExports[name]; } } else if (bindingType === BIND_SIMPLE_CATCH) { var scope$1 = this.currentScope(); scope$1.lexical.push(name); } else if (bindingType === BIND_FUNCTION) { var scope$2 = this.currentScope(); if (this.treatFunctionsAsVar) { redeclared = scope$2.lexical.indexOf(name) > -1; } else { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } scope$2.functions.push(name); } else { for (var i = this.scopeStack.length - 1; i >= 0; --i) { var scope$3 = this$1.scopeStack[i]; if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || !this$1.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { redeclared = true; break } scope$3.var.push(name); if (this$1.inModule && (scope$3.flags & SCOPE_TOP)) { delete this$1.undefinedExports[name]; } if (scope$3.flags & SCOPE_VAR) { break } } } if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } }; pp$5.checkLocalExport = function(id) { // scope.functions must be empty as Module code is always strict. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) { this.undefinedExports[id.name] = id; } }; pp$5.currentScope = function() { return this.scopeStack[this.scopeStack.length - 1] }; pp$5.currentVarScope = function() { var this$1 = this; for (var i = this.scopeStack.length - 1;; i--) { var scope = this$1.scopeStack[i]; if (scope.flags & SCOPE_VAR) { return scope } } }; // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. pp$5.currentThisScope = function() { var this$1 = this; for (var i = this.scopeStack.length - 1;; i--) { var scope = this$1.scopeStack[i]; if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } } }; var Node = function Node(parser, pos, loc) { this.type = ""; this.start = pos; this.end = 0; if (parser.options.locations) { this.loc = new SourceLocation(parser, loc); } if (parser.options.directSourceFile) { this.sourceFile = parser.options.directSourceFile; } if (parser.options.ranges) { this.range = [pos, 0]; } }; // Start an AST node, attaching a start offset. var pp$6 = Parser.prototype; pp$6.startNode = function() { return new Node(this, this.start, this.startLoc) }; pp$6.startNodeAt = function(pos, loc) { return new Node(this, pos, loc) }; // Finish an AST node, adding `type` and `end` properties. function finishNodeAt(node, type, pos, loc) { node.type = type; node.end = pos; if (this.options.locations) { node.loc.end = loc; } if (this.options.ranges) { node.range[1] = pos; } return node } pp$6.finishNode = function(node, type) { return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) }; // Finish node at given position pp$6.finishNodeAt = function(node, type, pos, loc) { return finishNodeAt.call(this, node, type, pos, loc) }; // The algorithm used to determine whether a regexp can appear at a // given point in the program is loosely based on sweet.js' approach. // See https://github.com/mozilla/sweet.js/wiki/design var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { this.token = token; this.isExpr = !!isExpr; this.preserveSpace = !!preserveSpace; this.override = override; this.generator = !!generator; }; var types$1 = { b_stat: new TokContext("{", false), b_expr: new TokContext("{", true), b_tmpl: new TokContext("${", false), p_stat: new TokContext("(", false), p_expr: new TokContext("(", true), q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), f_stat: new TokContext("function", false), f_expr: new TokContext("function", true), f_expr_gen: new TokContext("function", true, false, null, true), f_gen: new TokContext("function", false, false, null, true) }; var pp$7 = Parser.prototype; pp$7.initialContext = function() { return [types$1.b_stat] }; pp$7.braceIsBlock = function(prevType) { var parent = this.curContext(); if (parent === types$1.f_expr || parent === types$1.f_stat) { return true } if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) { return !parent.isExpr } // The check for `tt.name && exprAllowed` detects whether we are // after a `yield` or `of` construct. See the `updateContext` for // `tt.name`. if (prevType === types._return || prevType === types.name && this.exprAllowed) { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) { return true } if (prevType === types.braceL) { return parent === types$1.b_stat } if (prevType === types._var || prevType === types._const || prevType === types.name) { return false } return !this.exprAllowed }; pp$7.inGeneratorContext = function() { var this$1 = this; for (var i = this.context.length - 1; i >= 1; i--) { var context = this$1.context[i]; if (context.token === "function") { return context.generator } } return false }; pp$7.updateContext = function(prevType) { var update, type = this.type; if (type.keyword && prevType === types.dot) { this.exprAllowed = false; } else if (update = type.updateContext) { update.call(this, prevType); } else { this.exprAllowed = type.beforeExpr; } }; // Token-specific context update code types.parenR.updateContext = types.braceR.updateContext = function() { if (this.context.length === 1) { this.exprAllowed = true; return } var out = this.context.pop(); if (out === types$1.b_stat && this.curContext().token === "function") { out = this.context.pop(); } this.exprAllowed = !out.isExpr; }; types.braceL.updateContext = function(prevType) { this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr); this.exprAllowed = true; }; types.dollarBraceL.updateContext = function() { this.context.push(types$1.b_tmpl); this.exprAllowed = true; }; types.parenL.updateContext = function(prevType) { var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; this.context.push(statementParens ? types$1.p_stat : types$1.p_expr); this.exprAllowed = true; }; types.incDec.updateContext = function() { // tokExprAllowed stays unchanged }; types._function.updateContext = types._class.updateContext = function(prevType) { if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) { this.context.push(types$1.f_expr); } else { this.context.push(types$1.f_stat); } this.exprAllowed = false; }; types.backQuote.updateContext = function() { if (this.curContext() === types$1.q_tmpl) { this.context.pop(); } else { this.context.push(types$1.q_tmpl); } this.exprAllowed = false; }; types.star.updateContext = function(prevType) { if (prevType === types._function) { var index = this.context.length - 1; if (this.context[index] === types$1.f_expr) { this.context[index] = types$1.f_expr_gen; } else { this.context[index] = types$1.f_gen; } } this.exprAllowed = true; }; types.name.updateContext = function(prevType) { var allowed = false; if (this.options.ecmaVersion >= 6 && prevType !== types.dot) { if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) { allowed = true; } } this.exprAllowed = allowed; }; // This file contains Unicode properties extracted from the ECMAScript // specification. The lists are extracted like so: // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) // #table-binary-unicode-properties var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; var unicodeBinaryProperties = { 9: ecma9BinaryProperties, 10: ecma9BinaryProperties + " Extended_Pictographic" }; // #table-unicode-general-category-values var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; // #table-unicode-script-values var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; var unicodeScriptValues = { 9: ecma9ScriptValues, 10: ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd" }; var data = {}; function buildUnicodeData(ecmaVersion) { var d = data[ecmaVersion] = { binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), nonBinary: { General_Category: wordsRegexp(unicodeGeneralCategoryValues), Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) } }; d.nonBinary.Script_Extensions = d.nonBinary.Script; d.nonBinary.gc = d.nonBinary.General_Category; d.nonBinary.sc = d.nonBinary.Script; d.nonBinary.scx = d.nonBinary.Script_Extensions; } buildUnicodeData(9); buildUnicodeData(10); var pp$9 = Parser.prototype; var RegExpValidationState = function RegExpValidationState(parser) { this.parser = parser; this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : ""); this.unicodeProperties = data[parser.options.ecmaVersion >= 10 ? 10 : parser.options.ecmaVersion]; this.source = ""; this.flags = ""; this.start = 0; this.switchU = false; this.switchN = false; this.pos = 0; this.lastIntValue = 0; this.lastStringValue = ""; this.lastAssertionIsQuantifiable = false; this.numCapturingParens = 0; this.maxBackReference = 0; this.groupNames = []; this.backReferenceNames = []; }; RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { var unicode = flags.indexOf("u") !== -1; this.start = start | 0; this.source = pattern + ""; this.flags = flags; this.switchU = unicode && this.parser.options.ecmaVersion >= 6; this.switchN = unicode && this.parser.options.ecmaVersion >= 9; }; RegExpValidationState.prototype.raise = function raise (message) { this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); }; // If u flag is given, this returns the code point at the index (it combines a surrogate pair). // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). RegExpValidationState.prototype.at = function at (i) { var s = this.source; var l = s.length; if (i >= l) { return -1 } var c = s.charCodeAt(i); if (!this.switchU || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { return c } return (c << 10) + s.charCodeAt(i + 1) - 0x35FDC00 }; RegExpValidationState.prototype.nextIndex = function nextIndex (i) { var s = this.source; var l = s.length; if (i >= l) { return l } var c = s.charCodeAt(i); if (!this.switchU || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { return i + 1 } return i + 2 }; RegExpValidationState.prototype.current = function current () { return this.at(this.pos) }; RegExpValidationState.prototype.lookahead = function lookahead () { return this.at(this.nextIndex(this.pos)) }; RegExpValidationState.prototype.advance = function advance () { this.pos = this.nextIndex(this.pos); }; RegExpValidationState.prototype.eat = function eat (ch) { if (this.current() === ch) { this.advance(); return true } return false }; function codePointToString$1(ch) { if (ch <= 0xFFFF) { return String.fromCharCode(ch) } ch -= 0x10000; return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00) } /** * Validate the flags part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp$9.validateRegExpFlags = function(state) { var this$1 = this; var validFlags = state.validFlags; var flags = state.flags; for (var i = 0; i < flags.length; i++) { var flag = flags.charAt(i); if (validFlags.indexOf(flag) === -1) { this$1.raise(state.start, "Invalid regular expression flag"); } if (flags.indexOf(flag, i + 1) > -1) { this$1.raise(state.start, "Duplicate regular expression flag"); } } }; /** * Validate the pattern part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp$9.validateRegExpPattern = function(state) { this.regexp_pattern(state); // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of // parsing contains a |GroupName|, reparse with the goal symbol // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* // exception if _P_ did not conform to the grammar, if any elements of _P_ // were not matched by the parse, or if any Early Error conditions exist. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { state.switchN = true; this.regexp_pattern(state); } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern pp$9.regexp_pattern = function(state) { state.pos = 0; state.lastIntValue = 0; state.lastStringValue = ""; state.lastAssertionIsQuantifiable = false; state.numCapturingParens = 0; state.maxBackReference = 0; state.groupNames.length = 0; state.backReferenceNames.length = 0; this.regexp_disjunction(state); if (state.pos !== state.source.length) { // Make the same messages as V8. if (state.eat(0x29 /* ) */)) { state.raise("Unmatched ')'"); } if (state.eat(0x5D /* [ */) || state.eat(0x7D /* } */)) { state.raise("Lone quantifier brackets"); } } if (state.maxBackReference > state.numCapturingParens) { state.raise("Invalid escape"); } for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { var name = list[i]; if (state.groupNames.indexOf(name) === -1) { state.raise("Invalid named capture referenced"); } } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction pp$9.regexp_disjunction = function(state) { var this$1 = this; this.regexp_alternative(state); while (state.eat(0x7C /* | */)) { this$1.regexp_alternative(state); } // Make the same message as V8. if (this.regexp_eatQuantifier(state, true)) { state.raise("Nothing to repeat"); } if (state.eat(0x7B /* { */)) { state.raise("Lone quantifier brackets"); } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative pp$9.regexp_alternative = function(state) { while (state.pos < state.source.length && this.regexp_eatTerm(state)) { } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term pp$9.regexp_eatTerm = function(state) { if (this.regexp_eatAssertion(state)) { // Handle `QuantifiableAssertion Quantifier` alternative. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion // is a QuantifiableAssertion. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { // Make the same message as V8. if (state.switchU) { state.raise("Invalid quantifier"); } } return true } if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { this.regexp_eatQuantifier(state); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion pp$9.regexp_eatAssertion = function(state) { var start = state.pos; state.lastAssertionIsQuantifiable = false; // ^, $ if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { return true } // \b \B if (state.eat(0x5C /* \ */)) { if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { return true } state.pos = start; } // Lookahead / Lookbehind if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { var lookbehind = false; if (this.options.ecmaVersion >= 9) { lookbehind = state.eat(0x3C /* < */); } if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { this.regexp_disjunction(state); if (!state.eat(0x29 /* ) */)) { state.raise("Unterminated group"); } state.lastAssertionIsQuantifiable = !lookbehind; return true } } state.pos = start; return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier pp$9.regexp_eatQuantifier = function(state, noError) { if ( noError === void 0 ) noError = false; if (this.regexp_eatQuantifierPrefix(state, noError)) { state.eat(0x3F /* ? */); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix pp$9.regexp_eatQuantifierPrefix = function(state, noError) { return ( state.eat(0x2A /* * */) || state.eat(0x2B /* + */) || state.eat(0x3F /* ? */) || this.regexp_eatBracedQuantifier(state, noError) ) }; pp$9.regexp_eatBracedQuantifier = function(state, noError) { var start = state.pos; if (state.eat(0x7B /* { */)) { var min = 0, max = -1; if (this.regexp_eatDecimalDigits(state)) { min = state.lastIntValue; if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { max = state.lastIntValue; } if (state.eat(0x7D /* } */)) { // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term if (max !== -1 && max < min && !noError) { state.raise("numbers out of order in {} quantifier"); } return true } } if (state.switchU && !noError) { state.raise("Incomplete quantifier"); } state.pos = start; } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom pp$9.regexp_eatAtom = function(state) { return ( this.regexp_eatPatternCharacters(state) || state.eat(0x2E /* . */) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) ) }; pp$9.regexp_eatReverseSolidusAtomEscape = function(state) { var start = state.pos; if (state.eat(0x5C /* \ */)) { if (this.regexp_eatAtomEscape(state)) { return true } state.pos = start; } return false }; pp$9.regexp_eatUncapturingGroup = function(state) { var start = state.pos; if (state.eat(0x28 /* ( */)) { if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { this.regexp_disjunction(state); if (state.eat(0x29 /* ) */)) { return true } state.raise("Unterminated group"); } state.pos = start; } return false }; pp$9.regexp_eatCapturingGroup = function(state) { if (state.eat(0x28 /* ( */)) { if (this.options.ecmaVersion >= 9) { this.regexp_groupSpecifier(state); } else if (state.current() === 0x3F /* ? */) { state.raise("Invalid group"); } this.regexp_disjunction(state); if (state.eat(0x29 /* ) */)) { state.numCapturingParens += 1; return true } state.raise("Unterminated group"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom pp$9.regexp_eatExtendedAtom = function(state) { return ( state.eat(0x2E /* . */) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state) ) }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier pp$9.regexp_eatInvalidBracedQuantifier = function(state) { if (this.regexp_eatBracedQuantifier(state, true)) { state.raise("Nothing to repeat"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter pp$9.regexp_eatSyntaxCharacter = function(state) { var ch = state.current(); if (isSyntaxCharacter(ch)) { state.lastIntValue = ch; state.advance(); return true } return false }; function isSyntaxCharacter(ch) { return ( ch === 0x24 /* $ */ || ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || ch === 0x2E /* . */ || ch === 0x3F /* ? */ || ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || ch >= 0x7B /* { */ && ch <= 0x7D /* } */ ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter // But eat eager. pp$9.regexp_eatPatternCharacters = function(state) { var start = state.pos; var ch = 0; while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { state.advance(); } return state.pos !== start }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter pp$9.regexp_eatExtendedPatternCharacter = function(state) { var ch = state.current(); if ( ch !== -1 && ch !== 0x24 /* $ */ && !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && ch !== 0x2E /* . */ && ch !== 0x3F /* ? */ && ch !== 0x5B /* [ */ && ch !== 0x5E /* ^ */ && ch !== 0x7C /* | */ ) { state.advance(); return true } return false }; // GroupSpecifier[U] :: // [empty] // `?` GroupName[?U] pp$9.regexp_groupSpecifier = function(state) { if (state.eat(0x3F /* ? */)) { if (this.regexp_eatGroupName(state)) { if (state.groupNames.indexOf(state.lastStringValue) !== -1) { state.raise("Duplicate capture group name"); } state.groupNames.push(state.lastStringValue); return } state.raise("Invalid group"); } }; // GroupName[U] :: // `<` RegExpIdentifierName[?U] `>` // Note: this updates `state.lastStringValue` property with the eaten name. pp$9.regexp_eatGroupName = function(state) { state.lastStringValue = ""; if (state.eat(0x3C /* < */)) { if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { return true } state.raise("Invalid capture group name"); } return false }; // RegExpIdentifierName[U] :: // RegExpIdentifierStart[?U] // RegExpIdentifierName[?U] RegExpIdentifierPart[?U] // Note: this updates `state.lastStringValue` property with the eaten name. pp$9.regexp_eatRegExpIdentifierName = function(state) { state.lastStringValue = ""; if (this.regexp_eatRegExpIdentifierStart(state)) { state.lastStringValue += codePointToString$1(state.lastIntValue); while (this.regexp_eatRegExpIdentifierPart(state)) { state.lastStringValue += codePointToString$1(state.lastIntValue); } return true } return false }; // RegExpIdentifierStart[U] :: // UnicodeIDStart // `$` // `_` // `\` RegExpUnicodeEscapeSequence[?U] pp$9.regexp_eatRegExpIdentifierStart = function(state) { var start = state.pos; var ch = state.current(); state.advance(); if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) { ch = state.lastIntValue; } if (isRegExpIdentifierStart(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierStart(ch) { return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ } // RegExpIdentifierPart[U] :: // UnicodeIDContinue // `$` // `_` // `\` RegExpUnicodeEscapeSequence[?U] // <ZWNJ> // <ZWJ> pp$9.regexp_eatRegExpIdentifierPart = function(state) { var start = state.pos; var ch = state.current(); state.advance(); if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) { ch = state.lastIntValue; } if (isRegExpIdentifierPart(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierPart(ch) { return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape pp$9.regexp_eatAtomEscape = function(state) { if ( this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || (state.switchN && this.regexp_eatKGroupName(state)) ) { return true } if (state.switchU) { // Make the same message as V8. if (state.current() === 0x63 /* c */) { state.raise("Invalid unicode escape"); } state.raise("Invalid escape"); } return false }; pp$9.regexp_eatBackReference = function(state) { var start = state.pos; if (this.regexp_eatDecimalEscape(state)) { var n = state.lastIntValue; if (state.switchU) { // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape if (n > state.maxBackReference) { state.maxBackReference = n; } return true } if (n <= state.numCapturingParens) { return true } state.pos = start; } return false }; pp$9.regexp_eatKGroupName = function(state) { if (state.eat(0x6B /* k */)) { if (this.regexp_eatGroupName(state)) { state.backReferenceNames.push(state.lastStringValue); return true } state.raise("Invalid named reference"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape pp$9.regexp_eatCharacterEscape = function(state) { return ( this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state) || (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || this.regexp_eatIdentityEscape(state) ) }; pp$9.regexp_eatCControlLetter = function(state) { var start = state.pos; if (state.eat(0x63 /* c */)) { if (this.regexp_eatControlLetter(state)) { return true } state.pos = start; } return false }; pp$9.regexp_eatZero = function(state) { if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { state.lastIntValue = 0; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape pp$9.regexp_eatControlEscape = function(state) { var ch = state.current(); if (ch === 0x74 /* t */) { state.lastIntValue = 0x09; /* \t */ state.advance(); return true } if (ch === 0x6E /* n */) { state.lastIntValue = 0x0A; /* \n */ state.advance(); return true } if (ch === 0x76 /* v */) { state.lastIntValue = 0x0B; /* \v */ state.advance(); return true } if (ch === 0x66 /* f */) { state.lastIntValue = 0x0C; /* \f */ state.advance(); return true } if (ch === 0x72 /* r */) { state.lastIntValue = 0x0D; /* \r */ state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter pp$9.regexp_eatControlLetter = function(state) { var ch = state.current(); if (isControlLetter(ch)) { state.lastIntValue = ch % 0x20; state.advance(); return true } return false }; function isControlLetter(ch) { return ( (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence pp$9.regexp_eatRegExpUnicodeEscapeSequence = function(state) { var start = state.pos; if (state.eat(0x75 /* u */)) { if (this.regexp_eatFixedHexDigits(state, 4)) { var lead = state.lastIntValue; if (state.switchU && lead >= 0xD800 && lead <= 0xDBFF) { var leadSurrogateEnd = state.pos; if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { var trail = state.lastIntValue; if (trail >= 0xDC00 && trail <= 0xDFFF) { state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; return true } } state.pos = leadSurrogateEnd; state.lastIntValue = lead; } return true } if ( state.switchU && state.eat(0x7B /* { */) && this.regexp_eatHexDigits(state) && state.eat(0x7D /* } */) && isValidUnicode(state.lastIntValue) ) { return true } if (state.switchU) { state.raise("Invalid unicode escape"); } state.pos = start; } return false }; function isValidUnicode(ch) { return ch >= 0 && ch <= 0x10FFFF } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape pp$9.regexp_eatIdentityEscape = function(state) { if (state.switchU) { if (this.regexp_eatSyntaxCharacter(state)) { return true } if (state.eat(0x2F /* / */)) { state.lastIntValue = 0x2F; /* / */ return true } return false } var ch = state.current(); if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { state.lastIntValue = ch; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape pp$9.regexp_eatDecimalEscape = function(state) { state.lastIntValue = 0; var ch = state.current(); if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { do { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); state.advance(); } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape pp$9.regexp_eatCharacterClassEscape = function(state) { var ch = state.current(); if (isCharacterClassEscape(ch)) { state.lastIntValue = -1; state.advance(); return true } if ( state.switchU && this.options.ecmaVersion >= 9 && (ch === 0x50 /* P */ || ch === 0x70 /* p */) ) { state.lastIntValue = -1; state.advance(); if ( state.eat(0x7B /* { */) && this.regexp_eatUnicodePropertyValueExpression(state) && state.eat(0x7D /* } */) ) { return true } state.raise("Invalid property name"); } return false }; function isCharacterClassEscape(ch) { return ( ch === 0x64 /* d */ || ch === 0x44 /* D */ || ch === 0x73 /* s */ || ch === 0x53 /* S */ || ch === 0x77 /* w */ || ch === 0x57 /* W */ ) } // UnicodePropertyValueExpression :: // UnicodePropertyName `=` UnicodePropertyValue // LoneUnicodePropertyNameOrValue pp$9.regexp_eatUnicodePropertyValueExpression = function(state) { var start = state.pos; // UnicodePropertyName `=` UnicodePropertyValue if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { var name = state.lastStringValue; if (this.regexp_eatUnicodePropertyValue(state)) { var value = state.lastStringValue; this.regexp_validateUnicodePropertyNameAndValue(state, name, value); return true } } state.pos = start; // LoneUnicodePropertyNameOrValue if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { var nameOrValue = state.lastStringValue; this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); return true } return false }; pp$9.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { if (!has(state.unicodeProperties.nonBinary, name)) { state.raise("Invalid property name"); } if (!state.unicodeProperties.nonBinary[name].test(value)) { state.raise("Invalid property value"); } }; pp$9.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { if (!state.unicodeProperties.binary.test(nameOrValue)) { state.raise("Invalid property name"); } }; // UnicodePropertyName :: // UnicodePropertyNameCharacters pp$9.regexp_eatUnicodePropertyName = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyNameCharacter(ch = state.current())) { state.lastStringValue += codePointToString$1(ch); state.advance(); } return state.lastStringValue !== "" }; function isUnicodePropertyNameCharacter(ch) { return isControlLetter(ch) || ch === 0x5F /* _ */ } // UnicodePropertyValue :: // UnicodePropertyValueCharacters pp$9.regexp_eatUnicodePropertyValue = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyValueCharacter(ch = state.current())) { state.lastStringValue += codePointToString$1(ch); state.advance(); } return state.lastStringValue !== "" }; function isUnicodePropertyValueCharacter(ch) { return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) } // LoneUnicodePropertyNameOrValue :: // UnicodePropertyValueCharacters pp$9.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { return this.regexp_eatUnicodePropertyValue(state) }; // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass pp$9.regexp_eatCharacterClass = function(state) { if (state.eat(0x5B /* [ */)) { state.eat(0x5E /* ^ */); this.regexp_classRanges(state); if (state.eat(0x5D /* [ */)) { return true } // Unreachable since it threw "unterminated regular expression" error before. state.raise("Unterminated character class"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash pp$9.regexp_classRanges = function(state) { var this$1 = this; while (this.regexp_eatClassAtom(state)) { var left = state.lastIntValue; if (state.eat(0x2D /* - */) && this$1.regexp_eatClassAtom(state)) { var right = state.lastIntValue; if (state.switchU && (left === -1 || right === -1)) { state.raise("Invalid character class"); } if (left !== -1 && right !== -1 && left > right) { state.raise("Range out of order in character class"); } } } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash pp$9.regexp_eatClassAtom = function(state) { var start = state.pos; if (state.eat(0x5C /* \ */)) { if (this.regexp_eatClassEscape(state)) { return true } if (state.switchU) { // Make the same message as V8. var ch$1 = state.current(); if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { state.raise("Invalid class escape"); } state.raise("Invalid escape"); } state.pos = start; } var ch = state.current(); if (ch !== 0x5D /* [ */) { state.lastIntValue = ch; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape pp$9.regexp_eatClassEscape = function(state) { var start = state.pos; if (state.eat(0x62 /* b */)) { state.lastIntValue = 0x08; /* <BS> */ return true } if (state.switchU && state.eat(0x2D /* - */)) { state.lastIntValue = 0x2D; /* - */ return true } if (!state.switchU && state.eat(0x63 /* c */)) { if (this.regexp_eatClassControlLetter(state)) { return true } state.pos = start; } return ( this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) ) }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter pp$9.regexp_eatClassControlLetter = function(state) { var ch = state.current(); if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { state.lastIntValue = ch % 0x20; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence pp$9.regexp_eatHexEscapeSequence = function(state) { var start = state.pos; if (state.eat(0x78 /* x */)) { if (this.regexp_eatFixedHexDigits(state, 2)) { return true } if (state.switchU) { state.raise("Invalid escape"); } state.pos = start; } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits pp$9.regexp_eatDecimalDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isDecimalDigit(ch = state.current())) { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); state.advance(); } return state.pos !== start }; function isDecimalDigit(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits pp$9.regexp_eatHexDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isHexDigit(ch = state.current())) { state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); state.advance(); } return state.pos !== start }; function isHexDigit(ch) { return ( (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) ) } function hexToInt(ch) { if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { return 10 + (ch - 0x41 /* A */) } if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { return 10 + (ch - 0x61 /* a */) } return ch - 0x30 /* 0 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence // Allows only 0-377(octal) i.e. 0-255(decimal). pp$9.regexp_eatLegacyOctalEscapeSequence = function(state) { if (this.regexp_eatOctalDigit(state)) { var n1 = state.lastIntValue; if (this.regexp_eatOctalDigit(state)) { var n2 = state.lastIntValue; if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; } else { state.lastIntValue = n1 * 8 + n2; } } else { state.lastIntValue = n1; } return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit pp$9.regexp_eatOctalDigit = function(state) { var ch = state.current(); if (isOctalDigit(ch)) { state.lastIntValue = ch - 0x30; /* 0 */ state.advance(); return true } state.lastIntValue = 0; return false }; function isOctalDigit(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence pp$9.regexp_eatFixedHexDigits = function(state, length) { var start = state.pos; state.lastIntValue = 0; for (var i = 0; i < length; ++i) { var ch = state.current(); if (!isHexDigit(ch)) { state.pos = start; return false } state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); state.advance(); } return true }; // Object type used to represent tokens. Note that normally, tokens // simply exist as properties on the parser object. This is only // used for the onToken callback and the external tokenizer. var Token = function Token(p) { this.type = p.type; this.value = p.value; this.start = p.start; this.end = p.end; if (p.options.locations) { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } if (p.options.ranges) { this.range = [p.start, p.end]; } }; // ## Tokenizer var pp$8 = Parser.prototype; // Move to the next token pp$8.next = function() { if (this.options.onToken) { this.options.onToken(new Token(this)); } this.lastTokEnd = this.end; this.lastTokStart = this.start; this.lastTokEndLoc = this.endLoc; this.lastTokStartLoc = this.startLoc; this.nextToken(); }; pp$8.getToken = function() { this.next(); return new Token(this) }; // If we're in an ES6 environment, make parsers iterable if (typeof Symbol !== "undefined") { pp$8[Symbol.iterator] = function() { var this$1 = this; return { next: function () { var token = this$1.getToken(); return { done: token.type === types.eof, value: token } } } }; } // Toggle strict mode. Re-reads the next number or string to please // pedantic tests (`"use strict"; 010;` should fail). pp$8.curContext = function() { return this.context[this.context.length - 1] }; // Read a single token, updating the parser object's token-related // properties. pp$8.nextToken = function() { var curContext = this.curContext(); if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } this.start = this.pos; if (this.options.locations) { this.startLoc = this.curPosition(); } if (this.pos >= this.input.length) { return this.finishToken(types.eof) } if (curContext.override) { return curContext.override(this) } else { this.readToken(this.fullCharCodeAtPos()); } }; pp$8.readToken = function(code) { // Identifier or keyword. '\uXXXX' sequences are allowed in // identifiers, so '\' also dispatches to that. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) { return this.readWord() } return this.getTokenFromCode(code) }; pp$8.fullCharCodeAtPos = function() { var code = this.input.charCodeAt(this.pos); if (code <= 0xd7ff || code >= 0xe000) { return code } var next = this.input.charCodeAt(this.pos + 1); return (code << 10) + next - 0x35fdc00 }; pp$8.skipBlockComment = function() { var this$1 = this; var startLoc = this.options.onComment && this.curPosition(); var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } this.pos = end + 2; if (this.options.locations) { lineBreakG.lastIndex = start; var match; while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { ++this$1.curLine; this$1.lineStart = match.index + match[0].length; } } if (this.options.onComment) { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition()); } }; pp$8.skipLineComment = function(startSkip) { var this$1 = this; var start = this.pos; var startLoc = this.options.onComment && this.curPosition(); var ch = this.input.charCodeAt(this.pos += startSkip); while (this.pos < this.input.length && !isNewLine(ch)) { ch = this$1.input.charCodeAt(++this$1.pos); } if (this.options.onComment) { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition()); } }; // Called at the start of the parse and after every token. Skips // whitespace and comments, and. pp$8.skipSpace = function() { var this$1 = this; loop: while (this.pos < this.input.length) { var ch = this$1.input.charCodeAt(this$1.pos); switch (ch) { case 32: case 160: // ' ' ++this$1.pos; break case 13: if (this$1.input.charCodeAt(this$1.pos + 1) === 10) { ++this$1.pos; } case 10: case 8232: case 8233: ++this$1.pos; if (this$1.options.locations) { ++this$1.curLine; this$1.lineStart = this$1.pos; } break case 47: // '/' switch (this$1.input.charCodeAt(this$1.pos + 1)) { case 42: // '*' this$1.skipBlockComment(); break case 47: this$1.skipLineComment(2); break default: break loop } break default: if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { ++this$1.pos; } else { break loop } } } }; // Called at the end of every token. Sets `end`, `val`, and // maintains `context` and `exprAllowed`, and skips the space after // the token, so that the next one's `start` will point at the // right position. pp$8.finishToken = function(type, val) { this.end = this.pos; if (this.options.locations) { this.endLoc = this.curPosition(); } var prevType = this.type; this.type = type; this.value = val; this.updateContext(prevType); }; // ### Token reading // This is the function that is called to fetch the next token. It // is somewhat obscure, because it works in character codes rather // than characters, and because operator parsing has been inlined // into it. // // All in the name of speed. // pp$8.readToken_dot = function() { var next = this.input.charCodeAt(this.pos + 1); if (next >= 48 && next <= 57) { return this.readNumber(true) } var next2 = this.input.charCodeAt(this.pos + 2); if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' this.pos += 3; return this.finishToken(types.ellipsis) } else { ++this.pos; return this.finishToken(types.dot) } }; pp$8.readToken_slash = function() { // '/' var next = this.input.charCodeAt(this.pos + 1); if (this.exprAllowed) { ++this.pos; return this.readRegexp() } if (next === 61) { return this.finishOp(types.assign, 2) } return this.finishOp(types.slash, 1) }; pp$8.readToken_mult_modulo_exp = function(code) { // '%*' var next = this.input.charCodeAt(this.pos + 1); var size = 1; var tokentype = code === 42 ? types.star : types.modulo; // exponentiation operator ** and **= if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { ++size; tokentype = types.starstar; next = this.input.charCodeAt(this.pos + 2); } if (next === 61) { return this.finishOp(types.assign, size + 1) } return this.finishOp(tokentype, size) }; pp$8.readToken_pipe_amp = function(code) { // '|&' var next = this.input.charCodeAt(this.pos + 1); if (next === code) { return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) } if (next === 61) { return this.finishOp(types.assign, 2) } return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1) }; pp$8.readToken_caret = function() { // '^' var next = this.input.charCodeAt(this.pos + 1); if (next === 61) { return this.finishOp(types.assign, 2) } return this.finishOp(types.bitwiseXOR, 1) }; pp$8.readToken_plus_min = function(code) { // '+-' var next = this.input.charCodeAt(this.pos + 1); if (next === code) { if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { // A `-->` line comment this.skipLineComment(3); this.skipSpace(); return this.nextToken() } return this.finishOp(types.incDec, 2) } if (next === 61) { return this.finishOp(types.assign, 2) } return this.finishOp(types.plusMin, 1) }; pp$8.readToken_lt_gt = function(code) { // '<>' var next = this.input.charCodeAt(this.pos + 1); var size = 1; if (next === code) { size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) } return this.finishOp(types.bitShift, size) } if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) { // `<!--`, an XML-style comment that should be interpreted as a line comment this.skipLineComment(4); this.skipSpace(); return this.nextToken() } if (next === 61) { size = 2; } return this.finishOp(types.relational, size) }; pp$8.readToken_eq_excl = function(code) { // '=!' var next = this.input.charCodeAt(this.pos + 1); if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) } if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>' this.pos += 2; return this.finishToken(types.arrow) } return this.finishOp(code === 61 ? types.eq : types.prefix, 1) }; pp$8.getTokenFromCode = function(code) { switch (code) { // The interpretation of a dot depends on whether it is followed // by a digit or another two dots. case 46: // '.' return this.readToken_dot() // Punctuation tokens. case 40: ++this.pos; return this.finishToken(types.parenL) case 41: ++this.pos; return this.finishToken(types.parenR) case 59: ++this.pos; return this.finishToken(types.semi) case 44: ++this.pos; return this.finishToken(types.comma) case 91: ++this.pos; return this.finishToken(types.bracketL) case 93: ++this.pos; return this.finishToken(types.bracketR) case 123: ++this.pos; return this.finishToken(types.braceL) case 125: ++this.pos; return this.finishToken(types.braceR) case 58: ++this.pos; return this.finishToken(types.colon) case 63: ++this.pos; return this.finishToken(types.question) case 96: // '`' if (this.options.ecmaVersion < 6) { break } ++this.pos; return this.finishToken(types.backQuote) case 48: // '0' var next = this.input.charCodeAt(this.pos + 1); if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number if (this.options.ecmaVersion >= 6) { if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number } // Anything else beginning with a digit is an integer, octal // number, or float. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9 return this.readNumber(false) // Quotes produce strings. case 34: case 39: // '"', "'" return this.readString(code) // Operators are parsed inline in tiny state machines. '=' (61) is // often referred to. `finishOp` simply skips the amount of // characters it is given as second argument, and returns a token // of the type given by its first argument. case 47: // '/' return this.readToken_slash() case 37: case 42: // '%*' return this.readToken_mult_modulo_exp(code) case 124: case 38: // '|&' return this.readToken_pipe_amp(code) case 94: // '^' return this.readToken_caret() case 43: case 45: // '+-' return this.readToken_plus_min(code) case 60: case 62: // '<>' return this.readToken_lt_gt(code) case 61: case 33: // '=!' return this.readToken_eq_excl(code) case 126: // '~' return this.finishOp(types.prefix, 1) } this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'"); }; pp$8.finishOp = function(type, size) { var str = this.input.slice(this.pos, this.pos + size); this.pos += size; return this.finishToken(type, str) }; pp$8.readRegexp = function() { var this$1 = this; var escaped, inClass, start = this.pos; for (;;) { if (this$1.pos >= this$1.input.length) { this$1.raise(start, "Unterminated regular expression"); } var ch = this$1.input.charAt(this$1.pos); if (lineBreak.test(ch)) { this$1.raise(start, "Unterminated regular expression"); } if (!escaped) { if (ch === "[") { inClass = true; } else if (ch === "]" && inClass) { inClass = false; } else if (ch === "/" && !inClass) { break } escaped = ch === "\\"; } else { escaped = false; } ++this$1.pos; } var pattern = this.input.slice(start, this.pos); ++this.pos; var flagsStart = this.pos; var flags = this.readWord1(); if (this.containsEsc) { this.unexpected(flagsStart); } // Validate pattern var state = this.regexpState || (this.regexpState = new RegExpValidationState(this)); state.reset(start, pattern, flags); this.validateRegExpFlags(state); this.validateRegExpPattern(state); // Create Literal#value property value. var value = null; try { value = new RegExp(pattern, flags); } catch (e) { // ESTree requires null if it failed to instantiate RegExp object. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral } return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value}) }; // Read an integer in the given radix. Return null if zero digits // were read, the integer value otherwise. When `len` is given, this // will return `null` unless the integer has exactly `len` digits. pp$8.readInt = function(radix, len) { var this$1 = this; var start = this.pos, total = 0; for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) { var code = this$1.input.charCodeAt(this$1.pos), val = (void 0); if (code >= 97) { val = code - 97 + 10; } // a else if (code >= 65) { val = code - 65 + 10; } // A else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9 else { val = Infinity; } if (val >= radix) { break } ++this$1.pos; total = total * radix + val; } if (this.pos === start || len != null && this.pos - start !== len) { return null } return total }; pp$8.readRadixNumber = function(radix) { this.pos += 2; // 0x var val = this.readInt(radix); if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); } if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); } return this.finishToken(types.num, val) }; // Read an integer, octal integer, or floating-point number. pp$8.readNumber = function(startsWithDot) { var start = this.pos; if (!startsWithDot && this.readInt(10) === null) { this.raise(start, "Invalid number"); } var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48; if (octal && this.strict) { this.raise(start, "Invalid number"); } if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; } var next = this.input.charCodeAt(this.pos); if (next === 46 && !octal) { // '.' ++this.pos; this.readInt(10); next = this.input.charCodeAt(this.pos); } if ((next === 69 || next === 101) && !octal) { // 'eE' next = this.input.charCodeAt(++this.pos); if (next === 43 || next === 45) { ++this.pos; } // '+-' if (this.readInt(10) === null) { this.raise(start, "Invalid number"); } } if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); } var str = this.input.slice(start, this.pos); var val = octal ? parseInt(str, 8) : parseFloat(str); return this.finishToken(types.num, val) }; // Read a string value, interpreting backslash-escapes. pp$8.readCodePoint = function() { var ch = this.input.charCodeAt(this.pos), code; if (ch === 123) { // '{' if (this.options.ecmaVersion < 6) { this.unexpected(); } var codePos = ++this.pos; code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos); ++this.pos; if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); } } else { code = this.readHexChar(4); } return code }; function codePointToString(code) { // UTF-16 Decoding if (code <= 0xFFFF) { return String.fromCharCode(code) } code -= 0x10000; return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00) } pp$8.readString = function(quote) { var this$1 = this; var out = "", chunkStart = ++this.pos; for (;;) { if (this$1.pos >= this$1.input.length) { this$1.raise(this$1.start, "Unterminated string constant"); } var ch = this$1.input.charCodeAt(this$1.pos); if (ch === quote) { break } if (ch === 92) { // '\' out += this$1.input.slice(chunkStart, this$1.pos); out += this$1.readEscapedChar(false); chunkStart = this$1.pos; } else { if (isNewLine(ch, this$1.options.ecmaVersion >= 10)) { this$1.raise(this$1.start, "Unterminated string constant"); } ++this$1.pos; } } out += this.input.slice(chunkStart, this.pos++); return this.finishToken(types.string, out) }; // Reads template string tokens. var INVALID_TEMPLATE_ESCAPE_ERROR = {}; pp$8.tryReadTemplateToken = function() { this.inTemplateElement = true; try { this.readTmplToken(); } catch (err) { if (err === INVALID_TEMPLATE_ESCAPE_ERROR) { this.readInvalidTemplateToken(); } else { throw err } } this.inTemplateElement = false; }; pp$8.invalidStringToken = function(position, message) { if (this.inTemplateElement && this.options.ecmaVersion >= 9) { throw INVALID_TEMPLATE_ESCAPE_ERROR } else { this.raise(position, message); } }; pp$8.readTmplToken = function() { var this$1 = this; var out = "", chunkStart = this.pos; for (;;) { if (this$1.pos >= this$1.input.length) { this$1.raise(this$1.start, "Unterminated template"); } var ch = this$1.input.charCodeAt(this$1.pos); if (ch === 96 || ch === 36 && this$1.input.charCodeAt(this$1.pos + 1) === 123) { // '`', '${' if (this$1.pos === this$1.start && (this$1.type === types.template || this$1.type === types.invalidTemplate)) { if (ch === 36) { this$1.pos += 2; return this$1.finishToken(types.dollarBraceL) } else { ++this$1.pos; return this$1.finishToken(types.backQuote) } } out += this$1.input.slice(chunkStart, this$1.pos); return this$1.finishToken(types.template, out) } if (ch === 92) { // '\' out += this$1.input.slice(chunkStart, this$1.pos); out += this$1.readEscapedChar(true); chunkStart = this$1.pos; } else if (isNewLine(ch)) { out += this$1.input.slice(chunkStart, this$1.pos); ++this$1.pos; switch (ch) { case 13: if (this$1.input.charCodeAt(this$1.pos) === 10) { ++this$1.pos; } case 10: out += "\n"; break default: out += String.fromCharCode(ch); break } if (this$1.options.locations) { ++this$1.curLine; this$1.lineStart = this$1.pos; } chunkStart = this$1.pos; } else { ++this$1.pos; } } }; // Reads a template token to search for the end, without validating any escape sequences pp$8.readInvalidTemplateToken = function() { var this$1 = this; for (; this.pos < this.input.length; this.pos++) { switch (this$1.input[this$1.pos]) { case "\\": ++this$1.pos; break case "$": if (this$1.input[this$1.pos + 1] !== "{") { break } // falls through case "`": return this$1.finishToken(types.invalidTemplate, this$1.input.slice(this$1.start, this$1.pos)) // no default } } this.raise(this.start, "Unterminated template"); }; // Used to read escaped characters pp$8.readEscapedChar = function(inTemplate) { var ch = this.input.charCodeAt(++this.pos); ++this.pos; switch (ch) { case 110: return "\n" // 'n' -> '\n' case 114: return "\r" // 'r' -> '\r' case 120: return String.fromCharCode(this.readHexChar(2)) // 'x' case 117: return codePointToString(this.readCodePoint()) // 'u' case 116: return "\t" // 't' -> '\t' case 98: return "\b" // 'b' -> '\b' case 118: return "\u000b" // 'v' -> '\u000b' case 102: return "\f" // 'f' -> '\f' case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n' case 10: // ' \n' if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; } return "" default: if (ch >= 48 && ch <= 55) { var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0]; var octal = parseInt(octalStr, 8); if (octal > 255) { octalStr = octalStr.slice(0, -1); octal = parseInt(octalStr, 8); } this.pos += octalStr.length - 1; ch = this.input.charCodeAt(this.pos); if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) { this.invalidStringToken( this.pos - 1 - octalStr.length, inTemplate ? "Octal literal in template string" : "Octal literal in strict mode" ); } return String.fromCharCode(octal) } if (isNewLine(ch)) { // Unicode new line characters after \ get removed from output in both // template literals and strings return "" } return String.fromCharCode(ch) } }; // Used to read character escape sequences ('\x', '\u', '\U'). pp$8.readHexChar = function(len) { var codePos = this.pos; var n = this.readInt(16, len); if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); } return n }; // Read an identifier, and return it as a string. Sets `this.containsEsc` // to whether the word contained a '\u' escape. // // Incrementally adds only escaped chars, adding other chunks as-is // as a micro-optimization. pp$8.readWord1 = function() { var this$1 = this; this.containsEsc = false; var word = "", first = true, chunkStart = this.pos; var astral = this.options.ecmaVersion >= 6; while (this.pos < this.input.length) { var ch = this$1.fullCharCodeAtPos(); if (isIdentifierChar(ch, astral)) { this$1.pos += ch <= 0xffff ? 1 : 2; } else if (ch === 92) { // "\" this$1.containsEsc = true; word += this$1.input.slice(chunkStart, this$1.pos); var escStart = this$1.pos; if (this$1.input.charCodeAt(++this$1.pos) !== 117) // "u" { this$1.invalidStringToken(this$1.pos, "Expecting Unicode escape sequence \\uXXXX"); } ++this$1.pos; var esc = this$1.readCodePoint(); if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) { this$1.invalidStringToken(escStart, "Invalid Unicode escape"); } word += codePointToString(esc); chunkStart = this$1.pos; } else { break } first = false; } return word + this.input.slice(chunkStart, this.pos) }; // Read an identifier or keyword token. Will check for reserved // words when necessary. pp$8.readWord = function() { var word = this.readWord1(); var type = types.name; if (this.keywords.test(word)) { if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword " + word); } type = keywords$1[word]; } return this.finishToken(type, word) }; // Acorn is a tiny, fast JavaScript parser written in JavaScript. // // Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and // various contributors and released under an MIT license. // // Git repositories for Acorn are available at // // http://marijnhaverbeke.nl/git/acorn // https://github.com/acornjs/acorn.git // // Please use the [github bug tracker][ghbt] to report issues. // // [ghbt]: https://github.com/acornjs/acorn/issues // // [walk]: util/walk.js var version = "6.1.1"; // The main exported interface (under `self.acorn` when in the // browser) is a `parse` function that takes a code string and // returns an abstract syntax tree as specified by [Mozilla parser // API][api]. // // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API function parse(input, options) { return Parser.parse(input, options) } // This function tries to parse a single expression at a given // offset in a string. Useful for parsing mixed-language formats // that embed JavaScript expressions. function parseExpressionAt(input, pos, options) { return Parser.parseExpressionAt(input, pos, options) } // Acorn is organized as a tokenizer and a recursive-descent parser. // The `tokenizer` export provides an interface to the tokenizer. function tokenizer(input, options) { return Parser.tokenizer(input, options) } var acorn = /*#__PURE__*/Object.freeze({ version: version, parse: parse, parseExpressionAt: parseExpressionAt, tokenizer: tokenizer, Parser: Parser, defaultOptions: defaultOptions, Position: Position, SourceLocation: SourceLocation, getLineInfo: getLineInfo, Node: Node, TokenType: TokenType, tokTypes: types, keywordTypes: keywords$1, TokContext: TokContext, tokContexts: types$1, isIdentifierChar: isIdentifierChar, isIdentifierStart: isIdentifierStart, Token: Token, isNewLine: isNewLine, lineBreak: lineBreak, lineBreakG: lineBreakG, nonASCIIwhitespace: nonASCIIwhitespace }); function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x.default : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } function getCjsExportFromNamespace (n) { return n && n.default || n; } var _acorn = getCjsExportFromNamespace(acorn); var lib = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.DynamicImportKey = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function () { function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } return get; }(); exports['default'] = dynamicImport; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint-disable no-underscore-dangle */ var DynamicImportKey = exports.DynamicImportKey = 'Import'; // NOTE: This allows `yield import()` to parse correctly. _acorn.tokTypes._import.startsExpr = true; function parseDynamicImport() { var node = this.startNode(); this.next(); if (this.type !== _acorn.tokTypes.parenL) { this.unexpected(); } return this.finishNode(node, DynamicImportKey); } function parenAfter() { return (/^(\s|\/\/.*|\/\*[^]*?\*\/)*\(/.test(this.input.slice(this.pos)) ); } function dynamicImport(Parser) { return function (_Parser) { _inherits(_class, _Parser); function _class() { _classCallCheck(this, _class); return _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).apply(this, arguments)); } _createClass(_class, [{ key: 'parseStatement', value: function () { function parseStatement(context, topLevel, exports) { if (this.type === _acorn.tokTypes._import && parenAfter.call(this)) { return this.parseExpressionStatement(this.startNode(), this.parseExpression()); } return _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'parseStatement', this).call(this, context, topLevel, exports); } return parseStatement; }() }, { key: 'parseExprAtom', value: function () { function parseExprAtom(refDestructuringErrors) { if (this.type === _acorn.tokTypes._import) { return parseDynamicImport.call(this); } return _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'parseExprAtom', this).call(this, refDestructuringErrors); } return parseExprAtom; }() }]); return _class; }(Parser); } }); var dynamicImport = unwrapExports(lib); var lib_1 = lib.DynamicImportKey; const Parser$1 = Parser.extend(dynamicImport); const parse$1 = (source) => Parser$1.parse(source, { sourceType: 'module', ecmaVersion: 9, preserveParens: true }); const parse_expression_at = (source, index) => Parser$1.parseExpressionAt(source, index, { ecmaVersion: 9, preserveParens: true }); const literals = new Map([['true', true], ['false', false], ['null', null]]); function read_expression(parser) { const start = parser.index; const name = parser.read_until(/\s*}/); if (name && /^[a-z]+$/.test(name)) { const end = start + name.length; if (literals.has(name)) { return { type: 'Literal', start, end, value: literals.get(name), raw: name, }; } return { type: 'Identifier', start, end: start + name.length, name, }; } parser.index = start; try { const node = parse_expression_at(parser.template, parser.index); parser.index = node.end; return node; } catch (err) { parser.acorn_error(err); } } function repeat(str, i) { let result = ''; while (i--) result += str; return result; } const script_closing_tag = '</script>'; function get_context(parser, attributes, start) { const context = attributes.find(attribute => attribute.name === 'context'); if (!context) return 'default'; if (context.value.length !== 1 || context.value[0].type !== 'Text') { parser.error({ code: 'invalid-script', message: `context attribute must be static` }, start); } const value = context.value[0].data; if (value !== 'module') { parser.error({ code: `invalid-script`, message: `If the context attribute is supplied, its value must be "module"` }, context.start); } return value; } function read_script(parser, start, attributes) { const script_start = parser.index; const script_end = parser.template.indexOf(script_closing_tag, script_start); if (script_end === -1) parser.error({ code: `unclosed-script`, message: `<script> must have a closing tag` }); const source = repeat(' ', script_start) + parser.template.slice(script_start, script_end); parser.index = script_end + script_closing_tag.length; let ast; try { ast = parse$1(source); } catch (err) { parser.acorn_error(err); } ast.start = script_start; return { start, end: parser.index, context: get_context(parser, attributes, start), content: ast, }; } var MAX_LINE_LENGTH = 100; var OFFSET_CORRECTION = 60; var TAB_REPLACEMENT = ' '; function sourceFragment(error, extraLines) { function processLines(start, end) { return lines.slice(start, end).map(function(line, idx) { var num = String(start + idx + 1); while (num.length < maxNumLength) { num = ' ' + num; } return num + ' |' + line; }).join('\n'); } var lines = error.source.split(/\n|\r\n?|\f/); var line = error.line; var column = error.column; var startLine = Math.max(1, line - extraLines) - 1; var endLine = Math.min(line + extraLines, lines.length + 1); var maxNumLength = Math.max(4, String(endLine).length) + 1; var cutLeft = 0; // correct column according to replaced tab before column column += (TAB_REPLACEMENT.length - 1) * (lines[line - 1].substr(0, column - 1).match(/\t/g) || []).length; if (column > MAX_LINE_LENGTH) { cutLeft = column - OFFSET_CORRECTION + 3; column = OFFSET_CORRECTION - 2; } for (var i = startLine; i <= endLine; i++) { if (i >= 0 && i < lines.length) { lines[i] = lines[i].replace(/\t/g, TAB_REPLACEMENT); lines[i] = (cutLeft > 0 && lines[i].length > cutLeft ? '\u2026' : '') + lines[i].substr(cutLeft, MAX_LINE_LENGTH - 2) + (lines[i].length > cutLeft + MAX_LINE_LENGTH - 1 ? '\u2026' : ''); } } return [ processLines(startLine, line), new Array(column + maxNumLength + 2).join('-') + '^', processLines(line, endLine) ].join('\n'); } var CssSyntaxError = function(message, source, offset, line, column) { // some VMs prevent setting line/column otherwise (iOS Safari 10 even throw an exception) var error = Object.create(SyntaxError.prototype); error.name = 'CssSyntaxError'; error.message = message; error.stack = (new Error().stack || '').replace(/^.+\n/, error.name + ': ' + error.message + '\n'); error.source = source; error.offset = offset; error.line = line; error.column = column; error.sourceFragment = function(extraLines) { return sourceFragment(error, isNaN(extraLines) ? 0 : extraLines); }; Object.defineProperty(error, 'formattedMessage', { get: function() { return ( 'Parse error: ' + error.message + '\n' + sourceFragment(error, 2) ); } }); // for backward capability error.parseError = { offset: offset, line: line, column: column }; return error; }; var error = CssSyntaxError; // token types (note: value shouldn't intersect with used char codes) var WHITESPACE = 1; var IDENTIFIER = 2; var NUMBER = 3; var STRING = 4; var COMMENT = 5; var PUNCTUATOR = 6; var CDO = 7; var CDC = 8; var ATRULE = 14; var FUNCTION = 15; var URL = 16; var RAW = 17; var TAB = 9; var N = 10; var F = 12; var R = 13; var SPACE = 32; var TYPE = { WhiteSpace: WHITESPACE, Identifier: IDENTIFIER, Number: NUMBER, String: STRING, Comment: COMMENT, Punctuator: PUNCTUATOR, CDO: CDO, CDC: CDC, Atrule: ATRULE, Function: FUNCTION, Url: URL, Raw: RAW, ExclamationMark: 33, // ! QuotationMark: 34, // " NumberSign: 35, // # DollarSign: 36, // $ PercentSign: 37, // % Ampersand: 38, // & Apostrophe: 39, // ' LeftParenthesis: 40, // ( RightParenthesis: 41, // ) Asterisk: 42, // * PlusSign: 43, // + Comma: 44, // , HyphenMinus: 45, // - FullStop: 46, // . Solidus: 47, // / Colon: 58, // : Semicolon: 59, // ; LessThanSign: 60, // < EqualsSign: 61, // = GreaterThanSign: 62, // > QuestionMark: 63, // ? CommercialAt: 64, // @ LeftSquareBracket: 91, // [ Backslash: 92, // \ RightSquareBracket: 93, // ] CircumflexAccent: 94, // ^ LowLine: 95, // _ GraveAccent: 96, // ` LeftCurlyBracket: 123, // { VerticalLine: 124, // | RightCurlyBracket: 125, // } Tilde: 126 // ~ }; var NAME = Object.keys(TYPE).reduce(function(result, key) { result[TYPE[key]] = key; return result; }, {}); // https://drafts.csswg.org/css-syntax/#tokenizer-definitions // > non-ASCII code point // > A code point with a value equal to or greater than U+0080 <control> // > name-start code point // > A letter, a non-ASCII code point, or U+005F LOW LINE (_). // > name code point // > A name-start code point, a digit, or U+002D HYPHEN-MINUS (-) // That means only ASCII code points has a special meaning and we a maps for 0..127 codes only var SafeUint32Array = typeof Uint32Array !== 'undefined' ? Uint32Array : Array; // fallback on Array when TypedArray is not supported var SYMBOL_TYPE = new SafeUint32Array(0x80); var PUNCTUATION = new SafeUint32Array(0x80); var STOP_URL_RAW = new SafeUint32Array(0x80); for (var i = 0; i < SYMBOL_TYPE.length; i++) { SYMBOL_TYPE[i] = IDENTIFIER; } // fill categories [ TYPE.ExclamationMark, // ! TYPE.QuotationMark, // " TYPE.NumberSign, // # TYPE.DollarSign, // $ TYPE.PercentSign, // % TYPE.Ampersand, // & TYPE.Apostrophe, // ' TYPE.LeftParenthesis, // ( TYPE.RightParenthesis, // ) TYPE.Asterisk, // * TYPE.PlusSign, // + TYPE.Comma, // , TYPE.HyphenMinus, // - TYPE.FullStop, // . TYPE.Solidus, // / TYPE.Colon, // : TYPE.Semicolon, // ; TYPE.LessThanSign, // < TYPE.EqualsSign, // = TYPE.GreaterThanSign, // > TYPE.QuestionMark, // ? TYPE.CommercialAt, // @ TYPE.LeftSquareBracket, // [ // TYPE.Backslash, // \ TYPE.RightSquareBracket, // ] TYPE.CircumflexAccent, // ^ // TYPE.LowLine, // _ TYPE.GraveAccent, // ` TYPE.LeftCurlyBracket, // { TYPE.VerticalLine, // | TYPE.RightCurlyBracket, // } TYPE.Tilde // ~ ].forEach(function(key) { SYMBOL_TYPE[Number(key)] = PUNCTUATOR; PUNCTUATION[Number(key)] = PUNCTUATOR; }); for (var i = 48; i <= 57; i++) { SYMBOL_TYPE[i] = NUMBER; } SYMBOL_TYPE[SPACE] = WHITESPACE; SYMBOL_TYPE[TAB] = WHITESPACE; SYMBOL_TYPE[N] = WHITESPACE; SYMBOL_TYPE[R] = WHITESPACE; SYMBOL_TYPE[F] = WHITESPACE; SYMBOL_TYPE[TYPE.Apostrophe] = STRING; SYMBOL_TYPE[TYPE.QuotationMark] = STRING; STOP_URL_RAW[SPACE] = 1; STOP_URL_RAW[TAB] = 1; STOP_URL_RAW[N] = 1; STOP_URL_RAW[R] = 1; STOP_URL_RAW[F] = 1; STOP_URL_RAW[TYPE.Apostrophe] = 1; STOP_URL_RAW[TYPE.QuotationMark] = 1; STOP_URL_RAW[TYPE.LeftParenthesis] = 1; STOP_URL_RAW[TYPE.RightParenthesis] = 1; // whitespace is punctuation ... PUNCTUATION[SPACE] = PUNCTUATOR; PUNCTUATION[TAB] = PUNCTUATOR; PUNCTUATION[N] = PUNCTUATOR; PUNCTUATION[R] = PUNCTUATOR; PUNCTUATION[F] = PUNCTUATOR; // ... hyper minus is not PUNCTUATION[TYPE.HyphenMinus] = 0; var _const = { TYPE: TYPE, NAME: NAME, SYMBOL_TYPE: SYMBOL_TYPE, PUNCTUATION: PUNCTUATION, STOP_URL_RAW: STOP_URL_RAW }; var PUNCTUATION$1 = _const.PUNCTUATION; var STOP_URL_RAW$1 = _const.STOP_URL_RAW; var TYPE$1 = _const.TYPE; var FULLSTOP = TYPE$1.FullStop; var PLUSSIGN = TYPE$1.PlusSign; var HYPHENMINUS = TYPE$1.HyphenMinus; var PUNCTUATOR$1 = TYPE$1.Punctuator; var TAB$1 = 9; var N$1 = 10; var F$1 = 12; var R$1 = 13; var SPACE$1 = 32; var BACK_SLASH = 92; var E = 101; // 'e'.charCodeAt(0) function firstCharOffset(source) { // detect BOM (https://en.wikipedia.org/wiki/Byte_order_mark) if (source.charCodeAt(0) === 0xFEFF || // UTF-16BE source.charCodeAt(0) === 0xFFFE) { // UTF-16LE return 1; } return 0; } function isHex(code) { return (code >= 48 && code <= 57) || // 0 .. 9 (code >= 65 && code <= 70) || // A .. F (code >= 97 && code <= 102); // a .. f } function isNumber(code) { return code >= 48 && code <= 57; } function isNewline(source, offset, code) { if (code === N$1 || code === F$1 || code === R$1) { if (code === R$1 && offset + 1 < source.length && source.charCodeAt(offset + 1) === N$1) { return 2; } return 1; } return 0; } function cmpChar(testStr, offset, referenceCode) { var code = testStr.charCodeAt(offset); // code.toLowerCase() if (code >= 65 && code <= 90) { code = code | 32; } return code === referenceCode; } function cmpStr(testStr, start, end, referenceStr) { if (end - start !== referenceStr.length) { return false; } if (start < 0 || end > testStr.length) { return false; } for (var i = start; i < end; i++) { var testCode = testStr.charCodeAt(i); var refCode = referenceStr.charCodeAt(i - start); // testStr[i].toLowerCase() if (testCode >= 65 && testCode <= 90) { testCode = testCode | 32; } if (testCode !== refCode) { return false; } } return true; } function endsWith(testStr, referenceStr) { return cmpStr(testStr, testStr.length - referenceStr.length, testStr.length, referenceStr); } function findLastNonSpaceLocation(scanner) { for (var i = scanner.source.length - 1; i >= 0; i--) { var code = scanner.source.charCodeAt(i); if (code !== SPACE$1 && code !== TAB$1 && code !== R$1 && code !== N$1 && code !== F$1) { break; } } return scanner.getLocation(i + 1); } function findWhiteSpaceEnd(source, offset) { for (; offset < source.length; offset++) { var code = source.charCodeAt(offset); if (code !== SPACE$1 && code !== TAB$1 && code !== R$1 && code !== N$1 && code !== F$1) { break; } } return offset; } function findCommentEnd(source, offset) { var commentEnd = source.indexOf('*/', offset); if (commentEnd === -1) { return source.length; } return commentEnd + 2; } function findStringEnd(source, offset, quote) { for (; offset < source.length; offset++) { var code = source.charCodeAt(offset); // TODO: bad string if (code === BACK_SLASH) { offset++; } else if (code === quote) { offset++; break; } } return offset; } function findDecimalNumberEnd(source, offset) { for (; offset < source.length; offset++) { var code = source.charCodeAt(offset); if (code < 48 || code > 57) { // not a 0 .. 9 break; } } return offset; } function findNumberEnd(source, offset, allowFraction) { var code; offset = findDecimalNumberEnd(source, offset); // fraction: .\d+ if (allowFraction && offset + 1 < source.length && source.charCodeAt(offset) === FULLSTOP) { code = source.charCodeAt(offset + 1); if (isNumber(code)) { offset = findDecimalNumberEnd(source, offset + 1); } } // exponent: e[+-]\d+ if (offset + 1 < source.length) { if ((source.charCodeAt(offset) | 32) === E) { // case insensitive check for `e` code = source.charCodeAt(offset + 1); if (code === PLUSSIGN || code === HYPHENMINUS) { if (offset + 2 < source.length) { code = source.charCodeAt(offset + 2); } } if (isNumber(code)) { offset = findDecimalNumberEnd(source, offset + 2); } } } return offset; } // skip escaped unicode sequence that can ends with space // [0-9a-f]{1,6}(\r\n|[ \n\r\t\f])? function findEscaseEnd(source, offset) { for (var i = 0; i < 7 && offset + i < source.length; i++) { var code = source.charCodeAt(offset + i); if (i !== 6 && isHex(code)) { continue; } if (i > 0) { offset += i - 1 + isNewline(source, offset + i, code); if (code === SPACE$1 || code === TAB$1) { offset++; } } break; } return offset; } function findIdentifierEnd(source, offset) { for (; offset < source.length; offset++) { var code = source.charCodeAt(offset); if (code === BACK_SLASH) { offset = findEscaseEnd(source, offset + 1); } else if (code < 0x80 && PUNCTUATION$1[code] === PUNCTUATOR$1) { break; } } return offset; } function findUrlRawEnd(source, offset) { for (; offset < source.length; offset++) { var code = source.charCodeAt(offset); if (code === BACK_SLASH) { offset = findEscaseEnd(source, offset + 1); } else if (code < 0x80 && STOP_URL_RAW$1[code] === 1) { break; } } return offset; } var utils = { firstCharOffset: firstCharOffset, isHex: isHex, isNumber: isNumber, isNewline: isNewline, cmpChar: cmpChar, cmpStr: cmpStr, endsWith: endsWith, findLastNonSpaceLocation: findLastNonSpaceLocation, findWhiteSpaceEnd: findWhiteSpaceEnd, findCommentEnd: findCommentEnd, findStringEnd: findStringEnd, findDecimalNumberEnd: findDecimalNumberEnd, findNumberEnd: findNumberEnd, findEscaseEnd: findEscaseEnd, findIdentifierEnd: findIdentifierEnd, findUrlRawEnd: findUrlRawEnd }; var TYPE$2 = _const.TYPE; var NAME$1 = _const.NAME; var SYMBOL_TYPE$1 = _const.SYMBOL_TYPE; var firstCharOffset$1 = utils.firstCharOffset; var cmpStr$1 = utils.cmpStr; var isNumber$1 = utils.isNumber; var findLastNonSpaceLocation$1 = utils.findLastNonSpaceLocation; var findWhiteSpaceEnd$1 = utils.findWhiteSpaceEnd; var findCommentEnd$1 = utils.findCommentEnd; var findStringEnd$1 = utils.findStringEnd; var findNumberEnd$1 = utils.findNumberEnd; var findIdentifierEnd$1 = utils.findIdentifierEnd; var findUrlRawEnd$1 = utils.findUrlRawEnd; var NULL = 0; var WHITESPACE$1 = TYPE$2.WhiteSpace; var IDENTIFIER$1 = TYPE$2.Identifier; var NUMBER$1 = TYPE$2.Number; var STRING$1 = TYPE$2.String; var COMMENT$1 = TYPE$2.Comment; var PUNCTUATOR$2 = TYPE$2.Punctuator; var CDO$1 = TYPE$2.CDO; var CDC$1 = TYPE$2.CDC; var ATRULE$1 = TYPE$2.Atrule; var FUNCTION$1 = TYPE$2.Function; var URL$1 = TYPE$2.Url; var RAW$1 = TYPE$2.Raw; var N$2 = 10; var F$2 = 12; var R$2 = 13; var STAR = TYPE$2.Asterisk; var SLASH = TYPE$2.Solidus; var FULLSTOP$1 = TYPE$2.FullStop; var PLUSSIGN$1 = TYPE$2.PlusSign; var HYPHENMINUS$1 = TYPE$2.HyphenMinus; var GREATERTHANSIGN = TYPE$2.GreaterThanSign; var LESSTHANSIGN = TYPE$2.LessThanSign; var EXCLAMATIONMARK = TYPE$2.ExclamationMark; var COMMERCIALAT = TYPE$2.CommercialAt; var QUOTATIONMARK = TYPE$2.QuotationMark; var APOSTROPHE = TYPE$2.Apostrophe; var LEFTPARENTHESIS = TYPE$2.LeftParenthesis; var RIGHTPARENTHESIS = TYPE$2.RightParenthesis; var LEFTCURLYBRACKET = TYPE$2.LeftCurlyBracket; var RIGHTCURLYBRACKET = TYPE$2.RightCurlyBracket; var LEFTSQUAREBRACKET = TYPE$2.LeftSquareBracket; var RIGHTSQUAREBRACKET = TYPE$2.RightSquareBracket; var MIN_BUFFER_SIZE = 16 * 1024; var OFFSET_MASK = 0x00FFFFFF; var TYPE_SHIFT = 24; var SafeUint32Array$1 = typeof Uint32Array !== 'undefined' ? Uint32Array : Array; // fallback on Array when TypedArray is not supported function computeLinesAndColumns(tokenizer, source) { var sourceLength = source.length; var start = firstCharOffset$1(source); var lines = tokenizer.lines; var line = tokenizer.startLine; var columns = tokenizer.columns; var column = tokenizer.startColumn; if (lines === null || lines.length < sourceLength + 1) { lines = new SafeUint32Array$1(Math.max(sourceLength + 1024, MIN_BUFFER_SIZE)); columns = new SafeUint32Array$1(lines.length); } for (var i = start; i < sourceLength; i++) { var code = source.charCodeAt(i); lines[i] = line; columns[i] = column++; if (code === N$2 || code === R$2 || code === F$2) { if (code === R$2 && i + 1 < sourceLength && source.charCodeAt(i + 1) === N$2) { i++; lines[i] = line; columns[i] = column; } line++; column = 1; } } lines[i] = line; columns[i] = column; tokenizer.linesAnsColumnsComputed = true; tokenizer.lines = lines; tokenizer.columns = columns; } function tokenLayout(tokenizer, source, startPos) { var sourceLength = source.length; var offsetAndType = tokenizer.offsetAndType; var balance = tokenizer.balance; var tokenCount = 0; var prevType = 0; var offset = startPos; var anchor = 0; var balanceCloseCode = 0; var balanceStart = 0; var balancePrev = 0; if (offsetAndType === null || offsetAndType.length < sourceLength + 1) { offsetAndType = new SafeUint32Array$1(sourceLength + 1024); balance = new SafeUint32Array$1(sourceLength + 1024); } while (offset < sourceLength) { var code = source.charCodeAt(offset); var type = code < 0x80 ? SYMBOL_TYPE$1[code] : IDENTIFIER$1; balance[tokenCount] = sourceLength; switch (type) { case WHITESPACE$1: offset = findWhiteSpaceEnd$1(source, offset + 1); break; case PUNCTUATOR$2: switch (code) { case balanceCloseCode: balancePrev = balanceStart & OFFSET_MASK; balanceStart = balance[balancePrev]; balanceCloseCode = balanceStart >> TYPE_SHIFT; balance[tokenCount] = balancePrev; balance[balancePrev++] = tokenCount; for (; balancePrev < tokenCount; balancePrev++) { if (balance[balancePrev] === sourceLength) { balance[balancePrev] = tokenCount; } } break; case LEFTSQUAREBRACKET: balance[tokenCount] = balanceStart; balanceCloseCode = RIGHTSQUAREBRACKET; balanceStart = (balanceCloseCode << TYPE_SHIFT) | tokenCount; break; case LEFTCURLYBRACKET: balance[tokenCount] = balanceStart; balanceCloseCode = RIGHTCURLYBRACKET; balanceStart = (balanceCloseCode << TYPE_SHIFT) | tokenCount; break; case LEFTPARENTHESIS: balance[tokenCount] = balanceStart; balanceCloseCode = RIGHTPARENTHESIS; balanceStart = (balanceCloseCode << TYPE_SHIFT) | tokenCount; break; } // /* if (code === STAR && prevType === SLASH) { type = COMMENT$1; offset = findCommentEnd$1(source, offset + 1); tokenCount--; // rewrite prev token break; } // edge case for -.123 and +.123 if (code === FULLSTOP$1 && (prevType === PLUSSIGN$1 || prevType === HYPHENMINUS$1)) { if (offset + 1 < sourceLength && isNumber$1(source.charCodeAt(offset + 1))) { type = NUMBER$1; offset = findNumberEnd$1(source, offset + 2, false); tokenCount--; // rewrite prev token break; } } // <!-- if (code === EXCLAMATIONMARK && prevType === LESSTHANSIGN) { if (offset + 2 < sourceLength && source.charCodeAt(offset + 1) === HYPHENMINUS$1 && source.charCodeAt(offset + 2) === HYPHENMINUS$1) { type = CDO$1; offset = offset + 3; tokenCount--; // rewrite prev token break; } } // --> if (code === HYPHENMINUS$1 && prevType === HYPHENMINUS$1) { if (offset + 1 < sourceLength && source.charCodeAt(offset + 1) === GREATERTHANSIGN) { type = CDC$1; offset = offset + 2; tokenCount--; // rewrite prev token break; } } // ident( if (code === LEFTPARENTHESIS && prevType === IDENTIFIER$1) { offset = offset + 1; tokenCount--; // rewrite prev token balance[tokenCount] = balance[tokenCount + 1]; balanceStart--; // 4 char length identifier and equal to `url(` (case insensitive) if (offset - anchor === 4 && cmpStr$1(source, anchor, offset, 'url(')) { // special case for url() because it can contain any symbols sequence with few exceptions anchor = findWhiteSpaceEnd$1(source, offset); code = source.charCodeAt(anchor); if (code !== LEFTPARENTHESIS && code !== RIGHTPARENTHESIS && code !== QUOTATIONMARK && code !== APOSTROPHE) { // url( offsetAndType[tokenCount++] = (URL$1 << TYPE_SHIFT) | offset; balance[tokenCount] = sourceLength; // ws* if (anchor !== offset) { offsetAndType[tokenCount++] = (WHITESPACE$1 << TYPE_SHIFT) | anchor; balance[tokenCount] = sourceLength; } // raw type = RAW$1; offset = findUrlRawEnd$1(source, anchor); } else { type = URL$1; } } else { type = FUNCTION$1; } break; } type = code; offset = offset + 1; break; case NUMBER$1: offset = findNumberEnd$1(source, offset + 1, prevType !== FULLSTOP$1); // merge number with a preceding dot, dash or plus if (prevType === FULLSTOP$1 || prevType === HYPHENMINUS$1 || prevType === PLUSSIGN$1) { tokenCount--; // rewrite prev token } break; case STRING$1: offset = findStringEnd$1(source, offset + 1, code); break; default: anchor = offset; offset = findIdentifierEnd$1(source, offset); // merge identifier with a preceding dash if (prevType === HYPHENMINUS$1) { // rewrite prev token tokenCount--; // restore prev prev token type // for case @-prefix-ident prevType = tokenCount === 0 ? 0 : offsetAndType[tokenCount - 1] >> TYPE_SHIFT; } if (prevType === COMMERCIALAT) { // rewrite prev token and change type to <at-keyword-token> tokenCount--; type = ATRULE$1; } } offsetAndType[tokenCount++] = (type << TYPE_SHIFT) | offset; prevType = type; } // finalize arrays offsetAndType[tokenCount] = offset; balance[tokenCount] = sourceLength; while (balanceStart !== 0) { balancePrev = balanceStart & OFFSET_MASK; balanceStart = balance[balancePrev]; balance[balancePrev] = sourceLength; } tokenizer.offsetAndType = offsetAndType; tokenizer.tokenCount = tokenCount; tokenizer.balance = balance; } // // tokenizer // var Tokenizer = function(source, startOffset, startLine, startColumn) { this.offsetAndType = null; this.balance = null; this.lines = null; this.columns = null; this.setSource(source, startOffset, startLine, startColumn); }; Tokenizer.prototype = { setSource: function(source, startOffset, startLine, startColumn) { var safeSource = String(source || ''); var start = firstCharOffset$1(safeSource); this.source = safeSource; this.firstCharOffset = start; this.startOffset = typeof startOffset === 'undefined' ? 0 : startOffset; this.startLine = typeof startLine === 'undefined' ? 1 : startLine; this.startColumn = typeof startColumn === 'undefined' ? 1 : startColumn; this.linesAnsColumnsComputed = false; this.eof = false; this.currentToken = -1; this.tokenType = 0; this.tokenStart = start; this.tokenEnd = start; tokenLayout(this, safeSource, start); this.next(); }, lookupType: function(offset) { offset += this.currentToken; if (offset < this.tokenCount) { return this.offsetAndType[offset] >> TYPE_SHIFT; } return NULL; }, lookupNonWSType: function(offset) { offset += this.currentToken; for (var type; offset < this.tokenCount; offset++) { type = this.offsetAndType[offset] >> TYPE_SHIFT; if (type !== WHITESPACE$1) { return type; } } return NULL; }, lookupValue: function(offset, referenceStr) { offset += this.currentToken; if (offset < this.tokenCount) { return cmpStr$1( this.source, this.offsetAndType[offset - 1] & OFFSET_MASK, this.offsetAndType[offset] & OFFSET_MASK, referenceStr ); } return false; }, getTokenStart: function(tokenNum) { if (tokenNum === this.currentToken) { return this.tokenStart; } if (tokenNum > 0) { return tokenNum < this.tokenCount ? this.offsetAndType[tokenNum - 1] & OFFSET_MASK : this.offsetAndType[this.tokenCount] & OFFSET_MASK; } return this.firstCharOffset; }, getOffsetExcludeWS: function() { if (this.currentToken > 0) { if ((this.offsetAndType[this.currentToken - 1] >> TYPE_SHIFT) === WHITESPACE$1) { return this.currentToken > 1 ? this.offsetAndType[this.currentToken - 2] & OFFSET_MASK : this.firstCharOffset; } } return this.tokenStart; }, getRawLength: function(startToken, endTokenType1, endTokenType2, includeTokenType2) { var cursor = startToken; var balanceEnd; loop: for (; cursor < this.tokenCount; cursor++) { balanceEnd = this.balance[cursor]; // belance end points to offset before start if (balanceEnd < startToken) { break loop; } // check token is stop type switch (this.offsetAndType[cursor] >> TYPE_SHIFT) { case endTokenType1: break loop; case endTokenType2: if (includeTokenType2) { cursor++; } break loop; default: // fast forward to the end of balanced block if (this.balance[balanceEnd] === cursor) { cursor = balanceEnd; } } } return cursor - this.currentToken; }, getTokenValue: function() { return this.source.substring(this.tokenStart, this.tokenEnd); }, substrToCursor: function(start) { return this.source.substring(start, this.tokenStart); }, skipWS: function() { for (var i = this.currentToken, skipTokenCount = 0; i < this.tokenCount; i++, skipTokenCount++) { if ((this.offsetAndType[i] >> TYPE_SHIFT) !== WHITESPACE$1) { break; } } if (skipTokenCount > 0) { this.skip(skipTokenCount); } }, skipSC: function() { while (this.tokenType === WHITESPACE$1 || this.tokenType === COMMENT$1) { this.next(); } }, skip: function(tokenCount) { var next = this.currentToken + tokenCount; if (next < this.tokenCount) { this.currentToken = next; this.tokenStart = this.offsetAndType[next - 1] & OFFSET_MASK; next = this.offsetAndType[next]; this.tokenType = next >> TYPE_SHIFT; this.tokenEnd = next & OFFSET_MASK; } else { this.currentToken = this.tokenCount; this.next(); } }, next: function() { var next = this.currentToken + 1; if (next < this.tokenCount) { this.currentToken = next; this.tokenStart = this.tokenEnd; next = this.offsetAndType[next]; this.tokenType = next >> TYPE_SHIFT; this.tokenEnd = next & OFFSET_MASK; } else { this.currentToken = this.tokenCount; this.eof = true; this.tokenType = NULL; this.tokenStart = this.tokenEnd = this.source.length; } }, eat: function(tokenType) { if (this.tokenType !== tokenType) { var offset = this.tokenStart; var message = NAME$1[tokenType] + ' is expected'; // tweak message and offset if (tokenType === IDENTIFIER$1) { // when identifier is expected but there is a function or url if (this.tokenType === FUNCTION$1 || this.tokenType === URL$1) { offset = this.tokenEnd - 1; message += ' but function found'; } } else { // when test type is part of another token show error for current position + 1 // e.g. eat(HYPHENMINUS) will fail on "-foo", but pointing on "-" is odd if (this.source.charCodeAt(this.tokenStart) === tokenType) { offset = offset + 1; } } this.error(message, offset); } this.next(); }, eatNonWS: function(tokenType) { this.skipWS(); this.eat(tokenType); }, consume: function(tokenType) { var value = this.getTokenValue(); this.eat(tokenType); return value; }, consumeFunctionName: function() { var name = this.source.substring(this.tokenStart, this.tokenEnd - 1); this.eat(FUNCTION$1); return name; }, consumeNonWS: function(tokenType) { this.skipWS(); return this.consume(tokenType); }, expectIdentifier: function(name) { if (this.tokenType !== IDENTIFIER$1 || cmpStr$1(this.source, this.tokenStart, this.tokenEnd, name) === false) { this.error('Identifier `' + name + '` is expected'); } this.next(); }, getLocation: function(offset, filename) { if (!this.linesAnsColumnsComputed) { computeLinesAndColumns(this, this.source); } return { source: filename, offset: this.startOffset + offset, line: this.lines[offset], column: this.columns[offset] }; }, getLocationRange: function(start, end, filename) { if (!this.linesAnsColumnsComputed) { computeLinesAndColumns(this, this.source); } return { source: filename, start: { offset: this.startOffset + start, line: this.lines[start], column: this.columns[start] }, end: { offset: this.startOffset + end, line: this.lines[end], column: this.columns[end] } }; }, error: function(message, offset) { var location = typeof offset !== 'undefined' && offset < this.source.length ? this.getLocation(offset) : this.eof ? findLastNonSpaceLocation$1(this) : this.getLocation(this.tokenStart); throw new error( message || 'Unexpected input', this.source, location.offset, location.line, location.column ); }, dump: function() { var offset = 0; return Array.prototype.slice.call(this.offsetAndType, 0, this.tokenCount).map(function(item, idx) { var start = offset; var end = item & OFFSET_MASK; offset = end; return { idx: idx, type: NAME$1[item >> TYPE_SHIFT], chunk: this.source.substring(start, end), balance: this.balance[idx] }; }, this); } }; // extend with error class Tokenizer.CssSyntaxError = error; // extend tokenizer with constants Object.keys(_const).forEach(function(key) { Tokenizer[key] = _const[key]; }); // extend tokenizer with static methods from utils Object.keys(utils).forEach(function(key) { Tokenizer[key] = utils[key]; }); // warm up tokenizer to elimitate code branches that never execute // fix soft deoptimizations (insufficient type feedback) new Tokenizer('\n\r\r\n\f<!---->//""\'\'/*\r\n\f*/1a;.\\31\t\+2{url(a);func();+1.2e3 -.4e-5 .6e+7}').getLocation(); var Tokenizer_1 = Tokenizer; var tokenizer$1 = Tokenizer_1; // // item item item item // /------\ /------\ /------\ /------\ // | data | | data | | data | | data | // null <--+-prev |<---+-prev |<---+-prev |<---+-prev | // | next-+--->| next-+--->| next-+--->| next-+--> null // \------/ \------/ \------/ \------/ // ^ ^ // | list | // | /------\ | // \--------------+-head | | // | tail-+--------------/ // \------/ // function createItem(data) { return { prev: null, next: null, data: data }; } var cursors = null; var List = function() { this.cursor = null; this.head = null; this.tail = null; }; List.createItem = createItem; List.prototype.createItem = createItem; List.prototype.getSize = function() { var size = 0; var cursor = this.head; while (cursor) { size++; cursor = cursor.next; } return size; }; List.prototype.fromArray = function(array) { var cursor = null; this.head = null; for (var i = 0; i < array.length; i++) { var item = createItem(array[i]); if (cursor !== null) { cursor.next = item; } else { this.head = item; } item.prev = cursor; cursor = item; } this.tail = cursor; return this; }; List.prototype.toArray = function() { var cursor = this.head; var result = []; while (cursor) { result.push(cursor.data); cursor = cursor.next; } return result; }; List.prototype.toJSON = List.prototype.toArray; List.prototype.isEmpty = function() { return this.head === null; }; List.prototype.first = function() { return this.head && this.head.data; }; List.prototype.last = function() { return this.tail && this.tail.data; }; function allocateCursor(node, prev, next) { var cursor; if (cursors !== null) { cursor = cursors; cursors = cursors.cursor; cursor.prev = prev; cursor.next = next; cursor.cursor = node.cursor; } else { cursor = { prev: prev, next: next, cursor: node.cursor }; } node.cursor = cursor; return cursor; } function releaseCursor(node) { var cursor = node.cursor; node.cursor = cursor.cursor; cursor.prev = null; cursor.next = null; cursor.cursor = cursors; cursors = cursor; } List.prototype.each = function(fn, context) { var item; if (context === undefined) { context = this; } // push cursor var cursor = allocateCursor(this, null, this.head); while (cursor.next !== null) { item = cursor.next; cursor.next = item.next; fn.call(context, item.data, item, this); } // pop cursor releaseCursor(this); }; List.prototype.eachRight = function(fn, context) { var item; if (context === undefined) { context = this; } // push cursor var cursor = allocateCursor(this, this.tail, null); while (cursor.prev !== null) { item = cursor.prev; cursor.prev = item.prev; fn.call(context, item.data, item, this); } // pop cursor releaseCursor(this); }; List.prototype.nextUntil = function(start, fn, context) { if (start === null) { return; } var item; if (context === undefined) { context = this; } // push cursor var cursor = allocateCursor(this, null, start); while (cursor.next !== null) { item = cursor.next; cursor.next = item.next; if (fn.call(context, item.data, item, this)) { break; } } // pop cursor releaseCursor(this); }; List.prototype.prevUntil = function(start, fn, context) { if (start === null) { return; } var item; if (context === undefined) { context = this; } // push cursor var cursor = allocateCursor(this, start, null); while (cursor.prev !== null) { item = cursor.prev; cursor.prev = item.prev; if (fn.call(context, item.data, item, this)) { break; } } // pop cursor releaseCursor(this); }; List.prototype.some = function(fn, context) { var cursor = this.head; if (context === undefined) { context = this; } while (cursor !== null) { if (fn.call(context, cursor.data, cursor, this)) { return true; } cursor = cursor.next; } return false; }; List.prototype.map = function(fn, context) { var result = []; var cursor = this.head; if (context === undefined) { context = this; } while (cursor !== null) { result.push(fn.call(context, cursor.data, cursor, this)); cursor = cursor.next; } return result; }; List.prototype.clear = function() { this.head = null; this.tail = null; }; List.prototype.copy = function() { var result = new List(); var cursor = this.head; while (cursor !== null) { result.insert(createItem(cursor.data)); cursor = cursor.next; } return result; }; List.prototype.updateCursors = function(prevOld, prevNew, nextOld, nextNew) { var cursor = this.cursor; while (cursor !== null) { if (cursor.prev === prevOld) { cursor.prev = prevNew; } if (cursor.next === nextOld) { cursor.next = nextNew; } cursor = cursor.cursor; } }; List.prototype.prepend = function(item) { // head // ^ // item this.updateCursors(null, item, this.head, item); // insert to the beginning of the list if (this.head !== null) { // new item <- first item this.head.prev = item; // new item -> first item item.next = this.head; } else { // if list has no head, then it also has no tail // in this case tail points to the new item this.tail = item; } // head always points to new item this.head = item; return this; }; List.prototype.prependData = function(data) { return this.prepend(createItem(data)); }; List.prototype.append = function(item) { // tail // ^ // item this.updateCursors(this.tail, item, null, item); // insert to the ending of the list if (this.tail !== null) { // last item -> new item this.tail.next = item; // last item <- new item item.prev = this.tail; } else { // if list has no tail, then it also has no head // in this case head points to new item this.head = item; } // tail always points to new item this.tail = item; return this; }; List.prototype.appendData = function(data) { return this.append(createItem(data)); }; List.prototype.insert = function(item, before) { if (before !== undefined && before !== null) { // prev before // ^ // item this.updateCursors(before.prev, item, before, item); if (before.prev === null) { // insert to the beginning of list if (this.head !== before) { throw new Error('before doesn\'t belong to list'); } // since head points to before therefore list doesn't empty // no need to check tail this.head = item; before.prev = item; item.next = before; this.updateCursors(null, item); } else { // insert between two items before.prev.next = item; item.prev = before.prev; before.prev = item; item.next = before; } } else { this.append(item); } }; List.prototype.insertData = function(data, before) { this.insert(createItem(data), before); }; List.prototype.remove = function(item) { // item // ^ // prev next this.updateCursors(item, item.prev, item, item.next); if (item.prev !== null) { item.prev.next = item.next; } else { if (this.head !== item) { throw new Error('item doesn\'t belong to list'); } this.head = item.next; } if (item.next !== null) { item.next.prev = item.prev; } else { if (this.tail !== item) { throw new Error('item doesn\'t belong to list'); } this.tail = item.prev; } item.prev = null; item.next = null; return item; }; List.prototype.appendList = function(list) { // ignore empty lists if (list.head === null) { return; } this.updateCursors(this.tail, list.tail, null, list.head); // insert to end of the list if (this.tail !== null) { // if destination list has a tail, then it also has a head, // but head doesn't change // dest tail -> source head this.tail.next = list.head; // dest tail <- source head list.head.prev = this.tail; } else { // if list has no a tail, then it also has no a head // in this case points head to new item this.head = list.head; } // tail always start point to new item this.tail = list.tail; list.head = null; list.tail = null; }; List.prototype.insertList = function(list, before) { if (before !== undefined && before !== null) { // ignore empty lists if (list.head === null) { return; } this.updateCursors(before.prev, list.tail, before, list.head); // insert in the middle of dist list if (before.prev !== null) { // before.prev <-> list.head before.prev.next = list.head; list.head.prev = before.prev; } else { this.head = list.head; } before.prev = list.tail; list.tail.next = before; list.head = null; list.tail = null; } else { this.appendList(list); } }; List.prototype.replace = function(oldItem, newItemOrList) { if ('head' in newItemOrList) { this.insertList(newItemOrList, oldItem); } else { this.insert(newItemOrList, oldItem); } this.remove(oldItem); }; var list = List; var TYPE$3 = tokenizer$1.TYPE; var WHITESPACE$2 = TYPE$3.WhiteSpace; var COMMENT$2 = TYPE$3.Comment; var sequence = function readSequence(recognizer) { var children = new list(); var child = null; var context = { recognizer: recognizer, space: null, ignoreWS: false, ignoreWSAfter: false }; this.scanner.skipSC(); while (!this.scanner.eof) { switch (this.scanner.tokenType) { case COMMENT$2: this.scanner.next(); continue; case WHITESPACE$2: if (context.ignoreWS) { this.scanner.next(); } else { context.space = this.WhiteSpace(); } continue; } child = recognizer.getNode.call(this, context); if (child === undefined) { break; } if (context.space !== null) { children.appendData(context.space); context.space = null; } children.appendData(child); if (context.ignoreWSAfter) { context.ignoreWSAfter = false; context.ignoreWS = true; } else { context.ignoreWS = false; } } return children; }; var noop = function() {}; function createParseContext(name) { return function() { return this[name](); }; } function processConfig(config) { var parserConfig = { context: {}, scope: {}, atrule: {}, pseudo: {} }; if (config.parseContext) { for (var name in config.parseContext) { switch (typeof config.parseContext[name]) { case 'function': parserConfig.context[name] = config.parseContext[name]; break; case 'string': parserConfig.context[name] = createParseContext(config.parseContext[name]); break; } } } if (config.scope) { for (var name in config.scope) { parserConfig.scope[name] = config.scope[name]; } } if (config.atrule) { for (var name in config.atrule) { var atrule = config.atrule[name]; if (atrule.parse) { parserConfig.atrule[name] = atrule.parse; } } } if (config.pseudo) { for (var name in config.pseudo) { var pseudo = config.pseudo[name]; if (pseudo.parse) { parserConfig.pseudo[name] = pseudo.parse; } } } if (config.node) { for (var name in config.node) { parserConfig[name] = config.node[name].parse; } } return parserConfig; } var create = function createParser(config) { var parser = { scanner: new tokenizer$1(), filename: '<unknown>', needPositions: false, tolerant: false, onParseError: noop, parseAtruleExpression: true, parseSelector: true, parseValue: true, parseCustomProperty: false, readSequence: sequence, tolerantParse: function(consumer, fallback) { if (this.tolerant) { var start = this.scanner.currentToken; try { return consumer.call(this); } catch (e) { this.onParseError(e); return fallback.call(this, start); } } else { return consumer.call(this); } }, getLocation: function(start, end) { if (this.needPositions) { return this.scanner.getLocationRange( start, end, this.filename ); } return null; }, getLocationFromList: function(list) { if (this.needPositions) { return this.scanner.getLocationRange( list.head !== null ? list.first().loc.start.offset - this.scanner.startOffset : this.scanner.tokenStart, list.head !== null ? list.last().loc.end.offset - this.scanner.startOffset : this.scanner.tokenStart, this.filename ); } return null; } }; config = processConfig(config || {}); for (var key in config) { parser[key] = config[key]; } return function(source, options) { options = options || {}; var context = options.context || 'default'; var ast; parser.scanner.setSource(source, options.offset, options.line, options.column); parser.filename = options.filename || '<unknown>'; parser.needPositions = Boolean(options.positions); parser.tolerant = Boolean(options.tolerant); parser.onParseError = typeof options.onParseError === 'function' ? options.onParseError : noop; parser.parseAtruleExpression = 'parseAtruleExpression' in options ? Boolean(options.parseAtruleExpression) : true; parser.parseSelector = 'parseSelector' in options ? Boolean(options.parseSelector) : true; parser.parseValue = 'parseValue' in options ? Boolean(options.parseValue) : true; parser.parseCustomProperty = 'parseCustomProperty' in options ? Boolean(options.parseCustomProperty) : false; if (!parser.context.hasOwnProperty(context)) { throw new Error('Unknown context `' + context + '`'); } ast = parser.context[context].call(parser, options); if (!parser.scanner.eof) { parser.scanner.error(); } // console.log(JSON.stringify(ast, null, 4)); return ast; }; }; var cmpChar$1 = tokenizer$1.cmpChar; var TYPE$4 = tokenizer$1.TYPE; var IDENTIFIER$2 = TYPE$4.Identifier; var STRING$2 = TYPE$4.String; var NUMBER$2 = TYPE$4.Number; var FUNCTION$2 = TYPE$4.Function; var URL$2 = TYPE$4.Url; var NUMBERSIGN = TYPE$4.NumberSign; var LEFTPARENTHESIS$1 = TYPE$4.LeftParenthesis; var LEFTSQUAREBRACKET$1 = TYPE$4.LeftSquareBracket; var PLUSSIGN$2 = TYPE$4.PlusSign; var HYPHENMINUS$2 = TYPE$4.HyphenMinus; var COMMA = TYPE$4.Comma; var SOLIDUS = TYPE$4.Solidus; var ASTERISK = TYPE$4.Asterisk; var PERCENTSIGN = TYPE$4.PercentSign; var BACKSLASH = TYPE$4.Backslash; var U = 117; // 'u'.charCodeAt(0) var _default = function defaultRecognizer(context) { switch (this.scanner.tokenType) { case NUMBERSIGN: return this.HexColor(); case COMMA: context.space = null; context.ignoreWSAfter = true; return this.Operator(); case SOLIDUS: case ASTERISK: case PLUSSIGN$2: case HYPHENMINUS$2: return this.Operator(); case LEFTPARENTHESIS$1: return this.Parentheses(this.readSequence, context.recognizer); case LEFTSQUAREBRACKET$1: return this.Brackets(this.readSequence, context.recognizer); case STRING$2: return this.String(); case NUMBER$2: switch (this.scanner.lookupType(1)) { case PERCENTSIGN: return this.Percentage(); case IDENTIFIER$2: // edge case: number with folowing \0 and \9 hack shouldn't to be a Dimension if (cmpChar$1(this.scanner.source, this.scanner.tokenEnd, BACKSLASH)) { return this.Number(); } else { return this.Dimension(); } default: return this.Number(); } case FUNCTION$2: return this.Function(this.readSequence, context.recognizer); case URL$2: return this.Url(); case IDENTIFIER$2: // check for unicode range, it should start with u+ or U+ if (cmpChar$1(this.scanner.source, this.scanner.tokenStart, U) && cmpChar$1(this.scanner.source, this.scanner.tokenStart + 1, PLUSSIGN$2)) { return this.UnicodeRange(); } else { return this.Identifier(); } } }; var atruleExpression = { getNode: _default }; var TYPE$5 = tokenizer$1.TYPE; var IDENTIFIER$3 = TYPE$5.Identifier; var NUMBER$3 = TYPE$5.Number; var NUMBERSIGN$1 = TYPE$5.NumberSign; var LEFTSQUAREBRACKET$2 = TYPE$5.LeftSquareBracket; var PLUSSIGN$3 = TYPE$5.PlusSign; var SOLIDUS$1 = TYPE$5.Solidus; var ASTERISK$1 = TYPE$5.Asterisk; var FULLSTOP$2 = TYPE$5.FullStop; var COLON = TYPE$5.Colon; var GREATERTHANSIGN$1 = TYPE$5.GreaterThanSign; var VERTICALLINE = TYPE$5.VerticalLine; var TILDE = TYPE$5.Tilde; function getNode(context) { switch (this.scanner.tokenType) { case PLUSSIGN$3: case GREATERTHANSIGN$1: case TILDE: context.space = null; context.ignoreWSAfter = true; return this.Combinator(); case SOLIDUS$1: // /deep/ return this.Combinator(); case FULLSTOP$2: return this.ClassSelector(); case LEFTSQUAREBRACKET$2: return this.AttributeSelector(); case NUMBERSIGN$1: return this.IdSelector(); case COLON: if (this.scanner.lookupType(1) === COLON) { return this.PseudoElementSelector(); } else { return this.PseudoClassSelector(); } case IDENTIFIER$3: case ASTERISK$1: case VERTICALLINE: return this.TypeSelector(); case NUMBER$3: return this.Percentage(); } } var selector = { getNode: getNode }; // https://drafts.csswg.org/css-images-4/#element-notation // https://developer.mozilla.org/en-US/docs/Web/CSS/element var element = function() { this.scanner.skipSC(); var id = this.IdSelector(); this.scanner.skipSC(); return new list().appendData( id ); }; // legacy IE function // expression '(' raw ')' var expression = function() { return new list().appendData( this.Raw(this.scanner.currentToken, 0, 0, false, false) ); }; var TYPE$6 = tokenizer$1.TYPE; var IDENTIFIER$4 = TYPE$6.Identifier; var COMMA$1 = TYPE$6.Comma; var SEMICOLON = TYPE$6.Semicolon; var HYPHENMINUS$3 = TYPE$6.HyphenMinus; var EXCLAMATIONMARK$1 = TYPE$6.ExclamationMark; // var '(' ident (',' <value>? )? ')' var _var = function() { var children = new list(); this.scanner.skipSC(); var identStart = this.scanner.tokenStart; this.scanner.eat(HYPHENMINUS$3); if (this.scanner.source.charCodeAt(this.scanner.tokenStart) !== HYPHENMINUS$3) { this.scanner.error('HyphenMinus is expected'); } this.scanner.eat(IDENTIFIER$4); children.appendData({ type: 'Identifier', loc: this.getLocation(identStart, this.scanner.tokenStart), name: this.scanner.substrToCursor(identStart) }); this.scanner.skipSC(); if (this.scanner.tokenType === COMMA$1) { children.appendData(this.Operator()); children.appendData(this.parseCustomProperty ? this.Value(null) : this.Raw(this.scanner.currentToken, EXCLAMATIONMARK$1, SEMICOLON, false, false) ); } return children; }; var value = { getNode: _default, '-moz-element': element, 'element': element, 'expression': expression, 'var': _var }; var scope = { AtruleExpression: atruleExpression, Selector: selector, Value: value }; var fontFace = { parse: { expression: null, block: function() { return this.Block(this.Declaration); } } }; var TYPE$7 = tokenizer$1.TYPE; var STRING$3 = TYPE$7.String; var IDENTIFIER$5 = TYPE$7.Identifier; var URL$3 = TYPE$7.Url; var LEFTPARENTHESIS$2 = TYPE$7.LeftParenthesis; var _import = { parse: { expression: function() { var children = new list(); this.scanner.skipSC(); switch (this.scanner.tokenType) { case STRING$3: children.appendData(this.String()); break; case URL$3: children.appendData(this.Url()); break; default: this.scanner.error('String or url() is expected'); } if (this.scanner.lookupNonWSType(0) === IDENTIFIER$5 || this.scanner.lookupNonWSType(0) === LEFTPARENTHESIS$2) { children.appendData(this.WhiteSpace()); children.appendData(this.MediaQueryList()); } return children; }, block: null } }; var media = { parse: { expression: function() { return new list().appendData( this.MediaQueryList() ); }, block: function() { return this.Block(this.Rule); } } }; var TYPE$8 = tokenizer$1.TYPE; var LEFTCURLYBRACKET$1 = TYPE$8.LeftCurlyBracket; var page = { parse: { expression: function() { if (this.scanner.lookupNonWSType(0) === LEFTCURLYBRACKET$1) { return null; } return new list().appendData( this.SelectorList() ); }, block: function() { return this.Block(this.Declaration); } } }; var TYPE$9 = tokenizer$1.TYPE; var WHITESPACE$3 = TYPE$9.WhiteSpace; var COMMENT$3 = TYPE$9.Comment; var IDENTIFIER$6 = TYPE$9.Identifier; var FUNCTION$3 = TYPE$9.Function; var LEFTPARENTHESIS$3 = TYPE$9.LeftParenthesis; var HYPHENMINUS$4 = TYPE$9.HyphenMinus; var COLON$1 = TYPE$9.Colon; function consumeRaw() { return new list().appendData( this.Raw(this.scanner.currentToken, 0, 0, false, false) ); } function parentheses() { var index = 0; this.scanner.skipSC(); // TODO: make it simplier if (this.scanner.tokenType === IDENTIFIER$6) { index = 1; } else if (this.scanner.tokenType === HYPHENMINUS$4 && this.scanner.lookupType(1) === IDENTIFIER$6) { index = 2; } if (index !== 0 && this.scanner.lookupNonWSType(index) === COLON$1) { return new list().appendData( this.Declaration() ); } return readSequence.call(this); } function readSequence() { var children = new list(); var space = null; var child; this.scanner.skipSC(); scan: while (!this.scanner.eof) { switch (this.scanner.tokenType) { case WHITESPACE$3: space = this.WhiteSpace(); continue; case COMMENT$3: this.scanner.next(); continue; case FUNCTION$3: child = this.Function(consumeRaw, this.scope.AtruleExpression); break; case IDENTIFIER$6: child = this.Identifier(); break; case LEFTPARENTHESIS$3: child = this.Parentheses(parentheses, this.scope.AtruleExpression); break; default: break scan; } if (space !== null) { children.appendData(space); space = null; } children.appendData(child); } return children; } var supports = { parse: { expression: function() { var children = readSequence.call(this); if (children.isEmpty()) { this.scanner.error('Condition is expected'); } return children; }, block: function() { return this.Block(this.Rule); } } }; var atrule = { 'font-face': fontFace, 'import': _import, 'media': media, 'page': page, 'supports': supports }; var dir = { parse: function() { return new list().appendData( this.Identifier() ); } }; var has$1 = { parse: function() { return new list().appendData( this.SelectorList() ); } }; var lang = { parse: function() { return new list().appendData( this.Identifier() ); } }; var selectorList = { parse: function selectorList() { return new list().appendData( this.SelectorList() ); } }; var matches = selectorList; var not = selectorList; var ALLOW_OF_CLAUSE = true; var nthWithOfClause = { parse: function() { return new list().appendData( this.Nth(ALLOW_OF_CLAUSE) ); } }; var nthChild = nthWithOfClause; var nthLastChild = nthWithOfClause; var DISALLOW_OF_CLAUSE = false; var nth = { parse: function nth() { return new list().appendData( this.Nth(DISALLOW_OF_CLAUSE) ); } }; var nthLastOfType = nth; var nthOfType = nth; var slotted = { parse: function compoundSelector() { return new list().appendData( this.Selector() ); } }; var pseudo = { 'dir': dir, 'has': has$1, 'lang': lang, 'matches': matches, 'not': not, 'nth-child': nthChild, 'nth-last-child': nthLastChild, 'nth-last-of-type': nthLastOfType, 'nth-of-type': nthOfType, 'slotted': slotted }; var cmpChar$2 = tokenizer$1.cmpChar; var isNumber$2 = tokenizer$1.isNumber; var TYPE$a = tokenizer$1.TYPE; var IDENTIFIER$7 = TYPE$a.Identifier; var NUMBER$4 = TYPE$a.Number; var PLUSSIGN$4 = TYPE$a.PlusSign; var HYPHENMINUS$5 = TYPE$a.HyphenMinus; var N$3 = 110; // 'n'.charCodeAt(0) var DISALLOW_SIGN = true; var ALLOW_SIGN = false; function checkTokenIsInteger(scanner, disallowSign) { var pos = scanner.tokenStart; if (scanner.source.charCodeAt(pos) === PLUSSIGN$4 || scanner.source.charCodeAt(pos) === HYPHENMINUS$5) { if (disallowSign) { scanner.error(); } pos++; } for (; pos < scanner.tokenEnd; pos++) { if (!isNumber$2(scanner.source.charCodeAt(pos))) { scanner.error('Unexpected input', pos); } } } // An+B microsyntax https://www.w3.org/TR/css-syntax-3/#anb var AnPlusB = { name: 'AnPlusB', structure: { a: [String, null], b: [String, null] }, parse: function() { var start = this.scanner.tokenStart; var end = start; var prefix = ''; var a = null; var b = null; if (this.scanner.tokenType === NUMBER$4 || this.scanner.tokenType === PLUSSIGN$4) { checkTokenIsInteger(this.scanner, ALLOW_SIGN); prefix = this.scanner.getTokenValue(); this.scanner.next(); end = this.scanner.tokenStart; } if (this.scanner.tokenType === IDENTIFIER$7) { var bStart = this.scanner.tokenStart; if (cmpChar$2(this.scanner.source, bStart, HYPHENMINUS$5)) { if (prefix === '') { prefix = '-'; bStart++; } else { this.scanner.error('Unexpected hyphen minus'); } } if (!cmpChar$2(this.scanner.source, bStart, N$3)) { this.scanner.error(); } a = prefix === '' ? '1' : prefix === '+' ? '+1' : prefix === '-' ? '-1' : prefix; var len = this.scanner.tokenEnd - bStart; if (len > 1) { // ..n-.. if (this.scanner.source.charCodeAt(bStart + 1) !== HYPHENMINUS$5) { this.scanner.error('Unexpected input', bStart + 1); } if (len > 2) { // ..n-{number}.. this.scanner.tokenStart = bStart + 2; } else { // ..n- {number} this.scanner.next(); this.scanner.skipSC(); } checkTokenIsInteger(this.scanner, DISALLOW_SIGN); b = '-' + this.scanner.getTokenValue(); this.scanner.next(); end = this.scanner.tokenStart; } else { prefix = ''; this.scanner.next(); end = this.scanner.tokenStart; this.scanner.skipSC(); if (this.scanner.tokenType === HYPHENMINUS$5 || this.scanner.tokenType === PLUSSIGN$4) { prefix = this.scanner.getTokenValue(); this.scanner.next(); this.scanner.skipSC(); } if (this.scanner.tokenType === NUMBER$4) { checkTokenIsInteger(this.scanner, prefix !== ''); if (!isNumber$2(this.scanner.source.charCodeAt(this.scanner.tokenStart))) { prefix = this.scanner.source.charAt(this.scanner.tokenStart); this.scanner.tokenStart++; } if (prefix === '') { // should be an operator before number this.scanner.error(); } else if (prefix === '+') { // plus is using by default prefix = ''; } b = prefix + this.scanner.getTokenValue(); this.scanner.next(); end = this.scanner.tokenStart; } else { if (prefix) { this.scanner.eat(NUMBER$4); } } } } else { if (prefix === '' || prefix === '+') { // no number this.scanner.error( 'Number or identifier is expected', this.scanner.tokenStart + ( this.scanner.tokenType === PLUSSIGN$4 || this.scanner.tokenType === HYPHENMINUS$5 ) ); } b = prefix; } return { type: 'AnPlusB', loc: this.getLocation(start, end), a: a, b: b }; }, generate: function(processChunk, node) { var a = node.a !== null && node.a !== undefined; var b = node.b !== null && node.b !== undefined; if (a) { processChunk( node.a === '+1' ? '+n' : node.a === '1' ? 'n' : node.a === '-1' ? '-n' : node.a + 'n' ); if (b) { b = String(node.b); if (b.charAt(0) === '-' || b.charAt(0) === '+') { processChunk(b.charAt(0)); processChunk(b.substr(1)); } else { processChunk('+'); processChunk(b); } } } else { processChunk(String(node.b)); } } }; var TYPE$b = tokenizer$1.TYPE; var ATRULE$2 = TYPE$b.Atrule; var SEMICOLON$1 = TYPE$b.Semicolon; var LEFTCURLYBRACKET$2 = TYPE$b.LeftCurlyBracket; var RIGHTCURLYBRACKET$1 = TYPE$b.RightCurlyBracket; function isBlockAtrule() { for (var offset = 1, type; type = this.scanner.lookupType(offset); offset++) { if (type === RIGHTCURLYBRACKET$1) { return true; } if (type === LEFTCURLYBRACKET$2 || type === ATRULE$2) { return false; } } this.scanner.skip(offset); this.scanner.eat(RIGHTCURLYBRACKET$1); } var Atrule = { name: 'Atrule', structure: { name: String, expression: ['AtruleExpression', null], block: ['Block', null] }, parse: function() { var start = this.scanner.tokenStart; var name; var nameLowerCase; var expression = null; var block = null; this.scanner.eat(ATRULE$2); name = this.scanner.substrToCursor(start + 1); nameLowerCase = name.toLowerCase(); this.scanner.skipSC(); expression = this.AtruleExpression(name); // turn empty AtruleExpression into null if (expression.children.head === null) { expression = null; } this.scanner.skipSC(); if (this.atrule.hasOwnProperty(nameLowerCase)) { if (typeof this.atrule[nameLowerCase].block === 'function') { if (this.scanner.tokenType !== LEFTCURLYBRACKET$2) { // FIXME: make tolerant this.scanner.error('Curly bracket is expected'); } block = this.atrule[nameLowerCase].block.call(this); } else { if (!this.tolerant || !this.scanner.eof) { this.scanner.eat(SEMICOLON$1); } } } else { switch (this.scanner.tokenType) { case SEMICOLON$1: this.scanner.next(); break; case LEFTCURLYBRACKET$2: // TODO: should consume block content as Raw? block = this.Block(isBlockAtrule.call(this) ? this.Declaration : this.Rule); break; default: if (!this.tolerant) { this.scanner.error('Semicolon or block is expected'); } } } return { type: 'Atrule', loc: this.getLocation(start, this.scanner.tokenStart), name: name, expression: expression, block: block }; }, generate: function(processChunk, node) { processChunk('@'); processChunk(node.name); if (node.expression !== null) { processChunk(' '); this.generate(processChunk, node.expression); } if (node.block) { this.generate(processChunk, node.block); } else { processChunk(';'); } }, walkContext: 'atrule' }; var TYPE$c = tokenizer$1.TYPE; var SEMICOLON$2 = TYPE$c.Semicolon; var LEFTCURLYBRACKET$3 = TYPE$c.LeftCurlyBracket; function consumeRaw$1(startToken) { return new list().appendData( this.Raw(startToken, SEMICOLON$2, LEFTCURLYBRACKET$3, false, true) ); } function consumeDefaultSequence() { return this.readSequence(this.scope.AtruleExpression); } var AtruleExpression = { name: 'AtruleExpression', structure: { children: [[]] }, parse: function(name) { var children = null; var startToken = this.scanner.currentToken; if (name !== null) { name = name.toLowerCase(); } if (this.parseAtruleExpression) { // custom consumer if (this.atrule.hasOwnProperty(name)) { if (typeof this.atrule[name].expression === 'function') { children = this.tolerantParse(this.atrule[name].expression, consumeRaw$1); } } else { // default consumer this.scanner.skipSC(); children = this.tolerantParse(consumeDefaultSequence, consumeRaw$1); } if (this.tolerant) { if (this.scanner.eof || (this.scanner.tokenType !== SEMICOLON$2 && this.scanner.tokenType !== LEFTCURLYBRACKET$3)) { children = consumeRaw$1.call(this, startToken); } } } else { children = consumeRaw$1.call(this, startToken); } if (children === null) { children = new list(); } return { type: 'AtruleExpression', loc: this.getLocationFromList(children), children: children }; }, generate: function(processChunk, node) { this.each(processChunk, node); }, walkContext: 'atruleExpression' }; var TYPE$d = tokenizer$1.TYPE; var IDENTIFIER$8 = TYPE$d.Identifier; var STRING$4 = TYPE$d.String; var DOLLARSIGN = TYPE$d.DollarSign; var ASTERISK$2 = TYPE$d.Asterisk; var COLON$2 = TYPE$d.Colon; var EQUALSSIGN = TYPE$d.EqualsSign; var LEFTSQUAREBRACKET$3 = TYPE$d.LeftSquareBracket; var RIGHTSQUAREBRACKET$1 = TYPE$d.RightSquareBracket; var CIRCUMFLEXACCENT = TYPE$d.CircumflexAccent; var VERTICALLINE$1 = TYPE$d.VerticalLine; var TILDE$1 = TYPE$d.Tilde; function getAttributeName() { if (this.scanner.eof) { this.scanner.error('Unexpected end of input'); } var start = this.scanner.tokenStart; var expectIdentifier = false; var checkColon = true; if (this.scanner.tokenType === ASTERISK$2) { expectIdentifier = true; checkColon = false; this.scanner.next(); } else if (this.scanner.tokenType !== VERTICALLINE$1) { this.scanner.eat(IDENTIFIER$8); } if (this.scanner.tokenType === VERTICALLINE$1) { if (this.scanner.lookupType(1) !== EQUALSSIGN) { this.scanner.next(); this.scanner.eat(IDENTIFIER$8); } else if (expectIdentifier) { this.scanner.error('Identifier is expected', this.scanner.tokenEnd); } } else if (expectIdentifier) { this.scanner.error('Vertical line is expected'); } if (checkColon && this.scanner.tokenType === COLON$2) { this.scanner.next(); this.scanner.eat(IDENTIFIER$8); } return { type: 'Identifier', loc: this.getLocation(start, this.scanner.tokenStart), name: this.scanner.substrToCursor(start) }; } function getOperator() { var start = this.scanner.tokenStart; var tokenType = this.scanner.tokenType; if (tokenType !== EQUALSSIGN && // = tokenType !== TILDE$1 && // ~= tokenType !== CIRCUMFLEXACCENT && // ^= tokenType !== DOLLARSIGN && // $= tokenType !== ASTERISK$2 && // *= tokenType !== VERTICALLINE$1 // |= ) { this.scanner.error('Attribute selector (=, ~=, ^=, $=, *=, |=) is expected'); } if (tokenType === EQUALSSIGN) { this.scanner.next(); } else { this.scanner.next(); this.scanner.eat(EQUALSSIGN); } return this.scanner.substrToCursor(start); } // '[' S* attrib_name ']' // '[' S* attrib_name S* attrib_matcher S* [ IDENT | STRING ] S* attrib_flags? S* ']' var AttributeSelector = { name: 'AttributeSelector', structure: { name: 'Identifier', matcher: [String, null], value: ['String', 'Identifier', null], flags: [String, null] }, parse: function() { var start = this.scanner.tokenStart; var name; var matcher = null; var value = null; var flags = null; this.scanner.eat(LEFTSQUAREBRACKET$3); this.scanner.skipSC(); name = getAttributeName.call(this); this.scanner.skipSC(); if (this.scanner.tokenType !== RIGHTSQUAREBRACKET$1) { // avoid case `[name i]` if (this.scanner.tokenType !== IDENTIFIER$8) { matcher = getOperator.call(this); this.scanner.skipSC(); value = this.scanner.tokenType === STRING$4 ? this.String() : this.Identifier(); this.scanner.skipSC(); } // attribute flags if (this.scanner.tokenType === IDENTIFIER$8) { flags = this.scanner.getTokenValue(); this.scanner.next(); this.scanner.skipSC(); } } this.scanner.eat(RIGHTSQUAREBRACKET$1); return { type: 'AttributeSelector', loc: this.getLocation(start, this.scanner.tokenStart), name: name, matcher: matcher, value: value, flags: flags }; }, generate: function(processChunk, node) { var flagsPrefix = ' '; processChunk('['); this.generate(processChunk, node.name); if (node.matcher !== null) { processChunk(node.matcher); if (node.value !== null) { this.generate(processChunk, node.value); // space between string and flags is not required if (node.value.type === 'String') { flagsPrefix = ''; } } } if (node.flags !== null) { processChunk(flagsPrefix); processChunk(node.flags); } processChunk(']'); } }; var TYPE$e = tokenizer$1.TYPE; var WHITESPACE$4 = TYPE$e.WhiteSpace; var COMMENT$4 = TYPE$e.Comment; var SEMICOLON$3 = TYPE$e.Semicolon; var ATRULE$3 = TYPE$e.Atrule; var LEFTCURLYBRACKET$4 = TYPE$e.LeftCurlyBracket; var RIGHTCURLYBRACKET$2 = TYPE$e.RightCurlyBracket; function consumeRaw$2(startToken) { return this.Raw(startToken, 0, SEMICOLON$3, true, true); } var Block = { name: 'Block', structure: { children: [['Atrule', 'Rule', 'Declaration']] }, parse: function(defaultConsumer) { if (!defaultConsumer) { defaultConsumer = this.Declaration; } var start = this.scanner.tokenStart; var children = new list(); this.scanner.eat(LEFTCURLYBRACKET$4); scan: while (!this.scanner.eof) { switch (this.scanner.tokenType) { case RIGHTCURLYBRACKET$2: break scan; case WHITESPACE$4: case COMMENT$4: case SEMICOLON$3: this.scanner.next(); break; case ATRULE$3: children.appendData(this.tolerantParse(this.Atrule, consumeRaw$2)); break; default: children.appendData(this.tolerantParse(defaultConsumer, consumeRaw$2)); } } if (!this.tolerant || !this.scanner.eof) { this.scanner.eat(RIGHTCURLYBRACKET$2); } return { type: 'Block', loc: this.getLocation(start, this.scanner.tokenStart), children: children }; }, generate: function(processChunk, node) { processChunk('{'); this.each(processChunk, node); processChunk('}'); }, walkContext: 'block' }; var TYPE$f = tokenizer$1.TYPE; var LEFTSQUAREBRACKET$4 = TYPE$f.LeftSquareBracket; var RIGHTSQUAREBRACKET$2 = TYPE$f.RightSquareBracket; // currently only Grid Layout uses square brackets, but left it universal // https://drafts.csswg.org/css-grid/#track-sizing // [ ident* ] var Brackets = { name: 'Brackets', structure: { children: [[]] }, parse: function(readSequence, recognizer) { var start = this.scanner.tokenStart; var children = null; this.scanner.eat(LEFTSQUAREBRACKET$4); children = readSequence.call(this, recognizer); this.scanner.eat(RIGHTSQUAREBRACKET$2); return { type: 'Brackets', loc: this.getLocation(start, this.scanner.tokenStart), children: children }; }, generate: function(processChunk, node) { processChunk('['); this.each(processChunk, node); processChunk(']'); } }; var CDC$2 = tokenizer$1.TYPE.CDC; var CDC_1 = { name: 'CDC', structure: [], parse: function() { var start = this.scanner.tokenStart; this.scanner.eat(CDC$2); // --> return { type: 'CDC', loc: this.getLocation(start, this.scanner.tokenStart) }; }, generate: function(processChunk) { processChunk('-->'); } }; var CDO$2 = tokenizer$1.TYPE.CDO; var CDO_1 = { name: 'CDO', structure: [], parse: function() { var start = this.scanner.tokenStart; this.scanner.eat(CDO$2); // <!-- return { type: 'CDO', loc: this.getLocation(start, this.scanner.tokenStart) }; }, generate: function(processChunk) { processChunk('<!--'); } }; var TYPE$g = tokenizer$1.TYPE; var IDENTIFIER$9 = TYPE$g.Identifier; var FULLSTOP$3 = TYPE$g.FullStop; // '.' ident var ClassSelector = { name: 'ClassSelector', structure: { name: String }, parse: function() { this.scanner.eat(FULLSTOP$3); return { type: 'ClassSelector', loc: this.getLocation(this.scanner.tokenStart - 1, this.scanner.tokenEnd), name: this.scanner.consume(IDENTIFIER$9) }; }, generate: function(processChunk, node) { processChunk('.'); processChunk(node.name); } }; var TYPE$h = tokenizer$1.TYPE; var PLUSSIGN$5 = TYPE$h.PlusSign; var SOLIDUS$2 = TYPE$h.Solidus; var GREATERTHANSIGN$2 = TYPE$h.GreaterThanSign; var TILDE$2 = TYPE$h.Tilde; // + | > | ~ | /deep/ var Combinator = { name: 'Combinator', structure: { name: String }, parse: function() { var start = this.scanner.tokenStart; switch (this.scanner.tokenType) { case GREATERTHANSIGN$2: case PLUSSIGN$5: case TILDE$2: this.scanner.next(); break; case SOLIDUS$2: this.scanner.next(); this.scanner.expectIdentifier('deep'); this.scanner.eat(SOLIDUS$2); break; default: this.scanner.error('Combinator is expected'); } return { type: 'Combinator', loc: this.getLocation(start, this.scanner.tokenStart), name: this.scanner.substrToCursor(start) }; }, generate: function(processChunk, node) { processChunk(node.name); } }; var TYPE$i = tokenizer$1.TYPE; var ASTERISK$3 = TYPE$i.Asterisk; var SOLIDUS$3 = TYPE$i.Solidus; // '/*' .* '*/' var Comment = { name: 'Comment', structure: { value: String }, parse: function() { var start = this.scanner.tokenStart; var end = this.scanner.tokenEnd; if ((end - start + 2) >= 2 && this.scanner.source.charCodeAt(end - 2) === ASTERISK$3 && this.scanner.source.charCodeAt(end - 1) === SOLIDUS$3) { end -= 2; } this.scanner.next(); return { type: 'Comment', loc: this.getLocation(start, this.scanner.tokenStart), value: this.scanner.source.substring(start + 2, end) }; }, generate: function(processChunk, node) { processChunk('/*'); processChunk(node.value); processChunk('*/'); } }; var TYPE$j = tokenizer$1.TYPE; var IDENTIFIER$a = TYPE$j.Identifier; var COLON$3 = TYPE$j.Colon; var EXCLAMATIONMARK$2 = TYPE$j.ExclamationMark; var SOLIDUS$4 = TYPE$j.Solidus; var ASTERISK$4 = TYPE$j.Asterisk; var DOLLARSIGN$1 = TYPE$j.DollarSign; var HYPHENMINUS$6 = TYPE$j.HyphenMinus; var SEMICOLON$4 = TYPE$j.Semicolon; var RIGHTCURLYBRACKET$3 = TYPE$j.RightCurlyBracket; var RIGHTPARENTHESIS$1 = TYPE$j.RightParenthesis; var PLUSSIGN$6 = TYPE$j.PlusSign; var NUMBERSIGN$2 = TYPE$j.NumberSign; var Declaration = { name: 'Declaration', structure: { important: [Boolean, String], property: String, value: ['Value', 'Raw'] }, parse: function() { var start = this.scanner.tokenStart; var property = readProperty.call(this); var important = false; var value; this.scanner.skipSC(); this.scanner.eat(COLON$3); if (isCustomProperty(property) ? this.parseCustomProperty : this.parseValue) { value = this.Value(property); } else { value = this.Raw(this.scanner.currentToken, EXCLAMATIONMARK$2, SEMICOLON$4, false, false); } if (this.scanner.tokenType === EXCLAMATIONMARK$2) { important = getImportant(this.scanner); this.scanner.skipSC(); } // TODO: include or not to include semicolon to range? // if (this.scanner.tokenType === SEMICOLON) { // this.scanner.next(); // } if (!this.scanner.eof && this.scanner.tokenType !== SEMICOLON$4 && this.scanner.tokenType !== RIGHTPARENTHESIS$1 && this.scanner.tokenType !== RIGHTCURLYBRACKET$3) { this.scanner.error(); } return { type: 'Declaration', loc: this.getLocation(start, this.scanner.tokenStart), important: important, property: property, value: value }; }, generate: function(processChunk, node, item) { processChunk(node.property); processChunk(':'); this.generate(processChunk, node.value); if (node.important) { processChunk(node.important === true ? '!important' : '!' + node.important); } if (item && item.next) { processChunk(';'); } }, walkContext: 'declaration' }; function isCustomProperty(name) { return name.length >= 2 && name.charCodeAt(0) === HYPHENMINUS$6 && name.charCodeAt(1) === HYPHENMINUS$6; } function readProperty() { var start = this.scanner.tokenStart; var prefix = 0; // hacks switch (this.scanner.tokenType) { case ASTERISK$4: case DOLLARSIGN$1: case PLUSSIGN$6: case NUMBERSIGN$2: prefix = 1; break; // TODO: not sure we should support this hack case SOLIDUS$4: prefix = this.scanner.lookupType(1) === SOLIDUS$4 ? 2 : 1; break; } if (this.scanner.lookupType(prefix) === HYPHENMINUS$6) { prefix++; } if (prefix) { this.scanner.skip(prefix); } this.scanner.eat(IDENTIFIER$a); return this.scanner.substrToCursor(start); } // ! ws* important function getImportant(scanner) { scanner.eat(EXCLAMATIONMARK$2); scanner.skipSC(); var important = scanner.consume(IDENTIFIER$a); // store original value in case it differ from `important` // for better original source restoring and hacks like `!ie` support return important === 'important' ? true : important; } var TYPE$k = tokenizer$1.TYPE; var WHITESPACE$5 = TYPE$k.WhiteSpace; var COMMENT$5 = TYPE$k.Comment; var SEMICOLON$5 = TYPE$k.Semicolon; function consumeRaw$3(startToken) { return this.Raw(startToken, 0, SEMICOLON$5, true, true); } var DeclarationList = { name: 'DeclarationList', structure: { children: [['Declaration']] }, parse: function() { var children = new list(); scan: while (!this.scanner.eof) { switch (this.scanner.tokenType) { case WHITESPACE$5: case COMMENT$5: case SEMICOLON$5: this.scanner.next(); break; default: children.appendData(this.tolerantParse(this.Declaration, consumeRaw$3)); } } return { type: 'DeclarationList', loc: this.getLocationFromList(children), children: children }; }, generate: function(processChunk, node) { this.each(processChunk, node); } }; var NUMBER$5 = tokenizer$1.TYPE.Number; // special reader for units to avoid adjoined IE hacks (i.e. '1px\9') function readUnit(scanner) { var unit = scanner.getTokenValue(); var backSlashPos = unit.indexOf('\\'); if (backSlashPos > 0) { // patch token offset scanner.tokenStart += backSlashPos; // return part before backslash return unit.substring(0, backSlashPos); } // no backslash in unit name scanner.next(); return unit; } // number ident var Dimension = { name: 'Dimension', structure: { value: String, unit: String }, parse: function() { var start = this.scanner.tokenStart; var value = this.scanner.consume(NUMBER$5); var unit = readUnit(this.scanner); return { type: 'Dimension', loc: this.getLocation(start, this.scanner.tokenStart), value: value, unit: unit }; }, generate: function(processChunk, node) { processChunk(node.value); processChunk(node.unit); } }; var TYPE$l = tokenizer$1.TYPE; var RIGHTPARENTHESIS$2 = TYPE$l.RightParenthesis; // <function-token> <sequence> ')' var _Function = { name: 'Function', structure: { name: String, children: [[]] }, parse: function(readSequence, recognizer) { var start = this.scanner.tokenStart; var name = this.scanner.consumeFunctionName(); var nameLowerCase = name.toLowerCase(); var children; children = recognizer.hasOwnProperty(nameLowerCase) ? recognizer[nameLowerCase].call(this, recognizer) : readSequence.call(this, recognizer); this.scanner.eat(RIGHTPARENTHESIS$2); return { type: 'Function', loc: this.getLocation(start, this.scanner.tokenStart), name: name, children: children }; }, generate: function(processChunk, node) { processChunk(node.name); processChunk('('); this.each(processChunk, node); processChunk(')'); }, walkContext: 'function' }; var isHex$1 = tokenizer$1.isHex; var TYPE$m = tokenizer$1.TYPE; var IDENTIFIER$b = TYPE$m.Identifier; var NUMBER$6 = TYPE$m.Number; var NUMBERSIGN$3 = TYPE$m.NumberSign; function consumeHexSequence(scanner, required) { if (!isHex$1(scanner.source.charCodeAt(scanner.tokenStart))) { if (required) { scanner.error('Unexpected input', scanner.tokenStart); } else { return; } } for (var pos = scanner.tokenStart + 1; pos < scanner.tokenEnd; pos++) { var code = scanner.source.charCodeAt(pos); // break on non-hex char if (!isHex$1(code)) { // break token, exclude symbol scanner.tokenStart = pos; return; } } // token is full hex sequence, go to next token scanner.next(); } // # ident var HexColor = { name: 'HexColor', structure: { value: String }, parse: function() { var start = this.scanner.tokenStart; this.scanner.eat(NUMBERSIGN$3); scan: switch (this.scanner.tokenType) { case NUMBER$6: consumeHexSequence(this.scanner, true); // if token is identifier then number consists of hex only, // try to add identifier to result if (this.scanner.tokenType === IDENTIFIER$b) { consumeHexSequence(this.scanner, false); } break; case IDENTIFIER$b: consumeHexSequence(this.scanner, true); break; default: this.scanner.error('Number or identifier is expected'); } return { type: 'HexColor', loc: this.getLocation(start, this.scanner.tokenStart), value: this.scanner.substrToCursor(start + 1) // skip # }; }, generate: function(processChunk, node) { processChunk('#'); processChunk(node.value); } }; var TYPE$n = tokenizer$1.TYPE; var IDENTIFIER$c = TYPE$n.Identifier; var Identifier = { name: 'Identifier', structure: { name: String }, parse: function() { return { type: 'Identifier', loc: this.getLocation(this.scanner.tokenStart, this.scanner.tokenEnd), name: this.scanner.consume(IDENTIFIER$c) }; }, generate: function(processChunk, node) { processChunk(node.name); } }; var TYPE$o = tokenizer$1.TYPE; var IDENTIFIER$d = TYPE$o.Identifier; var NUMBERSIGN$4 = TYPE$o.NumberSign; // '#' ident var IdSelector = { name: 'IdSelector', structure: { name: String }, parse: function() { this.scanner.eat(NUMBERSIGN$4); return { type: 'IdSelector', loc: this.getLocation(this.scanner.tokenStart - 1, this.scanner.tokenEnd), name: this.scanner.consume(IDENTIFIER$d) }; }, generate: function(processChunk, node) { processChunk('#'); processChunk(node.name); } }; var TYPE$p = tokenizer$1.TYPE; var IDENTIFIER$e = TYPE$p.Identifier; var NUMBER$7 = TYPE$p.Number; var LEFTPARENTHESIS$4 = TYPE$p.LeftParenthesis; var RIGHTPARENTHESIS$3 = TYPE$p.RightParenthesis; var COLON$4 = TYPE$p.Colon; var SOLIDUS$5 = TYPE$p.Solidus; var MediaFeature = { name: 'MediaFeature', structure: { name: String, value: ['Identifier', 'Number', 'Dimension', 'Ratio', null] }, parse: function() { var start = this.scanner.tokenStart; var name; var value = null; this.scanner.eat(LEFTPARENTHESIS$4); this.scanner.skipSC(); name = this.scanner.consume(IDENTIFIER$e); this.scanner.skipSC(); if (this.scanner.tokenType !== RIGHTPARENTHESIS$3) { this.scanner.eat(COLON$4); this.scanner.skipSC(); switch (this.scanner.tokenType) { case NUMBER$7: if (this.scanner.lookupType(1) === IDENTIFIER$e) { value = this.Dimension(); } else if (this.scanner.lookupNonWSType(1) === SOLIDUS$5) { value = this.Ratio(); } else { value = this.Number(); } break; case IDENTIFIER$e: value = this.Identifier(); break; default: this.scanner.error('Number, dimension, ratio or identifier is expected'); } this.scanner.skipSC(); } this.scanner.eat(RIGHTPARENTHESIS$3); return { type: 'MediaFeature', loc: this.getLocation(start, this.scanner.tokenStart), name: name, value: value }; }, generate: function(processChunk, node) { processChunk('('); processChunk(node.name); if (node.value !== null) { processChunk(':'); this.generate(processChunk, node.value); } processChunk(')'); } }; var TYPE$q = tokenizer$1.TYPE; var WHITESPACE$6 = TYPE$q.WhiteSpace; var COMMENT$6 = TYPE$q.Comment; var IDENTIFIER$f = TYPE$q.Identifier; var LEFTPARENTHESIS$5 = TYPE$q.LeftParenthesis; var MediaQuery = { name: 'MediaQuery', structure: { children: [['Identifier', 'MediaFeature', 'WhiteSpace']] }, parse: function() { this.scanner.skipSC(); var children = new list(); var child = null; var space = null; scan: while (!this.scanner.eof) { switch (this.scanner.tokenType) { case COMMENT$6: this.scanner.next(); continue; case WHITESPACE$6: space = this.WhiteSpace(); continue; case IDENTIFIER$f: child = this.Identifier(); break; case LEFTPARENTHESIS$5: child = this.MediaFeature(); break; default: break scan; } if (space !== null) { children.appendData(space); space = null; } children.appendData(child); } if (child === null) { this.scanner.error('Identifier or parenthesis is expected'); } return { type: 'MediaQuery', loc: this.getLocationFromList(children), children: children }; }, generate: function(processChunk, node) { this.each(processChunk, node); } }; var COMMA$2 = tokenizer$1.TYPE.Comma; var MediaQueryList = { name: 'MediaQueryList', structure: { children: [['MediaQuery']] }, parse: function(relative) { var children = new list(); this.scanner.skipSC(); while (!this.scanner.eof) { children.appendData(this.MediaQuery(relative)); if (this.scanner.tokenType !== COMMA$2) { break; } this.scanner.next(); } return { type: 'MediaQueryList', loc: this.getLocationFromList(children), children: children }; }, generate: function(processChunk, node) { this.eachComma(processChunk, node); } }; // https://drafts.csswg.org/css-syntax-3/#the-anb-type var Nth = { name: 'Nth', structure: { nth: ['AnPlusB', 'Identifier'], selector: ['SelectorList', null] }, parse: function(allowOfClause) { this.scanner.skipSC(); var start = this.scanner.tokenStart; var end = start; var selector = null; var query; if (this.scanner.lookupValue(0, 'odd') || this.scanner.lookupValue(0, 'even')) { query = this.Identifier(); } else { query = this.AnPlusB(); } this.scanner.skipSC(); if (allowOfClause && this.scanner.lookupValue(0, 'of')) { this.scanner.next(); selector = this.SelectorList(); if (this.needPositions) { end = selector.children.last().loc.end.offset; } } else { if (this.needPositions) { end = query.loc.end.offset; } } return { type: 'Nth', loc: this.getLocation(start, end), nth: query, selector: selector }; }, generate: function(processChunk, node) { this.generate(processChunk, node.nth); if (node.selector !== null) { processChunk(' of '); this.generate(processChunk, node.selector); } } }; var NUMBER$8 = tokenizer$1.TYPE.Number; var _Number = { name: 'Number', structure: { value: String }, parse: function() { return { type: 'Number', loc: this.getLocation(this.scanner.tokenStart, this.scanner.tokenEnd), value: this.scanner.consume(NUMBER$8) }; }, generate: function(processChunk, node) { processChunk(node.value); } }; // '/' | '*' | ',' | ':' | '+' | '-' var Operator = { name: 'Operator', structure: { value: String }, parse: function() { var start = this.scanner.tokenStart; this.scanner.next(); return { type: 'Operator', loc: this.getLocation(start, this.scanner.tokenStart), value: this.scanner.substrToCursor(start) }; }, generate: function(processChunk, node) { processChunk(node.value); } }; var TYPE$r = tokenizer$1.TYPE; var LEFTPARENTHESIS$6 = TYPE$r.LeftParenthesis; var RIGHTPARENTHESIS$4 = TYPE$r.RightParenthesis; var Parentheses = { name: 'Parentheses', structure: { children: [[]] }, parse: function(readSequence, recognizer) { var start = this.scanner.tokenStart; var children = null; this.scanner.eat(LEFTPARENTHESIS$6); children = readSequence.call(this, recognizer); this.scanner.eat(RIGHTPARENTHESIS$4); return { type: 'Parentheses', loc: this.getLocation(start, this.scanner.tokenStart), children: children }; }, generate: function(processChunk, node) { processChunk('('); this.each(processChunk, node); processChunk(')'); } }; var TYPE$s = tokenizer$1.TYPE; var NUMBER$9 = TYPE$s.Number; var PERCENTSIGN$1 = TYPE$s.PercentSign; var Percentage = { name: 'Percentage', structure: { value: String }, parse: function() { var start = this.scanner.tokenStart; var number = this.scanner.consume(NUMBER$9); this.scanner.eat(PERCENTSIGN$1); return { type: 'Percentage', loc: this.getLocation(start, this.scanner.tokenStart), value: number }; }, generate: function(processChunk, node) { processChunk(node.value); processChunk('%'); } }; var TYPE$t = tokenizer$1.TYPE; var IDENTIFIER$g = TYPE$t.Identifier; var FUNCTION$4 = TYPE$t.Function; var COLON$5 = TYPE$t.Colon; var RIGHTPARENTHESIS$5 = TYPE$t.RightParenthesis; // : ident [ '(' .. ')' ]? var PseudoClassSelector = { name: 'PseudoClassSelector', structure: { name: String, children: [['Raw'], null] }, parse: function() { var start = this.scanner.tokenStart; var children = null; var name; var nameLowerCase; this.scanner.eat(COLON$5); if (this.scanner.tokenType === FUNCTION$4) { name = this.scanner.consumeFunctionName(); nameLowerCase = name.toLowerCase(); if (this.pseudo.hasOwnProperty(nameLowerCase)) { this.scanner.skipSC(); children = this.pseudo[nameLowerCase].call(this); this.scanner.skipSC(); } else { children = new list().appendData( this.Raw(this.scanner.currentToken, 0, 0, false, false) ); } this.scanner.eat(RIGHTPARENTHESIS$5); } else { name = this.scanner.consume(IDENTIFIER$g); } return { type: 'PseudoClassSelector', loc: this.getLocation(start, this.scanner.tokenStart), name: name, children: children }; }, generate: function(processChunk, node) { processChunk(':'); processChunk(node.name); if (node.children !== null) { processChunk('('); this.each(processChunk, node); processChunk(')'); } }, walkContext: 'function' }; var TYPE$u = tokenizer$1.TYPE; var IDENTIFIER$h = TYPE$u.Identifier; var FUNCTION$5 = TYPE$u.Function; var COLON$6 = TYPE$u.Colon; var RIGHTPARENTHESIS$6 = TYPE$u.RightParenthesis; // :: ident [ '(' .. ')' ]? var PseudoElementSelector = { name: 'PseudoElementSelector', structure: { name: String, children: [['Raw'], null] }, parse: function() { var start = this.scanner.tokenStart; var children = null; var name; var nameLowerCase; this.scanner.eat(COLON$6); this.scanner.eat(COLON$6); if (this.scanner.tokenType === FUNCTION$5) { name = this.scanner.consumeFunctionName(); nameLowerCase = name.toLowerCase(); if (this.pseudo.hasOwnProperty(nameLowerCase)) { this.scanner.skipSC(); children = this.pseudo[nameLowerCase].call(this); this.scanner.skipSC(); } else { children = new list().appendData( this.Raw(this.scanner.currentToken, 0, 0, false, false) ); } this.scanner.eat(RIGHTPARENTHESIS$6); } else { name = this.scanner.consume(IDENTIFIER$h); } return { type: 'PseudoElementSelector', loc: this.getLocation(start, this.scanner.tokenStart), name: name, children: children }; }, generate: function(processChunk, node) { processChunk('::'); processChunk(node.name); if (node.children !== null) { processChunk('('); this.each(processChunk, node); processChunk(')'); } }, walkContext: 'function' }; var isNumber$3 = tokenizer$1.isNumber; var TYPE$v = tokenizer$1.TYPE; var NUMBER$a = TYPE$v.Number; var SOLIDUS$6 = TYPE$v.Solidus; var FULLSTOP$4 = TYPE$v.FullStop; // Terms of <ratio> should to be a positive number (not zero or negative) // (see https://drafts.csswg.org/mediaqueries-3/#values) // However, -o-min-device-pixel-ratio takes fractional values as a ratio's term // and this is using by various sites. Therefore we relax checking on parse // to test a term is unsigned number without exponent part. // Additional checks may to be applied on lexer validation. function consumeNumber(scanner) { var value = scanner.consumeNonWS(NUMBER$a); for (var i = 0; i < value.length; i++) { var code = value.charCodeAt(i); if (!isNumber$3(code) && code !== FULLSTOP$4) { scanner.error('Unsigned number is expected', scanner.tokenStart - value.length + i); } } if (Number(value) === 0) { scanner.error('Zero number is not allowed', scanner.tokenStart - value.length); } return value; } // <positive-integer> S* '/' S* <positive-integer> var Ratio = { name: 'Ratio', structure: { left: String, right: String }, parse: function() { var start = this.scanner.tokenStart; var left = consumeNumber(this.scanner); var right; this.scanner.eatNonWS(SOLIDUS$6); right = consumeNumber(this.scanner); return { type: 'Ratio', loc: this.getLocation(start, this.scanner.tokenStart), left: left, right: right }; }, generate: function(processChunk, node) { processChunk(node.left); processChunk('/'); processChunk(node.right); } }; var Raw = { name: 'Raw', structure: { value: String }, parse: function(startToken, endTokenType1, endTokenType2, includeTokenType2, excludeWhiteSpace) { var startOffset = this.scanner.getTokenStart(startToken); var endOffset; this.scanner.skip( this.scanner.getRawLength( startToken, endTokenType1, endTokenType2, includeTokenType2 ) ); if (excludeWhiteSpace && this.scanner.tokenStart > startOffset) { endOffset = this.scanner.getOffsetExcludeWS(); } else { endOffset = this.scanner.tokenStart; } return { type: 'Raw', loc: this.getLocation(startOffset, endOffset), value: this.scanner.source.substring(startOffset, endOffset) }; }, generate: function(processChunk, node) { processChunk(node.value); } }; var TYPE$w = tokenizer$1.TYPE; var LEFTCURLYBRACKET$5 = TYPE$w.LeftCurlyBracket; function consumeRaw$4(startToken) { return this.Raw(startToken, LEFTCURLYBRACKET$5, 0, false, true); } var Rule = { name: 'Rule', structure: { selector: ['SelectorList', 'Raw'], block: ['Block'] }, parse: function() { var startToken = this.scanner.currentToken; var startOffset = this.scanner.tokenStart; var selector = this.parseSelector ? this.tolerantParse(this.SelectorList, consumeRaw$4) : consumeRaw$4.call(this, startToken); var block = this.Block(this.Declaration); return { type: 'Rule', loc: this.getLocation(startOffset, this.scanner.tokenStart), selector: selector, block: block }; }, generate: function(processChunk, node) { this.generate(processChunk, node.selector); this.generate(processChunk, node.block); }, walkContext: 'rule' }; var Selector = { name: 'Selector', structure: { children: [[ 'TypeSelector', 'IdSelector', 'ClassSelector', 'AttributeSelector', 'PseudoClassSelector', 'PseudoElementSelector', 'Combinator', 'WhiteSpace' ]] }, parse: function() { var children = this.readSequence(this.scope.Selector); // nothing were consumed if (children.isEmpty()) { this.scanner.error('Selector is expected'); } return { type: 'Selector', loc: this.getLocationFromList(children), children: children }; }, generate: function(processChunk, node) { this.each(processChunk, node); } }; var TYPE$x = tokenizer$1.TYPE; var COMMA$3 = TYPE$x.Comma; var LEFTCURLYBRACKET$6 = TYPE$x.LeftCurlyBracket; var SelectorList = { name: 'SelectorList', structure: { children: [['Selector', 'Raw']] }, parse: function() { var children = new list(); while (!this.scanner.eof) { children.appendData(this.parseSelector ? this.Selector() : this.Raw(this.scanner.currentToken, COMMA$3, LEFTCURLYBRACKET$6, false, false) ); if (this.scanner.tokenType === COMMA$3) { this.scanner.next(); continue; } break; } return { type: 'SelectorList', loc: this.getLocationFromList(children), children: children }; }, generate: function(processChunk, node) { this.eachComma(processChunk, node); }, walkContext: 'selector' }; var STRING$5 = tokenizer$1.TYPE.String; var _String = { name: 'String', structure: { value: String }, parse: function() { return { type: 'String', loc: this.getLocation(this.scanner.tokenStart, this.scanner.tokenEnd), value: this.scanner.consume(STRING$5) }; }, generate: function(processChunk, node) { processChunk(node.value); } }; var TYPE$y = tokenizer$1.TYPE; var WHITESPACE$7 = TYPE$y.WhiteSpace; var COMMENT$7 = TYPE$y.Comment; var EXCLAMATIONMARK$3 = TYPE$y.ExclamationMark; var ATRULE$4 = TYPE$y.Atrule; var CDO$3 = TYPE$y.CDO; var CDC$3 = TYPE$y.CDC; function consumeRaw$5(startToken) { return this.Raw(startToken, 0, 0, false, false); } var StyleSheet = { name: 'StyleSheet', structure: { children: [['Comment', 'Atrule', 'Rule', 'Raw']] }, parse: function() { var start = this.scanner.tokenStart; var children = new list(); var child; scan: while (!this.scanner.eof) { switch (this.scanner.tokenType) { case WHITESPACE$7: this.scanner.next(); continue; case COMMENT$7: // ignore comments except exclamation comments (i.e. /*! .. */) on top level if (this.scanner.source.charCodeAt(this.scanner.tokenStart + 2) !== EXCLAMATIONMARK$3) { this.scanner.next(); continue; } child = this.Comment(); break; case CDO$3: // <!-- child = this.CDO(); break; case CDC$3: // --> child = this.CDC(); break; // CSS Syntax Module Level 3 // §2.2 Error handling // At the "top level" of a stylesheet, an <at-keyword-token> starts an at-rule. case ATRULE$4: child = this.Atrule(); break; // Anything else starts a qualified rule ... default: child = this.tolerantParse(this.Rule, consumeRaw$5); } children.appendData(child); } return { type: 'StyleSheet', loc: this.getLocation(start, this.scanner.tokenStart), children: children }; }, generate: function(processChunk, node) { this.each(processChunk, node); }, walkContext: 'stylesheet' }; var TYPE$z = tokenizer$1.TYPE; var IDENTIFIER$i = TYPE$z.Identifier; var ASTERISK$5 = TYPE$z.Asterisk; var VERTICALLINE$2 = TYPE$z.VerticalLine; function eatIdentifierOrAsterisk() { if (this.scanner.tokenType !== IDENTIFIER$i && this.scanner.tokenType !== ASTERISK$5) { this.scanner.error('Identifier or asterisk is expected'); } this.scanner.next(); } // ident // ident|ident // ident|* // * // *|ident // *|* // |ident // |* var TypeSelector = { name: 'TypeSelector', structure: { name: String }, parse: function() { var start = this.scanner.tokenStart; if (this.scanner.tokenType === VERTICALLINE$2) { this.scanner.next(); eatIdentifierOrAsterisk.call(this); } else { eatIdentifierOrAsterisk.call(this); if (this.scanner.tokenType === VERTICALLINE$2) { this.scanner.next(); eatIdentifierOrAsterisk.call(this); } } return { type: 'TypeSelector', loc: this.getLocation(start, this.scanner.tokenStart), name: this.scanner.substrToCursor(start) }; }, generate: function(processChunk, node) { processChunk(node.name); } }; var isHex$2 = tokenizer$1.isHex; var TYPE$A = tokenizer$1.TYPE; var IDENTIFIER$j = TYPE$A.Identifier; var NUMBER$b = TYPE$A.Number; var PLUSSIGN$7 = TYPE$A.PlusSign; var HYPHENMINUS$7 = TYPE$A.HyphenMinus; var FULLSTOP$5 = TYPE$A.FullStop; var QUESTIONMARK = TYPE$A.QuestionMark; function scanUnicodeNumber(scanner) { for (var pos = scanner.tokenStart + 1; pos < scanner.tokenEnd; pos++) { var code = scanner.source.charCodeAt(pos); // break on fullstop or hyperminus/plussign after exponent if (code === FULLSTOP$5 || code === PLUSSIGN$7) { // break token, exclude symbol scanner.tokenStart = pos; return false; } } return true; } // https://drafts.csswg.org/css-syntax-3/#urange function scanUnicodeRange(scanner) { var hexStart = scanner.tokenStart + 1; // skip + var hexLength = 0; scan: { if (scanner.tokenType === NUMBER$b) { if (scanner.source.charCodeAt(scanner.tokenStart) !== FULLSTOP$5 && scanUnicodeNumber(scanner)) { scanner.next(); } else if (scanner.source.charCodeAt(scanner.tokenStart) !== HYPHENMINUS$7) { break scan; } } else { scanner.next(); // PLUSSIGN } if (scanner.tokenType === HYPHENMINUS$7) { scanner.next(); } if (scanner.tokenType === NUMBER$b) { scanner.next(); } if (scanner.tokenType === IDENTIFIER$j) { scanner.next(); } if (scanner.tokenStart === hexStart) { scanner.error('Unexpected input', hexStart); } } // validate for U+x{1,6} or U+x{1,6}-x{1,6} // where x is [0-9a-fA-F] for (var i = hexStart, wasHyphenMinus = false; i < scanner.tokenStart; i++) { var code = scanner.source.charCodeAt(i); if (isHex$2(code) === false && (code !== HYPHENMINUS$7 || wasHyphenMinus)) { scanner.error('Unexpected input', i); } if (code === HYPHENMINUS$7) { // hex sequence shouldn't be an empty if (hexLength === 0) { scanner.error('Unexpected input', i); } wasHyphenMinus = true; hexLength = 0; } else { hexLength++; // too long hex sequence if (hexLength > 6) { scanner.error('Too long hex sequence', i); } } } // check we have a non-zero sequence if (hexLength === 0) { scanner.error('Unexpected input', i - 1); } // U+abc??? if (!wasHyphenMinus) { // consume as many U+003F QUESTION MARK (?) code points as possible for (; hexLength < 6 && !scanner.eof; scanner.next()) { if (scanner.tokenType !== QUESTIONMARK) { break; } hexLength++; } } } var UnicodeRange = { name: 'UnicodeRange', structure: { value: String }, parse: function() { var start = this.scanner.tokenStart; this.scanner.next(); // U or u scanUnicodeRange(this.scanner); return { type: 'UnicodeRange', loc: this.getLocation(start, this.scanner.tokenStart), value: this.scanner.substrToCursor(start) }; }, generate: function(processChunk, node) { processChunk(node.value); } }; var TYPE$B = tokenizer$1.TYPE; var STRING$6 = TYPE$B.String; var URL$4 = TYPE$B.Url; var RAW$2 = TYPE$B.Raw; var RIGHTPARENTHESIS$7 = TYPE$B.RightParenthesis; // url '(' S* (string | raw) S* ')' var Url = { name: 'Url', structure: { value: ['String', 'Raw'] }, parse: function() { var start = this.scanner.tokenStart; var value; this.scanner.eat(URL$4); this.scanner.skipSC(); switch (this.scanner.tokenType) { case STRING$6: value = this.String(); break; case RAW$2: value = this.Raw(this.scanner.currentToken, 0, RAW$2, true, false); break; default: this.scanner.error('String or Raw is expected'); } this.scanner.skipSC(); this.scanner.eat(RIGHTPARENTHESIS$7); return { type: 'Url', loc: this.getLocation(start, this.scanner.tokenStart), value: value }; }, generate: function(processChunk, node) { processChunk('url'); processChunk('('); this.generate(processChunk, node.value); processChunk(')'); } }; var endsWith$1 = tokenizer$1.endsWith; var TYPE$C = tokenizer$1.TYPE; var WHITESPACE$8 = TYPE$C.WhiteSpace; var COMMENT$8 = TYPE$C.Comment; var FUNCTION$6 = TYPE$C.Function; var COLON$7 = TYPE$C.Colon; var SEMICOLON$6 = TYPE$C.Semicolon; var EXCLAMATIONMARK$4 = TYPE$C.ExclamationMark; // 'progid:' ws* 'DXImageTransform.Microsoft.' ident ws* '(' .* ')' function checkProgid(scanner) { var offset = 0; for (var type; type = scanner.lookupType(offset); offset++) { if (type !== WHITESPACE$8 && type !== COMMENT$8) { break; } } if (scanner.lookupValue(offset, 'alpha(') || scanner.lookupValue(offset, 'chroma(') || scanner.lookupValue(offset, 'dropshadow(')) { if (scanner.lookupType(offset) !== FUNCTION$6) { return false; } } else { if (scanner.lookupValue(offset, 'progid') === false || scanner.lookupType(offset + 1) !== COLON$7) { return false; } } return true; } var Value = { name: 'Value', structure: { children: [[]] }, parse: function(property) { // special parser for filter property since it can contains non-standart syntax for old IE if (property !== null && endsWith$1(property, 'filter') && checkProgid(this.scanner)) { this.scanner.skipSC(); return this.Raw(this.scanner.currentToken, EXCLAMATIONMARK$4, SEMICOLON$6, false, false); } var start = this.scanner.tokenStart; var children = this.readSequence(this.scope.Value); return { type: 'Value', loc: this.getLocation(start, this.scanner.tokenStart), children: children }; }, generate: function(processChunk, node) { this.each(processChunk, node); } }; var WHITESPACE$9 = tokenizer$1.TYPE.WhiteSpace; var SPACE$2 = Object.freeze({ type: 'WhiteSpace', loc: null, value: ' ' }); var WhiteSpace = { name: 'WhiteSpace', structure: { value: String }, parse: function() { this.scanner.eat(WHITESPACE$9); return SPACE$2; // return { // type: 'WhiteSpace', // loc: this.getLocation(this.scanner.tokenStart, this.scanner.tokenEnd), // value: this.scanner.consume(WHITESPACE) // }; }, generate: function(processChunk, node) { processChunk(node.value); } }; var node = { AnPlusB: AnPlusB, Atrule: Atrule, AtruleExpression: AtruleExpression, AttributeSelector: AttributeSelector, Block: Block, Brackets: Brackets, CDC: CDC_1, CDO: CDO_1, ClassSelector: ClassSelector, Combinator: Combinator, Comment: Comment, Declaration: Declaration, DeclarationList: DeclarationList, Dimension: Dimension, Function: _Function, HexColor: HexColor, Identifier: Identifier, IdSelector: IdSelector, MediaFeature: MediaFeature, MediaQuery: MediaQuery, MediaQueryList: MediaQueryList, Nth: Nth, Number: _Number, Operator: Operator, Parentheses: Parentheses, Percentage: Percentage, PseudoClassSelector: PseudoClassSelector, PseudoElementSelector: PseudoElementSelector, Ratio: Ratio, Raw: Raw, Rule: Rule, Selector: Selector, SelectorList: SelectorList, String: _String, StyleSheet: StyleSheet, TypeSelector: TypeSelector, UnicodeRange: UnicodeRange, Url: Url, Value: Value, WhiteSpace: WhiteSpace }; var parser = { parseContext: { default: 'StyleSheet', stylesheet: 'StyleSheet', atrule: 'Atrule', atruleExpression: function(options) { return this.AtruleExpression(options.atrule ? String(options.atrule) : null); }, mediaQueryList: 'MediaQueryList', mediaQuery: 'MediaQuery', rule: 'Rule', selectorList: 'SelectorList', selector: 'Selector', block: function() { return this.Block(this.Declaration); }, declarationList: 'DeclarationList', declaration: 'Declaration', value: function(options) { return this.Value(options.property ? String(options.property) : null); } }, scope: scope, atrule: atrule, pseudo: pseudo, node: node }; var parser$1 = create(parser); function walk(ast, { enter, leave }) { visit(ast, null, enter, leave); } let shouldSkip = false; const context = { skip: () => shouldSkip = true }; const childKeys = {}; const toString$1 = Object.prototype.toString; function isArray$1(thing) { return toString$1.call(thing) === '[object Array]'; } function visit(node, parent, enter, leave, prop, index) { if (!node) return; if (enter) { const _shouldSkip = shouldSkip; shouldSkip = false; enter.call(context, node, parent, prop, index); const skipped = shouldSkip; shouldSkip = _shouldSkip; if (skipped) return; } const keys = childKeys[node.type] || ( childKeys[node.type] = Object.keys(node).filter(key => typeof node[key] === 'object') ); for (let i = 0; i < keys.length; i += 1) { const key = keys[i]; const value = node[key]; if (isArray$1(value)) { for (let j = 0; j < value.length; j += 1) { visit(value[j], node, enter, leave, key, j); } } else if (value && value.type) { visit(value, node, enter, leave, key, null); } } if (leave) { leave(node, parent, prop, index); } } function read_style(parser, start, attributes) { const content_start = parser.index; const styles = parser.read_until(/<\/style>/); const content_end = parser.index; let ast; try { ast = parser$1(styles, { positions: true, offset: content_start, }); } catch (err) { if (err.name === 'CssSyntaxError') { parser.error({ code: `css-syntax-error`, message: err.message }, err.offset); } else { throw err; } } ast = JSON.parse(JSON.stringify(ast)); // tidy up AST walk(ast, { enter: (node) => { // replace `ref:a` nodes if (node.type === 'Selector') { for (let i = 0; i < node.children.length; i += 1) { const a = node.children[i]; const b = node.children[i + 1]; if (is_ref_selector(a, b)) { parser.error({ code: `invalid-ref-selector`, message: 'ref selectors are no longer supported' }, a.loc.start.offset); } } } if (node.loc) { node.start = node.loc.start.offset; node.end = node.loc.end.offset; delete node.loc; } } }); parser.eat('</style>', true); const end = parser.index; return { start, end, attributes, children: ast.children, content: { start: content_start, end: content_end, styles, }, }; } function is_ref_selector(a, b) { if (!b) return false; return ( a.type === 'TypeSelector' && a.name === 'ref' && b.type === 'PseudoClassSelector' ); } // https://dev.w3.org/html5/html-author/charref var entities = { CounterClockwiseContourIntegral: 8755, ClockwiseContourIntegral: 8754, DoubleLongLeftRightArrow: 10234, DiacriticalDoubleAcute: 733, NotSquareSupersetEqual: 8931, CloseCurlyDoubleQuote: 8221, DoubleContourIntegral: 8751, FilledVerySmallSquare: 9642, NegativeVeryThinSpace: 8203, NotPrecedesSlantEqual: 8928, NotRightTriangleEqual: 8941, NotSucceedsSlantEqual: 8929, CapitalDifferentialD: 8517, DoubleLeftRightArrow: 8660, DoubleLongRightArrow: 10233, EmptyVerySmallSquare: 9643, NestedGreaterGreater: 8811, NotDoubleVerticalBar: 8742, NotLeftTriangleEqual: 8940, NotSquareSubsetEqual: 8930, OpenCurlyDoubleQuote: 8220, ReverseUpEquilibrium: 10607, DoubleLongLeftArrow: 10232, DownLeftRightVector: 10576, LeftArrowRightArrow: 8646, NegativeMediumSpace: 8203, RightArrowLeftArrow: 8644, SquareSupersetEqual: 8850, leftrightsquigarrow: 8621, DownRightTeeVector: 10591, DownRightVectorBar: 10583, LongLeftRightArrow: 10231, Longleftrightarrow: 10234, NegativeThickSpace: 8203, PrecedesSlantEqual: 8828, ReverseEquilibrium: 8651, RightDoubleBracket: 10215, RightDownTeeVector: 10589, RightDownVectorBar: 10581, RightTriangleEqual: 8885, SquareIntersection: 8851, SucceedsSlantEqual: 8829, blacktriangleright: 9656, longleftrightarrow: 10231, DoubleUpDownArrow: 8661, DoubleVerticalBar: 8741, DownLeftTeeVector: 10590, DownLeftVectorBar: 10582, FilledSmallSquare: 9724, GreaterSlantEqual: 10878, LeftDoubleBracket: 10214, LeftDownTeeVector: 10593, LeftDownVectorBar: 10585, LeftTriangleEqual: 8884, NegativeThinSpace: 8203, NotReverseElement: 8716, NotTildeFullEqual: 8775, RightAngleBracket: 10217, RightUpDownVector: 10575, SquareSubsetEqual: 8849, VerticalSeparator: 10072, blacktriangledown: 9662, blacktriangleleft: 9666, leftrightharpoons: 8651, rightleftharpoons: 8652, twoheadrightarrow: 8608, DiacriticalAcute: 180, DiacriticalGrave: 96, DiacriticalTilde: 732, DoubleRightArrow: 8658, DownArrowUpArrow: 8693, EmptySmallSquare: 9723, GreaterEqualLess: 8923, GreaterFullEqual: 8807, LeftAngleBracket: 10216, LeftUpDownVector: 10577, LessEqualGreater: 8922, NonBreakingSpace: 160, NotRightTriangle: 8939, NotSupersetEqual: 8841, RightTriangleBar: 10704, RightUpTeeVector: 10588, RightUpVectorBar: 10580, UnderParenthesis: 9181, UpArrowDownArrow: 8645, circlearrowright: 8635, downharpoonright: 8642, ntrianglerighteq: 8941, rightharpoondown: 8641, rightrightarrows: 8649, twoheadleftarrow: 8606, vartriangleright: 8883, CloseCurlyQuote: 8217, ContourIntegral: 8750, DoubleDownArrow: 8659, DoubleLeftArrow: 8656, DownRightVector: 8641, LeftRightVector: 10574, LeftTriangleBar: 10703, LeftUpTeeVector: 10592, LeftUpVectorBar: 10584, LowerRightArrow: 8600, NotGreaterEqual: 8817, NotGreaterTilde: 8821, NotLeftTriangle: 8938, OverParenthesis: 9180, RightDownVector: 8642, ShortRightArrow: 8594, UpperRightArrow: 8599, bigtriangledown: 9661, circlearrowleft: 8634, curvearrowright: 8631, downharpoonleft: 8643, leftharpoondown: 8637, leftrightarrows: 8646, nLeftrightarrow: 8654, nleftrightarrow: 8622, ntrianglelefteq: 8940, rightleftarrows: 8644, rightsquigarrow: 8605, rightthreetimes: 8908, straightepsilon: 1013, trianglerighteq: 8885, vartriangleleft: 8882, DiacriticalDot: 729, DoubleRightTee: 8872, DownLeftVector: 8637, GreaterGreater: 10914, HorizontalLine: 9472, InvisibleComma: 8291, InvisibleTimes: 8290, LeftDownVector: 8643, LeftRightArrow: 8596, Leftrightarrow: 8660, LessSlantEqual: 10877, LongRightArrow: 10230, Longrightarrow: 10233, LowerLeftArrow: 8601, NestedLessLess: 8810, NotGreaterLess: 8825, NotLessGreater: 8824, NotSubsetEqual: 8840, NotVerticalBar: 8740, OpenCurlyQuote: 8216, ReverseElement: 8715, RightTeeVector: 10587, RightVectorBar: 10579, ShortDownArrow: 8595, ShortLeftArrow: 8592, SquareSuperset: 8848, TildeFullEqual: 8773, UpperLeftArrow: 8598, ZeroWidthSpace: 8203, curvearrowleft: 8630, doublebarwedge: 8966, downdownarrows: 8650, hookrightarrow: 8618, leftleftarrows: 8647, leftrightarrow: 8596, leftthreetimes: 8907, longrightarrow: 10230, looparrowright: 8620, nshortparallel: 8742, ntriangleright: 8939, rightarrowtail: 8611, rightharpoonup: 8640, trianglelefteq: 8884, upharpoonright: 8638, ApplyFunction: 8289, DifferentialD: 8518, DoubleLeftTee: 10980, DoubleUpArrow: 8657, LeftTeeVector: 10586, LeftVectorBar: 10578, LessFullEqual: 8806, LongLeftArrow: 10229, Longleftarrow: 10232, NotTildeEqual: 8772, NotTildeTilde: 8777, Poincareplane: 8460, PrecedesEqual: 10927, PrecedesTilde: 8830, RightArrowBar: 8677, RightTeeArrow: 8614, RightTriangle: 8883, RightUpVector: 8638, SucceedsEqual: 10928, SucceedsTilde: 8831, SupersetEqual: 8839, UpEquilibrium: 10606, VerticalTilde: 8768, VeryThinSpace: 8202, bigtriangleup: 9651, blacktriangle: 9652, divideontimes: 8903, fallingdotseq: 8786, hookleftarrow: 8617, leftarrowtail: 8610, leftharpoonup: 8636, longleftarrow: 10229, looparrowleft: 8619, measuredangle: 8737, ntriangleleft: 8938, shortparallel: 8741, smallsetminus: 8726, triangleright: 9657, upharpoonleft: 8639, DownArrowBar: 10515, DownTeeArrow: 8615, ExponentialE: 8519, GreaterEqual: 8805, GreaterTilde: 8819, HilbertSpace: 8459, HumpDownHump: 8782, Intersection: 8898, LeftArrowBar: 8676, LeftTeeArrow: 8612, LeftTriangle: 8882, LeftUpVector: 8639, NotCongruent: 8802, NotLessEqual: 8816, NotLessTilde: 8820, Proportional: 8733, RightCeiling: 8969, RoundImplies: 10608, ShortUpArrow: 8593, SquareSubset: 8847, UnderBracket: 9141, VerticalLine: 124, blacklozenge: 10731, exponentiale: 8519, risingdotseq: 8787, triangledown: 9663, triangleleft: 9667, CircleMinus: 8854, CircleTimes: 8855, Equilibrium: 8652, GreaterLess: 8823, LeftCeiling: 8968, LessGreater: 8822, MediumSpace: 8287, NotPrecedes: 8832, NotSucceeds: 8833, OverBracket: 9140, RightVector: 8640, Rrightarrow: 8667, RuleDelayed: 10740, SmallCircle: 8728, SquareUnion: 8852, SubsetEqual: 8838, UpDownArrow: 8597, Updownarrow: 8661, VerticalBar: 8739, backepsilon: 1014, blacksquare: 9642, circledcirc: 8858, circleddash: 8861, curlyeqprec: 8926, curlyeqsucc: 8927, diamondsuit: 9830, eqslantless: 10901, expectation: 8496, nRightarrow: 8655, nrightarrow: 8603, preccurlyeq: 8828, precnapprox: 10937, quaternions: 8461, straightphi: 981, succcurlyeq: 8829, succnapprox: 10938, thickapprox: 8776, updownarrow: 8597, Bernoullis: 8492, CirclePlus: 8853, EqualTilde: 8770, Fouriertrf: 8497, ImaginaryI: 8520, Laplacetrf: 8466, LeftVector: 8636, Lleftarrow: 8666, NotElement: 8713, NotGreater: 8815, Proportion: 8759, RightArrow: 8594, RightFloor: 8971, Rightarrow: 8658, TildeEqual: 8771, TildeTilde: 8776, UnderBrace: 9183, UpArrowBar: 10514, UpTeeArrow: 8613, circledast: 8859, complement: 8705, curlywedge: 8911, eqslantgtr: 10902, gtreqqless: 10892, lessapprox: 10885, lesseqqgtr: 10891, lmoustache: 9136, longmapsto: 10236, mapstodown: 8615, mapstoleft: 8612, nLeftarrow: 8653, nleftarrow: 8602, precapprox: 10935, rightarrow: 8594, rmoustache: 9137, sqsubseteq: 8849, sqsupseteq: 8850, subsetneqq: 10955, succapprox: 10936, supsetneqq: 10956, upuparrows: 8648, varepsilon: 949, varnothing: 8709, Backslash: 8726, CenterDot: 183, CircleDot: 8857, Congruent: 8801, Coproduct: 8720, DoubleDot: 168, DownArrow: 8595, DownBreve: 785, Downarrow: 8659, HumpEqual: 8783, LeftArrow: 8592, LeftFloor: 8970, Leftarrow: 8656, LessTilde: 8818, Mellintrf: 8499, MinusPlus: 8723, NotCupCap: 8813, NotExists: 8708, OverBrace: 9182, PlusMinus: 177, Therefore: 8756, ThinSpace: 8201, TripleDot: 8411, UnionPlus: 8846, backprime: 8245, backsimeq: 8909, bigotimes: 10754, centerdot: 183, checkmark: 10003, complexes: 8450, dotsquare: 8865, downarrow: 8595, gtrapprox: 10886, gtreqless: 8923, heartsuit: 9829, leftarrow: 8592, lesseqgtr: 8922, nparallel: 8742, nshortmid: 8740, nsubseteq: 8840, nsupseteq: 8841, pitchfork: 8916, rationals: 8474, spadesuit: 9824, subseteqq: 10949, subsetneq: 8842, supseteqq: 10950, supsetneq: 8843, therefore: 8756, triangleq: 8796, varpropto: 8733, DDotrahd: 10513, DotEqual: 8784, Integral: 8747, LessLess: 10913, NotEqual: 8800, NotTilde: 8769, PartialD: 8706, Precedes: 8826, RightTee: 8866, Succeeds: 8827, SuchThat: 8715, Superset: 8835, Uarrocir: 10569, UnderBar: 818, andslope: 10840, angmsdaa: 10664, angmsdab: 10665, angmsdac: 10666, angmsdad: 10667, angmsdae: 10668, angmsdaf: 10669, angmsdag: 10670, angmsdah: 10671, angrtvbd: 10653, approxeq: 8778, awconint: 8755, backcong: 8780, barwedge: 8965, bbrktbrk: 9142, bigoplus: 10753, bigsqcup: 10758, biguplus: 10756, bigwedge: 8896, boxminus: 8863, boxtimes: 8864, capbrcup: 10825, circledR: 174, circledS: 9416, cirfnint: 10768, clubsuit: 9827, cupbrcap: 10824, curlyvee: 8910, cwconint: 8754, doteqdot: 8785, dotminus: 8760, drbkarow: 10512, dzigrarr: 10239, elinters: 9191, emptyset: 8709, eqvparsl: 10725, fpartint: 10765, geqslant: 10878, gesdotol: 10884, gnapprox: 10890, hksearow: 10533, hkswarow: 10534, imagline: 8464, imagpart: 8465, infintie: 10717, integers: 8484, intercal: 8890, intlarhk: 10775, laemptyv: 10676, ldrushar: 10571, leqslant: 10877, lesdotor: 10883, llcorner: 8990, lnapprox: 10889, lrcorner: 8991, lurdshar: 10570, mapstoup: 8613, multimap: 8888, naturals: 8469, otimesas: 10806, parallel: 8741, plusacir: 10787, pointint: 10773, precneqq: 10933, precnsim: 8936, profalar: 9006, profline: 8978, profsurf: 8979, raemptyv: 10675, realpart: 8476, rppolint: 10770, rtriltri: 10702, scpolint: 10771, setminus: 8726, shortmid: 8739, smeparsl: 10724, sqsubset: 8847, sqsupset: 8848, subseteq: 8838, succneqq: 10934, succnsim: 8937, supseteq: 8839, thetasym: 977, thicksim: 8764, timesbar: 10801, triangle: 9653, triminus: 10810, trpezium: 9186, ulcorner: 8988, urcorner: 8989, varkappa: 1008, varsigma: 962, vartheta: 977, Because: 8757, Cayleys: 8493, Cconint: 8752, Cedilla: 184, Diamond: 8900, DownTee: 8868, Element: 8712, Epsilon: 917, Implies: 8658, LeftTee: 8867, NewLine: 10, NoBreak: 8288, NotLess: 8814, Omicron: 927, OverBar: 175, Product: 8719, UpArrow: 8593, Uparrow: 8657, Upsilon: 933, alefsym: 8501, angrtvb: 8894, angzarr: 9084, asympeq: 8781, backsim: 8765, because: 8757, bemptyv: 10672, between: 8812, bigcirc: 9711, bigodot: 10752, bigstar: 9733, boxplus: 8862, ccupssm: 10832, cemptyv: 10674, cirscir: 10690, coloneq: 8788, congdot: 10861, cudarrl: 10552, cudarrr: 10549, cularrp: 10557, curarrm: 10556, dbkarow: 10511, ddagger: 8225, ddotseq: 10871, demptyv: 10673, diamond: 8900, digamma: 989, dotplus: 8724, dwangle: 10662, epsilon: 949, eqcolon: 8789, equivDD: 10872, gesdoto: 10882, gtquest: 10876, gtrless: 8823, harrcir: 10568, intprod: 10812, isindot: 8949, larrbfs: 10527, larrsim: 10611, lbrksld: 10639, lbrkslu: 10637, ldrdhar: 10599, lesdoto: 10881, lessdot: 8918, lessgtr: 8822, lesssim: 8818, lotimes: 10804, lozenge: 9674, ltquest: 10875, luruhar: 10598, maltese: 10016, minusdu: 10794, napprox: 8777, natural: 9838, nearrow: 8599, nexists: 8708, notinva: 8713, notinvb: 8951, notinvc: 8950, notniva: 8716, notnivb: 8958, notnivc: 8957, npolint: 10772, nsqsube: 8930, nsqsupe: 8931, nvinfin: 10718, nwarrow: 8598, olcross: 10683, omicron: 959, orderof: 8500, orslope: 10839, pertenk: 8241, planckh: 8462, pluscir: 10786, plussim: 10790, plustwo: 10791, precsim: 8830, quatint: 10774, questeq: 8799, rarrbfs: 10528, rarrsim: 10612, rbrksld: 10638, rbrkslu: 10640, rdldhar: 10601, realine: 8475, rotimes: 10805, ruluhar: 10600, searrow: 8600, simplus: 10788, simrarr: 10610, subedot: 10947, submult: 10945, subplus: 10943, subrarr: 10617, succsim: 8831, supdsub: 10968, supedot: 10948, suphsub: 10967, suplarr: 10619, supmult: 10946, supplus: 10944, swarrow: 8601, topfork: 10970, triplus: 10809, tritime: 10811, uparrow: 8593, upsilon: 965, uwangle: 10663, vzigzag: 10650, zigrarr: 8669, Aacute: 193, Abreve: 258, Agrave: 192, Assign: 8788, Atilde: 195, Barwed: 8966, Bumpeq: 8782, Cacute: 262, Ccaron: 268, Ccedil: 199, Colone: 10868, Conint: 8751, CupCap: 8781, Dagger: 8225, Dcaron: 270, DotDot: 8412, Dstrok: 272, Eacute: 201, Ecaron: 282, Egrave: 200, Exists: 8707, ForAll: 8704, Gammad: 988, Gbreve: 286, Gcedil: 290, HARDcy: 1066, Hstrok: 294, Iacute: 205, Igrave: 204, Itilde: 296, Jsercy: 1032, Kcedil: 310, Lacute: 313, Lambda: 923, Lcaron: 317, Lcedil: 315, Lmidot: 319, Lstrok: 321, Nacute: 323, Ncaron: 327, Ncedil: 325, Ntilde: 209, Oacute: 211, Odblac: 336, Ograve: 210, Oslash: 216, Otilde: 213, Otimes: 10807, Racute: 340, Rarrtl: 10518, Rcaron: 344, Rcedil: 342, SHCHcy: 1065, SOFTcy: 1068, Sacute: 346, Scaron: 352, Scedil: 350, Square: 9633, Subset: 8912, Supset: 8913, Tcaron: 356, Tcedil: 354, Tstrok: 358, Uacute: 218, Ubreve: 364, Udblac: 368, Ugrave: 217, Utilde: 360, Vdashl: 10982, Verbar: 8214, Vvdash: 8874, Yacute: 221, Zacute: 377, Zcaron: 381, aacute: 225, abreve: 259, agrave: 224, andand: 10837, angmsd: 8737, angsph: 8738, apacir: 10863, approx: 8776, atilde: 227, barvee: 8893, barwed: 8965, becaus: 8757, bernou: 8492, bigcap: 8898, bigcup: 8899, bigvee: 8897, bkarow: 10509, bottom: 8869, bowtie: 8904, boxbox: 10697, bprime: 8245, brvbar: 166, bullet: 8226, bumpeq: 8783, cacute: 263, capand: 10820, capcap: 10827, capcup: 10823, capdot: 10816, ccaron: 269, ccedil: 231, circeq: 8791, cirmid: 10991, colone: 8788, commat: 64, compfn: 8728, conint: 8750, coprod: 8720, copysr: 8471, cularr: 8630, cupcap: 10822, cupcup: 10826, cupdot: 8845, curarr: 8631, curren: 164, cylcty: 9005, dagger: 8224, daleth: 8504, dcaron: 271, dfisht: 10623, divide: 247, divonx: 8903, dlcorn: 8990, dlcrop: 8973, dollar: 36, drcorn: 8991, drcrop: 8972, dstrok: 273, eacute: 233, easter: 10862, ecaron: 283, ecolon: 8789, egrave: 232, egsdot: 10904, elsdot: 10903, emptyv: 8709, emsp13: 8196, emsp14: 8197, eparsl: 10723, eqcirc: 8790, equals: 61, equest: 8799, female: 9792, ffilig: 64259, ffllig: 64260, forall: 8704, frac12: 189, frac13: 8531, frac14: 188, frac15: 8533, frac16: 8537, frac18: 8539, frac23: 8532, frac25: 8534, frac34: 190, frac35: 8535, frac38: 8540, frac45: 8536, frac56: 8538, frac58: 8541, frac78: 8542, gacute: 501, gammad: 989, gbreve: 287, gesdot: 10880, gesles: 10900, gtlPar: 10645, gtrarr: 10616, gtrdot: 8919, gtrsim: 8819, hairsp: 8202, hamilt: 8459, hardcy: 1098, hearts: 9829, hellip: 8230, hercon: 8889, homtht: 8763, horbar: 8213, hslash: 8463, hstrok: 295, hybull: 8259, hyphen: 8208, iacute: 237, igrave: 236, iiiint: 10764, iinfin: 10716, incare: 8453, inodot: 305, intcal: 8890, iquest: 191, isinsv: 8947, itilde: 297, jsercy: 1112, kappav: 1008, kcedil: 311, kgreen: 312, lAtail: 10523, lacute: 314, lagran: 8466, lambda: 955, langle: 10216, larrfs: 10525, larrhk: 8617, larrlp: 8619, larrpl: 10553, larrtl: 8610, latail: 10521, lbrace: 123, lbrack: 91, lcaron: 318, lcedil: 316, ldquor: 8222, lesdot: 10879, lesges: 10899, lfisht: 10620, lfloor: 8970, lharul: 10602, llhard: 10603, lmidot: 320, lmoust: 9136, loplus: 10797, lowast: 8727, lowbar: 95, lparlt: 10643, lrhard: 10605, lsaquo: 8249, lsquor: 8218, lstrok: 322, lthree: 8907, ltimes: 8905, ltlarr: 10614, ltrPar: 10646, mapsto: 8614, marker: 9646, mcomma: 10793, midast: 42, midcir: 10992, middot: 183, minusb: 8863, minusd: 8760, mnplus: 8723, models: 8871, mstpos: 8766, nVDash: 8879, nVdash: 8878, nacute: 324, ncaron: 328, ncedil: 326, nearhk: 10532, nequiv: 8802, nesear: 10536, nexist: 8708, nltrie: 8940, nprcue: 8928, nrtrie: 8941, nsccue: 8929, nsimeq: 8772, ntilde: 241, numero: 8470, nvDash: 8877, nvHarr: 10500, nvdash: 8876, nvlArr: 10498, nvrArr: 10499, nwarhk: 10531, nwnear: 10535, oacute: 243, odblac: 337, odsold: 10684, ograve: 242, ominus: 8854, origof: 8886, oslash: 248, otilde: 245, otimes: 8855, parsim: 10995, percnt: 37, period: 46, permil: 8240, phmmat: 8499, planck: 8463, plankv: 8463, plusdo: 8724, plusdu: 10789, plusmn: 177, preceq: 10927, primes: 8473, prnsim: 8936, propto: 8733, prurel: 8880, puncsp: 8200, qprime: 8279, rAtail: 10524, racute: 341, rangle: 10217, rarrap: 10613, rarrfs: 10526, rarrhk: 8618, rarrlp: 8620, rarrpl: 10565, rarrtl: 8611, ratail: 10522, rbrace: 125, rbrack: 93, rcaron: 345, rcedil: 343, rdquor: 8221, rfisht: 10621, rfloor: 8971, rharul: 10604, rmoust: 9137, roplus: 10798, rpargt: 10644, rsaquo: 8250, rsquor: 8217, rthree: 8908, rtimes: 8906, sacute: 347, scaron: 353, scedil: 351, scnsim: 8937, searhk: 10533, seswar: 10537, sfrown: 8994, shchcy: 1097, sigmaf: 962, sigmav: 962, simdot: 10858, smashp: 10803, softcy: 1100, solbar: 9023, spades: 9824, sqsube: 8849, sqsupe: 8850, square: 9633, squarf: 9642, ssetmn: 8726, ssmile: 8995, sstarf: 8902, subdot: 10941, subset: 8834, subsim: 10951, subsub: 10965, subsup: 10963, succeq: 10928, supdot: 10942, supset: 8835, supsim: 10952, supsub: 10964, supsup: 10966, swarhk: 10534, swnwar: 10538, target: 8982, tcaron: 357, tcedil: 355, telrec: 8981, there4: 8756, thetav: 977, thinsp: 8201, thksim: 8764, timesb: 8864, timesd: 10800, topbot: 9014, topcir: 10993, tprime: 8244, tridot: 9708, tstrok: 359, uacute: 250, ubreve: 365, udblac: 369, ufisht: 10622, ugrave: 249, ulcorn: 8988, ulcrop: 8975, urcorn: 8989, urcrop: 8974, utilde: 361, vangrt: 10652, varphi: 966, varrho: 1009, veebar: 8891, vellip: 8942, verbar: 124, wedbar: 10847, wedgeq: 8793, weierp: 8472, wreath: 8768, xoplus: 10753, xotime: 10754, xsqcup: 10758, xuplus: 10756, xwedge: 8896, yacute: 253, zacute: 378, zcaron: 382, zeetrf: 8488, AElig: 198, Acirc: 194, Alpha: 913, Amacr: 256, Aogon: 260, Aring: 197, Breve: 728, Ccirc: 264, Colon: 8759, Cross: 10799, Dashv: 10980, Delta: 916, Ecirc: 202, Emacr: 274, Eogon: 280, Equal: 10869, Gamma: 915, Gcirc: 284, Hacek: 711, Hcirc: 292, IJlig: 306, Icirc: 206, Imacr: 298, Iogon: 302, Iukcy: 1030, Jcirc: 308, Jukcy: 1028, Kappa: 922, OElig: 338, Ocirc: 212, Omacr: 332, Omega: 937, Prime: 8243, RBarr: 10512, Scirc: 348, Sigma: 931, THORN: 222, TRADE: 8482, TSHcy: 1035, Theta: 920, Tilde: 8764, Ubrcy: 1038, Ucirc: 219, Umacr: 362, Union: 8899, Uogon: 370, UpTee: 8869, Uring: 366, VDash: 8875, Vdash: 8873, Wcirc: 372, Wedge: 8896, Ycirc: 374, acirc: 226, acute: 180, aelig: 230, aleph: 8501, alpha: 945, amacr: 257, amalg: 10815, angle: 8736, angrt: 8735, angst: 8491, aogon: 261, aring: 229, asymp: 8776, awint: 10769, bcong: 8780, bdquo: 8222, bepsi: 1014, blank: 9251, blk12: 9618, blk14: 9617, blk34: 9619, block: 9608, boxDL: 9559, boxDR: 9556, boxDl: 9558, boxDr: 9555, boxHD: 9574, boxHU: 9577, boxHd: 9572, boxHu: 9575, boxUL: 9565, boxUR: 9562, boxUl: 9564, boxUr: 9561, boxVH: 9580, boxVL: 9571, boxVR: 9568, boxVh: 9579, boxVl: 9570, boxVr: 9567, boxdL: 9557, boxdR: 9554, boxdl: 9488, boxdr: 9484, boxhD: 9573, boxhU: 9576, boxhd: 9516, boxhu: 9524, boxuL: 9563, boxuR: 9560, boxul: 9496, boxur: 9492, boxvH: 9578, boxvL: 9569, boxvR: 9566, boxvh: 9532, boxvl: 9508, boxvr: 9500, breve: 728, bsemi: 8271, bsime: 8909, bsolb: 10693, bumpE: 10926, bumpe: 8783, caret: 8257, caron: 711, ccaps: 10829, ccirc: 265, ccups: 10828, cedil: 184, check: 10003, clubs: 9827, colon: 58, comma: 44, crarr: 8629, cross: 10007, csube: 10961, csupe: 10962, ctdot: 8943, cuepr: 8926, cuesc: 8927, cupor: 10821, cuvee: 8910, cuwed: 8911, cwint: 8753, dashv: 8867, dblac: 733, ddarr: 8650, delta: 948, dharl: 8643, dharr: 8642, diams: 9830, disin: 8946, doteq: 8784, dtdot: 8945, dtrif: 9662, duarr: 8693, duhar: 10607, eDDot: 10871, ecirc: 234, efDot: 8786, emacr: 275, empty: 8709, eogon: 281, eplus: 10865, epsiv: 949, eqsim: 8770, equiv: 8801, erDot: 8787, erarr: 10609, esdot: 8784, exist: 8707, fflig: 64256, filig: 64257, fllig: 64258, fltns: 9649, forkv: 10969, frasl: 8260, frown: 8994, gamma: 947, gcirc: 285, gescc: 10921, gimel: 8503, gneqq: 8809, gnsim: 8935, grave: 96, gsime: 10894, gsiml: 10896, gtcir: 10874, gtdot: 8919, harrw: 8621, hcirc: 293, hoarr: 8703, icirc: 238, iexcl: 161, iiint: 8749, iiota: 8489, ijlig: 307, imacr: 299, image: 8465, imath: 305, imped: 437, infin: 8734, iogon: 303, iprod: 10812, isinE: 8953, isins: 8948, isinv: 8712, iukcy: 1110, jcirc: 309, jmath: 567, jukcy: 1108, kappa: 954, lAarr: 8666, lBarr: 10510, langd: 10641, laquo: 171, larrb: 8676, lbarr: 10508, lbbrk: 10098, lbrke: 10635, lceil: 8968, ldquo: 8220, lescc: 10920, lhard: 8637, lharu: 8636, lhblk: 9604, llarr: 8647, lltri: 9722, lneqq: 8808, lnsim: 8934, loang: 10220, loarr: 8701, lobrk: 10214, lopar: 10629, lrarr: 8646, lrhar: 8651, lrtri: 8895, lsime: 10893, lsimg: 10895, lsquo: 8216, ltcir: 10873, ltdot: 8918, ltrie: 8884, ltrif: 9666, mDDot: 8762, mdash: 8212, micro: 181, minus: 8722, mumap: 8888, nabla: 8711, napos: 329, natur: 9838, ncong: 8775, ndash: 8211, neArr: 8663, nearr: 8599, ngsim: 8821, nhArr: 8654, nharr: 8622, nhpar: 10994, nlArr: 8653, nlarr: 8602, nless: 8814, nlsim: 8820, nltri: 8938, notin: 8713, notni: 8716, nprec: 8832, nrArr: 8655, nrarr: 8603, nrtri: 8939, nsime: 8772, nsmid: 8740, nspar: 8742, nsube: 8840, nsucc: 8833, nsupe: 8841, numsp: 8199, nwArr: 8662, nwarr: 8598, ocirc: 244, odash: 8861, oelig: 339, ofcir: 10687, ohbar: 10677, olarr: 8634, olcir: 10686, oline: 8254, omacr: 333, omega: 969, operp: 10681, oplus: 8853, orarr: 8635, order: 8500, ovbar: 9021, parsl: 11005, phone: 9742, plusb: 8862, pluse: 10866, pound: 163, prcue: 8828, prime: 8242, prnap: 10937, prsim: 8830, quest: 63, rAarr: 8667, rBarr: 10511, radic: 8730, rangd: 10642, range: 10661, raquo: 187, rarrb: 8677, rarrc: 10547, rarrw: 8605, ratio: 8758, rbarr: 10509, rbbrk: 10099, rbrke: 10636, rceil: 8969, rdquo: 8221, reals: 8477, rhard: 8641, rharu: 8640, rlarr: 8644, rlhar: 8652, rnmid: 10990, roang: 10221, roarr: 8702, robrk: 10215, ropar: 10630, rrarr: 8649, rsquo: 8217, rtrie: 8885, rtrif: 9656, sbquo: 8218, sccue: 8829, scirc: 349, scnap: 10938, scsim: 8831, sdotb: 8865, sdote: 10854, seArr: 8664, searr: 8600, setmn: 8726, sharp: 9839, sigma: 963, simeq: 8771, simgE: 10912, simlE: 10911, simne: 8774, slarr: 8592, smile: 8995, sqcap: 8851, sqcup: 8852, sqsub: 8847, sqsup: 8848, srarr: 8594, starf: 9733, strns: 175, subnE: 10955, subne: 8842, supnE: 10956, supne: 8843, swArr: 8665, swarr: 8601, szlig: 223, theta: 952, thkap: 8776, thorn: 254, tilde: 732, times: 215, trade: 8482, trisb: 10701, tshcy: 1115, twixt: 8812, ubrcy: 1118, ucirc: 251, udarr: 8645, udhar: 10606, uharl: 8639, uharr: 8638, uhblk: 9600, ultri: 9720, umacr: 363, uogon: 371, uplus: 8846, upsih: 978, uring: 367, urtri: 9721, utdot: 8944, utrif: 9652, uuarr: 8648, vBarv: 10985, vDash: 8872, varpi: 982, vdash: 8866, veeeq: 8794, vltri: 8882, vprop: 8733, vrtri: 8883, wcirc: 373, wedge: 8743, xcirc: 9711, xdtri: 9661, xhArr: 10234, xharr: 10231, xlArr: 10232, xlarr: 10229, xodot: 10752, xrArr: 10233, xrarr: 10230, xutri: 9651, ycirc: 375, Aopf: 120120, Ascr: 119964, Auml: 196, Barv: 10983, Beta: 914, Bopf: 120121, Bscr: 8492, CHcy: 1063, COPY: 169, Cdot: 266, Copf: 8450, Cscr: 119966, DJcy: 1026, DScy: 1029, DZcy: 1039, Darr: 8609, Dopf: 120123, Dscr: 119967, Edot: 278, Eopf: 120124, Escr: 8496, Esim: 10867, Euml: 203, Fopf: 120125, Fscr: 8497, GJcy: 1027, Gdot: 288, Gopf: 120126, Gscr: 119970, Hopf: 8461, Hscr: 8459, IEcy: 1045, IOcy: 1025, Idot: 304, Iopf: 120128, Iota: 921, Iscr: 8464, Iuml: 207, Jopf: 120129, Jscr: 119973, KHcy: 1061, KJcy: 1036, Kopf: 120130, Kscr: 119974, LJcy: 1033, Lang: 10218, Larr: 8606, Lopf: 120131, Lscr: 8466, Mopf: 120132, Mscr: 8499, NJcy: 1034, Nopf: 8469, Nscr: 119977, Oopf: 120134, Oscr: 119978, Ouml: 214, Popf: 8473, Pscr: 119979, QUOT: 34, Qopf: 8474, Qscr: 119980, Rang: 10219, Rarr: 8608, Ropf: 8477, Rscr: 8475, SHcy: 1064, Sopf: 120138, Sqrt: 8730, Sscr: 119982, Star: 8902, TScy: 1062, Topf: 120139, Tscr: 119983, Uarr: 8607, Uopf: 120140, Upsi: 978, Uscr: 119984, Uuml: 220, Vbar: 10987, Vert: 8214, Vopf: 120141, Vscr: 119985, Wopf: 120142, Wscr: 119986, Xopf: 120143, Xscr: 119987, YAcy: 1071, YIcy: 1031, YUcy: 1070, Yopf: 120144, Yscr: 119988, Yuml: 376, ZHcy: 1046, Zdot: 379, Zeta: 918, Zopf: 8484, Zscr: 119989, andd: 10844, andv: 10842, ange: 10660, aopf: 120146, apid: 8779, apos: 39, ascr: 119990, auml: 228, bNot: 10989, bbrk: 9141, beta: 946, beth: 8502, bnot: 8976, bopf: 120147, boxH: 9552, boxV: 9553, boxh: 9472, boxv: 9474, bscr: 119991, bsim: 8765, bsol: 92, bull: 8226, bump: 8782, cdot: 267, cent: 162, chcy: 1095, cirE: 10691, circ: 710, cire: 8791, comp: 8705, cong: 8773, copf: 120148, copy: 169, cscr: 119992, csub: 10959, csup: 10960, dArr: 8659, dHar: 10597, darr: 8595, dash: 8208, diam: 8900, djcy: 1106, dopf: 120149, dscr: 119993, dscy: 1109, dsol: 10742, dtri: 9663, dzcy: 1119, eDot: 8785, ecir: 8790, edot: 279, emsp: 8195, ensp: 8194, eopf: 120150, epar: 8917, epsi: 1013, escr: 8495, esim: 8770, euml: 235, euro: 8364, excl: 33, flat: 9837, fnof: 402, fopf: 120151, fork: 8916, fscr: 119995, gdot: 289, geqq: 8807, gjcy: 1107, gnap: 10890, gneq: 10888, gopf: 120152, gscr: 8458, gsim: 8819, gtcc: 10919, hArr: 8660, half: 189, harr: 8596, hbar: 8463, hopf: 120153, hscr: 119997, iecy: 1077, imof: 8887, iocy: 1105, iopf: 120154, iota: 953, iscr: 119998, isin: 8712, iuml: 239, jopf: 120155, jscr: 119999, khcy: 1093, kjcy: 1116, kopf: 120156, kscr: 120000, lArr: 8656, lHar: 10594, lang: 10216, larr: 8592, late: 10925, lcub: 123, ldca: 10550, ldsh: 8626, leqq: 8806, ljcy: 1113, lnap: 10889, lneq: 10887, lopf: 120157, lozf: 10731, lpar: 40, lscr: 120001, lsim: 8818, lsqb: 91, ltcc: 10918, ltri: 9667, macr: 175, male: 9794, malt: 10016, mlcp: 10971, mldr: 8230, mopf: 120158, mscr: 120002, nbsp: 160, ncap: 10819, ncup: 10818, ngeq: 8817, ngtr: 8815, nisd: 8954, njcy: 1114, nldr: 8229, nleq: 8816, nmid: 8740, nopf: 120159, npar: 8742, nscr: 120003, nsim: 8769, nsub: 8836, nsup: 8837, ntgl: 8825, ntlg: 8824, oast: 8859, ocir: 8858, odiv: 10808, odot: 8857, ogon: 731, oint: 8750, omid: 10678, oopf: 120160, opar: 10679, ordf: 170, ordm: 186, oror: 10838, oscr: 8500, osol: 8856, ouml: 246, para: 182, part: 8706, perp: 8869, phiv: 966, plus: 43, popf: 120161, prap: 10935, prec: 8826, prnE: 10933, prod: 8719, prop: 8733, pscr: 120005, qint: 10764, qopf: 120162, qscr: 120006, quot: 34, rArr: 8658, rHar: 10596, race: 10714, rang: 10217, rarr: 8594, rcub: 125, rdca: 10551, rdsh: 8627, real: 8476, rect: 9645, rhov: 1009, ring: 730, ropf: 120163, rpar: 41, rscr: 120007, rsqb: 93, rtri: 9657, scap: 10936, scnE: 10934, sdot: 8901, sect: 167, semi: 59, sext: 10038, shcy: 1096, sime: 8771, simg: 10910, siml: 10909, smid: 8739, smte: 10924, solb: 10692, sopf: 120164, spar: 8741, squf: 9642, sscr: 120008, star: 9734, subE: 10949, sube: 8838, succ: 8827, sung: 9834, sup1: 185, sup2: 178, sup3: 179, supE: 10950, supe: 8839, tbrk: 9140, tdot: 8411, tint: 8749, toea: 10536, topf: 120165, tosa: 10537, trie: 8796, tscr: 120009, tscy: 1094, uArr: 8657, uHar: 10595, uarr: 8593, uopf: 120166, upsi: 965, uscr: 120010, utri: 9653, uuml: 252, vArr: 8661, vBar: 10984, varr: 8597, vert: 124, vopf: 120167, vscr: 120011, wopf: 120168, wscr: 120012, xcap: 8898, xcup: 8899, xmap: 10236, xnis: 8955, xopf: 120169, xscr: 120013, xvee: 8897, yacy: 1103, yicy: 1111, yopf: 120170, yscr: 120014, yucy: 1102, yuml: 255, zdot: 380, zeta: 950, zhcy: 1078, zopf: 120171, zscr: 120015, zwnj: 8204, AMP: 38, Acy: 1040, Afr: 120068, And: 10835, Bcy: 1041, Bfr: 120069, Cap: 8914, Cfr: 8493, Chi: 935, Cup: 8915, Dcy: 1044, Del: 8711, Dfr: 120071, Dot: 168, ENG: 330, ETH: 208, Ecy: 1069, Efr: 120072, Eta: 919, Fcy: 1060, Ffr: 120073, Gcy: 1043, Gfr: 120074, Hat: 94, Hfr: 8460, Icy: 1048, Ifr: 8465, Int: 8748, Jcy: 1049, Jfr: 120077, Kcy: 1050, Kfr: 120078, Lcy: 1051, Lfr: 120079, Lsh: 8624, Map: 10501, Mcy: 1052, Mfr: 120080, Ncy: 1053, Nfr: 120081, Not: 10988, Ocy: 1054, Ofr: 120082, Pcy: 1055, Pfr: 120083, Phi: 934, Psi: 936, Qfr: 120084, REG: 174, Rcy: 1056, Rfr: 8476, Rho: 929, Rsh: 8625, Scy: 1057, Sfr: 120086, Sub: 8912, Sum: 8721, Sup: 8913, Tab: 9, Tau: 932, Tcy: 1058, Tfr: 120087, Ucy: 1059, Ufr: 120088, Vcy: 1042, Vee: 8897, Vfr: 120089, Wfr: 120090, Xfr: 120091, Ycy: 1067, Yfr: 120092, Zcy: 1047, Zfr: 8488, acd: 8767, acy: 1072, afr: 120094, amp: 38, and: 8743, ang: 8736, apE: 10864, ape: 8778, ast: 42, bcy: 1073, bfr: 120095, bot: 8869, cap: 8745, cfr: 120096, chi: 967, cir: 9675, cup: 8746, dcy: 1076, deg: 176, dfr: 120097, die: 168, div: 247, dot: 729, ecy: 1101, efr: 120098, egs: 10902, ell: 8467, els: 10901, eng: 331, eta: 951, eth: 240, fcy: 1092, ffr: 120099, gEl: 10892, gap: 10886, gcy: 1075, gel: 8923, geq: 8805, ges: 10878, gfr: 120100, ggg: 8921, glE: 10898, gla: 10917, glj: 10916, gnE: 8809, gne: 10888, hfr: 120101, icy: 1080, iff: 8660, ifr: 120102, int: 8747, jcy: 1081, jfr: 120103, kcy: 1082, kfr: 120104, lEg: 10891, lap: 10885, lat: 10923, lcy: 1083, leg: 8922, leq: 8804, les: 10877, lfr: 120105, lgE: 10897, lnE: 8808, lne: 10887, loz: 9674, lrm: 8206, lsh: 8624, map: 8614, mcy: 1084, mfr: 120106, mho: 8487, mid: 8739, nap: 8777, ncy: 1085, nfr: 120107, nge: 8817, ngt: 8815, nis: 8956, niv: 8715, nle: 8816, nlt: 8814, not: 172, npr: 8832, nsc: 8833, num: 35, ocy: 1086, ofr: 120108, ogt: 10689, ohm: 8486, olt: 10688, ord: 10845, orv: 10843, par: 8741, pcy: 1087, pfr: 120109, phi: 966, piv: 982, prE: 10931, pre: 10927, psi: 968, qfr: 120110, rcy: 1088, reg: 174, rfr: 120111, rho: 961, rlm: 8207, rsh: 8625, scE: 10932, sce: 10928, scy: 1089, sfr: 120112, shy: 173, sim: 8764, smt: 10922, sol: 47, squ: 9633, sub: 8834, sum: 8721, sup: 8835, tau: 964, tcy: 1090, tfr: 120113, top: 8868, ucy: 1091, ufr: 120114, uml: 168, vcy: 1074, vee: 8744, vfr: 120115, wfr: 120116, xfr: 120117, ycy: 1099, yen: 165, yfr: 120118, zcy: 1079, zfr: 120119, zwj: 8205, DD: 8517, GT: 62, Gg: 8921, Gt: 8811, Im: 8465, LT: 60, Ll: 8920, Lt: 8810, Mu: 924, Nu: 925, Or: 10836, Pi: 928, Pr: 10939, Re: 8476, Sc: 10940, Xi: 926, ac: 8766, af: 8289, ap: 8776, dd: 8518, ee: 8519, eg: 10906, el: 10905, gE: 8807, ge: 8805, gg: 8811, gl: 8823, gt: 62, ic: 8291, ii: 8520, in: 8712, it: 8290, lE: 8806, le: 8804, lg: 8822, ll: 8810, lt: 60, mp: 8723, mu: 956, ne: 8800, ni: 8715, nu: 957, oS: 9416, or: 8744, pi: 960, pm: 177, pr: 8826, rx: 8478, sc: 8827, wp: 8472, wr: 8768, xi: 958, }; const windows_1252 = [ 8364, 129, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338, 141, 381, 143, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250, 339, 157, 382, 376, ]; const entity_pattern = new RegExp( `&(#?(?:x[\\w\\d]+|\\d+|${Object.keys(entities).join('|')}));?`, 'g' ); function decode_character_references(html) { return html.replace(entity_pattern, (match, entity) => { let code; // Handle named entities if (entity[0] !== '#') { code = entities[entity]; } else if (entity[1] === 'x') { code = parseInt(entity.substring(2), 16); } else { code = parseInt(entity.substring(1), 10); } if (!code) { return match; } return String.fromCodePoint(validate_code(code)); }); } const NUL = 0; // some code points are verboten. If we were inserting HTML, the browser would replace the illegal // code points with alternatives in some cases - since we're bypassing that mechanism, we need // to replace them ourselves // // Source: http://en.wikipedia.org/wiki/Character_encodings_in_HTML#Illegal_characters function validate_code(code) { // line feed becomes generic whitespace if (code === 10) { return 32; } // ASCII range. (Why someone would use HTML entities for ASCII characters I don't know, but...) if (code < 128) { return code; } // code points 128-159 are dealt with leniently by browsers, but they're incorrect. We need // to correct the mistake or we'll end up with missing € signs and so on if (code <= 159) { return windows_1252[code - 128]; } // basic multilingual plane if (code < 55296) { return code; } // UTF-16 surrogate halves if (code <= 57343) { return NUL; } // rest of the basic multilingual plane if (code <= 65535) { return code; } // supplementary multilingual plane 0x10000 - 0x1ffff if (code >= 65536 && code <= 131071) { return code; } // supplementary ideographic plane 0x20000 - 0x2ffff if (code >= 131072 && code <= 196607) { return code; } return NUL; } // Adapted from https://github.com/acornjs/acorn/blob/6584815dca7440e00de841d1dad152302fdd7ca5/src/tokenize.js // Reproduced under MIT License https://github.com/acornjs/acorn/blob/master/LICENSE function full_char_code_at(str, i) { let code = str.charCodeAt(i); if (code <= 0xd7ff || code >= 0xe000) return code; let next = str.charCodeAt(i + 1); return (code << 10) + next - 0x35fdc00; } const reserved = new Set([ 'arguments', 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'enum', 'eval', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'implements', 'import', 'in', 'instanceof', 'interface', 'let', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'static', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield', ]); const void_element_names = /^(?:area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/; function is_void(name) { return void_element_names.test(name) || name.toLowerCase() === '!doctype'; } function fuzzymatch(name, names) { const set = new FuzzySet(names); const matches = set.get(name); return matches && matches[0] && matches[0][0] > 0.7 ? matches[0][1] : null; } // adapted from https://github.com/Glench/fuzzyset.js/blob/master/lib/fuzzyset.js // BSD Licensed const GRAM_SIZE_LOWER = 2; const GRAM_SIZE_UPPER = 3; // return an edit distance from 0 to 1 function _distance(str1, str2) { if (str1 === null && str2 === null) throw 'Trying to compare two null values'; if (str1 === null || str2 === null) return 0; str1 = String(str1); str2 = String(str2); const distance = levenshtein(str1, str2); if (str1.length > str2.length) { return 1 - distance / str1.length; } else { return 1 - distance / str2.length; } } // helper functions function levenshtein(str1, str2) { const current = []; let prev; let value; for (let i = 0; i <= str2.length; i++) { for (let j = 0; j <= str1.length; j++) { if (i && j) { if (str1.charAt(j - 1) === str2.charAt(i - 1)) { value = prev; } else { value = Math.min(current[j], current[j - 1], prev) + 1; } } else { value = i + j; } prev = current[j]; current[j] = value; } } return current.pop(); } const non_word_regex = /[^\w, ]+/; function iterate_grams(value, gram_size = 2) { const simplified = '-' + value.toLowerCase().replace(non_word_regex, '') + '-'; const len_diff = gram_size - simplified.length; const results = []; if (len_diff > 0) { for (let i = 0; i < len_diff; ++i) { value += '-'; } } for (let i = 0; i < simplified.length - gram_size + 1; ++i) { results.push(simplified.slice(i, i + gram_size)); } return results; } function gram_counter(value, gram_size = 2) { // return an object where key=gram, value=number of occurrences const result = {}; const grams = iterate_grams(value, gram_size); let i = 0; for (i; i < grams.length; ++i) { if (grams[i] in result) { result[grams[i]] += 1; } else { result[grams[i]] = 1; } } return result; } function sort_descending(a, b) { return b[0] - a[0]; } class FuzzySet { __init() {this.exact_set = {};} __init2() {this.match_dict = {};} __init3() {this.items = {};} constructor(arr) {FuzzySet.prototype.__init.call(this);FuzzySet.prototype.__init2.call(this);FuzzySet.prototype.__init3.call(this); // initialization for (let i = GRAM_SIZE_LOWER; i < GRAM_SIZE_UPPER + 1; ++i) { this.items[i] = []; } // add all the items to the set for (let i = 0; i < arr.length; ++i) { this.add(arr[i]); } } add(value) { const normalized_value = value.toLowerCase(); if (normalized_value in this.exact_set) { return false; } let i = GRAM_SIZE_LOWER; for (i; i < GRAM_SIZE_UPPER + 1; ++i) { this._add(value, i); } } _add(value, gram_size) { const normalized_value = value.toLowerCase(); const items = this.items[gram_size] || []; const index = items.length; items.push(0); const gram_counts = gram_counter(normalized_value, gram_size); let sum_of_square_gram_counts = 0; let gram; let gram_count; for (gram in gram_counts) { gram_count = gram_counts[gram]; sum_of_square_gram_counts += Math.pow(gram_count, 2); if (gram in this.match_dict) { this.match_dict[gram].push([index, gram_count]); } else { this.match_dict[gram] = [[index, gram_count]]; } } const vector_normal = Math.sqrt(sum_of_square_gram_counts); items[index] = [vector_normal, normalized_value]; this.items[gram_size] = items; this.exact_set[normalized_value] = value; }; get(value) { const normalized_value = value.toLowerCase(); const result = this.exact_set[normalized_value]; if (result) { return [[1, result]]; } let results = []; // start with high gram size and if there are no results, go to lower gram sizes for ( let gram_size = GRAM_SIZE_UPPER; gram_size >= GRAM_SIZE_LOWER; --gram_size ) { results = this.__get(value, gram_size); if (results) { return results; } } return null; } __get(value, gram_size) { const normalized_value = value.toLowerCase(); const matches = {}; const gram_counts = gram_counter(normalized_value, gram_size); const items = this.items[gram_size]; let sum_of_square_gram_counts = 0; let gram; let gram_count; let i; let index; let other_gram_count; for (gram in gram_counts) { gram_count = gram_counts[gram]; sum_of_square_gram_counts += Math.pow(gram_count, 2); if (gram in this.match_dict) { for (i = 0; i < this.match_dict[gram].length; ++i) { index = this.match_dict[gram][i][0]; other_gram_count = this.match_dict[gram][i][1]; if (index in matches) { matches[index] += gram_count * other_gram_count; } else { matches[index] = gram_count * other_gram_count; } } } } const vector_normal = Math.sqrt(sum_of_square_gram_counts); let results = []; let match_score; // build a results list of [score, str] for (const match_index in matches) { match_score = matches[match_index]; results.push([ match_score / (vector_normal * items[match_index][0]), items[match_index][1], ]); } results.sort(sort_descending); let new_results = []; const end_index = Math.min(50, results.length); // truncate somewhat arbitrarily to 50 for (let i = 0; i < end_index; ++i) { new_results.push([ _distance(results[i][1], normalized_value), results[i][1], ]); } results = new_results; results.sort(sort_descending); new_results = []; for (let i = 0; i < results.length; ++i) { if (results[i][0] == results[0][0]) { new_results.push([results[i][0], this.exact_set[results[i][1]]]); } } return new_results; }; } function list$1(items, conjunction = 'or') { if (items.length === 1) return items[0]; return `${items.slice(0, -1).join(', ')} ${conjunction} ${items[ items.length - 1 ]}`; } const valid_tag_name = /^\!?[a-zA-Z]{1,}:?[a-zA-Z0-9\-]*/; const meta_tags = new Map([ ['svelte:head', 'Head'], ['svelte:options', 'Options'], ['svelte:window', 'Window'], ['svelte:body', 'Body'] ]); const valid_meta_tags = Array.from(meta_tags.keys()).concat('svelte:self', 'svelte:component'); const specials = new Map([ [ 'script', { read: read_script, property: 'js', }, ], [ 'style', { read: read_style, property: 'css', }, ], ]); const SELF = /^svelte:self(?=[\s\/>])/; const COMPONENT = /^svelte:component(?=[\s\/>])/; // based on http://developers.whatwg.org/syntax.html#syntax-tag-omission const disallowed_contents = new Map([ ['li', new Set(['li'])], ['dt', new Set(['dt', 'dd'])], ['dd', new Set(['dt', 'dd'])], [ 'p', new Set( 'address article aside blockquote div dl fieldset footer form h1 h2 h3 h4 h5 h6 header hgroup hr main menu nav ol p pre section table ul'.split( ' ' ) ), ], ['rt', new Set(['rt', 'rp'])], ['rp', new Set(['rt', 'rp'])], ['optgroup', new Set(['optgroup'])], ['option', new Set(['option', 'optgroup'])], ['thead', new Set(['tbody', 'tfoot'])], ['tbody', new Set(['tbody', 'tfoot'])], ['tfoot', new Set(['tbody'])], ['tr', new Set(['tr', 'tbody'])], ['td', new Set(['td', 'th', 'tr'])], ['th', new Set(['td', 'th', 'tr'])], ]); function parent_is_head(stack) { let i = stack.length; while (i--) { const { type } = stack[i]; if (type === 'Head') return true; if (type === 'Element' || type === 'InlineComponent') return false; } return false; } function tag(parser) { const start = parser.index++; let parent = parser.current(); if (parser.eat('!--')) { const data = parser.read_until(/-->/); parser.eat('-->', true, 'comment was left open, expected -->'); parser.current().children.push({ start, end: parser.index, type: 'Comment', data, }); return; } const is_closing_tag = parser.eat('/'); const name = read_tag_name(parser); if (meta_tags.has(name)) { const slug = meta_tags.get(name).toLowerCase(); if (is_closing_tag) { if ( (name === 'svelte:window' || name === 'svelte:body') && parser.current().children.length ) { parser.error({ code: `invalid-${name.slice(7)}-content`, message: `<${name}> cannot have children` }, parser.current().children[0].start); } } else { if (name in parser.meta_tags) { parser.error({ code: `duplicate-${slug}`, message: `A component can only have one <${name}> tag` }, start); } if (parser.stack.length > 1) { parser.error({ code: `invalid-${slug}-placement`, message: `<${name}> tags cannot be inside elements or blocks` }, start); } parser.meta_tags[name] = true; } } const type = meta_tags.has(name) ? meta_tags.get(name) : (/[A-Z]/.test(name[0]) || name === 'svelte:self' || name === 'svelte:component') ? 'InlineComponent' : name === 'title' && parent_is_head(parser.stack) ? 'Title' : name === 'slot' && !parser.customElement ? 'Slot' : 'Element'; const element = { start, end: null, // filled in later type, name, attributes: [], children: [], }; parser.allow_whitespace(); if (is_closing_tag) { if (is_void(name)) { parser.error({ code: `invalid-void-content`, message: `<${name}> is a void element and cannot have children, or a closing tag` }, start); } parser.eat('>', true); // close any elements that don't have their own closing tags, e.g. <div><p></div> while (parent.name !== name) { if (parent.type !== 'Element') parser.error({ code: `invalid-closing-tag`, message: `</${name}> attempted to close an element that was not open` }, start); parent.end = start; parser.stack.pop(); parent = parser.current(); } parent.end = parser.index; parser.stack.pop(); return; } else if (disallowed_contents.has(parent.name)) { // can this be a child of the parent element, or does it implicitly // close it, like `<li>one<li>two`? if (disallowed_contents.get(parent.name).has(name)) { parent.end = start; parser.stack.pop(); } } const unique_names = new Set(); let attribute; while ((attribute = read_attribute(parser, unique_names))) { element.attributes.push(attribute); parser.allow_whitespace(); } if (name === 'svelte:component') { const index = element.attributes.findIndex(attr => attr.type === 'Attribute' && attr.name === 'this'); if (!~index) { parser.error({ code: `missing-component-definition`, message: `<svelte:component> must have a 'this' attribute` }, start); } const definition = element.attributes.splice(index, 1)[0]; if (definition.value === true || definition.value.length !== 1 || definition.value[0].type === 'Text') { parser.error({ code: `invalid-component-definition`, message: `invalid component definition` }, definition.start); } element.expression = definition.value[0].expression; } // special cases – top-level <script> and <style> if (specials.has(name) && parser.stack.length === 1) { const special = specials.get(name); parser.eat('>', true); const content = special.read(parser, start, element.attributes); if (content) parser[special.property].push(content); return; } parser.current().children.push(element); const self_closing = parser.eat('/') || is_void(name); parser.eat('>', true); if (self_closing) { // don't push self-closing elements onto the stack element.end = parser.index; } else if (name === 'textarea') { // special case element.children = read_sequence( parser, () => parser.template.slice(parser.index, parser.index + 11) === '</textarea>' ); parser.read(/<\/textarea>/); element.end = parser.index; } else if (name === 'script') { // special case const start = parser.index; const data = parser.read_until(/<\/script>/); const end = parser.index; element.children.push({ start, end, type: 'Text', data }); parser.eat('</script>', true); element.end = parser.index; } else if (name === 'style') { // special case const start = parser.index; const data = parser.read_until(/<\/style>/); const end = parser.index; element.children.push({ start, end, type: 'Text', data }); parser.eat('</style>', true); } else { parser.stack.push(element); } } function read_tag_name(parser) { const start = parser.index; if (parser.read(SELF)) { // check we're inside a block, otherwise this // will cause infinite recursion let i = parser.stack.length; let legal = false; while (i--) { const fragment = parser.stack[i]; if (fragment.type === 'IfBlock' || fragment.type === 'EachBlock') { legal = true; break; } } if (!legal) { parser.error({ code: `invalid-self-placement`, message: `<svelte:self> components can only exist inside if-blocks or each-blocks` }, start); } return 'svelte:self'; } if (parser.read(COMPONENT)) return 'svelte:component'; const name = parser.read_until(/(\s|\/|>)/); if (meta_tags.has(name)) return name; if (name.startsWith('svelte:')) { const match = fuzzymatch(name.slice(7), valid_meta_tags); let message = `Valid <svelte:...> tag names are ${list$1(valid_meta_tags)}`; if (match) message += ` (did you mean '${match}'?)`; parser.error({ code: 'invalid-tag-name', message }, start); } if (!valid_tag_name.test(name)) { parser.error({ code: `invalid-tag-name`, message: `Expected valid tag name` }, start); } return name; } function read_attribute(parser, unique_names) { const start = parser.index; if (parser.eat('{')) { parser.allow_whitespace(); if (parser.eat('...')) { const expression = read_expression(parser); parser.allow_whitespace(); parser.eat('}', true); return { start, end: parser.index, type: 'Spread', expression }; } else { const value_start = parser.index; const name = parser.read_identifier(); parser.allow_whitespace(); parser.eat('}', true); return { start, end: parser.index, type: 'Attribute', name, value: [{ start: value_start, end: value_start + name.length, type: 'AttributeShorthand', expression: { start: value_start, end: value_start + name.length, type: 'Identifier', name } }] }; } } let name = parser.read_until(/[\s=\/>"']/); if (!name) return null; let end = parser.index; parser.allow_whitespace(); const colon_index = name.indexOf(':'); const type = colon_index !== -1 && get_directive_type(name.slice(0, colon_index)); if (unique_names.has(name)) { parser.error({ code: `duplicate-attribute`, message: 'Attributes need to be unique' }, start); } if (type !== "EventHandler") { unique_names.add(name); } let value = true; if (parser.eat('=')) { value = read_attribute_value(parser); end = parser.index; } else if (parser.match_regex(/["']/)) { parser.error({ code: `unexpected-token`, message: `Expected =` }, parser.index); } if (type) { const [directive_name, ...modifiers] = name.slice(colon_index + 1).split('|'); if (type === 'Ref') { parser.error({ code: `invalid-ref-directive`, message: `The ref directive is no longer supported — use \`bind:this={${directive_name}}\` instead` }, start); } if (value[0]) { if (value.length > 1 || value[0].type === 'Text') { parser.error({ code: `invalid-directive-value`, message: `Directive value must be a JavaScript expression enclosed in curly braces` }, value[0].start); } } const directive = { start, end, type, name: directive_name, modifiers, expression: (value[0] && value[0].expression) || null }; if (type === 'Transition') { const direction = name.slice(0, colon_index); directive.intro = direction === 'in' || direction === 'transition'; directive.outro = direction === 'out' || direction === 'transition'; } if (!directive.expression && (type === 'Binding' || type === 'Class')) { directive.expression = { start: directive.start + colon_index + 1, end: directive.end, type: 'Identifier', name: directive.name }; } return directive; } return { start, end, type: 'Attribute', name, value, }; } function get_directive_type(name) { if (name === 'use') return 'Action'; if (name === 'animate') return 'Animation'; if (name === 'bind') return 'Binding'; if (name === 'class') return 'Class'; if (name === 'on') return 'EventHandler'; if (name === 'let') return 'Let'; if (name === 'ref') return 'Ref'; if (name === 'in' || name === 'out' || name === 'transition') return 'Transition'; } function read_attribute_value(parser) { const quote_mark = parser.eat(`'`) ? `'` : parser.eat(`"`) ? `"` : null; const regex = ( quote_mark === `'` ? /'/ : quote_mark === `"` ? /"/ : /(\/>|[\s"'=<>`])/ ); const value = read_sequence(parser, () => !!parser.match_regex(regex)); if (quote_mark) parser.index += 1; return value; } function read_sequence(parser, done) { let current_chunk = { start: parser.index, end: null, type: 'Text', data: '', }; const chunks = []; while (parser.index < parser.template.length) { const index = parser.index; if (done()) { current_chunk.end = parser.index; if (current_chunk.data) chunks.push(current_chunk); chunks.forEach(chunk => { if (chunk.type === 'Text') chunk.data = decode_character_references(chunk.data); }); return chunks; } else if (parser.eat('{')) { if (current_chunk.data) { current_chunk.end = index; chunks.push(current_chunk); } parser.allow_whitespace(); const expression = read_expression(parser); parser.allow_whitespace(); parser.eat('}', true); chunks.push({ start: index, end: parser.index, type: 'MustacheTag', expression, }); current_chunk = { start: parser.index, end: null, type: 'Text', data: '', }; } else { current_chunk.data += parser.template[parser.index++]; } } parser.error({ code: `unexpected-eof`, message: `Unexpected end of input` }); } function error_on_assignment_pattern(parser) { if (parser.eat('=')) { parser.error({ code: 'invalid-assignment-pattern', message: 'Assignment patterns are not supported' }, parser.index - 1); } } function error_on_rest_pattern_not_last(parser) { parser.error({ code: 'rest-pattern-not-last', message: 'Rest destructuring expected to be last' }, parser.index); } function read_context(parser) { const context = { start: parser.index, end: null, type: null }; if (parser.eat('[')) { context.type = 'ArrayPattern'; context.elements = []; do { parser.allow_whitespace(); const lastContext = context.elements[context.elements.length - 1]; if (lastContext && lastContext.type === 'RestIdentifier') { error_on_rest_pattern_not_last(parser); } if (parser.template[parser.index] === ',') { context.elements.push(null); } else { context.elements.push(read_context(parser)); parser.allow_whitespace(); } } while (parser.eat(',')); error_on_assignment_pattern(parser); parser.eat(']', true); context.end = parser.index; } else if (parser.eat('{')) { context.type = 'ObjectPattern'; context.properties = []; do { parser.allow_whitespace(); if (parser.eat('...')) { parser.allow_whitespace(); const start = parser.index; const name = parser.read_identifier(); const key = { start, end: parser.index, type: 'Identifier', name }; const property = { start, end: parser.index, type: 'Property', kind: 'rest', shorthand: true, key, value: key }; context.properties.push(property); parser.allow_whitespace(); if (parser.eat(',')) { parser.error({ code: `comma-after-rest`, message: `Comma is not permitted after the rest element` }, parser.index - 1); } break; } const start = parser.index; const name = parser.read_identifier(); const key = { start, end: parser.index, type: 'Identifier', name }; parser.allow_whitespace(); const value = parser.eat(':') ? (parser.allow_whitespace(), read_context(parser)) : key; const property = { start, end: value.end, type: 'Property', kind: 'init', shorthand: value.type === 'Identifier' && value.name === name, key, value }; context.properties.push(property); parser.allow_whitespace(); } while (parser.eat(',')); error_on_assignment_pattern(parser); parser.eat('}', true); context.end = parser.index; } else if (parser.eat('...')) { const name = parser.read_identifier(); if (name) { context.type = 'RestIdentifier'; context.end = parser.index; context.name = name; } else { parser.error({ code: 'invalid-context', message: 'Expected a rest pattern' }); } } else { const name = parser.read_identifier(); if (name) { context.type = 'Identifier'; context.end = parser.index; context.name = name; } else { parser.error({ code: 'invalid-context', message: 'Expected a name, array pattern or object pattern' }); } error_on_assignment_pattern(parser); } return context; } const whitespace = /[ \t\r\n]/; function trim_start(str) { let i = 0; while (whitespace.test(str[i])) i += 1; return str.slice(i); } function trim_end(str) { let i = str.length; while (whitespace.test(str[i - 1])) i -= 1; return str.slice(0, i); } function trim_whitespace(block, trim_before, trim_after) { if (!block.children || block.children.length === 0) return; // AwaitBlock const first_child = block.children[0]; const last_child = block.children[block.children.length - 1]; if (first_child.type === 'Text' && trim_before) { first_child.data = trim_start(first_child.data); if (!first_child.data) block.children.shift(); } if (last_child.type === 'Text' && trim_after) { last_child.data = trim_end(last_child.data); if (!last_child.data) block.children.pop(); } if (block.else) { trim_whitespace(block.else, trim_before, trim_after); } if (first_child.elseif) { trim_whitespace(first_child, trim_before, trim_after); } } function mustache(parser) { const start = parser.index; parser.index += 1; parser.allow_whitespace(); // {/if}, {/each} or {/await} if (parser.eat('/')) { let block = parser.current(); let expected; if (block.type === 'ElseBlock' || block.type === 'PendingBlock' || block.type === 'ThenBlock' || block.type === 'CatchBlock') { block.end = start; parser.stack.pop(); block = parser.current(); expected = 'await'; } if (block.type === 'IfBlock') { expected = 'if'; } else if (block.type === 'EachBlock') { expected = 'each'; } else if (block.type === 'AwaitBlock') { expected = 'await'; } else { parser.error({ code: `unexpected-block-close`, message: `Unexpected block closing tag` }); } parser.eat(expected, true); parser.allow_whitespace(); parser.eat('}', true); while (block.elseif) { block.end = parser.index; parser.stack.pop(); block = parser.current(); if (block.else) { block.else.end = start; } } // strip leading/trailing whitespace as necessary const char_before = parser.template[block.start - 1]; const char_after = parser.template[parser.index]; const trim_before = !char_before || whitespace.test(char_before); const trim_after = !char_after || whitespace.test(char_after); trim_whitespace(block, trim_before, trim_after); block.end = parser.index; parser.stack.pop(); } else if (parser.eat(':else')) { if (parser.eat('if')) { parser.error({ code: 'invalid-elseif', message: `'elseif' should be 'else if'` }); } parser.allow_whitespace(); // :else if if (parser.eat('if')) { const block = parser.current(); if (block.type !== 'IfBlock') parser.error({ code: `invalid-elseif-placement`, message: 'Cannot have an {:else if ...} block outside an {#if ...} block' }); parser.require_whitespace(); const expression = read_expression(parser); parser.allow_whitespace(); parser.eat('}', true); block.else = { start: parser.index, end: null, type: 'ElseBlock', children: [ { start: parser.index, end: null, type: 'IfBlock', elseif: true, expression, children: [], }, ], }; parser.stack.push(block.else.children[0]); } // :else else { const block = parser.current(); if (block.type !== 'IfBlock' && block.type !== 'EachBlock') { parser.error({ code: `invalid-else-placement`, message: 'Cannot have an {:else} block outside an {#if ...} or {#each ...} block' }); } parser.allow_whitespace(); parser.eat('}', true); block.else = { start: parser.index, end: null, type: 'ElseBlock', children: [], }; parser.stack.push(block.else); } } else if (parser.eat(':then')) { // TODO DRY out this and the next section const pending_block = parser.current(); if (pending_block.type === 'PendingBlock') { pending_block.end = start; parser.stack.pop(); const await_block = parser.current(); if (!parser.eat('}')) { parser.require_whitespace(); await_block.value = parser.read_identifier(); parser.allow_whitespace(); parser.eat('}', true); } const then_block = { start, end: null, type: 'ThenBlock', children: [], skip: false }; await_block.then = then_block; parser.stack.push(then_block); } } else if (parser.eat(':catch')) { const then_block = parser.current(); if (then_block.type === 'ThenBlock') { then_block.end = start; parser.stack.pop(); const await_block = parser.current(); if (!parser.eat('}')) { parser.require_whitespace(); await_block.error = parser.read_identifier(); parser.allow_whitespace(); parser.eat('}', true); } const catch_block = { start, end: null, type: 'CatchBlock', children: [], skip: false }; await_block.catch = catch_block; parser.stack.push(catch_block); } } else if (parser.eat('#')) { // {#if foo}, {#each foo} or {#await foo} let type; if (parser.eat('if')) { type = 'IfBlock'; } else if (parser.eat('each')) { type = 'EachBlock'; } else if (parser.eat('await')) { type = 'AwaitBlock'; } else { parser.error({ code: `expected-block-type`, message: `Expected if, each or await` }); } parser.require_whitespace(); const expression = read_expression(parser); const block = type === 'AwaitBlock' ? { start, end: null, type, expression, value: null, error: null, pending: { start: null, end: null, type: 'PendingBlock', children: [], skip: true }, then: { start: null, end: null, type: 'ThenBlock', children: [], skip: true }, catch: { start: null, end: null, type: 'CatchBlock', children: [], skip: true }, } : { start, end: null, type, expression, children: [], }; parser.allow_whitespace(); // {#each} blocks must declare a context – {#each list as item} if (type === 'EachBlock') { parser.eat('as', true); parser.require_whitespace(); block.context = read_context(parser); parser.allow_whitespace(); if (parser.eat(',')) { parser.allow_whitespace(); block.index = parser.read_identifier(); if (!block.index) parser.error({ code: `expected-name`, message: `Expected name` }); parser.allow_whitespace(); } if (parser.eat('(')) { parser.allow_whitespace(); block.key = read_expression(parser); parser.allow_whitespace(); parser.eat(')', true); parser.allow_whitespace(); } } let await_block_shorthand = type === 'AwaitBlock' && parser.eat('then'); if (await_block_shorthand) { parser.require_whitespace(); block.value = parser.read_identifier(); parser.allow_whitespace(); } parser.eat('}', true); parser.current().children.push(block); parser.stack.push(block); if (type === 'AwaitBlock') { let child_block; if (await_block_shorthand) { block.then.skip = false; child_block = block.then; } else { block.pending.skip = false; child_block = block.pending; } child_block.start = parser.index; parser.stack.push(child_block); } } else if (parser.eat('@html')) { // {@html content} tag parser.require_whitespace(); const expression = read_expression(parser); parser.allow_whitespace(); parser.eat('}', true); parser.current().children.push({ start, end: parser.index, type: 'RawMustacheTag', expression, }); } else if (parser.eat('@debug')) { let identifiers; // Implies {@debug} which indicates "debug all" if (parser.read(/\s*}/)) { identifiers = []; } else { const expression = read_expression(parser); identifiers = expression.type === 'SequenceExpression' ? expression.expressions : [expression]; identifiers.forEach(node => { if (node.type !== 'Identifier') { parser.error({ code: 'invalid-debug-args', message: '{@debug ...} arguments must be identifiers, not arbitrary expressions' }, node.start); } }); parser.allow_whitespace(); parser.eat('}', true); } parser.current().children.push({ start, end: parser.index, type: 'DebugTag', identifiers }); } else { const expression = read_expression(parser); parser.allow_whitespace(); parser.eat('}', true); parser.current().children.push({ start, end: parser.index, type: 'MustacheTag', expression, }); } } function text(parser) { const start = parser.index; let data = ''; while ( parser.index < parser.template.length && !parser.match('<') && !parser.match('{') ) { data += parser.template[parser.index++]; } parser.current().children.push({ start, end: parser.index, type: 'Text', data: decode_character_references(data), }); } function fragment(parser) { if (parser.match('<')) { return tag; } if (parser.match('{')) { return mustache; } return text; } function getLocator(source, options) { if (options === void 0) { options = {}; } var offsetLine = options.offsetLine || 0; var offsetColumn = options.offsetColumn || 0; var originalLines = source.split('\n'); var start = 0; var lineRanges = originalLines.map(function (line, i) { var end = start + line.length + 1; var range = { start: start, end: end, line: i }; start = end; return range; }); var i = 0; function rangeContains(range, index) { return range.start <= index && index < range.end; } function getLocation(range, index) { return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index }; } function locate(search, startIndex) { if (typeof search === 'string') { search = source.indexOf(search, startIndex || 0); } var range = lineRanges[i]; var d = search >= range.end ? 1 : -1; while (range) { if (rangeContains(range, search)) return getLocation(range, search); i += d; range = lineRanges[i]; } } return locate; } function locate(source, search, options) { if (typeof options === 'number') { throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument'); } return getLocator(source, options)(search, options && options.startIndex); } function tabs_to_spaces(str) { return str.replace(/^\t+/, match => match.split('\t').join(' ')); } function get_code_frame( source, line, column ) { const lines = source.split('\n'); const frame_start = Math.max(0, line - 2); const frame_end = Math.min(line + 3, lines.length); const digits = String(frame_end + 1).length; return lines .slice(frame_start, frame_end) .map((str, i) => { const isErrorLine = frame_start + i === line; let line_num = String(i + frame_start + 1); while (line_num.length < digits) line_num = ` ${line_num}`; if (isErrorLine) { const indicator = repeat(' ', digits + 2 + tabs_to_spaces(str.slice(0, column)).length) + '^'; return `${line_num}: ${tabs_to_spaces(str)}\n${indicator}`; } return `${line_num}: ${tabs_to_spaces(str)}`; }) .join('\n'); } class CompileError extends Error { toString() { return `${this.message} (${this.start.line}:${this.start.column})\n${this.frame}`; } } function error$1(message, props ) { const error = new CompileError(message); error.name = props.name; const start = locate(props.source, props.start, { offsetLine: 1 }); const end = locate(props.source, props.end || props.start, { offsetLine: 1 }); error.code = props.code; error.start = start; error.end = end; error.pos = props.start; error.filename = props.filename; error.frame = get_code_frame(props.source, start.line - 1, start.column); throw error; } class Parser$2 { __init() {this.index = 0;} __init2() {this.stack = [];} __init3() {this.css = [];} __init4() {this.js = [];} __init5() {this.meta_tags = {};} constructor(template, options) {Parser$2.prototype.__init.call(this);Parser$2.prototype.__init2.call(this);Parser$2.prototype.__init3.call(this);Parser$2.prototype.__init4.call(this);Parser$2.prototype.__init5.call(this); if (typeof template !== 'string') { throw new TypeError('Template must be a string'); } this.template = template.replace(/\s+$/, ''); this.filename = options.filename; this.customElement = options.customElement; this.html = { start: null, end: null, type: 'Fragment', children: [], }; this.stack.push(this.html); let state = fragment; while (this.index < this.template.length) { state = state(this) || fragment; } if (this.stack.length > 1) { const current = this.current(); const type = current.type === 'Element' ? `<${current.name}>` : 'Block'; const slug = current.type === 'Element' ? 'element' : 'block'; this.error({ code: `unclosed-${slug}`, message: `${type} was left open` }, current.start); } if (state !== fragment) { this.error({ code: `unexpected-eof`, message: 'Unexpected end of input' }); } if (this.html.children.length) { let start = this.html.children[0] && this.html.children[0].start; while (/\s/.test(template[start])) start += 1; let end = this.html.children[this.html.children.length - 1] && this.html.children[this.html.children.length - 1].end; while (/\s/.test(template[end - 1])) end -= 1; this.html.start = start; this.html.end = end; } else { this.html.start = this.html.end = null; } } current() { return this.stack[this.stack.length - 1]; } acorn_error(err) { this.error({ code: `parse-error`, message: err.message.replace(/ \(\d+:\d+\)$/, '') }, err.pos); } error({ code, message }, index = this.index) { error$1(message, { name: 'ParseError', code, source: this.template, start: index, filename: this.filename }); } eat(str, required, message) { if (this.match(str)) { this.index += str.length; return true; } if (required) { this.error({ code: `unexpected-${this.index === this.template.length ? 'eof' : 'token'}`, message: message || `Expected ${str}` }); } return false; } match(str) { return this.template.slice(this.index, this.index + str.length) === str; } match_regex(pattern) { const match = pattern.exec(this.template.slice(this.index)); if (!match || match.index !== 0) return null; return match[0]; } allow_whitespace() { while ( this.index < this.template.length && whitespace.test(this.template[this.index]) ) { this.index++; } } read(pattern) { const result = this.match_regex(pattern); if (result) this.index += result.length; return result; } read_identifier() { const start = this.index; let i = this.index; const code = full_char_code_at(this.template, i); if (!isIdentifierStart(code, true)) return null; i += code <= 0xffff ? 1 : 2; while (i < this.template.length) { const code = full_char_code_at(this.template, i); if (!isIdentifierChar(code, true)) break; i += code <= 0xffff ? 1 : 2; } const identifier = this.template.slice(this.index, this.index = i); if (reserved.has(identifier)) { this.error({ code: `unexpected-reserved-word`, message: `'${identifier}' is a reserved word in JavaScript and cannot be used here` }, start); } return identifier; } read_until(pattern) { if (this.index >= this.template.length) this.error({ code: `unexpected-eof`, message: 'Unexpected end of input' }); const start = this.index; const match = pattern.exec(this.template.slice(start)); if (match) { this.index = start + match.index; return this.template.slice(start, this.index); } this.index = this.template.length; return this.template.slice(start); } require_whitespace() { if (!whitespace.test(this.template[this.index])) { this.error({ code: `missing-whitespace`, message: `Expected whitespace` }); } this.allow_whitespace(); } } function parse$2( template, options = {} ) { const parser = new Parser$2(template, options); // TODO we way want to allow multiple <style> tags — // one scoped, one global. for now, only allow one if (parser.css.length > 1) { parser.error({ code: 'duplicate-style', message: 'You can only have one top-level <style> tag per component' }, parser.css[1].start); } const instance_scripts = parser.js.filter(script => script.context === 'default'); const module_scripts = parser.js.filter(script => script.context === 'module'); if (instance_scripts.length > 1) { parser.error({ code: `invalid-script`, message: `A component can only have one instance-level <script> element` }, instance_scripts[1].start); } if (module_scripts.length > 1) { parser.error({ code: `invalid-script`, message: `A component can only have one <script context="module"> element` }, module_scripts[1].start); } return { html: parser.html, css: parser.css[0], instance: instance_scripts[0], module: module_scripts[0] }; } exports.Parser = Parser$2; exports.default = parse$2; //# sourceMappingURL=index.js.map
28.112881
4,351
0.62314
da8a9868ca3808b4337f9e30d70d93cdaa94991b
219
php
PHP
classes/report/fields/test.php
adityazad/atoum
52b632b57d3c535b2910968bbef92190c769ae36
[ "BSD-3-Clause" ]
1
2021-03-12T08:38:17.000Z
2021-03-12T08:38:17.000Z
classes/report/fields/test.php
adityazad/atoum
52b632b57d3c535b2910968bbef92190c769ae36
[ "BSD-3-Clause" ]
null
null
null
classes/report/fields/test.php
adityazad/atoum
52b632b57d3c535b2910968bbef92190c769ae36
[ "BSD-3-Clause" ]
1
2021-10-31T05:12:58.000Z
2021-10-31T05:12:58.000Z
<?php namespace mageekguy\atoum\report\fields; use mageekguy\atoum, mageekguy\atoum\report ; abstract class test extends report\field { public abstract function setWithTest(atoum\test $test, $event = null); } ?>
13.6875
71
0.753425
560ef11c28354ccd5f7542f0c6cabbc292ce5c04
2,661
rs
Rust
src/clkg0_clk/ctl1.rs
Colin-Suckow/ADuCM302x
f0d62f2b527184e1f192d4f2153f5827fd57fe3c
[ "Unlicense" ]
null
null
null
src/clkg0_clk/ctl1.rs
Colin-Suckow/ADuCM302x
f0d62f2b527184e1f192d4f2153f5827fd57fe3c
[ "Unlicense" ]
null
null
null
src/clkg0_clk/ctl1.rs
Colin-Suckow/ADuCM302x
f0d62f2b527184e1f192d4f2153f5827fd57fe3c
[ "Unlicense" ]
null
null
null
#[doc = "Reader of register CTL1"] pub type R = crate::R<u32, super::CTL1>; #[doc = "Writer for register CTL1"] pub type W = crate::W<u32, super::CTL1>; #[doc = "Register CTL1 `reset()`'s with value 0x0010_0404"] impl crate::ResetValue for super::CTL1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x0010_0404 } } #[doc = "Reader of field `HCLKDIVCNT`"] pub type HCLKDIVCNT_R = crate::R<u8, u8>; #[doc = "Write proxy for field `HCLKDIVCNT`"] pub struct HCLKDIVCNT_W<'a> { w: &'a mut W, } impl<'a> HCLKDIVCNT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x3f) | ((value as u32) & 0x3f); self.w } } #[doc = "Reader of field `PCLKDIVCNT`"] pub type PCLKDIVCNT_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PCLKDIVCNT`"] pub struct PCLKDIVCNT_W<'a> { w: &'a mut W, } impl<'a> PCLKDIVCNT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x3f << 8)) | (((value as u32) & 0x3f) << 8); self.w } } #[doc = "Reader of field `ACLKDIVCNT`"] pub type ACLKDIVCNT_R = crate::R<u8, u8>; #[doc = "Write proxy for field `ACLKDIVCNT`"] pub struct ACLKDIVCNT_W<'a> { w: &'a mut W, } impl<'a> ACLKDIVCNT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 16)) | (((value as u32) & 0xff) << 16); self.w } } impl R { #[doc = "Bits 0:5 - HCLK Divide Count"] #[inline(always)] pub fn hclkdivcnt(&self) -> HCLKDIVCNT_R { HCLKDIVCNT_R::new((self.bits & 0x3f) as u8) } #[doc = "Bits 8:13 - PCLK Divide Count"] #[inline(always)] pub fn pclkdivcnt(&self) -> PCLKDIVCNT_R { PCLKDIVCNT_R::new(((self.bits >> 8) & 0x3f) as u8) } #[doc = "Bits 16:23 - ACLK Divide Count"] #[inline(always)] pub fn aclkdivcnt(&self) -> ACLKDIVCNT_R { ACLKDIVCNT_R::new(((self.bits >> 16) & 0xff) as u8) } } impl W { #[doc = "Bits 0:5 - HCLK Divide Count"] #[inline(always)] pub fn hclkdivcnt(&mut self) -> HCLKDIVCNT_W { HCLKDIVCNT_W { w: self } } #[doc = "Bits 8:13 - PCLK Divide Count"] #[inline(always)] pub fn pclkdivcnt(&mut self) -> PCLKDIVCNT_W { PCLKDIVCNT_W { w: self } } #[doc = "Bits 16:23 - ACLK Divide Count"] #[inline(always)] pub fn aclkdivcnt(&mut self) -> ACLKDIVCNT_W { ACLKDIVCNT_W { w: self } } }
29.898876
86
0.570086
a33251536b39193730e2057f858c0ce1597ee0f7
3,862
java
Java
kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth/builtin/EncTsPreauth.java
dwalluck/directory-kerby
bac1ba2db016775856ed1e1fd94b56026c57817c
[ "Apache-2.0" ]
97
2015-03-17T08:47:38.000Z
2022-03-25T09:39:56.000Z
kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth/builtin/EncTsPreauth.java
dwalluck/directory-kerby
bac1ba2db016775856ed1e1fd94b56026c57817c
[ "Apache-2.0" ]
29
2015-11-18T16:10:40.000Z
2021-08-30T13:05:15.000Z
kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth/builtin/EncTsPreauth.java
nikosnikolaidis/directory-kerby
dd78ce66ba792b919f9afa3d1a3b6fd95956679b
[ "Apache-2.0" ]
82
2015-03-17T08:01:49.000Z
2022-03-21T08:13:19.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.client.preauth.builtin; import org.apache.kerby.kerberos.kerb.KrbCodec; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.client.preauth.AbstractPreauthPlugin; import org.apache.kerby.kerberos.kerb.client.request.KdcRequest; import org.apache.kerby.kerberos.kerb.common.EncryptionUtil; import org.apache.kerby.kerberos.kerb.preauth.PaFlag; import org.apache.kerby.kerberos.kerb.preauth.PaFlags; import org.apache.kerby.kerberos.kerb.preauth.PluginRequestContext; import org.apache.kerby.kerberos.kerb.preauth.builtin.EncTsPreauthMeta; import org.apache.kerby.kerberos.kerb.type.base.EncryptedData; import org.apache.kerby.kerberos.kerb.type.base.KeyUsage; import org.apache.kerby.kerberos.kerb.type.pa.PaData; import org.apache.kerby.kerberos.kerb.type.pa.PaDataEntry; import org.apache.kerby.kerberos.kerb.type.pa.PaDataType; import org.apache.kerby.kerberos.kerb.type.pa.PaEncTsEnc; public class EncTsPreauth extends AbstractPreauthPlugin { public EncTsPreauth() { super(new EncTsPreauthMeta()); } /** * {@inheritDoc} */ @Override public void prepareQuestions(KdcRequest kdcRequest, PluginRequestContext requestContext) throws KrbException { kdcRequest.needAsKey(); } /** * {@inheritDoc} */ @Override public void tryFirst(KdcRequest kdcRequest, PluginRequestContext requestContext, PaData outPadata) throws KrbException { if (kdcRequest.getAsKey() == null) { kdcRequest.needAsKey(); } outPadata.addElement(makeEntry(kdcRequest)); } /** * {@inheritDoc} */ @Override public boolean process(KdcRequest kdcRequest, PluginRequestContext requestContext, PaDataEntry inPadata, PaData outPadata) throws KrbException { if (kdcRequest.getAsKey() == null) { kdcRequest.needAsKey(); } outPadata.addElement(makeEntry(kdcRequest)); return true; } /** * {@inheritDoc} */ @Override public PaFlags getFlags(PaDataType paType) { PaFlags paFlags = new PaFlags(0); paFlags.setFlag(PaFlag.PA_REAL); return paFlags; } /** * Make padata entry. * * @param kdcRequest The kdc request * @return PaDataEntry to be made. */ private PaDataEntry makeEntry(KdcRequest kdcRequest) throws KrbException { PaEncTsEnc paTs = new PaEncTsEnc(); paTs.setPaTimestamp(kdcRequest.getPreauthTime()); EncryptedData paDataValue = EncryptionUtil.seal(paTs, kdcRequest.getAsKey(), KeyUsage.AS_REQ_PA_ENC_TS); PaDataEntry tsPaEntry = new PaDataEntry(); tsPaEntry.setPaDataType(PaDataType.ENC_TIMESTAMP); tsPaEntry.setPaDataValue(KrbCodec.encode(paDataValue)); return tsPaEntry; } }
33.582609
91
0.683066
7be979dfabcaa1cc5ae07508bda5294b6be43860
2,123
cc
C++
misc/wcc_check.cc
rox906/libgrape-lite
a0af7ebde9eb44cd83ecb79ee6c3ed958e647741
[ "Apache-2.0" ]
255
2020-07-16T11:25:25.000Z
2022-03-30T08:45:07.000Z
misc/wcc_check.cc
rox906/libgrape-lite
a0af7ebde9eb44cd83ecb79ee6c3ed958e647741
[ "Apache-2.0" ]
67
2020-07-22T02:00:40.000Z
2022-03-23T02:30:52.000Z
misc/wcc_check.cc
rox906/libgrape-lite
a0af7ebde9eb44cd83ecb79ee6c3ed958e647741
[ "Apache-2.0" ]
69
2020-07-20T13:02:01.000Z
2022-03-31T06:29:24.000Z
/** Copyright 2020 Alibaba Group Holding Limited. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <inttypes.h> #include <stdio.h> #include <map> #include <unordered_map> int main(int argc, char** argv) { if (argc < 3) { printf("usage: ./wcc_check <result-1> <result-2>\n"); return 0; } std::map<uint64_t, int> cluster_name1, cluster_name2; FILE* fin1 = fopen(argv[1], "r"); FILE* fin2 = fopen(argv[2], "r"); uint64_t vid1, cid1, vid2, cid2; int ret = 0; while (fscanf(fin1, "%" PRIu64 "%" PRIu64, &vid1, &cid1) != EOF) { if (fscanf(fin2, "%" PRIu64 "%" PRIu64, &vid2, &cid2) == EOF) { printf("Vertex number not match...\n"); ret = 1; break; } if (vid1 != vid2) { printf("Vertex id not match: %" PRIu64 " v.s. %" PRIu64 "\n", vid1, vid2); ret = 1; break; } auto iter1 = cluster_name1.find(cid1); auto iter2 = cluster_name2.find(cid2); if (iter1 == cluster_name1.end() && iter2 == cluster_name2.end()) { int new_cname = cluster_name1.size(); cluster_name1[cid1] = new_cname; cluster_name2[cid2] = new_cname; } else if (iter1 != cluster_name1.end() && iter2 != cluster_name2.end()) { if (iter1->second != iter2->second) { printf("Vertex cluster name not match - A: %" PRIu64 " v.s. %" PRIu64 "\n", vid1, vid2); ret = 1; break; } } else { printf("Vertex cluster name not match - B: %" PRIu64 " v.s. %" PRIu64 "\n", vid1, vid2); ret = 1; break; } } fclose(fin1); fclose(fin2); return ret; }
27.217949
80
0.606689
7ad5083ebc9c706a472fb7a802d1393b2ceb8f47
567
cs
C#
sample/Jobs/InjectSampleJob.cs
khanhna/SilkierQuartz
03f7340d6148128af55998edc01f379273465ad7
[ "MIT" ]
200
2020-06-06T12:10:39.000Z
2022-03-26T20:38:59.000Z
sample/Jobs/InjectSampleJob.cs
khanhna/SilkierQuartz
03f7340d6148128af55998edc01f379273465ad7
[ "MIT" ]
77
2020-06-22T03:32:50.000Z
2022-03-23T11:40:27.000Z
sample/Jobs/InjectSampleJob.cs
khanhna/SilkierQuartz
03f7340d6148128af55998edc01f379273465ad7
[ "MIT" ]
37
2020-06-19T05:43:07.000Z
2022-03-24T00:13:54.000Z
using Microsoft.Extensions.Options; using Quartz; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace SilkierQuartz.Example.Jobs { public class InjectSampleJob : IJob { InjectProperty _options; public InjectSampleJob(IOptions<InjectProperty> options) { _options = options.Value; } public Task Execute(IJobExecutionContext context) { Console.WriteLine(_options.WriteText); return Task.CompletedTask; } } }
22.68
64
0.664903
d16c0ce738cb805486e3514375d473e8899ce32e
3,912
cs
C#
src/BuildSoft.OscCore.Test/Runtime/TestUtil.cs
ChanyaVRC/OscCore
46f1a3b61d66cef321150e0fabbfb64a59dd30e9
[ "MIT" ]
null
null
null
src/BuildSoft.OscCore.Test/Runtime/TestUtil.cs
ChanyaVRC/OscCore
46f1a3b61d66cef321150e0fabbfb64a59dd30e9
[ "MIT" ]
1
2022-02-22T00:40:57.000Z
2022-02-23T15:40:33.000Z
src/BuildSoft.OscCore.Test/Runtime/TestUtil.cs
ChanyaVRC/OscCore
46f1a3b61d66cef321150e0fabbfb64a59dd30e9
[ "MIT" ]
null
null
null
using System; namespace BuildSoft.OscCore.Tests; public static class TestUtil { static readonly byte[] k_Swap32 = new byte[4]; static readonly byte[] k_Swap64 = new byte[8]; public static int ReverseBytes(this int self) { k_Swap32[0] = (byte)(self >> 24); k_Swap32[1] = (byte)(self >> 16); k_Swap32[2] = (byte)(self >> 8); k_Swap32[3] = (byte)(self); return BitConverter.ToInt32(k_Swap32, 0); } public static float ReverseBytes(this float self) { var fBytes = BitConverter.GetBytes(self); k_Swap32[0] = fBytes[3]; k_Swap32[1] = fBytes[2]; k_Swap32[2] = fBytes[1]; k_Swap32[3] = fBytes[0]; return BitConverter.ToSingle(k_Swap32, 0); } public static double ReverseBytes(this double self) { var dBytes = BitConverter.GetBytes(self); k_Swap64[0] = dBytes[7]; k_Swap64[1] = dBytes[6]; k_Swap64[2] = dBytes[5]; k_Swap64[3] = dBytes[4]; k_Swap64[4] = dBytes[3]; k_Swap64[5] = dBytes[2]; k_Swap64[6] = dBytes[1]; k_Swap64[7] = dBytes[0]; return BitConverter.ToDouble(k_Swap64, 0); } public static byte[] ReversedCopy(byte[] source) { var copy = new byte[source.Length]; Array.Copy(source, copy, source.Length); Array.Reverse(copy); return copy; } public static byte[] RandomFloatBytes(int byteCount = 2048) { var bytes = new byte[byteCount]; for (int i = 0; i < bytes.Length; i += 4) { var f = Random.Shared.Next() * 2f - 1f; var fBytes = BitConverter.GetBytes(f); for (int j = 0; j < fBytes.Length; j++) { bytes[i + j] = fBytes[j]; } } return bytes; } public static byte[] RandomIntBytes(int byteCount = 2048) { var bytes = new byte[byteCount]; for (int i = 0; i < bytes.Length; i += 4) { var iValue = Random.Shared.Next(-1000, 1000); var iBytes = BitConverter.GetBytes(iValue); for (int j = 0; j < iBytes.Length; j++) bytes[i + j] = iBytes[j]; } return bytes; } public static byte[] RandomColor32Bytes(int byteCount = 2048) { var bytes = new byte[byteCount]; for (int i = 0; i < bytes.Length; i += 4) { var iValue = Random.Shared.Next(0, 255); var iBytes = BitConverter.GetBytes(iValue); for (int j = 0; j < iBytes.Length; j++) bytes[i + j] = iBytes[j]; } return bytes; } public static byte[] RandomMidiBytes(int byteCount = 2048) { var bytes = new byte[byteCount]; for (int i = 0; i < bytes.Length; i += 4) { var port = (byte)Random.Shared.Next(1, 16); var status = (byte)Random.Shared.Next(0, 127); var data1 = (byte)Random.Shared.Next(10, 255); var data2 = (byte)Random.Shared.Next(10, 255); bytes[i] = port; bytes[i + 1] = status; bytes[i + 2] = data1; bytes[i + 3] = data2; } return bytes; } public static byte[] RandomTimestampBytes(int count = 2048) { var bytes = new byte[count]; for (int i = 0; i < bytes.Length; i += 8) { var seconds = Random.Shared.Next(0, 255); var sBytes = BitConverter.GetBytes(seconds); for (int j = 0; j < sBytes.Length; j++) bytes[i + j] = sBytes[j]; var fractions = Random.Shared.Next(0, 10000000); var fBytes = BitConverter.GetBytes(fractions); var end = 4 + fBytes.Length; for (int j = 4; j < end; j++) bytes[i + j] = fBytes[j - 4]; } return bytes; } }
28.977778
65
0.518405
384937a4fe03461b231ee2ceb80ad3af41baf81a
450
cs
C#
AndroidEntryKeyboardTest/AndroidEntryKeyboardTestPage.xaml.cs
Depechie/XamarinFormsAndroidSoftKeyboardToggle
923c62cbee051792b86faebf0fedf6c4fc295d7b
[ "MIT" ]
null
null
null
AndroidEntryKeyboardTest/AndroidEntryKeyboardTestPage.xaml.cs
Depechie/XamarinFormsAndroidSoftKeyboardToggle
923c62cbee051792b86faebf0fedf6c4fc295d7b
[ "MIT" ]
null
null
null
AndroidEntryKeyboardTest/AndroidEntryKeyboardTestPage.xaml.cs
Depechie/XamarinFormsAndroidSoftKeyboardToggle
923c62cbee051792b86faebf0fedf6c4fc295d7b
[ "MIT" ]
1
2020-01-21T03:12:06.000Z
2020-01-21T03:12:06.000Z
using Xamarin.Forms; namespace AndroidEntryKeyboardTest { public partial class AndroidEntryKeyboardTestPage : ContentPage { public AndroidEntryKeyboardTestPage() { InitializeComponent(); } private void OnShowKeyboardClicked(object sender, System.EventArgs e) { BarcodeEntry.IsSoftKeyboardEnabled = true; } private void OnUnfocused(object sender, FocusEventArgs e) { BarcodeEntry.IsSoftKeyboardEnabled = false; } } }
19.565217
71
0.764444
8da3b8ba1fcd03b933f517c69eec1b4cc5c498ac
541
js
JavaScript
src/useWindowSize.js
oven425/Web_Study
64db5204362422d0f145268879d1c7ae00373226
[ "MIT" ]
null
null
null
src/useWindowSize.js
oven425/Web_Study
64db5204362422d0f145268879d1c7ae00373226
[ "MIT" ]
null
null
null
src/useWindowSize.js
oven425/Web_Study
64db5204362422d0f145268879d1c7ae00373226
[ "MIT" ]
null
null
null
import { useEffect, useState } from "react"; export const useWindowSize=()=>{ const [size, setSize]=useState({width:0,height:0}); useEffect(()=>{ function onResize(){ setSize({width:window.innerWidth,height:window.innerHeight}); //console.log(`useWindowSize width:${window.innerWidth} height:${window.innerHeight}`); } window.addEventListener("resize", onResize); return()=>{ window.removeEventListener("resize", onResize); } },[]); return size; }
31.823529
99
0.604436
cdd12707ead4a83ea7d4e1f6f2c039b470d832a8
2,810
cs
C#
SP_ASPNET_1/SP_ASPNET_1/DbFiles/Operations/BlogPostOperations.cs
Feelav/SP_ASPNET
4c043505d26702daf61979aede246ab2fb54d21d
[ "MIT" ]
null
null
null
SP_ASPNET_1/SP_ASPNET_1/DbFiles/Operations/BlogPostOperations.cs
Feelav/SP_ASPNET
4c043505d26702daf61979aede246ab2fb54d21d
[ "MIT" ]
null
null
null
SP_ASPNET_1/SP_ASPNET_1/DbFiles/Operations/BlogPostOperations.cs
Feelav/SP_ASPNET
4c043505d26702daf61979aede246ab2fb54d21d
[ "MIT" ]
null
null
null
using SP_ASPNET_1.DbFiles.UnitsOfWork; using SP_ASPNET_1.Models; using SP_ASPNET_1.ViewModels; using SP_ASPNET_1.BusinessLogic; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; namespace SP_ASPNET_1.DbFiles.Operations { public class BlogPostOperations { private SchoolUnitOfWork _unitOfWork = new SchoolUnitOfWork(); public async Task<BlogIndexViewModel> GetBlogIndexViewModelAsync() { List<BlogPost> blogPosts = (await _unitOfWork.BlogPostSchoolRepository.GetAsync(null, b => b.OrderByDescending(d => d.DateTime), "Author")).ToList(); return new BlogIndexViewModel() { BlogPosts = blogPosts.GetRange(1, blogPosts.Count - 1), RecentBlogPost = blogPosts.Take(1).FirstOrDefault() }; } public BlogIndexViewModel GetBlogIndexViewModel() { List<BlogPost> blogPosts = _unitOfWork.BlogPostSchoolRepository .Get(null, b => b.OrderByDescending(d => d.DateTime), "Author").ToList(); return new BlogIndexViewModel() { BlogPosts = blogPosts.GetRange(1, blogPosts.Count - 1), RecentBlogPost = blogPosts.Take(1).FirstOrDefault() }; } public BlogPost GetBlogPostByIdD(int id) { return _unitOfWork.BlogPostSchoolRepository.GetByID(id); } public BlogPost GetLatestBlogPost() { return _unitOfWork.BlogPostSchoolRepository.Get(null, x => x.OrderByDescending(entity => entity.DateTime)) .FirstOrDefault(); } public BlogPost GetRandomBlogPost() { List<BlogPost> posts = _unitOfWork.BlogPostSchoolRepository.Get(null, x => x.OrderByDescending(entity => entity.DateTime)) .ToList(); Random rnd = new Random(); return posts[rnd.Next(posts.Count)]; } internal void Create(BlogPost blogPost) { try { this._unitOfWork.BlogPostSchoolRepository.Insert(blogPost); this._unitOfWork.Save(); } catch (Exception e) { Console.WriteLine(e); throw; } } public void Delete(int id) { try { BlogPost post = this.GetBlogPostByIdD(id); this._unitOfWork.BlogPostSchoolRepository.Remove(post); this._unitOfWork.Save(); } catch (Exception e) { Console.WriteLine(e); throw; } } } }
30.543478
161
0.560498
b03aadfdbbb56089c9f71534a4007b8d00fee687
4,545
py
Python
test_discretization/test_svm.py
wsgan001/AnomalyDetection
397673dc6ce978361a3fc6f2fd34879f69bc962a
[ "MIT" ]
null
null
null
test_discretization/test_svm.py
wsgan001/AnomalyDetection
397673dc6ce978361a3fc6f2fd34879f69bc962a
[ "MIT" ]
null
null
null
test_discretization/test_svm.py
wsgan001/AnomalyDetection
397673dc6ce978361a3fc6f2fd34879f69bc962a
[ "MIT" ]
1
2020-03-16T21:50:52.000Z
2020-03-16T21:50:52.000Z
import pandas as pd import math import random from sklearn import svm headerfile = './nslkdd/data/kddcup.names' datfile = './nslkdd/data/KDDTrain+_20Percent.txt' headers=open(headerfile,'r').readlines()[1:] headers = [h.split(':')[0] for h in headers] headers.append('attack') headers.append('attack_idx') df = pd.read_csv(open(datfile), names=headers) df.iloc[0] # convert attack labels to integer index attacks=open(headerfile,'r').readline().replace('.\n','').split(',') for i in range(len(attacks)): df['attack'][df['attack']==attacks[i]]=i # convert protocol_type to integer index pt=list(set(df['protocol_type'])) for i in range(len(pt)): df['protocol_type'][df['protocol_type']==pt[i]]=i # convert service to integer index pt=list(set(df['service'])) for i in range(len(pt)): df['service'][df['service']==pt[i]]=i # convert flag to integer index pt=list(set(df['flag'])) for i in range(len(pt)): df['flag'][df['flag']==pt[i]]=i # scale big nums to log2 count scaled=['duration','src_bytes','dst_bytes','num_root','num_compromised','num_file_creations','count','srv_count','dst_host_count', 'dst_host_srv_count'] for i in range(len(scaled)): for j in range(df.shape[0]): df[scaled[i]].iloc[j]=int(math.log(1+df[scaled[i]].iloc[j],2)) df.iloc[0] # don't include last field, difficulty flag is meta data for i in range(len(headers)): print headers[i], max(df[headers[i]]) df.shape # 25192, 43 # idx = [i for i in range(df.shape[0])] import random random.shuffle(idx) ptr=20000 idxTrain=idx[0:ptr] idxTest=idx[ptr:len(idx)] xTrain = df.iloc[idxTrain,1:41] yTrain = df.iloc[idxTrain,41] xTest = df.iloc[idxTest,1:41] yTest = df.iloc[idxTest,41] clf = svm.SVC() clf.fit(xTrain, yTrain) preds = clf.predict(xTest) #divisor = sum(yTest==11) tp = 0 tn = 0 fp = 0 fn = 0 for i in range(len(preds)): if preds[i]==11 and yTest.iloc[i] == 11: tp = tp + 1 if preds[i]!=11 and yTest.iloc[i] != 11: tn = tn + 1 if preds[i]!=11 and yTest.iloc[i] == 11: fn = fn + 1 if preds[i]==11 and yTest.iloc[i] != 11: fp = fp + 1 print tp print tn print fp print fn #accuracy=clf.accuracy( ## 2804 11 in preds; 2794 11 in yTest ## TN .997 #1.0*sum([preds[i]==11 and yTest.iloc[i] == 11 for i in range(len(preds))]) / sum (yTest==11)*1.0 # ## TP .9929 #1.0*sum([preds[i]!=11 and yTest.iloc[i] != 11 for i in range(len(preds))]) / sum (yTest!=11)*1.0 # ## FN .003 #1.0*sum([preds[i]!=11 and yTest.iloc[i] == 11 for i in range(len(preds))]) / sum (yTest==11)*1.0 # ## FP .007 #1.0*sum([preds[i]==11 and yTest.iloc[i] != 11 for i in range(len(preds))]) / sum (yTest!=11)*1.0 for s in set(yTest): # TN .997 attacks[s], s, sum(yTest==s), 1.*sum([preds[i]==s and yTest.iloc[i] == s for i in range(len(preds))]) / sum (yTest==s)*1.0, 1.*sum([preds[i]!=s and yTest.iloc[i] != s for i in range(len(preds))]) / sum (yTest!=s)*1.0 from sklearn.metrics import confusion_matrix confusion_matrix(list(yTest), list(preds)) ''' array([[ 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 132, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 1731, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 29, 0, 0, 37, 1, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 3, 0, 2, 8, 2761, 0, 0, 0, 0, 0, 0, 0, 3], [ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0], [ 0, 0, 1, 0, 6, 0, 1, 0, 0, 111, 0, 1, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 3, 0, 1, 0, 0, 0, 0, 144, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 99, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, 0], [ 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 22]]) '''
34.172932
224
0.480088
c52b423ddde87143633c3b01cd761394aa931e12
292
css
CSS
src/css/imports/_footer.css
higginbg/ncm-inc-2
ecee5f8fa50b926b80e1ff425284da08d5e026da
[ "MIT" ]
null
null
null
src/css/imports/_footer.css
higginbg/ncm-inc-2
ecee5f8fa50b926b80e1ff425284da08d5e026da
[ "MIT" ]
2
2021-08-11T23:30:20.000Z
2022-02-26T22:10:03.000Z
src/css/imports/_footer.css
higginbg/ncm-inc
2285bc1907c68275bdbbaf1dd64befd7d429f633
[ "MIT" ]
null
null
null
footer { height: var(--footer-height); margin-top: calc(-1 * var(--footer-height)); box-shadow: var(--footer-shadow); } .neg-margin { margin-top: calc(-0.75 * var(--neg-margin)); } @media (--breakpoint-large) { .neg-margin { margin-top: calc(-0.75 * var(--neg-margin)); } }
18.25
48
0.59589
f4139c009e5a25f1163601cec2123bbb86fa5a77
1,624
cs
C#
PossumLabs.Specflow.Core.UnitTests/FluidDataCreation/SetupUnitTestObjectFactory.cs
BasHamer/PossumLabs.Specflow.Core
ba5574f7e4a0c83187f22295abe62b912927d8c1
[ "MIT" ]
1
2019-10-29T15:07:03.000Z
2019-10-29T15:07:03.000Z
PossumLabs.Specflow.Core.UnitTests/FluidDataCreation/SetupUnitTestObjectFactory.cs
BasHamer/PossumLabs.Specflow.Core
ba5574f7e4a0c83187f22295abe62b912927d8c1
[ "MIT" ]
14
2019-02-04T05:03:48.000Z
2020-01-21T00:19:58.000Z
PossumLabs.Specflow.Core.UnitTests/FluidDataCreation/SetupUnitTestObjectFactory.cs
BasHamer/PossumLabs.Specflow.Core
ba5574f7e4a0c83187f22295abe62b912927d8c1
[ "MIT" ]
null
null
null
using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace PossumLabs.Specflow.Core.UnitTests.FluidDataCreation { [TestClass] public class SetupUnitTestObjectFactory { public DataCreatorFactory DataCreatorFactory { get; set; } public PossumLabs.Specflow.Core.Variables.ObjectFactory Factory { get; set; } [TestInitialize] public void Initialize() { DataCreatorFactory = new DataCreatorFactory(); Factory = new PossumLabs.Specflow.Core.Variables.ObjectFactory(); var interpeter = new PossumLabs.Specflow.Core.Variables.Interpeter(Factory); var templateManager = new PossumLabs.Specflow.Core.Variables.TemplateManager(); templateManager.Initialize(Assembly.GetExecutingAssembly()); Setup = new Setup(DataCreatorFactory, Factory, templateManager, interpeter); new PossumLabs.Specflow.Core.Variables.ExistingDataManager(interpeter).Initialize(Assembly.GetExecutingAssembly()); } private Setup Setup { get; set; } [TestMethod] public void MakeSureExistingDataIsLoaded() { Factory.Register<ValueObject>(o => new ValueObject { Name = "special" }); Setup.WithParentObject("P1", configurer: p=>p.ComplexValue.Value=42); Setup.ParentObjects["P1"].ComplexValue.Value.Should().Be(42); Setup.ParentObjects["P1"].ComplexValue.Name.Should().Be("special"); } } }
36.088889
127
0.68165
20cb7aea0ed08e8f30a790ee37dd5f5c5b48b6b7
25,699
cs
C#
tests/Meziantou.Framework.DependencyScanning.Tests/ScannerTests.cs
DomLatr/Meziantou.Framework
d21820b39ec19b833b759881311d10ffa917abab
[ "MIT" ]
null
null
null
tests/Meziantou.Framework.DependencyScanning.Tests/ScannerTests.cs
DomLatr/Meziantou.Framework
d21820b39ec19b833b759881311d10ffa917abab
[ "MIT" ]
74
2021-06-21T19:05:18.000Z
2022-03-21T19:09:07.000Z
tests/Meziantou.Framework.DependencyScanning.Tests/ScannerTests.cs
aTiKhan/Meziantou.Framework
bf0ba9dd2db78516a93bb8b029f35f4ab6973843
[ "MIT" ]
null
null
null
#pragma warning disable MA0101 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using LibGit2Sharp; using Meziantou.Framework.DependencyScanning.Scanners; using Meziantou.Framework.Globbing; using TestUtilities; using Xunit; using Xunit.Abstractions; namespace Meziantou.Framework.DependencyScanning.Tests { public sealed class ScannerTests : IDisposable { private readonly TemporaryDirectory _directory; private readonly ITestOutputHelper _testOutputHelper; public ScannerTests(ITestOutputHelper testOutputHelper) { _directory = TemporaryDirectory.Create(); _testOutputHelper = testOutputHelper; } [Fact] public async Task NpmPackageJsonDependencies() { const string Original = @"{ ""name"": ""sample"", ""version"": ""0.1.0"", ""dependencies"": { ""a"": ""1.0.0"" }, ""devDependencies"": { ""b"": ""1.2.3"", ""c"": null } }"; const string Expected = @"{ ""name"": ""sample"", ""version"": ""0.1.0"", ""dependencies"": { ""a"": ""2.0.0"" }, ""devDependencies"": { ""b"": ""2.0.0"", ""c"": null } }"; AddFile("package.json", Original); var result = await GetDependencies(new NpmPackageJsonDependencyScanner()); AssertContainDependency(result, (DependencyType.Npm, "a", "1.0.0", 5, 8), (DependencyType.Npm, "b", "1.2.3", 8, 8)); await UpdateDependencies(result, "2.0.0"); AssertFileContentEqual("package.json", Expected, ignoreNewLines: true); } [Fact] public async Task NuSpecDependencies() { const string Original = @"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <metadata> <id>sample</id> <version>1.0.0</version> <authors>Microsoft</authors> <dependencies> <dependency id=""another-package"" version=""3.0.0"" /> <dependency id=""yet-another-package"" version=""1.0.0"" /> </dependencies> </metadata> </package>"; const string Expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <metadata> <id>sample</id> <version>1.0.0</version> <authors>Microsoft</authors> <dependencies> <dependency id=""another-package"" version=""2.0.0"" /> <dependency id=""yet-another-package"" version=""2.0.0"" /> </dependencies> </metadata> </package>"; AddFile("test.nuspec", Original); var result = await GetDependencies(new NuSpecDependencyScanner()); AssertContainDependency(result, (DependencyType.NuGet, "another-package", "3.0.0", 8, 14), (DependencyType.NuGet, "yet-another-package", "1.0.0", 9, 14)); await UpdateDependencies(result, "2.0.0"); AssertFileContentEqual("test.nuspec", Expected, ignoreNewLines: true); } [Fact] public async Task MsBuildReferencesDependencies() { const string Original = @"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <RootNamespace>Sample</RootNamespace> </PropertyGroup> <!-- Comment --> <ItemGroup> <PackageReference Include=""TestPackage"" Version=""4.2.1"" /> </ItemGroup> </Project> "; const string Expected = @"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <RootNamespace>Sample</RootNamespace> </PropertyGroup> <!-- Comment --> <ItemGroup> <PackageReference Include=""TestPackage"" Version=""2.0.0"" /> </ItemGroup> </Project> "; AddFile("test.csproj", Original); var result = await GetDependencies(new MsBuildReferencesDependencyScanner()); AssertContainDependency(result, (DependencyType.NuGet, "TestPackage", "4.2.1", 10, 6)); await UpdateDependencies(result, "2.0.0"); AssertFileContentEqual("test.csproj", Expected, ignoreNewLines: true); } [Fact] public async Task MsBuildSdkReferencesDependencies() { const string Original = @"<Project Sdk=""MSBuild.Sdk.Extras/2.0.54""> <Sdk Name=""My.Custom.Sdk1"" Version=""1.0.0"" /> <Import Sdk=""My.Custom.Sdk2/2.0.55"" /> </Project> "; const string Expected = @"<Project Sdk=""MSBuild.Sdk.Extras/1.2.3""> <Sdk Name=""My.Custom.Sdk1"" Version=""1.2.3"" /> <Import Sdk=""My.Custom.Sdk2/1.2.3"" /> </Project> "; AddFile("test.csproj", Original); var result = await GetDependencies(new MsBuildReferencesDependencyScanner()); AssertContainDependency(result, (DependencyType.NuGet, "MSBuild.Sdk.Extras", "2.0.54", 1, 2), (DependencyType.NuGet, "My.Custom.Sdk1", "1.0.0", 2, 6), (DependencyType.NuGet, "My.Custom.Sdk2", "2.0.55", 3, 6)); await UpdateDependencies(result, "1.2.3"); AssertFileContentEqual("test.csproj", Expected, ignoreNewLines: true); } [Fact] public async Task PackagesReferencesWithNamespaceDependencies() { const string Original = @"<?xml version=""1.0"" encoding=""utf-8""?> <Project Sdk=""Microsoft.NET.Sdk"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <RootNamespace>Sample</RootNamespace> </PropertyGroup> <!-- Comment --> <ItemGroup> <PackageReference Include=""TestPackage"" Version=""4.2.1"" /> </ItemGroup> </Project> "; const string Expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <Project Sdk=""Microsoft.NET.Sdk"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <RootNamespace>Sample</RootNamespace> </PropertyGroup> <!-- Comment --> <ItemGroup> <PackageReference Include=""TestPackage"" Version=""2.0.0"" /> </ItemGroup> </Project> "; AddFile("test.csproj", Original); var result = await GetDependencies(new MsBuildReferencesDependencyScanner()); AssertContainDependency(result, (DependencyType.NuGet, "TestPackage", "4.2.1", 11, 6)); await UpdateDependencies(result, "2.0.0"); AssertFileContentEqual("test.csproj", Expected, ignoreNewLines: true); } [Fact] public async Task ProjectJsonDependencies() { const string Original = @"{ ""dependencies"": { ""a"": { ""version"": ""1.0.1"", ""type"": ""platform"" }, ""b"": { ""target"": ""project"" }, ""c"": ""1.0.2"", }, ""tools"": { ""d"": ""1.0.3"" } }"; const string Expected = @"{ ""dependencies"": { ""a"": { ""version"": ""2.0.0"", ""type"": ""platform"" }, ""b"": { ""target"": ""project"" }, ""c"": ""2.0.0"" }, ""tools"": { ""d"": ""2.0.0"" } }"; AddFile("project.json", Original); var result = await GetDependencies(new ProjectJsonDependencyScanner()); AssertContainDependency(result, (DependencyType.NuGet, "a", "1.0.1", 3, 8), (DependencyType.NuGet, "c", "1.0.2", 10, 8), (DependencyType.NuGet, "d", "1.0.3", 13, 8)); await UpdateDependencies(result, "2.0.0"); AssertFileContentEqual("project.json", Expected, ignoreNewLines: true); } [Fact] public async Task PythonRequirementsDependencies() { const string Original = "A==1.1.0\nB==1.2.0\r\nC==1.3.0"; const string Expected = "A==2.0.0\nB==2.0.0\r\nC==2.0.0"; AddFile("requirements.txt", Original); var result = await GetDependencies(new PythonRequirementsDependencyScanner()); AssertContainDependency(result, (DependencyType.PyPi, "A", "1.1.0", 1, 4), (DependencyType.PyPi, "B", "1.2.0", 2, 4), (DependencyType.PyPi, "C", "1.3.0", 3, 4)); await UpdateDependencies(result, "2.0.0"); AssertFileContentEqual("requirements.txt", Expected, ignoreNewLines: false); } [Fact] public async Task PackagesConfigDependencies() { const string Original = @"<?xml version=""1.0"" encoding=""utf-8"" ?> <packages> <package id=""A"" version=""4.2.1"" targetFramework=""net461"" /> </packages>"; const string Expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <packages> <package id=""A"" version=""2.0.0"" targetFramework=""net461"" /> </packages>"; AddFile("packages.config", Original); var result = await GetDependencies(new PackagesConfigDependencyScanner()); AssertContainDependency(result, (DependencyType.NuGet, "A", "4.2.1", 3, 4)); await UpdateDependencies(result, "2.0.0"); AssertFileContentEqual("packages.config", Expected, ignoreNewLines: true); } [Fact] public async Task PackagesConfigWithCsprojDependencies() { const string Original = @"<?xml version=""1.0"" encoding=""utf-8"" ?> <packages> <package id=""NUnit"" version=""3.11.0"" targetFramework=""net461"" /> </packages>"; const string OriginalCsproj = @"<?xml version=""1.0"" encoding=""utf-8""?> <Project ToolsVersion=""15.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Import Project=""..\packages\NUnit.3.11.0\build\NUnit.props"" Condition=""Exists('..\packages\NUnit.3.11.0\build\NUnit.props')"" /> <Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" /> <ItemGroup> <Reference Include=""nunit.framework, Version=3.11.0.0, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL""> <HintPath>..\packages\NUnit.3.11.0\lib\net45\nunit.framework.dll</HintPath> </Reference> </ItemGroup> <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" /> <Target Name=""EnsureNuGetPackageBuildImports"" BeforeTargets=""PrepareForBuild""> <PropertyGroup> <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText> </PropertyGroup> <Error Condition=""!Exists('..\packages\NUnit.3.11.0\build\NUnit.props')"" Text=""$([System.String]::Format('$(ErrorText)', '..\packages\NUnit.3.11.0\build\NUnit.props'))"" /> </Target> </Project>"; const string Expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <packages> <package id=""NUnit"" version=""3.12.0-beta00"" targetFramework=""net461"" /> </packages>"; const string ExpectedCsproj = @"<?xml version=""1.0"" encoding=""utf-8""?> <Project ToolsVersion=""15.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Import Project=""..\packages\NUnit.3.12.0-beta00\build\NUnit.props"" Condition=""Exists('..\packages\NUnit.3.12.0-beta00\build\NUnit.props')"" /> <Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" /> <ItemGroup> <Reference Include=""nunit.framework, Version=3.12.0.0, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL""> <HintPath>..\packages\NUnit.3.12.0-beta00\lib\net45\nunit.framework.dll</HintPath> </Reference> </ItemGroup> <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" /> <Target Name=""EnsureNuGetPackageBuildImports"" BeforeTargets=""PrepareForBuild""> <PropertyGroup> <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText> </PropertyGroup> <Error Condition=""!Exists('..\packages\NUnit.3.12.0-beta00\build\NUnit.props')"" Text=""$([System.String]::Format('$(ErrorText)', '..\packages\NUnit.3.12.0-beta00\build\NUnit.props'))"" /> </Target> </Project>"; AddFile("packages.config", Original); AddFile("file.csproj", OriginalCsproj); var result = await GetDependencies(new PackagesConfigDependencyScanner()); AssertContainDependency(result, (DependencyType.NuGet, "NUnit", "3.11.0", 3, 4), (DependencyType.NuGet, "NUnit", "3.11.0", 7, 8), (DependencyType.NuGet, "NUnit", "3.11.0", 6, 6), (DependencyType.NuGet, "NUnit", "3.11.0", 15, 6)); await UpdateDependencies(result, "3.12.0-beta00"); AssertFileContentEqual("packages.config", Expected, ignoreNewLines: true); AssertFileContentEqual("file.csproj", ExpectedCsproj, ignoreNewLines: true); } [Fact] public async Task DockerfileFromDependencies() { const string Original = @" FROM a.com/b:1.2.2 FROM a.com/c:1.2.3 AS base CMD /code/run-app "; const string Expected = @" FROM a.com/b:2.0.0 FROM a.com/c:2.0.0 AS base CMD /code/run-app "; AddFile("Dockerfile", Original); var result = await GetDependencies(new DockerfileDependencyScanner()); AssertContainDependency(result, (DependencyType.DockerImage, "a.com/b", "1.2.2", 2, 14), (DependencyType.DockerImage, "a.com/c", "1.2.3", 3, 14)); await UpdateDependencies(result, "2.0.0"); AssertFileContentEqual("Dockerfile", Expected, ignoreNewLines: false); } [Fact] public async Task GlobalJsonFromDependencies() { const string Original = @"{ ""sdk"": { ""version"": ""3.1.100"", ""rollForward"": ""disable"" }, ""msbuild-sdks"": { ""My.Custom.Sdk"": ""5.0.0"", ""My.Other.Sdk"": ""1.0.0-beta"" } }"; const string Expected = @"{ ""sdk"": { ""version"": ""3.1.400"", ""rollForward"": ""disable"" }, ""msbuild-sdks"": { ""My.Custom.Sdk"": ""3.1.400"", ""My.Other.Sdk"": ""3.1.400"" } }"; AddFile("global.json", Original); var result = await GetDependencies(new DotNetGlobalJsonDependencyScanner()); AssertContainDependency(result, (DependencyType.DotNetSdk, ".NET SDK", "3.1.100", 3, 24), (DependencyType.NuGet, "My.Custom.Sdk", "5.0.0", 7, 28), (DependencyType.NuGet, "My.Other.Sdk", "1.0.0-beta", 8, 32)); await UpdateDependencies(result, "3.1.400"); AssertFileContentEqual("global.json", Expected, ignoreNewLines: true); } [RunIfFact(FactOperatingSystem.Windows)] public async Task GitSubmodulesFromDependencies() { // Initialize remote repository await using var remote = TemporaryDirectory.Create(); await ExecuteProcess("git", "init", remote.FullPath); await ExecuteProcess("git", "config user.name test", remote.FullPath); await ExecuteProcess("git", "config user.email test@example.com", remote.FullPath); await File.WriteAllTextAsync(remote.GetFullPath("test.txt"), "content"); await ExecuteProcess("git", "add .", remote.FullPath); await ExecuteProcess("git", "commit -m commit-message", remote.FullPath); // Get remote head string head; using (var repository = new Repository(remote.FullPath)) { head = repository.Head.Tip.Sha; _testOutputHelper.WriteLine("Head: " + head); } // Initialize current directory await ExecuteProcess("git", "init", _directory.FullPath); await ExecuteProcess("git", "config user.name test", _directory.FullPath); await ExecuteProcess("git", "config user.email test@example.com", _directory.FullPath); await File.WriteAllTextAsync(_directory.GetFullPath("test.txt"), "content"); await ExecuteProcess("git", "add .", _directory.FullPath); await ExecuteProcess("git", "commit -m commit-message", _directory.FullPath); // Add submodule await ExecuteProcess2("git", new string[] { "submodule", "add", remote.FullPath, "submodule_path" }, _directory.FullPath); // List files var files = Directory.GetFiles(_directory.FullPath, "*", SearchOption.AllDirectories); _testOutputHelper.WriteLine("Content of " + _directory.FullPath); foreach (var file in files) { var attr = File.GetAttributes(file); _testOutputHelper.WriteLine($"{file} ({attr})"); } // Assert var result = await GetDependencies(new GitSubmoduleDependencyScanner()); AssertContainDependency(result, (DependencyType.GitSubmodule, remote.FullPath, head, 0, 0)); Assert.All(result, result => Assert.False(result.Location.IsUpdatable)); async Task ExecuteProcess(string process, string args, string workingDirectory) { _testOutputHelper.WriteLine($"Executing: '{process}' {args} ({workingDirectory})"); AssertProcessResult(await ProcessExtensions.RunAsTaskAsync(process, args, workingDirectory)); } async Task ExecuteProcess2(string process, string[] args, string workingDirectory) { _testOutputHelper.WriteLine($"Executing: '{process}' {string.Join(" ", args)} ({workingDirectory})"); AssertProcessResult(await ProcessExtensions.RunAsTaskAsync(process, args, workingDirectory)); } void AssertProcessResult(ProcessResult result) { if (result.ExitCode == 0) { _testOutputHelper.WriteLine("git command succeeds\n" + string.Join("\n", result.Output)); return; } Assert.False(true, "git command failed. Logs:\n" + string.Join("\n", result.Output)); } } [Fact] public async Task GitHubActions() { const string Path = ".github/workflows/sample.yml"; const string Original = @"name: demo on: [push] jobs: check-bats-version: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v1 - uses: docker://test/setup:v3 - run: npm install -g bats - run: bats -v container: image: node:10.16-jessie services: nginx: image: nginx:latest redis: image: redis:1.0 "; const string Expected = @"name: demo on: [push] jobs: check-bats-version: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3.0.0 - uses: actions/setup-node@v3.0.0 - uses: docker://test/setup:v3.0.0 - run: npm install -g bats - run: bats -v container: image: node:v3.0.0 services: nginx: image: nginx:v3.0.0 redis: image: redis:v3.0.0 "; AddFile(Path, Original); var scanner = new GitHubActionsScanner(); Assert.True(scanner.ShouldScanFile(Path)); var result = await GetDependencies(scanner); AssertContainDependency(result, (DependencyType.GitHubActions, "actions/checkout", "v2", 7, 32), (DependencyType.GitHubActions, "actions/setup-node", "v1", 8, 34), (DependencyType.DockerImage, "test/setup", "v3", 9, 35), (DependencyType.DockerImage, "node", "10.16-jessie", 13, 19), (DependencyType.DockerImage, "nginx", "latest", 16, 22), (DependencyType.DockerImage, "redis", "1.0", 18, 22)); await UpdateDependencies(result, "v3.0.0"); AssertFileContentEqual(Path, Expected, ignoreNewLines: false); } [Fact] public async Task Regex() { const string Original = @" container: image: node:10 services: abc "; const string Expected = @" container: image: node:v3.0.0 services: abc "; AddFile("custom/sample.yml", Original); var result = await GetDependencies(new RegexScanner() { FilePatterns = new GlobCollection(Glob.Parse("**/*", GlobOptions.None)), DependencyType = DependencyType.DockerImage, RegexPattern = "image: (?<name>[a-z]+):(?<version>[0-9]+)", }); AssertContainDependency(result, (DependencyType.DockerImage, "node", "10", 3, 15)); await UpdateDependencies(result, "v3.0.0"); AssertFileContentEqual("custom/sample.yml", Expected, ignoreNewLines: false); } [Fact] public async Task DotNetToolsDependencies() { const string Original = @"{ ""version"": 1, ""isRoot"": true, ""tools"": { ""dotnet-validate"": { ""version"": ""0.0.1-preview.130"", ""commands"": [ ""dotnet-validate"" ] }, ""dotnet-format"": { ""version"": ""5.0.211103"", ""commands"": [ ""dotnet-format"" ] } } }"; const string Expected = @"{ ""version"": 1, ""isRoot"": true, ""tools"": { ""dotnet-validate"": { ""version"": ""2.0.0"", ""commands"": [ ""dotnet-validate"" ] }, ""dotnet-format"": { ""version"": ""2.0.0"", ""commands"": [ ""dotnet-format"" ] } } }"; AddFile("dotnet-tools.json", Original); var result = await GetDependencies(new DotNetToolManifestDependencyScanner()); AssertContainDependency(result, (DependencyType.NuGet, "dotnet-validate", "0.0.1-preview.130", 5, 22), (DependencyType.NuGet, "dotnet-format", "5.0.211103", 11, 20)); await UpdateDependencies(result, "2.0.0"); AssertFileContentEqual("dotnet-tools.json", Expected, ignoreNewLines: true); } private async Task<List<Dependency>> GetDependencies(DependencyScanner scanner) { var dependencies = new List<Dependency>(); await foreach (var dep in DependencyScanner.ScanDirectoryAsync(_directory.FullPath, new ScannerOptions { DegreeOfParallelism = 1, Scanners = new[] { scanner } })) { dependencies.Add(dep); } // Execute in parallel and compare the number of found dependencies var dependencies2 = new List<Dependency>(); await foreach (var dep in DependencyScanner.ScanDirectoryAsync(_directory.FullPath, new ScannerOptions { DegreeOfParallelism = 16, Scanners = new[] { scanner } })) { dependencies2.Add(dep); } Assert.Equal(dependencies.Count, dependencies2.Count); return dependencies; } private static async Task UpdateDependencies(IEnumerable<Dependency> dependencies, string newVersion) { await DependencyScanner.UpdateAllAsync(dependencies, newVersion, CancellationToken.None); } private void AddFile(string path, string content) => AddFile(path, content, Encoding.UTF8); private void AddFile(string path, string content, Encoding encoding) => AddFile(path, encoding.GetBytes(content)); private void AddFile(string path, byte[] content) { var fullPath = _directory.GetFullPath(path); Directory.CreateDirectory(fullPath.Parent); File.WriteAllBytes(fullPath, content); } private static void AssertContainDependency(IEnumerable<Dependency> dependencies, params (DependencyType Type, string Name, string Version, int Line, int Column)[] expectedDepedencies) { foreach (var expected in expectedDepedencies) { Assert.True(dependencies.Any(d => d.Type == expected.Type && d.Name == expected.Name && d.Version == expected.Version && (expected.Line == 0 || ((ILocationLineInfo)d.Location).LineNumber == expected.Line) && (expected.Column == 0 || ((ILocationLineInfo)d.Location).LinePosition == expected.Column)), $"Dependency '{expected}' not found. Dependencies ({dependencies.Count()}):\n{string.Join("\n", dependencies)}"); } } private void AssertFileContentEqual(string path, string expected, bool ignoreNewLines) { var fullPath = _directory.GetFullPath(path); AssertExtensions.StringEquals(expected, File.ReadAllText(fullPath), ignoreNewLines); } public void Dispose() { _directory.Dispose(); } } }
37.137283
247
0.594342
eca242410c3f7365228bfa53cdb4a295070d10aa
1,510
sql
SQL
storage/cockroach/migrations/000001_tables.up.sql
arcadium-dev/arcade
02621a1ab887baf794043cea41ce9fc4778d4f5d
[ "Apache-2.0" ]
null
null
null
storage/cockroach/migrations/000001_tables.up.sql
arcadium-dev/arcade
02621a1ab887baf794043cea41ce9fc4778d4f5d
[ "Apache-2.0" ]
1
2021-11-06T17:09:46.000Z
2021-11-06T17:09:46.000Z
storage/cockroach/migrations/000001_tables.up.sql
arcadium-dev/arcade
02621a1ab887baf794043cea41ce9fc4778d4f5d
[ "Apache-2.0" ]
null
null
null
BEGIN; CREATE TABLE IF NOT EXISTS players ( player_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), name TEXT UNIQUE NOT NULL, description TEXT NOT NULL, created TIMESTAMP NOT NULL DEFAULT (now() AT TIME ZONE 'utc'), updated TIMESTAMP NOT NULL DEFAULT (now() AT TIME ZONE 'utc') ); CREATE TABLE IF NOT EXISTS rooms ( room_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), name TEXT NOT NULL, description TEXT NOT NULL, created TIMESTAMP NOT NULL DEFAULT (now() AT TIME ZONE 'utc'), updated TIMESTAMP NOT NULL DEFAULT (now() AT TIME ZONE 'utc') ); CREATE TABLE IF NOT EXISTS items ( item_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), name TEXT NOT NULL, description TEXT NOT NULL, created TIMESTAMP NOT NULL DEFAULT (now() AT TIME ZONE 'utc'), updated TIMESTAMP NOT NULL DEFAULT (now() AT TIME ZONE 'utc') ); CREATE TABLE IF NOT EXISTS links ( link_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), name TEXT NOT NULL, description TEXT NOT NULL, created TIMESTAMP NOT NULL DEFAULT (now() AT TIME ZONE 'utc'), updated TIMESTAMP NOT NULL DEFAULT (now() AT TIME ZONE 'utc') ); COMMIT; BEGIN; INSERT INTO players (player_id, name, description) VALUES ( '00000000-0000-0000-0000-000000000001', 'Nobody', 'A person of no importance.' ); INSERT INTO rooms (room_id, name, description) VALUES ( '00000000-0000-0000-0000-000000000001', 'Limbo', 'A place for lost, forgotten, or unwanted persons or things.' ); COMMIT;
26.034483
64
0.705298
cd35c6aa3cc21c9de993da29657dd6271d64077b
2,051
dart
Dart
lib/widgets/settings.dart
irfanrev/trex-markicabs_fluttergame
dd83b2f07a9c753ec4a1f42d5d97721fd8fe99d0
[ "MIT" ]
null
null
null
lib/widgets/settings.dart
irfanrev/trex-markicabs_fluttergame
dd83b2f07a9c753ec4a1f42d5d97721fd8fe99d0
[ "MIT" ]
null
null
null
lib/widgets/settings.dart
irfanrev/trex-markicabs_fluttergame
dd83b2f07a9c753ec4a1f42d5d97721fd8fe99d0
[ "MIT" ]
null
null
null
import 'package:dino_run/game/audio_manager.dart'; import 'package:flutter/material.dart'; /// This class displays the settings menu on [MainMenu]. class Settings extends StatelessWidget { final Function onBackPressed; const Settings({ Key key, @required this.onBackPressed, }) : assert(onBackPressed != null), super(key: key); @override Widget build(BuildContext context) { return Container( width: 300.0, child: Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ Text( 'Settings', style: TextStyle(fontSize: 60.0, color: Colors.white), ), ValueListenableBuilder( valueListenable: AudioManager.instance.listenableSfx, builder: (BuildContext context, bool isSfxOn, Widget child) { return SwitchListTile( value: isSfxOn, title: Text( 'SFX', style: TextStyle(fontSize: 30.0, color: Colors.white), ), onChanged: (bool value) { AudioManager.instance.setSfx(value); }, ); }, ), ValueListenableBuilder( valueListenable: AudioManager.instance.listenableBgm, builder: (BuildContext context, bool isBgmOn, Widget child) { return SwitchListTile( value: isBgmOn, title: Text( 'BGM', style: TextStyle(fontSize: 30.0, color: Colors.white), ), onChanged: (bool value) { AudioManager.instance.setBgm(value); }, ); }, ), IconButton( icon: Icon( Icons.arrow_back_ios_rounded, size: 30.0, color: Colors.white, ), onPressed: onBackPressed, ), ], ), ); } }
29.724638
73
0.511945
ab66e312d9f6c59052aa8c944a60c460c44e496c
6,073
dart
Dart
lib/utils/geometry/radial_menu_collisions.dart
dungnv2602/flutter_ui_challenges
09d1fdc14120de10f39ca57da01aa02166a4e3a1
[ "Apache-2.0" ]
null
null
null
lib/utils/geometry/radial_menu_collisions.dart
dungnv2602/flutter_ui_challenges
09d1fdc14120de10f39ca57da01aa02166a4e3a1
[ "Apache-2.0" ]
null
null
null
lib/utils/geometry/radial_menu_collisions.dart
dungnv2602/flutter_ui_challenges
09d1fdc14120de10f39ca57da01aa02166a4e3a1
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020. Joe Ng - dungnv2602. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. * * This class is a modified version from the original authored by Matt Carroll/Fluttery * Credit goes to Matt Carroll/Fluttery */ import 'dart:math'; import 'dart:ui'; import 'geometry.dart'; Set<Point> intersect(Size size, Point origin, double menuRadius) { print('Screen size: $size'); print('Intersections for point: $origin'); final radius = menuRadius; final topPoints = _topIntersections(size, origin, radius); final bottomPoints = _bottomIntersections(size, origin, radius); final leftPoints = _leftIntersections(size, origin, radius); final rightPoints = _rightIntersections(size, origin, radius); return topPoints ..addAll(bottomPoints) ..addAll(leftPoints) ..addAll(rightPoints); } Set<Point> _topIntersections(Size screenSize, Point origin, double menuRadius) { final intersections = _findIntersections( Point(0.0, 0.0) - origin, Point(screenSize.width, 0.0) - origin, menuRadius, ); print('Top intersections:'); final topPoints = intersections.map((Point point) { Point specificPoint = point + origin; print(' - $specificPoint'); return specificPoint; }).toSet(); topPoints.removeWhere((Point point) { return point.x < 0.0 || point.x > screenSize.width; }); print('Found ${topPoints.length} top intersections.'); return topPoints; } Set<Point> _bottomIntersections( Size screenSize, Point origin, double menuRadius) { final intersections = _findIntersections( Point(0.0, screenSize.height) - origin, Point(screenSize.width, screenSize.height) - origin, menuRadius, ); print('Bottom intersections:'); final bottomPoints = intersections.map((Point point) { Point specificPoint = point + origin; print(' - $specificPoint'); return specificPoint; }).toSet(); bottomPoints.removeWhere((Point point) { return point.x < 0.0 || point.x > screenSize.width; }); print('Found ${bottomPoints.length} bottom intersections.'); return bottomPoints; } Set<Point> _leftIntersections( Size screenSize, Point origin, double menuRadius) { final intersections = _findIntersections( Point(0.0, 0.0) - origin, Point(0.0, screenSize.height) - origin, menuRadius, ); print('Left intersections:'); final leftPoints = intersections.map((Point point) { Point specificPoint = point + origin; print(' - $specificPoint'); return specificPoint; }).toSet(); leftPoints.removeWhere((Point point) { return point.y < 0.0 || point.y > screenSize.height; }); print('Found ${leftPoints.length} left intersections.'); return leftPoints; } Set<Point> _rightIntersections( Size screenSize, Point origin, double menuRadius) { final intersections = _findIntersections( Point(screenSize.width, 0.0) - origin, Point(screenSize.width, screenSize.height) - origin, menuRadius, ); print('Right intersections:'); final rightPoints = intersections.map((Point point) { Point specificPoint = point + origin; print(' - $specificPoint'); return specificPoint; }).toSet(); rightPoints.removeWhere((Point point) { return point.y < 0.0 || point.y > screenSize.height; }); print('Found ${rightPoints.length} right intersections.'); return rightPoints; } // Calculate intersections // http://mathworld.wolfram.com/Circle-LineIntersection.html // // As stated on the website, this finds intersections assuming a circle // origin of (0.0, 0.0) therefore input points [p1] and [p2] should be // offset by the actual circle origin before calling this method. Set<Point> _findIntersections(Point p1, Point p2, double radius) { final double dx = p2.x - p1.x; final double dy = p2.y - p1.y; final double dSgn = dy >= 0 ? 1.0 : -1.0; final double dr = sqrt(pow(dx, 2) + pow(dy, 2)); final double D = (p1.x * p2.y) - (p2.x * p1.y); final discriminant = (pow(radius, 2) * pow(dr, 2)) - pow(D, 2); if (discriminant <= 0) { // No intersection. return Set<Point<double>>(); } final xIntersect1 = ((D * dy) + (dSgn * dx * sqrt((pow(radius, 2) * pow(dr, 2)) - pow(D, 2)))) / pow(dr, 2); final yIntersect1 = (-(D * dx) + (dy.abs() * sqrt((pow(radius, 2) * pow(dr, 2)) - pow(D, 2)))) / pow(dr, 2); final xIntersect2 = ((D * dy) - (dSgn * dx * sqrt((pow(radius, 2) * pow(dr, 2)) - pow(D, 2)))) / pow(dr, 2); final yIntersect2 = (-(D * dx) - (dy.abs() * sqrt((pow(radius, 2) * pow(dr, 2)) - pow(D, 2)))) / pow(dr, 2); return [ Point(xIntersect1, yIntersect1), Point(xIntersect2, yIntersect2), ].toSet(); } Arc rotatePointsToMakeRoom({ Arc arc, Point origin, Point direction, double radius, double extraSpace, }) { return Arc( from: _adjustAngleToMakeRoom( intersectionAngle: arc.from, rotationDirection: arc.direction == RadialDirection.clockwise ? RadialDirection.clockwise : RadialDirection.counterClockwise, radius: radius, extraSpace: extraSpace, ), to: _adjustAngleToMakeRoom( intersectionAngle: arc.to, rotationDirection: arc.direction == RadialDirection.clockwise ? RadialDirection.counterClockwise : RadialDirection.clockwise, radius: radius, extraSpace: extraSpace, ), direction: arc.direction, ); } Angle _adjustAngleToMakeRoom({ Angle intersectionAngle, RadialDirection rotationDirection, double radius, double extraSpace, }) { print('Adjusting angle $intersectionAngle to make room for $extraSpace pts. ' 'Direction: ${radialDirectionName(rotationDirection)}'); final isClockwise = rotationDirection == RadialDirection.clockwise; final directionMultiplier = isClockwise ? 1.0 : -1.0; final bubbleRadius = extraSpace; final theta = Angle.fromRadians(asin(bubbleRadius / radius) * directionMultiplier); return intersectionAngle + theta; }
29.769608
87
0.671991
50b30f01b7df254c8db68a4fccc15ade29e20ce9
1,127
dart
Dart
lib/bloc/signup/sign_up_event.dart
vibeus-con/Vibeus
6fb4b77bc639b6df20388b815d92f03b0c7f05eb
[ "MIT" ]
1
2021-08-06T09:39:50.000Z
2021-08-06T09:39:50.000Z
lib/bloc/signup/sign_up_event.dart
vibeus-con/Vibeus
6fb4b77bc639b6df20388b815d92f03b0c7f05eb
[ "MIT" ]
null
null
null
lib/bloc/signup/sign_up_event.dart
vibeus-con/Vibeus
6fb4b77bc639b6df20388b815d92f03b0c7f05eb
[ "MIT" ]
1
2021-08-06T09:39:55.000Z
2021-08-06T09:39:55.000Z
import 'package:equatable/equatable.dart'; import 'package:flutter/cupertino.dart'; @immutable abstract class SignUpEvent extends Equatable { const SignUpEvent(); @override List<Object> get props => []; } class EmailChanged extends SignUpEvent { final String email; EmailChanged({@required this.email}); @override List<Object> get props => [email]; @override String toString() => 'EmailChanged {email: $email}'; } class PasswordChanged extends SignUpEvent { final String password; PasswordChanged({@required this.password}); @override List<Object> get props => [password]; @override String toString() => 'PasswordChanged {password: $password}'; } class Submitted extends SignUpEvent { final String email; final String password; Submitted({this.email, this.password}); @override List<Object> get props => [email, password]; } class SignUpWithCredentialsPressed extends SignUpEvent { final String email; final String password; SignUpWithCredentialsPressed({@required this.email, @required this.password}); @override List<Object> get props => [email, password]; }
20.490909
80
0.726708
58bd7d9875f7feebc3d89f2c2bdf9236842f0d17
1,088
css
CSS
src/OneGit.Web/wwwroot/css/site.css
olegburov/Auth0-Coding-Project
7e724d429e86db27ff850c856dce4ef36ef1350a
[ "MIT" ]
11
2018-07-04T00:39:32.000Z
2020-04-21T13:19:08.000Z
src/OneGit.Web/wwwroot/css/site.css
olegburov/Auth0-Coding-Project
7e724d429e86db27ff850c856dce4ef36ef1350a
[ "MIT" ]
1
2018-09-26T03:38:00.000Z
2018-09-26T03:38:00.000Z
src/OneGit.Web/wwwroot/css/site.css
olegburov/Auth0
7e724d429e86db27ff850c856dce4ef36ef1350a
[ "MIT" ]
null
null
null
body { padding-top: 50px; padding-bottom: 20px; } /* Wrapping element */ /* Set some basic padding to keep content from hitting the edges */ .body-content { padding-left: 15px; padding-right: 15px; } /* Carousel */ .carousel-caption p { font-size: 20px; line-height: 1.4; } /* Make .svg files in the carousel display properly in older browsers */ .carousel-inner .item img[src$=".svg"] { width: 100%; } /* QR code generator */ #qrCode { margin: 15px; } /* Hide/rearrange for smaller screens */ @media screen and (max-width: 767px) { /* Hide captions */ .carousel-caption { display: none; } } .avatar { display: inline-block; overflow: hidden; line-height: 1; vertical-align: middle; border-radius: 3px; } .header-nav-current-user { padding-bottom: 0px; font-size: inherit; } .dropdown-divider { height: 1px; margin: 8px 1px; background-color: #e1e4e8; } .user-profile-repo-filter { padding-top: 16px !important; padding-bottom: 16px !important; } .nav-tabs > li { margin-bottom: -2px !important; }
16.738462
72
0.643382
af5fb10d412f2b358040690ce3c5b5ad1ef7391c
2,193
py
Python
disc/disc03.py
FyisFe/UCB-CS61A-20Fall
40312a939e17c3de6735df7fc2eb2d66286f87ad
[ "MIT" ]
3
2022-01-21T15:52:32.000Z
2022-03-06T11:02:34.000Z
disc/disc03.py
FyisFe/UCB-CS61A-20Fall
40312a939e17c3de6735df7fc2eb2d66286f87ad
[ "MIT" ]
null
null
null
disc/disc03.py
FyisFe/UCB-CS61A-20Fall
40312a939e17c3de6735df7fc2eb2d66286f87ad
[ "MIT" ]
1
2022-02-13T08:28:27.000Z
2022-02-13T08:28:27.000Z
def multiply(m, n): if n > m: m, n = n, m if n == 0: return 0 return m + multiply(m, n - 1) # print(multiply(3, 5)) def rec(x, y): # x ^ y if y > 0: return x * rec(x, y - 1) return 1 # print(rec(3, 5)) def hailstone(n): # n is even: n = n / 2 # n is odd: n = n * 3 + 1 # n == 1, stop if n == 1: return 1 if n % 2 == 0: return 1 + hailstone(n // 2) return 1 + hailstone(n * 3 + 1) # print(hailstone(10)) # hailstone(10): # hailstone(5): # hailstone(16): # hailstone(8): # hailstone(4): # hailstone(2): # hailstone(1): # hailstone(1) -> 1 # hailstone(2) -> 2 # hailstone(4) -> 3 # hailstone(8) -> 4 # hailstone(16) -> 5 # hailstone(5) -> 6 # hailstone(10) -> 7 # 7 def first_digit(n): return int(str(n)[:1]) def remaining_digit(n): if n < 10: return 0 return int(str(n)[1:]) def merge(n1, n2): if n1 == 0 and n2 == 0: return "" first_digit_n1 = first_digit(n1) first_digit_n2 = first_digit(n2) if first_digit_n1 > first_digit_n2: return int(str(first_digit_n1) + str(merge(remaining_digit(n1), n2))) else: return int(str(first_digit_n2) + str(merge(n1, remaining_digit(n2)))) # print(merge(31, 42)) # 4321 # print(merge(21, 0)) # 21 # print(merge(21, 31)) # 3211 # print(merge(310, 420)) # 4321 # print(merge(310000, 420)) # 4321 # print(merge(22, 22)) # 2222 def make_func_repeater(f, x): def repeat(times): if times <= 1: return f(x) return f(repeat(times - 1)) return repeat # incr_1 = make_func_repeater(lambda x: x + 1, 1) # print(incr_1(2)) # 3 # print(incr_1(5)) # 6 def is_prime(n): def prime_helper(cur): if n == 1: return False if cur == n: return True if n % cur == 0: return False return prime_helper(cur + 1) return prime_helper(2) print(is_prime(7)) # True print(is_prime(10)) # False print(is_prime(1)) # False
19.936364
77
0.50114
eb37747a67c83d7ce16611d6e1ef98f7f5d09646
1,064
css
CSS
public/css/preloader.css
biohazardhome/dps
435cc7c6459f88d0ba88278f59de2c1577f7d8ed
[ "MIT" ]
null
null
null
public/css/preloader.css
biohazardhome/dps
435cc7c6459f88d0ba88278f59de2c1577f7d8ed
[ "MIT" ]
null
null
null
public/css/preloader.css
biohazardhome/dps
435cc7c6459f88d0ba88278f59de2c1577f7d8ed
[ "MIT" ]
null
null
null
.preloader { display: none; text-align: center; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(128, 128, 128, 0.53); } .cp-spinner { width:48px; height:48px; display:inline-block; box-sizing:border-box; position:relative; } .cp-round:before{ content:" "; position:absolute; top:0; left:0; width:100%; height:100%; border-radius:50%; display:inline-block; box-sizing:border-box; border-top:solid 6px #cbbb9a; border-right:solid 6px #cbbb9a; border-bottom:solid 6px #cbbb9a; border-left:solid 6px #cbbb9a; } .cp-round:after{ content:" "; position:absolute; top:0; left:0; width:100%; height:100%; border-radius:50%; display:inline-block; box-sizing:border-box; border-top:solid 6px #e0d1b4; border-right:solid 6px transparent; border-bottom:solid 6px transparent; border-left:solid 6px transparent; animation:cp-round-animate 1s ease-in-out infinite; } @keyframes cp-round-animate { 0% { transform:rotate(0); } 100% { transform:rotate(360deg); } }
17.16129
52
0.684211
181e0acc75c4adf262cdc7bd6ee77cc19b7ce428
483
sql
SQL
alembic/backport_instances.sql
BrianJKoopman/librarian
2d4164b60fe41d1a192f03d8baad12c0d11d0394
[ "BSD-2-Clause" ]
5
2016-02-17T17:51:05.000Z
2021-12-09T19:08:17.000Z
alembic/backport_instances.sql
BrianJKoopman/librarian
2d4164b60fe41d1a192f03d8baad12c0d11d0394
[ "BSD-2-Clause" ]
60
2016-01-29T20:40:04.000Z
2021-05-28T14:13:18.000Z
alembic/backport_instances.sql
simonsobs/librarian
188370d84a988f898bb9de4593078c1868602f08
[ "BSD-2-Clause" ]
6
2017-11-13T10:40:34.000Z
2020-07-10T00:42:57.000Z
-- Copyright 2016 the HERA Collaboration -- Licensed under the 2-clause BSD License -- -- Use this script to seed the "alembic_version" table on instances -- of the Librarian database that have already been deployed. The -- magic hex number is the Alembic revision identifier of the -- "initial schema" that these deployed databases have been using. CREATE TABLE alembic_version (version_num VARCHAR(32) NOT NULL); INSERT INTO alembic_version (version_num) VALUES ('71df5b41ae41');
43.909091
67
0.784679
45a1d01de991db1f3c078db5c2a68149a65d0023
28,450
py
Python
hello.py
DevrisOfStar/SW
27fffb10d7a853875d8bd5a2579af9331be371ef
[ "MIT" ]
null
null
null
hello.py
DevrisOfStar/SW
27fffb10d7a853875d8bd5a2579af9331be371ef
[ "MIT" ]
null
null
null
hello.py
DevrisOfStar/SW
27fffb10d7a853875d8bd5a2579af9331be371ef
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import string reload(sys) sys.setdefaultencoding('utf8') from flask import Flask, request, url_for, redirect, session, flash from flask import render_template from flaskext.mysql import MySQL app = Flask(__name__) app.secret_key = '#ekd@aA/3g dE~2A!jEdH.,!RA' #Secret key in Session # mysql 초기설정 mysql = MySQL() app.config['MYSQL_DATABASE_USER'] = 'root' app.config['MYSQL_DATABASE_PASSWORD'] = '-' app.config['MYSQL_DATABASE_DB'] = 'aboutmydog' app.config['MYSQL_DATABASE_HOST'] = '210.89.180.38' mysql.init_app(app) # error handler @app.errorhandler(404) def page_not_found(error) : return render_template('404.html'),404 # main 부분 @app.route('/') # 완료 def home(username = None) : # get userName in index cursor = mysql.connect().cursor() cursor.execute("SELECT * from board_table LIMIT 5") data = cursor.fetchall() cursor.execute("SELECT * FROM item_table LIMIT 6") item = cursor.fetchall() if 'username' in session : username = session['username'] else : username = None return render_template('index.html',username = username, data=data, item=item) #signup, login 부분 @app.route('/signup/', methods=['GET','POST']) # 완료 def signup() : return render_template('member_info.html') @app.route('/signup_verify/', methods=['GET','POST']) # 완료 def signup_verify() : button = request.values.get('button') UserID = request.values.get('ID') if button == "save" : # 정보 가져오기 Password = request.values.get('password') Password2 = request.values.get('password2') UserName = request.values.get('name') Zipcode = request.values.get('zipcode') address1 = request.values.get('address1') address2 = request.values.get('address2') email = request.values.get('email') phoneNum = request.values.get('phoneNum') address = address1 address = address + address2 # 유효성 확인 : password 유효성 검사만 추가하면됨 cursor = mysql.connect().cursor() cursor.execute('select * from member where mem_id = %s',UserID) data = cursor.fetchone() if not(UserID and Password and Password2 and UserName and Zipcode and address1 and address2 and email and phoneNum) : return "<script>alert('빈공간이 존재합니다.'); history.back();</script>" if data is not None : return "<script>alert('중복된 ID입니다.'); history.back();</script>" if Password != Password2 : return "<script>alert('두 비밀번호가 일치하지 않습니다.'); history.back();</script>" # insert문 conn = mysql.connect() cursor = conn.cursor() cursor.execute("""Insert into member (mem_id,pwd,name,address,tel,email,zip) values (%s,%s,%s,%s,%s,%s,%s)""",(UserID,Password,UserName,address,phoneNum,email,Zipcode)) conn.commit() return render_template('index.html') elif button == "cancel" : return render_template('index.html') elif button == "verify" : cursor = mysql.connect().cursor() cursor.execute('select * from member where mem_id = %s',UserID) data = cursor.fetchone() if UserID =="": return """ <script>alert('ID를 입력해주세요.'); history.back();</script> """ if data is None : return """ <script>alert('ID를 사용할 수 있습니다.'); history.back();</script> """ else : return """ <script>alert('ID를 이미 사용하고 있습니다.'); history.back();</script> """ @app.route('/login/', methods=['GET','POST']) # 완료 def login() : return render_template('login.html') @app.route('/logout/', methods=['GET','POST']) # 완료 def logout() : session.pop('username', None) return redirect(url_for('home')) # login DB 검사 @app.route('/Authenticate/',methods=['GET','POST']) # 완료 def Authenticate() : userID = request.form.get('ID') password = request.form.get('PW') cursor = mysql.connect().cursor() cursor.execute("Select * from member where mem_id = %s and pwd = %s",(userID,password)) data = cursor.fetchone() if data is None : return """ <script>alert('로그인에 실패했습니다.'); history.back();</script> """ else : session['username'] = userID return redirect(url_for('home')) # Search 부분 @app.route('/search', methods=['GET', 'POST']) #완료 def search(): search_key=request.values.get('searchBar') if search_key == "" or search_key == None : # 애완용품 탭 + 검색어 입력을 하지 않았을 때, conn = mysql.connect() cursor = conn.cursor() cursor.execute("select * from item_table") data = cursor.fetchall() return render_template('search_result.html', data=data) conn = mysql.connect() cursor = conn.cursor() cursor.execute("SELECT * FROM item_table WHERE item_name like %s" , ("%" + search_key + "%",)) #cursor.execute("select * from item_table") data = cursor.fetchall() if data is None : return "<script>alert('검색결과가 없습니다.'); history.back();</script>" else : return render_template('search_result.html', search_key=search_key, data=data) # 베스트 상품 @app.route('/search/best_product/',methods=['GET','POST']) # 완료 def bestproduct(): if 'username' in session : username = session['username'] else : return render_template('login.html') conn = mysql.connect() cursor = conn.cursor() cursor.execute("Select * from item_table limit 6") data = cursor.fetchall() return render_template('search_result.html', username = username, data = data) # 카테고리별 데이터 보여주기 @app.route('/search/category/<number>',methods=['GET','POST']) # 완료 def category(number = None) : conn = mysql.connect() cursor = conn.cursor() cursor.execute("SELECT * FROM item_table WHERE item_id like %s" , (number + "%")) data = cursor.fetchall() if data is None : return "<script>alert('검색결과가 없습니다.'); history.back();</script>" else : return render_template('search_result.html', data = data) # 상품 검색 결과 선택 부분 @app.route('/item_select/', methods=['Get','POST']) # 완료 def item_select() : button = request.values.get("button") number = request.values.get("number") if 'username' in session : username = session['username'] else : username = None if button == "order" : # 장바구니 추가 cost = request.values.get("cost") conn = mysql.connect() cursor = conn.cursor() cursor.execute("insert into cart_table values (%s, %s, 1, %s)",(username,number,cost)) conn.commit() return "<script>alert('장바구니에 추가하였습니다.'); history.back();</script>" elif button == "detail" : return item_detail(number = number) # item detail 부분 @app.route('/item_detail/', methods=['GET','POST']) # 완료 def item_detail(number = None) : number = request.values.get("number") if number is None : return render_template('404.html') else : # 아이템 정보를 DB에서 가져옴 cursor = mysql.connect().cursor() cursor.execute("Select * from item_table Where item_id = %s",number) data = cursor.fetchall() return render_template('item_detail.html',data = data) @app.route('/item_order/', methods=['GET','POST']) # 완료 def order() : # 주문 - 결제 부분 button = request.values.get('button') amount = request.values.get('amount') # 총계 counts = request.values.get('counts') # 주문 개수 item = request.values.get('item') if 'username' in session : username = session['username'] else : return render_template('login.html') if button == "card" : return render_template('payment_card.html',amount=amount,username = username) if button == "bank" : return render_template('payment_bank.html',amount=amount,username = username) if button == "insert" : conn = mysql.connect() cursor = conn.cursor() cursor.execute("update cart_table set amount = %s where item_id=%s and mem_id = %s",(counts,item,username)) conn.commit() return "<script>alert('물품을 수정하였습니다.'); history.back();</script>" if button == "delete" : conn = mysql.connect() cursor = conn.cursor() cursor.execute("delete from cart_table where item_id = %s and mem_id = %s",(item,username)) conn.commit() return "<script>alert('물품을 삭제하였습니다.'); history.back();</script>" if button == "cancel" : return render_template('search_result.html') if button == "order" : return "<script>alert('취소를 누르고, 장바구니담기 버튼을 눌러주세요.'); history.back();</script>" @app.route('/payment_card/', methods=['GET','POST']) # 구현 부족 def paymentcard() : # 결제 부분 - 카드결제 or 무통장입금 cardnum_1 = request.values.get('cardnum_1') cardnum_2 = request.values.get('cardnum_2') cardnum_3 = request.values.get('cardnum_3') cardnum_4 = request.values.get('cardnum_4') cardcvc = request.values.get('cardcvc') cardmonth = request.values.get('cardmonth') button = request.values.get('button') if button == "cancel" : return render_template('mypage.html') if not (cardnum_1 and cardnum_2 and cardnum_3 and cardnum_4 and cardcvc and cardmonth) : return "<script>alert('빈공간이 존재합니다.'); history.back();</script>" else : return render_template('index.html') @app.route('/payment_bank/',methods=['GET','POST']) # 구현 부족 def paymentbank() : name = request.values.get('name') button = request.values.get('button') if button == "cancel" : return render_template('mypage.html') if not (name) : return "<script>alert('빈공간이 존재합니다.'); history.back();</script>" else : return "<script>alert('계좌번호 : 123-456-7890 (국민)으로 입금부탁드립니다.'); history.back();</script>" # community 부분 @app.route('/community/',methods=['GET','POST']) # 완료 def community(): if 'username' in session : username = session['username'] cursor = mysql.connect().cursor() cursor.execute("Select * from board_table") data = cursor.fetchall() return render_template('community.html',username = username, data=data) else : return redirect(url_for('home')) # community - writer 부분 @app.route('/community/write/', methods=['GET','POST']) # 완료 def writeBoard() : return render_template('writer.html') # community - writer : 게시글 등록 @app.route('/community/write/db/',methods=['GET','POST']) # 완료 def writeDB() : button = request.values.get('button') if button == 'list' : return redirect(url_for('community')) elif button == 'cancel' : return redirect(url_for('community')) elif button =='writeOn' : UserID = session['username'] subject = request.values.get('subject') content = request.values.get('content') password = request.values.get('password') if subject == '': return "<script>alert('제목을 입력해주세요'); history.back();</script>" if content == '' : return "<script>alert('내용을 입력해주세요'); history.back();</script>" if password == '' : return "<script>alert('비밀번호를 입력해주세요'); history.back();</script>" # insert문 conn = mysql.connect() cursor = conn.cursor() cursor.execute("""Insert into board_table (title, content, writer_id, password) values (%s,%s,%s,%s)""",(subject, content, UserID, password)) conn.commit() return "<script>alert('게시글이 등록되었습니다.'); history.back();</script>" # community - read 부분 @app.route('/coummunity/board/<number>') # 완료 def readBoard(number = None) : if 'username' in session : username = session['username'] cursor = mysql.connect().cursor() cursor.execute("Select * from board_table where bd_num = %s",number) data = cursor.fetchall() if data is None : return """ <script>alert('게시글이 존재하지 않습니다.'); history.back();</script> """ else : # 조회수 상승 conn = mysql.connect() cursor = conn.cursor() cursor.execute("update board_table set hit=hit+1 where bd_num = %s",number) conn.commit() return render_template('read.html',username = username, data = data) else : return """ <script>alert('로그인이 필요합니다.'); history.back();</script> """ # button handler @app.route('/read_btn/') # 완료 def read_btn() : # data read username = session['username'] button = request.values.get('button') number = request.values.get('number') # switch : page redirection if button == "list" : return redirect(url_for('community')) elif button == "modify" : conn = mysql.connect() cursor = conn.cursor() cursor.execute("select * from board_table where bd_num = %s and writer_id = %s",(number,username)) data = cursor.fetchall() if data is None : return "<script>alert('수정권한이 없습니다.'); history.back();</script>" return render_template('modify.html',username = username, number = number, data = data) elif button == "delete" : return render_template('delete.html',username = username, number = number) else : return redirect(url_for('community')) # community - modify : 게시글 수정 @app.route('/community/modify/db/',methods=['GET','POST']) # 완료 def modifyDB() : button = request.values.get('button') if button == 'list' : return redirect(url_for('community')) elif button == 'cancel' : return redirect(url_for('community')) elif button =='modify' : UserID = session['username'] number = request.values.get('number') subject = request.values.get('subject') content = request.values.get('content') password = request.values.get('password') if subject == '': return "<script>alert('제목을 입력해주세요'); history.back();</script>" if content == '' : return "<script>alert('내용을 입력해주세요'); history.back();</script>" if password == '' : return "<script>alert('비밀번호를 입력해주세요'); history.back();</script>" # 비밀번호 확인 conn = mysql.connect() cursor = conn.cursor() cursor.execute("Select * from board_table where bd_num = %s and password = %s", (number,password)) data = cursor.fetchall() if data is None : return "<script>alert('비밀번호가 틀립니다.'); history.back();</script>" # update문 conn = mysql.connect() cursor = conn.cursor() cursor.execute("""update board_table set title = %s, content = %s where bd_num = %s """,(subject, content, number)) conn.commit() return "<script>alert('게시글이 수정되었습니다.'); history.back();</script>" # community - delete 부분 @app.route('/comunity/delete/') # 완료 def delete(number = None) : return render_template("delete.html",number=number) # community - delete : 게시글 삭제 @app.route('/delete/') # 완료 def deleteDB() : button = request.values.get('button') number = request.values.get('num') if button == 'cancel' : return redirect(url_for('community')) elif button =='delete' : UserID = session['username'] password = request.values.get('password') if password == '' : return "<script>alert('비밀번호를 입력해주세요'); history.back();</script>" # 비밀번호 확인 conn = mysql.connect() cursor = conn.cursor() cursor.execute("Select * from board_table where bd_num = %s and password = %s", (number,password)) data = cursor.fetchall() if data is None : return "<script>alert('비밀번호가 틀리거나 이미 게시글이 존재하지 않습니다.'); history.back();</script>" # delete문 conn = mysql.connect() cursor = conn.cursor() cursor.execute("delete from board_table where bd_num = %s", number) conn.commit() return "<script>alert('게시글이 삭제되었습니다.'); history.back();</script>" # admin 부분 @app.route('/admin/',methods=['GET','POST']) # 완료 def admin() : if 'username' in session : username = session['username'] return render_template('admin.html',username = username) else : return """ <script>alert('로그인이 필요합니다.'); history.back();</script> """ # item admin data db에서 가져와 페이지에 로드 @app.route('/admin_item/', methods=['GET','POST']) # 완료 def adminitem(): if 'username' in session : username = session['username'] cursor = mysql.connect().cursor() cursor.execute("Select * from item_table") data = cursor.fetchall() return render_template('admin_item.html',username = username, data = data) else : return """ <script>alert('로그인이 필요합니다.'); history.back();</script> """ # admin item - 정보수정창으로 이동 @app.route('/admin_item/modify/',methods=['GET','POST']) # 완료 def modifyItem() : if 'username' in session : username = session['username'] button = request.values.get('button') if button == 'itemDelete' : number = request.values.get('number') conn = mysql.connect() cursor = conn.cursor() cursor.execute("delete from item_table where item_id = %s", number) conn.commit() return redirect('admin_item') elif button == 'itemDetail': number = request.values.get('number') cursor = mysql.connect().cursor() cursor.execute("Select * from item_table where item_id = %s", number) data = cursor.fetchall() return render_template('admin_item_detail.html',username = username, data=data) else: return render_template('admin_item.html',username = username) # admin item - 등록창으로 이동 @app.route('/admin_item/register/',methods=['GET','POST']) # 완료 def registerItem() : if 'username' in session : username = session['username'] return render_template('admin_item_register.html',username = username) else : return redirect('home') # admin item - Item DB에 등록 @app.route('/admin_item/register_item/',methods=['GET','POST']) # 완료 def InsertItem() : button = request.values.get('button') if button == 'cancel' : return redirect('admin') # button == 'save' ID = request.values.get('prodID') Name = request.values.get('prodName') Price = request.values.get('prodP') Counts = request.values.get('prodQ') Detail = request.values.get('prodD') # 유효성 확인 - 빈공간 및 Prmiary 중복 확인 if not(ID and Name and Price and Counts and Detail) : return "<script>alert('빈공간이 존재합니다.'); history.back();</script>" conn = mysql.connect() cursor = conn.cursor() cursor.execute("select * from item_table where item_id = %s", ID) data = cursor.fetchone() if data is None : # insert문 conn2 = mysql.connect() cursor2 = conn2.cursor() cursor2.execute("""insert item_table values (%s, %s, %s, %s, %s)""" ,(ID, Name, Price, Detail, Counts)) conn2.commit() return "<script>alert('등록이 완료되었습니다.'); history.back();</script>" else : return "<script>alert('상품번호가 이미 존재합니다.'); history.back();</script>" # admin item - Item DB를 업데이트 @app.route('/admin_item/update/',methods=['GET','POST']) # 완료 def updateItem() : button = request.values.get('button') if button == 'cancel' : return redirect('/admin_item/') # button == 'save' ID = request.values.get('prodID') Name = request.values.get('prodName') Price = request.values.get('prodP') Counts = request.values.get('prodQ') Detail = request.values.get('prodD') # 유효성 확인 if not(ID and Name and Price and Counts and Detail) : return "<script>alert('빈공간이 존재합니다.'); history.back();</script>" # update문 conn = mysql.connect() cursor = conn.cursor() cursor.execute("""update item_table set item_name = %s, item_price = %s, item_info = %s, stock = %s where item_id = %s""" ,(Name, Price, Detail, Counts, ID)) conn.commit() return redirect('admin_item') # member admin data db에서 가져와 페이지에 로드 @app.route('/admin_member/', methods=['GET','POST']) # 완료 def adminmember(): if 'username' in session : username = session['username'] cursor = mysql.connect().cursor() cursor.execute("Select * from member") data = cursor.fetchall() return render_template('admin_member.html',username = username, data = data) else: return """ <script>alert('로그인이 필요합니다.'); history.back();</script> """ # admin member - 주문정보 list 가져오기 @app.route('/admin_member/orderdetail',methods =['GET','POST']) # 완료 def adminorderdetail(): if 'username' in session : username = session['username'] Name = request.values.get('ID') cursor = mysql.connect().cursor() cursor.execute("Select * from orderlist_table where order_name = %s",(Name)) data = cursor.fetchall() return render_template('member_orderDetail.html',username = username, data = data) else: return """ <script>alert('로그인이 필요합니다.'); history.back();</script> """ # admin member - 주문 상태 업데이트 @app.route('/admin_member/update/',methods=['GET','POST']) # 완료 def updateOrder() : state = request.values.get("state") number = request.values.get("number") # 유효성 확인 if not (state and number) : return "<script>alert('빈공간이 존재합니다.'); history.back();</script>" # update문 conn = mysql.connect() cursor = conn.cursor() cursor.execute("""update orderlist_table set state = %s where order_num = %s""" ,(state, number)) conn.commit() return "<script>alert('수정이 완료되었습니다.'); history.back();</script>" # board admin data db에서 가져와 페이지에 로드 @app.route('/admin_board/', methods=['GET','POST']) # 완료 def adminboard(): if 'username' in session : username = session['username'] cursor = mysql.connect().cursor() cursor.execute("Select * from board_table") data = cursor.fetchall() return render_template('admin_board.html',username = username,data = data) else: return """ <script>alert('로그인이 필요합니다.'); history.back();</script> """ @app.route('/admin_board/modify/', methods=['GET','POST']) def modifyadminboard() : if 'username' in session : username = session['username'] number = request.values.get('number') conn=mysql.connect() cursor = conn.cursor() cursor.execute("delete from board_table where bd_num=%s",number) conn.commit() return redirect('admin_board') else: return """ <script>alert('로그인이 필요합니다.'); history.back();</script> """ @app.route('/admin_board/process/', methods=['GET','POST']) def processadminboard() : button = request.values.get('button') number = request.values.get('number') if button == "delete" : conn = mysql.connect() cursor = conn.cursor() cursor.execute("delete from board_table where bd_num = %s",(number)) conn.commit() return "<script>alert('삭제완료되었습니다.'); history.back();</script>" elif button == "modify" : title = request.values.get('subject') content = request.values.get('content') conn = mysql.connect() cursor = conn.cursor() cursor.execute("update board_table set title = %s, content = %s where bd_num = %s",(title, content, number)) conn.commit() return "<script>alert('수정완료되었습니다.'); history.back();</script>" elif button == "cancel" : return redirect(url_for('admin_board')) # mypage 부분 - 완료 @app.route('/mypage/',methods=['GET','POST']) @app.route('/mypage/<username>',methods=['GET','POST']) def mypage() : if 'username' in session : username = session['username'] amount = 0 conn = mysql.connect() cursor = conn.cursor() cursor.execute("select * from cart_table, item_table where cart_table.item_id = item_table.item_id and cart_table.mem_id = %s",username) data = cursor.fetchall() data2 = data if data2 is not None : for row in data2 : amount = amount + row[2] * row[3] return render_template('mypage.html',username = username, data = data, amount = amount) else: return """ <script>alert('로그인이 필요합니다.'); history.back();</script> """ # 주문번호별 리스트 보여주기 @app.route('/my_order/',methods=['GET','POST']) @app.route('/my_order/<username>',methods=['GET','POST']) def myorder(username = None) : if 'username' in session : username = session['username'] cursor = mysql.connect().cursor() cursor.execute("Select * from orderlist_table where order_name = %s",(username)) data = cursor.fetchall() return render_template('my_order.html',username = username, data = data) else: return """ <script>alert('로그인이 필요합니다.'); history.back();</script> """ @app.route('/my_revise/',methods=['GET','POST']) # 완료 @app.route('/my_revise/<username>',methods=['GET','POST']) def myrevise(username = None) : if 'username' in session : username = session['username'] cursor = mysql.connect().cursor() cursor.execute("select * from member where mem_id = %s",username) data = cursor.fetchall() return render_template('my_revise.html',username = username, data=data) else: return """ <script>alert('로그인이 필요합니다.'); history.back();</script> """ # my_revise - 유효성 검사 후, 처리 @app.route('/vertify/', methods=['GET','POST']) # 확인 필요 def vertify() : # 1 : cancel, 2 : save, 3 : drop function = request.values.get('button') if function == '1' : # cancel return redirect(url_for('mypage')) elif function == '2' : # save # 정보 가져오기 UserID = session['username'] Password = request.values.get('password') Password2 = request.values.get('password2') UserName = request.values.get('name') Zipcode = request.values.get('zipcode') address1 = request.values.get('address1') address2 = request.values.get('address2') email = request.values.get('email') phoneNum = request.values.get('phonenum') address = address1 address = address + " " address = address + address2 # 유효성 확인 : password 유효성 검사만 추가하면됨 if not(Password and Password2 and UserName and Zipcode and address and email and phoneNum) : return "<script>alert('빈공간이 존재합니다.'); history.back();</script>" if Password != Password2 : return "<script>alert('두 비밀번호가 일치하지 않습니다.'); history.back();</script>" # update문 conn = mysql.connect() cursor = conn.cursor() cursor.execute("""update member set pwd = %s, name = %s, address = %s, tel = %s, email = %s, zip = %s where mem_id = %s""",(Password, UserName, address, phoneNum, email, Zipcode, UserID)) conn.commit() return "<script>alert('수정이 완료되었습니다.'); history.back();</script>" elif function == '3' : username = session['username'] session.pop('username',None) # delete문 conn = mysql.connect() cursor = conn.cursor() cursor.execute("delete from member where mem_id = %s",(username)) conn.commit() return "<script>alert('탈퇴가 완료되었습니다.'); history.back() </script> " else : return errorhandler(404) if __name__ == '__main__': app.run(debug=True) #app.run(debug=True)
37.044271
145
0.587979
58c0278cd816d57c9b7f341d7bfb795caccd85da
1,501
css
CSS
server-core/src/main/java/io/onedev/server/web/component/savedquery/saved-queries.css
parampavar/onedev
d1e2417d0e06ee6abfc2fcb75497cbf9af7eaad1
[ "MIT" ]
1
2020-05-22T16:25:13.000Z
2020-05-22T16:25:13.000Z
server-core/src/main/java/io/onedev/server/web/component/savedquery/saved-queries.css
parampavar/onedev
d1e2417d0e06ee6abfc2fcb75497cbf9af7eaad1
[ "MIT" ]
null
null
null
server-core/src/main/java/io/onedev/server/web/component/savedquery/saved-queries.css
parampavar/onedev
d1e2417d0e06ee6abfc2fcb75497cbf9af7eaad1
[ "MIT" ]
1
2022-03-15T19:33:12.000Z
2022-03-15T19:33:12.000Z
.saved-queries>.head { white-space: nowrap; } .saved-queries>.head>* { display: inline-block; } .saved-queries>.head>.actions { margin: 8px 0 0 12px; } .saved-queries>.head>.actions>a { color: #444; opacity: 100; margin-right: 8px; font-size: 16px; } .saved-queries>.head>.actions .close-saved-queries { font-size: 17px; display: inline-block; } .saved-queries>.body>* { margin-bottom: 20px; } .saved-queries>.body>:last-child { margin-bottom: 0; } .saved-queries>.body .btn-group { white-space: nowrap; } .saved-queries>.body .btn-group .btn { float: none; display: inline-block; } .saved-queries>.body .watch-status:after, .saved-queries>.body .subscription-status:after { display: none; } .saved-queries>.body .watch-status:before, .saved-queries>.body .subscription-status:before { line-height: 12px; } .edit-saved-queries th { font-weight: bold !important; } .edit-saved-queries th.property-name { width: 30%; } .edit-saved-queries>.property { border: 1px solid #E8E8E8; background: #F9F9F9; border-radius: 4px; padding: 10px; } .edit-saved-queries .editable .bean.list>thead>tr>th { border-bottom: none; padding-bottom: 4px; } .query-save-support { display: table; width: 100%; } .query-save-support>div { display: table-cell; } .query-save-support>.side { border: 2px solid #E0E0E0; padding: 20px; border-radius: 4px; width: 1%; } .query-save-support>.main { vertical-align: top; min-width: 330px; } .query-save-support>.side+.main { padding-left: 20px; }
19.24359
54
0.69487
d16855827d2bf5e4b77688fdfa60f6ac259eb3c5
101
sh
Shell
test/Identity.Dapper.Tests.Integration/MySQL/restart.sh
sinangun/Identity.Dapper
db494657483080c6c81c304cd83986793f7efc20
[ "MIT" ]
266
2016-06-17T05:23:44.000Z
2022-01-18T15:17:07.000Z
test/Identity.Dapper.Tests.Integration/MySQL/restart.sh
sinangun/Identity.Dapper
db494657483080c6c81c304cd83986793f7efc20
[ "MIT" ]
68
2016-06-16T19:01:23.000Z
2021-03-08T07:07:40.000Z
test/Identity.Dapper.Tests.Integration/MySQL/restart.sh
sinangun/Identity.Dapper
db494657483080c6c81c304cd83986793f7efc20
[ "MIT" ]
78
2016-07-30T12:10:29.000Z
2022-01-14T04:20:55.000Z
docker-compose stop docker rm $(docker ps -a | grep mysql | awk '{ print $1 }') docker-compose up -d
33.666667
59
0.673267
729f26ff0a94e791265471e16a02298440eeb2fd
780
cs
C#
MACHINA/Assets/Scripts/Scene/FadeImage.cs
kurokurogamer/MAKINAS
9e156691b4eae6a4d135ff356926d2cd3f959875
[ "Unlicense" ]
null
null
null
MACHINA/Assets/Scripts/Scene/FadeImage.cs
kurokurogamer/MAKINAS
9e156691b4eae6a4d135ff356926d2cd3f959875
[ "Unlicense" ]
null
null
null
MACHINA/Assets/Scripts/Scene/FadeImage.cs
kurokurogamer/MAKINAS
9e156691b4eae6a4d135ff356926d2cd3f959875
[ "Unlicense" ]
null
null
null
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class FadeImage : FadeUI { // フェイドするイメージ private Image _image; protected override void Awake() { base.Awake(); _image = GetComponent<Image>(); if (_image) { _image.color = new Color(_image.color.r, _image.color.g, _image.color.b, _alpha); } } protected override void OnDisable() { base.OnDisable(); if (!_image) { _image = GetComponent<Image>(); } Debug.Log("処理"); if (_image) { _image.color = new Color(_image.color.r, _image.color.g, _image.color.b, _alpha); } } // Update is called once per frame void Update() { Fade(); _image.color = new Color(_image.color.r, _image.color.g, _image.color.b, _alpha); } }
17.727273
84
0.666667
5170eda9666f3196946ae117578c9e9eb582aad2
31
sql
SQL
server/db/sql/pictures/drop.sql
kevinnorris/pintclone
55a2ce4c7c10c3cc91b4320ddc5ed2888254306e
[ "MIT" ]
null
null
null
server/db/sql/pictures/drop.sql
kevinnorris/pintclone
55a2ce4c7c10c3cc91b4320ddc5ed2888254306e
[ "MIT" ]
null
null
null
server/db/sql/pictures/drop.sql
kevinnorris/pintclone
55a2ce4c7c10c3cc91b4320ddc5ed2888254306e
[ "MIT" ]
null
null
null
DROP TABLE ${schema~}.Pictures;
31
31
0.741935
47ee4dfa4f75171e207f6be69eba501851b2a012
1,452
dart
Dart
lib/providers/notifiers.dart
castaway/nag_me
6c752bf5a9f0a42fa6d7c50d09c87d0496f19ee3
[ "BSD-3-Clause" ]
null
null
null
lib/providers/notifiers.dart
castaway/nag_me
6c752bf5a9f0a42fa6d7c50d09c87d0496f19ee3
[ "BSD-3-Clause" ]
null
null
null
lib/providers/notifiers.dart
castaway/nag_me
6c752bf5a9f0a42fa6d7c50d09c87d0496f19ee3
[ "BSD-3-Clause" ]
null
null
null
import 'dart:convert'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:nag_me_lib/nag_me.dart'; class Notifiers with ChangeNotifier { String owner_id; List<Notifier> _notifiers = []; List<Notifier> get list { return [..._notifiers]; } Future<void> loadNotifiers() async { // we fetch these from firebase! final query = await FirebaseFirestore.instance .collection('users') .doc(this.owner_id) .collection('notifiers') .get(); final List<DocumentSnapshot> docs = query.docs; this._notifiers = docs.map((doc) { Engine chosen = Engine.values.firstWhere((val) => val.toString() == doc.data()['engine']); return Notifier( owner_id: this.owner_id, engine: chosen, settings: NotifierSetting.getInstance(chosen, jsonDecode(doc.data()['settings'])), last_modified: DateTime.parse(doc.data()['last_modified']) ); }).toList(); } Future<void> addNotifier(Notifier newNotifier) async { await FirebaseFirestore.instance .collection('users') .doc(this.owner_id) .collection('notifiers') .add({ 'engine' : newNotifier.engine.toString(), 'settings': newNotifier.settings.toString(), 'last_modified': newNotifier.last_modified.toString() }); _notifiers.add(newNotifier); notifyListeners(); } }
28.470588
92
0.646694
6596e936eaac8b70c34d8600db4026bd54c7a301
996
swift
Swift
Tests/ResponseTests.swift
LucianoPolit/Leash
ecacf20e75d0106f870cea4f2f22421dd2b4af53
[ "MIT" ]
17
2017-11-27T15:35:00.000Z
2022-02-20T23:12:28.000Z
Tests/ResponseTests.swift
LucianoPolit/Leash
ecacf20e75d0106f870cea4f2f22421dd2b4af53
[ "MIT" ]
1
2019-03-12T18:56:55.000Z
2019-05-14T07:13:53.000Z
Tests/ResponseTests.swift
LucianoPolit/Leash
ecacf20e75d0106f870cea4f2f22421dd2b4af53
[ "MIT" ]
1
2019-03-12T17:26:07.000Z
2019-03-12T17:26:07.000Z
// // ResponseTests.swift // Example // // Created by Luciano Polit on 11/28/17. // Copyright © 2017 Luciano Polit. All rights reserved. // import Foundation import XCTest @testable import Leash class ResponseTests: BaseTestCase { let failure = Response<Data>.failure(Leash.Error.unknown) let success = Response.success(value: Data(), extra: "extra") } // MARK: - Utils extension ResponseTests { func testFailure() { XCTAssertTrue(failure.isFailure) XCTAssertFalse(success.isFailure) } func testIsSuccess() { XCTAssertFalse(failure.isSuccess) XCTAssertTrue(success.isSuccess) } func testError() { XCTAssertNotNil(failure.error) XCTAssertNil(success.error) } func testValue() { XCTAssertNil(failure.value) XCTAssertNotNil(success.value) } func testExtra() { XCTAssertNil(failure.extra) XCTAssertNotNil(success.extra) } }
19.92
65
0.638554
651364d9a6c39499e50c20e1b977687fd9724dc0
103
css
CSS
src/main/css/google/khmer/index.css
superflycss/utilities-fonts
83680e581aa6c78aba4cb48f64606749803ba4ac
[ "MIT" ]
3
2018-03-09T05:47:34.000Z
2019-02-26T16:31:45.000Z
src/main/css/google/khmer/index.css
superflycss/utilities-fonts
83680e581aa6c78aba4cb48f64606749803ba4ac
[ "MIT" ]
10
2018-05-06T19:53:24.000Z
2020-05-15T20:36:41.000Z
src/main/css/google/khmer/index.css
superflycss/utilities-fonts
83680e581aa6c78aba4cb48f64606749803ba4ac
[ "MIT" ]
2
2017-07-13T20:14:38.000Z
2018-03-09T05:47:38.000Z
.u-font-khmer-400 { font-family: 'Khmer' !important; font-weight: 400 !important; }
25.75
42
0.572816
c44a0627e809de0fb6c2b324059d3a75c1dda6ab
6,723
cpp
C++
src/shogun/classifier/FeatureBlockLogisticRegression.cpp
srgnuclear/shogun
33c04f77a642416376521b0cd1eed29b3256ac13
[ "Ruby", "MIT" ]
1
2015-11-05T18:31:14.000Z
2015-11-05T18:31:14.000Z
src/shogun/classifier/FeatureBlockLogisticRegression.cpp
waderly/shogun
9288b6fa38e001d63c32188f7f847dadea66e2ae
[ "Ruby", "MIT" ]
null
null
null
src/shogun/classifier/FeatureBlockLogisticRegression.cpp
waderly/shogun
9288b6fa38e001d63c32188f7f847dadea66e2ae
[ "Ruby", "MIT" ]
null
null
null
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Copyright (C) 2012 Sergey Lisitsyn */ #include <shogun/classifier/FeatureBlockLogisticRegression.h> #include <shogun/lib/slep/slep_solver.h> #include <shogun/lib/slep/slep_options.h> #include <shogun/lib/IndexBlockGroup.h> #include <shogun/lib/IndexBlockTree.h> namespace shogun { CFeatureBlockLogisticRegression::CFeatureBlockLogisticRegression() : CLinearMachine() { init(); register_parameters(); } CFeatureBlockLogisticRegression::CFeatureBlockLogisticRegression( float64_t z, CDotFeatures* train_features, CBinaryLabels* train_labels, CIndexBlockRelation* feature_relation) : CLinearMachine() { init(); set_feature_relation(feature_relation); set_z(z); set_features(train_features); set_labels(train_labels); register_parameters(); } void CFeatureBlockLogisticRegression::init() { m_feature_relation=NULL; m_z=0.0; m_q=2.0; m_termination=0; m_regularization=0; m_tolerance=1e-3; m_max_iter=1000; } CFeatureBlockLogisticRegression::~CFeatureBlockLogisticRegression() { SG_UNREF(m_feature_relation); } void CFeatureBlockLogisticRegression::register_parameters() { SG_ADD((CSGObject**)&m_feature_relation, "feature_relation", "feature relation", MS_NOT_AVAILABLE); SG_ADD(&m_z, "z", "regularization coefficient", MS_AVAILABLE); SG_ADD(&m_q, "q", "q of L1/Lq", MS_AVAILABLE); SG_ADD(&m_termination, "termination", "termination", MS_NOT_AVAILABLE); SG_ADD(&m_regularization, "regularization", "regularization", MS_NOT_AVAILABLE); SG_ADD(&m_tolerance, "tolerance", "tolerance", MS_NOT_AVAILABLE); SG_ADD(&m_max_iter, "max_iter", "maximum number of iterations", MS_NOT_AVAILABLE); } CIndexBlockRelation* CFeatureBlockLogisticRegression::get_feature_relation() const { SG_REF(m_feature_relation); return m_feature_relation; } void CFeatureBlockLogisticRegression::set_feature_relation(CIndexBlockRelation* feature_relation) { SG_REF(feature_relation); SG_UNREF(m_feature_relation); m_feature_relation = feature_relation; } int32_t CFeatureBlockLogisticRegression::get_max_iter() const { return m_max_iter; } int32_t CFeatureBlockLogisticRegression::get_regularization() const { return m_regularization; } int32_t CFeatureBlockLogisticRegression::get_termination() const { return m_termination; } float64_t CFeatureBlockLogisticRegression::get_tolerance() const { return m_tolerance; } float64_t CFeatureBlockLogisticRegression::get_z() const { return m_z; } float64_t CFeatureBlockLogisticRegression::get_q() const { return m_q; } void CFeatureBlockLogisticRegression::set_max_iter(int32_t max_iter) { ASSERT(max_iter>=0) m_max_iter = max_iter; } void CFeatureBlockLogisticRegression::set_regularization(int32_t regularization) { ASSERT(regularization==0 || regularization==1) m_regularization = regularization; } void CFeatureBlockLogisticRegression::set_termination(int32_t termination) { ASSERT(termination>=0 && termination<=4) m_termination = termination; } void CFeatureBlockLogisticRegression::set_tolerance(float64_t tolerance) { ASSERT(tolerance>0.0) m_tolerance = tolerance; } void CFeatureBlockLogisticRegression::set_z(float64_t z) { m_z = z; } void CFeatureBlockLogisticRegression::set_q(float64_t q) { m_q = q; } bool CFeatureBlockLogisticRegression::train_machine(CFeatures* data) { if (data && (CDotFeatures*)data) set_features((CDotFeatures*)data); ASSERT(features) ASSERT(m_labels) int32_t n_vecs = m_labels->get_num_labels(); SGVector<float64_t> y(n_vecs); for (int32_t i=0; i<n_vecs; i++) y[i] = ((CBinaryLabels*)m_labels)->get_label(i); slep_options options = slep_options::default_options(); options.q = m_q; options.regularization = m_regularization; options.termination = m_termination; options.tolerance = m_tolerance; options.max_iter = m_max_iter; options.loss = LOGISTIC; EIndexBlockRelationType relation_type = m_feature_relation->get_relation_type(); switch (relation_type) { case GROUP: { CIndexBlockGroup* feature_group = (CIndexBlockGroup*)m_feature_relation; SGVector<index_t> ind = feature_group->get_SLEP_ind(); options.ind = ind.vector; options.n_feature_blocks = ind.vlen-1; if (ind[ind.vlen-1] > features->get_dim_feature_space()) SG_ERROR("Group of features covers more features than available\n") options.gWeight = SG_MALLOC(double, options.n_feature_blocks); for (int32_t i=0; i<options.n_feature_blocks; i++) options.gWeight[i] = 1.0; options.mode = FEATURE_GROUP; options.loss = LOGISTIC; options.n_nodes = 0; slep_result_t result = slep_solver(features, y.vector, m_z, options); SG_FREE(options.gWeight); int32_t n_feats = features->get_dim_feature_space(); SGVector<float64_t> new_w(n_feats); for (int i=0; i<n_feats; i++) new_w[i] = result.w[i]; set_bias(result.c[0]); w = new_w; } break; case TREE: { CIndexBlockTree* feature_tree = (CIndexBlockTree*)m_feature_relation; SGVector<float64_t> ind_t = feature_tree->get_SLEP_ind_t(); SGVector<float64_t> G; if (feature_tree->is_general()) { G = feature_tree->get_SLEP_G(); options.general = true; } options.ind_t = ind_t.vector; options.G = G.vector; options.n_nodes = ind_t.vlen/3; options.n_feature_blocks = ind_t.vlen/3; options.mode = FEATURE_TREE; options.loss = LOGISTIC; slep_result_t result = slep_solver(features, y.vector, m_z, options); int32_t n_feats = features->get_dim_feature_space(); SGVector<float64_t> new_w(n_feats); for (int i=0; i<n_feats; i++) new_w[i] = result.w[i]; set_bias(result.c[0]); w = new_w; } break; default: SG_ERROR("Not supported feature relation type\n") } return true; } float64_t CFeatureBlockLogisticRegression::apply_one(int32_t vec_idx) { return CMath::exp(-(features->dense_dot(vec_idx, w.vector, w.vlen) + bias)); } SGVector<float64_t> CFeatureBlockLogisticRegression::apply_get_outputs(CFeatures* data) { if (data) { if (!data->has_property(FP_DOT)) SG_ERROR("Specified features are not of type CDotFeatures\n") set_features((CDotFeatures*) data); } if (!features) return SGVector<float64_t>(); int32_t num=features->get_num_vectors(); ASSERT(num>0) ASSERT(w.vlen==features->get_dim_feature_space()) float64_t* out=SG_MALLOC(float64_t, num); features->dense_dot_range(out, 0, num, NULL, w.vector, w.vlen, bias); for (int32_t i=0; i<num; i++) out[i] = 2.0/(1.0+CMath::exp(-out[i])) - 1.0; return SGVector<float64_t>(out,num); } }
25.660305
100
0.754425
b99a657c1289c7dd3b6464494771c26b040768a8
3,837
go
Go
data/asset_store_test.go
Joro97/Cloud_Asset_Uploader
ffb1a2c8d8ee791bcb029a46480882eb43f31c28
[ "MIT" ]
null
null
null
data/asset_store_test.go
Joro97/Cloud_Asset_Uploader
ffb1a2c8d8ee791bcb029a46480882eb43f31c28
[ "MIT" ]
null
null
null
data/asset_store_test.go
Joro97/Cloud_Asset_Uploader
ffb1a2c8d8ee791bcb029a46480882eb43f31c28
[ "MIT" ]
null
null
null
package data import ( "context" "os" "testing" "CloudAssetUploader/constants" "github.com/rs/zerolog/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) var ( db *DB invalidConnStr = "notMongodb://username:password@host:port" ) func TestMain(m *testing.M) { setUp() code := m.Run() tearDown() os.Exit(code) } func setUp() { setLocalhostEnvVars() connStr, _ := BuildConnectionStringForMongoDB() database, _ := NewDB(connStr) db = database } func setLocalhostEnvVars() { err := os.Setenv("MONGO_USERNAME", "mongoadmin") err = os.Setenv("MONGO_PASSWORD", "bigSecret") err = os.Setenv("MONGO_CONTAINER_NAME", "localhost") err = os.Setenv("MONGO_PORT", "12345") if err != nil { log.Error().Msg("Could not set environment variables for connection to MongoDB container from local machine. Integration tests will fail.") } } func TestIntegrationBuildConnectionStringForDBReturnsErrorsForMissingEnvVars(t *testing.T) { os.Unsetenv("MONGO_USERNAME") _, err := BuildConnectionStringForMongoDB() assert.Error(t, err) os.Setenv("MONGO_USERNAME", "mongoadmin") os.Unsetenv("MONGO_PASSWORD") _, err = BuildConnectionStringForMongoDB() assert.Error(t, err) os.Setenv("MONGO_PASSWORD", "bigSecret") os.Unsetenv("MONGO_CONTAINER_NAME") _, err = BuildConnectionStringForMongoDB() assert.Error(t, err) os.Setenv("MONGO_CONTAINER_NAME", "localhost") os.Unsetenv("MONGO_PORT") _, err = BuildConnectionStringForMongoDB() assert.Error(t, err) os.Setenv("MONGO_PORT", "12345") } func TestIntegrationNewDBReturnsAnErrorForInvalidConnectionString(t *testing.T) { _, err := NewDB(invalidConnStr) assert.Error(t, err) } func TestIntegrationAddNewAssetAddsAssetWithProperNameAndUrl(t *testing.T) { _, err := db.AddNewAsset(constants.MockID, constants.MockURL) require.NoError(t, err) } func TestIntegrationSetAssetStatusShouldReturnProperAssetWithValidIdAndStatus(t *testing.T) { _, err := db.AddNewAsset(constants.MockID, constants.MockURL) require.NoError(t, err) asset, err := db.SetAssetStatus(constants.MockID, constants.AssetStatusUploaded) require.NoError(t, err) assert.Equal(t, constants.MockID, asset.Name) assert.Equal(t, constants.AssetStatusUploaded, asset.UploadStatus) } func TestIntegrationSetAssetStatusShouldReturnProperErrorWithInvalidStatus(t *testing.T) { _, err := db.SetAssetStatus(constants.MockID, constants.InvalidStatus) require.Error(t, err) } func TestIntegrationSetAssetStatusShouldReturnProperErrorWithNonExistentAssetId(t *testing.T) { _, err := db.SetAssetStatus(constants.MockNonExistentID, constants.AssetStatusUploaded) require.Error(t, err) } func TestIntegrationGetAssetShouldReturnProperAssetWhenValidId(t *testing.T) { _, err := db.AddNewAsset(constants.MockID, constants.MockURL) require.NoError(t, err) asset, err := db.GetAsset(constants.MockID) require.NoError(t, err) assert.Equal(t, constants.MockID, asset.Name) } func TestIntegrationGetAssetShouldReturnProperErrorWhenNonExistentIdProvided(t *testing.T) { _, err := db.AddNewAsset(constants.MockID, constants.MockURL) require.NoError(t, err) asset, err := db.GetAsset(constants.MockNonExistentID) require.Error(t, err) assert.Nil(t, asset) } func tearDown() { defer db.Client.Disconnect(context.Background()) err := os.Unsetenv("MONGO_USERNAME") err = os.Unsetenv("MONGO_PASSWORD") err = os.Unsetenv("MONGO_CONTAINER_NAME") err = os.Unsetenv("MONGO_PORT") if err != nil { log.Error().Msg("Could not unset all MongoDB env vars properly. Please unset manually.") } assetInfoCollection := db.Client.Database(constants.AssetUploaderDatabaseName).Collection(constants.AssetUploaderCollectionName) err = assetInfoCollection.Drop(context.Background()) if err != nil { log.Error().Msg("Could not drop database after tests.") } }
28.849624
141
0.763617
b59754a8a4421bd8a6bd8d59a047a487ca8d1dc8
12,808
lua
Lua
payback.lua
jgoldhammer/moneymoney-payback
cff9b48aba9f55ea9f28636e12c72ec21488e9bd
[ "Unlicense", "MIT" ]
11
2016-01-25T18:33:14.000Z
2019-05-23T05:57:45.000Z
payback.lua
jgoldhammer/moneymoney-payback
cff9b48aba9f55ea9f28636e12c72ec21488e9bd
[ "Unlicense", "MIT" ]
5
2016-05-14T08:42:14.000Z
2021-01-30T08:32:38.000Z
payback.lua
jgoldhammer/moneymoney-payback
cff9b48aba9f55ea9f28636e12c72ec21488e9bd
[ "Unlicense", "MIT" ]
3
2017-04-27T20:13:35.000Z
2018-03-07T18:57:22.000Z
-- --------------------------------------------------------------------------------------------------------------------- -- -- MoneyMoney Web Banking Extension -- http://moneymoney-app.com/api/webbanking -- -- -- The MIT License (MIT) -- -- Copyright (c) 2012-2016 MRH applications GmbH -- -- 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. -- -- --------------------------------------------------------------------------------------------------------------------- -- --------------------------------------------------------------------------------------------------------------------- -- -- Get portfolio of Payback online account. -- -- ATTENTION: This extension requires MoneyMoney version 2.2.2 or higher -- -- --------------------------------------------------------------------------------------------------------------------- -- --------------------------------------------------------------------------------------------------------------------- -- Common MoneyMoney extension informations -- --------------------------------------------------------------------------------------------------------------------- WebBanking { version = 2.11, country = "de", url = "https://www.payback.de/login#loginSecureTab", services = {"Payback-Punkte"}, description = string.format(MM.localizeText("Get points of %s"), "Payback account") } -- --------------------------------------------------------------------------------------------------------------------- -- Helper functions -- --------------------------------------------------------------------------------------------------------------------- local function strToAmount(str) -- Helper function for converting localized amount strings to Lua numbers. print("raw value: ".. str) local convertedValue = string.gsub(string.gsub(string.gsub(str, " .+", ""), "%.", ""), ",", ".") print("converted value " .. convertedValue) return convertedValue end --Helper for priniting nested table local function deep_print(tbl) for i, v in pairs(tbl) do if type(v) == "table" then deep_print(v) else print(i, v) end end end -- --------------------------------------------------------------------------------------------------------------------- local function strToAmountWithDefault(str, defaultValue) -- Helper function for converting localized amount strings to Lua numbers with a default value. local value = strToAmount(str) if value == nil or value == "" then value = defaultValue end return value end -- --------------------------------------------------------------------------------------------------------------------- local function strToDate(str) -- Helper function for converting localized date strings to timestamps. local d, m, y = string.match(str, "(%d%d)%.(%d%d)%.(%d%d%d%d)") if d and m and y then return os.time { year = y, month = m, day = d, hour = 0, min = 0, sec = 0 } end end -- --------------------------------------------------------------------------------------------------------------------- local function printElementWithPrefix(prefix, element) -- Helper function for debugging HTML elements with a prtinable prefix if element:children():length() >= 1 then element:children():each(function(index, element2) local newPrefix = prefix .. "-" .. index print(newPrefix .. "=" .. element2:text()) printElementWithPrefix(newPrefix, element2) end) end end -- --------------------------------------------------------------------------------------------------------------------- local function strToFullDate (str) -- Helper function for converting localized date strings to timestamps. local d, m, y = string.match(str, "(%d%d).(%d%d).(%d%d%d%d)") return os.time{year=y, month=m, day=d} end local function printElement(element) -- Helper function for debugging HTML elements printElementWithPrefix('0', element) end -- --------------------------------------------------------------------------------------------------------------------- -- The following variables are used to save state. -- --------------------------------------------------------------------------------------------------------------------- local connection local overview_html -- --------------------------------------------------------------------------------------------------------------------- -- -- MoneyMoney API Extension -- -- @see: http://moneymoney-app.com/api/webbanking/ -- -- --------------------------------------------------------------------------------------------------------------------- function SupportsBank(protocol, bankCode) -- Using artificial bankcode to identify the DWS Investments group. return bankCode == "Payback-Punkte" and protocol == ProtocolWebBanking end -- --------------------------------------------------------------------------------------------------------------------- function InitializeSession(protocol, bankCode, username, customer, password) print("InitializeSession with " .. protocol .. " connecting " .. url .. " with ".. username) MM.printStatus("Start to login for user ".. username) -- Create HTTPS connection object. connection = Connection() connection.language = "de-de" -- just ask the mpm to get a userId-- --local request = connection:get("https://mpm.payback.de/js?wp_id=3125530"); -- Fetch login page. local loginPage = HTML(connection:get(url)) -- Fill in login credentials. loginPage:xpath("//*[@id='aliasInputSecure']"):attr("value", username) loginPage:xpath("//*[@id='passwordInput']"):attr("value", password) MM.printStatus("parameters for login filled in - username = " .. username); local loginForm = loginPage:xpath("//form[@name='loginForm']"); tprint(loginForm, 2); -- Submit login form. local response, code, headers, status = connection:request(loginForm:submit()) -- local response, code, headers, status = connection:request(loginPage:xpath("//input[@id='loginSubmitButtonSecure']"):click()) MM.printStatus("status code " ..code) MM.printStatus("headers " ..headers) MM.printStatus("status " ..status) MM.printStatus("login response " ..response) overview_html = HTML(response) -- Submit login form. -- MM.printStatus("request " ..request) -- overview_html = HTML(request) -- Check for failed login. local failure = overview_html:xpath("//*[@id='errorNotification']") if failure:length() > 0 then print("Login failed. Reason: " .. failure:xpath("//*p[@class='MsoNormal']")) MM.printStatus("Login failed..."); return LoginFailed end MM.printStatus("Login success- go to correct paypack page "); -- hard coded point url ... overview_html = HTML(connection:get("https://www.payback.de/pb/punktekonto/id/13598/")) print("Session initialization completed successfully.") MM.printStatus("Login successfull...") return nil end -- --------------------------------------------------------------------------------------------------------------------- function ListAccounts(knownAccounts) local accountNumber = overview_html:xpath("//p[text()='Kundennummer:']/span"):text(); -- Supports only one account local account = { owner = overview_html:xpath("//*/p[@class='welcome-msg']/strong"):text(), name = "Paypack Punkte Konto (" .. accountNumber .. ")", accountNumber = accountNumber, portfolio = false, currency = "EUR", type = AccountTypeUnknown } return { account } end -- --------------------------------------------------------------------------------------------------------------------- function RefreshAccount(account, since) local transactions = {} -- the datefields can be filled directly overview_html:xpath("//input[@id='date1']"):attr("value", os.date("%d.%m.%Y", since)) overview_html:xpath("//input[@id='date2']"):attr("value", os.date("%d.%m.%Y")) MM.printStatus("Fill in date ranges" ) print("Submitting transaction search form for " .. account.accountNumber) -- local form = overview_html:xpath("//form[@id='pointRangeForm']") --overview_html = HTML(form):submit() -- MM.printStatus("Form for pointRangeForm: " .. deep_print(form)) -- local response = connection:request(overview_html:xpath("//input[@title='Anzeigen']"):click()) overview_html = HTML(connection:request(overview_html:xpath("//input[@title='Anzeigen']"):click())) -- Get paypack points from text next to select box local balance = overview_html:xpath("//span[@id='serverPoints']"):text() -- eleminate the dot in the point number and divide it with 100 to get the euro equivalent balance = string.gsub(balance,"%.","")/100 MM.printStatus("balance " .. balance) local firstPage =true; repeat local noMorePages = true; -- Check if the HTML table with transactions exists. if overview_html:xpath("//table[@class='mypoints']/tbody/tr[1]/td[1]"):length() > 0 then -- Extract transactions. overview_html:xpath("//table[@class='mypoints']/tbody/tr[position()>0]"):each(function (index, row) local columns = row:children() local transaction = { valueDate = strToFullDate(columns:get(1):text()), bookingDate = strToFullDate(columns:get(1):text()), name = columns:get(2):text(), purpose = columns:get(3):text() .. " : " .. columns:get(4):text(), true, currency = "EUR", amount = strToAmount(columns:get(4):text(), true)/100 } table.insert(transactions, transaction) end) local linkCounter if firstPage then linkCounter = 1 else linkCounter = 2 end local nextPageLink = overview_html:xpath("//div[@class='pager-list']/a[".. linkCounter .."]"); -- check website for more pages to extract transactions for if nextPageLink:length()> 0 then local link = overview_html:xpath("//div[@class='pager-list']/a[".. linkCounter .."]") overview_html = HTML(connection:request(overview_html:xpath("//div[@class='pager-list']/a[".. linkCounter .."]"):click())) noMorePages = false; firstPage=false; MM.printStatus("Getting more transactions...") end end until (noMorePages); -- Return balance and array of transactions. return {balance=balance, transactions=transactions, securities=nil} end -- --------------------------------------------------------------------------------------------------------------------- function EndSession() -- Submit logout form. local logout_html = HTML(connection:request(overview_html:xpath("//a[@id='pbLogin']"):click())) print("Logged out successfully!") end -- Print contents of `tbl`, with indentation. -- `indent` sets the initial level of indentation. function tprint (tbl, indent) if not indent then indent = 0 end for k, v in pairs(tbl) do formatting = string.rep(" ", indent) .. k .. ": " if type(v) == "table" then print(formatting) tprint(v, indent+1) elseif type(v) == 'boolean' then print(formatting .. tostring(v)) elseif type(v) == 'function' then print(formatting .. tostring(v)) elseif type(v) == 'userdata' then print(formatting .. tostring(v)) else print(formatting .. v) end end end
38.812121
138
0.524204
93f4a5c92b470c496e908831f3aeb861990d23a6
291
cs
C#
src/NadekoBot/Modules/Searches/Crypto/IStockDataService.cs
StefanPuia/nadeko
9fa0718b159dd230584f5ab4b2937ad0f1de0fec
[ "MIT" ]
null
null
null
src/NadekoBot/Modules/Searches/Crypto/IStockDataService.cs
StefanPuia/nadeko
9fa0718b159dd230584f5ab4b2937ad0f1de0fec
[ "MIT" ]
1
2022-03-29T05:36:35.000Z
2022-03-29T05:36:35.000Z
src/NadekoBot/Modules/Searches/Crypto/IStockDataService.cs
StefanPuia/nadeko
9fa0718b159dd230584f5ab4b2937ad0f1de0fec
[ "MIT" ]
null
null
null
namespace NadekoBot.Modules.Searches; public interface IStockDataService { public Task<StockData?> GetStockDataAsync(string symbol); Task<IReadOnlyCollection<SymbolData>> SearchSymbolAsync(string query); Task<IReadOnlyCollection<CandleData>> GetCandleDataAsync(string query); }
36.375
75
0.810997
8eaf245bbb2fb9296f8dc5df777e74109bd6205e
7,119
js
JavaScript
modules/components/Students/components/Student/index.js
hmltnbrn/library-check-out
f41e8d596cb4c4b5ced458cde52d19300b47b534
[ "MIT" ]
1
2016-12-07T22:53:02.000Z
2016-12-07T22:53:02.000Z
modules/components/Students/components/Student/index.js
hmltnbrn/library-check-out
f41e8d596cb4c4b5ced458cde52d19300b47b534
[ "MIT" ]
null
null
null
modules/components/Students/components/Student/index.js
hmltnbrn/library-check-out
f41e8d596cb4c4b5ced458cde52d19300b47b534
[ "MIT" ]
null
null
null
import React from 'react'; import {Link} from 'react-router'; import DocumentTitle from 'react-document-title'; import Paper from 'material-ui/Paper'; import {Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table'; import Divider from 'material-ui/Divider'; import moment from "moment"; import * as libraryService from './../../../../services/library-service'; class Student extends React.Component { constructor(props) { super(props); this.state = { student: {}, current_books: [], history_books: [] } } componentDidMount() { if (this.props.signedIn === true) { this.findStudents(); } else { this.props.setPageTitle("Student"); } } componentWillReceiveProps(nextProps) { if (this.props.signedIn === false && nextProps.signedIn === true) { this.findStudents(); } else if (this.props.signedIn === true && nextProps.signedIn === false) { this.props.setPageTitle("Student"); } } findStudents() { libraryService.findStudentHistoryById({studentId: this.props.params.studentId}) .then(data => { this.setState({ student: data.student[0], current_books: data.out_books, history_books: data.in_books }, this.setTitle); }); } setTitle() { let title = this.state.student !== undefined ? this.state.student.name + " " + this.state.student.class : 'Student'; this.props.setPageTitle(title); } render() { let listCurrentBooks = this.state.current_books.map(book => { let date_out = moment(book.date_out).format('dddd, MMMM D, YYYY'); return ( <TableRow key={book.id}> <TableRowColumn>{book.title}</TableRowColumn> <TableRowColumn>{book.level}</TableRowColumn> <TableRowColumn>{date_out}</TableRowColumn> </TableRow> ); }); let listHistoryBooks = this.state.history_books.map(book => { let date_out = moment(book.date_out).format('dddd, MMMM D, YYYY'); let date_in = moment(book.date_in).format('dddd, MMMM D, YYYY'); return ( <TableRow key={book.id}> <TableRowColumn>{book.title}</TableRowColumn> <TableRowColumn>{book.level}</TableRowColumn> <TableRowColumn>{date_out}</TableRowColumn> <TableRowColumn>{date_in}</TableRowColumn> </TableRow> ); }); if (this.props.signedIn === true) { return ( <DocumentTitle title={"Library | " + this.state.student.name}> <div className="students flex flex-column align-center"> <div className="student-active" style={this.state.student.active === true ? {color:'#2E7D32'} : {color:'#C62828'}}> {this.state.student.active === true ? "Active" : "Inactive"} </div> <Divider style={{width:'70%',marginBottom:18}}/> <Paper className="student-current-paper"> <Table style={{tableLayout:'auto'}} bodyStyle={{overflow:'auto'}} > <TableHeader displaySelectAll={false} adjustForCheckbox={false} > <TableRow> <TableHeaderColumn colSpan="7" style={{textAlign:'center',fontSize:18}} > Current Books </TableHeaderColumn> </TableRow> </TableHeader> <TableBody displayRowCheckbox={false} > <TableRow> <TableHeaderColumn>Book Title</TableHeaderColumn> <TableHeaderColumn>Level</TableHeaderColumn> <TableHeaderColumn>Date Checked Out</TableHeaderColumn> </TableRow> {listCurrentBooks} </TableBody> </Table> </Paper> <Paper className="student-history-paper"> <Table style={{tableLayout:'auto'}} bodyStyle={{overflow:'auto'}} > <TableHeader displaySelectAll={false} adjustForCheckbox={false} > <TableRow> <TableHeaderColumn colSpan="7" style={{textAlign:'center',fontSize:18}} > History </TableHeaderColumn> </TableRow> </TableHeader> <TableBody displayRowCheckbox={false} > <TableRow> <TableHeaderColumn>Book Title</TableHeaderColumn> <TableHeaderColumn>Level</TableHeaderColumn> <TableHeaderColumn>Date Checked Out</TableHeaderColumn> <TableHeaderColumn>Date Checked In</TableHeaderColumn> </TableRow> {listHistoryBooks} </TableBody> </Table> </Paper> </div> </DocumentTitle> ); } else { return ( <DocumentTitle title="Library | Student"> <div className="students flex flex-column align-center"> <p>Sign in to view this page.</p> </div> </DocumentTitle> ); } } }; export default Student;
42.12426
139
0.410029
dd76e34c2776b9a51ab9cc2f36d2fcd86ebf19ae
38,682
java
Java
itext/src/main/java/com/itextpdf/text/pdf/PdfStamper.java
tombueng/itextpdf
1ed117515691c37a12f790cfa0aa8e78b53e1916
[ "RSA-MD" ]
null
null
null
itext/src/main/java/com/itextpdf/text/pdf/PdfStamper.java
tombueng/itextpdf
1ed117515691c37a12f790cfa0aa8e78b53e1916
[ "RSA-MD" ]
null
null
null
itext/src/main/java/com/itextpdf/text/pdf/PdfStamper.java
tombueng/itextpdf
1ed117515691c37a12f790cfa0aa8e78b53e1916
[ "RSA-MD" ]
null
null
null
/* * * This file is part of the iText (R) project. * Copyright (c) 1998-2016 iText Group NV * Authors: Bruno Lowagie, Paulo Soares, et al. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation with the addition of the * following permission added to Section 15 as permitted in Section 7(a): * FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY * ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT * OF THIRD PARTY RIGHTS * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA, 02110-1301 USA, or download the license from the following URL: * http://itextpdf.com/terms-of-use/ * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License. * * In accordance with Section 7(b) of the GNU Affero General Public License, * a covered work must retain the producer line in every PDF that is created * or manipulated using iText. * * You can be released from the requirements of the license by purchasing * a commercial license. Buying such a license is mandatory as soon as you * develop commercial activities involving the iText software without * disclosing the source code of your own applications. * These activities include: offering paid services to customers as an ASP, * serving PDFs on the fly in a web application, shipping iText with a closed * source product. * * For more information, please contact iText Software Corp. at this * address: sales@itextpdf.com */ package com.itextpdf.text.pdf; import com.itextpdf.text.DocWriter; import com.itextpdf.text.DocumentException; import com.itextpdf.text.ExceptionConverter; import com.itextpdf.text.Image; import com.itextpdf.text.Rectangle; import com.itextpdf.text.error_messages.MessageLocalization; import com.itextpdf.text.pdf.collection.PdfCollection; import com.itextpdf.text.pdf.interfaces.PdfEncryptionSettings; import com.itextpdf.text.pdf.interfaces.PdfViewerPreferences; import com.itextpdf.text.pdf.security.LtvVerification; import com.itextpdf.text.xml.xmp.XmpWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.cert.Certificate; import java.util.HashMap; import java.util.List; import java.util.Map; /** Applies extra content to the pages of a PDF document. * This extra content can be all the objects allowed in PdfContentByte * including pages from other Pdfs. The original PDF will keep * all the interactive elements including bookmarks, links and form fields. * <p> * It is also possible to change the field values and to * flatten them. New fields can be added but not flattened. * @author Paulo Soares */ public class PdfStamper implements PdfViewerPreferences, PdfEncryptionSettings { /** * The writer */ protected PdfStamperImp stamper; private Map<String, String> moreInfo; protected boolean hasSignature; protected PdfSignatureAppearance sigApp; protected XmlSignatureAppearance sigXmlApp; private LtvVerification verification; /** Starts the process of adding extra content to an existing PDF * document. * <p> * The reader will be closed when this PdfStamper is closed * @param reader the original document. It cannot be reused * @param os the output stream * @throws DocumentException on error * @throws IOException on error */ public PdfStamper(final PdfReader reader, final OutputStream os) throws DocumentException, IOException { stamper = new PdfStamperImp(reader, os, '\0', false); } /** * Starts the process of adding extra content to an existing PDF * document. * <p> * The reader will be closed when this PdfStamper is closed * @param reader the original document. It cannot be reused * @param os the output stream * @param pdfVersion the new pdf version or '\0' to keep the same version as the original * document * @throws DocumentException on error * @throws IOException on error */ public PdfStamper(final PdfReader reader, final OutputStream os, final char pdfVersion) throws DocumentException, IOException { stamper = new PdfStamperImp(reader, os, pdfVersion, false); } /** * Starts the process of adding extra content to an existing PDF * document, possibly as a new revision. * <p> * The reader will be closed when this PdfStamper is closed * @param reader the original document. It cannot be reused * @param os the output stream * @param pdfVersion the new pdf version or '\0' to keep the same version as the original * document * @param append if <CODE>true</CODE> appends the document changes as a new revision. This is * only useful for multiple signatures as nothing is gained in speed or memory * @throws DocumentException on error * @throws IOException on error */ public PdfStamper(final PdfReader reader, final OutputStream os, final char pdfVersion, final boolean append) throws DocumentException, IOException { stamper = new PdfStamperImp(reader, os, pdfVersion, append); } /** Gets the optional <CODE>String</CODE> map to add or change values in * the info dictionary. * @return the map or <CODE>null</CODE> * */ public Map<String, String> getMoreInfo() { return this.moreInfo; } /** An optional <CODE>String</CODE> map to add or change values in * the info dictionary. Entries with <CODE>null</CODE> * values delete the key in the original info dictionary * @param moreInfo additional entries to the info dictionary * */ public void setMoreInfo(final Map<String, String> moreInfo) { this.moreInfo = moreInfo; } /** * Replaces a page from this document with a page from other document. Only the content * is replaced not the fields and annotations. This method must be called before * getOverContent() or getUndercontent() are called for the same page. * @param r the <CODE>PdfReader</CODE> from where the new page will be imported * @param pageImported the page number of the imported page * @param pageReplaced the page to replace in this document * @since iText 2.1.1 */ public void replacePage(final PdfReader r, final int pageImported, final int pageReplaced) { stamper.replacePage(r, pageImported, pageReplaced); } /** * Inserts a blank page. All the pages above and including <CODE>pageNumber</CODE> will * be shifted up. If <CODE>pageNumber</CODE> is bigger than the total number of pages * the new page will be the last one. * @param pageNumber the page number position where the new page will be inserted * @param mediabox the size of the new page */ public void insertPage(final int pageNumber, final Rectangle mediabox) { stamper.insertPage(pageNumber, mediabox); } /** * Gets the signing instance. The appearances and other parameters can the be set. * @return the signing instance */ public PdfSignatureAppearance getSignatureAppearance() { return sigApp; } /** * Gets the xml signing instance. The appearances and other parameters can the be set. * @return the xml signing instance */ public XmlSignatureAppearance getXmlSignatureAppearance() { return sigXmlApp; } /** * Causes any pending changes to the direct under/over content (e.g. stamps) and page replacements to be applied to the output PDF. References to the adjusted content * are released. If very large numbers of pages are being modified, call this method periodically to write the changes to * the output PDF file and release the stamps from the heap. * * A few precautions about using this method: * * 1) After using flush() method, over/under content objects should be updated via getOverContent() or getUnderContent() calls respectively in case you want to make any further stamps to the same page; * 2) PdfReader, that is associated with PdfStamper which is flushed, must not be used for any other purposes. This is due to the fact that after flush some new references in PdfReader's inner structure appear, but you won't be able to get actual objects behind those references. * */ public void flush(){ try{ stamper.alterContents(); stamper.pagesToContent.clear(); } catch (IOException e){ throw new ExceptionConverter(e); } } /** * Closes the document. No more content can be written after the * document is closed. * <p> * If closing a signed document with an external signature the closing must be done * in the <CODE>PdfSignatureAppearance</CODE> instance. * @throws DocumentException on error * @throws IOException on error */ public void close() throws DocumentException, IOException { if (stamper.closed) return; if (!hasSignature) { mergeVerification(); stamper.close(moreInfo); } else { throw new DocumentException("Signature defined. Must be closed in PdfSignatureAppearance."); } } /** Gets a <CODE>PdfContentByte</CODE> to write under the page of * the original document. * @param pageNum the page number where the extra content is written * @return a <CODE>PdfContentByte</CODE> to write under the page of * the original document */ public PdfContentByte getUnderContent(final int pageNum) { return stamper.getUnderContent(pageNum); } /** Gets a <CODE>PdfContentByte</CODE> to write over the page of * the original document. * @param pageNum the page number where the extra content is written * @return a <CODE>PdfContentByte</CODE> to write over the page of * the original document */ public PdfContentByte getOverContent(final int pageNum) { return stamper.getOverContent(pageNum); } /** Checks if the content is automatically adjusted to compensate * the original page rotation. * @return the auto-rotation status */ public boolean isRotateContents() { return stamper.isRotateContents(); } /** Flags the content to be automatically adjusted to compensate * the original page rotation. The default is <CODE>true</CODE>. * @param rotateContents <CODE>true</CODE> to set auto-rotation, <CODE>false</CODE> * otherwise */ public void setRotateContents(final boolean rotateContents) { stamper.setRotateContents(rotateContents); } /** Sets the encryption options for this document. The userPassword and the * ownerPassword can be null or have zero length. In this case the ownerPassword * is replaced by a random string. The open permissions for the document can be * AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations, * AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting. * The permissions can be combined by ORing them. * @param userPassword the user password. Can be null or empty * @param ownerPassword the owner password. Can be null or empty * @param permissions the user permissions * @param strength128Bits <code>true</code> for 128 bit key length, <code>false</code> for 40 bit key length * @throws DocumentException if anything was already written to the output */ public void setEncryption(final byte userPassword[], final byte ownerPassword[], final int permissions, final boolean strength128Bits) throws DocumentException { if (stamper.isAppend()) throw new DocumentException(MessageLocalization.getComposedMessage("append.mode.does.not.support.changing.the.encryption.status")); if (stamper.isContentWritten()) throw new DocumentException(MessageLocalization.getComposedMessage("content.was.already.written.to.the.output")); stamper.setEncryption(userPassword, ownerPassword, permissions, strength128Bits ? PdfWriter.STANDARD_ENCRYPTION_128 : PdfWriter.STANDARD_ENCRYPTION_40); } /** Sets the encryption options for this document. The userPassword and the * ownerPassword can be null or have zero length. In this case the ownerPassword * is replaced by a random string. The open permissions for the document can be * AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations, * AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting. * The permissions can be combined by ORing them. * @param userPassword the user password. Can be null or empty * @param ownerPassword the owner password. Can be null or empty * @param permissions the user permissions * @param encryptionType the type of encryption. It can be one of STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128. * Optionally DO_NOT_ENCRYPT_METADATA can be ored to output the metadata in cleartext * @throws DocumentException if the document is already open */ public void setEncryption(final byte userPassword[], final byte ownerPassword[], final int permissions, final int encryptionType) throws DocumentException { if (stamper.isAppend()) throw new DocumentException(MessageLocalization.getComposedMessage("append.mode.does.not.support.changing.the.encryption.status")); if (stamper.isContentWritten()) throw new DocumentException(MessageLocalization.getComposedMessage("content.was.already.written.to.the.output")); stamper.setEncryption(userPassword, ownerPassword, permissions, encryptionType); } /** * Sets the encryption options for this document. The userPassword and the * ownerPassword can be null or have zero length. In this case the ownerPassword * is replaced by a random string. The open permissions for the document can be * AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations, * AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting. * The permissions can be combined by ORing them. * @param strength <code>true</code> for 128 bit key length, <code>false</code> for 40 bit key length * @param userPassword the user password. Can be null or empty * @param ownerPassword the owner password. Can be null or empty * @param permissions the user permissions * @throws DocumentException if anything was already written to the output */ public void setEncryption(final boolean strength, final String userPassword, final String ownerPassword, final int permissions) throws DocumentException { setEncryption(DocWriter.getISOBytes(userPassword), DocWriter.getISOBytes(ownerPassword), permissions, strength); } /** * Sets the encryption options for this document. The userPassword and the * ownerPassword can be null or have zero length. In this case the ownerPassword * is replaced by a random string. The open permissions for the document can be * AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations, * AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting. * The permissions can be combined by ORing them. * @param encryptionType the type of encryption. It can be one of STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128. * Optionally DO_NOT_ENCRYPT_METADATA can be ored to output the metadata in cleartext * @param userPassword the user password. Can be null or empty * @param ownerPassword the owner password. Can be null or empty * @param permissions the user permissions * @throws DocumentException if anything was already written to the output */ public void setEncryption(final int encryptionType, final String userPassword, final String ownerPassword, final int permissions) throws DocumentException { setEncryption(DocWriter.getISOBytes(userPassword), DocWriter.getISOBytes(ownerPassword), permissions, encryptionType); } /** * Sets the certificate encryption options for this document. An array of one or more public certificates * must be provided together with an array of the same size for the permissions for each certificate. * The open permissions for the document can be * AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations, * AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting. * The permissions can be combined by ORing them. * Optionally DO_NOT_ENCRYPT_METADATA can be ored to output the metadata in cleartext * @param certs the public certificates to be used for the encryption * @param permissions the user permissions for each of the certificates * @param encryptionType the type of encryption. It can be one of STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128. * @throws DocumentException if the encryption was set too late */ public void setEncryption(final Certificate[] certs, final int[] permissions, final int encryptionType) throws DocumentException { if (stamper.isAppend()) throw new DocumentException(MessageLocalization.getComposedMessage("append.mode.does.not.support.changing.the.encryption.status")); if (stamper.isContentWritten()) throw new DocumentException(MessageLocalization.getComposedMessage("content.was.already.written.to.the.output")); stamper.setEncryption(certs, permissions, encryptionType); } /** Gets a page from other PDF document. Note that calling this method more than * once with the same parameters will retrieve the same object. * @param reader the PDF document where the page is * @param pageNumber the page number. The first page is 1 * @return the template representing the imported page */ public PdfImportedPage getImportedPage(final PdfReader reader, final int pageNumber) { return stamper.getImportedPage(reader, pageNumber); } /** Gets the underlying PdfWriter. * @return the underlying PdfWriter */ public PdfWriter getWriter() { return stamper; } /** Gets the underlying PdfReader. * @return the underlying PdfReader */ public PdfReader getReader() { return stamper.reader; } /** Gets the <CODE>AcroFields</CODE> object that allows to get and set field values * and to merge FDF forms. * @return the <CODE>AcroFields</CODE> object */ public AcroFields getAcroFields() { return stamper.getAcroFields(); } /** Determines if the fields are flattened on close. The fields added with * {@link #addAnnotation(PdfAnnotation,int)} will never be flattened. * @param flat <CODE>true</CODE> to flatten the fields, <CODE>false</CODE> * to keep the fields */ public void setFormFlattening(final boolean flat) { stamper.setFormFlattening(flat); } /** Determines if the FreeText annotations are flattened on close. * @param flat <CODE>true</CODE> to flatten the FreeText annotations, <CODE>false</CODE> * (the default) to keep the FreeText annotations as active content. */ public void setFreeTextFlattening(final boolean flat) { stamper.setFreeTextFlattening(flat); } /** * Flatten annotations with an appearance stream on close(). * * @param flat boolean to indicate whether iText should flatten annotations or not. */ public void setAnnotationFlattening(final boolean flat) { stamper.setFlatAnnotations(flat); } /** * Adds an annotation of form field in a specific page. This page number * can be overridden with {@link PdfAnnotation#setPlaceInPage(int)}. * @param annot the annotation * @param page the page */ public void addAnnotation(final PdfAnnotation annot, final int page) { stamper.addAnnotation(annot, page); } /** * Adds an empty signature. * @param name the name of the signature * @param page the page number * @param llx lower left x coordinate of the signature's position * @param lly lower left y coordinate of the signature's position * @param urx upper right x coordinate of the signature's position * @param ury upper right y coordinate of the signature's position * @return a signature form field * @since 2.1.4 */ public PdfFormField addSignature(final String name, final int page, final float llx, final float lly, final float urx, final float ury) { PdfAcroForm acroForm = stamper.getAcroForm(); PdfFormField signature = PdfFormField.createSignature(stamper); acroForm.setSignatureParams(signature, name, llx, lly, urx, ury); acroForm.drawSignatureAppearences(signature, llx, lly, urx, ury); addAnnotation(signature, page); return signature; } /** * Adds the comments present in an FDF file. * @param fdf the FDF file * @throws IOException on error */ public void addComments(final FdfReader fdf) throws IOException { stamper.addComments(fdf); } /** * Sets the bookmarks. The list structure is defined in * {@link SimpleBookmark}. * @param outlines the bookmarks or <CODE>null</CODE> to remove any */ public void setOutlines(final List<HashMap<String, Object>> outlines) { stamper.setOutlines(outlines); } /** * Sets the thumbnail image for a page. * @param image the image * @param page the page * @throws PdfException on error * @throws DocumentException on error */ public void setThumbnail(final Image image, final int page) throws PdfException, DocumentException { stamper.setThumbnail(image, page); } /** * Adds <CODE>name</CODE> to the list of fields that will be flattened on close, * all the other fields will remain. If this method is never called or is called * with invalid field names, all the fields will be flattened. * <p> * Calling <CODE>setFormFlattening(true)</CODE> is needed to have any kind of * flattening. * @param name the field name * @return <CODE>true</CODE> if the field exists, <CODE>false</CODE> otherwise */ public boolean partialFormFlattening(final String name) { return stamper.partialFormFlattening(name); } /** Adds a JavaScript action at the document level. When the document * opens all this JavaScript runs. The existing JavaScript will be replaced. * @param js the JavaScript code */ public void addJavaScript(final String js) { stamper.addJavaScript(js, !PdfEncodings.isPdfDocEncoding(js)); } /** Adds a JavaScript action at the document level. When the document * opens all this JavaScript runs. The existing JavaScript will be replaced. * @param name the name for the JavaScript snippet in the name tree * @param js the JavaScript code */ public void addJavaScript(final String name, final String js) { stamper.addJavaScript(name, PdfAction.javaScript(js, stamper, !PdfEncodings.isPdfDocEncoding(js))); } /** Adds a file attachment at the document level. Existing attachments will be kept. * @param description the file description * @param fileStore an array with the file. If it's <CODE>null</CODE> * the file will be read from the disk * @param file the path to the file. It will only be used if * <CODE>fileStore</CODE> is not <CODE>null</CODE> * @param fileDisplay the actual file name stored in the pdf * @throws IOException on error */ public void addFileAttachment(final String description, final byte fileStore[], final String file, final String fileDisplay) throws IOException { addFileAttachment(description, PdfFileSpecification.fileEmbedded(stamper, file, fileDisplay, fileStore)); } /** Adds a file attachment at the document level. Existing attachments will be kept. * @param description the file description * @param fs the file specification * @throws IOException */ public void addFileAttachment(final String description, final PdfFileSpecification fs) throws IOException { stamper.addFileAttachment(description, fs); } /** * This is the most simple way to change a PDF into a * portable collection. Choose one of the following names: * <ul> * <li>PdfName.D (detailed view) * <li>PdfName.T (tiled view) * <li>PdfName.H (hidden) * </ul> * Pass this name as a parameter and your PDF will be * a portable collection with all the embedded and * attached files as entries. * @param initialView can be PdfName.D, PdfName.T or PdfName.H */ public void makePackage( final PdfName initialView ) { PdfCollection collection = new PdfCollection(0); collection.put(PdfName.VIEW, initialView); stamper.makePackage( collection ); } /** * Adds or replaces the Collection Dictionary in the Catalog. * @param collection the new collection dictionary. */ public void makePackage(final PdfCollection collection) { stamper.makePackage(collection); } /** * Sets the viewer preferences. * @param preferences the viewer preferences * @see PdfViewerPreferences#setViewerPreferences(int) */ public void setViewerPreferences(final int preferences) { stamper.setViewerPreferences(preferences); } /** Adds a viewer preference * @param key a key for a viewer preference * @param value the value for the viewer preference * @see PdfViewerPreferences#addViewerPreference */ public void addViewerPreference(final PdfName key, final PdfObject value) { stamper.addViewerPreference(key, value); } /** * Sets the XMP metadata. * @param xmp * @see PdfWriter#setXmpMetadata(byte[]) */ public void setXmpMetadata(final byte[] xmp) { stamper.setXmpMetadata(xmp); } public void createXmpMetadata() { stamper.createXmpMetadata(); } public XmpWriter getXmpWriter() { return stamper.getXmpWriter(); } /** * Gets the 1.5 compression status. * @return <code>true</code> if the 1.5 compression is on */ public boolean isFullCompression() { return stamper.isFullCompression(); } /** * Sets the document's compression to the new 1.5 mode with object streams and xref * streams. Be attentive!!! If you want set full compression , you should set immediately after creating PdfStamper, * before editing the document.It can be set once and it can't be unset. */ public void setFullCompression() throws DocumentException { if (stamper.isAppend()) return; stamper.fullCompression = true; stamper.setAtLeastPdfVersion(PdfWriter.VERSION_1_5); } /** * Sets the open and close page additional action. * @param actionType the action type. It can be <CODE>PdfWriter.PAGE_OPEN</CODE> * or <CODE>PdfWriter.PAGE_CLOSE</CODE> * @param action the action to perform * @param page the page where the action will be applied. The first page is 1 * @throws PdfException if the action type is invalid */ public void setPageAction(final PdfName actionType, final PdfAction action, final int page) throws PdfException { stamper.setPageAction(actionType, action, page); } /** * Sets the display duration for the page (for presentations) * @param seconds the number of seconds to display the page. A negative value removes the entry * @param page the page where the duration will be applied. The first page is 1 */ public void setDuration(final int seconds, final int page) { stamper.setDuration(seconds, page); } /** * Sets the transition for the page * @param transition the transition object. A <code>null</code> removes the transition * @param page the page where the transition will be applied. The first page is 1 */ public void setTransition(final PdfTransition transition, final int page) { stamper.setTransition(transition, page); } /** * Applies a digital signature to a document, possibly as a new revision, making * possible multiple signatures. The returned PdfStamper * can be used normally as the signature is only applied when closing. * <p> * A possible use for adding a signature without invalidating an existing one is: * <p> * <pre> * KeyStore ks = KeyStore.getInstance("pkcs12"); * ks.load(new FileInputStream("my_private_key.pfx"), "my_password".toCharArray()); * String alias = (String)ks.aliases().nextElement(); * PrivateKey key = (PrivateKey)ks.getKey(alias, "my_password".toCharArray()); * Certificate[] chain = ks.getCertificateChain(alias); * PdfReader reader = new PdfReader("original.pdf"); * FileOutputStream fout = new FileOutputStream("signed.pdf"); * PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0', new * File("/temp"), true); * PdfSignatureAppearance sap = stp.getSignatureAppearance(); * sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); * sap.setReason("I'm the author"); * sap.setLocation("Lisbon"); * // comment next line to have an invisible signature * sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null); * stp.close(); * </pre> * @param reader the original document * @param os the output stream or <CODE>null</CODE> to keep the document in the temporary file * @param pdfVersion the new pdf version or '\0' to keep the same version as the original * document * @param tempFile location of the temporary file. If it's a directory a temporary file will be created there. * If it's a file it will be used directly. The file will be deleted on exit unless <CODE>os</CODE> is null. * In that case the document can be retrieved directly from the temporary file. If it's <CODE>null</CODE> * no temporary file will be created and memory will be used * @param append if <CODE>true</CODE> the signature and all the other content will be added as a * new revision thus not invalidating existing signatures * @return a <CODE>PdfStamper</CODE> * @throws DocumentException on error * @throws IOException on error */ public static PdfStamper createSignature(final PdfReader reader, final OutputStream os, final char pdfVersion, File tempFile, final boolean append) throws DocumentException, IOException { PdfStamper stp; if (tempFile == null) { ByteBuffer bout = new ByteBuffer(); stp = new PdfStamper(reader, bout, pdfVersion, append); stp.sigApp = new PdfSignatureAppearance(stp.stamper); stp.sigApp.setSigout(bout); } else { if (tempFile.isDirectory()) tempFile = File.createTempFile("pdf", ".pdf", tempFile); FileOutputStream fout = new FileOutputStream(tempFile); stp = new PdfStamper(reader, fout, pdfVersion, append); stp.sigApp = new PdfSignatureAppearance(stp.stamper); stp.sigApp.setTempFile(tempFile); } stp.sigApp.setOriginalout(os); stp.sigApp.setStamper(stp); stp.hasSignature = true; PdfDictionary catalog = reader.getCatalog(); PdfDictionary acroForm = (PdfDictionary)PdfReader.getPdfObject(catalog.get(PdfName.ACROFORM), catalog); if (acroForm != null) { acroForm.remove(PdfName.NEEDAPPEARANCES); stp.stamper.markUsed(acroForm); } return stp; } /** * Applies a digital signature to a document. The returned PdfStamper * can be used normally as the signature is only applied when closing. * <p> * Note that the pdf is created in memory. * <p> * A possible use is: * <p> * <pre> * KeyStore ks = KeyStore.getInstance("pkcs12"); * ks.load(new FileInputStream("my_private_key.pfx"), "my_password".toCharArray()); * String alias = (String)ks.aliases().nextElement(); * PrivateKey key = (PrivateKey)ks.getKey(alias, "my_password".toCharArray()); * Certificate[] chain = ks.getCertificateChain(alias); * PdfReader reader = new PdfReader("original.pdf"); * FileOutputStream fout = new FileOutputStream("signed.pdf"); * PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0'); * PdfSignatureAppearance sap = stp.getSignatureAppearance(); * sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); * sap.setReason("I'm the author"); * sap.setLocation("Lisbon"); * // comment next line to have an invisible signature * sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null); * stp.close(); * </pre> * @param reader the original document * @param os the output stream * @param pdfVersion the new pdf version or '\0' to keep the same version as the original * document * @throws DocumentException on error * @throws IOException on error * @return a <CODE>PdfStamper</CODE> */ public static PdfStamper createSignature(final PdfReader reader, final OutputStream os, final char pdfVersion) throws DocumentException, IOException { return createSignature(reader, os, pdfVersion, null, false); } /** * Applies a digital signature to a document. The returned PdfStamper * can be used normally as the signature is only applied when closing. * <p> * A possible use is: * <p> * <pre> * KeyStore ks = KeyStore.getInstance("pkcs12"); * ks.load(new FileInputStream("my_private_key.pfx"), "my_password".toCharArray()); * String alias = (String)ks.aliases().nextElement(); * PrivateKey key = (PrivateKey)ks.getKey(alias, "my_password".toCharArray()); * Certificate[] chain = ks.getCertificateChain(alias); * PdfReader reader = new PdfReader("original.pdf"); * FileOutputStream fout = new FileOutputStream("signed.pdf"); * PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0', new File("/temp")); * PdfSignatureAppearance sap = stp.getSignatureAppearance(); * sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); * sap.setReason("I'm the author"); * sap.setLocation("Lisbon"); * // comment next line to have an invisible signature * sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null); * stp.close(); * </pre> * @param reader the original document * @param os the output stream or <CODE>null</CODE> to keep the document in the temporary file * @param pdfVersion the new pdf version or '\0' to keep the same version as the original * document * @param tempFile location of the temporary file. If it's a directory a temporary file will be created there. * If it's a file it will be used directly. The file will be deleted on exit unless <CODE>os</CODE> is null. * In that case the document can be retrieved directly from the temporary file. If it's <CODE>null</CODE> * no temporary file will be created and memory will be used * @return a <CODE>PdfStamper</CODE> * @throws DocumentException on error * @throws IOException on error */ public static PdfStamper createSignature(final PdfReader reader, final OutputStream os, final char pdfVersion, final File tempFile) throws DocumentException, IOException { return createSignature(reader, os, pdfVersion, tempFile, false); } public static PdfStamper createXmlSignature(final PdfReader reader, final OutputStream os) throws IOException, DocumentException { PdfStamper stp = new PdfStamper(reader, os); stp.sigXmlApp = new XmlSignatureAppearance(stp.stamper); //stp.sigApp.setSigout(bout); //stp.sigApp.setOriginalout(os); stp.sigXmlApp.setStamper(stp); return stp; } /** * Gets the PdfLayer objects in an existing document as a Map * with the names/titles of the layers as keys. * @return a Map with all the PdfLayers in the document (and the name/title of the layer as key) * @since 2.1.2 */ public Map<String, PdfLayer> getPdfLayers() { return stamper.getPdfLayers(); } /** * Marks the specified object as used or changed. Used objects will be written to a new revision when using PdfStamper * in append mode. The specified PdfObject needs to be an Indirect Reference or its getIndRef() method should not * return null. * * @param obj the used PDF object */ public void markUsed(PdfObject obj) { stamper.markUsed(obj); } public LtvVerification getLtvVerification() { if (verification == null) verification = new LtvVerification(this); return verification; } public boolean addNamedDestination(final String name, final int page, final PdfDestination dest) throws IOException { HashMap<Object, PdfObject> namedDestinations = stamper.getNamedDestinations(); if (getReader().getNamedDestination().containsKey(name)){ return false; } PdfDestination d = new PdfDestination(dest); d.addPage(getReader().getPageOrigRef(page)); namedDestinations.put(name, new PdfArray(d)); return true; } void mergeVerification() throws IOException { if (verification == null) return; verification.merge(); } protected PdfStamper() { } }
45.189252
280
0.697379
a37f0be5deb12c4360a1ef55a56154d88adfc870
6,392
java
Java
src/gen/java/fakekube/io/model/IoK8sApiAutoscalingV2beta2HPAScalingRules.java
ahadas/fakekube
0848aca921b0baa4678ea283ee1f744a72c2599c
[ "Apache-2.0" ]
4
2020-02-18T13:16:45.000Z
2020-02-27T11:16:49.000Z
src/gen/java/fakekube/io/model/IoK8sApiAutoscalingV2beta2HPAScalingRules.java
ahadas/fakekube
0848aca921b0baa4678ea283ee1f744a72c2599c
[ "Apache-2.0" ]
4
2020-03-25T09:22:12.000Z
2021-06-10T15:03:25.000Z
src/gen/java/fakekube/io/model/IoK8sApiAutoscalingV2beta2HPAScalingRules.java
ahadas/fakekube
0848aca921b0baa4678ea283ee1f744a72c2599c
[ "Apache-2.0" ]
2
2020-01-19T08:20:36.000Z
2020-03-04T13:40:39.000Z
package fakekube.io.model; import fakekube.io.model.IoK8sApiAutoscalingV2beta2HPAScalingPolicy; import io.swagger.annotations.ApiModel; import java.util.ArrayList; import java.util.List; import javax.validation.constraints.*; import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import com.fasterxml.jackson.annotation.JsonProperty; /** * HPAScalingRules configures the scaling behavior for one direction. These Rules are applied after calculating DesiredReplicas from metrics for the HPA. They can limit the scaling velocity by specifying scaling policies. They can prevent flapping by specifying the stabilization window, so that the number of replicas is not set instantly, instead, the safest value from the stabilization window is chosen. **/ @ApiModel(description="HPAScalingRules configures the scaling behavior for one direction. These Rules are applied after calculating DesiredReplicas from metrics for the HPA. They can limit the scaling velocity by specifying scaling policies. They can prevent flapping by specifying the stabilization window, so that the number of replicas is not set instantly, instead, the safest value from the stabilization window is chosen.") public class IoK8sApiAutoscalingV2beta2HPAScalingRules { @ApiModelProperty(value = "policies is a list of potential scaling polices which can be used during scaling. At least one policy must be specified, otherwise the HPAScalingRules will be discarded as invalid") @Valid /** * policies is a list of potential scaling polices which can be used during scaling. At least one policy must be specified, otherwise the HPAScalingRules will be discarded as invalid **/ private List<IoK8sApiAutoscalingV2beta2HPAScalingPolicy> policies = null; @ApiModelProperty(value = "selectPolicy is used to specify which policy should be used. If not set, the default value MaxPolicySelect is used.") /** * selectPolicy is used to specify which policy should be used. If not set, the default value MaxPolicySelect is used. **/ private String selectPolicy = null; @ApiModelProperty(value = "StabilizationWindowSeconds is the number of seconds for which past recommendations should be considered while scaling up or scaling down. StabilizationWindowSeconds must be greater than or equal to zero and less than or equal to 3600 (one hour). If not set, use the default values: - For scale up: 0 (i.e. no stabilization is done). - For scale down: 300 (i.e. the stabilization window is 300 seconds long).") /** * StabilizationWindowSeconds is the number of seconds for which past recommendations should be considered while scaling up or scaling down. StabilizationWindowSeconds must be greater than or equal to zero and less than or equal to 3600 (one hour). If not set, use the default values: - For scale up: 0 (i.e. no stabilization is done). - For scale down: 300 (i.e. the stabilization window is 300 seconds long). **/ private Integer stabilizationWindowSeconds = null; /** * policies is a list of potential scaling polices which can be used during scaling. At least one policy must be specified, otherwise the HPAScalingRules will be discarded as invalid * @return policies **/ @JsonProperty("policies") public List<IoK8sApiAutoscalingV2beta2HPAScalingPolicy> getPolicies() { return policies; } public void setPolicies(List<IoK8sApiAutoscalingV2beta2HPAScalingPolicy> policies) { this.policies = policies; } public IoK8sApiAutoscalingV2beta2HPAScalingRules policies(List<IoK8sApiAutoscalingV2beta2HPAScalingPolicy> policies) { this.policies = policies; return this; } public IoK8sApiAutoscalingV2beta2HPAScalingRules addPoliciesItem(IoK8sApiAutoscalingV2beta2HPAScalingPolicy policiesItem) { this.policies.add(policiesItem); return this; } /** * selectPolicy is used to specify which policy should be used. If not set, the default value MaxPolicySelect is used. * @return selectPolicy **/ @JsonProperty("selectPolicy") public String getSelectPolicy() { return selectPolicy; } public void setSelectPolicy(String selectPolicy) { this.selectPolicy = selectPolicy; } public IoK8sApiAutoscalingV2beta2HPAScalingRules selectPolicy(String selectPolicy) { this.selectPolicy = selectPolicy; return this; } /** * StabilizationWindowSeconds is the number of seconds for which past recommendations should be considered while scaling up or scaling down. StabilizationWindowSeconds must be greater than or equal to zero and less than or equal to 3600 (one hour). If not set, use the default values: - For scale up: 0 (i.e. no stabilization is done). - For scale down: 300 (i.e. the stabilization window is 300 seconds long). * @return stabilizationWindowSeconds **/ @JsonProperty("stabilizationWindowSeconds") public Integer getStabilizationWindowSeconds() { return stabilizationWindowSeconds; } public void setStabilizationWindowSeconds(Integer stabilizationWindowSeconds) { this.stabilizationWindowSeconds = stabilizationWindowSeconds; } public IoK8sApiAutoscalingV2beta2HPAScalingRules stabilizationWindowSeconds(Integer stabilizationWindowSeconds) { this.stabilizationWindowSeconds = stabilizationWindowSeconds; return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class IoK8sApiAutoscalingV2beta2HPAScalingRules {\n"); sb.append(" policies: ").append(toIndentedString(policies)).append("\n"); sb.append(" selectPolicy: ").append(toIndentedString(selectPolicy)).append("\n"); sb.append(" stabilizationWindowSeconds: ").append(toIndentedString(stabilizationWindowSeconds)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private static String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
49.9375
438
0.774562
2f5fe8a50067a04a1cdd9e6415c91b2417a0ac69
627
dart
Dart
example/lib/src/widgets.dart
EstefaniaRealcore/flutter_reactive_ble
ea29bd23152c4257294bb9e468950247cf98a63f
[ "BSD-3-Clause" ]
1
2021-09-03T09:29:31.000Z
2021-09-03T09:29:31.000Z
example/lib/src/widgets.dart
jonahwilliams/flutter_reactive_ble
6e0597449a7faf49f97548832a5fbb33b6ddb9ce
[ "BSD-3-Clause" ]
null
null
null
example/lib/src/widgets.dart
jonahwilliams/flutter_reactive_ble
6e0597449a7faf49f97548832a5fbb33b6ddb9ce
[ "BSD-3-Clause" ]
2
2021-11-18T09:23:12.000Z
2021-11-18T09:56:10.000Z
import 'package:flutter/material.dart'; class BluetoothIcon extends StatelessWidget { const BluetoothIcon(); @override Widget build(BuildContext context) => const SizedBox( width: 64, height: 64, child: Align(alignment: Alignment.center, child: Icon(Icons.bluetooth)), ); } class StatusMessage extends StatelessWidget { const StatusMessage(this.text); final String text; @override Widget build(BuildContext context) => Padding( padding: const EdgeInsets.symmetric(vertical: 20), child: Text(text, style: const TextStyle(fontWeight: FontWeight.bold)), ); }
25.08
80
0.695375
b286a8d2d3e93fb28cc338819644b856920fda22
159
css
CSS
src/components/Pages/TemplatePage/TemplatePage.css
St3ve89/teambuild-front
29e55ec1914cabbf839739c6fd9f3bd090c1d0fb
[ "MIT" ]
1
2019-05-22T03:45:10.000Z
2019-05-22T03:45:10.000Z
src/components/Pages/TemplatePage/TemplatePage.css
St3ve89/teambuild-front
29e55ec1914cabbf839739c6fd9f3bd090c1d0fb
[ "MIT" ]
10
2020-09-05T02:39:52.000Z
2022-02-26T12:19:06.000Z
src/components/Pages/TemplatePage/TemplatePage.css
St3ve89/teambuild-front
29e55ec1914cabbf839739c6fd9f3bd090c1d0fb
[ "MIT" ]
null
null
null
.background { position: relative; } .content-box { position: absolute; z-index: 5; top: 100px; width: 100%; } /* Write your code below */
13.25
27
0.584906
e297fa0b7b6a69ae5298140f59213c322070f9e7
4,784
py
Python
segreg/model/alt/tests/test_one_bkpt_segreg_alt.py
stevelill/segreg
71e213d8f36b7bf28d1975bd17b59f61d9dba174
[ "BSD-3-Clause" ]
null
null
null
segreg/model/alt/tests/test_one_bkpt_segreg_alt.py
stevelill/segreg
71e213d8f36b7bf28d1975bd17b59f61d9dba174
[ "BSD-3-Clause" ]
null
null
null
segreg/model/alt/tests/test_one_bkpt_segreg_alt.py
stevelill/segreg
71e213d8f36b7bf28d1975bd17b59f61d9dba174
[ "BSD-3-Clause" ]
null
null
null
""" Testing alternative one-bkpt segreg. """ # Author: Steven Lillywhite # License: BSD 3 clause import unittest import numpy.testing from segreg import data from segreg.model import one_bkpt_segreg from segreg.model import segreg_util from segreg.model.alt import one_bkpt_segreg_alt from segreg.model.alt import regression_alt from segreg.data import _testing_util class TestOneBkptSegregAlt(unittest.TestCase): def setUp(self): num_data = 100 x_min = 0 x_max = 100 u = 50 v = 10 m1 = -0.05 m2 = 0.4 func = segreg_util.one_bkpt_segmented_func(u, v, m1, m2) stddev = 2.0 seed = 123456789 #seed = None self._indep, self._dep = _testing_util.generate_fake_data_normal_errors(num_data, x_min, x_max, func, stddev, seed=seed) def test_one_fixed_bkpt_tieout(self): """ Tie out new cython one bkpt regression with previous all-python regression_util. """ index = 7 ols_data1 = regression_alt.ols_terms( self._indep[0:index], self._dep[0:index]) ols_data2 = regression_alt.ols_terms( self._indep[index:], self._dep[index:]) # TODO: double check that cases where bkpt equals data point are ok # consider bkpt to be on left, right, or middle u1 = self._indep[index - 1] u2 = self._indep[index] u3 = 0.5 * (u1 + u2) tol = 1.0e-11 for u in [u1, u2, u3]: v, m1, m2, rss = one_bkpt_segreg.fixed_bkpt_least_squares(ols_data1, ols_data2, u) a_v, a_m1, a_m2, a_rss = one_bkpt_segreg_alt._fixed_bkpt_ls_impl(ols_data1, ols_data2, u) self.assertAlmostEqual(v, a_v, delta=tol) self.assertAlmostEqual(m1, a_m1, delta=tol) self.assertAlmostEqual(m2, a_m2, delta=tol) self.assertAlmostEqual(rss, a_rss, delta=tol) b_v, b_m1, b_m2 = one_bkpt_segreg_alt.fixed_bkpt_ls_regression(self._indep, self._dep, u) self.assertAlmostEqual(v, b_v, delta=tol) self.assertAlmostEqual(m1, b_m1, delta=tol) self.assertAlmostEqual(m2, b_m2, delta=tol) c_v, c_m1, c_m2, c_rss = one_bkpt_segreg_alt.fixed_bkpt_ls(self._indep, self._dep, u) self.assertAlmostEqual(v, c_v, delta=tol) self.assertAlmostEqual(m1, c_m1, delta=tol) self.assertAlmostEqual(m2, c_m2, delta=tol) self.assertAlmostEqual(rss, c_rss, delta=tol) def test_one_bkpt_estimation_tie_out(self): tol = 1.0e-8 (est_params, est_value) = one_bkpt_segreg_alt.estimate_one_bkpt_segreg_basic(self._indep, self._dep) (est_params2, est_value2) = one_bkpt_segreg_alt.estimate_one_bkpt_segreg(self._indep, self._dep) numpy.testing.assert_allclose(est_params, est_params2) self.assertAlmostEqual(est_value, est_value2, delta=tol) (est_params3, est_value3) = one_bkpt_segreg.estimate_one_bkpt_segreg(self._indep, self._dep) numpy.testing.assert_allclose(est_params2, est_params3) self.assertAlmostEqual(est_value2, est_value3, delta=tol) def test_rss_for_region(self): indep, dep = data.test1() ols_data = regression_alt.ols_terms(indep, dep) num_data, sum_x, sum_y, sum_xx, sum_yy, sum_xy = ols_data u = 20.0 v = 8.0 m = 0.02 term = v - m * u expected = (sum_yy - 2.0 * term * sum_y - 2.0 * m * sum_xy + m * m * sum_xx + 2.0 * m * term * sum_x + term * term * num_data) computed = one_bkpt_segreg_alt.rss_for_region(ols_data, u, v, m) self.assertAlmostEqual(expected, computed, delta=1.0e-12) if __name__ == "__main__": unittest.main()
34.919708
90
0.510033
60892f8ecee0aca4dc6ee1b77a15915cc8d3c055
7,043
h
C
ios/libnode/include/node/jsrtisolateshim.h
ivandisi/nodejs-mobile-react-native
d6c0eb50ba0048f929303e110105569925c1efef
[ "MIT" ]
1
2020-01-26T15:16:37.000Z
2020-01-26T15:16:37.000Z
libs/ios/nodemobile/include/node/jsrtisolateshim.h
staltz/nodejs-mobile-cordova
4ded39db91149098931f4ec53a64d2f5caf6c397
[ "MIT" ]
18
2019-12-27T19:58:20.000Z
2022-02-27T08:17:49.000Z
libs/ios/nodemobile/include/node/jsrtisolateshim.h
staltz/nodejs-mobile-cordova
4ded39db91149098931f4ec53a64d2f5caf6c397
[ "MIT" ]
2
2022-03-16T10:50:05.000Z
2022-03-17T06:33:55.000Z
// Copyright Microsoft. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and / or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #ifndef DEPS_CHAKRASHIM_SRC_JSRTISOLATESHIM_H_ #define DEPS_CHAKRASHIM_SRC_JSRTISOLATESHIM_H_ #include "uv.h" #include <vector> // CHAKRA-TODO : now that node is using libc++ for C++11 support can we remove // all OSX_SDK_TR1 specialization? #if !defined(OSX_SDK_TR1) && defined(__APPLE__) #include <AvailabilityMacros.h> #if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < MAC_OS_X_VERSION_10_9 #define OSX_SDK_TR1 #endif #endif #include <unordered_map> namespace v8 { class Isolate; class TryCatch; extern bool g_disableIdleGc; } // namespace v8 namespace jsrt { enum CachedPropertyIdRef : int { #define DEF(x, ...) x, #include "jsrtcachedpropertyidref.inc" Count }; enum CachedSymbolPropertyIdRef { #define DEFSYMBOL(x, ...) x, #include "jsrtcachedpropertyidref.inc" SymbolCount }; class IsolateShim { public: v8::ArrayBuffer::Allocator* arrayBufferAllocator; bool NewContext(JsContextRef * context, bool exposeGC, bool useGlobalTTState, JsValueRef globalObjectTemplateInstance); bool GetMemoryUsage(size_t * memoryUsage); void CollectGarbage(); bool Dispose(); bool IsDisposing(); static v8::Isolate * New(size_t optReplayUriLength, const char* optReplayUri, bool doRecord, bool doReplay, bool doDebug, uint32_t snapInterval, uint32_t snapHistoryLength); static v8::Isolate * GetCurrentAsIsolate(); static IsolateShim * GetCurrent(); static IsolateShim * FromIsolate(v8::Isolate * isolate); static void DisposeAll(); static ContextShim * GetContextShim(JsContextRef contextRef); JsRuntimeHandle GetRuntimeHandle(); static ContextShim * GetContextShimOfObject(JsValueRef valueRef); void Enter(); void Exit(); void PushScope(ContextShim::Scope * scope, JsContextRef contextRef); void PushScope(ContextShim::Scope * scope, ContextShim * contextShim); void PopScope(ContextShim::Scope * scope); // TTD_NODE static bool RunSingleStepOfReverseMoveLoop(v8::Isolate* isolate, uint64_t* moveMode, int64_t* nextEventTime); ContextShim * GetCurrentContextShim(); // Symbols propertyIdRef JsPropertyIdRef GetSelfSymbolPropertyIdRef(); JsPropertyIdRef GetToStringTagSymbolPropertyIdRef(); JsPropertyIdRef GetKeepAliveObjectSymbolPropertyIdRef(); JsPropertyIdRef GetCachedSymbolPropertyIdRef( CachedSymbolPropertyIdRef cachedSymbolPropertyIdRef); // String propertyIdRef JsPropertyIdRef GetProxyTrapPropertyIdRef(ProxyTraps trap); JsPropertyIdRef GetCachedPropertyIdRef( CachedPropertyIdRef cachedPropertyIdRef); void RequestInterrupt(v8::InterruptCallback callback, void* data); void DisableExecution(); bool IsExeuctionDisabled(); void EnableExecution(); static inline bool IsIdleGcEnabled() { return !v8::g_disableIdleGc; } bool AddMessageListener(void * that); void RemoveMessageListeners(void * that); template <typename Fn> void ForEachMessageListener(Fn fn) { for (auto i = messageListeners.begin(); i != messageListeners.end(); i++) { fn(*i); } } void RunMicrotasks(); void QueueMicrotask(JsValueRef task); JsValueRef GetChakraShimJsArrayBuffer(); JsValueRef GetChakraInspectorShimJsArrayBuffer(); void SetData(unsigned int slot, void* data); void* GetData(unsigned int slot); ContextShim* debugContext; inline uv_prepare_t* idleGc_prepare_handle() { return &idleGc_prepare_handle_; } inline uv_timer_t* idleGc_timer_handle() { return &idleGc_timer_handle_; } inline bool IsJsScriptExecuted() { return jsScriptExecuted; } inline void SetScriptExecuted() { jsScriptExecuted = true; } inline void ResetScriptExecuted() { jsScriptExecuted = false; } inline void SetIsIdleGcScheduled() { isIdleGcScheduled = true; } inline void ResetIsIdleGcScheduled() { isIdleGcScheduled = false; } inline bool IsIdleGcScheduled() { return isIdleGcScheduled; } void SetPromiseRejectCallback(v8::PromiseRejectCallback callback); private: struct MicroTask { explicit MicroTask(JsValueRef task) : task(task) { JsAddRef(this->task, nullptr); } ~MicroTask() { if (this->task) { JsRelease(this->task, nullptr); } } MicroTask(MicroTask&& other) : task(other.task) { other.task = nullptr; } MicroTask(const MicroTask&) = delete; JsValueRef task; }; // Construction/Destruction should go thru New/Dispose explicit IsolateShim(JsRuntimeHandle runtime); ~IsolateShim(); static v8::Isolate * ToIsolate(IsolateShim * isolate); static void CHAKRA_CALLBACK JsContextBeforeCollectCallback(JsRef contextRef, void* data); static void CHAKRA_CALLBACK PromiseRejectionCallback( JsValueRef promise, JsValueRef reason, bool handled, void* callbackState); JsRuntimeHandle runtime; JsPropertyIdRef symbolPropertyIdRefs[CachedSymbolPropertyIdRef::SymbolCount]; JsPropertyIdRef cachedPropertyIdRefs[CachedPropertyIdRef::Count]; bool isDisposing; ContextShim::Scope * contextScopeStack; IsolateShim ** prevnext; IsolateShim * next; friend class v8::TryCatch; v8::TryCatch * tryCatchStackTop; std::vector<void *> messageListeners; // Node only has 4 slots (internals::Internals::kNumIsolateDataSlots = 4) void * embeddedData[4]; // CHAKRA-TODO: support multiple shims static IsolateShim * s_isolateList; static THREAD_LOCAL IsolateShim * s_currentIsolate; static THREAD_LOCAL IsolateShim * s_previousIsolate; uv_prepare_t idleGc_prepare_handle_; uv_timer_t idleGc_timer_handle_; bool jsScriptExecuted = false; bool isIdleGcScheduled = false; std::vector<MicroTask> microtaskQueue; }; } // namespace jsrt #endif // DEPS_CHAKRASHIM_SRC_JSRTISOLATESHIM_H_
30.357759
80
0.732358
7fa1a2682a640374f3beab650f9adf287f8b4019
2,997
php
PHP
src/Controller/BaseMail.php
mail2telegram/bot-handler
181b47e444e4079fc11d039247129b91a0a66d2b
[ "MIT" ]
null
null
null
src/Controller/BaseMail.php
mail2telegram/bot-handler
181b47e444e4079fc11d039247129b91a0a66d2b
[ "MIT" ]
18
2020-06-25T08:03:59.000Z
2020-07-21T10:31:27.000Z
src/Controller/BaseMail.php
mail2telegram/bot-handler
181b47e444e4079fc11d039247129b91a0a66d2b
[ "MIT" ]
null
null
null
<?php namespace M2T\Controller; use M2T\AccountManager; use M2T\Client\ImapClient; use M2T\Client\SmtpClient; use M2T\Client\TelegramClient; use M2T\Model\Attachment; use M2T\Model\Email; use M2T\Model\Mailbox; use M2T\State; abstract class BaseMail extends BaseMailbox { protected const MSG_SENT = 'Отправлено'; protected State $state; protected TelegramClient $messenger; protected AccountManager $accountManager; protected SmtpClient $smtpClient; protected ImapClient $imapClient; /** @noinspection MagicMethodsValidityInspection PhpMissingParentConstructorInspection */ public function __construct( State $state, TelegramClient $messenger, AccountManager $accountManager, SmtpClient $smtpClient, ImapClient $imapClient ) { $this->state = $state; $this->messenger = $messenger; $this->accountManager = $accountManager; $this->smtpClient = $smtpClient; $this->imapClient = $imapClient; } protected function send(Mailbox $mailAccount, Email $email): bool { $result = $this->smtpClient->send($mailAccount, $email); if (!$result) { $this->replyError(); return false; } // Gmail при отправке по SMTP сам добавляет письмо в отправленные. // А Яндекс нет. В крайнем случае будет добавлено дважды. if ($mailAccount->smtpHost !== 'smtp.gmail.com') { $this->imapClient->appendToSent($mailAccount, $email); } $this->messenger->sendMessage($this->state->chatId, static::MSG_SENT); return true; } protected function parseMessageAndAttachment(array $update, Email $email): void { $email->message = $update['message']['text'] ?? ''; $email->message = $update['message']['caption'] ?? $email->message; $fileName = ''; $fileContent = ''; $fileId = ''; $action = ''; if (isset($update['message']['document'])) { $fileId = $update['message']['document']['file_id']; $action = 'upload_document'; } elseif (isset($update['message']['photo'])) { $fileId = $update['message']['photo'][1]['file_id']; $action = 'upload_photo'; } elseif (isset($update['message']['video'])) { $fileId = $update['message']['video']['file_id']; $action = 'upload_video'; } elseif (isset($update['message']['audio'])) { $fileId = $update['message']['audio']['file_id']; $action = 'upload_audio'; } if ($action) { $this->messenger->sendChatAction($this->state->chatId, $action); if (!$this->messenger->getFile($fileId, $fileName, $fileContent)) { $this->replyError(); return; } if ($fileContent) { $email->attachment = new Attachment($fileName, $fileContent); } } } }
32.225806
93
0.584585
c1dfc985095b599b2dd855cfc7f8807e58165a69
759
sql
SQL
src/test/resources/sql-data.sql
jacobwinkworth-qa/IMS
85f2223376fdabfc14798aec51d57cc0424eeb5f
[ "MIT" ]
null
null
null
src/test/resources/sql-data.sql
jacobwinkworth-qa/IMS
85f2223376fdabfc14798aec51d57cc0424eeb5f
[ "MIT" ]
null
null
null
src/test/resources/sql-data.sql
jacobwinkworth-qa/IMS
85f2223376fdabfc14798aec51d57cc0424eeb5f
[ "MIT" ]
1
2020-11-27T14:48:14.000Z
2020-11-27T14:48:14.000Z
INSERT INTO customers (first_name, surname) VALUES ('jacob', 'winkworth'); INSERT INTO customers (first_name, surname) VALUES ('ian', 'biel'); INSERT INTO items (name, value) VALUES ('ball', 9.99); INSERT INTO items (name, value) VALUES ('shoe', 5.0); INSERT INTO items (name, value) VALUES ('frisbee', 10.0); INSERT INTO orders (customer_id) VALUES (1); INSERT INTO orders_items (order_id, item_id, quantity) VALUES (last_insert_id(), 1, 1); INSERT INTO orders_items (order_id, item_id, quantity) VALUES (last_insert_id(), 2, 1); INSERT INTO orders (customer_id) VALUES (2); INSERT INTO orders_items (order_id, item_id, quantity) VALUES (last_insert_id(), 1, 1); INSERT INTO orders_items (order_id, item_id, quantity) VALUES (last_insert_id(), 2, 1);
27.107143
54
0.729908
e31b269aba99dcbb3c7a8948b07f2ffccb9a172d
127
rb
Ruby
db/migrate/20150630211926_add_upvotes_to_links.rb
dgf1979/epicodus-hacker_new_alike
59322743c0b1b7b2f3189d4de176abfefc738896
[ "Unlicense" ]
null
null
null
db/migrate/20150630211926_add_upvotes_to_links.rb
dgf1979/epicodus-hacker_new_alike
59322743c0b1b7b2f3189d4de176abfefc738896
[ "Unlicense" ]
null
null
null
db/migrate/20150630211926_add_upvotes_to_links.rb
dgf1979/epicodus-hacker_new_alike
59322743c0b1b7b2f3189d4de176abfefc738896
[ "Unlicense" ]
null
null
null
class AddUpvotesToLinks < ActiveRecord::Migration def change add_column :links, :upvotes, :integer, default: 0 end end
21.166667
53
0.748031
4cd3ac30ff7ef18771e1874a26a247e4c9d3a971
7,683
py
Python
PDFMergerUI.py
manuelprogramming/PDFMerger
2e3b48ed3cb01152035fef0fb0f8a30be404cf5c
[ "MIT" ]
null
null
null
PDFMergerUI.py
manuelprogramming/PDFMerger
2e3b48ed3cb01152035fef0fb0f8a30be404cf5c
[ "MIT" ]
null
null
null
PDFMergerUI.py
manuelprogramming/PDFMerger
2e3b48ed3cb01152035fef0fb0f8a30be404cf5c
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'PDFMerger.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_PDFMergerUI(object): def setupUi(self, PDFMergerUI): PDFMergerUI.setObjectName("PDFMergerUI") PDFMergerUI.setEnabled(True) PDFMergerUI.resize(403, 392) PDFMergerUI.setWindowTitle("PDFMerger") icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("Icon_PDF.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) PDFMergerUI.setWindowIcon(icon) PDFMergerUI.setStyleSheet("") self.centralwidget = QtWidgets.QWidget(PDFMergerUI) self.centralwidget.setEnabled(True) self.centralwidget.setObjectName("centralwidget") self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget) self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 401, 351)) self.verticalLayoutWidget.setObjectName("verticalLayoutWidget") self.verticalLayoutMain = QtWidgets.QVBoxLayout(self.verticalLayoutWidget) self.verticalLayoutMain.setContentsMargins(0, 0, 0, 0) self.verticalLayoutMain.setObjectName("verticalLayoutMain") self.item_list = QtWidgets.QListWidget(self.verticalLayoutWidget) self.item_list.setObjectName("item_list") self.verticalLayoutMain.addWidget(self.item_list) self.horizontalLayout_mode = QtWidgets.QHBoxLayout() self.horizontalLayout_mode.setObjectName("horizontalLayout_mode") self.radioButton_merge = QtWidgets.QRadioButton(self.verticalLayoutWidget) self.radioButton_merge.setAutoFillBackground(False) self.radioButton_merge.setChecked(True) self.radioButton_merge.setObjectName("radioButton_merge") self.horizontalLayout_mode.addWidget(self.radioButton_merge) self.radioButton_split = QtWidgets.QRadioButton(self.verticalLayoutWidget) self.radioButton_split.setObjectName("radioButton_split") self.horizontalLayout_mode.addWidget(self.radioButton_split) self.verticalLayoutMain.addLayout(self.horizontalLayout_mode) self.process_label = QtWidgets.QLabel(self.verticalLayoutWidget) self.process_label.setText("") self.process_label.setObjectName("process_label") self.verticalLayoutMain.addWidget(self.process_label) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.verticalLayoutMain.addItem(spacerItem) self.action_button = QtWidgets.QPushButton(self.verticalLayoutWidget) self.action_button.setObjectName("action_button") self.verticalLayoutMain.addWidget(self.action_button) self.load_button = QtWidgets.QPushButton(self.verticalLayoutWidget) self.load_button.setObjectName("load_button") self.verticalLayoutMain.addWidget(self.load_button) self.save_button = QtWidgets.QPushButton(self.verticalLayoutWidget) self.save_button.setObjectName("save_button") self.verticalLayoutMain.addWidget(self.save_button) self.horizontalLayout_deleteButtons = QtWidgets.QHBoxLayout() self.horizontalLayout_deleteButtons.setObjectName("horizontalLayout_deleteButtons") self.delete_all_files_button = QtWidgets.QPushButton(self.verticalLayoutWidget) self.delete_all_files_button.setObjectName("delete_all_files_button") self.horizontalLayout_deleteButtons.addWidget(self.delete_all_files_button) self.delete_selected_file_button = QtWidgets.QPushButton(self.verticalLayoutWidget) self.delete_selected_file_button.setObjectName("delete_selected_file_button") self.horizontalLayout_deleteButtons.addWidget(self.delete_selected_file_button) self.verticalLayoutMain.addLayout(self.horizontalLayout_deleteButtons) PDFMergerUI.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(PDFMergerUI) self.menubar.setGeometry(QtCore.QRect(0, 0, 403, 21)) self.menubar.setObjectName("menubar") self.menuDatei = QtWidgets.QMenu(self.menubar) self.menuDatei.setObjectName("menuDatei") self.menuMode = QtWidgets.QMenu(self.menubar) self.menuMode.setObjectName("menuMode") self.menuPDF = QtWidgets.QMenu(self.menuMode) self.menuPDF.setObjectName("menuPDF") self.menuConverter = QtWidgets.QMenu(self.menuMode) self.menuConverter.setObjectName("menuConverter") PDFMergerUI.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(PDFMergerUI) self.statusbar.setObjectName("statusbar") PDFMergerUI.setStatusBar(self.statusbar) self.action_ffnen = QtWidgets.QAction(PDFMergerUI) self.action_ffnen.setObjectName("action_ffnen") self.actionexit = QtWidgets.QAction(PDFMergerUI) self.actionexit.setObjectName("actionexit") self.actionexit_2 = QtWidgets.QAction(PDFMergerUI) self.actionexit_2.setObjectName("actionexit_2") self.actionMerge = QtWidgets.QAction(PDFMergerUI) self.actionMerge.setObjectName("actionMerge") self.actionSplit = QtWidgets.QAction(PDFMergerUI) self.actionSplit.setObjectName("actionSplit") self.actionImage = QtWidgets.QAction(PDFMergerUI) self.actionImage.setObjectName("actionImage") self.menuDatei.addAction(self.actionexit_2) self.menuPDF.addAction(self.actionMerge) self.menuPDF.addAction(self.actionSplit) self.menuConverter.addAction(self.actionImage) self.menuMode.addAction(self.menuPDF.menuAction()) self.menuMode.addAction(self.menuConverter.menuAction()) self.menubar.addAction(self.menuDatei.menuAction()) self.menubar.addAction(self.menuMode.menuAction()) self.retranslateUi(PDFMergerUI) QtCore.QMetaObject.connectSlotsByName(PDFMergerUI) def retranslateUi(self, PDFMergerUI): _translate = QtCore.QCoreApplication.translate self.radioButton_merge.setText(_translate("PDFMergerUI", "Merge")) self.radioButton_split.setText(_translate("PDFMergerUI", "Split")) self.action_button.setText(_translate("PDFMergerUI", "Merge")) self.load_button.setText(_translate("PDFMergerUI", "Load File")) self.save_button.setText(_translate("PDFMergerUI", "Save File")) self.delete_all_files_button.setText(_translate("PDFMergerUI", "Delete All Files")) self.delete_selected_file_button.setText(_translate("PDFMergerUI", "Delete Selected File")) self.menuDatei.setTitle(_translate("PDFMergerUI", "Datei")) self.menuMode.setTitle(_translate("PDFMergerUI", "Mode")) self.menuPDF.setTitle(_translate("PDFMergerUI", "PDF")) self.menuConverter.setTitle(_translate("PDFMergerUI", "Converter")) self.action_ffnen.setText(_translate("PDFMergerUI", "öffnen")) self.actionexit.setText(_translate("PDFMergerUI", "exit")) self.actionexit_2.setText(_translate("PDFMergerUI", "Exit")) self.actionMerge.setText(_translate("PDFMergerUI", "Merge")) self.actionSplit.setText(_translate("PDFMergerUI", "Split")) self.actionImage.setText(_translate("PDFMergerUI", "Image")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) PDFMergerUI = QtWidgets.QMainWindow() ui = Ui_PDFMergerUI() ui.setupUi(PDFMergerUI) PDFMergerUI.show() sys.exit(app.exec_())
54.878571
114
0.737863