hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
40b372d2230aed9f784021dc63b2cec284825796
3,612
py
Python
tests/test_cosmo_rates.py
Raimer/flarestack
60659d368db93ead7b53addf3af9f1e8ac3a52bc
[ "MIT" ]
1
2021-04-19T06:26:03.000Z
2021-04-19T06:26:03.000Z
tests/test_cosmo_rates.py
Raimer/flarestack
60659d368db93ead7b53addf3af9f1e8ac3a52bc
[ "MIT" ]
null
null
null
tests/test_cosmo_rates.py
Raimer/flarestack
60659d368db93ead7b53addf3af9f1e8ac3a52bc
[ "MIT" ]
null
null
null
import logging import unittest import numpy as np from astropy import units as u from flarestack.cosmo import get_rate from flarestack.cosmo.rates import source_maps from flarestack.cosmo.rates.tde_rates import tde_evolutions, local_tde_rates from flarestack.cosmo.rates.sfr_rates import sfr_evolutions, local_sfr_rates from flarestack.cosmo.rates.ccsn_rates import kcc_rates, sn_subclass_rates from flarestack.cosmo.rates.grb_rates import grb_evolutions, local_grb_rates from flarestack.cosmo.rates.fbot_rates import local_fbot_rates from flarestack.cosmo.rates.frb_rates import local_frb_rates zrange = np.linspace(0.0, 8.0, 5) class TestCosmoRates(unittest.TestCase): def setUp(self): pass def test_get_rates(self): logging.info("Testing get_rates util functions.") for vals in source_maps.values(): for val in vals: f = get_rate(val) f(1.0) def test_tde_rates(self): for evolution in tde_evolutions.keys(): for rate in local_tde_rates.keys(): f = get_rate("tde", evolution_name=evolution, rate_name=rate) f(zrange) f = get_rate("tde", evolution_name="biehl_18_jetted", m=-2) true = 2.e-07 / (u.Mpc**3 * u.yr) self.assertAlmostEqual(f(1.0)/true, 1.0, delta=0.05) def test_sfr_rates(self): for evolution in sfr_evolutions.keys(): for rate in local_sfr_rates.keys(): f = get_rate("sfr", evolution_name=evolution, rate_name=rate) f(zrange) f = get_rate("sfr") true = 0.08687592762508031 * u.solMass / (u.Mpc**3 * u.yr) self.assertAlmostEqual(f(1.0)/true, 1.0, delta=0.05) def test_ccsn_rates(self): for kcc_name in kcc_rates.keys(): for (subclass_fractions_name, (sn_type, _)) in sn_subclass_rates.items(): for sn_subclass in sn_type.keys(): f = get_rate( "ccsn", kcc_name=kcc_name, sn_subclass=sn_subclass, subclass_fractions_name=subclass_fractions_name ) f(zrange) f = get_rate("ccsn", sn_subclass="Ibc", fraction=0.5) true = 7.236764771169189e-05 / (u.Mpc**3 * u.yr) self.assertAlmostEqual(f(1.0)/true, 1.0, delta=0.05) def test_grn_rates(self): for evolution in grb_evolutions.keys(): for rate in local_grb_rates.keys(): f = get_rate("grb", evolution_name=evolution, rate_name=rate) f(zrange) f = get_rate("grb", evolution_name="lien_14") true = 1.7635240284867526e-09 / (u.Mpc**3 * u.yr) self.assertAlmostEqual(f(1.0)/true, 1.0, delta=0.05) def test_fbot_rates(self): for evolution in sfr_evolutions.keys(): for rate in local_fbot_rates.keys(): f = get_rate("fbot", evolution_name=evolution, rate_name=rate) f(zrange) f = get_rate("fbot") true = 4.054209955837081e-06/ (u.Mpc**3 * u.yr) self.assertAlmostEqual(f(1.0)/true, 1.0, delta=0.05) def test_frb_rates(self): for evolution in sfr_evolutions.keys(): for rate in local_frb_rates.keys(): f = get_rate("frb", evolution_name=evolution, rate_name=rate) f(zrange) f = get_rate("frb") true = 0.418741971152887 / (u.Mpc**3 * u.yr) self.assertAlmostEqual(f(1.0)/true, 1.0, delta=0.05) if __name__ == '__main__': unittest.main()
32.836364
85
0.612126
a52ae84554a8810aaddd160a90be63482d6984e4
2,637
kt
Kotlin
mbcarkit/src/test/java/com/daimler/mbcarkit/network/model/ApiRifabilityTest.kt
mercedes-benz/MBSDK-Mobile-Android
3721af583408721b9cd5cf89dd7b99256e9d7dda
[ "MIT" ]
15
2019-09-09T15:48:51.000Z
2021-12-25T16:51:50.000Z
mbcarkit/src/test/java/com/daimler/mbcarkit/network/model/ApiRifabilityTest.kt
mercedes-benz/MBSDK-Mobile-Android
3721af583408721b9cd5cf89dd7b99256e9d7dda
[ "MIT" ]
2
2020-03-25T13:28:05.000Z
2021-01-01T19:04:57.000Z
mbcarkit/src/test/java/com/daimler/mbcarkit/network/model/ApiRifabilityTest.kt
Daimler/MBSDK-Mobile-Android
3721af583408721b9cd5cf89dd7b99256e9d7dda
[ "MIT" ]
7
2019-09-17T08:17:00.000Z
2021-07-20T14:30:38.000Z
package com.daimler.mbcarkit.network.model import org.assertj.core.api.SoftAssertions import org.assertj.core.api.junit.jupiter.SoftAssertionsExtension import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.EnumSource @ExtendWith(SoftAssertionsExtension::class) class ApiRifabilityTest { @Test fun `map ApiRifability to Rifability with canReceiveVac enabled`(softly: SoftAssertions) { val apiRifability = ApiRifability( null, null, null, true, ApiVehicleConnectivity.ADAPTER ) val rifability = apiRifability.toRifability() softly.assertThat(rifability.isRifable).isEqualTo(true) } @Test fun `map ApiRifability to Rifability with rifSupportedForVac enabled`(softly: SoftAssertions) { val apiRifability = ApiRifability( null, true, null, null, ApiVehicleConnectivity.ADAPTER ) val rifability = apiRifability.toRifability() softly.assertThat(rifability.isRifable).isEqualTo(true) } @Test fun `map ApiRifability to Rifability with rifable enabled`(softly: SoftAssertions) { val apiRifability = ApiRifability( true, null, null, null, ApiVehicleConnectivity.ADAPTER ) val rifability = apiRifability.toRifability() softly.assertThat(rifability.isRifable).isEqualTo(true) } @Test fun `map ApiRifability to Rifability with nothing enabled`(softly: SoftAssertions) { val apiRifability = ApiRifability( null, null, null, null, ApiVehicleConnectivity.ADAPTER ) val rifability = apiRifability.toRifability() softly.assertThat(rifability.isRifable).isEqualTo(false) } @ParameterizedTest @EnumSource(ApiVehicleConnectivity::class) internal fun `map ApiRifability to Rifability should set isConnectVehicle correctly`(vehicleConnectivity: ApiVehicleConnectivity, softly: SoftAssertions) { val expectedIsConnectVehicle = vehicleConnectivity == ApiVehicleConnectivity.BUILT_IN val apiRifability = ApiRifability( null, null, null, null, vehicleConnectivity ) val rifability = apiRifability.toRifability() softly.assertThat(rifability.isConnectVehicle).isEqualTo(expectedIsConnectVehicle) } }
30.662791
159
0.660978
64d62d5869a46b85c284d6b017c0a725e75667a9
975
java
Java
src/main/java/com/lb_stuff/bukkit/command/PluginInfoCommand.java
LB--/NameHist
1cdb9006cd35b991de7b57f05a4ad834f2090d99
[ "Unlicense" ]
1
2015-02-19T04:02:28.000Z
2015-02-19T04:02:28.000Z
src/main/java/com/lb_stuff/bukkit/command/PluginInfoCommand.java
LB--/NameHist
1cdb9006cd35b991de7b57f05a4ad834f2090d99
[ "Unlicense" ]
4
2015-02-19T04:02:26.000Z
2015-08-20T23:19:59.000Z
src/main/java/com/lb_stuff/bukkit/command/PluginInfoCommand.java
LB--/KataParty
4043f981fb5e819caabbf0d8359f04472543cc71
[ "Unlicense" ]
null
null
null
package com.lb_stuff.bukkit.command; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import static org.bukkit.ChatColor.*; public class PluginInfoCommand implements CommandExecutor { private final Plugin inst; public PluginInfoCommand(Plugin plugin) { inst = plugin; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(args.length == 0) { PluginDescriptionFile d = inst.getDescription(); sender.sendMessage(""+BOLD+d.getName()+RESET+" v"+d.getVersion()+" by "+d.getAuthors().get(0)); sender.sendMessage("For help, use "+"/help "+d.getName()+" [page-#]"); String website = d.getWebsite(); if(website != null) { sender.sendMessage(""+AQUA+UNDERLINE+website); sender.sendMessage(""); } return true; } return false; } }
26.351351
98
0.72
34a23162f509ef4f1b56dcf6658fae927890befc
143
kt
Kotlin
robotframework-kolib-core/src/main/kotlin/de/qualersoft/robotframework/library/annotation/KeywordTag.kt
qualersoft/robotframework-kolib
4b37d24658295207085232b53bb415368b39542f
[ "Apache-2.0" ]
null
null
null
robotframework-kolib-core/src/main/kotlin/de/qualersoft/robotframework/library/annotation/KeywordTag.kt
qualersoft/robotframework-kolib
4b37d24658295207085232b53bb415368b39542f
[ "Apache-2.0" ]
16
2021-06-20T15:51:52.000Z
2022-02-14T20:04:28.000Z
robotframework-kolib-core/src/main/kotlin/de/qualersoft/robotframework/library/annotation/KeywordTag.kt
qualersoft/robotframework-kolib
4b37d24658295207085232b53bb415368b39542f
[ "Apache-2.0" ]
null
null
null
package de.qualersoft.robotframework.library.annotation @Retention(AnnotationRetention.RUNTIME) annotation class KeywordTag(val value:String)
28.6
55
0.867133
6bba88f64db346f604999d9d57fc6896dfbac880
1,049
swift
Swift
NineNews/NineNews/Models/News.swift
pakidanish/ninenews
1cd0d1c2c724bd4a88c21fbe9ab41d96a5dafec2
[ "MIT" ]
null
null
null
NineNews/NineNews/Models/News.swift
pakidanish/ninenews
1cd0d1c2c724bd4a88c21fbe9ab41d96a5dafec2
[ "MIT" ]
null
null
null
NineNews/NineNews/Models/News.swift
pakidanish/ninenews
1cd0d1c2c724bd4a88c21fbe9ab41d96a5dafec2
[ "MIT" ]
null
null
null
// // News.swift // NineNews // // Created by Danish Aziz on 19/10/19. // Copyright © 2019 Danish Aziz. All rights reserved. // import UIKit struct News: Codable { let id: Int? let categories: [Category]? let authors: [Author]? let url: String? let lastModified: Int? let onTime: Int? let sponsored: Bool? let displayName: String? let article: [Article] let relatedAssets: [RelatedAsset] let relatedImages: [AssetRelatedImage] let assetType: String? let timeStamp: Int enum CodingKeys: String, CodingKey { case id = "id" case categories = "categories" case authors = "authors" case url = "url" case lastModified = "lastModified" case onTime = "onTime" case sponsored = "sponsored" case displayName = "displayName" case article = "assets" case relatedAssets = "relatedAssets" case relatedImages = "relatedImages" case assetType = "assetType" case timeStamp = "timeStamp" } }
24.97619
54
0.617731
5f5e5288aa16303de8773ee3c17c139171168dad
942
swift
Swift
Example/RxService/Network/ImageSearch/ImageSearchCell.swift
DragonCherry/RxService
15f4e87046447e4232793bef972df263b9b09b06
[ "MIT" ]
3
2017-07-05T09:23:07.000Z
2021-09-20T05:46:28.000Z
Example/RxService/Network/ImageSearch/ImageSearchCell.swift
DragonCherry/RxService
15f4e87046447e4232793bef972df263b9b09b06
[ "MIT" ]
null
null
null
Example/RxService/Network/ImageSearch/ImageSearchCell.swift
DragonCherry/RxService
15f4e87046447e4232793bef972df263b9b09b06
[ "MIT" ]
null
null
null
// // ImageSearchCell.swift // RxService_Example // // Created by DragonCherry on 7/10/17. // Copyright © 2017 CocoaPods. All rights reserved. // import RxSwift import RxCocoa import RxSwiftExt import RxService class ImageSearchCell: UITableViewCell { @IBOutlet weak var thumbnailView: UIImageView! @IBOutlet weak var titleView: UILabel! var disposeBag: DisposeBag? var viewModel: ImageSearchViewModel? { didSet { guard let viewModel = self.viewModel else { return } let disposeBag = DisposeBag() viewModel.title .map(Optional.init) .drive(titleView.rx.text) .disposed(by: disposeBag) viewModel.image .drive(thumbnailView.rx.image) .disposed(by: disposeBag) self.disposeBag = disposeBag } } }
23.55
64
0.575372
2a7d0f51ae7b79d6cd2fb97d62ae3641923e01ca
1,080
java
Java
src/test/java/com/mn/modules/api/BaseTest.java
qinfuji/mn
d0041edb976bc20645d6c093e4cc410d75ca3da2
[ "Apache-2.0" ]
null
null
null
src/test/java/com/mn/modules/api/BaseTest.java
qinfuji/mn
d0041edb976bc20645d6c093e4cc410d75ca3da2
[ "Apache-2.0" ]
7
2020-09-06T02:02:08.000Z
2022-02-26T14:08:14.000Z
src/test/java/com/mn/modules/api/BaseTest.java
qinfuji/mn
d0041edb976bc20645d6c093e4cc410d75ca3da2
[ "Apache-2.0" ]
null
null
null
package com.mn.modules.api; import com.github.jsonzou.jmockdata.JMockData; import com.github.jsonzou.jmockdata.MockConfig; import com.mn.MNBIApplication; import com.mn.modules.api.entity.ChancePoint; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; @ActiveProfiles({"test"}) @ExtendWith(SpringExtension.class) @RunWith(SpringRunner.class) @SpringBootTest(classes = MNBIApplication.class) @Transactional public class BaseTest { protected final MockConfig CHANCE_MOCK_CONFIG = new MockConfig() .globalConfig().excludes("id","estimateResults"); public ChancePoint getTempChancePoint(){ ChancePoint cp = new ChancePoint(); return JMockData.mock(ChancePoint.class, CHANCE_MOCK_CONFIG); } }
33.75
70
0.8
70adb7d08b2256f79ecb7f417f744f7f521f7a44
1,426
h
C
Plugins/SPlanner/Source/SPlanner/Public/SPlanner/AI/LOD/SP_AILODComponent.h
mrouffet/SPlanner
a2a72b979e33d276a119fffc6728ad5524891171
[ "MIT" ]
2
2020-03-25T12:13:23.000Z
2021-06-15T15:00:42.000Z
Plugins/SPlanner/Source/SPlanner/Public/SPlanner/AI/LOD/SP_AILODComponent.h
mrouffet/SPlanner
a2a72b979e33d276a119fffc6728ad5524891171
[ "MIT" ]
null
null
null
Plugins/SPlanner/Source/SPlanner/Public/SPlanner/AI/LOD/SP_AILODComponent.h
mrouffet/SPlanner
a2a72b979e33d276a119fffc6728ad5524891171
[ "MIT" ]
null
null
null
// Copyright 2020 Maxime ROUFFET. All Rights Reserved. #pragma once #include <Curves/CurveFloat.h> #include <SPlanner/Base/LOD/SP_LODComponent.h> #include "SP_AILODComponent.generated.h" UCLASS(BlueprintType, Blueprintable, DisplayName = "SP_AILODComponent", ClassGroup = "SPlanner|LOD|AI", meta = (BlueprintSpawnableComponent)) class SPLANNER_API USP_AILODComponent : public USP_LODComponent { GENERATED_BODY() protected: /** * The maximum planner depth while building a plan. * Plan generation complexity: O(!n), n = MaxPlannerDepth. */ UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "SPlanner") FRuntimeFloatCurve MaxPlannerDepthCurve; /** * Minimum time to wait before constructing a new plan. * Use <= 0 to compute instantly. */ UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "SPlanner") FRuntimeFloatCurve TimeBeforeConstructPlanCurve; public: USP_AILODComponent(const FObjectInitializer& ObjectInitializer); /** * Getter of MaxPlannerDepth using MaxPlannerDepthCurve and LODLevel. * Eval LODLevel using GetLevel() if LODLevel < 0.0f. */ UFUNCTION(BlueprintPure, Category = "SPlanner|LOD|AI") int GetMaxPlannerDepth() const; /** * Getter of TimeBeforeConstructPlan using TimeBeforeConstructPlanCurve and LODLevel. * Eval LODLevel using GetLevel() if LODLevel < 0.0f. */ UFUNCTION(BlueprintPure, Category = "SPlanner|LOD|AI") float GetTimeBeforeConstructPlan() const; };
31
141
0.774194
5f3ad771738aed63ee4ff5dff933ac6dd00eb51f
3,000
ts
TypeScript
src/lib/custom-resources/cdk-security-hub-send-invites/runtime/src/index.ts
Amrib24/aws-secure-environment-accelerator
48e4aceed58748b55fa11e62e62a9326131ffe6b
[ "Apache-2.0" ]
454
2020-10-28T16:54:11.000Z
2022-03-30T14:01:50.000Z
src/lib/custom-resources/cdk-security-hub-send-invites/runtime/src/index.ts
Amrib24/aws-secure-environment-accelerator
48e4aceed58748b55fa11e62e62a9326131ffe6b
[ "Apache-2.0" ]
227
2020-10-29T19:20:02.000Z
2022-03-30T16:01:01.000Z
src/lib/custom-resources/cdk-security-hub-send-invites/runtime/src/index.ts
Amrib24/aws-secure-environment-accelerator
48e4aceed58748b55fa11e62e62a9326131ffe6b
[ "Apache-2.0" ]
169
2020-10-28T16:54:15.000Z
2022-03-31T22:26:12.000Z
/** * Copyright 2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * and limitations under the License. */ import * as AWS from 'aws-sdk'; AWS.config.logger = console; import { CloudFormationCustomResourceEvent } from 'aws-lambda'; import { errorHandler } from '@aws-accelerator/custom-resource-runtime-cfn-response'; import { throttlingBackOff } from '@aws-accelerator/custom-resource-cfn-utils'; const hub = new AWS.SecurityHub(); export const handler = errorHandler(onEvent); async function onEvent(event: CloudFormationCustomResourceEvent) { console.log(`Sending Security Hub Invites to Sub Accounts...`); console.log(JSON.stringify(event, null, 2)); // eslint-disable-next-line default-case switch (event.RequestType) { case 'Create': return onCreate(event); case 'Update': return onUpdate(event); case 'Delete': return onDelete(event); } } async function onCreate(event: CloudFormationCustomResourceEvent) { const memberAccounts = event.ResourceProperties.memberAccounts; // Creating Members console.log(`Creating Members for "${memberAccounts}"`); const accountIds: string[] = []; // Security Hub will only process 50. const pageSize = 50; for (let i = 0; i < memberAccounts.length; i += pageSize) { const currentPage = memberAccounts.slice().splice(i, pageSize); const pagedMemberParams = { AccountDetails: currentPage, }; console.log(`Creating Members (paged) for "${pagedMemberParams}"`); const createResponse = await throttlingBackOff(() => hub.createMembers(pagedMemberParams).promise()); console.log(`Create Sub Accounts Response "${JSON.stringify(createResponse)}""`); for (const account of currentPage) { accountIds.push(account.AccountId); } } console.log(`Inviting Members for "${accountIds}"`); // Security Hub will only process 50. for (let i = 0; i < accountIds.length; i += pageSize) { const currentPage = accountIds.slice().splice(i, pageSize); const pagedParams = { AccountIds: currentPage, }; console.log(`Inviting Members (paged) for "${pagedParams}"`); const inviteResponse = await throttlingBackOff(() => hub.inviteMembers(pagedParams).promise()); console.log(`Invite Sub Accounts Response "${JSON.stringify(inviteResponse)}"`); } } async function onUpdate(event: CloudFormationCustomResourceEvent) { return onCreate(event); } async function onDelete(_: CloudFormationCustomResourceEvent) { console.log(`Nothing to do for delete...`); }
36.585366
117
0.715
964144d1cfe58b22900a36cecb2ce5d6774fab74
290
php
PHP
eds-www/aula04/tipo.php
IvanIndaia/php
bcd66a1f3b132968bd17d53df9a09aadd1d1f75a
[ "MIT" ]
null
null
null
eds-www/aula04/tipo.php
IvanIndaia/php
bcd66a1f3b132968bd17d53df9a09aadd1d1f75a
[ "MIT" ]
null
null
null
eds-www/aula04/tipo.php
IvanIndaia/php
bcd66a1f3b132968bd17d53df9a09aadd1d1f75a
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang=""pt-br"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="_css/estilo.css" <title></title> </head> <div> <?php $n = 4.5; $no = "Ivan Alex"; $n = 31; echo "$no tem $n anos" ?> </div> </body> </html>
16.111111
49
0.472414
bd9223f358deb1612719c0d7bc624a4a659556bc
4,716
sql
SQL
gestao_produtos/loja.sql
univer30/gestao-produto
24bc7bf61a118dd6a1af4eced43363b3d1e6ef39
[ "MIT" ]
null
null
null
gestao_produtos/loja.sql
univer30/gestao-produto
24bc7bf61a118dd6a1af4eced43363b3d1e6ef39
[ "MIT" ]
null
null
null
gestao_produtos/loja.sql
univer30/gestao-produto
24bc7bf61a118dd6a1af4eced43363b3d1e6ef39
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 5.1.0 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Tempo de geração: 23-Jun-2021 às 18:19 -- Versão do servidor: 10.4.19-MariaDB -- versão do PHP: 7.3.28 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Banco de dados: `loja` -- -- -------------------------------------------------------- -- -- Estrutura da tabela `pedidos` -- CREATE TABLE `pedidos` ( `id` int(11) NOT NULL, `nome` varchar(100) DEFAULT NULL, `endereco` varchar(100) DEFAULT NULL, `updated_at` varchar(30) DEFAULT NULL, `created_at` varchar(30) DEFAULT NULL, `num` int(11) DEFAULT NULL, `bairro` varchar(30) DEFAULT NULL, `cidade` varchar(30) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Extraindo dados da tabela `pedidos` -- INSERT INTO `pedidos` (`id`, `nome`, `endereco`, `updated_at`, `created_at`, `num`, `bairro`, `cidade`) VALUES (16, 'Rodrigo de souza', 'AV: esmeralda', '2021-06-22 03:24:07', '2021-06-22 03:24:07', 1188, 'Centro', 'Vera Cruz'); -- -------------------------------------------------------- -- -- Estrutura da tabela `produto` -- CREATE TABLE `produto` ( `id` int(11) NOT NULL, `nome` varchar(100) NOT NULL, `valor` varchar(30) NOT NULL, `qtd_estoque` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Estrutura da tabela `produtos` -- CREATE TABLE `produtos` ( `id` int(11) NOT NULL, `nome` varchar(100) DEFAULT NULL, `valor` decimal(10,2) DEFAULT NULL, `qtde` int(11) DEFAULT NULL, `updated_at` varchar(30) DEFAULT NULL, `created_at` varchar(30) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Extraindo dados da tabela `produtos` -- INSERT INTO `produtos` (`id`, `nome`, `valor`, `qtde`, `updated_at`, `created_at`) VALUES (25, 'Liquidificador', '100.00', 100, '2021-06-22 12:48:55', '2021-06-20 17:31:17'), (33, 'Microondas Philco', '599.50', 3, '2021-06-22 12:46:38', '2021-06-22 12:46:38'), (30, 'Celular Galaxy J7', '30.00', 30, '2021-06-20 19:39:13', '2021-06-20 19:38:53'), (31, 'TV LG', '1900.00', 8, '2021-06-21 23:03:38', '2021-06-21 23:03:38'), (34, 'Computador apple', '2150.17', 1, '2021-06-22 12:47:49', '2021-06-22 12:47:49'), (35, 'Batedeira Arno Vermelha', '450.50', 6, '2021-06-23 14:10:43', '2021-06-23 14:10:43'), (36, 'playstantion 5', '4500.75', 13, '2021-06-23 15:04:45', '2021-06-23 15:04:45'); -- -------------------------------------------------------- -- -- Estrutura da tabela `produto_pedidos` -- CREATE TABLE `produto_pedidos` ( `id` int(11) NOT NULL, `produto` varchar(30) DEFAULT NULL, `qtde` int(11) DEFAULT NULL, `pedido` int(11) NOT NULL, `updated_at` varchar(30) NOT NULL, `created_at` varchar(30) NOT NULL, `valor` decimal(10,2) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Extraindo dados da tabela `produto_pedidos` -- INSERT INTO `produto_pedidos` (`id`, `produto`, `qtde`, `pedido`, `updated_at`, `created_at`, `valor`) VALUES (23, 'TV LG', 1, 16, '2021-06-23 15:59:12', '2021-06-23 15:59:12', '1900.00'), (24, 'playstantion 5', 1, 16, '2021-06-23 16:08:36', '2021-06-23 16:08:36', '4500.75'), (20, 'Microondas Philco', 1, 15, '2021-06-23 15:51:42', '2021-06-23 15:51:42', '599.50'); -- -- Índices para tabelas despejadas -- -- -- Índices para tabela `pedidos` -- ALTER TABLE `pedidos` ADD PRIMARY KEY (`id`); -- -- Índices para tabela `produto` -- ALTER TABLE `produto` ADD PRIMARY KEY (`id`); -- -- Índices para tabela `produtos` -- ALTER TABLE `produtos` ADD PRIMARY KEY (`id`); -- -- Índices para tabela `produto_pedidos` -- ALTER TABLE `produto_pedidos` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT de tabelas despejadas -- -- -- AUTO_INCREMENT de tabela `pedidos` -- ALTER TABLE `pedidos` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19; -- -- AUTO_INCREMENT de tabela `produto` -- ALTER TABLE `produto` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de tabela `produtos` -- ALTER TABLE `produtos` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=37; -- -- AUTO_INCREMENT de tabela `produto_pedidos` -- ALTER TABLE `produto_pedidos` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
27.103448
117
0.639525
0a46196499749d403ed95c7f2468c51f96c78eb7
126
asm
Assembly
tests/rule_deferred.asm
clubby789/customasm
c85b2422d933e6266dd817e0ec3cbb9e30b181fa
[ "Apache-2.0" ]
1
2021-01-02T13:38:01.000Z
2021-01-02T13:38:01.000Z
tests/rule_deferred.asm
clubby789/customasm
c85b2422d933e6266dd817e0ec3cbb9e30b181fa
[ "Apache-2.0" ]
null
null
null
tests/rule_deferred.asm
clubby789/customasm
c85b2422d933e6266dd817e0ec3cbb9e30b181fa
[ "Apache-2.0" ]
null
null
null
; ::: include #ruledef test { ld {x} => 0x55 @ x`8 } ; ::: ld label ; = 0x5502 label: ; ::: ld var ; = 0x5511 var = 0x11
9.692308
24
0.5
cb5789a0c3dc7787195c77457e68c75a8bcbd11e
114
html
HTML
web/feedmetatitle.html
seriousbusinessbe/java-brusselnieuws-rss
a18183e1122fce6f5389446b096085ff081b98c3
[ "MIT" ]
null
null
null
web/feedmetatitle.html
seriousbusinessbe/java-brusselnieuws-rss
a18183e1122fce6f5389446b096085ff081b98c3
[ "MIT" ]
null
null
null
web/feedmetatitle.html
seriousbusinessbe/java-brusselnieuws-rss
a18183e1122fce6f5389446b096085ff081b98c3
[ "MIT" ]
null
null
null
<!--<h3>--> {{feedmeta.name | uppercase}} <em class="pull-right">{{feedmeta.price | currency}}</em> <!--</h3>-->
28.5
58
0.561404
e50787b34ed6423c6cda906971de3dd447ecbc58
43
sql
SQL
api/db/migrations/20210921094124_add-organizaton-table.down.sql
wearedevx/keystone
9568c07442cfc242274ec20f8784cd5fd24c7146
[ "MIT" ]
22
2020-01-15T14:22:15.000Z
2022-03-31T21:49:29.000Z
api/db/migrations/20210921094124_add-organizaton-table.down.sql
wearedevx/keystone
9568c07442cfc242274ec20f8784cd5fd24c7146
[ "MIT" ]
119
2020-01-29T15:04:31.000Z
2022-03-22T15:22:21.000Z
api/db/migrations/20210921094124_add-organizaton-table.down.sql
wearedevx/keystone
9568c07442cfc242274ec20f8784cd5fd24c7146
[ "MIT" ]
5
2020-01-04T00:56:14.000Z
2020-02-14T21:53:44.000Z
DROP TABLE IF EXISTS public.organizations;
21.5
42
0.837209
5bd12b539cdcb98c79e6858730abcfb01bbd702b
262
swift
Swift
MovieSwift/MovieSwift/flux/models/Keyword.swift
dreampiggy/MovieSwiftUI
21fd16b564bcab2afc0a9986a1f38d1990c8609b
[ "Apache-2.0" ]
6,327
2019-06-07T17:56:10.000Z
2022-03-28T09:28:11.000Z
MovieSwift/MovieSwift/flux/models/Keyword.swift
dreampiggy/MovieSwiftUI
21fd16b564bcab2afc0a9986a1f38d1990c8609b
[ "Apache-2.0" ]
57
2019-06-21T16:48:03.000Z
2022-01-05T17:12:54.000Z
MovieSwift/MovieSwift/flux/models/Keyword.swift
dreampiggy/MovieSwiftUI
21fd16b564bcab2afc0a9986a1f38d1990c8609b
[ "Apache-2.0" ]
650
2019-06-13T04:37:46.000Z
2022-03-31T06:16:19.000Z
// // Keyword.swift // MovieSwift // // Created by Thomas Ricouard on 16/06/2019. // Copyright © 2019 Thomas Ricouard. All rights reserved. // import Foundation import SwiftUI struct Keyword: Codable, Identifiable { let id: Int let name: String }
15.411765
58
0.69084
0c995cb75529ea456e281ad4b7103361577ad5f9
2,693
sql
SQL
src/db/dbscript/TienNghiBenChoThue.sql
longshaww/RentApartment
74f7de0da4a3e0a4c2c85d64d7788ee7d6df6b86
[ "MIT" ]
null
null
null
src/db/dbscript/TienNghiBenChoThue.sql
longshaww/RentApartment
74f7de0da4a3e0a4c2c85d64d7788ee7d6df6b86
[ "MIT" ]
12
2022-03-30T00:52:10.000Z
2022-03-30T01:58:47.000Z
src/db/dbscript/TienNghiBenChoThue.sql
longshaww/RentApartment
74f7de0da4a3e0a4c2c85d64d7788ee7d6df6b86
[ "MIT" ]
null
null
null
INSERT INTO apartment.dbo.TienNghiBenChoThue (MaTienNghiBCT,TenTienNghiBCT) VALUES (N'TNBCT1',N'Nhân viên xách hành lý'), (N'TNBCT10',N'Bảo vệ 24 giờ'), (N'TNBCT11',N'Dịch vụ trả phòng muộn'), (N'TNBCT12',N'Dịch vụ chăm sóc y tế'), (N'TNBCT13',N'Điện thoại di động'), (N'TNBCT14',N'Nhật báo tại sảnh'), (N'TNBCT15',N'Dịch vụ hỗ trợ đặt Tour'), (N'TNBCT16',N'Bãi đậu xe'), (N'TNBCT17',N'Nhận phòng sớm'), (N'TNBCT18',N'Thang máy'); INSERT INTO apartment.dbo.TienNghiBenChoThue (MaTienNghiBCT,TenTienNghiBCT) VALUES (N'TNBCT19',N'Trả phòng muộn'), (N'TNBCT2',N'Thức uống chào mừng miễn phí'), (N'TNBCT20',N'Nhà hàng'), (N'TNBCT21',N'Nhà hàng phục vụ bữa tối'), (N'TNBCT22',N'Nhà hàng phục vụ bữa trưa'), (N'TNBCT23',N'Dịch vụ dọn phòng'), (N'TNBCT24',N'Két an toàn'), (N'TNBCT25',N'WiFi tại khu vực chung'), (N'TNBCT26',N'Truyền hình cáp'), (N'TNBCT27',N'Bàn làm việc'); INSERT INTO apartment.dbo.TienNghiBenChoThue (MaTienNghiBCT,TenTienNghiBCT) VALUES (N'TNBCT28',N'Máy sấy tóc'), (N'TNBCT29',N'Két an toàn trong phòng'), (N'TNBCT3',N'Dịch vụ concierge/hỗ trợ khách'), (N'TNBCT30',N'Nhà bếp mini'), (N'TNBCT31',N'Lò vi sóng'), (N'TNBCT32',N'Minibar'), (N'TNBCT33',N'Phòng tắm đứng và bồn tắm riêng'), (N'TNBCT34',N'Phòng tắm vòi sen'), (N'TNBCT35',N'TV'), (N'TNBCT36',N'Máy lạnh'); INSERT INTO apartment.dbo.TienNghiBenChoThue (MaTienNghiBCT,TenTienNghiBCT) VALUES (N'TNBCT37',N'Hội trường đa chức năng'), (N'TNBCT38',N'Phòng gia đình'), (N'TNBCT39',N'Phòng không hút thuốc'), (N'TNBCT4',N'Dịch vụ thu đổi ngoại tệ'), (N'TNBCT40',N'Sân thượng/Sân hiên'), (N'TNBCT41',N'Không khói thuốc'), (N'TNBCT42',N'Bữa sáng với thực đơn gọi món'), (N'TNBCT43',N'Bữa tối với thực đơn gọi món'), (N'TNBCT44',N'Bữa trưa với thực đơn gọi món'), (N'TNBCT45',N'Bữa sáng'); INSERT INTO apartment.dbo.TienNghiBenChoThue (MaTienNghiBCT,TenTienNghiBCT) VALUES (N'TNBCT46',N'Thuận tiện cho người khuyết tật'), (N'TNBCT47',N'Phòng được trang bị phù hợp cho người khuyết tật'), (N'TNBCT48',N'Phòng tắm phù hợp cho người khuyết tật'), (N'TNBCT49',N'Chỗ đậu xe cho người khuyết tật'), (N'TNBCT5',N'Người gác cửa'), (N'TNBCT50',N'Xông hơi ướt'), (N'TNBCT51',N'Dịch vụ spa'), (N'TNBCT52',N'Đưa đón sân bay'), (N'TNBCT53',N'Cho thuê xe hơi'), (N'TNBCT54',N'Đưa đón sân bay (thu phí)'); INSERT INTO apartment.dbo.TienNghiBenChoThue (MaTienNghiBCT,TenTienNghiBCT) VALUES (N'TNBCT55',N'Đưa đón sân bay'), (N'TNBCT56',N'Wifi (miễn phí)'), (N'TNBCT57',N'Máy photocopy'), (N'TNBCT6',N'EARLY_CHECK_IN'), (N'TNBCT7',N'Dịch vụ nhận phòng cấp tốc'), (N'TNBCT8',N'Dịch vụ trả phòng cấp tốc'), (N'TNBCT9',N'Quầy lễ tân');
42.746032
82
0.67397
4d8f27c1d517e6b0734975cb613674cf1afe7b16
200
html
HTML
src/app/game-board/game-board.component.html
jlardani93/enhanced-angular-rpg
dddf6681ce29eb1f95fd4b17ed9210517bf7c628
[ "MIT" ]
null
null
null
src/app/game-board/game-board.component.html
jlardani93/enhanced-angular-rpg
dddf6681ce29eb1f95fd4b17ed9210517bf7c628
[ "MIT" ]
null
null
null
src/app/game-board/game-board.component.html
jlardani93/enhanced-angular-rpg
dddf6681ce29eb1f95fd4b17ed9210517bf7c628
[ "MIT" ]
null
null
null
<div [ngStyle]="renderGameContainer()"> <div *ngFor="let square of childGameBoard.board; let i = index" [ngStyle]="renderSquare(i)"> <div [ngStyle]="renderSprite(i)"> </div> </div> </div>
28.571429
94
0.64
e756776ad007654e5eb338322bedf51f4c8a907b
616
js
JavaScript
test/controller/mock.js
gailagbana/e-commerce-node-template
9359611b4c9c54f85ed18214c0ec262f170eeef2
[ "ISC" ]
2
2021-03-09T07:40:47.000Z
2021-05-04T10:12:54.000Z
test/controller/mock.js
gailagbana/e-commerce-node-template
9359611b4c9c54f85ed18214c0ec262f170eeef2
[ "ISC" ]
5
2020-08-12T22:23:26.000Z
2021-05-10T11:29:19.000Z
test/controller/mock.js
gailagbana/e-commerce-node-template
9359611b4c9c54f85ed18214c0ec262f170eeef2
[ "ISC" ]
5
2020-10-30T15:14:34.000Z
2021-08-09T10:00:47.000Z
/** */ const sinon = require('sinon'); module.exports = { createRecord: sinon.spy((data) => ({ id: 1, _id: "sjdhflkjasdf32uiw7p", })), readRecords: sinon.spy(() => { return [{ id: 1, _id: "jdfhlksdhf837qyh", }, { id: 2, _id: "hf3289jdwuy90" }]; }), updateRecords: sinon.spy((conditions, data) => { if (!Object.keys(data).length) { return { ok: 1, nModified: 0 } } return { ok: 1, nModified: 1 }; }), deleteRecords: sinon.spy((conditions) => { return { ok: 1, nModified: 1 }; }), }
22.814815
52
0.478896
87647e9081b279b4400f7f3950e5a0ce310c5d85
606
swift
Swift
Framework/src/Array-safe-get.swift
jmcintyre/metaz
fe9ae078e72f3a93f8f31270beaf1b4735d0221d
[ "MIT" ]
235
2015-01-05T00:01:04.000Z
2022-03-20T20:43:15.000Z
Framework/src/Array-safe-get.swift
jmcintyre/metaz
fe9ae078e72f3a93f8f31270beaf1b4735d0221d
[ "MIT" ]
132
2015-01-02T16:23:33.000Z
2022-03-16T22:17:26.000Z
Framework/src/Array-safe-get.swift
jmcintyre/metaz
fe9ae078e72f3a93f8f31270beaf1b4735d0221d
[ "MIT" ]
38
2015-01-03T21:56:05.000Z
2021-04-15T19:40:37.000Z
// // File.swift // MetaZKit // // Created by Brian Olsen on 22/02/2020. // import Foundation extension Array { // Safely lookup an index that might be out of bounds, // returning nil if it does not exist public func safeGet(index: Int) -> Element? { if 0 <= index && index < count { return self[index] } else { return nil } } } extension Array where Element: CustomStringConvertible { public func join(sep: String = ", ") -> String { return self.reduce("", { $0 + ($0.isEmpty ? "" : sep) + String(describing:$1) }) } }
22.444444
88
0.570957
3d2657c6f04907a995f810d68e38389f6585edc5
270
rs
Rust
resources/icons/vscode/data/double_extension_to_icon_name_map.rs
lstwn/broot
12a54018af817353fc0d42b7c8c08a454449856b
[ "MIT" ]
7,101
2018-11-27T15:50:46.000Z
2022-03-31T20:06:49.000Z
resources/icons/vscode/data/double_extension_to_icon_name_map.rs
lstwn/broot
12a54018af817353fc0d42b7c8c08a454449856b
[ "MIT" ]
467
2019-01-07T19:33:40.000Z
2022-03-31T23:46:14.000Z
resources/icons/vscode/data/double_extension_to_icon_name_map.rs
lstwn/broot
12a54018af817353fc0d42b7c8c08a454449856b
[ "MIT" ]
206
2018-12-02T20:44:30.000Z
2022-03-30T22:44:22.000Z
// SEE ./README on how to edit this file [ ( "tar.gz" , "file_type_zip" ) , ( "tar.xz" , "file_type_zip" ) , ( "tar.zst" , "file_type_zip" ) , ]
38.571429
74
0.307407
20617fe85b6f19f94d4ddd5ee080cacc5ec98431
2,710
kts
Kotlin
sample-compose/build.gradle.kts
chRyNaN/chords
5a2e21c9b4789c878f0459e3d5c6fcfcbc66658d
[ "Apache-2.0" ]
20
2020-01-18T18:35:36.000Z
2021-05-02T01:43:02.000Z
sample-compose/build.gradle.kts
chRyNaN/GuitarChords
5a2e21c9b4789c878f0459e3d5c6fcfcbc66658d
[ "Apache-2.0" ]
8
2020-03-21T12:14:27.000Z
2021-12-29T23:43:17.000Z
sample-compose/build.gradle.kts
chRyNaN/chords
5a2e21c9b4789c878f0459e3d5c6fcfcbc66658d
[ "Apache-2.0" ]
4
2020-01-26T18:45:12.000Z
2020-12-28T21:21:20.000Z
import com.chrynan.chords.buildSrc.LibraryConstants import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { kotlin("multiplatform") id("com.android.application") id("org.jetbrains.compose") } group = LibraryConstants.group version = LibraryConstants.versionName kotlin { targets { android() jvm() } sourceSets { all { languageSettings { languageSettings.enableLanguageFeature("InlineClasses") languageSettings.optIn("kotlin.RequiresOptIn") } } commonMain { dependencies { implementation(project(":chords-compose")) implementation(compose.runtime) implementation(compose.ui) implementation(compose.material) implementation("com.chrynan.colors:colors-compose:0.7.0") implementation("com.chrynan.presentation:presentation-compose:0.6.0") implementation("com.chrynan.navigation:navigation-compose:0.2.2") implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0") } } } } android { compileSdk = LibraryConstants.Android.compileSdkVersion defaultConfig { applicationId = "com.chrynan.chords.sample.compose" minSdk = 25 targetSdk = LibraryConstants.Android.targetSdkVersion testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } buildTypes { getByName("release") { proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro") } } compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } tasks.withType<KotlinCompile> { kotlinOptions { jvmTarget = "1.8" // Opt-in to experimental compose APIs freeCompilerArgs = listOf( "-Xopt-in=kotlin.RequiresOptIn" ) } } sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml") sourceSets["main"].java.srcDirs("src/androidMain/kotlin") sourceSets["main"].res.srcDirs("src/androidMain/res") sourceSets["test"].java.srcDirs("src/androidTest/kotlin") sourceSets["test"].res.srcDirs("src/androidTest/res") } tasks.withType<Jar> { duplicatesStrategy = DuplicatesStrategy.INHERIT } dependencies { implementation("androidx.core:core-ktx:1.7.0") implementation("androidx.appcompat:appcompat:1.4.0") implementation("com.google.android.material:material:1.4.0") implementation("androidx.activity:activity-compose:1.4.0") }
29.78022
95
0.644649
8435b20dad61d829369f0f5dafa35729bbf89e8f
1,227
html
HTML
share/templates/preferences.html
bricas/rubric
9d60d867042bf941951b7dbd30c0d2e06f2ec8a8
[ "Artistic-1.0" ]
1
2016-05-09T06:11:14.000Z
2016-05-09T06:11:14.000Z
share/templates/preferences.html
bricas/rubric
9d60d867042bf941951b7dbd30c0d2e06f2ec8a8
[ "Artistic-1.0" ]
null
null
null
share/templates/preferences.html
bricas/rubric
9d60d867042bf941951b7dbd30c0d2e06f2ec8a8
[ "Artistic-1.0" ]
null
null
null
<h2>preferences / settings</h2> [% IF email_missing %] <h3 class='error'>You must provide an email address!</h3> [% END %] [% IF email_invalid %] <h3 class='error'>That isn't a valid email address!</h3> [% END %] [% IF password_missing %] <h3 class='error'>You must supply your current password!</h3> [% END %] [% IF password_wrong %] <h3 class='error'>You got your password wrong!</h3> [% END %] [% IF password_mismatch %] <h3 class='error'>Your passwords didn't match!</h3> [% END %] <div class='preferences'> <form id='preferences' action='preferences' method='POST'> <table> <tr> <th>old password</th> <td>[% widget.password(name => password) %]</td> </tr> <tr> <th>new password</th> <td>[% widget.password(name => password_1) %]</td> </tr> <tr> <th>new password (again)</th> <td>[% widget.password(name => password_2) %]</td> </tr> <tr> <th>email</th> [% email = email OR current_user.email %] <td>[% widget.input(name => 'email', value => email) %]</td> </tr> <tr><td class='submit' colspan='2'> <input type='submit' name='submit' value='submit' /> </td></tr> </table> </form> </div>
28.534884
70
0.568867
b3c62c713c55c9ddd8810c8b8d1f4678fc64af7a
108
sql
SQL
schema/revert/receiving/enrollment.sql
UWIT-IAM/uw-redcap-client
38a1eb426fa80697446df7a466a41e0305382606
[ "MIT" ]
21
2019-04-19T22:45:22.000Z
2022-01-28T01:32:09.000Z
schema/revert/receiving/enrollment.sql
sonali-mhihim/id3c
1e3967d6c24e9cadb34cae1c5e1e79415a2250dc
[ "MIT" ]
219
2019-04-19T21:42:24.000Z
2022-03-29T21:41:04.000Z
schema/revert/receiving/enrollment.sql
sonali-mhihim/id3c
1e3967d6c24e9cadb34cae1c5e1e79415a2250dc
[ "MIT" ]
9
2020-03-11T20:07:26.000Z
2022-03-05T00:36:11.000Z
-- Revert seattleflu/schema:receiving/enrollment from pg begin; drop table receiving.enrollment; commit;
13.5
56
0.796296
26149daa3dca087dadfeca3f3c06a69cf8ab49ab
315
java
Java
artifacts/DamageSourceSword.java
SDF-Bramble/Artifacts-Reloaded
fe573e9b0e5265220122ff82752f894c420a985b
[ "MIT" ]
2
2018-06-21T09:15:11.000Z
2018-07-08T19:29:33.000Z
artifacts/DamageSourceSword.java
SDF-Bramble/Artifacts-Reloaded
fe573e9b0e5265220122ff82752f894c420a985b
[ "MIT" ]
null
null
null
artifacts/DamageSourceSword.java
SDF-Bramble/Artifacts-Reloaded
fe573e9b0e5265220122ff82752f894c420a985b
[ "MIT" ]
1
2018-05-28T15:19:19.000Z
2018-05-28T15:19:19.000Z
package com.draco18s.artifacts; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.DamageSource; import net.minecraft.util.StatCollector; public class DamageSourceSword extends DamageSource { public static DamageSource instance; public DamageSourceSword(String name) { super(name); } }
22.5
53
0.815873
71cf5bf3b1e4cb25e4811264574717a53d06e8b8
9,127
sql
SQL
queries/log4shell/log4shell.search.MD5.sql
lizardlabs/Log-Parser-Lizard-Queries
c20068d50fbd0784413e411de8ec64b49bc8e2e9
[ "Unlicense" ]
5
2018-09-03T12:33:13.000Z
2021-12-11T07:15:36.000Z
queries/log4shell/log4shell.search.MD5.sql
lizardlabs/Log-Parser-Lizard-Queries
c20068d50fbd0784413e411de8ec64b49bc8e2e9
[ "Unlicense" ]
null
null
null
queries/log4shell/log4shell.search.MD5.sql
lizardlabs/Log-Parser-Lizard-Queries
c20068d50fbd0784413e411de8ec64b49bc8e2e9
[ "Unlicense" ]
null
null
null
/* Log4Shell (CVE-2021-44228) helper This SQL query will search for log4j*.jar files on your system, vulnerable to CVE-2021-44228 (nicknamed Log4Shell), by using Microsoft Logparser 2.2. It will calculated MD5 hashes of every log4*j.jar file that will be found in the selected folders and compare their hash with a list of MD5 hashes. The list of known MD5 haseshes is taken from here: https://github.com/mubix/CVE-2021-44228-Log4Shell-Hashes/blob/main/md5sum.txt More about log4shell resources: https://www.lunasec.io/docs/blog/log4j-zero-day/ https://mbechler.github.io/2021/12/10/PSA_Log4Shell_JNDI_Injection/ What you need to run this script: - Microsoft Logparses 2.2. Download from here: https://www.microsoft.com/en-us/download/details.aspx?id=24659 - Optimally Log Parser Lizard - GUI for logparser. Download from here: https://lizard-labs.com/log_parser_lizard.aspx - This script is on GitHub: https://github.com/lizardlabs/Log-Parser-Lizard-Queries HOW TO USE: A) From command line: 1) Change the paths you want to search after the FORM keyword 2) Run logparser from command line: C:\>LogParser -i:FS file:log4shell.search.MD5.sql B) Optionally, use Log Parser Lizard GUI (www.lizard-labs.com) 1) copy and paste the script in Log Parser Lizard and click Run 2) Modify the folders you want to search (after FROM) 3) Click Run. You can export results in Excel for analysis/ NOTES: Alternatively, you can change the script to look for log4j*.jar files only instead of filtering by hashes. */ -- QUERY PROPERTIES: -i:FS SELECT -- TOP 10000 -- limit the number of output records if needed Name, Path, EXTRACT_PATH(Path) AS Folder, ContentHashMD5 USING HASHMD5_FILE(Path) AS ContentHashMD5 /*************************************************************************************** CHANGE THE LIST OF FOLDERS YOU WANT TO SEARCH: list of locations you want to search (use wildcard lof4j*.jar for better performance) ***************************************************************************************/ FROM 'c:\Program Files\log4j*.jar', 'c:\Program Files (x86)\log4j*.jar' -- Filter known MD5 hashes. List of MD5 hashes is taken from here: https://github.com/mubix/CVE-2021-44228-Log4Shell-Hashes/blob/main/md5sum.txt (you may update the list if necesary) WHERE to_lowercase(ContentHashMD5) IN ( -- # 2.X versions '2addabe2ceca2145955c02a6182f7fc5' -- ./apache-log4j-2.0-alpha2-bin/log4j-core-2.0-alpha2.jar ;'5b1d4e4eea828a724c8b0237326829b3' -- ./apache-log4j-2.0-beta1-bin/log4j-core-2.0-beta1.jar ;'ce9e9a27c2a5caa47754999eb9c549b8' -- ./apache-log4j-2.0-beta2-bin/log4j-core-2.0-beta2.jar ;'1538d8c342e3e2a31cd16e01e3865276' -- ./apache-log4j-2.0-beta3-bin/log4j-core-2.0-beta3.jar ;'9cb138881a317a7f49c74c3e462f35f4' -- ./apache-log4j-2.0-beta4-bin/log4j-core-2.0-beta4.jar ;'578ffc5bcccb29f6be2d23176c0425e0' -- ./apache-log4j-2.0-beta5-bin/log4j-core-2.0-beta5.jar ;'5b73a0ad257c57e7441778edee4620a7' -- ./apache-log4j-2.0-beta6-bin/log4j-core-2.0-beta6.jar ;'e32489039dab38637557882cca0653d7' -- ./apache-log4j-2.0-beta7-bin/log4j-core-2.0-beta7.jar ;'db025370dbe801ac623382edb2336ede' -- ./apache-log4j-2.0-beta8-bin/log4j-core-2.0-beta8.jar ;'152ecb3ce094ac5bc9ea39d6122e2814' -- ./apache-log4j-2.0-beta9-bin/log4j-core-2.0-beta9.jar ;'cd70a1888ecdd311c1990e784867ce1e' -- ./apache-log4j-2.0-bin/log4j-core-2.0.jar ;'088df113ad249ab72bf19b7f00b863d5' -- ./apache-log4j-2.0-rc1-bin/log4j-core-2.0-rc1.jar ;'de8d01cc15fd0c74fea8bbb668e289f5' -- ./apache-log4j-2.0-rc2-bin/log4j-core-2.0-rc2.jar ;'fbfa5f33ab4b29a6fdd52473ee7b834d' -- ./apache-log4j-2.0.1-bin/log4j-core-2.0.1.jar ;'8c0cf3eb047154a4f8e16daf5a209319' -- ./apache-log4j-2.0.2-bin/log4j-core-2.0.2.jar ;'8d331544b2e7b20ad166debca2550d73' -- ./apache-log4j-2.1-bin/log4j-core-2.1.jar ;'5e4bca5ed20b94ab19bb65836da93f96' -- ./apache-log4j-2.2-bin/log4j-core-2.2.jar ;'110ab3e3e4f3780921e8ee5dde3373ad' -- ./apache-log4j-2.3-bin/log4j-core-2.3.jar ;'0079c907230659968f0fc0e41a6abcf9' -- ./apache-log4j-2.4-bin/log4j-core-2.4.jar ;'f0c43adaca2afc71c6cc80f851b38818' -- ./apache-log4j-2.4.1-bin/log4j-core-2.4.1.jar ;'dd0e3e0b404083ec69618aabb50b8ac0' -- ./apache-log4j-2.5-bin/log4j-core-2.5.jar ;'5523f144faef2bfca08a3ca8b2becd6a' -- ./apache-log4j-2.6-bin/log4j-core-2.6.jar ;'48f7f3cda53030a87e8c387d8d1e4265' -- ./apache-log4j-2.6.1-bin/log4j-core-2.6.1.jar ;'472c8e1fbaa0e61520e025c255b5d168' -- ./apache-log4j-2.6.2-bin/log4j-core-2.6.2.jar ;'2b63e0e5063fdaccf669a1e26384f3fd' -- ./apache-log4j-2.7-bin/log4j-core-2.7.jar ;'c6d233bc8e9cfe5da690059d27d9f88f' -- ./apache-log4j-2.8-bin/log4j-core-2.8.jar ;'547bb3ed2deb856d0e3bbd77c27b9625' -- ./apache-log4j-2.8.1-bin/log4j-core-2.8.1.jar ;'4a5177a172764bda6f4472b94ba17ccb' -- ./apache-log4j-2.8.2-bin/log4j-core-2.8.2.jar ;'a27e67868b69b7223576d6e8511659dd' -- ./apache-log4j-2.9.0-bin/log4j-core-2.9.0.jar ;'a3a6bc23ffc5615efcb637e9fd8be7ec' -- ./apache-log4j-2.9.1-bin/log4j-core-2.9.1.jar ;'0042e7de635dc1c6c0c5a1ebd2c1c416' -- ./apache-log4j-2.10.0-bin/log4j-core-2.10.0.jar ;'90c12763ac2a49966dbb9a6d98be361d' -- ./apache-log4j-2.11.0-bin/log4j-core-2.11.0.jar ;'71d3394226547d81d1bf6373a5b0e53a' -- ./apache-log4j-2.11.1-bin/log4j-core-2.11.1.jar ;'8da9b75725fb3357cb9872adf7711f9f' -- ./apache-log4j-2.11.2-bin/log4j-core-2.11.2.jar ;'7943c49b634b404144557181f550a59c' -- ./apache-log4j-2.12.0-bin/log4j-core-2.12.0.jar ;'df949e7d73479ab717e5770814de0ae9' -- ./apache-log4j-2.12.1-bin/log4j-core-2.12.1.jar ;'2803991d51c98421be35d2db4ed3c2ac' -- ./apache-log4j-2.13.0-bin/log4j-core-2.13.0.jar ;'5ff1dab00c278ab8c7d46aadc60b4074' -- ./apache-log4j-2.13.1-bin/log4j-core-2.13.1.jar ;'b8e0d2779abbf38586b869f8b8e2eb46' -- ./apache-log4j-2.13.2-bin/log4j-core-2.13.2.jar ;'46e660d79456e6f751c22b94976f6ad5' -- ./apache-log4j-2.13.3-bin/log4j-core-2.13.3.jar ;'62ad26fbfb783183663ba5bfdbfb5ace' -- ./apache-log4j-2.14.0-bin/log4j-core-2.14.0.jar ;'3570d00d9ceb3ca645d6927f15c03a62' -- ./apache-log4j-2.14.1-bin/log4j-core-2.14.1.jar ;'f5e2d2a9543ee3c4339b6f90b6cb01fc' -- ./log4j-2.0-alpha1/log4j-core-2.0-alpha1.jar -- # Possibly Vulnerable 1.x ;'4d4609998fbc124ce6f0d1d48fca2614' -- ./apache-log4j-1.2.15/log4j-1.2.15.jar ;'4a11e911b2403bb6c6cf5e746497fe7a' -- ./apache-log4j-1.2.16/log4j-1.2.16.jar ;'fb87bd84e336ca3dc6b6c108f51bf25e' -- ./apache-log4j-1.2.17/log4j-1.2.17.jar ;'4a116eb60586d4163e3866edc02de4b3' -- ./jakarta-log4j-1.0.4/log4j.jar ;'0c6ac98a9f2735db7e426eb35894d60a' -- ./jakarta-log4j-1.0.4/log4j-core.jar ;'e9581a3b41ee050fab9256eb17c84bab' -- ./jakarta-log4j-1.1.3/dist/lib/log4j.jar ;'c77f1f3db70f14deda3aa1b6f77ac764' -- ./jakarta-log4j-1.1.3/dist/lib/log4j-core.jar ;'4d3c0c848b3765661fea690c4ab55577' -- ./jakarta-log4j-1.2beta4/dist/lib/log4j-1.2beta4.jar ;'5bfbbff4bac4e8a035d553ef1663ee79' -- ./jakarta-log4j-1.2rc1/dist/lib/log4j-1.2rc1.jar ;'a41bce4ac75fdba55a26cfccb9e3b8bf' -- ./jakarta-log4j-1.2.1/dist/lib/log4j-1.2.1.jar ;'0fd5de3cfc23bac1798ca58835add117' -- ./jakarta-log4j-1.2.2/dist/lib/log4j-1.2.2.jar ;'781359b1dea2e898179f40be29f63e0c' -- ./jakarta-log4j-1.2.3/dist/lib/log4j-1.2.3.jar ;'98b84abac0f8b6fbcb4fdc42dc33f2c7' -- ./jakarta-log4j-1.2.4/dist/lib/log4j-1.2.4.jar ;'0342459732ebdfc427d7288a39ea5538' -- ./jakarta-log4j-1.2.5/dist/lib/log4j-1.2.5.jar ;'56e4cf9fabcc73bcece4259add1e3588' -- ./jakarta-log4j-1.2.6/dist/lib/log4j-1.2.6.jar ;'8631619c6becebaac70862ac9c36af44' -- ./jakarta-log4j-1.2.7/dist/lib/log4j-1.2.7.jar ;'18a4ca847248e5b8606325684342701c' -- ./jakarta-log4j-1.2.8/dist/lib/log4j-1.2.8.jar ;'6a44d84b72897f28189f4792e2015b93' -- ./logging-log4j-1.2.9/dist/lib/log4j-1.2.9.jar ;'1f441dc337a302406bc697ec1b57ac40' -- ./logging-log4j-1.2.11/dist/lib/log4j-1.2.11.jar ;'223504f742addd3f631ed8bdf689f1c9' -- ./logging-log4j-1.2.12/dist/lib/log4j-1.2.12.jar ;'52169b4a318e3246483f39f62b84b948' -- ./logging-log4j-1.2.13/dist/lib/log4j-1.2.13.jar ;'599b8ba07d1d04f0ea34414e861d7ad1' -- ./logging-log4j-1.2.14/dist/lib/log4j-1.2.14.jar ;'7b12acacd61b3fbf17e8031a2407c46b' -- ./logging-log4j-1.3alpha-1/log4j-1.3alpha-1.jar ;'ab37ae9c53a099a229c94efbfce53f45' -- ./logging-log4j-1.3alpha-3/log4j-1.3alpha-3.jar ;'f55f20a38c004a262423f06b30e76061' -- ./logging-log4j-1.3alpha-5/log4j-1.3alpha-5.jar ;'ec6960de2fb51373bcea5ec107fcd55a' -- ./logging-log4j-1.3alpha-6/log4j-1.3alpha-6.jar ;'3d430a2bf410c39019d253da5aaa979a' -- ./logging-log4j-1.3alpha-7/log4j-1.3alpha-7.jar ;'2970dc6cee4b87d3fb987132039aae2f' -- ./logging-log4j-1.3alpha-8/lib/log4j-1.3alpha-8.jar ;'a0594d1a36dcf6aa66859aacc5df463b' -- ./logging-log4j-1.3alpha-8/lib/log4j-all-1.3alpha-8.jar ;'ddf718e2073a01d87cb0cc39805024ad' -- ./logging-log4j-1.3alpha-8/lib/log4j-nt-1.3alpha-8.jar ) /* WTFPL License (public domain): This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The F*ck You Want To Public License, Version 2, as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. */
58.50641
182
0.741207
90c2fd51663ea230c9e1dd1141d4141d2f154625
946
py
Python
download.py
mlux86/bytefm-downloader
9ea734fce35edeb2819b340575669b9021a345f9
[ "MIT" ]
null
null
null
download.py
mlux86/bytefm-downloader
9ea734fce35edeb2819b340575669b9021a345f9
[ "MIT" ]
null
null
null
download.py
mlux86/bytefm-downloader
9ea734fce35edeb2819b340575669b9021a345f9
[ "MIT" ]
null
null
null
import json import os from urllib.parse import urlparse, quote import urllib3 def cookies_to_header(cookies): if cookies is None: return {} return { 'Cookie': ';'.join(map(lambda cookie: f'{cookie["name"]}={cookie["value"]}', cookies)) } def get_json(url, cookies=None): headers = cookies_to_header(cookies) http = urllib3.PoolManager() r = http.request('GET', url, headers=headers, preload_content=False) return json.loads(r.data) def download_file(url, path, cookies=None): headers = cookies_to_header(cookies) http = urllib3.PoolManager() r = http.request('GET', url, headers=headers, preload_content=False) with open(path, 'wb') as out: while True: data = r.read(2**16) if not data: break out.write(data) r.release_conn() def file_name_from_url(url): a = urlparse(url) return os.path.basename(a.path)
24.25641
94
0.636364
718b679c89170ac78a6b677ff705f8db2282a5ef
194
ts
TypeScript
src/locales/index.ts
bobolinks/haohaochifan
525feb89a75529ca70ae4d9a1788bb35203cf8bd
[ "MIT" ]
null
null
null
src/locales/index.ts
bobolinks/haohaochifan
525feb89a75529ca70ae4d9a1788bb35203cf8bd
[ "MIT" ]
null
null
null
src/locales/index.ts
bobolinks/haohaochifan
525feb89a75529ca70ae4d9a1788bb35203cf8bd
[ "MIT" ]
null
null
null
import zh from './zh-CN'; import en from './en-US'; import { appData } from '../store'; export const $s = appData.lang === 'en-US' ? en : zh; export default { 'zh-CN': zh, 'en-US': en, };
17.636364
53
0.56701
f761f5cc5dfe7575d1e7d7fdbc3244562c5b15d8
10,466
c
C
Windsolar/commands.c
itay-raveh/windsolar
8516f321bc983e6d748b40dfd0eb0a12171f5638
[ "Apache-2.0" ]
2
2022-01-14T20:49:03.000Z
2022-01-15T22:35:26.000Z
Windsolar/commands.c
itay-raveh/windsolar
8516f321bc983e6d748b40dfd0eb0a12171f5638
[ "Apache-2.0" ]
null
null
null
Windsolar/commands.c
itay-raveh/windsolar
8516f321bc983e6d748b40dfd0eb0a12171f5638
[ "Apache-2.0" ]
null
null
null
// // Created by itay on 1/2/22. // #include <stdio.h> #include <string.h> #include <math.h> #ifdef WIN32 #include <Windows.h> #else #include <unistd.h> #endif #include "commands.h" #include "frames.h" #include "utils.h" void printCommandRuntimeError(char *command, char *msg) { fprintf(stderr, "Runtime Error: %s: %s\n", command, msg); } #define DATA_COUNT_MSG(exp) "Expected at least " #exp " items in the Data Stack, found less" #define DATA_TYPE_MSG(exp, found) "Expected Data of type " #exp ", found " #found bool CALL(LabelNode *restrict pt, Stack *const restrict ps, Stack *const restrict ds) { if (ds->len < 1) { printCommandRuntimeError("CALL", DATA_COUNT_MSG(1)); return false; } DataFrame *df = Stack_pop(ds); if (df->isNumber) { printCommandRuntimeError("CALL", DATA_TYPE_MSG("STRING", "NUMBER")); return false; } while (pt != NULL && strcmp(pt->label, df->str) != 0) pt = pt->next; if (pt == NULL) { char str[100] = "No subroutine named "; strcat(str, df->str); printCommandRuntimeError("CALL", str); return false; } DataFrame_free(df); Stack *reverse = Stack_new(); for (InstNode *inst = pt->blockHead; inst != NULL; inst = inst->next) { ProgramFrame *pf = ProgramFrame_new(inst->type, newstr(inst->str, strlen(inst->str))); Stack_push(reverse, pf); } do Stack_push(ps, Stack_pop(reverse)); while (reverse->len > 0); Stack_free(reverse, (void (*)(void *)) ProgramFrame_free); return true; } bool CCALL(LabelNode *restrict pt, Stack *const restrict ps, Stack *const restrict ds) { if (ds->len < 2) { printCommandRuntimeError("CCALL", DATA_COUNT_MSG(2)); return false; } DataFrame *df1 = Stack_pop(ds), *df2 = Stack_pop(ds); if (!df2->isNumber) { printCommandRuntimeError("CCALL", DATA_TYPE_MSG("NUMBER", "STRING")); return false; } if (df2->number != 0) { Stack_push(ds, df1); DataFrame_free(df2); return CALL(pt, ps, ds); } else { DataFrame_free(df1); DataFrame_free(df2); return true; } } bool BRANCH(LabelNode *restrict pt, Stack *const restrict ps, Stack *const restrict ds) { if (ds->len < 3) { printCommandRuntimeError("BRANCH", DATA_COUNT_MSG(3)); return false; } DataFrame *df1 = Stack_pop(ds), *df2 = Stack_pop(ds), *df3 = Stack_pop(ds); if (!df3->isNumber) { printCommandRuntimeError("BRANCH", DATA_TYPE_MSG("NUMBER", "STRING")); return false; } if (df3->number != 0) { Stack_push(ds, df2); DataFrame_free(df1); } else { Stack_push(ds, df1); DataFrame_free(df2); } DataFrame_free(df3); return CALL(pt, ps, ds); } bool BINARY_OP(Stack *const restrict ds, char *const restrict op) { if (ds->len < 2) { printCommandRuntimeError(op, DATA_COUNT_MSG(2)); return false; } DataFrame *df1 = Stack_pop(ds); if (!df1->isNumber) { printCommandRuntimeError(op, DATA_TYPE_MSG("NUMBER", "STRING")); return false; } DataFrame *df2 = Stack_pop(ds); if (!df2->isNumber) { printCommandRuntimeError(op, DATA_TYPE_MSG("NUMBER", "STRING")); return false; } double res; if (strcmp(op, "ADD") == 0) res = df2->number + df1->number; else if (strcmp(op, "SUB") == 0) res = df2->number - df1->number; else if (strcmp(op, "MUL") == 0) res = df2->number * df1->number; else if (strcmp(op, "DIV") == 0) res = df2->number / df1->number; else if (strcmp(op, "MOD") == 0) res = (int32_t) df2->number % (int32_t) df1->number; Stack_push(ds, DataFrame_new(&res, NULL)); DataFrame_free(df1); DataFrame_free(df2); return true; } bool BINARY_CMP(Stack *const restrict ds, char *const restrict cmp) { if (ds->len < 2) { printCommandRuntimeError(cmp, DATA_COUNT_MSG(2)); return false; } DataFrame *df1 = Stack_pop(ds); if (!df1->isNumber) { printCommandRuntimeError(cmp, DATA_TYPE_MSG("NUMBER", "STRING")); return false; } DataFrame *df2 = Stack_pop(ds); if (!df2->isNumber) { printCommandRuntimeError(cmp, DATA_TYPE_MSG("NUMBER", "STRING")); return false; } double res; if (strcmp(cmp, "EQ") == 0) res = df2->number == df1->number; else if (strcmp(cmp, "NE") == 0) res = df2->number != df1->number; else if (strcmp(cmp, "GT") == 0) res = df2->number > df1->number; else if (strcmp(cmp, "GE") == 0) res = df2->number >= df1->number; else if (strcmp(cmp, "LT") == 0) res = df2->number < df1->number; else if (strcmp(cmp, "LE") == 0) res = df2->number <= df1->number; else if (strcmp(cmp, "AND") == 0) res = df2->number && df1->number; else if (strcmp(cmp, "OR") == 0) res = df2->number || df1->number; else return false; Stack_push(ds, DataFrame_new(&res, NULL)); DataFrame_free(df1); DataFrame_free(df2); return true; } bool NOT(Stack *const restrict ds) { if (ds->len < 1) { printCommandRuntimeError("NOT", DATA_COUNT_MSG(1)); return false; } DataFrame *df = Stack_pop(ds); if (!df->isNumber) { printCommandRuntimeError("NOT", DATA_TYPE_MSG("NUMBER", "STRING")); return false; } double res = !df->number; Stack_push(ds, DataFrame_new(&res, NULL)); DataFrame_free(df); return true; } bool POP(Stack *const restrict ds) { if (ds->len < 1) { printCommandRuntimeError("POP", DATA_COUNT_MSG(1)); return false; } DataFrame_free(Stack_pop(ds)); return true; } bool DUP(Stack *const restrict ds) { if (ds->len < 1) { printCommandRuntimeError("DUP", DATA_COUNT_MSG(1)); return false; } DataFrame *df = Stack_pop(ds), *df_copy; if (df->isNumber) df_copy = DataFrame_new(&df->number, NULL); else df_copy = DataFrame_new(NULL, df->str); Stack_push(ds, df); Stack_push(ds, df_copy); return true; } bool DUP2(Stack *const restrict ds) { if (ds->len < 1) { printCommandRuntimeError("DUP", DATA_COUNT_MSG(1)); return false; } DataFrame *df1 = Stack_pop(ds), *df1_copy, *df2 = Stack_pop(ds), *df2_copy; if (df1->isNumber) df1_copy = DataFrame_new(&df1->number, NULL); else df1_copy = DataFrame_new(NULL, df1->str); if (df2->isNumber) df2_copy = DataFrame_new(&df2->number, NULL); else df2_copy = DataFrame_new(NULL, df2->str); Stack_push(ds, df2); Stack_push(ds, df1); Stack_push(ds, df2_copy); Stack_push(ds, df1_copy); return true; } bool SWAP12(Stack *const restrict ds) { if (ds->len < 2) { printCommandRuntimeError("SWAP12", DATA_COUNT_MSG(2)); return false; } DataFrame *first = Stack_pop(ds), *second = Stack_pop(ds); Stack_push(ds, first); Stack_push(ds, second); return true; } bool SWAP13(Stack *const restrict ds) { if (ds->len < 3) { printCommandRuntimeError("SWAP13", DATA_COUNT_MSG(3)); return false; } DataFrame *first = Stack_pop(ds), *second = Stack_pop(ds), *third = Stack_pop(ds); Stack_push(ds, first); Stack_push(ds, second); Stack_push(ds, third); return true; } bool WRITE(Stack *const restrict ds) { if (ds->len < 1) { printCommandRuntimeError("WRITE", DATA_COUNT_MSG(1)); return false; } DataFrame *df = Stack_pop(ds); if (df->isNumber) { if (floor(df->number) == ceil(df->number)) printf("%0.0f", df->number); else printf("%f", df->number); } else { char *p = df->str; while (*p != '\0') { if (*p == '\\') { char c; switch (*(p + 1)) { case 'a': c = '\a'; break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; } putc(c, stdout); p += 2; } else { putc(*p, stdout); p++; } } } DataFrame_free(df); return true; } #define MAX_INPUT_LEN 100 bool READ(Stack *const restrict ds) { char *inp = malloc_s(MAX_INPUT_LEN); if (fgets(inp, MAX_INPUT_LEN, stdin) == NULL) { printCommandRuntimeError("READ", "Could not read user input"); return false; } *strchr(inp, '\n') = '\0'; DataFrame *df = DataFrame_new(NULL, inp); Stack_push(ds, df); return true; } bool SLEEP(Stack *const restrict ds) { if (ds->len < 1) { printCommandRuntimeError("SLEEP", DATA_COUNT_MSG(1)); return false; } DataFrame *df = Stack_pop(ds); if (!df->isNumber) { printCommandRuntimeError("SLEEP", DATA_TYPE_MSG("NUMBER", "STRING")); return false; } #ifdef WIN32 Sleep(pollingDelay * 1000); #else usleep(df->number * 1000 * 1000); #endif return true; } bool execCommand(LabelNode *restrict pt, Stack *const restrict ps, Stack *const restrict ds, char *const restrict command) { #define IS(s) (strcmp(command, s) == 0) if (IS("CALL")) return CALL(pt, ps, ds); if (IS("CCALL")) return CCALL(pt, ps, ds); if (IS("BRANCH")) return BRANCH(pt, ps, ds); if (IS("ADD") || IS("SUB") || IS("MUL") || IS("DIV") || IS("MOD")) return BINARY_OP(ds, command); if (IS("NOT")) return NOT(ds); if (IS("EQ") || IS("NE") || IS("GT") || IS("GE") || IS("LT") || IS("LE") || IS("AND") || IS("OR")) return BINARY_CMP(ds, command); if (IS("POP")) return POP(ds); if (IS("DUP")) return DUP(ds); if (IS("DUP2")) return DUP2(ds); if (IS("SWAP12")) return SWAP12(ds); if (IS("SWAP13")) return SWAP13(ds); if (IS("WRITE")) return WRITE(ds); if (IS("READ")) return READ(ds); if (IS("SLEEP")) return SLEEP(ds); printCommandRuntimeError(command, "No such command"); return false; }
24.683962
117
0.55752
06b1b6ae7e8b328480b3d7a25d93bb1bab2f08e7
1,936
kt
Kotlin
android/src/main/kotlin/dev/jeremyko/proximity_sensor/ProximityStreamHandler.kt
jeremyko/flutter-proximity-sensor-plugin
01632a07f39ac35c8c3d60b28e69deac548057ae
[ "MIT" ]
1
2021-12-23T15:45:23.000Z
2021-12-23T15:45:23.000Z
android/src/main/kotlin/dev/jeremyko/proximity_sensor/ProximityStreamHandler.kt
jeremyko/flutter-proximity-sensor-plugin
01632a07f39ac35c8c3d60b28e69deac548057ae
[ "MIT" ]
3
2021-09-27T07:54:17.000Z
2022-03-23T14:48:24.000Z
android/src/main/kotlin/dev/jeremyko/proximity_sensor/ProximityStreamHandler.kt
jeremyko/flutter-proximity-sensor-plugin
01632a07f39ac35c8c3d60b28e69deac548057ae
[ "MIT" ]
null
null
null
package dev.jeremyko.proximity_sensor import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.EventChannel import java.io.IOException import java.lang.UnsupportedOperationException //////////////////////////////////////////////////////////////////////////////////////////////////// class ProximityStreamHandler( private val applicationContext: Context, private val messenger: BinaryMessenger ): EventChannel.StreamHandler, SensorEventListener { private var eventSink: EventChannel.EventSink? = null private lateinit var sensorManager: SensorManager private var proximitySensor: Sensor? = null override fun onListen(arguments: Any?, events: EventChannel.EventSink?) { eventSink = events sensorManager = applicationContext.getSystemService(Context.SENSOR_SERVICE) as SensorManager proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY) ?: throw UnsupportedOperationException("proximity sensor unavailable") sensorManager.registerListener(this, proximitySensor, SensorManager.SENSOR_DELAY_NORMAL) } override fun onCancel(arguments: Any?) { sensorManager.unregisterListener(this, proximitySensor) } override fun onSensorChanged(event: SensorEvent?) { val distance = event ?.values?.get(0)?.toInt() //get distance if (distance != null) { if(distance > 0) { // distance > 0 , nothing is near eventSink ?.success(0) }else{ // distance == 0, something is near eventSink ?.success(1) } } } override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { //do nothing } }
37.230769
101
0.670455
4b8affbcb3818cf5b58c9ca9b503248fbc9d96df
1,029
dart
Dart
05-functions/projects/starter/bin/starter.dart
YojerLiu/da-materials
9e45ce671dd1ec544e01711ffdb610e59c017c80
[ "Apache-2.0" ]
null
null
null
05-functions/projects/starter/bin/starter.dart
YojerLiu/da-materials
9e45ce671dd1ec544e01711ffdb610e59c017c80
[ "Apache-2.0" ]
null
null
null
05-functions/projects/starter/bin/starter.dart
YojerLiu/da-materials
9e45ce671dd1ec544e01711ffdb610e59c017c80
[ "Apache-2.0" ]
null
null
null
import 'dart:math'; void main() { challenge1(); challenge2(); } /// Write a function that checks if a number is prime. void challenge1() { final list = [144, 125, 13, 98, 37]; list.forEach((element) => print('Is $element prime? ${isPrime(element)}')); } /// Write a function named `repeatTask` with the following definition: /// ``` /// int repeatTask(int times, int input, Function task) /// ``` /// It repeats a given `task` on `input` for `times` number of times. void challenge2() { final list = [1, 2, 3]; list.forEach((element) { print(repeatTask(4, element, (int number) => number * number)); }); } bool isPrime(int number) { if (number == 1 || number == 2) { return false; } final root = sqrt(number); for (var i = 3; i <= root; i++) { if (number % i == 0) { return false; } } return true; } int repeatTask(int times, int input, Function task) { var result = 0; for (var i = 0; i < times; i++) { result = task(input); input = result; } return result; }
22.369565
77
0.596696
4c22a3e1df8f2f85cc35bc80b353943158e41cae
3,852
dart
Dart
note_it/lib/components/navigation.dart
MartienJun/flutter_note_it
6ca49588f31fecdbb71589f6f18d2da09dd1b9a2
[ "Apache-2.0" ]
1
2021-03-25T12:43:11.000Z
2021-03-25T12:43:11.000Z
note_it/lib/components/navigation.dart
MartienJun/flutter_note_it
6ca49588f31fecdbb71589f6f18d2da09dd1b9a2
[ "Apache-2.0" ]
null
null
null
note_it/lib/components/navigation.dart
MartienJun/flutter_note_it
6ca49588f31fecdbb71589f6f18d2da09dd1b9a2
[ "Apache-2.0" ]
2
2020-10-13T06:06:10.000Z
2021-03-25T12:43:15.000Z
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; // Components import 'package:note_it/components/constants.dart'; // Screens import 'package:note_it/screens/home_screen.dart'; import 'package:note_it/screens/user_screen.dart'; import 'package:note_it/screens/reminder_screen.dart'; class MyNavigation extends StatefulWidget { static const String id = 'my_navigation'; @override _MyNavigationState createState() => _MyNavigationState(); } class _MyNavigationState extends State<MyNavigation> { PageController _pageController = PageController(); // List of the screen List<Widget> _screens = [ HomeScreen(), ReminderScreen(), UserScreen(), ]; // Index of the screen int _selectedIndex = 0; // Method set the index state void _onPageChanged(int index) { setState(() { _selectedIndex = index; }); } // Method to move to the selected page void _onItemTapped(int selectedIndex) { _pageController.jumpToPage(selectedIndex); } @override Widget build(BuildContext context) { return Scaffold( body: PageView( controller: _pageController, /* Is a controller for PageView, that lets you manipulate which page is visible in a PageView. PageController also lets you control the offset in terms of pages, which are increments of the viewport size. */ children: _screens, onPageChanged: _onPageChanged, ), // floatingActionButton: FloatingActionButton( // onPressed: null, // elevation: 1.0, // backgroundColor: primaryColor, // child: Icon( // Icons.add, // //color: secondaryColor, // ), // ), bottomNavigationBar: BottomNavigationBar( backgroundColor: primaryColor, currentIndex: _selectedIndex, //If i tapped, then ... onTap: _onItemTapped, //List of Item (Screens) items: [ // Index 0 - note BottomNavigationBarItem( icon: SvgPicture.asset( 'assets/icons/writing.svg', width: 30.0, color: _selectedIndex == 0 ? secondaryColor : Colors.white, ), title: Text( 'Note', style: TextStyle( color: _selectedIndex == 0 ? secondaryColor : Colors.white, fontWeight: _selectedIndex == 0 ? FontWeight.w700 : FontWeight.w400, ), ), backgroundColor: primaryColor, ), // Index 1 - reminder BottomNavigationBarItem( icon: SvgPicture.asset( 'assets/icons/notification.svg', width: 30.0, color: _selectedIndex == 1 ? secondaryColor : Colors.white, ), title: Text( 'Reminder', style: TextStyle( color: _selectedIndex == 1 ? secondaryColor : Colors.white, fontWeight: _selectedIndex == 1 ? FontWeight.w700 : FontWeight.w400, ), ), backgroundColor: primaryColor, ), // Index 2 - profile BottomNavigationBarItem( icon: SvgPicture.asset( 'assets/icons/user.svg', width: 20.0, color: _selectedIndex == 2 ? secondaryColor : Colors.white, ), title: Text( 'User', style: TextStyle( color: _selectedIndex == 2 ? secondaryColor : Colors.white, fontWeight: _selectedIndex == 2 ? FontWeight.w700 : FontWeight.w400, ), ), backgroundColor: primaryColor, ), ], ), ); } }
29.40458
78
0.562305
5b26e406b94b640128f36a73c3e147e62b0aca3b
6,996
asm
Assembly
Appl/FileMgrs2/CommonDesktop/CTool/ctoolProcess.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
504
2018-11-18T03:35:53.000Z
2022-03-29T01:02:51.000Z
Appl/FileMgrs2/CommonDesktop/CTool/ctoolProcess.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
96
2018-11-19T21:06:50.000Z
2022-03-06T10:26:48.000Z
Appl/FileMgrs2/CommonDesktop/CTool/ctoolProcess.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
73
2018-11-19T20:46:53.000Z
2022-03-29T00:59:26.000Z
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1992 -- All Rights Reserved PROJECT: File Managers MODULE: Installable Tools -- Process Class Methods FILE: ctoolProcess.asm AUTHOR: Adam de Boor, Aug 25, 1992 ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- Adam 8/25/92 Initial revision DESCRIPTION: ProcessClass methods $Id: ctoolProcess.asm,v 1.3 98/06/03 13:47:11 joon Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ToolCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FMGetSelectedFiles %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Fetch the files currently selected. CALLED BY: MSG_FM_GET_SELECTED_FILES PASS: ds = dgroup RETURN: ax = handle of quick transfer block (0 if couldn't alloc) DESTROYED: cx, dx, bp SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 8/25/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FMGetSelectedFiles method extern dynamic FileManagerClass, MSG_FM_GET_SELECTED_FILES .enter ; ; get current target folder object ; mov bx, ds:[targetFolder] ; bx:si = target folder ; object mov si, FOLDER_OBJECT_OFFSET ; common offset tst bx ; check if any target if _NEWDESK or _FCAB or _ZMGR or not _TREE_MENU jz none else jnz callCommon ; if target exists, use ; it tst ds:[treeRelocated] jz none ; no tree yet mov bx, handle DesktopUI ; else, use tree object mov si, offset DesktopUI:TreeObject callCommon: endif ; if _GMGR mov ax, MSG_META_APP_GET_SELECTION call ObjMessageCall done: .leave ret none: ; ; Nothing with the target, so return a block with nothing selected. ; mov ax, size FileQuickTransferHeader mov cx, ALLOC_DYNAMIC_LOCK or mask HF_SHARABLE or \ (mask HAF_ZERO_INIT shl 8) call MemAlloc jc fail ; ; Initialize to be [SP_TOP] \ as a reasonable (and quick) default. ; mov es, ax mov es:[FQTH_diskHandle], SP_TOP mov {word}es:[FQTH_pathname], '\\' or (0 shl 8) call MemUnlock mov_tr ax, bx jmp done fail: ; ; Couldn't alloc -- return 0. ; clr ax jmp done FMGetSelectedFiles endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FMOpenFiles %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Open the files in the passed CALLED BY: MSG_FM_OPEN_FILES PASS: cx = handle of first block with a FileQuickTransferHeader and following array of FileOperationInfoEntry structures. More than one block of files may be passed by linking successive blocks through their FQTH_nextBlock fields. The final block must have an FQTH_nextBlock of 0. RETURN: carry set on error (all things that could be opened will have been opened, however) All blocks in the chain are freed, regardless of the success of the operation. DESTROYED: ax, cx, dx, bp SIDE EFFECTS: lots PSEUDO CODE/STRATEGY: Implement this when it becomes necessary. REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 8/25/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FMOpenFiles method extern dynamic FileManagerClass, MSG_FM_OPEN_FILES .enter .leave ret FMOpenFiles endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FMDupAndAdd %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Duplicate a resource from a tool library and make one of the objects in that resource a generic child of one of our own. CALLED BY: MSG_FM_DUP_AND_ADD PASS: ^lcx:dx = object to add as generic child, after its resource has been duplicated bp = FileManagerParent to which to add the duplicated object RETURN: ^lcx:dx = duplicated object DESTROYED: ax, bp SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 8/25/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if _NEWDESK fmParents optr Desktop, ; FMP_APPLICATION Desktop ; FMP_DISPLAY_GROUP else fmParents optr Desktop, ; FMP_APPLICATION FileSystemDisplayGroup ; FMP_DISPLAY_GROUP endif FMDupAndAdd method extern dynamic FileManagerClass, MSG_FM_DUP_AND_ADD .enter EC < cmp bp, length fmParents > EC < ERROR_A INVALID_FM_PARENT > CheckHack <type fmParents eq 4> shl bp shl bp ; ; Fetch and save generic parent. ; mov bx, cs:[fmParents][bp].handle mov si, cs:[fmParents][bp].chunk push bx, si ; ; Figure thread running parent to use as thread to run duplicated ; block. ; mov ax, MGIT_EXEC_THREAD call MemGetInfo ; ; Duplicate the resource itself. ; mov bx, cx ; bx <- resource to duplicate mov_tr cx, ax ; cx <- thread to run duplicate clr ax ; owned by us, please call ObjDuplicateResource ; ; Now add the indicated object within the duplicate as the last child ; of the appropriate generic parent. ; mov cx, bx ; ^lcx:dx <- new child pop bx, si mov bp, CCO_LAST or mask CCF_MARK_DIRTY mov ax, MSG_GEN_ADD_CHILD call ObjMessageCall .leave ret FMDupAndAdd endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DesktopCallToolLibrary %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Call a particular routine in a tool library on the process thread of the file manager. CALLED BY: MSG_DESKTOP_CALL_TOOL_LIBRARY PASS: ds = dgroup cx = handle of library to call (will be replaced by the handle of the process before the call is issued) si = entry point to call dx, bp = as appropriate to the call RETURN: nothing DESTROYED: SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 8/26/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DesktopCallToolLibrary method extern dynamic DesktopClass, MSG_DESKTOP_CALL_TOOL_LIBRARY .enter mov bx, cx ; bx <- library mov cx, handle 0 ; cx <- us mov ax, GGIT_ATTRIBUTES call GeodeGetInfo test ax, mask GA_ENTRY_POINTS_IN_C jnz callC callCommon: mov_tr ax, si ; ax <- entry # call ProcGetLibraryEntry ; bx:ax <- virtual fptr call ProcCallFixedOrMovable ; call it, dude .leave ret callC: push cx, dx, bp jmp callCommon DesktopCallToolLibrary endm ToolCode ends
26.104478
89
0.581618
b530a7485ea6bb3037fbff30cb4494b911225b6c
5,948
rs
Rust
src/udma0/cfg.rs
jeandudey/cc13x2-rs
215918099301ec75e9dfad531f5cf46e13077a39
[ "MIT" ]
null
null
null
src/udma0/cfg.rs
jeandudey/cc13x2-rs
215918099301ec75e9dfad531f5cf46e13077a39
[ "MIT" ]
null
null
null
src/udma0/cfg.rs
jeandudey/cc13x2-rs
215918099301ec75e9dfad531f5cf46e13077a39
[ "MIT" ]
null
null
null
#[doc = "Reader of register CFG"] pub type R = crate::R<u32, super::CFG>; #[doc = "Writer for register CFG"] pub type W = crate::W<u32, super::CFG>; #[doc = "Register CFG `reset()`'s with value 0"] impl crate::ResetValue for super::CFG { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `RESERVED8`"] pub type RESERVED8_R = crate::R<u32, u32>; #[doc = "Write proxy for field `RESERVED8`"] pub struct RESERVED8_W<'a> { w: &'a mut W, } impl<'a> RESERVED8_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = (self.w.bits & !(0x00ff_ffff << 8)) | (((value as u32) & 0x00ff_ffff) << 8); self.w } } #[doc = "Reader of field `PRTOCTRL`"] pub type PRTOCTRL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PRTOCTRL`"] pub struct PRTOCTRL_W<'a> { w: &'a mut W, } impl<'a> PRTOCTRL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07 << 5)) | (((value as u32) & 0x07) << 5); self.w } } #[doc = "Reader of field `RESERVED1`"] pub type RESERVED1_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RESERVED1`"] pub struct RESERVED1_W<'a> { w: &'a mut W, } impl<'a> RESERVED1_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 1)) | (((value as u32) & 0x0f) << 1); self.w } } #[doc = "Reader of field `MASTERENABLE`"] pub type MASTERENABLE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MASTERENABLE`"] pub struct MASTERENABLE_W<'a> { w: &'a mut W, } impl<'a> MASTERENABLE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bits 8:31 - 31:8\\] Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."] #[inline(always)] pub fn reserved8(&self) -> RESERVED8_R { RESERVED8_R::new(((self.bits >> 8) & 0x00ff_ffff) as u32) } #[doc = "Bits 5:7 - 7:5\\] Sets the AHB-Lite bus protocol protection state by controlling the AHB signal HProt\\[3:1\\] as follows: Bit \\[7\\] Controls HProt\\[3\\] to indicate if a cacheable access is occurring. Bit \\[6\\] Controls HProt\\[2\\] to indicate if a bufferable access is occurring. Bit \\[5\\] Controls HProt\\[1\\] to indicate if a privileged access is occurring. When bit \\[n\\] = 1 then the corresponding HProt bit is high. When bit \\[n\\] = 0 then the corresponding HProt bit is low. This field controls HProt\\[3:1\\] signal for all transactions initiated by uDMA except two transactions below: - the read from the address indicated by source address pointer - the write to the address indicated by destination address pointer HProt\\[3:1\\] for these two exceptions can be controlled by dedicated fields in the channel configutation descriptor."] #[inline(always)] pub fn prtoctrl(&self) -> PRTOCTRL_R { PRTOCTRL_R::new(((self.bits >> 5) & 0x07) as u8) } #[doc = "Bits 1:4 - 4:1\\] Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."] #[inline(always)] pub fn reserved1(&self) -> RESERVED1_R { RESERVED1_R::new(((self.bits >> 1) & 0x0f) as u8) } #[doc = "Bit 0 - 0:0\\] Enables the controller: 0: Disables the controller 1: Enables the controller"] #[inline(always)] pub fn masterenable(&self) -> MASTERENABLE_R { MASTERENABLE_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bits 8:31 - 31:8\\] Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."] #[inline(always)] pub fn reserved8(&mut self) -> RESERVED8_W { RESERVED8_W { w: self } } #[doc = "Bits 5:7 - 7:5\\] Sets the AHB-Lite bus protocol protection state by controlling the AHB signal HProt\\[3:1\\] as follows: Bit \\[7\\] Controls HProt\\[3\\] to indicate if a cacheable access is occurring. Bit \\[6\\] Controls HProt\\[2\\] to indicate if a bufferable access is occurring. Bit \\[5\\] Controls HProt\\[1\\] to indicate if a privileged access is occurring. When bit \\[n\\] = 1 then the corresponding HProt bit is high. When bit \\[n\\] = 0 then the corresponding HProt bit is low. This field controls HProt\\[3:1\\] signal for all transactions initiated by uDMA except two transactions below: - the read from the address indicated by source address pointer - the write to the address indicated by destination address pointer HProt\\[3:1\\] for these two exceptions can be controlled by dedicated fields in the channel configutation descriptor."] #[inline(always)] pub fn prtoctrl(&mut self) -> PRTOCTRL_W { PRTOCTRL_W { w: self } } #[doc = "Bits 1:4 - 4:1\\] Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."] #[inline(always)] pub fn reserved1(&mut self) -> RESERVED1_W { RESERVED1_W { w: self } } #[doc = "Bit 0 - 0:0\\] Enables the controller: 0: Disables the controller 1: Enables the controller"] #[inline(always)] pub fn masterenable(&mut self) -> MASTERENABLE_W { MASTERENABLE_W { w: self } } }
38.875817
223
0.634331
79fda9a15d364aad8ef1a5d43f78a78fff6fbbb5
2,057
asm
Assembly
programs/oeis/172/A172076.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
programs/oeis/172/A172076.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
programs/oeis/172/A172076.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
; A172076: a(n) = n*(n+1)*(14*n-11)/6. ; 0,1,17,62,150,295,511,812,1212,1725,2365,3146,4082,5187,6475,7960,9656,11577,13737,16150,18830,21791,25047,28612,32500,36725,41301,46242,51562,57275,63395,69936,76912,84337,92225,100590,109446,118807,128687,139100,150060,161581,173677,186362,199650,213555,228091,243272,259112,275625,292825,310726,329342,348687,368775,389620,411236,433637,456837,480850,505690,531371,557907,585312,613600,642785,672881,703902,735862,768775,802655,837516,873372,910237,948125,987050,1027026,1068067,1110187,1153400,1197720,1243161,1289737,1337462,1386350,1436415,1487671,1540132,1593812,1648725,1704885,1762306,1821002,1880987,1942275,2004880,2068816,2134097,2200737,2268750,2338150,2408951,2481167,2554812,2629900,2706445,2784461,2863962,2944962,3027475,3111515,3197096,3284232,3372937,3463225,3555110,3648606,3743727,3840487,3938900,4038980,4140741,4244197,4349362,4456250,4564875,4675251,4787392,4901312,5017025,5134545,5253886,5375062,5498087,5622975,5749740,5878396,6008957,6141437,6275850,6412210,6550531,6690827,6833112,6977400,7123705,7272041,7422422,7574862,7729375,7885975,8044676,8205492,8368437,8533525,8700770,8870186,9041787,9215587,9391600,9569840,9750321,9933057,10118062,10305350,10494935,10686831,10881052,11077612,11276525,11477805,11681466,11887522,12095987,12306875,12520200,12735976,12954217,13174937,13398150,13623870,13852111,14082887,14316212,14552100,14790565,15031621,15275282,15521562,15770475,16022035,16276256,16533152,16792737,17055025,17320030,17587766,17858247,18131487,18407500,18686300,18967901,19252317,19539562,19829650,20122595,20418411,20717112,21018712,21323225,21630665,21941046,22254382,22570687,22889975,23212260,23537556,23865877,24197237,24531650,24869130,25209691,25553347,25900112,26250000,26603025,26959201,27318542,27681062,28046775,28415695,28787836,29163212,29541837,29923725,30308890,30697346,31089107,31484187,31882600,32284360,32689481,33097977,33509862,33925150,34343855,34765991,35191572,35620612,36053125 mov $2,$0 lpb $0,1 sub $0,1 add $3,$2 add $1,$3 add $2,11 lpe
187
1,946
0.849295
4d98b755a12024014c1a5bab2079bf05995348bc
20,291
html
HTML
enc/enc_rus/meta/other/dict.html
MKadaner/FarManager
c99a14c12e3481dd25ce71451ecd264656f631bb
[ "BSD-3-Clause" ]
1,256
2015-07-07T12:19:17.000Z
2022-03-31T18:41:41.000Z
enc/enc_rus/meta/other/dict.html
MKadaner/FarManager
c99a14c12e3481dd25ce71451ecd264656f631bb
[ "BSD-3-Clause" ]
305
2017-11-01T18:58:50.000Z
2022-03-22T11:07:23.000Z
enc/enc_rus/meta/other/dict.html
MKadaner/FarManager
c99a14c12e3481dd25ce71451ecd264656f631bb
[ "BSD-3-Clause" ]
183
2017-10-28T11:31:14.000Z
2022-03-30T16:46:24.000Z
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Словарь</title> <meta http-equiv="Content-Type" Content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="../../styles/styles.css"> </head> <body> <img src="../../images/bookmarks.png" align=right width=48 height=48 alt=""> <h1>Словарь</h1> <div class=navbar> <a href="../index.html">главная</a> </div> <div class=shortdescr> Часть материалов, описывающих свойства файловой системы взяты с сайта <a href="http://www.windowsfaq.ru/" target="_blank" title="WindowsFAQ.ru">http://www.windowsfaq.ru/</a>. Все ссылки на MSDN, упомянутые в <em>Словаре</em>, открываются в отдельном окне в виде результатов поиска по сайту <a href="https://msdn.microsoft.com/" target="_blank">msdn.microsoft.com</a> (см. также <a href="https://msdn.microsoft.com/ru-ru/" target="_blank">MSDN по русски</a>). </div> <div class=dfn><h3><a name="plugin">Plugin - плагин</a></h3></div> <div class=dfndescr> Программный компонент-добавка к Far Manager, позволяющая реализовать дополнительные функции. Плагин фактически - обычная библиотека, которая выполняется в контексте консольного процесса - так что ваш плагин может делать всё (ну или почти всё), что может делать обычное консольное Windows приложение. Сама идея плагинов позволяет настраивать оболочку под себя, добавляя нужное и выкидывая лишнее. <br> <br> </div> <div class=dfn><h3><a name="reparsepoints">Reparse Points</a></h3></div> <div class=dfndescr> Большая часть нововведений в файловой системе Windows 2000 стала возможной благодаря введению концепции Reparse Points, специальных "крючков" в файловой системе, позволяющих подключать дополнительные подсистемы хранения данных без использования дополнительных программ. <p>Reparse Points в действительности являются специальными объектами файловой системы, обладающими специальными атрибутами, которые позволяют использовать дополнительную функциональность подсистемы хранения данных. Любой файл или папка может иметь Reparse Point, что означает, что по одному и тому же пути при обращении к ресурсу могут быть доступны сразу несколько видов расширенной функциональности. <br> См. также: <a title="MSDN: Reparse Points" href="https://search.microsoft.com/Results.aspx?qsc0=3&FORM=QBMH2&l=2&q=Reparse+Points" target="_blank">MSDN: Reparse Points</a> <br> <br> </div> <div class=dfn><h3><a name="directoryjunctions">Directory Junctions</a></h3></div> <div class=dfndescr> Directory Junctions (слияния папок) позволяют соединять папки вместе таким образом, что вы можете привязать любую имеющуюся папку к любой другой локальной папке. Например, если имеются три папки, c:\folder1, c:\folder2 и c:\documents, то можно создать точки перехода к папке c:\documents таким образом, что она будет казаться подпапкой других двух папок, т.е. на диске будут существовать папки c:\folder1\documents и c:\folder2\documents.</P> <p>Изначально предполагалось, что в поставку будет входить специальная утилита linkd.exe, предназначенная для создания Directory Junctions, однако сейчас эта программа не включена в Win2000 и поставляется в составе Resource Kit. Также Directory Junctions могут быть созданы при помощи API, однако это потребует написания собственной программы. <p>На первый взгляд, Directory Junctions и Distributed File System выполняют одни и те же задачи, так как оба этих сервиса создают видимость единого дерева папок, в действительности состоящих из множества распределённых папок. Однако между ними есть несколько существенных различий:</p> <ul> <li>Система DFS использует службу Active Directory для хранения своей информации</li> <li>Благодаря использованию Active Directory система DFS может обеспечивать защиту от сбоев и выравнивание нагрузки на систему, в то время как Directory Junctions не обеспечивают ни того, ни другого, хотя это и не является необходимым в контексте локального компьютера</li> <li>Система DFS в основном нацелена на объединение сетевых ресурсов в единое пространство имён, в то время как Directory Junctions связывают только локальные ресурсы</li> <li>DFS может работать с использованием нескольких файловых систем, а Directory Junctions основаны только на NTFS 5.0</li> <li>Система DFS требует программы-клиента, а Directory Junctions - нет.</li> </ul> <br> См. также: <a title="MSDN: Directory Junctions" href="https://search.microsoft.com/Results.aspx?qsc0=3&FORM=QBMH2&l=2&q=Directory+Junctions" target="_blank">MSDN: Directory Junctions</a>, <a title="MSDN: Inside Win2K NTFS, Part 1" href="https://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnw2kmag00/html/NTFSPart1.asp" target="_blank">MSDN: Inside Win2K NTFS, Part 1</a>. <br> <br> </div> <div class=dfn><h3><a name="mountpoints">Mount Points - точки подключения томов</a></h3></div> <div class=dfndescr> Mount Points (точки подключения) по сути являются тем же самым, что и Directory Junctions, однако позволяют лишь подключать корневую папку одного раздела к папке на другом разделе диска. Mount Points создаются с использованием Reparse Points, и, следовательно, нуждаются в NTFS 5.0.</p> <p>Mount Points полезны для увеличения размеров раздела без фактического изменения структуры разделов на диске. Например, можно создать точку подключения диска D: в качестве папки C:\Documents, что приведёт в итоге к видимости увеличения доступного на диске C: пространства. <br> См. также: <a title="MSDN: Volume Mount Points" href="https://search.microsoft.com/Results.aspx?qsc0=3&FORM=QBMH2&l=2&q=Volume+Mount+Points" target="_blank">MSDN: Volume Mount Points</a> <br> <br> </div> <div class=dfn><h3><a name="hardlinks">Hard Links - жёсткие ссылки</a></h3></div> <div class=dfndescr> Hard Link - это когда один и тот же файл имеет два имени. Допустим, один и тот же файл имеет имена 1.txt и 2.txt: если пользователь сотрёт файл 1, останется файл 2. Если сотрёт 2 - останется файл 1, то есть оба имени, с момента создания, совершенно равноправны. Файл физически стирается лишь тогда, когда будет удалено его последнее имя. Жёсткая ссылка может быть создана только в пределах одного раздела диска (естественно, файловая система должна поддерживать жёсткие ссылки). <br> См. также: <a title="MSDN: Hard Links" href="https://search.microsoft.com/Results.aspx?qsc0=3&FORM=QBMH2&l=2&q=Hard+Links" target="_blank">MSDN: Hard Links</a>, <a title="Q106166 - Windows NT Backup and Hard Links" href="https://support.microsoft.com/support/kb/articles/Q106/1/66.asp" target="_blank">Q106166 - Windows NT Backup and Hard Links</a>. <br> <br> </div> <div class=dfn><h3><a name="symboliclinks">Symbolic Links - символическая ссылка</a></h3></div> <div class=dfndescr> <p>Гораздо более практичная возможность, позволяющая делать виртуальные каталоги - ровно так же, как и виртуальные диски командой subst в DOSе. Применения достаточно разнообразны: во-первых, упрощение системы каталогов. Если вам не нравится каталог "<code>Documents and settings\Administrator\Documents</code>", вы можете прилинковать его в корневой каталог - система будет по прежнему общаться с каталогом с дремучим путём, а вы - с гораздо более коротким именем, полностью ему эквивалентным.</p> <p>Символические ссылки (SymLink) на NTFS поддерживаются, начиная с Windows Vista (NT 6.0). Они представляют собой улучшеный вариант связей каталогов - символические ссылки могут указывать как на папки, так и на файлы, как на локальные, так и на сетевые, при этом поддерживаются относительные пути.</p> <br> См. также: <a title="MSDN: Symbolic Links" href="https://search.microsoft.com/Results.aspx?qsc0=3&FORM=QBMH2&l=2&q=Symbolic+Links" target="_blank">MSDN: Symbolic Links</a>, <a title="Inside Win2K NTFS, Part 1" href="https://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnw2kmag00/html/NTFSPart1.asp" target="_blank">Windows 2000 Magazine: Inside Win2K NTFS, Part 1</a>. <br> <br> </div> <div class=dfn><h3><a name="sparsefile">Sparse File - разрежённый (распределённые) файл</a></h3></div> <div class=dfndescr> NTFS5 поддерживает разрежённые файлы, которые состоят из больших областей последовательных нулевых разрядов. Такой файл можно пометить как разрежённый и дать файловой системе возможность выделять место для хранения только значимых разрядов данного файла. NTFS хранит информацию только о том, где размещены значимые данные. Подобный способ позволяет оптимально распределять дисковую память на томах NTFS при хранении разрежённых файлов и обработке этих файлов приложениями. <br> См. также: <a title="MSDN: Sparse Files" href="https://search.microsoft.com/Results.aspx?qsc0=3&FORM=QBMH2&l=2&q=Sparse+Files" target="_blank">MSDN: Sparse Files</a>, <a title="Возможности NTFS (на osp.ru)" href="http://www.osp.ru/win2000/2001/07/175039/" target="_blank">Возможности NTFS</a>. <br> <br> </div> <div class=dfn><h3><a name="filemasks">Маски файлов</a></h3></div> <div class=dfndescr>Маски файлов часто используются в командах Far Manager для выбора отдельных файлов и папок или их групп. Маски могут включать обычные допустимые в именах файлов символы, '<code>*</code>' и '<code>?</code>', а также специальные выражения: <table class="cont"> <tr class="cont"><th class="cont" width="40%">Метасимвол</th><th class="cont" width="60%">Описание</th></tr> <tr class="cont"><td class="cont" width="40%"><code>*</code></td> <td class="cont" width="60%">Любое количество символов</td></tr> <tr class="cont"><td class="cont" width="40%"><code>?</code></td> <td class="cont" width="60%">Любой символ</td></tr> <tr class="cont"><td class="cont" width="40%"><code>[c,x-z]</code></td> <td class="cont" width="60%">Любой символ из находящихся в квадратных скобках. Допускаются и отдельные символы, и их диапазоны.</td></tr> </table> Например, файлы <code>ftp.exe</code>, <code>fc.exe</code> и <code>f.ext</code> могут быть выбраны с помощью маски <code>f*.ex?</code>, маска <code>*co*</code> выберет и <code>color.ini</code>, и <code>edit.com</code>, маска <code>[c-f,t]*.txt</code> может выбрать <code>config.txt</code>, <code>demo.txt</code>, <code>faq.txt</code> и <code>tips.txt</code>. <p>Во многих командах Far Manager можно задать несколько разделённых запятыми или точкой с запятой масок. Например, чтобы выбрать все документы, вы можете ввести <code>*.doc,*.txt,*.wri</code> в команде "Пометить группу". </p> <p>Допускается заключать любую из масок (но не весь список) в кавычки. Например, это нужно делать, когда маска содержит один из символов-разделителей (запятую или точку с запятой), чтобы такая маска не была спутана со списком.</p> <p>В некоторых ситуациях (поиск файлов, пометка файлов, ассоциации файлов, группы сортировки и раскраска файлов) можно использовать маски исключения. <b>Маска исключения</b> есть одна или несколько масок файлов, которой не должны соответствовать имена требуемых файлов, она отделяется от основной маски символом '<code><b>|</b></code>'.</p> Примеры использования масок исключения: <ol> <li><code><b>*.cpp</b></code><br>Все файлы с расширением cpp.</li> <li><code><b>*.*|*.bak,*.tmp</b></code><br>Все файлы, кроме файлов с расширением bak и tmp.</li> <li><code><b>*.*|</b></code><br>Ошибка - введён спецсимвол '<code><b>|</b></code>', но сама маска исключения не указана.</li> <li><code><b>*.*|*.bak|*.tmp</b></code><br>Ошибка - спецсимвол '<code><b>|</b></code>' не может встречаться более одного раза.</li> <li><code><b>|*.bak</b></code><br>Обрабатывается как '<code>*|*.bak</code>'</li> </ol> </div> <div class=dfn><h3><a name="panelcolumntype">Типы колонок</a></h3></div> <div class=shortdescr> Допускаются следующие типы колонок: </div> <div class=descr> <div class=dfn>N - имя файла, допускаются модификаторы (например "<b>MOR&quot;</b>):</div> <div class=dfndescr>M - показывать символы пометки;<br> O - показывать имена без путей (предназначено в основном для подключаемых модулей);<br> R - выравнивать не умещающиеся имена по правому краю (дополнительно F - выравнивать все имена по правому краю),<br> N - не отображать расширения файлов. </div> <div class=dfn>X - расширение файла, допускаются модификаторы:</div> <div class=dfndescr>R - выравнивать расширение по правому краю. </div> <div class=dfn>S - размер файла.</div> <div class=dfndescr>Для размеров допускаются модификаторы:<br> C - форматировать размер файла запятыми;<br> T - использовать 1000 вместо 1024 как делитель, если ширины колонки не хватает для показа полного размера файла.<br> F - размер файла выводится в виде десятичной дроби, используя наиболее подходящую единицу измерения, например 0,97 К, 1,44 М, 53,2 Г;<br> E - экономичный режим, между размером и суффиксом пробел не ставится<br> </div> <div class=dfn>P - выделенный размер файла.</div> <div class=dfndescr>Для размеров допускаются модификаторы:<br> C - форматировать размер файла запятыми;<br> T - использовать 1000 вместо 1024 как делитель, если ширины колонки не хватает для показа полного размера файла.<br> F - размер файла выводится в виде десятичной дроби, используя наиболее подходящую единицу измерения, например 0,97 К, 1,44 М, 53,2 Г;<br> E - экономичный режим, между размером и суффиксом пробел не ставится<br> </div> <div class=dfn>G - размер потоков файла.</div> <div class=dfndescr>Для размеров допускаются модификаторы:<br> C - форматировать размер файла запятыми;<br> T - использовать 1000 вместо 1024 как делитель, если ширины колонки не хватает для показа полного размера файла.<br> F - размер файла выводится в виде десятичной дроби, используя наиболее подходящую единицу измерения, например 0,97 К, 1,44 М, 53,2 Г;<br> E - экономичный режим, между размером и суффиксом пробел не ставится<br> </div> <div class=dfn>D - дата модификации файла</div> <div class=dfn>T - время модификации файла</div> <div class=dfn>DM - дата и время модификации файла</div> <div class=dfndescr>Допускаются модификаторы:<br> B - краткий (в стиле Unix) формат времени файла;<br> M - использование текстовых имён месяцев;</div> <div class=dfn>DC - дата и время создания файла</div> <div class=dfndescr>Допускаются модификаторы:<br> B - краткий (в стиле Unix) формат времени файла;<br> M - использование текстовых имён месяцев;</div> <div class=dfn>DA - дата и время последнего доступа к файлу</div> <div class=dfndescr>Допускаются модификаторы:<br> B - краткий (в стиле Unix) формат времени файла;<br> M - использование текстовых имён месяцев;</div> <div class=dfn>DE - дата и время изменения файла</div> <div class=dfndescr>Допускаются модификаторы:<br> B - краткий (в стиле Unix) формат времени файла;<br> M - использование текстовых имён месяцев;</div> <div class=dfn>A - атрибуты файла</div> <div class=dfn>Z - описание файла</div> <div class=dfn>O - владелец файла</div> <div class=dfndescr>Допускаются модификаторы:<br> L - отображать также имя домена</div> <div class=dfn>LN - количество жёстких ссылок</div> <div class=dfn>F - количество потоков</div> <div class=dfn>C0..C99 - пользовательские типы колонок.</div> </div> <div class=shortdescr> Если описание типов колонок содержит более одной колонки имени файла, панель файлов будет отображаться в многоколоночной форме.</div> <div class=dfn><h3><a name="columnwidths">Ширина колонок</a></h3></div> <div class=shortdescr> <p>Строка <code>ColumnWidths</code> в структуре <a href="../structures/panelmode.html">PanelMode</a> описывает ширину колонок панели (например, &quot;<code><b>0,8,0,5&quot;</b></code>). <p>Формат строки простой - числа (представляющие ширину колонки) разделённые запятой. <p>Если ширина равна 0, то используется значение по умолчанию. Если ширина колонки с именем, описанием или владельцем равна 0, она будет подсчитана автоматически, в зависимости от ширины панели. Для правильной работы с различной шириной экрана настоятельно рекомендуется, чтобы в каждом режиме просмотра была хотя бы одна колонка с автоматически вычисляемой шириной.</p> <p>При использовании 12-часового формата времени надо увеличить на единицу стандартную ширину колонки времени файла или колонки времени и даты файла. После дальнейшего увеличения в этих колонках также будут показаны секунды и миллисекунды.</p> <p>Для показа года в 4-хсимвольном формате нужно увеличить ширину колонки даты на 2. </p> <br> </div> <div class=dfn><h3><a name="keybfocus">Фокус ввода элементов диалога</a></h3></div> <div class=dfndescr>Для распределения сообщений от клавиатуры используется концепция так называемого клавиатурного фокуса ввода. Фокус ввода - это атрибут, который присваивается элементу диалога. Если элемент имеет фокус ввода, то он получает все клавиатурные сообщения (в основном :-) из системной очереди Far Manager. <p>Менеджер диалогов Far Manager может передавать фокус ввода от одного элемента другому. Когда вы нажимаете клавиши <kbd>Tab</kbd>, <kbd>Shift</kbd>+<kbd>Tab</kbd> или <kbd>Alt</kbd>+Символ, фокус ввода передаётся следующему/предыдущему элементу диалога (или элементу диалога, имеющему соответствующую горячую клавишу). <p>Функция обработки диалога может проследить за получением и потерей фокуса ввода. Когда элемент получает фокус ввода, функции-обработчику передаётся сообщение <a href="../dialogapi/dmsg/dn_gotfocus.html">DN_GOTFOCUS</a>. Когда элемент теряет фокус ввода, функции-обработчику передаётся сообщение <a href="../dialogapi/dmsg/dn_killfocus.html">DN_KILLFOCUS</a>. В ответ на сообщение <a href="../dialogapi/dmsg/dn_killfocus.html">DN_KILLFOCUS</a> функция обработки диалога может запретить потерю фокуса ввода, вернув значение -1. Сообщение <a href="../dialogapi/dmsg/dn_gotfocus.html">DN_GOTFOCUS</a> носит чисто информативный характер, т.е. вы не можете отменить данное событие, как таковое.</p> <p>Программный интерфейс Dialog API Far Manager содержит два сообщения, позволяющие узнать или изменить элемент, владеющий фокусом ввода. Эти сообщения имеют соответственно имена <a href="../dialogapi/dmsg/dm_getfocus.html">DM_GETFOCUS</a> и <a href="../dialogapi/dmsg/dm_setfocus.html">DM_SETFOCUS</a>. <p>Ниже перечислены элементы диалога, которые могут иметь клавиатурный фокус ввода (при условии, что для этих элементов не выставлены флаги <a href="../dialogapi/flags/dif_nofocus.html">DIF_NOFOCUS</a> и/или <a href="../dialogapi/flags/dif_disable.html">DIF_DISABLE</a>):</p> <table class="cont"> <tr class="cont"><th class="cont" width="40%">Элемент</th><th class="cont" width="60%">Описание</th></tr> <tr class="cont"><td class="cont" width="40%"><a href="../dialogapi/controls/di_button.html">DI_BUTTON</a></td> <td class="cont" width="60%">Кнопка (Push Button).</td></tr> <tr class="cont"><td class="cont" width="40%"><a href="../dialogapi/controls/di_checkbox.html">DI_CHECKBOX</a></td> <td class="cont" width="60%">Контрольный переключатель (Check Box).</td></tr> <tr class="cont"><td class="cont" width="40%"><a href="../dialogapi/controls/di_combobox.html">DI_COMBOBOX</a></td> <td class="cont" width="60%">Комбинированный список.</td></tr> <tr class="cont"><td class="cont" width="40%"><a href="../dialogapi/controls/di_edit.html">DI_EDIT</a></td> <td class="cont" width="60%">Поле ввода.</td></tr> <tr class="cont"><td class="cont" width="40%"><a href="../dialogapi/controls/di_fixedit.html">DI_FIXEDIT</a></td> <td class="cont" width="60%">Поле ввода фиксированного размера.</td></tr> <tr class="cont"><td class="cont" width="40%"><a href="../dialogapi/controls/di_listbox.html">DI_LISTBOX</a></td> <td class="cont" width="60%">Окно списка.</td></tr> <tr class="cont"><td class="cont" width="40%"><a href="../dialogapi/controls/di_pswedit.html">DI_PSWEDIT</a></td> <td class="cont" width="60%">Поле ввода пароля.</td></tr> <tr class="cont"><td class="cont" width="40%"><a href="../dialogapi/controls/di_radiobutton.html">DI_RADIOBUTTON</a></td> <td class="cont" width="60%">Селекторная кнопка (Radio Button).</td></tr> <tr class="cont"><td class="cont" width="40%"><a href="../dialogapi/controls/di_usercontrol.html">DI_USERCONTROL</a></td> <td class="cont" width="60%">Элемент управления, определяемый программистом.</td></tr> </table> </div> </body> </html>
49.490244
283
0.745404
74546666fb932b1ccc942882b77f2f6032cdb570
4,208
sql
SQL
DBMS-05-Company Database/Company-Insert Scripts.sql
001anisa/vtu-dbms-lab
b3a9516c2a7ab41dabd62a664b59614c33afd8a5
[ "MIT" ]
20
2020-12-03T13:28:44.000Z
2022-03-30T07:27:21.000Z
DBMS-05-Company Database/Company-Insert Scripts.sql
001anisa/vtu-dbms-lab
b3a9516c2a7ab41dabd62a664b59614c33afd8a5
[ "MIT" ]
1
2022-02-21T07:27:30.000Z
2022-02-21T07:28:13.000Z
DBMS-05-Company Database/Company-Insert Scripts.sql
001anisa/vtu-dbms-lab
b3a9516c2a7ab41dabd62a664b59614c33afd8a5
[ "MIT" ]
40
2020-12-04T06:56:49.000Z
2022-02-24T17:46:30.000Z
--Inserting records into EMPLOYEE table INSERT INTO EMPLOYEE (SSN, NAME, ADDRESS, SEX, SALARY) VALUES ('ABC01','BEN SCOTT','BANGALORE','M', 450000); INSERT INTO EMPLOYEE (SSN, NAME, ADDRESS, SEX, SALARY) VALUES ('ABC02','HARRY SMITH','BANGALORE','M', 500000); INSERT INTO EMPLOYEE (SSN, NAME, ADDRESS, SEX, SALARY) VALUES ('ABC03','LEAN BAKER','BANGALORE','M', 700000); INSERT INTO EMPLOYEE (SSN, NAME, ADDRESS, SEX, SALARY) VALUES ('ABC04','MARTIN SCOTT','MYSORE','M', 500000); INSERT INTO EMPLOYEE (SSN, NAME, ADDRESS, SEX, SALARY) VALUES ('ABC05','RAVAN HEGDE','MANGALORE','M', 650000); INSERT INTO EMPLOYEE (SSN, NAME, ADDRESS, SEX, SALARY) VALUES ('ABC06','GIRISH HOSUR','MYSORE','M', 450000); INSERT INTO EMPLOYEE (SSN, NAME, ADDRESS, SEX, SALARY) VALUES ('ABC07','NEELA SHARMA','BANGALORE','F', 800000); INSERT INTO EMPLOYEE (SSN, NAME, ADDRESS, SEX, SALARY) VALUES ('ABC08','ADYA KOLAR','MANGALORE','F', 350000); INSERT INTO EMPLOYEE (SSN, NAME, ADDRESS, SEX, SALARY) VALUES ('ABC09','PRASANNA KUMAR','MANGALORE','M', 300000); INSERT INTO EMPLOYEE (SSN, NAME, ADDRESS, SEX, SALARY) VALUES ('ABC10','VEENA KUMARI','MYSORE','M', 600000); INSERT INTO EMPLOYEE (SSN, NAME, ADDRESS, SEX, SALARY) VALUES ('ABC11','DEEPAK RAJ','BANGALORE','M', 500000); SELECT * FROM EMPLOYEE; ---------------------------------- --Inserting records into DEPARTMENT table INSERT INTO DEPARTMENT VALUES ('1','ACCOUNTS','ABC09', '2016-01-03'); INSERT INTO DEPARTMENT VALUES ('2','IT','ABC11', '2017-02-04'); INSERT INTO DEPARTMENT VALUES ('3','HR','ABC01', '2016-04-05'); INSERT INTO DEPARTMENT VALUES ('4','HELPDESK', 'ABC10', '2017-06-03'); INSERT INTO DEPARTMENT VALUES ('5','SALES','ABC06', '2017-01-08'); SELECT * FROM DEPARTMENT; ---------------------------------- --Updating EMPLOYEE records UPDATE EMPLOYEE SET SUPERSSN=NULL, DNO='3' WHERE SSN='ABC01'; UPDATE EMPLOYEE SET SUPERSSN='ABC03', DNO='5' WHERE SSN='ABC02'; UPDATE EMPLOYEE SET SUPERSSN='ABC04', DNO='5' WHERE SSN='ABC03'; UPDATE EMPLOYEE SET SUPERSSN='ABC06', DNO='5' WHERE SSN='ABC04'; UPDATE EMPLOYEE SET DNO='5', SUPERSSN='ABC06' WHERE SSN='ABC05'; UPDATE EMPLOYEE SET DNO='5', SUPERSSN='ABC07' WHERE SSN='ABC06'; UPDATE EMPLOYEE SET DNO='5', SUPERSSN=NULL WHERE SSN='ABC07'; UPDATE EMPLOYEE SET DNO='1', SUPERSSN='ABC09' WHERE SSN='ABC08'; UPDATE EMPLOYEE SET DNO='1', SUPERSSN=NULL WHERE SSN='ABC09'; UPDATE EMPLOYEE SET DNO='4', SUPERSSN=NULL WHERE SSN='ABC10'; UPDATE EMPLOYEE SET DNO='2', SUPERSSN=NULL WHERE SSN='ABC11'; SELECT * FROM EMPLOYEE; ------------------------------- --Inserting records into DLOCATION table INSERT INTO DLOCATION VALUES ('BENGALURU', '1'); INSERT INTO DLOCATION VALUES ('BENGALURU', '2'); INSERT INTO DLOCATION VALUES ('BENGALURU', '3'); INSERT INTO DLOCATION VALUES ('MYSORE', '4'); INSERT INTO DLOCATION VALUES ('MYSORE', '5'); SELECT * FROM DLOCATION; -------------------------------- --Inserting records into PROJECT table INSERT INTO PROJECT VALUES (1000,'IOT','BENGALURU','5'); INSERT INTO PROJECT VALUES (1001,'CLOUD','BENGALURU','5'); INSERT INTO PROJECT VALUES (1002,'BIGDATA','BENGALURU','5'); INSERT INTO PROJECT VALUES (1003,'SENSORS','BENGALURU','3'); INSERT INTO PROJECT VALUES (1004,'BANK MANAGEMENT','BENGALURU','1'); INSERT INTO PROJECT VALUES (1005,'SALARY MANAGEMENT','BANGALORE','1'); INSERT INTO PROJECT VALUES (1006,'OPENSTACK','BENGALURU','4'); INSERT INTO PROJECT VALUES (1007,'SMART CITY','BENGALURU','2'); SELECT * FROM PROJECT; ------------------------------ --Inserting records into WORKS_ON table INSERT INTO WORKS_ON VALUES (4, 'ABC02', 1000); INSERT INTO WORKS_ON VALUES (6, 'ABC02', 1001); INSERT INTO WORKS_ON VALUES (8, 'ABC02', 1002); INSERT INTO WORKS_ON VALUES (10,'ABC03', 1000); INSERT INTO WORKS_ON VALUES (3, 'ABC05', 1000); INSERT INTO WORKS_ON VALUES (4, 'ABC06', 1001); INSERT INTO WORKS_ON VALUES (5, 'ABC07', 1002); INSERT INTO WORKS_ON VALUES (6, 'ABC04', 1002); INSERT INTO WORKS_ON VALUES (7, 'ABC01', 1003); INSERT INTO WORKS_ON VALUES (5, 'ABC08', 1004); INSERT INTO WORKS_ON VALUES (6, 'ABC09', 1005); INSERT INTO WORKS_ON VALUES (4, 'ABC10', 1006); INSERT INTO WORKS_ON VALUES (10,'ABC11', 1007); SELECT * FROM WORKS_ON;
30.057143
70
0.681321
e96c47d2f50d0bf3aff2534ff6211ee34a2e95a9
3,091
kt
Kotlin
src/test/java/org/tokend/sdk/test/jsonapi/OffersModelTest.kt
TamaraGambarova/kotlin-sdk
941186aee243d0639d72e7ee189d509afc6292b9
[ "Apache-2.0" ]
null
null
null
src/test/java/org/tokend/sdk/test/jsonapi/OffersModelTest.kt
TamaraGambarova/kotlin-sdk
941186aee243d0639d72e7ee189d509afc6292b9
[ "Apache-2.0" ]
null
null
null
src/test/java/org/tokend/sdk/test/jsonapi/OffersModelTest.kt
TamaraGambarova/kotlin-sdk
941186aee243d0639d72e7ee189d509afc6292b9
[ "Apache-2.0" ]
null
null
null
package org.tokend.sdk.test.jsonapi import org.junit.Assert import org.junit.Test import org.tokend.sdk.api.generated.resources.OfferResource import org.tokend.sdk.factory.JsonApiToolsProvider class OffersModelTest { @Test fun singleOffer() { val document = JsonApiToolsProvider.getResourceConverter().readDocument( offerResponseUnincluded.toByteArray(), OfferResource::class.java ) val offer = document.get() JsonApiUtil.checkResourceNullability(offer) Assert.assertTrue(offer.isFilled()) Assert.assertNotNull(offer.baseAsset) Assert.assertNotNull(offer.quoteAsset) } private val offerResponseUnincluded = "{ \n" + " \"data\":{ \n" + " \"type\":\"offers\",\n" + " \"id\":\"10\",\n" + " \"attributes\":{ \n" + " \"order_book_id\":0,\n" + " \"fee\":{\n" + " \"fixed\": \"0.000000\",\n" + " \"calculated_percent\": \"0.000000\"\n" + " },\n" + " \"base_asset_code\":\"RTOKEN\",\n" + " \"quote_asset_code\":\"BTC\",\n" + " \"is_buy\":true,\n" + " \"base_amount\":\"1.000000\",\n" + " \"quote_amount\":\"9.000000\",\n" + " \"price\":\"9.000000\",\n" + " \"created_at\":\"2018-09-04T16:10:42Z\"\n" + " },\n" + " \"relationships\":{ \n" + " \"base_balance\":{ \n" + " \"data\":{ \n" + " \"type\":\"balances\",\n" + " \"id\":\"BDAS3BZ3CWUB56I2IVCEK3MUWGMLRSXPAEM634YHZWGKSGD7RNSZDIJT\"\n" + " }\n" + " },\n" + " \"quote_balance\":{ \n" + " \"data\":{ \n" + " \"type\":\"balances\",\n" + " \"id\":\"BCGYBQEWG3MTWFBHVPHOYTXXKWK6PW6IF3QACB7QW2KIUBU3UIJMAYXI\"\n" + " }\n" + " },\n" + " \"owner\":{ \n" + " \"data\":{ \n" + " \"type\":\"accounts\",\n" + " \"id\":\"GAULFBQKQTFHHHZEIRMYVCGTY47FKWEW7P2BY2YT45HAEODAIJUJH23T\"\n" + " }\n" + " },\n" + " \"base_asset\":{ \n" + " \"data\":{ \n" + " \"type\":\"assets\",\n" + " \"id\":\"RTOKEN\"\n" + " }\n" + " },\n" + " \"quote_asset\":{ \n" + " \"data\":{ \n" + " \"type\":\"assets\",\n" + " \"id\":\"BTC\"\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}" }
40.142857
100
0.354254
847f9c8cb8dcb85f29de080839133d8b6fd8d311
43
sql
SQL
mysql_commands/basic_table_queries/all_users.sql
mkallgren08/rpg-characters-sr
fcc33683168c57c7114416a79d53d628363bf370
[ "MIT" ]
null
null
null
mysql_commands/basic_table_queries/all_users.sql
mkallgren08/rpg-characters-sr
fcc33683168c57c7114416a79d53d628363bf370
[ "MIT" ]
null
null
null
mysql_commands/basic_table_queries/all_users.sql
mkallgren08/rpg-characters-sr
fcc33683168c57c7114416a79d53d628363bf370
[ "MIT" ]
null
null
null
USE wg5icchmkdst975b; SELECT * FROM users;
14.333333
21
0.790698
7091ad8a8911606d6b2d6d64657f89b3f4b13037
2,442
h
C
mvp_tips/CPUID/CPUID/BlockDiagram.h
allen7575/The-CPUID-Explorer
77d0feef70482b2e36cff300ea24271384329f60
[ "Naumen", "Condor-1.1", "MS-PL" ]
9
2017-08-31T06:03:18.000Z
2019-01-06T05:07:26.000Z
mvp_tips/CPUID/CPUID/BlockDiagram.h
allen7575/The-CPUID-Explorer
77d0feef70482b2e36cff300ea24271384329f60
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
mvp_tips/CPUID/CPUID/BlockDiagram.h
allen7575/The-CPUID-Explorer
77d0feef70482b2e36cff300ea24271384329f60
[ "Naumen", "Condor-1.1", "MS-PL" ]
8
2017-08-31T06:23:22.000Z
2022-01-24T06:47:19.000Z
#pragma once #include "Block.h" #include "Arrow.h" #include "CPUCoreRegion.h" #include "LogicalAddressLines.h" #include "PhysicalAddressLines.h" #include "CacheTLBInfo.h" // CBlockDiagram dialog class CBlockDiagram : public CPropertyPage { DECLARE_DYNCREATE(CBlockDiagram) public: CBlockDiagram(); virtual ~CBlockDiagram(); // Dialog Data enum { IDD = IDD_BLOCK_DIAGRAM }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support static void GetCPUID2Descriptors(CByteArray & b); void ComputeLayout(); BOOL initialized; void ComputeCacheTLBInformation(CCacheTLBInfo & ctl, const BYTE* descriptors); static BOOL QueryL3(); static BOOL QueryPrefetch(); DECLARE_MESSAGE_MAP() protected: CArrow c_PrefetchRegion; CBlock c_CPURegion; CBlock c_Gap1; CCPUCoreRegion c_CPUCoreRegion; CBlock c_Gap2; CCacheTLBInfo c_L1CacheRegion; CLogicalAddressLines c_LogicalAddressLinesRegion; CCacheTLBInfo c_TLBRegion; CCacheTLBInfo c_L2CacheRegion; CCacheTLBInfo c_L3CacheRegion; CPhysicalAddressLines c_PhysicalAddressLinesRegion; CBlock c_MemoryRegion; protected: virtual BOOL OnInitDialog(); afx_msg void OnSize(UINT nType, int cx, int cy); protected: void ComputeExtendedL1Information(CCacheTLBInfo & region); void ComputeExtendedL2Information(CCacheTLBInfo & region); void ComputeExtendedTLBInformation(CCacheTLBInfo & region); void ComputePrefetchInformation(); BOOL OnToolTipNotify(UINT id, NMHDR * pNMHDR, LRESULT * pResult); BOOL FormatExtendedTLBInfo(UINT assoc, UINT count, CString & shortDesc, UINT shortFmt, CString & longDesc, UINT longFmt); BOOL FormatL1CacheInfo(UINT CacheSize, UINT Associativity, UINT LinesPerTag, UINT LineSize, CString & LongDesc, UINT LongFmt, CString & ShortDesc, UINT ShortFmt ); BOOL FormatL2CacheInfo(UINT CacheSize, UINT Associativity, UINT LinesPerTag, UINT LineSize, CString & LongDesc, UINT LongFmt, CString & ShortDesc, UINT ShortFmt ); BOOL GetShortAssociativity(UINT assoc, CString & way); BOOL GetLongAssociativity(UINT assoc, CString & way); BOOL GetShortL2Associativity(UINT assoc, CString & way); BOOL GetLongL2Associativity(UINT assoc, CString & way); public: virtual BOOL OnSetActive(); protected: virtual void PostNcDestroy(); };
35.911765
166
0.732187
9c0e477a9b895b1253cfcaaf775a82ed239995c8
15,029
js
JavaScript
framework/src/main/webapp/js/suredy-list.js
ynbz/framework
65effc284952e9f8ab99bfffb627d7e0d10cd79f
[ "MIT" ]
null
null
null
framework/src/main/webapp/js/suredy-list.js
ynbz/framework
65effc284952e9f8ab99bfffb627d7e0d10cd79f
[ "MIT" ]
null
null
null
framework/src/main/webapp/js/suredy-list.js
ynbz/framework
65effc284952e9f8ab99bfffb627d7e0d10cd79f
[ "MIT" ]
null
null
null
/** * This is list plugin * * @author VIVID.G * @since 2015-6-30 * @version v0.1 */ // var btns = [ { // text : 'button1', // icon : 'icon-user', // style : 'btn-default', // click : function(page, pageSize, key) { // } // }, { // text : '按钮组2', // icon : 'icon-key', // style : 'btn-primary', // click : function(page, pageSize, key) { // }, // children : [ { // text : '子按钮1', // icon : 'icon-user', // click : function(page, pageSize, key) { // } // }, { // split : true // }, { // text : '子按钮2', // // icon : 'icon-key', // click : function(page, pageSize, key) { // } // } ] // } ]; (function($, window, document, undefined) { $.suredy = $.extend({}, $.suredy); var SuredyList = function($list, options) { var me = this; this.list = $list; this.options = $.extend({ header : true, footer : true, search : true, checkbox : false, title : false, searchDefaultText : '输入查询关键字', searchValue : false, searchFieldName : 'search', pageFieldName : 'page', pageSizeFieldName : 'pageSize', paginate : function(page, pageSize, key) { }, btns : [] }, options); this.page = function() { var page = me.list.data('page'); return page ? Number(page) : 1; }(); this.count = function() { var count = me.list.data('count'); return count ? Number(count) : 0; }(); this.pageSize = function() { var pageSize = me.list.data('page-size'); return pageSize ? Number(pageSize) : 25; }(); this.pages = function() { return Math.ceil(me.count / me.pageSize); }(); this.clickFunction = {}; }; SuredyList.prototype = { make : function() { var classes = this.list.attr('class'); classes = classes.replace(/suredy\-list/g, ''); // remove all classes this.list.removeClass(); // add classes this.list.addClass('suredy-list'); // wrap all column $('>tbody', this.list).children().wrapAll('<tr><td class="list-content"><table></table></td></tr>'); // add classes $('table', this.list).first().addClass(classes + ' table table-bordered table-striped table-hover margin-0 padding-0'); // make head this.makeHead(); // make footer this.makeFooter(); // make checkbox this.makeCheckbox(); var pagination = $('ul.pagination li.page-btn', this.list); // previous btn style if (pagination.first().data('page') === 1) $('ul.pagination li.previous', this.list).addClass('disabled'); // next btn style if (pagination.last().data('page') === this.pages) $('ul.pagination li.next', this.list).addClass('disabled'); // marke content row $('.list-content>table>tbody>tr', this.list).not('.title-row').not('.not-content-row').addClass('content-row'); }, makeHead : function() { if (!this.options.header) return; var header = '<tr><td height="51"><div class="row"><div class="col-md-9 col-sm-9 col-xs-12">{title}{btns}</div><div class="col-md-3 col-sm-3 col-xs-12 text-right">{search}</div></div></td></tr>'; // title header = header.replace(/\{title\}/g, this.options.title ? '<div class="btn btn-link"><h4 style="display: inline; font-weight: bold;">' + this.options.title + '</h4></div>' : ''); // btns var btns = this.makeButtons(); header = header.replace(/\{btns\}/g, btns || ''); // search var search = this.makeSearch(); header = header.replace(/\{search\}/g, search || ''); $('>tbody', this.list).prepend(header); }, makeFooter : function() { if (!this.options.footer) return; var footer = '<tr><td height="51"><div class="row"><div class="col-md-9 col-sm-9 col-xs-12">{paginal}</div><div class="col-md-3 col-sm-3 col-xs-12 text-right">{pageInfo}</div></div></td></tr>'; // paginal var paginal = this.makePaginal(); footer = footer.replace(/\{paginal\}/g, paginal || ''); // pageInfo var pageInfo = this.makePageInfo(); footer = footer.replace(/\{pageInfo\}/g, pageInfo || ''); $('>tbody', this.list).append(footer); }, makeCheckbox : function() { var trs = $('.list-content>table>tbody>tr', this.list); if (!this.options.checkbox) { trs.removeClass('checked'); return; } trs.each(function(i) { var tr = $(this); var tds = tr.children(); if (tds.length <= 0) return false; var checkbox = '<{tagName} class="text-center" width="30"><div><i class="icon-check-empty row-checkbox"></i><div></{tagName}>'; if (tr.hasClass('no-checkbox')) { checkbox = '<{tagName} class="text-center" width="30"></{tagName}>'; } var tagName = tds.get(0).tagName; // tagName checkbox = checkbox.replace(/\{tagName\}/g, tagName); tr.prepend(checkbox); }); // title row no need class: checked var titleRow = $('.list-content>table>tbody>tr.title-row', this.list); titleRow.removeClass('checked'); // relation checked if (trs.not('.title-row').length === $('.list-content>table>tbody>tr.checked', this.list).length) { $('i.row-checkbox', titleRow).removeClass('icon-check-empty').addClass('icon-check'); } else { $('i.row-checkbo', titleRow).removeClass('icon-check').addClass('icon-check-empty'); } }, makeButtons : function() { var btns = this.options.btns || []; if (!$.isArray(btns)) btns = [ btns ]; if (btns.length <= 0) return ''; var me = this; var html = ''; $(btns).each(function(i) { var data = this; if (!data) return true; if (data.children) html += me.makeButtonGroup(data); else html += me.makeButton(data); }); return html; }, makeSearch : function() { if (!this.options.search) return ''; var html = '<div class="input-group"><input type="text" class="form-control" name="{searchFieldName}" placeholder="{searchDefaultText}"{searchValue}><div class="input-group-addon btn search-btn"><i class="icon-search"></i></div></div>'; // searchFieldName html = html.replace(/\{searchFieldName\}/g, this.options.searchFieldName || ''); // searchDefaultText html = html.replace(/\{searchDefaultText\}/g, this.options.searchDefaultText || ''); // searchValue html = html.replace(/\{searchValue\}/g, this.options.searchValue ? 'value="' + this.options.searchValue + '"' : ''); return html; }, makePaginal : function() { if (this.pages <= 0) return ''; var html = '<ul class="pagination margin-0">{previous}{btns}{next}</ul>'; // previous html = html.replace(/\{previous\}/g, '<li class="previous"><a class="icon-arrow-left" href="#"></a></li>'); // btns var btns = ''; var page = Math.floor((this.page - 1) / 10) * 10 + 1; for ( var i = 0; i < 10 && page <= this.pages; i++, page++) { btns += '<li class="page-btn' + (page === this.page ? ' active' : '') + '" data-page="' + page + '"><a href="#">' + page + '</a></li>'; } html = html.replace(/\{btns\}/g, btns || ''); // next html = html.replace(/\{next\}/g, '<li class="next"><a class="icon-arrow-right" href="#"></a></li>'); return html; }, makePageInfo : function() { var html = '<div class="text-nowrap" style="margin: 10px 0;" title="共{pages}页({pageSize}条/页 - 共{count}条)">共{pages}页({pageSize}条/页 - 共{count}条)</div>'; // pages html = html.replace(/\{pages\}/g, this.pages); // pageSize html = html.replace(/\{pageSize\}/g, this.pageSize); // count html = html.replace(/\{count\}/g, this.count); return html; }, makeButton : function(data) { var html = '<div class="btn {style}" id="{id}">{icon}{text}</div>&nbsp;'; var id = ('' + Math.random()).replace('0.', ''); // click function if (data.click) this.clickFunction[id] = data.click; // style html = html.replace(/\{style\}/g, data.style || 'btn-default'); // id html = html.replace(/\{id\}/g, id); // icon html = html.replace(/\{icon\}/g, data.icon ? '<i class="' + data.icon + '">&nbsp;</i>&nbsp;' : ''); // text html = html.replace(/\{text\}/g, data.text || '自定义按钮'); return html; }, makeButtonGroup : function(data) { var me = this; var html = '<div class="btn-group"><div class="btn dropdown-toggle {style}" id="{id}" data-toggle="dropdown">{icon}{text}{caret}</div>{children}</div>&nbsp;'; var id = ('' + Math.random()).replace('0.', ''); // click function if (data.click) this.clickFunction[id] = data.click; // style html = html.replace(/\{style\}/g, data.style || 'btn-default'); // id html = html.replace(/\{id\}/g, id); // icon html = html.replace(/\{icon\}/g, data.icon ? '<i class="' + data.icon + '">&nbsp;</i>&nbsp;' : ''); // text html = html.replace(/\{text\}/g, data.text || '自定义按钮'); // caret html = html.replace(/\{caret\}/g, '&nbsp;&nbsp;<i class="icon-caret-down"></i>'); // children var children = '<ul class="dropdown-menu">{child}</ul>'; var child = ''; $(data.children).each(function(i) { if (this.split) { child += '<li class="divider"></li>'; return true; } var cid = ('' + Math.random()).replace('0.', ''); // click function if (this.click) me.clickFunction[cid] = this.click; var html = '<li id="{id}"><a href="#">{icon}{text}</a></li>'; // id html = html.replace(/\{id\}/g, cid); // icon html = html.replace(/\{icon\}/g, this.icon ? '<i class="' + this.icon + '">&nbsp;</i>&nbsp;' : ''); // text html = html.replace(/\{text\}/g, this.text || '自定义按钮'); child += html; }); children = children.replace(/\{child\}/g, child); html = html.replace(/\{children\}/g, children); return html; } }; var changePageBar = function($list, pre, currentPage, pages) { var pageBtns = $('ul.pagination li.page-btn', $list); var page = pre ? pageBtns.first().data('page') - 10 : pageBtns.last().data('page') + 1; pageBtns.addClass('animated flipOutY'); pageBtns.last().one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() { var $this = $(this); var newPageBtns = ''; for ( var i = 0; i < 10 && page <= pages; i++, page++) { newPageBtns += '<li class="page-btn' + (page === currentPage ? ' active' : '') + '" data-page="' + page + '"><a href="#">' + page + '</a></li>'; } $this.after(newPageBtns); pageBtns.remove(); $('ul.pagination li.page-btn', $list).addClass('animated flipInY'); if ($('ul.pagination li.page-btn', $list).first().data('page') === 1) $('ul.pagination li.previous', $list).addClass('disabled'); else $('ul.pagination li.previous', $list).removeClass('disabled'); if ($('ul.pagination li.page-btn', $list).last().data('page') === pages) $('ul.pagination li.next', $list).addClass('disabled'); else $('ul.pagination li.next', $list).removeClass('disabled'); }); return true; }; $.fn.list = function(options) { return this.each(function(i) { var $list = $(this); var list = new SuredyList($list, options); list.make(); // button click $('.btn', $list).on('click', function(event) { var func = list.clickFunction[$(this).attr('id')]; if (!func) return true; var searchText = $('.suredy-list input[name="' + list.options.searchFieldName + '"]').val(); func.call(this, list.page, list.pageSize, searchText); }); // button group's child click $('.btn-group li', $list).on('click', function(event) { var func = list.clickFunction[$(this).attr('id')]; if (!func) return true; var searchText = $('.suredy-list input[name="' + list.options.searchFieldName + '"]').val(); func.call(this, list.page, list.pageSize, searchText); }); // pagination btn click $('ul.pagination li.previous', $list).on('click', function(event) { var $this = $(this); if ($this.hasClass('disabled')) return true; changePageBar($list, true, list.page, list.pages); return true; }); // next btn click $('ul.pagination li.next', $list).on('click', function(event) { var $this = $(this); if ($this.hasClass('disabled')) return true; changePageBar($list, false, list.page, list.pages); return true; }); // page btn click $('ul.pagination', $list).delegate('li.page-btn', 'click', function(event) { var $this = $(this); if ($this.hasClass('active')) return true; var func = list.options.paginate; if (!func) return true; var searchText = $('.suredy-list input[name="' + list.options.searchFieldName + '"]').val(); func.call(this, $this.data('page'), list.pageSize, searchText); return true; }); // search box $('.suredy-list input[name="' + list.options.searchFieldName + '"]').on('keypress', function(event) { if (event.keyCode !== 13) return true; var func = list.options.paginate; if (!func) return true; var searchText = $(this).val(); func.call(this, list.page, list.pageSize, searchText); return true; }); // search btn $('.suredy-list .search-btn').on('click', function(event) { var func = list.options.paginate; if (!func) return true; var searchText = $('.suredy-list input[name="' + list.options.searchFieldName + '"]').val(); func.call(this, list.page, list.pageSize, searchText); return true; }); // checkbox all click $('.list-content>table>tbody>tr.title-row', $list).delegate('i.row-checkbox', 'click', function(event) { var $icon = $(this); var checked = $icon.hasClass('icon-check'); if (checked) { // make style to unchecked $('.list-content>table>tbody>tr.title-row i.row-checkbox', $list).removeClass('icon-check').addClass('icon-check-empty'); $('.list-content>table>tbody>tr.content-row.checked', $list).removeClass('checked'); } else { // make style to checked $('.list-content>table>tbody>tr.title-row i.row-checkbox', $list).removeClass('icon-check-empty').addClass('icon-check'); $('.list-content>table>tbody>tr.content-row', $list).addClass('checked'); } return false; }); // checkbox click $('.list-content>table>tbody>tr.content-row', $list).delegate('i.row-checkbox', 'click', function(event) { var $icon = $(this); var parentTr = $icon.parents('tr.content-row'); var checked = parentTr.hasClass('checked'); if (checked) { // make style to unchecked parentTr.removeClass('checked'); } else { // make style to checked parentTr.addClass('checked'); } if ($('.list-content>table>tbody>tr.content-row', $list).not('.checked').length > 0) { $('.list-content>table>tbody>tr.title-row i.row-checkbox', $list).removeClass('icon-check').addClass('icon-check-empty'); } else { $('.list-content>table>tbody>tr.title-row i.row-checkbox', $list).removeClass('icon-check-empty').addClass('icon-check'); } return false; }); }); }; $.suredy.list = { checked : function($list) { return $('tr.content-row.checked .row-checkbox', $list).parents('tr.content-row'); } }; })(jQuery, window, document);
27.677716
239
0.588462
5cc5b82263a6535f166f515fb7921f434f957895
7,809
css
CSS
public/css/master.css
ypn/livefootball
f3551b1a8e54a3c6c539f44dfdcab4596a5ccf90
[ "MIT" ]
null
null
null
public/css/master.css
ypn/livefootball
f3551b1a8e54a3c6c539f44dfdcab4596a5ccf90
[ "MIT" ]
null
null
null
public/css/master.css
ypn/livefootball
f3551b1a8e54a3c6c539f44dfdcab4596a5ccf90
[ "MIT" ]
null
null
null
@import url(https://fonts.googleapis.com/css?family=Ubuntu);body { font-family: 'Roboto', sans-serif; } .box { height: 100vh; } .red { background: #222635; } .green { background: #101117; overflow: hidden; } .green .g-content { height: 100%; overflow-y: auto; } .no-gutters { margin-right: 0; margin-left: 0; } [class^="col-"], [class*=" col-"] { padding-right: 0; padding-left: 0; } .m-nav-bar { -webkit-transition: .3s ease-in-out; transition: .3s ease-in-out; } .m-content { -webkit-transition: .3s ease-in-out; transition: .3s ease-in-out; } /*Scrollbar*/ .hero__background { position: absolute; top: 0; left: 0; width: 100%; height: 100vh; z-index: 1; } .left-size-bar { position: relative; } #wechat { width: 100%; height: 100%; } [data-canvas-image] { display: none; } /*stop*/ #left-side-bar { float: left; width: 36px; border-right: 1px solid rgba(255, 255, 255, 0.08); -webkit-transition: .5s ease-in-out; transition: .5s ease-in-out; } #content-center { float: left; width: calc(100% - 36px); -webkit-transition: .5s ease-in-out; transition: .5s ease-in-out; } .content-wrapper.collapse-left-bar #left-side-bar { width: 20%; } .content-wrapper nav { -webkit-transition: .5s ease-in-out; transition: .5s ease-in-out; width: 100%; height: 0; } .content-wrapper.collapse-left-bar nav { height: 50px; } .content-wrapper.collapse-left-bar #content-center { width: 80%; } #content-right { border-left: 1px solid rgba(255, 255, 255, 0.08); } @media (max-width: 992px) { .red { height: 50px; -webkit-transition: .3s ease-in-out; transition: .3s ease-in-out; } #wrapper.toggle .red { height: 50vh; } } @media (min-width: 992px) { #wrapper.toggle .m-nav-bar { width: 36px; } .green { height: 100vh; } #wrapper.toggle .m-content { width: calc(100% - 36px); } } .humburger-button { width: 27px; height: 35px; margin-top: 15px; margin-right: 5px; float: right; -webkit-transform: rotate(0deg); transform: rotate(0deg); -webkit-transition: .5s ease-in-out; transition: .5s ease-in-out; cursor: pointer; } .humburger-button span { display: block; position: absolute; height: 2px; width: 100%; background: #d3531a; border-radius: 2px; opacity: 1; left: 0; -webkit-transform: rotate(0deg); transform: rotate(0deg); -webkit-transition: .25s ease-in-out; transition: .25s ease-in-out; } /* Icon 4 */ #nav-icon4 span:nth-child(1) { top: 0px; -webkit-transform-origin: left center; transform-origin: left center; } #nav-icon4 span:nth-child(2) { top: 8px; -webkit-transform-origin: left center; transform-origin: left center; } #nav-icon4 span:nth-child(3) { top: 16px; -webkit-transform-origin: left center; transform-origin: left center; } #nav-icon4.open span:nth-child(1) { -webkit-transform: rotate(45deg); transform: rotate(45deg); top: 1px; left: 5px; } #nav-icon4.open span:nth-child(2) { width: 0%; opacity: 0; } #nav-icon4.open span:nth-child(3) { -webkit-transform: rotate(-45deg); transform: rotate(-45deg); top: 20px; left: 5px; } /* Shared */ .loginBtn { -webkit-box-sizing: border-box; box-sizing: border-box; position: relative; /* width: 13em; - apply for fixed size */ margin: 0.2em; padding: 0 15px 0 46px; border: none; text-align: left; line-height: 34px; white-space: nowrap; border-radius: 0.2em; font-size: 16px; color: #FFF; display: inline-block; } .loginBtn:before { content: ""; -webkit-box-sizing: border-box; box-sizing: border-box; position: absolute; top: 0; left: 0; width: 34px; height: 100%; } .loginBtn:focus { outline: none; text-decoration: none; } .loginBtn:active { -webkit-box-shadow: inset 0 0 0 32px rgba(0, 0, 0, 0.1); box-shadow: inset 0 0 0 32px rgba(0, 0, 0, 0.1); text-decoration: none; } .loginBtn:hover { text-decoration: none; } /* Facebook */ .loginBtn--facebook { background-color: #4C69BA; background-image: -webkit-gradient(linear, left top, left bottom, from(#4C69BA), to(#3B55A0)); background-image: linear-gradient(#4C69BA, #3B55A0); /*font-family: "Helvetica neue", Helvetica Neue, Helvetica, Arial, sans-serif;*/ text-shadow: 0 -1px 0 #354C8C; } .loginBtn--facebook:before { border-right: #364e92 1px solid; background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/14082/icon_facebook.png") 6px 6px no-repeat; } .loginBtn--facebook:hover, .loginBtn--facebook:focus { background-color: #5B7BD5; background-image: -webkit-gradient(linear, left top, left bottom, from(#5B7BD5), to(#4864B1)); background-image: linear-gradient(#5B7BD5, #4864B1); } /* Google */ .loginBtn--google { /*font-family: "Roboto", Roboto, arial, sans-serif;*/ background: #DD4B39; } .loginBtn--google:before { border-right: #BB3F30 1px solid; background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/14082/icon_google.png") 6px 6px no-repeat; } .loginBtn--google:hover, .loginBtn--google:focus { background: #E74B37; } .video-js .vjs-big-play-button { display: block; opacity: 0; -webkit-transform: scale(0, 0); transform: scale(0, 0); -webkit-transition: .2s ease-in-out; transition: .2s ease-in-out; border: none; background: transparent; font-size: 7em; } .video-js:hover .vjs-big-play-button, .video-js .vjs-big-play-button:focus { border: none; background: transparent; } .vjs-paused.vjs-has-started .vjs-big-play-button { opacity: 0.7; -webkit-transform: scale(1.2, 1.2); transform: scale(1.2, 1.2); -webkit-transition: .2s ease-in-out; transition: .2s ease-in-out; } .video-js button { outline: none; } .vjs-live-display { background: red; line-height: 2em; padding: 0 5px; border-radius: 6px; -webkit-transform: translateY(-50%); transform: translateY(-50%); position: relative; top: 50%; font-size: 11px; font-weight: bold; } /* Outer */ .popup { width: 100%; height: 100%; display: none; position: fixed; z-index: 9; top: 0px; left: 0px; background: rgba(0, 0, 0, 0.75); } /* Inner */ .popup-inner { max-width: 700px; width: 90%; padding: 15px; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); -webkit-box-shadow: 0px 2px 6px black; box-shadow: 0px 2px 6px black; border-radius: 3px; background: #fff; } /* Close Button */ .popup-close { width: 30px; height: 30px; padding-top: 4px; display: inline-block; position: absolute; top: 0px; right: 0px; -webkit-transition: ease 0.25s all; transition: ease 0.25s all; -webkit-transform: translate(50%, -50%); transform: translate(50%, -50%); border-radius: 1000px; background: rgba(0, 0, 0, 0.8); font-family: Arial, Sans-Serif; font-size: 20px; text-align: center; line-height: 100%; color: #fff; } .popup-close:hover { -webkit-transform: translate(50%, -50%) rotate(180deg); transform: translate(50%, -50%) rotate(180deg); background: black; text-decoration: none; } /* Outer */ .popup { background: rgba(0, 0, 0, 0.75); } /* Inner */ .popup-inner { position: absolute; top: 30%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } .pop-up-content { color: #000; } /* Close Button */ .popup-close { -webkit-transition: ease 0.25s all; transition: ease 0.25s all; -webkit-transform: translate(-50%, -50%); transform: translate(50%, -50%); } .popup-close:hover { -webkit-transform: translate(50%, -50%) rotate(180deg); transform: translate(50%, -50%) rotate(180deg); background: black; } /*Custom videojs player */ /*stop*/
18.288056
108
0.642336
9b98464aed39a67dfa86492a500d66d1e67c6993
2,104
js
JavaScript
src/objects/Craftable.js
PersonofNote/phaserjs
2783df840f031ad76e2a36719e51e9f4e93e1fc1
[ "MIT" ]
null
null
null
src/objects/Craftable.js
PersonofNote/phaserjs
2783df840f031ad76e2a36719e51e9f4e93e1fc1
[ "MIT" ]
null
null
null
src/objects/Craftable.js
PersonofNote/phaserjs
2783df840f031ad76e2a36719e51e9f4e93e1fc1
[ "MIT" ]
null
null
null
export default class Craftable extends Phaser.GameObjects.Sprite { constructor(scene, x, y, texture, frame, name, description){ super(scene, x, y, texture, frame, name, description); this.name = name; this.description = description; this.scene = scene; this.pickedUp = false; // Call update function, commented out for now //this.scene.events.on('update', (time, delta) => { this.update(time, delta)} ); //TWEENS var bounce = this.scene.tweens.createTimeline(); bounce.add({ targets: this, x: x + (50*Math.floor(Math.random()*2) == 1 ? 1 : -1), y: y + 25, ease: 'EaseOutIn', duration: 250 }); bounce.add({ targets: this, x: x + (100*Math.floor(Math.random()*2) == 1 ? 1 : -1), y: {from: y - 2, to: y}, ease: 'Bounce', duration: 150, yoyo: false }); bounce.add({ targets: this, x: x + (4*Math.floor(Math.random()*2) == 1 ? 1 : -1), y: {from: y - 2, to: y}, ease: 'Bounce', duration: 50, yoyo: false }); // METHODS scene.add.existing(this); this.setInteractive(); bounce.play(); // Toggle picked up state for theoretical non-drag movement this.on('pointerdown', () => {this.pickedUp = !this.pickedUp }, scene); this.drag = this.scene.plugins.get('rexdragplugin').add(this); this.drag.drag(); this.on('dragend', ()=> { Phaser.Math.Snap.To(this.x, 16); console.log( Phaser.Math.Snap.To(8, 16)) }, this); //Callback to snap } /* update() { if (this.pickedUp === true) { this.on('pointermove', (pointer) => {this.x = pointer.position.x; this.y = pointer.position.y}, this.scene); }else{ this.on('pointermove', (pointer) => {this.x = this.x; this.y = this.y}, this.scene); //This seems like it could get out of hand and crash the game. } } */ }
32.369231
155
0.514734
5b5c18c0b7242c700e8af15d2a9cd86266ca928e
315
asm
Assembly
programs/oeis/092/A092598.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
programs/oeis/092/A092598.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
programs/oeis/092/A092598.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
; A092598: Natural numbers n for which sum of decimal digits is greater than n/4. ; 1,2,3,4,5,6,7,8,9,13,14,15,16,17,18,19,25,26,27,28,29,37,38,39,49 mov $2,$0 add $0,5 mov $1,$0 add $1,42 mov $3,$0 mov $0,1 add $3,1 mov $4,42 sub $4,$3 lpb $0,1 sub $0,1 add $1,4 add $4,2 div $1,$4 lpe pow $1,2 add $1,$2
15
81
0.6
c112d5b2851b4dbe613c90ca458f12e1ff85d824
1,982
swift
Swift
PNRefresh/RefreshNormalHeader.swift
pszertlek/PNRefresh
fd8bc402b44e6fc8794fd20afaa5bb572174c6ec
[ "MIT" ]
null
null
null
PNRefresh/RefreshNormalHeader.swift
pszertlek/PNRefresh
fd8bc402b44e6fc8794fd20afaa5bb572174c6ec
[ "MIT" ]
null
null
null
PNRefresh/RefreshNormalHeader.swift
pszertlek/PNRefresh
fd8bc402b44e6fc8794fd20afaa5bb572174c6ec
[ "MIT" ]
null
null
null
// // RefreshNormalHeader.swift // PNRefresh // // Created by apple on 2018/3/15. // Copyright © 2018年 Pszertlek. All rights reserved. // import Foundation public class RefreshNormalHeader: RefreshHeader { var activityIndicatorViewStyle: UIActivityIndicatorViewStyle = .gray { didSet { self.setNeedsLayout() } } lazy var arrowView: UIImageView = UIImageView(image: nil) lazy var loadingView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: activityIndicatorViewStyle) override func setState(_ oldValue: RefreshState) { if state == .idle { if oldValue == .refreshing { self.arrowView.transform = CGAffineTransform.identity UIView.animate(withDuration: RefreshSlowAnimationDuration, animations: { [unowned self] in self.loadingView.alpha = 0.0 }, completion: { [unowned self] (finished) in if self.state == .idle { self.loadingView.alpha = 1.0 self.loadingView.stopAnimating() self.arrowView.isHidden = false } }) } else { self.loadingView.stopAnimating() self.arrowView.isHidden = false UIView.animate(withDuration: RefreshFastAnimationDuration, animations: { [unowned self] in self.arrowView.transform = .identity }) } } else if state == .pull { UIView.animate(withDuration: RefreshFastAnimationDuration, animations: { [unowned self] in self.arrowView.transform = CGAffineTransform(rotationAngle: CGFloat(0.000001 - Double.pi)) }) } else if state == .refreshing { self.loadingView.alpha = 1.0 self.loadingView.startAnimating() self.arrowView.isHidden = true } } }
38.115385
127
0.586781
40b41f2c0cafa1e47c1ed6bb963ba65d9a45677a
25,674
py
Python
src/pss_crew.py
herzbube/YaDc
1efec27162635c15588525013ec9f9174585fcf9
[ "Apache-2.0" ]
null
null
null
src/pss_crew.py
herzbube/YaDc
1efec27162635c15588525013ec9f9174585fcf9
[ "Apache-2.0" ]
null
null
null
src/pss_crew.py
herzbube/YaDc
1efec27162635c15588525013ec9f9174585fcf9
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: UTF-8 -*- import discord import os from typing import Dict, List, Set, Tuple from cache import PssCache import emojis import pss_assert import pss_entity as entity import pss_core as core import pss_lookups as lookups import settings import utility as util # ---------- Constants ---------- CHARACTER_DESIGN_BASE_PATH = 'CharacterService/ListAllCharacterDesigns2?languageKey=en' CHARACTER_DESIGN_KEY_NAME = 'CharacterDesignId' CHARACTER_DESIGN_DESCRIPTION_PROPERTY_NAME = 'CharacterDesignName' COLLECTION_DESIGN_BASE_PATH = 'CollectionService/ListAllCollectionDesigns?languageKey=en' COLLECTION_DESIGN_KEY_NAME = 'CollectionDesignId' COLLECTION_DESIGN_DESCRIPTION_PROPERTY_NAME = 'CollectionName' __PRESTIGE_FROM_BASE_PATH = f'CharacterService/PrestigeCharacterFrom?languagekey=en&characterDesignId=' __PRESTIGE_TO_BASE_PATH = f'CharacterService/PrestigeCharacterTo?languagekey=en&characterDesignId=' # ---------- Initilization ---------- __prestige_from_cache_dict = {} __prestige_to_cache_dict = {} # ---------- Classes ---------- class CharDesignDetails(entity.EntityDesignDetails): def __init__(self, char_design_info: dict, collections_designs_data: dict = None, level: int = None): special = _get_ability_name(char_design_info) equipment_slots = _convert_equipment_mask(int(char_design_info['EquipmentMask'])) collection_name = _get_collection_name(char_design_info, collections_designs_data) walk_speed = char_design_info['WalkingSpeed'] run_speed = char_design_info['RunSpeed'] ability = _get_stat('SpecialAbilityArgument', level, char_design_info) if special: ability += f' ({special})' self.__ability: str = ability self.__collection_name: str = collection_name self.__equipment_slots: str = equipment_slots self.__gender: str = char_design_info['GenderType'] self.__level: int = level self.__race: str = char_design_info['RaceType'] self.__rarity: str = char_design_info['Rarity'] self.__speed: str = f'{walk_speed}/{run_speed}' self.__stat_attack: str = _get_stat('Attack', level, char_design_info) self.__stat_engine: str = _get_stat('Engine', level, char_design_info) self.__stat_fire_resistance: str = char_design_info['FireResistance'] self.__stat_hp: str = _get_stat('Hp', level, char_design_info) self.__stat_pilot: str = _get_stat('Pilot', level, char_design_info) self.__stat_repair: str = _get_stat('Repair', level, char_design_info) self.__stat_science: str = _get_stat('Science', level, char_design_info) self.__stat_weapon: str = _get_stat('Weapon', level, char_design_info) self.__training_capacity: str = char_design_info['TrainingCapacity'] details_long: List[Tuple[str, str]] = [ ('Level', self.__level), ('Rarity', self.__rarity), ('Race', self.__race), ('Collection', self.__collection_name), ('Gender', self.__gender), ('Ability', self.__ability), ('HP', self.__stat_hp), ('Attack', self.__stat_attack), ('Repair', self.__stat_repair), ('Pilot', self.__stat_pilot), ('Science', self.__stat_science), ('Engine', self.__stat_engine), ('Weapon', self.__stat_weapon), ('Walk/run speed', self.__speed), ('Fire resist', self.__stat_fire_resistance), ('Training cap', self.__training_capacity), ('Slots', self.__equipment_slots) ] details_short: List[Tuple[str, str, bool]] = [ ('Rarity', self.__rarity, False), ('Ability', self.__ability, True), ('Collection', self.__collection_name, True) ] super().__init__( name=char_design_info[CHARACTER_DESIGN_DESCRIPTION_PROPERTY_NAME], description=char_design_info['CharacterDesignDescription'], details_long=details_long, details_short=details_short ) @property def ability(self) -> str: return self.__ability @property def attack(self) -> str: return self.__stat_attack @property def collection_name(self) -> str: return self.__collection_name @property def engine(self) -> str: return self.__stat_engine @property def equipment_slots(self) -> str: return self.__equipment_slots @property def fire_resistance(self) -> str: return self.__stat_fire_resistance @property def gender(self) -> str: return self.__gender @property def hp(self) -> str: return self.__stat_hp @property def level(self) -> int: return self.__level @property def pilot(self) -> str: return self.__stat_pilot @property def race(self) -> str: return self.__race @property def rarity(self) -> str: return self.__rarity @property def repair(self) -> str: return self.__stat_repair @property def science(self) -> str: return self.__stat_science @property def speed(self) -> str: return self.__speed @property def training_capacity(self) -> str: return self.__training_capacity @property def weapon(self) -> str: return self.__stat_weapon class CollectionDesignDetails(entity.EntityDesignDetails): def __init__(self, collection_design_info: dict): collection_crew = _get_collection_chars_designs_infos(collection_design_info) collection_perk = collection_design_info['EnhancementType'] collection_perk = lookups.COLLECTION_PERK_LOOKUP.get(collection_design_info['EnhancementType'], collection_design_info['EnhancementType']) min_combo = collection_design_info['MinCombo'] max_combo = collection_design_info['MaxCombo'] base_enhancement_value = collection_design_info['BaseEnhancementValue'] step_enhancement_value = collection_design_info['StepEnhancementValue'] self.__characters: str = ', '.join(collection_crew) self.__min_max_combo = f'{min_combo}...{max_combo}' self.__enhancement = f'{base_enhancement_value} (Base), {step_enhancement_value} (Step)' details_long: List[Tuple[str, str]] = [ ('Combo Min...Max', self.__min_max_combo), (collection_perk, self.__enhancement), ('Characters', self.__characters) ] details_short: List[Tuple[str, str, bool]] = [ ] super().__init__( name=collection_design_info[COLLECTION_DESIGN_DESCRIPTION_PROPERTY_NAME], description=collection_design_info['CollectionDescription'], details_long=details_long, details_short=details_short, hyperlink='https://pixelstarships.fandom.com/wiki/Category:Crew_Collections' ) @property def characters(self) -> str: return self.__characters @property def min_max_combo(self) -> str: return self.__min_max_combo @property def enhancement(self) -> str: return self.__enhancement class PrestigeDetails(entity.EntityDesignDetails): def __init__(self, char_design_info: dict, prestige_infos: Dict[str, List[str]], error_message: str, title_template: str, sub_title_template: str): self.__char_design_name: str = char_design_info[CHARACTER_DESIGN_DESCRIPTION_PROPERTY_NAME] self.__count: int = sum([len(prestige_partners) for prestige_partners in prestige_infos.values()]) self.__error: str = error_message self.__prestige_infos: Dict[str, List[str]] = prestige_infos self.__title_template: str = title_template or '**$char_design_name$** has **$count$** combinations:' self.__sub_title_template: str = sub_title_template or '**$char_design_name$**:' @property def char_design_name(self) -> str: return self.__char_design_name @property def count(self) -> int: return self.__count @property def error(self) -> str: return self.__error @property def prestige_infos(self) -> Dict[str, List[str]]: return self.__prestige_infos @property def title(self) -> str: result = self.__title_template result = result.replace('$char_design_name$', self.char_design_name) result = result.replace('$count$', str(self.count)) return result def get_details_as_embed(self) -> discord.Embed: return None def get_details_as_text_long(self) -> List[str]: result = [self.title] if self.error: result.append(self.error) else: for char_design_name in sorted(list(self.prestige_infos.keys())): prestige_partners = sorted(self.prestige_infos[char_design_name]) result.append(self._get_sub_title(char_design_name)) result.append(f'> {", ".join(prestige_partners)}') return result def get_details_as_text_short(self) -> List[str]: return self.get_details_as_text_long() def _get_sub_title(self, char_design_name: str) -> str: result = self.__sub_title_template.replace('$char_design_name$', char_design_name) return result class PrestigeFromDetails(PrestigeDetails): def __init__(self, char_from_design_info: dict, chars_designs_data: dict = None, prestige_from_data: dict = None): chars_designs_data = chars_designs_data or character_designs_retriever.get_data_dict3() error = None prestige_infos = {} template_title = '**$char_design_name$** has **$count$** prestige combinations:' template_subtitle = 'To **$char_design_name$** with:' if prestige_from_data: for value in prestige_from_data.values(): char_info_2_name = chars_designs_data[value['CharacterDesignId2']][CHARACTER_DESIGN_DESCRIPTION_PROPERTY_NAME] char_info_to_name = chars_designs_data[value['ToCharacterDesignId']][CHARACTER_DESIGN_DESCRIPTION_PROPERTY_NAME] prestige_infos.setdefault(char_info_to_name, []).append(char_info_2_name) else: if char_from_design_info['Rarity'] == 'Special': error = 'One cannot prestige **Special** crew.' elif char_from_design_info['Rarity'] == 'Legendary': error = 'One cannot prestige **Legendary** crew.' else: error = 'noone' super().__init__(char_from_design_info, prestige_infos, error, template_title, template_subtitle) class PrestigeToDetails(PrestigeDetails): def __init__(self, char_to_design_info: dict, chars_designs_data: dict = None, prestige_to_data: dict = None): chars_designs_data = chars_designs_data or character_designs_retriever.get_data_dict3() error = None prestige_infos = {} template_title = '**$char_design_name$** has **$count$** prestige recipes:' template_subtitle = '**$char_design_name$** with:' if prestige_to_data: prestige_recipes: Dict[str, Set[str]] = {} for value in prestige_to_data.values(): char_1_design_name = chars_designs_data[value['CharacterDesignId1']][CHARACTER_DESIGN_DESCRIPTION_PROPERTY_NAME] char_2_design_name = chars_designs_data[value['CharacterDesignId2']][CHARACTER_DESIGN_DESCRIPTION_PROPERTY_NAME] prestige_recipes.setdefault(char_1_design_name, set()).add(char_2_design_name) prestige_recipes.setdefault(char_2_design_name, set()).add(char_1_design_name) prestige_recipe_ingredients: List[Tuple[str, Set[str]]] = [(char_design_name, prestige_partners) for char_design_name, prestige_partners in prestige_recipes.items()] prestige_infos: Dict[str, List[str]] = {} while prestige_recipe_ingredients: prestige_recipe_ingredients = sorted(prestige_recipe_ingredients, key=lambda t: len(t[1]), reverse=True) (char_design_name, prestige_partners) = prestige_recipe_ingredients[0] prestige_infos[char_design_name] = list(prestige_partners) prestige_recipe_ingredients = PrestigeToDetails._update_prestige_recipe_ingredients(prestige_recipe_ingredients) else: if char_to_design_info['Rarity'] == 'Special': error = 'One cannot prestige to **Special** crew.' elif char_to_design_info['Rarity'] == 'Common': error = 'One cannot prestige to **Common** crew.' else: error = 'noone' super().__init__(char_to_design_info, prestige_infos, error, template_title, template_subtitle) @staticmethod def _update_prestige_recipe_ingredients(prestige_recipe_ingredients: List[Tuple[str, Set[str]]]) -> List[Tuple[str, Set[str]]]: result: List[Tuple[str, Set[str]]] = [] # Take 1st char name & prestige partners # Remove that pair from the result # Iterate through (base_char_design_name, base_prestige_partners) = prestige_recipe_ingredients[0] for (char_design_name, prestige_partners) in prestige_recipe_ingredients[1:]: if base_char_design_name in prestige_partners and char_design_name in base_prestige_partners: prestige_partners = [x for x in prestige_partners if x != base_char_design_name] if prestige_partners: result.append((char_design_name, prestige_partners)) return result # ---------- Helper functions ---------- def _convert_equipment_mask(equipment_mask: int) -> str: result = [] for k in lookups.EQUIPMENT_MASK_LOOKUP.keys(): if (equipment_mask & k) != 0: result.append(lookups.EQUIPMENT_MASK_LOOKUP[k]) if result: return ', '.join(result) else: return '-' def _get_ability_name(char_design_info: dict) -> str: if char_design_info: special = char_design_info['SpecialAbilityType'] if special in lookups.SPECIAL_ABILITIES_LOOKUP.keys(): return lookups.SPECIAL_ABILITIES_LOOKUP[special] return None def _get_collection_chars_designs_infos(collection_design_info: Dict[str, str]) -> list: collection_id = collection_design_info[COLLECTION_DESIGN_KEY_NAME] chars_designs_data = character_designs_retriever.get_data_dict3() chars_designs_infos = [chars_designs_data[char_id] for char_id in chars_designs_data.keys() if chars_designs_data[char_id][COLLECTION_DESIGN_KEY_NAME] == collection_id] result = [char_design_info[CHARACTER_DESIGN_DESCRIPTION_PROPERTY_NAME] for char_design_info in chars_designs_infos] result.sort() return result def _get_collection_name(char_design_info: dict, collections_designs_data: dict = None) -> str: if char_design_info: collection_id = char_design_info[COLLECTION_DESIGN_KEY_NAME] if collection_id and collection_id != '0': collection_design_info = collection_designs_retriever.get_entity_design_info_by_id(collection_id) return collection_design_info[COLLECTION_DESIGN_DESCRIPTION_PROPERTY_NAME] return None def _get_stat(stat_name: str, level: int, char_design_info: dict) -> str: is_special_stat = stat_name.lower().startswith('specialability') if is_special_stat: max_stat_name = 'SpecialAbilityFinalArgument' else: max_stat_name = f'Final{stat_name}' min_value = float(char_design_info[stat_name]) max_value = float(char_design_info[max_stat_name]) progression_type = char_design_info['ProgressionType'] result = _get_stat_value(min_value, max_value, level, progression_type) return result def _get_stat_value(min_value: float, max_value: float, level: int, progression_type: str) -> str: if level is None or level < 1 or level > 40: return f'{min_value:0.1f} - {max_value:0.1f}' else: return f'{_calculate_stat_value(min_value, max_value, level, progression_type):0.1f}' def _calculate_stat_value(min_value: float, max_value: float, level: int, progression_type: str) -> float: exponent = lookups.PROGRESSION_TYPES[progression_type] result = min_value + (max_value - min_value) * ((level - 1) / 39) ** exponent return result # ---------- Crew info ---------- def get_char_design_details_by_id(char_design_id: str, level: int, chars_designs_data: dict = None, collections_designs_data: dict = None) -> CharDesignDetails: if char_design_id: if chars_designs_data is None: chars_designs_data = character_designs_retriever.get_data_dict3() if char_design_id and char_design_id in chars_designs_data.keys(): char_design_info = chars_designs_data[char_design_id] char_design_details = CharDesignDetails(char_design_info, collections_designs_data=collections_designs_data, level=level) return char_design_details return None def get_char_design_details_by_name(char_name: str, level: int, as_embed: bool = settings.USE_EMBEDS): pss_assert.valid_entity_name(char_name, 'char_name') pss_assert.parameter_is_valid_integer(level, 'level', min_value=1, max_value=40, allow_none=True) char_design_info = character_designs_retriever.get_entity_design_info_by_name(char_name) if char_design_info is None: return [f'Could not find a crew named **{char_name}**.'], False else: char_design_details = CharDesignDetails(char_design_info, level=level) if as_embed: return char_design_details.get_details_as_embed(), True else: return char_design_details.get_details_as_text_long(), True # ---------- Collection Info ---------- def get_collection_design_details_by_name(collection_name: str, as_embed: bool = settings.USE_EMBEDS): pss_assert.valid_entity_name(collection_name) collection_design_info = collection_designs_retriever.get_entity_design_info_by_name(collection_name) if collection_design_info is None: return [f'Could not find a collection named **{collection_name}**.'], False else: collection_design_details = CollectionDesignDetails(collection_design_info) if as_embed: return collection_design_details.get_details_as_embed(), True else: return collection_design_details.get_details_as_text_long(), True # ---------- Prestige from Info ---------- def get_prestige_from_info(char_name: str, as_embed: bool = settings.USE_EMBEDS): pss_assert.valid_entity_name(char_name) chars_designs_data = character_designs_retriever.get_data_dict3() char_from_design_info = character_designs_retriever.get_entity_design_info_by_name(char_name, entity_designs_data=chars_designs_data) if not char_from_design_info: return [f'Could not find a crew named **{char_name}**.'], False else: prestige_from_data = _get_prestige_from_data(char_from_design_info) prestige_from_details = PrestigeFromDetails(char_from_design_info, chars_designs_data=chars_designs_data, prestige_from_data=prestige_from_data) if as_embed: return prestige_from_details.get_details_as_embed(), True else: return prestige_from_details.get_details_as_text_long(), True def _get_prestige_from_data(char_design_info: dict) -> dict: if not char_design_info: return {} char_design_id = char_design_info[CHARACTER_DESIGN_KEY_NAME] if char_design_id in __prestige_from_cache_dict.keys(): prestige_from_cache = __prestige_from_cache_dict[char_design_id] else: prestige_from_cache = _create_and_add_prestige_from_cache(char_design_id) return prestige_from_cache.get_data_dict3() def _create_and_add_prestige_from_cache(char_design_id: str) -> PssCache: cache = _create_prestige_from_cache(char_design_id) __prestige_from_cache_dict[char_design_id] = cache return cache def _create_prestige_from_cache(char_design_id: str) -> PssCache: url = f'{__PRESTIGE_FROM_BASE_PATH}{char_design_id}' name = f'PrestigeFrom{char_design_id}' result = PssCache(url, name, None) return result # ---------- Prestige to Info ---------- def get_prestige_to_info(char_name: str, as_embed: bool = settings.USE_EMBEDS): pss_assert.valid_entity_name(char_name) chars_designs_data = character_designs_retriever.get_data_dict3() char_to_design_info = character_designs_retriever.get_entity_design_info_by_name(char_name, entity_designs_data=chars_designs_data) if not char_to_design_info: return [f'Could not find a crew named **{char_name}**.'], False else: prestige_to_data = _get_prestige_to_data(char_to_design_info) prestige_to_details = PrestigeToDetails(char_to_design_info, chars_designs_data=chars_designs_data, prestige_to_data=prestige_to_data) if as_embed: return prestige_to_details.get_details_as_embed(), True else: return prestige_to_details.get_details_as_text_long(), True def _get_prestige_to_data(char_design_info: dict) -> dict: if not char_design_info: return {} char_design_id = char_design_info[CHARACTER_DESIGN_KEY_NAME] if char_design_id in __prestige_to_cache_dict.keys(): prestige_to_cache = __prestige_to_cache_dict[char_design_id] else: prestige_to_cache = _create_and_add_prestige_to_cache(char_design_id) return prestige_to_cache.get_data_dict3() def _create_and_add_prestige_to_cache(char_design_id: str) -> PssCache: cache = _create_prestige_to_cache(char_design_id) __prestige_to_cache_dict[char_design_id] = cache return cache def _create_prestige_to_cache(char_design_id: str) -> PssCache: url = f'{__PRESTIGE_TO_BASE_PATH}{char_design_id}' name = f'PrestigeTo{char_design_id}' result = PssCache(url, name, None) return result # ---------- Level Info ---------- def get_level_costs(from_level: int, to_level: int = None) -> list: # If to_level: assert that to_level > from_level and <= 41 # Else: swap both, set from_level = 1 if to_level: pss_assert.parameter_is_valid_integer(from_level, 'from_level', 1, to_level - 1) pss_assert.parameter_is_valid_integer(to_level, 'to_level', from_level + 1, 40) else: pss_assert.parameter_is_valid_integer(from_level, 'from_level', 2, 40) to_level = from_level from_level = 1 crew_costs = _get_crew_costs(from_level, to_level, lookups.GAS_COSTS_LOOKUP, lookups.XP_COSTS_LOOKUP) legendary_crew_costs = _get_crew_costs(from_level, to_level, lookups.GAS_COSTS_LEGENDARY_LOOKUP, lookups.XP_COSTS_LEGENDARY_LOOKUP) crew_cost_txt = _get_crew_cost_txt(from_level, to_level, crew_costs) legendary_crew_cost_txt = _get_crew_cost_txt(from_level, to_level, legendary_crew_costs) result = ['**Level costs** (non-legendary crew, max research)'] result.extend(crew_cost_txt) result.append(settings.EMPTY_LINE) result.append('**Level costs** (legendary crew, max research)') result.extend(legendary_crew_cost_txt) return result, True def _get_crew_costs(from_level: int, to_level: int, gas_costs_lookup: list, xp_cost_lookup: list) -> (int, int, int, int): gas_cost = gas_costs_lookup[to_level - 1] xp_cost = xp_cost_lookup[to_level - 1] gas_cost_from = sum(gas_costs_lookup[from_level:to_level]) xp_cost_from = sum(xp_cost_lookup[from_level:to_level]) if from_level > 1: return (None, None, gas_cost_from, xp_cost_from) else: return (gas_cost, xp_cost, gas_cost_from, xp_cost_from) def _get_crew_cost_txt(from_level: int, to_level: int, costs: tuple) -> list: result = [] if from_level == 1: result.append(f'Getting from level {to_level - 1:d} to {to_level:d} requires {costs[1]:,} {emojis.pss_stat_xp} and {costs[0]:,}{emojis.pss_gas_big}.') result.append(f'Getting from level {from_level:d} to {to_level:d} requires {costs[3]:,} {emojis.pss_stat_xp} and {costs[2]:,}{emojis.pss_gas_big}.') return result # ---------- Initilization ---------- character_designs_retriever = entity.EntityDesignsRetriever( CHARACTER_DESIGN_BASE_PATH, CHARACTER_DESIGN_KEY_NAME, CHARACTER_DESIGN_DESCRIPTION_PROPERTY_NAME, cache_name='CharacterDesigns' ) collection_designs_retriever = entity.EntityDesignsRetriever( COLLECTION_DESIGN_BASE_PATH, COLLECTION_DESIGN_KEY_NAME, COLLECTION_DESIGN_DESCRIPTION_PROPERTY_NAME, cache_name='CollectionDesigns' ) # Get stat for level: # - get exponent 'p' by ProgressionType: # - Linear: p = 1.0 # - EaseIn: p = 2.0 # - EaseOut: p = 0.5 # - get min stat 'min' & max stat 'max' # result = min + (max - min) * ((level - 1) / 39) ** p # ---------- Testing ---------- if __name__ == '__main__': f = get_level_costs(20, 30) test_crew = [('alpaco', 5)] for (crew_name, level) in test_crew: os.system('clear') result = get_char_design_details_by_name(crew_name, level, as_embed=False) for line in result[0]: print(line) print('') result = get_prestige_from_info(crew_name, as_embed=False) for line in result[0]: print(line) print('') result = get_prestige_to_info(crew_name, as_embed=False) for line in result[0]: print(line) print('') result = ''
34.095618
177
0.697554
291864a9f70adccb40c2460cf98f86ea4e0f1e74
21,425
py
Python
trove/tests/fakes/swift.py
ISCAS-VDI/trove-base
6a13b8771f8c9f259577e79d12355f9142964169
[ "Apache-2.0" ]
null
null
null
trove/tests/fakes/swift.py
ISCAS-VDI/trove-base
6a13b8771f8c9f259577e79d12355f9142964169
[ "Apache-2.0" ]
null
null
null
trove/tests/fakes/swift.py
ISCAS-VDI/trove-base
6a13b8771f8c9f259577e79d12355f9142964169
[ "Apache-2.0" ]
null
null
null
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P. # 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. from hashlib import md5 from mock import MagicMock, patch import json import os import socket import swiftclient import swiftclient.client as swift_client import uuid from oslo_log import log as logging from six.moves import http_client from swiftclient import client as swift from trove.common.i18n import _ # noqa LOG = logging.getLogger(__name__) class FakeSwiftClient(object): """Logs calls instead of executing.""" def __init__(self, *args, **kwargs): pass @classmethod def Connection(self, *args, **kargs): LOG.debug("fake FakeSwiftClient Connection") return FakeSwiftConnection() class FakeSwiftConnection(object): """Logging calls instead of executing.""" MANIFEST_QUERY_STRING_PUT = 'multipart-manifest=put' MANIFEST_QUERY_STRING_DELETE = 'multipart-manifest=delete' COPY_OBJECT_HEADER_KEY = 'X-Copy-From' url = 'http://mockswift/v1' def __init__(self, *args, **kwargs): self.manifest_prefix = None self.manifest_name = None self.container_objects = {} def get_auth(self): return ( u"http://127.0.0.1:8080/v1/AUTH_c7b038976df24d96bf1980f5da17bd89", u'MIINrwYJKoZIhvcNAQcCoIINoDCCDZwCAQExCTAHBgUrDgMCGjCCDIgGCSqGSIb3' u'DQEHAaCCDHkEggx1eyJhY2Nlc3MiOiB7InRva2VuIjogeyJpc3N1ZWRfYXQiOiAi' u'MjAxMy0wMy0xOFQxODoxMzoyMC41OTMyNzYiLCAiZXhwaXJlcyI6ICIyMDEzLTAz' u'LTE5VDE4OjEzOjIwWiIsICJpZCI6ICJwbGFjZWhvbGRlciIsICJ0ZW5hbnQiOiB7' u'ImVuYWJsZWQiOiB0cnVlLCAiZGVzY3JpcHRpb24iOiBudWxsLCAibmFtZSI6ICJy' u'ZWRkd2FyZiIsICJpZCI6ICJjN2IwMzg5NzZkZjI0ZDk2YmYxOTgwZjVkYTE3YmQ4' u'OSJ9fSwgInNlcnZpY2VDYXRhbG9nIjogW3siZW5kcG9pbnRzIjogW3siYWRtaW5') def get_account(self): return ({'content-length': '2', 'accept-ranges': 'bytes', 'x-timestamp': '1363049003.92304', 'x-trans-id': 'tx9e5da02c49ed496395008309c8032a53', 'date': 'Tue, 10 Mar 2013 00:43:23 GMT', 'x-account-bytes-used': '0', 'x-account-container-count': '0', 'content-type': 'application/json; charset=utf-8', 'x-account-object-count': '0'}, []) def head_container(self, container): LOG.debug("fake head_container(%s)" % container) if container == 'missing_container': raise swift.ClientException('fake exception', http_status=http_client.NOT_FOUND) elif container == 'unauthorized_container': raise swift.ClientException('fake exception', http_status=http_client.UNAUTHORIZED) elif container == 'socket_error_on_head': raise socket.error(111, 'ECONNREFUSED') pass def put_container(self, container): LOG.debug("fake put_container(%s)" % container) pass def get_container(self, container, **kwargs): LOG.debug("fake get_container(%s)" % container) fake_header = None fake_body = [{'name': 'backup_001'}, {'name': 'backup_002'}, {'name': 'backup_003'}] return fake_header, fake_body def head_object(self, container, name): LOG.debug("fake put_container(%(container)s, %(name)s)" % {'container': container, 'name': name}) checksum = md5() if self.manifest_name == name: for object_name in sorted(self.container_objects): object_checksum = md5(self.container_objects[object_name]) # The manifest file etag for a HEAD or GET is the checksum of # the concatenated checksums. checksum.update(object_checksum.hexdigest()) # this is included to test bad swift segment etags if name.startswith("bad_manifest_etag_"): return {'etag': '"this_is_an_intentional_bad_manifest_etag"'} else: if name in self.container_objects: checksum.update(self.container_objects[name]) else: return {'etag': 'fake-md5-sum'} # Currently a swift HEAD object returns etag with double quotes return {'etag': '"%s"' % checksum.hexdigest()} def get_object(self, container, name, resp_chunk_size=None): LOG.debug("fake get_object(%(container)s, %(name)s)" % {'container': container, 'name': name}) if container == 'socket_error_on_get': raise socket.error(111, 'ECONNREFUSED') if 'metadata' in name: fake_object_header = None metadata = {} if container == 'unsupported_version': metadata['version'] = '9.9.9' else: metadata['version'] = '1.0.0' metadata['backup_id'] = 123 metadata['volume_id'] = 123 metadata['backup_name'] = 'fake backup' metadata['backup_description'] = 'fake backup description' metadata['created_at'] = '2013-02-19 11:20:54,805' metadata['objects'] = [{ 'backup_001': {'compression': 'zlib', 'length': 10}, 'backup_002': {'compression': 'zlib', 'length': 10}, 'backup_003': {'compression': 'zlib', 'length': 10} }] metadata_json = json.dumps(metadata, sort_keys=True, indent=2) fake_object_body = metadata_json return (fake_object_header, fake_object_body) fake_header = {'etag': '"fake-md5-sum"'} if resp_chunk_size: def _object_info(): length = 0 while length < (1024 * 1024): yield os.urandom(resp_chunk_size) length += resp_chunk_size fake_object_body = _object_info() else: fake_object_body = os.urandom(1024 * 1024) return (fake_header, fake_object_body) def put_object(self, container, name, contents, **kwargs): LOG.debug("fake put_object(%(container)s, %(name)s)" % {'container': container, 'name': name}) if container == 'socket_error_on_put': raise socket.error(111, 'ECONNREFUSED') headers = kwargs.get('headers', {}) query_string = kwargs.get('query_string', '') object_checksum = md5() if query_string == self.MANIFEST_QUERY_STRING_PUT: # the manifest prefix format is <container>/<prefix> where # container is where the object segments are in and prefix is the # common prefix for all segments. self.manifest_name = name object_checksum.update(contents) elif self.COPY_OBJECT_HEADER_KEY in headers: # this is a copy object operation source_path = headers.get(self.COPY_OBJECT_HEADER_KEY) source_name = source_path.split('/')[1] self.container_objects[name] = self.container_objects[source_name] else: if hasattr(contents, 'read'): chunk_size = 128 object_content = "" chunk = contents.read(chunk_size) while chunk: object_content += chunk object_checksum.update(chunk) chunk = contents.read(chunk_size) self.container_objects[name] = object_content else: object_checksum.update(contents) self.container_objects[name] = contents # this is included to test bad swift segment etags if name.startswith("bad_segment_etag_"): return "this_is_an_intentional_bad_segment_etag" return object_checksum.hexdigest() def post_object(self, container, name, headers={}): LOG.debug("fake post_object(%(container)s, %(name)s, %(head)s)" % {'container': container, 'name': name, 'head': str(headers)}) def delete_object(self, container, name): LOG.debug("fake delete_object(%(container)s, %(name)s)" % {'container': container, 'name': name}) if container == 'socket_error_on_delete': raise socket.error(111, 'ECONNREFUSED') pass class Patcher(object): """Objects that need to mock global symbols throughout their existence should extend this base class. The object acts as a context manager which, when used in conjunction with the 'with' statement, terminates all running patchers when it leaves the scope. """ def __init__(self): self.__patchers = None def __enter__(self): self.__patchers = [] return self def __exit__(self, type, value, traceback): # Stop patchers in the LIFO order. while self.__patchers: self.__patchers.pop().stop() def _start_patcher(self, patcher): """All patchers started by this method will be automatically terminated on __exit__(). """ self.__patchers.append(patcher) return patcher.start() class SwiftClientStub(Patcher): """ Component for controlling behavior of Swift Client Stub. Instantiated before tests are invoked in "fake" mode. Invoke methods to control behavior so that systems under test can interact with this as it is a real swift client with a real backend example: if FAKE: swift_stub = SwiftClientStub() swift_stub.with_account('xyz') # returns swift account info and auth token component_using_swift.get_swift_account() if FAKE: swift_stub.with_container('test-container-name') # returns swift container information - mostly faked component_using.swift.create_container('test-container-name') component_using_swift.get_container_info('test-container-name') if FAKE: swift_stub.with_object('test-container-name', 'test-object-name', 'test-object-contents') # returns swift object info and contents component_using_swift.create_object('test-container-name', 'test-object-name', 'test-contents') component_using_swift.get_object('test-container-name', 'test-object-name') if FAKE: swift_stub.without_object('test-container-name', 'test-object-name') # allows object to be removed ONCE component_using_swift.remove_object('test-container-name', 'test-object-name') # throws ClientException - 404 component_using_swift.get_object('test-container-name', 'test-object-name') component_using_swift.remove_object('test-container-name', 'test-object-name') if FAKE: swift_stub.without_object('test-container-name', 'test-object-name') # allows container to be removed ONCE component_using_swift.remove_container('test-container-name') # throws ClientException - 404 component_using_swift.get_container('test-container-name') component_using_swift.remove_container('test-container-name') """ def __init__(self): super(SwiftClientStub, self).__init__() self._connection = swift_client.Connection() self._containers = {} self._containers_list = [] self._objects = {} def _remove_object(self, name, some_list): idx = [i for i, obj in enumerate(some_list) if obj['name'] == name] if len(idx) == 1: del some_list[idx[0]] def _ensure_object_exists(self, container, name): self._connection.get_object(container, name) def with_account(self, account_id): """ setups up account headers example: if FAKE: swift_stub = SwiftClientStub() swift_stub.with_account('xyz') # returns swift account info and auth token component_using_swift.get_swift_account() :param account_id: account id """ def account_resp(): return ({'content-length': '2', 'accept-ranges': 'bytes', 'x-timestamp': '1363049003.92304', 'x-trans-id': 'tx9e5da02c49ed496395008309c8032a53', 'date': 'Tue, 10 Mar 2013 00:43:23 GMT', 'x-account-bytes-used': '0', 'x-account-container-count': '0', 'content-type': 'application/json; charset=utf-8', 'x-account-object-count': '0'}, self._containers_list) get_auth_return_value = ( u"http://127.0.0.1:8080/v1/AUTH_c7b038976df24d96bf1980f5da17bd89", u'MIINrwYJKoZIhvcNAQcCoIINoDCCDZwCAQExCTAHBgUrDgMCGjCCDIgGCSqGSIb3' u'DQEHAaCCDHkEggx1eyJhY2Nlc3MiOiB7InRva2VuIjogeyJpc3N1ZWRfYXQiOiAi' u'MjAxMy0wMy0xOFQxODoxMzoyMC41OTMyNzYiLCAiZXhwaXJlcyI6ICIyMDEzLTAz' u'LTE5VDE4OjEzOjIwWiIsICJpZCI6ICJwbGFjZWhvbGRlciIsICJ0ZW5hbnQiOiB7' u'ImVuYWJsZWQiOiB0cnVlLCAiZGVzY3JpcHRpb24iOiBudWxsLCAibmFtZSI6ICJy' u'ZWRkd2FyZiIsICJpZCI6ICJjN2IwMzg5NzZkZjI0ZDk2YmYxOTgwZjVkYTE3YmQ4' u'OSJ9fSwgInNlcnZpY2VDYXRhbG9nIjogW3siZW5kcG9pbnRzIjogW3siYWRtaW5') get_auth_patcher = patch.object( swift_client.Connection, 'get_auth', MagicMock(return_value=get_auth_return_value)) self._start_patcher(get_auth_patcher) get_account_patcher = patch.object( swift_client.Connection, 'get_account', MagicMock(return_value=account_resp())) self._start_patcher(get_account_patcher) return self def _create_container(self, container_name): container = {'count': 0, 'bytes': 0, 'name': container_name} self._containers[container_name] = container self._containers_list.append(container) self._objects[container_name] = [] def _ensure_container_exists(self, container): self._connection.get_container(container) def _delete_container(self, container): self._remove_object(container, self._containers_list) del self._containers[container] del self._objects[container] def with_container(self, container_name): """ sets expectations for creating a container and subsequently getting its information example: if FAKE: swift_stub.with_container('test-container-name') # returns swift container information - mostly faked component_using.swift.create_container('test-container-name') component_using_swift.get_container_info('test-container-name') :param container_name: container name that is expected to be created """ def container_resp(container): return ({'content-length': '2', 'x-container-object-count': '0', 'accept-ranges': 'bytes', 'x-container-bytes-used': '0', 'x-timestamp': '1363370869.72356', 'x-trans-id': 'tx7731801ac6ec4e5f8f7da61cde46bed7', 'date': 'Fri, 10 Mar 2013 18:07:58 GMT', 'content-type': 'application/json; charset=utf-8'}, self._objects[container]) # if this is called multiple times then nothing happens put_container_patcher = patch.object(swift_client.Connection, 'put_container') self._start_patcher(put_container_patcher) def side_effect_func(*args, **kwargs): if args[0] in self._containers: return container_resp(args[0]) else: raise swiftclient.ClientException('Resource Not Found', http_status=404) self._create_container(container_name) # return container headers get_container_patcher = patch.object( swift_client.Connection, 'get_container', MagicMock(side_effect=side_effect_func)) self._start_patcher(get_container_patcher) return self def without_container(self, container): """ sets expectations for removing a container and subsequently throwing an exception for further interactions example: if FAKE: swift_stub.without_container('test-container-name') # returns swift container information - mostly faked component_using.swift.remove_container('test-container-name') # throws exception "Resource Not Found - 404" component_using_swift.get_container_info('test-container-name') :param container: container name that is expected to be removed """ # first ensure container self._ensure_container_exists(container) self._delete_container(container) return self def with_object(self, container, name, contents): """ sets expectations for creating an object and subsequently getting its contents example: if FAKE: swift_stub.with_object('test-container-name', 'test-object-name', 'test-object-contents') # returns swift object info and contents component_using_swift.create_object('test-container-name', 'test-object-name', 'test-contents') component_using_swift.get_object('test-container-name', 'test-object-name') :param container: container name that is the object belongs :param name: the name of the object expected to be created :param contents: the contents of the object """ put_object_patcher = patch.object( swift_client.Connection, 'put_object', MagicMock(return_value=uuid.uuid1())) self._start_patcher(put_object_patcher) def side_effect_func(*args, **kwargs): if (args[0] in self._containers and args[1] in map(lambda x: x['name'], self._objects[args[0]])): return ( {'content-length': len(contents), 'accept-ranges': 'bytes', 'last-modified': 'Mon, 10 Mar 2013 01:06:34 GMT', 'etag': 'eb15a6874ce265e2c3eb1b4891567bab', 'x-timestamp': '1363568794.67584', 'x-trans-id': 'txef3aaf26c897420c8e77c9750ce6a501', 'date': 'Mon, 10 Mar 2013 05:35:14 GMT', 'content-type': 'application/octet-stream'}, [obj for obj in self._objects[args[0]] if obj['name'] == args[1]][0]['contents']) else: raise swiftclient.ClientException('Resource Not Found', http_status=404) get_object_patcher = patch.object( swift_client.Connection, 'get_object', MagicMock(side_effect=side_effect_func)) self._start_patcher(get_object_patcher) self._remove_object(name, self._objects[container]) self._objects[container].append( {'bytes': 13, 'last_modified': '2013-03-15T22:10:49.361950', 'hash': 'ccc55aefbf92aa66f42b638802c5e7f6', 'name': name, 'content_type': 'application/octet-stream', 'contents': contents}) return self def without_object(self, container, name): """ sets expectations for deleting an object example: if FAKE: swift_stub.without_object('test-container-name', 'test-object-name') # allows container to be removed ONCE component_using_swift.remove_container('test-container-name') # throws ClientException - 404 component_using_swift.get_container('test-container-name') component_using_swift.remove_container('test-container-name') :param container: container name that is the object belongs :param name: the name of the object expected to be removed """ self._ensure_container_exists(container) self._ensure_object_exists(container, name) def side_effect_func(*args, **kwargs): if not [obj for obj in self._objects[args[0]] if obj['name'] == [args[1]]]: raise swiftclient.ClientException('Resource Not found', http_status=404) else: return None delete_object_patcher = patch.object( swift_client.Connection, 'delete_object', MagicMock(side_effect=side_effect_func)) self._start_patcher(delete_object_patcher) self._remove_object(name, self._objects[container]) return self def fake_create_swift_client(calculate_etag=False, *args): return FakeSwiftClient.Connection(*args)
39.897579
79
0.625624
b2cf11ab3d7e9318bb55599575d25a729b83ace2
319
py
Python
mayan/apps/dependencies/permissions.py
CMU-313/fall-2021-hw2-451-unavailable-for-legal-reasons
0e4e919fd2e1ded6711354a0330135283e87f8c7
[ "Apache-2.0" ]
2
2021-09-12T19:41:19.000Z
2021-09-12T19:41:20.000Z
mayan/apps/dependencies/permissions.py
CMU-313/fall-2021-hw2-451-unavailable-for-legal-reasons
0e4e919fd2e1ded6711354a0330135283e87f8c7
[ "Apache-2.0" ]
37
2021-09-13T01:00:12.000Z
2021-10-02T03:54:30.000Z
mayan/apps/dependencies/permissions.py
CMU-313/fall-2021-hw2-451-unavailable-for-legal-reasons
0e4e919fd2e1ded6711354a0330135283e87f8c7
[ "Apache-2.0" ]
1
2021-09-22T13:17:30.000Z
2021-09-22T13:17:30.000Z
from django.utils.translation import ugettext_lazy as _ from mayan.apps.permissions import PermissionNamespace namespace = PermissionNamespace(label=_('Dependencies'), name='dependencies') permission_dependencies_view = namespace.add_permission( label=_('View dependencies'), name='dependencies_view' )
31.9
78
0.793103
857b57a76f7b09469d84979c778cf9d5bb62a9a0
770
js
JavaScript
lib/datastore.js
sjlu/deploy
3a37b87a9cd30dd41b25283b7949b9fec91d6abb
[ "MIT" ]
2
2015-10-09T17:30:37.000Z
2015-10-09T18:59:33.000Z
lib/datastore.js
sjlu/deploy
3a37b87a9cd30dd41b25283b7949b9fec91d6abb
[ "MIT" ]
null
null
null
lib/datastore.js
sjlu/deploy
3a37b87a9cd30dd41b25283b7949b9fec91d6abb
[ "MIT" ]
1
2015-10-09T17:18:58.000Z
2015-10-09T17:18:58.000Z
var Promise = require('bluebird') var Datastore = require('nedb') Promise.promisifyAll(Datastore.prototype); var path = require('path') var Promise = require('bluebird') var _ = require('lodash') var ds = {} ds.repos = new Datastore({ filename: path.join(__dirname, '../.data/repos.db'), autoload: true }) ds.repos.ensureIndex({ fieldName: 'id', unique: true }); ds.builds = new Datastore({ filename: path.join(__dirname, '../.data/builds.db'), autoload: true }) ds.repos.ensureIndex({ fieldName: '_id', unique: true }); ds.deploys = new Datastore({ filename: path.join(__dirname, '../.data/deploys.db'), autoload: true }) ds.signoffs = new Datastore({ filename: path.join(__dirname, '../.data/signoffs.db'), autoload: true }) module.exports = ds
22.647059
57
0.680519
7db66b2f6735faf28f2bf708e49067e1cfa1a30d
1,867
asm
Assembly
lib/trs80_crt0.asm
grancier/z180
e83f35e36c9b4d1457e40585019430e901c86ed9
[ "ClArtistic" ]
null
null
null
lib/trs80_crt0.asm
grancier/z180
e83f35e36c9b4d1457e40585019430e901c86ed9
[ "ClArtistic" ]
null
null
null
lib/trs80_crt0.asm
grancier/z180
e83f35e36c9b4d1457e40585019430e901c86ed9
[ "ClArtistic" ]
1
2019-12-03T23:57:48.000Z
2019-12-03T23:57:48.000Z
; TRS 80 Program boot ; ; Stefano Bodrato 2008 ; ; $Id: trs80_crt0.asm,v 1.21 2016/07/15 21:03:25 dom Exp $ ; MODULE trs80_crt0 ;-------- ; Include zcc_opt.def to find out some info ;-------- defc crt0 = 1 INCLUDE "zcc_opt.def" ;-------- ; Some scope definitions ;-------- EXTERN _main ;main() is always external to crt0 code PUBLIC cleanup ;jp'd to by exit() PUBLIC l_dcal ;jp(hl) ;-------- ; Set an origin for the application (-zorg=) default to $5200 ;-------- IF !DEFINED_CRT_ORG_CODE IF (startup=2) defc CRT_ORG_CODE = 22500 ELSE defc CRT_ORG_CODE = $5200 ENDIF ENDIF org CRT_ORG_CODE start: ld (start1+1),sp ;Save entry stack IF STACKPTR ld sp,STACKPTR ENDIF ld hl,-64 add hl,sp ld sp,hl call crt0_init_bss ld (exitsp),sp ; Optional definition for auto MALLOC init ; it assumes we have free space between the end of ; the compiled program and the stack pointer IF DEFINED_USING_amalloc INCLUDE "amalloc.def" ENDIF call _main ;Call user program cleanup: ; ; Deallocate memory which has been allocated here! ; IF !DEFINED_nostreams EXTERN closeall call closeall ENDIF cleanup_exit: start1: ld sp,0 ;Restore stack to entry value ret l_dcal: jp (hl) ;Used for function pointer calls defm "Small C+ TRS80" ;Unnecessary file signature defb 0 INCLUDE "crt0_runtime_selection.asm" INCLUDE "crt0_section.asm" SECTION code_crt_init IF (startup=2) ld hl,$4800 ; Address of the Graphics map COLOUR GENIE ELSE ld hl,$3c00 ; Address of the Graphics map ENDIF ld (base_graphics),hl
19.247423
73
0.58436
849e9d3cbf590721c0fe851104c8416dbce19692
3,844
kt
Kotlin
app/src/main/java/com/roshastudio/roshastu/utils/edittextValid.kt
sepandd97/Roshastu
1f840c763e4be909afcb6af98d52b5542de43e09
[ "MIT" ]
null
null
null
app/src/main/java/com/roshastudio/roshastu/utils/edittextValid.kt
sepandd97/Roshastu
1f840c763e4be909afcb6af98d52b5542de43e09
[ "MIT" ]
null
null
null
app/src/main/java/com/roshastudio/roshastu/utils/edittextValid.kt
sepandd97/Roshastu
1f840c763e4be909afcb6af98d52b5542de43e09
[ "MIT" ]
null
null
null
package com.roshastudio.roshastu.utils import android.text.Editable import android.text.TextWatcher import android.util.Patterns import androidx.databinding.BindingAdapter import kotlin.properties.Delegates object edittextValid { var name: String? = null var regstatus = false var status = false var mobilststus: Boolean = false var namestatus: Boolean = false var emailstatus: Boolean = false var pasststus: Boolean = false var login: Boolean = true var regester: Boolean = false fun getstatusserver(servrr: Boolean) { login = servrr } @BindingAdapter(value = ["app:typeed", "app:edterror"], requireAll = true) @JvmStatic fun error( edt: com.google.android.material.textfield.TextInputLayout, typeed: String?, edterror: String? ) { var edtt = edt.editText edtt!!.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged( s: CharSequence?, start: Int, count: Int, after: Int ) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { when (typeed) { "mobile" -> { if (s.isNullOrEmpty()) { mobilststus = false edt.error = "خالی نباشد" } else if (s.length in 11..12) { mobilststus = true edt.error = null } else if (s.length !in 11..12) { mobilststus = false edt.error = "تعداد صحیح نیست" } } "pass" -> { if (s.isNullOrEmpty()) { pasststus = false edt.error = "خالی " } else if (s.length < 5) { pasststus = false edt.error = "کوتاه است" } else if (name.equals(s.toString())) { pasststus = false edt.error = "نام و پسورد یکی نباشد" } else if (s.length > 5) { pasststus = true edt.error = null } } "name" -> { if (s.isNullOrEmpty()) { namestatus = false edt.error = "خالی " } else { name = s.toString() namestatus = true edt.error = null } } "email" -> { if (!Patterns.EMAIL_ADDRESS.matcher(s).matches()) { emailstatus = false edt.error = "فرمت ایمیل اشتباه است" } else if (s.isNullOrEmpty()) { emailstatus = false edt.error = "خالی " } else { emailstatus = true edt.error = null } } } status = pasststus == true && mobilststus == true regstatus = emailstatus == true && status == true && namestatus == true } override fun afterTextChanged(s: Editable?) { if (login == false && status == true) { edt.error = "رمز یا پسورد اشتباه است" } } }) } }
31.252033
95
0.403226
dddeb8608bde592332acc22f10ed9aede75cc362
4,309
php
PHP
app/scope/UserWechat.php
hunzsig/phpure
98e00292f19089a9002e16112b62ddf6b759ca36
[ "MIT" ]
1
2019-05-29T09:13:36.000Z
2019-05-29T09:13:36.000Z
app/scope/UserWechat.php
hunzsig/phpure
98e00292f19089a9002e16112b62ddf6b759ca36
[ "MIT" ]
null
null
null
app/scope/UserWechat.php
hunzsig/phpure
98e00292f19089a9002e16112b62ddf6b759ca36
[ "MIT" ]
null
null
null
<?php namespace App\Scope; use Yonna\Database\DB; use Yonna\Foundation\Str; use Yonna\Log\Log; use App\Helper\Assets; use App\Mapping\User\AccountType; use App\Mapping\User\UserStatus; use Yonna\Throwable\Exception; use Yonna\Validator\ArrayValidator; /** * Class UserWechat * @package App\Scope */ class UserWechat extends AbstractScope { /** * @return mixed * @throws Exception\ThrowException */ public function bind() { ArrayValidator::required($this->input(), ['phone'], function ($error) { Exception::throw($error); }); $openid = $this->request()->getLoggingId(); if (!is_string($openid)) { Exception::throw('openid error'); } $checkOpenId = $this->scope(UserAccount::class, 'one', ['string' => $openid]); if ($checkOpenId) { Exception::throw('openid already bind'); } $sdk = $this->scope(SdkWxmpUser::class, 'one', ['openid' => $openid]); if (!$sdk) { Exception::throw('wechat user is not authenticated'); } $phone = $this->input('phone'); $metas = $this->input('metas'); $licenses = $this->input('licenses'); // 合并一下从微信获得的数据,如果用户有自定义则跳过 if (empty($metas['sex']) && !empty($sdk['sdk_wxmp_user_sex'])) { $metas['sex'] = (int)$sdk['sdk_wxmp_user_sex']; } if (empty($metas['name']) && !empty($sdk['sdk_wxmp_user_nickname'])) { $metas['name'] = $sdk['sdk_wxmp_user_nickname']; } if (empty($metas['avatar']) && !empty($sdk['sdk_wxmp_user_headimgurl'])) { $src = Assets::getUrlSource($sdk['sdk_wxmp_user_headimgurl']); if ($src) { $res = (new Xoss($this->request()))->saveFile($src); if ($res) { $metas['avatar'] = $res['xoss_key']; } } } if (!is_array($metas['avatar'])) { $metas['avatar'] = [$metas['avatar']]; } $user_id = DB::transTrace(function () use ($phone, $openid, $metas, $licenses) { $find = $this->scope(UserAccount::class, 'one', ['string' => $phone]); $user_id = $find['user_account_user_id'] ?? null; // 有数据则绑定原有账号,没数据则新建账号 if ($user_id) { // 更新数据 $data = [ 'id' => $user_id, 'metas' => $metas, ]; $this->scope(User::class, 'update', $data); // 许可判定 if ($licenses) { foreach ($licenses as $l) { $this->scope(UserLicense::class, 'insert', [ 'user_id' => $user_id, 'license_id' => $l, ]); } } } else { $data = [ 'password' => Str::randomLetter(10), 'accounts' => [$phone => AccountType::PHONE], 'licenses' => $licenses, 'metas' => $metas, 'status' => UserStatus::APPROVED, ]; $user_id = $this->scope(User::class, 'insert', $data); } // 记录openid $this->scope(UserAccount::class, 'insert', [ 'user_id' => $user_id, 'string' => $openid, 'type' => AccountType::WX_OPEN_ID, ]); return $user_id; }); // 写日志 $input = $this->input(); $log = [ 'user_id' => $user_id, 'ip' => $this->request()->getIp(), 'client_id' => $this->request()->getClientId(), 'input' => $input, ]; Log::db()->info($log, 'login-bind'); // 设定client_id为登录状态 $onlineKey = UserLogin::ONLINE_REDIS_KEY . $log['client_id']; $onlineId = DB::redis()->get($onlineKey); $onlineId = (int)$onlineId; if ($onlineId > 0) { DB::redis()->expire($onlineKey, UserLogin::ONLINE_KEEP_TIME); } else { DB::redis()->set($onlineKey, $user_id, UserLogin::ONLINE_KEEP_TIME); } return $this->scope(User::class, 'one', ['id' => $user_id]); } }
34.75
88
0.467626
c425aa8f9707f863b42ba5039ad76021ec15987a
3,644
c
C
src/main.c
pierresaid/nbody-simulation
99094f9285208d551bd2266d3c421f18be77d5d7
[ "MIT" ]
null
null
null
src/main.c
pierresaid/nbody-simulation
99094f9285208d551bd2266d3c421f18be77d5d7
[ "MIT" ]
null
null
null
src/main.c
pierresaid/nbody-simulation
99094f9285208d551bd2266d3c421f18be77d5d7
[ "MIT" ]
null
null
null
#include <math.h> #include "../include/setup.h" #include "../include/data.h" //#include <GL/glut.h> //#include <GL/freeglut.h> size_t globalWorkSize[] = {1, 0, 0}; cl_command_queue queue; cl_kernel kernel; s_data data; cl_mem bodies_buffer; int paused = 0; void process(); void display() { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1, 1, 1); glPointSize(1); glBegin(GL_POINTS); int i = 0; while (i < data.config.nb_bodies) { glVertex2i(data.bodies[i].x, data.bodies[i].y); ++i; } glEnd(); glFlush(); } const double s_soft = 1000000; const float gravity = 0.66742; void process() { if (paused == 0) { // int i = 0; // while (i < data.config.nb_bodies) { // data.bodies[i].x += data.bodies[i].speed_x; // data.bodies[i].y += data.bodies[i].speed_y; // ++i; // } clEnqueueWriteBuffer(queue, bodies_buffer, CL_TRUE, 0, sizeof(s_body) * data.config.nb_bodies, data.bodies, 0, NULL, NULL); cl_int err = clSetKernelArg(kernel, 0, sizeof(cl_mem), &bodies_buffer); err = clSetKernelArg(kernel, 1, sizeof(int), &data.config.nb_bodies); if (err != CL_SUCCESS) { printf("Set Arg error : %d\n", err); exit(0); } clEnqueueNDRangeKernel(queue, kernel, 1, NULL, globalWorkSize, NULL, 0, NULL, NULL); clFlush(queue); clFinish(queue); clEnqueueReadBuffer(queue, bodies_buffer, CL_TRUE, 0, sizeof(s_body) * data.config.nb_bodies, data.bodies, 0, NULL, NULL); glutPostRedisplay(); } glutTimerFunc(1000 / 60, process, 0); } void keyboardCB(int key, int x, int y) { switch (key) { case GLUT_KEY_F1: glutLeaveMainLoop(); case GLUT_KEY_F2: paused = paused == 0 ? 1 : 0; return; } glutPostRedisplay(); } void setup_opengl(s_config *config) { int argc = 1; char *argv[1] = {(char *) "Something"}; glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE); glutInitWindowSize(1920, 1080); glutCreateWindow("nbody-simulator"); glutSpecialFunc(keyboardCB); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, config->map_size, 0.0, config->map_size); } int main(int argc, char **argv) { cl_program program; cl_context context; data.config.nb_bodies = 7000; globalWorkSize[0] = (size_t) data.config.nb_bodies; data.config.map_size = 100000; create_program(&program, &context, &kernel, &queue); setup_opengl(&data.config); data.bodies = setup_bodies(&data.config); data.bodies[0].x = data.config.map_size - (4 * (data.config.map_size / 10)); data.bodies[0].y = data.config.map_size - (4 * (data.config.map_size / 10)); data.bodies[0].mass = 1300000000; data.bodies[0].speed_x = 0; data.bodies[0].speed_y = 0; bodies_buffer = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(s_body) * (data.config.nb_bodies), data.bodies, NULL); glutDisplayFunc(display); process(); glutMainLoop(); clReleaseKernel(kernel); clReleaseProgram(program); clReleaseCommandQueue(queue); clReleaseContext(context); }
26.794118
118
0.560099
83b71e9456035e4d92297d05578ee6e22c3700ae
1,837
swift
Swift
SwellAR/Particle Simulation/WeatherMap.swift
alexandergovoni/SwellAR
e479e139ab2b32606af645fa757701da3c01963e
[ "BSD-3-Clause" ]
null
null
null
SwellAR/Particle Simulation/WeatherMap.swift
alexandergovoni/SwellAR
e479e139ab2b32606af645fa757701da3c01963e
[ "BSD-3-Clause" ]
null
null
null
SwellAR/Particle Simulation/WeatherMap.swift
alexandergovoni/SwellAR
e479e139ab2b32606af645fa757701da3c01963e
[ "BSD-3-Clause" ]
2
2018-11-06T14:11:47.000Z
2019-04-15T12:30:13.000Z
// Copyright © 2018 Refrakt <info@refrakt.org> // All rights reserved. // // This source code is licensed under the BSD 3-Clause license found in the // LICENSE file in the root directory of this source tree. import Foundation /// A particle simulation of actual ocean currents. /// /// Based on https://github.com/mapbox/webgl-wind /// class WeatherMap { let particleScreen: ParticleScreen let plane: SimplePlane let maskTexture: GLuint struct Config: Codable { let mapWidth: Int let mapHeight: Int let fadeOpacity: Float let colorFactor: Float let speedFactor: Float let dropRate: Float let dropRateBump: Float let resolution: Int let colors: [HexColor] } init(config: Config, oceanCurrents: OceanCurrents, maskTexture: GLuint) { let particleState = ParticleState(resolution: config.resolution, oceanCurrents: oceanCurrents) particleState.speedFactor = config.speedFactor particleState.dropRate = config.dropRate particleState.dropRateBump = config.dropRateBump let colors = config.colors.map{$0.uiColor.cgColor} let colorRamp = ColorRamp(colors: colors) particleScreen = ParticleScreen(width: config.mapWidth, height: config.mapHeight, particleState: particleState, colorRamp: colorRamp) particleScreen.colorFactor = config.colorFactor particleScreen.fadeOpacity = config.fadeOpacity self.plane = SimplePlane(width: config.mapWidth, height: config.mapHeight) self.maskTexture = maskTexture } func render(on target: ARViewController.Target) { particleScreen.particleState.update() particleScreen.draw() plane.render(texture: particleScreen.texture, mask: maskTexture, on: target) } }
35.326923
141
0.692433
ec171db6b01a096f14075e3c1959a890397072be
5,413
kt
Kotlin
jetbrains-core/src/software/aws/toolkits/jetbrains/ui/AsyncComboBox.kt
drakejin/aws-toolkit-jetbrains
fec0dbb39f5dfabf2f3abc617805c2a592bd3714
[ "Apache-2.0" ]
610
2018-09-18T17:15:44.000Z
2022-03-02T11:29:45.000Z
jetbrains-core/src/software/aws/toolkits/jetbrains/ui/AsyncComboBox.kt
drakejin/aws-toolkit-jetbrains
fec0dbb39f5dfabf2f3abc617805c2a592bd3714
[ "Apache-2.0" ]
2,639
2018-09-18T17:16:42.000Z
2022-03-29T14:06:05.000Z
jetbrains-core/src/software/aws/toolkits/jetbrains/ui/AsyncComboBox.kt
drakejin/aws-toolkit-jetbrains
fec0dbb39f5dfabf2f3abc617805c2a592bd3714
[ "Apache-2.0" ]
142
2018-09-18T17:27:00.000Z
2022-03-05T21:00:52.000Z
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.ui import com.intellij.openapi.Disposable import com.intellij.openapi.application.ModalityState import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.ui.ComboBox import com.intellij.ui.AnimatedIcon import com.intellij.ui.SimpleListCellRenderer import com.intellij.util.Alarm import com.intellij.util.AlarmFactory import kotlinx.coroutines.launch import org.jetbrains.annotations.TestOnly import org.jetbrains.concurrency.AsyncPromise import software.aws.toolkits.jetbrains.core.coroutines.disposableCoroutineScope import software.aws.toolkits.jetbrains.utils.ui.selected import java.awt.Component import java.util.concurrent.Future import java.util.concurrent.atomic.AtomicBoolean import javax.swing.DefaultComboBoxModel import javax.swing.JList import javax.swing.MutableComboBoxModel import javax.swing.event.ListDataListener class AsyncComboBox<T>( private val comboBoxModel: MutableComboBoxModel<T> = DefaultComboBoxModel(), customizer: SimpleListCellRenderer.Customizer<in T>? = null ) : ComboBox<T>(comboBoxModel), Disposable { private val loading = AtomicBoolean(false) private val scope = disposableCoroutineScope(this) init { renderer = object : SimpleListCellRenderer<T>() { override fun getListCellRendererComponent( list: JList<out T>?, value: T?, index: Int, selected: Boolean, hasFocus: Boolean ): Component { val component = super.getListCellRendererComponent(list, value, index, selected, hasFocus) as SimpleListCellRenderer<*> if (loading.get() && index == -1) { component.icon = AnimatedIcon.Default.INSTANCE component.text = "Loading" } return component } override fun customize(list: JList<out T>, value: T, index: Int, selected: Boolean, hasFocus: Boolean) { customizer?.customize(this, value, index) } } } private val reloadAlarm = AlarmFactory.getInstance().create(Alarm.ThreadToUse.SWING_THREAD, this) private var currentIndicator: ProgressIndicator? = null @Synchronized fun proposeModelUpdate(newModel: suspend (MutableComboBoxModel<T>) -> Unit) { reloadAlarm.cancelAllRequests() currentIndicator?.cancel() loading.set(true) removeAllItems() val indicator = EmptyProgressIndicator(ModalityState.NON_MODAL).also { currentIndicator = it } // delay with magic number to debounce reloadAlarm.addRequest( { ProgressManager.getInstance().runProcess( { scope.launch { newModel.invoke(delegatedComboBoxModel(indicator)) indicator.checkCanceled() loading.set(false) repaint() } }, indicator ) }, 350 ) } override fun dispose() { } override fun getSelectedItem(): Any? { if (loading.get()) { return null } return super.getSelectedItem() } @TestOnly @Synchronized internal fun waitForSelection(): Future<T?> { val future = AsyncPromise<T>() while (loading.get()) { Thread.onSpinWait() } future.setResult(selected()) return future } override fun setSelectedItem(anObject: Any?) { if (loading.get()) { return } super.setSelectedItem(anObject) } private fun delegatedComboBoxModel(indicator: ProgressIndicator) = object : MutableComboBoxModel<T> { override fun getSize() = comboBoxModel.size override fun getElementAt(index: Int): T = comboBoxModel.getElementAt(index) override fun addListDataListener(l: ListDataListener?) { throw NotImplementedError() } override fun removeListDataListener(l: ListDataListener?) { throw NotImplementedError() } override fun setSelectedItem(anItem: Any?) { comboBoxModel.selectedItem = anItem } override fun getSelectedItem(): Any = comboBoxModel.selectedItem override fun addElement(item: T?) { indicator.checkCanceled() comboBoxModel.addElement(item) } override fun removeElement(obj: Any?) { indicator.checkCanceled() comboBoxModel.removeElement(item) } override fun insertElementAt(item: T?, index: Int) { indicator.checkCanceled() comboBoxModel.insertElementAt(item, index) } override fun removeElementAt(index: Int) { indicator.checkCanceled() comboBoxModel.removeElementAt(index) } } }
33.83125
135
0.61537
0bb8618a64cd74cacaa43f4d1d49f5d2a220b49c
1,189
js
JavaScript
js/ChessBox.js
bubblecigar/chicken
c9136928e0ae6a03d58ddd4e929e647bbfa5ed3c
[ "MIT" ]
null
null
null
js/ChessBox.js
bubblecigar/chicken
c9136928e0ae6a03d58ddd4e929e647bbfa5ed3c
[ "MIT" ]
null
null
null
js/ChessBox.js
bubblecigar/chicken
c9136928e0ae6a03d58ddd4e929e647bbfa5ed3c
[ "MIT" ]
null
null
null
import React from 'react' import styled from 'styled-components' import { GlobalContext } from './app' import Chess from './Chess' const ChessBoxStyle = styled.div` margin: 20px; position: relative; width: calc(50% - 40px); background: white; animation-name: ${props => props.inTurn ? 'bordering' : ''}; animation-duration: 1s; animation-direction: alternate; animation-iteration-count: infinite; @keyframes bordering { from { transform: translateY(0) } to { transform: translateY(-15px) } } ` const ChessGroup = styled.div` display: flex; flex-wrap: wrap; ` const Chessbox = ({ color }) => { const { gameObject } = React.useContext(GlobalContext) return gameObject ? ( <ChessBoxStyle className="nes-container with-title" inTurn={gameObject.status === color}> <p className="title">{gameObject[`${color}Player`] ? gameObject[`${color}Player`].userName : '*'}</p> <ChessGroup> { gameObject.chess.filter(c => c.color === color).map( (c, i) => <Chess key={i} i={i} chess={c} at={null} /> ) } </ChessGroup> </ChessBoxStyle> ) : null } export default Chessbox
25.847826
107
0.624054
883bed4fdc63f6454fea3b958283244c287b8dfc
8,388
kt
Kotlin
app/src/main/kotlin/de/uni_marburg/mathematik/ds/serval/utils/Utils.kt
Thames1990/aardvark
9cb9c7de4a6075f800e84a612a07c8e2efaa5c1a
[ "MIT" ]
null
null
null
app/src/main/kotlin/de/uni_marburg/mathematik/ds/serval/utils/Utils.kt
Thames1990/aardvark
9cb9c7de4a6075f800e84a612a07c8e2efaa5c1a
[ "MIT" ]
null
null
null
app/src/main/kotlin/de/uni_marburg/mathematik/ds/serval/utils/Utils.kt
Thames1990/aardvark
9cb9c7de4a6075f800e84a612a07c8e2efaa5c1a
[ "MIT" ]
null
null
null
package de.uni_marburg.mathematik.ds.serval.utils import android.annotation.SuppressLint import android.arch.lifecycle.LifecycleOwner import android.arch.lifecycle.LiveData import android.arch.lifecycle.Observer import android.content.Context import android.location.Address import android.support.constraint.ConstraintSet import android.support.design.internal.SnackbarContentLayout import android.support.design.widget.AppBarLayout import android.support.design.widget.Snackbar import android.support.v4.view.ViewPager import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import ca.allanwang.kau.utils.* import com.afollestad.materialdialogs.MaterialDialog import com.crashlytics.android.answers.Answers import com.crashlytics.android.answers.CustomEvent import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.BitmapDescriptor import com.google.android.gms.maps.model.BitmapDescriptorFactory import com.google.android.gms.maps.model.MapStyleOptions import com.mikepenz.community_material_typeface_library.CommunityMaterial import com.mikepenz.iconics.IconicsDrawable import de.uni_marburg.mathematik.ds.serval.Aardvark import de.uni_marburg.mathematik.ds.serval.R import de.uni_marburg.mathematik.ds.serval.model.Event import de.uni_marburg.mathematik.ds.serval.settings.AppearancePrefs import de.uni_marburg.mathematik.ds.serval.settings.BehaviourPrefs import de.uni_marburg.mathematik.ds.serval.settings.BehaviourPrefs.animationsEnabled import de.uni_marburg.mathematik.ds.serval.settings.ExperimentalPrefs import de.uni_marburg.mathematik.ds.serval.settings.MapPrefs import net.sharewire.googlemapsclustering.Cluster import net.sharewire.googlemapsclustering.ClusterManager import net.sharewire.googlemapsclustering.IconGenerator import org.jetbrains.anko.bundleOf import java.time.Instant import java.util.* import java.util.concurrent.TimeUnit inline val analyticsAreEnabled: Boolean get() = BehaviourPrefs.analyticsEnabled inline val animationsAreEnabled: Boolean get() = BehaviourPrefs.animationsEnabled inline val currentTimeInMillis: Long @SuppressLint("NewApi") get() = if (buildIsOreoAndUp) Instant.now().toEpochMilli() else Calendar.getInstance().timeInMillis inline val currentTimeInSeconds: Long @SuppressLint("NewApi") get() = if (buildIsOreoAndUp) Instant.now().epochSecond else Calendar.getInstance()[Calendar.SECOND].toLong() inline val experimentalSettingsAreEnabled: Boolean get() = ExperimentalPrefs.enabled inline val Cluster<Event>.sizeText: String get() { val eventCount: Int = items.size return if (MapPrefs.showExactClusterSize) eventCount.toString() else when (eventCount) { in 0 until 10 -> eventCount.toString() in 10 until 50 -> "10+" in 50 until 100 -> "50+" in 100 until 250 -> "100+" in 250 until 500 -> "250+" in 500 until 1000 -> "500+" else -> "1000+" } } inline val List<Address>.mostProbableAddressLine: String get() = first() .getAddressLine(0) .replace(oldValue = "unnamed road, ", newValue = "", ignoreCase = true) .replace(oldValue = ", ", newValue = "\n") inline var ViewPager.item get() = currentItem set(value) = setCurrentItem(value, animationsEnabled) operator fun ViewGroup.get(position: Int): View = getChildAt(position) /** * Create Fabric Answers instance. */ inline fun answers(action: Answers.() -> Unit) = Answers.getInstance().action() inline fun doOnDebugBuild(block: () -> Unit) { if (isDebugBuild) block() } /** * Log custom events to analytics services. */ fun logAnalytics(name: String, vararg events: Pair<String, Any>) { if (analyticsAreEnabled) { answers { logCustom(CustomEvent(name).apply { events.forEach { (key: String, value: Any) -> if (value is Number) putCustomAttribute(key, value) else putCustomAttribute(key, value.toString()) } }) } events.forEach { (key: String, value: Any) -> Aardvark.firebaseAnalytics.logEvent(name, bundleOf(key to value)) } } } /** * Create themed snackbar. */ @SuppressLint("RestrictedApi") inline fun snackbarThemed(crossinline builder: Snackbar.() -> Unit): Snackbar.() -> Unit = { builder() val snackbarBaseLayout = view as FrameLayout val snackbarContentLayout = snackbarBaseLayout[0] as SnackbarContentLayout snackbarContentLayout.apply { messageView.setTextColor(AppearancePrefs.Theme.textColor) actionView.setTextColor(AppearancePrefs.Theme.accentColor) //only set if previous text colors are set view.setBackgroundColor( AppearancePrefs.Theme.backgroundColor.withAlpha(255).colorToForeground(0.1f) ) } } fun styledMarker(context: Context): BitmapDescriptor = BitmapDescriptorFactory.fromBitmap( IconicsDrawable(context) .icon(CommunityMaterial.Icon.cmd_map_marker) .color(AppearancePrefs.Theme.textColor) .toBitmap() ) fun AppBarLayout.expand(animate: Boolean = animationsEnabled) = setExpanded(true, animate) fun ClusterManager<Event>.setIcons( context: Context, backgroundContourWidthDp: Int = 1, sizeDp: Int = 56, paddingDp: Int = 8 ) = setIconGenerator(object : IconGenerator<Event> { override fun getClusterIcon(cluster: Cluster<Event>): BitmapDescriptor = BitmapDescriptorFactory.fromBitmap( IconicsDrawable(context) .iconText(cluster.sizeText) .color(AppearancePrefs.Theme.textColor) .backgroundColor(AppearancePrefs.Theme.backgroundColor) .backgroundContourColor(AppearancePrefs.Theme.textColor) .backgroundContourWidthDp(backgroundContourWidthDp) .sizeDp(sizeDp) .roundedCornersDp(sizeDp / 2) .paddingDp(paddingDp) .toBitmap() ) override fun getClusterItemIcon(event: Event): BitmapDescriptor = styledMarker(context) }) fun ConstraintSet.withHorizontalChain( leftId: Int, leftSide: Int, rightId: Int, rightSide: Int, chainIds: IntArray, weights: FloatArray?, style: Int ) = createHorizontalChain(leftId, leftSide, rightId, rightSide, chainIds, weights, style) /** * Converts distance in meters in formatted string with meters/kilometers. */ fun Float.formatDistance(context: Context): String = if (this < 1000) String.format(context.string(R.string.distance_in_meter), this) else String.format(context.string(R.string.distance_in_kilometer), this.div(1000)) fun GoogleMap.withStyle( context: Context ) = setMapStyle(MapStyleOptions.loadRawResourceStyle(context, AppearancePrefs.Theme.mapStyle)) fun <T : Any, L : LiveData<T>> LifecycleOwner.observe( liveData: L, onChanged: (T?) -> Unit ) = liveData.observe(this, Observer(onChanged)) /** * Converts UNIX time to human readable information in relation to the current time. */ fun Long.formatPassedSeconds(context: Context): String { val id: Int val quantity: Long when { this < 60 -> { id = R.plurals.kau_x_seconds quantity = this } TimeUnit.SECONDS.toMinutes(this) < 60 -> { id = R.plurals.kau_x_minutes quantity = TimeUnit.SECONDS.toMinutes(this) } TimeUnit.SECONDS.toHours(this) < 24 -> { id = R.plurals.kau_x_hours quantity = TimeUnit.SECONDS.toHours(this) } else -> { id = R.plurals.kau_x_days quantity = TimeUnit.SECONDS.toDays(this) } } return context.plural(id, quantity) } /** * Theme material dialog. */ fun MaterialDialog.Builder.theme(): MaterialDialog.Builder { val dimmerTextColor = AppearancePrefs.Theme.textColor.adjustAlpha(0.8f) titleColor(AppearancePrefs.Theme.textColor) contentColor(dimmerTextColor) widgetColor(dimmerTextColor) backgroundColor(AppearancePrefs.Theme.backgroundColor.lighten(0.1f).withMinAlpha(200)) positiveColor(AppearancePrefs.Theme.textColor) negativeColor(AppearancePrefs.Theme.textColor) neutralColor(AppearancePrefs.Theme.textColor) return this }
35.392405
96
0.713162
b338b387e9ebf4b3b022de9218d5dc0b0343347f
2,290
rb
Ruby
spec/unit/influxdb_rails_spec.rb
restaumatic/influxdb-rails
b26aa7282428cdc6e53838440b29da524d36c628
[ "MIT" ]
null
null
null
spec/unit/influxdb_rails_spec.rb
restaumatic/influxdb-rails
b26aa7282428cdc6e53838440b29da524d36c628
[ "MIT" ]
null
null
null
spec/unit/influxdb_rails_spec.rb
restaumatic/influxdb-rails
b26aa7282428cdc6e53838440b29da524d36c628
[ "MIT" ]
null
null
null
require "spec_helper" RSpec.describe InfluxDB::Rails do before do InfluxDB::Rails.configure do |config| config.application_name = "my-rails-app" config.ignored_environments = [] config.client.time_precision = "ms" end end describe ".current_timestamp" do let(:timestamp) { 1_513_009_229_111 } it "should return the current timestamp in the configured precision" do expect(Process).to receive(:clock_gettime) .with(Process::CLOCK_REALTIME, :millisecond) .and_return(timestamp) expect(InfluxDB::Rails.current_timestamp).to eq(timestamp) end end describe ".ignorable_exception?" do it "should be true for exception types specified in the configuration" do class DummyException < RuntimeError; end exception = DummyException.new InfluxDB::Rails.configure do |config| config.ignored_exceptions << "DummyException" end expect(InfluxDB::Rails.ignorable_exception?(exception)).to be_truthy end it "should be true for exception types specified in the configuration" do exception = ActionController::RoutingError.new("foo") expect(InfluxDB::Rails.ignorable_exception?(exception)).to be_truthy end it "should be false for valid exceptions" do exception = ZeroDivisionError.new expect(InfluxDB::Rails.ignorable_exception?(exception)).to be_falsey end end describe "rescue" do it "should transmit an exception when passed" do expect(InfluxDB::Rails.client).to receive(:write_point) InfluxDB::Rails.rescue do raise ArgumentError, "wrong" end end it "should also raise the exception when in an ignored environment" do InfluxDB::Rails.configure do |config| config.ignored_environments = %w[development test] end expect do InfluxDB::Rails.rescue do raise ArgumentError, "wrong" end end.to raise_error(ArgumentError) end end describe "rescue_and_reraise" do it "should transmit an exception when passed" do expect(InfluxDB::Rails.client).to receive(:write_point) expect do InfluxDB::Rails.rescue_and_reraise { raise ArgumentError, "wrong" } end.to raise_error(ArgumentError) end end end
28.987342
77
0.695633
bcc59aa3add8e60aec2ea33f03bff84ab238eb79
7,383
js
JavaScript
docs/api/output/dr.handler.js
gnovos/gnovos.github.io
63a88367bcfe0a7e1ca105a667c4aff92d852956
[ "MIT" ]
null
null
null
docs/api/output/dr.handler.js
gnovos/gnovos.github.io
63a88367bcfe0a7e1ca105a667c4aff92d852956
[ "MIT" ]
null
null
null
docs/api/output/dr.handler.js
gnovos/gnovos.github.io
63a88367bcfe0a7e1ca105a667c4aff92d852956
[ "MIT" ]
null
null
null
Ext.data.JsonP.dr_handler({"tagname":"class","name":"dr.handler","autodetected":{},"files":[{"filename":"layout.js","href":"layout.html#dr-handler"}],"members":[{"name":"args","tagname":"attribute","owner":"dr.handler","id":"attribute-args","meta":{}},{"name":"event","tagname":"attribute","owner":"dr.handler","id":"attribute-event","meta":{"required":true}},{"name":"method","tagname":"attribute","owner":"dr.handler","id":"attribute-method","meta":{}},{"name":"reference","tagname":"attribute","owner":"dr.handler","id":"attribute-reference","meta":{}},{"name":"type","tagname":"attribute","owner":"dr.handler","id":"attribute-type","meta":{}}],"alternateClassNames":[],"aliases":{},"id":"class-dr.handler","short_doc":"Declares a handler in a node, view, class or other class instance. ...","component":false,"superclasses":[],"subclasses":[],"mixedInto":[],"mixins":[],"parentMixins":[],"requires":[],"uses":[],"html":"<div><pre class=\"hierarchy\"><h4>Files</h4><div class='dependency'><a href='source/layout.html#dr-handler' target='_blank'>layout.js</a></div></pre><div class='doc-contents'><p>Declares a handler in a node, view, class or other class instance. Handlers can only be created with the <code>&lt;handler&gt;&lt;/handler&gt;</code> tag syntax.</p>\n\n<p>Handlers are called when an event fires with new value, if available.</p>\n\n<p>Here is a simple handler that listens for an onx event in the local scope. The handler runs when x changes:</p>\n\n<pre><code>&lt;handler event=\"onx\"&gt;\n // do something now that x has changed\n&lt;/handler&gt;\n</code></pre>\n\n<p>When a handler uses the args attribute, it can recieve the value that changed:</p>\n\n<p>Sometimes it's nice to use a single method to respond to multiple events:</p>\n\n<pre><code>&lt;handler event=\"onx\" method=\"handlePosition\"&gt;&lt;/handler&gt;\n&lt;handler event=\"ony\" method=\"handlePosition\"&gt;&lt;/handler&gt;\n&lt;method name=\"handlePosition\"&gt;\n // do something now that x or y have changed\n&lt;/method&gt;\n</code></pre>\n\n<p>When a handler uses the args attribute, it can receive the value that changed:</p>\n\n<pre class='inline-example '><code>&lt;handler event=\"onwidth\" args=\"widthValue\"&gt;\n exampleLabel.setAttribute(\"text\", \"Parent view received width value of \" + widthValue)\n&lt;/handler&gt;\n\n&lt;text id=\"exampleLabel\" x=\"50\" y=\"5\" text=\"no value yet\" color=\"coral\" outline=\"1px dotted coral\" padding=\"10px\"&gt;&lt;/text&gt;\n&lt;text x=\"50\" y=\"${exampleLabel.y + exampleLabel.height + 20}\" text=\"no value yet\" color=\"white\" bgcolor=\"#DDAA00\" padding=\"10px\"&gt;\n &lt;handler event=\"onwidth\" args=\"wValue\"&gt;\n this.setAttribute(\"text\", \"This label received width value of \" + wValue)\n &lt;/handler&gt;\n&lt;/text&gt;\n</code></pre>\n\n<p>It's also possible to listen for events on another scope. This handler listens for onidle events on <a href=\"#!/api/dr.idle\" rel=\"dr.idle\" class=\"docClass\">dr.idle</a> instead of the local scope:</p>\n\n<pre class='inline-example '><code>&lt;handler event=\"onidle\" args=\"time\" reference=\"<a href=\"#!/api/dr.idle\" rel=\"dr.idle\" class=\"docClass\">dr.idle</a>\"&gt;\n exampleLabel.setAttribute('text', 'received time from <a href=\"#!/api/dr.idle-event-onidle\" rel=\"dr.idle-event-onidle\" class=\"docClass\">dr.idle.onidle</a>: ' + Math.round(time));\n&lt;/handler&gt;\n&lt;text id=\"exampleLabel\" x=\"50\" y=\"5\" text=\"no value yet\" color=\"coral\" outline=\"1px dotted coral\" padding=\"10px\"&gt;&lt;/text&gt;\n</code></pre>\n</div><div class='members'><div class='members-section'><h3 class='members-title icon-attribute'>Attributes</h3><div class='subsection'><div class='definedBy'>Defined By</div><h4 class='members-subtitle'>Required attributes</h3><div id='attribute-event' class='member first-child not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='dr.handler'>dr.handler</span><br/><a href='source/layout.html#dr-handler-attribute-event' target='_blank' class='view-source'>view source</a></div><a href='#!/api/dr.handler-attribute-event' class='name expandable'>event</a> : String<span class=\"signature\"><span class='required' >required</span></span></div><div class='description'><div class='short'>The name of the event to listen for, e.g. ...</div><div class='long'><p>The name of the event to listen for, e.g. 'onwidth'.</p>\n</div></div></div></div><div class='subsection'><div class='definedBy'>Defined By</div><h4 class='members-subtitle'>Optional attributes</h3><div id='attribute-args' class='member first-child not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='dr.handler'>dr.handler</span><br/><a href='source/layout.html#dr-handler-attribute-args' target='_blank' class='view-source'>view source</a></div><a href='#!/api/dr.handler-attribute-args' class='name expandable'>args</a> : String[]<span class=\"signature\"></span></div><div class='description'><div class='short'><p>A comma separated list of method arguments.</p>\n</div><div class='long'><p>A comma separated list of method arguments.</p>\n</div></div></div><div id='attribute-method' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='dr.handler'>dr.handler</span><br/><a href='source/layout.html#dr-handler-attribute-method' target='_blank' class='view-source'>view source</a></div><a href='#!/api/dr.handler-attribute-method' class='name expandable'>method</a> : String<span class=\"signature\"></span></div><div class='description'><div class='short'>If set, the handler call a local method. ...</div><div class='long'><p>If set, the handler call a local method. Useful when multiple handlers need to do the same thing.</p>\n</div></div></div><div id='attribute-reference' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='dr.handler'>dr.handler</span><br/><a href='source/layout.html#dr-handler-attribute-reference' target='_blank' class='view-source'>view source</a></div><a href='#!/api/dr.handler-attribute-reference' class='name expandable'>reference</a> : String<span class=\"signature\"></span></div><div class='description'><div class='short'><p>If set, the handler will listen for an event in another scope.</p>\n</div><div class='long'><p>If set, the handler will listen for an event in another scope.</p>\n</div></div></div><div id='attribute-type' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='dr.handler'>dr.handler</span><br/><a href='source/layout.html#dr-handler-attribute-type' target='_blank' class='view-source'>view source</a></div><a href='#!/api/dr.handler-attribute-type' class='name expandable'>type</a> : \"js\"/\"coffee\"<span class=\"signature\"></span></div><div class='description'><div class='short'>The compiler to use for this method. ...</div><div class='long'><p>The compiler to use for this method. Inherits from the immediate class if unspecified.</p>\n</div></div></div></div></div></div></div>","meta":{}});
7,383
7,383
0.692808
fb3dbeab48ac7bd0ea03d295522d421c0191255b
2,789
java
Java
src/main/java/com/db/convert/domain/Species.java
chanakaDe/ensembl-db-convert
d6ae2faf8947ae5819a7241f231145c702adb9e3
[ "Apache-2.0" ]
1
2020-03-16T06:44:51.000Z
2020-03-16T06:44:51.000Z
src/main/java/com/db/convert/domain/Species.java
chanakaDe/ensembl-db-convert
d6ae2faf8947ae5819a7241f231145c702adb9e3
[ "Apache-2.0" ]
null
null
null
src/main/java/com/db/convert/domain/Species.java
chanakaDe/ensembl-db-convert
d6ae2faf8947ae5819a7241f231145c702adb9e3
[ "Apache-2.0" ]
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.db.convert.domain; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlTransient; /** * * @author chanu1993@gmail.com */ @Entity @Table(name = "species") public class Species implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "species_id") private Integer speciesId; @Basic(optional = false) @NotNull @Size(min = 1, max = 20) @Column(name = "name") private String name; @OneToMany(cascade = CascadeType.ALL, mappedBy = "speciesId", fetch = FetchType.LAZY) private List<Genome> genomeList; public Species() { } public Species(Integer speciesId) { this.speciesId = speciesId; } public Species(Integer speciesId, String name) { this.speciesId = speciesId; this.name = name; } public Integer getSpeciesId() { return speciesId; } public void setSpeciesId(Integer speciesId) { this.speciesId = speciesId; } public String getName() { return name; } public void setName(String name) { this.name = name; } @XmlTransient public List<Genome> getGenomeList() { return genomeList; } public void setGenomeList(List<Genome> genomeList) { this.genomeList = genomeList; } @Override public int hashCode() { int hash = 0; hash += (speciesId != null ? speciesId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Species)) { return false; } Species other = (Species) object; if ((this.speciesId == null && other.speciesId != null) || (this.speciesId != null && !this.speciesId.equals(other.speciesId))) { return false; } return true; } @Override public String toString() { return "com.mycompany.dbconvert.model.Species[ speciesId=" + speciesId + " ]"; } }
25.354545
137
0.656508
2ad343018621a63c3d075dc05f4d452249f686fc
5,515
sql
SQL
lcb.sql
MilanOdavic/lcb3
70a05842cce787da4f216d64fea0c9adbdbdc2ea
[ "MIT" ]
null
null
null
lcb.sql
MilanOdavic/lcb3
70a05842cce787da4f216d64fea0c9adbdbdc2ea
[ "MIT" ]
null
null
null
lcb.sql
MilanOdavic/lcb3
70a05842cce787da4f216d64fea0c9adbdbdc2ea
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 4.9.0.1 -- https://www.phpmyadmin.net/ -- -- Host: localhost -- Generation Time: Jan 04, 2020 at 10:25 AM -- Server version: 10.4.6-MariaDB -- PHP Version: 7.3.8 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `lcb` -- -- -------------------------------------------------------- -- -- Table structure for table `articles` -- CREATE TABLE `articles` ( `id` int(11) NOT NULL, `categories_id` int(11) NOT NULL, `text` text COLLATE utf8_unicode_ci NOT NULL, `title` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `users_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `articles` -- INSERT INTO `articles` (`id`, `categories_id`, `text`, `title`, `users_id`) VALUES (1, 1, 'q3', 'q3', 1), (2, 1, 'ovo je clanak 2', 'naslov clanka 2', 1), (3, 2, 'ovo je clanak 3', 'naslov clanka 3', 1), (4, 1, 'ovo je clanak 4', 'naslov clanka 4', 3), (24, 17, 'art11', 'art11', 1), (25, 17, 'art2', 'art2', 1), (26, 17, 'art3', 'art3', 1), (27, 17, 'art4', 'art4', 1); -- -------------------------------------------------------- -- -- Table structure for table `categories` -- CREATE TABLE `categories` ( `id` int(11) NOT NULL, `title` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `users_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `categories` -- INSERT INTO `categories` (`id`, `title`, `users_id`) VALUES (1, 'kategorija 1', 1), (2, 'kategorija 22', 1), (17, 'cat1', 1), (18, 'cat2', 1), (19, 'cat33', 1), (22, 'cat4', 3); -- -------------------------------------------------------- -- -- Table structure for table `comments` -- CREATE TABLE `comments` ( `id` int(11) NOT NULL, `articles_id` int(11) NOT NULL, `users_id` int(11) NOT NULL, `title` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `text` text COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `comments` -- INSERT INTO `comments` (`id`, `articles_id`, `users_id`, `title`, `text`) VALUES (1, 1, 1, 'qqq11', 'qqq11'), (4, 3, 3, 'xxx', 'xxx'), (6, 1, 1, 'qwe', 'qwe'), (7, 1, 3, 'xxx1', '1xxx'), (8, 2, 3, 'xxx1234', 'xxx22222'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `pass` varchar(100) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `name`, `pass`) VALUES (1, 'milan', 'milan'), (2, 'kaca', 'kaca'), (3, 'xxx', 'xxx'), (4, 'bla1', 'bla1'), (5, 'bla1', 'bla1'), (6, 'bla1', 'bla1'), (7, 'qwe', 'qwe'), (8, 'eee', 'www'), (9, 'qwe', 'qwe'), (10, 'eee', 'qqq'), (11, 'www', 'www'), (12, 'qwe123', 'qwe'), (13, 'xxx2', 'xxx2'); -- -- Indexes for dumped tables -- -- -- Indexes for table `articles` -- ALTER TABLE `articles` ADD PRIMARY KEY (`id`), ADD KEY `articles_ibfk_1` (`categories_id`), ADD KEY `articles_users` (`users_id`); -- -- Indexes for table `categories` -- ALTER TABLE `categories` ADD PRIMARY KEY (`id`), ADD KEY `categories_users` (`users_id`); -- -- Indexes for table `comments` -- ALTER TABLE `comments` ADD PRIMARY KEY (`id`), ADD KEY `comments_articles` (`articles_id`), ADD KEY `comments_users` (`users_id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `articles` -- ALTER TABLE `articles` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=31; -- -- AUTO_INCREMENT for table `categories` -- ALTER TABLE `categories` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24; -- -- AUTO_INCREMENT for table `comments` -- ALTER TABLE `comments` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; -- -- Constraints for dumped tables -- -- -- Constraints for table `articles` -- ALTER TABLE `articles` ADD CONSTRAINT `articles_ibfk_1` FOREIGN KEY (`categories_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `articles_users` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `categories` -- ALTER TABLE `categories` ADD CONSTRAINT `categories_users` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `comments` -- ALTER TABLE `comments` ADD CONSTRAINT `comments_articles` FOREIGN KEY (`articles_id`) REFERENCES `articles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `comments_users` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
24.842342
132
0.642792
00d4e0318280664c18b402d192f0b11639b01b7c
858
swift
Swift
Notflix/Sources/Services/APIService/APIError.swift
qeude/Notflix
ea6fb99a79dabfaa4421705707d6d624937ff511
[ "MIT" ]
77
2020-05-15T12:19:36.000Z
2022-03-16T17:57:00.000Z
Notflix/Sources/Services/APIService/APIError.swift
qeude/NetflixLike
f3ba7ee026d8d703b906e665405686a04998f95a
[ "MIT" ]
2
2020-05-21T21:22:26.000Z
2020-09-10T15:54:33.000Z
Notflix/Sources/Services/APIService/APIError.swift
qeude/NetflixLike
f3ba7ee026d8d703b906e665405686a04998f95a
[ "MIT" ]
12
2020-05-20T03:33:32.000Z
2022-02-16T23:07:03.000Z
// // APIError.swift // Notflix // // Created by Quentin Eude on 26/01/2020. // Copyright © 2020 Quentin Eude. All rights reserved. // protocol LocalizedError: Error { var localizedDescription: String { get } } enum APIError: LocalizedError { case encoding case decoding case server(message: String) case invalidUrl case statusCode case invalidResponse var localizedDescription: String { switch self { case .encoding: return "APIError while encoding" case .decoding: return "APIError while decoding" case .server(let message): return "APIError due to the server with message: \(message)" case .invalidUrl: return "APIError invalidUrl" case .statusCode: return "APIError status code error" case .invalidResponse: return "APIError invalid response" } } }
28.6
95
0.678322
56f9896d15fddcc9b9c4b5f0acff8624b677f312
45
ts
TypeScript
node_modules/@coreui/icons/js/free/cil-comment-square.d.ts
yashn007/nodejs
d15b0a52a043172321b9abc6761fabf235832cca
[ "MIT" ]
1,950
2018-05-09T13:26:46.000Z
2022-03-31T00:32:37.000Z
node_modules/@coreui/icons/js/free/cil-comment-square.d.ts
yashn007/nodejs
d15b0a52a043172321b9abc6761fabf235832cca
[ "MIT" ]
41
2020-07-21T23:11:07.000Z
2022-01-30T23:58:12.000Z
node_modules/@coreui/icons/js/free/cil-comment-square.d.ts
yashn007/nodejs
d15b0a52a043172321b9abc6761fabf235832cca
[ "MIT" ]
175
2018-05-11T22:01:22.000Z
2022-03-27T16:49:12.000Z
export declare const cilCommentSquare: any[];
45
45
0.822222
a34cc0b450b84c6dde21a71cb52ec047f72db659
756
asm
Assembly
programs/oeis/152/A152579.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/152/A152579.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/152/A152579.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A152579: a(n) = (10*n+3)*(10*n+17). ; 51,351,851,1551,2451,3551,4851,6351,8051,9951,12051,14351,16851,19551,22451,25551,28851,32351,36051,39951,44051,48351,52851,57551,62451,67551,72851,78351,84051,89951,96051,102351,108851,115551,122451,129551,136851,144351,152051,159951,168051,176351,184851,193551,202451,211551,220851,230351,240051,249951,260051,270351,280851,291551,302451,313551,324851,336351,348051,359951,372051,384351,396851,409551,422451,435551,448851,462351,476051,489951,504051,518351,532851,547551,562451,577551,592851,608351,624051,639951,656051,672351,688851,705551,722451,739551,756851,774351,792051,809951,828051,846351,864851,883551,902451,921551,940851,960351,980051,999951 mov $1,2 add $1,$0 mul $1,$0 mul $1,100 add $1,51 mov $0,$1
75.6
656
0.801587
9bdec73026e5bbdac106055c96216f40bbe49a03
703
js
JavaScript
backend/core/services/admin_svs/searchlocationsvs.js
StealthAdder/AVS-RFID_TEC
00d9e05ab6692243298ca86a950d7b0051f8e869
[ "MIT" ]
9
2020-10-17T20:05:34.000Z
2022-03-10T02:02:12.000Z
backend/core/services/admin_svs/searchlocationsvs.js
StealthAdder/AVS-RFID_TEC
00d9e05ab6692243298ca86a950d7b0051f8e869
[ "MIT" ]
9
2020-10-21T04:20:17.000Z
2021-08-08T20:28:21.000Z
backend/core/services/admin_svs/searchlocationsvs.js
StealthAdder/AVS-RFID_TEC
00d9e05ab6692243298ca86a950d7b0051f8e869
[ "MIT" ]
null
null
null
const speedLimitRef = require('../../../api/models/speedLimitRef'); const searchlocationsvs = () => { return async (req, res, next) => { // console.log(req.body.location.toUpperCase()); try { let result = await speedLimitRef.findOne({ zipcode: req.body.location.toUpperCase(), }); if (result === null) { result = await speedLimitRef.findOne({ location: req.body.location.toUpperCase(), }); if (result === null) { result = 'Not found'; } } console.log(result); res.send({ result, }); } catch (error) { console.log(error); } }; }; module.exports = searchlocationsvs;
24.241379
67
0.544808
0b729c6af7d440093ab2706bff962e7602e418a9
1,327
py
Python
integration/phore/tests/shardsynctest.py
phoreproject/synapse
77d10ca2eb7828ca9f7c8e29b72a73cf2c07f954
[ "MIT" ]
9
2018-09-30T18:56:26.000Z
2019-10-30T23:09:07.000Z
integration/phore/tests/shardsynctest.py
phoreproject/synapse
77d10ca2eb7828ca9f7c8e29b72a73cf2c07f954
[ "MIT" ]
102
2018-11-09T16:17:59.000Z
2020-11-04T19:06:01.000Z
integration/phore/tests/shardsynctest.py
phoreproject/graphene
77d10ca2eb7828ca9f7c8e29b72a73cf2c07f954
[ "MIT" ]
5
2018-11-05T14:29:24.000Z
2020-06-08T19:26:05.000Z
import logging from phore.framework import tester, validatornode, shardnode from phore.pb import common_pb2 class ShardSyncTest(tester.Tester): def __init__(self): logging.info(logging.INFO) super().__init__() def _do_run(self): beacon_nodes = [self.create_beacon_node() for _ in range(1)] beacon_nodes[0].start() beacon_nodes[0].wait_for_rpc() shard_node_configs = [shardnode.ShardConfig.from_beacon(beacon_nodes[0]) for _ in range(2)] shard_nodes = [] for c in shard_node_configs: c.initial_shards = ['1'] shard_nodes.append(self.create_shard_node(c)) shard_nodes[0].start() shard_nodes[0].wait_for_rpc() shard_nodes[1].start() shard_nodes[1].wait_for_rpc() validator_node = self.create_validator_node( validatornode.ValidatorConfig.from_beacon_and_shard(beacon_nodes[0], shard_nodes[0], "0-255") ) validator_node.start() validator_node.wait_for_rpc() shard_nodes[0].wait_for_slot(4, 1) shard_node_0_addr = shard_nodes[0].get_listening_addresses().Addresses[0] shard_nodes[1].connect(common_pb2.ConnectMessage(Address=shard_node_0_addr)) shard_nodes[1].wait_for_slot(8, 1) ex = ShardSyncTest() ex.run()
26.54
105
0.667671
fbb6dbbfc12ec57b4a1173b98063000195417f5a
1,464
java
Java
src/main/java/offer/sort/MergeSort.java
physicsLoveJava/algorithms-practice-record
d0ad21214b2e008d81ba07717da3dca062a7071b
[ "MIT" ]
null
null
null
src/main/java/offer/sort/MergeSort.java
physicsLoveJava/algorithms-practice-record
d0ad21214b2e008d81ba07717da3dca062a7071b
[ "MIT" ]
null
null
null
src/main/java/offer/sort/MergeSort.java
physicsLoveJava/algorithms-practice-record
d0ad21214b2e008d81ba07717da3dca062a7071b
[ "MIT" ]
null
null
null
package offer.sort; import java.util.Comparator; public class MergeSort { public static <E extends Comparable> void sort(E[] arr, Comparator<E> comparator) { if(arr == null) { return ; } sort(arr, 0, arr.length - 1, comparator); } private static <E extends Comparable> void sort(E[] arr, int start, int end, Comparator<E> comparator) { if(start >= end) { return; } int mid = (end + start) / 2; sort(arr, start, mid, comparator); sort(arr, mid + 1, end, comparator); merge(arr, start, mid, end, comparator); } private static <E extends Comparable> void merge(E[] arr, int start, int mid, int end, Comparator<E> comparator) { Object[] aux = new Object[end - start + 1]; for (int i = start; i <= end; i++) { aux[i - start] = arr[i]; } int i = start; int j = mid + 1; int k = 0; while(i <= mid && j <= end) { int cmp = comparator.compare(arr[i], arr[j]); if(cmp >= 0) { aux[k++] = arr[j++]; }else { aux[k++] = arr[i++]; } } while(i > mid && j <= end) { aux[k++] = arr[j++]; } while(j > end && i <= mid) { aux[k++] = arr[i++]; } for (int l = 0; l < aux.length; l++) { arr[start + l] = (E) aux[l]; } } }
28.153846
118
0.452186
5c881d41707ae670e2244d42a7f639380c82c9d9
168
h
C
YZOpenSDKDemo/YouzanBaseDemo/YZBaseDemo/Features/ViewControllers/YZBaseDemo-Bridging-Header.h
cluesblues/YouzanMobileSDK-iOS
a57813a344670a9b9f8ca9cd8afb6e34d71a1070
[ "MIT" ]
62
2017-08-02T05:31:08.000Z
2021-09-06T09:06:13.000Z
YZOpenSDKDemo/YouzanBaseDemo/YZBaseDemo/Features/ViewControllers/YZBaseDemo-Bridging-Header.h
seasaliu/YouzanMobileSDK-iOS
5f64cf42aa369da74f326805c34a5c0b58468629
[ "MIT" ]
28
2017-11-09T02:36:18.000Z
2021-12-10T07:01:36.000Z
YZOpenSDKDemo/YouzanBaseDemo/YZBaseDemo/Features/ViewControllers/YZBaseDemo-Bridging-Header.h
seasaliu/YouzanMobileSDK-iOS
5f64cf42aa369da74f326805c34a5c0b58468629
[ "MIT" ]
20
2017-07-26T03:15:32.000Z
2021-05-25T06:41:42.000Z
// // Use this file to import your target's public headers that you would like to expose to Swift. // #import <YZSDKCore/YZSDKCore.h> #import <YZBaseSDK/YZBaseSDK.h>
24
96
0.738095
22623be062e338a218203836b3bc945a0858b1b6
198
kt
Kotlin
app/src/main/java/bootcamp/snt/bootcampsantandertodo/data/TodosCallback.kt
fernandosantis/dio-kotlin-api-interation-santander
068e486ca0607f61ccbc58827a90c6233d56b2cf
[ "Apache-2.0" ]
null
null
null
app/src/main/java/bootcamp/snt/bootcampsantandertodo/data/TodosCallback.kt
fernandosantis/dio-kotlin-api-interation-santander
068e486ca0607f61ccbc58827a90c6233d56b2cf
[ "Apache-2.0" ]
null
null
null
app/src/main/java/bootcamp/snt/bootcampsantandertodo/data/TodosCallback.kt
fernandosantis/dio-kotlin-api-interation-santander
068e486ca0607f61ccbc58827a90c6233d56b2cf
[ "Apache-2.0" ]
null
null
null
package bootcamp.snt.bootcampsantandertodo.data import bootcamp.snt.bootcampsantandertodo.model.Todo interface TodosCallback { fun onSucesso(todos: List<Todo>?) fun onFalha(t: Throwable) }
24.75
52
0.792929
04b4bd72079c20876a01250f5c67397a14a640d9
464
dart
Dart
example/lib/mvc/route_test/two/controller.dart
lxiuyuan/flutter_mvc
bbefd61f50ead028d43d8a95a4af1d2adf0c3692
[ "BSD-2-Clause" ]
11
2020-04-10T02:14:20.000Z
2021-08-03T03:23:44.000Z
example/lib/mvc/route_test/two/controller.dart
lxiuyuan/flutter_mvc
bbefd61f50ead028d43d8a95a4af1d2adf0c3692
[ "BSD-2-Clause" ]
null
null
null
example/lib/mvc/route_test/two/controller.dart
lxiuyuan/flutter_mvc
bbefd61f50ead028d43d8a95a4af1d2adf0c3692
[ "BSD-2-Clause" ]
1
2021-11-06T08:43:39.000Z
2021-11-06T08:43:39.000Z
import 'package:flutter_mvc_example/mvc/route_test/three/controller.dart'; import 'view.dart'; import 'package:flutter_mvc/flutter_mvc.dart'; ///Description:第二个界面 ///Author:djy ///date created 2020/07/13 class RouteTwoController extends BaseController { RouteTwoController():super(RouteTwoPage()); @override void initState(){ super.initState(); } void onPushClick() { RouteThreeController(this).push(context); } }
20.173913
74
0.700431
aee1ba1a79892562d43396b11583523cbc5a9b80
1,505
rs
Rust
core/fuzz/fuzz_targets/fuzz_copy.rs
sanpii/elephantry
7fe5597ba08aa7d315c75122797757507e4558ad
[ "MIT" ]
1
2020-05-31T21:17:37.000Z
2020-05-31T21:17:37.000Z
core/fuzz/fuzz_targets/fuzz_copy.rs
sanpii/elephantry
7fe5597ba08aa7d315c75122797757507e4558ad
[ "MIT" ]
null
null
null
core/fuzz/fuzz_targets/fuzz_copy.rs
sanpii/elephantry
7fe5597ba08aa7d315c75122797757507e4558ad
[ "MIT" ]
null
null
null
#![no_main] use libfuzzer_sys::fuzz_target; #[derive(Debug, arbitrary::Arbitrary, elephantry::Entity)] #[elephantry(model="Model", structure="Structure")] struct Entity { bigint: i64, bit: u8, boolean: bool, r#box: elephantry::Box, bytea: elephantry::Bytea, char: char, varchar: String, circle: elephantry::Circle, float8: f64, hstore: elephantry::Hstore, integer: i32, line: elephantry::Line, lseg: elephantry::Segment, money: f32, path: elephantry::Path, point: elephantry::Point, polygon: elephantry::Polygon, float4: f32, smallint: i16, text: String, } fuzz_target!(|entity: Entity| { let database_url = std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost".to_string()); let elephantry = elephantry::Pool::new(&database_url).unwrap(); elephantry.execute("create extension if not exists hstore").unwrap(); elephantry.execute("create temporary table entity( bit bit, bigint bigint, box box, bytea bytea, boolean boolean, char char, varchar varchar, circle circle, float8 float8, hstore hstore, integer integer, line line, lseg lseg, money money, path path, point point, polygon polygon, float4 float4, smallint smallint, text text );").unwrap(); let _ = elephantry.copy::<Model, _>(vec![entity].into_iter()); });
25.508475
93
0.612625
9e6710324b2e551725ea5e039664e26333f0c7c6
752
rs
Rust
src/lib.rs
HaruxOS/static_assert
8af903e6710e4dbbc4788948f22eb4792ca33f0e
[ "Apache-2.0" ]
1
2021-09-10T06:38:40.000Z
2021-09-10T06:38:40.000Z
src/lib.rs
HaruxOS/static_assert
8af903e6710e4dbbc4788948f22eb4792ca33f0e
[ "Apache-2.0" ]
null
null
null
src/lib.rs
HaruxOS/static_assert
8af903e6710e4dbbc4788948f22eb4792ca33f0e
[ "Apache-2.0" ]
null
null
null
// SPDX-License-Identifier: Apache-2.0 /* * File: src/lib.rs * * Static assertions for Rust. * * Author: HTG-YT * Copyright (c) 2021 The HaruxOS Project Team */ #![no_std] #![feature(decl_macro)] /// Statically asserts that an expression is true. pub macro static_assert { ($($arguments:tt)*) => { const _: () = const { core::assert!($($arguments)*) }; } } /// Statically asserts that two values are equal. pub macro static_assert_eq { ($($arguments:tt)*) => { const _: () = const { core::assert_eq!($($arguments)*) }; } } /// Statically asserts that two values are not equal. pub macro static_assert_ne { ($($arguments:tt)*) => { const _: () = const { core::assert_ne!($($arguments)*) }; } }
22.117647
65
0.597074
1344ce3cfe0d0671816187324b89fcc2915ba676
8,291
h
C
clang/Type.h
djp952/tools-llvm
01503ab630354dc7196a8dfe15f4525bf9a0e1ec
[ "MIT" ]
1
2016-09-11T11:32:08.000Z
2016-09-11T11:32:08.000Z
clang/Type.h
djp952/tools-llvm
01503ab630354dc7196a8dfe15f4525bf9a0e1ec
[ "MIT" ]
3
2016-06-04T03:55:58.000Z
2016-06-09T03:13:15.000Z
clang/Type.h
djp952/tools-llvm
01503ab630354dc7196a8dfe15f4525bf9a0e1ec
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- // Copyright (c) 2016 Michael G. Brehm // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //--------------------------------------------------------------------------- #ifndef __TYPE_H_ #define __TYPE_H_ #pragma once #include "TranslationUnitReferenceHandle.h" #pragma warning(push, 4) // Enable maximum compiler warnings using namespace System; namespace zuki::tools::llvm::clang { namespace local = zuki::tools::llvm::clang; // FORWARD DECLARATIONS // ref class ArrayType; enum class CallingConvention; ref class Cursor; enum class CxxReferenceQualifier; value class EnumerateFieldsResult; ref class TypeCollection; ref class TypeFieldOffsets; value class TypeKind; //--------------------------------------------------------------------------- // Class Type // // The type of an element in the abstract syntax tree //--------------------------------------------------------------------------- public ref class Type { public: //----------------------------------------------------------------------- // Overloaded Operators // operator== (static) // static bool operator==(Type^ lhs, Type^ rhs); // operator!= (static) // static bool operator!=(Type^ lhs, Type^ rhs); //----------------------------------------------------------------------- // Member Functions // EnumerateFields // // Enumerates the direct field cursor of this type void EnumerateFields(Func<Cursor^, EnumerateFieldsResult>^ func); // Equals // // Overrides Object::Equals() virtual bool Equals(Object^ rhs) override; // Equals // // Compares this Type instance to another Type instance bool Equals(Type^ rhs); // GetHashCode // // Overrides Object::GetHashCode() virtual int GetHashCode(void) override; // ToString // // Overrides Object::ToString() virtual String^ ToString(void) override; //----------------------------------------------------------------------- // Properties // Alignment // // Gets the alignment of a type in bytes as per C++ standard property Nullable<__int64> Alignment { Nullable<__int64> get(void); } // ArgumentTypes // // Gets a collection of template argument types property TypeCollection^ ArgumentTypes { TypeCollection^ get(void); } // ArrayElementType // // Gets the element type of an array type property Type^ ArrayElementType { Type^ get(void); } // ArraySize // // Gets the size of a constant array type property Nullable<__int64> ArraySize { Nullable<__int64> get(void); } // CallingConvention // // Gets the calling convention for a function type property local::CallingConvention CallingConvention { local::CallingConvention get(void); } // CanonicalType // // Gets the canonical type for this type property Type^ CanonicalType { Type^ get(void); } // ClassType // // Gets the class type for this type property Type^ ClassType { Type^ get(void); } // CxxReferenceQualifier // // Gets the c++ reference qualifier (lvalue/rvalue) for the type property local::CxxReferenceQualifier CxxReferenceQualifier { local::CxxReferenceQualifier get(void); } // DeclarationCursor // // Gets the declaration cursor of this type property Cursor^ DeclarationCursor { Cursor^ get(void); } // ElementCount // // Gets the number of elements in an array or vector type property Nullable<__int64> ElementCount { Nullable<__int64> get(void); } // ElementType // // Gets the element type of an array, complex, or vector type property Type^ ElementType { Type^ get(void); } // FieldBitOffset // // Gets a special indexer-only class for accessing field offsets property TypeFieldOffsets^ FieldBitOffset { TypeFieldOffsets^ get(void); } // IsConstQualified // // Gets a flag indicating if this type is const-qualified property bool IsConstQualified { bool get(void); } // IsPOD // // Gets a flag indicating if this type is a plain old data type property bool IsPOD { bool get(void); } // IsRestrictQualified // // Gets a flag indicating if this type is restrict-qualified (Obj-C) property bool IsRestrictQualified { bool get(void); } // IsVariadicFunction // // Gets a flag indicating if this type is a variadic function type property bool IsVariadicFunction { bool get(void); } // IsVolatileQualified // // Gets a flag indicating if this type is volatile-qualified property bool IsVolatileQualified { bool get(void); } // Kind // // Gets the kind of this type property TypeKind Kind { TypeKind get(void); } // NamedType // // Gets the named type for this type property Type^ NamedType { Type^ get(void); } // ObjectiveCEncoding // // Gets the Objective-C encoding property String^ ObjectiveCEncoding { String^ get(void); } // PointeeType // // Gets the pointee type for pointer types property Type^ PointeeType { Type^ get(void); } // ResultType // // Gets the result type for a function type property Type^ ResultType { Type^ get(void); } // Size // // Gets the size of a type in bytes as per C++ standard property Nullable<__int64> Size { Nullable<__int64> get(void); } // Spelling // // Gets the spelling of this Type property String^ Spelling { String^ get(void); } // TemplateArgumentTypes // // Gets a collection of template argument types property TypeCollection^ TemplateArgumentTypes { TypeCollection^ get(void); } internal: //----------------------------------------------------------------------- // Internal Member Functions // Create // // Creates a new Type instance static Type^ Create(SafeHandle^ owner, TranslationUnitHandle^ transunit, CXType type); private: // TypeHandle // // TranslationUnitReferenceHandle specialization for CXType using TypeHandle = TranslationUnitReferenceHandle<CXType>; // Instance Constructor // Type(TypeHandle^ handle); //----------------------------------------------------------------------- // Member Variables TypeHandle^ m_handle; // Underlying safe handle String^ m_spelling; // Cached type spelling TypeCollection^ m_argtypes; // Cached argument types Type^ m_arraytype; // Cached array element type Type^ m_canonical; // Cached canonical type Type^ m_classtype; // Cached class type Cursor^ m_declaration; // Cached declaration cursor Type^ m_elementtype; // Cached element type Type^ m_pointee; // Cached pointee type Type^ m_resulttype; // Cached result type TypeCollection^ m_templateargs; // Cached template arg types TypeFieldOffsets^ m_fieldoffsets; // Cached field offsets Type^ m_named; // Cached named type String^ m_objcencoding; // Cached Obj-C encoding }; //--------------------------------------------------------------------------- } // zuki::tools::llvm::clang #pragma warning(pop) #endif // __TYPE_H_
23.962428
88
0.619346
d2ea4d8357fd1974097b4e8887c3ac09c4b35ebe
1,104
swift
Swift
Sources/SystemKit/Time/Timer.swift
apparata/SystemK
a08bfef8e8343aca3a0ccd0372c6a81ef3dfb86d
[ "MIT" ]
1
2022-01-17T07:39:04.000Z
2022-01-17T07:39:04.000Z
Sources/SystemKit/Time/Timer.swift
apparata/SystemKit
a08bfef8e8343aca3a0ccd0372c6a81ef3dfb86d
[ "MIT" ]
null
null
null
Sources/SystemKit/Time/Timer.swift
apparata/SystemKit
a08bfef8e8343aca3a0ccd0372c6a81ef3dfb86d
[ "MIT" ]
null
null
null
// // Copyright © 2016 Apparata AB. All rights reserved. // import Foundation public class Timer { public typealias TimerHandler = (_ timer: Timer) -> Void public var handler: TimerHandler? private var timer: Foundation.Timer? public init() { } deinit { timer?.invalidate() } public func startOneShot(_ timeInterval: Foundation.TimeInterval) { start(timeInterval, repeats: false) } public func startRepeating(_ timeInterval: Foundation.TimeInterval) { start(timeInterval, repeats: true) } private func start(_ timeInterval: Foundation.TimeInterval, repeats: Bool) { if let oldTimer = timer { oldTimer.invalidate() } timer = Foundation.Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(Timer.timerFiredHandler(_:)), userInfo: nil, repeats: repeats) } public func stop() { timer?.invalidate() } @objc private func timerFiredHandler(_ timer: Any) { handler?(self) } }
24
172
0.622283
ed179f8c4547823fc060a7082cf7a7956284f513
1,908
kt
Kotlin
src/main/kotlin/no/nav/helse/Saksbehandling.kt
navikt/helse-spa
b838e0d48529231ed95beb91e780bdb2f15f99fe
[ "MIT" ]
1
2019-09-11T10:18:17.000Z
2019-09-11T10:18:17.000Z
src/main/kotlin/no/nav/helse/Saksbehandling.kt
navikt/helse-spa
b838e0d48529231ed95beb91e780bdb2f15f99fe
[ "MIT" ]
7
2018-12-10T12:17:46.000Z
2019-09-23T12:54:35.000Z
src/main/kotlin/no/nav/helse/Saksbehandling.kt
navikt/helse-spa
b838e0d48529231ed95beb91e780bdb2f15f99fe
[ "MIT" ]
null
null
null
package no.nav.helse import arrow.core.Either import arrow.core.flatMap import arrow.core.left import arrow.core.right import no.nav.helse.Behandlingsfeil.Companion.mvpFilter import no.nav.helse.behandling.* import no.nav.helse.behandling.mvp.MVPFeil import no.nav.helse.behandling.søknad.Sykepengesøknad import no.nav.helse.fastsetting.vurderFakta import no.nav.helse.probe.SaksbehandlingProbe fun Sykepengesøknad.behandle(oppslag: Oppslag, probe: SaksbehandlingProbe): Either<Behandlingsfeil, SykepengeVedtak> = mvpFilter().flatMap { hentRegisterData(oppslag) }.flatMap { faktagrunnlagResultat -> faktagrunnlagResultat.mvpFilter() }.flatMap { faktagrunnlagResultat -> faktagrunnlagResultat.fastsettFakta() }.flatMap { avklarteFakta -> avklarteFakta.prøvVilkår(probe) }.flatMap { behandlingsgrunnlag -> behandlingsgrunnlag.beregnSykepenger() }.flatMap { sykepengeberegning -> sykepengeberegning.fattVedtak() } fun Sykepengesøknad.mvpFilter() = when (type) { "ARBEIDSTAKERE" -> right() else -> mvpFilter(this, listOf( MVPFeil("Søknadstype - $type", "Søknaden er av feil type") )).left() } private fun Sykepengesøknad.hentRegisterData(oppslag: Oppslag): Either<Behandlingsfeil, FaktagrunnlagResultat> = oppslag.hentRegisterData(this) private fun FaktagrunnlagResultat.fastsettFakta(): Either<Behandlingsfeil, AvklarteFakta> = vurderFakta(this) private fun AvklarteFakta.prøvVilkår(probe: SaksbehandlingProbe): Either<Behandlingsfeil, Behandlingsgrunnlag> = vilkårsprøving(this, probe) private fun Behandlingsgrunnlag.beregnSykepenger(): Either<Behandlingsfeil, Sykepengeberegning> = sykepengeBeregning(this) private fun Sykepengeberegning.fattVedtak(): Either<Behandlingsfeil, SykepengeVedtak> = vedtak(this)
38.16
118
0.736373
49e4f8407ad61268e461ff38fda371bd49f1c388
322
sql
SQL
sql1_persediaan/buku_pengeluaran_barang_sql/buku_pengeluaran_dinkes.sql
muntaza/Open_Persediaan
8010839926cc6a357faf40481c7d7f43c1f66a3e
[ "BSD-2-Clause" ]
4
2020-05-26T07:52:34.000Z
2022-01-09T17:02:21.000Z
sql1_persediaan/buku_pengeluaran_barang_sql/buku_pengeluaran_dinkes.sql
muntaza/Open_Persediaan
8010839926cc6a357faf40481c7d7f43c1f66a3e
[ "BSD-2-Clause" ]
null
null
null
sql1_persediaan/buku_pengeluaran_barang_sql/buku_pengeluaran_dinkes.sql
muntaza/Open_Persediaan
8010839926cc6a357faf40481c7d7f43c1f66a3e
[ "BSD-2-Clause" ]
1
2020-05-26T07:52:36.000Z
2020-05-26T07:52:36.000Z
DROP VIEW IF EXISTS view_buku_pengeluaran_dinkes; CREATE VIEW view_buku_pengeluaran_dinkes AS SELECT * FROM view_buku_pengeluaran_kabupaten WHERE 1 = 1 AND id_skpd = 5; GRANT ALL PRIVILEGES ON view_buku_pengeluaran_dinkes TO lap_dinkes; REVOKE INSERT, UPDATE, DELETE ON view_buku_pengeluaran_dinkes FROM lap_dinkes;
18.941176
78
0.841615
04f557ebd4cd0e99c514db517fb64c514d2c5775
3,139
java
Java
DesignPattern/src/m2i/formation/java/Personne.java
anouvene/JAVA
067fbf78c3f844406e9aeba1b89a9248b5fc7651
[ "MIT" ]
null
null
null
DesignPattern/src/m2i/formation/java/Personne.java
anouvene/JAVA
067fbf78c3f844406e9aeba1b89a9248b5fc7651
[ "MIT" ]
1
2019-04-27T13:51:31.000Z
2019-04-27T13:51:31.000Z
DesignPattern/src/m2i/formation/java/Personne.java
anouvene/JAVA
067fbf78c3f844406e9aeba1b89a9248b5fc7651
[ "MIT" ]
1
2019-05-05T13:19:38.000Z
2019-05-05T13:19:38.000Z
package m2i.formation.java; public class Personne { private int _idPersonne; private String _nom; private String _prenom; private float _poids; private float _taille; private Genre _sexe; private int _idSociete; public Personne(int _idPersonne, String _nom, String _prenom, float _poids, float _taille, Genre _sexe) { super(); this._idPersonne = _idPersonne; this._nom = _nom; this._prenom = _prenom; this._poids = _poids; this._taille = _taille; this._sexe = _sexe; } public Personne(int idPersonne, String nom, String prenom, float poids, float taille, Genre sexe, int idSociete) { this._idPersonne = idPersonne; this._nom = nom; this._prenom = prenom; this._poids = poids; this._taille = taille; this._sexe = sexe; this._idSociete = idSociete; } // GETTERS & SETTERS public int get_idPersonne() { return _idPersonne; } public String get_nom() { return _nom; } public void set_idPersonne(int _idPersonne) { this._idPersonne = _idPersonne; } public void set_nom(String _nom) { this._nom = _nom; } public String get_prenom() { return _prenom; } public void set_prenom(String _prenom) { this._prenom = _prenom; } public float get_poids() { return _poids; } public void set_poids(float _poids) { this._poids = _poids; } public float get_taille() { return _taille; } public void set_taille(float _taille) { this._taille = _taille; } public Genre get_sexe() { return _sexe; } public void set_sexe(Genre _sexe) { this._sexe = _sexe; } public int get_idSociete() { return _idSociete; } public void set_idSociete(int _idSociete) { this._idSociete = _idSociete; } /** * IMC * @return float IMC */ public float IMC() { return this._poids/this._taille * this._taille; } /** * Poids mini * @return float Poids mini */ public float poidsMin() { return 19 * this._taille * this._taille; } /** * Poids maxi * @return float Poids maxi */ public float poidsMax() { return 25 * this._taille * this._taille; } /** * Poids ideal * @return float Taille ideal */ public float poidsIdeal() { if(this._sexe == Genre.MASCULIN) return 22 * this._taille * this._taille; else return 21 * this._taille * this._taille; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Personne [_nom="); builder.append(_nom); builder.append(", _prenom="); builder.append(_prenom); builder.append(", _poids="); builder.append(_poids); builder.append(", _taille="); builder.append(_taille); builder.append(", _sexe="); builder.append(_sexe); builder.append(", IMC()="); builder.append(IMC()); builder.append(", poidsMin()="); builder.append(poidsMin()); builder.append(", poidsMax()="); builder.append(poidsMax()); builder.append(", poidsIdeal()="); builder.append(poidsIdeal()); builder.append("]"); return builder.toString(); } }
19.867089
116
0.63842
ddf894d0753bb6fa6816d1cea0d90f55d7a66c62
3,263
php
PHP
core/helpers/php/validator.class.php
JVillator0/MonstersUniversity
96627c26c67c1c57dea2a60428c132474ac8fe56
[ "MIT" ]
2
2020-10-21T00:35:38.000Z
2020-10-24T23:15:53.000Z
core/helpers/php/validator.class.php
JVillator0/MonstersUniversity
96627c26c67c1c57dea2a60428c132474ac8fe56
[ "MIT" ]
null
null
null
core/helpers/php/validator.class.php
JVillator0/MonstersUniversity
96627c26c67c1c57dea2a60428c132474ac8fe56
[ "MIT" ]
null
null
null
<?php class cls_validator{ //remueve los espacios de todas las posiones del arreglo public function validateForm($fields){ foreach($fields as $index => $value){ $value = trim($value); $fields[$index] = $value; } return $fields; } //DE ESTA MANERA SE VALIDA EL XSS, ya que le aplicamos a todas las posiciones del arreglo enviado el metodo dicho //'strip_tags' quita todas las etiquetas html y php de un string, las remueve directamente //'htmlspecialchars' reemplaza los caracteres html y php con codigos especiales, se mostraran pero no se ejecutaran //'htmlentities' realiza lo mismo que la anterior, pero solo se utiliza cuando se usa una codificacion diferente a UTF-8 o ISO-8859-1 //las validaciones no deberian dejar pasar ningun caracter de ese tipo, pero por cualquier cosa, tambien existe este metodo public function validateXSS($fields){ $fields = array_map("htmlspecialchars", $fields); return $fields; } //verifica el valor utilizando una expresion regular que debe concordar con el valor enviado public function validateId($value){ return filter_var($value, FILTER_VALIDATE_INT, array('min_range' => 1)); } //verifica el valor utilizando una expresion regular que debe concordar con el valor enviado public function validateEmail($email){ return filter_var($email, FILTER_VALIDATE_EMAIL); } //verifica el valor utilizando una expresion regular que debe concordar con el valor enviado public function validateAlphabetic($value, $minimum, $maximum){ return preg_match("/^[a-zA-ZñÑáÁéÉíÍóÓúÚ\s]{".$minimum.",".$maximum."}$/", $value); } //verifica el valor utilizando una expresion regular que debe concordar con el valor enviado public function validateAlphanumeric($value, $minimum, $maximum){ return preg_match("/^[a-zA-Z0-9ñÑáÁéÉíÍóÓúÚ\s\.]{".$minimum.",".$maximum."}$/", $value); } //verifica el valor utilizando una expresion regular que debe concordar con el valor enviado public function validateMoney($value){ return preg_match("/^[0-9]+(?:\.[0-9]{1,2})?$/", $value); } //verifica el valor utilizando una expresion regular que debe concordar con el valor enviado public function validatePassword($value){ return strlen($value) >= 8 && preg_match("/^(?=.*[A-Z])/", $value) && preg_match("/^(?=.*[a-z])/", $value) && preg_match("/^(?=.*\d)(?=.*[\W_])/", $value); } //verifica el valor utilizando una expresion regular que debe concordar con el valor enviado public function validateTelephone($value){ return preg_match("/^\d{4}-\d{4}$/", $value); } //verifica el valor utilizando una expresion regular que debe concordar con el valor enviado public function validateDUI($value){ return preg_match("/^\d{8}-\d{1}$/", $value); } //verifica el valor utilizando una expresion regular que debe concordar con el valor enviado public function validateNIT($value){ return preg_match("/^\d{4}-\d{6}-\d{3}-\d{1}$/", $value); } //verifica el valor utilizando una expresion regular que debe concordar con el valor enviado public function validateDate($value){ return true && strlen($value) > 0; } //verifica el valor utilizando una expresion regular que debe concordar con el valor enviado public function validateStr($value){ return strlen($value) > 0; } } ?>
41.833333
157
0.724487
d26a7dea28ca5834ae32b895ce39f5737291cf4f
2,280
php
PHP
resources/views/admin/types/index.blade.php
mo3auya91/oreganoapps
100acdcd4c5b8eccda9ce807300e09eae5ecfdd1
[ "MIT" ]
null
null
null
resources/views/admin/types/index.blade.php
mo3auya91/oreganoapps
100acdcd4c5b8eccda9ce807300e09eae5ecfdd1
[ "MIT" ]
4
2021-02-02T18:01:32.000Z
2022-02-27T03:22:16.000Z
resources/views/admin/types/index.blade.php
mo3auya91/oreganoapps
100acdcd4c5b8eccda9ce807300e09eae5ecfdd1
[ "MIT" ]
null
null
null
@extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-12"> <div class="card"> <div class="card-header">Types</div> <div class="card-body"> <a href="{{route('types.create')}}" class="btn btn-success float-right mb-3"><i class="fas fa-plus"></i> Create </a> <div class="clearfix"></div> <table class="table table-bordered"> <thead> <tr> <th scope="col">#</th> <th scope="col">Title</th> <th scope="col">Slug</th> <th scope="col">Last Update</th> <th scope="col">Actions</th> </tr> </thead> <tbody> @foreach($types as $type) <tr id="type-row-{{$type->id}}"> <th scope="row">{{$type->id}}</th> <td>{{$type->title}}</td> <td>{{$type->slug}}</td> <td>{{\Carbon\Carbon::parse($type->updated_at)->diffForHumans()}}</td> <td> <a href="{{route('types.edit',['type'=>$type->id])}}" class="btn btn-link"><i class="fas fa-eye"></i> Edit</a> | <a href="javascript:" class="btn btn-link text-danger delete-type" data-id="{{$type->id}}"><i class="fas fa-trash"></i> Delete</a> </td> </tr> @endforeach </tbody> </table> </div> </div> </div> </div> </div> @endsection
47.5
117
0.307895
724011447c932af693b76ee2c604637aa6bd4f60
388
asm
Assembly
programs/oeis/093/A093918.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/093/A093918.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/093/A093918.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A093918: a(2k-1)=(2k-1)^2+k, a(2k)=6k^2+k+1: Last term in rows of triangle A093915. ; 2,8,11,27,28,58,53,101,86,156,127,223,176,302,233,393,298,496,371,611,452,738,541,877,638,1028,743,1191,856,1366,977,1553,1106,1752,1243,1963,1388,2186,1541,2421,1702,2668,1871,2927,2048,3198,2233,3481,2426,3776 mov $1,$0 add $0,1 pow $1,2 add $1,$0 add $0,$1 bin $1,2 mod $1,$0 add $1,$0 mov $0,$1
29.846154
213
0.675258
86680a803d7b8d09b5e3f6aa459400dbbfcc0a5c
213
swift
Swift
Source/Extensions/UIEdgeInsets+Utils.swift
tingxins/SwiftEntryKit
59b4a1fe18cb4a48ffe226dd14c8dce2767c3a54
[ "MIT" ]
5,899
2018-04-23T07:51:35.000Z
2022-03-31T18:43:11.000Z
Source/Extensions/UIEdgeInsets+Utils.swift
tingxins/SwiftEntryKit
59b4a1fe18cb4a48ffe226dd14c8dce2767c3a54
[ "MIT" ]
720
2015-01-01T03:06:30.000Z
2021-08-06T18:44:14.000Z
Source/Extensions/UIEdgeInsets+Utils.swift
tingxins/SwiftEntryKit
59b4a1fe18cb4a48ffe226dd14c8dce2767c3a54
[ "MIT" ]
535
2018-05-06T07:38:33.000Z
2022-03-25T15:40:49.000Z
// // UIEdgeInsets.swift // FBSnapshotTestCase // // Created by Daniel Huri on 4/21/18. // import UIKit extension UIEdgeInsets { var hasVerticalInsets: Bool { return top > 0 || bottom > 0 } }
14.2
38
0.629108
b290559efcb0f7f8b18eeaa3e6bbd8b389814fc0
188
kt
Kotlin
presentation/src/test/java/com/raiden/karpukhinomgupsdiplom/screens/info/InfoViewModelTest.kt
Raiden18/Integrity-control
a076b7b8ebb47d336c4c8a62992b860b29710e92
[ "Apache-2.0" ]
2
2019-05-09T17:44:48.000Z
2019-05-14T10:38:50.000Z
presentation/src/test/java/com/raiden/karpukhinomgupsdiplom/screens/info/InfoViewModelTest.kt
Raiden18/Integrity-control
a076b7b8ebb47d336c4c8a62992b860b29710e92
[ "Apache-2.0" ]
null
null
null
presentation/src/test/java/com/raiden/karpukhinomgupsdiplom/screens/info/InfoViewModelTest.kt
Raiden18/Integrity-control
a076b7b8ebb47d336c4c8a62992b860b29710e92
[ "Apache-2.0" ]
null
null
null
package com.raiden.karpukhinomgupsdiplom.screens.info import junitparams.JUnitParamsRunner import org.junit.runner.RunWith @RunWith(JUnitParamsRunner::class) open class InfoViewModelTest
26.857143
53
0.87234
a8f822aeb1475e28a75676c28aea0ac1ecd6c8a9
2,198
rs
Rust
lib/src/util/pid.rs
forbjok/chandler3
d6addb6da67f9973a678e9caea11858a7ac37e64
[ "Apache-2.0", "MIT" ]
null
null
null
lib/src/util/pid.rs
forbjok/chandler3
d6addb6da67f9973a678e9caea11858a7ac37e64
[ "Apache-2.0", "MIT" ]
null
null
null
lib/src/util/pid.rs
forbjok/chandler3
d6addb6da67f9973a678e9caea11858a7ac37e64
[ "Apache-2.0", "MIT" ]
null
null
null
use std::fs; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use sysinfo::{Pid, ProcessRefreshKind}; use tracing::{debug, error}; use crate::util; pub struct PidLock { path: PathBuf, } impl PidLock { pub fn acquire(path: impl AsRef<Path>) -> Option<Self> { let path = util::normalize_path(path); debug!("Trying to acquire PID lock at {}", path.display()); if path.exists() { debug!("PID file found at {:?}", path); if let Ok(mut file) = fs::File::open(&path) { let mut pid = String::new(); // Try to read content of PID-lock file into a string. if let Err(err) = file.read_to_string(&mut pid) { error!("Could not read PID-lock file: {}", err.to_string()); return None; } if let Ok(pid) = pid.parse::<Pid>() { debug!("File contains PID {}.", pid); if process_exists(pid) { // Process already exists, cannot get lock. debug!("Process with PID {} exists, cannot get lock.", pid); return None; } } } } // Try to create a PID file... if let Ok(mut file) = fs::File::create(&path) { // Write our PID to the newly created file. if let Err(err) = file.write(format!("{}", std::process::id()).as_bytes()) { error!("Could not write PID-lock file: {}", err.to_string()); return None; } } else { error!("Could not create PID-lock file!"); return None; }; Some(Self { path }) } } impl Drop for PidLock { fn drop(&mut self) { debug!("Dropping PID-lock at {}", self.path.display()); fs::remove_file(&self.path).expect("Could not remove PID-lock file!"); } } fn process_exists(pid: Pid) -> bool { use sysinfo::{RefreshKind, System, SystemExt}; let sys = System::new_with_specifics(RefreshKind::new().with_processes(ProcessRefreshKind::new())); sys.process(pid).is_some() }
30.957746
103
0.510919
3ea76c2a5fd7d5c744fa282d7ff9c1f5882f202e
2,651
h
C
Jx3Full/Source/Source/Server/SO3GameCenter/KFellowshipCenter.h
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
2
2021-07-31T15:35:01.000Z
2022-02-28T05:54:54.000Z
Jx3Full/Source/Source/Server/SO3GameCenter/KFellowshipCenter.h
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
null
null
null
Jx3Full/Source/Source/Server/SO3GameCenter/KFellowshipCenter.h
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
5
2021-02-03T10:25:39.000Z
2022-02-23T07:08:37.000Z
//////////////////////////////////////////////////////////////////////////////// // // FileName : KFellowshipCenter.h // Version : 1.0 // Creator : Lin Jiaqi // Create Date : 2007-07-19 15:04:58 // Comment : // Reconstructed by Jeffrey Chen, 2007-11-29. // //////////////////////////////////////////////////////////////////////////////// #ifndef _FELLOWSHIP_CENTER_H_ #define _FELLOWSHIP_CENTER_H_ #include <map> #include <set> #include <deque> #include <vector> #include <algorithm> #include "KGameServer.h" #include "KLRUCacheMap.h" // KGFellowshipCenter is just a fellowship data cache between game sever and database. // It does not understand the data structure of fellowship and does not responsible for the consistency. #define KG_FELLOWSHIP_DB_DATA_VERSION 1 struct KG_FELLOWSHIP_CACHE { int nUpdateCount; BYTE byData[0]; }; class KGFellowshipCenter { public: KGFellowshipCenter() { m_lCurrentTimeStamp = 0; m_lNextSaveTime = 0; }; ~KGFellowshipCenter() {}; BOOL Init(); void UnInit(); void Active(); BOOL UpdateFellowshipData(DWORD dwPlayerID, size_t uDataLength, BYTE byData[]); BOOL GetFellowshipData(DWORD dwPlayerID); BOOL SaveFellowshipData(DWORD dwPlayerID); void SaveAllFellowshipData(); void OnLoadFellowshipData(DWORD dwPlayerID, BYTE* pbyFellowshipData, size_t uDataSize); private: struct OnFellowshipRecycleFunc { OnFellowshipRecycleFunc() : m_pFellowshipCenter(NULL) {}; inline bool operator() (DWORD dwPlayerID, IKG_Buffer*& rpiBuffer) { KG_FELLOWSHIP_CACHE* pFellowshipCache = NULL; assert(m_pFellowshipCenter); assert(rpiBuffer->GetSize() >= sizeof(KG_FELLOWSHIP_CACHE)); pFellowshipCache = (KG_FELLOWSHIP_CACHE*)rpiBuffer->GetData(); assert(pFellowshipCache); if (pFellowshipCache->nUpdateCount) { m_pFellowshipCenter->SaveFellowshipData(dwPlayerID); pFellowshipCache->nUpdateCount = 0; } KG_COM_RELEASE(rpiBuffer); return true; } KGFellowshipCenter* m_pFellowshipCenter; } m_CacheRecycleFunc; KLRUCahceMap<DWORD, IKG_Buffer*, OnFellowshipRecycleFunc> m_FellowshipCache; time_t m_lCurrentTimeStamp; time_t m_lNextSaveTime; }; #endif //_FELLOWSHIP_CENTER_H_ //////////////////////////////////////////////////////////////////////////
28.202128
106
0.577518
ee1b9a5db6b8feeb19af2ffc5fce2af1c9d491c8
918
asm
Assembly
EngineHacks/CoreHacks/CombatArt/AnimeEffect/BattleGenerateHitFix.asm
MokhaLeee/FE16re-Proto
a3bf9ea299f117de0dc90aa4b139bd4f8167418e
[ "MIT" ]
5
2021-11-28T19:51:03.000Z
2021-12-25T06:15:13.000Z
EngineHacks/CoreHacks/CombatArt/AnimeEffect/BattleGenerateHitFix.asm
MokhaLeee/FE16re-Proto
a3bf9ea299f117de0dc90aa4b139bd4f8167418e
[ "MIT" ]
null
null
null
EngineHacks/CoreHacks/CombatArt/AnimeEffect/BattleGenerateHitFix.asm
MokhaLeee/FE16re-Proto
a3bf9ea299f117de0dc90aa4b139bd4f8167418e
[ "MIT" ]
null
null
null
.thumb .macro blh to,reg=r4 push {\reg} ldr \reg,=\to mov r14,\reg pop {\reg} .short 0xF800 .endm .macro SET_FUNC name, value .global \name .type \name, function .set \name, \value .endm .macro SET_DATA name, value .global \name .type \name, object .set \name, \value .endm SET_DATA gBattleHitIterator, 0x203A608 .global BattleGenerateHitFix .type BattleGenerateHitFix, function @ ORG $2B884 BattleGenerateHitFix: push {r0-r3, lr} blh isCombatArt cmp r0, #1 bne .L1_Nope .L0_CombatArt: @ gBattleHitIterator->info |= BATTLE_HIT_ATTR_SURESHOT ldr r3, =gBattleHitIterator ldr r3,[r3] ldr r0,[r3] ldr r1, =0x4000 orr r0, r1, r0 str r0,[r3] .L1_Nope: pop {r0-r3} pop {r0} mov lr, r0 @ Vanilla 2BB84 mov r0, #0x13 ldsb r0,[r4, r0] cmp r0, #0 bne .L2 ldr r1, =0x802B893 bx r1 .L2: ldsb r0,[r5, r0] ldr r1, =0x802B88F bx r1 .align .ltorg
13.304348
55
0.653595
f97e32d6db1e5ddfb74f4d30672fa5f7cd6d6587
1,968
dart
Dart
lib/widgets/item_list/items/subclass/subclass_image.widget.dart
TheBrenny/littlelight
8b3aed001beb8eee61b4897a606a920f2ae59d99
[ "MIT" ]
140
2019-04-04T02:35:15.000Z
2022-03-27T09:52:36.000Z
lib/widgets/item_list/items/subclass/subclass_image.widget.dart
TheBrenny/littlelight
8b3aed001beb8eee61b4897a606a920f2ae59d99
[ "MIT" ]
123
2019-04-04T15:51:56.000Z
2022-03-30T01:30:04.000Z
lib/widgets/item_list/items/subclass/subclass_image.widget.dart
TheBrenny/littlelight
8b3aed001beb8eee61b4897a606a920f2ae59d99
[ "MIT" ]
30
2019-04-04T09:53:12.000Z
2022-03-27T07:21:15.000Z
import 'package:bungie_api/models/destiny_inventory_item_definition.dart'; import 'package:bungie_api/models/destiny_item_component.dart'; import 'package:bungie_api/models/destiny_item_instance_component.dart'; import 'package:bungie_api/models/destiny_talent_grid_definition.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:little_light/utils/destiny_data.dart'; import 'package:little_light/utils/destiny_utils/subclass_talentgrid_info.dart'; import 'package:little_light/widgets/common/destiny_item.stateful_widget.dart'; class SubClassImageWidget extends DestinyItemStatefulWidget { SubClassImageWidget( DestinyItemComponent item, DestinyInventoryItemDefinition definition, DestinyItemInstanceComponent instanceInfo) : super(item, definition, instanceInfo); @override _SubClassImageWidgetState createState() => _SubClassImageWidgetState(); } class _SubClassImageWidgetState extends DestinyItemState<SubClassImageWidget> { String imagePath; bool loaded = false; @override void initState() { super.initState(); getDefinitions(); } getDefinitions() async { var talentGridDef = await widget.manifest .getDefinition<DestinyTalentGridDefinition>( definition.talentGrid.talentGridHash); var talentGrid = widget.profile.getTalentGrid(item?.itemInstanceId); var cat = extractTalentGridNodeCategory(talentGridDef, talentGrid); var path = DestinyData.getSubclassImagePath(definition.classType, definition.talentGrid.hudDamageType, cat?.identifier); try { await rootBundle.load(path); imagePath = path; } catch (e) {} loaded = true; setState(() {}); } @override Widget build(BuildContext context) { if (imagePath != null) { return Image.asset( imagePath, fit: BoxFit.fitWidth, alignment: Alignment.topRight, ); } return Container(); } }
32.8
80
0.748476
1e88262ce8b9b4c3b00ba6e6eecc8f1dd11f9181
39
lua
Lua
[models]/JStreamer3/Settings/settings_S.lua
BesteerHU/mtavc
b125c26cbc06afb24f0cfc32d508bf370440f5ca
[ "MIT" ]
null
null
null
[models]/JStreamer3/Settings/settings_S.lua
BesteerHU/mtavc
b125c26cbc06afb24f0cfc32d508bf370440f5ca
[ "MIT" ]
null
null
null
[models]/JStreamer3/Settings/settings_S.lua
BesteerHU/mtavc
b125c26cbc06afb24f0cfc32d508bf370440f5ca
[ "MIT" ]
null
null
null
unloadMap = true AllowInteriors = false
19.5
22
0.820513
1674a6a1835db0163c030e79b182aa4edbc86a90
138
h
C
include/core/ds.h
FelixLee1995/Jupiter
90db14069f121248d392aeb1bb9f60a4d0175f93
[ "BSD-3-Clause" ]
1
2021-07-14T17:05:16.000Z
2021-07-14T17:05:16.000Z
include/core/ds.h
FelixLee1995/Jupiter
90db14069f121248d392aeb1bb9f60a4d0175f93
[ "BSD-3-Clause" ]
null
null
null
include/core/ds.h
FelixLee1995/Jupiter
90db14069f121248d392aeb1bb9f60a4d0175f93
[ "BSD-3-Clause" ]
1
2021-07-15T06:23:15.000Z
2021-07-15T06:23:15.000Z
// // Created by felix lee on 2020/12/14. // #ifndef JUPITER_DS_H #define JUPITER_DS_H #include "CBaseType.h" #endif //JUPITER_DS_H
9.857143
38
0.702899
d6b2aaa0271b009739118d0ff1ef901e370745f0
2,595
swift
Swift
Archive/Manager/InstagramStoryShareManager.swift
TTOzzi/Archive_iOS
9bd8096be02de50b9d75bb48619c56e4f0fcd782
[ "MIT" ]
6
2021-10-25T00:59:48.000Z
2022-02-14T13:38:04.000Z
Archive/Manager/InstagramStoryShareManager.swift
TTOzzi/Archive_iOS
9bd8096be02de50b9d75bb48619c56e4f0fcd782
[ "MIT" ]
23
2021-09-16T13:25:21.000Z
2022-03-18T12:30:06.000Z
Archive/Manager/InstagramStoryShareManager.swift
TTOzzi/Archive_iOS
9bd8096be02de50b9d75bb48619c56e4f0fcd782
[ "MIT" ]
2
2021-09-11T08:00:10.000Z
2021-09-30T14:35:06.000Z
// // InstagramStoryShareManager.swift // Archive // // Created by hanwe on 2021/11/10. // import UIKit class InstagramStoryShareManager: NSObject { // MARK: private property private let instagramStoryScheme: String = "instagram-stories://share" private let stickerImageKey: String = "com.instagram.sharedSticker.stickerImage" private let backgroundTopColorKey: String = "com.instagram.sharedSticker.backgroundTopColor" private let backgroundBottomColorKey: String = "com.instagram.sharedSticker.backgroundBottomColor" // MARK: property // MARK: lifeCycle // MARK: private func private func colorToHexStr(_ color: UIColor) -> String { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 color.getRed(&r, green: &g, blue: &b, alpha: &a) let rgb: Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0 return NSString(format: "#%06x", rgb) as String } // MARK: func static let shared: InstagramStoryShareManager = { let instance = InstagramStoryShareManager() return instance }() func share(view: UIView, backgroundTopColor: UIColor, backgroundBottomColor: UIColor, completion: @escaping (Bool) -> Void, failure: @escaping (String) -> Void) { if let storyShareURL = URL(string: self.instagramStoryScheme) { if UIApplication.shared.canOpenURL(storyShareURL) { let renderer = UIGraphicsImageRenderer(size: view.bounds.size) let renderImage = renderer.image { _ in view.drawHierarchy(in: view.bounds, afterScreenUpdates: true) } guard let imageData = renderImage.pngData() else { return } let pasteboardItems: [String: Any] = [ self.stickerImageKey: imageData, self.backgroundTopColorKey: colorToHexStr(backgroundTopColor), self.backgroundBottomColorKey: colorToHexStr(backgroundBottomColor) ] let pasteboardOptions = [ UIPasteboard.OptionsKey.expirationDate: Date().addingTimeInterval(300) ] UIPasteboard.general.setItems([pasteboardItems], options: pasteboardOptions) UIApplication.shared.open(storyShareURL, options: [:], completionHandler: { value in completion(value) }) } else { failure("인스타그램이 필요합니다") } } } }
37.608696
166
0.60501
e9b278cbc56cfa38ac9441681c3ec97494681134
1,702
dart
Dart
lib/src/parser/json/post.dart
Wetbikeboy2500/web_content_parser
c63c6087c1d866bd39a564aafb580678d0b0f8e7
[ "MIT" ]
1
2022-01-05T03:55:31.000Z
2022-01-05T03:55:31.000Z
lib/src/parser/json/post.dart
Wetbikeboy2500/web_content_parser
c63c6087c1d866bd39a564aafb580678d0b0f8e7
[ "MIT" ]
2
2021-08-10T00:12:15.000Z
2021-12-07T03:08:03.000Z
lib/src/parser/json/post.dart
Wetbikeboy2500/web_content_parser
c63c6087c1d866bd39a564aafb580678d0b0f8e7
[ "MIT" ]
null
null
null
import 'package:json_annotation/json_annotation.dart'; import './author.dart'; import './id.dart'; part 'post.g.dart'; @JsonSerializable(explicitToJson: true) class Post { final String coverurl; final bool completed; final String altnames; final List<String> categories; final String type; final String description; @JsonKey(fromJson: _id) final ID id; @JsonKey(fromJson: _authors) final List<Author> authors; final String name; final int chapterNumber; @JsonKey(fromJson: _dateTime, toJson: _dateTimeString) final DateTime? released; Post({ required this.id, required this.name, this.coverurl = '', this.completed = false, this.altnames = '', this.authors = const <Author>[], this.categories = const <String>[], this.description = '', this.type = 'unknown', this.chapterNumber = 0, this.released, }); factory Post.fromJson(Map<String, dynamic> json) => _$PostFromJson(json); Map<String, dynamic> toJson() => _$PostToJson(this); static List<Author> _authors(List<dynamic>? authorList) { if (authorList != null) { if (authorList.isNotEmpty) { return authorList.map((dynamic auth) => (auth is Author) ? auth : Author.fromJson(auth)).toList(); } else { return const <Author>[]; } } else { return const <Author>[]; } } static ID _id(dynamic id) { return (id is ID) ? id : ID.fromJson(id); } static DateTime? _dateTime(dynamic time) { if (time == null) { return null; } return (time is DateTime) ? time : DateTime.parse(time as String); } static String? _dateTimeString(DateTime? time) { return time?.toIso8601String(); } }
24.666667
106
0.650411
c3c4450b1aa89ae0cbf113ed25212664f80ea935
108
go
Go
server.go
QPixel/youtube-irc
fd612bd5aeb85e346add5cd6eba95b277e3183db
[ "MIT" ]
null
null
null
server.go
QPixel/youtube-irc
fd612bd5aeb85e346add5cd6eba95b277e3183db
[ "MIT" ]
null
null
null
server.go
QPixel/youtube-irc
fd612bd5aeb85e346add5cd6eba95b277e3183db
[ "MIT" ]
null
null
null
package youtubeirc // server.go // This contains all the logic for operating the WebSocket and IRC servers
21.6
74
0.787037
951c890b9f4c4c94e2285d5fb09781748be55a12
2,238
lua
Lua
Framework/EsoUi/ingame/help/gamepad/help_itemassistance_gamepad.lua
martin-repo/eso-addon-framework
5a0873e624abee2b560b47cdd8571bb24b526663
[ "MIT" ]
3
2021-09-19T00:31:05.000Z
2021-12-22T07:30:15.000Z
Framework/EsoUi/ingame/help/gamepad/help_itemassistance_gamepad.lua
martin-repo/eso-addon-framework
5a0873e624abee2b560b47cdd8571bb24b526663
[ "MIT" ]
null
null
null
Framework/EsoUi/ingame/help/gamepad/help_itemassistance_gamepad.lua
martin-repo/eso-addon-framework
5a0873e624abee2b560b47cdd8571bb24b526663
[ "MIT" ]
null
null
null
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:26' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] ZO_Help_ItemAssistance_Gamepad = ZO_Help_MechanicAssistance_Gamepad:Subclass() function ZO_Help_ItemAssistance_Gamepad:New(...) return ZO_Help_MechanicAssistance_Gamepad.New(self, ...) end function ZO_Help_ItemAssistance_Gamepad:Initialize(control) ZO_Help_MechanicAssistance_Gamepad.Initialize(self, control, ZO_ITEM_ASSISTANCE_CATEGORIES_DATA) self:SetGoToDetailsSourceKeybindText(GetString(SI_GAMEPAD_HELP_GO_TO_INVENTORY_KEYBIND)) self:SetDetailsHeader(GetString(SI_CUSTOMER_SERVICE_ITEM_NAME)) self:SetDetailsInstructions(GetString(SI_CUSTOMER_SERVICE_ITEM_ASSISTANCE_NAME_INSTRUCTIONS)) end function ZO_Help_ItemAssistance_Gamepad:AddDescriptionEntry() --Do nothing, because we don't want item assistance having a description field anymore end function ZO_Help_ItemAssistance_Gamepad:GetSceneName() return "helpItemAssistanceGamepad" end function ZO_Help_ItemAssistance_Gamepad:GoToDetailsSourceScene() SCENE_MANAGER:Push("gamepad_inventory_root") end function ZO_Help_ItemAssistance_Gamepad:GetFieldEntryTitle() return GetString(SI_CUSTOMER_SERVICE_ITEM_ASSISTANCE) end function ZO_Help_ItemAssistance_Gamepad:RegisterDetails() local savedDetails = self:GetSavedField(ZO_HELP_TICKET_FIELD_TYPE.DETAILS) if savedDetails then SetCustomerServiceTicketItemTargetByLink(savedDetails) end end function ZO_Help_ItemAssistance_Gamepad:GetDisplayedDetails() local savedDetails = self:GetSavedField(ZO_HELP_TICKET_FIELD_TYPE.DETAILS) if savedDetails then return zo_strformat(SI_TOOLTIP_ITEM_NAME, GetItemLinkName(savedDetails)) else return self:GetDetailsInstructions() end end function ZO_Help_ItemAssistance_Gamepad_OnInitialize(control) HELP_ITEM_ASSISTANCE_GAMEPAD = ZO_Help_ItemAssistance_Gamepad:New(control) end
39.263158
100
0.773905
764619f0b73b0d21a2057c5e0dc9c2c90b0fa6a8
102
sql
SQL
gpdb/contrib/postgis/raster/test/regress/check_gdal.sql
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
3
2017-12-10T16:41:21.000Z
2020-07-08T12:59:12.000Z
gpdb/contrib/postgis/raster/test/regress/check_gdal.sql
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
gpdb/contrib/postgis/raster/test/regress/check_gdal.sql
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
4
2017-12-10T16:41:35.000Z
2020-11-28T12:20:30.000Z
SELECT CASE WHEN strpos(postgis_gdal_version(), 'GDAL_DATA') <> 0 THEN false ELSE NULL END;
14.571429
55
0.686275
85afe719135ec10d180bf5789cde8c71bac03895
763
js
JavaScript
Resources/config/file_list.js
loop-recur/neotvremote
4bb18fd71a3d945140c9768c956288fcd6e569a0
[ "Apache-2.0" ]
null
null
null
Resources/config/file_list.js
loop-recur/neotvremote
4bb18fd71a3d945140c9768c956288fcd6e569a0
[ "Apache-2.0" ]
null
null
null
Resources/config/file_list.js
loop-recur/neotvremote
4bb18fd71a3d945140c9768c956288fcd6e569a0
[ "Apache-2.0" ]
null
null
null
FileList = [ "config/channels.js", "controllers/favorites.js", "controllers/remote.js", "controllers/searches.js", "controllers/hosts.js", "controllers/settings.js", "controllers/feedback.js", "helpers/application.js", "helpers/ui.js", "lib/benchmarker.js", "lib/bonjour.js", "lib/channel.js", "lib/channel_download.js", "lib/favorites.js", "lib/fb_graph.js", "lib/feedback.js", "lib/hosts.js", "lib/xbmc.js", "layouts/application.js", "views/channels.js", "views/channel_list.js", "views/favorites/index.js", "views/favorites/edit.js", "views/feedback/index.js", "views/gesture.js", "views/hosts/index.js", "views/hosts/show.js", "views/play_controls.js", "views/remote.js", "views/searches/index.js", "views/settings/index.js" ];
22.441176
28
0.697248
c2706045dd40332319f02aab71d29e0bc6afc105
1,492
go
Go
main.go
kjlyon/snap-relay
ee1d22b9a6021279549beca706966618d2f12028
[ "Apache-2.0" ]
null
null
null
main.go
kjlyon/snap-relay
ee1d22b9a6021279549beca706966618d2f12028
[ "Apache-2.0" ]
null
null
null
main.go
kjlyon/snap-relay
ee1d22b9a6021279549beca706966618d2f12028
[ "Apache-2.0" ]
null
null
null
/* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2017 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "github.com/intelsdi-x/snap-plugin-lib-go/v1/plugin" "github.com/intelsdi-x/snap-relay/graphite" "github.com/intelsdi-x/snap-relay/relay" "github.com/intelsdi-x/snap-relay/statsd" ) const ( pluginName = "plugin-relay" pluginVersion = 1 ) func main() { plugin.Flags = append(plugin.Flags, graphite.GraphiteTCPListenPortFlag) plugin.Flags = append(plugin.Flags, graphite.GraphiteUDPListenPortFlag) plugin.Flags = append(plugin.Flags, statsd.StatsdTCPListenPortFlag) plugin.Flags = append(plugin.Flags, statsd.StatsdUDPListenPortFlag) plugin.StartStreamCollector( relay.New( graphite.TCPListenPortOption(&graphite.GraphiteTCPPort), graphite.UDPListenPortOption(&graphite.GraphiteUDPPort), statsd.TCPListenPortOption(&statsd.StatsdTCPPort), statsd.UDPListenPortOption(&statsd.StatsdUDPPort), ), pluginName, pluginVersion, ) }
30.44898
72
0.782842
cb5bbf2000272ee72e147197b55b88d334d87d08
115
kt
Kotlin
src/main/kotlin/javabot/operations/throttle/NickServViolationException.kt
topriddy/javabot
cd21e5a9408190a065fbf6d284744188f2b00089
[ "BSD-3-Clause" ]
31
2015-01-06T16:03:04.000Z
2019-04-12T21:55:57.000Z
src/main/kotlin/javabot/operations/throttle/NickServViolationException.kt
topriddy/javabot
cd21e5a9408190a065fbf6d284744188f2b00089
[ "BSD-3-Clause" ]
172
2015-01-11T13:23:02.000Z
2021-07-20T11:55:58.000Z
src/main/kotlin/javabot/operations/throttle/NickServViolationException.kt
topriddy/javabot
cd21e5a9408190a065fbf6d284744188f2b00089
[ "BSD-3-Clause" ]
26
2015-01-06T16:03:05.000Z
2021-08-06T13:14:56.000Z
package javabot.operations.throttle class NickServViolationException(message: String) : RuntimeException(message)
28.75
77
0.86087
c23501e1bba2e9fa64ef6f4f24b96d68faaeb1fa
1,664
go
Go
sink/filter.go
chatoooo/logoon
4f3cafa6fcd40fb8c1d4f4669eae72b792338776
[ "MIT" ]
null
null
null
sink/filter.go
chatoooo/logoon
4f3cafa6fcd40fb8c1d4f4669eae72b792338776
[ "MIT" ]
null
null
null
sink/filter.go
chatoooo/logoon
4f3cafa6fcd40fb8c1d4f4669eae72b792338776
[ "MIT" ]
null
null
null
package sink import ( "github.com/chatoooo/logoon/core" //"fmt" ) type StandardSinkFilter struct { severityComparator SeverityComparator filter core.Filter } func (this *StandardSinkFilter) SetFilter(filter core.Filter) { this.filter = filter //fmt.Printf("Setting filter: %#v,\n%#v\n\n", filter, this.filter) } func (this *StandardSinkFilter) shouldSeverity(msg core.LogMessage) bool { var result bool switch this.filter.Severity.CmpOp { case core.FILTER_CMP_NONE: result = true case core.FILTER_CMP_GE: result = this.severityComparator.ge(msg.Severity(), this.filter.Severity.Level) case core.FILTER_CMP_EQ: result = this.severityComparator.eq(msg.Severity(), this.filter.Severity.Level) case core.FILTER_CMP_LT: result = this.severityComparator.lt(msg.Severity(), this.filter.Severity.Level) case core.FILTER_CMP_GT: result = this.severityComparator.gt(msg.Severity(), this.filter.Severity.Level) } return result } func (this *StandardSinkFilter) shouldTags(msg core.LogMessage) bool { if this.filter.Tags != nil && len(this.filter.Tags) > 0 { msgTags := msg.Tags() for _, filterTag := range this.filter.Tags { for _, messageTag := range msgTags { if filterTag == messageTag { return true } } } return false } return true } func (this *StandardSinkFilter) ShouldOutput(msg core.LogMessage) bool { var severity, tags bool severity = this.shouldSeverity(msg) if !severity { return severity } tags = this.shouldTags(msg) if this.filter.TagsExclude { tags = !tags } //fmt.Printf("ShouldOutput: severity:%v, tags:%v, filter: %#v\n\n", severity, tags, this.filter) return tags }
25.6
97
0.722356
0fa0b3715c54dd55a52e71a712bdae22942e2067
727
swift
Swift
Sources/Date+StartEnd.swift
chipp/DateUtilities
0823f2fee83ba76e2cf8de0c694632452e9b076c
[ "MIT" ]
null
null
null
Sources/Date+StartEnd.swift
chipp/DateUtilities
0823f2fee83ba76e2cf8de0c694632452e9b076c
[ "MIT" ]
2
2018-01-17T10:26:04.000Z
2020-01-21T08:30:23.000Z
Sources/Date+StartEnd.swift
chipp/DateUtilities
0823f2fee83ba76e2cf8de0c694632452e9b076c
[ "MIT" ]
null
null
null
// // Created by Vladimir Burdukov on 8/26/16. // import Foundation public extension Date { public func start(of unit: Calendar.Component) -> Date { var date = Date() var interval: TimeInterval = 0 guard Context.calendar.dateInterval(of: unit, start: &date, interval: &interval, for: self) else { assertionFailure() return date } return date } public func end(of unit: Calendar.Component) -> Date { var date = Date() var interval: TimeInterval = 0 guard Context.calendar.dateInterval(of: unit, start: &date, interval: &interval, for: self) else { assertionFailure() return date } interval -= 0.001 return date.addingTimeInterval(interval) } }
22.030303
102
0.656121
017d53ffaeb978292587dee33c510829c6a10efd
1,105
kt
Kotlin
corekit/src/main/java/com/laohu/kit/extensions/FragmentExtension.kt
huyongli/AndroidKit
36990176c66902a30606636f469743f3ac94a480
[ "Apache-2.0" ]
null
null
null
corekit/src/main/java/com/laohu/kit/extensions/FragmentExtension.kt
huyongli/AndroidKit
36990176c66902a30606636f469743f3ac94a480
[ "Apache-2.0" ]
null
null
null
corekit/src/main/java/com/laohu/kit/extensions/FragmentExtension.kt
huyongli/AndroidKit
36990176c66902a30606636f469743f3ac94a480
[ "Apache-2.0" ]
null
null
null
package com.laohu.kit.extensions import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider inline fun <reified T : ViewModel> Fragment.getViewModel(noinline creator: (() -> T)? = null): T { return if (creator == null) { ViewModelProvider(this).get(T::class.java) } else { ViewModelProvider(this, SimpleViewModelFactory(creator)).get(T::class.java) } } inline fun <reified T : ViewModel> Fragment.getActivityViewModel(noinline creator: (() -> T)? = null): T { return activity!!.getViewModel(creator) } inline fun <reified T : ViewDataBinding> Fragment.dataBindingView(@LayoutRes layoutId: Int, parent: ViewGroup?): T { val inflater = LayoutInflater.from(this.context) val binding = DataBindingUtil.inflate<T>(inflater, layoutId, parent, false) binding.lifecycleOwner = viewLifecycleOwner return binding }
38.103448
116
0.761086
f9ff195b5248d536c70e0099f9092456ab97d98a
383
go
Go
event_test.go
echocat/slf4g
6522a0078041ea12c4487b992b3ba766f24ce0ab
[ "MIT" ]
null
null
null
event_test.go
echocat/slf4g
6522a0078041ea12c4487b992b3ba766f24ce0ab
[ "MIT" ]
null
null
null
event_test.go
echocat/slf4g
6522a0078041ea12c4487b992b3ba766f24ce0ab
[ "MIT" ]
null
null
null
package log type entries []entry func (instance *entries) add(key string, value interface{}) { *instance = append(*instance, entry{key, value}) } func (instance *entries) consumer() func(key string, value interface{}) error { return func(key string, value interface{}) error { instance.add(key, value) return nil } } type entry struct { key string value interface{} }
19.15
79
0.70235
fba161d43df5848924ece6bcdd1dc7fdc61d2d57
17,819
java
Java
src/main/java/carpet/helpers/FeatureGenerator.java
Oliver-makes-code/fabric-carpet
f12b2d819d4b6b8580ab5229d096cdd583e6bd80
[ "MIT" ]
1
2022-03-09T03:35:27.000Z
2022-03-09T03:35:27.000Z
src/main/java/carpet/helpers/FeatureGenerator.java
Oliver-makes-code/fabric-carpet
f12b2d819d4b6b8580ab5229d096cdd583e6bd80
[ "MIT" ]
null
null
null
src/main/java/carpet/helpers/FeatureGenerator.java
Oliver-makes-code/fabric-carpet
f12b2d819d4b6b8580ab5229d096cdd583e6bd80
[ "MIT" ]
null
null
null
package carpet.helpers; import carpet.CarpetSettings; import carpet.fakes.ChunkGeneratorInterface; import com.mojang.datafixers.util.Pair; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.OptionalInt; import java.util.Random; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; import net.minecraft.core.QuartPos; import net.minecraft.core.Registry; import net.minecraft.data.worldgen.ProcessorLists; import net.minecraft.data.worldgen.placement.PlacementUtils; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.tags.BiomeTags; import net.minecraft.util.valueproviders.ConstantInt; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.chunk.ChunkGenerator; import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.feature.ConfiguredStructureFeature; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.StructureFeature; import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.JigsawConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.SimpleRandomFeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.TreeConfiguration; import net.minecraft.world.level.levelgen.feature.featuresize.TwoLayersFeatureSize; import net.minecraft.world.level.levelgen.feature.foliageplacers.BlobFoliagePlacer; import net.minecraft.world.level.levelgen.feature.foliageplacers.FancyFoliagePlacer; import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider; import net.minecraft.world.level.levelgen.structure.BoundingBox; import net.minecraft.world.level.levelgen.structure.StructureSet; import net.minecraft.world.level.levelgen.structure.pools.StructurePoolElement; import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool; import net.minecraft.world.level.levelgen.feature.treedecorators.BeehiveDecorator; import net.minecraft.world.level.levelgen.feature.trunkplacers.FancyTrunkPlacer; import net.minecraft.world.level.levelgen.feature.trunkplacers.StraightTrunkPlacer; import net.minecraft.world.level.levelgen.placement.PlacedFeature; import net.minecraft.world.level.levelgen.structure.StructureStart; import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement; public class FeatureGenerator { public static final Object boo = new Object(); synchronized public static Boolean plop(String featureName, ServerLevel world, BlockPos pos) { Thing custom = featureMap.get(featureName); if (custom != null) { return custom.plop(world, pos); } ResourceLocation id = new ResourceLocation(featureName); ConfiguredStructureFeature<?, ?> structureFeature = world.registryAccess().registryOrThrow(Registry.CONFIGURED_STRUCTURE_FEATURE_REGISTRY).get(id); if (structureFeature != null) { return plopAnywhere( structureFeature, world, pos, world.getChunkSource().getGenerator(), false); } ConfiguredFeature<?, ?> configuredFeature = world.registryAccess().registryOrThrow(Registry.CONFIGURED_FEATURE_REGISTRY).get(id); if (configuredFeature != null) { CarpetSettings.skipGenerationChecks.set(true); try { return configuredFeature.place(world, world.getChunkSource().getGenerator(), world.random, pos); } finally { CarpetSettings.skipGenerationChecks.set(false); } } StructureFeature<?> structure = Registry.STRUCTURE_FEATURE.get(id); if (structure != null) { ConfiguredStructureFeature<?,?> configuredStandard = getDefaultFeature(structure, world, pos); if (configuredStandard != null) return plopAnywhere(configuredStandard, world, pos, world.getChunkSource().getGenerator(), false); } Feature<?> feature = Registry.FEATURE.get(id); if (feature != null) { ConfiguredFeature<?,?> configuredStandard = getDefaultFeature(feature, world, pos, true); if (configuredStandard != null) { CarpetSettings.skipGenerationChecks.set(true); try { return configuredStandard.place(world, world.getChunkSource().getGenerator(), world.random, pos); } finally { CarpetSettings.skipGenerationChecks.set(false); } } } return null; } public static ConfiguredStructureFeature<?, ?> resolveConfiguredStructure(String name, ServerLevel world, BlockPos pos) { ResourceLocation id = new ResourceLocation(name); ConfiguredStructureFeature<?, ?> configuredStructureFeature = world.registryAccess().registryOrThrow(Registry.CONFIGURED_STRUCTURE_FEATURE_REGISTRY).get(id); if (configuredStructureFeature != null) return configuredStructureFeature; StructureFeature<?> structureFeature = Registry.STRUCTURE_FEATURE.get(id); if (structureFeature == null) return null; return getDefaultFeature(structureFeature, world, pos); } synchronized public static Boolean plopGrid(ConfiguredStructureFeature<?, ?> structureFeature, ServerLevel world, BlockPos pos) { return plopAnywhere( structureFeature, world, pos, world.getChunkSource().getGenerator(), true); } @FunctionalInterface private interface Thing { Boolean plop(ServerLevel world, BlockPos pos); } private static Thing simplePlop(ConfiguredFeature<?,?> feature) { return (w, p) -> { CarpetSettings.skipGenerationChecks.set(true); try { return feature.place(w, w.getChunkSource().getGenerator(), w.random, p); } finally { CarpetSettings.skipGenerationChecks.set(false); } }; } private static <FC extends FeatureConfiguration, F extends Feature<FC>> Thing simplePlop(F feature, FC config) { return simplePlop(new ConfiguredFeature<>(feature, config)); } private static Thing simpleTree(TreeConfiguration config) { //config.ignoreFluidCheck(); return simplePlop(new ConfiguredFeature(Feature.TREE, config)); } private static Thing spawnCustomStructure(ConfiguredStructureFeature<?,?> structure) { return setupCustomStructure(structure,false); } private static Thing setupCustomStructure(ConfiguredStructureFeature<?,?> structure, boolean wireOnly) { return (w, p) -> plopAnywhere(structure, w, p, w.getChunkSource().getGenerator(), wireOnly); } public static Boolean spawn(String name, ServerLevel world, BlockPos pos) { if (featureMap.containsKey(name)) return featureMap.get(name).plop(world, pos); return null; } private static ConfiguredStructureFeature<?, ?> getDefaultFeature(StructureFeature<?> structure, ServerLevel world, BlockPos pos) { // would be nice to have a way to grab structures of this type for position Holder<Biome> existingBiome = world.getBiome(pos); ConfiguredStructureFeature<?, ?> result = null; for (var confstr : world.registryAccess().registryOrThrow(Registry.CONFIGURED_STRUCTURE_FEATURE_REGISTRY).entrySet().stream(). filter(cS -> cS.getValue().feature == structure).map(Map.Entry::getValue).toList()) { result = confstr; if (confstr.biomes.contains(existingBiome)) return result; } return result; } private static ConfiguredFeature<?, ?> getDefaultFeature(Feature<?> feature, ServerLevel world, BlockPos pos, boolean tryHard) { List<HolderSet<PlacedFeature>> configuredStepFeatures = world.getBiome(pos).value().getGenerationSettings().features(); for (HolderSet<PlacedFeature> step: configuredStepFeatures) for (Holder<PlacedFeature> provider: step) { if (provider.value().feature().value().feature() == feature) return provider.value().feature().value(); } if (!tryHard) return null; return world.registryAccess().registryOrThrow(Registry.CONFIGURED_FEATURE_REGISTRY).entrySet().stream(). filter(cS -> cS.getValue().feature() == feature). findFirst().map(Map.Entry::getValue).orElse(null); } public static <T extends FeatureConfiguration> StructureStart shouldStructureStartAt(ServerLevel world, BlockPos pos, ConfiguredStructureFeature<T, ?> structure, boolean computeBox) { long seed = world.getSeed(); ChunkGenerator generator = world.getChunkSource().getGenerator(); ChunkGeneratorInterface cgi = (ChunkGeneratorInterface) generator; List<StructurePlacement> structureConfig = cgi.getPlacementsForFeatureCM(structure); ChunkPos chunkPos = new ChunkPos(pos); boolean couldPlace = structureConfig.stream().anyMatch(p -> p.isFeatureChunk(generator, world.getSeed(), chunkPos.x, chunkPos.z)); if (!couldPlace) return null; final HolderSet<Biome> structureBiomes = structure.biomes(); if (!computeBox) { Holder<Biome> genBiome = generator.getNoiseBiome(QuartPos.fromBlock(pos.getX()), QuartPos.fromBlock(pos.getY()), QuartPos.fromBlock(pos.getZ())); if (structureBiomes.contains(genBiome) && structure.feature.canGenerate( world.registryAccess(), generator, generator.getBiomeSource(), world.getStructureManager(), seed, chunkPos, structure.config, world, structureBiomes::contains )) { return StructureStart.INVALID_START; } } else { final StructureStart filledStructure = structure.generate( world.registryAccess(), generator, generator.getBiomeSource(), world.getStructureManager(), seed, chunkPos, 0, world, structureBiomes::contains); if (filledStructure != null && filledStructure.isValid()) { return filledStructure; } } return null; } private static TreeConfiguration.TreeConfigurationBuilder createTree(Block block, Block block2, int i, int j, int k, int l) { return new TreeConfiguration.TreeConfigurationBuilder(BlockStateProvider.simple(block), new StraightTrunkPlacer(i, j, k), BlockStateProvider.simple(block2), new BlobFoliagePlacer(ConstantInt.of(l), ConstantInt.of(0), 3), new TwoLayersFeatureSize(1, 0, 1)); } public static final Map<String, Thing> featureMap = new HashMap<>() {{ put("oak_bees", simpleTree( createTree(Blocks.OAK_LOG, Blocks.OAK_LEAVES, 4, 2, 0, 2).ignoreVines().decorators(List.of(new BeehiveDecorator(1.00F))).build())); put("fancy_oak_bees", simpleTree( (new TreeConfiguration.TreeConfigurationBuilder(BlockStateProvider.simple(Blocks.OAK_LOG), new FancyTrunkPlacer(3, 11, 0), BlockStateProvider.simple(Blocks.OAK_LEAVES), new FancyFoliagePlacer(ConstantInt.of(2), ConstantInt.of(4), 4), new TwoLayersFeatureSize(0, 0, 0, OptionalInt.of(4)))).ignoreVines().decorators(List.of(new BeehiveDecorator(1.00F))).build())); put("birch_bees", simpleTree( createTree(Blocks.BIRCH_LOG, Blocks.BIRCH_LEAVES, 5, 2, 0, 2).ignoreVines().decorators(List.of(new BeehiveDecorator(1.00F))).build())); put("coral_tree", simplePlop(Feature.CORAL_TREE, FeatureConfiguration.NONE)); put("coral_claw", simplePlop(Feature.CORAL_CLAW, FeatureConfiguration.NONE)); put("coral_mushroom", simplePlop(Feature.CORAL_MUSHROOM, FeatureConfiguration.NONE)); put("coral", simplePlop(Feature.SIMPLE_RANDOM_SELECTOR, new SimpleRandomFeatureConfiguration(HolderSet.direct( PlacementUtils.inlinePlaced(Feature.CORAL_TREE, FeatureConfiguration.NONE), PlacementUtils.inlinePlaced(Feature.CORAL_CLAW, FeatureConfiguration.NONE), PlacementUtils.inlinePlaced(Feature.CORAL_MUSHROOM, FeatureConfiguration.NONE) )))); put("bastion_remnant_units", spawnCustomStructure(StructureFeature.BASTION_REMNANT.configured( new JigsawConfiguration(Holder.direct(new StructureTemplatePool( new ResourceLocation("bastion/starts"), new ResourceLocation("empty"), List.of( Pair.of(StructurePoolElement.single("bastion/units/air_base", ProcessorLists.BASTION_GENERIC_DEGRADATION), 1) ), StructureTemplatePool.Projection.RIGID )), 6), BiomeTags.HAS_BASTION_REMNANT) )); put("bastion_remnant_hoglin_stable", spawnCustomStructure(StructureFeature.BASTION_REMNANT.configured( new JigsawConfiguration(Holder.direct(new StructureTemplatePool( new ResourceLocation("bastion/starts"), new ResourceLocation("empty"), List.of( Pair.of(StructurePoolElement.single("bastion/hoglin_stable/air_base", ProcessorLists.BASTION_GENERIC_DEGRADATION), 1) ), StructureTemplatePool.Projection.RIGID )), 6), BiomeTags.HAS_BASTION_REMNANT) )); put("bastion_remnant_treasure", spawnCustomStructure(StructureFeature.BASTION_REMNANT.configured( new JigsawConfiguration(Holder.direct(new StructureTemplatePool( new ResourceLocation("bastion/starts"), new ResourceLocation("empty"), List.of( Pair.of(StructurePoolElement.single("bastion/treasure/big_air_full", ProcessorLists.BASTION_GENERIC_DEGRADATION), 1) ), StructureTemplatePool.Projection.RIGID )), 6), BiomeTags.HAS_BASTION_REMNANT) )); put("bastion_remnant_bridge", spawnCustomStructure(StructureFeature.BASTION_REMNANT.configured( new JigsawConfiguration(Holder.direct(new StructureTemplatePool( new ResourceLocation("bastion/starts"), new ResourceLocation("empty"), List.of( Pair.of(StructurePoolElement.single("bastion/bridge/starting_pieces/entrance_base", ProcessorLists.BASTION_GENERIC_DEGRADATION), 1) ), StructureTemplatePool.Projection.RIGID )), 6), BiomeTags.HAS_BASTION_REMNANT) )); }}; public static boolean plopAnywhere(ConfiguredStructureFeature<?, ?> structure, ServerLevel world, BlockPos pos, ChunkGenerator generator, boolean wireOnly) { if (world.isClientSide()) return false; CarpetSettings.skipGenerationChecks.set(true); try { StructureStart start = structure.generate(world.registryAccess(), generator, generator.getBiomeSource(), world.getStructureManager(), world.getSeed(), new ChunkPos(pos), 0, world, b -> true ); if (start == StructureStart.INVALID_START) { return false; } Random rand = new Random(world.getRandom().nextInt()); int j = pos.getX() >> 4; int k = pos.getZ() >> 4; long chId = ChunkPos.asLong(j, k); world.getChunk(j, k).addReferenceForFeature(structure, chId); BoundingBox box = start.getBoundingBox(); if (!wireOnly) { Registry<ConfiguredStructureFeature<?, ?>> registry3 = world.registryAccess().registryOrThrow(Registry.CONFIGURED_STRUCTURE_FEATURE_REGISTRY); world.setCurrentlyGenerating(() -> { Objects.requireNonNull(structure); return registry3.getResourceKey(structure).map(Object::toString).orElseGet(structure::toString); }); start.placeInChunk(world, world.structureFeatureManager(), generator, rand, box, new ChunkPos(j, k)); } //structurestart.notifyPostProcessAt(new ChunkPos(j, k)); int i = Math.max(box.getXSpan(),box.getZSpan())/16+1; //int i = getRadius(); for (int k1 = j - i; k1 <= j + i; ++k1) { for (int l1 = k - i; l1 <= k + i; ++l1) { if (k1 == j && l1 == k) continue; if (box.intersects(k1<<4, l1<<4, (k1<<4) + 15, (l1<<4) + 15)) { world.getChunk(k1, l1).addReferenceForFeature(structure, chId); } } } } catch (Exception booboo) { CarpetSettings.LOG.error("Unknown Exception while plopping structure: "+booboo, booboo); return false; } finally { CarpetSettings.skipGenerationChecks.set(false); } return true; } }
49.635097
404
0.659184