repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
agilewalker/SwiftyChardet | SwiftyChardet/euctwfreq.swift | 1 | 33374 | /*
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Wu Hui Yuan - port to Swift
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
*/
// EUCTW frequency table
// Converted from big5 work
// by Taiwan's Mandarin Promotion Council
// <http://www.edu.tw:81/mandr/>
// 128 --> 0.42261
// 256 --> 0.57851
// 512 --> 0.74851
// 1024 --> 0.89384
// 2048 --> 0.97583
//
// Idea Distribution Ratio = 0.74851/(1-0.74851) =2.98
// Random Distribution Ration = 512/(5401-512)=0.105
//
// Typical Distribution Ratio about 25% of Ideal one, still much higher than RDR
let EUCTW_TYPICAL_DISTRIBUTION_RATIO = 0.75
// Char to FreqOrder table ,
let EUCTW_TABLE_SIZE = 8102
let EUCTW_CHAR_TO_FREQ_ORDER: [Int] = [
1,1800,1506, 255,1431, 198, 9, 82, 6,7310, 177, 202,3615,1256,2808, 110, // 2742
3735, 33,3241, 261, 76, 44,2113, 16,2931,2184,1176, 659,3868, 26,3404,2643, // 2758
1198,3869,3313,4060, 410,2211, 302, 590, 361,1963, 8, 204, 58,4296,7311,1931, // 2774
63,7312,7313, 317,1614, 75, 222, 159,4061,2412,1480,7314,3500,3068, 224,2809, // 2790
3616, 3, 10,3870,1471, 29,2774,1135,2852,1939, 873, 130,3242,1123, 312,7315, // 2806
4297,2051, 507, 252, 682,7316, 142,1914, 124, 206,2932, 34,3501,3173, 64, 604, // 2822
7317,2494,1976,1977, 155,1990, 645, 641,1606,7318,3405, 337, 72, 406,7319, 80, // 2838
630, 238,3174,1509, 263, 939,1092,2644, 756,1440,1094,3406, 449, 69,2969, 591, // 2854
179,2095, 471, 115,2034,1843, 60, 50,2970, 134, 806,1868, 734,2035,3407, 180, // 2870
995,1607, 156, 537,2893, 688,7320, 319,1305, 779,2144, 514,2374, 298,4298, 359, // 2886
2495, 90,2707,1338, 663, 11, 906,1099,2545, 20,2436, 182, 532,1716,7321, 732, // 2902
1376,4062,1311,1420,3175, 25,2312,1056, 113, 399, 382,1949, 242,3408,2467, 529, // 2918
3243, 475,1447,3617,7322, 117, 21, 656, 810,1297,2295,2329,3502,7323, 126,4063, // 2934
706, 456, 150, 613,4299, 71,1118,2036,4064, 145,3069, 85, 835, 486,2114,1246, // 2950
1426, 428, 727,1285,1015, 800, 106, 623, 303,1281,7324,2127,2354, 347,3736, 221, // 2966
3503,3110,7325,1955,1153,4065, 83, 296,1199,3070, 192, 624, 93,7326, 822,1897, // 2982
2810,3111, 795,2064, 991,1554,1542,1592, 27, 43,2853, 859, 139,1456, 860,4300, // 2998
437, 712,3871, 164,2392,3112, 695, 211,3017,2096, 195,3872,1608,3504,3505,3618, // 3014
3873, 234, 811,2971,2097,3874,2229,1441,3506,1615,2375, 668,2076,1638, 305, 228, // 3030
1664,4301, 467, 415,7327, 262,2098,1593, 239, 108, 300, 200,1033, 512,1247,2077, // 3046
7328,7329,2173,3176,3619,2673, 593, 845,1062,3244, 88,1723,2037,3875,1950, 212, // 3062
266, 152, 149, 468,1898,4066,4302, 77, 187,7330,3018, 37, 5,2972,7331,3876, // 3078
7332,7333, 39,2517,4303,2894,3177,2078, 55, 148, 74,4304, 545, 483,1474,1029, // 3094
1665, 217,1869,1531,3113,1104,2645,4067, 24, 172,3507, 900,3877,3508,3509,4305, // 3110
32,1408,2811,1312, 329, 487,2355,2247,2708, 784,2674, 4,3019,3314,1427,1788, // 3126
188, 109, 499,7334,3620,1717,1789, 888,1217,3020,4306,7335,3510,7336,3315,1520, // 3142
3621,3878, 196,1034, 775,7337,7338, 929,1815, 249, 439, 38,7339,1063,7340, 794, // 3158
3879,1435,2296, 46, 178,3245,2065,7341,2376,7342, 214,1709,4307, 804, 35, 707, // 3174
324,3622,1601,2546, 140, 459,4068,7343,7344,1365, 839, 272, 978,2257,2572,3409, // 3190
2128,1363,3623,1423, 697, 100,3071, 48, 70,1231, 495,3114,2193,7345,1294,7346, // 3206
2079, 462, 586,1042,3246, 853, 256, 988, 185,2377,3410,1698, 434,1084,7347,3411, // 3222
314,2615,2775,4308,2330,2331, 569,2280, 637,1816,2518, 757,1162,1878,1616,3412, // 3238
287,1577,2115, 768,4309,1671,2854,3511,2519,1321,3737, 909,2413,7348,4069, 933, // 3254
3738,7349,2052,2356,1222,4310, 765,2414,1322, 786,4311,7350,1919,1462,1677,2895, // 3270
1699,7351,4312,1424,2437,3115,3624,2590,3316,1774,1940,3413,3880,4070, 309,1369, // 3286
1130,2812, 364,2230,1653,1299,3881,3512,3882,3883,2646, 525,1085,3021, 902,2000, // 3302
1475, 964,4313, 421,1844,1415,1057,2281, 940,1364,3116, 376,4314,4315,1381, 7, // 3318
2520, 983,2378, 336,1710,2675,1845, 321,3414, 559,1131,3022,2742,1808,1132,1313, // 3334
265,1481,1857,7352, 352,1203,2813,3247, 167,1089, 420,2814, 776, 792,1724,3513, // 3350
4071,2438,3248,7353,4072,7354, 446, 229, 333,2743, 901,3739,1200,1557,4316,2647, // 3366
1920, 395,2744,2676,3740,4073,1835, 125, 916,3178,2616,4317,7355,7356,3741,7357, // 3382
7358,7359,4318,3117,3625,1133,2547,1757,3415,1510,2313,1409,3514,7360,2145, 438, // 3398
2591,2896,2379,3317,1068, 958,3023, 461, 311,2855,2677,4074,1915,3179,4075,1978, // 3414
383, 750,2745,2617,4076, 274, 539, 385,1278,1442,7361,1154,1964, 384, 561, 210, // 3430
98,1295,2548,3515,7362,1711,2415,1482,3416,3884,2897,1257, 129,7363,3742, 642, // 3446
523,2776,2777,2648,7364, 141,2231,1333, 68, 176, 441, 876, 907,4077, 603,2592, // 3462
710, 171,3417, 404, 549, 18,3118,2393,1410,3626,1666,7365,3516,4319,2898,4320, // 3478
7366,2973, 368,7367, 146, 366, 99, 871,3627,1543, 748, 807,1586,1185, 22,2258, // 3494
379,3743,3180,7368,3181, 505,1941,2618,1991,1382,2314,7369, 380,2357, 218, 702, // 3510
1817,1248,3418,3024,3517,3318,3249,7370,2974,3628, 930,3250,3744,7371, 59,7372, // 3526
585, 601,4078, 497,3419,1112,1314,4321,1801,7373,1223,1472,2174,7374, 749,1836, // 3542
690,1899,3745,1772,3885,1476, 429,1043,1790,2232,2116, 917,4079, 447,1086,1629, // 3558
7375, 556,7376,7377,2020,1654, 844,1090, 105, 550, 966,1758,2815,1008,1782, 686, // 3574
1095,7378,2282, 793,1602,7379,3518,2593,4322,4080,2933,2297,4323,3746, 980,2496, // 3590
544, 353, 527,4324, 908,2678,2899,7380, 381,2619,1942,1348,7381,1341,1252, 560, // 3606
3072,7382,3420,2856,7383,2053, 973, 886,2080, 143,4325,7384,7385, 157,3886, 496, // 3622
4081, 57, 840, 540,2038,4326,4327,3421,2117,1445, 970,2259,1748,1965,2081,4082, // 3638
3119,1234,1775,3251,2816,3629, 773,1206,2129,1066,2039,1326,3887,1738,1725,4083, // 3654
279,3120, 51,1544,2594, 423,1578,2130,2066, 173,4328,1879,7386,7387,1583, 264, // 3670
610,3630,4329,2439, 280, 154,7388,7389,7390,1739, 338,1282,3073, 693,2857,1411, // 3686
1074,3747,2440,7391,4330,7392,7393,1240, 952,2394,7394,2900,1538,2679, 685,1483, // 3702
4084,2468,1436, 953,4085,2054,4331, 671,2395, 79,4086,2441,3252, 608, 567,2680, // 3718
3422,4087,4088,1691, 393,1261,1791,2396,7395,4332,7396,7397,7398,7399,1383,1672, // 3734
3748,3182,1464, 522,1119, 661,1150, 216, 675,4333,3888,1432,3519, 609,4334,2681, // 3750
2397,7400,7401,7402,4089,3025, 0,7403,2469, 315, 231,2442, 301,3319,4335,2380, // 3766
7404, 233,4090,3631,1818,4336,4337,7405, 96,1776,1315,2082,7406, 257,7407,1809, // 3782
3632,2709,1139,1819,4091,2021,1124,2163,2778,1777,2649,7408,3074, 363,1655,3183, // 3798
7409,2975,7410,7411,7412,3889,1567,3890, 718, 103,3184, 849,1443, 341,3320,2934, // 3814
1484,7413,1712, 127, 67, 339,4092,2398, 679,1412, 821,7414,7415, 834, 738, 351, // 3830
2976,2146, 846, 235,1497,1880, 418,1992,3749,2710, 186,1100,2147,2746,3520,1545, // 3846
1355,2935,2858,1377, 583,3891,4093,2573,2977,7416,1298,3633,1078,2549,3634,2358, // 3862
78,3750,3751, 267,1289,2099,2001,1594,4094, 348, 369,1274,2194,2175,1837,4338, // 3878
1820,2817,3635,2747,2283,2002,4339,2936,2748, 144,3321, 882,4340,3892,2749,3423, // 3894
4341,2901,7417,4095,1726, 320,7418,3893,3026, 788,2978,7419,2818,1773,1327,2859, // 3910
3894,2819,7420,1306,4342,2003,1700,3752,3521,2359,2650, 787,2022, 506, 824,3636, // 3926
534, 323,4343,1044,3322,2023,1900, 946,3424,7421,1778,1500,1678,7422,1881,4344, // 3942
165, 243,4345,3637,2521, 123, 683,4096, 764,4346, 36,3895,1792, 589,2902, 816, // 3958
626,1667,3027,2233,1639,1555,1622,3753,3896,7423,3897,2860,1370,1228,1932, 891, // 3974
2083,2903, 304,4097,7424, 292,2979,2711,3522, 691,2100,4098,1115,4347, 118, 662, // 3990
7425, 611,1156, 854,2381,1316,2861, 2, 386, 515,2904,7426,7427,3253, 868,2234, // 4006
1486, 855,2651, 785,2212,3028,7428,1040,3185,3523,7429,3121, 448,7430,1525,7431, // 4022
2164,4348,7432,3754,7433,4099,2820,3524,3122, 503, 818,3898,3123,1568, 814, 676, // 4038
1444, 306,1749,7434,3755,1416,1030, 197,1428, 805,2821,1501,4349,7435,7436,7437, // 4054
1993,7438,4350,7439,7440,2195, 13,2779,3638,2980,3124,1229,1916,7441,3756,2131, // 4070
7442,4100,4351,2399,3525,7443,2213,1511,1727,1120,7444,7445, 646,3757,2443, 307, // 4086
7446,7447,1595,3186,7448,7449,7450,3639,1113,1356,3899,1465,2522,2523,7451, 519, // 4102
7452, 128,2132, 92,2284,1979,7453,3900,1512, 342,3125,2196,7454,2780,2214,1980, // 4118
3323,7455, 290,1656,1317, 789, 827,2360,7456,3758,4352, 562, 581,3901,7457, 401, // 4134
4353,2248, 94,4354,1399,2781,7458,1463,2024,4355,3187,1943,7459, 828,1105,4101, // 4150
1262,1394,7460,4102, 605,4356,7461,1783,2862,7462,2822, 819,2101, 578,2197,2937, // 4166
7463,1502, 436,3254,4103,3255,2823,3902,2905,3425,3426,7464,2712,2315,7465,7466, // 4182
2332,2067, 23,4357, 193, 826,3759,2102, 699,1630,4104,3075, 390,1793,1064,3526, // 4198
7467,1579,3076,3077,1400,7468,4105,1838,1640,2863,7469,4358,4359, 137,4106, 598, // 4214
3078,1966, 780, 104, 974,2938,7470, 278, 899, 253, 402, 572, 504, 493,1339,7471, // 4230
3903,1275,4360,2574,2550,7472,3640,3029,3079,2249, 565,1334,2713, 863, 41,7473, // 4246
7474,4361,7475,1657,2333, 19, 463,2750,4107, 606,7476,2981,3256,1087,2084,1323, // 4262
2652,2982,7477,1631,1623,1750,4108,2682,7478,2864, 791,2714,2653,2334, 232,2416, // 4278
7479,2983,1498,7480,2654,2620, 755,1366,3641,3257,3126,2025,1609, 119,1917,3427, // 4294
862,1026,4109,7481,3904,3760,4362,3905,4363,2260,1951,2470,7482,1125, 817,4110, // 4310
4111,3906,1513,1766,2040,1487,4112,3030,3258,2824,3761,3127,7483,7484,1507,7485, // 4326
2683, 733, 40,1632,1106,2865, 345,4113, 841,2524, 230,4364,2984,1846,3259,3428, // 4342
7486,1263, 986,3429,7487, 735, 879, 254,1137, 857, 622,1300,1180,1388,1562,3907, // 4358
3908,2939, 967,2751,2655,1349, 592,2133,1692,3324,2985,1994,4114,1679,3909,1901, // 4374
2185,7488, 739,3642,2715,1296,1290,7489,4115,2198,2199,1921,1563,2595,2551,1870, // 4390
2752,2986,7490, 435,7491, 343,1108, 596, 17,1751,4365,2235,3430,3643,7492,4366, // 4406
294,3527,2940,1693, 477, 979, 281,2041,3528, 643,2042,3644,2621,2782,2261,1031, // 4422
2335,2134,2298,3529,4367, 367,1249,2552,7493,3530,7494,4368,1283,3325,2004, 240, // 4438
1762,3326,4369,4370, 836,1069,3128, 474,7495,2148,2525, 268,3531,7496,3188,1521, // 4454
1284,7497,1658,1546,4116,7498,3532,3533,7499,4117,3327,2684,1685,4118, 961,1673, // 4470
2622, 190,2005,2200,3762,4371,4372,7500, 570,2497,3645,1490,7501,4373,2623,3260, // 4486
1956,4374, 584,1514, 396,1045,1944,7502,4375,1967,2444,7503,7504,4376,3910, 619, // 4502
7505,3129,3261, 215,2006,2783,2553,3189,4377,3190,4378, 763,4119,3763,4379,7506, // 4518
7507,1957,1767,2941,3328,3646,1174, 452,1477,4380,3329,3130,7508,2825,1253,2382, // 4534
2186,1091,2285,4120, 492,7509, 638,1169,1824,2135,1752,3911, 648, 926,1021,1324, // 4550
4381, 520,4382, 997, 847,1007, 892,4383,3764,2262,1871,3647,7510,2400,1784,4384, // 4566
1952,2942,3080,3191,1728,4121,2043,3648,4385,2007,1701,3131,1551, 30,2263,4122, // 4582
7511,2026,4386,3534,7512, 501,7513,4123, 594,3431,2165,1821,3535,3432,3536,3192, // 4598
829,2826,4124,7514,1680,3132,1225,4125,7515,3262,4387,4126,3133,2336,7516,4388, // 4614
4127,7517,3912,3913,7518,1847,2383,2596,3330,7519,4389, 374,3914, 652,4128,4129, // 4630
375,1140, 798,7520,7521,7522,2361,4390,2264, 546,1659, 138,3031,2445,4391,7523, // 4646
2250, 612,1848, 910, 796,3765,1740,1371, 825,3766,3767,7524,2906,2554,7525, 692, // 4662
444,3032,2624, 801,4392,4130,7526,1491, 244,1053,3033,4131,4132, 340,7527,3915, // 4678
1041,2987, 293,1168, 87,1357,7528,1539, 959,7529,2236, 721, 694,4133,3768, 219, // 4694
1478, 644,1417,3331,2656,1413,1401,1335,1389,3916,7530,7531,2988,2362,3134,1825, // 4710
730,1515, 184,2827, 66,4393,7532,1660,2943, 246,3332, 378,1457, 226,3433, 975, // 4726
3917,2944,1264,3537, 674, 696,7533, 163,7534,1141,2417,2166, 713,3538,3333,4394, // 4742
3918,7535,7536,1186, 15,7537,1079,1070,7538,1522,3193,3539, 276,1050,2716, 758, // 4758
1126, 653,2945,3263,7539,2337, 889,3540,3919,3081,2989, 903,1250,4395,3920,3434, // 4774
3541,1342,1681,1718, 766,3264, 286, 89,2946,3649,7540,1713,7541,2597,3334,2990, // 4790
7542,2947,2215,3194,2866,7543,4396,2498,2526, 181, 387,1075,3921, 731,2187,3335, // 4806
7544,3265, 310, 313,3435,2299, 770,4134, 54,3034, 189,4397,3082,3769,3922,7545, // 4822
1230,1617,1849, 355,3542,4135,4398,3336, 111,4136,3650,1350,3135,3436,3035,4137, // 4838
2149,3266,3543,7546,2784,3923,3924,2991, 722,2008,7547,1071, 247,1207,2338,2471, // 4854
1378,4399,2009, 864,1437,1214,4400, 373,3770,1142,2216, 667,4401, 442,2753,2555, // 4870
3771,3925,1968,4138,3267,1839, 837, 170,1107, 934,1336,1882,7548,7549,2118,4139, // 4886
2828, 743,1569,7550,4402,4140, 582,2384,1418,3437,7551,1802,7552, 357,1395,1729, // 4902
3651,3268,2418,1564,2237,7553,3083,3772,1633,4403,1114,2085,4141,1532,7554, 482, // 4918
2446,4404,7555,7556,1492, 833,1466,7557,2717,3544,1641,2829,7558,1526,1272,3652, // 4934
4142,1686,1794, 416,2556,1902,1953,1803,7559,3773,2785,3774,1159,2316,7560,2867, // 4950
4405,1610,1584,3036,2419,2754, 443,3269,1163,3136,7561,7562,3926,7563,4143,2499, // 4966
3037,4406,3927,3137,2103,1647,3545,2010,1872,4144,7564,4145, 431,3438,7565, 250, // 4982
97, 81,4146,7566,1648,1850,1558, 160, 848,7567, 866, 740,1694,7568,2201,2830, // 4998
3195,4147,4407,3653,1687, 950,2472, 426, 469,3196,3654,3655,3928,7569,7570,1188, // 5014
424,1995, 861,3546,4148,3775,2202,2685, 168,1235,3547,4149,7571,2086,1674,4408, // 5030
3337,3270, 220,2557,1009,7572,3776, 670,2992, 332,1208, 717,7573,7574,3548,2447, // 5046
3929,3338,7575, 513,7576,1209,2868,3339,3138,4409,1080,7577,7578,7579,7580,2527, // 5062
3656,3549, 815,1587,3930,3931,7581,3550,3439,3777,1254,4410,1328,3038,1390,3932, // 5078
1741,3933,3778,3934,7582, 236,3779,2448,3271,7583,7584,3657,3780,1273,3781,4411, // 5094
7585, 308,7586,4412, 245,4413,1851,2473,1307,2575, 430, 715,2136,2449,7587, 270, // 5110
199,2869,3935,7588,3551,2718,1753, 761,1754, 725,1661,1840,4414,3440,3658,7589, // 5126
7590, 587, 14,3272, 227,2598, 326, 480,2265, 943,2755,3552, 291, 650,1883,7591, // 5142
1702,1226, 102,1547, 62,3441, 904,4415,3442,1164,4150,7592,7593,1224,1548,2756, // 5158
391, 498,1493,7594,1386,1419,7595,2055,1177,4416, 813, 880,1081,2363, 566,1145, // 5174
4417,2286,1001,1035,2558,2599,2238, 394,1286,7596,7597,2068,7598, 86,1494,1730, // 5190
3936, 491,1588, 745, 897,2948, 843,3340,3937,2757,2870,3273,1768, 998,2217,2069, // 5206
397,1826,1195,1969,3659,2993,3341, 284,7599,3782,2500,2137,2119,1903,7600,3938, // 5222
2150,3939,4151,1036,3443,1904, 114,2559,4152, 209,1527,7601,7602,2949,2831,2625, // 5238
2385,2719,3139, 812,2560,7603,3274,7604,1559, 737,1884,3660,1210, 885, 28,2686, // 5254
3553,3783,7605,4153,1004,1779,4418,7606, 346,1981,2218,2687,4419,3784,1742, 797, // 5270
1642,3940,1933,1072,1384,2151, 896,3941,3275,3661,3197,2871,3554,7607,2561,1958, // 5286
4420,2450,1785,7608,7609,7610,3942,4154,1005,1308,3662,4155,2720,4421,4422,1528, // 5302
2600, 161,1178,4156,1982, 987,4423,1101,4157, 631,3943,1157,3198,2420,1343,1241, // 5318
1016,2239,2562, 372, 877,2339,2501,1160, 555,1934, 911,3944,7611, 466,1170, 169, // 5334
1051,2907,2688,3663,2474,2994,1182,2011,2563,1251,2626,7612, 992,2340,3444,1540, // 5350
2721,1201,2070,2401,1996,2475,7613,4424, 528,1922,2188,1503,1873,1570,2364,3342, // 5366
3276,7614, 557,1073,7615,1827,3445,2087,2266,3140,3039,3084, 767,3085,2786,4425, // 5382
1006,4158,4426,2341,1267,2176,3664,3199, 778,3945,3200,2722,1597,2657,7616,4427, // 5398
7617,3446,7618,7619,7620,3277,2689,1433,3278, 131, 95,1504,3946, 723,4159,3141, // 5414
1841,3555,2758,2189,3947,2027,2104,3665,7621,2995,3948,1218,7622,3343,3201,3949, // 5430
4160,2576, 248,1634,3785, 912,7623,2832,3666,3040,3786, 654, 53,7624,2996,7625, // 5446
1688,4428, 777,3447,1032,3950,1425,7626, 191, 820,2120,2833, 971,4429, 931,3202, // 5462
135, 664, 783,3787,1997, 772,2908,1935,3951,3788,4430,2909,3203, 282,2723, 640, // 5478
1372,3448,1127, 922, 325,3344,7627,7628, 711,2044,7629,7630,3952,2219,2787,1936, // 5494
3953,3345,2220,2251,3789,2300,7631,4431,3790,1258,3279,3954,3204,2138,2950,3955, // 5510
3956,7632,2221, 258,3205,4432, 101,1227,7633,3280,1755,7634,1391,3281,7635,2910, // 5526
2056, 893,7636,7637,7638,1402,4161,2342,7639,7640,3206,3556,7641,7642, 878,1325, // 5542
1780,2788,4433, 259,1385,2577, 744,1183,2267,4434,7643,3957,2502,7644, 684,1024, // 5558
4162,7645, 472,3557,3449,1165,3282,3958,3959, 322,2152, 881, 455,1695,1152,1340, // 5574
660, 554,2153,4435,1058,4436,4163, 830,1065,3346,3960,4437,1923,7646,1703,1918, // 5590
7647, 932,2268, 122,7648,4438, 947, 677,7649,3791,2627, 297,1905,1924,2269,4439, // 5606
2317,3283,7650,7651,4164,7652,4165, 84,4166, 112, 989,7653, 547,1059,3961, 701, // 5622
3558,1019,7654,4167,7655,3450, 942, 639, 457,2301,2451, 993,2951, 407, 851, 494, // 5638
4440,3347, 927,7656,1237,7657,2421,3348, 573,4168, 680, 921,2911,1279,1874, 285, // 5654
790,1448,1983, 719,2167,7658,7659,4441,3962,3963,1649,7660,1541, 563,7661,1077, // 5670
7662,3349,3041,3451, 511,2997,3964,3965,3667,3966,1268,2564,3350,3207,4442,4443, // 5686
7663, 535,1048,1276,1189,2912,2028,3142,1438,1373,2834,2952,1134,2012,7664,4169, // 5702
1238,2578,3086,1259,7665, 700,7666,2953,3143,3668,4170,7667,4171,1146,1875,1906, // 5718
4444,2601,3967, 781,2422, 132,1589, 203, 147, 273,2789,2402, 898,1786,2154,3968, // 5734
3969,7668,3792,2790,7669,7670,4445,4446,7671,3208,7672,1635,3793, 965,7673,1804, // 5750
2690,1516,3559,1121,1082,1329,3284,3970,1449,3794, 65,1128,2835,2913,2759,1590, // 5766
3795,7674,7675, 12,2658, 45, 976,2579,3144,4447, 517,2528,1013,1037,3209,7676, // 5782
3796,2836,7677,3797,7678,3452,7679,2602, 614,1998,2318,3798,3087,2724,2628,7680, // 5798
2580,4172, 599,1269,7681,1810,3669,7682,2691,3088, 759,1060, 489,1805,3351,3285, // 5814
1358,7683,7684,2386,1387,1215,2629,2252, 490,7685,7686,4173,1759,2387,2343,7687, // 5830
4448,3799,1907,3971,2630,1806,3210,4449,3453,3286,2760,2344, 874,7688,7689,3454, // 5846
3670,1858, 91,2914,3671,3042,3800,4450,7690,3145,3972,2659,7691,3455,1202,1403, // 5862
3801,2954,2529,1517,2503,4451,3456,2504,7692,4452,7693,2692,1885,1495,1731,3973, // 5878
2365,4453,7694,2029,7695,7696,3974,2693,1216, 237,2581,4174,2319,3975,3802,4454, // 5894
4455,2694,3560,3457, 445,4456,7697,7698,7699,7700,2761, 61,3976,3672,1822,3977, // 5910
7701, 687,2045, 935, 925, 405,2660, 703,1096,1859,2725,4457,3978,1876,1367,2695, // 5926
3352, 918,2105,1781,2476, 334,3287,1611,1093,4458, 564,3146,3458,3673,3353, 945, // 5942
2631,2057,4459,7702,1925, 872,4175,7703,3459,2696,3089, 349,4176,3674,3979,4460, // 5958
3803,4177,3675,2155,3980,4461,4462,4178,4463,2403,2046, 782,3981, 400, 251,4179, // 5974
1624,7704,7705, 277,3676, 299,1265, 476,1191,3804,2121,4180,4181,1109, 205,7706, // 5990
2582,1000,2156,3561,1860,7707,7708,7709,4464,7710,4465,2565, 107,2477,2157,3982, // 6006
3460,3147,7711,1533, 541,1301, 158, 753,4182,2872,3562,7712,1696, 370,1088,4183, // 6022
4466,3563, 579, 327, 440, 162,2240, 269,1937,1374,3461, 968,3043, 56,1396,3090, // 6038
2106,3288,3354,7713,1926,2158,4467,2998,7714,3564,7715,7716,3677,4468,2478,7717, // 6054
2791,7718,1650,4469,7719,2603,7720,7721,3983,2661,3355,1149,3356,3984,3805,3985, // 6070
7722,1076, 49,7723, 951,3211,3289,3290, 450,2837, 920,7724,1811,2792,2366,4184, // 6086
1908,1138,2367,3806,3462,7725,3212,4470,1909,1147,1518,2423,4471,3807,7726,4472, // 6102
2388,2604, 260,1795,3213,7727,7728,3808,3291, 708,7729,3565,1704,7730,3566,1351, // 6118
1618,3357,2999,1886, 944,4185,3358,4186,3044,3359,4187,7731,3678, 422, 413,1714, // 6134
3292, 500,2058,2345,4188,2479,7732,1344,1910, 954,7733,1668,7734,7735,3986,2404, // 6150
4189,3567,3809,4190,7736,2302,1318,2505,3091, 133,3092,2873,4473, 629, 31,2838, // 6166
2697,3810,4474, 850, 949,4475,3987,2955,1732,2088,4191,1496,1852,7737,3988, 620, // 6182
3214, 981,1242,3679,3360,1619,3680,1643,3293,2139,2452,1970,1719,3463,2168,7738, // 6198
3215,7739,7740,3361,1828,7741,1277,4476,1565,2047,7742,1636,3568,3093,7743, 869, // 6214
2839, 655,3811,3812,3094,3989,3000,3813,1310,3569,4477,7744,7745,7746,1733, 558, // 6230
4478,3681, 335,1549,3045,1756,4192,3682,1945,3464,1829,1291,1192, 470,2726,2107, // 6246
2793, 913,1054,3990,7747,1027,7748,3046,3991,4479, 982,2662,3362,3148,3465,3216, // 6262
3217,1946,2794,7749, 571,4480,7750,1830,7751,3570,2583,1523,2424,7752,2089, 984, // 6278
4481,3683,1959,7753,3684, 852, 923,2795,3466,3685, 969,1519, 999,2048,2320,1705, // 6294
7754,3095, 615,1662, 151, 597,3992,2405,2321,1049, 275,4482,3686,4193, 568,3687, // 6310
3571,2480,4194,3688,7755,2425,2270, 409,3218,7756,1566,2874,3467,1002, 769,2840, // 6326
194,2090,3149,3689,2222,3294,4195, 628,1505,7757,7758,1763,2177,3001,3993, 521, // 6342
1161,2584,1787,2203,2406,4483,3994,1625,4196,4197, 412, 42,3096, 464,7759,2632, // 6358
4484,3363,1760,1571,2875,3468,2530,1219,2204,3814,2633,2140,2368,4485,4486,3295, // 6374
1651,3364,3572,7760,7761,3573,2481,3469,7762,3690,7763,7764,2271,2091, 460,7765, // 6390
4487,7766,3002, 962, 588,3574, 289,3219,2634,1116, 52,7767,3047,1796,7768,7769, // 6406
7770,1467,7771,1598,1143,3691,4198,1984,1734,1067,4488,1280,3365, 465,4489,1572, // 6422
510,7772,1927,2241,1812,1644,3575,7773,4490,3692,7774,7775,2663,1573,1534,7776, // 6438
7777,4199, 536,1807,1761,3470,3815,3150,2635,7778,7779,7780,4491,3471,2915,1911, // 6454
2796,7781,3296,1122, 377,3220,7782, 360,7783,7784,4200,1529, 551,7785,2059,3693, // 6470
1769,2426,7786,2916,4201,3297,3097,2322,2108,2030,4492,1404, 136,1468,1479, 672, // 6486
1171,3221,2303, 271,3151,7787,2762,7788,2049, 678,2727, 865,1947,4493,7789,2013, // 6502
3995,2956,7790,2728,2223,1397,3048,3694,4494,4495,1735,2917,3366,3576,7791,3816, // 6518
509,2841,2453,2876,3817,7792,7793,3152,3153,4496,4202,2531,4497,2304,1166,1010, // 6534
552, 681,1887,7794,7795,2957,2958,3996,1287,1596,1861,3154, 358, 453, 736, 175, // 6550
478,1117, 905,1167,1097,7796,1853,1530,7797,1706,7798,2178,3472,2287,3695,3473, // 6566
3577,4203,2092,4204,7799,3367,1193,2482,4205,1458,2190,2205,1862,1888,1421,3298, // 6582
2918,3049,2179,3474, 595,2122,7800,3997,7801,7802,4206,1707,2636, 223,3696,1359, // 6598
751,3098, 183,3475,7803,2797,3003, 419,2369, 633, 704,3818,2389, 241,7804,7805, // 6614
7806, 838,3004,3697,2272,2763,2454,3819,1938,2050,3998,1309,3099,2242,1181,7807, // 6630
1136,2206,3820,2370,1446,4207,2305,4498,7808,7809,4208,1055,2605, 484,3698,7810, // 6646
3999, 625,4209,2273,3368,1499,4210,4000,7811,4001,4211,3222,2274,2275,3476,7812, // 6662
7813,2764, 808,2606,3699,3369,4002,4212,3100,2532, 526,3370,3821,4213, 955,7814, // 6678
1620,4214,2637,2427,7815,1429,3700,1669,1831, 994, 928,7816,3578,1260,7817,7818, // 6694
7819,1948,2288, 741,2919,1626,4215,2729,2455, 867,1184, 362,3371,1392,7820,7821, // 6710
4003,4216,1770,1736,3223,2920,4499,4500,1928,2698,1459,1158,7822,3050,3372,2877, // 6726
1292,1929,2506,2842,3701,1985,1187,2071,2014,2607,4217,7823,2566,2507,2169,3702, // 6742
2483,3299,7824,3703,4501,7825,7826, 666,1003,3005,1022,3579,4218,7827,4502,1813, // 6758
2253, 574,3822,1603, 295,1535, 705,3823,4219, 283, 858, 417,7828,7829,3224,4503, // 6774
4504,3051,1220,1889,1046,2276,2456,4004,1393,1599, 689,2567, 388,4220,7830,2484, // 6790
802,7831,2798,3824,2060,1405,2254,7832,4505,3825,2109,1052,1345,3225,1585,7833, // 6806
809,7834,7835,7836, 575,2730,3477, 956,1552,1469,1144,2323,7837,2324,1560,2457, // 6822
3580,3226,4005, 616,2207,3155,2180,2289,7838,1832,7839,3478,4506,7840,1319,3704, // 6838
3705,1211,3581,1023,3227,1293,2799,7841,7842,7843,3826, 607,2306,3827, 762,2878, // 6854
1439,4221,1360,7844,1485,3052,7845,4507,1038,4222,1450,2061,2638,4223,1379,4508, // 6870
2585,7846,7847,4224,1352,1414,2325,2921,1172,7848,7849,3828,3829,7850,1797,1451, // 6886
7851,7852,7853,7854,2922,4006,4007,2485,2346, 411,4008,4009,3582,3300,3101,4509, // 6902
1561,2664,1452,4010,1375,7855,7856, 47,2959, 316,7857,1406,1591,2923,3156,7858, // 6918
1025,2141,3102,3157, 354,2731, 884,2224,4225,2407, 508,3706, 726,3583, 996,2428, // 6934
3584, 729,7859, 392,2191,1453,4011,4510,3707,7860,7861,2458,3585,2608,1675,2800, // 6950
919,2347,2960,2348,1270,4511,4012, 73,7862,7863, 647,7864,3228,2843,2255,1550, // 6966
1346,3006,7865,1332, 883,3479,7866,7867,7868,7869,3301,2765,7870,1212, 831,1347, // 6982
4226,4512,2326,3830,1863,3053, 720,3831,4513,4514,3832,7871,4227,7872,7873,4515, // 6998
7874,7875,1798,4516,3708,2609,4517,3586,1645,2371,7876,7877,2924, 669,2208,2665, // 7014
2429,7878,2879,7879,7880,1028,3229,7881,4228,2408,7882,2256,1353,7883,7884,4518, // 7030
3158, 518,7885,4013,7886,4229,1960,7887,2142,4230,7888,7889,3007,2349,2350,3833, // 7046
516,1833,1454,4014,2699,4231,4519,2225,2610,1971,1129,3587,7890,2766,7891,2961, // 7062
1422, 577,1470,3008,1524,3373,7892,7893, 432,4232,3054,3480,7894,2586,1455,2508, // 7078
2226,1972,1175,7895,1020,2732,4015,3481,4520,7896,2733,7897,1743,1361,3055,3482, // 7094
2639,4016,4233,4521,2290, 895, 924,4234,2170, 331,2243,3056, 166,1627,3057,1098, // 7110
7898,1232,2880,2227,3374,4522, 657, 403,1196,2372, 542,3709,3375,1600,4235,3483, // 7126
7899,4523,2767,3230, 576, 530,1362,7900,4524,2533,2666,3710,4017,7901, 842,3834, // 7142
7902,2801,2031,1014,4018, 213,2700,3376, 665, 621,4236,7903,3711,2925,2430,7904, // 7158
2431,3302,3588,3377,7905,4237,2534,4238,4525,3589,1682,4239,3484,1380,7906, 724, // 7174
2277, 600,1670,7907,1337,1233,4526,3103,2244,7908,1621,4527,7909, 651,4240,7910, // 7190
1612,4241,2611,7911,2844,7912,2734,2307,3058,7913, 716,2459,3059, 174,1255,2701, // 7206
4019,3590, 548,1320,1398, 728,4020,1574,7914,1890,1197,3060,4021,7915,3061,3062, // 7222
3712,3591,3713, 747,7916, 635,4242,4528,7917,7918,7919,4243,7920,7921,4529,7922, // 7238
3378,4530,2432, 451,7923,3714,2535,2072,4244,2735,4245,4022,7924,1764,4531,7925, // 7254
4246, 350,7926,2278,2390,2486,7927,4247,4023,2245,1434,4024, 488,4532, 458,4248, // 7270
4025,3715, 771,1330,2391,3835,2568,3159,2159,2409,1553,2667,3160,4249,7928,2487, // 7286
2881,2612,1720,2702,4250,3379,4533,7929,2536,4251,7930,3231,4252,2768,7931,2015, // 7302
2736,7932,1155,1017,3716,3836,7933,3303,2308, 201,1864,4253,1430,7934,4026,7935, // 7318
7936,7937,7938,7939,4254,1604,7940, 414,1865, 371,2587,4534,4535,3485,2016,3104, // 7334
4536,1708, 960,4255, 887, 389,2171,1536,1663,1721,7941,2228,4027,2351,2926,1580, // 7350
7942,7943,7944,1744,7945,2537,4537,4538,7946,4539,7947,2073,7948,7949,3592,3380, // 7366
2882,4256,7950,4257,2640,3381,2802, 673,2703,2460, 709,3486,4028,3593,4258,7951, // 7382
1148, 502, 634,7952,7953,1204,4540,3594,1575,4541,2613,3717,7954,3718,3105, 948, // 7398
3232, 121,1745,3837,1110,7955,4259,3063,2509,3009,4029,3719,1151,1771,3838,1488, // 7414
4030,1986,7956,2433,3487,7957,7958,2093,7959,4260,3839,1213,1407,2803, 531,2737, // 7430
2538,3233,1011,1537,7960,2769,4261,3106,1061,7961,3720,3721,1866,2883,7962,2017, // 7446
120,4262,4263,2062,3595,3234,2309,3840,2668,3382,1954,4542,7963,7964,3488,1047, // 7462
2704,1266,7965,1368,4543,2845, 649,3383,3841,2539,2738,1102,2846,2669,7966,7967, // 7478
1999,7968,1111,3596,2962,7969,2488,3842,3597,2804,1854,3384,3722,7970,7971,3385, // 7494
2410,2884,3304,3235,3598,7972,2569,7973,3599,2805,4031,1460, 856,7974,3600,7975, // 7510
2885,2963,7976,2886,3843,7977,4264, 632,2510, 875,3844,1697,3845,2291,7978,7979, // 7526
4544,3010,1239, 580,4545,4265,7980, 914, 936,2074,1190,4032,1039,2123,7981,7982, // 7542
7983,3386,1473,7984,1354,4266,3846,7985,2172,3064,4033, 915,3305,4267,4268,3306, // 7558
1605,1834,7986,2739, 398,3601,4269,3847,4034, 328,1912,2847,4035,3848,1331,4270, // 7574
3011, 937,4271,7987,3602,4036,4037,3387,2160,4546,3388, 524, 742, 538,3065,1012, // 7590
7988,7989,3849,2461,7990, 658,1103, 225,3850,7991,7992,4547,7993,4548,7994,3236, // 7606
1243,7995,4038, 963,2246,4549,7996,2705,3603,3161,7997,7998,2588,2327,7999,4550, // 7622
8000,8001,8002,3489,3307, 957,3389,2540,2032,1930,2927,2462, 870,2018,3604,1746, // 7638
2770,2771,2434,2463,8003,3851,8004,3723,3107,3724,3490,3390,3725,8005,1179,3066, // 7654
8006,3162,2373,4272,3726,2541,3163,3108,2740,4039,8007,3391,1556,2542,2292, 977, // 7670
2887,2033,4040,1205,3392,8008,1765,3393,3164,2124,1271,1689, 714,4551,3491,8009, // 7686
2328,3852, 533,4273,3605,2181, 617,8010,2464,3308,3492,2310,8011,8012,3165,8013, // 7702
8014,3853,1987, 618, 427,2641,3493,3394,8015,8016,1244,1690,8017,2806,4274,4552, // 7718
8018,3494,8019,8020,2279,1576, 473,3606,4275,3395, 972,8021,3607,8022,3067,8023, // 7734
8024,4553,4554,8025,3727,4041,4042,8026, 153,4555, 356,8027,1891,2888,4276,2143, // 7750
408, 803,2352,8028,3854,8029,4277,1646,2570,2511,4556,4557,3855,8030,3856,4278, // 7766
8031,2411,3396, 752,8032,8033,1961,2964,8034, 746,3012,2465,8035,4279,3728, 698, // 7782
4558,1892,4280,3608,2543,4559,3609,3857,8036,3166,3397,8037,1823,1302,4043,2706, // 7798
3858,1973,4281,8038,4282,3167, 823,1303,1288,1236,2848,3495,4044,3398, 774,3859, // 7814
8039,1581,4560,1304,2849,3860,4561,8040,2435,2161,1083,3237,4283,4045,4284, 344, // 7830
1173, 288,2311, 454,1683,8041,8042,1461,4562,4046,2589,8043,8044,4563, 985, 894, // 7846
8045,3399,3168,8046,1913,2928,3729,1988,8047,2110,1974,8048,4047,8049,2571,1194, // 7862
425,8050,4564,3169,1245,3730,4285,8051,8052,2850,8053, 636,4565,1855,3861, 760, // 7878
1799,8054,4286,2209,1508,4566,4048,1893,1684,2293,8055,8056,8057,4287,4288,2210, // 7894
479,8058,8059, 832,8060,4049,2489,8061,2965,2490,3731, 990,3109, 627,1814,2642, // 7910
4289,1582,4290,2125,2111,3496,4567,8062, 799,4291,3170,8063,4568,2112,1737,3013, // 7926
1018, 543, 754,4292,3309,1676,4569,4570,4050,8064,1489,8065,3497,8066,2614,2889, // 7942
4051,8067,8068,2966,8069,8070,8071,8072,3171,4571,4572,2182,1722,8073,3238,3239, // 7958
1842,3610,1715, 481, 365,1975,1856,8074,8075,1962,2491,4573,8076,2126,3611,3240, // 7974
433,1894,2063,2075,8077, 602,2741,8078,8079,8080,8081,8082,3014,1628,3400,8083, // 7990
3172,4574,4052,2890,4575,2512,8084,2544,2772,8085,8086,8087,3310,4576,2891,8088, // 8006
4577,8089,2851,4578,4579,1221,2967,4053,2513,8090,8091,8092,1867,1989,8093,8094, // 8022
8095,1895,8096,8097,4580,1896,4054, 318,8098,2094,4055,4293,8099,8100, 485,8101, // 8038
938,3862, 553,2670, 116,8102,3863,3612,8103,3498,2671,2773,3401,3311,2807,8104, // 8054
3613,2929,4056,1747,2930,2968,8105,8106, 207,8107,8108,2672,4581,2514,8109,3015, // 8070
890,3614,3864,8110,1877,3732,3402,8111,2183,2353,3403,1652,8112,8113,8114, 941, // 8086
2294, 208,3499,4057,2019, 330,4294,3865,2892,2492,3733,4295,8115,8116,8117,8118, // 8102
]
| lgpl-2.1 |
huang1988519/WechatArticles | WechatArticles/WechatArticles/Transform/PresentTransiton.swift | 1 | 2816 | //
// PresentTransiton.swift
// WechatArticle
//
// Created by hwh on 15/11/12.
// Copyright © 2015年 hwh. All rights reserved.
//
import UIKit
//import Spring
public class PresentTransition : NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
var isPresenting = true
var duration = 0.7
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView()!
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
let toController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
var frame = transitionContext.finalFrameForViewController(toController!)
if isPresenting {
container.addSubview(fromView)
container.addSubview(toView)
fromView.backgroundColor = UIColor.clearColor()
frame.origin.x = CGRectGetWidth(frame)
toView.frame = frame
UIView.animateWithDuration(
duration,
delay: 0,
usingSpringWithDamping: 0.5,
initialSpringVelocity: 2,
options: .CurveEaseInOut,
animations: { () -> Void in
frame.origin.x = 0
toView.frame = frame
},
completion: nil)
}
else {
container.addSubview(toView)
container.addSubview(fromView)
UIView.animateWithDuration(
duration,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 2,
options: .CurveEaseIn,
animations: { () -> Void in
frame.origin.y = CGRectGetHeight(frame)
fromView.frame = frame
}, completion: nil)
}
delay(duration, closure: {
transitionContext.completeTransition(true)
})
}
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return duration
}
public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = true
return self
}
public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = false
return self
}
} | apache-2.0 |
practicalswift/swift | validation-test/compiler_crashers_fixed/26869-swift-printingdiagnosticconsumer-handlediagnostic.swift | 65 | 433 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
let v{{c n{a B{struct S{let d{{e={
| apache-2.0 |
ReduxKit/ReduxKitBond | ReduxKitBond/ReduxKitBond.swift | 1 | 1172 | //
// ReduxKitBond.swift
// ReduxKitBond
//
// Created by Karl Bowden on 20/12/2015.
// Copyright © 2015 ReduxKit. All rights reserved.
//
import Bond
import ReduxKit
/**
Uses `createStateStream` to create a `ReduxKit.Store<State>` using a
`Bond.Observable<State>` stream.
*/
public func createStore<State>(
reducer: ((State?, Action) -> State),
state: State? = nil)
-> Store<State> {
return createStreamStore(createStream, reducer: reducer, state: state)
}
/**
Accepts a `State` and returns `ReduxKit.StateStream<State>` using a
`Bond.Observable<State>` as the stream provider.
*/
public func createStream<State>(state: State) -> StateStream<State> {
let observable = Observable(state)
return StateStream(
dispatch: observable.next,
subscribe: { createDisposable(observable.observe($0)) },
getState: { observable.value })
}
/**
Accepts a `Bond.DisposableType` and returns it wrapped as a `ReduxDisposable`.
*/
public func createDisposable(disposable: DisposableType) -> ReduxDisposable {
return SimpleReduxDisposable(disposed: { disposable.isDisposed }, dispose: disposable.dispose)
}
| mit |
jfosterdavis/Charles | Charles/PieTimerView.swift | 1 | 3692 | //
// PieTimerView.swift
// Charles
//
// Created by Jacob Foster Davis on 5/27/17.
// Copyright © 2017 Zero Mu, LLC. All rights reserved.
//
import Foundation
import UIKit
//@IBDesignable
class PieTimerView:UIView
{
@IBInspectable var progressColor: UIColor = UIColor.darkGray
{
didSet {}
}
@IBInspectable var circleColor: UIColor = UIColor.gray
{
didSet { }
}
@IBInspectable var ringThickness: CGFloat = 1.0
{
didSet { }
}
@IBInspectable var fullPie: Bool = true
{
didSet { }
}
@IBInspectable var startAngle: Int = 0
{
didSet { }
}
@IBInspectable var endAngle: Int = 90
{
didSet { }
}
@IBInspectable var percentCrustVisible: CGFloat = 20
{
didSet { }
}
override func draw(_ rect: CGRect)
{
let dotPath = UIBezierPath(ovalIn: rect)
let shapeLayer = CAShapeLayer()
shapeLayer.path = dotPath.cgPath
shapeLayer.fillColor = circleColor.cgColor
layer.addSublayer(shapeLayer)
if percentCrustVisible > 100 {
percentCrustVisible = 100
} else if percentCrustVisible < 0 {
percentCrustVisible = 0
}
if fullPie {
ringThickness = min(bounds.size.width/2, bounds.size.height/2)
}
drawProgressRing(rect: rect)
}
internal func drawProgressRing(rect: CGRect)->()
{
let halfSize:CGFloat = max( bounds.size.width/2, bounds.size.height/2)
let desiredLineWidth:CGFloat = ringThickness * (1 - (percentCrustVisible/100)) // your desired value
let startAngleRads = CGFloat(Double(startAngle - 90) / 180.0 * Double.pi)
let endAngleRads = CGFloat(Double(endAngle - 90) / 180.0 * Double.pi)
let circlePath = UIBezierPath(
arcCenter: CGPoint(x: halfSize, y: halfSize),
radius: CGFloat( (halfSize - (desiredLineWidth/2))) , //make the slice 80% size of crust
startAngle: startAngleRads,
endAngle: endAngleRads,
clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
// let newFillColor = calculateColorDeviation(color1: objectiveRingColor, color2: progressRingColor)
// shapeLayer.fillColor = newFillColor.withAlphaComponent(1.0).cgColor
shapeLayer.fillColor = circleColor.cgColor
shapeLayer.strokeColor = progressColor.cgColor
shapeLayer.lineWidth = desiredLineWidth
layer.addSublayer(shapeLayer)
}
///sets the procession of the progress pie to the given angle
func setProgress(angle: Int) {
var desiredAngle = angle
if desiredAngle > 360 {
desiredAngle = 360
} else if desiredAngle < -360 {
desiredAngle = -360
}
endAngle = desiredAngle
self.setNeedsDisplay()
}
///sets the procession of the progress pie to the given percent of a full rotation
func setProgress(percent: Float) {
var desiredAngle = 360.0 * percent / 100.0
if desiredAngle > 360 {
desiredAngle = 360
} else if desiredAngle < -360 {
desiredAngle = -360
}
endAngle = Int(desiredAngle)
self.setNeedsDisplay()
}
///changes the color of the progress pie
func setProgressColor(color: UIColor) {
progressColor = color
self.setNeedsDisplay()
}
}
| apache-2.0 |
mlmc03/SwiftFM-DroidFM | SwiftFM/HanekeSwift/Haneke/UIButton+Haneke.swift | 3 | 11859 | //
// UIButton+Haneke.swift
// Haneke
//
// Created by Joan Romano on 10/1/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
public extension UIButton {
public var hnk_imageFormat : Format<UIImage> {
let bounds = self.bounds
assert(bounds.size.width > 0 && bounds.size.height > 0, "[\(Mirror(reflecting: self).description) \(#function)]: UIButton size is zero. Set its frame, call sizeToFit or force layout first. You can also set a custom format with a defined size if you don't want to force layout.")
let contentRect = self.contentRectForBounds(bounds)
let imageInsets = self.imageEdgeInsets
let scaleMode = self.contentHorizontalAlignment != UIControlContentHorizontalAlignment.Fill || self.contentVerticalAlignment != UIControlContentVerticalAlignment.Fill ? ImageResizer.ScaleMode.AspectFit : ImageResizer.ScaleMode.Fill
let imageSize = CGSizeMake(CGRectGetWidth(contentRect) - imageInsets.left - imageInsets.right, CGRectGetHeight(contentRect) - imageInsets.top - imageInsets.bottom)
return HanekeGlobals.UIKit.formatWithSize(imageSize, scaleMode: scaleMode, allowUpscaling: scaleMode == ImageResizer.ScaleMode.AspectFit ? false : true)
}
public func hnk_setImageFromURL(URL: NSURL, state: UIControlState = .Normal, placeholder: UIImage? = nil, format: Format<UIImage>? = nil, failure fail: ((NSError?) -> ())? = nil, success succeed: ((UIImage) -> ())? = nil) {
let fetcher = NetworkFetcher<UIImage>(URL: URL)
self.hnk_setImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, failure: fail, success: succeed)
}
public func hnk_setImage(image: UIImage, key: String, state: UIControlState = .Normal, placeholder: UIImage? = nil, format: Format<UIImage>? = nil, success succeed: ((UIImage) -> ())? = nil) {
let fetcher = SimpleFetcher<UIImage>(key: key, value: image)
self.hnk_setImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, success: succeed)
}
public func hnk_setImageFromFile(path: String, state: UIControlState = .Normal, placeholder: UIImage? = nil, format: Format<UIImage>? = nil, failure fail: ((NSError?) -> ())? = nil, success succeed: ((UIImage) -> ())? = nil) {
let fetcher = DiskFetcher<UIImage>(path: path)
self.hnk_setImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, failure: fail, success: succeed)
}
public func hnk_setImageFromFetcher(fetcher: Fetcher<UIImage>, state: UIControlState = .Normal, placeholder: UIImage? = nil, format: Format<UIImage>? = nil, failure fail: ((NSError?) -> ())? = nil, success succeed: ((UIImage) -> ())? = nil){
self.hnk_cancelSetImage()
self.hnk_imageFetcher = fetcher
let didSetImage = self.hnk_fetchImageForFetcher(fetcher, state: state, format : format, failure: fail, success: succeed)
if didSetImage { return }
if let placeholder = placeholder {
self.setImage(placeholder, forState: state)
}
}
public func hnk_cancelSetImage() {
if let fetcher = self.hnk_imageFetcher {
fetcher.cancelFetch()
self.hnk_imageFetcher = nil
}
}
// MARK: Internal Image
// See: http://stackoverflow.com/questions/25907421/associating-swift-things-with-nsobject-instances
var hnk_imageFetcher : Fetcher<UIImage>! {
get {
let wrapper = objc_getAssociatedObject(self, &HanekeGlobals.UIKit.SetImageFetcherKey) as? ObjectWrapper
let fetcher = wrapper?.value as? Fetcher<UIImage>
return fetcher
}
set (fetcher) {
var wrapper : ObjectWrapper?
if let fetcher = fetcher {
wrapper = ObjectWrapper(value: fetcher)
}
objc_setAssociatedObject(self, &HanekeGlobals.UIKit.SetImageFetcherKey, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func hnk_fetchImageForFetcher(fetcher : Fetcher<UIImage>, state : UIControlState = .Normal, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())?, success succeed : ((UIImage) -> ())?) -> Bool {
let format = format ?? self.hnk_imageFormat
let cache = Shared.imageCache
if cache.formats[format.name] == nil {
cache.addFormat(format)
}
var animated = false
let fetch = cache.fetch(fetcher: fetcher, formatName: format.name, failure: {[weak self] error in
if let strongSelf = self {
if strongSelf.hnk_shouldCancelImageForKey(fetcher.key) { return }
strongSelf.hnk_imageFetcher = nil
fail?(error)
}
}) { [weak self] image in
if let strongSelf = self {
if strongSelf.hnk_shouldCancelImageForKey(fetcher.key) { return }
strongSelf.hnk_setImage(image, state: state, animated: animated, success: succeed)
}
}
animated = true
return fetch.hasSucceeded
}
func hnk_setImage(image : UIImage, state : UIControlState, animated : Bool, success succeed : ((UIImage) -> ())?) {
self.hnk_imageFetcher = nil
if let succeed = succeed {
succeed(image)
} else if animated {
UIView.transitionWithView(self, duration: HanekeGlobals.UIKit.SetImageAnimationDuration, options: .TransitionCrossDissolve, animations: {
self.setImage(image, forState: state)
}, completion: nil)
} else {
self.setImage(image, forState: state)
}
}
func hnk_shouldCancelImageForKey(key:String) -> Bool {
if self.hnk_imageFetcher?.key == key { return false }
Log.debug("Cancelled set image for \((key as NSString).lastPathComponent)")
return true
}
// MARK: Background image
public var hnk_backgroundImageFormat : Format<UIImage> {
let bounds = self.bounds
assert(bounds.size.width > 0 && bounds.size.height > 0, "[\(Mirror(reflecting: self).description) \(#function)]: UIButton size is zero. Set its frame, call sizeToFit or force layout first. You can also set a custom format with a defined size if you don't want to force layout.")
let imageSize = self.backgroundRectForBounds(bounds).size
return HanekeGlobals.UIKit.formatWithSize(imageSize, scaleMode: .Fill)
}
public func hnk_setBackgroundImageFromURL(URL : NSURL, state : UIControlState = .Normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) {
let fetcher = NetworkFetcher<UIImage>(URL: URL)
self.hnk_setBackgroundImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, failure: fail, success: succeed)
}
public func hnk_setBackgroundImage(image : UIImage, key: String, state : UIControlState = .Normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, success succeed : ((UIImage) -> ())? = nil) {
let fetcher = SimpleFetcher<UIImage>(key: key, value: image)
self.hnk_setBackgroundImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, success: succeed)
}
public func hnk_setBackgroundImageFromFile(path: String, state : UIControlState = .Normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) {
let fetcher = DiskFetcher<UIImage>(path: path)
self.hnk_setBackgroundImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, failure: fail, success: succeed)
}
public func hnk_setBackgroundImageFromFetcher(fetcher : Fetcher<UIImage>, state : UIControlState = .Normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil){
self.hnk_cancelSetBackgroundImage()
self.hnk_backgroundImageFetcher = fetcher
let didSetImage = self.hnk_fetchBackgroundImageForFetcher(fetcher, state: state, format : format, failure: fail, success: succeed)
if didSetImage { return }
if let placeholder = placeholder {
self.setBackgroundImage(placeholder, forState: state)
}
}
public func hnk_cancelSetBackgroundImage() {
if let fetcher = self.hnk_backgroundImageFetcher {
fetcher.cancelFetch()
self.hnk_backgroundImageFetcher = nil
}
}
// MARK: Internal Background image
// See: http://stackoverflow.com/questions/25907421/associating-swift-things-with-nsobject-instances
var hnk_backgroundImageFetcher : Fetcher<UIImage>! {
get {
let wrapper = objc_getAssociatedObject(self, &HanekeGlobals.UIKit.SetBackgroundImageFetcherKey) as? ObjectWrapper
let fetcher = wrapper?.value as? Fetcher<UIImage>
return fetcher
}
set (fetcher) {
var wrapper : ObjectWrapper?
if let fetcher = fetcher {
wrapper = ObjectWrapper(value: fetcher)
}
objc_setAssociatedObject(self, &HanekeGlobals.UIKit.SetBackgroundImageFetcherKey, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func hnk_fetchBackgroundImageForFetcher(fetcher: Fetcher<UIImage>, state: UIControlState = .Normal, format: Format<UIImage>? = nil, failure fail: ((NSError?) -> ())?, success succeed : ((UIImage) -> ())?) -> Bool {
let format = format ?? self.hnk_backgroundImageFormat
let cache = Shared.imageCache
if cache.formats[format.name] == nil {
cache.addFormat(format)
}
var animated = false
let fetch = cache.fetch(fetcher: fetcher, formatName: format.name, failure: {[weak self] error in
if let strongSelf = self {
if strongSelf.hnk_shouldCancelBackgroundImageForKey(fetcher.key) { return }
strongSelf.hnk_backgroundImageFetcher = nil
fail?(error)
}
}) { [weak self] image in
if let strongSelf = self {
if strongSelf.hnk_shouldCancelBackgroundImageForKey(fetcher.key) { return }
strongSelf.hnk_setBackgroundImage(image, state: state, animated: animated, success: succeed)
}
}
animated = true
return fetch.hasSucceeded
}
func hnk_setBackgroundImage(image: UIImage, state: UIControlState, animated: Bool, success succeed: ((UIImage) -> ())?) {
self.hnk_backgroundImageFetcher = nil
if let succeed = succeed {
succeed(image)
} else if animated {
UIView.transitionWithView(self, duration: HanekeGlobals.UIKit.SetImageAnimationDuration, options: .TransitionCrossDissolve, animations: {
self.setBackgroundImage(image, forState: state)
}, completion: nil)
} else {
self.setBackgroundImage(image, forState: state)
}
}
func hnk_shouldCancelBackgroundImageForKey(key: String) -> Bool {
if self.hnk_backgroundImageFetcher?.key == key { return false }
Log.debug("Cancelled set background image for \((key as NSString).lastPathComponent)")
return true
}
}
| apache-2.0 |
ataka/cwmealticket | CWMealTicket/CWHttpClient.swift | 1 | 1426 | //
// CWMHttpClient.swift
// CWMealTicket
//
// Created by 安宅 正之 on 2015/02/25.
// Copyright (c) 2015年 Masayuki Ataka. All rights reserved.
//
import UIKit
class CWHttpClient: NSObject {
private let roomId :String = ""
private let userToken :String = ""
private let baseUrl :String = "https://api.chatwork.com/v1"
private let messageFormat :String = "/rooms/%@/messages"
func sendMessage(message :String)
{
let base :NSURL = NSURL(string: baseUrl)!
let path :String = String(format: messageFormat, arguments: [roomId])
let requestUrl :NSURL = base.URLByAppendingPathComponent(path)
var request = NSMutableURLRequest(URL: requestUrl)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue(userToken, forHTTPHeaderField: "X-ChatWorkToken")
request.HTTPMethod = "POST"
request.HTTPBody = "body=\(message)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
var task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {data, response, error in
if (error == nil) {
var result = NSString(data: data, encoding: NSUTF8StringEncoding)!
println(result)
} else {
println(error)
}
})
task.resume()
}
}
| mit |
Jpadilla1/react-native-ios-charts | RNiOSCharts/RNScatterChart.swift | 1 | 855 | //
// RNPieChart.swift
// PoliRank
//
// Created by Jose Padilla on 2/8/16.
// Copyright © 2016 Facebook. All rights reserved.
//
import Charts
import SwiftyJSON
@objc(RNScatterChart)
class RNScatterChart : ScatterChartView {
override init(frame: CGRect) {
super.init(frame: frame);
self.frame = frame;
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented");
}
func setConfig(_ config: String!) {
setBarLineChartViewBaseProps(config);
var labels: [String] = [];
var json: JSON = nil;
if let data = config.data(using: String.Encoding.utf8) {
json = JSON(data: data);
};
if json["labels"].exists() {
labels = json["labels"].arrayValue.map({$0.stringValue});
}
self.data = getScatterData(labels, json: json);
}
}
| mit |
alimysoyang/CommunicationDebugger | CommunicationDebugger/AYHTCPClientsManage.swift | 1 | 3015 | //
// AYHTCPClientsManage.swift
// CommunicationDebugger
//
// Created by alimysoyang on 15/11/23.
// Copyright © 2015年 alimysoyang. All rights reserved.
//
import Foundation
/**
* TCP服务端管理接入的TCP客户端的队列数据管理器
*/
class AYHTCPClientsManage: NSObject
{
// MARK: - properties
private var tcpClients:AYHSynchronizedArray<AYHTCPClientSocket> = AYHSynchronizedArray<AYHTCPClientSocket>();
var tcpClientSocket:AYHTCPClientSocket? {
get {
if (self.tcpClients.count == 0)
{
return nil;
}
return self.tcpClients.last;
}
}
var isEmpty:Bool {
get { return self.tcpClients.isEmpty; }
}
// MARK: - life cycle
override init()
{
super.init();
}
deinit
{
}
// MARK: - public methods
func addClientSocket(newSocket:GCDAsyncSocket)
{
let tcpClientSocket:AYHTCPClientSocket = AYHTCPClientSocket(clientSocket: newSocket);
var isExists:Bool = false;
for index in 0..<self.tcpClients.count
{
let item:AYHTCPClientSocket = self.tcpClients[index];
if let itemSocket = item.socket where itemSocket === newSocket
{
isExists = true;
break;
}
}
if (!isExists)
{
self.tcpClients.append(tcpClientSocket, completionClosure: { () -> Void in
});
}
}
func removeAtSocket(socket:GCDAsyncSocket)
{
var index:Int = self.tcpClients.count - 1;
while (index >= 0)
{
let item:AYHTCPClientSocket = self.tcpClients[index];
if let itemSocket = item.socket where itemSocket === socket
{
self.tcpClients.removeAtIndex(index);
break;
}
index--;
}
}
func removeClientSocketAtIndex(index:Int)
{
if (index < 0 || index > self.tcpClients.count)
{
return;
}
self.tcpClients.removeAtIndex(index);
}
func removeAtClientSocket(clientSocket:AYHTCPClientSocket?)
{
guard let lTcpClientSocket = clientSocket else
{
return;
}
var foundIndex:Int = -1;
for index in 0..<self.tcpClients.count
{
let item:AYHTCPClientSocket = self.tcpClients[index];
if let itemSocket = item.socket, removeSocket = lTcpClientSocket.socket
{
if (itemSocket === removeSocket)
{
foundIndex = index;
break;
}
}
}
if (foundIndex >= 0)
{
self.tcpClients.removeAtIndex(foundIndex);
}
}
func removeAll()
{
self.tcpClients.removeAll({ () -> Void in
});
}
} | mit |
Jnosh/swift | test/decl/protocol/indirectly_recursive_requirement.swift | 14 | 725 | // RUN: %target-typecheck-verify-swift
protocol Incrementable {
func successor() -> Self
}
protocol _ForwardIndex {
associatedtype Distance = MyInt // expected-note{{declared here}}
}
protocol ForwardIndex : _ForwardIndex {
}
protocol _BidirectionalIndex : _ForwardIndex {
func predecessor() -> Self
}
protocol BidirectionalIndex : ForwardIndex, _BidirectionalIndex {
}
protocol _RandomAccessIndex : _BidirectionalIndex {
associatedtype Distance // expected-warning{{redeclaration of associated type 'Distance}}
}
protocol RandomAccessIndex
: BidirectionalIndex, _RandomAccessIndex {}
struct MyInt : RandomAccessIndex
{
typealias Distance = MyInt
func predecessor() -> MyInt {
return self
}
}
| apache-2.0 |
adanilyak/ShareScreenshot | ShareScreenshot/Classes/Helpers/UITools.swift | 1 | 2298 | //
// UITools.swift
// ShareScreenshot
//
// Created by Alexander Danilyak on 19/07/2017.
//
import UIKit
extension Bundle {
// Shortcut for accessing Pod's bundle
@nonobjc
static func podBundle(for anyClass: AnyClass = UITools.self) -> Bundle? {
let rootBundle = Bundle(for: anyClass)
guard let url = rootBundle.url(forResource: "ShareScreenshot", withExtension: "bundle") else {
return nil
}
return Bundle(url: url)
}
}
// All UI helpers
class UITools {
// Initial Nav Controller
@nonobjc
static var shareScreenshotNavigation: UINavigationController? {
return UIStoryboard(name: "ShareScreenshot", bundle: Bundle.podBundle()).instantiateInitialViewController() as? UINavigationController
}
}
extension UIColor {
// Shortcut for creating UIColor with a hex string like this "ff00ff"
convenience init(hexString: String) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
// Default Apple's blue color
@nonobjc
static var standardBlue: UIColor = UIColor(hexString: "007AFF")
}
extension String {
// Shortcut for localized string
static func localized(key: String) -> String {
guard let bundle = Bundle.podBundle() else {
return key
}
return NSLocalizedString(key,
tableName: "Localizable",
bundle: bundle,
value: "",
comment: "")
}
}
| mit |
tudormunteanu/UITableViewSwift | TableViewTests/TableViewTests.swift | 1 | 922 | //
// TableViewTests.swift
// TableViewTests
//
// Created by Tudor Munteanu on 25/03/15.
// Copyright (c) 2015 http://mowowstudios.com. All rights reserved.
//
import UIKit
import XCTest
class TableViewTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
LearningSwift2/LearningApps | SimpleLocalNotification/SimpleLocalNotification/AppDelegate.swift | 1 | 800 | //
// AppDelegate.swift
// SimpleLocalNotification
//
// Created by Phil Wright on 3/21/16.
// Copyright © 2016 Touchopia, LLC. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound, .Badge], categories: nil)
application.registerUserNotificationSettings(settings)
return true
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
print("Got the notification")
}
}
| apache-2.0 |
cam-hop/APIUtility | RxSwiftFluxDemo/Carthage/Checkouts/RxSwiftFlux/RxSwiftFlux/Action.swift | 2 | 485 | //
// Action.swift
// RxSwiftFlux
//
// Created by DUONG VANHOP on 2017/06/14.
// Copyright © 2017年 DUONG VANHOP. All rights reserved.
//
import Foundation
public protocol Action {
associatedtype Payload
associatedtype ErrorType
func invoke(_ dispatcher: Dispatcher)
}
public class ActionCreator {
public static let dispatcher = DefaultDispatcher.shared
public class func invoke<T: Action>(action: T) {
action.invoke(self.dispatcher)
}
}
| mit |
danielbyon/Convert | Sources/Convert/Energy.swift | 1 | 3216 | //
// Energy.swift
// Convert
//
// Copyright © 2017 Daniel Byon
//
// 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.
//
import Foundation
import CoreGraphics
public struct Energy: Convertible {
public enum Unit: Double {
case joule = 1.0
case kilojoule = 1_000.0
case gramcalorie = 4.184
case kilocalorie = 4_184.0
case watthour = 3_600.0
case kilowattHour = 360_000_0.0
case btu = 1_055.06
case footPound = 1.355_82
}
public let value: Double
public let unit: Unit
public init(value: Double, unit: Unit) {
self.value = value
self.unit = unit
}
}
public extension Double {
var joule: Energy {
return Energy(value: self, unit: .joule)
}
var kilojoule: Energy {
return Energy(value: self, unit: .kilojoule)
}
var gramcalorie: Energy {
return Energy(value: self, unit: .gramcalorie)
}
var kilocalorie: Energy {
return Energy(value: self, unit: .kilocalorie)
}
var watthour: Energy {
return Energy(value: self, unit: .watthour)
}
var kilowatthour: Energy {
return Energy(value: self, unit: .kilowattHour)
}
var btu: Energy {
return Energy(value: self, unit: .btu)
}
var footPound: Energy {
return Energy(value: self, unit: .footPound)
}
}
public extension CGFloat {
var joule: Energy {
return Energy(value: Double(self), unit: .joule)
}
var kilojoule: Energy {
return Energy(value: Double(self), unit: .kilojoule)
}
var gramcalorie: Energy {
return Energy(value: Double(self), unit: .gramcalorie)
}
var kilocalorie: Energy {
return Energy(value: Double(self), unit: .kilocalorie)
}
var watthour: Energy {
return Energy(value: Double(self), unit: .watthour)
}
var kilowatthour: Energy {
return Energy(value: Double(self), unit: .kilowattHour)
}
var btu: Energy {
return Energy(value: Double(self), unit: .btu)
}
var footPound: Energy {
return Energy(value: Double(self), unit: .footPound)
}
}
| mit |
ishkawa/APIKit | Sources/APIKit/Combine/Combine.swift | 1 | 4058 | #if canImport(Combine)
import Foundation
import Combine
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public struct SessionTaskPublisher<Request: APIKit.Request>: Publisher {
/// The kind of values published by this publisher.
public typealias Output = Request.Response
/// The kind of errors this publisher might publish.
public typealias Failure = SessionTaskError
private let request: Request
private let session: Session
private let callbackQueue: CallbackQueue?
public init(request: Request, session: Session, callbackQueue: CallbackQueue?) {
self.request = request
self.session = session
self.callbackQueue = callbackQueue
}
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == SessionTaskPublisher.Failure, S.Input == SessionTaskPublisher.Output {
subscriber.receive(subscription: SessionTaskSubscription(request: request,
session: session,
callbackQueue: callbackQueue,
downstream: subscriber))
}
private final class SessionTaskSubscription<Request: APIKit.Request, Downstream: Subscriber>: Subscription where Request.Response == Downstream.Input, Downstream.Failure == Failure {
private let request: Request
private let session: Session
private let callbackQueue: CallbackQueue?
private var downstream: Downstream?
private var task: SessionTask?
init(request: Request, session: Session, callbackQueue: CallbackQueue?, downstream: Downstream) {
self.request = request
self.session = session
self.callbackQueue = callbackQueue
self.downstream = downstream
}
func request(_ demand: Subscribers.Demand) {
assert(demand > 0)
guard let downstream = self.downstream else { return }
self.downstream = nil
task = session.send(request, callbackQueue: callbackQueue) { result in
switch result {
case .success(let response):
_ = downstream.receive(response)
downstream.receive(completion: .finished)
case .failure(let error):
downstream.receive(completion: .failure(error))
}
}
}
func cancel() {
task?.cancel()
downstream = nil
}
}
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public extension Session {
/// Calls `sessionTaskPublisher(for:callbackQueue:)` of `Session.shared`.
///
/// - parameter request: The request to be sent.
/// - parameter callbackQueue: The queue where the handler runs. If this parameters is `nil`, default `callbackQueue` of `Session` will be used.
/// - returns: A publisher that wraps a session task for the request.
static func sessionTaskPublisher<Request: APIKit.Request>(for request: Request, callbackQueue: CallbackQueue? = nil) -> SessionTaskPublisher<Request> {
return SessionTaskPublisher(request: request, session: .shared, callbackQueue: callbackQueue)
}
/// Returns a publisher that wraps a session task for the request.
///
/// The publisher publishes `Request.Response` when the task completes, or terminates if the task fails with an error.
/// - parameter request: The request to be sent.
/// - parameter callbackQueue: The queue where the handler runs. If this parameters is `nil`, default `callbackQueue` of `Session` will be used.
/// - returns: A publisher that wraps a session task for the request.
func sessionTaskPublisher<Request: APIKit.Request>(for request: Request, callbackQueue: CallbackQueue? = nil) -> SessionTaskPublisher<Request> {
return SessionTaskPublisher(request: request, session: self, callbackQueue: callbackQueue)
}
}
#endif
| mit |
darrarski/DRNet | DRNet-Example-iOS/DRNet-Example-iOS/UI/Example2ViewController.swift | 1 | 8375 | //
// Example2ViewController.swift
// DRNet-Example-iOS
//
// Created by Dariusz Rybicki on 10/11/14.
// Copyright (c) 2014 Darrarski. All rights reserved.
//
import UIKit
import DRNet
class Example2ViewController: ImageTextViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Example 2"
initMenu()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
runExample()
}
func runExample() {
// remove all cached responses in iOS shared URL cache, to assure DRNet caching works
NSURLCache.sharedURLCache().removeAllCachedResponses()
exampleInProgress = true
label.text = "UIImageView extension with remote image loader that supports caching and offline mode."
imageView.loadImageFromURL(
NSURL(string: "http://placekitten.com/g/1024/512")!,
onLoadFromCacheSuccess: { [weak self] (source: DRNet.URLCacheResponse.Source) -> Void in
let sourceString: String = {
switch source {
case .Unknown:
return "unknown"
case .MemoryCache:
return "memory"
case .DiskCache:
return "disk"
}
}()
self?.logText("Successfully loaded from \(sourceString) cache.")
return
},
onLoadFromCacheFailure: { [weak self] (errors) -> Void in
self?.logText("Error(s) occured when loading from cache:")
self?.logErrors(errors)
},
onLoadFromNetworkSuccess: { [weak self] () -> Void in
self?.logText("Successfully loaded from network.")
return
},
onLoadFromNetworkFailure: { [weak self] (errors) -> Void in
self?.logText("Error(s) occured when loading from network:")
self?.logErrors(errors)
},
onComplete: { [weak self] () -> Void in
self?.logText("Done.\n\nTap on image to open options menu.")
self?.exampleInProgress = false
}
)
}
// MARK: - Menu
private var imageViewTapGestureRecognizer: UITapGestureRecognizer?
private func initMenu() {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: "showMenu")
imageView.addGestureRecognizer(gestureRecognizer)
imageView.userInteractionEnabled = true
}
func showMenu() {
if exampleInProgress {
return
}
let alertController = UIAlertController(title: "Options", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
alertController.addAction(
UIAlertAction(
title: "Reload image",
style: UIAlertActionStyle.Default,
handler: { [weak self] (action) -> Void in
self?.runExample()
return
}
)
)
alertController.addAction(
UIAlertAction(
title: "Clear cache",
style: UIAlertActionStyle.Destructive,
handler: { (action) -> Void in
ImageViewCacheProvider.removeAllCachedResponses()
}
)
)
alertController.addAction(
UIAlertAction(
title: "Cancel",
style: UIAlertActionStyle.Cancel,
handler: nil
)
)
self.presentViewController(alertController, animated: true, completion: nil)
}
// MARK: - Helpers
private var exampleInProgress = false
private func logErrors(errors: [NSError]) {
dispatch_async(dispatch_get_main_queue(), { [weak self] () -> Void in
var output: String = "\n\n---\n\n".join(
errors.map({ (error) in
var message: String = error.localizedDescription
if let failureReason = error.localizedFailureReason {
message += ", " + failureReason
}
if countElements(error.debugDescription) > 0 {
message += ", " + error.debugDescription
}
return message
})
)
if let sself = self {
if let currentText = sself.label.text {
sself.label.text = currentText + "\n\n" + output
}
else {
sself.label.text = output
}
}
})
}
private func logText(text: String) {
dispatch_async(dispatch_get_main_queue(), { [weak self] () -> Void in
if let sself = self {
if let currentText = sself.label.text {
sself.label.text = currentText + "\n\n" + text
}
else {
sself.label.text = text
}
}
})
}
}
private let ImageViewNetworkProvider = DRNet.URLSessionProvider(session: NSURLSession.sharedSession())
private let ImageViewCacheProvider = DRNet.URLCacheProvider(
memoryCapacity: .Limit(bytes: 10 * 1024 * 1024),
diskCapacity: .Limit(bytes: 10 * 1024 * 1024),
diskPath: "ImageViewCache"
)
extension UIImageView {
func loadImageFromURL(url: NSURL,
onLoadFromCacheSuccess: (source: DRNet.URLCacheResponse.Source) -> Void,
onLoadFromCacheFailure: (errors: [NSError]) -> Void,
onLoadFromNetworkSuccess: () -> Void,
onLoadFromNetworkFailure: (errors: [NSError]) -> Void,
onComplete: () -> Void) {
let request = DRNet.Request(
method: .GET,
url: url,
headers: DRNet.RequestStandardHeaders(
[
"Accept": "image/*"
]
),
parameters: nil
)
let operation = DRNet.Operation(
validators: [
DRNet.ResponseDataValidator(),
DRNet.ResponseStatusCodeValidator(200..<299)
],
dataDeserializer: DRNet.ResponseImageDeserializer(),
handlerClosure: { [weak self] (operation, request, task, response, deserializedData, errors) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self?.image = deserializedData as? UIImage
return
})
}
)
var loadedFromCache = false
operation.perfromRequest(request,
usingProvider: ImageViewCacheProvider,
onError: { (response, deserializedData, errors, shouldHandle) -> Void in
shouldHandle.memory = false
onLoadFromCacheFailure(errors: errors)
},
onSuccess: { (response, deserializedData, shouldHandle) -> Void in
loadedFromCache = true
onLoadFromCacheSuccess(source: (response as DRNet.URLCacheResponse).source)
},
onComplete: { (response, deserializedData, errors) -> Void in
operation.perfromRequest(request,
usingProvider: ImageViewNetworkProvider,
onError: { (response, deserializedData, errors, shouldHandle) -> Void in
shouldHandle.memory = !loadedFromCache
onLoadFromNetworkFailure(errors: errors)
},
onSuccess: { (response, deserializedData, shouldHandle) -> Void in
ImageViewCacheProvider.saveResponse(response, forRequest: request)
onLoadFromNetworkSuccess()
},
onComplete: { (response, deserializedData, errors) -> Void in
onComplete()
}
)
}
)
}
} | mit |
wikimedia/wikipedia-ios | Wikipedia/Code/TalkPageFindInPageState.swift | 1 | 2069 | import Foundation
final class TalkPageFindInPageState {
// MARK: - Properties
let searchController = TalkPageFindInPageSearchController()
var keyboardBar: FindAndReplaceKeyboardBar?
var selectedIndex: Int = -1 {
didSet {
updateView()
}
}
var selectedMatch: TalkPageFindInPageSearchController.SearchResult? {
guard matches.indices.contains(selectedIndex) else {
return nil
}
return matches[selectedIndex]
}
var matches: [TalkPageFindInPageSearchController.SearchResult] = [] {
didSet {
updateView()
}
}
// MARK: - Public
/// Next result, looping to start of matches if at end
func next() {
guard !matches.isEmpty else {
return
}
guard selectedIndex < matches.count - 1 else {
selectedIndex = 0
return
}
selectedIndex += 1
}
/// Previous result, looping to end of matches if at beginning
func previous() {
guard !matches.isEmpty else {
return
}
guard selectedIndex > 0 else {
selectedIndex = matches.count - 1
return
}
selectedIndex -= 1
}
func reset(_ topics: [TalkPageCellViewModel]) {
matches = []
selectedIndex = -1
keyboardBar?.reset()
topics.forEach {
$0.highlightText = nil
$0.activeHighlightResult = nil
}
}
func search(term: String, in topics: [TalkPageCellViewModel], traitCollection: UITraitCollection, theme: Theme) {
selectedIndex = -1
matches = searchController.search(term: term, in: topics, traitCollection: traitCollection, theme: theme)
topics.forEach {
$0.highlightText = matches.isEmpty ? nil : term
$0.activeHighlightResult = nil
}
}
// MARK: - Private
private func updateView() {
keyboardBar?.updateMatchCounts(index: selectedIndex, total: UInt(matches.count))
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/13705-swift-typebase-gettypeofmember.swift | 11 | 270 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
struct S {
protocol d : a< {
{
}
typealias e = b
protocol b {
}
{
}
{
}
}
{
}
func a<f : a
| mit |
pelotoncycle/Peloton-UIColors | Example/Peloton-UIColors/AppDelegate.swift | 1 | 451 | //
// AppDelegate.swift
// Peloton-UIColors
//
// Created by Ryan Fitzgerald on 07/20/2016.
// Copyright (c) 2016 Ryan Fitzgerald. All rights reserved.
//
import UIKit
@UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? = nil) -> Bool {
return true
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/08575-resolvetypedecl.swift | 11 | 248 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class d<T where S<T> : AnyObject
protocol A {
class A : d
}
let a {
enum B : A
| mit |
22377832/swiftdemo | WeixinDemo/WeixinDemo/AppDelegate.swift | 1 | 2169 | //
// AppDelegate.swift
// WeixinDemo
//
// Created by adults on 2017/3/31.
// Copyright © 2017年 adults. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
idomizrachi/Regen | regen/Dependencies/Stencil/Errors.swift | 1 | 2549 | public class TemplateDoesNotExist: Error, CustomStringConvertible {
let templateNames: [String]
let loader: Loader?
public init(templateNames: [String], loader: Loader? = nil) {
self.templateNames = templateNames
self.loader = loader
}
public var description: String {
let templates = templateNames.joined(separator: ", ")
if let loader = loader {
return "Template named `\(templates)` does not exist in loader \(loader)"
}
return "Template named `\(templates)` does not exist. No loaders found"
}
}
public struct TemplateSyntaxError: Error, Equatable, CustomStringConvertible {
public let reason: String
public var description: String { return reason }
public internal(set) var token: Token?
public internal(set) var stackTrace: [Token]
public var templateName: String? { return token?.sourceMap.filename }
var allTokens: [Token] {
return stackTrace + (token.map { [$0] } ?? [])
}
public init(reason: String, token: Token? = nil, stackTrace: [Token] = []) {
self.reason = reason
self.stackTrace = stackTrace
self.token = token
}
public init(_ description: String) {
self.init(reason: description)
}
}
extension Error {
func withToken(_ token: Token?) -> Error {
if var error = self as? TemplateSyntaxError {
error.token = error.token ?? token
return error
} else {
return TemplateSyntaxError(reason: "\(self)", token: token)
}
}
}
public protocol ErrorReporter: AnyObject {
func renderError(_ error: Error) -> String
}
open class SimpleErrorReporter: ErrorReporter {
open func renderError(_ error: Error) -> String {
guard let templateError = error as? TemplateSyntaxError else { return error.localizedDescription }
func describe(token: Token) -> String {
let templateName = token.sourceMap.filename ?? ""
let location = token.sourceMap.location
let highlight = """
\(String(Array(repeating: " ", count: location.lineOffset)))\
^\(String(Array(repeating: "~", count: max(token.contents.count - 1, 0))))
"""
return """
\(templateName)\(location.lineNumber):\(location.lineOffset): error: \(templateError.reason)
\(location.content)
\(highlight)
"""
}
var descriptions = templateError.stackTrace.reduce([]) { $0 + [describe(token: $1)] }
let description = templateError.token.map(describe(token:)) ?? templateError.reason
descriptions.append(description)
return descriptions.joined(separator: "\n")
}
}
| mit |
manavgabhawala/swift | test/IRGen/objc_generic_protocol_conformance.swift | 1 | 916 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -Xllvm -new-mangling-for-tests -emit-silgen -primary-file %s -import-objc-header %S/Inputs/objc_generic_protocol_conformance.h | %FileCheck --check-prefix=SIL %s
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -Xllvm -new-mangling-for-tests -emit-ir -primary-file %s -import-objc-header %S/Inputs/objc_generic_protocol_conformance.h | %FileCheck --check-prefix=IR %s
// REQUIRES: objc_interop
protocol P {
func foo()
}
extension Foo: P {}
// SIL-LABEL: sil hidden [transparent] [thunk] @_T0So3FooCyxG33objc_generic_protocol_conformance1PADs9AnyObjectRzlAdEP3fooyyFTW {{.*}} @pseudogeneric
// IR-LABEL: define hidden swiftcc void @_T0So3FooCyxG33objc_generic_protocol_conformance1PADs9AnyObjectRzlAdEP3fooyyFTW(%TSo3FooC** noalias nocapture swiftself dereferenceable({{4|8}}), %swift.type*{{( %Self)?}}, i8**{{( %SelfWitnessTable)?}})
| apache-2.0 |
material-components/material-components-ios | catalog/MDCCatalog/MDCCatalogComponentsController.swift | 2 | 17406 | // Copyright 2015-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import CatalogByConvention
import MaterialCatalog
import MaterialComponents.MaterialFlexibleHeader
import MaterialComponents.MaterialLibraryInfo
import MaterialComponents.MaterialRipple
import MaterialComponents.MaterialShadowElevations
import MaterialComponents.MaterialShadowLayer
import MaterialComponents.MaterialThemes
import MaterialComponents.MaterialTypography
import MaterialComponents.MaterialIcons_ic_arrow_back
class MDCCatalogComponentsController: UICollectionViewController,
UICollectionViewDelegateFlowLayout, MDCRippleTouchControllerDelegate
{
fileprivate struct Constants {
static let headerScrollThreshold: CGFloat = 30
static let inset: CGFloat = 16
static let menuTopVerticalSpacing: CGFloat = 38
static let logoWidthHeight: CGFloat = 30
static let menuButtonWidthHeight: CGFloat = 24
static let spacing: CGFloat = 1
}
fileprivate lazy var headerViewController = MDCFlexibleHeaderViewController()
private lazy var rippleController: MDCRippleTouchController = {
let controller = MDCRippleTouchController()
controller.delegate = self
controller.shouldProcessRippleWithScrollViewGestures = false
return controller
}()
private lazy var logo: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
return imageView
}()
private lazy var menuButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
let dotsImage = MDCIcons.imageFor_ic_more_horiz()?.withRenderingMode(.alwaysTemplate)
button.setImage(dotsImage, for: .normal)
button.adjustsImageWhenHighlighted = false
button.accessibilityLabel = "Menu"
button.accessibilityHint = "Opens catalog configuration options."
// Without this compiler version check, the build fails on Xcode versions <11.4 with the error:
// "Use of undeclared type 'UIPointerInteractionDelegate'"
// Ideally, we would be able to tie this to an iOS version rather than a compiler version, but
// such a solution does not seem to be available for Swift.
#if compiler(>=5.2)
if #available(iOS 13.4, *) {
let interaction = UIPointerInteraction(delegate: self)
button.addInteraction(interaction)
}
#endif
return button
}()
private let node: CBCNode
private lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.adjustsFontSizeToFitWidth = true
return titleLabel
}()
private var logoLeftPaddingConstraint: NSLayoutConstraint?
private var menuButtonRightPaddingConstraint: NSLayoutConstraint?
private var menuTopPaddingConstraint: NSLayoutConstraint?
init(collectionViewLayout ignoredLayout: UICollectionViewLayout, node: CBCNode) {
self.node = node
let layout = UICollectionViewFlowLayout()
let sectionInset: CGFloat = Constants.spacing
layout.sectionInset = UIEdgeInsets(
top: sectionInset,
left: sectionInset,
bottom: sectionInset,
right: sectionInset)
layout.minimumInteritemSpacing = Constants.spacing
layout.minimumLineSpacing = Constants.spacing
super.init(collectionViewLayout: layout)
title = "Material Components for iOS"
addChild(headerViewController)
headerViewController.isTopLayoutGuideAdjustmentEnabled = true
headerViewController.inferTopSafeAreaInsetFromViewController = true
headerViewController.headerView.minMaxHeightIncludesSafeArea = false
headerViewController.headerView.maximumHeight = 128
headerViewController.headerView.minimumHeight = 56
collectionView?.register(
MDCCatalogCollectionViewCell.self,
forCellWithReuseIdentifier: "MDCCatalogCollectionViewCell")
collectionView?.backgroundColor = AppTheme.containerScheme.colorScheme.backgroundColor
MDCIcons.ic_arrow_backUseNewStyle(true)
NotificationCenter.default.addObserver(
self,
selector: #selector(self.themeDidChange),
name: AppTheme.didChangeGlobalThemeNotificationName,
object: nil)
}
@objc func themeDidChange(notification: NSNotification) {
let colorScheme = AppTheme.containerScheme.colorScheme
headerViewController.headerView.backgroundColor = colorScheme.primaryColor
setNeedsStatusBarAppearanceUpdate()
titleLabel.textColor = colorScheme.onPrimaryColor
menuButton.tintColor = colorScheme.onPrimaryColor
collectionView?.collectionViewLayout.invalidateLayout()
collectionView?.reloadData()
}
convenience init(node: CBCNode) {
self.init(collectionViewLayout: UICollectionViewLayout(), node: node)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
rippleController.addRipple(to: self.collectionView!)
let containerView = UIView(frame: headerViewController.headerView.bounds)
containerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
titleLabel.text = title!
titleLabel.textColor = AppTheme.containerScheme.colorScheme.onPrimaryColor
titleLabel.textAlignment = .center
titleLabel.font = AppTheme.containerScheme.typographyScheme.headline6
titleLabel.sizeToFit()
let titleInsets = UIEdgeInsets(
top: 0,
left: Constants.inset,
bottom: Constants.inset,
right: Constants.inset)
let titleSize = titleLabel.sizeThatFits(containerView.bounds.size)
containerView.addSubview(titleLabel)
headerViewController.headerView.addSubview(containerView)
headerViewController.headerView.forwardTouchEvents(for: containerView)
containerView.addSubview(logo)
let colorScheme = AppTheme.containerScheme.colorScheme
let image = MDCDrawImage(
CGRect(
x: 0,
y: 0,
width: Constants.logoWidthHeight,
height: Constants.logoWidthHeight),
{ MDCCatalogDrawMDCLogoLight($0, $1) },
colorScheme)
logo.image = image
menuButton.addTarget(
self.navigationController,
action: #selector(navigationController?.presentMenu),
for: .touchUpInside)
menuButton.tintColor = colorScheme.onPrimaryColor
containerView.addSubview(menuButton)
setupFlexibleHeaderContentConstraints()
constrainLabel(
label: titleLabel,
containerView: containerView,
insets: titleInsets,
height: titleSize.height)
headerViewController.headerView.backgroundColor = colorScheme.primaryColor
headerViewController.headerView.trackingScrollView = collectionView
headerViewController.headerView.setShadowLayer(MDCShadowLayer()) { (layer, intensity) in
let shadowLayer = layer as? MDCShadowLayer
CATransaction.begin()
CATransaction.setDisableActions(true)
shadowLayer!.elevation = ShadowElevation(intensity * ShadowElevation.appBar.rawValue)
CATransaction.commit()
}
view.addSubview(headerViewController.view)
headerViewController.didMove(toParent: self)
collectionView?.accessibilityIdentifier = "componentList"
collectionView?.contentInsetAdjustmentBehavior = .always
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionView?.collectionViewLayout.invalidateLayout()
navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func willAnimateRotation(
to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval
) {
collectionView?.collectionViewLayout.invalidateLayout()
}
override var childForStatusBarStyle: UIViewController? {
return headerViewController
}
override var childForStatusBarHidden: UIViewController? {
return headerViewController
}
@available(iOS 11, *)
override func viewSafeAreaInsetsDidChange() {
// Re-constraint the title label to account for changes in safeAreaInsets's left and right.
logoLeftPaddingConstraint?.constant = Constants.inset + view.safeAreaInsets.left
menuButtonRightPaddingConstraint?.constant = -1 * (Constants.inset + view.safeAreaInsets.right)
menuTopPaddingConstraint?.constant = Constants.inset + view.safeAreaInsets.top
}
func setupFlexibleHeaderContentConstraints() {
logoLeftPaddingConstraint = NSLayoutConstraint(
item: logo,
attribute: .leading,
relatedBy: .equal,
toItem: logo.superview,
attribute: .leading,
multiplier: 1,
constant: Constants.inset)
logoLeftPaddingConstraint?.isActive = true
menuButtonRightPaddingConstraint = NSLayoutConstraint(
item: menuButton,
attribute: .trailing,
relatedBy: .equal,
toItem: menuButton.superview,
attribute: .trailing,
multiplier: 1,
constant: -1 * Constants.inset)
menuButtonRightPaddingConstraint?.isActive = true
menuTopPaddingConstraint = NSLayoutConstraint(
item: menuButton,
attribute: .top,
relatedBy: .equal,
toItem: menuButton.superview,
attribute: .top,
multiplier: 1,
constant: Constants.menuTopVerticalSpacing)
menuTopPaddingConstraint?.isActive = true
NSLayoutConstraint(
item: logo,
attribute: .centerY,
relatedBy: .equal,
toItem: menuButton,
attribute: .centerY,
multiplier: 1,
constant: 0
).isActive = true
NSLayoutConstraint(
item: logo,
attribute: .width,
relatedBy: .equal,
toItem: logo,
attribute: .height,
multiplier: 1,
constant: 0
).isActive = true
NSLayoutConstraint(
item: logo,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: Constants.logoWidthHeight
).isActive = true
NSLayoutConstraint(
item: menuButton,
attribute: .width,
relatedBy: .equal,
toItem: menuButton,
attribute: .height,
multiplier: 1,
constant: 0
).isActive = true
NSLayoutConstraint(
item: menuButton,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: Constants.menuButtonWidthHeight
).isActive = true
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(
_ collectionView: UICollectionView,
numberOfItemsInSection section: Int
) -> Int {
return node.children.count
}
// MARK: MDCRippleTouchControllerDelegate
func rippleTouchController(
_ rippleTouchController: MDCRippleTouchController,
shouldProcessRippleTouchesAtTouchLocation location: CGPoint
) -> Bool {
return self.collectionView?.indexPathForItem(at: location) != nil
}
func rippleTouchController(
_ rippleTouchController: MDCRippleTouchController,
rippleViewAtTouchLocation location: CGPoint
) -> MDCRippleView? {
if let indexPath = self.collectionView?.indexPathForItem(at: location) {
let cell = self.collectionView?.cellForItem(at: indexPath)
return MDCRippleView.injectedRippleView(for: cell!)
}
return MDCRippleView()
}
// MARK: UICollectionViewDelegate
override func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
let cell =
collectionView.dequeueReusableCell(
withReuseIdentifier: "MDCCatalogCollectionViewCell",
for: indexPath)
cell.backgroundColor = AppTheme.containerScheme.colorScheme.backgroundColor
let componentName = node.children[indexPath.row].title
if let catalogCell = cell as? MDCCatalogCollectionViewCell {
catalogCell.populateView(componentName)
}
// Ensure that ripple animations aren't recycled.
MDCRippleView.injectedRippleView(for: view).cancelAllRipples(animated: false, completion: nil)
return cell
}
func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath
) -> CGSize {
let dividerWidth: CGFloat = 1
var safeInsets: CGFloat = 0
safeInsets = view.safeAreaInsets.left + view.safeAreaInsets.right
var cellWidthHeight: CGFloat
// iPhones have 2 columns in portrait and 3 in landscape
if UIDevice.current.userInterfaceIdiom == .phone {
cellWidthHeight = (view.frame.size.width - 3 * dividerWidth - safeInsets) / 2
if view.frame.size.width > view.frame.size.height {
cellWidthHeight = (view.frame.size.width - 4 * dividerWidth - safeInsets) / 3
}
} else {
// iPads have 4 columns in portrait, and 5 in landscape
cellWidthHeight = (view.frame.size.width - 5 * dividerWidth - safeInsets) / 4
if view.frame.size.width > view.frame.size.height {
cellWidthHeight = (view.frame.size.width - 6 * dividerWidth - safeInsets) / 5
}
}
return CGSize(width: cellWidthHeight, height: cellWidthHeight)
}
override func collectionView(
_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath
) {
let node = self.node.children[indexPath.row]
var vc: UIViewController
if node.isExample() {
vc = node.createExampleViewController()
} else {
vc = MDCNodeListViewController(node: node)
}
self.navigationController?.setMenuBarButton(for: vc)
self.navigationController?.pushViewController(vc, animated: true)
}
// MARK: Private
func constrainLabel(
label: UILabel,
containerView: UIView,
insets: UIEdgeInsets,
height: CGFloat
) {
NSLayoutConstraint(
item: label,
attribute: .leading,
relatedBy: .equal,
toItem: logo,
attribute: .trailing,
multiplier: 1.0,
constant: insets.left
).isActive = true
NSLayoutConstraint(
item: label,
attribute: .trailing,
relatedBy: .equal,
toItem: menuButton,
attribute: .leading,
multiplier: 1.0,
constant: -insets.right
).isActive = true
NSLayoutConstraint(
item: label,
attribute: .bottom,
relatedBy: .equal,
toItem: containerView,
attribute: .bottom,
multiplier: 1.0,
constant: -insets.bottom
).isActive = true
NSLayoutConstraint(
item: label,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: height
).isActive = true
}
}
// Without this compiler version check, the build fails on Xcode versions <11.4 with the error:
// "Use of undeclared type 'UIPointerInteractionDelegate'"
// Ideally, we would be able to tie this to an iOS version rather than a compiler version, but such
// a solution does not seem to be available for Swift.
#if compiler(>=5.2)
@available(iOS 13.4, *)
extension MDCCatalogComponentsController: UIPointerInteractionDelegate {
@available(iOS 13.4, *)
func pointerInteraction(
_ interaction: UIPointerInteraction,
styleFor region: UIPointerRegion
) -> UIPointerStyle? {
guard let interactionView = interaction.view else {
return nil
}
let targetedPreview = UITargetedPreview(view: interactionView)
let pointerStyle = UIPointerStyle(effect: .highlight(targetedPreview))
return pointerStyle
}
}
#endif
// UIScrollViewDelegate
extension MDCCatalogComponentsController {
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == headerViewController.headerView.trackingScrollView {
self.headerViewController.headerView.trackingScrollDidScroll()
}
}
override func scrollViewDidEndDragging(
_ scrollView: UIScrollView,
willDecelerate decelerate: Bool
) {
let headerView = headerViewController.headerView
if scrollView == headerView.trackingScrollView {
headerView.trackingScrollDidEndDraggingWillDecelerate(decelerate)
}
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView == headerViewController.headerView.trackingScrollView {
self.headerViewController.headerView.trackingScrollDidEndDecelerating()
}
}
override func scrollViewWillEndDragging(
_ scrollView: UIScrollView,
withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>
) {
let headerView = headerViewController.headerView
if scrollView == headerView.trackingScrollView {
headerView.trackingScrollWillEndDragging(
withVelocity: velocity,
targetContentOffset: targetContentOffset)
}
}
}
| apache-2.0 |
EstefaniaGilVaquero/ciceIOS | AppDataPickerView/AppDataPickerView/ViewController.swift | 1 | 1388 | //
// ViewController.swift
// AppDataPickerView
//
// Created by stefy83 on 24/05/16.
// Copyright © 2016 CICE. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
//MARK: - IBOUTLET
@IBOutlet weak var myDateLBL: UILabel!
@IBOutlet weak var myDateTF: UITextField!
//MARK: - IBACTION
@IBAction func showPickerDateEditing(myTextField: UITextField) {
//Fase de creacion del pickerDate
let pickerDateView = UIDatePicker()
pickerDateView.datePickerMode = UIDatePickerMode.DateAndTime
myTextField.inputView = pickerDateView
pickerDateView.addTarget(self, action: #selector(ViewController.datePickerValueChanged(_:)), forControlEvents: .ValueChanged)
}
//MARK: - UTILS
func datePickerValueChanged(sender: UIDatePicker){
let dateFormatter = NSDateFormatter()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
}
| apache-2.0 |
hffmnn/Swiftz | SwiftzTests/StringExtSpec.swift | 1 | 389 | //
// StringExtSpec.swift
// swiftz
//
// Created by Robert Widmann on 1/19/15.
// Copyright (c) 2015 TypeLift. All rights reserved.
//
import XCTest
import Swiftz
class StringExtSpec : XCTestCase {
func testStringExt() {
// some testing is done with properties in TestTests.swift
XCTAssert(String.unlines("foo\nbar\n".lines()) == "foo\nbar\n", "lines / unlines a string")
}
}
| bsd-3-clause |
jsslai/Action | Carthage/Checkouts/RxSwift/RxCocoa/iOS/UITextView+Rx.swift | 1 | 3468 | //
// UITextView+Rx.swift
// RxCocoa
//
// Created by Yuta ToKoRo on 7/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
extension UITextView {
/**
Factory method that enables subclasses to implement their own `delegate`.
- returns: Instance of delegate proxy that wraps `delegate`.
*/
public override func createRxDelegateProxy() -> RxScrollViewDelegateProxy {
return RxTextViewDelegateProxy(parentObject: self)
}
}
extension Reactive where Base: UITextView {
/**
Reactive wrapper for `text` property.
*/
public var text: ControlProperty<String> {
let source: Observable<String> = Observable.deferred { [weak textView = self.base] in
let text = textView?.text ?? ""
let textChanged = textView?.textStorage
// This project uses text storage notifications because
// that's the only way to catch autocorrect changes
// in all cases. Other suggestions are welcome.
.rx.didProcessEditingRangeChangeInLength
// This observe on is here because text storage
// will emit event while process is not completely done,
// so rebinding a value will cause an exception to be thrown.
.observeOn(MainScheduler.asyncInstance)
.map { _ in
return textView?.textStorage.string ?? ""
}
?? Observable.empty()
return textChanged
.startWith(text)
}
let bindingObserver = UIBindingObserver(UIElement: self.base) { (textView, text: String) in
// This check is important because setting text value always clears control state
// including marked text selection which is imporant for proper input
// when IME input method is used.
if textView.text != text {
textView.text = text
}
}
return ControlProperty(values: source, valueSink: bindingObserver)
}
/**
Reactive wrapper for `delegate` message.
*/
public var didBeginEditing: ControlEvent<()> {
return ControlEvent<()>(events: self.delegate.methodInvoked(#selector(UITextViewDelegate.textViewDidBeginEditing(_:)))
.map { a in
return ()
})
}
/**
Reactive wrapper for `delegate` message.
*/
public var didEndEditing: ControlEvent<()> {
return ControlEvent<()>(events: self.delegate.methodInvoked(#selector(UITextViewDelegate.textViewDidEndEditing(_:)))
.map { a in
return ()
})
}
/**
Reactive wrapper for `delegate` message.
*/
public var didChange: ControlEvent<()> {
return ControlEvent<()>(events: self.delegate.methodInvoked(#selector(UITextViewDelegate.textViewDidChange(_:)))
.map { a in
return ()
})
}
/**
Reactive wrapper for `delegate` message.
*/
public var didChangeSelection: ControlEvent<()> {
return ControlEvent<()>(events: self.delegate.methodInvoked(#selector(UITextViewDelegate.textViewDidChangeSelection(_:)))
.map { a in
return ()
})
}
}
#endif
| mit |
mrommel/MiRoRecipeBook | MiRoRecipeBook/MiRoRecipeBook/Presentation/Recipes/RecipesWireframe.swift | 1 | 1467 | //
// RecipesWireframe.swift
// MiRoRecipeBook
//
// Created by Michael Rommel on 12.12.16.
// Copyright © 2016 MiRo Soft. All rights reserved.
//
import UIKit
class RecipesWireframe: CommonWireframe {
fileprivate let kRecipesStoryboardName = "Recipes"
func getRecipesInterface() -> RecipeCollectionViewController {
//let recipesTableViewController = RecipesTableViewController.instantiate(fromStoryboard: kRecipesStoryboardName)
let recipesTableViewController = RecipeCollectionViewController.instantiate(fromStoryboard: kRecipesStoryboardName)
return recipesTableViewController
}
func presentDetail(forRecipe recipe: Recipe?) {
let recipesDetailViewController = RecipeDetailViewController.instantiate(fromStoryboard: kRecipesStoryboardName)
recipesDetailViewController.recipe = recipe
let menuButton = UIButton(type: .custom)
menuButton.setImage(UIImage(named: "menu-alt-24.png"), for: .normal)
menuButton.frame = CGRect(x: 10, y: 0, width: 42, height: 42)
menuButton.addTarget(self, action: #selector(goBack), for: .touchUpInside)
recipesDetailViewController.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: menuButton)
let targetNavigationController = UINavigationController(rootViewController: recipesDetailViewController)
UIApplication.shared.topMostViewController()?.present(targetNavigationController, animated: false, completion: nil)
}
}
| gpl-3.0 |
apple/swift | validation-test/compiler_crashers_fixed/00767-swift-constraints-constraintsystem-solve.swift | 65 | 563 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
let f = {
}
struct A {
var b {
let b {
class func c<h : A.init<T>, y)
func b.count], f: Hashable> (m: c<()
let h : b {
protocol d = [1](")
protocol A : a {
func a<d
| apache-2.0 |
SuperAwesomeLTD/sa-mobile-sdk-ios | Pod/Classes/UI/Video/VideoViewController.swift | 1 | 7931 | //
// VideoViewController.swift
// SuperAwesome
//
// Created by Gabriel Coman on 17/12/2018.
//
import UIKit
@objc(SAVideoViewController) class VideoViewController: UIViewController, Injectable {
private lazy var controller: AdControllerType = dependencies.resolve()
private lazy var orientationProvider: OrientationProviderType = dependencies.resolve()
private lazy var stringProvider: StringProviderType = dependencies.resolve()
private var videoPlayer: AwesomeVideoPlayer!
private var chrome: AdSocialVideoPlayerControlsView!
private var logger: LoggerType = dependencies.resolve(param: VideoViewController.self)
private let config: AdConfig
private let control: VideoPlayerControls = VideoPlayerController()
private let videoEvents: VideoEvents
private var completed: Bool = false
private var closeDialog: UIAlertController?
init(adResponse: AdResponse, callback: AdEventCallback?, config: AdConfig) {
self.config = config
videoEvents = VideoEvents(adResponse)
super.init(nibName: nil, bundle: nil)
self.controller.adResponse = adResponse
self.controller.callback = callback
self.controller.parentalGateEnabled = config.isParentalGateEnabled
self.controller.bumperPageEnabled = config.isBumperPageEnabled
videoEvents.delegate = self
}
override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent }
override var prefersStatusBarHidden: Bool { true }
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { .fade }
@available(iOS 11.0, *)
override var prefersHomeIndicatorAutoHidden: Bool { true }
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
orientationProvider.findSupportedOrientations(config.orientation, super.supportedInterfaceOrientations)
}
required init?(coder aDecoder: NSCoder) {
fatalError("Don't use this externally!")
}
override func viewDidLoad() {
super.viewDidLoad()
// initial view setup
view.backgroundColor = .black
view.layoutMargins = .zero
// setup video player
videoPlayer = AwesomeVideoPlayer()
videoPlayer.setControls(controller: control)
videoPlayer.layoutMargins = .zero
videoPlayer.setDelegate(delegate: self)
view.addSubview(videoPlayer)
videoPlayer.bind(
toTheEdgesOf: view,
insets: UIEdgeInsets(top: 0.0, left: 0.0, bottom: Padding.s.negative, right: 0.0)
)
// setup chrome
chrome = AdSocialVideoPlayerControlsView(smallClick: config.showSmallClick,
showSafeAdLogo: config.showSafeAdLogo)
chrome.layoutMargins = .zero
chrome.setCloseAction { [weak self] in
self?.closeAction()
}
chrome.setClickAction { [weak self] in
self?.clickAction()
}
chrome.setPadlockAction { [weak self] in
self?.controller.handleSafeAdTap()
}
chrome.setVolumeAction { [weak self] in
self?.volumeAction()
}
videoPlayer.setControlsView(
controllerView: chrome,
insets: UIEdgeInsets(top: 0.0, left: 0.0, bottom: Padding.s.negative, right: 0.0)
)
if let avPlayer = videoPlayer.getAVPlayer() {
let muted = config.shouldMuteOnStart
avPlayer.isMuted = muted
chrome.setMuted(muted)
if muted {
chrome.makeVolumeButtonVisible()
}
}
if config.closeButtonState == .visibleImmediately {
chrome.makeCloseButtonVisible()
}
// play ad
if let url = controller.filePathUrl {
control.play(url: url)
}
// register notification for foreground
// swiftlint:disable discarded_notification_center_observer
NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] notification in
self?.willEnterForeground(notification)
}
// register notification for background
// swiftlint:disable discarded_notification_center_observer
NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weak self] _ in
self?.didEnterBackground()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
control.start()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
control.pause()
super.viewWillDisappear(animated)
}
deinit {
NotificationCenter.default.removeObserver(self,
name: UIApplication.willEnterForegroundNotification,
object: nil)
NotificationCenter.default.removeObserver(self,
name: UIApplication.didEnterBackgroundNotification,
object: nil)
}
private func didEnterBackground() {
closeDialog?.dismiss(animated: true)
closeDialog = nil
}
@objc
func willEnterForeground(_ notification: Notification) {
control.start()
}
private func clickAction() {
controller.handleAdTapForVast()
}
private func closeAction() {
if config.shouldShowCloseWarning && !completed {
control.pause()
closeDialog = showQuestionDialog(title: stringProvider.closeDialogTitle,
message: stringProvider.closeDialogMessage,
yesTitle: stringProvider.closeDialogCloseAction,
noTitle: stringProvider.closeDialogResumeAction) { [weak self] in
self?.close()
} noAction: { [weak self] in
self?.control.start()
}
} else {
close()
}
}
private func volumeAction() {
if let avPlayer = videoPlayer.getAVPlayer() {
let toggle = !avPlayer.isMuted
avPlayer.isMuted = toggle
chrome.setMuted(toggle)
}
}
private func close() {
videoPlayer.destroy()
dismiss(animated: true) { [weak self] in
self?.controller.close()
}
}
}
extension VideoViewController: VideoEventsDelegate {
func hasBeenVisible() {
controller.triggerViewableImpression()
controller.triggerDwellTime()
if config.closeButtonState == .visibleWithDelay {
chrome.makeCloseButtonVisible()
}
}
}
extension VideoViewController: VideoPlayerDelegate {
func didPrepare(videoPlayer: VideoPlayer, time: Int, duration: Int) {
videoEvents.prepare(player: videoPlayer, time: time, duration: duration)
controller.adShown()
}
func didUpdateTime(videoPlayer: VideoPlayer, time: Int, duration: Int) {
videoEvents.time(player: videoPlayer, time: time, duration: duration)
}
func didComplete(videoPlayer: VideoPlayer, time: Int, duration: Int) {
completed = true
videoEvents.complete(player: videoPlayer, time: time, duration: duration)
chrome.makeCloseButtonVisible()
controller.adEnded()
if config.shouldCloseAtEnd {
closeAction()
}
}
func didError(videoPlayer: VideoPlayer, error: Error, time: Int, duration: Int) {
videoEvents.error(player: videoPlayer, time: time, duration: duration)
controller.adFailedToShow()
closeAction()
}
}
| lgpl-3.0 |
sora0077/OctoKit | OctoKitTests/OctoKitTests.swift | 1 | 902 | //
// OctoKitTests.swift
// OctoKitTests
//
// Created by 林達也 on 2015/06/07.
// Copyright (c) 2015年 林達也. All rights reserved.
//
import UIKit
import XCTest
class OctoKitTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Display information/Control graphic draw order/GraphicDrawOrderViewController.swift | 1 | 3997 | //
// Copyright 2016 Esri.
//
// 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.
import UIKit
import ArcGIS
class GraphicDrawOrderViewController: UIViewController {
@IBOutlet var mapView: AGSMapView!
@IBOutlet var buttons: [UIButton]!
var map: AGSMap!
private var graphicsOverlay = AGSGraphicsOverlay()
private var graphics = [AGSGraphic]()
private var drawIndex: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["GraphicDrawOrderViewController"]
// create an instance of a map with ESRI streets basemap
self.map = AGSMap(basemapStyle: .arcGISStreets)
// assign map to the map view
self.mapView.map = self.map
// add the graphics overlay to the map view
self.mapView.graphicsOverlays.add(self.graphicsOverlay)
// add the graphics to the overlay
self.addGraphics()
// set map scale
let mapScale: Double = 53500
// initial viewpoint
self.mapView.setViewpointCenter(AGSPoint(x: -13148960, y: 4000040, spatialReference: .webMercator()), scale: mapScale)
// restricting map scale to preserve the graphics overlapping
self.map.minScale = mapScale
self.map.maxScale = mapScale
}
private func addGraphics() {
// starting x and y
let x: Double = -13149000
let y: Double = 4e6
// distance between the graphics
let delta: Double = 100
// blue marker
var geometry = AGSPoint(x: x, y: y, spatialReference: .webMercator())
var symbol = AGSPictureMarkerSymbol(image: UIImage(named: "BlueMarker")!)
var graphic = AGSGraphic(geometry: geometry, symbol: symbol, attributes: nil)
graphics.append(graphic)
// red marker
geometry = AGSPoint(x: x + delta, y: y, spatialReference: .webMercator())
symbol = AGSPictureMarkerSymbol(image: UIImage(named: "RedMarker2")!)
graphic = AGSGraphic(geometry: geometry, symbol: symbol, attributes: nil)
graphics.append(graphic)
// green marker
geometry = AGSPoint(x: x, y: y + delta, spatialReference: .webMercator())
symbol = AGSPictureMarkerSymbol(image: UIImage(named: "GreenMarker")!)
graphic = AGSGraphic(geometry: geometry, symbol: symbol, attributes: nil)
graphics.append(graphic)
// Violet marker
geometry = AGSPoint(x: x + delta, y: y + delta, spatialReference: .webMercator())
symbol = AGSPictureMarkerSymbol(image: UIImage(named: "VioletMarker")!)
graphic = AGSGraphic(geometry: geometry, symbol: symbol, attributes: nil)
graphics.append(graphic)
// add the graphics to the overlay
self.graphicsOverlay.graphics.addObjects(from: graphics)
}
// MARK: - Actions
@IBAction func buttonAction(_ sender: UIButton) {
// increment draw index by 1 and assign as the zIndex for the respective graphic
self.drawIndex += 1
// the button's tag value specifies which graphic to re-index
// for example, a button tag value of 1 will move self.graphics[1] - the red marker
graphics[sender.tag].zIndex = self.drawIndex
}
}
| apache-2.0 |
cnoon/swift-compiler-crashes | crashes-duplicates/15249-swift-sourcemanager-getmessage.swift | 11 | 214 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
p(
var {
if true {
protocol a {
class
case ,
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/19036-no-stacktrace.swift | 11 | 220 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B {
var b = (
let {
let a {
{
}
class
case ,
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/16004-swift-sourcemanager-getmessage.swift | 11 | 236 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let start = ( ) {
if true {
func f
{
for {
struct A {
class
case ,
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/15373-swift-sourcemanager-getmessage.swift | 11 | 241 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
return m( {
func f {
[ {
for
var : {
protocol a {
deinit {
class
case ,
| mit |
yuhaifei123/WeiBo_Swift | WeiBo_Swift/WeiBo_Swift/class/tool(工具)/loading(下拉刷新)/Home_RefreshControl.swift | 1 | 4091 | //
// Home_RefreshControl.swift
// WeiBo_Swift
//
// Created by 虞海飞 on 2017/1/18.
// Copyright © 2017年 虞海飞. All rights reserved.
//
import UIKit
class Home_RefreshControl: UIRefreshControl {
override init() {
super.init();
setupUI();
}
/// 页面设置
private func setupUI(){
self.addSubview(homeRefreshView);
homeRefreshView.snp.makeConstraints { (make) in
make.size.equalTo(CGSize(width: 170, height:70.0 ));
make.center.equalTo(self);
};
//kvc 添加观察者
self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.new, context: nil);
}
/// 结束刷新
override func endRefreshing() {
super.endRefreshing();
homeRefreshView.stopLoadingAnimation();
loadingfloat = false;
}
//判断值,判断箭头方向
private var arrow : Bool = false;
//判断是不是转转圈圈
private var loadingfloat : Bool = false;
///
/// kvc 监听方法
/// - Parameters:
/// - keyPath: <#keyPath description#>
/// - object: <#object description#>
/// - change: <#change description#>
/// - context: <#context description#>
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
//控件的 Y
let viewY = self.frame.origin.y;
if viewY >= 0 {
return;
}
// 下啦到一定程度,程序自己刷新是
if isRefreshing == true && loadingfloat == false{
homeRefreshView.startLoadingAnimation();
loadingfloat = true;
}
if viewY >= -50 && arrow == false {
homeRefreshView.rotaionArrowItem();
print("翻转");
arrow = true;
}
else if viewY < -50 && arrow == true {
homeRefreshView.rotaionArrowItem();
print("开始翻转");
arrow = false;
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//对象销毁,会调用这个方法。防止循环引用
deinit {
removeObserver(self, forKeyPath: "frame");
}
private lazy var homeRefreshView : HomeRefreshView = HomeRefreshView.refreshView();
}
/// 子类,与 HomeRefreshView.xib 相同
class HomeRefreshView : UIView {
/// 箭头
@IBOutlet weak var imageView_ArrowItem: UIImageView!
/// 圆圆圈
@IBOutlet weak var imageView_Loading: UIImageView!
/// 圆圆圈view
@IBOutlet weak var view_LoadView: UIView!
///选择箭头
func rotaionArrowItem(){
UIView.animate(withDuration: 0.2) {
//动画效果
//transform 形变后的 frame
self.imageView_ArrowItem.transform = self.imageView_ArrowItem.transform.rotated(by: CGFloat(M_PI));
}
}
/// 开始转圈圈动画
func startLoadingAnimation() {
//把前面的view 隐藏了
self.view_LoadView.isHidden = true;
let rotateAni = CABasicAnimation(keyPath: "transform.rotation")
rotateAni.fromValue = 0.0
rotateAni.toValue = M_PI * 2.0
rotateAni.duration = 10
rotateAni.repeatCount = MAXFLOAT
//不停的转动
rotateAni.isRemovedOnCompletion = false;
imageView_Loading.layer.add(rotateAni, forKey: nil);
}
/// 停止转圈圈动画
func stopLoadingAnimation(){
self.view_LoadView.isHidden = false;
//停止动画
imageView_Loading.stopAnimating();
}
class func refreshView() -> HomeRefreshView{
//得到最后一个
return Bundle.main.loadNibNamed("HomeRefreshView", owner: nil, options: nil)?.last as! HomeRefreshView;
}
}
| apache-2.0 |
exponent/exponent | ios/versioned/sdk43/ExpoModulesCore/Swift/Methods/AnyArgumentType.swift | 2 | 1177 |
struct AnyArgumentType: CustomDebugStringConvertible {
let baseType: Any.Type
let typeName: String
private let castHelper: (Any) -> AnyMethodArgument?
private let canCastHelper: (Any) -> Bool
init<T: AnyMethodArgument>(_ baseType: T.Type) {
self.baseType = baseType
self.typeName = String(describing: baseType)
self.castHelper = { $0 as? T }
// handle class metatypes separately in order to allow T.self != base.
if baseType is AnyClass {
self.canCastHelper = { x in
sequence(
first: Mirror(reflecting: x), next: { $0.superclassMirror }
)
.contains { $0.subjectType == baseType }
}
} else {
self.canCastHelper = { $0 is T }
}
}
func cast<T>(_ object: T) -> AnyMethodArgument? {
return castHelper(object)
}
func canCast<T>(_ object: T) -> Bool {
return canCastHelper(object)
}
func canCastToType<T>(_ type: T.Type) -> Bool {
return baseType is T.Type
}
func castWrappedType<T>(_ type: T.Type) -> T? {
return baseType as? T
}
// MARK: CustomDebugStringConvertible
var debugDescription: String {
return String(describing: baseType)
}
}
| bsd-3-clause |
DarielChen/DemoCode | iOS动画指南/iOS动画指南 - 5.下雪的粒子效果、帧动画/2.penguinRun/penguinRun/ViewController.swift | 1 | 4647 | //
// ViewController.swift
// penguinRun
//
// Created by Dariel on 16/7/23.
// Copyright © 2016年 Dariel. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// 添加走路动画的图片
var walkFrames = [
UIImage(named: "walk01.png")!,
UIImage(named: "walk02.png")!,
UIImage(named: "walk03.png")!,
UIImage(named: "walk04.png")!
]
// 添加滑行的图片
var slideFrames = [
UIImage(named: "slide01.png")!,
UIImage(named: "slide02.png")!,
UIImage(named: "slide01.png")!
]
let animationDuration = 1.0
let penguinWidth: CGFloat = 108.0
let penguinHeight: CGFloat = 96.0
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(bgView)
view.addSubview(leftButton)
view.addSubview(rightButton)
view.addSubview(slideButton)
view.addSubview(penguinView)
// 设置好需要走动动画
loadWalkAnimation()
}
// 走路的动画
func loadWalkAnimation() {
// 将需要添加帧动画的图片添加进去
penguinView.animationImages = walkFrames
// 设置播放时间
penguinView.animationDuration = animationDuration / 3
// 设置重复次数
penguinView.animationRepeatCount = 3
}
// 滑行的动画
func loadSlideAnimation() {
penguinView.animationImages = slideFrames
penguinView.animationDuration = animationDuration
penguinView.animationRepeatCount = 1
}
// 判断左右 如果不是右边翻转图片
var isLookingRight: Bool = true {
didSet {
let xScale: CGFloat = isLookingRight ? 1 : -1
penguinView.transform = CGAffineTransformMakeScale(xScale, 1)
slideButton.transform = penguinView.transform
}
}
func leftBtnClick() {
isLookingRight = false
penguinView.startAnimating()
UIView.animateWithDuration(animationDuration, delay: 0.0, options: .CurveEaseOut, animations: {
self.penguinView.center.x -= self.penguinWidth
}, completion: nil)
}
func rightBtnClick() {
isLookingRight = true
penguinView.startAnimating()
UIView.animateWithDuration(animationDuration, delay: 0.0, options: .CurveEaseOut, animations: {
self.penguinView.center.x += self.penguinWidth
}, completion: nil)
}
func slideBtnClick() {
// 设置滑行动画
loadSlideAnimation()
penguinView.startAnimating()
UIView.animateWithDuration(animationDuration - 0.02, delay: 0.0, options: .CurveEaseOut, animations: {
self.penguinView.center.x += self.isLookingRight ?
self.penguinWidth : -self.penguinWidth
}, completion: {_ in
self.loadWalkAnimation()
})
}
// MARK: - 设置UI
lazy var bgView : UIImageView = {
let bgView = UIImageView(image:UIImage(named: "bg"))
bgView.frame = self.view.bounds
return bgView
}()
lazy var leftButton : UIButton = {
let btn = UIButton()
btn.setImage(UIImage(named: "btn-left"), forState: .Normal)
btn.frame = CGRect(x: 0, y: UIScreen.mainScreen().bounds.height-100, width: 100, height: 100)
btn.addTarget(self, action: Selector("leftBtnClick"), forControlEvents: .TouchUpInside)
return btn
}()
lazy var rightButton : UIButton = {
let btn = UIButton()
btn.setImage(UIImage(named: "btn-right"), forState: .Normal)
btn.frame = CGRect(x: 100, y: UIScreen.mainScreen().bounds.height-100, width: 100, height: 100)
btn.addTarget(self, action: Selector("rightBtnClick"), forControlEvents: .TouchUpInside)
return btn
}()
lazy var slideButton : UIButton = {
let btn = UIButton()
btn.setImage(UIImage(named: "btn-slide"), forState: .Normal)
btn.frame = CGRect(x: UIScreen.mainScreen().bounds.width-100, y: UIScreen.mainScreen().bounds.height-100, width: 100, height: 100)
btn.addTarget(self, action: Selector("slideBtnClick"), forControlEvents: .TouchUpInside)
return btn
}()
lazy var penguinView : UIImageView = {
let penguin = UIImageView()
penguin.image = UIImage(named: "walk01")
penguin.frame = CGRect(x: 100, y: UIScreen.mainScreen().bounds.height-175, width: self.penguinWidth , height: 96)
return penguin
}()
}
| mit |
leizh007/HiPDA | HiPDA/HiPDA/Sections/Me/FavoritesAndAtttention/AttentionViewModel.swift | 1 | 374 | //
// AttentionViewModel.swift
// HiPDA
//
// Created by leizh007 on 2017/7/8.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import Foundation
class AttentionViewModel: FavoritesAndAttentionBaseViewModel {
override func transform(html: String) throws -> [FavoritesAndAttentionBaseModel] {
return try HtmlParser.attentionModels(from: html)
}
}
| mit |
mchaffee1/SwiftUtils | Controls/PopupMenu/PopupMenuTableViewController.swift | 1 | 2997 | //
// PopupMenuTableViewController.swift
// SwiftUtils
//
// Created by Michael Chaffee on 10/18/15.
// Copyright © 2015 Michael Chaffee. All rights reserved.
//
/*
View controller for PopupMenu class.
*/
import UIKit
// TODO: Clean up all the code
protocol PopupMenuTableViewControllerDelegate: class {
func popupMenuVCDismissed(selection: String)
}
class PopupMenuTableViewController: UITableViewController {
// MARK: - Internal Properties
var font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
var delegate: PopupMenuTableViewControllerDelegate?
var values = [String]() // these are populated with the button texts in order
var suppressDidDisappear = false // Used to suppress a spurious viewDidDisappear call on selection-made
// MARK: - Private Properties
private let bundleIdentifier = "com.chaf.SwiftUtils"
private let cellIdentifier = "PopupMenuTableViewCell"
// MARK: - Initializers
convenience init() {
self.init(nibName: "PopupMenuTableViewController", bundle: NSBundle(identifier: "com.chaf.SwiftUtils"))
tableView.registerNib(UINib(nibName: cellIdentifier, bundle: NSBundle(identifier: bundleIdentifier)), forCellReuseIdentifier: cellIdentifier)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return values.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let value = values[indexPath.row]
let cell: PopupMenuTableViewCell! = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as? PopupMenuTableViewCell
cell.value = value
cell.viewController = self
return cell
}
// Send an empty string back to the delegate to indicate cancel-with-no-selection
override func viewDidDisappear(animated: Bool) {
if !suppressDidDisappear {
self.delegate?.popupMenuVCDismissed("")
}
}
// Send back the selected value after the user touched it
internal func cellButtonPressed(value: String) {
// Stick our delegate in a holding tank while the dismissViewController operation takes place.
// To avoid spurious empty callbacks.
suppressDidDisappear = true
dismissViewControllerAnimated(true) {
self.delegate?.popupMenuVCDismissed(value)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
mirego/PinLayout | Example/PinLayoutSample/UI/Common/BaseFormView.swift | 1 | 3001 | // Copyright (c) 2017 Luc Dion
// 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.
import UIKit
import PinLayout
class BaseFormView: UIView {
let formScrollView = UIScrollView()
init() {
super.init(frame: .zero)
formScrollView.showsVerticalScrollIndicator = false
formScrollView.keyboardDismissMode = .onDrag
formScrollView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapScrollView)))
addSubview(formScrollView)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
}
override func layoutSubviews() {
super.layoutSubviews()
formScrollView.pin.all()
}
@objc
internal func keyboardWillShow(notification: Notification) {
guard let sizeValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
setFormScrollView(bottomInset: sizeValue.cgRectValue.height)
}
@objc
internal func keyboardWillHide(notification: Notification) {
resetScrollOffset()
}
@objc
internal func didTapScrollView() {
endEditing(true)
resetScrollOffset()
}
private func resetScrollOffset() {
guard formScrollView.contentInset != .zero else { return }
setFormScrollView(bottomInset: 0)
}
private func setFormScrollView(bottomInset: CGFloat) {
formScrollView.contentInset = UIEdgeInsets(top: formScrollView.contentInset.top, left: 0,
bottom: bottomInset, right: 0)
}
}
| mit |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Profile Editor OutlineView/PropertyListEditor Source/PropertyListEnums.swift | 1 | 2961 | //
// PropertyListEnums.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
// MARK: - Value Constraints
/// `PropertyListValueConstraints` represent constraints for valid values on property list items. A
/// value constraint can take one of two forms: a formatter that should be used to convert to and
/// from a string representation of the value; and an array of valid values that represent all the
/// values the item can have.
enum PropertyListValueConstraint {
/// Represents a formatter value constraint.
case formatter(Foundation.Formatter)
/// Represents an array of valid values.
case valueArray([PropertyListValidValue])
}
/// `PropertyListValidValues` represent the valid values that a property list item can have.
struct PropertyListValidValue {
/// An object representation of the value.
let value: PropertyListItemConvertible
/// A localized, user-presentable description of the value.
let localizedDescription: String
}
// MARK: - Tree Node Operations
/// The `TreeNodeOperation` enum enumerates the different operations that can be taken on a tree
/// node. Because all operations on a property list item ultimately boils down to replacing an item
/// with a new one, we need some way to discern what corresponding node operation needs to take
/// place. That’s what `TreeNodeOperations` are for.
enum TreeNodeOperation {
/// Indicates that a child node should be inserted at the specified index.
case insertChildAt(Int)
/// Indicates that the child node at the specified index should be removed.
case removeChildAt(Int)
/// Indicates that the child node at the specified index should have its children regenerated.
case regenerateChildrenForChildAt(Int)
/// Indicates that the node should regenerate its children.
case regenerateChildren
/// Returns the inverse of the specified operation. This is useful when undoing an operation.
var inverseOperation: TreeNodeOperation {
switch self {
case let .insertChildAt(index):
return .removeChildAt(index)
case let .removeChildAt(index):
return .insertChildAt(index)
case .regenerateChildrenForChildAt, .regenerateChildren:
return self
}
}
/// Performs the instance’s operation on the specified tree node.
/// - parameter treeNode: The tree node on which to perform the operation.
func performOperation(on treeNode: PropertyListTreeNode) {
switch self {
case let .insertChildAt(index):
treeNode.insertChild(at: index)
case let .removeChildAt(index):
treeNode.removeChild(at: index)
case let .regenerateChildrenForChildAt(index):
treeNode.child(at: index).regenerateChildren()
case .regenerateChildren:
treeNode.regenerateChildren()
}
}
}
| mit |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Value Info Processors/ValueInfoProcessorFont.swift | 1 | 2791 | //
// ValueInfoProcessorFont.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Foundation
import ProfilePayloads
class ValueInfoProcessorFont: ValueInfoProcessor {
// MARK: -
// MARK: Intialization
override init() {
super.init(withIdentifier: "font")
}
override func valueInfo(forData data: Data) -> ValueInfo? {
var valueInfo = ValueInfo()
var fontInformation: FontInformation
// Get FontInfo
do {
guard let fontInfo = try FontInformation(data: data) else {
Log.shared.error(message: "Failed to create font information from passed data", category: String(describing: self))
return nil
}
fontInformation = fontInfo
} catch {
Log.shared.error(message: "Failed to create font information from passed data with error: \(error)", category: String(describing: self))
return nil
}
let fontDescriptions = fontInformation.descriptions(forLanguage: .english)
let fontDescription: FontDescription
if let unicode = fontDescriptions.first(where: { $0.platformIdentifier == .unicode }) {
fontDescription = unicode
} else if let macintosh = fontDescriptions.first(where: { $0.platformIdentifier == .macintosh }) {
fontDescription = macintosh
} else {
return nil
}
// Title
if let fontName = fontDescription.fullName ?? fontDescription.postScriptName {
valueInfo.title = fontName
} else {
valueInfo.title = NSLocalizedString("Unknown Font", comment: "")
}
// Top
valueInfo.topLabel = NSLocalizedString("Format", comment: "")
valueInfo.topContent = fontInformation.formatString
// Center
valueInfo.centerLabel = NSLocalizedString("Version", comment: "")
valueInfo.centerContent = fontDescription.version ?? "Unknown"
// Bottom
if let manufacturer = fontDescription.manufacturer {
valueInfo.bottomLabel = NSLocalizedString("Manufacturer", comment: "")
valueInfo.bottomContent = manufacturer
} else if let designer = fontDescription.designer {
valueInfo.bottomLabel = NSLocalizedString("Designer", comment: "")
valueInfo.bottomContent = designer
} else if let copyright = fontDescription.copyright {
valueInfo.bottomLabel = NSLocalizedString("Copyright", comment: "")
valueInfo.bottomContent = copyright
}
// Icon
valueInfo.icon = NSWorkspace.shared.icon(forFileType: fontInformation.uti as String)
return valueInfo
}
}
| mit |
nghiaphunguyen/NKit | NKit/Source/NKTableView/NKTableHeaderFooterView.swift | 1 | 628 | //
// NKTableHeaderFooterView.swift
// NKit
//
// Created by Nghia Nguyen on 2/9/17.
// Copyright © 2017 Nghia Nguyen. All rights reserved.
//
import UIKit
open class NKTableHeaderFooterView: UITableViewHeaderFooterView {
public override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.setupView()
self.setupRx()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupView()
self.setupRx()
}
@objc dynamic open func setupView() {}
@objc dynamic open func setupRx() {}
}
| mit |
Bersaelor/SwiftyHYGDB | Sources/SwiftyHYGDB/Star3D+CVS.swift | 1 | 4025 | //
// Star3D+CSV.swift
// Pods-SwiftyHYGDB_Example
//
// Created by Konrad Feiler on 10.09.17.
//
import Foundation
extension Star3D: CSVWritable {
public static let headerLine = "id,hip,hd,hr,gl,bf,proper,ra,dec,dist,rv,mag,absmag,spect,ci,x,y,z"
public var csvLine: String? {
guard let starData = self.starData?.value else { return nil }
var result = starData.csvLine
result.append((x.compressedString).appending(","))
result.append((y.compressedString).appending(","))
result.append((z.compressedString).appending(","))
return result
}
}
/// High performance initializer
extension Star3D {
init? (rowPtr: UnsafeMutablePointer<CChar>, advanceByYears: Double? = nil, indexers: inout SwiftyDBValueIndexers) {
var index = 0
guard let dbID: Int32 = readNumber(at: &index, stringPtr: rowPtr) else { return nil }
let hip_id: Int32? = readNumber(at: &index, stringPtr: rowPtr)
let hd_id: Int32? = readNumber(at: &index, stringPtr: rowPtr)
let hr_id: Int32? = readNumber(at: &index, stringPtr: rowPtr)
let gl_id = readString(at: &index, stringPtr: rowPtr)
let bayerFlamstedt = readString(at: &index, stringPtr: rowPtr)
let properName = readString(at: &index, stringPtr: rowPtr)
guard var right_ascension: Float = readNumber(at: &index, stringPtr: rowPtr),
var declination: Float = readNumber(at: &index, stringPtr: rowPtr),
let dist: Double = readNumber(at: &index, stringPtr: rowPtr) else { return nil }
let pmra: Double? = advanceByYears != nil ? readNumber(at: &index, stringPtr: rowPtr) : nil
let pmdec: Double? = advanceByYears != nil ? readNumber(at: &index, stringPtr: rowPtr) : nil
let rv: Float? = readNumber(at: &index, stringPtr: rowPtr)
guard let mag: Float = readNumber(at: &index, stringPtr: rowPtr),
let absmag: Float = readNumber(at: &index, stringPtr: rowPtr) else { return nil }
let spectralType = readString(at: &index, stringPtr: rowPtr)
let colorIndex: Float? = readNumber(at: &index, stringPtr: rowPtr)
guard var x: Float = readNumber(at: &index, stringPtr: rowPtr),
var y: Float = readNumber(at: &index, stringPtr: rowPtr),
var z: Float = readNumber(at: &index, stringPtr: rowPtr) else { return nil }
if let pmra = pmra, let pmdec = pmdec, let advanceByYears = advanceByYears,
let vx: Double = readNumber(at: &index, stringPtr: rowPtr),
let vy: Double = readNumber(at: &index, stringPtr: rowPtr),
let vz: Double = readNumber(at: &index, stringPtr: rowPtr) {
RadialStar.precess(right_ascension: &right_ascension, declination: &declination,
pmra: pmra, pmdec: pmdec, advanceByYears: Float(advanceByYears))
x += Float(advanceByYears * vx)
y += Float(advanceByYears * vy)
z += Float(advanceByYears * vz)
}
self.dbID = dbID
self.x = x
self.y = y
self.z = z
let starData = StarData(right_ascension: right_ascension,
declination: declination,
db_id: dbID,
hip_id: hip_id,
hd_id: hd_id,
hr_id: hr_id,
gl_id: indexers.glIds.index(for: gl_id),
bayer_flamstedt: indexers.bayerFlamstedts.index(for: bayerFlamstedt),
properName: indexers.properNames.index(for: properName),
distance: dist, rv: rv,
mag: mag, absmag: absmag,
spectralType: indexers.spectralTypes.index(for: spectralType),
colorIndex: colorIndex)
self.starData = Box(starData)
}
}
| mit |
Themaister/RetroArch | pkg/apple/MouseEmulation/EmulatorTouchMouse.swift | 5 | 5838 | //
// EmulatorTouchMouse.swift
// RetroArchiOS
//
// Created by Yoshi Sugawara on 12/27/21.
// Copyright © 2021 RetroArch. All rights reserved.
//
/**
Touch mouse behavior:
- Mouse movement: Pan finger around screen
- Left click: Tap with one finger
- Right click: Tap with two fingers (or hold with one finger and tap with another)
- Click-and-drag: Double tap and hold for 1 second, then pan finger around screen to drag mouse
Code adapted from iDOS/dospad: https://github.com/litchie/dospad
*/
import Combine
import UIKit
@objc public protocol EmulatorTouchMouseHandlerDelegate: AnyObject {
func handleMouseClick(isLeftClick: Bool, isPressed: Bool)
func handleMouseMove(x: CGFloat, y: CGFloat)
}
@objcMembers public class EmulatorTouchMouseHandler: NSObject {
enum MouseHoldState {
case notHeld, wait, held
}
struct MouseClick {
var isRightClick = false
var isPressed = false
}
struct TouchInfo {
let touch: UITouch
let origin: CGPoint
let holdState: MouseHoldState
}
var enabled = false
let view: UIView
weak var delegate: EmulatorTouchMouseHandlerDelegate?
private let positionChangeThreshold: CGFloat = 20.0
private let mouseHoldInterval: TimeInterval = 1.0
private var pendingMouseEvents = [MouseClick]()
private var mouseEventPublisher: AnyPublisher<MouseClick, Never> {
mouseEventSubject.eraseToAnyPublisher()
}
private let mouseEventSubject = PassthroughSubject<MouseClick, Never>()
private var subscription: AnyCancellable?
private var primaryTouch: TouchInfo?
private var secondaryTouch: TouchInfo?
private let mediumHaptic = UIImpactFeedbackGenerator(style: .medium)
public init(view: UIView, delegate: EmulatorTouchMouseHandlerDelegate? = nil) {
self.view = view
self.delegate = delegate
super.init()
setup()
}
private func setup() {
subscription = mouseEventPublisher
.sink(receiveValue: {[weak self] value in
self?.pendingMouseEvents.append(value)
self?.processMouseEvents()
})
}
private func processMouseEvents() {
guard let event = pendingMouseEvents.first else {
return
}
delegate?.handleMouseClick(isLeftClick: !event.isRightClick, isPressed: event.isPressed)
if event.isPressed {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
self?.mouseEventSubject.send(MouseClick(isRightClick: event.isRightClick, isPressed: false))
}
}
pendingMouseEvents.removeFirst()
processMouseEvents()
}
@objc private func beginHold() {
guard let primaryTouch = primaryTouch, primaryTouch.holdState == .wait else {
return
}
self.primaryTouch = TouchInfo(touch: primaryTouch.touch, origin: primaryTouch.origin, holdState: .held)
mediumHaptic.impactOccurred()
delegate?.handleMouseClick(isLeftClick: true, isPressed: true)
}
private func endHold() {
guard let primaryTouch = primaryTouch else { return }
if primaryTouch.holdState == .notHeld {
return
}
if primaryTouch.holdState == .wait {
Thread.cancelPreviousPerformRequests(withTarget: self, selector: #selector(beginHold), object: self)
} else {
delegate?.handleMouseClick(isLeftClick: true, isPressed: false)
}
self.primaryTouch = TouchInfo(touch: primaryTouch.touch, origin: primaryTouch.origin, holdState: .notHeld)
}
public func touchesBegan(touches: Set<UITouch>) {
guard enabled, let touch = touches.first else {
return
}
if primaryTouch == nil {
primaryTouch = TouchInfo(touch: touch, origin: touch.location(in: view), holdState: .wait)
if touch.tapCount == 2 {
self.perform(#selector(beginHold), with: nil, afterDelay: mouseHoldInterval)
}
} else if secondaryTouch == nil {
secondaryTouch = TouchInfo(touch: touch, origin: touch.location(in: view), holdState: .notHeld)
}
}
public func touchesEnded(touches: Set<UITouch>) {
guard enabled else { return }
for touch in touches {
if touch == primaryTouch?.touch {
if touch.tapCount > 0 {
for _ in 1...touch.tapCount {
mouseEventSubject.send(MouseClick(isRightClick: false, isPressed: true))
}
}
endHold()
primaryTouch = nil
secondaryTouch = nil
} else if touch == secondaryTouch?.touch {
if touch.tapCount > 0 {
mouseEventSubject.send(MouseClick(isRightClick: true, isPressed: true))
endHold()
}
secondaryTouch = nil
}
}
delegate?.handleMouseMove(x: 0, y: 0)
}
public func touchesMoved(touches: Set<UITouch>) {
guard enabled else { return }
for touch in touches {
if touch == primaryTouch?.touch {
let a = touch.previousLocation(in: view)
let b = touch.location(in: view)
if primaryTouch?.holdState == .wait && (distanceBetween(pointA: a, pointB: b) > positionChangeThreshold) {
endHold()
}
delegate?.handleMouseMove(x: b.x-a.x, y: b.y-a.y)
}
}
}
public func touchesCancelled(touches: Set<UITouch>) {
guard enabled else { return }
for touch in touches {
if touch == primaryTouch?.touch {
endHold()
}
}
primaryTouch = nil
secondaryTouch = nil
}
func distanceBetween(pointA: CGPoint, pointB: CGPoint) -> CGFloat {
let dx = pointA.x - pointB.x
let dy = pointA.y - pointB.y
return sqrt(dx*dx*dy*dy)
}
}
| gpl-3.0 |
dflax/FlickSearch | FlickrSearchTests/FlickrSearchTests.swift | 1 | 915 | //
// FlickrSearchTests.swift
// FlickrSearchTests
//
// Created by Daniel Flax on 4/20/15.
// Copyright (c) 2015 Daniel Flax. All rights reserved.
//
import UIKit
import XCTest
class FlickrSearchTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
lorentey/swift | test/Sema/substring_to_string_conversion_swift4.swift | 20 | 3095 | // RUN: %target-swift-frontend -typecheck -verify -swift-version 4 %s
let s = "Hello"
let ss = s[s.startIndex..<s.endIndex]
// CTP_Initialization
do {
let s1: String = { return ss }() // expected-error {{cannot convert value of type 'Substring' to closure result type 'String'}} {{29-29=String(}} {{31-31=)}}
_ = s1
}
// CTP_ReturnStmt
do {
func returnsAString() -> String {
return ss // expected-error {{cannot convert return expression of type 'Substring' to return type 'String'}} {{12-12=String(}} {{14-14=)}}
}
}
// CTP_ThrowStmt
// Doesn't really make sense for this fix-it - see case in diagnoseContextualConversionError:
// The conversion destination of throw is always ErrorType (at the moment)
// if this ever expands, this should be a specific form like () is for
// return.
// CTP_EnumCaseRawValue
// Substrings can't be raw values because they aren't literals.
// CTP_DefaultParameter
do {
func foo(x: String = ss) {} // expected-error {{default argument value of type 'Substring' cannot be converted to type 'String'}} {{24-24=String(}} {{26-26=)}}
}
// CTP_CalleeResult
do {
func getSubstring() -> Substring { return ss }
let gottenString : String = getSubstring() // expected-error {{cannot convert value of type 'Substring' to specified type 'String'}} {{31-31=String(}} {{45-45=)}}
_ = gottenString
}
// CTP_CallArgument
do {
func takesAString(_ s: String) {}
takesAString(ss) // expected-error {{cannot convert value of type 'Substring' to expected argument type 'String'}} {{16-16=String(}} {{18-18=)}}
}
// CTP_ClosureResult
do {
[ss].map { (x: Substring) -> String in x } // expected-error {{declared closure result 'Substring' is incompatible with contextual type 'String'}}
}
// CTP_ArrayElement
do {
let a: [String] = [ ss ] // expected-error {{cannot convert value of type 'Substring' to expected element type 'String'}} {{23-23=String(}} {{25-25=)}}
_ = a
}
// CTP_DictionaryKey
do {
let d: [ String : String ] = [ ss : s ] // expected-error {{cannot convert value of type 'Substring' to expected dictionary key type 'String'}} {{34-34=String(}} {{36-36=)}}
_ = d
}
// CTP_DictionaryValue
do {
let d: [ String : String ] = [ s : ss ] // expected-error {{cannot convert value of type 'Substring' to expected dictionary value type 'String'}} {{38-38=String(}} {{40-40=)}}
_ = d
}
// CTP_CoerceOperand
do {
let s1: String = ss as String // expected-error {{cannot convert value of type 'Substring' to type 'String' in coercion}} {{20-20=String(}} {{22-22=)}}
_ = s1
}
// CTP_AssignSource
do {
let s1: String = ss // expected-error {{cannot convert value of type 'Substring' to specified type 'String'}} {{20-20=String(}} {{22-22=)}}
_ = s1
}
// Substring-to-String via subscripting in a context expecting String
func takesString(_ s: String) {}
// rdar://33474838
protocol Derivable {
func derive() -> Substring
}
func foo<T: Derivable>(t: T) -> String {
return t.derive() // expected-error {{cannot convert return expression of type 'Substring' to return type 'String'}} {{10-10=String(}} {{20-20=)}}
}
| apache-2.0 |
Nickelfox/PaginationUIManager | Example/PaginationUIManager-Example/AppDelegate.swift | 1 | 2103 | //
// AppDelegate.swift
// PaginationUIManager-Example
//
// Created by Ravindra Soni on 07/09/17.
// Copyright © 2017 Nickelfox. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
toygar/VideoThumbView | VideoThumbnailViewKit/VideoThumbnailView/VideoThumbnailView.swift | 2 | 4213 | //
// VideoThumbnailView.swift
// VideoThumbnailView
//
// Created by Toygar Dundaralp on 9/29/15.
// Copyright (c) 2015 Toygar Dundaralp. All rights reserved.
//
import UIKit
import AVFoundation
public class VideoThumbnailView: UIView {
private var videoScroll = UIScrollView()
private var thumImageView = UIImageView()
private var arrThumbViews = NSMutableArray()
private var scrollContentWidth = 0.0
private var videoURL = NSURL()
private var videoDuration = 0.0
private var activityIndicator = UIActivityIndicatorView()
init(frame: CGRect, videoURL url: NSURL, thumbImageWidth thumbWidth: Double) {
super.init(frame: frame)
self.videoURL = url
self.videoDuration = self.getVideoTime(url)
activityIndicator = UIActivityIndicatorView(
frame: CGRect(
x: self.center.x - 15,
y: self.frame.size.height / 2 - 15,
width: 30.0,
height: 30.0))
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = .White
activityIndicator.startAnimating()
addSubview(self.activityIndicator)
videoScroll = UIScrollView(
frame: CGRect(
x: 0.0,
y: 0.0,
width: self.frame.size.width,
height: self.frame.size.height))
videoScroll.showsHorizontalScrollIndicator = false
videoScroll.showsVerticalScrollIndicator = false
videoScroll.bouncesZoom = false
videoScroll.bounces = false
self.addSubview(videoScroll)
self.thumbImageProcessing(
videoUrl: videoURL,
thumbWidth: thumbWidth) { (thumbImages, error) -> Void in
// println(thumbImages)
}
self.layer.masksToBounds = true
}
private func thumbImageProcessing(
videoUrl url: NSURL,
thumbWidth: Double,
completion: ((thumbImages: NSMutableArray?, error: NSError?) -> Void)?) {
let priority = DISPATCH_QUEUE_PRIORITY_HIGH
dispatch_async(dispatch_get_global_queue(priority, 0)) {
for index in 0...Int(self.videoDuration) {
let thumbXCoords = Double(index) * thumbWidth
self.thumImageView = UIImageView(
frame: CGRect(
x: thumbXCoords,
y: 0.0,
width: thumbWidth,
height: Double(self.frame.size.height)))
self.thumImageView.contentMode = .ScaleAspectFit
self.thumImageView.backgroundColor = UIColor.clearColor()
self.thumImageView.layer.borderColor = UIColor.grayColor().CGColor
self.thumImageView.layer.borderWidth = 0.25
self.thumImageView.tag = index
self.thumImageView.image = self.generateVideoThumbs(
self.videoURL,
second: Double(index),
thumbWidth: thumbWidth)
self.scrollContentWidth = self.scrollContentWidth + thumbWidth
self.videoScroll.addSubview(self.thumImageView)
self.videoScroll.sendSubviewToBack(self.thumImageView)
if let imageView = self.thumImageView as UIImageView? {
self.arrThumbViews.addObject(imageView)
}
}
self.videoScroll.contentSize = CGSize(
width: Double(self.scrollContentWidth),
height: Double(self.frame.size.height))
self.activityIndicator.stopAnimating()
completion?(thumbImages: self.arrThumbViews, error: nil)
self.videoScroll.setContentOffset(CGPoint(x: 0.0, y: 0.0), animated: true)
}
}
private func getVideoTime(url: NSURL) -> Float64 {
let videoTime = AVURLAsset(URL: url, options: nil)
return CMTimeGetSeconds(videoTime.duration)
}
private func generateVideoThumbs(url: NSURL, second: Float64, thumbWidth: Double) -> UIImage {
let asset = AVURLAsset(URL: url, options: nil)
let generator = AVAssetImageGenerator(asset: asset)
generator.maximumSize = CGSize(width: thumbWidth, height: Double(self.frame.size.height))
generator.appliesPreferredTrackTransform = false
let thumbTime = CMTimeMakeWithSeconds(second, 1)
do {
let ref = try generator.copyCGImageAtTime(thumbTime, actualTime: nil)
return UIImage(CGImage: ref)
}catch {
print(error)
}
return UIImage()
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit |
Raizlabs/ios-template | {{ cookiecutter.project_name | replace(' ', '') }}/app/{{ cookiecutter.project_name | replace(' ', '') }}/Components/Representable/SimpleTableCellItem.swift | 1 | 1186 | //
// SimpleTableCellItem.swift
// {{ cookiecutter.project_name | replace(' ', '') }}
//
// Created by {{ cookiecutter.lead_dev }} on {% now 'utc', '%D' %}.
// Copyright © {% now 'utc', '%Y' %} {{ cookiecutter.company_name }}. All rights reserved.
//
import Foundation
public struct SimpleTableCellItem {
public typealias VoidBlock = () -> Void
let text: String
let selectCell: VoidBlock
public init(text: String, selectCell: @escaping VoidBlock) {
self.text = text
self.selectCell = selectCell
}
}
extension SimpleTableCellItem: TableViewCellRepresentable, CellIdentifiable {
public static func register(_ tableView: UITableView) {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
}
public func cell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: type(of: self).reuseIdentifier, for: indexPath)
cell.textLabel?.text = text
return cell
}
public func performSelection() {
self.selectCell()
}
public func canSelect() -> Bool {
return true
}
}
| mit |
akio0911/til | 20201203/CombineExample/CombineExample/ViewController.swift | 1 | 281 | //
// ViewController.swift
// CombineExample
//
// Created by akio0911 on 2020/12/03.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| mit |
langyanduan/SegueKit | Example/Example/ViewController.swift | 2 | 4496 | //
// ViewController.swift
// Example
//
// Created by langyanduan on 16/5/24.
// Copyright © 2016年 langyanduan. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import SegueKit
class ViewController: UIViewController {
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func onBtnA(_ sender: AnyObject) {
performSegue(with: "A") { (segue) in
segue.destination.view.backgroundColor = UIColor.yellow
}
}
@IBAction func onBtnB(_ sender: AnyObject) {
performSegue(with: R.segue.viewController.b) { (segue) in
segue.destination.view.backgroundColor = UIColor.green
}
}
@IBAction func onBtnC(_ sender: AnyObject) {
rx.performSegue("C")
.subscribeNext { (segue) in
segue.destination.view.backgroundColor = UIColor.red
}
.addDisposableTo(disposeBag)
}
@IBAction func onBtnD(_ sender: AnyObject) {
rx.performSegue(R.segue.viewController.d)
.subscribeNext { (segue) in
segue.destination.view.backgroundColor = UIColor.blue
}
.addDisposableTo(disposeBag)
}
@IBAction func onBtnVC(_ sender: AnyObject) {
rx.performSegue(R.segue.viewController.viewController)
.subscribeNext { [unowned self] (segue) in
for view in segue.destination.view.subviews {
if let button = view as? UIButton {
button.rx.tap
.bindTo(segue.destination.rx.segue(R.segue.uIViewController.viewController)) { (segue, _) in
segue.destination.view.backgroundColor = UIColor.red
}
.addDisposableTo(self.disposeBag)
break
}
}
}
.addDisposableTo(disposeBag)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
}
deinit {
print("deinit ViewController")
}
}
class BaseViewController: UIViewController {
let baseDisposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
rx.segue(R.segue.baseViewController.base)
.subscribeNext { (segue, sender) in
segue.destination.view.backgroundColor = UIColor.cyan
}
.addDisposableTo(baseDisposeBag)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
}
deinit {
print("deinit BaseViewController")
}
}
class A: BaseViewController {
let disposeBag = DisposeBag()
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
button.rx.tap.bindTo(rx.segue("A")) { (segue, _) in
segue.destination.view.backgroundColor = UIColor.black
}.addDisposableTo(disposeBag)
}
deinit {
print("deinit A")
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
}
}
class B: BaseViewController {
let disposeBag = DisposeBag()
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
button.rx.tap.bindTo(rx.segue(R.segue.b.b)) { (segue, _) in
segue.destination.view.backgroundColor = UIColor.brown
}.addDisposableTo(disposeBag)
}
deinit {
print("deinit B")
}
}
class C: BaseViewController {
var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
rx.segue("C").subscribeNext { (segue, sender) in
segue.destination.view.backgroundColor = UIColor.purple
}.addDisposableTo(disposeBag)
}
deinit {
print("deinit C")
}
}
class D: BaseViewController {
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
rx.segue(R.segue.d.d).subscribeNext { (segue, sender) in
segue.destination.view.backgroundColor = UIColor.orange
}.addDisposableTo(disposeBag)
}
deinit {
print("deinit D")
}
}
| mit |
gcharita/XMLMapper | XMLMapper/Classes/XMLDateFormatterTransform.swift | 1 | 790 | //
// XMLDateFormatterTransform.swift
// XMLMapper
//
// Created by Giorgos Charitakis on 15/09/2017.
//
//
import Foundation
open class XMLDateFormatterTransform: XMLTransformType {
public typealias Object = Date
public typealias XML = String
public let dateFormatter: DateFormatter
public init(dateFormatter: DateFormatter) {
self.dateFormatter = dateFormatter
}
open func transformFromXML(_ value: Any?) -> Date? {
if let dateString = value as? String {
return dateFormatter.date(from: dateString)
}
return nil
}
open func transformToXML(_ value: Date?) -> String? {
if let date = value {
return dateFormatter.string(from: date)
}
return nil
}
}
| mit |
dbettermann/DBAlertController | DBAlertControllerTests/DBAlertControllerTests.swift | 2 | 940 | //
// DBAlertControllerTests.swift
// DBAlertControllerTests
//
// Created by Dylan Bettermann on 5/11/15.
// Copyright (c) 2015 Dylan Bettermann. All rights reserved.
//
import UIKit
import XCTest
class DBAlertControllerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
Bouke/DNS | Tests/DNSTests/DNSTests.swift | 1 | 11252 | import XCTest
@testable import DNS
class DNSTests: XCTestCase {
static var allTests: [(String, (DNSTests) -> () throws -> Void)] {
return [
("testReadMe", testReadMe),
("testPointerRecord", testPointerRecord),
("testMessage1", testMessage1),
("testMessage2", testMessage2),
("testMessage3", testMessage3),
("testMessage4", testMessage4),
("testMessage5", testMessage5),
("testDeserializeName", testDeserializeName),
("testDeserializeCorruptedName", testDeserializeCorruptedName),
("testSerializeName", testSerializeName),
("testSerializeNameCondensed", testSerializeNameCondensed),
("testLinuxTestSuiteIncludesAllTests", testLinuxTestSuiteIncludesAllTests),
("testDeserializeFuzzMessages", testDeserializeFuzzMessages),
("testDeserializeInvalidQuestion", testDeserializeInvalidQuestion),
("testDeserializeInvalidLabel", testDeserializeInvalidLabel),
("testNameServerRecordLabel", testNameServerRecord),
("testMXRecordLabel", testMailExchangeRecord)
]
}
func testReadMe() throws {
// If the code below doesn't work, also update the README.md to
// demonstrate the changes in the API.
let request = Message(
type: .query,
questions: [Question(name: "apple.com.", type: .pointer)]
)
let requestData = try request.serialize()
// Not shown here: send to DNS server over UDP, receive reply.
let responseData = requestData
// Decoding a message
let response = try Message(deserialize: responseData)
print(response.answers.first ?? "No answers")
}
func testPointerRecord() {
var labels0 = Labels()
var serialized0 = Data()
let pointer0 = PointerRecord(name: "_hap._tcp.local.", ttl: 120, destination: "Swift._hap._tcp.local.")
try! pointer0.serialize(onto: &serialized0, labels: &labels0)
var labels1 = Labels()
var serialized1 = Data()
let pointer1 = PointerRecord(name: "_hap._tcp.local.", ttl: 120, destination: "Swift._hap._tcp.local.")
try! pointer1.serialize(onto: &serialized1, labels: &labels1)
XCTAssertEqual(serialized0.hex, serialized1.hex)
var position = serialized0.startIndex
let rcf = try! deserializeRecordCommonFields(serialized0, &position)
let pointer0copy = try! PointerRecord(deserialize: serialized0, position: &position, common: rcf)
XCTAssertEqual(pointer0, pointer0copy)
}
func testNameServerRecord() {
var labels0 = Labels()
var serialized0 = Data()
let nameServer = NameServerRecord(name: "google.com.", type: 1, internetClass: .nameServer, unique: true, ttl: 3600, nameServer: "ns1.google.com.")
try! nameServer.serialize(onto: &serialized0, labels: &labels0)
var labels1 = Labels()
var serialized1 = Data()
let nameServer1 = NameServerRecord(name: "google.com.", type: 1, internetClass: .nameServer, unique: true, ttl: 3600, nameServer: "ns1.google.com.")
try! nameServer1.serialize(onto: &serialized1, labels: &labels1)
XCTAssertEqual(serialized0.hex, serialized1.hex)
var position = serialized0.startIndex
let rcf = try! deserializeRecordCommonFields(serialized0, &position)
let nameServer0Copy = try! NameServerRecord(deserialize: serialized0, position: &position, common: rcf)
XCTAssertEqual(nameServer, nameServer0Copy)
}
func testMailExchangeRecord() {
var labels0 = Labels()
var serialized0 = Data()
let nameServer = MailExchangeRecord(name: "google.com.", type: 1, internetClass: .nameServer, unique: true, ttl: 3600, priority: 40, exchangeServer: "ex1.google.com.")
try! nameServer.serialize(onto: &serialized0, labels: &labels0)
var labels1 = Labels()
var serialized1 = Data()
let nameServer1 = MailExchangeRecord(name: "google.com.", type: 1, internetClass: .nameServer, unique: true, ttl: 3600, priority: 40, exchangeServer: "ex1.google.com.")
try! nameServer1.serialize(onto: &serialized1, labels: &labels1)
XCTAssertEqual(serialized0.hex, serialized1.hex)
var position = serialized0.startIndex
let rcf = try! deserializeRecordCommonFields(serialized0, &position)
let nameServer0Copy = try! MailExchangeRecord(deserialize: serialized0, position: &position, common: rcf)
XCTAssertEqual(nameServer, nameServer0Copy)
}
func testMessage1() {
let message0 = Message(id: 4529, type: .response, operationCode: .query, authoritativeAnswer: false, truncation: false, recursionDesired: false, recursionAvailable: false, returnCode: .nonExistentDomain)
let serialized0 = try! message0.serialize()
XCTAssertEqual(serialized0.hex, "11b180030000000000000000")
let message1 = try! Message(deserialize: serialized0)
let serialized1 = try! message1.serialize()
XCTAssertEqual(serialized0.hex, serialized1.hex)
}
func testMessage2() {
let message0 = Message(id: 18765, type: .response, operationCode: .query, authoritativeAnswer: true, truncation: true, recursionDesired: true, recursionAvailable: true, returnCode: .noError)
let serialized0 = try! message0.serialize()
XCTAssertEqual(serialized0.hex, "494d87800000000000000000")
let message1 = try! Message(deserialize: serialized0)
let serialized1 = try! message1.serialize()
XCTAssertEqual(serialized0.hex, serialized1.hex)
}
func testMessage3() {
let message0 = Message(type: .query,
questions: [Question(name: "_airplay._tcp._local", type: .pointer)])
let serialized0 = try! message0.serialize()
let message1 = try! Message(deserialize: serialized0)
let serialized1 = try! message1.serialize()
XCTAssertEqual(serialized0.hex, serialized1.hex)
}
func testMessage4() {
let service = "_airplay._tcp._local."
let name = "example.\(service)"
let message0 = Message(type: .response,
questions: [Question(name: service, type: .pointer)],
answers: [PointerRecord(name: service, ttl: 120, destination: name)])
let serialized0 = try! message0.serialize()
let message1 = try! Message(deserialize: serialized0)
let serialized1 = try! message1.serialize()
XCTAssertEqual(serialized0.hex, serialized1.hex)
}
func testMessage5() {
let service = "_airplay._tcp._local."
let name = "example.\(service)"
let server = "example.local."
let message0 = Message(type: .response,
questions: [Question(name: service, type: .pointer)],
answers: [PointerRecord(name: service, ttl: 120, destination: name),
ServiceRecord(name: name, ttl: 120, port: 7000, server: server)],
additional: [HostRecord<IPv4>(name: server, ttl: 120, ip: IPv4("10.0.1.2")!),
TextRecord(name: service, ttl: 120, attributes: ["hello": "world"])])
let serialized0 = try! message0.serialize()
let message1 = try! Message(deserialize: serialized0)
let serialized1 = try! message1.serialize()
XCTAssertEqual(serialized0.hex, serialized1.hex)
}
func testDeserializeName() {
// This is part of a record. The name can be found by following two pointers indicated by 0xc000 (mask).
let data = Data(hex: "000084000000000200000006075a6974686f656b0c5f6465766963652d696e666f045f746370056c6f63616c000010000100001194000d0c6d6f64656c3d4a3432644150085f616972706c6179c021000c000100001194000a075a6974686f656bc044")!
var position = 89
let name = try! deserializeName(data, &position)
XCTAssertEqual(name, "Zithoek._airplay._tcp.local.")
XCTAssertEqual(position, 99)
}
func testDeserializeFuzzMessages() {
let data = Data(hex: "000084000001000200000002085f61692e706c6179045f746370065f6c6f63616c00000c0001c00c000c0001000000780013076578616d706c65085f616972706c6179c015c03200210001000000780015000000001b58076578616d706c65056c6f63616c00c057000100010000007800040a000102c00c000c000100000078000c0b68656c6c6f3d776f726c64")!
_ = try? Message(deserialize: data) // should either deserialize or throw, but not segfault
}
func testDeserializeInvalidQuestion() {
let data = Data(hex: "14bf8ba7a13993cdb5346356008119")!
_ = try? Message(deserialize: data) // should either deserialize or throw, but not segfault
}
func testDeserializeInvalidLabel() {
let data = Data(hex: "e983e8f7b88aed06c83f590fc00c6e5a6d0fe8898a21dd")!
_ = try? Message(deserialize: data) // should either deserialize or throw, but not segfault
}
func testDeserializeCorruptedName() {
let data = Data(hex: "000084000001000200009302085f616972706c6179045f746370065f6c6f63616c00000c0001c00c000c0001000000480013076578616d706c65085f616972706c6179c03ac03200210001000000780015000000001b5807656a616d706c65056c6f63616c00c057000100010000007800040a000102c00c0010000143000078000c0b68656c6c6f3d7767726c64")!
if (try? Message(deserialize: data)) != nil {
return XCTFail("Should not have deserialized message")
}
}
func testSerializeName() {
let message = Message(type: .response,
questions: [Question(name: "🤩", type: .pointer)])
let size0 = try! message.serialize().count
XCTAssertEqual(size0, 22)
}
func testSerializeNameCondensed() {
var message = Message(type: .response,
questions: [Question(name: "abc.def.ghi.jk.local.", type: .pointer)])
let size0 = try! message.serialize().count
XCTAssertEqual(size0, 38)
message.questions.append(Question(name: "abc.def.ghi.jk.local.", type: .pointer))
let size1 = try! message.serialize().count
XCTAssertEqual(size1, size0 + 6)
message.questions.append(Question(name: "def.ghi.jk.local.", type: .pointer))
let size2 = try! message.serialize().count
XCTAssertEqual(size2, size1 + 10)
message.questions.append(Question(name: "xyz.def.ghi.jk.local.", type: .pointer))
let size3 = try! message.serialize().count
XCTAssertEqual(size3, size2 + 10)
}
// from: https://oleb.net/blog/2017/03/keeping-xctest-in-sync/#appendix-code-generation-with-sourcery
func testLinuxTestSuiteIncludesAllTests() {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let thisClass = type(of: self)
let linuxCount = thisClass.allTests.count
let darwinCount = Int(thisClass
.defaultTestSuite.testCaseCount)
XCTAssertEqual(linuxCount, darwinCount,
"\(darwinCount - linuxCount) tests are missing from allTests")
#endif
}
}
| mit |
parkera/swift-corelibs-foundation | Foundation/URLSession/libcurl/EasyHandle.swift | 1 | 30463 | // Foundation/URLSession/EasyHandle.swift - URLSession & libcurl
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 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
//
// -----------------------------------------------------------------------------
///
/// libcurl *easy handle* wrapper.
/// These are libcurl helpers for the URLSession API code.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/
/// - SeeAlso: URLSession.swift
///
// -----------------------------------------------------------------------------
import CoreFoundation
import Dispatch
/// Minimal wrapper around the [curl easy interface](https://curl.haxx.se/libcurl/c/)
///
/// An *easy handle* manages the state of a transfer inside libcurl.
///
/// As such the easy handle's responsibility is implementing the HTTP
/// protocol while the *multi handle* is in charge of managing sockets and
/// reading from / writing to these sockets.
///
/// An easy handle is added to a multi handle in order to associate it with
/// an actual socket. The multi handle will then feed bytes into the easy
/// handle and read bytes from the easy handle. But this process is opaque
/// to use. It is further worth noting, that with HTTP/1.1 persistent
/// connections and with HTTP/2 there's a 1-to-many relationship between
/// TCP streams and HTTP transfers / easy handles. A single TCP stream and
/// its socket may be shared by multiple easy handles.
///
/// A single HTTP request-response exchange (refered to here as a
/// *transfer*) corresponds directly to an easy handle. Hence anything that
/// needs to be configured for a specific transfer (e.g. the URL) will be
/// configured on an easy handle.
///
/// A single `URLSessionTask` may do multiple, consecutive transfers, and
/// as a result it will have to reconfigure its easy handle between
/// transfers. An easy handle can be re-used once its transfer has
/// completed.
///
/// - Note: All code assumes that it is being called on a single thread /
/// `Dispatch` only -- it is intentionally **not** thread safe.
internal final class _EasyHandle {
let rawHandle = CFURLSessionEasyHandleInit()
weak var delegate: _EasyHandleDelegate?
fileprivate var headerList: _CurlStringList?
fileprivate var pauseState: _PauseState = []
internal var timeoutTimer: _TimeoutSource!
internal lazy var errorBuffer = [UInt8](repeating: 0, count: Int(CFURLSessionEasyErrorSize))
internal var _config: URLSession._Configuration? = nil
internal var _url: URL? = nil
init(delegate: _EasyHandleDelegate) {
self.delegate = delegate
setupCallbacks()
}
deinit {
CFURLSessionEasyHandleDeinit(rawHandle)
}
}
extension _EasyHandle: Equatable {}
internal func ==(lhs: _EasyHandle, rhs: _EasyHandle) -> Bool {
return lhs.rawHandle == rhs.rawHandle
}
extension _EasyHandle {
enum _Action {
case abort
case proceed
case pause
}
enum _WriteBufferResult {
case abort
case pause
/// Write the given number of bytes into the buffer
case bytes(Int)
}
}
internal extension _EasyHandle {
func completedTransfer(withError error: NSError?) {
delegate?.transferCompleted(withError: error)
}
}
internal protocol _EasyHandleDelegate: class {
/// Handle data read from the network.
/// - returns: the action to be taken: abort, proceed, or pause.
func didReceive(data: Data) -> _EasyHandle._Action
/// Handle header data read from the network.
/// - returns: the action to be taken: abort, proceed, or pause.
func didReceive(headerData data: Data, contentLength: Int64) -> _EasyHandle._Action
/// Fill a buffer with data to be sent.
///
/// - parameter data: The buffer to fill
/// - returns: the number of bytes written to the `data` buffer, or `nil` to stop the current transfer immediately.
func fill(writeBuffer buffer: UnsafeMutableBufferPointer<Int8>) -> _EasyHandle._WriteBufferResult
/// The transfer for this handle completed.
/// - parameter errorCode: An NSURLError code, or `nil` if no error occurred.
func transferCompleted(withError error: NSError?)
/// Seek the input stream to the given position
func seekInputStream(to position: UInt64) throws
/// Gets called during the transfer to update progress.
func updateProgressMeter(with propgress: _EasyHandle._Progress)
}
extension _EasyHandle {
func set(verboseModeOn flag: Bool) {
try! CFURLSession_easy_setopt_long(rawHandle, CFURLSessionOptionVERBOSE, flag ? 1 : 0).asError()
}
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CFURLSessionOptionDEBUGFUNCTION.html
func set(debugOutputOn flag: Bool, task: URLSessionTask) {
if flag {
try! CFURLSession_easy_setopt_ptr(rawHandle, CFURLSessionOptionDEBUGDATA, UnsafeMutableRawPointer(Unmanaged.passUnretained(task).toOpaque())).asError()
try! CFURLSession_easy_setopt_dc(rawHandle, CFURLSessionOptionDEBUGFUNCTION, printLibcurlDebug(handle:type:data:size:userInfo:)).asError()
} else {
try! CFURLSession_easy_setopt_ptr(rawHandle, CFURLSessionOptionDEBUGDATA, nil).asError()
try! CFURLSession_easy_setopt_ptr(rawHandle, CFURLSessionOptionDEBUGFUNCTION, nil).asError()
}
}
func set(passHeadersToDataStream flag: Bool) {
try! CFURLSession_easy_setopt_long(rawHandle, CFURLSessionOptionHEADER, flag ? 1 : 0).asError()
}
/// Follow any Location: header that the server sends as part of a HTTP header in a 3xx response
func set(followLocation flag: Bool) {
try! CFURLSession_easy_setopt_long(rawHandle, CFURLSessionOptionFOLLOWLOCATION, flag ? 1 : 0).asError()
}
/// Switch off the progress meter. It will also prevent the CFURLSessionOptionPROGRESSFUNCTION from getting called.
func set(progressMeterOff flag: Bool) {
try! CFURLSession_easy_setopt_long(rawHandle, CFURLSessionOptionNOPROGRESS, flag ? 1 : 0).asError()
}
/// Skip all signal handling
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_NOSIGNAL.html
func set(skipAllSignalHandling flag: Bool) {
try! CFURLSession_easy_setopt_long(rawHandle, CFURLSessionOptionNOSIGNAL, flag ? 1 : 0).asError()
}
/// Set error buffer for error messages
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_ERRORBUFFER.html
func set(errorBuffer buffer: UnsafeMutableBufferPointer<UInt8>?) {
let buffer = buffer ?? errorBuffer.withUnsafeMutableBufferPointer { $0 }
try! CFURLSession_easy_setopt_ptr(rawHandle, CFURLSessionOptionERRORBUFFER, buffer.baseAddress).asError()
}
/// Request failure on HTTP response >= 400
func set(failOnHTTPErrorCode flag: Bool) {
try! CFURLSession_easy_setopt_long(rawHandle, CFURLSessionOptionFAILONERROR, flag ? 1 : 0).asError()
}
/// URL to use in the request
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_URL.html
func set(url: URL) {
_url = url
url.absoluteString.withCString {
try! CFURLSession_easy_setopt_ptr(rawHandle, CFURLSessionOptionURL, UnsafeMutablePointer(mutating: $0)).asError()
}
}
func set(sessionConfig config: URLSession._Configuration) {
_config = config
}
/// Set allowed protocols
///
/// - Note: This has security implications. Not limiting this, someone could
/// redirect a HTTP request into one of the many other protocols that libcurl
/// supports.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_PROTOCOLS.html
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_REDIR_PROTOCOLS.html
func setAllowedProtocolsToHTTPAndHTTPS() {
let protocols = (CFURLSessionProtocolHTTP | CFURLSessionProtocolHTTPS)
try! CFURLSession_easy_setopt_long(rawHandle, CFURLSessionOptionPROTOCOLS, protocols).asError()
try! CFURLSession_easy_setopt_long(rawHandle, CFURLSessionOptionREDIR_PROTOCOLS, protocols).asError()
#if os(Android)
// See https://curl.haxx.se/docs/sslcerts.html
// For SSL on Android you need a "cacert.pem" to be
// accessible at the path pointed to by this env var.
// Downloadable here: https://curl.haxx.se/ca/cacert.pem
if let caInfo = getenv("URLSessionCertificateAuthorityInfoFile") {
if String(cString: caInfo) == "INSECURE_SSL_NO_VERIFY" {
try! CFURLSession_easy_setopt_long(rawHandle, CFURLSessionOptionSSL_VERIFYPEER, 0).asError()
}
else {
try! CFURLSession_easy_setopt_ptr(rawHandle, CFURLSessionOptionCAINFO, caInfo).asError()
}
}
#endif
//TODO: Added in libcurl 7.45.0
//TODO: Set default protocol for schemeless URLs
//CURLOPT_DEFAULT_PROTOCOL available only in libcurl 7.45.0
}
//TODO: Proxy setting, namely CFURLSessionOptionPROXY, CFURLSessionOptionPROXYPORT,
// CFURLSessionOptionPROXYTYPE, CFURLSessionOptionNOPROXY, CFURLSessionOptionHTTPPROXYTUNNEL, CFURLSessionOptionPROXYHEADER,
// CFURLSessionOptionHEADEROPT, etc.
/// set preferred receive buffer size
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_BUFFERSIZE.html
func set(preferredReceiveBufferSize size: Int) {
try! CFURLSession_easy_setopt_long(rawHandle, CFURLSessionOptionBUFFERSIZE, numericCast(min(size, Int(CFURLSessionMaxWriteSize)))).asError()
}
/// Set custom HTTP headers
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_HTTPHEADER.html
func set(customHeaders headers: [String]) {
let list = _CurlStringList(headers)
try! CFURLSession_easy_setopt_ptr(rawHandle, CFURLSessionOptionHTTPHEADER, list.asUnsafeMutablePointer).asError()
// We need to retain the list for as long as the rawHandle is in use.
headerList = list
}
///TODO: Wait for pipelining/multiplexing. Unavailable on Ubuntu 14.0
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_PIPEWAIT.html
//TODO: The public API does not allow us to use CFURLSessionOptionSTREAM_DEPENDS / CFURLSessionOptionSTREAM_DEPENDS_E
// Might be good to add support for it, though.
///TODO: Set numerical stream weight when CURLOPT_PIPEWAIT is enabled
/// - Parameter weight: values are clamped to lie between 0 and 1
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_STREAM_WEIGHT.html
/// - SeeAlso: http://httpwg.org/specs/rfc7540.html#StreamPriority
/// Enable automatic decompression of HTTP downloads
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_ACCEPT_ENCODING.html
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_HTTP_CONTENT_DECODING.html
func set(automaticBodyDecompression flag: Bool) {
if flag {
"".withCString {
try! CFURLSession_easy_setopt_ptr(rawHandle, CFURLSessionOptionACCEPT_ENCODING, UnsafeMutableRawPointer(mutating: $0)).asError()
}
try! CFURLSession_easy_setopt_long(rawHandle, CFURLSessionOptionHTTP_CONTENT_DECODING, 1).asError()
} else {
try! CFURLSession_easy_setopt_ptr(rawHandle, CFURLSessionOptionACCEPT_ENCODING, nil).asError()
try! CFURLSession_easy_setopt_long(rawHandle, CFURLSessionOptionHTTP_CONTENT_DECODING, 0).asError()
}
}
/// Set request method
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_CUSTOMREQUEST.html
func set(requestMethod method: String) {
method.withCString {
try! CFURLSession_easy_setopt_ptr(rawHandle, CFURLSessionOptionCUSTOMREQUEST, UnsafeMutableRawPointer(mutating: $0)).asError()
}
}
/// Download request without body
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_NOBODY.html
func set(noBody flag: Bool) {
try! CFURLSession_easy_setopt_long(rawHandle, CFURLSessionOptionNOBODY, flag ? 1 : 0).asError()
}
/// Enable data upload
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_UPLOAD.html
func set(upload flag: Bool) {
try! CFURLSession_easy_setopt_long(rawHandle, CFURLSessionOptionUPLOAD, flag ? 1 : 0).asError()
}
/// Set size of the request body to send
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_INFILESIZE_LARGE.html
func set(requestBodyLength length: Int64) {
try! CFURLSession_easy_setopt_int64(rawHandle, CFURLSessionOptionINFILESIZE_LARGE, length).asError()
}
func set(timeout value: Int) {
try! CFURLSession_easy_setopt_long(rawHandle, CFURLSessionOptionTIMEOUT, numericCast(value)).asError()
}
func getTimeoutIntervalSpent() -> Double {
var timeSpent = Double()
CFURLSession_easy_getinfo_double(rawHandle, CFURLSessionInfoTOTAL_TIME, &timeSpent)
return timeSpent / 1000
}
}
fileprivate func printLibcurlDebug(handle: CFURLSessionEasyHandle, type: CInt, data: UnsafeMutablePointer<Int8>, size: Int, userInfo: UnsafeMutableRawPointer?) -> CInt {
// C.f. <https://curl.haxx.se/libcurl/c/CURLOPT_DEBUGFUNCTION.html>
let info = CFURLSessionInfo(value: type)
let text = data.withMemoryRebound(to: UInt8.self, capacity: size, {
let buffer = UnsafeBufferPointer<UInt8>(start: $0, count: size)
return String(utf8Buffer: buffer)
}) ?? "";
guard let userInfo = userInfo else { return 0 }
let task = Unmanaged<URLSessionTask>.fromOpaque(userInfo).takeUnretainedValue()
printLibcurlDebug(type: info, data: text, task: task)
return 0
}
fileprivate func printLibcurlDebug(type: CFURLSessionInfo, data: String, task: URLSessionTask) {
// libcurl sends is data with trailing CRLF which inserts lots of newlines into our output.
NSLog("[\(task.taskIdentifier)] \(type.debugHeader) \(data.mapControlToPictures)")
}
fileprivate extension String {
/// Replace control characters U+0000 - U+0019 to Control Pictures U+2400 - U+2419
var mapControlToPictures: String {
let d = self.unicodeScalars.map { (u: UnicodeScalar) -> UnicodeScalar in
switch u.value {
case 0..<0x20: return UnicodeScalar(u.value + 0x2400)!
default: return u
}
}
return String(String.UnicodeScalarView(d))
}
}
extension _EasyHandle {
/// Send and/or receive pause state for an `EasyHandle`
struct _PauseState : OptionSet {
let rawValue: Int8
init(rawValue: Int8) { self.rawValue = rawValue }
static let receivePaused = _PauseState(rawValue: 1 << 0)
static let sendPaused = _PauseState(rawValue: 1 << 1)
}
}
extension _EasyHandle._PauseState {
func setState(on handle: _EasyHandle) {
try! CFURLSessionEasyHandleSetPauseState(handle.rawHandle, contains(.sendPaused) ? 1 : 0, contains(.receivePaused) ? 1 : 0).asError()
}
}
extension _EasyHandle._PauseState : TextOutputStreamable {
func write<Target : TextOutputStream>(to target: inout Target) {
switch (self.contains(.receivePaused), self.contains(.sendPaused)) {
case (false, false): target.write("unpaused")
case (true, false): target.write("receive paused")
case (false, true): target.write("send paused")
case (true, true): target.write("send & receive paused")
}
}
}
extension _EasyHandle {
/// Pause receiving data.
///
/// - SeeAlso: https://curl.haxx.se/libcurl/c/curl_easy_pause.html
func pauseReceive() {
guard !pauseState.contains(.receivePaused) else { return }
pauseState.insert(.receivePaused)
pauseState.setState(on: self)
}
/// Pause receiving data.
///
/// - Note: Chances are high that delegate callbacks (with pending data)
/// will be called before this method returns.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/curl_easy_pause.html
func unpauseReceive() {
guard pauseState.contains(.receivePaused) else { return }
pauseState.remove(.receivePaused)
pauseState.setState(on: self)
}
/// Pause sending data.
///
/// - SeeAlso: https://curl.haxx.se/libcurl/c/curl_easy_pause.html
func pauseSend() {
guard !pauseState.contains(.sendPaused) else { return }
pauseState.insert(.sendPaused)
pauseState.setState(on: self)
}
/// Pause sending data.
///
/// - Note: Chances are high that delegate callbacks (with pending data)
/// will be called before this method returns.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/curl_easy_pause.html
func unpauseSend() {
guard pauseState.contains(.sendPaused) else { return }
pauseState.remove(.sendPaused)
pauseState.setState(on: self)
}
}
internal extension _EasyHandle {
/// errno number from last connect failure
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLINFO_OS_ERRNO.html
var connectFailureErrno: Int {
#if os(Windows) && (arch(arm64) || arch(x86_64))
var errno = Int32()
#else
var errno = Int()
#endif
try! CFURLSession_easy_getinfo_long(rawHandle, CFURLSessionInfoOS_ERRNO, &errno).asError()
return numericCast(errno)
}
}
extension CFURLSessionInfo : Equatable {
public static func ==(lhs: CFURLSessionInfo, rhs: CFURLSessionInfo) -> Bool {
return lhs.value == rhs.value
}
}
extension CFURLSessionInfo {
public var debugHeader: String {
switch self {
case CFURLSessionInfoTEXT: return " "
case CFURLSessionInfoHEADER_OUT: return "=> Send header ";
case CFURLSessionInfoDATA_OUT: return "=> Send data ";
case CFURLSessionInfoSSL_DATA_OUT: return "=> Send SSL data ";
case CFURLSessionInfoHEADER_IN: return "<= Recv header ";
case CFURLSessionInfoDATA_IN: return "<= Recv data ";
case CFURLSessionInfoSSL_DATA_IN: return "<= Recv SSL data ";
default: return " "
}
}
}
extension _EasyHandle {
/// the URL a redirect would go to
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLINFO_REDIRECT_URL.html
var redirectURL: URL? {
var p: UnsafeMutablePointer<Int8>? = nil
try! CFURLSession_easy_getinfo_charp(rawHandle, CFURLSessionInfoREDIRECT_URL, &p).asError()
guard let cstring = p else { return nil }
guard let s = String(cString: cstring, encoding: .utf8) else { return nil }
return URL(string: s)
}
}
fileprivate extension _EasyHandle {
static func from(callbackUserData userdata: UnsafeMutableRawPointer?) -> _EasyHandle? {
guard let userdata = userdata else { return nil }
return Unmanaged<_EasyHandle>.fromOpaque(userdata).takeUnretainedValue()
}
}
fileprivate extension _EasyHandle {
func resetTimer() {
//simply create a new timer with the same queue, timeout and handler
//this must cancel the old handler and reset the timer
timeoutTimer = _TimeoutSource(queue: timeoutTimer.queue, milliseconds: timeoutTimer.milliseconds, handler: timeoutTimer.handler)
}
/// Forward the libcurl callbacks into Swift methods
func setupCallbacks() {
// write
try! CFURLSession_easy_setopt_ptr(rawHandle, CFURLSessionOptionWRITEDATA, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())).asError()
try! CFURLSession_easy_setopt_wc(rawHandle, CFURLSessionOptionWRITEFUNCTION) { (data: UnsafeMutablePointer<Int8>, size: Int, nmemb: Int, userdata: UnsafeMutableRawPointer?) -> Int in
guard let handle = _EasyHandle.from(callbackUserData: userdata) else { return 0 }
defer {
handle.resetTimer()
}
return handle.didReceive(data: data, size: size, nmemb: nmemb)
}.asError()
// read
try! CFURLSession_easy_setopt_ptr(rawHandle, CFURLSessionOptionREADDATA, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())).asError()
try! CFURLSession_easy_setopt_wc(rawHandle, CFURLSessionOptionREADFUNCTION) { (data: UnsafeMutablePointer<Int8>, size: Int, nmemb: Int, userdata: UnsafeMutableRawPointer?) -> Int in
guard let handle = _EasyHandle.from(callbackUserData: userdata) else { return 0 }
defer {
handle.resetTimer()
}
return handle.fill(writeBuffer: data, size: size, nmemb: nmemb)
}.asError()
// header
try! CFURLSession_easy_setopt_ptr(rawHandle, CFURLSessionOptionHEADERDATA, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())).asError()
try! CFURLSession_easy_setopt_wc(rawHandle, CFURLSessionOptionHEADERFUNCTION) { (data: UnsafeMutablePointer<Int8>, size: Int, nmemb: Int, userdata: UnsafeMutableRawPointer?) -> Int in
guard let handle = _EasyHandle.from(callbackUserData: userdata) else { return 0 }
defer {
handle.resetTimer()
}
var length = Double()
try! CFURLSession_easy_getinfo_double(handle.rawHandle, CFURLSessionInfoCONTENT_LENGTH_DOWNLOAD, &length).asError()
return handle.didReceive(headerData: data, size: size, nmemb: nmemb, contentLength: length)
}.asError()
// socket options
try! CFURLSession_easy_setopt_ptr(rawHandle, CFURLSessionOptionSOCKOPTDATA, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())).asError()
try! CFURLSession_easy_setopt_sc(rawHandle, CFURLSessionOptionSOCKOPTFUNCTION) { (userdata: UnsafeMutableRawPointer?, fd: CInt, type: CFURLSessionSocketType) -> CInt in
guard let handle = _EasyHandle.from(callbackUserData: userdata) else { return 0 }
guard type == CFURLSessionSocketTypeIPCXN else { return 0 }
do {
try handle.setSocketOptions(for: fd)
return 0
} catch {
return 1
}
}.asError()
// seeking in input stream
try! CFURLSession_easy_setopt_ptr(rawHandle, CFURLSessionOptionSEEKDATA, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())).asError()
try! CFURLSession_easy_setopt_seek(rawHandle, CFURLSessionOptionSEEKFUNCTION, { (userdata, offset, origin) -> Int32 in
guard let handle = _EasyHandle.from(callbackUserData: userdata) else { return CFURLSessionSeekFail }
return handle.seekInputStream(offset: offset, origin: origin)
}).asError()
// progress
try! CFURLSession_easy_setopt_long(rawHandle, CFURLSessionOptionNOPROGRESS, 0).asError()
try! CFURLSession_easy_setopt_ptr(rawHandle, CFURLSessionOptionPROGRESSDATA, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())).asError()
try! CFURLSession_easy_setopt_tc(rawHandle, CFURLSessionOptionXFERINFOFUNCTION, { (userdata: UnsafeMutableRawPointer?, dltotal :Int64, dlnow: Int64, ultotal: Int64, ulnow: Int64) -> Int32 in
guard let handle = _EasyHandle.from(callbackUserData: userdata) else { return -1 }
handle.updateProgressMeter(with: _Progress(totalBytesSent: ulnow, totalBytesExpectedToSend: ultotal, totalBytesReceived: dlnow, totalBytesExpectedToReceive: dltotal))
return 0
}).asError()
}
/// This callback function gets called by libcurl when it receives body
/// data.
///
/// - SeeAlso: <https://curl.haxx.se/libcurl/c/CURLOPT_WRITEFUNCTION.html>
func didReceive(data: UnsafeMutablePointer<Int8>, size: Int, nmemb: Int) -> Int {
let d: Int = {
let buffer = Data(bytes: data, count: size*nmemb)
switch delegate?.didReceive(data: buffer) {
case .proceed?: return size * nmemb
case .abort?: return 0
case .pause?:
pauseState.insert(.receivePaused)
return Int(CFURLSessionWriteFuncPause)
case nil:
/* the delegate disappeared */
return 0
}
}()
return d
}
/// This callback function gets called by libcurl when it receives header
/// data.
///
/// - SeeAlso: <https://curl.haxx.se/libcurl/c/CURLOPT_HEADERFUNCTION.html>
func didReceive(headerData data: UnsafeMutablePointer<Int8>, size: Int, nmemb: Int, contentLength: Double) -> Int {
let buffer = Data(bytes: data, count: size*nmemb)
let d: Int = {
switch delegate?.didReceive(headerData: buffer, contentLength: Int64(contentLength)) {
case .proceed?: return size * nmemb
case .abort?: return 0
case .pause?:
pauseState.insert(.receivePaused)
return Int(CFURLSessionWriteFuncPause)
case nil:
/* the delegate disappeared */
return 0
}
}()
setCookies(headerData: buffer)
return d
}
func setCookies(headerData data: Data) {
guard let config = _config, config.httpCookieAcceptPolicy != HTTPCookie.AcceptPolicy.never else { return }
guard let headerData = String(data: data, encoding: String.Encoding.utf8) else { return }
// Convert headerData from a string to a dictionary.
// Ignore headers like 'HTTP/1.1 200 OK\r\n' which do not have a key value pair.
// Value can have colons (ie, date), so only split at the first one, ie header:value
let headerComponents = headerData.split(separator: ":", maxSplits: 1)
var headers: [String: String] = [:]
//Trim the leading and trailing whitespaces (if any) before adding the header information to the dictionary.
if headerComponents.count > 1 {
headers[String(headerComponents[0].trimmingCharacters(in: .whitespacesAndNewlines))] = headerComponents[1].trimmingCharacters(in: .whitespacesAndNewlines)
}
let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: _url!)
guard cookies.count > 0 else { return }
if let cookieStorage = config.httpCookieStorage {
cookieStorage.setCookies(cookies, for: _url, mainDocumentURL: nil)
}
}
/// This callback function gets called by libcurl when it wants to send data
/// it to the network.
///
/// - SeeAlso: <https://curl.haxx.se/libcurl/c/CURLOPT_READFUNCTION.html>
func fill(writeBuffer data: UnsafeMutablePointer<Int8>, size: Int, nmemb: Int) -> Int {
let d: Int = {
let buffer = UnsafeMutableBufferPointer(start: data, count: size * nmemb)
switch delegate?.fill(writeBuffer: buffer) {
case .pause?:
pauseState.insert(.sendPaused)
return Int(CFURLSessionReadFuncPause)
case .abort?:
return Int(CFURLSessionReadFuncAbort)
case .bytes(let length)?:
return length
case nil:
/* the delegate disappeared */
return Int(CFURLSessionReadFuncAbort)
}
}()
return d
}
func setSocketOptions(for fd: CInt) throws {
//TODO: At this point we should call setsockopt(2) to set the QoS on
// the socket based on the QoS of the request.
//
// On Linux this can be done with IP_TOS. But there's both IntServ and
// DiffServ.
//
// Not sure what Darwin uses.
//
// C.f.:
// <https://en.wikipedia.org/wiki/Type_of_service>
// <https://en.wikipedia.org/wiki/Quality_of_service>
}
func updateProgressMeter(with propgress: _Progress) {
delegate?.updateProgressMeter(with: propgress)
}
func seekInputStream(offset: Int64, origin: CInt) -> CInt {
let d: Int32 = {
/// libcurl should only use SEEK_SET
guard origin == SEEK_SET else { fatalError("Unexpected 'origin' in seek.") }
do {
if let delegate = delegate {
try delegate.seekInputStream(to: UInt64(offset))
return CFURLSessionSeekOk
} else {
return CFURLSessionSeekCantSeek
}
} catch {
return CFURLSessionSeekCantSeek
}
}()
return d
}
}
extension _EasyHandle {
/// The progress of a transfer.
///
/// The number of bytes that we expect to download and upload, and the
/// number of bytes downloaded and uploaded so far.
///
/// Unknown values will be set to zero. E.g. if the number of bytes
/// expected to be downloaded is unknown, `totalBytesExpectedToReceive`
/// will be zero.
struct _Progress {
let totalBytesSent: Int64
let totalBytesExpectedToSend: Int64
let totalBytesReceived: Int64
let totalBytesExpectedToReceive: Int64
}
}
extension _EasyHandle {
/// A simple wrapper / helper for libcurl’s `slist`.
///
/// It's libcurl's way to represent an array of strings.
internal class _CurlStringList {
fileprivate var rawList: OpaquePointer? = nil
init() {}
init(_ strings: [String]) {
strings.forEach { append($0) }
}
deinit {
CFURLSessionSListFreeAll(rawList)
}
}
}
extension _EasyHandle._CurlStringList {
func append(_ string: String) {
string.withCString {
rawList = CFURLSessionSListAppend(rawList, $0)
}
}
var asUnsafeMutablePointer: UnsafeMutableRawPointer? {
return rawList.map{ UnsafeMutableRawPointer($0) }
}
}
extension CFURLSessionEasyCode : Equatable {
public static func ==(lhs: CFURLSessionEasyCode, rhs: CFURLSessionEasyCode) -> Bool {
return lhs.value == rhs.value
}
}
extension CFURLSessionEasyCode : Error {
public var _domain: String { return "libcurl.Easy" }
public var _code: Int { return Int(self.value) }
}
internal extension CFURLSessionEasyCode {
func asError() throws {
if self == CFURLSessionEasyCodeOK { return }
throw self
}
}
| apache-2.0 |
SuPair/iContactU | iContactU/AppDelegate.swift | 2 | 4357 | //
// AppDelegate.swift
// Test
//
// Created by Riccardo Sallusti on 06/09/14.
// Copyright (c) 2014 Riccardo Sallusti. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
UINavigationBar.appearance().barTintColor = UIColor(hexString: "ef3c39")
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
if BreezeStore.iCloudAvailable() {
BreezeStore.setupiCloudStoreWithContentNameKey("iCloud\(BreezeStore.appName)", localStoreName: "\(BreezeStore.appName)", transactionLogs: "iCloud_transactions_logs")
println("iCloud store created.")
} else {
BreezeStore.setupStoreWithName("\(BreezeStore.appName)", storeType: NSSQLiteStoreType, options: [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true])
println("local store created.")
}
var version:NSString = UIDevice.currentDevice().systemVersion as NSString;
if version.doubleValue >= 8 {
// ios 8 code
let notificationTypes:UIUserNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
let notificationSettings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
}
else{
// FOR IOS7 IT IS NOT NECESSARY
/*
UIApplication.sharedApplication().registerForRemoteNotificationTypes(UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound | UIRemoteNotificationType.Alert)*/
}
//UIApplication.sharedApplication().cancelAllLocalNotifications()
let notificationsCount = UIApplication.sharedApplication().scheduledLocalNotifications.count
println("ALL SCHEDULED NOTIFICATIONS: \(notificationsCount)")
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
//self.saveContext()
}
}
| mit |
Roommate-App/roomy | roomy/Pods/IBAnimatable/Sources/Controllers/AnimatableTableViewController.swift | 5 | 3528 | //
// Created by phimage on 26/03/2017.
// Copyright © 2017 IBAnimatable. All rights reserved.
//
import UIKit
@IBDesignable
open class AnimatableTableViewController: UITableViewController, ViewControllerDesignable, StatusBarDesignable,
RootWindowDesignable, TransitionAnimatable, RefreshControlDesignable {
// MARK: - ViewControllerDesignable
@IBInspectable open var hideNavigationBar: Bool = false
// MARK: - StatusBarDesignable
@IBInspectable open var lightStatusBar: Bool = false
// MARK: - RootWindowDesignable
@IBInspectable open var rootWindowBackgroundColor: UIColor?
// MARK: - TransitionAnimatable
@IBInspectable var _transitionAnimationType: String? {
didSet {
if let _transitionAnimationType = _transitionAnimationType {
transitionAnimationType = TransitionAnimationType(string: _transitionAnimationType)
}
}
}
open var transitionAnimationType: TransitionAnimationType = .none
@IBInspectable open var transitionDuration: Double = .nan
open var interactiveGestureType: InteractiveGestureType = .none
@IBInspectable var _interactiveGestureType: String? {
didSet {
if let _interactiveGestureType = _interactiveGestureType {
interactiveGestureType = InteractiveGestureType(string: _interactiveGestureType)
}
}
}
// MARK: - RefreshControlDesignable
@IBInspectable open var hasRefreshControl: Bool = false {
didSet {
configureRefreshController()
}
}
@IBInspectable open var refreshControlTintColor: UIColor? {
didSet {
configureRefreshController()
}
}
@IBInspectable open var refreshControlBackgroundColor: UIColor? {
didSet {
configureRefreshController()
}
}
// MARK: - Lifecylce
open override func viewDidLoad() {
super.viewDidLoad()
configureRefreshController()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
configureHideNavigationBar()
configureRootWindowBackgroundColor()
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
resetHideNavigationBar()
}
open override var preferredStatusBarStyle: UIStatusBarStyle {
if lightStatusBar {
return .lightContent
}
return .default
}
open override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
// Configure custom transition animation
guard (segue.destination is PresentationDesignable) == false else {
return
}
if case .none = transitionAnimationType {
return
}
let toViewController = segue.destination
// If interactiveGestureType hasn't been set
let transitionManager = TransitionPresenterManager.shared
if case .none = interactiveGestureType {
toViewController.transitioningDelegate = transitionManager.retrievePresenter(transitionAnimationType: transitionAnimationType,
transitionDuration: transitionDuration)
} else {
toViewController.transitioningDelegate = transitionManager.retrievePresenter(transitionAnimationType: transitionAnimationType,
transitionDuration: transitionDuration,
interactiveGestureType: interactiveGestureType)
}
}
}
| mit |
adrfer/swift | validation-test/compiler_crashers_fixed/25374-swift-diagnosticengine-emitdiagnostic.swift | 13 | 260 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a{{}func a{{{}}}protocol c:a{var:a}let a
| apache-2.0 |
ray3132138/TestKitchen_1606 | TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBSearchHeaderView.swift | 1 | 1560 | //
// CBSearchHeaderView.swift
// TestKitchen
//
// Created by qianfeng on 16/8/18.
// Copyright © 2016年 ray. All rights reserved.
//
import UIKit
class CBSearchHeaderView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
/*
//创建一个搜索框
let searchBar = UISearchBar(frame: CGRectMake(0,0,bounds.size.width,bounds.size.height))
searchBar.placeholder = "输入菜名或食材搜索"
//searchBar的背景颜色修改
//searchBar.barTintColor = UIColor.whiteColor()
addSubview(searchBar)
*/
let textField = UITextField(frame: CGRectMake(40,4,bounds.size.width-40*2,bounds.size.height-4*2))
textField.borderStyle = .RoundedRect
textField.placeholder = "输入菜名或食材搜索"
addSubview(textField)
//左边搜索图片
let imageView = UIImageView.createImageView("search1")
imageView.frame = CGRectMake(0, 0, 25, 25)
textField.leftView = imageView
textField.leftViewMode = .Always
backgroundColor = UIColor(white: 0.8, alpha: 1.0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| mit |
bunnyblue/actor-platform | actor-apps/app-ios/Actor/Resources/AppTheme.swift | 18 | 13941 | //
// Copyright (c) 2015 Actor LLC. <https://actor.im>
//
import Foundation
var MainAppTheme = AppTheme()
class AppTheme {
var navigation: AppNavigationBar { get { return AppNavigationBar() } }
var tab: AppTabBar { get { return AppTabBar() } }
var search: AppSearchBar { get { return AppSearchBar() } }
var list: AppList { get { return AppList() } }
var bubbles: ChatBubbles { get { return ChatBubbles() } }
var text: AppText { get { return AppText() } }
var chat: AppChat { get { return AppChat() } }
var common: AppCommon { get { return AppCommon() } }
func applyAppearance(application: UIApplication) {
navigation.applyAppearance(application)
tab.applyAppearance(application)
search.applyAppearance(application)
list.applyAppearance(application)
}
}
class AppText {
var textPrimary: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } }
}
class AppChat {
var chatField: UIColor { get { return UIColor.whiteColor() } }
var attachColor: UIColor { get { return UIColor.RGB(0x5085CB) } }
var sendEnabled: UIColor { get { return UIColor.RGB(0x50A1D6) } }
var sendDisabled: UIColor { get { return UIColor.alphaBlack(0.56) } }
var profileBgTint: UIColor { get { return UIColor.RGB(0x5085CB) } }
}
class AppCommon {
var isDarkKeyboard: Bool { get { return false } }
var tokenFieldText: UIColor { get { return UIColor.alphaBlack(0xDE/255.0) } }
var tokenFieldTextSelected: UIColor { get { return UIColor.alphaBlack(0xDE/255.0) } }
var tokenFieldBg: UIColor { get { return UIColor.RGB(0x5085CB) } }
}
class ChatBubbles {
// Basic colors
var text : UIColor { get { return UIColor.RGB(0x141617) } }
var textUnsupported : UIColor { get { return UIColor.RGB(0x50b1ae) } }
var bgOut: UIColor { get { return UIColor.RGB(0xD2FEFD) } }
var bgOutBorder: UIColor { get { return UIColor.RGB(0x99E4E3) } }
var bgIn : UIColor { get { return UIColor.whiteColor() } }
var bgInBorder:UIColor { get { return UIColor.RGB(0xCCCCCC) } }
var statusActive : UIColor { get { return UIColor.RGB(0x3397f9) } }
var statusPassive : UIColor { get { return UIColor.alphaBlack(0.27) } }
// TODO: Fix
var statusDanger : UIColor { get { return UIColor.redColor() } }
var statusMediaActive : UIColor { get { return UIColor.RGB(0x1ed2f9) } }
var statusMediaPassive : UIColor { get { return UIColor.whiteColor() } }
// TODO: Fix
var statusMediaDanger : UIColor { get { return UIColor.redColor() } }
var statusDialogActive : UIColor { get { return UIColor.RGB(0x3397f9) } }
var statusDialogPassive : UIColor { get { return UIColor.alphaBlack(0.27) } }
// TODO: Fix
var statusDialogDanger : UIColor { get { return UIColor.redColor() } }
// Dialog-based colors
var statusDialogSending : UIColor { get { return statusDialogPassive } }
var statusDialogSent : UIColor { get { return statusDialogPassive } }
var statusDialogReceived : UIColor { get { return statusDialogPassive } }
var statusDialogRead : UIColor { get { return statusDialogActive } }
var statusDialogError : UIColor { get { return statusDialogDanger } }
// Text-based bubble colors
var statusSending : UIColor { get { return statusPassive } }
var statusSent : UIColor { get { return statusPassive } }
var statusReceived : UIColor { get { return statusPassive } }
var statusRead : UIColor { get { return statusActive } }
var statusError : UIColor { get { return statusDanger } }
var textBgOut: UIColor { get { return bgOut } }
var textBgOutBorder : UIColor { get { return bgOutBorder } }
var textBgIn : UIColor { get { return bgIn } }
var textBgInBorder : UIColor { get { return bgInBorder } }
var textDateOut : UIColor { get { return UIColor.alphaBlack(0.27) } }
var textDateIn : UIColor { get { return UIColor.RGB(0x979797) } }
var textOut : UIColor { get { return text } }
var textIn : UIColor { get { return text } }
var textUnsupportedOut : UIColor { get { return textUnsupported } }
var textUnsupportedIn : UIColor { get { return textUnsupported } }
// Media-based bubble colors
var statusMediaSending : UIColor { get { return statusMediaPassive } }
var statusMediaSent : UIColor { get { return statusMediaPassive } }
var statusMediaReceived : UIColor { get { return statusMediaPassive } }
var statusMediaRead : UIColor { get { return statusMediaActive } }
var statusMediaError : UIColor { get { return statusMediaDanger } }
var mediaBgOut: UIColor { get { return UIColor.whiteColor() } }
var mediaBgOutBorder: UIColor { get { return UIColor.RGB(0xCCCCCC) } }
var mediaBgIn: UIColor { get { return mediaBgOut } }
var mediaBgInBorder: UIColor { get { return mediaBgOutBorder } }
var mediaDateBg: UIColor { get { return UIColor.RGB(0x2D394A, alpha: 0.54) } }
var mediaDate: UIColor { get { return UIColor.whiteColor() } }
// Service-based bubble colors
var serviceBg: UIColor { get { return UIColor.RGB(0x2D394A, alpha: 0.56) } }
var chatBgTint: UIColor { get { return UIColor.RGB(0xe7e0c4) } }
}
class AppList {
var actionColor : UIColor { get { return UIColor.RGB(0x5085CB) } }
var bgColor: UIColor { get { return UIColor.whiteColor() } }
var bgSelectedColor : UIColor { get { return UIColor.RGB(0xd9d9d9) } }
var backyardColor : UIColor { get { return UIColor(red: 238/255.0, green: 238/255.0, blue: 238/255.0, alpha: 1) } }
var separatorColor : UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0x1e/255.0) } }
var textColor : UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } }
var hintColor : UIColor { get { return UIColor(red: 164/255.0, green: 164/255.0, blue: 164/255.0, alpha: 1) } }
var sectionColor : UIColor { get { return UIColor(red: 164/255.0, green: 164/255.0, blue: 164/255.0, alpha: 1) } }
// var arrowColor : UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } }
var dialogTitle: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } }
var dialogText: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0x8A/255.0) } }
var dialogDate: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0x8A/255.0) } }
var unreadText: UIColor { get { return UIColor.whiteColor() } }
var unreadBg: UIColor { get { return UIColor.RGB(0x50A1D6) } }
var contactsTitle: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } }
var contactsShortTitle: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } }
func applyAppearance(application: UIApplication) {
UITableViewHeaderFooterView.appearance().tintColor = sectionColor
}
}
class AppSearchBar {
var statusBarLightContent : Bool { get { return false } }
var backgroundColor : UIColor { get { return UIColor.RGB(0xf1f1f1) } }
var cancelColor : UIColor { get { return UIColor.RGB(0x8E8E93) } }
var fieldBackgroundColor: UIColor { get { return UIColor.whiteColor() } }
var fieldTextColor: UIColor { get { return UIColor.blackColor().alpha(0.56) } }
func applyAppearance(application: UIApplication) {
// SearchBar Text Color
var textField = UITextField.my_appearanceWhenContainedIn(UISearchBar.self)
// textField.tintColor = UIColor.redColor()
var font = UIFont(name: "HelveticaNeue", size: 14.0)
textField.defaultTextAttributes = [NSFontAttributeName: font!,
NSForegroundColorAttributeName : fieldTextColor]
}
func applyStatusBar() {
if (statusBarLightContent) {
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
} else {
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true)
}
}
func styleSearchBar(searchBar: UISearchBar) {
// SearchBar Minimal Style
searchBar.searchBarStyle = UISearchBarStyle.Default
// SearchBar Transculent
searchBar.translucent = false
// SearchBar placeholder animation fix
searchBar.placeholder = "";
// SearchBar background color
searchBar.barTintColor = backgroundColor.forTransparentBar()
searchBar.setBackgroundImage(Imaging.imageWithColor(backgroundColor, size: CGSize(width: 1, height: 1)), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default)
searchBar.backgroundColor = backgroundColor
// SearchBar field color
var fieldBg = Imaging.imageWithColor(fieldBackgroundColor, size: CGSize(width: 14,height: 28))
.roundCorners(14, h: 28, roundSize: 4)
searchBar.setSearchFieldBackgroundImage(fieldBg.stretchableImageWithLeftCapWidth(7, topCapHeight: 0), forState: UIControlState.Normal)
// SearchBar cancel color
searchBar.tintColor = cancelColor
}
}
class AppTabBar {
private let mainColor = UIColor.RGB(0x5085CB)
var backgroundColor : UIColor { get { return UIColor.whiteColor() } }
var showText : Bool { get { return true } }
var selectedIconColor: UIColor { get { return mainColor } }
var selectedTextColor : UIColor { get { return mainColor } }
var unselectedIconColor:UIColor { get { return mainColor.alpha(0.56) } }
var unselectedTextColor : UIColor { get { return mainColor.alpha(0.56) } }
var barShadow : String? { get { return "CardTop2" } }
func createSelectedIcon(name: String) -> UIImage {
return UIImage(named: name)!.tintImage(selectedIconColor)
.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
}
func createUnselectedIcon(name: String) -> UIImage {
return UIImage(named: name)!.tintImage(unselectedIconColor)
.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
}
func applyAppearance(application: UIApplication) {
var tabBar = UITabBar.appearance()
// TabBar Background color
tabBar.barTintColor = backgroundColor;
// TabBar Shadow
if (barShadow != nil) {
tabBar.shadowImage = UIImage(named: barShadow!);
} else {
tabBar.shadowImage = nil
}
var tabBarItem = UITabBarItem.appearance()
// TabBar Unselected Text
tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: unselectedTextColor], forState: UIControlState.Normal)
// TabBar Selected Text
tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: selectedTextColor], forState: UIControlState.Selected)
}
}
class AppNavigationBar {
var statusBarLightContent : Bool { get { return true } }
var barColor:UIColor { get { return /*UIColor.RGB(0x5085CB)*/ UIColor.RGB(0x3576cc) } }
var barSolidColor:UIColor { get { return UIColor.RGB(0x5085CB) } }
var titleColor: UIColor { get { return UIColor.whiteColor() } }
var subtitleColor: UIColor { get { return UIColor.whiteColor() } }
var subtitleActiveColor: UIColor { get { return UIColor.whiteColor() } }
var shadowImage : String? { get { return nil } }
var progressPrimary: UIColor { get { return UIColor.RGB(0x1484ee) } }
var progressSecondary: UIColor { get { return UIColor.RGB(0xaccceb) } }
func applyAppearance(application: UIApplication) {
// StatusBar style
if (statusBarLightContent) {
application.statusBarStyle = UIStatusBarStyle.LightContent
} else {
application.statusBarStyle = UIStatusBarStyle.Default
}
var navAppearance = UINavigationBar.appearance();
// NavigationBar Icon
navAppearance.tintColor = titleColor;
// NavigationBar Text
navAppearance.titleTextAttributes = [NSForegroundColorAttributeName: titleColor];
// NavigationBar Background
navAppearance.barTintColor = barColor;
// navAppearance.setBackgroundImage(Imaging.imageWithColor(barColor, size: CGSize(width: 1, height: 1)), forBarMetrics: UIBarMetrics.Default)
// navAppearance.shadowImage = Imaging.imageWithColor(barColor, size: CGSize(width: 1, height: 2))
// Small hack for correct background color
UISearchBar.appearance().backgroundColor = barColor
// NavigationBar Shadow
// navAppearance.shadowImage = nil
// if (shadowImage == nil) {
// navAppearance.shadowImage = UIImage()
// navAppearance.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
// } else {
// navAppearance.shadowImage = UIImage(named: shadowImage!)
// }
}
func applyAuthStatusBar() {
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true)
}
func applyStatusBar() {
if (statusBarLightContent) {
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
} else {
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true)
}
}
func applyStatusBarFast() {
if (statusBarLightContent) {
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false)
} else {
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: false)
}
}
} | mit |
LYM-mg/DemoTest | 其他功能/SwiftyDemo/Pods/SkeletonView/Sources/Collections/UIView+CollectionSkeleton.swift | 1 | 847 | //
// UIView+CollectionSkeleton.swift
// SkeletonView-iOS
//
// Created by Juanpe Catalán on 02/02/2018.
// Copyright © 2018 SkeletonView. All rights reserved.
//
import UIKit
extension UIView {
func addDummyDataSourceIfNeeded() {
guard let collection = self as? CollectionSkeleton else { return }
collection.addDummyDataSource()
collection.disableUserInteraction()
}
func updateDummyDataSourceIfNeeded() {
guard let collection = self as? CollectionSkeleton else { return }
collection.updateDummyDataSource()
}
func removeDummyDataSourceIfNeeded(reloadAfter reload: Bool = true) {
guard let collection = self as? CollectionSkeleton else { return }
collection.removeDummyDataSource(reloadAfter: reload)
collection.enableUserInteraction()
}
}
| mit |
alejandrogarin/ADGCloudKit | Example/ADGCloudKit/ChildViewController.swift | 1 | 3102 | //
// CloudContext.swift
// ADGCloudKit
//
// Created by Alejandro Diego Garin
// The MIT License (MIT)
//
// Copyright (c) 2015 Alejandro Garin @alejandrogarin
//
// 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.
import Foundation
import UIKit
import CoreLocation
import ADGCloudKit
class ChildViewController: BaseViewController {
var parent: Parent?
var dao = ChildDAO()
override func onFindAllRecords() {
var predicate: NSPredicate?
if let parent = self.parent, record = parent.asCKRecord() {
predicate = NSPredicate(format: "refToParent == %@", record)
}
self.dao.findObjectsWithPredicate(predicate, sortDescriptors: [NSSortDescriptor(key: "stringAttribute", ascending: true)], resultsLimit: nil) { [unowned self] (records, error) -> Void in
print(error)
if let records = records {
self.datasource = records
self.tableView.reloadData()
}
}
}
override func onDelete(object: CloudRecord, indexPath: NSIndexPath) {
try! self.dao.deleteObject(object as! Child, completionHandler: { [unowned self] (error) -> Void in
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
self.datasource.removeAtIndex(indexPath.row)
self.tableView.endUpdates()
})
}
override func onCellIdentifier() -> String {
return "ChildCell"
}
@IBAction func onAddTouched(sender: AnyObject) {
let object = Child()
object.stringAttribute = self.adg_randomStringWithLength(4)
if let parent = self.parent {
object.refToParent = parent.asCKReferenceWithDeleteAction()
}
self.dao.insertObject(object) { (object, error) -> Void in
print(error)
if let object = object {
self.datasource.append(object)
self.tableView.reloadData()
}
}
}
}
| mit |
ReactiveKit/ReactiveGitter | Carthage/Checkouts/Bond/Bond-App/AppDelegate.swift | 6 | 555 | //
// AppDelegate.swift
// Bond-App
//
// Created by Srdan Rasic on 29/08/16.
// Copyright © 2016 Swift Bond. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = UIViewController()
window?.makeKeyAndVisible()
return true
}
}
| mit |
flomerz/iOS-IUToDo | IUToDo/DataManager.swift | 1 | 4043 | //
// DataManager.swift
// IUToDo
//
// Created by Flo on 28/12/14.
// Copyright (c) 2014 Flo. All rights reserved.
//
import Foundation
import CoreData
import Alamofire
import SwiftyJSON
import AlamofireSwiftyJSON
class DataManager {
class var SERVER: String { return "http://192.168.0.138:9000/" }
// Local
class func loadToDos(context: NSManagedObjectContext) -> [ToDo]? {
var fetchRequest = NSFetchRequest(entityName: ToDo.ENTITY_NAME)
fetchRequest.returnsObjectsAsFaults = false
return context.executeFetchRequest(fetchRequest, error: nil) as [ToDo]?
}
class func addToDo(title:String, subject:String, context: NSManagedObjectContext, callback: () -> Void) {
let todo = (NSEntityDescription.insertNewObjectForEntityForName(ToDo.ENTITY_NAME, inManagedObjectContext: context) as ToDo)
todo.title = title
todo.subject = subject
context.save(nil)
syncToDoFromLocalToRemote(todo, context: context, callback: callback)
}
class func updateToDo(todo:ToDo, context: NSManagedObjectContext, callback: () -> Void) {
context.save(nil)
syncToDoFromLocalToRemote(todo, context: context, callback: callback)
}
class func doneToDo(todo:ToDo, context: NSManagedObjectContext, callback: () -> Void) {
todo.doneDate = NSDate()
context.save(nil)
syncToDoFromLocalToRemote(todo, context: context, callback: callback)
}
// Sync
class func syncToDos(context: NSManagedObjectContext, callback: () -> Void) {
syncToDosFromLocalToRemote(context, callback: { () -> Void in
self.syncToDosFromRemoteToLocal(context, callback: callback)
})
}
class func syncToDoFromLocalToRemote(todo:ToDo, context: NSManagedObjectContext, callback: () -> Void) {
Alamofire.request(.POST, SERVER,
parameters: ["id": todo.externalID, "title": todo.title, "subject": todo.subject, "doneDate": todo.doneDateString()]
).responseSwiftyJSON { (request, response, json, error) in
todo.update(json)
context.save(nil)
//NSLog("synced todo from local to remote: %@", todo)
callback()
}
}
class func syncToDosFromLocalToRemote(context: NSManagedObjectContext, callback: () -> Void) {
if let todos = loadToDos(context)? {
var todosCount = todos.count
if todosCount > 0 {
for(todo:ToDo) in todos {
syncToDoFromLocalToRemote(todo, context: context, callback: { () -> Void in
if --todosCount == 0 {
callback()
}
})
}
} else {
callback()
}
}
}
class func syncToDosFromRemoteToLocal(context: NSManagedObjectContext, callback: () -> Void) {
Alamofire.request(.GET, SERVER).responseSwiftyJSON { (request, response, json, error) in
for (key: String, todoJson: JSON) in json {
var todo:ToDo?
var fetchRequest = NSFetchRequest(entityName: ToDo.ENTITY_NAME)
fetchRequest.predicate = NSPredicate(format: "externalID = %i", todoJson["id"].int64Value)
if let fetchResults = context.executeFetchRequest(fetchRequest, error: nil) as? [ToDo] {
if fetchResults.count == 1 {
todo = fetchResults[0]
}
}
if todo == nil {
todo = (NSEntityDescription.insertNewObjectForEntityForName(ToDo.ENTITY_NAME, inManagedObjectContext: context) as ToDo)
}
todo!.update(todoJson)
context.save(nil)
//NSLog("synced todo from remote to local: %@", todo!)
}
callback()
}
}
} | gpl-2.0 |
TrinadhKandula/MonkeyTestingiOS | samplePrj/PBDataTableView/PBDataTable/Classes/PBDataTableView.swift | 1 | 16536 | //
// PBDataTableView.swift
// PBDataTable
//
// Created by praveen b on 6/10/16.
// Copyright © 2016 Praveen. All rights reserved.
//
import UIKit
protocol PBDataTableViewDelegate: class {
func tableViewDidSelectedRow(indexPath: NSIndexPath)
func tableViewCellEditButtonTapped(indexPath: NSIndexPath)
}
class PBDataTableView: UIView, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate , UISearchControllerDelegate{
@IBOutlet var searchBarHeightConstraint: NSLayoutConstraint!
@IBOutlet var searchBarTrailingConstraint: NSLayoutConstraint!
@IBOutlet var headerVwTrailingConstraint: NSLayoutConstraint!
@IBOutlet var tableVwTrailingConstraint: NSLayoutConstraint!
@IBOutlet var scrollSuperViewTrailingConstraint: NSLayoutConstraint!
@IBOutlet var bgScrollView: UIScrollView!
@IBOutlet var searchBar: UISearchBar!
@IBOutlet var tableHeaderView: UIView!
@IBOutlet var dataTableView: UITableView!
@IBOutlet var noRecordLbl: UILabel!
var filteredDataTableArray: NSMutableArray = NSMutableArray()
var dataTableArray: NSMutableArray = NSMutableArray()
var columnDataArray: NSMutableArray = NSMutableArray()
var columnWidth: CGFloat = 80
var totalColumnWidth: CGFloat = 0
var enableSorting: Bool = true
var enableCellOuterBorder: Bool = true
var enableCellInnerBorder: Bool = true
var enableSearchBar: Bool = true
var shouldShowSearchResults = false
var searchBarBackgroundColor: UIColor = UIColor(red: 246/255, green: 139/255, blue: 31/255, alpha: 1)
var searchBarTxtFldFont: UIFont = UIFont(name: "Helvetica", size: 15)!
var searchBarTxtFldTxtColor: UIColor = UIColor(red: 64/255, green: 64/255, blue: 64/255, alpha: 1)
var searchBarTxtFldBackgroundColor: UIColor = UIColor.clearColor()
var searchBarTxtFldPlaceholderColor: UIColor = UIColor(red: 225/255, green: 225/255, blue: 225/255, alpha: 1)
var searchBarTxtFldPlaceholder: String = "Search with First and Last name"
var searchBarGlassIconTintColor: UIColor = UIColor.whiteColor()
var searchBarCancelBtnFont: UIFont = UIFont(name: "Helvetica", size: 15)!
var searchBarCancelBtnColor: UIColor = UIColor(red: 64/255, green: 64/255, blue: 64/255, alpha: 1)
var lastColumnButtonHeaderName = "Edit"
var delegate: PBDataTableViewDelegate!
//Setup the tableview with number of Columns and Rows
func setupView() {
//To Calculate total width of the header view
for eachHeader in columnDataArray {
let eachLblWidth = CGFloat(eachHeader.objectForKey("widthSize") as! NSNumber)
totalColumnWidth = eachLblWidth + totalColumnWidth
}
if ApplicationDelegate.cellLastColumnButtonEnable == true {
totalColumnWidth = totalColumnWidth + 80
ApplicationDelegate.numberOfColumns = columnDataArray.count + 1
}else {
ApplicationDelegate.numberOfColumns = columnDataArray.count
}
if enableSearchBar {
searchBarCustomizeView()
searchBar.hidden = false
searchBarHeightConstraint.constant = 44
}else {
searchBar.hidden = true
searchBarHeightConstraint.constant = 0
}
//Create Header View for Tableview
self.createTableHeaderView()
let nib = UINib(nibName: "PBDataTableViewCell", bundle: nil)
dataTableView.registerNib(nib, forCellReuseIdentifier: "Cell")
}
//Customize the Search bar
func searchBarCustomizeView() {
// To get a pure color
searchBar.backgroundImage = UIImage()
searchBar.backgroundColor = searchBarBackgroundColor
let textFieldInsideSearchBar = searchBar.valueForKey("searchField") as? UITextField
textFieldInsideSearchBar?.textColor = searchBarTxtFldTxtColor
textFieldInsideSearchBar?.font = searchBarTxtFldFont
textFieldInsideSearchBar?.backgroundColor = searchBarTxtFldBackgroundColor
textFieldInsideSearchBar?.tintColor = UIColor.blackColor()
textFieldInsideSearchBar?.placeholder = searchBarTxtFldPlaceholder
let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.valueForKey("placeholderLabel") as? UILabel
textFieldInsideSearchBarLabel?.textColor = searchBarTxtFldPlaceholderColor
if let glassIconView = textFieldInsideSearchBar!.leftView as? UIImageView {
//Magnifying glass
glassIconView.image = glassIconView.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
glassIconView.tintColor = searchBarGlassIconTintColor
}
UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses([UISearchBar.classForCoder()])
.setTitleTextAttributes([
NSFontAttributeName: searchBarCancelBtnFont,
NSForegroundColorAttributeName: searchBarCancelBtnColor
],forState: UIControlState.Normal)
}
//Check the total width and re-size the scrollview.superview width by changing the Trailing Constraint
func configureView() {
if totalColumnWidth > CGRectGetWidth(self.frame) {
scrollSuperViewTrailingConstraint.constant = (CGRectGetWidth(bgScrollView.frame)-totalColumnWidth)
searchBarTrailingConstraint.constant = 0
self.updateConstraints()
self.layoutIfNeeded()
bgScrollView.contentSize = CGSizeMake(CGRectGetWidth(bgScrollView.frame)-scrollSuperViewTrailingConstraint.constant, CGRectGetHeight(self.frame)-searchBarHeightConstraint.constant)
dataTableView.reloadData()
}else {
tableVwTrailingConstraint.constant = (CGRectGetWidth(bgScrollView.frame) - totalColumnWidth)
headerVwTrailingConstraint.constant = tableVwTrailingConstraint.constant
searchBarTrailingConstraint.constant = tableVwTrailingConstraint.constant
self.updateConstraints()
self.layoutIfNeeded()
}
}
func createTableHeaderView() {
var headerCount = 0
var headerLblXaxis: CGFloat = 0
for eachHeader in columnDataArray {
let eachLblWidth = CGFloat(eachHeader.objectForKey("widthSize") as! NSNumber)
//Header Label
let columnHeaderLbl = UILabel()
columnHeaderLbl.text = eachHeader.objectForKey("name") as? String
columnHeaderLbl.textAlignment = .Center
columnHeaderLbl.font = UIFont(name: "Arial", size: 14)
columnHeaderLbl.tag = 1000+headerCount
columnHeaderLbl.textColor = UIColor.whiteColor()
columnHeaderLbl.adjustsFontSizeToFitWidth = true
tableHeaderView.addSubview(columnHeaderLbl)
if enableSorting {
columnHeaderLbl.frame = CGRectMake(headerLblXaxis, 0, eachLblWidth-25, CGRectGetHeight(tableHeaderView.frame))
//Header Sort ImageView
let sortImg = UIImageView(image: UIImage(named: "none"))
sortImg.accessibilityIdentifier = "0"
sortImg.frame = CGRectMake(CGRectGetMaxX(columnHeaderLbl.frame)+5, (CGRectGetHeight(tableHeaderView.frame)-sortImg.image!.size.height)/2, sortImg.image!.size.width, sortImg.image!.size.height)
sortImg.tag = 2000+headerCount
tableHeaderView.addSubview(sortImg)
//Header Button to Sort the rows on tap
let headerBtn = UIButton(type: .Custom)
headerBtn.frame = CGRectMake(CGRectGetMinX(columnHeaderLbl.frame), 0, eachLblWidth, CGRectGetHeight(columnHeaderLbl.frame))
headerBtn.backgroundColor = UIColor.clearColor()
headerBtn.addTarget(self, action: #selector(headerColumnBtnTapped), forControlEvents: .TouchUpInside)
headerBtn.tag = 3000+headerCount
tableHeaderView.addSubview(headerBtn)
}else {
columnHeaderLbl.frame = CGRectMake(headerLblXaxis, 0, eachLblWidth, CGRectGetHeight(tableHeaderView.frame))
}
headerLblXaxis = eachLblWidth + headerLblXaxis
headerCount += 1
}
//Add Edit Button On Header
if ApplicationDelegate.cellLastColumnButtonEnable == true {
let editButton = UILabel()
editButton.text = lastColumnButtonHeaderName
editButton.textAlignment = .Center
editButton.font = UIFont(name: "Arial", size: 14)
editButton.textColor = UIColor.whiteColor()
editButton.adjustsFontSizeToFitWidth = true
tableHeaderView.addSubview(editButton)
editButton.frame = CGRectMake(headerLblXaxis, 0, 70, CGRectGetHeight(tableHeaderView.frame))
}
}
//MARK: - TableView DataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if shouldShowSearchResults {
if filteredDataTableArray.count > 0 {
noRecordLbl.hidden = true
dataTableView.hidden = false
}else {
noRecordLbl.hidden = false
dataTableView.hidden = true
}
return filteredDataTableArray.count
}else {
if dataTableArray.count > 0 {
noRecordLbl.hidden = true
dataTableView.hidden = false
}else {
noRecordLbl.hidden = false
dataTableView.hidden = true
}
return dataTableArray.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! PBDataTableViewCell
cell.backgroundColor = UIColor.whiteColor()
configureCell(cell, indexPath: indexPath)
if enableCellOuterBorder {
cell.leftBorderView.hidden = false
cell.rightBorderView.hidden = false
cell.bottomBorderView.hidden = false
}else {
cell.leftBorderView.hidden = true
cell.rightBorderView.hidden = true
cell.bottomBorderView.hidden = true
}
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate.tableViewDidSelectedRow(indexPath)
}
//Configure Tableview Cells with Defined Label
func configureCell(cell: PBDataTableViewCell, indexPath: NSIndexPath) {
let columnDict: NSDictionary!
if shouldShowSearchResults {
columnDict = filteredDataTableArray.objectAtIndex(indexPath.row) as! NSDictionary
}else {
columnDict = dataTableArray.objectAtIndex(indexPath.row) as! NSDictionary
}
var labelXaxis: CGFloat = 0
for i in 0..<ApplicationDelegate.numberOfColumns {
var columnLbl: UILabel!
var columnBtn: UIButton!
if i == ApplicationDelegate.numberOfColumns-1 && ApplicationDelegate.cellLastColumnButtonEnable == true {
columnBtn = cell.contentView.viewWithTag(100+i) as? UIButton
columnBtn.addTarget(self, action: #selector(editBtnTapped(_:)), forControlEvents: .TouchUpInside)
var rect = columnBtn!.frame
rect.origin.x = labelXaxis+5
rect.size.width = CGRectGetWidth(columnBtn.frame)
columnBtn!.frame = rect
}else {
columnLbl = cell.contentView.viewWithTag(100+i) as? UILabel
var rect = columnLbl!.frame
rect.origin.x = labelXaxis
rect.size.width = CGFloat(columnDataArray.objectAtIndex(i).objectForKey("widthSize") as! NSNumber)
columnLbl!.frame = rect
columnLbl!.text = String(columnDict.objectForKey("rowColumn\(i+1)")!)
labelXaxis = labelXaxis + CGRectGetWidth((columnLbl?.frame)!)
}
let innerLine = cell.contentView.viewWithTag(200+i)
if enableCellInnerBorder {
innerLine?.frame = CGRectMake(CGRectGetMaxX(columnLbl!.frame)-1, 0, 1, CGRectGetHeight(cell.frame))
innerLine?.hidden = false
}else {
innerLine?.hidden = true
}
}
}
func editBtnTapped(sender: UIButton) {
let btnPosition = sender.convertPoint(CGPointZero, toView: dataTableView)
let selectedIndex = dataTableView.indexPathForRowAtPoint(btnPosition)
delegate.tableViewCellEditButtonTapped(selectedIndex!)
}
func headerColumnBtnTapped(sender: UIButton) {
for i in 0..<ApplicationDelegate.numberOfColumns {
if sender.tag == i+3000 {
let headerSortImg = sender.superview!.viewWithTag(2000+i) as? UIImageView
if ((headerSortImg!.accessibilityIdentifier == "0") || (headerSortImg!.accessibilityIdentifier == "2")) {
headerSortImg?.image = UIImage(named: "ascending")
headerSortImg?.accessibilityIdentifier = "1"
//To Sort the table data Array in Ascending Order, respect to the Column header Tapped
sortingDataTableArray(headerSortImg!.tag-2000, boolValue: true)
}else {
headerSortImg?.image = UIImage(named: "descending")
headerSortImg?.accessibilityIdentifier = "2"
//To Sort the table data Array in Decending Order, respect to the Column header Tapped
sortingDataTableArray(headerSortImg!.tag-2000, boolValue: false)
}
}else {
let headerSortImg = sender.superview!.viewWithTag(2000+i) as? UIImageView
headerSortImg?.image = UIImage(named: "none")
headerSortImg?.accessibilityIdentifier = "0"
}
}
}
//MARK: - Sorting Method
func sortingDataTableArray(intValue: Int, boolValue: Bool) {
let sort = NSSortDescriptor(key: "rowColumn\(intValue+1)", ascending:boolValue)
if shouldShowSearchResults {
filteredDataTableArray.sortUsingDescriptors([sort])
}else {
dataTableArray.sortUsingDescriptors([sort])
}
dataTableView.reloadData()
}
//MARK: - Search Bar Delegate Methods
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
shouldShowSearchResults = true
searchBar.showsCancelButton = true
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.showsCancelButton = false
shouldShowSearchResults = false
searchBar.text = ""
searchBar.resignFirstResponder()
dataTableView.reloadData()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
if !shouldShowSearchResults {
shouldShowSearchResults = true
dataTableView.reloadData()
}
searchBar.resignFirstResponder()
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if searchText == "" {
shouldShowSearchResults = false
}else {
shouldShowSearchResults = true
//filtered with firstname and last name. Give the column names respectively to be sorted
let results = dataTableArray.filter({ person in
if let firstname = person["rowColumn1"] as? String, let lastname = person["rowColumn2"] as? String, query = searchBar.text {
return firstname.rangeOfString(query, options: [.CaseInsensitiveSearch, .DiacriticInsensitiveSearch]) != nil || lastname.rangeOfString(query, options: [.CaseInsensitiveSearch, .DiacriticInsensitiveSearch]) != nil
}
return false
})
filteredDataTableArray = NSMutableArray(array: results)
}
dataTableView.reloadData()
}
}
| mit |
Zewo/Epoch | Sources/HTTP/Client/Client.swift | 1 | 8986 | import Core
import IO
import Venice
import struct Foundation.URL
public enum ClientError : Error {
case schemeRequired
case invalidScheme
case hostRequired
}
open class Client {
fileprivate typealias Connection = (
stream: DuplexStream,
serializer: RequestSerializer,
parser: ResponseParser
)
public struct Configuration {
/// Pool size
public var poolSize: ClosedRange<Int> = 5 ... 10
/// Parser buffer size
public var parserBufferSize: Int = 4096
/// Serializer buffer size
public var serializerBufferSize: Int = 4096
/// Address resolution timeout
public var addressResolutionTimeout: Duration = 1.minute
/// Connection timeout
public var connectionTimeout: Duration = 1.minute
/// Borrow timeout
public var borrowTimeout: Duration = 5.minutes
/// Parse timeout
public var parseTimeout: Duration = 5.minutes
/// Serialization timeout
public var serializeTimeout: Duration = 5.minutes
/// Close connection timeout
public var closeConnectionTimeout: Duration = 1.minute
public init() {}
public static var `default`: Configuration {
return Configuration()
}
}
/// Client configuration.
public let configuration: Configuration
private let host: String
private let port: Int
private let pool: Pool
/// Creates a new HTTP client
public init(uri: String, configuration: Configuration = .default) throws {
let uri = try URI(uri)
let (host, port, secure) = try Client.extract(uri: uri)
self.host = host
self.port = port
self.configuration = configuration
self.pool = try Pool(size: configuration.poolSize) {
let (stream, serializer, parser) = try Client.connection(
host: host,
port: port,
secure: secure,
configuration: configuration
)
return Connection(
stream: stream,
serializer: serializer,
parser: parser
)
}
}
deinit {
pool.close()
}
private static func extract(uri: URI) throws -> (String, Int, Bool) {
var secure = true
guard let scheme = uri.scheme else {
throw ClientError.schemeRequired
}
switch scheme {
case "https":
secure = true
case "http":
secure = false
default:
throw ClientError.invalidScheme
}
guard let host = uri.host else {
throw ClientError.hostRequired
}
let port = uri.port ?? (secure ? 443 : 80)
return (host, port, secure)
}
private static func connection(
host: String,
port: Int,
secure: Bool,
configuration: Configuration
) throws -> (DuplexStream, RequestSerializer, ResponseParser) {
let stream: DuplexStream
if secure {
stream = try TLSStream(
host: host,
port: port,
deadline: configuration.addressResolutionTimeout.fromNow()
)
} else {
stream = try TCPStream(
host: host,
port: port,
deadline: configuration.addressResolutionTimeout.fromNow()
)
}
try stream.open(deadline: configuration.connectionTimeout.fromNow())
let serializer = RequestSerializer(
stream: stream,
bufferSize: configuration.serializerBufferSize
)
let parser = ResponseParser(
stream: stream,
bufferSize: configuration.parserBufferSize
)
return (stream, serializer, parser)
}
private static func configureHeaders(
request: Request,
host: String,
port: Int,
closeConnection: Bool = false
) {
if request.host == nil {
request.host = host + ":" + port.description
}
if request.userAgent == nil {
request.userAgent = "Zewo"
}
if closeConnection {
request.connection = "close"
}
}
public static func send(_ request: Request, configuration: Configuration = .default) throws -> Response {
let (host, port, secure) = try extract(uri: request.uri)
let (stream, serializer, parser) = try connection(
host: host,
port: port,
secure: secure,
configuration: configuration
)
configureHeaders(
request: request,
host: host,
port: port,
closeConnection: true
)
try serializer.serialize(
request,
deadline: configuration.serializeTimeout.fromNow()
)
let response = try parser.parse(
deadline: configuration.parseTimeout.fromNow()
)
if let upgrade = request.upgradeConnection {
try upgrade(response, stream)
}
try stream.close(deadline: configuration.closeConnectionTimeout.fromNow())
return response
}
public func send(_ request: Request) throws -> Response {
var retryCount = 0
loop: while true {
let connection = try pool.borrow(
deadline: configuration.borrowTimeout.fromNow()
)
let stream = connection.stream
let serializer = connection.serializer
let parser = connection.parser
Client.configureHeaders(request: request, host: host, port: port)
do {
try serializer.serialize(
request,
deadline: configuration.serializeTimeout.fromNow()
)
let response = try parser.parse(
deadline: configuration.parseTimeout.fromNow()
)
if let upgrade = request.upgradeConnection {
try upgrade(response, stream)
try stream.close(deadline: configuration.closeConnectionTimeout.fromNow())
pool.dispose(connection)
} else {
pool.return(connection)
}
return response
} catch {
pool.dispose(connection)
retryCount += 1
guard retryCount < 10 else {
throw error
}
continue loop
}
}
}
}
fileprivate class Pool {
fileprivate var size: ClosedRange<Int>
fileprivate var borrowed = 0
fileprivate var available: [Client.Connection] = []
fileprivate var waitList: Channel<Void>
fileprivate var waiting: Int = 0
fileprivate let create: () throws -> Client.Connection
fileprivate init(
size: ClosedRange<Int>,
_ create: @escaping () throws -> Client.Connection
) throws {
self.size = size
self.create = create
waitList = try Channel()
for _ in 0 ..< size.lowerBound {
let connection = try create()
self.available.append(connection)
}
}
fileprivate func close() {
let deadline = 30.seconds.fromNow()
for connection in available {
try? connection.stream.close(deadline: deadline)
}
}
fileprivate func `return`(_ stream: Client.Connection) {
available.append(stream)
borrowed -= 1
if waiting > 0 {
try? waitList.send((), deadline: .immediately)
}
}
fileprivate func dispose(_ stream: Client.Connection) {
borrowed -= 1
}
fileprivate func borrow(deadline: Deadline) throws -> Client.Connection {
var waitCount = 0
while true {
if let stream = available.popLast() {
borrowed += 1
return stream
}
if borrowed + available.count < size.upperBound {
let stream = try create()
borrowed += 1
return stream
}
waitCount += 1
defer {
waiting -= waitCount
}
try waitList.receive(deadline: deadline)
}
}
}
| mit |
richardpiazza/SOSwift | Sources/SOSwift/CreativeWorkOrProductOrURL.swift | 1 | 2546 | import Foundation
import CodablePlus
public enum CreativeWorkOrProductOrURL: Codable {
case creativeWork(value: CreativeWork)
case product(value: Product)
case url(value: URL)
public init(_ value: CreativeWork) {
self = .creativeWork(value: value)
}
public init(_ value: Product) {
self = .product(value: value)
}
public init(_ value: URL) {
self = .url(value: value)
}
public init(from decoder: Decoder) throws {
var dictionary: [String : Any]?
do {
let jsonContainer = try decoder.container(keyedBy: DictionaryKeys.self)
dictionary = try jsonContainer.decode(Dictionary<String, Any>.self)
} catch {
}
guard let jsonDictionary = dictionary else {
let container = try decoder.singleValueContainer()
let value = try container.decode(URL.self)
self = .url(value: value)
return
}
guard let type = jsonDictionary[SchemaKeys.type.rawValue] as? String else {
throw SchemaError.typeDecodingError
}
let container = try decoder.singleValueContainer()
switch type {
case CreativeWork.schemaName:
let value = try container.decode(CreativeWork.self)
self = .creativeWork(value: value)
case Product.schemaName:
let value = try container.decode(Product.self)
self = .product(value: value)
default:
throw SchemaError.typeDecodingError
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .creativeWork(let value):
try container.encode(value)
case .product(let value):
try container.encode(value)
case .url(let value):
try container.encode(value)
}
}
public var creativeWork: CreativeWork? {
switch self {
case .creativeWork(let value):
return value
default:
return nil
}
}
public var product: Product? {
switch self {
case .product(let value):
return value
default:
return nil
}
}
public var url: URL? {
switch self {
case .url(let value):
return value
default:
return nil
}
}
}
| mit |
CoderZZF/DYZB | DYZB/DYZB/Classes/Tools/Extension/UIColor-Extension.swift | 1 | 513 | //
// UIColor-Extension.swift
// DYZB
//
// Created by zhangzhifu on 2017/3/15.
// Copyright © 2017年 seemygo. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(r: CGFloat, g : CGFloat, b : CGFloat) {
self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0)
}
class func randomColor() -> UIColor {
return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))
}
}
| apache-2.0 |
huangboju/Moots | UICollectionViewLayout/preview-transition-master/PreviewTransition/TableViewController/Halpers/ConstraintsHalper.swift | 1 | 2843 | //
// ConstraintsHelper.swift
// AnimatedPageView
//
// Created by Alex K. on 13/04/16.
// Copyright © 2016 Alex K. All rights reserved.
//
import UIKit
struct ConstraintInfo {
var attribute: NSLayoutAttribute = .left
var secondAttribute: NSLayoutAttribute = .notAnAttribute
var constant: CGFloat = 0
var identifier: String?
var relation: NSLayoutRelation = .equal
}
precedencegroup constOp {
associativity: left
higherThan: AssignmentPrecedence
}
infix operator >>>-: constOp
@discardableResult
func >>>- <T: UIView>(left: (T, T), block: (inout ConstraintInfo) -> Void) -> NSLayoutConstraint {
var info = ConstraintInfo()
block(&info)
info.secondAttribute = info.secondAttribute == .notAnAttribute ? info.attribute : info.secondAttribute
let constraint = NSLayoutConstraint(item: left.1,
attribute: info.attribute,
relatedBy: info.relation,
toItem: left.0,
attribute: info.secondAttribute,
multiplier: 1,
constant: info.constant)
constraint.identifier = info.identifier
left.0.addConstraint(constraint)
return constraint
}
@discardableResult
func >>>- <T: UIView>(left: T, block: (inout ConstraintInfo) -> Void) -> NSLayoutConstraint {
var info = ConstraintInfo()
block(&info)
let constraint = NSLayoutConstraint(item: left,
attribute: info.attribute,
relatedBy: info.relation,
toItem: nil,
attribute: info.attribute,
multiplier: 1,
constant: info.constant)
constraint.identifier = info.identifier
left.addConstraint(constraint)
return constraint
}
@discardableResult
func >>>- <T: UIView>(left: (T, T, T), block: (inout ConstraintInfo) -> Void) -> NSLayoutConstraint {
var info = ConstraintInfo()
block(&info)
info.secondAttribute = info.secondAttribute == .notAnAttribute ? info.attribute : info.secondAttribute
let constraint = NSLayoutConstraint(item: left.1,
attribute: info.attribute,
relatedBy: info.relation,
toItem: left.2,
attribute: info.secondAttribute,
multiplier: 1,
constant: info.constant)
constraint.identifier = info.identifier
left.0.addConstraint(constraint)
return constraint
}
| mit |
huangboju/Moots | UICollectionViewLayout/UICollectionViewFlexLayout-master/Tests/UICollectionViewFlexLayoutTests/Utils/LayoutDelegate.swift | 1 | 3181 | #if os(iOS)
import UIKit
import Stubber
import UICollectionViewFlexLayout
final class LayoutDelegate: NSObject, UICollectionViewDelegateFlexLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlexLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return Stubber.invoke(collectionView(_:layout:sizeForItemAt:), args: (collectionView, collectionViewLayout, indexPath), default: .zero)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlexLayout, verticalSpacingBetweenSectionAt section: Int, and nextSection: Int) -> CGFloat {
return Stubber.invoke(collectionView(_:layout:verticalSpacingBetweenSectionAt:and:), args: (collectionView, collectionViewLayout, section, nextSection), default: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlexLayout, marginForSectionAt section: Int) -> UIEdgeInsets {
return Stubber.invoke(collectionView(_:layout:marginForSectionAt:), args: (collectionView, collectionViewLayout, section), default: .zero)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlexLayout, paddingForSectionAt section: Int) -> UIEdgeInsets {
return Stubber.invoke(collectionView(_:layout:paddingForSectionAt:), args: (collectionView, collectionViewLayout, section), default: .zero)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlexLayout, horizontalSpacingBetweenItemAt indexPath: IndexPath, and nextIndexPath: IndexPath) -> CGFloat {
return Stubber.invoke(collectionView(_:layout:horizontalSpacingBetweenItemAt:and:), args: (collectionView, collectionViewLayout, indexPath, nextIndexPath), default: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlexLayout, verticalSpacingBetweenItemAt indexPath: IndexPath, and nextIndexPath: IndexPath) -> CGFloat {
return Stubber.invoke(collectionView(_:layout:verticalSpacingBetweenItemAt:and:), args: (collectionView, collectionViewLayout, indexPath, nextIndexPath), default: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlexLayout, marginForItemAt indexPath: IndexPath) -> UIEdgeInsets {
return Stubber.invoke(collectionView(_:layout:marginForItemAt:), args: (collectionView, collectionViewLayout, indexPath), default: .zero)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlexLayout, paddingForItemAt indexPath: IndexPath) -> UIEdgeInsets {
return Stubber.invoke(collectionView(_:layout:paddingForItemAt:), args: (collectionView, collectionViewLayout, indexPath), default: .zero)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlexLayout, zIndexForItemAt indexPath: IndexPath) -> Int {
return Stubber.invoke(collectionView(_:layout:zIndexForItemAt:), args: (collectionView, collectionViewLayout, indexPath), default: 0)
}
}
#endif
| mit |
mightydeveloper/swift | validation-test/compiler_crashers/22253-swift-type-transform.swift | 8 | 292 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
enum S<T , U, g {
class c
enum S<T {
enum S<T {
enum b : c
| apache-2.0 |
adamcin/SwiftCJ | SwiftCJ/CJError.swift | 1 | 554 | import Foundation
public struct CJError {
public let title: String?
public let code: String?
public let message: String?
static func errorForDictionary(dict: [NSObject: AnyObject]) -> CJError? {
if let errorDict = dict["error"] as? [NSObject: AnyObject] {
let title = errorDict["title"] as? String
let code = errorDict["code"] as? String
let message = errorDict["message"] as? String
return CJError(title: title, code: code, message: message)
}
return nil
}
}
| mit |
damicreabox/Git2Swift | Sources/Git2Swift/remote/Remotes.swift | 1 | 3431 | //
// Remotes.swift
// Git2Swift
//
// Created by Damien Giron on 17/08/2016.
// Copyright © 2016 Creabox. All rights reserved.
//
import Foundation
import CLibgit2
/// Manage remote repository
public class Remotes {
/// Repository
private let repository : Repository
/// Constructor with repository manager
///
/// - parameter repository: Repository
///
/// - returns: Remotes
init(repository: Repository) {
self.repository = repository
}
/// Find remote names
///
/// - throws: GitError
///
/// - returns: String array
public func remoteNames() throws -> [String] {
// Store remote names
var remotes = git_strarray()
// List remotes
let error = git_remote_list(&remotes, repository.pointer.pointee)
if (error != 0) {
throw gitUnknownError("Unable to list remotes", code: error)
}
return git_strarray_to_strings(&remotes)
}
/// Find remote by name.
///
/// - parameter name: Remote name
///
/// - throws: GitError
///
/// - returns: Remote
public func get(name: String) throws -> Remote {
// Remote pointer
let remote = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1)
// Lookup remote
let error = git_remote_lookup(remote, repository.pointer.pointee, name)
if (error != 0) {
remote.deinitialize()
remote.deallocate(capacity: 1)
switch(error) {
case GIT_ENOTFOUND.rawValue:
throw GitError.notFound(ref: name)
case GIT_EINVALIDSPEC.rawValue:
throw GitError.invalidSpec(spec: name)
default:
throw gitUnknownError("Unable to lookup remote \(name)", code: error)
}
}
return Remote(repository: repository, pointer: remote, name: name)
}
/// Create remote
///
/// - parameter name: Remote name
/// - parameter url: URL
///
/// - throws: GitError
///
/// - returns: Remote
public func create(name: String, url: URL) throws -> Remote {
// Remote pointer
let remote = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1)
// Create remote
let error = git_remote_create(remote, repository.pointer.pointee,
name, url.path)
if (error != 0) {
switch(error) {
case GIT_EINVALIDSPEC.rawValue:
throw GitError.invalidSpec(spec: name)
case GIT_EEXISTS.rawValue:
throw GitError.alreadyExists(ref: name)
default:
throw gitUnknownError("Unable to create remote \(name)",
code: error)
}
}
return Remote(repository: repository, pointer: remote, name: name)
}
/// Remove remote
///
/// - parameter name: Remote name
///
/// - throws: GitError
public func remove(name: String) throws {
// remove remote
let error = git_remote_delete(repository.pointer.pointee, name)
if (error != 0) {
throw gitUnknownError("Unable to remove remote \(name)",
code: error)
}
}
}
| apache-2.0 |
lsn-sokna/TextFieldEffects | TextFieldEffects/TextFieldEffects/MadokaTextField.swift | 1 | 5438 | //
// MadokaTextField.swift
// TextFieldEffects
//
// Created by Raúl Riera on 05/02/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
@IBDesignable public class MadokaTextField: TextFieldEffects {
@IBInspectable public var placeholderColor: UIColor? {
didSet {
updatePlaceholder()
}
}
@IBInspectable public var borderColor: UIColor? {
didSet {
updateBorder()
}
}
override public var placeholder: String? {
didSet {
updatePlaceholder()
}
}
override public var bounds: CGRect {
didSet {
updateBorder()
updatePlaceholder()
}
}
private let borderThickness: CGFloat = 1
private let placeholderInsets = CGPoint(x: 6, y: 6)
private let textFieldInsets = CGPoint(x: 6, y: 6)
private let borderLayer = CAShapeLayer()
private var backgroundLayerColor: UIColor?
// MARK: - TextFieldsEffectsProtocol
override public func drawViewsForRect(rect: CGRect) {
let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height))
placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y)
placeholderLabel.font = placeholderFontFromFont(font!)
updateBorder()
updatePlaceholder()
layer.addSublayer(borderLayer)
addSubview(placeholderLabel)
}
private func updateBorder() {
let rect = rectForBorder(bounds)
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: rect.origin.x + borderThickness, y: rect.height - borderThickness))
path.addLineToPoint(CGPoint(x: rect.width - borderThickness, y: rect.height - borderThickness))
path.addLineToPoint(CGPoint(x: rect.width - borderThickness, y: rect.origin.y + borderThickness))
path.addLineToPoint(CGPoint(x: rect.origin.x + borderThickness, y: rect.origin.y + borderThickness))
path.closePath()
borderLayer.path = path.CGPath
borderLayer.lineCap = kCALineCapSquare
borderLayer.lineWidth = borderThickness
borderLayer.fillColor = nil
borderLayer.strokeColor = borderColor?.CGColor
borderLayer.strokeEnd = percentageForBottomBorder()
}
private func percentageForBottomBorder() -> CGFloat {
let borderRect = rectForBorder(bounds)
let sumOfSides = (borderRect.width * 2) + (borderRect.height * 2)
return (borderRect.width * 100 / sumOfSides) / 100
}
private func updatePlaceholder() {
placeholderLabel.text = placeholder
placeholderLabel.textColor = placeholderColor
placeholderLabel.sizeToFit()
layoutPlaceholderInTextRect()
if isFirstResponder() || text!.isNotEmpty {
animateViewsForTextEntry()
}
}
private func placeholderFontFromFont(font: UIFont) -> UIFont! {
let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.65)
return smallerFont
}
private func rectForBorder(bounds: CGRect) -> CGRect {
let newRect = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y)
return newRect
}
private func layoutPlaceholderInTextRect() {
if text!.isNotEmpty {
return
}
placeholderLabel.transform = CGAffineTransformIdentity
let textRect = textRectForBounds(bounds)
var originX = textRect.origin.x
switch textAlignment {
case .Center:
originX += textRect.size.width/2 - placeholderLabel.bounds.width/2
case .Right:
originX += textRect.size.width - placeholderLabel.bounds.width
default:
break
}
placeholderLabel.frame = CGRect(x: originX, y: textRect.height - placeholderLabel.bounds.height - placeholderInsets.y,
width: placeholderLabel.bounds.width, height: placeholderLabel.bounds.height)
}
override public func animateViewsForTextEntry() {
borderLayer.strokeEnd = 1
UIView.animateWithDuration(0.3, animations: {
let translate = CGAffineTransformMakeTranslation(-self.placeholderInsets.x, self.placeholderLabel.bounds.height + (self.placeholderInsets.y * 2))
let scale = CGAffineTransformMakeScale(0.9, 0.9)
self.placeholderLabel.transform = CGAffineTransformConcat(translate, scale)
})
}
override public func animateViewsForTextDisplay() {
if text!.isEmpty {
borderLayer.strokeEnd = percentageForBottomBorder()
UIView.animateWithDuration(0.3, animations: {
self.placeholderLabel.transform = CGAffineTransformIdentity
})
}
}
// MARK: - Overrides
override public func editingRectForBounds(bounds: CGRect) -> CGRect {
let newBounds = rectForBorder(bounds)
return CGRectInset(newBounds, textFieldInsets.x, 0)
}
override public func textRectForBounds(bounds: CGRect) -> CGRect {
let newBounds = rectForBorder(bounds)
return CGRectInset(newBounds, textFieldInsets.x, 0)
}
}
| mit |
mcgarrett007/AES | AES/StundenplanViewController.swift | 1 | 11092 | //
// StundenplanViewController.swift
// AES Maintal
//
// Created by Tim Mischok on 21.03.17.
// Copyright © 2017 Ferida Mischok. All rights reserved.
//
import UIKit
import ActionSheetPicker_3_0
import WebKit
import Alamofire
import Kanna
class StundenplanViewController: UIViewController{
var header: String = ""
var StrNumStr = String()
var defaults = UserDefaults(suiteName: "group.com.mischok.AES-Maintal")
var Klassen: [String] = []
@IBOutlet weak var organizeButton: UIBarButtonItem!
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
if defaults!.value(forKey: "Klasse") == nil{
defaults!.set("Alle", forKey: "Klasse")
}
self.title = header.localized
webView = WKWebView()
self.view = webView
self.getClass()
// Do any additional setup after loading the view.
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
self.Klassen.removeAll()
}
func getClass(){
if self.defaults!.stringArray(forKey: "KlasssenArray") != nil{
self.Klassen = self.defaults!.stringArray(forKey: "KlassenArray")!
}else{
URLCache.shared.removeAllCachedResponses()
Alamofire.request("http://infoline:14031879@www.data.aes-maintal.de/DATA/_SCH/_SCH_STD-PLAN/frames/navbar.htm", method: .post).authenticate(user: "infoline", password: "14031879").responseString{ response in
switch response.result {
case .failure(let Error):
print(Error)
case .success:
if let html = response.result.value {
if html == ""{
self.Klassen.append("Alle")
}else{
let str = html.components(separatedBy: "var")
let str1 = str[3].replacingOccurrences(of: ";", with: "")
let str2 = str1.replacingOccurrences(of: " classes =", with: "")
let str3 = str2.replacingOccurrences(of: "[", with: "")
let str4 = str3.replacingOccurrences(of: "]", with: "")
let str5 = str4.components(separatedBy: ",")
for (index, value) in str5.enumerated(){
let st = value.replacingOccurrences(of: "\"", with: "")
if index == 0{
self.Klassen.append("05A")
continue
}else if index == str5.count - 1{
self.Klassen.append("EW O")
self.Klassen.insert("Alle", at: 0)
if self.defaults!.stringArray(forKey: "KlassenArray") == nil && self.Klassen.count > 10{
self.defaults!.set(self.Klassen, forKey: "KlassenArray")
}
self.getContent()
}else{
self.Klassen.append(st)
continue
}
}
}
}
}
}
}
}
@IBAction func changeClass(_ sender: Any) {
if self.defaults!.stringArray(forKey: "KlassenArray") != nil{
self.Klassen = self.defaults!.stringArray(forKey: "KlassenArray")!
}else{
self.getClass()
}
ActionSheetMultipleStringPicker.show(withTitle: "Klassenauswahl".localized, rows: [Klassen], initialSelection: [0], doneBlock: {
picker, indexes, values in
let text1 = "\(values!)"
let text2 = text1.replacingOccurrences(of: " ", with: "")
let text3 = text2.replacingOccurrences(of: "(", with: "")
let text4 = text3.replacingOccurrences(of: ")", with: "")
let text5 = text4.replacingOccurrences(of: "\n", with: "")
self.defaults!.set(text5, forKey: "Klasse")
self.getContent()
return
}, cancel: { ActionMultipleStringCancelBlock in return }, origin: sender)
}
@objc func getContent(){
let KlasseStr = "\(defaults!.value(forKey: "Klasse")!)"
if KlasseStr == "Alle"{
let alert = UIAlertController(title: "Warnung", message: "Zum Benutzen des Stundenplans bitte eine Klasse auswählen.", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
URLCache.shared.removeAllCachedResponses()
let url = URL(string: "http://infoline:14031879@data.aes-maintal.de/DATA/_SCH/_SCH_STD-PLAN/welcome.htm")
let request = URLRequest(url: url!)
self.webView.load(request)
}else{
if Klassen.count == 1{
Klassen.removeAll()
self.getClass()
}
if Klassen.isEmpty{
self.getClass()
}
for (index,value) in Klassen.enumerated(){
let Str = "\(value)"
if Str.contains(KlasseStr){
StrNumStr = "\(index)"
if index == 1{
StrNumStr = "01"
}else if index == 2{
StrNumStr = "02"
}else if index == 3{
StrNumStr = "03"
}else if index == 4{
StrNumStr = "04"
}else if index == 5{
StrNumStr = "05"
}else if index == 6{
StrNumStr = "06"
}else if index == 7{
StrNumStr = "07"
}else if index == 8{
StrNumStr = "08"
}else if index == 9{
StrNumStr = "09"
}else if index == 10{
StrNumStr = "10"
}
URLCache.shared.removeAllCachedResponses()
Alamofire.request("http://infoline:14031879@data.aes-maintal.de/DATA/_SCH/_SCH_STD-PLAN/32/c/c000\(StrNumStr).htm").authenticate(user: "infoline", password: "14031879").responseString(){ response in
switch response.result {
case .success:
if let html = response.result.value{
usleep(1000)
self.webView.loadHTMLString(html, baseURL: URL(string: "http://infoline:14031879@data.aes-maintal.de/DATA/_SCH/_SCH_STD-PLAN/32/c/c000\(self.StrNumStr).htm"))
}
var Klasse1 = [String]()
URLCache.shared.removeAllCachedResponses()
Alamofire.request("http://infoline:14031879@www.data.aes-maintal.de/DATA/_SCH/_SCH_STD-PLAN/frames/navbar.htm", method: .post).authenticate(user: "infoline", password: "14031879").responseString { response in
switch response.result {
case .failure(let Error):
print(Error)
case .success:
if let html = response.result.value {
if html == ""{
Klasse1.append("Alle")
}else{
let str = html.components(separatedBy: "var")
let str1 = str[3].replacingOccurrences(of: ";", with: "")
let str2 = str1.replacingOccurrences(of: " classes =", with: "")
let str3 = str2.replacingOccurrences(of: "[", with: "")
let str4 = str3.replacingOccurrences(of: "]", with: "")
let str5 = str4.components(separatedBy: ",")
for (index, value) in str5.enumerated(){
let st = value.replacingOccurrences(of: "\"", with: "")
if index == 0{
Klasse1.append("05A")
continue
}else if index == str5.count - 1{
Klasse1.append("ENS")
Klasse1.insert("Alle", at: 0)
if Klasse1 != self.Klassen{
if Klasse1.isEmpty{
}else{
if Klasse1.count > 10{
self.defaults!.removeObject(forKey: "KlasseArray")
self.defaults!.set(Klasse1, forKey: "KlasseArray")
}
}
}
}else{
Klasse1.append(st)
continue
}
}
}
}
}
}
case .failure(let error):
print(error)
}
}
}else{
continue
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
an-indya/WorldWatch | WorldWatch WatchKit Extension/LocalTimeRowController.swift | 1 | 347 | //
// LocalTimeRowController.swift
// AppleWatchDemo
//
// Created by Anindya Sengupta on 27/11/2014.
// Copyright (c) 2014 Anindya Sengupta. All rights reserved.
//
import WatchKit
class LocalTimeRowController: NSObject {
@IBOutlet weak var countryLabel: WKInterfaceLabel!
@IBOutlet weak var localTimeLabel: WKInterfaceDate!
}
| mit |
peaks-cc/iOS11_samplecode | chapter_12/HomeKitSample/App/Code/Protocol/ActionSelector.swift | 1 | 158 | //
// ActionSelector.swift
//
// Created by ToKoRo on 2017-09-03.
//
import HomeKit
protocol ActionSelector {
func selectAction(_ action: HMAction)
}
| mit |
thefuntasty/Funtasty-CleanSwift-templates | Clean Swift/Specs.xctemplate/___FILEBASENAME___InteractorSpec.swift | 1 | 1319 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
import Quick
import Nimble
@testable import ___PROJECTNAME___
class ___FILEBASENAMEASIDENTIFIER___InteractorSpec: QuickSpec {
// MARK: - Output Spy
class ___FILEBASENAMEASIDENTIFIER___InteractorOutputSpy: ___FILEBASENAMEASIDENTIFIER___InteractorOutput {
}
// MARK: - Worker Spy
class ___FILEBASENAMEASIDENTIFIER___WorkerSpy: ___FILEBASENAMEASIDENTIFIER___WorkerProtocol {
}
override func spec() {
// MARK: - Subject under test
var sut: ___FILEBASENAMEASIDENTIFIER___Interactor!
// MARK: - Test lifecycle
describe("___FILEBASENAMEASIDENTIFIER___Interactor") {
beforeEach {
sut = ___FILEBASENAMEASIDENTIFIER___Interactor()
}
it("<# it can do something #>") {
// when
let outputSpy = ___FILEBASENAMEASIDENTIFIER___InteractorOutputSpy()
sut.output = outputSpy
let workerSpy = ___FILEBASENAMEASIDENTIFIER___WorkerSpy()
sut.worker = workerSpy
// then
// given
}
}
}
}
| mit |
uxmstudio/UXMPDFKit | Pod/Classes/Model/PDFAction.swift | 1 | 8202 | //
// PDFAction.swift
// Pods
//
// Created by Chris Anderson on 9/12/16.
//
//
import Foundation
open class PDFAction {
public static func fromPDFDictionary(_ sourceDictionary: CGPDFDictionaryRef, documentReference: CGPDFDocument) -> PDFAction? {
var action: PDFAction?
var destinationName: CGPDFStringRef? = nil
var destinationString: UnsafePointer<Int8>? = nil
var actionDictionary: CGPDFDictionaryRef? = nil
var destinationArray: CGPDFArrayRef? = nil
if CGPDFDictionaryGetDictionary(sourceDictionary, "A", &actionDictionary) {
var actionType: UnsafePointer<Int8>? = nil
if CGPDFDictionaryGetName(actionDictionary!, "S", &actionType) {
/// Handle GoTo action types
if strcmp(actionType, "GoTo") == 0 {
if !CGPDFDictionaryGetArray(actionDictionary!, "D", &destinationArray) {
CGPDFDictionaryGetString(actionDictionary!, "D", &destinationName)
}
}
else { /// Handle other link action type possibility
/// URI action type
if strcmp(actionType, "URI") == 0 {
var uriString: CGPDFStringRef? = nil
if CGPDFDictionaryGetString(actionDictionary!, "URI", &uriString) {
let uri = UnsafeRawPointer(CGPDFStringGetBytePtr(uriString!)!).assumingMemoryBound(to: Int8.self)
if let target = String(validatingUTF8: uri) {
action = PDFActionURL(stringUrl: target)
}
}
}
}
}
}
else {
/// Handle other link target possibilities
if !CGPDFDictionaryGetArray(sourceDictionary, "Dest", &destinationArray) {
if !CGPDFDictionaryGetString(sourceDictionary, "Dest", &destinationName) {
CGPDFDictionaryGetName(sourceDictionary, "Dest", &destinationString)
}
}
}
/// Handle a destination name
if destinationName != nil {
let catalogDictionary: CGPDFDictionaryRef = documentReference.catalog!
var namesDictionary: CGPDFDictionaryRef? = nil
if CGPDFDictionaryGetDictionary(catalogDictionary, "Names", &namesDictionary) {
var destsDictionary: CGPDFDictionaryRef? = nil
if CGPDFDictionaryGetDictionary(namesDictionary!, "Dests", &destsDictionary) {
let localDestinationName = UnsafeRawPointer(CGPDFStringGetBytePtr(destinationName!)!).assumingMemoryBound(to: Int8.self)
destinationArray = self.destinationWithName(localDestinationName, node: destsDictionary!)
}
}
}
/// Handle a destination string
if destinationString != nil {
let catalogDictionary: CGPDFDictionaryRef = documentReference.catalog!
var destsDictionary: CGPDFDictionaryRef? = nil
if CGPDFDictionaryGetDictionary(catalogDictionary, "Dests", &destsDictionary) {
var targetDictionary: CGPDFDictionaryRef? = nil
if CGPDFDictionaryGetDictionary(destsDictionary!, destinationString!, &targetDictionary) {
CGPDFDictionaryGetArray(targetDictionary!, "D", &destinationArray)
}
}
}
/// Handle a destination array
if (destinationArray != nil) {
var targetPageNumber = 0
var pageDictionaryFromDestArray: CGPDFDictionaryRef? = nil
if CGPDFArrayGetDictionary(destinationArray!, 0, &pageDictionaryFromDestArray) {
let pageCount = documentReference.numberOfPages
for pageNumber in 1...pageCount {
let pageRef: CGPDFPage = documentReference.page(at: pageNumber)!
let pageDictionaryFromPage: CGPDFDictionaryRef = pageRef.dictionary!
if pageDictionaryFromPage == pageDictionaryFromDestArray {
targetPageNumber = pageNumber
break
}
}
}
else {
var pageNumber: CGPDFInteger = 0
if CGPDFArrayGetInteger(destinationArray!, 0, &pageNumber) {
targetPageNumber = (pageNumber + 1)
}
}
/// We have a target page number, make GoTo link
if targetPageNumber > 0 {
action = PDFActionGoTo(pageIndex: targetPageNumber)
}
}
return action
}
fileprivate static func destinationWithName(_ destinationName: UnsafePointer<Int8>, node: CGPDFDictionaryRef) -> CGPDFArrayRef? {
var destinationArray: CGPDFArrayRef? = nil
var limitsArray: CGPDFArrayRef? = nil
if CGPDFDictionaryGetArray(node, "Limits", &limitsArray) {
var lowerLimit: CGPDFStringRef? = nil
var upperLimit: CGPDFStringRef? = nil
if CGPDFArrayGetString(limitsArray!, 0, &lowerLimit)
&& CGPDFArrayGetString(limitsArray!, 1, &upperLimit) {
let llu = CGPDFStringGetBytePtr(lowerLimit!)!
let ulu = CGPDFStringGetBytePtr(upperLimit!)!
let ll:UnsafePointer<Int8> = UnsafeRawPointer(llu).assumingMemoryBound(to: Int8.self)
let ul:UnsafePointer<Int8> = UnsafeRawPointer(ulu).assumingMemoryBound(to: Int8.self)
if (strcmp(destinationName, ll) < 0) || (strcmp(destinationName, ul) > 0) {
return nil
}
}
}
var namesArray: CGPDFArrayRef? = nil
if CGPDFDictionaryGetArray(node, "Names", &namesArray) {
let namesCount = CGPDFArrayGetCount(namesArray!)
for i in stride(from: 0, to: namesCount, by: 2) {
var destName: CGPDFStringRef? = nil
if CGPDFArrayGetString(namesArray!, i, &destName) {
let dnu = CGPDFStringGetBytePtr(destName!)!
let dn: UnsafePointer<Int8> = UnsafeRawPointer(dnu).assumingMemoryBound(to: Int8.self)
if strcmp(dn, destinationName) == 0 {
if !CGPDFArrayGetArray(namesArray!, (i + 1), &destinationArray) {
var destinationDictionary: CGPDFDictionaryRef? = nil
if CGPDFArrayGetDictionary(namesArray!, (i + 1), &destinationDictionary) {
CGPDFDictionaryGetArray(destinationDictionary!, "D", &destinationArray)
}
}
return destinationArray!
}
}
}
}
var kidsArray: CGPDFArrayRef? = nil
if CGPDFDictionaryGetArray(node, "Kids", &kidsArray) {
let kidsCount = CGPDFArrayGetCount(kidsArray!)
for i in 0..<kidsCount {
var kidNode: CGPDFDictionaryRef? = nil
if CGPDFArrayGetDictionary(kidsArray!, i, &kidNode) {
destinationArray = self.destinationWithName(destinationName, node: kidNode!)
if destinationArray != nil {
return destinationArray!
}
}
}
}
return nil
}
}
| mit |
uxmstudio/UXMPDFKit | Pod/Classes/Extensions/CGPoint.swift | 1 | 1004 | //
// CGPoint.swift
// Pods
//
// Created by Chris Anderson on 2/1/17.
//
//
import Foundation
extension CGPoint {
/// Create a rectangle using two points
///
/// - parameter self: The first point to use
/// - parameter point: The second point to utilize
///
/// - returns: A rectangle using the two points as opposite corners
func rect(from point: CGPoint) -> CGRect {
return CGRect(x: min(self.x, point.x),
y: min(self.y, point.y),
width: abs(self.x - point.x),
height: abs(self.y - point.y))
}
/// Get the distance between two points
///
/// - parameter self: The first point to use
/// - parameter point: The second point to utilize
///
/// - returns: A float value of the distance between points
func distance(point: CGPoint) -> CGFloat {
let dx = point.x - self.x
let dy = point.y - self.y
return sqrt(dx*dx + dy*dy)
}
}
| mit |
s1Moinuddin/TextFieldWrapper | Example/TextFieldWrapper/SimpleViewController.swift | 1 | 4008 | //
// TestOneViewController.swift
// UltimateTextFieldExample
//
// Created by Shuvo on 7/28/17.
// Copyright © 2017 Shuvo. All rights reserved.
//
import UIKit
import TextFieldWrapper
class SimpleViewController: UIViewController {
//MARK:- Private Outlets
@IBOutlet weak private var countLabel: UILabel!
@IBOutlet weak private var customTxtFld: SMTextField!
@IBOutlet weak private var phoneNumTxtFld: SMHoshiTextField!
@IBOutlet weak private var phoneNumLabel: UILabel!
@IBOutlet weak private var shakeBttn: UIButton!
@IBOutlet weak private var nextBttn: UIButton!
@IBOutlet weak private var dummyBttn: UIButton!
//MARK:- Private Constant
private let cornerRadius:CGFloat = 4
private let borderWidth:CGFloat = 2
private let borderColor:CGColor = UIColor.black.cgColor
//MARK:- View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupButtons()
customTxtFld.characterChangedEvent = { [weak self] (str, num) in
self?.countLabel.text = "NameFld No. of characters = \(num)/15"
}
customTxtFld.zoomScale = 1.4
customTxtFld.addBlurToView = self.view
customTxtFld.maxCharacter = 15
customTxtFld.placeholderFont = UIFont.systemFont(ofSize: 13.0, weight: UIFontWeightLight)
phoneNumTxtFld.zoomScale = 1.8
phoneNumTxtFld.maxCharacter = 12
phoneNumTxtFld.shouldTrim = false
phoneNumTxtFld.addBlurToView = self.view
phoneNumTxtFld.characterChangedEvent = { [weak self] (str, num) in
self?.phoneNumLabel.text = "\(num) / 12"
print("phoneNumTxtFld: \(str)--Num: \(num)")
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
//MARK:- Private Methods
private func setupButtons() {
shakeBttn.layer.cornerRadius = cornerRadius
shakeBttn.layer.borderWidth = borderWidth
shakeBttn.layer.borderColor = borderColor
nextBttn.layer.cornerRadius = cornerRadius
nextBttn.layer.borderWidth = borderWidth
nextBttn.layer.borderColor = borderColor
dummyBttn.layer.cornerRadius = cornerRadius
dummyBttn.layer.borderWidth = borderWidth
dummyBttn.layer.borderColor = borderColor
}
//MARK:- Button Action
@IBAction private func shakeBtnAction(_ sender: UIButton) {
if sender.isSelected {
phoneNumTxtFld.shake()
customTxtFld.placeholderColor = .red
customTxtFld.shake(completion: { [weak self] in
self?.customTxtFld.placeholderColor = .blue
})
} else {
phoneNumTxtFld.shake(borderColor: .red, borderWidth: 2.0)
customTxtFld.placeholderColor = .green
customTxtFld.shake(borderColor: .red, borderWidth: 4, completion: {
[weak self] in
self?.customTxtFld.placeholderColor = .brown
})
}
sender.isSelected = !sender.isSelected
print("is Text withing limit = \(customTxtFld.isValid)")
}
@IBAction private func dummyAction(_ sender: UIButton) {
self.view.endEditing(true)
phoneNumLabel.text = phoneNumTxtFld.isValid ? phoneNumLabel.text : "Not Valid"
}
@IBAction private func goNextAction(_ sender: UIButton) {
self.view.endEditing(true)
let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc = storyBoard.instantiateViewController(withIdentifier: "ListViewController")
navigationController?.pushViewController(vc, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
kaltura/playkit-ios | Classes/Player/Decorators/PlayerDecoratorBase.swift | 1 | 5551 | // ===================================================================================================
// Copyright (C) 2017 Kaltura Inc.
//
// Licensed under the AGPLv3 license, unless a different license for a
// particular library is specified in the applicable library path.
//
// You may obtain a copy of the License at
// https://www.gnu.org/licenses/agpl-3.0.html
// ===================================================================================================
import Foundation
import AVFoundation
import AVKit
@objc open class PlayerDecoratorBase: NSObject, Player {
fileprivate var player: Player!
public func setPlayer(_ player: Player!) {
self.player = player
}
public func getPlayer() -> Player {
return self.player
}
// ***************************** //
// MARK: - Player
// ***************************** //
weak public var mediaEntry: PKMediaEntry? {
return self.player.mediaEntry
}
public var settings: PKPlayerSettings {
return self.player.settings
}
public var mediaFormat: PKMediaSource.MediaFormat {
return self.player.mediaFormat
}
public var sessionId: String {
return self.player.sessionId
}
public func addObserver(_ observer: AnyObject, event: PKEvent.Type, block: @escaping (PKEvent) -> Void) {
//Assert.shouldNeverHappen();
}
public func addObserver(_ observer: AnyObject, events: [PKEvent.Type], block: @escaping (PKEvent) -> Void) {
//Assert.shouldNeverHappen();
}
public func removeObserver(_ observer: AnyObject, event: PKEvent.Type) {
//Assert.shouldNeverHappen();
}
public func removeObserver(_ observer: AnyObject, events: [PKEvent.Type]) {
//Assert.shouldNeverHappen();
}
public func updatePluginConfig(pluginName: String, config: Any) {
self.player.updatePluginConfig(pluginName: pluginName, config: config)
}
public func updateTextTrackStyling() {
self.player.updateTextTrackStyling()
}
public func isLive() -> Bool {
return self.player.isLive()
}
public func getController(type: PKController.Type) -> PKController? {
return self.player.getController(type: type)
}
public func addPeriodicObserver(interval: TimeInterval, observeOn dispatchQueue: DispatchQueue? = nil, using block: @escaping (TimeInterval) -> Void) -> UUID {
return self.player.addPeriodicObserver(interval: interval, observeOn: dispatchQueue, using: block)
}
public func addBoundaryObserver(boundaries: [PKBoundary], observeOn dispatchQueue: DispatchQueue? = nil, using block: @escaping (TimeInterval, Double) -> Void) -> UUID {
return self.player.addBoundaryObserver(boundaries: boundaries, observeOn: dispatchQueue, using: block)
}
public func removePeriodicObserver(_ token: UUID) {
self.player.removePeriodicObserver(token)
}
public func removeBoundaryObserver(_ token: UUID) {
self.player.removeBoundaryObserver(token)
}
// ***************************** //
// MARK: - BasicPlayer
// ***************************** //
public var duration: Double {
return self.player.duration
}
open var currentState: PlayerState {
return self.player.currentState
}
open var isPlaying: Bool {
return self.player.isPlaying
}
public weak var view: PlayerView? {
get {
return self.player.view
}
set {
self.player.view = newValue
}
}
public var currentTime: TimeInterval {
get {
return self.player.currentTime
}
set {
self.player.currentTime = newValue
}
}
public var currentProgramTime: Date? {
return self.player.currentProgramTime
}
public var currentAudioTrack: String? {
return self.player.currentAudioTrack
}
public var currentTextTrack: String? {
return self.player.currentTextTrack
}
public var rate: Float {
get {
return self.player.rate
}
set {
self.player.rate = newValue
}
}
public var volume: Float {
get {
return self.player.volume
}
set {
self.player.volume = newValue
}
}
@objc public var loadedTimeRanges: [PKTimeRange]? {
return self.player.loadedTimeRanges
}
@objc public var bufferedTime: TimeInterval {
return self.player.bufferedTime
}
open func play() {
self.player.play()
}
open func pause() {
self.player.pause()
}
open func resume() {
self.player.resume()
}
open func stop() {
self.player.stop()
}
public func replay() {
self.player.replay()
}
open func seek(to time: TimeInterval) {
self.player.seek(to: time)
}
open func seekToLiveEdge() {
self.player.seekToLiveEdge()
}
public func selectTrack(trackId: String) {
self.player.selectTrack(trackId: trackId)
}
open func destroy() {
self.player.destroy()
}
open func prepare(_ config: MediaConfig) {
self.player.prepare(config)
}
public func startBuffering() {
self.player.startBuffering()
}
}
| agpl-3.0 |
treejames/firefox-ios | UITests/ViewMemoryLeakTests.swift | 10 | 5113 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
/// Set of tests that wait for weak references to views to be cleared. Technically, this is
/// non-deterministic and there are no guarantees the references will be set to nil. In practice,
/// though, the references are consistently cleared, which should be good enough for testing.
class ViewMemoryLeakTests: KIFTestCase, UITextFieldDelegate {
private var webRoot: String!
override func setUp() {
webRoot = SimplePageServer.start()
}
override func tearDown() {
if tester().tryFindingTappableViewWithAccessibilityLabel("home", error: nil) {
tester().tapViewWithAccessibilityLabel("home")
}
BrowserUtils.resetToAboutHome(tester())
}
func testAboutHomeDisposed() {
// about:home is already active on startup; grab a reference to it.
let browserViewController = UIApplication.sharedApplication().keyWindow!.rootViewController!
weak var aboutHomeController = getChildViewController(browserViewController, childClass: "HomePanelViewController")
// Change the page to make about:home go away.
tester().tapViewWithAccessibilityIdentifier("url")
let url = "\(webRoot)/numberedPage.html?page=1"
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Page 1")
tester().runBlock { _ in
return (aboutHomeController == nil) ? KIFTestStepResult.Success : KIFTestStepResult.Wait
}
XCTAssertNil(aboutHomeController, "about:home controller disposed")
}
func testSearchViewControllerDisposed() {
// Type the URL to make the search controller appear.
tester().tapViewWithAccessibilityIdentifier("url")
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("foobar")
let browserViewController = UIApplication.sharedApplication().keyWindow!.rootViewController!
weak var searchViewController = getChildViewController(browserViewController, childClass: "SearchViewController")
XCTAssertNotNil(searchViewController, "Got search controller reference")
// Submit to close about:home and the search controller.
tester().enterTextIntoCurrentFirstResponder("\n")
tester().runBlock { _ in
return (searchViewController == nil) ? KIFTestStepResult.Success : KIFTestStepResult.Wait
}
XCTAssertNil(searchViewController, "Search controller disposed")
}
func testTabTrayDisposed() {
let browserViewController = UIApplication.sharedApplication().keyWindow!.rootViewController!
// Enter the tab tray.
tester().tapViewWithAccessibilityLabel("Show Tabs")
tester().waitForViewWithAccessibilityLabel("Tabs Tray")
weak var tabTrayController = browserViewController.presentedViewController
weak var tabCell = tester().waitForTappableViewWithAccessibilityLabel("home")
XCTAssertNotNil(tabTrayController, "Got tab tray reference")
XCTAssertNotNil(tabCell, "Got tab cell reference")
// Leave the tab tray.
tester().tapViewWithAccessibilityLabel("home")
tester().runBlock { _ in
return (tabTrayController == nil) ? KIFTestStepResult.Success : KIFTestStepResult.Wait
}
XCTAssertNil(tabTrayController, "Tab tray controller disposed")
tester().runBlock { _ in
return (tabCell == nil) ? KIFTestStepResult.Success : KIFTestStepResult.Wait
}
XCTAssertNil(tabCell, "Tab tray cell disposed")
}
func testWebViewDisposed() {
weak var webView = tester().waitForViewWithAccessibilityLabel("Web content")
XCTAssertNotNil(webView, "webView found")
tester().tapViewWithAccessibilityLabel("Show Tabs")
let tabsView = tester().waitForViewWithAccessibilityLabel("Tabs Tray").subviews.first as! UICollectionView
let cell = tabsView.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0))!
tester().swipeViewWithAccessibilityLabel(cell.accessibilityLabel, inDirection: KIFSwipeDirection.Left)
tester().waitForTappableViewWithAccessibilityLabel("Show Tabs")
tester().runBlock { _ in
return (webView == nil) ? KIFTestStepResult.Success : KIFTestStepResult.Wait
}
XCTAssertNil(webView, "webView disposed")
}
private func getChildViewController(parent: UIViewController, childClass: String) -> UIViewController {
let childControllers = parent.childViewControllers.filter { child in
let description = NSString(string: child.description)
return description.containsString(childClass)
}
XCTAssertEqual(childControllers.count, 1, "Found 1 child controller of type: \(childClass)")
return childControllers.first as! UIViewController
}
}
| mpl-2.0 |
HeartRateLearning/HRLApp | HRLApp/Modules/ListWorkoutDates/Presenter/ListWorkoutDatesModuleInput.swift | 1 | 301 | //
// ListWorkoutDatesListWorkoutDatesModuleInput.swift
// HRLApp
//
// Created by Enrique de la Torre on 30/01/2017.
// Copyright © 2017 Enrique de la Torre. All rights reserved.
//
import Foundation
protocol ListWorkoutDatesModuleInput: class {
func configure(withWorkoutAt index: Int)
}
| mit |
codepgq/AnimateDemo | Animate/Animate/controller/BaseAnimation/Scale/ScaleController.swift | 1 | 1396 | //
// ScaleController.swift
// Animate
//
// Created by Mac on 17/2/7.
// Copyright © 2017年 Mac. All rights reserved.
//
import UIKit
class ScaleController: UIViewController {
@IBOutlet weak var imgView1: UIImageView!
@IBOutlet weak var imgView2: UIImageView!
@IBOutlet weak var imgView3: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
startAnimation()
}
func startAnimation(){
//Scale
let scaleAnimate = Animate.baseAnimationWithKeyPath("transform.scale", fromValue: nil, toValue: 1.2, duration: 1.5, repeatCount: Float.infinity, timingFunction: nil)
scaleAnimate.autoreverses = true
imgView1.layer.add(scaleAnimate, forKey: "transform.scale")
//Scale
let scaleXAnimate = Animate.baseAnimationWithKeyPath("transform.scale.x", fromValue: nil, toValue: 2.0, duration: 1.5, repeatCount: Float.infinity, timingFunction: nil)
scaleXAnimate.autoreverses = true
imgView2.layer.add(scaleXAnimate, forKey: "transform.scale.x")
//Scale
let scaleYAnimate = Animate.baseAnimationWithKeyPath("transform.scale.y", fromValue: nil, toValue: 1.5, duration: 1.5, repeatCount: Float.infinity, timingFunction: nil)
scaleYAnimate.autoreverses = true
imgView3.layer.add(scaleYAnimate, forKey: "transform.scale.y")
}
}
| apache-2.0 |
quickthyme/PUTcat | PUTcat/Application/UseCase/Parser/UseCaseFetchParserList.swift | 1 | 222 |
import Foundation
class UseCaseFetchParserList {
class func action(transactionID: String) -> Composed.Action<Any, PCList<PCParser>> {
return PCParserRepository.fetchList(transactionID: transactionID)
}
}
| apache-2.0 |
TCA-Team/iOS | TUM Campus App/FilmTableViewCell.swift | 1 | 479 | //
// FilmTableViewCell.swift
// Campus
//
// Created by Till on 12.06.18.
// Copyright © 2018 LS1 TUM. All rights reserved.
//
import UIKit
class FilmTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| gpl-3.0 |
IdeasOnCanvas/Callisto | Callisto/GithubAction.swift | 1 | 7567 | //
// Github.swift
// Callisto
//
// Created by Patrick Kladek on 02.08.19.
// Copyright © 2019 IdeasOnCanvas. All rights reserved.
//
import Foundation
import ArgumentParser
/// Responsible to read the build summaries and post them to github
final class Github: ParsableCommand {
public static let configuration = CommandConfiguration(abstract: "Upload Build Summary to Github")
@Option(help: "Token to access Github")
var githubToken: String
@Option(help: "Organisation Account Name in Github")
var githubOrganisation: String
@Option(help: "Github Repository Name")
var githubRepository: String
@Option(help: "Github Branch")
var branch: String
@Flag(help: "Delete previously postet comments from pull qequest")
var deletePreviousComments: Bool = false
@Argument(help: "Location for .buildReport file", completion: .file(), transform: URL.init(fileURLWithPath:))
var files: [URL] = []
func run() throws {
let uploadAction = UploadAction(upload: self)
try uploadAction.run()
}
}
final class UploadAction {
let githubController: GitHubCommunicationController
let upload: Github
// MARK: - Lifecycle
init(upload: Github) {
self.upload = upload
let repo = GithubRepository(organisation: upload.githubOrganisation, repository: upload.githubRepository)
let access = GithubAccess(token: upload.githubToken)
self.githubController = GitHubCommunicationController(access: access, repository: repo)
}
// MARK: - UploadAction
func run() throws {
let inputFiles = self.upload.files
guard inputFiles.hasElements else { quit(.invalidBuildInformationFile) }
let infos = self.filteredBuildInfos(inputFiles.map { BuildInformation.read(url: $0) }.compactMap { result -> BuildInformation? in
switch result {
case .success(let info):
return info
case .failure(let error):
LogError("\(error)")
return nil
}
})
guard infos.hasElements else { quit(.invalidBuildInformationFile) }
let currentBranch = self.loadCurrentBranch()
LogMessage("Did load Branch:")
LogMessage(" * \(currentBranch.title ?? "<nil>") \(currentBranch.number ?? -1)")
LogMessage(" * \(currentBranch.url?.absoluteString ?? "<nil>")")
if self.upload.deletePreviousComments {
let result = self.githubController.fetchPreviousComments(on: currentBranch)
switch result {
case .failure(let error):
LogError(error.localizedDescription)
case .success(let comments):
let commentsToDelete = comments.filter { $0.isCallistoComment }
if commentsToDelete.hasElements {
LogMessage("Found \(commentsToDelete.count) outdated build comment\(commentsToDelete.count > 1 ? "s" : ""). Deleting ...")
}
_ = commentsToDelete.map { comment in
switch self.githubController.deleteComment(comment: comment) {
case .success:
LogMessage("Deleted comment with ID: \(comment.id!)")
case .failure(let error):
LogError(error.localizedDescription)
}
}
}
}
if infos.filter({ $0.isEmpty == false }).hasElements {
let message = "# Build Summary\n\(infos.compactMap { self.markdownText(from: $0) }.joined(separator: "\n"))"
switch self.githubController.postComment(on: currentBranch, comment: Comment(body: message, id: nil)) {
case .success:
LogMessage("Successfully posted BuildReport to GitHub")
case .failure(let error):
LogError(error.localizedDescription)
}
}
quit(.success)
}
}
// MARK: - Private
private extension UploadAction {
func filteredBuildInfos(_ infos: [BuildInformation]) -> [BuildInformation] {
let coreInfos = self.commonInfos(infos)
let stripped = self.stripInfos(coreInfos, from: infos)
var allBuildInfos = stripped
if let coreInfos = coreInfos {
allBuildInfos.append(coreInfos)
}
return allBuildInfos
}
func loadCurrentBranch() -> Branch {
switch self.githubController.branch(named: self.upload.branch) {
case .success(let branch):
return branch
case .failure(let error):
LogError(error.localizedDescription)
quit(.reloadBranchFailed)
}
}
func commonInfos(_ infos: [BuildInformation]) -> BuildInformation? {
guard infos.count > 1 else { return nil }
let commonErrors = infos[0].errors.filter { infos[1].errors.contains($0) }
let commonWarnings = infos[0].warnings.filter { infos[1].warnings.contains($0) }
let commonUnitTests = infos[0].unitTests.filter { infos[1].unitTests.contains($0) }
return BuildInformation(platform: "Core",
errors: commonErrors,
warnings: commonWarnings,
unitTests: commonUnitTests,
config: .empty)
}
func stripInfos(_ strip: BuildInformation?, from: [BuildInformation]) -> [BuildInformation] {
guard let strip = strip else { return from }
return from.map { info -> BuildInformation in
BuildInformation(platform: info.platform,
errors: info.errors.deleting(strip.errors),
warnings: info.warnings.deleting(strip.warnings),
unitTests: info.unitTests.deleting(strip.unitTests),
config: .empty)
}
}
func logBuildInfo(_ infos: [BuildInformation]) {
for info in infos {
LogMessage("*** \(info.platform) ***")
for error in info.errors {
LogError(error.description)
}
for warning in info.warnings {
LogWarning(warning.description)
}
for unitTest in info.unitTests {
LogWarning(unitTest.description)
}
}
}
func markdownText(from info: BuildInformation) -> String? {
guard info.errors.hasElements ||
info.warnings.hasElements ||
info.unitTests.hasElements else { return nil }
var string = info.githubSummaryTitle
string += "\n\n"
if info.errors.hasElements {
string += "\n\n"
string += info.errors.map { ":red_circle: **\($0.file):\($0.line)**\n\($0.message)" }.joined(separator: "\n\n")
}
if info.warnings.hasElements {
string += "\n\n"
string += info.warnings.map { ":warning: **\($0.file):\($0.line)**\n\($0.message)" }.joined(separator: "\n\n")
}
if info.unitTests.hasElements {
string += "\n\n"
string += info.unitTests.map { ":large_blue_circle: `\($0.method)`\n\($0.assertType)\n\($0.explanation)" }.joined(separator: "\n\n")
}
string += "\n\n"
return string
}
}
private extension Comment {
var isCallistoComment: Bool {
guard self.id != nil else { return false }
let text = self.body as NSString
return text.range(of: "# Build Summary\n").location == 0
}
}
| mit |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTransaction/Sources/FeatureTransactionDomain/Send/BlockchainNameResolution/BlockchainNameResolutionService.swift | 1 | 3034 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import MoneyKit
import PlatformKit
public protocol BlockchainNameResolutionServiceAPI {
func validate(
domainName: String,
currency: CryptoCurrency
) -> AnyPublisher<ReceiveAddress?, Never>
func reverseResolve(
address: String
) -> AnyPublisher<[String], Never>
}
final class BlockchainNameResolutionService: BlockchainNameResolutionServiceAPI {
private let repository: BlockchainNameResolutionRepositoryAPI
private let factory: ExternalAssetAddressServiceAPI
init(
repository: BlockchainNameResolutionRepositoryAPI = resolve(),
factory: ExternalAssetAddressServiceAPI = resolve()
) {
self.repository = repository
self.factory = factory
}
func validate(
domainName: String,
currency: CryptoCurrency
) -> AnyPublisher<ReceiveAddress?, Never> {
guard preValidate(domainName: domainName) else {
return .just(nil)
}
return repository
.resolve(domainName: domainName, currency: currency.code)
.eraseError()
.flatMap { [factory] response -> AnyPublisher<ReceiveAddress?, Error> in
factory
.makeExternalAssetAddress(
asset: currency,
address: response.address,
label: Self.label(address: response.address, domain: domainName),
onTxCompleted: { _ in .empty() }
)
.map { $0 as ReceiveAddress }
.publisher
.eraseToAnyPublisher()
.eraseError()
}
.replaceError(with: nil)
.eraseToAnyPublisher()
}
func reverseResolve(
address: String
) -> AnyPublisher<[String], Never> {
repository
.reverseResolve(address: address)
.replaceError(with: [])
.map { $0.map(\.domainName) }
.eraseToAnyPublisher()
}
private static func label(address: String, domain: String) -> String {
"\(domain) (\(address.prefix(4))...\(address.suffix(4)))"
}
private func preValidate(domainName: String) -> Bool {
preValidateEmojiDomain(domainName)
|| preValidateRegularDomain(domainName)
}
private func preValidateEmojiDomain(_ domainName: String) -> Bool {
domainName.containsEmoji
}
private func preValidateRegularDomain(_ domainName: String) -> Bool {
// Separated by '.' (period)
let components = domainName.components(separatedBy: ".")
// Must have more than one component
guard components.count > 1 else {
return false
}
// No component may be empty
guard !components.contains(where: \.isEmpty) else {
return false
}
// Pre validation passes
return true
}
}
| lgpl-3.0 |
CrazyKids/ADSideMenu | ADSideMenuSample/ADSideMenuSampleTests/ADSideMenuSampleTests.swift | 1 | 1006 | //
// ADSideMenuSampleTests.swift
// ADSideMenuSampleTests
//
// Created by duanhongjin on 16/6/17.
// Copyright © 2016年 CrazyKids. All rights reserved.
//
import XCTest
@testable import ADSideMenuSample
class ADSideMenuSampleTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
pepaslabs/TODOApp | TODOApp/ListsTableViewController.swift | 1 | 3291 | //
// ListsTableViewController.swift
// TODOApp
//
// Created by Pepas Personal on 8/2/15.
// Copyright (c) 2015 Pepas Personal. All rights reserved.
//
import UIKit
class ListsTableViewController: UITableViewController
{
private var dataSource: ListsTableViewDataSource = ListsTableViewDataSource()
override func viewDidLoad()
{
super.viewDidLoad()
title = "Lists"
_setupTableView()
}
}
// MARK: Factory methods
extension ListsTableViewController
{
class func storyboard() -> UIStoryboard
{
let storyboard = UIStoryboard(name: "ListsTableViewController", bundle: nil)
return storyboard
}
class func instantiateFromStoryboard() -> ListsTableViewController
{
let storyboard = self.storyboard()
let vc = storyboard.instantiateViewControllerWithIdentifier("ListsTableViewController") as! ListsTableViewController
return vc
}
}
extension ListsTableViewController: UITableViewDelegate
{
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
if let title = dataSource.titleAtIndex(indexPath.row)
{
switch title {
case "Tasks":
_presentTasksTableViewController()
case "Done":
_presentDoneTableViewController()
default:
return
}
}
}
}
// MARK: private helpers
extension ListsTableViewController
{
private func _setupTableView()
{
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
tableView.dataSource = dataSource
}
private func _presentTasksTableViewController()
{
// let vc = TasksTableViewController.instantiateFromStoryboard()
let vc = TasksTableViewController2Factory.createDefaultController()
navigationController?.showViewController(vc, sender: self)
}
private func _presentDoneTableViewController()
{
// let vc = DoneTableViewController.instantiateFromStoryboard()
let vc = TasksTableViewController2Factory.createDoneController()
navigationController?.showViewController(vc, sender: self)
}
}
class ListsTableViewDataSource: NSObject
{
func titleAtIndex(index: Int) -> String?
{
switch index {
case 0:
return "Tasks"
case 1:
return "Done"
default:
return nil
}
}
}
extension ListsTableViewDataSource: UITableViewDataSource
{
@objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 2
}
@objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell", forIndexPath: indexPath) as! UITableViewCell
_configureCell(cell, atIndex: indexPath.row)
return cell
}
}
// MARK: private helpers
extension ListsTableViewDataSource
{
private func _configureCell(cell: UITableViewCell, atIndex index: Int)
{
cell.textLabel?.text = titleAtIndex(index)
}
}
| mit |
CUITCHE/code-obfuscation | obfuse-code/obfuse-code/flag.swift | 1 | 13161 | //
// flag.swift
// CodeObfuscation
//
// Created by hejunqiu on 2017/7/10.
// Copyright © 2017年 CHE. All rights reserved.
//
import Foundation
fileprivate protocol Value {
/// 返回值的string形式,要求返回的string能转换成值
var string: String { get }
/// 用string设置值
///
/// - Parameter str: 值的string形式
/// - Returns: optional类型,如果改string不能匹配到值,则返回一个字符串表示出错。
func set(str: String) -> String?
func set(str: Substring) -> String?
}
extension Value {
func set(str: Substring) -> String? {
return set(str: String(str))
}
}
public struct Flag {
fileprivate static var identifier = 0
fileprivate let id: Int = {
defer {
Flag.identifier += 1
}
return Flag.identifier
}()
let name: String
let usage: String
fileprivate var value: Value
fileprivate let defValue: String
var isBoolFlag: Bool {
return value is _Bool
}
static func unquoteUsage(flag: Flag) -> (name: String, usage: String) {
let usage = flag.usage as NSString
let first = usage.range(of: "`")
let second = usage.range(of: "`", options: .backwards, range: NSRange.init(location: 0, length: usage.length), locale: nil)
if first.location != second.location {
let name = usage.substring(with: NSRange.init(location: first.location + 1, length: second.location - first.location - 1))
let usageNew = usage.substring(to: first.location) + name + usage.substring(from: second.location + 1)
return (name: name, usage: usageNew)
}
var name = "value"
if flag.value is _Bool {
name = ""
} else if flag.value is _Integer {
name = "int"
} else if flag.value is _Float {
name = "float"
} else if flag.value is _String {
name = "string"
}
return (name: name, usage: usage as String)
}
}
public typealias __bool = Bool
fileprivate class _Bool: Value {
var val: UnsafeMutablePointer<__bool>
init(booleanLiteral value: Bool) {
self.val = UnsafeMutablePointer<__bool>.allocate(capacity: MemoryLayout<__bool>.size)
self.val.initialize(to: value)
}
deinit {
val.deinitialize()
val.deallocate(capacity: MemoryLayout<__bool>.size)
}
fileprivate func set(str: String) -> String? {
if let b = Bool(str) {
val.pointee = b
} else {
return "invalid syntax"
}
return nil
}
var string: String {
return val.pointee ? "true" : "false"
}
}
fileprivate class _Integer: Value {
var val: UnsafeMutablePointer<sint64>
init(value: sint64) {
self.val = UnsafeMutablePointer<sint64>.allocate(capacity: MemoryLayout<sint64>.size)
self.val.initialize(to: value)
}
deinit {
val.deinitialize()
val.deallocate(capacity: MemoryLayout<sint64>.size)
}
func set(str: String) -> String? {
if let val = sint64(str) {
self.val.pointee = val
} else {
return "invalid syntax"
}
return nil
}
var string: String {
return String(self.val.pointee)
}
}
fileprivate class _Float: Value {
var val: UnsafeMutablePointer<Double>
init(value: Double) {
self.val = UnsafeMutablePointer<Double>.allocate(capacity: MemoryLayout<Double>.size)
self.val.initialize(to: value)
}
deinit {
val.deinitialize()
val.deallocate(capacity: MemoryLayout<Double>.size)
}
func set(str: String) -> String? {
if let val = Double(str) {
self.val.pointee = val
} else {
return "invalid syntax"
}
return nil
}
var string: String {
return String(self.val.pointee)
}
}
fileprivate class _String: Value {
var val: UnsafeMutablePointer<NSString>
init(value: String) {
self.val = UnsafeMutablePointer<NSString>.allocate(capacity: MemoryLayout<NSString>.size)
self.val.initialize(to: value as NSString)
}
deinit {
val.deinitialize()
val.deallocate(capacity: MemoryLayout<NSString>.size)
}
func set(str: String) -> String? {
self.val.pointee = str as NSString
return nil
}
var string: String {
return self.val.pointee as String
}
}
public struct FlagSet {
let name: String
fileprivate var parsed = false
fileprivate var formal = [String: Flag]()
fileprivate var actual = [String: Flag]()
var args: [String]
var output: UnsafeMutablePointer<FILE>? = nil
init() {
var argv = CommandLine.arguments
let name = argv.removeFirst()
self.name = (name as NSString).lastPathComponent
self.args = argv
}
}
fileprivate extension FlagSet {
func out() -> UnsafeMutablePointer<FILE> {
if self.output == nil {
return stderr
}
return self.output!
}
mutating func bindVariable(value: Value, name: String, usage: String) {
if formal.index(forKey: name) != nil {
var msg: String
if self.name.characters.count == 0 {
msg = "flag redefined: \(name)"
} else {
msg = "\(self.name) flag redefined: \(name)"
}
putln(text: msg)
}
let flag = Flag.init(name: name, usage: usage, value: value, defValue: value.string)
formal[name] = flag
}
mutating func Bool(value: Bool, name: String, usage: String) -> UnsafePointer<__bool> {
let bool = _Bool.init(booleanLiteral: value)
self.bindVariable(value: bool, name: name, usage: usage)
return UnsafePointer<__bool>(bool.val)
}
mutating func Integer(value: sint64, name: String, usage: String) -> UnsafePointer<sint64> {
let integer = _Integer.init(value: value)
self.bindVariable(value: integer, name: name, usage: usage)
return UnsafePointer<sint64>(integer.val)
}
mutating func Float(value: Double, name: String, usage: String) -> UnsafePointer<Double> {
let float = _Float.init(value: value)
self.bindVariable(value: float, name: name, usage: usage)
return UnsafePointer<Double>(float.val)
}
mutating func string(value: String, name: String, usage: String) -> UnsafePointer<NSString> {
let string = _String.init(value: value)
self.bindVariable(value: string, name: name, usage: usage)
return UnsafePointer<NSString>(string.val)
}
mutating func parse() {
self.parsed = true
while true {
let (seen, error) = self.parseOne()
if seen {
continue
}
if error == nil {
break
}
putln(text: error!)
exit(2)
}
}
mutating func parseOne() -> (Bool, String?) {
if args.isEmpty {
return (false, nil)
}
let s = args[0]
if s.count == 0 || s[s.startIndex] != "-" || s.count == 1 {
return (false, "Unknown identifier: \(s)")
}
var numMinuses = 1
if s[s.index(after: s.startIndex)] == "-" {
if s.characters.count == 2 {
args.removeFirst()
return (false, nil)
}
numMinuses += 1
}
var name = s[s.index(s.startIndex, offsetBy: numMinuses)...]
if name.isEmpty || name[name.startIndex] == "-" || name[name.startIndex] == "=" {
return (false, "bad flag syntax: \(s)")
}
args.removeFirst()
var hasValue = false
var value: Substring = ""
for (i, ch) in name.characters.dropFirst().enumerated() {
if ch == "=" {
hasValue = true
value = name[name.index(name.startIndex, offsetBy: i + 1 + 1)...]
name = name[...name.index(name.startIndex, offsetBy: i)]
break
}
}
let flag = formal[String(name)]
if let flag = flag {
if flag.isBoolFlag { // special case: doesn't need an arg
if hasValue {
if let err = flag.value.set(str: value) {
return (false, "invalid boolean value \(value) for -\(name): \(err)")
}
} else {
if let err = flag.value.set(str: "true") {
return (false, "invalid boolean value for -\(name): \(err)")
}
}
} else {
// It must have a value, which might be the next argument.
if hasValue == false && args.count > 0 {
hasValue = true
value = args.first![...]
args.removeFirst()
}
if hasValue == false {
return (false, "flag needs an argument: -\(name)")
}
if let err = flag.value.set(str: value) {
return (false, "invalid value \(value) for flag -\(name): \(err)");
}
}
} else {
if name == "help" || name == "h" { // special case for nice help message.
self.usage()
exit(0)
}
return (false, "flag provided but not defined: -\(name)")
}
actual[String(name)] = flag
return (true, nil)
}
}
public extension FlagSet {
fileprivate func usage() {
defaultUsage()
}
public func defaultUsage() {
if name.characters.count == 0 {
putln(text: "Usage:")
} else {
putln(text: "Usage of \(name):")
}
printDefault()
}
public func printDefault() {
self.visitAll { (flag) in
let name = " -\(flag.name)" // Two spaces before -; see next two comments.
var s = ""
let info = Flag.unquoteUsage(flag: flag)
if info.name.characters.count > 0 {
s += " " + info.name
}
// Boolean flags of one ASCII letter are so common we
// treat them specially, putting their usage on the same line.
if s.characters.count + name.characters.count <= 4 {
s += "\t"
} else {
// Four spaces before the tab triggers good alignment
// for both 4- and 8-space tab stops.
s += "\n \t"
}
s += info.usage
if isZeroValue(flag: flag, value: flag.defValue) == false {
if flag.value is _String {
s += " (default \"\(flag.defValue)\")"
} else {
s += " (default \(flag.defValue))"
}
}
s += "\n"
print(colorText: name, otherText: s)
}
}
public func visitAll(fn: (_ flag: Flag) -> Void) {
let values = formal.values.sorted { $0.id < $1.id }
for flag in values {
fn(flag)
}
}
fileprivate func putln(text: String) {
fputs("\(text)\n", stderr)
}
fileprivate func print(colorText: String, otherText: String) {
fputs("\u{001b}[0;1m\(colorText)\u{001b}[0m\(otherText)\n", stderr)
}
fileprivate func isZeroValue(flag: Flag, value: String) -> Bool {
// Build a zero value of the flag's Value type, and see if the
// result of calling its String method equals the value passed in.
// This works unless the Value type is itself an interface type.
switch value {
case "false":
return true
case "":
return true
case "0":
return true
default:
return false
}
}
}
fileprivate var FlagCommandLine = FlagSet.init()
@objc
public class flag: NSObject {
static func Bool(name: String, defValue: Bool, usage: String) -> UnsafePointer<__bool> {
return FlagCommandLine.Bool(value: defValue, name: name, usage: usage)
}
static func Integer(name: String, defValue: sint64, usage: String) -> UnsafePointer<sint64> {
return FlagCommandLine.Integer(value: defValue, name: name, usage: usage)
}
static func Float(name: String, defValue: Double, usage: String) -> UnsafePointer<Double> {
return FlagCommandLine.Float(value: defValue, name: name, usage: usage)
}
static func String(name: String, defValue: String, usage: String) -> UnsafePointer<NSString> {
let str = FlagCommandLine.string(value: defValue, name: name, usage: usage)
return str
}
static func parse() {
FlagCommandLine.parse()
}
static func parsed() -> Bool {
return FlagCommandLine.parsed
}
static public var executedPath: String {
get {
return CommandLine.arguments.first ?? ""
}
}
}
| mit |
Kawoou/FlexibleImage | Sources/Device/ImageNoneDevice.swift | 1 | 6507 | //
// ImageNoneDevice.swift
// FlexibleImage
//
// Created by Kawoou on 2017. 5. 10..
// Copyright © 2017년 test. All rights reserved.
//
#if !os(OSX)
import UIKit
#else
import AppKit
#endif
internal class ImageNoneDevice: ImageDevice {
// MARK: - Property
internal var context: CGContext?
internal var drawRect: CGRect?
internal var memorySize: Int?
internal var memoryPool: UnsafeMutablePointer<UInt8>?
// MARK: - ImageDevice
internal override func beginGenerate(_ isAlphaProcess: Bool) {
/// Space Size
let scale = self.imageScale
guard let imageRef = self.cgImage else { return }
defer { self.image = nil }
/// Calc size
let tempW = self.spaceSize.width + self.margin.horizontal + self.padding.horizontal
let tempH = self.spaceSize.height + self.margin.vertical + self.padding.vertical
let width = Int(tempW * scale)
let height = Int(tempH * scale)
let spaceRect = CGRect(
x: 0,
y: 0,
width: width,
height: height
)
self.drawRect = spaceRect
/// Alloc Memory
self.memorySize = width * height * 4
self.memoryPool = UnsafeMutablePointer<UInt8>.allocate(capacity: self.memorySize!)
memset(self.memoryPool!, 0, self.memorySize!)
/// Create Context
self.context = CGContext(
data: self.memoryPool,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: width * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: (CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue)
)
/// Push Context
guard let context = self.context else {
self.drawRect = nil
#if swift(>=4.1)
self.memoryPool!.deallocate()
#else
self.memoryPool!.deallocate(capacity: self.memorySize!)
#endif
self.memorySize = nil
self.memoryPool = nil
return
}
/// Corner Radius
if self.corner.isZero() == false {
let cornerPath = self.corner.clipPath(spaceRect)
context.addPath(cornerPath.cgPath)
context.clip()
}
/// Draw Background
if let background = self.background {
context.saveGState()
context.setBlendMode(.normal)
context.setFillColor(background.cgColor)
context.fill(spaceRect)
context.restoreGState()
}
/// Draw
let size = self.scale ?? self.spaceSize
let tempX = self.offset.x + self.margin.left + self.padding.left
let tempY = self.offset.y + self.margin.top + self.padding.top
context.saveGState()
context.setBlendMode(.normal)
context.setAlpha(self.opacity)
if let rotateRadius = self.rotate {
context.translateBy(
x: self.spaceSize.width * 0.5,
y: self.spaceSize.height * 0.5
)
context.rotate(by: rotateRadius)
let calcX = -size.width * 0.5 + tempX
let calcY = -size.height * 0.5 + tempY
let rect = CGRect(
x: calcX * scale,
y: calcY * scale,
width: size.width * scale,
height: size.height * scale
)
self.draw(imageRef, in: rect, on: context)
} else {
let rect = CGRect(
x: tempX * scale,
y: tempY * scale,
width: size.width * scale,
height: size.height * scale
)
self.draw(imageRef, in: rect, on: context)
}
context.restoreGState()
/// Push clip
context.saveGState()
if !isAlphaProcess {
context.clip(to: spaceRect, mask: context.makeImage()!)
}
}
internal override func endGenerate() -> CGImage? {
guard let context = self.context else { return nil }
defer {
self.drawRect = nil
#if swift(>=4.1)
self.memoryPool!.deallocate()
#else
self.memoryPool!.deallocate(capacity: self.memorySize!)
#endif
self.memorySize = nil
self.memoryPool = nil
}
let scale = self.imageScale
/// Pop clip
context.restoreGState()
/// Draw border
if let border = self.border {
let borderPath: FIBezierPath
let borderSize = self.scale ?? self.spaceSize
let borderRect = CGRect(
x: (self.offset.x + self.margin.left) * scale,
y: (self.offset.y + self.margin.top) * scale,
width: (borderSize.width + self.padding.left + self.padding.right) * scale,
height: (borderSize.height + self.padding.top + self.padding.bottom) * scale
)
if border.radius > 0 {
#if !os(OSX)
borderPath = UIBezierPath(roundedRect: borderRect, cornerRadius: border.radius * 2)
#else
borderPath = NSBezierPath(roundedRect: borderRect, xRadius: border.radius * 2, yRadius: border.radius * 2)
#endif
} else {
borderPath = FIBezierPath(rect: borderRect)
}
context.saveGState()
context.setStrokeColor(border.color.cgColor)
context.addPath(borderPath.cgPath)
context.setLineWidth(border.lineWidth)
context.replacePathWithStrokedPath()
context.drawPath(using: .stroke)
context.restoreGState()
}
/// Post-processing
let width = Int(self.drawRect!.width)
let height = Int(self.drawRect!.height)
self.postProcessList.forEach { closure in
closure(context, width, height, memoryPool!)
}
/// Convert Image
return context.makeImage()
}
// MARK: - Lifecycle
internal override init() {
super.init()
self.type = .None
}
}
| mit |
noahemmet/FingerPaint | FingerPaint/ArrayExtensions.swift | 1 | 928 | //
// ArrayExtensions.swift
// FingerPaint
//
// Created by Noah Emmet on 5/8/16.
// Copyright © 2016 Sticks. All rights reserved.
//
import Foundation
extension Array {
public func elementAtIndex(index: Int) -> Element? {
guard index < self.count && index > 0 else {
return nil
}
return self[index]
}
}
extension Array where Element: Equatable {
public mutating func insertUniquely(element: Element) {
if !self.contains(element) {
self.append(element)
}
}
public mutating func insertUniqueContentsOf(elements: [Element]) {
for element in elements {
self.insertUniquely(element)
}
}
public mutating func remove(element: Element) {
guard let index = self.indexOf(element) else {
print("element not found")
return
}
self.removeAtIndex(index)
}
public mutating func removeContentsOf(elements: [Element]) {
for element in elements {
self.remove(element)
}
}
} | apache-2.0 |
cwwise/CWWeChat | CWWeChat/ChatModule/CWChatKit/Message/View/CWMessageCell.swift | 2 | 8697 | //
// CWMessageCell.swift
// CWWeChat
//
// Created by wei chen on 2017/7/14.
// Copyright © 2017年 cwcoder. All rights reserved.
//
import UIKit
protocol CWMessageCellDelegate: NSObjectProtocol {
/// 点击cell文字中的URL
///
/// - Parameters:
/// - cell: cell
/// - link: link
func messageCellDidTap(_ cell: CWMessageCell, link: URL)
/// 点击cell文字中的电话
///
/// - Parameters:
/// - cell: cell
/// - phone: phone
func messageCellDidTap(_ cell: CWMessageCell, phone: String)
/// cell被点击
///
/// - Parameter cell: cell
func messageCellDidTap(_ cell: CWMessageCell)
/// cell 重发按钮点击
///
/// - Parameter cell: cell
func messageCellResendButtonClick(_ cell: CWMessageCell)
/// 头像点击的回调方法
///
/// - Parameter userId: 用户id
func messageCellUserAvatarDidClick(_ userId: String)
}
/*
cell 每一种cell 对应左右布局 两种不同的reuseIdentifier
TextContentView
ImageContentView
**/
class CWMessageCell: UICollectionViewCell {
weak var delegate: CWMessageCellDelegate?
var message: CWMessageModel?
// MARK: 属性
/// 用户名称
var usernameLabel:UILabel = {
let usernameLabel = UILabel()
usernameLabel.backgroundColor = UIColor.clear
usernameLabel.font = UIFont.systemFont(ofSize: 12)
usernameLabel.text = "nickname"
return usernameLabel
}()
/// 头像
lazy var avatarImageView:UIImageView = {
let avatarImageView = UIImageView()
avatarImageView.contentMode = .scaleAspectFit
avatarImageView.backgroundColor = UIColor.gray
avatarImageView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(avatarViewDidTapDown(_:)))
avatarImageView.addGestureRecognizer(tap)
return avatarImageView
}()
/// 消息的内容部分
lazy var messageContentView: MessageContentView = {
let messageContentView: MessageContentView
let messageType = CWMessageType(identifier: self.reuseIdentifier!)
switch messageType {
case .text:
messageContentView = TextMessageContentView()
case .image:
messageContentView = ImageMessageContentView()
case .voice:
messageContentView = VoiceMessageContentView()
// case .video:
// <#code#>
// case .file:
// <#code#>
case .location:
messageContentView = LocationMessageContentView()
case .emoticon:
messageContentView = EmoticonMessageContentView()
case .notification:
messageContentView = NotificationMessageContentView()
default:
messageContentView = MessageContentView()
}
messageContentView.addGestureRecognizer(self.longPressGestureRecognizer)
messageContentView.addGestureRecognizer(self.doubletapGesture)
messageContentView.addGestureRecognizer(self.tapGestureRecognizer)
self.tapGestureRecognizer.require(toFail: self.doubletapGesture)
self.tapGestureRecognizer.require(toFail: self.longPressGestureRecognizer)
self.contentView.addSubview(messageContentView)
return messageContentView
}()
/// 指示
var activityView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
/// 发送失败按钮
lazy var errorButton:UIButton = {
let errorButton = UIButton(type: .custom)
errorButton.setImage(CWAsset.MessageSendFail.image, for: UIControlState())
errorButton.sizeToFit()
errorButton.addTarget(self, action: #selector(errorButtonClick(_:)), for: .touchUpInside)
errorButton.isHidden = true
return errorButton
}()
///手势操作
fileprivate(set) lazy var tapGestureRecognizer: UITapGestureRecognizer = {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(bubbleTapped(_:)))
return tapGestureRecognizer
}()
fileprivate(set) lazy var doubletapGesture: UITapGestureRecognizer = {
let doubletapGesture = UITapGestureRecognizer(target: self, action: #selector(bubbleDoubleTapped(_:)))
doubletapGesture.numberOfTapsRequired = 2
return doubletapGesture
}()
fileprivate(set) lazy var longPressGestureRecognizer: UILongPressGestureRecognizer = {
let longpressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(bubbleLongPressed(_:)))
longpressGestureRecognizer.delegate = self
return longpressGestureRecognizer
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.addSubview(avatarImageView)
self.contentView.addSubview(usernameLabel)
self.contentView.addSubview(activityView)
self.contentView.addSubview(errorButton)
}
// 设置
func refresh(message: CWMessageModel) {
self.message = message
updateState()
// 赋值
let userId = message.targetId
let avatarURL = "\(kImageBaseURLString)\(userId).jpg"
avatarImageView.kf.setImage(with: URL(string: avatarURL), placeholder: defaultHeadeImage)
self.messageContentView.refresh(message: message)
}
func updateState() {
guard let message = message else {
return
}
// 如果是收到消息 则隐藏
if message.isSend == false {
activityView.stopAnimating()
errorButton.isHidden = true
return
}
// 发送中展示
if message.sendStatus == .successed {
activityView.stopAnimating()
errorButton.isHidden = true
}
// 如果失败就显示重发按钮
else if message.sendStatus == .failed {
activityView.stopAnimating()
errorButton.isHidden = false
} else {
activityView.startAnimating()
errorButton.isHidden = true
}
}
func updateProgress() {
self.messageContentView.updateProgress()
}
// MARK: cell中的事件处理
///头像点击
@objc func avatarViewDidTapDown(_ tap: UITapGestureRecognizer) {
guard let delegate = self.delegate, let message = message, tap.state == .ended else {
return
}
let targetId = message.isSend ? message.targetId : message.senderId
delegate.messageCellUserAvatarDidClick(targetId)
}
// MARK: 手势事件
@objc func bubbleTapped(_ tapGestureRecognizer: UITapGestureRecognizer) {
guard tapGestureRecognizer.state == .ended else {
return
}
self.delegate?.messageCellDidTap(self)
}
@objc func bubbleDoubleTapped(_ tapGestureRecognizer: UITapGestureRecognizer) {
}
@objc func bubbleLongPressed(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
if longPressGestureRecognizer.state == .began {
}
}
@objc func errorButtonClick(_ button: UIButton) {
self.delegate?.messageCellResendButtonClick(self)
}
override var isSelected: Bool {
didSet {
}
}
// MARK: UIMenuController
@objc func copyContentMessage() {
}
override func becomeFirstResponder() -> Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - UIGestureRecognizerDelegate
extension CWMessageCell: UIGestureRecognizerDelegate {
}
// MARK: - 布局
extension CWMessageCell {
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
super.apply(layoutAttributes)
guard let layoutAttributes = layoutAttributes as? CWMessageLayoutAttributes else {
return
}
avatarImageView.frame = layoutAttributes.avaterFrame
usernameLabel.frame = layoutAttributes.usernameFrame
messageContentView.frame = layoutAttributes.messageContainerFrame
//
activityView.frame = layoutAttributes.activityFrame
errorButton.frame = layoutAttributes.errorFrame
}
}
| mit |
mightydeveloper/swift | validation-test/compiler_crashers/26954-swift-functiontype-get.swift | 9 | 257 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
<{}
func a{
{enum A{class B<T:T.e
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.